public Task BulkSend(IEnumerable<Marble> items)
 {
     _marbles.AddRange(items);
     if (items.LastOrDefault()?.Kind == NotificationKind.OnCompleted)
         _completion.SetResult(null);
     else if (items.LastOrDefault()?.Kind == NotificationKind.OnError)
         _completion.SetException(new Exception(items.Last().Value.ToString()));
     return Task.CompletedTask;
 }
Example #2
0
		public bool Process(ILogger logger, IEnumerable<string> args, MetaProjectPersistence metaProject, ComponentsList components, string packagesOutputDirectory)
		{
			// BIG TODO: reengineer command parsing
			var componentNamePattern = args.LastOrDefault();
			if (componentNamePattern == null || componentNamePattern.StartsWith("-") || componentNamePattern.EndsWith("\"")) {
				logger.Error("No component pattern specified");
				return true;
			}
			string tags = args.ParseStringParameter("tags");
			string licenseUrl = args.ParseStringParameter("licenseUrl");
			string projectUrl = args.ParseStringParameter("projectUrl");
			string iconUrl = args.ParseStringParameter("iconUrl");
			string copyright = args.ParseStringParameter("copyright");
			bool requireLicenseAcceptance = args.Contains("-r");
			if (licenseUrl == null && requireLicenseAcceptance) {
				logger.Error("Requiring license acceptance demands a license url");
				return true;
			}
			var specificComponent = components.FindComponent<IProject>(componentNamePattern, c => c.CanBecomeNugget);
			if (specificComponent == null)
				return true;
			if (specificComponent.PromoteToNuget(logger, packagesOutputDirectory, tags,
				licenseUrl, projectUrl, iconUrl, copyright, requireLicenseAcceptance) != null)
				ScanCommand.Rescan(logger, metaProject, components);
			return true;
		}
        public async Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> events)
        {
            // Workaround for event hub sending null on timeout
            events = events ?? Enumerable.Empty<EventData>();

            foreach (var eventData in events)
            {
                var updateTemperatureEvent = JsonConvert.DeserializeObject<UpdateTemperatureEvent>(Encoding.UTF8.GetString(eventData.GetBytes()));
                eventData.Properties["BuildingId"] = _buildingLookupService.GetBuildingId(updateTemperatureEvent.DeviceId);
            }

            if(!await _elasticSearchWriter.WriteAsync(events.ToList(), _token).ConfigureAwait(false))
            {
                return;
            }

            try
            {
                EventData checkpointEventData = events.LastOrDefault();

                await context.CheckpointAsync(checkpointEventData);

                WarmStorageEventSource.Log.CheckpointCompleted(ProcessorName, _eventHubName, context.Lease.PartitionId, checkpointEventData.Offset);
            }
            catch (Exception ex)
            {
                if (!(ex is StorageException || ex is LeaseLostException))
                {
                    throw;
                }

                WarmStorageEventSource.Log.UnableToCheckpoint(ex, ProcessorName, _eventHubName, context.Lease.PartitionId);
            }
        }
