/// <summary> /// Initiates the connection to the STOMP server. /// </summary> /// <param name="host"></param> /// <param name="login"></param> /// <param name="passcode"></param> /// <param name="headers"></param> /// <param name="cancellationToken"></param> /// <returns></returns> internal async Task ConnectAsync(string host, string login, string passcode, IEnumerable <KeyValuePair <string, string> > headers, CancellationToken cancellationToken) { headers ??= Enumerable.Empty <KeyValuePair <string, string> >(); if (GetStompVersionHeader() is string acceptVersion) { headers = headers.Prepend(new KeyValuePair <string, string>("accept-version", acceptVersion)); } if (host != null) { headers = headers.Prepend(new KeyValuePair <string, string>("host", host)); } logger.LogInformation("Initating STOMP connection: Host={Host}", host); var result = await SendFrameAndWaitAsync(StompCommand.Connect, headers, null, frame => frame.Command == StompCommand.Connected || frame.Command == StompCommand.Error, cancellationToken); if (result.Command == StompCommand.Error) { throw new StompException($"ERROR waiting for CONNECTED response: {Encoding.UTF8.GetString(result.Body.Span)}"); } if (result.Command != StompCommand.Connected) { throw new StompException("Did not receive CONNECTED response."); } version = result.GetHeaderValue("version") is string _version?ParseStompVersionHeader(_version) : StompVersion.Stomp_1_0; session = result.GetHeaderValue("session"); logger.LogInformation("STOMP connection established: Version={Version} Session={Session}", StompVersionHeaderToString(version), session); }
private IList <SectionModel <string, AutocompleteSuggestion> > addStaticElements(IEnumerable <SectionModel <string, AutocompleteSuggestion> > sections) { var suggestions = sections.SelectMany(section => section.Items); IEnumerable <SectionModel <string, AutocompleteSuggestion> > collections = sections; if (isSuggestingProjects.Value) { if (shouldAddProjectCreationSuggestion()) { sections = sections .Prepend( SectionModel <string, AutocompleteSuggestion> .SingleElement( new CreateEntitySuggestion(Resources.CreateProject, currentQuery) ) ); } if (!hasAnyProjects) { sections = sections.Append(SectionModel <string, AutocompleteSuggestion> .SingleElement( NoEntityInfoMessage.CreateProject()) ); } } if (isSuggestingTags.Value) { if (shouldAddTagCreationSuggestion()) { sections = sections .Prepend( SectionModel <string, AutocompleteSuggestion> .SingleElement( new CreateEntitySuggestion(Resources.CreateTag, currentQuery) ) ); } if (!hasAnyTags) { sections = sections.Append(SectionModel <string, AutocompleteSuggestion> .SingleElement( NoEntityInfoMessage.CreateTag()) ); } } return(sections.ToList()); bool shouldAddProjectCreationSuggestion() => canCreateProjectsInWorkspace && !textFieldInfo.Value.HasProject && currentQuery.LengthInBytes() <= MaxProjectNameLengthInBytes && !string.IsNullOrEmpty(currentQuery); bool shouldAddTagCreationSuggestion() => !string.IsNullOrEmpty(currentQuery) && currentQuery.IsAllowedTagByteSize() && suggestions.None(item => item is TagSuggestion tagSuggestion && tagSuggestion.Name.IsSameCaseInsensitiveTrimedTextAs(currentQuery)); }
private static List <int> RandomizeVertexListFromZero(IEnumerable <int> vertices) { // Not probably the most efficient way to handle this. // Sort list by new GUIDs (randomization trick) skip 0 because it has to be prepended. vertices = vertices.Skip(1).OrderBy(x => Guid.NewGuid()); return(vertices.Prepend(0).ToList()); }
/// <summary> /// Converts 4 chars /// </summary> /// <returns>int value</returns> public static int GetMagicBytes(params byte[] chars) { if (chars.Length > 4) { return(0); } IEnumerable <byte> v = chars; if (chars.Length == 3) { v = v.Prepend((byte)0); } else if (chars.Length < 4) { v = Enumerable.Repeat((byte)0, chars.Length - 4).Concat(v); } v = v.Reverse(); unsafe { fixed(byte *chs = v.ToArray()) { return(Marshal.ReadInt32((IntPtr)chs)); } } }
public void Prepend( IEnumerable<object> sut, object[] items ) { var prepended = sut.Prepend( items ); Assert.Equal( sut.Count() + items.Length, prepended.Count() ); Assert.True( sut.All( x => prepended.Contains( x ) ) ); Assert.True( items.All( x => prepended.Contains( x ) ) ); }
/// <inheritdoc /> public (bool success, IEnumerable <Character> targets) Calculate(Character user, IEnumerable <Character> otherCharacters) { var targets = otherCharacters.Prepend(user).ToArray(); var r = _random.Next(targets.Length); return(true, new[] { targets[r] }); }
/// <summary> /// Resolves a 'type_specifier' into a <see cref="Type"/>. /// </summary> /// <param name="node"></param> /// <param name="assemblies"></param> /// <param name="namespaces"></param> /// <returns></returns> static Type ResolveTypeSpecifier(ParseTreeNode node, IEnumerable <Assembly> assemblies, IEnumerable <string> namespaces) { var id = node.Node("qualified_identifier"); if (id == null) { throw new ParseException("missing qualified_identifier"); } var typeName = GetQualifiedIdentifier(id); // resolve type args var args = node .Nodes("type_arg_opt") .Nodes("type_arg_list") .Nodes("type_specifier") .Select(i => ResolveTypeSpecifier(i, assemblies, namespaces)) .ToArray(); // for each namespace, attempt to resolve type from assemblies var type = namespaces .Prepend("") .Reverse() .SelectMany(i => assemblies .Select(j => GetTypeByFullyQualifiedName(j, GetFullyQualifiedTypeName(i, typeName), args))) .FirstOrDefault(i => i != null); if (type == null) { throw new TypeLoadException("Cannot resolve type " + GetGenericTypeName(typeName, args)); } return(type); }
public IEnumerable <Expression> Process( PropertyInfo prop, IEnumerable <Expression> expressions, Expression modelExpression) { return(expressions.Prepend(TR.WriteText(TR.GetFormatted(Prefix, modelExpression)))); }
public TypeConvention( IEnumerable <Func <Type, bool> > predicates, Action <ConventionTypeConfiguration <T> > entityConfigurationAction) : base(predicates.Prepend <Func <Type, bool> >(TypeConvention <T> ._ofTypePredicate)) { this._entityConfigurationAction = entityConfigurationAction; }
public async Task <byte[]> ExportActivityForHQOwner(Guid userId, Guid headQuarterId, Nullable <Guid> schoolId) { Entities.School headQuarter = await _unitOfWork.Schools.GetByIdIncludeClasses(headQuarterId); List <Guid> schoolIds = new List <Guid> { headQuarter.Id }; IEnumerable <Entities.School> efSchools = await _unitOfWork.Schools.FindIncludeClasses(s => s.ParentId.Equals(headQuarterId)); efSchools.Prepend(headQuarter); IEnumerable <School> schools = _mapper.Map <IEnumerable <Entities.School>, IEnumerable <School> >(efSchools); schools = schools.Where(s => !schoolId.HasValue || s.Id.Equals(schoolId.Value)); byte[] result; using (var package = new ExcelPackage()) { foreach (var school in schools) { await AppendSheetForEachSchool(package.Workbook.Worksheets, school); } result = package.GetAsByteArray(); } return(result); }
/// <summary> /// Runs an instance of this DarkRift installation and waits for exit. /// </summary> /// <param name="args">The args to pass to the server.</param> /// <returns>The exit code of the server.</returns> public int Run(IEnumerable <string> args) { // Calculate the executable file to run string fullPath; if (Platform == ServerPlatform.Framework) { fullPath = Path.Combine(InstallationPath, "DarkRift.Server.Console.exe"); } else { fullPath = "dotnet"; args = args.Prepend(Path.Combine(InstallationPath, "Lib", "DarkRift.Server.Console.dll")); } using Process process = new Process { StartInfo = new ProcessStartInfo(fullPath, string.Join(" ", args)) }; process.Start(); process.WaitForExit(); return(process.ExitCode); }
public void Select(string table, IEnumerable <string> fields) { fields = fields.Prepend(string.Empty); var fieldsQuery = fields.Aggregate((a, b) => $"{a}, \"{b}\"").Substring(2); _selectQuery = $"SELECT {fieldsQuery} FROM \"{table}\""; }
public static TabDefItem FromMember(TableDefinition.Member member) { IEnumerable <TabDefItem> children = member.alternatives.Select(alt => FromAlternative(alt)); if (member.signal) { children = children.Prepend(new TabDefSignal() { Label = member.signalFullname }); } TabDefItem tabDefItem; if (member.dataType.Primitive) { tabDefItem = new TabDefPrimitive() { DataTypeName = member.dataType.name }; } else { tabDefItem = new TabDefMember() { DataTypeName = member.dataType.name }; } tabDefItem.Label = member.fullname; tabDefItem.Children = new ObservableCollection <TabDefItem>(children); return(tabDefItem); }
public Task StartAsync(CancellationToken cancellationToken) { // Log application parts found IEnumerable <string> partNames = _applicationPartManager.ApplicationParts.Select(x => x.Name); _logger.LogInformation( string.Join(separator: Environment.NewLine, values: partNames.Prepend("Application parts found:"))); // Log controllers found ControllerFeature feature = new ControllerFeature(); _applicationPartManager.PopulateFeature(feature); IEnumerable <string> controllerNames = feature.Controllers.Select(x => x.Name); _logger.LogInformation( string.Join(separator: Environment.NewLine, values: controllerNames.Prepend("Controllers found:"))); // Log endpoints found Task.Run( async() => { await Task.Delay(3000); // wait 3 seconds for middleware to be built IEnumerable <string> endpointNames = _endpointDataSource.Endpoints.Select(x => x.DisplayName); _logger.LogInformation( string.Join(separator: Environment.NewLine, values: endpointNames.Prepend("Endpoints found:"))); }); return(Task.CompletedTask); }
private static long ProcessTree(IEnumerable <int> input) { var set = input.Prepend(0) .OrderBy(_ => _) .ToList(); var pathways = new long[set.Count]; pathways[0] = 1; //in any given set of paths, there is at least 1 path for (var i = 0; i < set.Count; i++) { var current = set[i]; var currentPathway = pathways[i]; for (var j = 1; j <= 3; j++) { var index = i + j; if (index >= set.Count || set[index] > current + 3) { break; } pathways[index] = pathways[index] + currentPathway; } } return(pathways.Last()); }
public void Prepend(IEnumerable <object> sut, object[] items) { var prepended = sut.Prepend(items); Assert.Equal(sut.Count() + items.Length, prepended.Count()); Assert.True(sut.All(x => prepended.Contains(x))); Assert.True(items.All(x => prepended.Contains(x))); }
private static string GetClassFolder(IEnumerable <string> pathParts) { var parts = pathParts .Prepend(Application.dataPath) .ToArray(); return(Path.Combine(parts)); }
public Guid CreateJob(IEnumerable <SeedTree> initialSeeds, IEnumerable <IScraper> scrapers, IEnumerable <ICuller> cullers) { var job = new ScrapeJob(initialSeeds, scrapers, cullers.Prepend(this.ResultCuller)); this.ScrapeJobs = this.ScrapeJobs.Add(job.JobGuid, job); return(job.JobGuid); }
private static IEnumerable <int> BuildNextRow(IEnumerable <int> row) { row = row.Prepend(0).Append(0); return(row .Zip(row.Skip(1), (a, b) => (a, b)) .Select(pair => pair.a + pair.b)); }
public IEnumerable <int> GetAdapters() { IEnumerable <int> adapters = this.GetInputRaw() .Select(i => int.Parse(i)) .OrderBy(i => i); return(adapters.Prepend(0).Append(adapters.Max() + 3)); }
public TypeConventionWithHaving( IEnumerable <Func <Type, bool> > predicates, Func <Type, TValue> capturingPredicate, Action <ConventionTypeConfiguration <T>, TValue> entityConfigurationAction) : base(predicates.Prepend <Func <Type, bool> >(TypeConvention <T> .OfTypePredicate), capturingPredicate) { this._entityConfigurationAction = entityConfigurationAction; }
/// <summary> /// Returns a sequence consisting of the head element and the given tail elements. /// </summary> /// <typeparam name="T">Type of sequence</typeparam> /// <param name="head">Head element of the new sequence.</param> /// <param name="tail">All elements of the tail. Must not be null.</param> /// <returns>A sequence consisting of the head elements and the given tail elements.</returns> /// <remarks>This operator uses deferred execution and streams its results.</remarks> public static IEnumerable <T> Concat <T>(this T head, IEnumerable <T> tail) { if (tail == null) { throw new ArgumentNullException(nameof(tail)); } return(tail.Prepend(head)); }
public StopwatchMock([NotNull] IEnumerable <TimeSpan> elapsedTimes) { if (elapsedTimes == null) { throw new ArgumentNullException(nameof(elapsedTimes)); } ElapsedTimes = elapsedTimes.Prepend(TimeSpan.Zero).ToList().GetEnumerator(); }
public void Prepent_SingleValue_ShouldPrepend() { IEnumerable <int> enumerable = Enumerable.Range(1, 3); List <int> result = enumerable.Prepend(0).ToList(); result.Should().BeEquivalentTo(new[] { 0, 1, 2, 3 }); }
/// <summary> /// Use when the user needs to decide on possible options /// It invokes <see cref="OnQuestion"/> where the implementer can either block uppm with user query or use the default value. /// </summary> /// <param name="question">Question to be asked from user</param> /// <param name="note">Displayed on top of the prompt</param> /// <param name="possibilities">If null any input will be accepted. Otherwise input is compared to these possible entries.</param> /// <param name="defaultValue">This value is used when user submits an empty input or in a potential unattended mode.</param> /// <returns>User answer or default</returns> public static string PromptForChoice( this PSCmdlet cmdlet, string question, string note = "", IEnumerable <string> possibilities = null, string defaultValue = "") { if (cmdlet is PSCmdletExtra cmdletex && cmdletex.Unattended.IsPresent) { return(defaultValue); } if (possibilities == null) { var message = string.IsNullOrWhiteSpace(note) ? $" (default is {defaultValue})" : $" {note}\n (default is {defaultValue})"; var answer = cmdlet.Host.UI.Prompt( question, message, new Collection <FieldDescription> { new FieldDescription("Answer") { DefaultValue = new PSObject(defaultValue), IsMandatory = true } } )["Answer"].BaseObject.ToString(); if (string.IsNullOrWhiteSpace(answer)) { return(defaultValue); } return(answer); } else { int defChoiceId = -1; int i = 0; foreach (var ch in possibilities) { if (ch == defaultValue) { defChoiceId = i; break; } i++; } if (defChoiceId < 0) { possibilities = possibilities.Prepend(defaultValue); defChoiceId = 0; } var choices = new Collection <ChoiceDescription>(possibilities.Select(p => new ChoiceDescription(p)).ToList()); var answerId = cmdlet.Host.UI.PromptForChoice(question, note, choices, defChoiceId); return(choices[answerId].Label); } }
public void Prepend_Throws_If_Source_Is_Null() { IEnumerable <int> source = null; // ReSharper disable once AssignNullToNotNullAttribute // ReSharper disable once ReturnValueOfPureMethodIsNotUsed var ex = Assert.Throws <ArgumentNullException>(() => source.Prepend(42)); ex.ParamName.Should().Be("source"); }
protected virtual async Task DeleteOverrideAsync(string id, string location, IEnumerable <string> attached) { await Task.Run(() => FileUtils.RecycleVisible(attached.Prepend(location).ToArray())); if (!FileUtils.Exists(location)) { RemoveFromList(id); } }
public static DirectoryInfo Combine(this DirectoryInfo directoryInfo, IEnumerable <string> str) { Contract.Requires(directoryInfo != null); Contract.Requires(str != null); string merged = Path.Combine(str.Prepend(directoryInfo.FullName).ToArray()); return(new DirectoryInfo(merged)); }
/// <summary> /// Prepend new SDKVersionHeaders /// </summary> /// <param name="httpClient"></param> private static void PrependNewSDKVersionHeaders(HttpClient httpClient) { IEnumerable <string> previousSDKHeaders = httpClient.DefaultRequestHeaders.GetValues(CoreConstants.Headers.SdkVersionHeaderName); httpClient.DefaultRequestHeaders.Remove(CoreConstants.Headers.SdkVersionHeaderName); httpClient.DefaultRequestHeaders.Add(CoreConstants.Headers.SdkVersionHeaderName, previousSDKHeaders.Prepend(AuthModuleVersionHeaderValue)); }
/// <summary> /// Adds a single element to the start of an IEnumerable, if it is not null. /// </summary> /// <typeparam name="T">Type of enumerable to return.</typeparam> /// <param name="tail">The source enumerable.</param> /// <param name="head">The element to prepend.</param> /// <returns>IEnumerable containing the specified additional element, followed by all the input elements.</returns> public static IEnumerable <T> PrependIfNotNull <T>(this IEnumerable <T> tail, T head) { if (head == null) { return(tail); } return(tail.Prepend <T>(head)); }
public static IEnumerable <T> AggregateAdd <T>(this IEnumerable <T> source, Func <T, T, T> aggregate, Func <T, T> add, Boolean prepend = false) { source = source.ToList(); T value = add(source.Aggregate(aggregate)); return(prepend ? source.Prepend(value) : source.Append(value)); }
/// <summary> /// Builds this project, using the default targets and the given loggers. /// </summary> /// <param name="loggers">An enumerator over all loggers to be used during the build.</param> /// <returns> /// Returns true on success; false otherwise. /// </returns> public bool Build(IEnumerable<ILogger> loggers) { var result = false; this.SwapMSBuildTasks(); using (var reader = this.Document.CreateReader()) { reader.MoveToContent(); var innerProject = new Microsoft.Build.Evaluation.Project(reader); result = innerProject.Build(loggers.Prepend(this.Logger)); reader.Close(); } return result; }
internal static Expression InvokeMember(string name, PSMethodInvocationConstraints constraints, Expression target, IEnumerable<Expression> args, bool @static, bool propertySet) { return Expression.Dynamic(PSInvokeMemberBinder.Get(name, new CallInfo(args.Count<Expression>(), new string[0]), @static, propertySet, constraints), typeof(object), args.Prepend<Expression>(target)); }
internal Expression InvokeMember(string name, PSMethodInvocationConstraints constraints, Expression target, IEnumerable<Expression> args, bool @static, bool propertySet) { var callInfo = new CallInfo(args.Count()); var classScope = _memberFunctionType != null ? _memberFunctionType.Type : null; var binder = name.Equals("new", StringComparison.OrdinalIgnoreCase) && @static ? (CallSiteBinder)PSCreateInstanceBinder.Get(callInfo, constraints, publicTypeOnly: true) : PSInvokeMemberBinder.Get(name, callInfo, @static, propertySet, constraints, classScope); return DynamicExpression.Dynamic(binder, typeof(object), args.Prepend(target)); }
private Expression InvokeBaseCtorMethod(PSMethodInvocationConstraints constraints, Expression target, IEnumerable<Expression> args) { var callInfo = new CallInfo(args.Count()); var binder = PSInvokeBaseCtorBinder.Get(callInfo, constraints); return DynamicExpression.Dynamic(binder, typeof(object), args.Prepend(target)); }
internal Expression InvokeDynamicMember(Expression memberNameExpr, PSMethodInvocationConstraints constraints, Expression target, IEnumerable<Expression> args, bool @static, bool propertySet) { var binder = PSInvokeDynamicMemberBinder.Get(new CallInfo(args.Count()), _memberFunctionType, @static, propertySet, constraints); return DynamicExpression.Dynamic(binder, typeof(object), args.Prepend(memberNameExpr).Prepend(target)); }