How to use postProcess method in mountebank

Best JavaScript code snippet using mountebank

json.js

Source:json.js Github

copy

Full Screen

1// Generated automatically by nearley, version 2.20.12// http://github.com/Hardmath123/nearley3(function () {4function id(x) { return x[0]; }5 //console.clear()6 const lexer = require('./lexer');7 let log = console.log.bind(console)8const fs = require('fs');9const required = (functionName, argumentName, item, type) => {10 if (Type.isUndefined(item)) {11 Type.ArgumentError(`"${argumentName}" is required for "${functionName}" function, but none is provided.`);12 }13 else if (type && type != 'any') {14 if (typeof type === 'string' && Type(item) !== type15 || Array.isArray(type) && !type.includes(Type(item)))16 Type.ArgumentError(`"${argumentName}" at "${functionName}()" must be typeof "${typeof type === 'string' ? type : type.join('/')}", got "${Type(item)}" instead.`);17 }18}19const localVariables = {};20const variables = {21 $this: null22};23const functions = {24 // debugging25 error (message) {26 required('error', 'message', message);27 console.error('>>> ' + message)28 return message29 },30 log (message) {31 required('log', 'message', message);32 log('>>> ' + message)33 return message34 },35 // array <=> string36 join (args, separator) {37 required('join', 'First argument', args, 'array');38 if (args.length === 0)39 return '';40 let result = '';41 args.map(i => functions.String(i));42 return args.join(43 separator !== undefined ? functions.String(separator)44 : undefined45 )46 },47 split (string, separator = '') {48 required('split', 'First argument', string, 'string');49 required('split', 'Second argument', separator, 'string');50 return string.split(separator)51 },52 // math operations53 sqrt (number) {54 required('sqrt', 'First argument', number, 'number');55 return Math.sqrt(number)56 },57 pow (x, y) {58 required('pow', 'First argument', x, 'number');59 required('pow', 'Second argument', y, 'number');60 return Math.pow(x, y)61 },62 length (item) {63 required('length', 'First argument', item, ['array', 'object', 'string']);64 if (Type.isString(item))65 return item.length;66 else {67 return Object.keys(item).length68 }69 },70 random (min, max) {71 if (min === undefined) {72 return +Math.random().toFixed(2)73 } else if (max === undefined) {74 // max = min75 return ~~(Math.random() * min)76 } else {77 if (min > max)78 return 0;79 return ~~(Math.random() * (max - min) + min)80 }81 },82 abs (number) {83 required('abs', 'First argument', number, 'number')84 return Math.abs(number) // bitwise | turn anything inside the () into a number85 },86 invert (hex) {87 required('invert', 'First argument', hex, 'hex')88 return invertHex(hex);89 },90 round (number) {91 required('round', 'First argument', number, 'number')92 return Math.round(number)93 },94 sum (first, second, ...rest) {95 required('sum', 'First argument', first, 'number');96 required('sum', 'Second argument', second, 'number');97 for (let i = 0; i < rest.length; i++) {98 let j = rest[i];99 required('sum', 'All arguments', j, 'number');100 if (j < 0) rest[i] = '(' + rest[i] + ')'101 }102 return eval(`(${first})+(${second})+${rest.length ? rest.join('+') : 0}`);103 },104 reduce (first, second, ...rest) {105 required('sum', 'First argument', first, 'number');106 required('sum', 'Second argument', second, 'number');107 for (let i = 0; i < rest.length; i++) {108 let j = rest[i];109 required('sum', 'All arguments', j, 'number');110 if (j < 0) rest[i] = '(' + rest[i] + ')'111 }112 return eval(`(${first})-(${second})-${rest.length ? rest.join('-') : 0}`);113 },114 multiply (first, second, ...rest) {115 required('sum', 'First argument', first, 'number');116 required('sum', 'Second argument', second, 'number');117 for (let i = 0; i < rest.length; i++) {118 let j = rest[i];119 required('sum', 'All arguments', j, 'number');120 if (j < 0) rest[i] = '(' + rest[i] + ')'121 }122 return eval(`(${first})*(${second})*${rest.length ? rest.join('*') : 1}`);123 },124 divide (first, second, ...rest) {125 required('sum', 'First argument', first, 'number');126 required('sum', 'Second argument', second, 'number');127 if (second === 0)128 Type.ArgumentError(`Function "divide" may accept only the first argument with a value 0.`);129 for (let i = 0; i < rest.length; i++) {130 let j = rest[i];131 required('sum', 'All arguments', j, 'number');132 if (j === 0)133 Type.ArgumentError(`Function "divide()" may accept value 0 only for the first argument.`);134 if (j < 0) rest[i] = '(' + rest[i] + ')'135 }136 return eval(`(${first})/(${second})/${rest.length ? rest.join('/') : 1}`);137 },138 // type convert139 String (item) {140 required('String', 'At least one argument', item)141 switch (Type(item)) {142 case 'object':143 case 'array':144 return JSON.stringify(item);145 default:146 return item + '';147 }148 },149 Number (item) {150 required('Number', 'At least one argument', item)151 return (item)|0 // bitwise | turn anything inside the () into a number152 },153 Boolean (item) {154 required('Boolean', 'At least one argument', item)155 return !!item156 },157 Array (item) {158 required('Array', 'At least one argument', item)159 switch (Type(item)) {160 case 'string':161 return item.split('');162 case 'object':163 return Object.values(item);164 /*case 'number':165 case 'null':166 case 'boolean':167 case 'hex':168 case 'array':*/169 default:170 return [item];171 }172 return []173 },174 Object (item) {175 required('Object', 'At least one argument', item)176 let key = Type(item);177 if (key === 'string')178 try {179 return JSON.parse(item)180 } catch (err) {}181 let obj = {}182 obj[key] = item183 return obj;184 },185 // type check186 isNumber (item) {187 required('isNumber', 'At least one argument', item);188 return Type(item) == 'number'189 },190 isString (item) {191 required('isString', 'At least one argument', item);192 return Type(item) == 'string' || Type(item) == 'hex'193 },194 isArray (item) {195 required('isArray', 'At least one argument', item);196 return Type(item) == 'array'197 },198 isNull (item) {199 required('isNull', 'At least one argument', item);200 return item === null;201 },202 isHex (item) {203 required('isHex', 'At least one argument', item);204 return Type(item) == 'hex';205 },206 // array/object interactions207 push (array, ...rest) {208 required('push', 'First argument', array, 'array');209 if (rest.length)210 for (let i = 0; i < rest.length; i++) {211 let j = rest[i];212 array.push(j);213 }214 else array.push(null)215 return array;216 },217 insert (target, insertable) {218 required('insert', 'First argument', target, ['object', 'array']);219 if (Type.isObject(target)) {220 required('insert', 'Second argument', insertable, 'object');221 return Object.assign(target, insertable);222 } else {223 required('insert', 'Second argument', insertable, 'array');224 return [...target, ...insertable];225 }226 },227 slice (target, start, end) {228 required('slice', 'First argument', target, ['array', 'string']);229 required('slice', 'Second argument', start, 'number');230 if (end === undefined) end = target.length231 else if (typeof end !== 'number') {232 required('slice', 'Third argument', end, 'number');233 }234 let result = null;235 return target.slice(start, end)236 },237 remove (target, item) {238 required('remove', 'First argument', target, ['string', 'object', 'array']);239 let result = null;240 if (Type.isObject(target)) {241 required('remove', 'Second argument', item, 'string');242 result = target[item]243 delete target[item];244 }245 else {246 required('remove', 'Second argument', item, 'number');247 if (Type.isArray(target)) {248 result = target.splice(item, 1)[0]249 } else {250 result = target.split('').splice(item, 1).join('')251 }252 }253 return result === undefined ? null : result;254 },255 reverse (target) {256 required('remove', 'First argument', target, ['string', 'array']);257 if (Type.isString(target)) {258 return target.split('').reverse().join('')259 }260 return target.reverse()261 }262};263//$this.variables = variables;264const Type = require('./Type')265function storeVariable (varName, value) {266 variables[varName] = value;267 return varName268}269function getArrayItem(item) {270 return item === undefined ? null : item;271}272function getValue(varName) {273 if (varName in variables) {274 return variables[varName]275 }276 //console.warn(new Error(`${varName} is not defined. undefined is returned instead.`))277 //variables[varName] = undefined;278 //return undefined;279}280function extractPair(kv, output) {281 if(kv[0]) { output[kv[0]] = kv[1]; }282}283function extractObject(d) {284 let output = {};285 extractPair(d[2], output);286 for (let i in d[3]) {287 extractPair(d[3][i][3], output);288 }289 return output;290}291function extractArray(d) {292 let output = [d[2]];293 for (let i in d[3]) {294 output.push(d[3][i][3]);295 }296 return output;297}298function invertHex(hex) {299 let n = hex.substr(1);300 if (n.length == 3) n = n[0] + n[0] + n[1] + n[1] + n[2] + n[2];301 return `#${(Number(`0x1${n}`) ^ 0xFFFFFF).toString(16).substr(1).toLowerCase()}`;302}303function readFile (fileName) {304 let content = null;305 try {306 // content = await fs.readFile(fileName, 'utf-8')307 content = fs.readFileSync(fileName, 'utf-8')308 /*let p = new sp(function(resolve, reject) {309 resolve(content);310 });311 return p.v*/312 } catch (err) {313 throw err;314 }315 return content;316}317var grammar = {318 Lexer: lexer,319 ParserRules: [320 {"name": "process", "symbols": ["main"], "postprocess": id},321 {"name": "process", "symbols": [(lexer.has("space") ? {type: "space"} : space)], "postprocess": d => ''},322 {"name": "process", "symbols": [], "postprocess": d => ''},323 {"name": "main$ebnf$1", "symbols": []},324 {"name": "main$ebnf$1$subexpression$1$subexpression$1", "symbols": ["var_assign"]},325 {"name": "main$ebnf$1$subexpression$1", "symbols": ["_", "main$ebnf$1$subexpression$1$subexpression$1"]},326 {"name": "main$ebnf$1", "symbols": ["main$ebnf$1", "main$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},327 {"name": "main", "symbols": ["main$ebnf$1", "json"], "postprocess": d => d[1]},328 {"name": "json$subexpression$1", "symbols": ["object"]},329 {"name": "json$subexpression$1", "symbols": ["array"]},330 {"name": "json$subexpression$1", "symbols": ["string"]},331 {"name": "json$subexpression$1", "symbols": ["number"]},332 {"name": "json$subexpression$1", "symbols": ["boolean"]},333 {"name": "json$subexpression$1", "symbols": ["if"]},334 {"name": "json", "symbols": ["_", "json$subexpression$1", "_"], "postprocess": d => {335 return d[1][0];336 } },337 {"name": "json", "symbols": [{"literal":"("}, "_", "json", "_", {"literal":")"}], "postprocess": d => d[2]},338 {"name": "json", "symbols": ["_", "myNull", "_"], "postprocess": d => null},339 {"name": "html", "symbols": [(lexer.has("htmlContent") ? {type: "htmlContent"} : htmlContent)], "postprocess": d => d[0].value},340 {"name": "varName", "symbols": [(lexer.has("variableName") ? {type: "variableName"} : variableName)], "postprocess": d => d[0].value},341 {"name": "variable", "symbols": ["varName"], "postprocess": (d, l, reject) => {342 if (getValue(d[0]) === undefined) return reject;343 return getValue(d[0])344 } },345 {"name": "variable", "symbols": [{"literal":"("}, "_", "variable", "_", {"literal":")"}], "postprocess": d => d[2]},346 {"name": "var_assign$subexpression$1", "symbols": ["if"]},347 {"name": "var_assign$subexpression$1", "symbols": ["import"]},348 {"name": "var_assign$subexpression$1", "symbols": ["string"]},349 {"name": "var_assign$subexpression$1", "symbols": ["number"]},350 {"name": "var_assign$subexpression$1", "symbols": ["html"]},351 {"name": "var_assign$subexpression$1", "symbols": ["boolean"]},352 {"name": "var_assign$subexpression$1", "symbols": ["object"]},353 {"name": "var_assign$subexpression$1", "symbols": ["array"]},354 {"name": "var_assign$subexpression$1", "symbols": ["myNull"]},355 {"name": "var_assign", "symbols": ["varName", "_", {"literal":"="}, "_", "var_assign$subexpression$1", "_", {"literal":";"}], "postprocess": function(d) {356 storeVariable(d[0], d[4][0]);357 return d[4][0];358 } },359 {"name": "is", "symbols": [{"literal":"is"}], "postprocess": d => "is"},360 {"name": "than", "symbols": [{"literal":"?"}], "postprocess": d => "?"},361 {"name": "than", "symbols": [{"literal":"than"}], "postprocess": d => "?"},362 {"name": "else", "symbols": [{"literal":"else"}], "postprocess": d => ":"},363 {"name": "else", "symbols": [{"literal":":"}], "postprocess": d => ":"},364 {"name": "if", "symbols": ["myNull", "_", "than", "_", "value", "_", "else", "_", "value"], "postprocess": d => d[8]},365 {"name": "if", "symbols": ["myNull", "_", "than", "_", "value"], "postprocess": d => null},366 {"name": "if$subexpression$1", "symbols": ["variable"]},367 {"name": "if$subexpression$1", "symbols": ["string"]},368 {"name": "if$subexpression$1", "symbols": ["number"]},369 {"name": "if$subexpression$1", "symbols": ["boolean"]},370 {"name": "if$subexpression$1", "symbols": ["condition"]},371 {"name": "if$subexpression$1", "symbols": ["object"]},372 {"name": "if$subexpression$1", "symbols": ["array"]},373 {"name": "if", "symbols": ["if$subexpression$1", "_", "than", "_", "value", "_", "else", "_", "value"], "postprocess": d => {374 if (Type.mayBeBoolean(d[0][0]))375 return d[0][0] ? d[4] : d[8]376 else if (Type.isObject(d[0][0]) || Type.isArray(d[0][0]))377 return d[4]378 Type.TypeError('boolean convertable', d[0][0]);379 }},380 {"name": "if$subexpression$2", "symbols": ["variable"]},381 {"name": "if$subexpression$2", "symbols": ["string"]},382 {"name": "if$subexpression$2", "symbols": ["number"]},383 {"name": "if$subexpression$2", "symbols": ["boolean"]},384 {"name": "if$subexpression$2", "symbols": ["ondition"]},385 {"name": "if$subexpression$2", "symbols": ["object"]},386 {"name": "if$subexpression$2", "symbols": ["array"]},387 {"name": "if", "symbols": ["if$subexpression$2", "_", "than", "_", "value"], "postprocess": d => {388 if (Type.mayBeBoolean(d[0][0]))389 return d[0][0] ? d[4] : null390 else if (Type.isObject(d[0][0]) || Type.isArray(d[0][0]))391 return d[4]392 Type.TypeError('boolean convertable', d[0][0]);393 }},394 {"name": "condition", "symbols": ["boolean", "_", {"literal":"=="}, "_", "boolean"], "postprocess": d => d[0] === d[4]},395 {"name": "condition", "symbols": ["string", "_", {"literal":"=="}, "_", "string"], "postprocess": d => d[0] === d[4]},396 {"name": "condition", "symbols": ["myNull", "_", {"literal":"=="}, "_", "myNull"], "postprocess": d => d[0] === d[4]},397 {"name": "condition", "symbols": ["array", "_", {"literal":"=="}, "_", "array"], "postprocess": d => JSON.stringify(d[0]) === JSON.stringify(d[4])},398 {"name": "condition", "symbols": ["object", "_", {"literal":"=="}, "_", "object"], "postprocess": d => JSON.stringify(d[0]) === JSON.stringify(d[4])},399 {"name": "condition", "symbols": ["boolean", "_", {"literal":"!="}, "_", "boolean"], "postprocess": d => d[0] !== d[4]},400 {"name": "condition", "symbols": ["string", "_", {"literal":"!="}, "_", "string"], "postprocess": d => d[0] !== d[4]},401 {"name": "condition", "symbols": ["myNull", "_", {"literal":"!="}, "_", "myNull"], "postprocess": d => d[0] !== d[4]},402 {"name": "condition", "symbols": ["array", "_", {"literal":"!="}, "_", "array"], "postprocess": d => JSON.stringify(d[0]) !== JSON.stringify(d[4])},403 {"name": "condition", "symbols": ["object", "_", {"literal":"!="}, "_", "object"], "postprocess": d => JSON.stringify(d[0]) !== JSON.stringify(d[4])},404 {"name": "condition", "symbols": ["number", "_", {"literal":"=="}, "_", "number"], "postprocess": d => d[0] === d[4]},405 {"name": "condition", "symbols": ["number", "_", {"literal":"!="}, "_", "number"], "postprocess": d => d[0] !== d[4]},406 {"name": "condition", "symbols": ["number", "_", {"literal":">"}, "_", "number"], "postprocess": d => d[0] > d[4]},407 {"name": "condition", "symbols": ["number", "_", {"literal":"<"}, "_", "number"], "postprocess": d => d[0] < d[4]},408 {"name": "condition", "symbols": ["number", "_", {"literal":">="}, "_", "number"], "postprocess": d => d[0] >= d[4]},409 {"name": "condition", "symbols": ["number", "_", {"literal":"<="}, "_", "number"], "postprocess": d => d[0] <= d[4]},410 {"name": "condition", "symbols": ["condition", "_", (lexer.has("logical_and") ? {type: "logical_and"} : logical_and), "_", "condition"], "postprocess": d => d[0] && d[4]},411 {"name": "condition", "symbols": ["condition", "_", (lexer.has("logical_or") ? {type: "logical_or"} : logical_or), "_", "condition"], "postprocess": d => d[0] || d[4]},412 {"name": "condition", "symbols": ["conditionalValues", "_", (lexer.has("logical_and") ? {type: "logical_and"} : logical_and), "_", "conditionalValues"], "postprocess": d => d[0] && d[4]},413 {"name": "condition", "symbols": ["condition", "_", (lexer.has("logical_and") ? {type: "logical_and"} : logical_and), "_", "conditionalValues"], "postprocess": d => d[0] && d[4]},414 {"name": "condition", "symbols": ["conditionalValues", "_", (lexer.has("logical_and") ? {type: "logical_and"} : logical_and), "_", "condition"], "postprocess": d => d[0] && d[4]},415 {"name": "condition", "symbols": ["conditionalValues", "_", (lexer.has("logical_or") ? {type: "logical_or"} : logical_or), "_", "conditionalValues"], "postprocess": d => d[0] || d[4]},416 {"name": "condition", "symbols": ["conditionalValues", "_", (lexer.has("logical_or") ? {type: "logical_or"} : logical_or), "_", "condition"], "postprocess": d => d[0] || d[4]},417 {"name": "condition", "symbols": ["condition", "_", (lexer.has("logical_or") ? {type: "logical_or"} : logical_or), "_", "conditionalValues"], "postprocess": d => d[0] || d[4]},418 {"name": "conditionalValues$subexpression$1", "symbols": ["string"]},419 {"name": "conditionalValues$subexpression$1", "symbols": ["number"]},420 {"name": "conditionalValues$subexpression$1", "symbols": ["myNull"]},421 {"name": "conditionalValues$subexpression$1", "symbols": ["array"]},422 {"name": "conditionalValues$subexpression$1", "symbols": ["object"]},423 {"name": "conditionalValues$subexpression$1", "symbols": ["boolean"]},424 {"name": "conditionalValues", "symbols": ["conditionalValues$subexpression$1"], "postprocess": d => d[0][0]},425 {"name": "conditionalValues", "symbols": [{"literal":"("}, "_", "if", "_", {"literal":")"}], "postprocess": d => d[2]},426 {"name": "conditionalValues", "symbols": [{"literal":"("}, "_", "conditionalValues", "_", {"literal":")"}], "postprocess": d => d[2]},427 {"name": "number", "symbols": [(lexer.has("number") ? {type: "number"} : number)], "postprocess": d => parseFloat(d[0].value)},428 {"name": "number", "symbols": [{"literal":"PI"}], "postprocess": d => 3.1415926536},429 {"name": "number", "symbols": [{"literal":"E"}], "postprocess": d => 2.7182818285},430 {"name": "number$subexpression$1", "symbols": ["objectItem"]},431 {"name": "number$subexpression$1", "symbols": ["arrayItem"]},432 {"name": "number$subexpression$1", "symbols": ["variable"]},433 {"name": "number$subexpression$1", "symbols": ["function"]},434 {"name": "number", "symbols": ["number$subexpression$1"], "postprocess": (d, l, reject) => {435 if (!Type.isNumber(d[0][0]))436 return reject;437 return d[0][0];438 } },439 {"name": "string_concat", "symbols": ["string", "_", {"literal":"+"}, "_", "string"], "postprocess": d => d[0] + d[4]},440 {"name": "boolean", "symbols": [{"literal":"not"}, "_", (lexer.has("space") ? {type: "space"} : space), "_", "condition"], "postprocess": d => !d[4]},441 {"name": "boolean", "symbols": ["is", "_", (lexer.has("space") ? {type: "space"} : space), "_", "condition"], "postprocess": d => d[4]},442 {"name": "boolean", "symbols": [{"literal":"!"}, "_", "boolean"], "postprocess": d => !d[2]},443 {"name": "boolean", "symbols": [{"literal":"!"}, "_", {"literal":"("}, "_", "boolean", "_", {"literal":")"}], "postprocess": d => !d[4]},444 {"name": "boolean", "symbols": [{"literal":"true"}], "postprocess": d => true},445 {"name": "boolean", "symbols": [{"literal":"false"}], "postprocess": d => false},446 {"name": "boolean", "symbols": [{"literal":"("}, "_", "boolean", "_", {"literal":")"}], "postprocess": d => d[2]},447 {"name": "boolean", "symbols": [{"literal":"("}, "_", "condition", "_", {"literal":")"}], "postprocess": d => d[2]},448 {"name": "boolean", "symbols": ["variable"], "postprocess": (d, l, reject) => {449 if (Type.isBoolean(d[0]))450 return d[0]451 return reject;452 } },453 {"name": "boolean", "symbols": ["function"], "postprocess": (d, l, reject) => {454 if (typeof d[0] !== 'boolean')455 return reject;456 return d[0]457 } },458 {"name": "myNull", "symbols": [{"literal":"null"}], "postprocess": d => null},459 {"name": "myNull", "symbols": [{"literal":"("}, "_", "myNull", "_", {"literal":")"}], "postprocess": d => d[2]},460 {"name": "myNull$subexpression$1", "symbols": ["objectItem"]},461 {"name": "myNull$subexpression$1", "symbols": ["arrayItem"]},462 {"name": "myNull$subexpression$1", "symbols": ["variable"]},463 {"name": "myNull$subexpression$1", "symbols": ["function"]},464 {"name": "myNull", "symbols": ["myNull$subexpression$1"], "postprocess": (d, l, reject) => {465 if (!Type.isNull(d[0][0]))466 return reject;467 return d[0][0];468 } },469 {"name": "object", "symbols": [{"literal":"{"}, "_", {"literal":"}"}], "postprocess": function(d) { return {}; }},470 {"name": "object$ebnf$1", "symbols": []},471 {"name": "object$ebnf$1$subexpression$1", "symbols": ["_", {"literal":","}, "_", "pair"]},472 {"name": "object$ebnf$1", "symbols": ["object$ebnf$1", "object$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},473 {"name": "object$ebnf$2$subexpression$1", "symbols": ["_", {"literal":","}]},474 {"name": "object$ebnf$2", "symbols": ["object$ebnf$2$subexpression$1"], "postprocess": id},475 {"name": "object$ebnf$2", "symbols": [], "postprocess": function(d) {return null;}},476 {"name": "object", "symbols": [{"literal":"{"}, "_", "pair", "object$ebnf$1", "object$ebnf$2", "_", {"literal":"}"}], "postprocess": extractObject},477 {"name": "object$subexpression$1", "symbols": ["objectItem"]},478 {"name": "object$subexpression$1", "symbols": ["arrayItem"]},479 {"name": "object$subexpression$1", "symbols": ["variable"]},480 {"name": "object$subexpression$1", "symbols": ["function"]},481 {"name": "object", "symbols": ["object$subexpression$1"], "postprocess": (d, l, reject) => {482 if (!Type.isObject(d[0][0]))483 return reject;484 return d[0][0];485 } },486 {"name": "objectItem", "symbols": ["object", "_", {"literal":"["}, "_", "string", "_", {"literal":"]"}], "postprocess": (d, l, reject) => {487 let f = d[0];488 let s = d[4];489 return getArrayItem(f[s]);490 }491 },492 {"name": "pair", "symbols": ["key", "_", {"literal":":"}, "_", "value"], "postprocess": d => [d[0], d[4]]},493 {"name": "key", "symbols": ["string"], "postprocess": id},494 {"name": "key", "symbols": ["property"], "postprocess": id},495 {"name": "property", "symbols": [(lexer.has("property") ? {type: "property"} : property)], "postprocess": d => d[0].value},496 {"name": "array", "symbols": [{"literal":"["}, "_", {"literal":"]"}], "postprocess": function(d) { return []; }},497 {"name": "array$ebnf$1", "symbols": []},498 {"name": "array$ebnf$1$subexpression$1", "symbols": ["_", {"literal":","}, "_", "value"]},499 {"name": "array$ebnf$1", "symbols": ["array$ebnf$1", "array$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},500 {"name": "array$ebnf$2$subexpression$1", "symbols": ["_", {"literal":","}]},501 {"name": "array$ebnf$2", "symbols": ["array$ebnf$2$subexpression$1"], "postprocess": id},502 {"name": "array$ebnf$2", "symbols": [], "postprocess": function(d) {return null;}},503 {"name": "array", "symbols": [{"literal":"["}, "_", "value", "array$ebnf$1", "array$ebnf$2", "_", {"literal":"]"}], "postprocess": extractArray},504 {"name": "array$subexpression$1", "symbols": ["objectItem"]},505 {"name": "array$subexpression$1", "symbols": ["arrayItem"]},506 {"name": "array$subexpression$1", "symbols": ["variable"]},507 {"name": "array$subexpression$1", "symbols": ["function"]},508 {"name": "array", "symbols": ["array$subexpression$1"], "postprocess": (d, l, reject) => {509 if (!Type.isArray(d[0][0]))510 return reject;511 return d[0][0];512 } },513 {"name": "arrayItem", "symbols": ["array", "_", {"literal":"["}, "_", "number", "_", {"literal":"]"}], "postprocess": (d, l, reject) => {514 let f = d[0];515 let s = d[4];516 return getArrayItem(f[s])517 }518 },519 {"name": "arrayItem", "symbols": ["array", "_", {"literal":"["}, "_", {"literal":"]"}], "postprocess": (d, l, reject) => {520 let f = d[0];521 let s = f.length-1;522 return getArrayItem(f[s])523 }524 },525 {"name": "function$subexpression$1$subexpression$1", "symbols": ["string"]},526 {"name": "function$subexpression$1$subexpression$1", "symbols": ["array"]},527 {"name": "function$subexpression$1$subexpression$1", "symbols": ["object"]},528 {"name": "function$subexpression$1", "symbols": ["function$subexpression$1$subexpression$1"], "postprocess": d => {529 let n = Object.values(d[0][0]);530 if (n === undefined) return null;531 return d[0][0];532 } },533 {"name": "function$ebnf$1$subexpression$1", "symbols": ["_", {"literal":"."}, "_", (lexer.has("functionName") ? {type: "functionName"} : functionName), "arguments"]},534 {"name": "function$ebnf$1", "symbols": ["function$ebnf$1$subexpression$1"]},535 {"name": "function$ebnf$1$subexpression$2", "symbols": ["_", {"literal":"."}, "_", (lexer.has("functionName") ? {type: "functionName"} : functionName), "arguments"]},536 {"name": "function$ebnf$1", "symbols": ["function$ebnf$1", "function$ebnf$1$subexpression$2"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},537 {"name": "function", "symbols": [{"literal":"for"}, "_", "function$subexpression$1", "_", {"literal":"=>"}, "function$ebnf$1"], "postprocess": d => {538 if (d[2] === null) throw 'Unexpected input in for loop.';539 let array = [];540 if (Type.isObject(d[2])) {541 array = {};542 }543 let keys = Object.keys(d[2])544 let values = Object.values(d[2])545 if (keys.length === 0) return d[2];546 for (let i = 0; i < keys.length; i++) {547 let value = functions[d[5][0][3].value](d[2][keys[i]], ...d[5][0][4]);548 for (let j = 1; j < d[5].length; j++) {549 let c = d[5][j];550 if (!functions[c[3].value]) {551 Type.Error('Function is not defined.');552 }553 value = functions[c[3]](554 value, ...c[4]555 );556 }557 558 if (Type.isObject(d[2])) {559 array[keys[i]] = value;560 }561 else array.push(value);562 }563 return array;564 } },565 {"name": "function", "symbols": [(lexer.has("functionName") ? {type: "functionName"} : functionName), "arguments"], "postprocess": d => {566 if (!functions[d[0]])567 Type.Error('Function is not defined.')568 return functions[d[0].value](...d[1]);569 } },570 {"name": "function$subexpression$2", "symbols": ["string"]},571 {"name": "function$subexpression$2", "symbols": ["number"]},572 {"name": "function$subexpression$2", "symbols": ["array"]},573 {"name": "function$subexpression$2", "symbols": ["object"]},574 {"name": "function", "symbols": ["function$subexpression$2", "_", {"literal":"=>"}, "_", (lexer.has("functionName") ? {type: "functionName"} : functionName), "arguments"], "postprocess": d => {575 if (!functions[d[4]])576 Type.Error('Function is not defined.')577 return functions[d[4].value](d[0][0], ...d[5]);578 } },579 {"name": "arguments", "symbols": [{"literal":"("}, "_", {"literal":")"}], "postprocess": d => []},580 {"name": "arguments$ebnf$1", "symbols": []},581 {"name": "arguments$ebnf$1$subexpression$1", "symbols": ["_", {"literal":","}, "_", "value"]},582 {"name": "arguments$ebnf$1", "symbols": ["arguments$ebnf$1", "arguments$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},583 {"name": "arguments$ebnf$2$subexpression$1", "symbols": ["_", {"literal":","}]},584 {"name": "arguments$ebnf$2", "symbols": ["arguments$ebnf$2$subexpression$1"], "postprocess": id},585 {"name": "arguments$ebnf$2", "symbols": [], "postprocess": function(d) {return null;}},586 {"name": "arguments", "symbols": [{"literal":"("}, "_", "value", "arguments$ebnf$1", "arguments$ebnf$2", "_", {"literal":")"}], "postprocess": d => extractArray(d)},587 {"name": "value", "symbols": [{"literal":"("}, "_", "value", "_", {"literal":")"}], "postprocess": d => d[2]},588 {"name": "value", "symbols": ["if"], "postprocess": id},589 {"name": "value", "symbols": ["html"], "postprocess": id},590 {"name": "value", "symbols": ["condition"], "postprocess": id},591 {"name": "value", "symbols": ["boolean"], "postprocess": id},592 {"name": "value", "symbols": ["object"], "postprocess": id},593 {"name": "value", "symbols": ["array"], "postprocess": id},594 {"name": "value", "symbols": ["import"], "postprocess": id},595 {"name": "value", "symbols": ["number"], "postprocess": id},596 {"name": "value", "symbols": ["hex"], "postprocess": id},597 {"name": "value", "symbols": ["string"], "postprocess": id},598 {"name": "value", "symbols": ["myNull"], "postprocess": d => null},599 {"name": "hex", "symbols": [(lexer.has("hexLong") ? {type: "hexLong"} : hexLong)], "postprocess": d => d[0].value},600 {"name": "hex", "symbols": [(lexer.has("hexShort") ? {type: "hexShort"} : hexShort)], "postprocess": d => d[0].value},601 {"name": "hex", "symbols": [{"literal":"("}, "_", "hex", "_", {"literal":")"}], "postprocess": d => d[2]},602 {"name": "hex", "symbols": ["variable"], "postprocess": (d, l, reject) => {603 if (Type.isHex(d[0]))604 return d[0]605 return reject;606 } },607 {"name": "hex", "symbols": ["function"], "postprocess": (d, l, reject) => {608 if (!Type.isHex(d[0]))609 return reject;610 return d[0];611 } },612 {"name": "string", "symbols": [(lexer.has("dstring") ? {type: "dstring"} : dstring)], "postprocess": d => d[0].value},613 {"name": "string", "symbols": [(lexer.has("sstring") ? {type: "sstring"} : sstring)], "postprocess": d => d[0].value},614 {"name": "string", "symbols": [(lexer.has("tstring") ? {type: "tstring"} : tstring)], "postprocess": d => d[0].value},615 {"name": "string", "symbols": ["hex"], "postprocess": id},616 {"name": "string$subexpression$1", "symbols": ["objectItem"]},617 {"name": "string$subexpression$1", "symbols": ["arrayItem"]},618 {"name": "string$subexpression$1", "symbols": ["variable"]},619 {"name": "string$subexpression$1", "symbols": ["function"]},620 {"name": "string", "symbols": ["string$subexpression$1"], "postprocess": (d, l, reject) => {621 if (!Type.isString(d[0][0]))622 return reject;623 return d[0][0];624 } },625 {"name": "string", "symbols": ["string_concat"], "postprocess": id},626 {"name": "string", "symbols": ["string", "_", {"literal":"["}, "_", "number", "_", {"literal":"]"}], "postprocess": (d, l, reject) => {627 let f = d[0];628 let s = d[4];629 return f[s];630 }631 },632 {"name": "string", "symbols": ["string", "_", {"literal":"["}, "_", {"literal":"]"}], "postprocess": (d, l, reject) => {633 let f = d[0];634 let s = f.length-1635 return f[s];636 } },637 {"name": "WS", "symbols": []},638 {"name": "WS", "symbols": [(lexer.has("space") ? {type: "space"} : space)], "postprocess": d => null},639 {"name": "_$ebnf$1", "symbols": []},640 {"name": "_$ebnf$1$subexpression$1", "symbols": ["WS", (lexer.has("comment") ? {type: "comment"} : comment)]},641 {"name": "_$ebnf$1", "symbols": ["_$ebnf$1", "_$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},642 {"name": "_", "symbols": ["_$ebnf$1", "WS"], "postprocess": d => {}},643 {"name": "semicolon", "symbols": [(lexer.has("semicolon") ? {type: "semicolon"} : semicolon)], "postprocess": d => d[0].value},644 {"name": "import", "symbols": [{"literal":"import"}, "_", "file"], "postprocess": function(d) {645 return d[2];646 } },647 {"name": "file", "symbols": ["string"], "postprocess": function(d, l, reject) {648 if (/\.json$/.test(d[0])) {649 let read = readFile(d[0])650 return JSON.parse(read.trim());651 }652 else {653 console.error(`[File Error]: "${d[0]}" is not found or is not json formated.`)654 return null655 }656 } }657]658 , ParserStart: "process"659}660if (typeof module !== 'undefined'&& typeof module.exports !== 'undefined') {661 module.exports = grammar;662} else {663 window.grammar = grammar;664}...