Example #4
0
		public bool Process(ILogger logger, IEnumerable<string> args, MetaProjectPersistence metaProject, ComponentsList components, string packagesOutputDirectory)
		{
			var nugetNamePattern = args.FirstOrDefault();
			if (nugetNamePattern == null || nugetNamePattern.StartsWith("-") || nugetNamePattern.EndsWith("\"")) {
				logger.Error("No nuget pattern specified");
				return true;
			}
			var nugetComponent = components.FindComponent<INugetSpec>(nugetNamePattern);
			if (nugetComponent == null)
				return true;
			logger.Info("== Nuget to add: {0}", nugetComponent);
			var componentNamePattern = args.LastOrDefault();
			if (componentNamePattern == null || componentNamePattern.StartsWith("-") || componentNamePattern.EndsWith("\"")) {
				logger.Error("No component pattern specified");
				return true;
			}
			var specificComponent = components.FindComponent<IProject>(componentNamePattern);
			if (specificComponent == null)
				return true;
			logger.Info("== Component to reference nuget: {0}", specificComponent);
			if (specificComponent == nugetComponent) {
				logger.Error("Nuget can't be added to itself");
				return true;
			}
			specificComponent.AddNuget(logger, nugetComponent, components, packagesOutputDirectory);
			return true;
		}
        public override Character GetTarget(IEnumerable<Character> targetsList)
        {
            return targetsList.LastOrDefault(character => (character.Team != this.Team && character.IsAlive));

            //var target = targetsList.LastOrDefault(character => (character.Team != this.Team && character.IsAlive));
            //return target;
        }
        public async Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> events)
        {
            // Workaround for event hub sending null on timeout
            events = events ?? Enumerable.Empty<EventData>();

            if(!await _elasticSearchWriter.WriteAsync(events.ToList(), _token).ConfigureAwait(false))
            {
                return;
            }

            try
            {
                EventData checkpointEventData = events.LastOrDefault();

                await context.CheckpointAsync(checkpointEventData);

                WarmStorageEventSource.Log.CheckpointCompleted(ProcessorName, _eventHubName, context.Lease.PartitionId, checkpointEventData.Offset);
            }
            catch (Exception ex)
            {
                if (!(ex is StorageException || ex is LeaseLostException))
                {
                    throw;
                }

                WarmStorageEventSource.Log.UnableToCheckpoint(ex, ProcessorName, _eventHubName, context.Lease.PartitionId);
            }
        }
Example #7
0
        public override int DetermineNodeId(IEnumerable <int> trail)
        {
            int nodeId = trail.LastOrDefault();

            nodeId = Helper.Reverse(nodeId);

            return nodeId;
        }
Example #8
0
        /// <summary>
        /// Filter for the last element in the selection set
        /// </summary>
        ///
        /// <param name="selection">
        /// The sequence of elements prior to this filter being applied.
        /// </param>
        ///
        /// <returns>
        /// The last element in the selection.
        /// </returns>

        public IEnumerable<IDomObject> Filter(IEnumerable<IDomObject> selection)
        {
            var last = selection.LastOrDefault();
            if (last != null)
            {
                yield return last;
            } 
        }
        public string MatchesConstraints(IEnumerable<string> packageVersions, string versionConstraint,
            string branch = null) {
            var doVersion = !string.IsNullOrWhiteSpace(versionConstraint);
            var doBranch = !string.IsNullOrWhiteSpace(branch);
            packageVersions = packageVersions.OrderBy(x => new SpecificVersion("x", x).Version);

            if (doBranch) {
                return doVersion
                    ? packageVersions.LastOrDefault(
                        x =>
                            x.EndsWith("-" + branch) &&
                            MatchesVersionConstraint(x.Split('-').First(), versionConstraint))
                    : packageVersions.LastOrDefault(x => x.EndsWith("-" + branch));
            }

            return doVersion
                ? packageVersions.LastOrDefault(x => MatchesVersionConstraint(x.Split('-').First(), versionConstraint))
                : null;
        }
Example #10
0
 private static IEnumerable<string> GetNodes(string id, IEnumerable<string[]> lines)
 {
     var line = lines.LastOrDefault(l => l[0] == id);
     if (line == null)
     {
         return new[] { "_" };
     }
     var newId = line[3];
     return (new[] { id }).Union(GetNodes(newId, lines));
 }
        public static IEnumerable<SortingInfo> AddRequiredSort(IEnumerable<SortingInfo> sort, IEnumerable<string> requiredSelectors) {
            sort = sort ?? new SortingInfo[0];
            requiredSelectors = requiredSelectors.Except(sort.Select(i => i.Selector));

            var desc = sort.LastOrDefault()?.Desc;

            return sort.Concat(requiredSelectors.Select(i => new SortingInfo {
                Selector = i,
                Desc = desc != null && desc.Value
            }));
        }
Example #12
0
        public void LoadsFromHistory(IEnumerable<Event> history)
        {
            foreach (var e in history)
            {
                ApplyChange(e, false);
            }

            var lastEvent = history.LastOrDefault();
            if (lastEvent != null)
            {
                Version = lastEvent.Version;
            }
        }
Example #13
0
		public override IEnumerable<CompletionItem> GetClasses(IEnumerable<string> path, Func<Type, bool> filter)
		{
			var prefixWithColon = PrefixWithColon;

			string contentProperty;
			var nodeType = GetNodeType(path.LastOrDefault(), out contentProperty);
			var contentType = GetContentType(nodeType, contentProperty);

			var types = GetExportedTypes();
			if (filter != null)
			{
				foreach (var result in types.Where(filter))
				{
					// special case, don't allow windows as a child control
					if (contentType != null
					    && typeof(Window).IsAssignableFrom(result))
						continue;
						

					yield return new CompletionItem
					{ 
						Name = prefixWithColon + result.Name, 
						Description = XmlComments.GetSummary(result),
						Type = CompletionType.Class
					}; 
				}
			}

			if (contentType != null 
				&& !contentType.IsAbstract 
				&& !types.Contains(contentType)
				&& contentType.Assembly == Assembly)
				yield return new CompletionItem
				{ 
					Name = prefixWithColon + contentType.Name, 
					Description = XmlComments.GetSummary(contentType),
					Type = CompletionType.Class
				}; 
			if (nodeType != null)
			{
				yield return new CompletionItem
				{
					Name = prefixWithColon + nodeType.Name + ".",
					Description = "Add a property tag",
					Type = CompletionType.Property
				};
			}

		}
		public string GetUrlUsingCategoryPathOrCanonical(IProduct product, IEnumerable<ICategory> categoryPath)
		{
			var category = categoryPath.LastOrDefault();
			if (category != null && product.Categories.Any(c => c.Id == category.Id))
			{
				return _categoryCatalogUrlService.GetUrlForPath(categoryPath) + "/" + product.UrlName;
			}
			
			category = product.Categories.FirstOrDefault();

			// todo: products can get their own url using storeUrl/productUrlName, but resolving and name conflicts need to be fixed
			if (category == null)
			{
				return product.UrlName;
			}

			return _categoryCatalogUrlService.GetCanonicalUrl(category) + "/" + product.UrlName;
		}
Example #15
0
		public override Func<Type, bool> GetFilter(IEnumerable<string> path)
		{
			string propertyName;
			var nodeType = GetNodeType(path.LastOrDefault(), out propertyName);
			var contentType = GetContentType(nodeType, propertyName);
			if (contentType != null)
			{
				var converter = TypeDescriptor.GetConverter(contentType);
				if (converter != null)
				{
					return t => contentType.IsAssignableFrom(t) || converter.CanConvertFrom(t);
				}
				else
				{
					return contentType.IsAssignableFrom;
				}
			}
			return null;
		}
Example #16
0
        private void UpdateThumbnails(IEnumerable<int> selection, bool scrollToSelection)
        {
            UpdateThumbnails();
            SelectedIndices = selection;

            // We would like to maintain the current scroll if scrollToSelection is false, but that's not easy with ListView
            // In the meantime just scroll to selection anyway (the alternative is to always pop to the top)
            // TODO: Rewrite ThumbnailList.UpdateImages to detect and perform incremental updates

            // Scroll to selection
            thumbnailList1.EnsureVisible(SelectedIndices.LastOrDefault());
            thumbnailList1.EnsureVisible(SelectedIndices.FirstOrDefault());
        }
        /// <summary>
        /// Transform an IEnumerable of <see cref="HttpMessageHandler"/>s into
        /// a chain of <see cref="HttpMessageHandler"/>s.
        /// </summary>
        /// <param name="handlers">
        /// Chain of <see cref="HttpMessageHandler" /> instances. 
        /// All but the last should be <see cref="DelegatingHandler"/>s. 
        /// </param>
        /// <returns>A chain of <see cref="HttpMessageHandler"/>s</returns>
        private static HttpMessageHandler CreatePipeline(IEnumerable<HttpMessageHandler> handlers)
        {
            HttpMessageHandler pipeline = handlers.LastOrDefault() ?? DefaultHandlerFactory();
            DelegatingHandler dHandler = pipeline as DelegatingHandler;
            if (dHandler != null)
            {
                dHandler.InnerHandler = DefaultHandlerFactory();
                pipeline = dHandler;
            }

            // Wire handlers up in reverse order
            IEnumerable<HttpMessageHandler> reversedHandlers = handlers.Reverse().Skip(1);
            foreach (HttpMessageHandler handler in reversedHandlers)
            {
                dHandler = handler as DelegatingHandler;
                if (dHandler == null)
                {
                    throw new ArgumentException(
                        string.Format(
                        "All message handlers except the last must be of the type '{0}'",
                        typeof(DelegatingHandler).Name));
                }

                dHandler.InnerHandler = pipeline;
                pipeline = dHandler;
            }

            return pipeline;
        }
Example #18
0
 public override Character GetTarget(IEnumerable<Character> targetsList)
 {
     Character target = targetsList.LastOrDefault(t => t.IsAlive && t.Team != this.Team);
     return target;
 }
Example #19
0
 public override Character GetTarget(IEnumerable<Character> targetsList)
 {
     var target = targetsList.LastOrDefault(s => s.Team != this.Team && s.IsAlive);
     return target;
 }
        internal static void Replace(BubbleGroup group, IEnumerable<VisualBubble> bubbles)
        {
            var unifiedGroup = @group as UnifiedBubbleGroup;
            if (unifiedGroup != null)
            {
                foreach (var innerGroup in unifiedGroup.Groups)
                {
                    Replace(innerGroup, bubbles);
                }
            }

            for (int i = 0; i < @group.Bubbles.Count; i++)
            {
                var bubble = @group.Bubbles[i];
                var bubbleReplacement = bubbles.LastOrDefault(x => x.ID == bubble.ID);
                if (bubbleReplacement != null)
                {
                    @group.Bubbles.RemoveAt(i);
                    @group.Bubbles.Insert(i, bubbleReplacement);
                }
            }
        }
 /// <summary>
 /// Return all position-type matches. These are selectors that are keyed to the position within the selection
 /// set itself.
 /// </summary>
 /// <param name="list"></param>
 /// <param name="selector"></param>
 /// <returns></returns>
 protected IEnumerable<IDomObject> GetResultPositionMatches(IEnumerable<IDomObject> list, Selector selector)
 {
     switch (selector.PositionType)
     {
         case PositionType.First:
             IDomObject first = list.FirstOrDefault();
             if (first != null)
             {
                 yield return first;
             }
             break;
         case PositionType.Last:
             IDomObject last = list.LastOrDefault();
             if (last != null)
             {
                 yield return last;
             }
             break;
         case PositionType.IndexEquals:
             int critIndex = selector.PositionIndex;
             if (critIndex < 0)
             {
                 critIndex = list.Count() + critIndex;
             }
             bool ok = true;
             IEnumerator<IDomObject> enumerator = list.GetEnumerator();
             for (int i = 0; i <= critIndex && ok; i++)
             {
                 ok = enumerator.MoveNext();
             }
             if (ok)
             {
                 yield return enumerator.Current;
             }
             else
             {
                 yield break;
             }
             break;
         case PositionType.IndexGreaterThan:
             int index = 0;
             foreach (IDomObject obj in list)
             {
                 if (index++ > selector.PositionIndex)
                 {
                     yield return obj;
                 }
             }
             break;
         case PositionType.IndexLessThan:
             int indexLess = 0;
             foreach (IDomObject obj in list)
             {
                 if (indexLess++ < selector.PositionIndex)
                 {
                     yield return obj;
                 }
                 else
                 {
                     break;
                 }
             }
             break;
     }
     yield break;
 }
 public override Character GetTarget(IEnumerable<Character> targetsList)
 {
     return targetsList.LastOrDefault(c => c.IsAlive && c.Team != this.Team);
 }
 private static string CreateRangeString(int key, IEnumerable<int> ranges)
 {
     return ranges.LastOrDefault(x => x < key) + " to " + (key - 1);
 }
