Esempio n. 1
0
 public void BadRegex_NoMagicSpecifierShouldBeHandled()
 {
     Create("");
     var searchData = new SearchData(@"\V", SearchKind.ForwardWithWrap, SearchOptions.None);
     var result = _search.FindNext(searchData, _textBuffer.GetPoint(0), _wordNavigator);
     Assert.True(result.IsNotFound);
 }
Esempio n. 2
0
 public void BadRegex_NoMagicSpecifierShouldBeHandled()
 {
     var snapshot = EditorUtil.CreateBuffer("hello world");
     var nav = _factory.Create<ITextStructureNavigator>();
     var searchData = new SearchData(SearchText.NewPattern(@"\V"), SearchKind.ForwardWithWrap, SearchOptions.None);
     var ret = _search.FindNext(searchData, snapshot.GetPoint(0), nav.Object);
     Assert.IsTrue(ret.IsNone());
 }
Esempio n. 3
0
 private FindOptions CreateFindOptions(string pattern, SearchKind kind, SearchOptions options)
 {
     var searchData = new SearchData(pattern, SearchOffsetData.None, kind, options);
     var serviceSearchData = _searchRaw.GetServiceSearchData(searchData, _wordNavigator);
     var findData = SearchService.ConvertToFindDataCore(serviceSearchData, _textBuffer.CurrentSnapshot);
     Assert.True(findData.IsResult);
     return findData.AsResult().FindOptions;
 }
Esempio n. 4
0
            public async Task WithOffsetLineBelowImplicitCount()
            {
                Create("cat", "dog", "fish");
                var bindResult = await _search.DoSearchAsync("dog/+1", enter : true);

                var searchResult = bindResult.AsComplete().Result;
                var searchData   = new SearchData("dog", SearchOffsetData.NewLine(1), SearchKind.ForwardWithWrap, SearchOptions.Default);

                Assert.Equal(searchData, searchResult.SearchData);
            }
Esempio n. 5
0
            private void SimulateSearch(string pattern, SearchKind searchKind = null, SearchOptions searchOptions = SearchOptions.None)
            {
                searchKind = searchKind ?? SearchKind.Forward;

                var data = new SearchData(pattern, SearchOffsetData.None, searchKind, searchOptions);

                _search.SetupGet(x => x.InSearch).Returns(true).Verifiable();
                _search.SetupGet(x => x.CurrentSearchData).Returns(data).Verifiable();
                _search.SetupGet(x => x.CurrentSearchText).Returns(pattern).Verifiable();
            }
Esempio n. 6
0
 /// <summary>
 /// 初始化search map,使每一格的step均为-1
 /// </summary>
 void ResetSearchMap()
 {
     for (int i = 0; i < length; i++)
     {
         for (int j = 0; j < width; j++)
         {
             searchMap[i, j] = new SearchData(-1);
         }
     }
 }
Esempio n. 7
0
        /// <summary>
        /// FindWindoEx só procura componente filho com o nome exato da classe do componente.
        /// este metodo procura um componente filho, neto, com o nome texto e parte do nome do componente...
        /// </summary>
        /// <param name="windowText">Texto exibido no componente</param>
        /// <param name="partClassName">nome da classe inicia com ...</param>
        /// <param name="hwnd">Janela a ser procurado o componente</param>
        /// <returns></returns>
        public static IntPtr GetChildWindowHandle(string windowText, string partClassName, IntPtr hwnd)
        {
            var searchData = new SearchData {
                classNamePart = partClassName, WindowText = windowText
            };

            EnumChildWindows(hwnd, CallBackSearch, ref searchData);

            return(searchData.ResultHandle);
        }
Esempio n. 8
0
        private IntPtr GetChildWindowHandleClassAndRect(string className, IntPtr parentHandle, RECT rect)
        {
            var searchData = new SearchData {
                ParentHandle = parentHandle, Text = className, Rect = rect
            };

            EnumWindows(CallbackClassAndRect, ref searchData);

            return(searchData.ResultHandle);
        }
Esempio n. 9
0
        private IntPtr GetChildWindowHandleRectSize(IntPtr parentHandle, Size size)
        {
            var searchData = new SearchData {
                ParentHandle = parentHandle, Size = size
            };

            EnumWindows(CallbackRectSize, ref searchData);

            return(searchData.ResultHandle);
        }
Esempio n. 10
0
        public static List <IntPtr> GetAllChildWindowsWithClass(IntPtr hWndParent, string wndClass)
        {
            SearchData sd = new SearchData {
                Wndclass = wndClass, listPtr = new List <IntPtr>()
            };

            EnumChildWindows(hWndParent, new EnumWindowsProc(EnumProcChild), ref sd);

            return(sd.listPtr);
        }
Esempio n. 11
0
        public HttpResponseMessage Post(SearchData searchTerm)
        {
            DataModel    data   = new DataModel();
            DataIntermed person = new DataIntermed();


            HttpResponseMessage hrm = data.SearchByLastName(searchTerm.searchStr, out person.acctNo, out person.pin, out person.bal, out person.fName, out person.lName, out person.index, out person.image);

            return(hrm);
        }
Esempio n. 12
0
 public ActionResult Edit([Bind(Include = "SearchDataId,Name,Location")] SearchData searchData)
 {
     if (ModelState.IsValid)
     {
         db.Entry(searchData).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(searchData));
 }
Esempio n. 13
0
        public JsonResult AjaxMethod(string term)
        {
            var m = new SearchData
            {
                searchText  = "text is " + term,
                resultCount = 23,
            };

            return(Json(m));
        }
