Best JavaScript code snippet using wpt
MatchQuery.js
Source:MatchQuery.js
1 /**2 @class3 A <code>MatchQuery</code> is a type of <code>Query</code> that accepts 4 text/numerics/dates, analyzes it, generates a query based on the5 <code>MatchQuery</code> type.6 7 @name ejs.MatchQuery8 @desc9 A Query that appects text, analyzes it, generates internal query based10 on the MatchQuery type.11 @param {String} field the document field/field to query against12 @param {String} qstr the query string13 */14 ejs.MatchQuery = function (field, qstr) {15 /**16 The internal query object. <code>Use get()</code>17 @member ejs.MatchQuery18 @property {Object} query19 */20 var query = {21 match: {}22 };23 24 query.match[field] = {25 query: qstr26 };27 return {28 /**29 Sets the boost value for documents matching the <code>Query</code>.30 @member ejs.MatchQuery31 @param {Number} boost A positive <code>double</code> value.32 @returns {Object} returns <code>this</code> so that calls can be chained.33 */34 boost: function (boost) {35 if (boost == null) {36 return query.match[field].boost;37 }38 query.match[field].boost = boost;39 return this;40 },41 /**42 Sets the query string for the <code>Query</code>.43 @member ejs.MatchQuery44 @param {String} qstr The query string to search for.45 @returns {Object} returns <code>this</code> so that calls can be chained.46 */47 query: function (qstr) {48 if (qstr == null) {49 return query.match[field].query;50 }51 query.match[field].query = qstr;52 return this;53 },54 /**55 Sets the type of the <code>MatchQuery</code>. Valid values are56 boolean, phrase, and phrase_prefix.57 @member ejs.MatchQuery58 @param {String} type Any of boolean, phrase, phrase_prefix.59 @returns {Object} returns <code>this</code> so that calls can be chained.60 */61 type: function (type) {62 if (type == null) {63 return query.match[field].type;64 }65 type = type.toLowerCase();66 if (type === 'boolean' || type === 'phrase' || type === 'phrase_prefix') {67 query.match[field].type = type;68 }69 return this;70 },71 /**72 Sets the fuzziness value for the <code>Query</code>.73 @member ejs.MatchQuery74 @param {Double} fuzz A <code>double</code> value between 0.0 and 1.0.75 @returns {Object} returns <code>this</code> so that calls can be chained.76 */77 fuzziness: function (fuzz) {78 if (fuzz == null) {79 return query.match[field].fuzziness;80 }81 query.match[field].fuzziness = fuzz;82 return this;83 },84 /**85 Sets the maximum threshold/frequency to be considered a low 86 frequency term in a <code>CommonTermsQuery</code>. 87 Set to a value between 0 and 1.88 @member ejs.MatchQuery89 @param {Number} freq A positive <code>double</code> value.90 @returns {Object} returns <code>this</code> so that calls can be chained.91 */92 cutoffFrequency: function (freq) {93 if (freq == null) {94 return query.match[field].cutoff_frequency;95 }96 query.match[field].cutoff_frequency = freq;97 return this;98 },99 100 /**101 Sets the prefix length for a fuzzy prefix <code>MatchQuery</code>.102 @member ejs.MatchQuery103 @param {Integer} l A positive <code>integer</code> length value.104 @returns {Object} returns <code>this</code> so that calls can be chained.105 */106 prefixLength: function (l) {107 if (l == null) {108 return query.match[field].prefix_length;109 }110 query.match[field].prefix_length = l;111 return this;112 },113 /**114 Sets the max expansions of a fuzzy <code>MatchQuery</code>.115 @member ejs.MatchQuery116 @param {Integer} e A positive <code>integer</code> value.117 @returns {Object} returns <code>this</code> so that calls can be chained.118 */119 maxExpansions: function (e) {120 if (e == null) {121 return query.match[field].max_expansions;122 }123 query.match[field].max_expansions = e;124 return this;125 },126 /**127 Sets default operator of the <code>Query</code>. Default: or.128 @member ejs.MatchQuery129 @param {String} op Any of "and" or "or", no quote characters.130 @returns {Object} returns <code>this</code> so that calls can be chained.131 */132 operator: function (op) {133 if (op == null) {134 return query.match[field].operator;135 }136 op = op.toLowerCase();137 if (op === 'and' || op === 'or') {138 query.match[field].operator = op;139 }140 return this;141 },142 /**143 Sets the default slop for phrases. If zero, then exact phrase matches144 are required. Default: 0.145 @member ejs.MatchQuery146 @param {Integer} slop A positive <code>integer</code> value.147 @returns {Object} returns <code>this</code> so that calls can be chained.148 */149 slop: function (slop) {150 if (slop == null) {151 return query.match[field].slop;152 }153 query.match[field].slop = slop;154 return this;155 },156 /**157 Sets the analyzer name used to analyze the <code>Query</code> object.158 @member ejs.MatchQuery159 @param {String} analyzer A valid analyzer name.160 @returns {Object} returns <code>this</code> so that calls can be chained.161 */162 analyzer: function (analyzer) {163 if (analyzer == null) {164 return query.match[field].analyzer;165 }166 query.match[field].analyzer = analyzer;167 return this;168 },169 /**170 Sets a percent value controlling how many "should" clauses in the171 resulting <code>Query</code> should match.172 @member ejs.MatchQuery173 @param {Integer} minMatch An <code>integer</code> between 0 and 100.174 @returns {Object} returns <code>this</code> so that calls can be chained.175 */176 minimumShouldMatch: function (minMatch) {177 if (minMatch == null) {178 return query.match[field].minimum_should_match;179 }180 query.match[field].minimum_should_match = minMatch;181 return this;182 },183 184 /**185 Sets rewrite method. Valid values are: 186 187 constant_score_auto - tries to pick the best constant-score rewrite 188 method based on term and document counts from the query189 190 scoring_boolean - translates each term into boolean should and 191 keeps the scores as computed by the query192 193 constant_score_boolean - same as scoring_boolean, expect no scores194 are computed.195 196 constant_score_filter - first creates a private Filter, by visiting 197 each term in sequence and marking all docs for that term198 199 top_terms_boost_N - first translates each term into boolean should200 and scores are only computed as the boost using the top N201 scoring terms. Replace N with an integer value.202 203 top_terms_N - first translates each term into boolean should204 and keeps the scores as computed by the query. Only the top N205 scoring terms are used. Replace N with an integer value.206 207 Default is constant_score_auto.208 This is an advanced option, use with care.209 @member ejs.MatchQuery210 @param {String} m The rewrite method as a string.211 @returns {Object} returns <code>this</code> so that calls can be chained.212 */213 rewrite: function (m) {214 if (m == null) {215 return query.match[field].rewrite;216 }217 218 m = m.toLowerCase();219 if (m === 'constant_score_auto' || m === 'scoring_boolean' ||220 m === 'constant_score_boolean' || m === 'constant_score_filter' ||221 m.indexOf('top_terms_boost_') === 0 || 222 m.indexOf('top_terms_') === 0) {223 224 query.match[field].rewrite = m;225 }226 227 return this;228 },229 230 /**231 Sets fuzzy rewrite method. Valid values are: 232 233 constant_score_auto - tries to pick the best constant-score rewrite 234 method based on term and document counts from the query235 236 scoring_boolean - translates each term into boolean should and 237 keeps the scores as computed by the query238 239 constant_score_boolean - same as scoring_boolean, expect no scores240 are computed.241 242 constant_score_filter - first creates a private Filter, by visiting 243 each term in sequence and marking all docs for that term244 245 top_terms_boost_N - first translates each term into boolean should246 and scores are only computed as the boost using the top N247 scoring terms. Replace N with an integer value.248 249 top_terms_N - first translates each term into boolean should250 and keeps the scores as computed by the query. Only the top N251 scoring terms are used. Replace N with an integer value.252 253 Default is constant_score_auto.254 This is an advanced option, use with care.255 256 @member ejs.MatchQuery257 @param {String} m The rewrite method as a string.258 @returns {Object} returns <code>this</code> so that calls can be chained.259 */260 fuzzyRewrite: function (m) {261 if (m == null) {262 return query.match[field].fuzzy_rewrite;263 }264 m = m.toLowerCase();265 if (m === 'constant_score_auto' || m === 'scoring_boolean' ||266 m === 'constant_score_boolean' || m === 'constant_score_filter' ||267 m.indexOf('top_terms_boost_') === 0 || 268 m.indexOf('top_terms_') === 0) {269 270 query.match[field].fuzzy_rewrite = m;271 }272 273 return this;274 },275 276 /**277 Set to false to use classic Levenshtein edit distance in the 278 fuzzy query.279 @member ejs.MatchQuery280 @param {Boolean} trueFalse A boolean value281 @returns {Object} returns <code>this</code> so that calls can be chained.282 */283 fuzzyTranspositions: function (trueFalse) {284 if (trueFalse == null) {285 return query.match[field].fuzzy_transpositions;286 }287 query.match[field].fuzzy_transpositions = trueFalse;288 return this;289 },290 /**291 Enables lenient parsing of the query string.292 @member ejs.MatchQuery293 @param {Boolean} trueFalse A boolean value294 @returns {Object} returns <code>this</code> so that calls can be chained.295 */296 lenient: function (trueFalse) {297 if (trueFalse == null) {298 return query.match[field].lenient;299 }300 query.match[field].lenient = trueFalse;301 return this;302 },303 304 /**305 Sets what happens when no terms match. Valid values are306 "all" or "none". 307 @member ejs.MatchQuery308 @param {String} q A no match action, "all" or "none".309 @returns {Object} returns <code>this</code> so that calls can be chained.310 */311 zeroTermsQuery: function (q) {312 if (q == null) {313 return query.match[field].zero_terms_query;314 }315 q = q.toLowerCase();316 if (q === 'all' || q === 'none') {317 query.match[field].zero_terms_query = q;318 }319 320 return this;321 },322 323 /**324 Allows you to serialize this object into a JSON encoded string.325 @member ejs.MatchQuery326 @returns {String} returns this object as a serialized JSON string.327 */328 toString: function () {329 return JSON.stringify(query);330 },331 /**332 The type of ejs object. For internal use only.333 334 @member ejs.MatchQuery335 @returns {String} the type of object336 */337 _type: function () {338 return 'query';339 },340 341 /**342 Retrieves the internal <code>query</code> object. This is typically used by343 internal API functions so use with caution.344 @member ejs.MatchQuery345 @returns {String} returns this object's internal <code>query</code> property.346 */347 _self: function () {348 return query;349 }350 };...
troc_get.ts
Source:troc_get.ts
1import { RequestHandler } from 'express'2import mongoose, { FilterQuery, Mongoose } from 'mongoose'3import type { Troc, Article as IArticle } from '../../types'4import TrocModel from '../models/troc'5import Article from '../models/article'6import Payment from '../models/payment'7import Subscribe from '../models/subscribe'8const { ObjectId } = mongoose.Types9/**10 * Return tous les infos nécéssaire au graphique11 */12export const getStats: RequestHandler = async (req, res, next) => {13 try {14 const { trocId = '', subscribeId = '' } = req.query15 if (!trocId && !subscribeId) throw 'trocId or subscribeId is required'16 if (typeof trocId !== 'string') throw 'trocId query need to be a string'17 if (typeof subscribeId !== 'string')18 throw 'subscribeId query need to be a string'19 if (subscribeId) {20 const [articlesProposed, articlesBuyed, payments] = await Promise.all([21 Article.find({ providerSubId: subscribeId }),22 Article.find({ buyerSubId: subscribeId }),23 Payment.find({ userSubId: subscribeId }),24 ])25 res.json({ articlesProposed, articlesBuyed, payments })26 } else {27 const [articlesProposed, articlesBuyed, payments] = await Promise.all([28 Article.find({ trocId }),29 Article.find({ trocId, sold: { $exists: true } }),30 Payment.find({ trocId }),31 ])32 res.json({ articlesProposed, articlesBuyed, payments })33 }34 } catch (error) {35 next(error)36 }37}38export const search: RequestHandler = async (req, res, next) => {39 let {40 _id,41 search,42 skip = 0,43 limit = 20,44 start,45 end,46 north,47 east,48 sud,49 west,50 } = req.query51 let matchQuery: FilterQuery<Troc & Document> = {}52 if (_id) matchQuery = { _id }53 else {54 matchQuery = { is_try: false }55 if (search && search.length) {56 let regexp = new RegExp(search, 'i')57 matchQuery.$or = []58 matchQuery.$or.push({ name: regexp })59 matchQuery.$or.push({ description: regexp })60 matchQuery.$or.push({ address: regexp })61 matchQuery.$or.push({ society: regexp })62 }63 if (start || end || north || east || sud || west) matchQuery.$and = []64 if (start)65 matchQuery.$and.push({ 'schedule.close': { $gte: new Date(start) } })66 if (end) matchQuery.$and.push({ 'schedule.open': { $lte: new Date(end) } })67 if (!isNaN(north)) matchQuery.$and.push({ 'location.lat': { $lt: +north } })68 if (!isNaN(east)) matchQuery.$and.push({ 'location.lng': { $lt: +east } })69 if (!isNaN(sud)) matchQuery.$and.push({ 'location.lat': { $gt: +sud } })70 if (!isNaN(west)) matchQuery.$and.push({ 'location.lng': { $gt: +west } })71 }72 const aggregate = TrocModel.aggregate()73 .match(matchQuery)74 .skip(Number(skip))75 .limit(Number(limit))76 addComputedFields(aggregate)77 if (req.session.user) lookupSubscribe(aggregate, req.session.user._id)78 const trocs = await aggregate.exec()79 res.json(trocs)80}81export const getTroc: RequestHandler = async (req, res, next) => {82 try {83 const { trocId } = req.query84 if (!trocId) throw 'query "trocId" is required'85 const aggregate = TrocModel.aggregate().match({ _id: new ObjectId(trocId) })86 if (req.session.user) lookupSubscribe(aggregate, req.session.user._id)87 addComputedFields(aggregate)88 const trocs = await aggregate.exec()89 if (!trocs.length) return next(Error('Not found'))90 res.json(trocs[0])91 } catch (error) {92 next(error)93 }94}95/**96 * Add computed fields from schedule97 */98export function addComputedFields(aggregate: mongoose.Aggregate<any[]>) {99 const NOW = new Date()100 aggregate101 .addFields({102 open: { $min: `$schedule.open` },103 close: { $max: `$schedule.close` },104 })105 .addFields({106 isClosed: { $gt: [NOW, '$close'] },107 isOpen: { $and: [{ $lt: [NOW, '$close'] }, { $gt: [NOW, '$open'] }] },108 })109}110/**111 * Add user role from subscribe document112 */113export function lookupSubscribe(114 aggregate: mongoose.Aggregate<Troc[]>,115 userId?: string116): void {117 aggregate118 .lookup({119 from: 'subscribes',120 let: { trocId: '$_id' },121 pipeline: [122 {123 $match: {124 $expr: {125 $and: [126 { $eq: ['$trocId', '$$trocId'] },127 { $eq: ['$userId', new ObjectId(userId)] },128 ],129 },130 },131 },132 ],133 as: 'subscribe',134 })135 .addFields({136 subscribe: { $arrayElemAt: ['$subscribe', 0] },137 })138}139/**140 * Retourne le compte des subscribes et des articles proposé141 */142export const getTrocCounter: RequestHandler = async (req, res, next) => {143 try {144 const { trocId } = req.query145 if (!trocId) throw 'Query "trocId" is required'146 const [articlesCount, subscribesCount] = await Promise.all([147 Article.countDocuments({ trocId }),148 Subscribe.countDocuments({ trocId, validedByUser: true }),149 ])150 res.json({ articlesCount, subscribesCount })151 } catch (error) {152 next(error)153 }...
Using AI Code Generation
1var wptoolbox = require('wptoolbox');2wp.matchQuery('Albert Einstein', function(err, result) {3 if (err) {4 console.log(err);5 } else {6 console.log(result);7 }8});9This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
Using AI Code Generation
1var wptools = require('wptools');2var fs = require('fs');3var async = require('async');4var data = fs.readFileSync('data.json', 'utf8');5var json = JSON.parse(data);6var i = 0;7var j = 0;8var k = 0;9var l = 0;10var m = 0;11var n = 0;12var json1 = [];13var json2 = [];14var json3 = [];15var json4 = [];16var json5 = [];17var json6 = [];18var json7 = [];19var json8 = [];20var json9 = [];21var json10 = [];22var json11 = [];23var json12 = [];24var json13 = [];25var json14 = [];26var json15 = [];27var json16 = [];28var json17 = [];29var json18 = [];30var json19 = [];31var json20 = [];32var json21 = [];33var json22 = [];34var json23 = [];35var json24 = [];36var json25 = [];37var json26 = [];38var json27 = [];39var json28 = [];40var json29 = [];41var json30 = [];42var json31 = [];43var json32 = [];44var json33 = [];45var json34 = [];46var json35 = [];47var json36 = [];48var json37 = [];49var json38 = [];50var json39 = [];51var json40 = [];52var json41 = [];53var json42 = [];54var json43 = [];55var json44 = [];56var json45 = [];57var json46 = [];58var json47 = [];59var json48 = [];60var json49 = [];61var json50 = [];62var json51 = [];63var json52 = [];64var json53 = [];65var json54 = [];66var json55 = [];67var json56 = [];68var json57 = [];69var json58 = [];70var json59 = [];71var json60 = [];72var json61 = [];73var json62 = [];74var json63 = [];75var json64 = [];76var json65 = [];77var json66 = [];78var json67 = [];79var json68 = [];80var json69 = [];81var json70 = [];82var json71 = [];83var json72 = [];84var json73 = [];85var json74 = [];86var json75 = [];87var json76 = [];88var json77 = [];89var json78 = [];90var json79 = [];91var json80 = [];92var json81 = [];93var json82 = [];94var json83 = [];
Using AI Code Generation
1var wptools = require('wptools');2var page = wptools.page('Barack Obama');3page.matchQuery('Barack Obama');4page.get(function(err,resp){5 console.log(resp);6});7{ 8 [ { title: 'Barack Obama',9 importance: 0.781,10 importance: 0.781,11 class: 'place' } ],12 {
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const query = wptools.page('Barack Obama');4query.get()5 .then(function (result) {6 console.log(result);7 fs.writeFile('result.json', JSON.stringify(result, null, 2), 'utf8', function (err) {8 if (err) {9 console.log('Some error occured - file either not saved or corrupted file saved.');10 } else {11 console.log('It\'s saved!');12 }13 });14 })15 .catch(function (error) {16 console.log(error);17 });
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!