예제 #1
0
 public DependencyParameter(Type parameterType, string name, Type createType, NotPresentBehavior notPresentBehavior, SearchMode searchMode) : base(parameterType)
 {
     this.name = name;
     this.createType = createType;
     this.notPresentBehavior = notPresentBehavior;
     this.searchMode = searchMode;
 }
예제 #2
0
        public SearchForm(ConsoleNode console, SearchMode mode)
        {
            InitializeComponent();

            //fill the data
            SetData(console, mode);
        }
예제 #3
0
        public IEnumerable<StudentViewModel> GetStudents(string name, SearchMode searchMode)
        {
            IEnumerable<Domain.Student> students;
            if (String.IsNullOrWhiteSpace(name))
            {
                students = _session.Query<Domain.Student>().ToList();
            }
            else
            {
                switch (searchMode)
                {
                    case SearchMode.BeginsWith:
                        students = _session.Advanced.LuceneQuery<Domain.Student>()
                                        .WhereStartsWith("FirstName", name).Boost(3)
                                        .WhereStartsWith("LastName", name)
                                        .ToList();
                        break;
                    case SearchMode.Contains:
                        students = _session.Advanced.LuceneQuery<Domain.Student>()
                                            .Where(String.Format("FirstName:*{0}*", name)).Boost(3)
                                            .Where(String.Format("LastName:*{0}*", name))
                                            .ToList();

                        break;
                    default:
                        students = _session.Query<Domain.Student>().ToList();
                        break;
                }
            }
            return Mapper.Map<IEnumerable<Domain.Student>, IEnumerable<StudentViewModel>>(students);
        }
예제 #4
0
파일: Program.cs 프로젝트: NikitaVas/CSharp
        static void ParseCommand_1(string[] args, SearchMode ch)
        {
            switch (ch)
            {
                case SearchMode.a:
                    break;
                case SearchMode.nm:
                    if (args.Length < 4)
                        throw new ArgumentException("Некорректная команда! Отсутствует <аргумент_3>.");
                    break;
                case SearchMode.sz:
                    {
                        long size;
                        if (!Int64.TryParse(args[3], out size))
                            throw new ArgumentException("Некорректная команда! Проверьте <аргумент_3>.");
                        break;
                    }
                case SearchMode.crt:
                case SearchMode.lat:
                case SearchMode.lwt:
                    {
                        DateTime date;
                        if (!DateTime.TryParse(args[3], out date))
                            throw new ArgumentException("Некорректная команда! Проверьте <аргумент_3>.");
                        break;
                    }
                case SearchMode.ctn:
                    if (args.Length < 4)
                        throw new ArgumentException("Некорректная команда! Отсутствует <аргумент_3>.");
                    word_to_change = args[3];
                    break;
            }


        }
        /// <summary>
        /// Resolves a dependency.
        /// </summary>
        /// <param name="typeToResolve">The type to be resolved.</param>
        /// <param name="typeToCreate">The type to be created, if the type cannot be resolved
        /// (and notPresent is set to <see cref="NotPresentBehavior.CreateNew"/>).</param>
        /// <param name="id">The ID of the object to be resolved. Pass null for the unnamed object.</param>
        /// <param name="notPresent">Flag to describe how to behave if the dependency is not found.</param>
        /// <param name="searchMode">Flag to describe whether searches are local only, or local and up.</param>
        /// <returns>The dependent object. If the object is not found, and notPresent
        /// is set to <see cref="NotPresentBehavior.ReturnNull"/>, will return null.</returns>
        public object Resolve(Type typeToResolve, Type typeToCreate, string id, NotPresentBehavior notPresent, SearchMode searchMode)
        {
            if (typeToResolve == null)
                throw new ArgumentNullException("typeToResolve");
            if (!Enum.IsDefined(typeof(NotPresentBehavior), notPresent))
                throw new ArgumentException(Properties.Resources.InvalidEnumerationValue, "notPresent");

            if (typeToCreate == null)
                typeToCreate = typeToResolve;

            DependencyResolutionLocatorKey key = new DependencyResolutionLocatorKey(typeToResolve, id);

            if (context.Locator.Contains(key, searchMode))
                return context.Locator.Get(key, searchMode);

            switch (notPresent)
            {
                case NotPresentBehavior.CreateNew:
                    return context.HeadOfChain.BuildUp(context, typeToCreate, null, key.ID);

                case NotPresentBehavior.ReturnNull:
                    return null;

                default:
                    throw new DependencyMissingException(
                        string.Format(CultureInfo.CurrentCulture,
                        Properties.Resources.DependencyMissing, typeToResolve.ToString()));
            }
        }
        /// <summary>
        /// Creates a default ISearchStrategy with the given parameters.
        /// </summary>
        public static ISearchStrategy Create(string searchPattern, bool ignoreCase, bool matchWholeWords, SearchMode mode)
        {
            if (searchPattern == null)
                throw new ArgumentNullException("searchPattern");
            RegexOptions options = RegexOptions.Compiled | RegexOptions.Multiline;
            if (ignoreCase)
                options |= RegexOptions.IgnoreCase;

            switch (mode) {
                case SearchMode.Normal:
                    searchPattern = Regex.Escape(searchPattern);
                    break;
                case SearchMode.Wildcard:
                    searchPattern = ConvertWildcardsToRegex(searchPattern);
                    break;
            }

            if (matchWholeWords)
                searchPattern = "\\b" + searchPattern + "\\b";
            try {
                Regex pattern = new Regex(searchPattern, options);
                return new RegexSearchStrategy(pattern);
            } catch (ArgumentException ex) {
                throw new SearchPatternException(ex.Message, ex);
            }
        }
        public TrackingPointGetter(string prompt, CurvesTopology crvTopology, int fromIndex, SearchMode mode)
        {
            _crvTopology = crvTopology;
            _fromIndex = fromIndex;

            if(!Enum.IsDefined(typeof(SearchMode), mode))
                throw new ArgumentException("Enum is undefined.", "mode");
            _sm = mode;

            if (!string.IsNullOrEmpty(prompt))
                _getPoint.SetCommandPrompt(prompt);

            if (fromIndex != -1)
            {
                switch(mode)
                {
                    case SearchMode.CurveLength:
                        _distances = crvTopology.MeasureAllEdgeLengths();
                        break;
                    case SearchMode.LinearDistance:
                        _distances = crvTopology.MeasureAllEdgeLinearDistances();
                        break;
                    case SearchMode.Links:
                        _distances = null;
                        break;
                    default:
                        throw new ApplicationException("Behaviour for this enum value is undefined.");
                }
            }
            _getPoint.DynamicDraw += DynamicDraw;

            _pathSearchMethod = PathMethod.FromMode(_sm, _crvTopology, _distances);
        }
예제 #8
0
        public override object Run(WorkFlowContext context, SearchMode mode, WorkFlow.Visitors.IVisitor visitor = null)
        {
            if (visitor == null)
                visitor = new DefaultVisitor();

            Queue<string> fila = new Queue<string>();
            List<string> mark = new List<string>();

            fila.Enqueue(context.SourceState);
            mark.Add(context.SourceState);

            while (fila.Count != 0)
            {
                string statusfila = fila.Dequeue();
                context.SourceState = statusfila;
                foreach (var item in this.GetActivities(context).OrderBy(x => x.Operation))
                {
                    context.Operation = item.Operation;
                    string newstatus = this.GetNextStatus(context);
                    visitor.Visit(statusfila, new Activity { Operation = item.Operation, Description = item.Description }, newstatus);

                    if (!mark.Contains(newstatus))
                    {
                        fila.Enqueue(newstatus);
                        mark.Add(newstatus);
                    }
                }
            }

            return visitor.EndVisit();
        }
예제 #9
0
        private TopDocs topDocs; //搜索到的doc。

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Search构造函数
        /// </summary>
        /// <param name="_form">主窗</param>
        /// <param name="_mode">搜索模式</param>
        public Search(FileFinder _form, SearchMode _mode)
        {
            //修改maxCluseCount是为了用PrefixQuery时没有数量的限制,
            //PrefixQuery会将找到的数据用TermQuery,然后用booleanQuery.add()方法。
            BooleanQuery.SetMaxClauseCount(int.MaxValue);

            this.oldBoolQuery = new BooleanQuery();
            this.form = _form;
            this.SetSearcher(_mode);
        }
예제 #10
0
        public SearchForm(ConsoleNode console, SearchMode mode)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //fill the data
            SetData(console, mode);
        }