Esempio n. 14
0
        public bool compare(SearchData x, SearchData y)
        {
            bool equal = true;

            if (!y.DriverId.Count.Equals(x.DriverId.Count))
            {
                return(false);
            }
            int index = 0;

            foreach (var itemy in y.DriverId)
            {
                if (!itemy.Equals(x.DriverId[index]))
                {
                    return(false);
                }
                index++;
            }
            if (!x.FinalDate.Equals(y.FinalDate))
            {
                return(false);
            }
            if (!x.InitialDate.Equals(y.InitialDate))
            {
                return(false);
            }
            if (!y.MessageId.Count().Equals(x.MessageId.Count()))
            {
                return(false);
            }
            index = 0;
            foreach (var itemy in y.MessageId.OrderBy(a => a).ToList())
            {
                if (!itemy.Equals(x.MessageId.OrderBy(a => a).ToList()[index]))
                {
                    return(false);
                }
                index++;
            }
            if (!x.VehiclesId.Count().Equals(y.VehiclesId.Count()))
            {
                return(false);
            }

            index = 0;
            foreach (var itemy in y.VehiclesId.OrderBy(a => a).ToList())
            {
                if (!itemy.Equals(x.VehiclesId.OrderBy(a => a).ToList()[index]))
                {
                    return(false);
                }
                index++;
            }
            return(equal);
        }
Esempio n. 15
0
        private async Task <ActionResult> RunQueryAsync(SearchData model, int page, int leftMostPage)
        {
            InitSearch();

            var options = new SearchOptions
            {
                SearchMode = SearchMode.All,

                // Skip past results that have already been returned.
                Skip = page * GlobalVariables.ResultsPerPage,

                // Take only the next page worth of results.
                Size = GlobalVariables.ResultsPerPage,

                // Include the total number of results.
                IncludeTotalCount = true,
            };

            // Enter Hotel property names into this list so only these values will be returned.
            // If Select is empty, all values will be returned, which can be inefficient.
            options.Select.Add("HotelName");
            options.Select.Add("Description");

            // For efficiency, the search call should be asynchronous, so use SearchAsync rather than Search.
            model.resultList = await _searchClient.SearchAsync <Hotel>(model.searchText, options).ConfigureAwait(false);

            // This variable communicates the total number of pages to the view.
            model.pageCount = ((int)model.resultList.TotalCount + GlobalVariables.ResultsPerPage - 1) / GlobalVariables.ResultsPerPage;

            // This variable communicates the page number being displayed to the view.
            model.currentPage = page;

            // Calculate the range of page numbers to display.
            if (page == 0)
            {
                leftMostPage = 0;
            }
            else if (page <= leftMostPage)
            {
                // Trigger a switch to a lower page range.
                leftMostPage = Math.Max(page - GlobalVariables.PageRangeDelta, 0);
            }
            else if (page >= leftMostPage + GlobalVariables.MaxPageRange - 1)
            {
                // Trigger a switch to a higher page range.
                leftMostPage = Math.Min(page - GlobalVariables.PageRangeDelta, model.pageCount - GlobalVariables.MaxPageRange);
            }

            model.leftMostPage = leftMostPage;

            // Calculate the number of page numbers to display.
            model.pageRange = Math.Min(model.pageCount - leftMostPage, GlobalVariables.MaxPageRange);

            return(View("IndexAsync", model));
        }
Esempio n. 16
0
    // Find the worlddata with the given offset from the current world position
    // Used to connect new nodes into the world
    WorldData FindNode(int aXOffset, int aYOffset)
    {
        Queue <SearchData> frontier = new Queue <SearchData>();
        SearchData         d        = new SearchData(world, 0, 0);

        frontier.Enqueue(d);
        List <WorldData> visited = new List <WorldData>();

        visited.Add(world);

        SearchData current = null;

        while (frontier.Count != 0)
        {
            current = frontier.Dequeue();

            if (current.worldData.up != null && !visited.Contains(current.worldData.up) && (current.worldData.up.state & GameManager.SensorData.Clear) != 0)
            {
                frontier.Enqueue(new SearchData(current.worldData.up, current.xoffset, current.yoffset + 1));
                visited.Add(current.worldData.up);
            }
            if (current.worldData.down != null && !visited.Contains(current.worldData.down) && (current.worldData.down.state & GameManager.SensorData.Clear) != 0)
            {
                frontier.Enqueue(new SearchData(current.worldData.down, current.xoffset, current.yoffset - 1));
                visited.Add(current.worldData.down);
            }
            if (current.worldData.left != null && !visited.Contains(current.worldData.left) && (current.worldData.left.state & GameManager.SensorData.Clear) != 0)
            {
                frontier.Enqueue(new SearchData(current.worldData.left, current.xoffset - 1, current.yoffset));
                visited.Add(current.worldData.left);
            }
            if (current.worldData.right != null && !visited.Contains(current.worldData.right) && (current.worldData.right.state & GameManager.SensorData.Clear) != 0)
            {
                frontier.Enqueue(new SearchData(current.worldData.right, current.xoffset + 1, current.yoffset));
                visited.Add(current.worldData.right);
            }

            // Find the node with the given offset from the initial world node
            if (current.xoffset == aXOffset && current.yoffset == aYOffset)
            {
                return(current.worldData);
            }
        }

        // Check if this is an edge of the world
        if (aXOffset == rightEdgeOffset || aXOffset == leftEdgeOffset || aYOffset == topEdgeOffset || aYOffset == bottomEdgeOffset)
        {
            WorldData newEdge = new WorldData();
            newEdge.state = GameManager.SensorData.OffGrid;
            //Debug.Log("Adding assumed edge at " + aXOffset + " " + aYOffset + " " + rightEdgeOffset + " " + leftEdgeOffset + " " + topEdgeOffset + " " + bottomEdgeOffset);
            return(newEdge);
        }

        return(null);
    }
        public async Task <SearchData> Get(string searchText)
        {
            SearchData model = new SearchData
            {
                SearchText = searchText
            };

            await _searchProvider.QueryPagingFull(model, 0, 0).ConfigureAwait(false);

            return(model);
        }