Full Screen

Full Screen

evaluate_models.py

Source:evaluate_models.py Github

copy

Full Screen

1import torch2import os3import sys4import pathlib5import argparse6from argparse import Namespace7from tqdm import tqdm8TOP_LEVEL_DIRECTORY = str(pathlib.Path(__file__).parent.resolve().parent.absolute())9sys.path.insert(0, TOP_LEVEL_DIRECTORY)10from benchie.benchie import Benchie11from utils import utils12from test import do_eval13from extract import extract14from utils import utils15from dataset import load_data16from thesis.helpers.PostprocessHelper import PostprocessHelper17from thesis.helpers.BenchieHelper import BenchieHelper18def benchie_eval(title, extraction_path, gold_file):19 # Load gold annotations to BenchIE20 benchie = Benchie()21 benchie.load_gold_annotations(filename=gold_file)22 # Add OIE systems extractions23 benchie.add_oie_system_extractions(24 oie_system_name="m2oie_en", filename=extraction_path + '/extraction_benchie_format.txt', silent=True)25 # Compute scores26 benchie.compute_precision()27 benchie.compute_recall()28 benchie.compute_f1()29 print(title)30 benchie.print_scores()31def load_model(args):32 model = utils.get_models(33 bert_config=args.bert_config,34 pred_n_labels=args.pred_n_labels,35 arg_n_labels=args.arg_n_labels,36 n_arg_heads=args.n_arg_heads,37 n_all_conj_expr_heads=args.n_all_conj_expr_heads,38 n_all_conj_term_heads=args.n_all_conj_term_heads,39 n_arg_layers=args.n_arg_layers,40 n_all_conj_expr_layers=args.n_all_conj_expr_layers,41 n_all_conj_term_layers=args.n_all_conj_term_layers,42 pos_emb_dim=args.pos_emb_dim,43 use_lstm=args.use_lstm,44 conj_mode=args.conj_mode,45 device=args.device)46 model.load_state_dict(torch.load(47 args.model_path, map_location=torch.device(args.device)))48 model.zero_grad()49 model.eval()50 return model51def load_test_dataset(args):52 loader = load_data(53 data_path=args.test_data_path,54 batch_size=args.batch_size,55 tokenizer_config=args.bert_config,56 train=False)57 return loader58 59def evaluation_args(args):60 # baseline61 baseline_args = Namespace()62 baseline_args.model_path = args.baseline_model_path63 baseline_args.device = args.device64 baseline_args.visible_device = args.visible_device65 baseline_args.conj_mode = False66 baseline_args = clean_config(baseline_args)67 # method268 method2_args = Namespace()69 method2_args.model_path = args.conj_model_path70 method2_args.device = args.device71 method2_args.visible_device = args.visible_device72 method2_args.conj_mode = True73 method2_args = clean_config(method2_args)74 carb_dataset_args = Namespace()75 carb_dataset_args.test_data_path = args.test_data_carb_path76 carb_dataset_args.bert_config = baseline_args.bert_config77 carb_dataset_args.batch_size = 178 benchie_dataset_args = Namespace()79 benchie_dataset_args.test_data_path = args.test_data_benchie_path80 benchie_dataset_args.bert_config = baseline_args.bert_config81 benchie_dataset_args.batch_size = 182 custom_dataset_args = Namespace()83 custom_dataset_args.test_data_path = args.test_data_custom_benchie_path84 custom_dataset_args.bert_config = baseline_args.bert_config85 custom_dataset_args.batch_size = 186 return baseline_args, method2_args, carb_dataset_args, benchie_dataset_args, custom_dataset_args87def extract_baseline_and_method1(args, baseline_args, baseline_model, carb_dataset, benchie_dataset, custom_benchie_dataset):88 # carb test baseline89 carb_test_baseline_path = args.save_path + '/carb_test_baseline'90 baseline_args.test_data_path = args.test_data_carb_path91 extract(baseline_args, baseline_model, carb_dataset,92 carb_test_baseline_path, conj_mode=baseline_args.conj_mode)93 # carb test method1_ct_sup94 carb_test_postprocess_path = args.save_path + '/carb_test_postprocess'95 os.makedirs(carb_test_postprocess_path, exist_ok=True)96 PostprocessHelper.postprocess(97 carb_test_baseline_path, carb_test_postprocess_path)98 # carb test method1_ct99 carb_test_postprocess_without_supplements_path = args.save_path + '/carb_test_postprocess_without_supplements'100 os.makedirs(carb_test_postprocess_without_supplements_path, exist_ok=True)101 PostprocessHelper.postprocess(102 carb_test_baseline_path, carb_test_postprocess_without_supplements_path, use_supplements=False)103 # benchie baseline104 benchie_baseline_path = args.save_path + '/benchie_baseline'105 baseline_args.test_data_path = args.test_data_benchie_path106 os.makedirs(benchie_baseline_path, exist_ok=True)107 extract(baseline_args, baseline_model, benchie_dataset,108 benchie_baseline_path, conj_mode=baseline_args.conj_mode)109 # benchie method1_ct_sup110 benchie_postprocess_path = args.save_path + '/benchie_postprocess'111 os.makedirs(benchie_postprocess_path, exist_ok=True)112 PostprocessHelper.postprocess(113 benchie_baseline_path, benchie_postprocess_path)114 # benchie method1_ct115 benchie_postprocess_without_supplements_path = args.save_path + '/benchie_postprocess_without_supplements'116 os.makedirs(benchie_postprocess_without_supplements_path, exist_ok=True)117 PostprocessHelper.postprocess(118 benchie_baseline_path, benchie_postprocess_without_supplements_path, use_supplements=False)119 # custom benchie baseline120 custom_benchie_baseline_path = args.save_path + '/custom_benchie_baseline'121 baseline_args.test_data_path = args.test_data_custom_benchie_path122 os.makedirs(custom_benchie_baseline_path, exist_ok=True)123 extract(baseline_args, baseline_model, custom_benchie_dataset,124 custom_benchie_baseline_path, conj_mode=baseline_args.conj_mode)125 # custom benchie method1_ct_sup126 custom_benchie_postprocess_path = args.save_path + '/custom_benchie_postprocess'127 os.makedirs(custom_benchie_postprocess_path, exist_ok=True)128 PostprocessHelper.postprocess(129 custom_benchie_baseline_path, custom_benchie_postprocess_path)130 # custom benchie method1_ct131 custom_benchie_postprocess_without_supplements_path = args.save_path + '/custom_benchie_postprocess_without_supplements'132 os.makedirs(custom_benchie_postprocess_without_supplements_path, exist_ok=True)133 PostprocessHelper.postprocess(134 custom_benchie_baseline_path, custom_benchie_postprocess_without_supplements_path, use_supplements=False)135 # custom1 benchie baseline136 custom1_benchie_baseline_path = args.save_path + '/custom1_benchie_baseline'137 baseline_args.test_data_path = args.test_data_custom_benchie_path138 os.makedirs(custom1_benchie_baseline_path, exist_ok=True)139 extract(baseline_args, baseline_model, custom_benchie_dataset,140 custom1_benchie_baseline_path, conj_mode=baseline_args.conj_mode)141 # custom1 benchie method1_ct_sup142 custom1_benchie_postprocess_path = args.save_path + '/custom1_benchie_postprocess'143 os.makedirs(custom1_benchie_postprocess_path, exist_ok=True)144 PostprocessHelper.postprocess(145 custom1_benchie_baseline_path, custom1_benchie_postprocess_path)146 # custom1 benchie method1147 custom1_benchie_postprocess_without_supplements_path = args.save_path + '/custom1_benchie_postprocess_without_supplements'148 os.makedirs(custom1_benchie_postprocess_without_supplements_path, exist_ok=True)149 PostprocessHelper.postprocess(150 custom1_benchie_baseline_path, custom1_benchie_postprocess_without_supplements_path, use_supplements=False)151 # custom2 benchie baseline152 custom2_benchie_baseline_path = args.save_path + '/custom2_benchie_baseline'153 baseline_args.test_data_path = args.test_data_custom_benchie_path154 os.makedirs(custom2_benchie_baseline_path, exist_ok=True)155 extract(baseline_args, baseline_model, custom_benchie_dataset,156 custom2_benchie_baseline_path, conj_mode=baseline_args.conj_mode)157 # custom2 benchie method1_ct_sup158 custom2_benchie_postprocess_path = args.save_path + '/custom2_benchie_postprocess'159 os.makedirs(custom2_benchie_postprocess_path, exist_ok=True)160 PostprocessHelper.postprocess(161 custom2_benchie_baseline_path, custom2_benchie_postprocess_path)162 # custom2 benchie method1163 custom2_benchie_postprocess_without_supplements_path = args.save_path + '/custom2_benchie_postprocess_without_supplements'164 os.makedirs(custom2_benchie_postprocess_without_supplements_path, exist_ok=True)165 PostprocessHelper.postprocess(166 custom2_benchie_baseline_path, custom2_benchie_postprocess_without_supplements_path, use_supplements=False)167def extract_method2(args, method2_args, method2_model,168 carb_dataset, benchie_dataset, custom_benchie_dataset):169 # carb test method2170 carb_test_method2_path = args.save_path + '/carb_test_method2'171 method2_args.test_data_path = args.test_data_carb_path172 extract(method2_args, method2_model, carb_dataset,173 carb_test_method2_path, conj_mode=method2_args.conj_mode)174 # benchie method2175 benchie_method2_path = args.save_path + '/benchie_method2'176 method2_args.test_data_path = args.test_data_benchie_path177 os.makedirs(benchie_method2_path, exist_ok=True)178 extract(method2_args, method2_model, benchie_dataset,179 benchie_method2_path, conj_mode=method2_args.conj_mode)180 # custom benchie method2181 custom_benchie_method2_path = args.save_path + '/custom_benchie_method2'182 method2_args.test_data_path = args.test_data_custom_benchie_path183 os.makedirs(custom_benchie_method2_path, exist_ok=True)184 extract(method2_args, method2_model, custom_benchie_dataset,185 custom_benchie_method2_path, conj_mode=method2_args.conj_mode)186 # custom1 benchie method2187 custom1_benchie_method2_path = args.save_path + '/custom1_benchie_method2'188 method2_args.test_data_path = args.test_data_custom_benchie_path189 os.makedirs(custom1_benchie_method2_path, exist_ok=True)190 extract(method2_args, method2_model, custom_benchie_dataset,191 custom1_benchie_method2_path, conj_mode=method2_args.conj_mode)192 # custom2 benchie method2193 custom2_benchie_method2_path = args.save_path + '/custom2_benchie_method2'194 method2_args.test_data_path = args.test_data_custom_benchie_path195 os.makedirs(custom2_benchie_method2_path, exist_ok=True)196 extract(method2_args, method2_model, custom_benchie_dataset,197 custom2_benchie_method2_path, conj_mode=method2_args.conj_mode)198def extract_all(args, baseline_args, method2_args, carb_dataset_args, benchie_dataset_args, custom_dataset_args):199 carb_dataset = load_test_dataset(carb_dataset_args)200 benchie_dataset = load_test_dataset(benchie_dataset_args)201 custom_benchie_dataset = load_test_dataset(custom_dataset_args)202 baseline_model = load_model(baseline_args)203 method2_model = load_model(method2_args)204 extract_baseline_and_method1(args, baseline_args, baseline_model,205 carb_dataset, benchie_dataset, custom_benchie_dataset)206 extract_method2(args, method2_args, method2_model,207 carb_dataset, benchie_dataset, custom_benchie_dataset)208def clean_config(config):209 device = torch.device(config.device if torch.cuda.is_available() else 'cpu')210 config.device = device211 config.pred_n_labels = 3212 config.arg_n_labels = 9213 config.conjunction_n_labels = 3214 config.all_conj_expr_n_labels = 3215 config.all_conj_term_n_labels = 3216 config.bert_config = 'bert-base-cased'217 config.pos_emb_dim = 64218 config.n_arg_heads = 8219 config.n_arg_layers = 4220 config.n_all_conj_expr_heads = 8221 config.n_all_conj_expr_layers = 4222 config.n_all_conj_term_heads = 8223 config.n_all_conj_term_layers = 4224 config.use_lstm = False225 config.binary = False226 return config227def evaluate_carb(args):228 baseline_path = args.save_path + '/carb_test_baseline'229 baseline_carb_test_results = do_eval(baseline_path, args.test_gold_path_carb)230 postprocess_path = args.save_path + '/carb_test_postprocess'231 baseline_postprocess_carb_test_results = do_eval(postprocess_path, args.test_gold_path_carb)232 postprocess_without_supplements_path = args.save_path + '/carb_test_postprocess_without_supplements'233 baseline_postprocess_without_supplements_carb_test_results = do_eval(postprocess_without_supplements_path, args.test_gold_path_carb)234 235 method2_path = args.save_path + '/carb_test_method2'236 method2_carb_test_results = do_eval(method2_path, args.test_gold_path_carb)237 238 utils.print_results("CARB BASELINE TEST RESULT", baseline_carb_test_results, [239 "F1 ", "PREC", "REC ", "AUC "])240 utils.print_results("CARB METHOD1_CT TEST RESULT", baseline_postprocess_without_supplements_carb_test_results, [241 "F1 ", "PREC", "REC ", "AUC "])242 utils.print_results("CARB METHOD1_CT_SUP TEST RESULT", baseline_postprocess_carb_test_results, [243 "F1 ", "PREC", "REC ", "AUC "])244 utils.print_results("CARB METHOD2 TEST RESULT", method2_carb_test_results, [245 "F1 ", "PREC", "REC ", "AUC "])246def evaluate_benchie(args):247 benchie_baseline_path = args.save_path + '/benchie_baseline'248 BenchieHelper.fix_format(benchie_baseline_path, args.test_data_benchie_path)249 benchie_postprocess_path = args.save_path + '/benchie_postprocess'250 BenchieHelper.fix_format(benchie_postprocess_path, args.test_data_benchie_path)251 benchie_postprocess_without_supplements_path = args.save_path + '/benchie_postprocess_without_supplements'252 BenchieHelper.fix_format(benchie_postprocess_without_supplements_path, args.test_data_benchie_path)253 benchie_method2_path = args.save_path + '/benchie_method2'254 BenchieHelper.fix_format(benchie_method2_path, args.test_data_benchie_path)255 custom_benchie_baseline_path = args.save_path + '/custom_benchie_baseline'256 BenchieHelper.fix_format(custom_benchie_baseline_path, args.test_data_custom_benchie_path)257 custom_benchie_postprocess_path = args.save_path + '/custom_benchie_postprocess'258 BenchieHelper.fix_format(custom_benchie_postprocess_path, args.test_data_custom_benchie_path)259 custom_benchie_postprocess_without_supplements_path = args.save_path + '/custom_benchie_postprocess_without_supplements'260 BenchieHelper.fix_format(custom_benchie_postprocess_without_supplements_path, args.test_data_custom_benchie_path)261 custom_benchie_method2_path = args.save_path + '/custom_benchie_method2'262 BenchieHelper.fix_format(custom_benchie_method2_path, args.test_data_custom_benchie_path)263 custom1_benchie_baseline_path = args.save_path + '/custom1_benchie_baseline'264 BenchieHelper.fix_format(custom1_benchie_baseline_path, args.test_data_custom_benchie_path)265 custom1_benchie_postprocess_path = args.save_path + '/custom1_benchie_postprocess'266 BenchieHelper.fix_format(custom1_benchie_postprocess_path, args.test_data_custom_benchie_path)267 custom1_benchie_postprocess_without_supplements_path = args.save_path + '/custom1_benchie_postprocess_without_supplements'268 BenchieHelper.fix_format(custom1_benchie_postprocess_without_supplements_path, args.test_data_custom_benchie_path)269 custom1_benchie_method2_path = args.save_path + '/custom1_benchie_method2'270 BenchieHelper.fix_format(custom1_benchie_method2_path, args.test_data_custom_benchie_path)271 custom2_benchie_baseline_path = args.save_path + '/custom2_benchie_baseline'272 BenchieHelper.fix_format(custom2_benchie_baseline_path, args.test_data_custom_benchie_path)273 custom2_benchie_postprocess_path = args.save_path + '/custom2_benchie_postprocess'274 BenchieHelper.fix_format(custom2_benchie_postprocess_path, args.test_data_custom_benchie_path)275 custom2_benchie_postprocess_without_supplements_path = args.save_path + '/custom2_benchie_postprocess_without_supplements'276 BenchieHelper.fix_format(custom2_benchie_postprocess_without_supplements_path, args.test_data_custom_benchie_path)277 custom2_benchie_method2_path = args.save_path + '/custom2_benchie_method2'278 BenchieHelper.fix_format(custom2_benchie_method2_path, args.test_data_custom_benchie_path)279 benchie_eval("Benchie BASELINE", benchie_baseline_path,280 args.test_gold_path_benchie)281 benchie_eval("Benchie CUSTOM BASELINE", custom_benchie_baseline_path,282 args.test_gold_path_custom_benchie)283 benchie_eval("Benchie CUSTOM_1 BASELINE", custom1_benchie_baseline_path,284 args.test_gold_path_custom1_benchie)285 benchie_eval("Benchie CUSTOM_2 BASELINE", custom2_benchie_baseline_path,286 args.test_gold_path_custom2_benchie)287 benchie_eval("Benchie METHOD1_CT", benchie_postprocess_without_supplements_path,288 args.test_gold_path_benchie)289 benchie_eval("Benchie CUSTOM METHOD1_CT", custom_benchie_postprocess_without_supplements_path,290 args.test_gold_path_custom_benchie)291 benchie_eval("Benchie CUSTOM_1 METHOD1_CT", custom1_benchie_postprocess_without_supplements_path,292 args.test_gold_path_custom1_benchie)293 benchie_eval("Benchie CUSTOM_2 METHOD1_CT", custom2_benchie_postprocess_without_supplements_path,294 args.test_gold_path_custom2_benchie)295 benchie_eval("Benchie METHOD1_CT_SUP", benchie_postprocess_path,296 args.test_gold_path_benchie)297 benchie_eval("Benchie CUSTOM METHOD1_CT_SUP", custom_benchie_postprocess_path,298 args.test_gold_path_custom_benchie)299 benchie_eval("Benchie CUSTOM_1 METHOD1_CT_SUP", custom1_benchie_postprocess_path,300 args.test_gold_path_custom1_benchie)301 benchie_eval("Benchie CUSTOM_2 METHOD1_CT_SUP", custom2_benchie_postprocess_path,302 args.test_gold_path_custom2_benchie)303 benchie_eval("Benchie METHOD2", benchie_method2_path,304 args.test_gold_path_benchie)305 benchie_eval("Benchie CUSTOM METHOD2", custom_benchie_method2_path,306 args.test_gold_path_custom_benchie)307 benchie_eval("Benchie CUSTOM_1 METHOD2", custom1_benchie_method2_path,308 args.test_gold_path_custom1_benchie)309 benchie_eval("Benchie CUSTOM_2 METHOD2", custom2_benchie_method2_path,310 args.test_gold_path_custom2_benchie)311def evaluate_all(args):312 evaluate_benchie(args)313 evaluate_carb(args)314def main(args):315 baseline_args, method2_args, carb_dataset_args, benchie_dataset_args, custom_dataset_args = evaluation_args(args)316 317 if not args.skip_extraction:318 extract_all(args, baseline_args, method2_args, carb_dataset_args, benchie_dataset_args, custom_dataset_args)319 evaluate_all(args)320if __name__ == '__main__':321 parser = argparse.ArgumentParser()322 # settings323 parser.add_argument(324 '--baseline_model_path', default='../results/original/baseline_model.bin')325 parser.add_argument(326 '--conj_model_path', default='../results/conj_with_score/conj_model.bin')327 parser.add_argument('--save_path', default='../results/evaluation')328 parser.add_argument('--test_data_benchie_path', default='../datasets/sample300_en.pkl')329 parser.add_argument('--test_data_custom_benchie_path', default='../datasets/sampleCustom_en.pkl')330 parser.add_argument('--test_data_carb_path', default='../datasets/carb_test.pkl')331 parser.add_argument('--test_gold_path_carb', default='../carb/CaRB_test.tsv')332 parser.add_argument('--test_gold_path_benchie', default='../benchie/gold/benchie_gold_annotations_en.txt')333 parser.add_argument('--test_gold_path_custom_benchie', default='../benchie/gold/benchie_gold_annotations_custom.txt')334 parser.add_argument('--test_gold_path_custom1_benchie', default='../benchie/gold/benchie_gold_annotations_custom1.txt')335 parser.add_argument('--test_gold_path_custom2_benchie', default='../benchie/gold/benchie_gold_annotations_custom2.txt')336 parser.add_argument('--device', default='cuda:0')337 parser.add_argument('--visible_device', default="0")338 parser.add_argument("--skip_extraction", action='store_true')339 main_args = parser.parse_args()340 os.environ["CUDA_VISIBLE_DEVICES"] = main_args.visible_device341 os.makedirs(main_args.save_path, exist_ok=True)...

Full Screen

Full Screen

grammar.js

Source:grammar.js Github

copy

Full Screen

1// Generated automatically by nearley, version 2.20.12// http://github.com/Hardmath123/nearley3(function () {4 function id(x) {5 return x[0];6 }7 var grammar = {8 Lexer: undefined,9 ParserRules: [10 {11 name: 'program',12 symbols: ['functions'],13 postprocess: (data) => {14 return {15 functions: data[0],16 };17 },18 },19 {20 name: 'args',21 symbols: [{ literal: '(' }, 'expressions', { literal: ')' }],22 postprocess: (data) => {23 return data[1];24 },25 },26 {27 name: 'args',28 symbols: [{ literal: '(' }, { literal: ')' }],29 postprocess: (data) => {30 return [];31 },32 },33 {34 name: 'data_type$string$1',35 symbols: [36 { literal: 'i' },37 { literal: 'n' },38 { literal: 't' },39 { literal: '8' },40 ],41 postprocess: function joiner(d) {42 return d.join('');43 },44 },45 { name: 'data_type', symbols: ['data_type$string$1'], postprocess: id },46 {47 name: 'data_type$string$2',48 symbols: [49 { literal: 'i' },50 { literal: 'n' },51 { literal: 't' },52 { literal: '1' },53 { literal: '6' },54 ],55 postprocess: function joiner(d) {56 return d.join('');57 },58 },59 { name: 'data_type', symbols: ['data_type$string$2'], postprocess: id },60 {61 name: 'data_type$string$3',62 symbols: [63 { literal: 'i' },64 { literal: 'n' },65 { literal: 't' },66 { literal: '3' },67 { literal: '2' },68 ],69 postprocess: function joiner(d) {70 return d.join('');71 },72 },73 { name: 'data_type', symbols: ['data_type$string$3'], postprocess: id },74 {75 name: 'data_type$string$4',76 symbols: [{ literal: 'i' }, { literal: 'n' }, { literal: 't' }],77 postprocess: function joiner(d) {78 return d.join('');79 },80 },81 { name: 'data_type', symbols: ['data_type$string$4'], postprocess: id },82 {83 name: 'data_type$string$5',84 symbols: [85 { literal: 'i' },86 { literal: 'n' },87 { literal: 't' },88 { literal: '6' },89 { literal: '4' },90 ],91 postprocess: function joiner(d) {92 return d.join('');93 },94 },95 { name: 'data_type', symbols: ['data_type$string$5'], postprocess: id },96 {97 name: 'data_type$string$6',98 symbols: [99 { literal: 'u' },100 { literal: 'i' },101 { literal: 'n' },102 { literal: 't' },103 { literal: '8' },104 ],105 postprocess: function joiner(d) {106 return d.join('');107 },108 },109 { name: 'data_type', symbols: ['data_type$string$6'], postprocess: id },110 {111 name: 'data_type$string$7',112 symbols: [113 { literal: 'u' },114 { literal: 'i' },115 { literal: 'n' },116 { literal: 't' },117 { literal: '1' },118 { literal: '6' },119 ],120 postprocess: function joiner(d) {121 return d.join('');122 },123 },124 { name: 'data_type', symbols: ['data_type$string$7'], postprocess: id },125 {126 name: 'data_type$string$8',127 symbols: [128 { literal: 'u' },129 { literal: 'i' },130 { literal: 'n' },131 { literal: 't' },132 { literal: '3' },133 { literal: '2' },134 ],135 postprocess: function joiner(d) {136 return d.join('');137 },138 },139 { name: 'data_type', symbols: ['data_type$string$8'], postprocess: id },140 {141 name: 'data_type$string$9',142 symbols: [143 { literal: 'u' },144 { literal: 'i' },145 { literal: 'n' },146 { literal: 't' },147 ],148 postprocess: function joiner(d) {149 return d.join('');150 },151 },152 { name: 'data_type', symbols: ['data_type$string$9'], postprocess: id },153 {154 name: 'data_type$string$10',155 symbols: [156 { literal: 'u' },157 { literal: 'i' },158 { literal: 'n' },159 { literal: 't' },160 { literal: '6' },161 { literal: '4' },162 ],163 postprocess: function joiner(d) {164 return d.join('');165 },166 },167 { name: 'data_type', symbols: ['data_type$string$10'], postprocess: id },168 {169 name: 'data_type$string$11',170 symbols: [171 { literal: 'b' },172 { literal: 'o' },173 { literal: 'o' },174 { literal: 'l' },175 ],176 postprocess: function joiner(d) {177 return d.join('');178 },179 },180 { name: 'data_type', symbols: ['data_type$string$11'], postprocess: id },181 {182 name: 'data_type$string$12',183 symbols: [184 { literal: 's' },185 { literal: 't' },186 { literal: 'r' },187 { literal: 'i' },188 { literal: 'n' },189 { literal: 'g' },190 ],191 postprocess: function joiner(d) {192 return d.join('');193 },194 },195 { name: 'data_type', symbols: ['data_type$string$12'], postprocess: id },196 {197 name: 'data_type$string$13',198 symbols: [199 { literal: 'c' },200 { literal: 'h' },201 { literal: 'a' },202 { literal: 'r' },203 ],204 postprocess: function joiner(d) {205 return d.join('');206 },207 },208 { name: 'data_type', symbols: ['data_type$string$13'], postprocess: id },209 {210 name: 'expressions',211 symbols: ['___', 'expression', '___'],212 postprocess: (data) => [data[1]],213 },214 {215 name: 'expressions',216 symbols: ['___', 'expression', '___', { literal: ',' }, 'expressions'],217 postprocess: (data) => [data[1], ...data[4]],218 },219 {220 name: 'functions',221 symbols: ['___', 'function', '___'],222 postprocess: (data) => [data[1]],223 },224 {225 name: 'functions',226 symbols: ['___', 'function', '___', { literal: '\n' }, 'functions'],227 postprocess: (data) => [data[1], ...data[4]],228 },229 {230 name: 'function',231 symbols: ['identifier', '___', 'args', '___', 'block_statements'],232 postprocess: (data) => {233 return {234 type: 'function',235 return: 'int32',236 return_default: true,237 name: data[0],238 args: data[2],239 stmts: data[4],240 };241 },242 },243 {244 name: 'function',245 symbols: [246 'data_type',247 '___',248 'identifier',249 '___',250 'args',251 '___',252 'block_statements',253 ],254 postprocess: (data) => {255 return {256 type: 'function',257 return: data[0],258 name: data[2],259 args: data[4],260 stmts: data[6],261 };262 },263 },264 {265 name: 'function',266 symbols: ['data_type', '___', 'identifier', '___', 'block_statements'],267 postprocess: (data) => {268 return {269 type: 'function',270 return: data[0],271 name: data[2],272 args: [],273 stmts: data[4],274 };275 },276 },277 {278 name: 'function',279 symbols: ['identifier', '___', 'block_statements'],280 postprocess: (data) => {281 return {282 type: 'function',283 return: 'int32',284 return_default: true,285 name: data[0],286 args: [],287 stmts: data[2],288 };289 },290 },291 {292 name: 'block_statements',293 symbols: [{ literal: '{' }, 'statements', { literal: '}' }],294 postprocess: (data) => {295 return data[1];296 },297 },298 {299 name: 'block_statements',300 symbols: [{ literal: '{' }, '___', { literal: '}' }],301 postprocess: (data) => {302 return [];303 },304 },305 {306 name: 'statements',307 symbols: ['___', 'statement', '___'],308 postprocess: (data) => [data[1]],309 },310 {311 name: 'statements',312 symbols: ['___', 'statement', '___', { literal: '\n' }, 'statements'],313 postprocess: (data) => [data[1], ...data[4]],314 },315 { name: 'statement', symbols: ['var_assignment'], postprocess: id },316 { name: 'statement', symbols: ['print_statement'], postprocess: id },317 { name: 'statement', symbols: ['while_loop'], postprocess: id },318 {319 name: 'while_loop$string$1',320 symbols: [321 { literal: 'w' },322 { literal: 'h' },323 { literal: 'i' },324 { literal: 'l' },325 { literal: 'e' },326 ],327 postprocess: function joiner(d) {328 return d.join('');329 },330 },331 {332 name: 'while_loop',333 symbols: [334 'while_loop$string$1',335 '__',336 'binary_expression',337 '__',338 { literal: '{' },339 '_',340 { literal: '\n' },341 'statements',342 { literal: '\n' },343 { literal: '}' },344 ],345 postprocess: (data) => {346 return {347 type: 'while_loop',348 condition: data[2],349 body: data[7],350 };351 },352 },353 {354 name: 'print_statement$string$1',355 symbols: [356 { literal: 'p' },357 { literal: 'r' },358 { literal: 'i' },359 { literal: 'n' },360 { literal: 't' },361 ],362 postprocess: function joiner(d) {363 return d.join('');364 },365 },366 {367 name: 'print_statement',368 symbols: ['print_statement$string$1', '__', 'expression'],369 postprocess: (data) => {370 return {371 type: 'print_statement',372 expression: data[2],373 };374 },375 },376 { name: 'expression', symbols: ['unary_expression'], postprocess: id },377 { name: 'expression', symbols: ['binary_expression'], postprocess: id },378 { name: 'unary_expression', symbols: ['number'], postprocess: id },379 { name: 'unary_expression', symbols: ['identifier'], postprocess: id },380 { name: 'operator', symbols: [{ literal: '+' }], postprocess: id },381 { name: 'operator', symbols: [{ literal: '-' }], postprocess: id },382 { name: 'operator', symbols: [{ literal: '*' }], postprocess: id },383 { name: 'operator', symbols: [{ literal: '/' }], postprocess: id },384 {385 name: 'operator$string$1',386 symbols: [{ literal: '>' }, { literal: '=' }],387 postprocess: function joiner(d) {388 return d.join('');389 },390 },391 { name: 'operator', symbols: ['operator$string$1'], postprocess: id },392 {393 name: 'operator$string$2',394 symbols: [{ literal: '<' }, { literal: '=' }],395 postprocess: function joiner(d) {396 return d.join('');397 },398 },399 { name: 'operator', symbols: ['operator$string$2'], postprocess: id },400 { name: 'operator', symbols: [{ literal: '>' }], postprocess: id },401 { name: 'operator', symbols: [{ literal: '<' }], postprocess: id },402 { name: 'operator', symbols: [{ literal: '=' }], postprocess: id },403 {404 name: 'binary_expression',405 symbols: ['unary_expression', '_', 'operator', '_', 'expression'],406 postprocess: (data) => {407 return {408 type: 'binary_expression',409 left: data[0],410 operator: data[2],411 right: data[4],412 };413 },414 },415 {416 name: 'var_assignment$string$1',417 symbols: [{ literal: ':' }, { literal: '=' }],418 postprocess: function joiner(d) {419 return d.join('');420 },421 },422 {423 name: 'var_assignment',424 symbols: [425 'identifier',426 '_',427 'var_assignment$string$1',428 '_',429 'expression',430 ],431 postprocess: (data) => {432 return {433 type: 'var_assignment',434 varname: data[0],435 value: data[4],436 };437 },438 },439 { name: 'identifier$ebnf$1', symbols: [/[a-z]/] },440 {441 name: 'identifier$ebnf$1',442 symbols: ['identifier$ebnf$1', /[a-z]/],443 postprocess: function arrpush(d) {444 return d[0].concat([d[1]]);445 },446 },447 {448 name: 'identifier',449 symbols: ['identifier$ebnf$1'],450 postprocess: (data) => data[0].join(''),451 },452 {453 name: 'number',454 symbols: ['digits', { literal: '.' }, 'digits'],455 postprocess: (data) => Number(data[0] + '.' + data[2]),456 },457 {458 name: 'number',459 symbols: ['digits'],460 postprocess: (data) => Number(data[0]),461 },462 { name: 'digits$ebnf$1', symbols: [/[0-9]/] },463 {464 name: 'digits$ebnf$1',465 symbols: ['digits$ebnf$1', /[0-9]/],466 postprocess: function arrpush(d) {467 return d[0].concat([d[1]]);468 },469 },470 {471 name: 'digits',472 symbols: ['digits$ebnf$1'],473 postprocess: (data) => data[0].join(''),474 },475 { name: '_$ebnf$1', symbols: [] },476 {477 name: '_$ebnf$1',478 symbols: ['_$ebnf$1', /[ \t]/],479 postprocess: function arrpush(d) {480 return d[0].concat([d[1]]);481 },482 },483 { name: '_', symbols: ['_$ebnf$1'] },484 { name: '__$ebnf$1', symbols: [/[ \t]/] },485 {486 name: '__$ebnf$1',487 symbols: ['__$ebnf$1', /[ \t]/],488 postprocess: function arrpush(d) {489 return d[0].concat([d[1]]);490 },491 },492 { name: '__', symbols: ['__$ebnf$1'] },493 { name: '___$ebnf$1', symbols: [] },494 {495 name: '___$ebnf$1',496 symbols: ['___$ebnf$1', /[ \t\n]/],497 postprocess: function arrpush(d) {498 return d[0].concat([d[1]]);499 },500 },501 { name: '___', symbols: ['___$ebnf$1'] },502 ],503 ParserStart: 'program',504 };505 if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {506 module.exports = grammar;507 } else {508 window.grammar = grammar;509 }...

Full Screen

Full Screen

test_polyoptions.py

Source:test_polyoptions.py Github

copy

Full Screen

1"""Tests for options manager for :class:`Poly` and public API functions. """2from sympy.polys.polyoptions import (3 Options, Expand, Gens, Wrt, Sort, Order, Field, Greedy, Domain,4 Split, Gaussian, Extension, Modulus, Symmetric, Strict, Auto,5 Frac, Formal, Polys, Include, All, Gen, Symbols, Method)6from sympy.polys.orderings import lex7from sympy.polys.domains import FF, GF, ZZ, QQ, EX8from sympy.polys.polyerrors import OptionError, GeneratorsError9from sympy import Integer, Symbol, I, sqrt10from sympy.utilities.pytest import raises11from sympy.abc import x, y, z12def test_Options_clone():13 opt = Options((x, y, z), {'domain': 'ZZ'})14 assert opt.gens == (x, y, z)15 assert opt.domain == ZZ16 assert ('order' in opt) is False17 new_opt = opt.clone({'gens': (x, y), 'order': 'lex'})18 assert opt.gens == (x, y, z)19 assert opt.domain == ZZ20 assert ('order' in opt) is False21 assert new_opt.gens == (x, y)22 assert new_opt.domain == ZZ23 assert ('order' in new_opt) is True24def test_Expand_preprocess():25 assert Expand.preprocess(False) is False26 assert Expand.preprocess(True) is True27 assert Expand.preprocess(0) is False28 assert Expand.preprocess(1) is True29 raises(OptionError, lambda: Expand.preprocess(x))30def test_Expand_postprocess():31 opt = {'expand': True}32 Expand.postprocess(opt)33 assert opt == {'expand': True}34def test_Gens_preprocess():35 assert Gens.preprocess((None,)) == ()36 assert Gens.preprocess((x, y, z)) == (x, y, z)37 assert Gens.preprocess(((x, y, z),)) == (x, y, z)38 a = Symbol('a', commutative=False)39 raises(GeneratorsError, lambda: Gens.preprocess((x, x, y)))40 raises(GeneratorsError, lambda: Gens.preprocess((x, y, a)))41def test_Gens_postprocess():42 opt = {'gens': (x, y)}43 Gens.postprocess(opt)44 assert opt == {'gens': (x, y)}45def test_Wrt_preprocess():46 assert Wrt.preprocess(x) == ['x']47 assert Wrt.preprocess('') == []48 assert Wrt.preprocess(' ') == []49 assert Wrt.preprocess('x,y') == ['x', 'y']50 assert Wrt.preprocess('x y') == ['x', 'y']51 assert Wrt.preprocess('x, y') == ['x', 'y']52 assert Wrt.preprocess('x , y') == ['x', 'y']53 assert Wrt.preprocess(' x, y') == ['x', 'y']54 assert Wrt.preprocess(' x, y') == ['x', 'y']55 assert Wrt.preprocess([x, y]) == ['x', 'y']56 raises(OptionError, lambda: Wrt.preprocess(','))57 raises(OptionError, lambda: Wrt.preprocess(0))58def test_Wrt_postprocess():59 opt = {'wrt': ['x']}60 Wrt.postprocess(opt)61 assert opt == {'wrt': ['x']}62def test_Sort_preprocess():63 assert Sort.preprocess([x, y, z]) == ['x', 'y', 'z']64 assert Sort.preprocess((x, y, z)) == ['x', 'y', 'z']65 assert Sort.preprocess('x > y > z') == ['x', 'y', 'z']66 assert Sort.preprocess('x>y>z') == ['x', 'y', 'z']67 raises(OptionError, lambda: Sort.preprocess(0))68 raises(OptionError, lambda: Sort.preprocess(set([x, y, z])))69def test_Sort_postprocess():70 opt = {'sort': 'x > y'}71 Sort.postprocess(opt)72 assert opt == {'sort': 'x > y'}73def test_Order_preprocess():74 assert Order.preprocess('lex') == lex75def test_Order_postprocess():76 opt = {'order': True}77 Order.postprocess(opt)78 assert opt == {'order': True}79def test_Field_preprocess():80 assert Field.preprocess(False) is False81 assert Field.preprocess(True) is True82 assert Field.preprocess(0) is False83 assert Field.preprocess(1) is True84 raises(OptionError, lambda: Field.preprocess(x))85def test_Field_postprocess():86 opt = {'field': True}87 Field.postprocess(opt)88 assert opt == {'field': True}89def test_Greedy_preprocess():90 assert Greedy.preprocess(False) is False91 assert Greedy.preprocess(True) is True92 assert Greedy.preprocess(0) is False93 assert Greedy.preprocess(1) is True94 raises(OptionError, lambda: Greedy.preprocess(x))95def test_Greedy_postprocess():96 opt = {'greedy': True}97 Greedy.postprocess(opt)98 assert opt == {'greedy': True}99def test_Domain_preprocess():100 assert Domain.preprocess(ZZ) == ZZ101 assert Domain.preprocess(QQ) == QQ102 assert Domain.preprocess(EX) == EX103 assert Domain.preprocess(FF(2)) == FF(2)104 assert Domain.preprocess(ZZ[x, y]) == ZZ[x, y]105 assert Domain.preprocess('Z') == ZZ106 assert Domain.preprocess('Q') == QQ107 assert Domain.preprocess('ZZ') == ZZ108 assert Domain.preprocess('QQ') == QQ109 assert Domain.preprocess('EX') == EX110 assert Domain.preprocess('FF(23)') == FF(23)111 assert Domain.preprocess('GF(23)') == GF(23)112 raises(OptionError, lambda: Domain.preprocess('Z[]'))113 assert Domain.preprocess('Z[x]') == ZZ[x]114 assert Domain.preprocess('Q[x]') == QQ[x]115 assert Domain.preprocess('ZZ[x]') == ZZ[x]116 assert Domain.preprocess('QQ[x]') == QQ[x]117 assert Domain.preprocess('Z[x,y]') == ZZ[x, y]118 assert Domain.preprocess('Q[x,y]') == QQ[x, y]119 assert Domain.preprocess('ZZ[x,y]') == ZZ[x, y]120 assert Domain.preprocess('QQ[x,y]') == QQ[x, y]121 raises(OptionError, lambda: Domain.preprocess('Z()'))122 assert Domain.preprocess('Z(x)') == ZZ.frac_field(x)123 assert Domain.preprocess('Q(x)') == QQ.frac_field(x)124 assert Domain.preprocess('ZZ(x)') == ZZ.frac_field(x)125 assert Domain.preprocess('QQ(x)') == QQ.frac_field(x)126 assert Domain.preprocess('Z(x,y)') == ZZ.frac_field(x, y)127 assert Domain.preprocess('Q(x,y)') == QQ.frac_field(x, y)128 assert Domain.preprocess('ZZ(x,y)') == ZZ.frac_field(x, y)129 assert Domain.preprocess('QQ(x,y)') == QQ.frac_field(x, y)130 assert Domain.preprocess('Q<I>') == QQ.algebraic_field(I)131 assert Domain.preprocess('QQ<I>') == QQ.algebraic_field(I)132 assert Domain.preprocess('Q<sqrt(2), I>') == QQ.algebraic_field(sqrt(2), I)133 assert Domain.preprocess(134 'QQ<sqrt(2), I>') == QQ.algebraic_field(sqrt(2), I)135 raises(OptionError, lambda: Domain.preprocess('abc'))136def test_Domain_postprocess():137 raises(GeneratorsError, lambda: Domain.postprocess({'gens': (x, y),138 'domain': ZZ[y, z]}))139 raises(GeneratorsError, lambda: Domain.postprocess({'gens': (),140 'domain': EX}))141 raises(GeneratorsError, lambda: Domain.postprocess({'domain': EX}))142def test_Split_preprocess():143 assert Split.preprocess(False) is False144 assert Split.preprocess(True) is True145 assert Split.preprocess(0) is False146 assert Split.preprocess(1) is True147 raises(OptionError, lambda: Split.preprocess(x))148def test_Split_postprocess():149 raises(NotImplementedError, lambda: Split.postprocess({'split': True}))150def test_Gaussian_preprocess():151 assert Gaussian.preprocess(False) is False152 assert Gaussian.preprocess(True) is True153 assert Gaussian.preprocess(0) is False154 assert Gaussian.preprocess(1) is True155 raises(OptionError, lambda: Gaussian.preprocess(x))156def test_Gaussian_postprocess():157 opt = {'gaussian': True}158 Gaussian.postprocess(opt)159 assert opt == {160 'gaussian': True,161 'extension': set([I]),162 'domain': QQ.algebraic_field(I),163 }164def test_Extension_preprocess():165 assert Extension.preprocess(True) is True166 assert Extension.preprocess(1) is True167 assert Extension.preprocess([]) is None168 assert Extension.preprocess(sqrt(2)) == set([sqrt(2)])169 assert Extension.preprocess([sqrt(2)]) == set([sqrt(2)])170 assert Extension.preprocess([sqrt(2), I]) == set([sqrt(2), I])171 raises(OptionError, lambda: Extension.preprocess(False))172 raises(OptionError, lambda: Extension.preprocess(0))173def test_Extension_postprocess():174 opt = {'extension': set([sqrt(2)])}175 Extension.postprocess(opt)176 assert opt == {177 'extension': set([sqrt(2)]),178 'domain': QQ.algebraic_field(sqrt(2)),179 }180 opt = {'extension': True}181 Extension.postprocess(opt)182 assert opt == {'extension': True}183def test_Modulus_preprocess():184 assert Modulus.preprocess(23) == 23185 assert Modulus.preprocess(Integer(23)) == 23186 raises(OptionError, lambda: Modulus.preprocess(0))187 raises(OptionError, lambda: Modulus.preprocess(x))188def test_Modulus_postprocess():189 opt = {'modulus': 5}190 Modulus.postprocess(opt)191 assert opt == {192 'modulus': 5,193 'domain': FF(5),194 }195 opt = {'modulus': 5, 'symmetric': False}196 Modulus.postprocess(opt)197 assert opt == {198 'modulus': 5,199 'domain': FF(5, False),200 'symmetric': False,201 }202def test_Symmetric_preprocess():203 assert Symmetric.preprocess(False) is False204 assert Symmetric.preprocess(True) is True205 assert Symmetric.preprocess(0) is False206 assert Symmetric.preprocess(1) is True207 raises(OptionError, lambda: Symmetric.preprocess(x))208def test_Symmetric_postprocess():209 opt = {'symmetric': True}210 Symmetric.postprocess(opt)211 assert opt == {'symmetric': True}212def test_Strict_preprocess():213 assert Strict.preprocess(False) is False214 assert Strict.preprocess(True) is True215 assert Strict.preprocess(0) is False216 assert Strict.preprocess(1) is True217 raises(OptionError, lambda: Strict.preprocess(x))218def test_Strict_postprocess():219 opt = {'strict': True}220 Strict.postprocess(opt)221 assert opt == {'strict': True}222def test_Auto_preprocess():223 assert Auto.preprocess(False) is False224 assert Auto.preprocess(True) is True225 assert Auto.preprocess(0) is False226 assert Auto.preprocess(1) is True227 raises(OptionError, lambda: Auto.preprocess(x))228def test_Auto_postprocess():229 opt = {'auto': True}230 Auto.postprocess(opt)231 assert opt == {'auto': True}232def test_Frac_preprocess():233 assert Frac.preprocess(False) is False234 assert Frac.preprocess(True) is True235 assert Frac.preprocess(0) is False236 assert Frac.preprocess(1) is True237 raises(OptionError, lambda: Frac.preprocess(x))238def test_Frac_postprocess():239 opt = {'frac': True}240 Frac.postprocess(opt)241 assert opt == {'frac': True}242def test_Formal_preprocess():243 assert Formal.preprocess(False) is False244 assert Formal.preprocess(True) is True245 assert Formal.preprocess(0) is False246 assert Formal.preprocess(1) is True247 raises(OptionError, lambda: Formal.preprocess(x))248def test_Formal_postprocess():249 opt = {'formal': True}250 Formal.postprocess(opt)251 assert opt == {'formal': True}252def test_Polys_preprocess():253 assert Polys.preprocess(False) is False254 assert Polys.preprocess(True) is True255 assert Polys.preprocess(0) is False256 assert Polys.preprocess(1) is True257 raises(OptionError, lambda: Polys.preprocess(x))258def test_Polys_postprocess():259 opt = {'polys': True}260 Polys.postprocess(opt)261 assert opt == {'polys': True}262def test_Include_preprocess():263 assert Include.preprocess(False) is False264 assert Include.preprocess(True) is True265 assert Include.preprocess(0) is False266 assert Include.preprocess(1) is True267 raises(OptionError, lambda: Include.preprocess(x))268def test_Include_postprocess():269 opt = {'include': True}270 Include.postprocess(opt)271 assert opt == {'include': True}272def test_All_preprocess():273 assert All.preprocess(False) is False274 assert All.preprocess(True) is True275 assert All.preprocess(0) is False276 assert All.preprocess(1) is True277 raises(OptionError, lambda: All.preprocess(x))278def test_All_postprocess():279 opt = {'all': True}280 All.postprocess(opt)281 assert opt == {'all': True}282def test_Gen_postprocess():283 opt = {'gen': x}284 Gen.postprocess(opt)285 assert opt == {'gen': x}286def test_Symbols_preprocess():287 raises(OptionError, lambda: Symbols.preprocess(x))288def test_Symbols_postprocess():289 opt = {'symbols': [x, y, z]}290 Symbols.postprocess(opt)291 assert opt == {'symbols': [x, y, z]}292def test_Method_preprocess():293 raises(OptionError, lambda: Method.preprocess(10))294def test_Method_postprocess():295 opt = {'method': 'f5b'}296 Method.postprocess(opt)...