예제 #11
0
    /// <summary>
    /// Creates a default ISearchStrategy with the given parameters.
    /// </summary>
    public static ISearchStrategy Create(string searchPattern, bool ignoreCase, bool matchWholeWords, SearchMode mode)
    {
      if (searchPattern == null)
      {
        throw new ArgumentNullException("searchPattern");
      }

      var regexOptions = RegexOptions.Compiled;
      if ((mode == SearchMode.Extended || mode == SearchMode.RegEx)
        && (searchPattern.IndexOf("\\r") > 0 || searchPattern.IndexOf("\\n") > 0))
      {
        // Don't change the Regex mode
      }
      else
      {
        regexOptions |= RegexOptions.Multiline;
      }

      if (ignoreCase)
      {
        regexOptions |= RegexOptions.IgnoreCase;
      }

      switch (mode)
      {
        case SearchMode.Normal:
          searchPattern = Regex.Escape(searchPattern);
          break;
        case SearchMode.Extended:
          try
          {
            searchPattern = Regex.Escape(StringHelper.StringFromCSharpLiteral(searchPattern));
          }
          catch (ArgumentException ex)
          {
            throw new SearchPatternException(ex.Message, ex);
          }
          break;
        case SearchMode.Wildcard:
          searchPattern = ConvertWildcardsToRegex(searchPattern);
          break;
        case SearchMode.XPath:
          return new XPathSearchStrategy(searchPattern);
      }

      try
      {
        var searchPattern2 = new Regex(searchPattern, regexOptions);
        return new RegexSearchStrategy(searchPattern2, matchWholeWords);
      }
      catch (ArgumentException ex)
      {
        throw new SearchPatternException(ex.Message, ex);
      }
    }
예제 #12
0
 //*********************************************************     
 //
 /// <summary>
 /// Minimum/maximum depth first search
 /// </summary>
 /// <param name="chessBoard">       Chess board</param>
 /// <param name="searchMode">       Search mode</param>
 /// <param name="ePlayerColor">     Color doing the move</param>
 /// <param name="iDepth">           Actual search depth</param>
 /// <param name="iWhiteMoveCount">  Number of moves white can do</param>
 /// <param name="iBlackMoveCount">  Number of moves black can do</param>
 /// <param name="iPermCount">       Total permutation evaluated</param>
 /// <returns>
 /// Points to give for this move
 /// </returns>
 //  
 //*********************************************************     
 private int MinMax(ChessBoard chessBoard, SearchMode searchMode, ChessBoard.PlayerColorE ePlayerColor, int iDepth, int iWhiteMoveCount, int iBlackMoveCount, ref int iPermCount) {
     int                         iRetVal;
     int                         iMoveCount;
     int                         iPts;
     List<ChessBoard.MovePosS>   moveList;
     ChessBoard.RepeatResultE    eResult;
     
     if (chessBoard.IsEnoughPieceForCheckMate()) {
         if (iDepth == 0 || m_bCancelSearch) {
             iRetVal = (ePlayerColor == ChessBoard.PlayerColorE.Black) ? -chessBoard.Points(searchMode, ePlayerColor, iWhiteMoveCount - iBlackMoveCount, 0, 0) :
                                                                          chessBoard.Points(searchMode, ePlayerColor, iWhiteMoveCount - iBlackMoveCount, 0, 0);
             iPermCount++;
         } else {
             moveList    = chessBoard.EnumMoveList(ePlayerColor);
             iMoveCount  = moveList.Count;
             if (ePlayerColor == ChessBoard.PlayerColorE.White) {
                 iWhiteMoveCount = iMoveCount;
             } else {
                 iBlackMoveCount = iMoveCount;
             }
             if (iMoveCount == 0) {
                 if (chessBoard.IsCheck(ePlayerColor)) {
                     iRetVal = -1000000 - iDepth;
                 } else {
                     iRetVal = 0; // Draw
                 }
             } else {
                 iRetVal  = Int32.MinValue;
                 foreach (ChessBoard.MovePosS move in moveList) {
                     eResult = chessBoard.DoMoveNoLog(move);
                     if (eResult == ChessBoard.RepeatResultE.NoRepeat) {
                         iPts = -MinMax(chessBoard,
                                        searchMode,
                                        (ePlayerColor == ChessBoard.PlayerColorE.Black) ? ChessBoard.PlayerColorE.White : ChessBoard.PlayerColorE.Black,
                                        iDepth - 1,
                                        iWhiteMoveCount,
                                        iBlackMoveCount,
                                        ref iPermCount);
                     } else {
                         iPts = 0;
                     }
                     chessBoard.UndoMoveNoLog(move);
                     if (iPts > iRetVal) {
                         iRetVal = iPts;
                     }
                 }
             }
         }
     } else {
         iRetVal = 0;
     }
     return(iRetVal);
 }
예제 #13
0
            public static List<String> calculateListOfMethodsFromFiles(List<String> sFileList, SearchMode smSearchMode,
                                                                       bool bOnlyAddFunctionsWithNoCustomRule)
            {
                bool bVerbose = false;
                var lsResolvedMethodsSignature = new List<string>();
                var lmiMethodsToResolve = new List<MethodInfo>();
                foreach (string sFile in sFileList)
                {
                    switch (smSearchMode)
                    {
                        case SearchMode.PublicMethods:
                            calculateListWithPublicMethods(sFile, lmiMethodsToResolve);
                            break;
                        case SearchMode.WebMethods:
                            calculateListWithWebMethods(sFile, lmiMethodsToResolve);
                            break;
                    }
                }

                foreach (MethodInfo miMethodInfo in lmiMethodsToResolve)
                {
                    String sMethodSignature = OunceLabsScannerHacks.fixDotNetSignature(miMethodInfo);
                    // DC adding all methods (for the reason below)
                    lsResolvedMethodsSignature.Add(sMethodSignature);


                    // DC removing the code below since queries to the DB are now taking a long time:
                    // For example: Select vuln_id, 'signature', 'signature' from rec where signature = 'HacmeBank_v2_WS.WS_UserManagement.Login(string;string):string';
                    // [2:03 AM] DEBUG: sql query:  in 2s:218     
                    // [2:03 AM] DEBUG: sql query:  in 2s:0
                    // [2:03 AM] DEBUG: sql query:  in 1s:968
                    // [2:03 AM] DEBUG: sql query:  in 1s:875
                    // [2:03 AM] DEBUG: sql query:  in 1s:843
                    // [2:03 AM] DEBUG: sql query:  in 1s:921
                    // [2:03 AM] DEBUG: sql query:  in 1s:937
                    // [2:03 AM] DEBUG: sql query:  in 1s:937
                    // [2:03 AM] DEBUG: sql query:  in 1s:921
                    /*
                    if (false == bOnlyAddFunctionsWithNoCustomRule)                  // check if we want the full list of possible webmethods or only the list of methods that don't have a custom rule
                        lsResolvedMethodsSignature.Add(sMethodSignature);

                    else if (sMethodSignature.IndexOf("()") == -1)                   // remove methods with no parameters
                        if (0 == Lddb_OunceV6.action_getVulnIdThatMatchesSignature("", sMethodSignature, false))
                            lsResolvedMethodsSignature.Add(sMethodSignature);
                        else
                            if (bVerbose)
                                 DI.log.info("Method {0} is already marked as a callback", sMethodSignature);
                     */
                }
                return lsResolvedMethodsSignature;
            }