Esempio n. 18
0
        /// <summary>
        ///     Wait for window starts with name.
        /// </summary>
        /// <param name="possibleStartsWithNames">beginning of the window name.</param>
        /// <returns>The IntPtr.</returns>
        public static IntPtr WaitForWindowStartsWith(string[] possibleStartsWithNames)
        {
            var sd = new SearchData {
                PossibleNames = possibleStartsWithNames
            };
            var waitForWindow = new Func <bool>(() => !EnumWindows(EnumTheWindows, sd));

            Waiter.SpinWaitEnsureSatisfied(waitForWindow, TimeSpan.FromSeconds(3), TimeSpan.FromMilliseconds(300),
                                           "No opened windows found with titles start with [" + string.Join(", ", possibleStartsWithNames) + "]");
            return(sd.HWnd);
        }
Esempio n. 19
0
 private void Timkiemmde()
 {
     try
     {
         dgv_DanhSach.DataSource = SearchData.Timkiemmade1(_idKyThi, txtmade.Text);
     }
     catch (Exception ex)
     {
         Log2File.LogExceptionToFile(ex);
     }
 }
Esempio n. 20
0
        public SearchUseCase(string s, string l)
        {
            data           = new SearchData();
            this.name      = s;
            this.location  = l;
            data.doctors   = new ObservableCollection <Doctor>();
            data.hospitals = new ObservableCollection <Hospital>();

            //doctors = new List<Doctor>();
            //hospitals = new List<Hospital>();
        }
Esempio n. 21
0
 public SearchMetricsContainer(string rawFile, DateTime dateAquired, MethodDataContainer methodData)
 {
     RawFile               = rawFile;
     Instrument            = methodData.Instrument;
     DateAcquired          = dateAquired;
     LabelingEfficiencyAtX = LabelingEfficiencyAtNTerm = LabelingEfficiencyAtK = -1;
     DigestionEfficiency   = IdentificationRate = MissedCleavageRate = -1;
     ChargeRatio3to2       = ChargeRatio4to2 = -1;
     MedianMassDrift       = -1;
     SearchData            = new SearchData();
 }
Esempio n. 22
0
 public SearchMetricsContainer(string rawFile, DateTime dateAquired, MethodDataContainer methodData)
 {
     RawFile               = rawFile;
     Instrument            = methodData.Instrument;
     DateAcquired          = dateAquired;
     DigestionEfficiency   = IdentificationRate = MissedCleavageRate = -1;
     ChargeRatio3to2       = ChargeRatio4to2 = -1;
     MedianMassDrift       = -1;
     SearchData            = new SearchData();
     ModificationFrequency = new SerializableDictionary <string, double>();
 }
Esempio n. 23
0
        public ViewResult Search()
        {
            var search = new SearchData(TempData);

            if (search.HasSearchTerm)
            {
                var vm = new SearchViewModel
                {
                    SearchTerm = search.SearchTerm
                };

                var options = new QueryOptions <Instrument>
                {
                    Includes = "Department, InstrumentBrands.Brand"
                };
                if (search.IsInstrument)
                {
                    options.Where = i => i.Name.Contains(vm.SearchTerm);
                    vm.Header     = $"Search results for instrument name '{vm.SearchTerm}'";
                }
                if (search.IsBrand)
                {
                    // if there's no space, search both first and last name by search term.
                    // Otherwise, assume there's a first and last name and refine search.
                    int index = vm.SearchTerm.LastIndexOf(' ');
                    if (index == -1)
                    {                                                           // no space
                        options.Where = ib => ib.InstrumentBrands.Any(
                            ib => ib.Brand.BrandName.Contains(vm.SearchTerm) || // OR
                            ib.Brand.ProductLine.Contains(vm.SearchTerm));
                    }
                    else
                    {                                                            // assume first and last name
                        string brandName   = vm.SearchTerm.Substring(0, index);
                        string productLine = vm.SearchTerm.Substring(index + 1); // skip space
                        options.Where = ib => ib.InstrumentBrands.Any(
                            ib => ib.Brand.BrandName.Contains(brandName) &&      // AND
                            ib.Brand.ProductLine.Contains(productLine));
                    }
                    vm.Header = $"Search results for brand '{vm.SearchTerm}'";
                }
                if (search.IsDepartment)
                {
                    options.Where = d => d.DepartmentId.Contains(vm.SearchTerm);
                    vm.Header     = $"Search results for department ID '{vm.SearchTerm}'";
                }
                vm.Instruments = data.Instruments.List(options);
                return(View("SearchResults", vm));
            }
            else
            {
                return(View("Index"));
            }
        }
Esempio n. 24
0
        public ActionResult Create([Bind(Include = "SearchDataId,Name,Location")] SearchData searchData)
        {
            if (ModelState.IsValid)
            {
                db.SearchDatas.Add(searchData);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(searchData));
        }