Full Screen

Full Screen

nearley-language-bootstrapped.js

Source:nearley-language-bootstrapped.js Github

copy

Full Screen

1// Generated automatically by nearley2// http://github.com/Hardmath123/nearley3(function () {4function id(x) {return x[0]; }5function insensitive(sl) {6 var s = sl.literal;7 result = [];8 for (var i=0; i<s.length; i++) {9 var c = s.charAt(i);10 if (c.toUpperCase() !== c || c.toLowerCase() !== c) {11 result.push(new RegExp("[" + c.toLowerCase() + c.toUpperCase() + "]"));12 } else {13 result.push({literal: c});14 }15 }16 return {subexpression: [{tokens: result, postprocess: function(d) {return d.join(""); }}]};17}18var grammar = {19 Lexer: undefined,20 ParserRules: [21 {"name": "dqstring$ebnf$1", "symbols": []},22 {"name": "dqstring$ebnf$1", "symbols": ["dqstring$ebnf$1", "dstrchar"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},23 {"name": "dqstring", "symbols": [{"literal":"\""}, "dqstring$ebnf$1", {"literal":"\""}], "postprocess": function(d) {return d[1].join(""); }},24 {"name": "sqstring$ebnf$1", "symbols": []},25 {"name": "sqstring$ebnf$1", "symbols": ["sqstring$ebnf$1", "sstrchar"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},26 {"name": "sqstring", "symbols": [{"literal":"'"}, "sqstring$ebnf$1", {"literal":"'"}], "postprocess": function(d) {return d[1].join(""); }},27 {"name": "btstring$ebnf$1", "symbols": []},28 {"name": "btstring$ebnf$1", "symbols": ["btstring$ebnf$1", /[^`]/], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},29 {"name": "btstring", "symbols": [{"literal":"`"}, "btstring$ebnf$1", {"literal":"`"}], "postprocess": function(d) {return d[1].join(""); }},30 {"name": "dstrchar", "symbols": [/[^\\"\n]/], "postprocess": id},31 {"name": "dstrchar", "symbols": [{"literal":"\\"}, "strescape"], "postprocess": 32 function(d) {33 return JSON.parse("\""+d.join("")+"\"");34 }35 },36 {"name": "sstrchar", "symbols": [/[^\\'\n]/], "postprocess": id},37 {"name": "sstrchar", "symbols": [{"literal":"\\"}, "strescape"], "postprocess": function(d) { return JSON.parse("\""+d.join("")+"\""); }},38 {"name": "sstrchar$string$1", "symbols": [{"literal":"\\"}, {"literal":"'"}], "postprocess": function joiner(d) {return d.join('');}},39 {"name": "sstrchar", "symbols": ["sstrchar$string$1"], "postprocess": function(d) {return "'"; }},40 {"name": "strescape", "symbols": [/["\\\/bfnrt]/], "postprocess": id},41 {"name": "strescape", "symbols": [{"literal":"u"}, /[a-fA-F0-9]/, /[a-fA-F0-9]/, /[a-fA-F0-9]/, /[a-fA-F0-9]/], "postprocess": 42 function(d) {43 return d.join("");44 }45 },46 {"name": "final", "symbols": ["whit?", "prog", "whit?"], "postprocess": function(d) { return d[1]; }},47 {"name": "prog", "symbols": ["prod"], "postprocess": function(d) { return [d[0]]; }},48 {"name": "prog", "symbols": ["prod", "whit", "prog"], "postprocess": function(d) { return [d[0]].concat(d[2]); }},49 {"name": "prod$ebnf$1$subexpression$1", "symbols": [{"literal":"-"}]},50 {"name": "prod$ebnf$1$subexpression$1", "symbols": [{"literal":"="}]},51 {"name": "prod$ebnf$1", "symbols": ["prod$ebnf$1$subexpression$1"]},52 {"name": "prod$ebnf$1$subexpression$2", "symbols": [{"literal":"-"}]},53 {"name": "prod$ebnf$1$subexpression$2", "symbols": [{"literal":"="}]},54 {"name": "prod$ebnf$1", "symbols": ["prod$ebnf$1", "prod$ebnf$1$subexpression$2"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},55 {"name": "prod", "symbols": ["word", "whit?", "prod$ebnf$1", {"literal":">"}, "whit?", "expression+"], "postprocess": function(d) { return {name: d[0], rules: d[5]}; }},56 {"name": "prod$ebnf$2$subexpression$1", "symbols": [{"literal":"-"}]},57 {"name": "prod$ebnf$2$subexpression$1", "symbols": [{"literal":"="}]},58 {"name": "prod$ebnf$2", "symbols": ["prod$ebnf$2$subexpression$1"]},59 {"name": "prod$ebnf$2$subexpression$2", "symbols": [{"literal":"-"}]},60 {"name": "prod$ebnf$2$subexpression$2", "symbols": [{"literal":"="}]},61 {"name": "prod$ebnf$2", "symbols": ["prod$ebnf$2", "prod$ebnf$2$subexpression$2"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},62 {"name": "prod", "symbols": ["word", {"literal":"["}, "wordlist", {"literal":"]"}, "whit?", "prod$ebnf$2", {"literal":">"}, "whit?", "expression+"], "postprocess": function(d) {return {macro: d[0], args: d[2], exprs: d[8]}}},63 {"name": "prod", "symbols": [{"literal":"@"}, "whit?", "js"], "postprocess": function(d) { return {body: d[2]}; }},64 {"name": "prod", "symbols": [{"literal":"@"}, "word", "whit", "word"], "postprocess": function(d) { return {config: d[1], value: d[3]}; }},65 {"name": "prod$string$1", "symbols": [{"literal":"@"}, {"literal":"i"}, {"literal":"n"}, {"literal":"c"}, {"literal":"l"}, {"literal":"u"}, {"literal":"d"}, {"literal":"e"}], "postprocess": function joiner(d) {return d.join('');}},66 {"name": "prod", "symbols": ["prod$string$1", "whit?", "string"], "postprocess": function(d) {return {include: d[2].literal, builtin: false}}},67 {"name": "prod$string$2", "symbols": [{"literal":"@"}, {"literal":"b"}, {"literal":"u"}, {"literal":"i"}, {"literal":"l"}, {"literal":"t"}, {"literal":"i"}, {"literal":"n"}], "postprocess": function joiner(d) {return d.join('');}},68 {"name": "prod", "symbols": ["prod$string$2", "whit?", "string"], "postprocess": function(d) {return {include: d[2].literal, builtin: true }}},69 {"name": "expression+", "symbols": ["completeexpression"]},70 {"name": "expression+", "symbols": ["expression+", "whit?", {"literal":"|"}, "whit?", "completeexpression"], "postprocess": function(d) { return d[0].concat([d[4]]); }},71 {"name": "expressionlist", "symbols": ["completeexpression"]},72 {"name": "expressionlist", "symbols": ["expressionlist", "whit?", {"literal":","}, "whit?", "completeexpression"], "postprocess": function(d) { return d[0].concat([d[4]]); }},73 {"name": "wordlist", "symbols": ["word"]},74 {"name": "wordlist", "symbols": ["wordlist", "whit?", {"literal":","}, "whit?", "word"], "postprocess": function(d) { return d[0].concat([d[4]]); }},75 {"name": "completeexpression", "symbols": ["expr"], "postprocess": function(d) { return {tokens: d[0]}; }},76 {"name": "completeexpression", "symbols": ["expr", "whit?", "js"], "postprocess": function(d) { return {tokens: d[0], postprocess: d[2]}; }},77 {"name": "expr_member", "symbols": ["word"], "postprocess": id},78 {"name": "expr_member", "symbols": [{"literal":"$"}, "word"], "postprocess": function(d) {return {mixin: d[1]}}},79 {"name": "expr_member", "symbols": ["word", {"literal":"["}, "expressionlist", {"literal":"]"}], "postprocess": function(d) {return {macrocall: d[0], args: d[2]}}},80 {"name": "expr_member$ebnf$1", "symbols": [{"literal":"i"}], "postprocess": id},81 {"name": "expr_member$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}},82 {"name": "expr_member", "symbols": ["string", "expr_member$ebnf$1"], "postprocess": function(d) { if (d[1]) {return insensitive(d[0]); } else {return d[0]; } }},83 {"name": "expr_member", "symbols": [{"literal":"%"}, "word"], "postprocess": function(d) {return {token: d[1]}}},84 {"name": "expr_member", "symbols": ["charclass"], "postprocess": id},85 {"name": "expr_member", "symbols": [{"literal":"("}, "whit?", "expression+", "whit?", {"literal":")"}], "postprocess": function(d) {return {'subexpression': d[2]} ;}},86 {"name": "expr_member", "symbols": ["expr_member", "whit?", "ebnf_modifier"], "postprocess": function(d) {return {'ebnf': d[0], 'modifier': d[2]}; }},87 {"name": "ebnf_modifier$string$1", "symbols": [{"literal":":"}, {"literal":"+"}], "postprocess": function joiner(d) {return d.join('');}},88 {"name": "ebnf_modifier", "symbols": ["ebnf_modifier$string$1"], "postprocess": id},89 {"name": "ebnf_modifier$string$2", "symbols": [{"literal":":"}, {"literal":"*"}], "postprocess": function joiner(d) {return d.join('');}},90 {"name": "ebnf_modifier", "symbols": ["ebnf_modifier$string$2"], "postprocess": id},91 {"name": "ebnf_modifier$string$3", "symbols": [{"literal":":"}, {"literal":"?"}], "postprocess": function joiner(d) {return d.join('');}},92 {"name": "ebnf_modifier", "symbols": ["ebnf_modifier$string$3"], "postprocess": id},93 {"name": "expr", "symbols": ["expr_member"]},94 {"name": "expr", "symbols": ["expr", "whit", "expr_member"], "postprocess": function(d){ return d[0].concat([d[2]]); }},95 {"name": "word", "symbols": [/[\w\?\+]/], "postprocess": function(d){ return d[0]; }},96 {"name": "word", "symbols": ["word", /[\w\?\+]/], "postprocess": function(d){ return d[0]+d[1]; }},97 {"name": "string", "symbols": ["dqstring"], "postprocess": function(d) {return { literal: d[0] }; }},98 {"name": "charclass", "symbols": [{"literal":"."}], "postprocess": function(d) { return new RegExp("."); }},99 {"name": "charclass", "symbols": [{"literal":"["}, "charclassmembers", {"literal":"]"}], "postprocess": function(d) { return new RegExp("[" + d[1].join('') + "]"); }},100 {"name": "charclassmembers", "symbols": []},101 {"name": "charclassmembers", "symbols": ["charclassmembers", "charclassmember"], "postprocess": function(d) { return d[0].concat([d[1]]); }},102 {"name": "charclassmember", "symbols": [/[^\\\]]/], "postprocess": function(d) { return d[0]; }},103 {"name": "charclassmember", "symbols": [{"literal":"\\"}, /./], "postprocess": function(d) { return d[0] + d[1]; }},104 {"name": "js", "symbols": [{"literal":"{"}, {"literal":"%"}, "jscode", {"literal":"%"}, {"literal":"}"}], "postprocess": function(d) { return d[2]; }},105 {"name": "jscode", "symbols": [], "postprocess": function() {return "";}},106 {"name": "jscode", "symbols": ["jscode", /[^%]/], "postprocess": function(d) {return d[0] + d[1];}},107 {"name": "jscode", "symbols": ["jscode", {"literal":"%"}, /[^}]/], "postprocess": function(d) {return d[0] + d[1] + d[2]; }},108 {"name": "whit", "symbols": ["whitraw"]},109 {"name": "whit", "symbols": ["whitraw?", "comment", "whit?"]},110 {"name": "whit?", "symbols": []},111 {"name": "whit?", "symbols": ["whit"]},112 {"name": "whitraw", "symbols": [/[\s]/]},113 {"name": "whitraw", "symbols": ["whitraw", /[\s]/]},114 {"name": "whitraw?", "symbols": []},115 {"name": "whitraw?", "symbols": ["whitraw"]},116 {"name": "comment", "symbols": [{"literal":"#"}, "commentchars", {"literal":"\n"}]},117 {"name": "commentchars", "symbols": []},118 {"name": "commentchars", "symbols": ["commentchars", /[^\n]/]}119]120 , ParserStart: "final"121}122if (typeof module !== 'undefined'&& typeof module.exports !== 'undefined') {123 module.exports = grammar;124} else {125 window.grammar = grammar;126}...