예제 #14
0
 private void SetData(ConsoleNode console, SearchMode mode)
 {
     try
     {
         lvMembers.Items.Clear();
         if (mode == SearchMode.User)
         {
             lbMembers.Text = "&Users:";
             this.Text = "Users";
             UserStorageView[] users = console.Manager.Admon_GetUserList(console.Credentials);
             foreach (UserStorageView user in users)
             {
                 UserItem ui = new UserItem(user.Username);
                 ui.ImageIndex = 3;
                 ui.User = user;
                 lvMembers.Items.Add(ui);
             }
         }
         else if (mode == SearchMode.Group)
         {
             lbMembers.Text = "&Groups:";
             this.Text = "Groups";
             GroupStorageView[] groups = console.Manager.Admon_GetGroups(console.Credentials);
             foreach (GroupStorageView group in groups)
             {
                 GroupItem gi = new GroupItem(group.GroupName);
                 gi.ImageIndex = 2;
                 gi.GroupView = group;
                 lvMembers.Items.Add(gi);
             }
         }
         else if (mode == SearchMode.Permission)
         {
             lbMembers.Text = "&Permissions:";
             this.Text = "Permissions";
             PermissionStorageView[] permissions = console.Manager.Admon_GetPermissions(console.Credentials);
             foreach (PermissionStorageView permission in permissions)
             {
                 PermissionItem prm = new PermissionItem(permission.PermissionName);
                 prm.ImageIndex = 12;
                 prm.Permission = new PermissionStorageView(permission.PermissionId, permission.PermissionName);
                 lvMembers.Items.Add(prm);
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error filling search list:" + ex.Message, "Search Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
예제 #15
0
        /// <summary>
        /// See <see cref="IReadableLocator.Contains(object, SearchMode)"/> for more information.
        /// </summary>
        public override bool Contains(object key, SearchMode options)
        {
            if (key == null)
                throw new ArgumentNullException("key");
            if (!Enum.IsDefined(typeof(SearchMode), options))
                throw new ArgumentException(Properties.Resources.InvalidEnumerationValue, "options");

            if (references.ContainsKey(key))
                return true;

            if (options == SearchMode.Up && ParentLocator != null)
                return ParentLocator.Contains(key, options);

            return false;
        }
예제 #16
0
        public override object Run(WorkFlowContext context, SearchMode mode, IVisitor visitor = null)
        {
            if (visitor == null)
                visitor = new DefaultVisitor();

            if (mode == SearchMode.Depth)
            {
                RunInDepth(context, visitor);
            }
            else if (mode == SearchMode.Breadth)
            {
                RunInWidth(context, visitor);
            }

            return visitor.EndVisit();
        }
예제 #17
0
        private void buttonFind_Click(object sender, EventArgs e)
        {
            if (radioButtonByLength.Checked)
            {
                _SearchMode = SearchMode.ByLength;
            }
            else if (radioButtonByPos.Checked)
            {
                _SearchMode = SearchMode.ByPos;
            }
            else
            {
                _SearchMode = SearchMode.None;
            }

            Close();
        }
예제 #18
0
 Search CreateSearchObj(string pattern, SearchMode mode)
 {
     Search s = null;
     switch (mode) {
         case SearchMode.Text:
             s = new SearchText(pattern);
             //s.Pattern = pattern;
             break;
         case SearchMode.Regex:
             s = new SearchRegex(pattern);
             //s.Pattern = pattern;
             break;
         case SearchMode.Migemo:
             s = new SearchMigemo(getMigemo().Query(pattern));
             //s.Pattern = getMigemo().Query(pattern);
             break;
         default:
             break;
     }
     return s;
 }
예제 #19
0
		/// <summary>
		/// A Basic Amazon Search
		/// </summary>
		/// <param name="mode">The search mode to use</param>
		/// <param name="search">The search</param>
		/// <see cref="http://msdn.microsoft.com/coding4fun/web/services/article.aspx?articleid=912260"/>
		public string BasicSearch(SearchMode mode, string search)
		{
			System.Text.StringBuilder details = new StringBuilder("Search Results:\n\n");
		
			try
			{
				AmazonWebService.KeywordRequest request = new AmazonWebService.KeywordRequest();
				request.locale = "us";
				request.type = "lite";
				request.sort = "reviewrank";
				request.mode = mode.ToString();
				request.keyword = search;
				request.tag = accessKeyId;
				request.devtag = accessKeyId;
				
				AmazonWebService.AmazonSearchService searchService = new Alexandria.Amazon.AmazonWebService.AmazonSearchService();
				AmazonWebService.ProductInfo info = searchService.KeywordSearchRequest(request);
				foreach(AmazonWebService.Details detail in info.Details)
				{
					details.Append(detail.ProductName + " [ ASIN: " + detail.Asin);					
					if (!string.IsNullOrEmpty(detail.OurPrice))
						details.Append(" Amazon: " + detail.OurPrice);
					int usedCount;
					int.TryParse(detail.UsedCount, out usedCount);
					if (usedCount > 0 && !string.IsNullOrEmpty(detail.UsedPrice))
						details.Append(", Used: " + detail.UsedPrice);
					details.Append("]\n");
					
					System.Diagnostics.Debug.WriteLine("Product Name: " + detail.ProductName);
				}
				
				return details.ToString();
			}
			catch (Exception ex)
			{
				throw new AlexandriaException("The was an error attempting to search Amazon", ex);
			}
		}
        public void SelectSearchMode(SearchMode searchMode)
        {
            switch (searchMode)
            {
                case SearchMode.Attendee:
                    UIUtil.DefaultProvider.WaitForDisplayAndClick("ctl00_ctl00_cphDialog_uclSearch_lbSearchAttendees", LocateBy.Id);
                    break;
                case SearchMode.Event:
                    UIUtil.DefaultProvider.WaitForDisplayAndClick("ctl00_ctl00_cphDialog_uclSearch_lbSearchEvents", LocateBy.Id);
                    break;
                case SearchMode.Transaction:
                    UIUtil.DefaultProvider.WaitForDisplayAndClick("ctl00_ctl00_cphDialog_uclSearch_lbSearchTransactions", LocateBy.Id);
                    break;
                case SearchMode.Help:
                    UIUtil.DefaultProvider.WaitForDisplayAndClick("ctl00_ctl00_cphDialog_uclSearch_lbSearchHelp", LocateBy.Id);
                    break;
                default:
                    break;
            }

            UIUtil.DefaultProvider.WaitForAJAXRequest();
            UIUtil.DefaultProvider.WaitForPageToLoad();
        }
예제 #21
0
        internal static SearchFilter CreateFilter(string searchString, SearchMode searchMode)
        {
            SearchFilter filter = new SearchFilter();
            if (!string.IsNullOrEmpty(searchString))
            {
                switch (searchMode)
                {
                    case SearchMode.All:
                        if (!SearchUtility.ParseSearchString(searchString, filter))
                        {
                            filter.nameFilter = searchString;
                            filter.classNames = new string[] { searchString };
                            filter.assetLabels = new string[] { searchString };
                            filter.assetBundleNames = new string[] { searchString };
                            filter.showAllHits = true;
                        }
                        return filter;

                    case SearchMode.Name:
                        filter.nameFilter = searchString;
                        return filter;

                    case SearchMode.Type:
                        filter.classNames = new string[] { searchString };
                        return filter;

                    case SearchMode.Label:
                        filter.assetLabels = new string[] { searchString };
                        return filter;

                    case SearchMode.AssetBundleName:
                        filter.assetBundleNames = new string[] { searchString };
                        return filter;
                }
            }
            return filter;
        }
예제 #22
0
        //--------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="FindAndReplaceViewModel"/> class.
        /// </summary>
        /// <param name="searchExtension">
        /// The search extension. Can be <see langword="null"/> at design-time.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="searchExtension"/> is <see langword="null"/>.
        /// </exception>
        public FindAndReplaceViewModel(SearchExtension searchExtension)
        {
            DisplayName = "Find & Replace";
            DockId = DockIdString;
            IsPersistent = true;
            DockWidth = new GridLength(200);
            DockHeight = new GridLength(1, GridUnitType.Auto);
            //Icon = MultiColorGlyphs.Find;

            if (!WindowsHelper.IsInDesignMode)
            {
                if (searchExtension == null)
                    throw new ArgumentNullException(nameof(searchExtension));

                _searchExtension = searchExtension;

                if (Query.Mode == SearchMode.Normal)
                {
                    _useRegexOrWildcards = false;
                    _regexOrWildcards = SearchMode.Regex;
                }
                else
                {
                    _useRegexOrWildcards = true;
                    _regexOrWildcards = Query.Mode;
                }

                Query.PropertyChanged += OnQueryChanged;

                FindPreviousCommand = ((CommandItem)searchExtension.CommandItems["FindPrevious"]).Command;
                FindNextCommand = ((CommandItem)searchExtension.CommandItems["FindNext"]).Command;
                ReplaceCommand = ((CommandItem)searchExtension.CommandItems["Replace"]).Command;
                ReplaceAllCommand = ((CommandItem)searchExtension.CommandItems["ReplaceAll"]).Command;
                CancelCommand = new DelegateCommand(Cancel);
            }
        }
예제 #23
0
 /// <summary>
 ///     Gets the track for the specified <paramref name="query"/> asynchronously.
 /// </summary>
 /// <param name="query">the track search query</param>
 /// <param name="mode">the track search mode</param>
 /// <param name="noCache">
 ///     a value indicating whether the track should be returned from cache, if it is cached.
 ///     Note this parameter does only take any effect is a cache provider is specified in constructor.
 /// </param>
 /// <param name="cancellationToken">
 ///     a cancellation token that can be used by other objects or threads to receive notice
 ///     of cancellation.
 /// </param>
 /// <returns>
 ///     a task that represents the asynchronous operation. The task result is the track
 ///     found for the specified <paramref name="query"/>
 /// </returns>
 public async Task <LavalinkTrack> GetTrackAsync(string query, SearchMode mode = SearchMode.None,
                                                 bool noCache = false, CancellationToken cancellationToken = default)
 => (await GetTracksAsync(query, mode, noCache, cancellationToken))?.FirstOrDefault();
예제 #24
0
 private bool Contains(string id, SearchMode searchMode, bool filtered)
 {
     return(Get(id, searchMode, filtered) != null);
 }
예제 #25
0
        protected List <Move>?startSearch(Position?position, SearchMode mode)
        {
            try {
                if (position is null)
                {
                    throw new PositionException("Null Position");
                }
                else if (SearchTimer is null)
                {
                    throw new PositionException("Null SearchTimer Stopwatch");
                }
                else
                {
                    SearchTimer.Reset();
                    IntervalNodes      =
                        HeartbeatNodes = (UInt64)NodeTotal;
                    LastBeatMS         = SearchTimer.ElapsedMilliseconds;
                }

                if (position.IsLegal())
                {
                    StartDepth = 0;     //[Init]
                    ClearSearchCounts();

                    if (UCI.IsDebug)
                    {
                        var dtStarted = DateTime.Now;
#if Herald
                        herald(dtStarted, position.Name);
#endif
#if NoteStartAndFinish
                        LogInfo(Level.note, $"Started at {dtStarted:yyyy-MM-dd HH:mm:ss.ff}");
#endif
                    }

                    SearchTimer.Start();

                    switch (mode)
                    {
                    case SearchMode.BestMove:
                        var mValue = position.IteratePlies(Bound);
                        break;

                    case SearchMode.Perft:
                        position.IterateCases();
                        break;
                    }
                }
                else
                {
                    throw new PositionException("Illegal Setup");
                }
            }
            catch (OperationCanceledException) {
                //
                // OperationCanceledException is thrown in MonitorBound() via ThrowIfCancellationRequested(),
                // when Cancel() has been called on the source of this Task's CancellationToken.  Catching
                // it here allows stack frames for an active search to return Position objects to the pool.
                //
            }
            catch (FinalPositionException ex) {
                LogInfo(Level.note, ex.Message);
            }
            catch (ApplicationException ex) {
#if StackTrace
                LogInfo(Level.error, ex.ToString());
#else
                LogInfo(Level.error, ex.Message);
#endif
            }
            catch (Exception ex) {
                LogInfo(Level.error, ex.ToString());
            }
            finally {
                if (SearchTimer.IsRunning)
                {
                    SearchTimer.Stop();
                }

                if (UCI.IsDebug)
                {
                    LogInfoNewLine(Level.note);
#if NoteStartAndFinish
                    LogInfo(Level.note, $"Finished at {DateTime.Now:yyyy-MM-dd HH:mm:ss.ff}");
#endif
                    var dElapsedMS = (Double)SearchTimer.ElapsedMilliseconds;
                    displayCounts(mode, dElapsedMS);
                }
            }

            //
            //[Optional]Repeat final bestmove report:
            //
            if (BestMoves is not null)
            {
                var sb = new StringBuilder();
                //[Note]refreshPV() has been called
                sb.BestMove(BestMoves, Rule);
                if (sb.Length > 0)
                {
                    LogLine(sb.ToString());
                }
            }

            return(BestMoves);
        }
예제 #26
0
 private void Cancel_button_Click(object sender, RoutedEventArgs e)
 {
     result = SearchMode.cancelFind;
     this.Close();
 }
예제 #27
0
 /// <summary>
 /// See <see cref="IReadableLocator.Get{T}(object, SearchMode)"/> for more information.
 /// </summary>
 public TItem Get <TItem>(object key, SearchMode options)
 {
     return((TItem)Get(key, options));
 }
예제 #28
0
 /// <summary>
 /// See <see cref="IReadableLocator.Contains(object, SearchMode)"/> for more information.
 /// </summary>
 public abstract bool Contains(object key, SearchMode options);
예제 #29
0
 public override bool Contains(object key, SearchMode options)
 {
     throw new NotImplementedException();
 }
예제 #30
0
        public MatchRules(DateTimeOffset time, SearchMode mode)
        {
            Mode          = mode;
            ReferenceTime = time;
            DateTime theDate = time.UtcDateTime.Date;

            switch (mode)
            {
            case SearchMode.AroundWorkingDay:
            {
                DateTime previous  = theDate - DefaultDayPeriod;
                DateTime endOfNext = theDate.AddDays(1) + DefaultDayPeriod;

                startJulianUtc = Ephemeris.ToJulianDay(new DateTimeOffset(previous, TimeSpan.Zero));
                endJulianUtc   = Ephemeris.ToJulianDay(new DateTimeOffset(endOfNext, TimeSpan.Zero));

                if (previous.DayOfWeek == DayOfWeek.Saturday || previous.DayOfWeek == DayOfWeek.Sunday)
                {
                    int dif = (previous.DayOfWeek + 7 - DayOfWeek.Friday) % 7;
                    startJulianUtc -= dif;
                }

                if (endOfNext.DayOfWeek == DayOfWeek.Sunday || endOfNext.DayOfWeek == DayOfWeek.Monday)
                {
                    int dif = (8 + DayOfWeek.Monday - endOfNext.DayOfWeek) % 7;
                    endJulianUtc += dif;
                }
                break;
            }

            case SearchMode.WithinTheDay:
            {
                startJulianUtc = Ephemeris.ToJulianDay(new DateTimeOffset(theDate, TimeSpan.Zero));
                endJulianUtc   = startJulianUtc + DefaultDayPeriod.TotalDays;
                break;
            }

            case SearchMode.WithinTheWeek:
            {
                int daysToLastSaturday = (7 + theDate.DayOfWeek - DayOfWeek.Saturday) % 7;
                startJulianUtc = Ephemeris.ToJulianDay(new DateTimeOffset(theDate, TimeSpan.Zero)) - daysToLastSaturday;
                endJulianUtc   = startJulianUtc + 8 + DefaultDayPeriod.TotalDays;
                break;
            }

            case SearchMode.WithinTheMonth:
            {
                DateTimeOffset firstOfMonth = new DateTimeOffset(theDate.Year, theDate.Month, 1, 0, 0, 0, TimeSpan.Zero);
                startJulianUtc = Ephemeris.ToJulianDay(firstOfMonth) - DefaultDayPeriod.TotalDays;
                firstOfMonth  += TimeSpan.FromDays(31);
                firstOfMonth  -= TimeSpan.FromDays(firstOfMonth.Day - 1);
                endJulianUtc   = Ephemeris.ToJulianDay(firstOfMonth) + DefaultDayPeriod.TotalDays;
                break;
            }

            case SearchMode.WithinTheYear:
            {
                DateTimeOffset firstOfYear = new DateTimeOffset(theDate.Year, 1, 1, 0, 0, 0, TimeSpan.Zero);
                startJulianUtc = Ephemeris.ToJulianDay(firstOfYear) - DefaultDayPeriod.TotalDays;
                firstOfYear   += TimeSpan.FromDays(366);
                firstOfYear   -= TimeSpan.FromDays(firstOfYear.Day - 1);
                endJulianUtc   = Ephemeris.ToJulianDay(firstOfYear) + DefaultDayPeriod.TotalDays;
                break;
            }

            //case SearchMode.WithinTheDecade:
            //    {
            //        int year = theDate.Year - theDate.Year % 10;
            //        DateTimeOffset firstOfCenturay = new DateTimeOffset(year, 1, 1, 0, 0, 0, TimeSpan.Zero);
            //        startJulianUtc = Ephemeris.ToJulianDay(firstOfCenturay);
            //        DateTimeOffset firstOfNextCentuary = new DateTimeOffset(year + 10, 1, 1, 0, 0, 0, TimeSpan.Zero);
            //        endJulianUtc = Ephemeris.ToJulianDay(firstOfNextCentuary);
            //        break;
            //    }
            default:
                throw new NotImplementedException();
            }
        }
예제 #31
0
파일: Program.cs 프로젝트: NikitaVas/CSharp
        static void Show(DirectoryInfo dr, string[] args, SearchMode ch)
        {
            FileSystemInfo[] files = null;
            if (choice_1 == FileOrDirectory.fl)
                files = dr.GetFiles("*", SearchOption.AllDirectories);
            else
                files = dr.GetDirectories("*", SearchOption.AllDirectories);

            if (files != null)
                if (args.Length < 4)
                    ShowInfo(files, ch, args[2]);
                else
                    ShowInfo(files, ch, args[3]);
        }
 public IAzureSearchClient SearchMode(SearchMode searchMode)
 {
     this._searchMode = searchMode;
     return(this);
 }
예제 #33
0
        private async Task <DocumentSearchResult <RoomModel> > SearchMeetongRoomAsync(SearchMode searchMode, string query, int floorNumber = 0)
        {
            SearchParameters parameters = new SearchParameters()
            {
                SearchMode = searchMode,
                Filter     = floorNumber == 0 ? null : SearchFilters.FloorNumberFilter + floorNumber.ToString()
            };

            try
            {
                DocumentSearchResult <RoomModel> searchResults = await _indexClient.Documents.SearchAsync <RoomModel>(query, parameters);

                return(searchResults);
            }
            catch (Exception ex)
            {
                throw HandleAzureSearchException(ex);
            }
        }
예제 #34
0
        //Show stuff
        public override void OnGUI(Rect rect)
        {
            var e = Event.current;

            EditorGUIUtility.SetIconSize(Vector2.zero);
            hoveringIndex = Mathf.Clamp(hoveringIndex, -1, currentNode.children.Count - 1);

            ///MAIN AREA
            mainRect = new Rect(rect.x, rect.y, rect.width, rect.height - helpRectHeight);
            if (EditorGUIUtility.isProSkin)
            {
                GUI.Box(mainRect, "", (GUIStyle)"PreBackground");
            }
            GUILayout.BeginArea(mainRect);

            //HEADER
            GUILayout.Space(2);
            GUILayout.Label(string.Format("<color=#{0}><size=15><b>{1}</b></size></color>", EditorGUIUtility.isProSkin? "dddddd" : "222222", title), headerStyle);

            ///SEARCH
            if (e.keyCode == KeyCode.DownArrow)
            {
                GUIUtility.keyboardControl = 0;
            }
            if (e.keyCode == KeyCode.UpArrow)
            {
                GUIUtility.keyboardControl = 0;
            }
            // GUILayout.Space(2);
            GUILayout.BeginHorizontal();
            GUI.SetNextControlName("SearchToolbar");
            search = EditorGUILayout.TextField(search, (GUIStyle)"ToolbarSeachTextField");
            if (GUILayout.Button("", (GUIStyle)"ToolbarSeachCancelButton"))
            {
                search = string.Empty;
                GUIUtility.keyboardControl = 0;
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            searchMode      = (SearchMode)EditorGUILayout.EnumPopup(searchMode);
            filterFavorites = EditorGUILayout.ToggleLeft("Filter Favorites", filterFavorites);
            GUILayout.EndHorizontal();

            EditorUtils.BoldSeparator();

            ///BACK
            if (currentNode.parent != null && string.IsNullOrEmpty(search))
            {
                GUILayout.BeginHorizontal("box");
                if (GUILayout.Button(string.Format("<b><size=14>◄ {0}/{1}</size></b>", currentNode.parent.name, currentNode.name), (GUIStyle)"label"))
                {
                    currentNode = currentNode.parent;
                }
                GUILayout.EndHorizontal();
                var lastRect = GUILayoutUtility.GetLastRect();
                if (lastRect.Contains(e.mousePosition))
                {
                    GUI.color = hoverColor;
                    GUI.DrawTexture(lastRect, EditorGUIUtility.whiteTexture);
                    GUI.color = Color.white;
                    base.editorWindow.Repaint();
                    hoveringIndex = -1;
                }
            }

            //Go back with right click as well...
            if (e.type == EventType.MouseDown && e.button == 1)
            {
                e.Use();
                if (currentNode.parent != null)
                {
                    currentNode = currentNode.parent;
                }
            }


            ///TREE
            scrollPos = EditorGUILayout.BeginScrollView(scrollPos, false, false);
            GUILayout.BeginVertical();

            if (search != lastSearch)
            {
                hoveringIndex = 0;
                if (!string.IsNullOrEmpty(search) && search.Length >= 2)
                {
                    var searchRootNode = new Node()
                    {
                        name = "Search Root"
                    };
                    var a = search.ToUpper();
                    foreach (var node in leafNodes)
                    {
                        var b     = node.name.ToUpper();
                        var match = false;
                        if (searchMode == SearchMode.Contains)
                        {
                            match = true;
                            var words = a.Split(' ');
                            foreach (var word in words)
                            {
                                if (!b.Contains(word))
                                {
                                    match = false;
                                    break;
                                }
                            }
                        }
                        if (searchMode == SearchMode.StartsWith && b.StartsWith(a))
                        {
                            match = true;
                        }
                        if (match)
                        {
                            searchRootNode.children[node.name] = node;
                        }
                    }
                    currentNode = searchRootNode;
                }
                else
                {
                    currentNode = rootNode;
                }
                lastSearch = search;
            }



            var  i          = 0;
            var  itemAdded  = false;
            Node lastParent = null;

            foreach (var childPair in currentNode.children)
            {
                var node = childPair.Value;

                if (search != null && search.Length >= 2)
                {
                    var currentParent = node.parent;
                    if (currentParent != lastParent)
                    {
                        lastParent = currentParent;
                        GUI.color  = EditorGUIUtility.isProSkin? Color.black : Color.white;
                        GUILayout.BeginHorizontal("box");
                        GUI.color = Color.white;
                        if (GUILayout.Button(currentParent.unfolded? "▼" : "▶", (GUIStyle)"label", GUILayout.Width(16)))
                        {
                            currentParent.unfolded = !currentParent.unfolded;
                        }
                        GUILayout.Label(string.Format("<size=12><b>{0}</b></size>", currentParent.fullPath));
                        GUILayout.EndHorizontal();
                    }

                    if (!node.parent.unfolded)
                    {
                        continue;
                    }
                }

                if (filterFavorites && !node.isFavorite && !node.HasAnyFavoriteChild())
                {
                    continue;
                }

                itemAdded = true;
                var leafItem     = node.item;
                var icon         = leafItem != null? leafItem.content.image : EditorUtils.folderIcon;
                var itemDisabled = leafItem != null && leafItem.func == null && leafItem.func2 == null;

                GUI.color = EditorGUIUtility.isProSkin? Color.white : new Color(0.8f, 0.8f, 0.8f, 1);
                GUILayout.BeginHorizontal("box");
                GUI.color = Color.white;

                //Prefix icon
                GUILayout.Label(icon, GUILayout.Width(32), GUILayout.Height(16));

                GUI.enabled = !itemDisabled;

                //Favorite
                GUI.color = node.isFavorite? Color.white : (node.HasAnyFavoriteChild()? new Color(1, 1, 1, 0.2f) : new Color(0f, 0f, 0f, 0.4f));
                if (GUILayout.Button(EditorUtils.favoriteIcon, GUIStyle.none, GUILayout.Width(16), GUILayout.Height(16)))
                {
                    node.ToggleFavorite();
                }
                GUI.color = Color.white;

                //Content
                var label = node.name;
                if (search != null && search.Length >= 2)                  //simple highlight
                {
                    label = Regex.Replace(label, search, "<b>$&</b>", RegexOptions.IgnoreCase);
                }

                if (GUILayout.Button(string.Format("<size=10>{0}</size>",
                                                   (leafItem == null? string.Format("<b>{0}</b>", label) : label)),
                                     (GUIStyle)"label", GUILayout.Width(0), GUILayout.ExpandWidth(true)))
                {
                    if (leafItem != null)
                    {
                        ExecuteItemFunc(leafItem);
                        break;
                    }
                    else
                    {
                        currentNode   = node;
                        hoveringIndex = 0;
                        break;
                    }
                }

                //Suffix icon
                GUILayout.Label(leafItem != null? "<b>+</b>" : "►", GUILayout.Width(20));

                GUILayout.EndHorizontal();
                var lastRect = GUILayoutUtility.GetLastRect();

                if (lastRect.Contains(e.mousePosition) && e.type == EventType.MouseMove)
                {
                    hoveringIndex = i;
                }

                if (hoveringIndex == i)
                {
                    GUI.color = hoverColor;
                    GUI.DrawTexture(lastRect, EditorGUIUtility.whiteTexture);
                    GUI.color = Color.white;
                    base.editorWindow.Repaint();
                }

                i++;

                GUI.enabled = true;
            }


            if (!itemAdded)
            {
                GUILayout.Label("No results to display with current search and filter combination");
            }

            GUILayout.EndVertical();
            EditorGUILayout.EndScrollView();
            GUILayout.EndArea();


            GUILayout.FlexibleSpace();


            ///HELP AREA
            var hoveringNode = hoveringIndex >= 0 && currentNode.children.Count > 0? currentNode.children.Values.ToList()[hoveringIndex] : null;
            var helpRect     = new Rect(rect.x + 2, rect.yMax - helpRectHeight + 2, rect.width - 4, helpRectHeight - 2);

            GUI.color = new Color(0, 0, 0, 0.3f);
            GUI.Box(helpRect, "", (GUIStyle)"TextField");
            GUI.color = Color.white;
            GUILayout.BeginArea(helpRect);
            GUILayout.BeginVertical();
            var doc = string.Empty;

            if (hoveringNode != null && hoveringNode.item != null)
            {
                doc = hoveringNode.item.content.tooltip;
                var memberInfo = hoveringNode.item.userData as MemberInfo;
                if (memberInfo != null && string.IsNullOrEmpty(doc))
                {
                    doc = DocsByReflection.GetMemberSummary(memberInfo);
                }
            }
            GUILayout.Label(doc, EditorStyles.wordWrappedLabel);
            GUILayout.EndVertical();
            GUILayout.EndArea();


            //handle the events
            HandeEvents(e);
            if (!init)
            {
                init = true;
                EditorGUI.FocusTextInControl("SearchToolbar");
            }

            EditorGUIUtility.SetIconSize(Vector2.zero);
        }
예제 #35
0
 /// <summary>
 ///     Gets the tracks for the specified <paramref name="query"/> asynchronously.
 /// </summary>
 /// <param name="query">the track search query</param>
 /// <param name="mode">the track search mode</param>
 /// <param name="noCache">
 ///     a value indicating whether the track should be returned from cache, if it is cached.
 ///     Note this parameter does only take any effect is a cache provider is specified in constructor.
 /// </param>
 /// <param name="cancellationToken">
 ///     a cancellation token that can be used by other objects or threads to receive notice
 ///     of cancellation.
 /// </param>
 /// <returns>
 ///     a task that represents the asynchronous operation. The task result are the tracks
 ///     found for the specified <paramref name="query"/>
 /// </returns>
 public async Task <IEnumerable <LavalinkTrack> > GetTracksAsync(string query, SearchMode mode = SearchMode.None,
                                                                 bool noCache = false, CancellationToken cancellationToken = default)
 => (await LoadTracksAsync(query, mode, noCache, cancellationToken))?.Tracks;
예제 #36
0
 public static void RequestSearch(string query, SearchMode mode)
 {
     SearchRequested?.Invoke(query, mode);
 }
예제 #37
0
 /// <summary>
 /// Initializes a new instance of the SearchParameters class.
 /// </summary>
 /// <param name="includeTotalResultCount">A value that specifies
 /// whether to fetch the total count of results. Default is false.
 /// Setting this value to true may have a performance impact. Note that
 /// the count returned is an approximation.</param>
 /// <param name="facets">The list of facet expressions to apply to the
 /// search query. Each facet expression contains a field name,
 /// optionally followed by a comma-separated list of name:value
 /// pairs.</param>
 /// <param name="filter">The OData $filter expression to apply to the
 /// search query.</param>
 /// <param name="highlightFields">The list of field names to use for
 /// hit highlights. Only searchable fields can be used for hit
 /// highlighting.</param>
 /// <param name="highlightPostTag">A string tag that is appended to hit
 /// highlights. Must be set with highlightPreTag. Default is
 /// &amp;lt;/em&amp;gt;.</param>
 /// <param name="highlightPreTag">A string tag that is prepended to hit
 /// highlights. Must be set with highlightPostTag. Default is
 /// &amp;lt;em&amp;gt;.</param>
 /// <param name="minimumCoverage">A number between 0 and 100 indicating
 /// the percentage of the index that must be covered by a search query
 /// in order for the query to be reported as a success. This parameter
 /// can be useful for ensuring search availability even for services
 /// with only one replica. The default is 100.</param>
 /// <param name="orderBy">The list of OData $orderby expressions by
 /// which to sort the results. Each expression can be either a field
 /// name or a call to either the geo.distance() or the search.score()
 /// functions. Each expression can be followed by asc to indicate
 /// ascending, and desc to indicate descending. The default is
 /// ascending order. Ties will be broken by the match scores of
 /// documents. If no OrderBy is specified, the default sort order is
 /// descending by document match score. There can be at most 32
 /// $orderby clauses.</param>
 /// <param name="queryType">A value that specifies the syntax of the
 /// search query. The default is 'simple'. Use 'full' if your query
 /// uses the Lucene query syntax. Possible values include: 'simple',
 /// 'full'</param>
 /// <param name="scoringParameters">The list of parameter values to be
 /// used in scoring functions (for example, referencePointParameter)
 /// using the format name-values. For example, if the scoring profile
 /// defines a function with a parameter called 'mylocation' the
 /// parameter string would be "mylocation--122.2,44.8" (without the
 /// quotes).</param>
 /// <param name="scoringProfile">The name of a scoring profile to
 /// evaluate match scores for matching documents in order to sort the
 /// results.</param>
 /// <param name="searchFields">The list of field names to which to
 /// scope the full-text search. When using fielded search
 /// (fieldName:searchExpression) in a full Lucene query, the field
 /// names of each fielded search expression take precedence over any
 /// field names listed in this parameter.</param>
 /// <param name="searchMode">A value that specifies whether any or all
 /// of the search terms must be matched in order to count the document
 /// as a match. Possible values include: 'any', 'all'</param>
 /// <param name="select">The list of fields to retrieve. If
 /// unspecified, all fields marked as retrievable in the schema are
 /// included.</param>
 /// <param name="skip">The number of search results to skip. This value
 /// cannot be greater than 100,000. If you need to scan documents in
 /// sequence, but cannot use $skip due to this limitation, consider
 /// using $orderby on a totally-ordered key and $filter with a range
 /// query instead.</param>
 /// <param name="top">The number of search results to retrieve. This
 /// can be used in conjunction with $skip to implement client-side
 /// paging of search results. If results are truncated due to
 /// server-side paging, the response will include a continuation token
 /// that can be used to issue another Search request for the next page
 /// of results.</param>
 public SearchParameters(bool includeTotalResultCount = default(bool), IList <string> facets = default(IList <string>), string filter = default(string), IList <string> highlightFields = default(IList <string>), string highlightPostTag = default(string), string highlightPreTag = default(string), double?minimumCoverage = default(double?), IList <string> orderBy = default(IList <string>), QueryType queryType = default(QueryType), IList <ScoringParameter> scoringParameters = default(IList <ScoringParameter>), string scoringProfile = default(string), IList <string> searchFields = default(IList <string>), SearchMode searchMode = default(SearchMode), IList <string> select = default(IList <string>), int?skip = default(int?), int?top = default(int?))
 {
     IncludeTotalResultCount = includeTotalResultCount;
     Facets            = facets;
     Filter            = filter;
     HighlightFields   = highlightFields;
     HighlightPostTag  = highlightPostTag;
     HighlightPreTag   = highlightPreTag;
     MinimumCoverage   = minimumCoverage;
     OrderBy           = orderBy;
     QueryType         = queryType;
     ScoringParameters = scoringParameters;
     ScoringProfile    = scoringProfile;
     SearchFields      = searchFields;
     SearchMode        = searchMode;
     Select            = select;
     Skip = skip;
     Top  = top;
     CustomInit();
 }
예제 #38
0
        /// <summary>
        /// <para>Searches for files and folders.</para>
        /// </summary>
        /// <param name="path">The path in the user's Dropbox to search. Should probably be a
        /// folder.</param>
        /// <param name="query">The string to search for. The search string is split on spaces
        /// into multiple tokens. For file name searching, the last token is used for prefix
        /// matching (i.e. "bat c" matches "bat cave" but not "batman car").</param>
        /// <param name="start">The starting index within the search results (used for
        /// paging).</param>
        /// <param name="maxResults">The maximum number of search results to return.</param>
        /// <param name="mode">The search mode (filename, filename_and_content, or
        /// deleted_filename).</param>
        /// <returns>The task that represents the asynchronous send operation. The TResult
        /// parameter contains the response from the server.</returns>
        /// <exception cref="Dropbox.Api.ApiException{SearchError}">Thrown if there is an error
        /// processing the request; This will contain a <see cref="SearchError"/>.</exception>
        public t.Task<SearchResult> SearchAsync(string path,
                                                string query,
                                                ulong start = 0,
                                                ulong maxResults = 100,
                                                SearchMode mode = null)
        {
            var searchArg = new SearchArg(path,
                                          query,
                                          start,
                                          maxResults,
                                          mode);

            return this.SearchAsync(searchArg);
        }
예제 #39
0
 /// <summary>
 /// See <see cref="IReadableLocator.Get(object, SearchMode)"/> for more information.
 /// </summary>
 public abstract object Get(object key, SearchMode options);
예제 #40
0
 public static string ToSerialString(this SearchMode value) => value switch
 {
예제 #41
0
        private static string GetAttributesString <TAttribute>(ICustomAttributeProvider source, SearchMode searchMode)
            where TAttribute : class, ITestInterface
        {
            var attributes =
                searchMode switch
            {
                SearchMode.Attributes => source.GetCustomAttributesWithInterfaceSupport <TAttribute>(true),
                SearchMode.MetadataAttributes => source.GetMetadataAttributes <TAttribute>(),
                SearchMode.MetadataAttributesSingleLevel => source.GetMetadataAttributes <TAttribute>(thisLevelOnly: true),
                _ => throw new ArgumentOutOfRangeException(nameof(searchMode), searchMode, null)
            };

            return(attributes
                   .GroupWhileEquals(
                       a => a.Origin,
                       a => a.GetType().Name.Split('+').Last().ReplaceOrdinal("Attribute", ""))
                   .Select(g => g.Key + ":" + g.Join(","))
                   .Join("; "));
        }
예제 #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DependencyParameter"/> class using the
 /// provided parameter type, name, creation type, not present behavior, and search mode.
 /// </summary>
 public DependencyParameter(Type parameterType, string name,
                            Type createType, NotPresentBehavior notPresentBehavior, SearchMode searchMode)
     : base(parameterType)
 {
     this.name               = name;
     this.createType         = createType;
     this.notPresentBehavior = notPresentBehavior;
     this.searchMode         = searchMode;
 }
예제 #43
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="record"></param>
 /// <param name="sfi"></param>
 /// <param name="search"></param>
 /// <param name="udc"></param>
 /// <param name="le"></param>
 public ReadRecordCommand(byte record, byte sfi, SearchMode search, byte[] udc, UInt32 le)
     : this(record, sfi, search, le)
 {
     Ins = 0xB3;
     Udc = udc;
 }
예제 #44
0
            AbstractSearchStrategy GetSearchStrategy(SearchMode mode, string[] terms)
            {
                if (terms.Length == 1)
                {
                    if (terms[0].StartsWith("tm:", StringComparison.Ordinal))
                    {
                        return(new MemberSearchStrategy(language, AddResult, terms[0].Substring(3)));
                    }

                    if (terms[0].StartsWith("t:", StringComparison.Ordinal))
                    {
                        return(new MemberSearchStrategy(language, AddResult, terms[0].Substring(2), MemberSearchKind.Type));
                    }

                    if (terms[0].StartsWith("m:", StringComparison.Ordinal))
                    {
                        return(new MemberSearchStrategy(language, AddResult, terms[0].Substring(2), MemberSearchKind.Member));
                    }

                    if (terms[0].StartsWith("md:", StringComparison.Ordinal))
                    {
                        return(new MemberSearchStrategy(language, AddResult, terms[0].Substring(3), MemberSearchKind.Method));
                    }

                    if (terms[0].StartsWith("f:", StringComparison.Ordinal))
                    {
                        return(new MemberSearchStrategy(language, AddResult, terms[0].Substring(2), MemberSearchKind.Field));
                    }

                    if (terms[0].StartsWith("p:", StringComparison.Ordinal))
                    {
                        return(new MemberSearchStrategy(language, AddResult, terms[0].Substring(2), MemberSearchKind.Property));
                    }

                    if (terms[0].StartsWith("e:", StringComparison.Ordinal))
                    {
                        return(new MemberSearchStrategy(language, AddResult, terms[0].Substring(2), MemberSearchKind.Event));
                    }

                    if (terms[0].StartsWith("c:", StringComparison.Ordinal))
                    {
                        return(new LiteralSearchStrategy(language, AddResult, terms[0].Substring(2)));
                    }

                    if (terms[0].StartsWith("@", StringComparison.Ordinal))
                    {
                        return(new MetadataTokenSearchStrategy(language, AddResult, terms[0].Substring(1)));
                    }
                }

                switch (mode)
                {
                case SearchMode.TypeAndMember:
                    return(new MemberSearchStrategy(language, AddResult, terms));

                case SearchMode.Type:
                    return(new MemberSearchStrategy(language, AddResult, terms, MemberSearchKind.Type));

                case SearchMode.Member:
                    return(new MemberSearchStrategy(language, AddResult, terms, MemberSearchKind.Member));

                case SearchMode.Literal:
                    return(new LiteralSearchStrategy(language, AddResult, terms));

                case SearchMode.Method:
                    return(new MemberSearchStrategy(language, AddResult, terms, MemberSearchKind.Method));

                case SearchMode.Field:
                    return(new MemberSearchStrategy(language, AddResult, terms, MemberSearchKind.Field));

                case SearchMode.Property:
                    return(new MemberSearchStrategy(language, AddResult, terms, MemberSearchKind.Property));

                case SearchMode.Event:
                    return(new MemberSearchStrategy(language, AddResult, terms, MemberSearchKind.Event));

                case SearchMode.Token:
                    return(new MetadataTokenSearchStrategy(language, AddResult, terms));
                }

                return(null);
            }
예제 #45
0
        /// <summary>
        /// Creates a default ISearchStrategy with the given parameters.
        /// </summary>
        public static ISearchStrategy Create(string searchPattern, bool ignoreCase, bool matchWholeWords, SearchMode mode)
        {
            if (searchPattern == null)
            {
                throw new ArgumentNullException("searchPattern");
            }

            var regexOptions = RegexOptions.Compiled;

            if ((mode == SearchMode.Extended || mode == SearchMode.RegEx) &&
                (searchPattern.IndexOf("\\r") > 0 || searchPattern.IndexOf("\\n") > 0))
            {
                // Don't change the Regex mode
            }
            else
            {
                regexOptions |= RegexOptions.Multiline;
            }

            if (ignoreCase)
            {
                regexOptions |= RegexOptions.IgnoreCase;
            }

            switch (mode)
            {
            case SearchMode.Normal:
                searchPattern = Regex.Escape(searchPattern);
                break;

            case SearchMode.Extended:
                try
                {
                    searchPattern = Regex.Escape(StringHelper.StringFromCSharpLiteral(searchPattern));
                }
                catch (ArgumentException ex)
                {
                    throw new SearchPatternException(ex.Message, ex);
                }
                break;

            case SearchMode.Wildcard:
                searchPattern = ConvertWildcardsToRegex(searchPattern);
                break;

            case SearchMode.XPath:
                return(new XPathSearchStrategy(searchPattern));
            }

            try
            {
                var searchPattern2 = new Regex(searchPattern, regexOptions);
                return(new RegexSearchStrategy(searchPattern2, matchWholeWords));
            }
            catch (ArgumentException ex)
            {
                throw new SearchPatternException(ex.Message, ex);
            }
        }
 protected ObjectLookupFieldFixedTypeAttribute(PrefabLookupKinds kinds, Type minimalType, SearchMode defaultSearchMode, Type[] interfacesRequired) : base(kinds, minimalType, defaultSearchMode, interfacesRequired)
 {
 }
    /// <summary>
    /// Page load.
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Arguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }
        else
        {
            // Set up drop down list
            if (ShowSearchMode)
            {
                if (!RequestHelper.IsPostBack())
                {
                    // Fill dropdownlist option with values
                    ControlsHelper.FillListControlWithEnum <SearchModeEnum>(drpSearchMode, "srch.dialog", useStringRepresentation: true);
                    drpSearchMode.SelectedValue = QueryHelper.GetString("searchmode", SearchMode.ToStringRepresentation());
                }
            }

            // Set up search text
            if (!RequestHelper.IsPostBack() && (!ShowOnlySearchButton))
            {
                txtSearchFor.Text = QueryHelper.GetString("searchtext", "");
            }
        }
    }
        /// <summary>
        /// Creates a default ISearchStrategy with the given parameters.
        /// </summary>
        public static ISearchStrategy Create(string searchPattern, bool ignoreCase, bool matchWholeWords, SearchMode mode)
        {
            if (searchPattern == null)
            {
                throw new ArgumentNullException("searchPattern");
            }
            RegexOptions options = RegexOptions.Compiled | RegexOptions.Multiline;

            if (ignoreCase)
            {
                options |= RegexOptions.IgnoreCase;
            }

            switch (mode)
            {
            case SearchMode.Normal:
                searchPattern = Regex.Escape(searchPattern);
                break;

            case SearchMode.Wildcard:
                searchPattern = ConvertWildcardsToRegex(searchPattern);
                break;
            }
            try {
                Regex pattern = new Regex(searchPattern, options);
                return(new RegexSearchStrategy(pattern, matchWholeWords));
            } catch (ArgumentException ex) {
                throw new SearchPatternException(ex.Message, ex);
            }
        }
예제 #49
0
 public RunningSearch(IList <LoadedAssembly> assemblies, string searchTerm, SearchMode searchMode,
                      Language language, ApiVisibility apiVisibility)
 {
     this.assemblies    = assemblies;
     this.language      = language;
     this.searchMode    = searchMode;
     this.apiVisibility = apiVisibility;
     this.searchRequest = Parse(searchTerm);
 }
예제 #50
0
 /// <summary>
 /// Constructor. It is private so that MUIFileSearcher is used only internal for this class.
 /// To access functionality in this class, static api should be used.
 /// </summary>
 /// <param name="target"></param>
 /// <param name="searchPaths"></param>
 /// <param name="searchMode"></param>
 private MUIFileSearcher(string target, Collection <string> searchPaths, SearchMode searchMode)
 {
     Target      = target;
     SearchPaths = searchPaths;
     SearchMode  = searchMode;
 }
예제 #51
0
파일: filename.cs 프로젝트: fukuyori/sift
        private void sourceRefresh(String path)
        {
            // DataGridの内容消去
            clsSource();
            checkBox1.Checked = false;
            clsTarget();
            clsRename();

            // マウスカーソル変更
            Cursor preCursor = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            // 項目無効
            allButtons(false);

            totalCount = 0;

            // ファイル名の取得
            using (var transaction = cn.BeginTransaction()) {
                using (SQLiteCommand cmd = cn.CreateCommand()) {
                    cmd.CommandText = "PRAGMA journal_mode = MEMORY";
                    cmd.ExecuteNonQuery();
                    sm = SearchMode.None;
                    recursiveFileList(path, ref totalCount);
                }
                transaction.Commit();
            }

            adapter = new SQLiteDataAdapter("SELECT Id, checked, path, file, size, date FROM flist;", cn);

            SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter);

            if (adapter != null)
                adapter.Fill(dtSource);

            // カーソルを元に戻す
            this.Cursor = preCursor;
            // 項目有効
            allButtons(true);
            // ボタン表示チェック
            buttonEnable();
            // 件数表示
            checkedCounter(totalCount);
            // パネル1を表示
            viewPanel(1);
        }
예제 #52
0
 public RunningSearch(IList <LoadedAssembly> assemblies, string searchTerm, SearchMode searchMode, Language language, ApiVisibility apiVisibility)
 {
     this.assemblies    = assemblies;
     this.searchTerm    = NativeMethods.CommandLineToArgumentArray(searchTerm);
     this.language      = language;
     this.searchMode    = searchMode;
     this.apiVisibility = apiVisibility;
 }
예제 #53
0
파일: Program.cs 프로젝트: NikitaVas/CSharp
        static void ShowInfo(FileSystemInfo[] finfo, SearchMode mode, object comparer)
        {
            Console.Clear();
            selected.Clear();
            foreach (FileSystemInfo d in finfo)
            {
                if (mode == SearchMode.a)
                {
                    ShowHelper(d);
                    Program.selected.Add(d);
                }
                else if (mode == SearchMode.nm)
                {
                    if (d.Name == (string)comparer)
                    {
                        ShowHelper(d);
                        selected.Add(d);
                    }
                }
                else if (mode == SearchMode.sz)
                {
                    FileInfo f = d as FileInfo;
                    long size;
                    Int64.TryParse((string)comparer, out size);
                    if (f.Length == size)
                    {
                        ShowHelper(f);
                        selected.Add(f);
                    }
                }
                else if (mode == SearchMode.crt)
                {
                    DateTime dt;
                    DateTime.TryParse((string)comparer, out dt);
                    if (d.CreationTime.Date == dt.Date)
                    {
                        ShowHelper(d);
                        selected.Add(d);
                    }
                }
                else if (mode == SearchMode.lat)
                {
                    DateTime dt;
                    DateTime.TryParse((string)comparer, out dt);
                    if (d.LastAccessTime.Date == dt.Date)
                    {
                        ShowHelper(d);
                        selected.Add(d);
                    }
                }
                else if (mode == SearchMode.lwt)
                {
                    DateTime dt;
                    DateTime.TryParse((string)comparer, out dt);
                    if (d.LastWriteTime.Date == dt.Date)
                    {
                        ShowHelper(d);
                        selected.Add(d);
                    }
                }
                else if (mode == SearchMode.ctn)
                {
                    if (d.Extension == ".txt")
                    {
                        using (StreamReader sr = File.OpenText(d.FullName))
                        {
                            string input = null;
                            input = sr.ReadToEnd();
                            if (input.IndexOf((string)comparer) != -1)
                            {
                                ShowHelper(d);
                                selected.Add(d);
                            }
                        }
                    }
                }
                else
                    throw new ArgumentException("Неверная команда!");
            }

            if (selected.Count == 0)
                Console.WriteLine("По Вашему запросу ничего не найдено");
        }
예제 #54
0
        // yes yes, I know it's complicated, but settle down ReSharper
        // ReSharper disable once FunctionComplexityOverflow
        private static bool TryGetGroupEvent(IrGroup group, DateTimeOffset start, SearchMode mode, out DateTimeOffset result)
        {
            var after = mode == SearchMode.After;
            var inc   = after ? 1 : -1; // used for incrementing values up or down depending on the direction we're searching

            var initHour   = after ? 0 : 23;
            var initMinute = after ? 0 : 59;
            var initSecond = after ? 0 : 59;

            // todo: make the length of the search configurable
            // @Spiralis: Changed the range from 367 to 4*365, as we need to look ahead for leap-years.
            for (var d = 0; d < (4 * 365); d++)
            {
                DateTimeOffset date;
                int            hour, minute, second;
                if (d == 0)
                {
                    // "after" events must be in the future
                    date = after ? start.AddSeconds(1) : start;

                    hour   = date.Hour;
                    minute = date.Minute;
                    second = date.Second;
                }
                else
                {
                    date = start.AddDays(d * inc);

                    hour   = initHour;
                    minute = initMinute;
                    second = initSecond;
                }

                var year       = date.Year;
                var month      = date.Month;
                var dayOfYear  = date.DayOfYear;
                var dayOfWeek  = (int)date.DayOfWeek + 1; // DayOfWeek enum is zero-indexed
                var dayOfMonth = date.Day;

                // check if today is an applicable date
                if (group.HasDates)
                {
                    var applicable = false;
                    foreach (var range in group.Dates)
                    {
                        if (InDateRange(range, year, month, dayOfMonth))
                        {
                            applicable = true;
                            break;
                        }
                    }

                    if (!applicable)
                    {
                        goto CONTINUE_DATE_LOOP;
                    }
                }

                if (group.HasDatesExcluded)
                {
                    foreach (var range in group.DatesExcluded)
                    {
                        if (InDateRange(range, year, month, dayOfMonth))
                        {
                            goto CONTINUE_DATE_LOOP;
                        }
                    }
                }

                // check if date is an applicable day of year
                if (group.HasDaysOfYear)
                {
                    var applicable = false;
                    foreach (var range in group.DaysOfYear)
                    {
                        if (InDayOfYearRange(range, year, dayOfYear))
                        {
                            applicable = true;
                            break;
                        }
                    }

                    if (!applicable)
                    {
                        goto CONTINUE_DATE_LOOP;
                    }
                }

                if (group.HasDaysOfYearExcluded)
                {
                    foreach (var range in group.DaysOfYearExcluded)
                    {
                        if (InDayOfYearRange(range, year, dayOfYear))
                        {
                            goto CONTINUE_DATE_LOOP;
                        }
                    }
                }

                // check if date is an applicable day of month
                if (group.HasDaysOfMonth)
                {
                    var applicable = false;
                    foreach (var range in group.DaysOfMonth)
                    {
                        if (InDayOfMonthRange(range, year, month, dayOfMonth))
                        {
                            applicable = true;
                            break;
                        }
                    }

                    if (!applicable)
                    {
                        goto CONTINUE_DATE_LOOP;
                    }
                }

                if (group.HasDaysOfMonthExcluded)
                {
                    foreach (var range in group.DaysOfMonthExcluded)
                    {
                        if (InDayOfMonthRange(range, year, month, dayOfMonth))
                        {
                            goto CONTINUE_DATE_LOOP;
                        }
                    }
                }

                // check if date is an applicable day of week
                if (group.HasDaysOfWeek && !InRule(7, group.DaysOfWeek, dayOfWeek))
                {
                    goto CONTINUE_DATE_LOOP;
                }

                if (group.HasDaysOfWeekExcluded && InRule(7, group.DaysOfWeekExcluded, dayOfWeek))
                {
                    goto CONTINUE_DATE_LOOP;
                }

                // if we've gotten this far, then today is an applicable day, let's keep going with hour checks
                var hourCount = after ? 24 - hour : hour + 1;
                for (; hourCount-- > 0; hour += inc, minute = initMinute, second = initSecond)
                {
                    if (group.HasHours && !InRule(24, group.Hours, hour))
                    {
                        continue;
                    }

                    if (group.HasHoursExcluded && InRule(24, group.HoursExcluded, hour))
                    {
                        continue;
                    }

                    // if we've gotten here, the date and hour are valid. Let's check for minutes
                    var minuteCount = after ? 60 - minute : minute + 1;
                    for (; minuteCount-- > 0; minute += inc, second = initSecond)
                    {
                        if (group.HasMinutes && !InRule(60, group.Minutes, minute))
                        {
                            continue;
                        }

                        if (group.HasMinutesExcluded && InRule(60, group.MinutesExcluded, minute))
                        {
                            continue;
                        }

                        // check for valid seconds
                        var secondCount = after ? 60 - second : second + 1;
                        for (; secondCount-- > 0; second += inc)
                        {
                            if (group.HasSeconds && !InRule(60, group.Seconds, second))
                            {
                                continue;
                            }

                            if (group.HasSecondsExcluded && InRule(60, group.SecondsExcluded, second))
                            {
                                continue;
                            }

                            // we've found our event
                            result = new DateTimeOffset(year, month, dayOfMonth, hour, minute, second, TimeSpan.Zero);
                            return(true);
                        }
                    }
                }

                CONTINUE_DATE_LOOP :;
            }

            // we didn't find an applicable date
            result = default(DateTimeOffset);
            return(false);
        }
예제 #55
0
 public abstract object Run(WorkFlowContext context, SearchMode mode, IVisitor visitor = null);
예제 #56
0
 // Token: 0x060027E6 RID: 10214 RVA: 0x00090CF4 File Offset: 0x0008EEF4
 protected ObjectLookupFieldAttribute(PrefabLookupKinds kinds, Type minimumType, SearchMode searchModeDefault, Type[] interfaceTypes)
 {
     this.Kinds       = kinds;
     this.MinimumType = minimumType;
     if (searchModeDefault != SearchMode.Default)
     {
         this.searchModeDefault = searchModeDefault;
     }
     this.RequiredInterfaces = (interfaceTypes ?? ObjectLookupFieldAttribute.Empty.TypeArray);
 }
예제 #57
0
 public override object Get(object key, SearchMode options)
 {
     throw new NotImplementedException();
 }
예제 #58
0
 internal Suggester(string name, SearchMode searchMode, IList <string> sourceFields)
 {
     Name         = name;
     SearchMode   = searchMode;
     SourceFields = sourceFields;
 }
예제 #59
0
        /// <summary>
        /// <para>Begins an asynchronous send to the search route.</para>
        /// </summary>
        /// <param name="path">The path in the user's Dropbox to search. Should probably be a
        /// folder.</param>
        /// <param name="query">The string to search for. The search string is split on spaces
        /// into multiple tokens. For file name searching, the last token is used for prefix
        /// matching (i.e. "bat c" matches "bat cave" but not "batman car").</param>
        /// <param name="start">The starting index within the search results (used for
        /// paging).</param>
        /// <param name="maxResults">The maximum number of search results to return.</param>
        /// <param name="mode">The search mode (filename, filename_and_content, or
        /// deleted_filename).</param>
        /// <param name="callback">The method to be called when the asynchronous send is
        /// completed.</param>
        /// <param name="callbackState">A user provided object that distinguished this send
        /// from other send requests.</param>
        /// <returns>An object that represents the asynchronous send request.</returns>
        public sys.IAsyncResult BeginSearch(string path,
                                            string query,
                                            ulong start = 0,
                                            ulong maxResults = 100,
                                            SearchMode mode = null,
                                            sys.AsyncCallback callback = null,
                                            object callbackState = null)
        {
            var searchArg = new SearchArg(path,
                                          query,
                                          start,
                                          maxResults,
                                          mode);

            return this.BeginSearch(searchArg, callback, callbackState);
        }
예제 #60
0
 public override int GetHashCode()
 {
     return(SearchMode.GetHashCode() ^ SeasonNumber.GetHashCode() ^ EpisodeNumber.GetHashCode());
 }