Esempio n. 25
0
        private static bool EnumChildWindowsCallback(IntPtr hWnd, ref SearchData data)
        {
            GetWindowInfo(hWnd, out string title, out string className);

            if ((string.IsNullOrEmpty(data.ClassName) || className == data.ClassName) && (string.IsNullOrEmpty(data.Title) || title == data.Title))
            {
                data.Results.Add(hWnd);
            }

            return(true);
        }
 private void cbothongke_SelectedIndexChanged(object sender, EventArgs e)
 {
     lbthongke.Text = "";
     if (cbothongke.SelectedIndex == 0)
     {
         LoadGrid();
         return;
     }
     dgv_DanhSach.DataSource = SearchData.Thongkediem(cbothongke.SelectedIndex, _idkythi);
     lbthongke.Text          = @"Có " + dgv_DanhSach.Rows.Count + @" Sinh viên có điểm " + cbothongke.Text;
 }
Esempio n. 27
0
        private void findusagestree_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
        {
            // Root node collapsing?
            SearchData data = e.Node.Tag as SearchData;

            if (data != null)
            {
                e.Node.ImageIndex         = General.Map.ScriptEditor.Editor.Icons.ScriptGroupIconsOffset;
                e.Node.SelectedImageIndex = e.Node.ImageIndex;
            }
        }
Esempio n. 28
0
 private static bool EnumProc(IntPtr hWnd, ref SearchData data)
 {
     var sb = new StringBuilder(1024);
     GetWindowText(hWnd, sb, sb.Capacity);
     if (sb.ToString().Contains(data.Title))
     {
     data.hWnd = hWnd;
     return false;    // Found the window
     }
     return true;
 }
Esempio n. 29
0
    public static float RouteStarCost(SearchData searchData, RoadData toEvaluate, int step)
    {
        if (toEvaluate == null || searchData.goal == null)//Car la route peut avoir été détruite, il faut donc vérifier!!
        {
            return(Single.PositiveInfinity);
        }

        return(Vector2.Distance(searchData.goal.transform.position, toEvaluate.transform.position)
               + step
               + 4 * Density(toEvaluate));
    }
        /// <summary>
        /// Initializes a new instance of the <see cref="FileEnumerator"/> class.
        /// </summary>
        /// <param name="path">The directory to search.</param>
        /// <param name="fileExtension">The file extension to search for.</param>
        /// <param name="searchOption">if set to <c>true</c> search the sub directories of <paramref name="path"/>.</param>
        /// <param name="dereferenceLinks">if set to <c>true</c> search the target of shortcuts.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="path"/> in null.
        /// -or-
        /// <paramref name="fileExtension"/> is null.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="searchOption"/> is not a valid <see cref="SearchOption"/> value.
        /// </exception>
        /// <exception cref="PathTooLongException">The specified path, file name, or combined exceed the system-defined maximum length.</exception>
        /// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
        public FileEnumerator(string path, string fileExtension, SearchOption searchOption, bool dereferenceLinks)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (fileExtension == null)
            {
                throw new ArgumentNullException(nameof(fileExtension));
            }
            if (searchOption < SearchOption.TopDirectoryOnly || searchOption > SearchOption.AllDirectories)
            {
                throw new ArgumentOutOfRangeException(nameof(searchOption));
            }

            string fullPath = Path.GetFullPath(path);
            string demandPath = GetPermissionPath(fullPath, false);
            new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPath).Demand();
            needPathDiscoveryDemand = false;

            searchData = new SearchData(fullPath, false);
            this.fileExtension = fileExtension;
            this.searchOption = searchOption;
            searchDirectories = new Queue<SearchData>();
            if (dereferenceLinks)
            {
                shellLink = new ShellLink();
                this.dereferenceLinks = true;
            }
            else
            {
                shellLink = null;
                this.dereferenceLinks = false;
            }
            shellLinkTarget = null;

            if (OS.IsWindows7OrLater)
            {
                // Suppress the querying of short filenames and use a larger buffer on Windows 7 and later.
                infoLevel = NativeEnums.FindExInfoLevel.Basic;
                additionalFlags = NativeEnums.FindExAdditionalFlags.LargeFetch;
            }
            else
            {
                infoLevel = NativeEnums.FindExInfoLevel.Standard;
                additionalFlags = NativeEnums.FindExAdditionalFlags.None;
            }
            oldErrorMode = SetErrorModeWrapper(NativeConstants.SEM_FAILCRITICALERRORS);
            state = -1;
            current = null;
            disposed = false;
            Init();
        }
Esempio n. 31
0
        public MetaData ReadMetaFromSearchData(SearchData data)
        {
            bool     local    = (bool)data.Fields.First(x => x.Item2 == "local").Item1;
            bool     isdelete = (bool)data.Fields.First(x => x.Item2 == "isdelete").Item1;
            DateTime time     = (DateTime)data.Fields.First(x => x.Item2 == "time").Item1;

            return(new MetaData(local, time, isdelete)
            {
                Id = data.Fields.First(x => x.Item2 == "").Item1
            });
        }
Esempio n. 32
0
    /**
     * Effectue une recherche d'itinéraire entre deux points du réseau routier.
     **/
    public static Stack <RoadData> RouteStar(RoadData goal, RoadData start, int keyPointsSpacing, string startOrientation)
    {
        if (goal == null)
        {
            return(null);
        }

        SearchData searchData = new SearchData(goal, start, keyPointsSpacing, startOrientation);

        return(AStar(searchData, -1, RouteStarNeighborhood, RouteStarCost, RouteStarRebuild, RouteStarGoal));
    }
 //
 public void SaveSearchData(SearchData searchData)
 {
     try
     {
         SearchRepo repo = new SearchRepo();
         repo.SaveSearchData(searchData);
     }catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 34
0
 public void BadRegex3()
 {
     var tss = MockObjectFactory.CreateTextSnapshot(42).Object;
     var nav = _factory.Create<ITextStructureNavigator>();
     _textSearch
         .Setup(x => x.FindNext(0, true, It.IsAny<FindData>()))
         .Throws(new InvalidOperationException())
         .Verifiable();
     var searchData = new SearchData(SearchText.NewStraightText("f("), SearchKind.ForwardWithWrap, SearchOptions.None);
     Assert.Throws<InvalidOperationException>(() => _search.FindNext(searchData, new SnapshotPoint(tss, 0), nav.Object));
     _factory.Verify();
 }
 // Save the facet text to temporary storage, optionally saving the state of the check boxes.
 private void SaveFacets(SearchData model, bool saveChecks = false)
 {
     for (int i = 0; i < model.facetText.Length; i++)
     {
         TempData["facet" + i.ToString()] = model.facetText[i];
         if (saveChecks)
         {
             TempData["faceton" + i.ToString()] = model.facetOn[i];
         }
     }
     TempData["facetcount"] = model.facetText.Length;
 }
Esempio n. 36
0
        public static IntPtr Find(int processId, string className)
        {
            SearchData sd = new SearchData
            {
                className = className,
                processId = (uint)processId,
                buffer = new StringBuilder(className == null ? 0 : className.Length)
            };

            EnumWindows(new EnumWindowsProc(EnumProc), ref sd);

            return sd.hWnd;
        }
 public void GetTags3()
 {
     Init(lines: "foo is the bar", lastSearch: "foo");
     var data = new SearchData(SearchText.NewPattern("foo"), SearchKind.Forward, SearchOptions.None);
     _search
         .Setup(x => x.FindNext(data, _textBuffer.GetPoint(0), _nav.Object))
         .Returns(FSharpOption.Create(new SnapshotSpan(_textBuffer.CurrentSnapshot, 0, 3)));
     _search
         .Setup(x => x.FindNext(data, _textBuffer.GetPoint(3), _nav.Object))
         .Returns(FSharpOption<SnapshotSpan>.None);
     var ret = _taggerRaw.GetTags(new NormalizedSnapshotSpanCollection(new SnapshotSpan(_textBuffer.CurrentSnapshot, 0, _textBuffer.CurrentSnapshot.Length)));
     Assert.AreEqual(1, ret.Count());
     Assert.AreEqual(new SnapshotSpan(_textBuffer.CurrentSnapshot, 0, 3), ret.Single().Span);
 }
Esempio n. 38
0
        private static bool EnumProcCaptionEquals(IntPtr hWnd, ref SearchData data)
        {
            uint procId;
            GetWindowThreadProcessId(hWnd, out procId);
            if (data.ParentId != (int) procId)
                return true;

            var sb = new StringBuilder(1024);
            GetWindowText(hWnd, sb, sb.Capacity);
            if (sb.ToString().Equals(data.SearchString))
            {
                data.Handle = hWnd;
                return false; // Found the wnd, halt enumeration
            }
            return true;
        }
        /// <summary>
        /// Aggiunge alla tabella le informazioni relative al messaggio ricevuto da un vicino (e possibile candidato
        /// per essere inoltrato, se non duplicato) oppure generato dallo stesso nodo e pronto per l'invio ai vicini,
        /// restituendo true se sono state aggiunte in modo corretto, altrimenti false se l'id del messaggio era già
        /// presente in tabella (duplicato).
        /// </summary>
        /// <param name="msgId">L'id del messaggio pronto per l'eventuale invio ai vicini.</param>
        /// <param name="connectionId">L'eventuale identificativo della connessione di provenienza del messaggio.</param>
        /// <param name="searchRef">L'eventuale riferimento ai dati di ricerca.</param>
        /// <returns>true se l'id del messaggio non è un duplicato; in caso contrario false.</returns>
        /// <remarks>
        /// Il riferimento ai dati di ricerca viene utilizzato soltanto dal nodo in cui inizia la ricerca, poiché
        /// consente di raccogliere i risultati via via in arrivo dai vicini, pertanto è necessario impostarlo se
        /// la ricerca inizia nel nodo corrente, altrimenti deve essere impostato a null.
        /// </remarks>
        public bool Add(Guid msgId, string connectionId, SearchData searchRef)
        {
            if (!ContainsEntry(msgId))
            {
                m_InternalTable.Add(msgId, new Entry
                {
                    SourceConnection = connectionId,
                    SearchReference = searchRef,
                    InsertionTime = DateTime.Now
                });

                return true;
            }

            return false; // duplicato
        }
Esempio n. 40
0
 public static bool EnumProc(IntPtr hWnd, ref SearchData data)
 {
     // Check classname and title
     // This is different from FindWindow() in that the code below allows partial matches
     StringBuilder sb = new StringBuilder(1024);
     GetClassName(hWnd, sb, sb.Capacity);
     if (sb.ToString().StartsWith(data.Wndclass))
     {
         sb = new StringBuilder(1024);
         GetWindowText(hWnd, sb, sb.Capacity);
         if (sb.ToString().StartsWith(data.Title))
         {
             data.hWnd = hWnd;
             return false;    // Found the wnd, halt enumeration
         }
     }
     return true;
 }
        /// <summary>
        /// Questo metodo permette di interrogare un nodo di ricerca e di avviare eventualmente una nuova ricerca.
        /// Prima verifica se il nodo di ricerca interrogato possiede una o più risorse compatibili con le opzioni
        /// specificate ed eventualmente le aggiunge ai risultati da inviare al client. Successivamente, controlla
        /// se la cache del gestore delle ricerche contiene uno o più risultati relativi ad una ricerca uguale, ma
        /// non ancora scaduta, ed eventualmente aggiunge anche questi ai risultati da inviare al client. Nel caso
        /// in cui la cache del gestore delle ricerche non dovesse contenere nessun risultato che corrisponde alle
        /// opzioni specificate, inizia una nuova ricerca attraverso la rete dei nodi di ricerca, ma nel frattempo
        /// restituisce al client i risultati disponibili oppure una lista vuota.
        /// </summary>
        /// <param name="options">Le opzioni di ricerca specificate dal client.</param>
        /// <param name="addresses">Gli eventuali indirizzi che corrispondono alle opzioni di ricerca.</param>
        public void Search(SearchOptions options, out List<Uri> addresses)
        {
            WriteToLog("Search options: <{0}-{1}>", options.Name, options.Version);

            // Trova eventuali risorse disponibili in questo nodo di ricerca.
            List<Uri> found = m_ResourceCache.Search(
                delegate(Uri uri, IEnumerable<TaskPerformerInfo> resources)
                {
                    foreach (var resource in resources)
                    {
                        if (resource.Name == options.Name && resource.Version == options.Version)
                        {
                            return true;
                        }
                    }
                    return false;
                }
            ).ToList<Uri>();

            // Trova eventuali risorse disponibili in altri nodi di ricerca.
            SearchData data = new SearchData(options);
            SearchResult result;
            if (!m_SearchManager.TryEnqueueNewSearch(data, out result))
            {
                found.AddRange(result.FoundServices);   // ricerca già presente --> recupera risultati correnti
            }
            else
            {
                WriteToLog("Starting new search...");

                if (m_CommunicationHandler.CreateNewSearch(data))
                {
                    WriteToLog("New search started.");
                }
                else
                {
                    WriteToLog("Error starting new search.");

                    m_SearchManager.Remove(data);   // rollback
                }
            }

            addresses = found.ToHashSet<Uri>().ToList<Uri>();
        }
Esempio n. 42
0
        public static bool EnumProc(IntPtr hWnd, ref SearchData data)
        {
            uint processId;
            GetWindowThreadProcessId(hWnd, out processId);

            if (processId == data.processId)
            {
                data.buffer.Length = 0;
                GetClassName(hWnd, data.buffer, data.buffer.Capacity + 1);

                if (data.className == null || data.buffer.ToString().Equals(data.className))
                {
                    data.hWnd = hWnd;
                    return false;
                }
            }

            return true;
        }
    public static Rhino.Commands.Result RTreeClosestPoint(RhinoDoc doc)
    {
        Rhino.DocObjects.ObjRef objref;
        var rc = Rhino.Input.RhinoGet.GetOneObject("select mesh", false, Rhino.DocObjects.ObjectType.Mesh, out objref);
        if (rc != Rhino.Commands.Result.Success)
          return rc;

        Mesh mesh = objref.Mesh();
        objref.Object().Select(false);
        doc.Views.Redraw();

        using (RTree tree = new RTree())
        {
          for (int i = 0; i < mesh.Vertices.Count; i++)
          {
        // we can make a C++ function that just builds an rtree from the
        // vertices in one quick shot, but for now...
        tree.Insert(mesh.Vertices[i], i);
          }

          while (true)
          {
        Point3d point;
        rc = Rhino.Input.RhinoGet.GetPoint("test point", false, out point);
        if (rc != Rhino.Commands.Result.Success)
          break;

        SearchData data = new SearchData(mesh, point);
        // Use the first vertex in the mesh to define a start sphere
        double distance = point.DistanceTo(mesh.Vertices[0]);
        Sphere sphere = new Sphere(point, distance * 1.1);
        if (tree.Search(sphere, SearchCallback, data))
        {
          doc.Objects.AddPoint(mesh.Vertices[data.Index]);
          doc.Views.Redraw();
          RhinoApp.WriteLine("Found point in {0} tests", data.HitCount);
        }
          }
        }
        return Rhino.Commands.Result.Success;
    }
Esempio n. 44
0
 public void FindNextMulitple5()
 {
     var tss = MockObjectFactory.CreateTextSnapshot(42).Object;
     var nav = _factory.Create<ITextStructureNavigator>();
     var data = new FindData("foo", tss, FindOptions.UseRegularExpressions | FindOptions.MatchCase, nav.Object);
     _textSearch
         .Setup(x => x.FindNext(10, true, data))
         .Returns(new SnapshotSpan(tss, 0, 3))
         .Verifiable();
     _textSearch
         .Setup(x => x.FindNext(3, true, data))
         .Returns(new SnapshotSpan(tss, 10, 3))
         .Verifiable();
     var searchData = new SearchData(SearchText.NewPattern("foo"), SearchKind.ForwardWithWrap, SearchOptions.None);
     var ret = _search.FindNextMultiple(searchData, new SnapshotPoint(tss, 10), nav.Object, 2);
     Assert.IsTrue(ret.IsSome());
     Assert.AreEqual(new SnapshotSpan(tss, 10, 3), ret.Value);
     _factory.Verify();
 }
Esempio n. 45
0
 public void FindNext3()
 {
     _settings.SetupGet(x => x.IgnoreCase).Returns(true).Verifiable();
     var data = new SearchData(SearchText.NewPattern("foo"), SearchKind.Forward, SearchOptions.None);
     AssertFindNext(data, "foo", FindOptions.MatchCase | FindOptions.UseRegularExpressions);
 }
Esempio n. 46
0
 public void MoveToNextOccuranceOfWordAtCursor9()
 {
     Create("  foo bar baz");
     var data = new SearchData(SearchText.NewPattern("foo"), SearchKind.ForwardWithWrap, SearchOptions.None);
     _vimData.LastSearchData = data;
     _statusUtil.Setup(x => x.OnError(Resources.NormalMode_NoWordUnderCursor)).Verifiable();
     _operations.MoveToNextOccuranceOfWordAtCursor(SearchKind.ForwardWithWrap, 1);
     _statusUtil.Verify();
     Assert.AreEqual(data, _vimData.LastSearchData);
 }
Esempio n. 47
0
 public void MoveToNextOccuranceOfLastSearch5()
 {
     Create("foo bar", "foo");
     var data = new SearchData(SearchText.NewPattern("foo"), SearchKind.BackwardWithWrap, SearchOptions.None);
     AllowOutlineExpansion(verify: true);
     _vimData.LastSearchData = data;
     _operations.MoveToNextOccuranceOfLastSearch(1, false);
     Assert.AreEqual(_textView.GetLine(1).Start, _textView.GetCaretPoint());
     _outlining.Verify();
 }
Esempio n. 48
0
 public void MoveToNextOccuranceOfLastSearch3()
 {
     Create("foo bar", "foo");
     AllowOutlineExpansion();
     var data = new SearchData(SearchText.NewPattern("foo"), SearchKind.ForwardWithWrap, SearchOptions.None);
     _vimData.LastSearchData = data;
     _operations.MoveToNextOccuranceOfLastSearch(2, false);
     Assert.AreEqual(0, _textView.GetCaretPoint());
 }
Esempio n. 49
0
 public void MoveToNextOccuranceOfLastSearch1()
 {
     Create("foo bar baz");
     var data = new SearchData(SearchText.NewPattern("beat"), SearchKind.ForwardWithWrap, SearchOptions.None);
     _vimData.LastSearchData = data;
     _statusUtil.Setup(x => x.OnError(Resources.Common_PatternNotFound("beat"))).Verifiable();
     _operations.MoveToNextOccuranceOfLastSearch(1, false);
     _statusUtil.Verify();
 }
Esempio n. 50
0
 public static IntPtr SearchForWindow(string wndclass, string title)
 {
     SearchData sd = new SearchData { Wndclass = wndclass, Title = title };
     EnumWindows(new EnumWindowsProc(EnumProc), ref sd);
     return sd.hWnd;
 }
Esempio n. 51
0
 public void RunSearch_NeedMoreUntilEndKey()
 {
     Create("foo bar");
     var data = new SearchData("b", SearchKind.ForwardWithWrap, s_options);
     Assert.IsTrue(_search.Begin(Path.Forward).Run("b").IsNeedMoreInput);
 }
Esempio n. 52
0
		public virtual List<InventoryItem> FindItemsInList(IList<InventoryItem> inventoryItems, SearchData search)
		{
			List<InventoryItem> items = new List<InventoryItem>();

			int count = 0;
			m_searchHasError = false;

			if (ServerProperties.Properties.MARKET_ENABLE_LOG && search.page == 0)
			{
				log.DebugFormat("MarketSearch: [{0}:{1}] SEARCHING MARKET: {2}", m_searchPlayer.Name, m_searchPlayer.Client.Account.Name, search);
			}

			foreach (InventoryItem item in inventoryItems)
			{
				// Error checking

				if (m_searchHasError)
					break;

				if (item.IsTradable == false)
					continue;

				if (item.SellPrice < 1)
					continue;

				if (item.OwnerLot == 0)
					continue;

				// search criteria

				if (search.name != "" && item.Name.ToLower().Contains(search.name.ToLower()) == false)
					continue;

				if (search.levelMin > 1 && item.Level < search.levelMin)
					continue;

				if (search.levelMax > -1 && search.levelMax < 52 && item.Level > search.levelMax)
					continue;

				if (search.qtyMin > 84 && item.Quality < search.qtyMin)
					continue;

				if (search.qtyMax < 100 && item.Quality > search.qtyMax)
					continue;

				if (search.priceMin > 1 && item.SellPrice < search.priceMin)
					continue;

				if (search.priceMax > 0 && item.SellPrice > search.priceMax)
					continue;

				if (search.visual > 0 && item.Effect == 0)
					continue;

				if (search.playerCrafted > 0 && item.IsCrafted == false)
					continue;

				if (search.proc > 0 && item.ProcSpellID == 0 && item.ProcSpellID1 == 0)
					continue;

				if (CheckSlot(item, search.slot) == false)
					continue;

				if (search.armorType > 0 && CheckForArmorType(item, search.armorType) == false)
					continue;

				if (search.hp > 0 && CheckForHP(item, search.hp) == false)
					continue;

				if (search.power > 0 && CheckForPower(item, search.power) == false)
					continue;

				if (search.bonus >= 0 && CheckForBonus(item, search.bonus) == false)
					continue;

				if (search.skill >= 0 && CheckForSkill(item, search.skill) == false)
					continue;

				if (search.resist >= 0 && CheckForResist(item, search.resist) == false)
					continue;

				if (search.damageType > 0 && CheckForDamageType(item, search.damageType) == false)
					continue;

				items.Add(item);

				if (++count >= ServerProperties.Properties.MARKET_SEARCH_LIMIT)
					break;
			}

			return items;
		}
Esempio n. 53
0
 private Span ApplySearchOffsetData(SnapshotSpan span, SearchOffsetData searchOffsetData)
 {
     var searchData = new SearchData("", searchOffsetData, SearchKind.Forward, SearchOptions.None);
     var serviceSearchData = _searchRaw.GetServiceSearchData(searchData, _wordNavigator);
     return _searchRaw.ApplySearchOffsetData(serviceSearchData, span).Value;
 }
Esempio n. 54
0
 private SearchResult FindNextPattern(string pattern, SearchPath path, SnapshotPoint point, int count)
 {
     var searchData = new SearchData(pattern, path, _globalSettings.WrapScan);
     return _search.FindNextPattern(point, searchData, _wordNavigator, count);
 }
Esempio n. 55
0
 private void AssertFindNext(
     SearchData data,
     string searchText,
     FindOptions options)
 {
     var isWrap = SearchKindUtil.IsWrap(data.Kind);
     var snapshot = MockObjectFactory.CreateTextSnapshot(10);
     var nav = _factory.Create<ITextStructureNavigator>();
     var findData = new FindData(searchText, snapshot.Object, options, nav.Object);
     _textSearch
         .Setup(x => x.FindNext(2, isWrap, findData))
         .Returns<SnapshotSpan?>(null)
         .Verifiable();
     _search.FindNext(data, new SnapshotPoint(snapshot.Object, 2), nav.Object);
     _factory.Verify();
 }
        private void SimulateSearch(string pattern, SearchKind searchKind = null, SearchOptions searchOptions = SearchOptions.None)
        {
            searchKind = searchKind ?? SearchKind.Forward;

            var data = new SearchData(pattern, searchKind, searchOptions);
            _search.SetupGet(x => x.InSearch).Returns(true).Verifiable();
            _search.SetupGet(x => x.CurrentSearchData).Returns(FSharpOption.Create(data)).Verifiable();
        }
Esempio n. 57
0
 public void FindNext2()
 {
     var data = new SearchData(SearchText.NewPattern("foo"), SearchKind.Forward, SearchOptions.None);
     AssertFindNext(data, FindOptions.MatchCase | FindOptions.UseRegularExpressions);
 }
Esempio n. 58
0
 private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, ref SearchData data);
 public void Search2()
 {
     var mode = _factory.Create<INormalMode>();
     _buffer.NormalModeImpl = mode.Object;
     _buffer.ModeKindImpl = ModeKind.Normal;
     var data = new SearchData("cat", SearchKind.Backward, SearchOptions.None);
     _search.SetupGet(x => x.InSearch).Returns(true).Verifiable();
     _search.SetupGet(x => x.CurrentSearchData).Returns(FSharpOption.Create(data)).Verifiable();
     SimulatKeystroke();
     Assert.AreEqual("?cat", _marginControl.StatusLine);
     _factory.Verify();
 }
