How to use mergeData method in Playwright Internal

Best JavaScript code snippet using playwright-internal

PublicationServices.js

Source:PublicationServices.js Github

copy

Full Screen

1var sql = require("../db/sql/PublicationSql");2var raSql = require("../db/sql/ResearchAreaSql");3var pSql = require("../db/sql/ProductSql");4var aSql = require("../db/sql/AssaySql");5var plSql = require("../db/sql/PlatformSql");6var ErrorResponse = require("../body/response/ErrorResponse");7var PublicationResponse = require("../body/response/PublicationResponse");8var GetEditPublicationResponse = require("../body/response/GetEditPublicationResponse");9var SuccessResponse = require("../body/response/SuccessResponse");10var nodeExcel = require('node-xlsx');11var util = require('../util/util');12var log4jHandler = require('../log4j/Log4jHandler');13var fs = require("fs");14var iconv = require('iconv-lite');15var pathConfig = require('../path-config');16var getPublication = (query) => {17 return new Promise((resolve, reject) => {18 let index = query.index;19 let offset = query.offset;20 let rows = (index - 1) * offset;21 if(isNaN(rows) || isNaN(offset)) {22 reject(ErrorResponse.error(util.CC, "index and offset are required, and type must be number"))23 } else {24 sql.selectPublication(rows, offset, query).then((publication) => {25 resolve(PublicationResponse.publication(index, publication[1], publication[0]))26 }).catch((err) => {27 log4jHandler.error(err)28 reject(ErrorResponse.error(util.orEC, "Select publication fail"));29 });30 }31 });32};33var editBasePublicationField = (id, field, value, user) => {34 return new Promise((resolve, reject) => {35 if(!id || !field || !value) {36 reject(ErrorResponse.error(util.CC, "id, field and value are required"));37 } else {38 if(field != "PublicationTitle" && field != "PublicationLink" && field != "PrimaryAuthor" && field != "Authors" && field != "JournalName" && field != "PublicationDate") {39 reject(ErrorResponse.error(util.CC, "Field is wrong"));40 } else {41 id = id.replace(/\s+/g,"")42 var sqlField = ""43 if(field == "PublicationTitle") {44 sqlField = "publication_title"45 }46 if(field == "PublicationLink") {47 sqlField = "publication_link"48 }49 if(field == "PrimaryAuthor") {50 sqlField = "primary_author"51 }52 if(field == "Authors") {53 sqlField = "authors"54 }55 if(field == "JournalName") {56 sqlField = "journal_name"57 }58 if(field == "PublicationDate") {59 sqlField = "publication_date"60 }61 sql.updateBasePublicationField(id, sqlField, value, user).then(() => {62 resolve(SuccessResponse.edit());63 }).catch((err) => {64 log4jHandler.error(err)65 if(err.message.indexOf('ER_DUP_ENTRY') != -1) {66 reject(ErrorResponse.error(util.orEC, "This publication link is already exist"))67 } else {68 reject(ErrorResponse.error(util.orEC, "Update base publication field fail"));69 }70 });71 }72 }73 }); 74}75var getEditPublication = (id, index, offset) => {76 return new Promise((resolve, reject) => {77 let rows = (index - 1) * offset;78 if(!id || isNaN(rows) || isNaN(offset)) {79 reject(ErrorResponse.error(util.CC, "id and index and offset are required, and type must be number"))80 } else {81 id = id.replace(/\s+/g,"")82 sql.selectUpdatePublication(id, rows, offset).then((updatePublication) => {83 if(updatePublication[0].length == 0) {84 reject(ErrorResponse.error(util.orCEC, "can not found this publication"))85 } else {86 resolve(GetEditPublicationResponse.getEditPublication(index, updatePublication[2], updatePublication[0], updatePublication[1]))87 }88 }).catch((err) => {89 log4jHandler.error(err)90 reject(ErrorResponse.error(util.orEC, "select update publication fail"))91 })92 }93 })94}95var removePublication = (id, subId, user) => {96 return new Promise((resolve, reject) => {97 if(!id) {98 reject(ErrorResponse.error(util.CC, "Publication id is required"))99 } else {100 id = id.replace(/\s+/g,"")101 if(!subId) {102 sql.selectDeleteSubPublication(id).then((subTotal) => {103 if(subTotal[0].total < 1) {104 sql.deleteBasePublication(id, user).then(() => {105 resolve(SuccessResponse.remove())106 }).catch((err) => {107 log4jHandler.error(err)108 reject(ErrorResponse.error(util.orEC, "delete base publication fail"))109 })110 } else {111 reject(ErrorResponse.error(util.orCEC, "This id can get subentry, but you are not send subId"))112 }113 }).catch((err) => {114 reject(ErrorResponse.error(util.orEC, "select delete sub publication fail"))115 })116 } else {117 subId = subId.replace(/\s+/g,"")118 sql.selectDeleteSubPublication(id).then((subTotal) => {119 if(subTotal[0].total > 1) {120 sql.deleteSubPublication(id, subId, user).then(() => {121 resolve(SuccessResponse.remove())122 }).catch((err) => {123 log4jHandler.error(err)124 reject(ErrorResponse.error(util.orEC, "delete sub publication fail"))125 })126 } else if(subTotal[0].total == 1) {127 sql.deletePublication(id, subId, user).then(() => {128 resolve(SuccessResponse.remove())129 }).catch((err) => {130 log4jHandler.error(err)131 reject(ErrorResponse.error(util.orEC, "delete publication fail"))132 })133 } else {134 reject(ErrorResponse.error(util.orCEC, "this id can not get any subentry"))135 }136 }).catch((err) => {137 reject(ErrorResponse.error(util.orEC, "select delete sub publication fail"))138 })139 }140 }141 })142}143var removeSubPublication = (id, subId, user) => {144 return new Promise((resolve, reject) => {145 if(!id || !subId) {146 reject(ErrorResponse.error(util.CC, "id and subId are required"))147 } else {148 id = id.replace(/\s+/g,"")149 subId = subId.replace(/\s+/g,"")150 sql.deleteSubPublication(id, subId, user).then(() => {151 resolve(SuccessResponse.remove())152 }).catch((err) => {153 log4jHandler.error(err)154 reject(ErrorResponse.error(util.orEC, "delete sub publication fail"))155 })156 }157 })158}159var addPublication = (publication, user) => {160 return new Promise((resolve, reject) => {161 if(!publication.PublicationLink || !publication.PublicationTitle || !publication.PublicationDate || !publication.PrimaryAuthor || !publication.Authors || !publication.JournalName) {162 reject(ErrorResponse.error(util.CC, "base publication field are required"))163 } else {164 if(!publication.SubPublication || publication.SubPublication.length == 0) {165 sql.insertBasePublication(publication, user).then((baseSuccess) => {166 resolve(Object.assign(SuccessResponse.add(), {id: baseSuccess[0].insertId}));167 }).catch((err) => {168 log4jHandler.error(err)169 if(err.message.indexOf('ER_DUP_ENTRY') != -1) {170 reject(ErrorResponse.error(util.orEC, "This publication link is already exist"))171 } else {172 reject(ErrorResponse.error(util.orEC, "insert base publication fail"))173 }174 })175 } else {176 var flag = true;177 for(let i = 0; i < publication.SubPublication.length; i++) {178 var subKey = new Array()179 for(var key in publication.SubPublication[i]){180 subKey.push(key)181 if(key != "Part") {182 if(!publication.SubPublication[i][key] || publication.SubPublication[i][key].length == 0) {183 flag = false184 } 185 }186 }187 if(subKey.indexOf('ResearchArea') == -1 || subKey.indexOf('CellLine') == -1 || subKey.indexOf('CellType') == -1 || subKey.indexOf('Species') == -1 || subKey.indexOf('Platform') == -1 || subKey.indexOf('Product') == -1 || subKey.indexOf('Assay') == -1 || subKey.indexOf('CellSeedingDensity') == -1 || subKey.indexOf('PlateCoating') == -1) {188 flag = false189 }190 }191 if(!flag) {192 reject(ErrorResponse.error(util.CC, "sub publication field are required"))193 } else {194 sql.insertPublication(publication, user).then((success) => {195 resolve(Object.assign(SuccessResponse.add(), {id: success[0].insertId}));196 }).catch((err) => {197 log4jHandler.error(err)198 if(err.message.indexOf('ER_DUP_ENTRY') != -1) {199 reject(ErrorResponse.error(util.orEC, "This publication link is already exist"))200 } else {201 reject(ErrorResponse.error(util.orEC, "insert publication fail"))202 }203 })204 }205 }206 }207 })208}209var editPublication = (publication, user) => {210 return new Promise((resolve, reject) => {211 var flag = true212 for(var key in publication) {213 if(!publication[key] && key != 'SubPublication') {214 flag = false215 }216 }217 if(!flag) {218 reject(ErrorResponse.error(util.orCC, "the base publication field have empty value"))219 } else {220 if(!publication.SubPublication || publication.SubPublication.length == 0) {221 sql.updateBasePublication(publication, user).then(() => {222 resolve(SuccessResponse.edit())223 }).catch((err) => {224 log4jHandler.error(err)225 if(err.message.indexOf('ER_DUP_ENTRY') != -1) {226 reject(ErrorResponse.error(util.orEC, "This publication link is already exist"))227 } else {228 reject(ErrorResponse.error(util.orEC, "update base publication fail"))229 }230 })231 } else {232 var subFlag = true233 for(let i = 0; i < publication.SubPublication.length; i++) {234 var subKeyArr = new Array()235 for(var subKey in publication.SubPublication[i]) {236 subKeyArr.push(subKey)237 if(subKey != "Part") {238 if(!publication.SubPublication[i][subKey] || publication.SubPublication[i][subKey].length == 0) {239 subFlag = false240 }241 }242 }243 if(subKeyArr.indexOf("SubId") == -1) {244 if(subKeyArr.indexOf('ResearchArea') == -1 || subKeyArr.indexOf('CellLine') == -1 || subKeyArr.indexOf('CellType') == -1 || subKeyArr.indexOf('Species') == -1 || subKeyArr.indexOf('Platform') == -1 || subKeyArr.indexOf('Product') == -1 || subKeyArr.indexOf('Assay') == -1 || subKeyArr.indexOf('CellSeedingDensity') == -1 || subKeyArr.indexOf('PlateCoating') == -1) {245 subFlag = false246 }247 }248 }249 if(!subFlag) {250 reject(ErrorResponse.error(util.orCC, "sub publication field are required"))251 } else {252 sql.updatePublication(publication, user).then(() => {253 resolve(SuccessResponse.edit())254 }).catch((err) => {255 log4jHandler.error(err)256 if(err.message.indexOf('ER_DUP_ENTRY') != -1) {257 reject(ErrorResponse.error(util.orEC, "This publication link is already exist"))258 } else {259 reject(ErrorResponse.error(util.orEC, "update publication fail"))260 }261 })262 }263 }264 }265 })266}267var importPublication = (file, user) => {268 return new Promise((resolve, reject) => {269 if(!file || file[0].originalname.substring(file[0].originalname.lastIndexOf(".")) != '.xlsx') {270 if(!file) {271 reject(ErrorResponse.error(util.CC, "Didn't get the file"))272 }273 if(file[0].originalname.substring(file[0].originalname.lastIndexOf(".")) != '.xlsx') {274 reject(ErrorResponse.error(util.CC, "File type is not xlsx"))275 } 276 } else {277 var excelFile = file[0].buffer278 var publicationExcel = nodeExcel.parse(excelFile);279 log4jHandler.info("import publication excel parse data: " + JSON.stringify(publicationExcel))280 var title = publicationExcel[0].data[0];281 if(title.indexOf('Publication Title') != -1 && title.indexOf('Journal Name') != -1 && title.indexOf('Publication Date') != -1 && title.indexOf('Author(s)') != -1 && title.indexOf('Publication Link') != -1) {282 var publication = [];283 for(let i = 1; i < publicationExcel[0].data.length; i++) {284 if(publicationExcel[0].data[i].length != 0) {285 var publicationItem = JSON.parse("{}");286 for(let j = 0; j < title.length; j++){287 publicationItem[title[j]] = publicationExcel[0].data[i][j]288 if(title[j] == "Author(s)") {289 publicationItem['Primary Author'] = publicationExcel[0].data[i][j].split(',')[0]290 }291 }292 publication.push(publicationItem)293 }294 }295 for(let i = 0; i < publication.length; i++) {296 publication[i]['Publication Date'] = util.formatDate(new Date(1900, 0, publication[i]['Publication Date'] - 1));297 }298 log4jHandler.info("import publication excel parse data convert format: " + JSON.stringify(publicationExcel))299 sql.importBasePublication(publication, user).then((importResponse) => {300 if(importResponse.length == 0) {301 resolve(SuccessResponse.importExcel())302 } else {303 resolve({link: importResponse})304 }305 }).catch((err) => {306 log4jHandler.error(err)307 if(err.message.indexOf('ER_DUP_ENTRY') != -1) {308 reject(ErrorResponse.error(util.orEC, "This excel have publication link is already exist"))309 } else {310 reject(ErrorResponse.error(util.orEC, "import publication fail"))311 }312 })313 } else {314 reject(ErrorResponse.error(util.CC, "Excel publication data format is wrong"))315 }316 }317 })318}319var exportPublication = (exportFilter) => {320 return new Promise((resolve, reject) => {321 getExportData(exportFilter).then((exportData) => {322 getExportDataValue(parseExportData(exportData)).then((tExportData) => {323 var mergeData = transExportDataValue(tExportData)324 var needExportData = new Array()325 needExportData.push(['ID', 'Publication Link', 'Publication Title', 'Publication Date', 'Primary Author', 'Author(s)', 'Journal Name', 'Research Area', 'Cell Line', 'Cell Types', 'Species', 'Platform', 'Product', 'Assay', 'Cell Seeding Density', 'Plate Coating', 'Part', 'Record-type', 'Create/Update Date'])326 for(let i = 0; i < mergeData.length; i++) {327 needExportData.push([328 'PUB-' + mergeData[i].ID + (mergeData[i].SubId ? '-' + mergeData[i].SubId : ''),329 mergeData[i].PublicationLink,330 mergeData[i].PublicationTitle,331 mergeData[i].PublicationDate,332 mergeData[i].PrimaryAuthor,333 mergeData[i].Authors,334 mergeData[i].JournalName,335 mergeData[i].ResearchArea,336 mergeData[i].CellLine,337 mergeData[i].CellTypes,338 mergeData[i].Species,339 mergeData[i].Platform,340 mergeData[i].Product,341 mergeData[i].Assay,342 mergeData[i].CellSeedingDensity,343 mergeData[i].PlateCoating,344 mergeData[i].part,345 mergeData[i].RecordType,346 mergeData[i].CUDate347 ]) 348 }349 //var content = ''350 //for(let i = 0; i < needExportData.length; i++) {351 //content = content + needExportData[i].join(',') + '\n'352 //}353 //let buffer = Buffer.from(content);354 var result = nodeExcel.build([{name:'sheet1', data: needExportData}]);355 //var result = iconv.encode(buffer, 'UCS-2BE')356 resolve(result)357 }).catch((err) => {358 reject(err)359 }) 360 }).catch((err) => {361 reject(err)362 }) 363 })364}365var exportPublicationToEndeca = () => {366 return new Promise((resolve, reject) => {367 getAllExportData().then((exportData) => {368 getExportDataValue(parseExportData(exportData)).then((tExportData) => {369 var mergeData = mergeExportData(transExportDataValue(tExportData))370 var needExportData = new Array()371 needExportData.push(['ID', 'Publication Link', 'Publication Title', 'Publication Date', 'Primary Author', 'Author(s)', 'Journal Name', 'Research Area', 'Cell Line', 'Cell Types', 'Species', 'Platform', 'Product', 'Assay', 'Cell Seeding Density', 'Plate Coating', 'Part', 'Record-type', 'Create/Update Date'])372 for(let i = 0; i < mergeData.length; i++) {373 needExportData.push([374 mergeData[i].ID,375 mergeData[i].PublicationLink,376 mergeData[i].PublicationTitle,377 mergeData[i].PublicationDate,378 mergeData[i].PrimaryAuthor,379 mergeData[i].Authors,380 mergeData[i].JournalName,381 mergeData[i].ResearchArea,382 mergeData[i].CellLine,383 mergeData[i].CellTypes,384 mergeData[i].Species,385 mergeData[i].Platform,386 mergeData[i].Product,387 mergeData[i].Assay,388 mergeData[i].CellSeedingDensity,389 mergeData[i].PlateCoating,390 mergeData[i].part,391 mergeData[i].RecordType,392 mergeData[i].CUDate393 ]) 394 }395 var result = nodeExcel.build([{name:'sheet1', data:needExportData}]);396 resolve(result)397 }).catch((err) => {398 reject(err)399 }) 400 }).catch((err) => {401 reject(err)402 }) 403 })404}405var pushToEndeca = () => {406 return new Promise((resolve, reject) => {407 getAllExportData().then((exportData) => {408 getExportDataValue(parseExportData(exportData)).then((tExportData) => {409 var mergeData = mergeExportData(transExportDataValue(tExportData))410 var needExportData = new Array()411 needExportData.push(['ID', 'Publication Link', 'Publication Title', 'Publication Date', 'Primary Author', 'Author(s)', 'Journal Name', 'Research Area', 'Cell Line', 'Cell Types', 'Species', 'Platform', 'Product', 'Assay', 'Cell Seeding Density', 'Plate Coating', 'Part', 'Record-type', 'Create/Update Date'])412 for(let i = 0; i < mergeData.length; i++) {413 needExportData.push([414 mergeData[i].ID,415 mergeData[i].PublicationLink,416 mergeData[i].PublicationTitle,417 mergeData[i].PublicationDate,418 mergeData[i].PrimaryAuthor,419 mergeData[i].Authors,420 mergeData[i].JournalName,421 mergeData[i].ResearchArea,422 mergeData[i].CellLine,423 mergeData[i].CellTypes,424 mergeData[i].Species,425 mergeData[i].Platform,426 mergeData[i].Product,427 mergeData[i].Assay,428 mergeData[i].CellSeedingDensity,429 mergeData[i].PlateCoating,430 mergeData[i].part,431 mergeData[i].RecordType,432 mergeData[i].CUDate433 ]) 434 }435 var content = ''436 for(let i = 0; i < needExportData.length; i++) {437 content = content + needExportData[i].join(' ') + '\n'438 }439 let buffer = Buffer.from(content);440 var tBuffer = iconv.encode(buffer, 'ucs2')441 fs.writeFileSync(pathConfig.path + 'DDE_Publication_Endeca_' + util.formatExportDate(new Date()) + '.txt', tBuffer);442 resolve(SuccessResponse.pushToEndeca())443 }).catch((err) => {444 reject(err)445 }) 446 }).catch((err) => {447 reject(err)448 }) 449 })450}451var getAllExportData = () => {452 return new Promise((resolve, reject) => {453 var data = new Array()454 sql.selectAllExportPublication().then((publication) => {455 if(publication.length >= 1) {456 for(let i = 0; i < publication.length; i++) {457 data.push(458 {459 ID: publication[i].id,460 PublicationLink: publication[i].publication_link,461 PublicationTitle: publication[i].publication_title,462 PublicationDate: util.formatDateUSA(new Date(publication[i].publication_date)),463 PrimaryAuthor: publication[i].primary_author,464 Authors: util.trimSpace(publication[i].authors),465 JournalName: publication[i].journal_name,466 CUDate: util.formatCuDateUSA(new Date(publication[i].cu_date)),467 SubId: publication[i].sub_id,468 ResearchArea: publication[i].research_area,469 CellLine: publication[i].cell_line,470 CellTypes: publication[i].cell_type,471 Species: publication[i].species,472 Platform: publication[i].platform,473 Product: publication[i].product,474 Assay: publication[i].assay,475 CellSeedingDensity: publication[i].cell_seeding_density,476 PlateCoating: publication[i].plate_coating,477 part: publication[i].part,478 RecordType: 'Rollup',479 }480 )481 }482 resolve(data)483 } else {484 reject(ErrorResponse.error(util.CC, "can't get any data"))485 }486 }).catch((err) => {487 log4jHandler.error(err)488 reject(ErrorResponse.error(util.orEC, "select all export publication fail"))489 })490 })491}492var getExportData = (exportFilter) => {493 return new Promise((resolve, reject) => {494 var data = new Array()495 sql.selectExportPublication(exportFilter).then((publication) => { 496 if(publication.length >= 1) {497 for(let i = 0; i < publication.length; i++) {498 data.push(499 {500 ID: publication[i].id,501 PublicationLink: publication[i].publication_link,502 PublicationTitle: publication[i].publication_title,503 PublicationDate: util.formatDateUSA(new Date(publication[i].publication_date)),504 PrimaryAuthor: publication[i].primary_author,505 Authors: util.trimSpace(publication[i].authors),506 JournalName: publication[i].journal_name,507 CUDate: util.formatCuDateUSA(new Date(publication[i].cu_date)),508 SubId: publication[i].sub_id,509 ResearchArea: publication[i].research_area,510 CellLine: publication[i].cell_line,511 CellTypes: publication[i].cell_type,512 Species: publication[i].species,513 Platform: publication[i].platform,514 Product: publication[i].product,515 Assay: publication[i].assay,516 CellSeedingDensity: publication[i].cell_seeding_density,517 PlateCoating: publication[i].plate_coating,518 part: publication[i].part,519 RecordType: 'Rollup',520 }521 )522 }523 resolve(data)524 } else {525 reject(ErrorResponse.error(util.CC, "use this filter can't get any data"))526 }527 }).catch((err) => {528 log4jHandler.error(err)529 reject(ErrorResponse.error(util.orEC, "select export publication fail"))530 })531 })532}533var parseExportData = (data) => {534 for(let i = 0; i < data.length; i++) {535 var researchAreaArr = new Array()536 var productArr = new Array()537 var assayArr = new Array()538 if(data[i].SubId) {539 if(data[i].ResearchArea.indexOf("~") != -1) {540 var rs = data[i].ResearchArea.split("~")541 for(let ri = 0; ri < rs.length; ri++) {542 researchAreaArr.push(rs[ri])543 }544 } else {545 researchAreaArr.push(data[i].ResearchArea)546 }547 if(data[i].Product.indexOf("~") != -1) {548 var ps = data[i].Product.split("~")549 for(let pi = 0; pi < ps.length; pi++) {550 productArr.push(ps[pi])551 }552 } else {553 productArr.push(data[i].Product)554 }555 if(data[i].Assay.indexOf("~") != -1) {556 var as = data[i].Assay.split("~")557 for(let ai = 0; ai < as.length; ai++) {558 assayArr.push(as[ai])559 }560 } else {561 assayArr.push(data[i].Assay)562 }563 }564 data[i].ResearchArea = researchAreaArr565 data[i].Product = productArr566 data[i].Assay = assayArr567 }568 return data569}570var getExportDataValue = (data) => {571 return new Promise((resolve, reject) => {572 raSql.selectReasearchAreaExportValue().then((raExportValue) => { 573 pSql.selectProductExportValue().then((pExportValue) => {574 aSql.selectAssayExportValue().then((aExportValue) => {575 plSql.selectPlatformExportValue().then((plExportValue) => {576 for(let e = 0; e < data.length; e++) {577 for(let ei = 0; ei < data[e].ResearchArea.length; ei++) {578 var rFlag = false579 for(let i = 0; i < raExportValue.length; i++) {580 if(data[e].ResearchArea[ei] == raExportValue[i].research_area_value) {581 rFlag = true582 data[e].ResearchArea[ei] = raExportValue[i].research_area_export583 }584 }585 if(!rFlag) {586 data[e].ResearchArea[ei] = ""587 }588 }589 for(let ej = 0; ej < data[e].Product.length; ej++) {590 var pFlag = false;591 for(let j = 0; j < pExportValue.length; j++) {592 if(data[e].Product[ej] == pExportValue[j].product_value && data[e].Platform == pExportValue[j].platform_fk) {593 pFlag = true594 data[e].Product[ej] = pExportValue[j].product_export_value595 }596 }597 if(!pFlag) {598 data[e].Product[ej] = ""599 }600 }601 for(let ek = 0; ek < data[e].Assay.length; ek++) {602 var aFlag = false;603 for(let k = 0; k < aExportValue.length; k++) {604 if(data[e].Assay[ek] == aExportValue[k].assay_by_business_value) {605 aFlag = true606 data[e].Assay[ek] = aExportValue[k].assay_by_business_export_value607 }608 }609 if(!aFlag) {610 data[e].Assay[ek] = ""611 }612 } 613 }614 for(let ep = 0; ep < data.length; ep++) {615 var plFlag = false;616 for(let m = 0; m < plExportValue.length; m++) {617 if(data[ep].Platform == plExportValue[m].platform_value) {618 plFlag = true619 data[ep].Platform = plExportValue[m].platform_export_value620 }621 }622 if(!plFlag) {623 data[ep].Platform = ""624 }625 }626 resolve(data)627 }).catch((err) => {628 log4jHandler.error(err)629 reject(ErrorResponse.error(util.orEC, "select platform export value fail"))630 })631 }).catch((err) => {632 log4jHandler.error(err)633 reject(ErrorResponse.error(util.orEC, "select assay export value fail"))634 })635 }).catch((err) => {636 log4jHandler.error(err)637 reject(ErrorResponse.error(util.orEC, "select product export value fail"))638 })639 }).catch((err) => {640 log4jHandler.error(err)641 reject(ErrorResponse.error(util.orEC, "select research area export value fail"))642 })643 })644}645var transExportDataValue = (exportDataValue) => {646 var value647 for(let i = 0; i < exportDataValue.length; i++) {648 var rValue;649 var pValue;650 var aValue;651 for(let ri = 0; ri < exportDataValue[i].ResearchArea.length; ri++) {652 if(ri == 0) {653 rValue = exportDataValue[i].ResearchArea[ri]654 } else {655 rValue = rValue + "~" + exportDataValue[i].ResearchArea[ri]656 }657 }658 for(let pi = 0; pi < exportDataValue[i].Product.length; pi++) {659 if(pi == 0) {660 pValue = exportDataValue[i].Product[pi]661 } else {662 pValue = pValue + "~" + exportDataValue[i].Product[pi]663 }664 }665 for(let ai = 0; ai < exportDataValue[i].Assay.length; ai++) {666 if(ai == 0) {667 aValue = exportDataValue[i].Assay[ai]668 } else {669 aValue = aValue + "~" + exportDataValue[i].Assay[ai]670 }671 }672 exportDataValue[i].ResearchArea = rValue673 exportDataValue[i].Product = pValue674 exportDataValue[i].Assay = aValue675 }676 return exportDataValue677}678var mergeExportData = (data) => {679 var mergeData = JSON.parse('{}')680 for(let i = 0; i < data.length; i++) {681 if(!mergeData[data[i].ID]) {682 mergeData[data[i].ID] = new Array()683 mergeData[data[i].ID].push(data[i])684 } else {685 mergeData[data[i].ID].push(data[i])686 }687 }688 for(var key in mergeData) {689 var merge = JSON.parse(JSON.stringify(mergeData[key][0]))690 merge.ID = "PBM-" + merge.ID691 merge.RecordType = "Mega"692 merge.SubCUDate = merge.SubId ? merge.CUDate : ''693 if(merge.SubId) {694 for(let k = 0; k < mergeData[key].length; k++) {695 for(let m = 0; m < mergeData[key][k].ResearchArea.split('~').length; m++) {696 if(merge.ResearchArea.indexOf(mergeData[key][k].ResearchArea.split('~')[m]) == -1) {697 merge.ResearchArea = merge.ResearchArea + "~" + mergeData[key][k].ResearchArea.split('~')[m]698 }699 }700 for(let m = 0; m < mergeData[key][k].CellLine.split('~').length; m++) {701 if(merge.CellLine.indexOf(mergeData[key][k].CellLine.split('~')[m]) == -1) {702 merge.CellLine = merge.CellLine + "~" + mergeData[key][k].CellLine.split('~')[m]703 }704 }705 for(let m = 0; m < mergeData[key][k].CellTypes.split('~').length; m++) {706 if(merge.CellTypes.indexOf(mergeData[key][k].CellTypes.split('~')[m]) == -1) {707 merge.CellTypes = merge.CellTypes + "~" + mergeData[key][k].CellTypes.split('~')[m]708 }709 }710 for(let m = 0; m < mergeData[key][k].Species.split('~').length; m++) {711 if(merge.Species.indexOf(mergeData[key][k].Species.split('~')[m]) == -1) {712 merge.Species = merge.Species + "~" + mergeData[key][k].Species.split('~')[m]713 }714 }715 for(let m = 0; m < mergeData[key][k].Platform.split('~').length; m++) {716 if(merge.Platform != mergeData[key][k].Platform.split('~')[m]) {717 merge.Platform = merge.Platform + "~" + mergeData[key][k].Platform.split('~')[m]718 }719 }720 for(let m = 0; m < mergeData[key][k].Product.split('~').length; m++) {721 if(merge.Product.indexOf(mergeData[key][k].Product.split('~')[m]) == -1) {722 merge.Product = merge.Product + "~" + mergeData[key][k].Product.split('~')[m]723 }724 }725 for(let m = 0; m < mergeData[key][k].Assay.split('~').length; m++) {726 if(merge.Assay.indexOf(mergeData[key][k].Assay.split('~')[m]) == -1) {727 merge.Assay = merge.Assay + "~" + mergeData[key][k].Assay.split('~')[m]728 }729 }730 for(let m = 0; m < mergeData[key][k].CellSeedingDensity.split('~').length; m++) {731 if(merge.CellSeedingDensity.indexOf(mergeData[key][k].CellSeedingDensity.split('~')[m]) == -1) {732 merge.CellSeedingDensity = merge.CellSeedingDensity + "~" + mergeData[key][k].CellSeedingDensity.split('~')[m]733 }734 }735 for(let m = 0; m < mergeData[key][k].PlateCoating.split('~').length; m++) {736 if(merge.PlateCoating.indexOf(mergeData[key][k].PlateCoating.split('~')[m]) == -1) {737 merge.PlateCoating = merge.PlateCoating + "~" + mergeData[key][k].PlateCoating.split('~')[m]738 }739 }740 for(let m = 0; m < (mergeData[key][k].part ? mergeData[key][k].part : '').split('~').length; m++) {741 if((merge.part ? merge.part : '').indexOf((mergeData[key][k].part ? mergeData[key][k].part : '').split('~')[m]) == -1) {742 merge.part = merge.part + "~" + (mergeData[key][k].part ? mergeData[key][k].part : '').split('~')[m]743 }744 }745 }746 }747 mergeData[key].push(merge)748 }749 var newMergeData = new Array()750 for(var nkey in mergeData) {751 for(let j = 0; j < mergeData[nkey].length; j++) {752 if(mergeData[nkey][j].RecordType == 'Rollup' || !mergeData[nkey][j].RecordType) {753 mergeData[nkey][j].RecordType = 'Rollup'754 mergeData[nkey][j].ID = "PUB-" + mergeData[nkey][j].ID + (mergeData[nkey][j].SubId ? '-' + mergeData[nkey][j].SubId : '')755 }756 newMergeData.push(mergeData[nkey][j])757 }758 }759 return newMergeData760}761module.exports = {762 getPublication: getPublication,763 editBasePublicationField: editBasePublicationField,764 getEditPublication: getEditPublication,765 addPublication: addPublication,766 removePublication: removePublication,767 removeSubPublication: removeSubPublication,768 editPublication: editPublication,769 importPublication: importPublication,770 exportPublication: exportPublication,771 exportPublicationToEndeca: exportPublicationToEndeca,772 pushToEndeca: pushToEndeca...

Full Screen

Full Screen

modelItems.js

Source:modelItems.js Github

copy

Full Screen

1'use strict'2import { quickPatch } from '../../utils/patch.js'3export class Axis {4 constructor(initData) { quickPatch(this, initData); }5 letter = null // must be upper-case6 drives = []7 homed = null8 machinePosition = null9 min = null10 max = null11 visible = null12}13export class BedOrChamber {14 constructor(initData) { quickPatch(this, initData); }15 number = null16 active = []17 standby = []18 name = null19 heaters = []20}21export class Drive {22 constructor(initData) { quickPatch(this, initData); }23 position = null24 babystepping = {25 value: null,26 interpolated: null27 }28 current = null29 acceleration = null30 minSpeed = null31 maxSpeed = null32}33export class Endstop {34 constructor(initData) { quickPatch(this, initData); }35 triggered = false36 position = 0 // 0: none, 1: low end 2: high end37 type = 0 // 0: active low, 1: active high, 3: zprobe, 4: motor load detection38}39export class ExpansionBoard {40 constructor(initData) { quickPatch(this, initData); }41 name = null42 revision = null43 firmware = new Firmware()44 vIn = {45 current: null,46 min: null,47 max: null48 }49 mcuTemp = {50 current: null,51 min: null,52 max: null53 }54 maxHeaters = null55 maxMotors = null56}57export class ExtraHeater {58 constructor(initData) { quickPatch(this, initData); }59 current = null60 name = null61 state = null62 sensor = null63}64export class Extruder {65 constructor(initData) { quickPatch(this, initData); }66 drives = []67 factor = 1.068 nonlinear = {69 a: 0,70 b: 0,71 upperLimit: 0.2,72 temperature: 073 }74}75export class Fan {76 constructor(initData) { quickPatch(this, initData); }77 value = null78 name = null79 rpm = null80 inverted = false81 frequency = null82 min = 0.083 max = 1.084 blip = 0.185 thermostatic = {86 control: true,87 heaters: [],88 temperature: null89 }90 pin = null91}92export class FileInfo {93 constructor(initData) {94 if (initData) {95 quickPatch(this, initData);96 if (!this.numLayers && initData.height && initData.firstLayerHeight && initData.layerHeight) {97 this.numLayers = Math.round((initData.height - initData.firstLayerHeight) / initData.layerHeight) + 198 }99 }100 }101 fileName = null102 size = null103 lastModified = null104 filament = []105 generatedBy = null106 height = null107 firstLayerHeight = null108 layerHeight = null109 numLayers = null110 printTime = null111 simulatedTime = null112}113export class Firmware {114 name = null115 version = null116 date = null117}118export class Heater {119 constructor(initData) { quickPatch(this, initData); }120 current = null121 name = null122 state = null // see RRF state enum123 model = {124 gain: null,125 timeConst: null,126 deadTime: null,127 maxPwm: null128 }129 max = null130 sensor = null131}132export class Layer {133 constructor(initData) { quickPatch(this, initData); }134 duration = null135 height = null136 filament = []137 fractionPrinted = null138}139export class NetworkInterface {140 constructor(initData) { quickPatch(this, initData); }141 type = null // one of ['wifi', 'lan']142 firmwareVersion = null143 speed = null // null if unknown and 0 if no link144 signal = null // only WiFi (dBm)145 configuredIP = null146 actualIP = null147 subnet = null148 gateway = null149 numReconnects = null150 activeProtocols = [] // one or more of ['http' 'ftp' 'telnet']151}152export class Probe {153 constructor(initData) { quickPatch(this, initData); }154 type = null155 value = null156 secondaryValues = []157 threshold = 500158 speed = 2159 diveHeight = 5160 triggerHeight = 0.7161 inverted = false162 recoveryTime = 0163 travelSpeed = 100164 maxProbeCount = 1165 tolerance = 0.03166 disablesBed = false167}168export class Spindle {169 constructor(initData) { quickPatch(this, initData); }170 active = null // RPM171 current = null // RPM172}173export class Storage {174 constructor(initData) { quickPatch(this, initData); }175 mounted = null176 speed = null // in Bytes/s177 capacity = null // in Bytes178 free = null // in Bytes179 openFiles = null180}181export class Tool {182 constructor(initData) { quickPatch(this, initData); }183 number = null184 active = []185 standby = []186 name = null187 filament = null188 fans = []189 heaters = []190 extruders = []191 mix = []192 spindle = -1193 axes = [] // may hold sub-arrays of drives per axis194 offsets = [] // offsets in the same order as the axes195}196function fixObject(item, preset) {197 let fixed = false;198 for (let key in preset) {199 if (!item.hasOwnProperty(key)) {200 item[key] = preset[key];201 fixed = true;202 } else if (!(item[key] instanceof Array) && item[key] instanceof Object) {203 fixed |= fixObject(item[key], preset[key]);204 }205 }206 return fixed;207}208function fixItems(items, ClassType) {209 let preset = new ClassType();210 items.forEach(function(item) {211 if (item !== null) {212 for (let key in preset) {213 if (!item.hasOwnProperty(key)) {214 item[key] = preset[key];215 if (preset[key] instanceof Object) {216 preset = new ClassType();217 }218 } else if (preset[key] instanceof Object) {219 if (fixObject(item[key], preset[key])) {220 preset = new ClassType();221 }222 }223 }224 }225 });226}227// TODO: Eventually this could be combined with the 'merge' function228// But getting everything the way it's supposed to work took longer than expected anyway...229export function fixMachineItems(state, mergeData) {230 if (mergeData.cnc && mergeData.cnc.spindles) {231 fixItems(state.cnc.spindles, Spindle);232 }233 if (mergeData.electronics && mergeData.electronics.expansionBoards) {234 fixItems(state.electronics.expansionBoards, ExpansionBoard);235 }236 if (mergeData.fans) {237 fixItems(state.fans, Fan);238 }239 if (mergeData.heat) {240 if (mergeData.heat.beds) {241 fixItems(state.heat.beds, BedOrChamber);242 }243 if (mergeData.heat.chambers) {244 fixItems(state.heat.chambers, BedOrChamber);245 }246 if (mergeData.heat.extra) {247 fixItems(state.heat.extra, ExtraHeater);248 }249 if (mergeData.heat.heaters) {250 fixItems(state.heat.heaters, Heater);251 }252 }253 // Layers are not verified for performance reasons254 if (mergeData.move) {255 if (mergeData.move.axes) {256 fixItems(state.move.axes, Axis);257 }258 if (mergeData.move.drives) {259 fixItems(state.move.drives, Drive);260 }261 if (mergeData.move.extruders) {262 fixItems(state.move.extruders, Extruder);263 }264 }265 if (mergeData.network && mergeData.network.interfaces) {266 fixItems(state.network.interfaces, NetworkInterface);267 }268 if (mergeData.sensors) {269 if (mergeData.sensors.endstops) {270 fixItems(state.sensors.endstops, Endstop);271 }272 if (mergeData.sensors.probes) {273 fixItems(state.sensors.probes, Probe);274 }275 }276 if (mergeData.storages) {277 fixItems(state.storages, Storage);278 }279 if (mergeData.tools) {280 fixItems(state.tools, Tool);281 }...

Full Screen

Full Screen

ImportWizard.js

Source:ImportWizard.js Github

copy

Full Screen

1(function () {2 var ns = $.namespace('pskl.controller.dialogs.importwizard');3 var stepDefinitions = {4 'IMAGE_IMPORT' : {5 controller : ns.steps.ImageImport,6 template : 'import-image-import'7 },8 'ADJUST_SIZE' : {9 controller : ns.steps.AdjustSize,10 template : 'import-adjust-size'11 },12 'INSERT_LOCATION' : {13 controller : ns.steps.InsertLocation,14 template : 'import-insert-location'15 },16 'SELECT_MODE' : {17 controller : ns.steps.SelectMode,18 template : 'import-select-mode'19 }20 };21 ns.ImportWizard = function (piskelController, args) {22 this.piskelController = piskelController;23 // Merge data object used by steps to communicate and share their24 // results.25 this.mergeData = {26 rawFiles : [],27 mergePiskel: null,28 origin: null,29 resize: null,30 insertIndex: null,31 insertMode: null32 };33 };34 pskl.utils.inherit(ns.ImportWizard, pskl.controller.dialogs.AbstractDialogController);35 ns.ImportWizard.prototype.init = function (initArgs) {36 this.superclass.init.call(this);37 // Prepare mergeData object and wizard steps.38 this.mergeData.rawFiles = initArgs.rawFiles;39 this.steps = this.createSteps_();40 // Start wizard widget.41 var wizardContainer = document.querySelector('.import-wizard-container');42 this.wizard = new pskl.widgets.Wizard(this.steps, wizardContainer);43 this.wizard.init();44 if (this.hasSingleImage_()) {45 this.wizard.goTo('IMAGE_IMPORT');46 } else if (this.hasSinglePiskelFile_()) {47 // If a piskel file was provided we can directly go to48 pskl.utils.PiskelFileUtils.loadFromFile(this.mergeData.rawFiles[0],49 // onSuccess50 function (piskel) {51 this.mergeData.mergePiskel = piskel;52 this.wizard.goTo('SELECT_MODE');53 }.bind(this),54 // onError55 function (reason) {56 this.closeDialog();57 $.publish(Events.PISKEL_FILE_IMPORT_FAILED, [reason]);58 }.bind(this)59 );60 } else {61 console.error('Unsupported import. Only single piskel or single image are supported at the moment.');62 this.closeDialog();63 }64 };65 ns.ImportWizard.prototype.back = function () {66 this.wizard.back();67 this.wizard.getCurrentStep().instance.onShow();68 };69 ns.ImportWizard.prototype.next = function () {70 var step = this.wizard.getCurrentStep();71 if (step.name === 'IMAGE_IMPORT') {72 if (this.piskelController.isEmpty()) {73 // If the current sprite is empty finalize immediately and replace the current sprite.74 this.mergeData.importMode = ns.steps.SelectMode.MODES.REPLACE;75 this.finalizeImport_();76 } else {77 this.wizard.goTo('SELECT_MODE');78 }79 } else if (step.name === 'SELECT_MODE') {80 if (this.mergeData.importMode === ns.steps.SelectMode.MODES.REPLACE) {81 this.finalizeImport_();82 } else if (this.hasSameSize_()) {83 this.wizard.goTo('INSERT_LOCATION');84 } else {85 this.wizard.goTo('ADJUST_SIZE');86 }87 } else if (step.name === 'ADJUST_SIZE') {88 this.wizard.goTo('INSERT_LOCATION');89 } else if (step.name === 'INSERT_LOCATION') {90 this.finalizeImport_();91 }92 };93 ns.ImportWizard.prototype.destroy = function (file) {94 Object.keys(this.steps).forEach(function (stepName) {95 var step = this.steps[stepName];96 step.instance.destroy();97 step.instance = null;98 step.el = null;99 }.bind(this));100 this.superclass.destroy.call(this);101 };102 ns.ImportWizard.prototype.createSteps_ = function () {103 // The IMAGE_IMPORT step is used only if there is a single image file104 // being imported.105 var hasSingleImage = this.hasSingleImage_();106 var steps = {};107 Object.keys(stepDefinitions).forEach(function (stepName) {108 if (stepName === 'IMAGE_IMPORT' && !hasSingleImage) {109 return;110 }111 var definition = stepDefinitions[stepName];112 var el = pskl.utils.Template.getAsHTML(definition.template);113 var instance = new definition.controller(this.piskelController, this, el);114 instance.init();115 steps[stepName] = {116 name: stepName,117 el: el,118 instance: instance119 };120 }.bind(this));121 if (hasSingleImage) {122 steps.IMAGE_IMPORT.el.classList.add('import-first-step');123 } else {124 steps.SELECT_MODE.el.classList.add('import-first-step');125 }126 return steps;127 };128 ns.ImportWizard.prototype.finalizeImport_ = function () {129 var piskel = this.mergeData.mergePiskel;130 var mode = this.mergeData.importMode;131 if (mode === ns.steps.SelectMode.MODES.REPLACE) {132 // Replace the current piskel and close the dialog.133 if (window.confirm(Constants.CONFIRM_OVERWRITE)) {134 this.piskelController.setPiskel(piskel);135 this.closeDialog();136 }137 } else if (mode === ns.steps.SelectMode.MODES.MERGE) {138 var merge = pskl.utils.MergeUtils.merge(this.piskelController.getPiskel(), piskel, {139 insertIndex: this.mergeData.insertIndex,140 insertMode: this.mergeData.insertMode,141 origin: this.mergeData.origin,142 resize: this.mergeData.resize143 });144 this.piskelController.setPiskel(merge);145 // Set the first imported layer as selected.146 var importedLayers = piskel.getLayers().length;147 var currentLayers = this.piskelController.getLayers().length;148 this.piskelController.setCurrentLayerIndex(currentLayers - importedLayers);149 this.closeDialog();150 }151 };152 ns.ImportWizard.prototype.hasSameSize_ = function () {153 var piskel = this.mergeData.mergePiskel;154 if (!piskel) {155 return false;156 }157 return piskel.width === this.piskelController.getWidth() &&158 piskel.height === this.piskelController.getHeight();159 };160 ns.ImportWizard.prototype.hasSingleImage_ = function () {161 if (this.mergeData.rawFiles.length !== 1) {162 return false;163 }164 var file = this.mergeData.rawFiles[0];165 return file.type.indexOf('image') === 0;166 };167 ns.ImportWizard.prototype.hasSinglePiskelFile_ = function () {168 if (this.mergeData.rawFiles.length !== 1) {169 return false;170 }171 var file = this.mergeData.rawFiles[0];172 return (/\.piskel$/).test(file.name);173 };...

Full Screen

Full Screen

nyt.data.tests.plot.js

Source:nyt.data.tests.plot.js Github

copy

Full Screen

...9function NYTTestPlot()10{11 this.graphCanvasMargins = {top:5,right:5,bottom:5,left:5};12 this.graphs = [];13 this.addGraph('g00',this.mergeData(term_terrorist_scope_complete,'TERRORIST'));14 //.addData(this.mergeData(term_iraq_scope_complete, 'Bin Laden'));15 //this.graphs[0].render();16 this.addGraph('g01', this.mergeData(term_bin_laden_scope_complete, 'BIN LADEN'));17 this.addGraph('g02',this.mergeData(term_al_quida_scope_complete,'AL-QAIDA'));18 this.addGraph('g10',this.mergeData(term_afghanistan_scope_complete,'AFGHANISTAN'));19 this.addGraph('g11',this.mergeData(term_iran_scope_complete,'IRAN'));20 this.addGraph('g12',this.mergeData(term_iraq_scope_complete,'IRAQ'));21 this.addGraph('g20',this.mergeData(term_war_scope_complete,'WAR / PEACE'))22 .addData(this.mergeData(term_peace_scope_complete,'PEACE'));23 this.addGraph('g30',this.mergeData(term_good_scope_complete,'GOOD / BAD / EVIL'))24 .addData(this.mergeData(term_bad_scope_complete,'BAD'))25 .addData(this.mergeData(term_evil_scope_complete,'EVIL'));26 this.addGraph('g40',this.mergeData(term_germany_scope_complete,'GERMANY'));27 this.addGraph('g41',this.mergeData(term_japan_scope_complete,'JAPAN'));28 this.addGraph('g42',this.mergeData(term_america_scope_complete,'AMERICA'));29 this.addGraph('g43',this.mergeData(term_china_scope_complete,'CHINA'));30 this.addGraph('g50',this.mergeData(term_hitler_scope_complete,'HITLER'));31 this.addGraph('g51',this.mergeData(term_stalin_scope_complete,'STALIN'));32 this.addGraph('g52',this.mergeData(term_bush_scope_complete,'BUSH'));33 this.addGraph('g60',this.mergeData(term_good_scope_complete,'GOOD'));34 this.addGraph('g61',this.mergeData(term_bad_scope_complete,'BAD'));35 this.addGraph('g62',this.mergeData(term_evil_scope_complete,'EVIL'));36 this.addGraph('g70',this.mergeData(term_bush_scope_complete,'BUSH / OBAMA'))37 .addData(this.mergeData(term_obama_scope_complete),'OBAMA');38 var i = -1;39 while(++i < this.graphs.length)40 {41 this.graphs[i].render();42 }43 window.addEventListener('resize',this.onResize.bind(this));44}45NYTTestPlot.prototype.addGraph = function(id,data)46{47 var g = new NYTGraph(id);48 g.addData(data);49 g.setMarginsCanvas(this.graphCanvasMargins);50 //g.canvas.setFontFamily('QuicksandBook');51 //g.canvas.setFontSize(10);...

Full Screen

Full Screen

RuleData.js

Source:RuleData.js Github

copy

Full Screen

1import getType from './../data/type/getType'2import exportMsg from './../data/utils/exportMsg'3const base = {4 num: '0-9',5 letter: {6 small: 'a-z',7 big: 'A-Z'8 },9 text: '\u4e00-\u9fa5',10 bd: {11 z: ',。?!‘’”“<>%',12 y: ',.?!\'\'""《》%'13 }14}15// 规则校验数据16class RuleData {17 constructor (initdata) {18 if (initdata) {19 this.initMain(initdata)20 }21 }22 /**23 * 加载24 * @param {*} initdata 参数25 */26 initMain(initdata) {27 if (!initdata) {28 this.$exportMsg('init无参数!')29 return false30 }31 // 类型32 this.type = initdata.type || 'reg'33 if (initdata.build) {34 this.buildData(initdata)35 } else {36 this.data = initdata.data37 }38 // 是否组合模式39 this.merge = this.formatMerge(initdata.merge)40 }41 /**42 * 格式化组合数据43 * @param {true | object} [mergeData] 组合式初始化数据44 * @returns {undefined | object}45 */46 formatMerge(mergeData) {47 if (mergeData) {48 if (mergeData === true) {49 mergeData = {}50 }51 if (!mergeData.limit) {52 mergeData.limit = {}53 }54 if (mergeData.limit.start === undefined) {55 mergeData.limit.start = '^'56 }57 if (mergeData.limit.end === undefined) {58 mergeData.limit.end = '$'59 }60 if (!mergeData.num) {61 mergeData.num = {}62 }63 if (mergeData.num.min === undefined) {64 mergeData.num.min = '1'65 }66 if (mergeData.num.max === undefined) {67 mergeData.num.max = ''68 }69 }70 return mergeData71 }72 /**73 * 初始化数据74 * @param {object} initdata 数据75 */76 buildData(initdata) {77 if (this.type == 'reg') {78 if (initdata.merge === undefined) {79 initdata.merge = true80 }81 let regData = this.buildRegData(initdata.build, base)82 this.data = regData83 }84 }85 /**86 * 创建RegStr数据87 * @param {undefined | true | object} propObject 指定的属性prop88 * @param {object} data 属性prop的归属数据89 * @returns {string}90 */91 buildRegData(propObject, data) {92 let regStr = ''93 if (propObject === true) {94 for (let n in data) {95 let info = data[n]96 if (getType(info) == 'object') {97 regStr += this.buildRegData(true, info)98 } else {99 regStr += info100 }101 }102 } else {103 let type = getType(propObject)104 if (type == 'object') {105 for (let i in propObject) {106 let prop = propObject[i]107 let info = data[i]108 if (getType(info) === 'object') {109 regStr += this.buildRegData(getType(prop) === 'string' ? true : prop, info)110 } else {111 regStr += info112 }113 }114 }115 }116 return regStr117 }118 /**119 * 根据mergeData生成regstr120 * @param {string} regData regstr121 * @param {object} mergeData 组合数据122 * @returns {string}123 */124 buildRegStr(regData, mergeData) {125 return `${mergeData.limit.start}[${regData}]{${mergeData.num.min},${mergeData.num.max}}${mergeData.limit.end}`126 }127 /**128 * 根据regstr生成Reg129 * @param {string} regData regstr130 * @param {object} mergeData 组合数据131 * @returns {RegExp}132 */133 buildReg(regData, mergeData) {134 return new RegExp(this.buildRegStr(regData, mergeData))135 }136 /**137 * 检查数据138 * @param {*} data 需要检查的数据139 * @param {*} option 选项140 * @returns {boolean}141 */142 check(data, option = {}) {143 if (this.type == 'reg') {144 let reg = this.data145 if (option.merge) {146 option.merge = this.formatMerge(option.merge)147 }148 let merge = option.merge || this.merge149 if (merge) {150 reg = this.buildReg(reg, merge)151 }152 let type = getType(reg)153 if (type != 'regexp') {154 reg = new RegExp(reg)155 }156 return reg.test(data)157 } else if (this.type == 'func') {158 return this.data(data, option)159 }160 }161 $exportMsg(info, type = 'error', option) {162 exportMsg(this.$selfName() + ':' + info, type, option)163 }164 $selfName() {165 return `[${this.constructor.name}]`166 }167 toString() {168 return this.$selfName()169 }170}...

Full Screen

Full Screen

GridBagLayout.js

Source:GridBagLayout.js Github

copy

Full Screen

1// ------------------------------------------------------------------2//3// ------------------------------------------------------------------4/* global $ */5/* global d3 */6/* global times */7/* global is_def */8/* global deep_copy */9window.GridBagLayout = function() {10 let com = {11 size: {12 r: 3,13 c: 2,14 },15 merge: [{16 s: {17 r: 0,18 c: 0,19 },20 e: {21 r: 1,22 c: 1,23 },24 }],25 // weight: [{c: {r: 2, c: 0}, x: 2}],26 grid: [],27 }28 this.set = function(opt_in) {29 if (is_def(opt_in.data)) {30 com[opt_in.tag] = opt_in.data31 }32 else if (is_def(opt_in.def)) {33 com[opt_in.tag] = opt_in.def34 }35 else {36 com[opt_in.tag] = null37 }38 }39 this.get = function(type) {40 return com[type]41 }42 function init(opt_in) {43 com = opt_in44 createGrid()45 mergeCell()46 computeDimension()47 // computeWeight()48 }49 this.init = init50 function getCell(r, c) {51 return com.grid[r][c]52 }53 this.getCell = getCell54 function createGrid() {55 com.grid = []56 for (let i = 0; i < com.size.r; i++) {57 com.grid.push([])58 for (let j = 0; j < com.size.c; j++) {59 com.grid[i].push({60 s: {61 r: i,62 c: j,63 },64 e: {65 r: i,66 c: j,67 },68 w: 1,69 })70 }71 }72 }73 function mergeCell() {74 for (let z = 0; z < com.merge.length; z++) {75 let mergeData = com.merge[z]76 for (let i = mergeData.s.r; i < mergeData.e.r + 1; i++) {77 for (let j = mergeData.s.c; j < mergeData.e.c + 1; j++) {78 com.grid[i][j].s = mergeData.s79 com.grid[i][j].e = mergeData.e80 }81 }82 }83 }84 function computeDimension() {85 for (let i = 0; i < com.size.r; i++) {86 for (let j = 0; j < com.size.c; j++) {87 let cell = com.grid[i][j]88 com.grid[i][j] = {89 y: cell.s.r / com.size.r,90 x: cell.s.c / com.size.c,91 h: (cell.e.r - cell.s.r + 1) / com.size.r,92 w: (cell.e.c - cell.s.c + 1) / com.size.c,93 }94 }95 }96 }97 // function computeWeight () {98 // for (var z = 0; z < com.weight.length; z++) {99 // let weightData = com.weight[z]100 // for (var i = mergeData.s.r; i < mergeData.e.r; i++) {101 // for (var j = mergeData.s.c; j < mergeData.e.c; j++) {102 // com.grid[i][j].s = mergeData.s103 // com.grid[i][j].e = mergeData.e104 // }105 // }106 // }107 // console.log(com.grid)108 // }...

Full Screen

Full Screen

merge.js

Source:merge.js Github

copy

Full Screen

1'use strict';2/**3 * Merges two matrices in all directions4 * 5 * @param {Array} base Base matrix on which merge is performed6 */7function merge(base) {8 return {9 top: (mergeData) => top(base, mergeData),10 bottom: (mergeData) => bottom(base, mergeData),11 left: (mergeData) => left(base, mergeData),12 right: (mergeData) => right(base, mergeData)13 }14}15module.exports = merge;16/**17 * Merges the base matrix with the incoming matrix in the top direction18 * @param {Array} base 19 * @param {Array} mergeData incoming matrix20 */21function top(base, mergeData) {22 let baseWidth = base[0].length || base.length;23 let mergeDataWidth = mergeData[mergeData.length - 1].length || mergeData.length;24 if (baseWidth !== mergeDataWidth) {25 return base;26 }27 if (!Array.isArray(base[0])) {28 base = [base];29 }30 if (!Array.isArray(mergeData[mergeData.length - 1])) {31 mergeData = [mergeData];32 }33 for (let row = mergeData.length - 1; row >= 0; row--) {34 base.unshift(mergeData[row].map((ele) => ele));35 }36 return base;37}38/**39 * Merges the base matrix with the incoming matrix in the bottom direction40 * @param {Array} base 41 * @param {Array} mergeData incoming matrix42 */43function bottom(base, mergeData) {44 let baseWidth = base[base.length - 1].length || base.length;45 let mergeDataWidth = mergeData[0].length || mergeData.length;46 if (baseWidth !== mergeDataWidth) {47 return base;48 }49 if (!Array.isArray(base[base.length - 1])) {50 base = [base];51 }52 if (!Array.isArray(mergeData[0])) {53 mergeData = [mergeData];54 }55 for (let row = 0; row < mergeData.length; row++) {56 base.push(mergeData[row].map((ele) => ele));57 }58 return base;59}60/**61 * Merges the base matrix with the incoming matrix in the left direction62 * @param {Array} base 63 * @param {Array} mergeData incoming matrix64 */65function left(base, mergeData) {66 let baseHeight = base.length;67 let mergeDataHeight = mergeData.length;68 if (!Array.isArray(base[0]) && !Array.isArray(mergeData[0])) {69 base.unshift.apply(base, mergeData);70 return base;71 }72 if (baseHeight !== mergeDataHeight) {73 return base;74 }75 for (let row = 0; row < baseHeight; row++) {76 base[row].unshift.apply(base[row], mergeData[row].map((ele) => ele));77 }78 return base;79}80/**81 * Merges the base matrix with the incoming matrix in the right direction82 * @param {Array} base 83 * @param {Array} mergeData incoming matrix84 */85function right(base, mergeData) {86 let baseHeight = base.length;87 let mergeDataHeight = mergeData.length;88 if (!Array.isArray(base[0]) && !Array.isArray(mergeData[0])) {89 base.push.apply(base, mergeData);90 return base;91 }92 if (baseHeight !== mergeDataHeight) {93 return base;94 }95 for (let row = 0; row < baseHeight; row++) {96 base[row].push.apply(base[row], mergeData[row].map((ele) => ele));97 }98 return base;...

Full Screen

Full Screen

processUri.js

Source:processUri.js Github

copy

Full Screen

1import winston from 'winston';2import axios from 'axios';3import config from './config';4import processTaxonomies from './processTaxonomies';5const inQ = config.get('rabbit:inQueue');6const persistQ = config.get('rabbit:persistQueue');7const isPodcastHeader = json => !!json.items_url;8const isEpisodeFeedPage = json => !!json.items;9const isUser = json => json.length && json[0] && json[0].token;10const getNextPage = (json) => {11 if (json.meta && json.meta.next_url) {12 return json.meta.next_url;13 }14 return undefined;15};16const work = async (doc, channel, msg) => {17 try {18 const res = await axios.get(doc.uri);19 if (res.status >= 200 && res.status < 300) {20 winston.info(`Got file at ${doc.uri}`);21 const mergeData = doc.mergeData || {};22 const data = { ...mergeData, ...res.data };23 let index;24 let type;25 let id;26 if (isEpisodeFeedPage(data)) {27 index = 'episodes';28 type = 'episode';29 } else if (isPodcastHeader(data)) {30 index = 'podcasts';31 type = 'podcast';32 id = doc.mergeData.docId;33 data.taxonomy_hierarchy = processTaxonomies(data);34 } else if (isUser(data)) {35 index = 'people';36 type = 'person';37 id = doc.mergeData.docId;38 } else {39 winston.error(`Unidentifiable document at ${doc.uri}`);40 return channel.ack(msg);41 }42 if (isPodcastHeader(data) || isUser(data)) {43 channel.sendToQueue(persistQ, Buffer.from(JSON.stringify({44 index,45 type,46 id,47 source: data,48 })), { persistent: true });49 } else if (isEpisodeFeedPage(data)) {50 data.items.forEach((item) => {51 channel.sendToQueue(persistQ, Buffer.from(JSON.stringify({52 index,53 type,54 id: item.id,55 source: { ...mergeData, ...item },56 })), { persistent: true });57 });58 }59 if (isPodcastHeader(data)) {60 channel.sendToQueue(inQ, Buffer.from(JSON.stringify({61 uri: data.items_url,62 mergeData: {63 podcast: data,64 },65 })), { persistent: true });66 } else if (isEpisodeFeedPage(data) && getNextPage(data)) {67 channel.sendToQueue(inQ, Buffer.from(JSON.stringify({68 uri: getNextPage(data),69 mergeData: doc.mergeData,70 })), { persistent: true });71 }72 } else {73 winston.error(`Got error code when requesting uri at ${doc.uri}`);74 }75 } catch (e) {76 winston.info(`Failed to get data for ${doc.uri}`);77 }78 return channel.ack(msg);79};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeData } = require('@playwright/test/lib/utils/mergeData');2const { mergeData } = require('@playwright/test/lib/utils/mergeData');3const { test } = require('@playwright/test');4test('test', async ({ page }) => {5 await page.screenshot({ path: `screenshot.png` });6});7const { test } = require('@playwright/test');8test('test', async ({ page }) => {9 await page.screenshot({ path: `screenshot.png` });10});11const { test } = require('@playwright/test');12test('test', async ({ page }) => {13 await page.screenshot({ path: `screenshot.png` });14});15const { test } = require('@playwright/test');16test('test', async ({ page }) => {17 await page.screenshot({ path: `screenshot.png` });18});19const { test } = require('@playwright/test');20test('test', async ({ page }) => {21 await page.screenshot({ path: `screenshot.png` });22});23const { test } = require('@playwright/test');24test('test', async ({ page }) => {25 await page.screenshot({ path: `screenshot.png` });26});27const { test } = require('@playwright/test');28test('test', async ({ page }) => {29 await page.screenshot({ path: `screenshot.png` });30});31const { test } = require('@playwright/test');32test('test', async ({ page }) => {33 await page.screenshot({ path: `screenshot.png` });34});35const { test } = require('@playwright/test');36test('test', async ({ page }) =>

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeData } = require('@playwright/test/lib/utils/mergeData');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 const data1 = await page.context().storageState();5 const data2 = await page.context().storageState();6 const mergedData = mergeData(data1, data2);7 await page.context().setStorageState(mergedData);8});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeData } = require("@playwright/test/lib/server/trace/viewer/traceModel");2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: `example.png` });8 await browser.close();9})();10const { mergeData } = require("@playwright/test/lib/server/trace/viewer/traceModel");11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await page.screenshot({ path: `example.png` });17 await browser.close();18})();19const { mergeData } = require("@playwright/test/lib/server/trace/viewer/traceModel");20const { chromium } = require('playwright');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await page.screenshot({ path: `example.png` });26 await browser.close();27})();28const { mergeData } = require("@playwright/test/lib/server/trace/viewer/traceModel");29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext();33 const page = await context.newPage();34 await page.screenshot({ path: `example.png` });35 await browser.close();36})();37const { mergeData } = require("@playwright/test/lib/server/trace/viewer/traceModel");38const { chromium } = require('playwright');39(async () => {40 const browser = await chromium.launch();41 const context = await browser.newContext();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeData } = require('@playwright/test/lib/utils/mergeData');2const { test } = require('@playwright/test');3const path = require('path');4test('test', async ({ page }) => {5 const data = await mergeData(path.join(__dirname, 'test-results'));6 console.log(data);7});8{9 {10 }11}12{13 {14 }15}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeData } = require('playwright-core/lib/utils/mergeData');2const { test } = require('playwright-test');3const { expect } = require('chai');4test('test', async ({ page }) => {5 const data = { a: 1 };6 const newData = { b: 2 };7 const mergedData = mergeData(data, newData);8 expect(mergedData).to.deep.equal({ a: 1, b: 2 });9});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeData } = require('@playwright/test/lib/server/traceViewer/traceModel');2const traceModel = mergeData(3 require('./trace1.json'),4 require('./trace2.json'),5 require('./trace3.json'),6 require('./trace4.json'),7 require('./trace5.json')8);9console.log(traceModel);10process.exit(0);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeData } = require('playwright-core/lib/utils/mergeData');2const data1 = {3};4const data2 = {5};6const result = mergeData(data1, data2);7console.log(result);8{9}10const { mergeData } = require('playwright-core/lib/utils/mergeData');11const data1 = {12};13const data2 = {14};15const result = mergeData(data1, data2);16console.log(result);17{18}19const { mergeData } = require('playwright-core/lib/utils/mergeData');20const data1 = {21};22const data2 = {23};24const result = mergeData(data1, data2);25console.log(result);26{27}28const { mergeData } = require('playwright-core/lib/utils/mergeData');29const data1 = {30};31const data2 = {32};33const result = mergeData(data1, data2);34console.log(result);35{36}37const { mergeData } = require('playwright-core/lib/utils/mergeData');38const data1 = {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeData } = require('playwright/lib/utils/mergeData');2const { test, expect } = require('@playwright/test');3test('test', async ({ page }) => {4 mergeData({ x: 1 }, { x: 2, y: 3 });5});6{ x: 1, y: 3 }7const { mergeData } = require('playwright/lib/utils/mergeData');8const { test, expect } = require('@playwright/test');9test('test', async ({ page }) => {10 mergeData({ x: 1 }, { x: 2, y: 3 }, { x: 4, z: 5 });11});12{ x: 4, y: 3, z: 5 }13const { mergeData } = require('playwright/lib/utils/mergeData');14const { test, expect } = require('@playwright/test');15test('test', async ({ page }) => {16 mergeData({ x: 1 }, { x: 2, y: 3, z: 5 }, { x: 4, z: 6 });17});18{ x: 4, y: 3, z: 6 }19const { mergeData } = require('playwright/lib/utils/mergeData');20const { test, expect } = require('@playwright/test');21test('test', async ({ page }) => {22 mergeData({ x: 1 }, { x: 2, y: 3, z: 5 }, { x: 4, z: 6 }, { x: 7, z: 8 });23});24{ x: 7, y: 3, z: 8 }25const { mergeData

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeData } = require('playwright/lib/utils/mergeData.js');2const { test } = require('@playwright/test');3test('My Test', async ({ page }) => {4 const data = await page.evaluate(() => {5 return {6 };7 });8 const newData = mergeData(data, { b: 3, c: 4 });9 console.log(newData);10});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeData } = require('playwright/lib/server/trace/recorder/recorderApp');2const data = mergeData([3 {4 {5 "requestHeaders": {},6 "responseHeaders": {},7 "responseContentDataUri": "data:text/plain;charset=utf-8;base64,PGh0bWw+PGhlYWQ+PHRpdGxlPkdvb2dsZTwvdGl0bGU+PC9oZWFkPjxib2R5PjxoMT5Hb29nbGU8L2gxPjwvYm9keT48L2h0bWw+",8 "responseHeadersText": "HTTP/1.1 200 OK\r\nDate: Tue, 02 Mar 2021 06:18:56 GMT\r\nExpires: -1\r\nCache-Control: private, max-age=0\r\nContent-Type: text/html; charset=ISO-8859-1\r\nP3P: CP=\"This is not a P3

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful