Example #1
1
        public int Calculate(IList<int> numbers, decimal currentSum, int globalMax)
        {
            int result = 0;
            decimal max = numbers.Count == 0 ? 1 : numbers[numbers.Count - 1];

            for (decimal i = max + 1; i <= globalMax; i++)
            {
                decimal sum = currentSum + values[(int)i];
                if (sum > half)
                    break;
                if (Math.Abs(sum-half)< 0.000000001m)
                {
                    foreach (var number in numbers.Concat(new int[] {(int)i}))
                    {
                        Console.Write(number.ToString()+",");
                    }
                    Console.Write("    "    +sum.ToString());
                    Console.WriteLine();
                    result++;
                    break;
                }

                if (i<globalMax && sum + sumOfValues[(int)i+1]< half)
                    break;

                List<int> newNumbers = new List<int>(numbers);
                newNumbers.Add((int)i);

                result += Calculate(newNumbers, sum, globalMax);
            }
            return result;
        }
Example #2
1
        public Connection(IMessageBus newMessageBus,
                          IJsonSerializer jsonSerializer,
                          string baseSignal,
                          string connectionId,
                          IList<string> signals,
                          IList<string> groups,
                          ITraceManager traceManager,
                          IAckHandler ackHandler,
                          IPerformanceCounterManager performanceCounterManager,
                          IProtectedData protectedData)
        {
            if (traceManager == null)
            {
                throw new ArgumentNullException("traceManager");
            }

            _bus = newMessageBus;
            _serializer = jsonSerializer;
            _baseSignal = baseSignal;
            _connectionId = connectionId;
            _signals = new List<string>(signals.Concat(groups));
            _groups = new DiffSet<string>(groups);
            _traceSource = traceManager["SignalR.Connection"];
            _ackHandler = ackHandler;
            _counters = performanceCounterManager;
            _protectedData = protectedData;
        }
Example #3
1
        public Connection(IMessageBus newMessageBus,
                          JsonSerializer jsonSerializer,
                          string baseSignal,
                          string connectionId,
                          IList<string> signals,
                          IList<string> groups,
                          ILoggerFactory loggerFactory,
                          IAckHandler ackHandler,
                          IPerformanceCounterManager performanceCounterManager,
                          IProtectedData protectedData,
                          IMemoryPool pool)
        {
            if (loggerFactory == null)
            {
                throw new ArgumentNullException("loggerFactory");
            }

            _bus = newMessageBus;
            _serializer = jsonSerializer;
            _baseSignal = baseSignal;
            _connectionId = connectionId;
            _signals = new List<string>(signals.Concat(groups));
            _groups = new DiffSet<string>(groups);
            _logger = loggerFactory.CreateLogger<Connection>();
            _ackHandler = ackHandler;
            _counters = performanceCounterManager;
            _protectedData = protectedData;
            _excludeMessage = m => ExcludeMessage(m);
            _pool = pool;
        }
 public ParseRelationOperation(IEnumerable<ParseObject> adds,
     IEnumerable<ParseObject> removes) {
   adds = adds ?? new ParseObject[0];
   removes = removes ?? new ParseObject[0];
   this.targetClassName = adds.Concat(removes).Select(o => o.ClassName).FirstOrDefault();
   this.adds = new ReadOnlyCollection<string>(IdsFromObjects(adds).ToList());
   this.removes = new ReadOnlyCollection<string>(IdsFromObjects(removes).ToList());
 }
Example #5
1
		private static bool CheckDigits (IList <int> digits, Tuple <int, int> factorsPair)
		{
			var allDigits = digits
				.Concat (factorsPair.Item1.GetDigits ())
				.Concat (factorsPair.Item2.GetDigits ())
				.ToList ();
			
			if (allDigits.Count != 9)
				return false;
			
			return nineDigits.SequenceEqual (
				allDigits.OrderBy (d => d));
		}
        public static IList<string> ProcessWatchers(this IBot bot, string repositoryName, IList<string> existingWatchers, IEnumerable<dynamic> watchers)
        {
            var currentWatchers = watchers.Select(c => c.login.ToString()).Cast<string>().ToList();
            var newWatchers = currentWatchers.Except(existingWatchers).ToList();
            foreach (var w in newWatchers)
            {
                bot.SayToAllRooms(string.Format("{0} is now watching {1}", w, repositoryName));
            }

            var noLongerWatching = existingWatchers.Except(currentWatchers).ToList();
            foreach (var w in noLongerWatching)
            {
                bot.SayToAllRooms(string.Format("{0} is no longer watching {1}", w, repositoryName));
            }

            return existingWatchers.Concat(newWatchers).Except(noLongerWatching).ToList();
        }
Example #7
1
        public IList<UserPostDto> GetPostsByInterests(IList<Interest> interests)
        {
            //get user interests
            //get sibling and parent interests
            var interestAndParentInterests = interests
                .Concat(interests.Select(x => x.ParentInterest))
                .Where(x => x != null)
                .Distinct()
                .ToList();

            var posts = _postRepository.GetPostsByInterestTypes(interestAndParentInterests).ToList();

            //get all media with any matching interests order by date desc limit by 100
            var recentPosts = posts.OrderByDescending(x => x.CreateDate).Take(200);

            /*
             * my thinking is take the last 100 because a user probably won't read past that..
             * if we only grab the first 10 then there is the problem that 11th might be extremely relevent
             * but shows up much later on cause it's
             * slightly older
             */

            return recentPosts.Select(
                post =>
                {
                    int rank = 0;

                    //we know the medium has a userInterest tied to it
                    if (interests.Contains(post.Interest))
                        rank = 10;
                    else if (post.Interest.ParentInterest != null && interestAndParentInterests.Contains(post.Interest.ParentInterest))
                        rank = 2;
                    else if (interestAndParentInterests.Contains(post.Interest))
                        rank = 1;

                    int daysSinceMediumCreated = (DateTime.UtcNow - post.CreateDate).Days;

                    rank -= daysSinceMediumCreated;

                    return new { Rank = rank, FeedItem = new UserPostDto(post) };
                }).OrderByDescending(x => x.Rank).Select(x => x.FeedItem).ToList();
        }
        private IList<DssExportHistory> GroupData(IList<LocationTransaction> locTrans, DssOutboundControl dssOutboundControl, DateTime effectiveDate)
        {
            #region 补充0成品工单
            var fgOrderDetIdList = locTrans
                 .Where(l => StringHelper.Eq(l.TransactionType, BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_RCT_WO))
                 .Select(l => l.OrderDetailId).Distinct().ToList();
            var rmOrderDetIdList = locTrans
                   .Where(l => StringHelper.Eq(l.TransactionType, BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_ISS_WO))
                   .Select(l => l.OrderDetailId).Distinct().ToList();

            var addList = rmOrderDetIdList.Except(fgOrderDetIdList).Distinct().ToList();

            #region 添加虚拟RCT-WO
            if (addList.Count > 0)
            {

                IList<LocationTransaction> virtualWOList = this.GetVirRctWo(addList);//GetVirtualRCTWO 修改为 GetVirRctWo
                if (virtualWOList.Count > 0)
                {
                    foreach (var virtualWO in virtualWOList)
                    {
                        virtualWO.TransactionType = BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_RCT_WO;
                        virtualWO.EffectiveDate = effectiveDate;
                        virtualWO.Qty = 0;
                    }
                    locTrans = locTrans.Concat(virtualWOList).ToList();
                }
            }
            #endregion
            #endregion

            #region Transformer
            var fgQuery = locTrans.Where(l => StringHelper.Eq(l.TransactionType, BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_RCT_WO)).ToList();
            var rmQuery = locTrans.Where(l => StringHelper.Eq(l.TransactionType, BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_ISS_WO)).ToList();

            log.Debug("Begin to group single data, count:" + fgQuery.Count);
            IList<DssExportHistory> dssExportHistoryList = this.GroupSingleDssExportHistory(fgQuery, rmQuery, dssOutboundControl, effectiveDate);
            #endregion

            return dssExportHistoryList;
        }
        private static void ParseParameters(IList<IWhere> wheres)
        {
            var index = 1;
            var list = new List<string>();

            var innerparams = wheres
                .Where(w => w.Parameter.Type == ParameterType.Query)
                .SelectMany(w => ((IAdfQuery) w.Parameter.Value).Wheres);

            // NULL and NOT NULL are rendered different and dont use a parameter
            var allWheres = wheres.Concat(innerparams).Where(w => w.Operator != OperatorType.IsNull && w.Operator != OperatorType.IsNotNull);

            foreach (var where in allWheres)
            {
                if (where.Parameter.Name.IsNullOrEmpty())
                {
                    where.Parameter.Name = where.Column.ColumnName;
                }

                if (list.Contains(where.Parameter.Name))
                {
                    where.Parameter.Name += index++;
                }

                list.Add(where.Parameter.Name);

                ApplyLike(where);
            }
        }
        public static IList<ParameterName> GenerateParameterNames(
            this SemanticModel semanticModel,
            IEnumerable<ArgumentSyntax> arguments,
            IList<string> reservedNames = null)
        {
            reservedNames = reservedNames ?? SpecializedCollections.EmptyList<string>();

            // We can't change the names of named parameters.  Any other names we're flexible on.
            var isFixed = reservedNames.Select(s => true).Concat(
                arguments.Select(a => a.NameColon != null)).ToList();

            var parameterNames = reservedNames.Concat(
                arguments.Select(semanticModel.GenerateNameForArgument)).ToList();

            return GenerateNames(reservedNames, isFixed, parameterNames);
        }
        private IEnumerable<IList<Color>> GetNextLayer(IList<Color> list)
        {
            var colors = new List<Color>() {
                Color.NotSet,
                Color.Blue,
                Color.Black,
                Color.Red,
                Color.White,
                Color.Yellow
            };

            foreach (var color in colors) {
                yield return list.Concat(new List<Color>() { color }).ToList();
            }
        }
