<commit_before>/*
Copyright (c) 2010, Geomatics and Cartographic Research Centre, Carleton 
University
All rights reserved.

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions are met:

 - Redistributions of source code must retain the above copyright notice, 
   this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 - Neither the name of the Geomatics and Cartographic Research Centre, 
   Carleton University nor the names of its contributors may be used to 
   endorse or promote products derived from this software without specific 
   prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

;(function($,$n2){
	"use strict";
	
	// Localization
	var _loc = function(str,args){ return $n2.loc(str,'nunaliit2-couch',args); };
	
	// Dispatcher
	var DH = 'n2.couchSearch';
	
	function SplitSearchTerms(line) {
		if( !line ) return null;
		
		var map = $n2.couchUtils.extractSearchTerms(line, false);
	
		var searchTerms = [];
		for(var term in map){
			var folded = map[term].folded;
			if( folded ) {
				searchTerms.push(folded);
			};
		};
		
		return searchTerms;
	};
	
	//============ ResearchResult ========================
	// Class that convey the result of a research
	var ResearchResult = $n2.Class({
		
		// identifier of the document found in research
		id: null,
		
		// How relevant this result is (lower number is better)
		index: null,
		
		// How many terms matched by this result
		count: null,
		
		initialize: function(opts_){
			var opts = $n2.extend({
				id: null
				,index: null
				,count: null
			},opts_);
			
			this.id = opts.id;
			this.index = opts.index;
			
			if( opts.count ){
				this.count = opts.count;
			} else {
				this.count = 1;
			};
		},
		
		add: function(result){
			if( this.index > result.index ){
				this.index = result.index;
			};
			
			this.count += result.count;
		}
	});
	
	//============ Research ========================
	// Abstract class that defines the API for researching
	// a concept in the database
	var Research = $n2.Class({
		
		id: null,
		
		initialize: function(opts_){
			var opts = $n2.extend({
				
			},opts_);
			
			this.id = $n2.getUniqueId();
		},
		
		execute: function(opts_){
			var opts = $n2.extend({
				onSuccess: function(resultMap, research){}
				,onError: function(err, research){}
				,onPartial: function(resultMap, research){}
			},opts_);
	
			throw 'Subclasses must implement method execute';
		}
	});
	
	//============ ResearchTerm ========================
	// Specialization of Research that looks up all documents
	// associated with one search term
	var ResearchTerm = $n2.Class(Research,{
		textTerm: null,
	
		constraint: null,
		
		designDoc: null,
		
		searchView: null,
		
		dispatchService: null,
		
		initialize: function(opts_){
			var opts = $n2.extend({
				textTerm: null
				,constraint: null
				,designDoc: null
				,searchView: null
				,dispatchService: null
			},opts_);
			
			Research.prototype.initialize.apply(this,arguments);
	
			this.textTerm = opts.textTerm;
			this.constraint = opts.constraint;
			this.designDoc = opts.designDoc;
			this.searchView = opts.searchView;
			this.dispatchService = opts.dispatchService;
			
			if( typeof this.textTerm !== 'string' ){
				throw 'In ResearchTerm constructor, the textTerm must be a string';
			};
			if( typeof this.designDoc !== 'object' ){
				throw 'In ResearchTerm constructor, the designDoc must be provided';
			};
			if( typeof this.searchView !== 'string' ){
				throw 'In ResearchTerm constructor, the searchView must be provided';
			};
		},

		arraySearchQuery: function(opts, constraint, term){
			var resultsByDocId = null;
			var expectedCount = constraint.length;
			
			for (var i = 0, e = constraint.length; i < e; i += 1) {
				if (!resultsByDocId){
					resultsByDocId = {};
				}
	
				this.designDoc.queryView({
					viewName: this.searchView
					,startkey: [constraint[i],term,0]
					,endkey: [constraint[i],term,{}]
					,constraint: constraint
					,onSuccess: function(rows) {
						for (var i = 0, e = rows.length; i < e; i += 1) {
							var docId = rows[i].id;
							var index = rows[i].key[1];
							
							if (resultsByDocId[docId] 
							&& resultsByDocId[docId].index <= index) {
								// Do nothing
							} else {
								var result = new ResearchResult({
									id: docId
									,index: index
								});
								resultsByDocId[docId] = result;
							}
						}
	
						// Only call opts.onSuccess when all the queries have returned.
						// Otherwise call opts.onPartial
						expectedCount -= 1;
						if (expectedCount <= 0) {
							opts.onSuccess(resultsByDocId);
						} else {
							opts.onPartial(resultsByDocId);
						}
					}
					,onError: function(err) {
						opts.onError(err);
					}
				});
			};
		},
		
		getDocumentsFromModelId: function(modelId){
			var docs = [];
			
			if (modelId && this.dispatchService) {
				var state = $n2.model.getModelState({
					dispatchService: this.dispatchService
					,modelId: modelId
				});

				if (state && state.added) {
					docs = state.added;
				}
			}

			return docs;
		},

		execute: function(opts_){
			var opts = $n2.extend({
				onSuccess: function(resultMap, research){}
				,onError: function(err, research){}
				,onPartial: function(resultMap, research){}
			},opts_);
			
			var _this = this;
	
			// Search terms are stored lower case in database
			var term = this.textTerm.toLowerCase();
			var resultsByDocId = null;
	
			if (this.constraint) {
				// Convert string to an array of 1 element for performing query view
				if (typeof(this.constraint) === 'string') {
					var key = [];
					key.push(this.constraint);
					this.constraint = key;
				};
			
				// Legacy search constraint 
				if ($n2.isArray(this.constraint)
					&& this.constraint.length > 0) {
					
					this.arraySearchQuery(opts, this.constraint, term);
				
				} else if (typeof this.constraint === "object" 
					&& this.constraint !== null) {

					// Updated Constraint
					if (this.constraint.type) { 
						if (this.constraint.type === "layers") {
							if (typeof this.constraint.layers === 'string') {
								var layerConstraint = [ this.constraint.layers ];
								this.arraySearchQuery(opts, layerConstraint, term);

							} else if ($n2.isArray(this.constraint.layers)) {
								this.arraySearchQuery(opts, this.constraint.layers, term);
							}

						} else if (this.constraint.type === "model" 
							&& typeof this.constraint.sourceModelId === 'string') {

							var modelDocs = this.getDocumentsFromModelId(this.constraint.sourceModelId);
							var startKey = [term,0];
							var endKey = [term,{}];
			
							this.designDoc.queryView({
								viewName: "text-search",
								startkey: startKey,
								endkey: endKey,
								onSuccess: function(rows) {
									var i, e, j, f, docId, index, result;
									var filteredRows = [];
									var resultsByDocId = {};

									// Filter out docs not found in model
									for (i = 0, e = rows.length; i < e; i += 1) {
										docId = rows[i].id;
										for (j = 0, f = modelDocs.length; j < f; j += 1) {
											if (modelDocs[j]._id === docId && filteredRows.indexOf(rows[i]) < 0) {
												filteredRows.push(rows[i]);
											}
										}
									}
									
									for (i = 0, e = filteredRows.length; i < e; i += 1) {
										docId = filteredRows[i].id;
										index = filteredRows[i].key[1];
										
										if (resultsByDocId[docId] && resultsByDocId[docId].index <= index) {
											// Do nothing
										} else {
											result = new ResearchResult({
												id: docId,
												index: index
											});
											resultsByDocId[docId] = result;
										}
									}
									
									opts.onSuccess(resultsByDocId);
								},
								onError: function(err) {
									opts.onError(err);
								}
							});
						}
					}

				} else {
					opts.onError('Invalid search constraint');
				}

			} else {

				// If no constraint provided, perform a regular text-search.
				var startKey = [term,0];
				var endKey = [term,{}];
	
				this.designDoc.queryView({
					viewName: this.searchView
					,startkey: startKey
					,endkey: endKey
					,onSuccess: function(rows) {
						var resultsByDocId = {};
						for(var i=0,e=rows.length; i<e; ++i) {
							var docId = rows[i].id;
							var index = rows[i].key[1];
							
							if( resultsByDocId[docId] 
							 && resultsByDocId[docId].index <= index ){<commit_msg>Refactored model search filter code.<commit_after>/*
Copyright (c) 2010, Geomatics and Cartographic Research Centre, Carleton 
University
All rights reserved.

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions are met:

 - Redistributions of source code must retain the above copyright notice, 
   this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 - Neither the name of the Geomatics and Cartographic Research Centre, 
   Carleton University nor the names of its contributors may be used to 
   endorse or promote products derived from this software without specific 
   prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

;(function($,$n2){
	"use strict";
	
	// Localization
	var _loc = function(str,args){ return $n2.loc(str,'nunaliit2-couch',args); };
	
	// Dispatcher
	var DH = 'n2.couchSearch';
	
	function SplitSearchTerms(line) {
		if( !line ) return null;
		
		var map = $n2.couchUtils.extractSearchTerms(line, false);
	
		var searchTerms = [];
		for(var term in map){
			var folded = map[term].folded;
			if( folded ) {
				searchTerms.push(folded);
			};
		};
		
		return searchTerms;
	};
	
	//============ ResearchResult ========================
	// Class that convey the result of a research
	var ResearchResult = $n2.Class({
		
		// identifier of the document found in research
		id: null,
		
		// How relevant this result is (lower number is better)
		index: null,
		
		// How many terms matched by this result
		count: null,
		
		initialize: function(opts_){
			var opts = $n2.extend({
				id: null
				,index: null
				,count: null
			},opts_);
			
			this.id = opts.id;
			this.index = opts.index;
			
			if( opts.count ){
				this.count = opts.count;
			} else {
				this.count = 1;
			};
		},
		
		add: function(result){
			if( this.index > result.index ){
				this.index = result.index;
			};
			
			this.count += result.count;
		}
	});
	
	//============ Research ========================
	// Abstract class that defines the API for researching
	// a concept in the database
	var Research = $n2.Class({
		
		id: null,
		
		initialize: function(opts_){
			var opts = $n2.extend({
				
			},opts_);
			
			this.id = $n2.getUniqueId();
		},
		
		execute: function(opts_){
			var opts = $n2.extend({
				onSuccess: function(resultMap, research){}
				,onError: function(err, research){}
				,onPartial: function(resultMap, research){}
			},opts_);
	
			throw 'Subclasses must implement method execute';
		}
	});
	
	//============ ResearchTerm ========================
	// Specialization of Research that looks up all documents
	// associated with one search term
	var ResearchTerm = $n2.Class(Research,{
		textTerm: null,
	
		constraint: null,
		
		designDoc: null,
		
		searchView: null,
		
		dispatchService: null,
		
		initialize: function(opts_){
			var opts = $n2.extend({
				textTerm: null
				,constraint: null
				,designDoc: null
				,searchView: null
				,dispatchService: null
			},opts_);
			
			Research.prototype.initialize.apply(this,arguments);
	
			this.textTerm = opts.textTerm;
			this.constraint = opts.constraint;
			this.designDoc = opts.designDoc;
			this.searchView = opts.searchView;
			this.dispatchService = opts.dispatchService;
			
			if( typeof this.textTerm !== 'string' ){
				throw 'In ResearchTerm constructor, the textTerm must be a string';
			};
			if( typeof this.designDoc !== 'object' ){
				throw 'In ResearchTerm constructor, the designDoc must be provided';
			};
			if( typeof this.searchView !== 'string' ){
				throw 'In ResearchTerm constructor, the searchView must be provided';
			};
		},

		arraySearchQuery: function(opts, constraint, term){
			var resultsByDocId = null;
			var expectedCount = constraint.length;
			
			for (var i = 0, e = constraint.length; i < e; i += 1) {
				if (!resultsByDocId){
					resultsByDocId = {};
				}
	
				this.designDoc.queryView({
					viewName: this.searchView
					,startkey: [constraint[i],term,0]
					,endkey: [constraint[i],term,{}]
					,constraint: constraint
					,onSuccess: function(rows) {
						for (var i = 0, e = rows.length; i < e; i += 1) {
							var docId = rows[i].id;
							var index = rows[i].key[1];
							
							if (resultsByDocId[docId] 
							&& resultsByDocId[docId].index <= index) {
								// Do nothing
							} else {
								var result = new ResearchResult({
									id: docId
									,index: index
								});
								resultsByDocId[docId] = result;
							}
						}
	
						// Only call opts.onSuccess when all the queries have returned.
						// Otherwise call opts.onPartial
						expectedCount -= 1;
						if (expectedCount <= 0) {
							opts.onSuccess(resultsByDocId);
						} else {
							opts.onPartial(resultsByDocId);
						}
					}
					,onError: function(err) {
						opts.onError(err);
					}
				});
			};
		},
		
		getDocumentsFromModelId: function(modelId){
			var docs = [];
			
			if (modelId && this.dispatchService) {
				var state = $n2.model.getModelState({
					dispatchService: this.dispatchService
					,modelId: modelId
				});

				if (state && state.added) {
					docs = state.added;
				}
			}

			return docs;
		},

		filterOutNonModelDocs: function(queryResults, modelDocs){
			var i, e, j, f, docId;
			var filteredResults = [];

			// Filter out docs not found in model
			for (i = 0, e = queryResults.length; i < e; i += 1) {
				docId = queryResults[i].id;
				for (j = 0, f = modelDocs.length; j < f; j += 1) {
					if (modelDocs[j]._id === docId 
						&& filteredResults.indexOf(queryResults[i]) < 0) {
						filteredResults.push(queryResults[i]);
					}
				}
			}

			return filteredResults;
		},

		getUniqueResults: function(filteredResults){
			var i, e, docId, index, result;
			var uniqueResults = {};

			for (i = 0, e = filteredResults.length; i < e; i += 1) {
				docId = filteredResults[i].id;
				index = filteredResults[i].key[1];
				
				if (uniqueResults[docId] 
					&& uniqueResults[docId].index <= index) {
					// Do nothing 

				} else {
					result = new ResearchResult({
						id: docId,
						index: index
					});
					uniqueResults[docId] = result;
				}
			}
			return uniqueResults;
		},

		execute: function(opts_){
			var opts = $n2.extend({
				onSuccess: function(resultMap, research){}
				,onError: function(err, research){}
				,onPartial: function(resultMap, research){}
			},opts_);
			
			var _this = this;
	
			// Search terms are stored lower case in database
			var term = this.textTerm.toLowerCase();
			var resultsByDocId = null;
	
			if (this.constraint) {
				// Convert string to an array of 1 element for performing query view
				if (typeof(this.constraint) === 'string') {
					var key = [];
					key.push(this.constraint);
					this.constraint = key;
				};
			
				// Legacy search constraint 
				if ($n2.isArray(this.constraint)
					&& this.constraint.length > 0) {
					
					this.arraySearchQuery(opts, this.constraint, term);
				
				} else if (typeof this.constraint === "object" 
					&& this.constraint !== null) {

					// Updated Constraint
					if (this.constraint.type) { 
						if (this.constraint.type === "layers") {
							if (typeof this.constraint.layers === 'string') {
								var layerConstraint = [ this.constraint.layers ];
								this.arraySearchQuery(opts, layerConstraint, term);

							} else if ($n2.isArray(this.constraint.layers)) {
								this.arraySearchQuery(opts, this.constraint.layers, term);
							}

						} else if (this.constraint.type === "model" 
							&& typeof this.constraint.sourceModelId === 'string') {

							var modelDocs = this.getDocumentsFromModelId(this.constraint.sourceModelId);
							var startKey = [term,0];
							var endKey = [term,{}];
			
							this.designDoc.queryView({
								viewName: "text-search",
								startkey: startKey,
								endkey: endKey,
								onSuccess: function(rows) {
									var i, e, j, f, docId, index, result;
									var filteredRows = [];
									var uniqueIndexResults = {};
									
									filteredRows = _this.filterOutNonModelDocs(rows, modelDocs);
									uniqueIndexResults = _this.getUniqueResults(filteredRows);
									
									opts.onSuccess(uniqueIndexResults);
								},
								onError: function(err) {
									opts.onError(err);
								}
							});
						}
					}

				} else {
					opts.onError('Invalid search constraint');
				}

			} else {

				// If no constraint provided, perform a regular text-search.
				var startKey = [term,0];
				var endKey = [term,{}];
	
				this.designDoc.queryView({
					viewName: this.searchView
					,startkey: startKey
					,endkey: endKey
					,onSuccess: function(rows) {
						var resultsByDocId = {};
						for(var i=0,e=rows.length; i<e; ++i) {
							var docId = rows[i].id;
							var index = rows[i].key[1];
							
							if( resultsByDocId[docId] 
								&& resultsByDocId[docId].index <= index ){
{'fraction_non_alphanumeric': 0.12461204220980757, 'fraction_numerical': 0.004552038071591144, 'mean_word_length': 2.64980177458939, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5521743', 'n_tokens_mistral': 7912, 'n_tokens_neox': 5675, 'n_words': 1706}