void SearchDialog_Load(object sender, EventArgs e) { if (this.searchParams != null) { if (this.searchParams.isFromTop) this.fromTopRadioButton.Checked = true; else this.fromSelectedRadioButton.Checked = true; if (this.searchParams.isForward) this.forwardRadioButton.Checked = true; else this.backwardRadioButton.Checked = true; this.regexCheckBox.Checked = this.searchParams.isRegex; this.caseSensitiveCheckBox.Checked = this.searchParams.isCaseSensitive; foreach (string item in this.searchParams.historyList) { this.searchComboBox.Items.Add(item); } if (this.searchComboBox.Items.Count > 0) this.searchComboBox.SelectedIndex = 0; } else { this.fromSelectedRadioButton.Checked = true; this.forwardRadioButton.Checked = true; this.searchParams = new SearchParams(); } }
public FlannColoredModelPoints(List<Tuple<CvPoint3D64f, CvColor>> modelPoints, IndexParams indexParams, SearchParams searchParams, double colorScale) { _modelPoints = modelPoints; _modelMat = new CvMat(_modelPoints.Count, 6, MatrixType.F32C1); unsafe { float* modelArr = _modelMat.DataSingle; foreach (var tuple in _modelPoints) { *(modelArr++) = (float)tuple.Item1.X; *(modelArr++) = (float)tuple.Item1.Y; *(modelArr++) = (float)tuple.Item1.Z; *(modelArr++) = (float)(tuple.Item2.R * colorScale / 255); *(modelArr++) = (float)(tuple.Item2.G * colorScale / 255); *(modelArr++) = (float)(tuple.Item2.B * colorScale / 255); } } _colorScale = colorScale; _modelDataMat = new Mat(_modelMat); _indexParam = indexParams; _searchParam = searchParams; _indexParam.IsEnabledDispose = false; _searchParam.IsEnabledDispose = false; _flannIndex = new Index(_modelDataMat, _indexParam); }
public void OnSearch(ref SearchParams param, System.ComponentModel.BackgroundWorker bw) { if (param.Act == SearchParams.Action.aContinue) { SearchNext(bw); return; } searchEnd = false; try { XElement xraw = XElement.Load(string.Format(SEARCH, param.Pattern)); XElement xroot = XElement.Parse(xraw.ToString()); var photos = (from photo in xroot.Element("photos").Elements("photo") select new FlickrImage { url = string.Format("http://farm{0}.static.flickr.com/{1}/{2}_{3}_t.jpg", (string)photo.Attribute("farm"), (string)photo.Attribute("server"), (string)photo.Attribute("id"), (string)photo.Attribute("secret")), urlBig = string.Format("http://farm{0}.static.flickr.com/{1}/{2}_{3}_b.jpg", (string)photo.Attribute("farm"), (string)photo.Attribute("server"), (string)photo.Attribute("id"), (string)photo.Attribute("secret")) }).Take(maxCount); photosFound = photos; currentStopIndex = 0; photosCount = photosFound.Count(); SearchNext(bw); } catch (Exception e) { Trace.WriteLine(e.Message, "ERROR"); } }
private void OnSearchStarted(SearchParams SearchParams) { if (SearchStartedEvent != null) { SearchStartedEvent(this, new SearchStartedEventArgs(SearchParams)); } }
/// <summary> /// /// </summary> /// <param name="indexParams"></param> /// <param name="searchParams"></param> public FlannBasedMatcher(IndexParams indexParams = null, SearchParams searchParams = null) { ptr = NativeMethods.features2d_FlannBasedMatcher_new( Cv2.ToPtr(indexParams), Cv2.ToPtr(searchParams)); }
public static extern void AsciiSearchAlgorithm_CancelSearch( SafeSearchHandle handle, ref SearchParams searchParams);
protected override SearchResult DoExecute(Query query, bool allVersions, IndexReader idxReader, Stopwatch timer) { var numDocs = idxReader.NumDocs(); var start = this.LucQuery.Skip; var maxtop = numDocs - start; if (maxtop < 1) return SearchResult.Empty; var user = this.LucQuery.User; var currentUser = AccessProvider.Current.GetCurrentUser(); if (user == null) user = currentUser; var isCurrentUser = user.Id == currentUser.Id; int top = this.LucQuery.Top != 0 ? this.LucQuery.Top : this.LucQuery.PageSize; if (top == 0) top = int.MaxValue; var searcher = new IndexSearcher(idxReader); var p = new SearchParams { query = query, allVersions = allVersions, searcher = searcher, user = user, isCurrentUser = isCurrentUser, skip = start, timer = timer, top = top }; SearchResult r = null; SearchResult r1 = null; try { var defaultTops = SenseNet.ContentRepository.Storage.StorageContext.Search.DefaultTopAndGrowth; var howManyList = new List<int>(defaultTops); if (howManyList[howManyList.Count - 1] == 0) howManyList[howManyList.Count - 1] = int.MaxValue; if (top < int.MaxValue) { var howMany = (top < int.MaxValue / 2) ? top * 2 : int.MaxValue; // numDocs; // * 4; // * 2; if ((long)howMany > maxtop) howMany = maxtop - start; while (howManyList.Count > 0) { if (howMany < howManyList[0]) break; howManyList.RemoveAt(0); } howManyList.Insert(0, howMany); } for (var i = 0; i < howManyList.Count; i++) { var defaultTop = howManyList[i]; if (defaultTop == 0) defaultTop = numDocs; p.howMany = defaultTop; p.useHowMany = i < howManyList.Count - 1; var maxSize = i == 0 ? numDocs : r.totalCount; p.collectorSize = Math.Min(defaultTop, maxSize - p.skip) + p.skip; r1 = Search(p); if (i == 0) r = r1; else r.Add(r1); p.skip += r.nextIndex; p.top = top - r.result.Count; if (r.result.Count >= top || r.result.Count >= r.totalCount) break; } p.timer.Stop(); return r; } finally { if (searcher != null) { searcher.Close(); searcher = null; } } }
// PixelFormat format) private void GetSearchAreaBitmap(ref SearchParams search) { game.CaptureArea(); // Get search bitmap Rectangle searchLocation = new Rectangle(0, 0, search.ToFind.Width,search.ToFind.Height); if (Monitor.TryEnter(game.GameScreenLOCK, 1000)) { try { // Set search bounds to captured area searchLocation = new Rectangle(0, 0, game.GameScreen.Width, game.GameScreen.Height); } finally { Monitor.Exit(game.GameScreenLOCK); } } // Set search bounds to captured area if (game.GameExtents.HasValue) {// Search in gamescreen if available search.UsingGameExtents = true; if (search.QuickCheck) { // Use pre-calculated offsets searchLocation.Width = search.ToFind.Width; searchLocation.Height = search.ToFind.Height; } else { // Add buffer searchLocation.X += 20; searchLocation.Y += 20; searchLocation.Width += 40; searchLocation.Height += 40; } } // Copy gamescreen to search area (this will add buffer of black pixels if required search.SearchArea = new Bitmap(searchLocation.Width,searchLocation.Height,search.ToFind.PixelFormat); if (Monitor.TryEnter(game.GameScreenLOCK,1000)) { try { using (Graphics g = Graphics.FromImage(search.SearchArea)) { g.DrawImage(game.GameScreen, searchLocation.Location); } } finally { Monitor.Exit(game.GameScreenLOCK); } } }
public string Start([FromBody] SearchParams searchParams) { return(_searchService.Start(searchParams)); }
public void Input(string message) { var words = message.Trim().Split(' '); switch (words[0]) { case "uci": ConfigureUCI(); break; case "setoption": break; case "isready": Output("readyok"); break; case "ucinewgame": Game.SetStartingPos(); break; case "position": { var isStartPos = false; var byFen = false; var byMoves = false; var fen = string.Empty; var i = 1; var positionParsingReady = false; for (; i < words.Length && !positionParsingReady; i++) { switch (words[i]) { case "startpos": isStartPos = true; break; case "moves": byMoves = true; positionParsingReady = true; break; case "fen": byFen = true; i++; while (true) { if (i == words.Length) { positionParsingReady = true; break; } if (words[i] == "moves") { byMoves = true; positionParsingReady = true; break; } fen += words[i++] + " "; } break; } } if (byFen) { Game.SetPositionByFEN(fen); } if (byMoves) { var moves = words.Skip(i).ToList(); Game.SetPositionByMoves(isStartPos && !byFen, moves); } } break; case "go": { var searchParams = new SearchParams(); for (var i = 0; i < words.Length; i++) { switch (words[i]) { case "wtime": searchParams.WhiteTime = long.Parse(words[++i]); break; case "btime": searchParams.BlackTime = long.Parse(words[++i]); break; case "winc": searchParams.WhiteTimeIncrement = long.Parse(words[++i]); break; case "binc": searchParams.BlackTimeIncrement = long.Parse(words[++i]); break; case "infinite": searchParams.Infinite = true; break; } } var results = Game.SearchMove(searchParams); var moveStr = results[0].Move.ToPositionString(); if (results.Count == 1 || results[1] == default(SearchTTEntry)) { Output($"bestmove {moveStr}"); } else { var ponderStr = results[1].Move.ToPositionString(); Output($"bestmove {moveStr} ponder {ponderStr}"); } } break; case "print": Output(Game.Print()); break; case "exit": case "quit": Exit(0); break; } }
public List <object> GetClusteredHelpers(SearchParams searchParams) { string path = System.Web.Hosting.HostingEnvironment.MapPath("~/Files/ProfileImages/"); IQueryable <HelperLocation> h = null; DbGeography targetCircle = null; List <HelperLocation> LoactionList = new List <HelperLocation>(); if (searchParams != null) { if (searchParams.Latitude > 0 && searchParams.Longitude > 0 && searchParams.Radius >= 0) { DbGeography center = DbGeography.FromText("Point(" + searchParams.Latitude + " " + searchParams.Longitude + ")"); targetCircle = center.Buffer(searchParams.Radius); h = helpaContext.HelperLocations .IncludeEntities(x => x.Helper, x => x.Location, x => x.Helper.HelperServices).Include(x => x.Helper.HelperServices.Select(q => q.Service)).Include(q => q.Helper.HelperServices.Select(x => x.HelperServiceScopes.Select(l => l.Scope))); var io = helpaContext.HelperLocations.Where(x => x.Location.LocationGeography.Latitude.ToString().Contains(targetCircle.Latitude.ToString()) && x.Location.LocationGeography.Longitude.ToString().Contains(targetCircle.Longitude.ToString())).ToList(); if (searchParams.ServiceId > 0) { h = h.Where(x => x.Helper.HelperServices.Any(m => m.ServiceId == searchParams.ServiceId)); } if (searchParams.LocationTypeId > 0) { h = h.Where(x => x.Helper.LocationType == searchParams.LocationTypeId); } if (searchParams.ScopeId > 0) { h = h.Where(x => x.Helper.HelperServices.Any(m => m.HelperServiceScopes.Any(n => n.HelperScopeId == searchParams.ScopeId))); } } } else { h = helpaContext.HelperLocations .IncludeEntities(x => x.Helper, x => x.Location, x => x.Helper.HelperServices.Select(y => y.Service)); var t = h.ToList(); if (searchParams != null) { if (searchParams.ServiceId > 0) { h = h.Where(x => x.Helper.HelperServices.Select(q => q.ServiceId).FirstOrDefault() == searchParams.ServiceId); } if (searchParams.LocationTypeId > 0) { h = h.Where(x => x.Helper.LocationType == searchParams.LocationTypeId); } if (searchParams.ScopeId > 0) { h = h.Where(x => x.Helper.HelperServices.Any(m => m.HelperServiceScopes.Any(n => n.HelperScopeId == searchParams.ScopeId))); } } } var pl = h.ToList(); foreach (var item in pl) { var lat = Convert.ToDouble(item.Location.LocationGeography.Latitude); var Longi = Convert.ToDouble(item.Location.LocationGeography.Longitude); var SearchLat = Convert.ToDouble(searchParams.Latitude); var SearchLongi = Convert.ToDouble(searchParams.Longitude); var sCoord = new GeoCoordinate(SearchLat, SearchLongi); var eCoord = new GeoCoordinate(lat, Longi); var DistanceRadius = sCoord.GetDistanceTo(eCoord); if (DistanceRadius <= searchParams.Radius) { LoactionList.Add(item); } } var r = helpaContext.AspNetUsers.Where(x => x.AspNetRoles.Select(y => y.Name).Contains("HELPER") && x.RowStatus == true).ToList(); var final = LoactionList.Join(r, x => x.Helper.UserId, y => y.Id, (x, y) => new { q = x, w = y }).ToList(); List <object> data = new List <object>(); HelpersHomeDTO helpers = new HelpersHomeDTO(); foreach (var item in final) { var w = item.w; var q = item.q; helpers = new HelpersHomeDTO(); helpers.LocalityName = item.q.Location.Locality; string location = item.q.Location.LocationGeography.StartPoint.ToString(); int startIndex = location.IndexOf("("); int endIndex = location.IndexOf(")"); var LatLong = location.Substring(startIndex + 1, endIndex - startIndex - 1).Split(null); helpers.Latitude = Math.Round(Convert.ToDouble(LatLong[1]), 8).ToString(); helpers.Longitude = Math.Round(Convert.ToDouble(LatLong[0]), 8).ToString(); var EMPLOYEE = helpaContext.AspNetUsers.Where(x => x.LocationId == item.q.LocationId).ToList(); helpers.NumberOfHelpersInLocality = final.Count(); List <HelpersInLocalty> Obj = new List <HelpersInLocalty>(); foreach (var v in final) { HelpersInLocalty ob = new HelpersInLocalty(); ob.UserId = v.w.Id; ob.Name = v.w.UserName; ob.ProfilePicture = path + v.w.ProfileImage; ob.Description = v.w.Description; ob.AverageRating = v.w.AverageRating.ToString(); ob.RatingCount = v.w.AverageRating.ToString(); ob.Status = v.w.RowStatus.ToString(); ob.Latitude = helpaContext.Locations.Where(x => x.LocationId == v.w.LocationId).Select(x => x.LocationGeography.Latitude).FirstOrDefault(); ob.Longitude = helpaContext.Locations.Where(x => x.LocationId == v.w.LocationId).Select(x => x.LocationGeography.Longitude).FirstOrDefault(); Obj.Add(ob); } helpers.HelpersInLocalties = Obj; data.Add(helpers); break; } if (data.Count > 0) { return(data); } return(null); }
public System.Threading.Tasks.Task <Bundle> Search(IEnumerable <KeyValuePair <string, string> > parameters, int?Count, SummaryType summary) { Bundle result = new Bundle(); result.Meta = new Meta(); result.Id = new Uri("urn:uuid:" + Guid.NewGuid().ToString("n")).OriginalString; result.Type = Bundle.BundleType.Searchset; result.ResourceBase = RequestDetails.BaseUri; result.Total = 0; // If there was no count provided, we'll just default in a value if (!Count.HasValue) { Count = 40; } // TODO: Thread the requests... // System.Threading.Tasks.Parallel.ForEach(_members, async (member) => foreach (var member in _members) { try { // create a connection with the supported format type FhirClient server = new FhirClient(member.Url); member.PrepareFhirClientSecurity(server); System.Diagnostics.Trace.WriteLine($"Searching {member.Url} {member.Name}"); server.PreferCompressedResponses = true; server.PreferredFormat = member.Format; SearchParams sp = new SearchParams(); foreach (var item in parameters) { if (item.Key == "_include") { sp.Include.Add(item.Value); } else { sp.Add(item.Key, item.Value); } } sp.Count = Count; sp.Summary = summary; // Bundle partialResult = server.Search(sp, ResourceName); Bundle partialResult = server.Search(sp, ResourceName); lock (result) { if (partialResult.Total.HasValue) { result.Total += partialResult.Total; } foreach (var entry in partialResult.Entry) { result.Entry.Add(entry); entry.Resource.ResourceBase = server.Endpoint; if (entry.Resource.Meta == null) { entry.Resource.Meta = new Meta(); } if (!string.IsNullOrEmpty(entry.Resource.Id)) { entry.Resource.Meta.AddExtension("http://hl7.org/fhir/StructureDefinition/extension-Meta.source|3.2", new FhirUri(entry.Resource.ResourceIdentity(entry.Resource.ResourceBase).OriginalString)); } var prov = member.CreateProvenance(); member.WithProvenance(prov, entry.Resource, entry.FullUrl); result.Entry.Add(new Bundle.EntryComponent() { FullUrl = $"urn-uuid{Guid.NewGuid().ToString("D")}", Search = new Bundle.SearchComponent() { Mode = Bundle.SearchEntryMode.Include }, Resource = prov }); } OperationOutcome oe = new OperationOutcome(); oe.Issue.Add(new OperationOutcome.IssueComponent() { Severity = OperationOutcome.IssueSeverity.Information, Code = OperationOutcome.IssueType.Informational, Details = new CodeableConcept(null, null, $"Searching {member.Name} found {partialResult.Total} results"), Diagnostics = partialResult.SelfLink?.OriginalString }); result.Entry.Add(new Bundle.EntryComponent() { Search = new Bundle.SearchComponent() { Mode = Bundle.SearchEntryMode.Outcome }, Resource = oe }); } } catch (FhirOperationException ex) { if (ex.Outcome != null) { ex.Outcome.Issue.Insert(0, new OperationOutcome.IssueComponent() { Severity = OperationOutcome.IssueSeverity.Information, Code = OperationOutcome.IssueType.Exception, Details = new CodeableConcept(null, null, $"Exception Searching {member.Name}"), Diagnostics = member.Url }); result.Entry.Add(new Bundle.EntryComponent() { Search = new Bundle.SearchComponent() { Mode = Bundle.SearchEntryMode.Outcome }, Resource = ex.Outcome }); } } catch (Exception ex) { // some other weirdness went on OperationOutcome oe = new OperationOutcome(); oe.Issue.Add(new OperationOutcome.IssueComponent() { Severity = OperationOutcome.IssueSeverity.Information, Code = OperationOutcome.IssueType.Exception, Details = new CodeableConcept(null, null, $"Exception Searching {member.Name}"), Diagnostics = member.Url }); oe.Issue.Add(new OperationOutcome.IssueComponent() { Severity = OperationOutcome.IssueSeverity.Error, Code = OperationOutcome.IssueType.Exception, Diagnostics = ex.Message }); result.Entry.Add(new Bundle.EntryComponent() { Search = new Bundle.SearchComponent() { Mode = Bundle.SearchEntryMode.Outcome }, Resource = oe }); } } // TODO:Merge Sort the results? // TODO:Mess with the back/next links return(System.Threading.Tasks.Task.FromResult(result)); }
public void TearDown() { //--- Clean Up --------------------------------------------------------- //Clean up by deleting all Test Endpoint SearchParams sp = new SearchParams().Where($"identifier={StaticTestData.TestIdentiferSystem}|"); try { clientFhir.Delete(ResourceType.Endpoint.GetLiteral(), sp); } catch (Exception Exec) { Assert.True(false, "Exception thrown on conditional delete of resource Endpoint: " + Exec.Message); } //Clean up by deleting all Test Patients sp = new SearchParams().Where($"identifier={StaticTestData.TestIdentiferSystem}|"); try { clientFhir.Delete(ResourceType.Patient.GetLiteral(), sp); } catch (Exception Exec) { Assert.True(false, "Exception thrown on conditional delete of resource Patient: " + Exec.Message); } //Clean up by deleting all Test Patients family sp = new SearchParams().Where($"family={PatientOneFamily}"); try { clientFhir.Delete(ResourceType.Patient.GetLiteral(), sp); } catch (Exception Exec) { Assert.True(false, "Exception thrown on conditional delete of resource Patient: " + Exec.Message); } //Clean up by deleting all Test Patients sp = new SearchParams().Where($"identifier={StaticTestData.TestIdentiferSystem}|"); try { clientFhir.Delete(ResourceType.Observation.GetLiteral(), sp); } catch (Exception Exec) { Assert.True(false, "Exception thrown on conditional delete of resource Patient: " + Exec.Message); } //Clean up by deleting all Test Organization sp = new SearchParams().Where($"identifier={StaticTestData.TestIdentiferSystem}|"); try { clientFhir.Delete(ResourceType.Organization.GetLiteral(), sp); } catch (Exception Exec) { Assert.True(false, "Exception thrown on conditional delete of resource Patient: " + Exec.Message); } Server.Dispose(); }
public async Task <PagedViewModelResult <PTOInformationViewModel> > GetAllActivePTOs(SearchParams searchParams) { _logger.LogInfo("Trying to get all active PTOs on language " + searchParams.Lang); try { PagedViewModelResult <PTOInformationViewModel> ptoInformation = _mapper.Map <PaginatedList <PTOInformation>, PagedViewModelResult <PTOInformationViewModel> >(await _ptoRepository.GetActivePTOs(_mapper.Map <PassInfoSearchParams>(searchParams))); //Get all PTOs which PTO descriptions are available var activePTOs = new List <PTOInformationViewModel>(); foreach (var item in ptoInformation.Items) { //Filter based on language from the paginated result. item.PTODescription = item?.PTODescription?.Where(p => p.SelectedLanguage == searchParams.Lang); if (item.PTODescription.Count() > 0) { activePTOs.Add(item); } } ptoInformation.Items = activePTOs; _logger.LogInfo("Retrieved all active PTOs on language " + searchParams.Lang); return(ptoInformation); } catch (Exception ex) { _logger.LogInfo(ex.Message); return(null); } }
public MatchingPoint FindStateFromScreen(bool quickCheck = false) { SearchParams search = new SearchParams(); MatchingPoint match = new MatchingPoint(); search.UsingGameExtents = false; search.MinimumConfidence = this.MinimumConfidence; search.QuickCheck = quickCheck; if (StopRequested) return match; //STEP1: Get image to find and mask(if available) search.ToFind = GetBitmapByType(StateBitmapType.RawImage); if (StopRequested) return match; //STEP2: Get area of screen to search GetSearchAreaBitmap(ref search); if (StopRequested) return match; //STEP3: Do search if (FindUsingAlternateMasks(search, ref match)) return match; return match; }
private bool FindHazy(SearchParams search, ref MatchingPoint match) { match = game.findBitmapWorker.FindInScreen(search.SearchArea, search.ToFind, search.Mask, search.QuickCheck, search.MinimumConfidence); if (match.Confident) game.UpdateGameExtents(match.X, match.Y); return match.Confident; }
public IResourceServiceOutcome PostFormSearch(string BaseRequestUri, HttpRequestMessage Request, string ResourceName, IEnumerable <Tuple <string, string> > FormParameterList) { using (DbContextTransaction Transaction = IUnitOfWork.BeginTransaction()) { try { IRequestMeta RequestMeta = IRequestMetaFactory.CreateRequestMeta().Set(Request, SearchParams.FromUriParamList(FormParameterList)); IResourceServiceOutcome ResourceServiceOutcome = IResourceApiServices.GetSearch(RequestMeta); ResourceServiceOutcome.SummaryType = RequestMeta.SearchParameterGeneric.SummaryType; Transaction.Commit(); return(ResourceServiceOutcome); } catch (Exception Exec) { Transaction.Rollback(); ILog.Error(Exec, "PyroService.PostFormSearch"); throw new PyroException(System.Net.HttpStatusCode.InternalServerError, Common.Tools.FhirOperationOutcomeSupport.Create(OperationOutcome.IssueSeverity.Error, OperationOutcome.IssueType.Exception, Exec.Message), Exec.Message); } } }
public int SearchCount(SearchParams s) { var searcher = Factory.CreateSearcher(); log.Write(LogEvent.Debug, "Search count query: {0}", s.Query); var hits = searcher.Search(s.Query); return hits.Length(); }
public new List <BankAccount> List(string customer_id, SearchParams filters = null) { return(base.List(customer_id, filters)); }
private SearchResult Search(SearchParams p) { var r = new SearchResult(p.timer); var t = r.searchTimer; t.BeginKernelTime(); var collector = CreateCollector(p.collectorSize); p.searcher.Search(p.query, collector); t.FinishKernelTime(); t.BeginCollectingTime(); //var topDocs = p.useHowMany ? collector.TopDocs(p.skip, p.howMany) : collector.TopDocs(p.skip); TopDocs topDocs = null; if (this.LucQuery.SortFields.Length > 0) { topDocs = p.useHowMany ? ((TopFieldCollector)collector).TopDocs(p.skip, p.howMany) : ((TopFieldCollector)collector).TopDocs(p.skip); } else { topDocs = p.useHowMany ? ((TopScoreDocCollector)collector).TopDocs(p.skip, p.howMany) : ((TopScoreDocCollector)collector).TopDocs(p.skip); } r.totalCount = topDocs.TotalHits; var hits = topDocs.ScoreDocs; t.FinishCollectingTime(); t.BeginPagingTime(); GetResultPage(hits, p, r); t.FinishPagingTime(); return r; }
public List <BankAccount> List(SearchParams filters = null) { return(base.List(null, filters)); }
public void RemoveSearch(SearchParams p) { if (!this._searchParamsCollection.Contains(p)) { return; } else { this._searchParamsCollection.Remove(p); } }
public async Task <object> List([FromUri] SearchParams searchParams) { return(Ok(await _stateService.List(searchParams))); }
internal static string SearchForSubtitleByImdbID(string imdbid, string language, string logintoken, IMLItem item) { #region vars SearchParams[] paramS = new SearchParams[1]; paramS[0].sublanguageid = language; paramS[0].imdbid = imdbid; string[] downloadlink = new string[25]; #endregion XmlRpcStruct moviesubs = OSoperations.Proxy.SearchSubtitles(logintoken, paramS); foreach (DictionaryEntry d in moviesubs) { OSoperations.token = Convert.ToString(d.Key); if (OSoperations.token != "data") continue; object obj = d.Value; Type type = obj.GetType(); string typename = type.Name; if (typename == "Boolean") return null; object[] subsarray = (object[])obj; downloadlink = new string[subsarray.Length]; for (int i = 0; i < subsarray.Length; i++) { object x = subsarray[i]; XmlRpcStruct subtitle = (XmlRpcStruct)x; foreach (DictionaryEntry e in subtitle) { OSoperations.token = Convert.ToString(e.Key); if (OSoperations.token != "ZipDownloadLink") continue; object val = e.Value; string str = (string)val; downloadlink[i] = str; } } } string firstSubtitleFound = downloadlink[0]; return firstSubtitleFound; }
public Task <List <BookingDTM> > GetAll(SearchParams search) { throw new NotImplementedException(); }
public ActionResult <FhirResponse> Update(string type, Resource resource, string id = null) { string versionId = Request.GetTypedHeaders().IfMatch?.FirstOrDefault()?.Tag.Buffer; Key key = Key.Create(type, id, versionId); if (key.HasResourceId()) { Request.TransferResourceIdIfRawBinary(resource, id); return(new ActionResult <FhirResponse>(_fhirService.Update(key, resource))); } else { return(new ActionResult <FhirResponse>(_fhirService.ConditionalUpdate(key, resource, SearchParams.FromUriParamList(Request.TupledParameters())))); } }
// GET: Clients/mSearch public async Task <List <ClientDTM> > GetClients(SearchParams mSearch) { List <ClientDTM> query = await TheRepo.ClientsDTM.GetAll(mSearch); return(query); }
private void TestLinqIncludeImpl() { var app = SetupHelper.BooksApp; var session = app.OpenSession(); var summary = new List<string>(); // chained properties, with multiple expressions in auto object var qReviews = session.EntitySet<IBookReview>().Where(r => r.Rating >= 1) .Include(r => new { r.User, r.Book.Publisher }); // will load users, referenced books AND its publishers var reviews = qReviews.ToList(); //Go through all reviews, touch properties of objects; // Without Include, accessing 'review.Book.Title' would cause loading of IBook entity; with Include there should be no extra db roundrips // We handle Loaded app event - fired for any record loaded; we increment loadCount in event handler _loadCount = 0; summary.Clear(); foreach (var rv in reviews) summary.Add(string.Format(" User {0} reviewed '{1}' from {2} and gave rating: {3}", rv.User.DisplayName, rv.Book.Title, rv.Book.Publisher.Name, rv.Rating)); Assert.IsTrue(summary.Count > 0, "Expected some summaries."); var txtSummary = string.Join(Environment.NewLine, summary); Assert.AreEqual(0, _loadCount, "Expected 0 load count"); // list properties, many2one and many2many; 2 forms of Include var qOrders = session.EntitySet<IBookOrder>().Where(o => o.Status != OrderStatus.Canceled) .Include(o => new { o.Lines, o.User }) // include version 1 - against results of query (IBookOrder) .Include((IBookOrderLine l) => l.Book) // include version 2 - against 'internal' results, order lines; means 'whenever we load IBookOrderLine, load all related Books' .Include((IBook b) => new { b.Publisher, b.Authors}) //again, for any book, load publisher and authors ; var orders = qOrders.ToList(); //verify - go thru all orders, touch lines, books, users, publishers; check there were no DB commands executed _loadCount = 0; summary.Clear(); foreach (var order in orders) foreach (var ol in order.Lines) { var authors = string.Join(", ", ol.Book.Authors.Select(a => a.FullName)); summary.Add(string.Format(" User {0} bought {1} books titled '{2}' by {3} from {4}.", order.User.UserName, ol.Quantity, ol.Book.Title, authors, ol.Book.Publisher.Name)); } txtSummary = string.Join(Environment.NewLine, summary); Assert.IsTrue(summary.Count > 0, "Expected non-empty summary"); Assert.AreEqual(0, _loadCount, "Expected no extra db load commands."); //Using nullable property session = app.OpenSession(); var qBooks = session.EntitySet<IBook>().Where(b => b.Price > 0) .Include(b => b.Editor); //book.Editor is nullable property var books = qBooks.ToList(); _loadCount = 0; summary.Clear(); foreach (var bk in books) { if (bk.Editor != null) summary.Add(string.Format("Book '{0}' edited by {1}.", bk.Title, bk.Editor.UserName)); } txtSummary = string.Join(Environment.NewLine, summary); Assert.AreEqual(0, _loadCount, "Expected zero load count."); //var txtLog = session.Context.LocalLog.GetAllAsText(); //single entity session = app.OpenSession(); var someBook = session.EntitySet<IBook>().Where(b => b.Price > 0).Include(b => b.Publisher).First(); Assert.IsNotNull(someBook, "Expected a book."); _loadCount = 0; var pubName = someBook.Publisher.Name; Assert.AreEqual(0, _loadCount, "Expected no load commands."); // for queries that do not return entities the include is simply ignored var bkGroups = session.EntitySet<IBook>().GroupBy(b => b.Publisher.Id).Include(b => b.Key).ToList(); Assert.IsNotNull(bkGroups, "Expected something here"); // Reviews query, but now using Context.AddInclude; var context = app.CreateSystemContext(); context.AddInclude((IBookOrder o) => new { o.Lines, o.User }) .AddInclude((IBookOrderLine l) => l.Book.Publisher); session = context.OpenSession(); var qOrders2 = session.EntitySet<IBookOrder>().Where(o => o.Status != OrderStatus.Canceled); var orders2 = qOrders2.ToList(); //verify - go thru all orders, touch lines, books, users, publishers; check there were no DB commands executed _loadCount = 0; summary.Clear(); foreach (var order in orders2) foreach (var ol in order.Lines) summary.Add(string.Format(" User {0} bought {1} books titled '{2}' from {3}.", order.User.UserName, ol.Quantity, ol.Book.Title, ol.Book.Publisher.Name)); txtSummary = string.Join(Environment.NewLine, summary); Assert.IsTrue(summary.Count > 0, "Expected non-empty summary"); Assert.AreEqual(0, _loadCount, "Expected no extra db load commands."); var removed = context.RemoveInclude((IBookOrder o) => new { o.Lines, o.User }) && context.RemoveInclude((IBookOrderLine l) => l.Book.Publisher); Assert.IsTrue(removed, "Removing Include from operation context failed."); Assert.IsFalse(context.HasIncludes(), "Removing Include from operation context failed."); //Search with includes; you can use a single include with ExecuteSearch. If you have more, use Context.AddInclude session = app.OpenSession(); var searchParams = new SearchParams() {OrderBy = "CreatedOn-desc", Take = 10}; var where = session.NewPredicate<IBookReview>() .And(r => r.Book.Category == BookCategory.Programming); var foundReviews = session.ExecuteSearch(where, searchParams, include: r => new { r.Book.Publisher, r.User }); Assert.IsTrue(foundReviews.Results.Count > 0, "Expected some reviews"); _loadCount = 0; summary.Clear(); foreach (var rv in foundReviews.Results) summary.Add(string.Format(" User {0} reviewed '{1}' from {2} and gave rating: {3}", rv.User.DisplayName, rv.Book.Title, rv.Book.Publisher.Name, rv.Rating)); txtSummary = string.Join(Environment.NewLine, summary); Assert.AreEqual(0, _loadCount, "Expected 0 load count"); }
public FhirResponse ConditionalUpdate(Key key, Resource resource, SearchParams _params) { Key existing = index.FindSingle(key.TypeName, _params).WithoutVersion(); return(this.Update(existing, resource)); }
public SearchStartedEventArgs(SearchParams SearchParams) { this.SearchParams = SearchParams; }
/// <summary> /// Matches a list of known signs with a list of candidates /// </summary> /// <param name="candidates"> candidate signs </param> /// <param name="knownSigns"> known signs </param> /// <returns> matched signs </returns> public List <TrafficSignMatch> MatchSigns(List <TrafficSign> candidates, List <TrafficSign> knownSigns) { // Return empty list if parameters are unusable if (candidates == null || knownSigns == null || candidates.Count < 1 || knownSigns.Count < 1) { return(new List <TrafficSignMatch>()); } Matches = new List <TrafficSignMatch>(); List <TrafficSignMatch> result = new List <TrafficSignMatch>(); LinearIndexParams ip = new LinearIndexParams(); SearchParams sp = new SearchParams(); // Iterate over candidates foreach (TrafficSign candi in Candidates) { // best match and score int bestScore = 0; TrafficSignMatch bestMatch = null; // Iterate over known signs foreach (TrafficSign knownsign in knownSigns) { VectorOfVectorOfDMatch match = new VectorOfVectorOfDMatch(); // Match the sign or log the problem try { match = knownsign.MatchToOtherSign(candi); } catch (Exception ex) { Console.WriteLine(ex.Message); } Mat mask = new Mat(match.Size, 1, DepthType.Cv8U, 1); mask.SetTo(new MCvScalar(255)); // Filter duplicate matches Features2DToolbox.VoteForUniqueness(match, 0.8, mask); // Compute the homography matrix Mat homography = Features2DToolbox.GetHomographyMatrixFromMatchedFeatures(knownsign.KeyPoints, candi.KeyPoints, match, mask, 1.5); // Compute a score for the match int score = ScoreMatch(homography, knownsign, candi); // Current score is better than previous if (score > bestScore) { bestScore = score; bestMatch = new TrafficSignMatch(candi, knownsign, score, match, homography); //ImageViewer viewer = new ImageViewer(); //viewer.Image = Draw(knownsign.ImageGray.Convert<Bgr, byte>(), candi.ImageGray.Convert<Bgr, byte>(), knownsign.KeyPoints, candi.KeyPoints, match); //viewer.Text = "Match score: " + score; //viewer.Show(); } } if (bestMatch != null && bestMatch.MatchScore > 0) { Matches.Add(bestMatch); } } return(result); }
private bool FindExact(SearchParams search, ref MatchingPoint match) { if (search.QuickCheck && search.SearchArea.Size == search.ToFind.Size) { match = game.findBitmapWorker.CheckExactMatch(search.SearchArea, search.ToFind, search.Mask, search.MinimumConfidence); if (!match.Confident) { try { if (game.DebugMode) { //string path = String.Format("{0}-notmatched-{1}-{2}.bmp", Assembly.GetCallingAssembly().Location, this.AssetName, DateTime.Now.ToString("hhmmss")); //search.SearchArea.Save(path); } } catch (Exception) { } } return match.Confident; } return false; }
private static IQueryable <WikiFightWebSqlLite> FilterWeightDivision(SearchParams searchQueryParams, IQueryable <WikiFightWebSqlLite> query) { switch (searchQueryParams.WeightDivision) { case WeightDivisions.Flyweight: query = query.Where(e => e.WeightClass == WeightDivision.Flyweight); break; case WeightDivisions.Bantamweight: query = query.Where(e => e.WeightClass == WeightDivision.Bantamweight); break; case WeightDivisions.Featherweight: query = query.Where(e => e.WeightClass == WeightDivision.Featherweight); break; case WeightDivisions.Lightweight: query = query.Where(e => e.WeightClass == WeightDivision.Lightweight); break; case WeightDivisions.Welterweight: query = query.Where(e => e.WeightClass == WeightDivision.Welterweight); break; case WeightDivisions.Middleweight: query = query.Where(e => e.WeightClass == WeightDivision.Middleweight); break; case WeightDivisions.LightHeavyweight: query = query.Where(e => e.WeightClass == WeightDivision.LightHeavyweight); break; case WeightDivisions.Heavyweight: query = query.Where(e => e.WeightClass == WeightDivision.Heavyweight); break; case WeightDivisions.SuperHeavyweight: query = query.Where(e => e.WeightClass == WeightDivision.SuperHeavyweight); break; case WeightDivisions.WomensStrawweight: query = query.Where(e => e.WeightClass == WeightDivision.WomensStrawweight); break; case WeightDivisions.WomensFlyweight: query = query.Where(e => e.WeightClass == WeightDivision.WomensFlyweight); break; case WeightDivisions.WomensBantamweight: query = query.Where(e => e.WeightClass == WeightDivision.WomensBantamweight); break; case WeightDivisions.WomensFeatherweight: query = query.Where(e => e.WeightClass == WeightDivision.WomensFeatherweight); break; case WeightDivisions.Any: break; default: throw new ArgumentOutOfRangeException(); } return(query); }
private bool FindUsingAlternateMasks(SearchParams search, ref MatchingPoint match) { Stack<StateBitmapType> typesToCheck = new Stack<StateBitmapType>(); typesToCheck.Push(StateBitmapType.Blue); typesToCheck.Push(StateBitmapType.Mask); #if DEBUG typesToCheck.Clear(); // Only check smartmask in debug #endif typesToCheck.Push(StateBitmapType.SmartMask); while (typesToCheck.Count > 0) { if (StopRequested) return false; StateBitmapType maskType = typesToCheck.Pop(); search.Mask = GetBitmapByType(maskType, search.ToFind.Size, search.ToFind.PixelFormat); if (StopRequested) return false; if (FindExact(search, ref match)) return true; if (search.QuickCheck) return false; // First match didnt work, but asked to be quick if (StopRequested) return false; if (FindHazy(search, ref match)) return true; if (StopRequested) return false; } return false; }
public new List <Subscription> List(string customer_id, SearchParams filters = null) { return(base.List(customer_id, filters)); }
public DocumentResult[] Search(SearchParams s) { var searcher = Factory.CreateSearcher(); log.Write(LogEvent.Debug, "Search query: {0}", s.Query); var hits = s.Sort != null && s.Sort.Length > 0 ? searcher.Search(s.Query, new Sort(s.Sort)) : searcher.Search(s.Query); var docs = new DocumentResult[Math.Min(hits.Length(), s.MaxResults)]; for (int i = 0; i < docs.Length; i++) docs[i] = new DocumentResult(hits.Doc(i), hits.Score(i)); searcher.Close(); log.Write(LogEvent.Debug, "Search results: {0} document(s)", docs.Length); return docs; }
private SearchPreProcessResult <T> PreProcessFileSystemNameRegularExpressionSearch <T>(SearchParams searchParams, Func <IPathMatcher, T, IPathComparer, bool> matchName, Func <IPathMatcher, T, IPathComparer, bool> matchRelativeName) { var pattern = searchParams.SearchString ?? ""; pattern = pattern.Trim(); if (string.IsNullOrWhiteSpace(pattern)) { return(null); } var data = _compiledTextSearchDataFactory.Create(searchParams, x => true); var provider = data.GetSearchContainer(data.ParsedSearchString.MainEntry); var matcher = new CompiledTextSearchProviderPathMatcher(provider); var comparer = searchParams.MatchCase ? PathComparerRegistry.CaseSensitive : PathComparerRegistry.CaseInsensitive; if (pattern.Contains('/') || pattern.Contains("\\\\")) { return(new SearchPreProcessResult <T> { Matcher = (item) => matchRelativeName(matcher, item, comparer), SearchData = data, }); } else { return(new SearchPreProcessResult <T> { Matcher = (item) => matchName(matcher, item, comparer), SearchData = data, }); } }
public void OnSearch(ref SearchParams param, System.ComponentModel.BackgroundWorker bw) { if (param.Act == SearchParams.Action.aContinue) { SearchNext(bw); return; } try { if (yahoo == null) yahoo = new YahooSearchService(); pattern = param.Pattern + " " + control.SelectedSize; resultCount = 0; start = 0; imagesFound = 0; imagesToLoad.Clear(); SearchNext(bw); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("error in search: " + e); } }
public FlannMatcher(int matchLimit, int kConstant, HierarchicalClusteringIndexParams hierarchicalParams, SearchParams searchParams) { _matchLimit = matchLimit; _kConstant = kConstant; _hierarchicalParams = hierarchicalParams; _searchParams = searchParams; }
private void search_Click(object sender, EventArgs e) { dataGridView1.Rows.Clear(); try { string nacionalidade = this.nacio_text.Text; string data_nascimento = this.dateTimePicker1.Text; string nome = this.nome_text.Text; // Argumentos 1º name , 2º birthday , 3º nacionalidade SearchParams sp = new SearchParams(); sp.filters = new String[] { nome , data_nascimento , nacionalidade } ; Person[] list = serverClient.GetAllPerson(sp).result; if (list == null) return; persons = new List<Person>(list); persons.ForEach(AddPerson); } catch (Exception exception) { var info = new InfoForm(); info.Add(exception.Message); info.ShowDialog(this); info.Dispose(); } /*dataGridView1.Rows.Clear(); IEnumerable<Person> list = server.GetAllPerson(); var filter = new PersonFilter(list); if (!nome_text.Text.Equals("")) { filter.Name((nome_text.Text)); } if (!(dateTimePicker1.Value.Date == DateTime.Now.Date)) { filter.Data(dateTimePicker1.Value); } if (!nacio_text.Text.Equals("")) { filter.Nacionalidade((nacio_text.Text)); } persons = filter.getFilter().ToList(); persons.ForEach(AddPerson);*/ }
//private static async Task<List<Medication>> GetMedicationsData(Hashtable parameters, string patientId) //{ // var mySearch = new SearchParams(); // mySearch.Parameters.Add(new Tuple<string, string>("patient", patientId)); // try // { // var fhirClient = new FhirClient("https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca"); // //Query the fhir server with search parameters, we will retrieve a bundle // var searchResultResponse = await Task.Run(() => fhirClient.Search<Hl7.Fhir.Model.MedicationOrder>(mySearch)); // //There is an array of "entries" that can return. Get a list of all the entries. // return // searchResultResponse // .Entry // .AsParallel() //as parallel since we are making network requests // .Select(entry => // { // var medOrders = fhirClient.Read<MedicationOrder>("MedicationOrder/" + entry.Resource.Id); // var safeCast = (medOrders?.Medication as ResourceReference)?.Reference; // if (string.IsNullOrWhiteSpace(safeCast)) // { // return null; // } // return fhirClient.Read<Medication>(safeCast); // }) // .Where(a => a != null) // .ToList(); //tolist to force the queries to occur now // } // catch (AggregateException e) // { // throw e.Flatten(); // } // catch (FhirOperationException) // { // // if we have issues we likely got a 404 and thus have no medication orders... // return new List<Medication>(); // } //} private DataTable GetMedicationsData(Hashtable parameters) { try { var mySearch = new SearchParams(); mySearch.Parameters.Add(new Tuple <string, string>("patient", parameters["patientid"].ToString())); DataTable dtMedications = new DataTable(); dtMedications.Columns.Add("CreatedBy"); dtMedications.Columns.Add("MedicationId"); dtMedications.Columns.Add("MedicationName"); dtMedications.Columns.Add("Direction"); dtMedications.Columns.Add("DosageFrequencyValue"); dtMedications.Columns.Add("DosageRoute"); dtMedications.Columns.Add("DosageAdditionalInstructions"); dtMedications.Columns.Add("DosageFrequencyUnit"); dtMedications.Columns.Add("DosageUnit"); dtMedications.Columns.Add("DosageQuantity"); dtMedications.Columns.Add("DosageFrequencyDescription"); dtMedications.Columns.Add("DosageDurationUnit"); dtMedications.Columns.Add("StopDate"); dtMedications.Columns.Add("StartDate"); dtMedications.Columns.Add("EnterDate"); try { #region DSTU2 var fhirClient = new FhirClient("https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/"); fhirClient.UseFormatParam = true; fhirClient.PreferredFormat = ResourceFormat.Json; //Query the fhir server with search parameters, we will retrieve a bundle var searchResultResponse = fhirClient.Search <MedicationOrder>(mySearch); //var searchResultResponse = fhirClient.Read<MedicationOrder>("MedicationOrder/4342010"); //return new List<Medication>(); List <Medication> objlist = new List <Medication>(); foreach (Bundle.EntryComponent entry in searchResultResponse.Entry) { try { if (entry.FullUrl == null) { return(dtMedications); } var medOrders = fhirClient.Read <MedicationOrder>("MedicationOrder/" + entry.Resource.Id); //var safeCast = (medOrders?.Medication as ResourceReference)?.Reference; //if (string.IsNullOrWhiteSpace(safeCast)) //{ // //return null; //} //else //{ DataRow dRowMedication = dtMedications.NewRow(); dRowMedication["CreatedBy"] = medOrders.Prescriber.Display; dRowMedication["MedicationId"] = medOrders.Id; try { dRowMedication["MedicationName"] = ((Hl7.Fhir.Model.CodeableConcept)medOrders.Medication).Text; } catch (Exception) { dRowMedication["MedicationName"] = ((Hl7.Fhir.Model.ResourceReference)medOrders.Medication).Display; } dRowMedication["Direction"] = medOrders.DosageInstruction[0].Text; if (medOrders.DosageInstruction[0].Timing.Repeat != null) { dRowMedication["DosageFrequencyValue"] = medOrders.DosageInstruction[0].Timing.Repeat.Period.ToString(); dRowMedication["DosageFrequencyUnit"] = medOrders.DosageInstruction[0].Timing.Repeat.PeriodUnits.ToString(); } if (medOrders.DosageInstruction[0].Route != null) { dRowMedication["DosageRoute"] = medOrders.DosageInstruction[0].Route.Coding[0].Display; } if (medOrders.DosageInstruction[0].AdditionalInstructions != null) { dRowMedication["DosageAdditionalInstructions"] = medOrders.DosageInstruction[0].AdditionalInstructions.Text; } if ((Hl7.Fhir.Model.Quantity)medOrders.DosageInstruction[0].Dose != null) { dRowMedication["DosageUnit"] = ((Hl7.Fhir.Model.Quantity)medOrders.DosageInstruction[0].Dose).Unit; dRowMedication["DosageQuantity"] = ((Hl7.Fhir.Model.Quantity)medOrders.DosageInstruction[0].Dose).Value; } dRowMedication["DosageFrequencyDescription"] = string.Empty; dRowMedication["DosageDurationUnit"] = medOrders.DispenseRequest.ExpectedSupplyDuration; if (medOrders.DosageInstruction[0].Timing.Repeat != null) { dRowMedication["StopDate"] = ((Hl7.Fhir.Model.Period)(medOrders.DosageInstruction[0].Timing.Repeat.Bounds)).End == null ? string.Empty : DateFormatMMDDYYYY(((Hl7.Fhir.Model.Period)(medOrders.DosageInstruction[0].Timing.Repeat.Bounds)).End); dRowMedication["StartDate"] = ((Hl7.Fhir.Model.Period)(medOrders.DosageInstruction[0].Timing.Repeat.Bounds)).Start == null ? string.Empty : DateFormatMMDDYYYY(((Hl7.Fhir.Model.Period)(medOrders.DosageInstruction[0].Timing.Repeat.Bounds)).Start); } dRowMedication["EnterDate"] = medOrders.DateWritten == null ? string.Empty : DateFormatMMDDYYYY(medOrders.DateWritten); dtMedications.Rows.Add(dRowMedication); //string MedicationName = medOrders.Medication.ToString(); //var Medication = fhirClient.Read<Medication>("Medication/" + safeCast); //objlist.Add(Medication); //} } catch (Exception) { throw; } } return(dtMedications); #endregion //return // searchResultResponse // .Entry // .Select(ResourceEntry => // { // var medOrders = fhirClient.Read<MedicationOrder>("MedicationOrder/" + ResourceEntry.Resource.Id); // var safeCast = (medOrders?.Medication as ResourceReference)?.Reference; // if (string.IsNullOrWhiteSpace(safeCast)) // { // return null; // } // return fhirClient.Read<Medication>(safeCast); // }) // .Where(a => a != null) // .ToList(); //tolist to force the queries to occur now } catch (AggregateException e) { throw e.Flatten(); } catch (FhirOperationException) { // if we have issues we likely got a 404 and thus have no medication orders... return(new DataTable()); } catch (Exception ex) { throw ex; } } catch (Exception) { throw; } }
private void GetResultPage(ScoreDoc[] hits, SearchParams p, SearchResult r) { var result = new List<LucObject>(); if (hits.Length == 0) { r.result = result; return; } var upperBound = hits.Length; var index = 0; while (true) { Document doc = p.searcher.Doc(hits[index].Doc); if (p.allVersions || IsPermitted(doc, p.user, p.isCurrentUser)) { result.Add(new LucObject(doc)); if (result.Count == p.top) { index++; break; } } if (++index >= upperBound) break; } r.nextIndex = index; r.result = result; }
public SearchResults Search(string resource, SearchParams searchCommand) { return(searcher.Search(resource, searchCommand)); }
public ProductsSearchParamsViewModel(long priceMin, long priceMax, string currencyName, SearchParams searchParams = null) { this._priceMin = priceMin / 100L; this._priceMax = priceMax / 100L; this._currencyName = currencyName; if (searchParams == null) { searchParams = new SearchParams(); } this._searchParams = searchParams; this.UpdateSelectedItem(); this.UpdatePrices(); }
public JsonResult Search(SearchParams @params) { var items = Service.Article.Search(@params.search.value, @params.OrderBy, @params.IsAsc, @params.length, @params.start); return Json(items); }
public SearchOptions Create(string compartmentType, string compartmentId, string resourceType, IReadOnlyList <Tuple <string, string> > queryParameters) { var searchOptions = new SearchOptions(); string continuationToken = null; var searchParams = new SearchParams(); var unsupportedSearchParameters = new List <Tuple <string, string> >(); // Extract the continuation token, filter out the other known query parameters that's not search related. foreach (Tuple <string, string> query in queryParameters ?? Enumerable.Empty <Tuple <string, string> >()) { if (query.Item1 == KnownQueryParameterNames.ContinuationToken) { // This is an unreachable case. The mapping of the query parameters makes it so only one continuation token can exist. if (continuationToken != null) { throw new InvalidSearchOperationException( string.Format(Core.Resources.MultipleQueryParametersNotAllowed, KnownQueryParameterNames.ContinuationToken)); } // Checks if the continuation token is base 64 bit encoded. Needed for systems that have cached continuation tokens from before they were encoded. if (Base64FormatRegex.IsMatch(query.Item2)) { continuationToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(query.Item2)); } else { continuationToken = query.Item2; } } else if (query.Item1 == KnownQueryParameterNames.Format) { // TODO: We need to handle format parameter. } else if (string.IsNullOrWhiteSpace(query.Item1) || string.IsNullOrWhiteSpace(query.Item2)) { // Query parameter with empty value is not supported. unsupportedSearchParameters.Add(query); } else if (string.Compare(query.Item1, KnownQueryParameterNames.Total, StringComparison.OrdinalIgnoreCase) == 0) { if (Enum.TryParse <TotalType>(query.Item2, true, out var totalType)) { // Estimate is not yet supported. if (totalType == TotalType.Estimate) { throw new SearchOperationNotSupportedException(Core.Resources.UnsupportedTotalParameter); } searchOptions.IncludeTotal = totalType; } else { throw new BadRequestException(Core.Resources.UnsupportedTotalParameter); } } else { // Parse the search parameters. try { // Basic format checking (e.g. integer value for _count key etc.). searchParams.Add(query.Item1, query.Item2); } catch (Exception ex) { throw new BadRequestException(ex.Message); } } } searchOptions.ContinuationToken = continuationToken; // Check the item count. if (searchParams.Count != null) { searchOptions.MaxItemCount = searchParams.Count.Value; } // Check to see if only the count should be returned searchOptions.CountOnly = searchParams.Summary == SummaryType.Count; // If the resource type is not specified, then the common // search parameters should be used. ResourceType parsedResourceType = ResourceType.DomainResource; if (!string.IsNullOrWhiteSpace(resourceType) && !Enum.TryParse(resourceType, out parsedResourceType)) { throw new ResourceNotSupportedException(resourceType); } var searchExpressions = new List <Expression>(); if (!string.IsNullOrWhiteSpace(resourceType)) { searchExpressions.Add(Expression.SearchParameter(_resourceTypeSearchParameter, Expression.StringEquals(FieldName.TokenCode, null, resourceType, false))); } searchExpressions.AddRange(searchParams.Parameters.Select( q => { try { return(_expressionParser.Parse(parsedResourceType.ToString(), q.Item1, q.Item2)); } catch (SearchParameterNotSupportedException) { unsupportedSearchParameters.Add(q); return(null); } }) .Where(item => item != null)); if (searchParams.Include?.Count > 0) { searchExpressions.AddRange(searchParams.Include.Select( q => _expressionParser.ParseInclude(parsedResourceType.ToString(), q)) .Where(item => item != null)); } if (!string.IsNullOrWhiteSpace(compartmentType)) { if (Enum.TryParse(compartmentType, out CompartmentType parsedCompartmentType)) { if (string.IsNullOrWhiteSpace(compartmentId)) { throw new InvalidSearchOperationException(Core.Resources.CompartmentIdIsInvalid); } searchExpressions.Add(Expression.CompartmentSearch(compartmentType, compartmentId)); } else { throw new InvalidSearchOperationException(string.Format(Core.Resources.CompartmentTypeIsInvalid, compartmentType)); } } if (searchExpressions.Count == 1) { searchOptions.Expression = searchExpressions[0]; } else if (searchExpressions.Count > 1) { searchOptions.Expression = Expression.And(searchExpressions.ToArray()); } if (unsupportedSearchParameters.Any()) { // TODO: Client can specify whether exception should be raised or not when it encounters unknown search parameters. // For now, we will ignore any unknown search parameters. } searchOptions.UnsupportedSearchParams = unsupportedSearchParameters; if (searchParams.Sort?.Count > 0) { var sortings = new List <(SearchParameterInfo, SortOrder)>(); List <(string parameterName, string reason)> unsupportedSortings = null; foreach (Tuple <string, Hl7.Fhir.Rest.SortOrder> sorting in searchParams.Sort) { try { SearchParameterInfo searchParameterInfo = _searchParameterDefinitionManager.GetSearchParameter(parsedResourceType.ToString(), sorting.Item1); sortings.Add((searchParameterInfo, sorting.Item2.ToCoreSortOrder())); } catch (SearchParameterNotSupportedException) { (unsupportedSortings ??= new List <(string parameterName, string reason)>()).Add((sorting.Item1, string.Format(Core.Resources.SearchParameterNotSupported, sorting.Item1, resourceType))); } } searchOptions.Sort = sortings; searchOptions.UnsupportedSortingParams = (IReadOnlyList <(string parameterName, string reason)>)unsupportedSortings ?? Array.Empty <(string parameterName, string reason)>(); } else { searchOptions.Sort = Array.Empty <(SearchParameterInfo searchParameterInfo, SortOrder sortOrder)>(); searchOptions.UnsupportedSortingParams = Array.Empty <(string parameterName, string reason)>(); } return(searchOptions); }
/// <summary> /// Create a Flann based matcher. /// </summary> /// <param name="indexParams">The type of index parameters</param> /// <param name="search">The search parameters</param> public FlannBasedMatcher(IIndexParams indexParams, SearchParams search) { _ptr = Features2DInvoke.cveFlannBasedMatcherCreate(indexParams.IndexParamPtr, search.Ptr, ref _descriptorMatcherPtr); }
//Örneğin İki Tarih Arası İStenirse bunu bir attribute ile meta dataya göm ve sayı tarih vb tüm alanlar için Kullan. public SearchResult Search(SearchParams searchParams) => new SearchCriteriaResolver().Search(searchParams);
public void OnSearch(ref SearchParams param, System.ComponentModel.BackgroundWorker bw) { if (param.Act == SearchParams.Action.aContinue) { SearchNext(bw); return; } try { var xraw = XElement.Load(string.Format(SEARCH, param.Pattern)); var xroot = XElement.Parse(xraw.ToString()); var links = (from item in xroot.Element("channel").Descendants("item") select new YouTubeElement { LinkUrl = item.Element("link").Value, EmbedUrl = GetEmbedUrlFromLink(item.Element("link").Value), ThumnailUrl = item.Elements().Where( child => child.Name.ToString().Contains("thumbnail") ).Single().Attribute("url").Value }).Take(20); elements = links.ToList<YouTubeElement>(); SearchNext(bw); } catch (Exception e) { } }
public SearchOptions Create(string compartmentType, string compartmentId, string resourceType, IReadOnlyList <Tuple <string, string> > queryParameters) { var searchOptions = new SearchOptions(); string continuationToken = null; var searchParams = new SearchParams(); var unsupportedSearchParameters = new List <Tuple <string, string> >(); // Extract the continuation token, filter out the other known query parameters that's not search related. foreach (Tuple <string, string> query in queryParameters ?? Enumerable.Empty <Tuple <string, string> >()) { if (query.Item1 == KnownQueryParameterNames.ContinuationToken) { // This is an unreachable case. The mapping of the query parameters makes it so only one continuation token can exist. if (continuationToken != null) { throw new InvalidSearchOperationException( string.Format(Core.Resources.MultipleQueryParametersNotAllowed, KnownQueryParameterNames.ContinuationToken)); } // Checks if the continuation token is base 64 bit encoded. Needed for systems that have cached continuation tokens from before they were encoded. if (Regex.IsMatch(query.Item2, "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$")) { continuationToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(query.Item2)); } else { continuationToken = query.Item2; } } else if (query.Item1 == KnownQueryParameterNames.Format) { // TODO: We need to handle format parameter. } else if (string.IsNullOrWhiteSpace(query.Item1) || string.IsNullOrWhiteSpace(query.Item2)) { // Query parameter with empty value is not supported. unsupportedSearchParameters.Add(query); } else { // Parse the search parameters. try { searchParams.Add(query.Item1, query.Item2); } catch (Exception ex) { _logger.LogInformation(ex, "Failed to parse the query parameter. Skipping."); // There was a problem parsing the parameter. Add it to list of unsupported parameters. unsupportedSearchParameters.Add(query); } } } searchOptions.ContinuationToken = continuationToken; // Check the item count. if (searchParams.Count != null) { searchOptions.MaxItemCount = searchParams.Count.Value; } // Check to see if only the count should be returned searchOptions.CountOnly = searchParams.Summary == SummaryType.Count; // If the resource type is not specified, then the common // search parameters should be used. ResourceType parsedResourceType = ResourceType.DomainResource; if (!string.IsNullOrWhiteSpace(resourceType) && !Enum.TryParse(resourceType, out parsedResourceType)) { throw new ResourceNotSupportedException(resourceType); } var searchExpressions = new List <Expression>(); if (!string.IsNullOrWhiteSpace(resourceType)) { searchExpressions.Add(Expression.SearchParameter(_resourceTypeSearchParameter, Expression.StringEquals(FieldName.TokenCode, null, resourceType, false))); } searchExpressions.AddRange(searchParams.Parameters.Select( q => { try { return(_expressionParser.Parse(parsedResourceType.ToString(), q.Item1, q.Item2)); } catch (SearchParameterNotSupportedException) { unsupportedSearchParameters.Add(q); return(null); } }) .Where(item => item != null)); if (!string.IsNullOrWhiteSpace(compartmentType)) { if (Enum.TryParse(compartmentType, out CompartmentType parsedCompartmentType)) { if (string.IsNullOrWhiteSpace(compartmentId)) { throw new InvalidSearchOperationException(Core.Resources.CompartmentIdIsInvalid); } searchExpressions.Add(Expression.CompartmentSearch(compartmentType, compartmentId)); } else { throw new InvalidSearchOperationException(string.Format(Core.Resources.CompartmentTypeIsInvalid, compartmentType)); } } if (searchExpressions.Count == 1) { searchOptions.Expression = searchExpressions[0]; } else if (searchExpressions.Count > 1) { searchOptions.Expression = Expression.And(searchExpressions.ToArray()); } if (unsupportedSearchParameters.Any()) { // TODO: Client can specify whether exception should be raised or not when it encounters unknown search parameters. // For now, we will ignore any unknown search parameters. } searchOptions.UnsupportedSearchParams = unsupportedSearchParameters; return(searchOptions); }