Example #12
1
 private static IList<TAgents> SonAgentMethod(int id, APIDataDataContext db, IList<TAgents> agent)
 {
     var sonagents = (from c in db.TAgents where c.DirectAgentID == id select c).ToList();
     foreach (var item in sonagents)
     {
         agent = SonAgentMethod(item.ID, db, agent);
     }
     agent = agent.Concat(sonagents).ToList();
     return agent;
 }
Example #13
1
		private static BasicBlock InlineIR(this CALLInstruction call,
			IList<BasicBlockInstruction> preamble,
			BasicBlock backend,
			Dictionary<Subprogram, Dictionary<VirtualRegister, VirtualRegister>> inlineRegMaps)
		{
			Dictionary<VirtualRegister, VirtualRegister> inlineRegMap;
			if (!inlineRegMaps.TryGetValue(call.Target, out inlineRegMap))
			{
				inlineRegMap = call.Target.LocalVariables.Select(lv => 
					new KeyValuePair<VirtualRegister, VirtualRegister>(lv, new VirtualRegister(lv.UnderlyingType, lv.StateSpace))).
					ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
				inlineRegMaps.Add(call.Target, inlineRegMap);
			}
			inlineRegMap = inlineRegMap.Concat(call.Target.FormalParameters.Zip(call.Arguments,
				(formal, actual) => new KeyValuePair<VirtualRegister, VirtualRegister>(formal,
				(actual is VirtualRegister) ? (actual as VirtualRegister) : 
				(formal.StateSpace != StateSpaces.REG) ? new VirtualRegister(formal.UnderlyingType, formal.StateSpace) :
				new VirtualRegister(formal.DataType)))).
				ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
			
			Dictionary<BasicBlock, BasicBlock> cfgmap = call.Target.GetBasicBlocks().Select(bb => 
			{
				VirtualRegister flag = (bb.Trailer is JumpIfInstruction) ?
					(bb.Trailer as JumpIfInstruction).Flag.MapOperand(inlineRegMap) : null;
				
				ControlFlowInstruction trailer;
				
				switch (bb.Trailer.OpCode)
				{
				case IROpCodes.RET:
					trailer = new JMPInstruction() { Target = backend };
					break;
				case IROpCodes.JMP:
					trailer = new JMPInstruction();
					break;
				case IROpCodes.JT:
					trailer = new JTInstruction(flag);
					break;
				case IROpCodes.JF:
					trailer = new JFInstruction(flag);
					break;
				default:
					throw new NotSupportedException();
				}
				
				return new KeyValuePair<BasicBlock, BasicBlock>(bb,
					new BasicBlock(bb.Code.Select(bbi => bbi.MapInstruction(inlineRegMap)).ToList(), trailer));
				
			}).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
			
			foreach (KeyValuePair<BasicBlock, BasicBlock> bbmap in cfgmap)
			{
				if (bbmap.Key.Successor != null)
					bbmap.Value.Successor = cfgmap[bbmap.Key.Successor];
				if (bbmap.Key.Target != null)
					bbmap.Value.Target = cfgmap[bbmap.Key.Target];
			}
			
			BasicBlock root = cfgmap[call.Target.CFGRoot];
			return new BasicBlock(preamble.Concat(root.Code).ToList(), root.Trailer);
		}
Example #14
0
        public ScreenRecordForm( IPluginHost pluginHost )
            : base(pluginHost)
        {
            this.StickyWindow = new DroidExplorer.UI.StickyWindow ( this );
            CommonResolutions = GetCommonResolutions ( );
            InitializeComponent ( );

            var defaultFile = "screenrecord_{0}_{1}.mp4".With ( this.PluginHost.Device, DateTime.Now.ToString ( "yyyy-MM-dd-hh" ) );
            this.location.Text = "/sdcard/{0}".With ( defaultFile );

            var resolution = new VideoSize ( PluginHost.CommandRunner.GetScreenResolution ( ) );
            var sizes = CommonResolutions.Concat ( new List<VideoSize> { resolution } ).OrderBy ( x => x.Size.Width ).Select ( x => x ).ToList ( );
            resolutionList.DataSource = sizes;
            resolutionList.DisplayMember = "Display";
            resolutionList.ValueMember = "Size";
            resolutionList.SelectedItem = resolution;

            rotateList.DataSource = GetRotateArgumentsList ( );
            rotateList.DisplayMember = "Display";
            rotateList.ValueMember = "Arguments";

            var bitrates = new List<BitRate> ( );

            for ( int i = 1; i < 25; i++ ) {
                bitrates.Add ( new BitRate ( i ) );
            }

            bitrateList.DataSource = bitrates;
            bitrateList.DisplayMember = "Display";
            bitrateList.ValueMember = "Value";
            bitrateList.SelectedItem = bitrates.Single ( x => x.Mbps == 4 );
            var ts = new TimeSpan ( 0, 0, 0, timeLimit.Value, 0 );
            displayTime.Text = ts.ToString ( );
        }
Example #15
0
        private static IList<int> Merge2ListRecurseImple(IList<int> thisList, IList<int> thatList,
                                                          int thisCounter, int thatCounter,
                                                          int thisLength, int thatLength,
                                                          IList<int> result) 
        {
            Contract.Requires(thisList != null && thatList != null);
            //Base Case
            //Do nothing when reaches end of lists
            if (thisCounter == thisLength
                && thatCounter == thatLength)
                return result;

            if (thisCounter < thisLength && thatCounter < thatLength)
            {
                if (thisList[thisCounter] > thatList[thatCounter])
                {
                    result.Add(thatList[thatCounter]);
                    ++thatCounter;
                }
                else
                {
                    result.Add(thisList[thisCounter]);
                    ++thisCounter;
                }
            }

            if (thisCounter == thisLength)
            {
                result = result.Concat(thatList).ToList();
                return result;
            }
            if (thatCounter == thatLength)
            {
                result = result.Concat(thisList).ToList();
                return result;
            }
            Contract.Ensures(result != null);
            return Merge2ListRecurseImple(thisList, thatList, thisCounter, thatCounter, thisLength, thatLength, result);
        }
        private static IList<string> OrderScripts(IList<string> dependencyScripts, IEnumerable<string> originalScripts)
        {
            var scripts = dependencyScripts.Concat(originalScripts).Distinct().ToList();

            if (scripts.Any(x => x.Contains("sf-list-selector")))
            {
                scripts.Insert(0, "client-components/selectors/common/sf-list-selector.js");
            }

            scripts.Insert(0, "client-components/selectors/common/sf-selectors.js");
            scripts.Insert(0, "client-components/selectors/common/sf-services.js");

            if (scripts.Any(x => x.Contains("sf-fields")))
            {
                scripts.Insert(0, "client-components/fields/sf-fields.js");
            }

            var mvcScripts = scripts.Where(x => x.IndexOf("Mvc/Scripts/", 0, StringComparison.Ordinal) >= 0).ToList();
            foreach (var mvcScript in mvcScripts)
            {
                scripts.Insert(0, mvcScript);
            }

            var angularScripts = scripts.Where(x => x.IndexOf("angular", 0, StringComparison.OrdinalIgnoreCase) >= 0).ToList();
            foreach (var angularScript in angularScripts)
            {
                scripts.Insert(0, angularScript);
            }

            return scripts.Distinct().ToList();
        }
        /// <summary>
        /// Returns the test counts.
        /// </summary>
        private static IList<BuildTestCount> GetTestCounts(
            IList<BuildTestCount> allBuildTestCounts)
        {
            if (allBuildTestCounts.Count == 1)
            {
                // The charting library does not work well with only one point.
                // So we'll give it two identical points.

                allBuildTestCounts = allBuildTestCounts
                    .Concat(allBuildTestCounts)
                    .ToList();
            }

            return allBuildTestCounts;
        }
 public Neighbour Choose(IList<Neighbour> neighbours, Neighbour self) {
     LogFacade.Instance.LogDebug("Choosing a master, candidates = " + (neighbours.IsNull() ? 0 : neighbours.Count));
     var n = neighbours.IsNull() ? null : neighbours.Concat(new [] { self }).Where(_ => !_.InEligibleForElection).Aggregate((i, j) => i.AbsoluteBootTime < j.AbsoluteBootTime ? i : j);
     LogFacade.Instance.LogInfo("Candidate selected: " + (n.IsNull() ? "None - thus self" : n.Name));
     return n;
 }
 /// <summary>
 /// Continue the upload functionality with setting of properties
 /// </summary>
 /// <param name="request">Current Http request object</param>
 /// <param name="refreshToken">Refresh token</param>
 /// <param name="environment">Flag to determine on-line or on-premise deployment</param>
 /// <param name="upload">Object for current file</param>
 /// <param name="fileExtension">Extension of current file</param>
 /// <param name="originalName">Original name of the file</param>
 /// <param name="listResponse">List of responses</param>
 /// <param name="folderName">Path of the folder</param>
 /// <param name="fileName">Name of the file</param>
 /// <param name="clientContext">SP client context</param>
 /// <param name="folder">Name of the folder</param>
 /// <param name="documentLibraryName">Name of the document library</param>
 /// <returns>list of all the responses being sent</returns>
 private static IList<string> SetDocumentProperties(HttpRequest request, string refreshToken, HttpPostedFile upload, string fileExtension, string originalName, IList<string> listResponse, string folderName, string fileName, ClientContext clientContext, string folder, string documentLibraryName)
 {
     Dictionary<string, string> mailProperties = ContinueUpload(request, refreshToken, upload, fileExtension);
     //setting original name property for attachment
     if (string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailOriginalName]))
     {
         mailProperties[ConstantStrings.MailOriginalName] = originalName;
     }
     return listResponse = listResponse.Concat(UploadDocument(folderName, upload, fileName, mailProperties, clientContext, folder, documentLibraryName)).ToList();
 }
Example #20
0
 public LevelsEntitiesController()
 {
     Entities = new List<LevelsEntity>();
     for (int i = 1; i <= 10; i++)
     {
         if (i % 2 == 1)
         {
             var newEntity = new LevelsEntity
             {
                 ID = i,
                 Name = "Name " + i,
                 Parent = Entities.LastOrDefault(),
                 BaseEntities = Entities.Concat(new[]
                     {
                         new LevelsBaseEntity
                         {
                             ID = i + 10,
                             Name = "Name " + (i + 10)
                         }
                     }).ToArray(),
                 DerivedAncestors = Entities.OfType<LevelsDerivedEntity>().ToArray()
             };
             Entities.Add(newEntity);
         }
         else
         {
             var newEntity = new LevelsDerivedEntity
             {
                 ID = i,
                 Name = "Name " + i,
                 DerivedName = "DerivedName " + i,
                 Parent = Entities.LastOrDefault(),
                 BaseEntities = Entities.Concat(new[]
                     {
                         new LevelsBaseEntity
                         {
                             ID = i + 10,
                             Name = "Name " + (i + 10)
                         }
                     }).ToArray(),
                 DerivedAncestors = Entities.OfType<LevelsDerivedEntity>().ToArray(),
                 AncestorsInDerivedEntity = Entities.ToArray()
             };
             Entities.Add(newEntity);
         }
     }
     Entities[8].Parent = Entities[9];
     Entities[1].DerivedAncestors = new LevelsDerivedEntity[] { (LevelsDerivedEntity)Entities[3] }; 
 }