Example #24
0
        void CheckSelectionInt(IEnumerable<Slide> slides)
        {
            if (!_inited) return;
            //check if Slides must be pre-chached
            if (slides.Count() > 0)
            {
                Slide CurrentSlide = slides.LastOrDefault();
                if (CurrentSlide != null)
                {
                    PresentationController.Instance.LoadSlide(CurrentSlide);
                    PresentationController.Instance.CanSelectNextSlide = this.CanSelectNextSlide(CurrentSlide);
                    PresentationController.Instance.CanSelectPrevSlide = this.CanSelectPrevSlide(CurrentSlide);
                }
            }
            else
            {
                PresentationController.Instance.CanSelectNextSlide = false;
                PresentationController.Instance.CanSelectPrevSlide = false;
            }

            if (OnCheckSelection != null)
                OnCheckSelection(this.SelectionList);

            PresentationController.Instance.SendSelectionChanged(slides);
            (Viewer as Control).Invalidate();
        }
Example #25
0
 public PluginLoaderException(string message, IEnumerable<Exception> failures)
     : base(message, failures.LastOrDefault())
 {
     InnerExceptions = failures;
 }
        private static bool ExistsSymbol(int code, IEnumerable<Tuple<int, int>> existingSymbolList)
        {
            var smallerOrLesserEntry = existingSymbolList.LastOrDefault(x => x.Item1 <= code);

            if (smallerOrLesserEntry != null)
            {
                var firstValue = smallerOrLesserEntry.Item1;
                var lastValue = firstValue + smallerOrLesserEntry.Item2;

                return code >= firstValue && code < lastValue;
            }
            return false;
        }
			private void RenderSitemapNodes(HtmlTextWriter writer, IEnumerable<Zongsoft.Plugins.PluginTreeNode> nodes)
			{
				if(nodes == null)
					return;

				var last = nodes.LastOrDefault();

				foreach(var node in nodes)
				{
					var treeNode = node.UnwrapValue<Controls.TreeViewNode>(Zongsoft.Plugins.ObtainMode.Auto, this, null);

					if(treeNode != null)
					{
						//生成<dt>开始元素
						writer.RenderBeginTag(HtmlTextWriterTag.Dt);

						if(node == last)
						{
							writer.WriteEncodedText(treeNode.Text);
						}
						else
						{
							writer.AddAttribute(HtmlTextWriterAttribute.Href, string.IsNullOrWhiteSpace(treeNode.NavigateUrl) ? "#" : treeNode.NavigateUrl);
							writer.AddAttribute(HtmlTextWriterAttribute.Alt, treeNode.ToolTip);
							writer.RenderBeginTag(HtmlTextWriterTag.A);
							writer.WriteEncodedText(treeNode.Text);
							writer.RenderEndTag();
						}

						//生成</dt>结束元素
						writer.RenderEndTag();

						//处理描述元素
						if(!string.IsNullOrWhiteSpace(treeNode.Description))
						{
							writer.RenderBeginTag(HtmlTextWriterTag.Dd);
							writer.WriteEncodedText(treeNode.Description);
							writer.RenderEndTag();
						}
					}
				}
			}
        /// <summary>
        /// Gets the relevant TFS <see cref="ChangesetSummary"/> for the root changeset given a set 
        /// of <see cref="ExtendedMerge"/> objects and a given <paramref name="tfsPathParentBranch"/>.
        /// </summary>
        /// <param name="merges">An array of <see cref="ExtendedMerge"/> objects describing the a set of merges.</param>
        /// <param name="tfsPathParentBranch">The tfs Path Parent Branch.</param>
        /// <param name="tfsPathBranchToCreate">The tfs Path Branch To Create.</param>
        /// <remarks>
        /// Each <see cref="ChangeType"/> uses the SourceChangeset, SourceItem, TargetChangeset, and TargetItem 
        /// properties with different semantics, depending on what it needs to describe, so the strategy to determine
        /// whether we are interested in a given ExtendedMerge summary depends on the SourceItem's <see cref="ChangeType"/>.
        /// </remarks>
        /// <returns><value>True</value> if the given <paramref name="merge"/> is relevant; <value>False</value> otherwise.
        /// </returns>
        private static ChangesetSummary GetRelevantChangesetBasedOnChangeType(IEnumerable<ExtendedMerge> merges, string tfsPathParentBranch, string tfsPathBranchToCreate)
        {
            merges = (merges ?? new ExtendedMerge[] {}).ToArray();
            var merge = merges.LastOrDefault(m => m.SourceItem.Item.ServerItem.Equals(tfsPathParentBranch, StringComparison.InvariantCultureIgnoreCase))
                     ?? merges.LastOrDefault();

            if (merge == null)
            {
                throw new GitTfsException("An unexpected error occured when trying to find the root changeset.\nFailed to find root changeset for " + tfsPathBranchToCreate + " branch in " + tfsPathParentBranch + " branch");
            }

            if (merge.SourceItem.ChangeType.HasFlag(ChangeType.Branch)
                || merge.SourceItem.ChangeType.HasFlag(ChangeType.Merge)
                || merge.SourceItem.ChangeType.HasFlag(ChangeType.Add))
            {
                Trace.WriteLine("Found C" + merge.SourceChangeset.ChangesetId + " on branch " + merge.SourceItem.Item.ServerItem);
                return merge.SourceChangeset;
            }
            if(merge.SourceItem.ChangeType.HasFlag(ChangeType.Rename))
            {
                Trace.WriteLine("Found C" + merge.TargetChangeset.ChangesetId + " on branch " + merge.TargetItem.Item);
                return merge.TargetChangeset;
            }
            throw new GitTfsException(
                "Don't know (yet) how to find the root changeset for an ExtendedMerge of type " +
                merge.SourceItem.ChangeType,
                new string[]
                            {
                                "Open an Issue on Github to notify the community that you need support for '" +
                                merge.SourceItem.ChangeType + "': https://github.com/git-tfs/git-tfs/issues"
                            });
        }
        /// <summary>
        /// Transform an IEnumerable of <see cref="HttpMessageHandler"/>s into
        /// a chain of <see cref="HttpMessageHandler"/>s.
        /// </summary>
        /// <param name="handlers">
        /// Chain of <see cref="HttpMessageHandler" /> instances. 
        /// All but the last should be <see cref="DelegatingHandler"/>s. 
        /// </param>
        /// <returns>A chain of <see cref="HttpMessageHandler"/>s</returns>
        private static HttpMessageHandler CreatePipeline(IEnumerable<HttpMessageHandler> handlers)
        {
            HttpMessageHandler pipeline = handlers.LastOrDefault() ?? GetDefaultHttpClientHandler();
            DelegatingHandler dHandler = pipeline as DelegatingHandler;
            if (dHandler != null)
            {
                dHandler.InnerHandler = GetDefaultHttpClientHandler();
                pipeline = dHandler;
            }

            // Wire handlers up in reverse order
            IEnumerable<HttpMessageHandler> reversedHandlers = handlers.Reverse().Skip(1);
            foreach (HttpMessageHandler handler in reversedHandlers)
            {
                dHandler = handler as DelegatingHandler;
                if (dHandler == null)
                {
                    throw new ArgumentException(
                        string.Format(
                        Resources.HttpMessageHandlerExtensions_WrongHandlerType,
                        typeof(DelegatingHandler).Name));
                }

                dHandler.InnerHandler = pipeline;
                pipeline = dHandler;
            }

            return pipeline;
        }
 private static string GetRequestedByFromCommit(IEnumerable<IBuildInformationNode> commits)
 {
     var lastCommit = commits.LastOrDefault();
     if (lastCommit == null) return null;
     return lastCommit.Fields["Committer"];
 }