Esempio n. 60
0
		/// <summary>
		/// Waits for a dialog and clicks the button specified.
		/// Use Spy++ to find the captions of the button's you want to click. Note that some buttons include an accelerator & which should be included.
		/// </summary>
		/// <param name="dialogCaption">The caption of the dialog on which the button exists</param>
		/// <param name="buttonCaption">The caption of the button (including any accelerator keys)</param>
		/// <param name="timeout">length of time to wait before we time out</param>
		/// <returns>True if the button was clicked, false otherwise</returns>
		protected bool WaitForDialogAndClickButton (CancellationToken token, string dialogCaption, string buttonCaption = null, int timeout = 30, string className = null)
		{
			var ts = new TimeSpan (0, 0, timeout);
			var dispatcher = System.Windows.Application.Current.Dispatcher;
			var start = DateTime.Now;
			var sw = new Stopwatch ();
			sw.Start ();
			try {
				// we want to keep looping until we find the window and button we are after or
				// the timeout exxpires
				while (true) {
					SearchData sd = new SearchData { Wndclass = className, Title = dialogCaption, ButtonCaption = buttonCaption };
					EnumWindows (new EnumWindowsProc (EnumProc), ref sd);
					IntPtr window = sd.hWnd;
					if (window != IntPtr.Zero) {
						IntPtr button = IntPtr.Zero;
						if (!string.IsNullOrEmpty(buttonCaption)) {
							button = FindWindowEx (window, IntPtr.Zero, "Button", buttonCaption); 
							if (button != IntPtr.Zero) {
								SendMessage (button, WM_LBUTTONDOWN, 0, 0);
								SendMessage (button, WM_LBUTTONUP, 0, 0);
								SendMessage (button, BM_SETSTATE, 1, 0);
								return true;
							}
						} else {
							SendMessage (window, WM_CLOSE, 0, 0);
							return true;
						}

					}
					System.Threading.Thread.Sleep (10);
					if (sw.ElapsedMilliseconds > ts.TotalMilliseconds || token.IsCancellationRequested) {
						break;
					}
				}
				return false;
			} finally {
				sw.Stop ();
			}
		}