Example #21
0
        private int CalculateRequiredDronesForDefense(int zoneId, IList<DroneWithDistance> myDrones, IEnumerable<DroneWithDistance> enemyDroneSquad, out int nbrTurnsToFail)
        {
            _log.WriteLine("Defense of zone {0}", zoneId);
            _log.WriteLine("My drones: {0}", string.Join(",", myDrones.Select(d => d.NbrTurns).OrderBy(n => n)));
            _log.WriteLine("Enemies:   {0}", string.Join(",", enemyDroneSquad.Select(d => d.NbrTurns).OrderBy(n => n)));

            var myTeamId = myDrones[0].Drone.TeamId;
            int nbrAllies = 0, nbrEnemies = 0;
            nbrTurnsToFail = nbrTurnsConsidered;

            var sortedDroneWaves = myDrones.Concat(enemyDroneSquad)
                .ToLookup(d => d.NbrTurns)
                .OrderBy(w => w.Key);

            foreach(var wave in sortedDroneWaves)
            {
                if(wave.Key > nbrTurnsConsidered)
                    break;

                int alliesBackup = 0;
                int enemiesBackup = 0;
                foreach(var drone in wave)
                {
                    if(drone.Drone.TeamId == myTeamId)
                        alliesBackup++;
                    else
                        enemiesBackup++;
                }

                if(nbrAllies + alliesBackup < nbrEnemies + enemiesBackup)
                {
                    nbrTurnsToFail = wave.Key;
                    return nbrAllies;
                }

                nbrAllies += alliesBackup;
                nbrEnemies += enemiesBackup;
            }

            return nbrEnemies;
        }
            /// <summary>
            /// Prepare model
            /// </summary>
            /// <param name="alreadyFilteredSpecOptionIds">IDs of already filtered specification options</param>
            /// <param name="filterableSpecificationAttributeOptionIds">IDs of filterable specification options</param>
            /// <param name="specificationAttributeService"></param>
            /// <param name="webHelper">Web helper</param>
            /// <param name="workContext">Work context</param>
            /// <param name="cacheManager">Cache manager</param>
            public virtual void PrepareSpecsFilters(IList<int> alreadyFilteredSpecOptionIds,
                int[] filterableSpecificationAttributeOptionIds,
                ISpecificationAttributeService specificationAttributeService, 
                IWebHelper webHelper, IWorkContext workContext, ICacheManager cacheManager)
            {
                Enabled = false;
                var optionIds = filterableSpecificationAttributeOptionIds != null
                    ? string.Join(",", filterableSpecificationAttributeOptionIds) : string.Empty;
                var cacheKey = string.Format(ModelCacheEventConsumer.SPECS_FILTER_MODEL_KEY, optionIds, workContext.WorkingLanguage.Id);

                var allOptions = specificationAttributeService.GetSpecificationAttributeOptionsByIds(filterableSpecificationAttributeOptionIds);
                var allFilters = cacheManager.Get(cacheKey, () => allOptions.Select(sao =>
                    new SpecificationAttributeOptionFilter
                    {
                        SpecificationAttributeId = sao.SpecificationAttribute.Id,
                        SpecificationAttributeName = sao.SpecificationAttribute.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                        SpecificationAttributeDisplayOrder = sao.SpecificationAttribute.DisplayOrder,
                        SpecificationAttributeOptionId = sao.Id,
                        SpecificationAttributeOptionName = sao.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                        SpecificationAttributeOptionColorRgb = sao.ColorSquaresRgb,
                        SpecificationAttributeOptionDisplayOrder = sao.DisplayOrder
                    }).ToList());

                if (!allFilters.Any())
                    return;

                //sort loaded options
                allFilters = allFilters.OrderBy(saof => saof.SpecificationAttributeDisplayOrder)
                    .ThenBy(saof => saof.SpecificationAttributeName)
                    .ThenBy(saof => saof.SpecificationAttributeOptionDisplayOrder)
                    .ThenBy(saof => saof.SpecificationAttributeOptionName).ToList();

                //prepare the model properties
                Enabled = true;
                var removeFilterUrl = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM);
                RemoveFilterUrl = ExcludeQueryStringParams(removeFilterUrl, webHelper);

                //get already filtered specification options
                var alreadyFilteredOptions = allFilters.Where(x => alreadyFilteredSpecOptionIds.Contains(x.SpecificationAttributeOptionId));
                AlreadyFilteredItems = alreadyFilteredOptions.Select(x =>
                    new SpecificationFilterItem
                    {
                        SpecificationAttributeName = x.SpecificationAttributeName,
                        SpecificationAttributeOptionName = x.SpecificationAttributeOptionName,
                        SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb
                    }).ToList();

                //get not filtered specification options
                NotFilteredItems = allFilters.Except(alreadyFilteredOptions).Select(x =>
                {
                    //filter URL
                    var alreadyFiltered = alreadyFilteredSpecOptionIds.Concat(new List<int> { x.SpecificationAttributeOptionId });
                    var queryString = string.Format("{0}={1}", QUERYSTRINGPARAM, GenerateFilteredSpecQueryParam(alreadyFiltered.ToList()));
                    var filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), queryString, null);

                    return new SpecificationFilterItem()
                    {
                        SpecificationAttributeName = x.SpecificationAttributeName,
                        SpecificationAttributeOptionName = x.SpecificationAttributeOptionName,
                        SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb,
                        FilterUrl = ExcludeQueryStringParams(filterUrl, webHelper)
                    };
                }).ToList();
            }
        protected SignatureHelpItem CreateItem(
            ISymbol orderSymbol,
            SemanticModel semanticModel,
            int position,
            ISymbolDisplayService symbolDisplayService,
            IAnonymousTypeDisplayService anonymousTypeDisplayService,
            bool isVariadic,
            Func<CancellationToken, IEnumerable<TaggedText>> documentationFactory,
            IList<SymbolDisplayPart> prefixParts,
            IList<SymbolDisplayPart> separatorParts,
            IList<SymbolDisplayPart> suffixParts,
            IList<SignatureHelpSymbolParameter> parameters,
            IList<SymbolDisplayPart> descriptionParts = null)
        {
            prefixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(prefixParts, semanticModel, position, symbolDisplayService);
            separatorParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(separatorParts, semanticModel, position, symbolDisplayService);
            suffixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(suffixParts, semanticModel, position, symbolDisplayService);
            parameters = parameters.Select(p => InlineDelegateAnonymousTypes(p, semanticModel, position, symbolDisplayService, anonymousTypeDisplayService)).ToList();
            descriptionParts = descriptionParts == null
                ? SpecializedCollections.EmptyList<SymbolDisplayPart>()
                : descriptionParts;

            var allParts = prefixParts.Concat(separatorParts)
                                      .Concat(suffixParts)
                                      .Concat(parameters.SelectMany(p => p.GetAllParts()))
                                      .Concat(descriptionParts);

            var directAnonymousTypeReferences =
                from part in allParts
                where part.Symbol.IsNormalAnonymousType()
                select (INamedTypeSymbol)part.Symbol;

            var info = anonymousTypeDisplayService.GetNormalAnonymousTypeDisplayInfo(
                orderSymbol, directAnonymousTypeReferences, semanticModel, position, symbolDisplayService);

            if (info.AnonymousTypesParts.Count > 0)
            {
                var anonymousTypeParts = new List<SymbolDisplayPart>
                {
                    new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, "\r\n\r\n")
                };

                anonymousTypeParts.AddRange(info.AnonymousTypesParts);

                return new SymbolKeySignatureHelpItem(
                    orderSymbol,
                    isVariadic,
                    documentationFactory,
                    info.ReplaceAnonymousTypes(prefixParts).ToTaggedText(),
                    info.ReplaceAnonymousTypes(separatorParts).ToTaggedText(),
                    info.ReplaceAnonymousTypes(suffixParts).ToTaggedText(),
                    parameters.Select(p => ReplaceAnonymousTypes(p, info)).Select(p => (SignatureHelpParameter)p),
                    anonymousTypeParts.ToTaggedText());
            }

            return new SymbolKeySignatureHelpItem(
                orderSymbol,
                isVariadic,
                documentationFactory,
                prefixParts.ToTaggedText(),
                separatorParts.ToTaggedText(),
                suffixParts.ToTaggedText(),
                parameters.Select(p => (SignatureHelpParameter)p),
                descriptionParts.ToTaggedText());
        }
		public static IList<string> GenerateParameterNames(
			this SemanticModel semanticModel,
			IEnumerable<AttributeArgumentSyntax> arguments,
			IList<string> reservedNames = null)
		{
			reservedNames = reservedNames ?? SpecializedCollections.EmptyList<string>();

			// We can't change the names of named parameters.  Any other names we're flexible on.
			var isFixed = reservedNames.Select(s => true).Concat(
				arguments.Select(a => a.NameEquals != null)).ToList();

			var parameterNames = reservedNames.Concat(
				arguments.Select(a => semanticModel.GenerateNameForArgument(a))).ToList();

			return NameGenerator.EnsureUniqueness(parameterNames, isFixed).Skip(reservedNames.Count).ToList();
		}
Example #25
0
 private IBuilder MergeSteps(IList<IBuilder> additionalSteps, MSBuildRunner msbuild, IEnumerable<Project> projects)
 {
     var prjs = projects.ToArray();
     if (additionalSteps.Count > 0)
     {
         return coreBuilderFactory.CreateMergingBuilder(additionalSteps.Concat(new[] { msbuild }), new ProjectBuilderTag(String.Format("Runtime deps with project builders for {0}", String.Join(", ", prjs.Select(p => p.Name))), prjs));
     }
     else
     {
         return msbuild;
     }
 }