Full Screen

Full Screen

unittest_handlerPostprocess.py

Source:unittest_handlerPostprocess.py Github

copy

Full Screen

1# Test under:2# CASA 5.4.03# 4# How to run:5# casapy-5.4.0 -c "exec(open('test_scripts/unittest_handlerPostprocess.py','r').read())"6# 7# TODO: 8# 9# DONE: 10# Needs to add 'do_revert_to_singlescale' argument to the 'handlerPostprocess.loop_postprocess' function.11# Ran 14 tests in 33836.663s12# 13from __future__ import print_function14import os, sys, shutil, logging, unittest15logging.basicConfig()16logger = logging.getLogger(__name__)17logger.setLevel(logging.DEBUG)18sys.path.append('.')19from phangsPipeline import handlerTemplate20from phangsPipeline import handlerKeys21from phangsPipeline import handlerPostprocess22from phangsPipeline import utilsFilenames23if sys.version_info.major <= 2:24 reload(handlerTemplate)25 reload(handlerKeys)26 reload(handlerPostprocess)27 reload(utilsFilenames)28class test_postprocess_handler(unittest.TestCase):29 30 key_handler = None31 postprocess_handler = None32 current_dir = None33 passed_steps = None34 35 def setUp(self):36 self.current_dir = os.getcwd()37 38 @classmethod39 def setUpClass(cls):40 # requires Python >= 2.741 cls.key_handler = handlerKeys.KeyHandler(master_key = 'test_keys/master_key.txt', dochecks = False)42 cls.postprocess_handler = handlerPostprocess.PostProcessHandler(key_handler = cls.key_handler)43 #cls.key_handler.get_vis_filename = utilsFilenames.get_vis_filename44 #cls.key_handler.get_cube_filename = utilsFilenames.get_cube_filename45 #self.key_handler._key_dir = os.getcwd()+os.sep+'key_templates'+os.sep46 #self.key_handler._imaging_root = os.getcwd()+os.sep+'test'+os.sep+'imaging'+os.sep47 #self.key_handler._postprocess_root = os.getcwd()+os.sep+'test'+os.sep+'postprocess'+os.sep48 #self.key_handler._product_root = os.getcwd()+os.sep+'test'+os.sep+'product'+os.sep49 #if not os.path.isdir(self.key_handler._postprocess_root):50 # os.makedirs(self.key_handler._postprocess_root)51 cls.passed_steps = []52 #cls.passed_steps = ['dirty','cleanmask','multiscale','singlescale']53 54 def tearDown(self):55 #if self.key_handler is not None:56 # del self.key_handler57 #if self.postprocess_handler is not None:58 # del self.postprocess_handler59 if self.current_dir is not None:60 os.chdir(self.current_dir)61 #if os.path.isdir('test'):62 # shutil.rmtree('test')63 pass64 65 def test_initialize_key_handler(self):66 assert self.key_handler is not None67 68 def test_initialize_postprocess_handler(self):69 assert self.postprocess_handler is not None70 71 def test_do_prep(self):72 if 'prep' in self.passed_steps:73 return74 #target = self.key_handler.get_targets()[0]75 product = 'co21' # self.key_handler.get_line_products()[0]76 #self.postprocess_handler.set_targets(only=[target])77 self.postprocess_handler.set_line_products(only=[product])78 self.postprocess_handler.set_no_cont_products(True)79 self.postprocess_handler.set_interf_configs(only=['7m','12m+7m'])80 #self.postprocess_handler.set_no_feather_configs(True)81 # 82 self.postprocess_handler.loop_postprocess(\83 do_prep=True,84 do_feather=False, 85 do_mosaic=False,86 do_cleanup=False,87 do_convolve=False,88 feather_apod=False, 89 feather_noapod=False,90 feather_before_mosaic=False,91 feather_after_mosaic=False,92 )93 # 94 for config in self.key_handler.get_interf_configs():95 assert utilsFilenames.get_cube_filename(target = target, config = config, product = product, ext = 'trimmed', casa = True, casaext = '.image') is not None96 this_cube_filename = utilsFilenames.get_cube_filename(target = target, config = config, product = product, ext = 'trimmed', casa = True, casaext = '.image')97 logger.debug('%r %s %s'%(this_cube_filename, 'isdir?', os.path.isdir(this_cube_filename) ) )98 assert os.path.isdir(this_cube_filename)99 100if __name__ == '__main__':101 unittest.main(exit=False)102else:...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var imposters = [{3 "stubs": [{4 "responses": [{5 "is": {6 "headers": {7 },8 }9 }]10 }]11}];12var options = {13};14mb.start(options, function () {15 mb.createImposter(2525, imposters[0], function (error, imposter) {16 console.log(imposter.port);17 });18});19module.exports = function (request, response) {20 response.body = 'Hello, world!';21 return response;22};23module.exports = function (request, response) {24 response.body = 'Hello, world!';25 return response;26};

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2mb.create({3}, function (error, server) {4 if (error) {5 console.error(error);6 } else {7 console.log('mountebank server started on port', server.port);8 }9});10mb.postProcess({11 {12 {13 is: {14 headers: {15 },16 }17 }18 }19}, function (error, result) {20 if (error) {21 console.error(error);22 } else {23 console.log('Successfully created stubs:', result);24 }25});26var mb = require('mountebank');27mb.create({28}, function (error, server) {29 if (error) {30 console.error(error);31 } else {32 console.log('mountebank server started on port', server.port);33 }34});35mb.postProcess({36 {37 {38 is: {39 headers: {40 },41 }42 }43 }44}, function (error, result) {45 if (error) {46 console.error(error);47 } else {48 console.log('Successfully created stubs:', result);49 }50});51var mb = require('mountebank');52mb.create({

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var fs = require('fs');3var imposter = JSON.parse(fs.readFileSync('imposter.json', 'utf8'));4mb.create(imposter, 2525).then(function (result) {5 console.log(result);6});7{8 {9 {10 "is": {11 "headers": {12 },13 }14 }15 }16 "postProcess": "function (request, response) { response.body += '!!!'; }"17}18var mb = require('mountebank');19var fs = require('fs');20var imposter = JSON.parse(fs.readFileSync('imposter.json', 'utf8'));21mb.create(imposter, 2525).then(function (result) {22 console.log(result);23});24{25 {26 {27 "is": {28 "headers": {29 },30 "body": {31 }32 }33 }34 }35 "postProcess": "function (request, response) { response.body = JSON.stringify({ name: 'John', age: 30 }); }"36}37The response body is {"name":"John","age":30}38var mb = require('mountebank');39var fs = require('fs');

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposters = require('mountebank').create();2var server = imposters.postProcess({3  callback: function (request, response, logger, next) {4    logger.info('post-processed request for ' + request.path);5    next();6  }7});8server.then(function () {9  console.log('post-processing server started');10});11var imposters = require('mountebank').create();12var server = imposters.postProcess({13  callback: function (request, response, logger, next) {14    logger.info('post-processed request for ' + request.path);15    next();16  }17});18server.then(function () {19  console.log('post-processing server started');20});21var imposters = require('mountebank').create();22var server = imposters.postProcess({23  callback: function (request, response, logger, next) {24    logger.info('post-processed request for ' + request.path);25    next();26  }27});28server.then(function () {29  console.log('post-processing server started');30});31var imposters = require('mountebank').create();32var server = imposters.postProcess({33  callback: function (request, response, logger, next) {34    logger.info('post-processed request for ' + request.path);35    next();36  }37});38server.then(function () {39  console.log('post-processing server started');40});41var imposters = require('

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const fs = require('fs');3const path = require('path');4const imposter = { port: 3000, protocol: 'http' };5const response = { statusCode: 200, headers: { 'Content-Type': 'text/html' }, body: 'Hello World' };6const predicate = { path: '/test', method: 'GET' };7const stub = { responses: [response], predicates: [predicate] };8const imposters = [imposter];9const config = { imposters: imposters, stubs: [stub] };10mb.start(config, () => {11 console.log('Mountebank started');12});13mb.post('/imposters', imposter, () => {14 console.log('Imposter created');15});16mb.post('/imposters/3000/stubs', stub, () => {17 console.log('Stub created');18});

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank'),2 assert = require('assert'),3 Q = require('q'),4 http = require('http');5mb.create({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log' })6.then(function (imposters) {7 return imposters[0].post({8 stubs: [{9 responses: [{10 is: { body: 'Hello world' }11 }]12 }]13 });14})15.then(function (imposter) {16 return Q.ninvoke(http, 'get', { port: 3000, path: '/' })17 .then(function (response) {18 assert.equal(response.statusCode, 200);19 assert.equal(response.body, 'Hello world');20 });21})22.then(function () {23 return mb.delete({ port: 2525 });24})25.done();

Full Screen

Using AI Code Generation

copy

Full Screen

1var response = {2 headers: {3 },4 body: {5 }6};7function postProcess (request, response) {8 response.headers['Access-Control-Allow-Origin'] = '*';9 return response;10}11module.exports = {12};13{14 {15 {16 "is": {17 "headers": {18 },19 "body": {20 }21 }22 }23 }24}25{26 {27 {28 "is": {29 "headers": {30 },31 "body": {32 },33 }34 }35 }36}37{38 {39 {40 "is": {41 "headers": {42 },43 "body": {44 },45 "_behaviors": {46 }47 }48 }49 }50}

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var varValue = "Hello World";3var stub = {4 responses: [{5 is: {6 }7 }]8};9var postProcess = function (request, response) {10 response.body = response.body.replace('varValue', varValue);11};12mb.create({13}, function (error, impostor) {14 console.log('impostor created');15});16var request = {17};18mb.send(request, function (error, response) {19 console.log(response.body);20});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run mountebank 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