content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the quicksight-2018-04-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.QuickSight.Model { /// <summary> /// Container for the parameters to the CreateGroup operation. /// Creates an Amazon QuickSight group. /// /// /// <para> /// The permissions resource is <code>arn:aws:quicksight:us-east-1:<i>&lt;relevant-aws-account-id&gt;</i>:group/default/<i>&lt;group-name&gt;</i> /// </code>. /// </para> /// /// <para> /// The response is a group object. /// </para> /// </summary> public partial class CreateGroupRequest : AmazonQuickSightRequest { private string _awsAccountId; private string _description; private string _groupName; private string _awsNamespace; /// <summary> /// Gets and sets the property AwsAccountId. /// <para> /// The ID for the AWS account that the group is in. Currently, you use the ID for the /// AWS account that contains your Amazon QuickSight account. /// </para> /// </summary> [AWSProperty(Required=true, Min=12, Max=12)] public string AwsAccountId { get { return this._awsAccountId; } set { this._awsAccountId = value; } } // Check to see if AwsAccountId property is set internal bool IsSetAwsAccountId() { return this._awsAccountId != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// A description for the group that you want to create. /// </para> /// </summary> [AWSProperty(Min=1, Max=512)] public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property GroupName. /// <para> /// A name for the group that you want to create. /// </para> /// </summary> [AWSProperty(Required=true, Min=1)] public string GroupName { get { return this._groupName; } set { this._groupName = value; } } // Check to see if GroupName property is set internal bool IsSetGroupName() { return this._groupName != null; } /// <summary> /// Gets and sets the property Namespace. /// <para> /// The namespace. Currently, you should set this to <code>default</code>. /// </para> /// </summary> [AWSProperty(Required=true, Max=64)] public string Namespace { get { return this._awsNamespace; } set { this._awsNamespace = value; } } // Check to see if Namespace property is set internal bool IsSetNamespace() { return this._awsNamespace != null; } } }
30.223077
149
0.585136
[ "Apache-2.0" ]
KenHundley/aws-sdk-net
sdk/src/Services/QuickSight/Generated/Model/CreateGroupRequest.cs
3,929
C#
using System; using Microsoft.Maui.Controls.CustomAttributes; using Microsoft.Maui.Controls.Internals; using Microsoft.Maui.Devices; #if UITEST && __IOS__ using Xamarin.UITest; using NUnit.Framework; #endif namespace Microsoft.Maui.Controls.Compatibility.ControlGallery.Issues { #if UITEST [NUnit.Framework.Category(Compatibility.UITests.UITestCategories.Github5000)] #endif [Preserve(AllMembers = true)] [Issue(IssueTracker.Github, 3049, "DisplayActionSheet freezes app in iOS custom renderer (iPad only)", PlatformAffected.iOS)] public class Issue3049 : TestContentPage { const string Button1Id = "button1"; const string Button2Id = "button2"; const string LabelId = "label"; const string Success = "Success"; const string Action1 = "Don't click me"; const string Skip = "skip"; protected override void Init() { Label instructions = new Label { Text = "Click the first button to open an ActionSheet. Click anywhere outside of the ActionSheet to close it. Then click the second button. If nothing happens (and the app is basically frozen), this test has failed.", AutomationId = LabelId }; Label skip = new Label { Text = "Skip this test -- this is not an iPad, so this is not relevant.", AutomationId = Skip }; Button button = new Button { Text = "Click me first", AutomationId = Button1Id }; button.Clicked += async (s, e) => { string action = await DisplayActionSheet(null, null, null, Action1, "Click outside ActionSheet instead"); System.Diagnostics.Debug.WriteLine("## " + action); }; Button button2 = new Button { Text = "Click me second", AutomationId = Button2Id }; button2.Clicked += (s, e) => { instructions.Text = Success; }; StackLayout stackLayout = new StackLayout { Children = { instructions, button, button2 } }; if (DeviceInfo.Idiom != DeviceIdiom.Tablet || DeviceInfo.Platform != DevicePlatform.iOS) stackLayout.Children.Insert(0, skip); Content = stackLayout; } #if UITEST && __IOS__ [Test] public void Issue3049Test() { RunningApp.WaitForElement(q => q.Marked(Button1Id)); if (RunningApp.Query(q => q.Marked(Skip)).Length > 0) Assert.Pass("Test ignored, not relevant on phone"); else { RunningApp.Tap(q => q.Marked(Button1Id)); RunningApp.WaitForElement(q => q.Marked(Action1)); // tap outside ActionSheet to dismiss it RunningApp.Tap(q => q.Marked(LabelId)); RunningApp.WaitForElement(q => q.Marked(Button2Id)); RunningApp.Tap(q => q.Marked(Button2Id)); RunningApp.WaitForElement(q => q.Marked(Success)); } } #endif } }
30.476744
279
0.699733
[ "MIT" ]
10088/maui
src/Compatibility/ControlGallery/src/Issues.Shared/Issue3049.cs
2,623
C#
// // THIS FILE HAS BEEN GENERATED AUTOMATICALLY // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING // // GENERATED USING @colyseus/schema 0.4.54 // using Colyseus.Schema; namespace SchemaTest.ArraySchemaTypes { public class IAmAChild : Schema { [Type(0, "number")] public float x = 0; [Type(1, "number")] public float y = 0; } }
18.842105
62
0.684358
[ "MIT" ]
AJ92/colyseus-unity3d
Assets/Editor/ColyseusTests/Schema/ArraySchemaTypes/IAmAChild.cs
358
C#
namespace SkuVaultApiWrapper.Models.SharedModels { public class ShippingInfo { public string City { get; set; } public string CompanyName { get; set; } public string Country { get; set; } public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Line1 { get; set; } public string Line2 { get; set; } public string PhoneNumber { get; set; } public string Postal { get; set; } public string Region { get; set; } public string ShippingCarrier { get; set; } public string ShippingClass { get; set; } public string ShippingStatus { get; set; } } }
30.47619
49
0.685938
[ "MIT" ]
ntoates/SkuVaultApiWrapper
SkuVaultApiWrapper/Models/SharedModels/ShippingInfo.cs
642
C#
namespace SilverbackShop.Baskets.Service.Dto { public class AddBasketItemDto { public string SKU { get; set; } public int Quantity { get; set; } } }
22.125
45
0.627119
[ "MIT" ]
lbovet/silverback
samples/SilverbackShop/src/Baskets.Service/Dto/AddBasketItemDto.cs
179
C#
// Author: Prasanna V. Loganathar // Created: 04:18 11-05-2015 // Project: LiquidState // License: http://www.apache.org/licenses/LICENSE-2.0 using System; namespace LiquidState.Core { public struct Transition<TState, TTrigger> { public Transition(TState source, TState destination) { Source = source; Destination = destination; Trigger = default(TTrigger); HasTrigger = false; } public Transition(TState source, TState destination, TTrigger trigger) { Source = source; Destination = destination; Trigger = trigger; HasTrigger = true; } public TState Source { get; } public TState Destination { get; } public TTrigger Trigger { get; } public bool HasTrigger { get; } } public class TriggerStateEventArgs<TState, TTrigger> : EventArgs { public TriggerStateEventArgs(TState currentState, TTrigger trigger) { Trigger = trigger; CurrentState = currentState; } public TTrigger Trigger { get; private set; } public TState CurrentState { get; private set; } } public class OptionalTriggerStateEventArgs<TState, TTrigger> : TriggerStateEventArgs<TState, TTrigger> { protected OptionalTriggerStateEventArgs(TState currentState, TTrigger trigger, bool hasTrigger = true) : base(currentState, trigger) { HasTrigger = hasTrigger; } protected OptionalTriggerStateEventArgs(TState currentState) : base(currentState, default(TTrigger)) { HasTrigger = false; } public bool HasTrigger { get; private set; } } public class TransitionEventArgs<TState, TTrigger> : OptionalTriggerStateEventArgs<TState, TTrigger> { public TransitionEventArgs(TState currentState, TState targetState, TTrigger trigger, bool hasTrigger = true) : base(currentState, trigger, hasTrigger) { TargetState = targetState; } public TransitionEventArgs(TState currentState, TState targetState) : base(currentState) { TargetState = targetState; } public TState TargetState { get; private set; } } public class TransitionExecutedEventArgs<TState, TTrigger> : OptionalTriggerStateEventArgs<TState, TTrigger> { public TransitionExecutedEventArgs(TState currentState, TState pastState, TTrigger trigger, bool hasTrigger = true) : base(currentState, trigger, hasTrigger) { PastState = pastState; } public TransitionExecutedEventArgs(TState currentState, TState pastState) : base(currentState) { PastState = pastState; } public TState PastState { get; private set; } } }
30.541667
117
0.625171
[ "Apache-2.0" ]
SUSSMicroTec/LiquidState
LiquidState/Core/Transition.cs
2,934
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SPACore.PhoneBook.Tests")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0d4c5d00-c144-4213-a007-4b8944113ab1")]
41.789474
84
0.778338
[ "MIT" ]
52ABP/SPA.PhoneBook
src/aspnet-core/test/SPACore.PhoneBook.Tests/Properties/AssemblyInfo.cs
796
C#
using AutoMapper; namespace Abp.VueTemplate.MenuManagement { public class MenuManagementApplicationAutoMapperProfile : Profile { public MenuManagementApplicationAutoMapperProfile() { /* You can configure your AutoMapper mapping configuration here. * Alternatively, you can split your mapping configurations * into multiple profile classes for a better organization. */ CreateMap<Menu, MenuDto>(); CreateMap<CreateOrUpdateMenuDto, Menu>(); //CreateMap<MenuDto, MenuInfo>() // .ForMember(d => d.Component, opt => { opt.MapFrom(s => s.ComponentPath); }) // .ForMember(d => d.Path, opt => { opt.MapFrom(s => s.RouterPath); }) // .ForMember(d => d.Meta, // opt => // { // opt.MapFrom(s => new MenuMetaInfo // { // Icon = s.Icon, // Title = s.DisplayName // }); // }); CreateMap<Menu, VueMenu>() .ForMember(d => d.Component, opt => { opt.MapFrom(s => s.ComponentPath); }) .ForMember(d => d.Path, opt => { opt.MapFrom(s => s.RouterPath); }) .ForMember(d => d.Meta, opt => { opt.MapFrom(s => new MenuMeta { Icon = s.Icon, Title = s.DisplayName }); }); } } }
38.928571
93
0.440367
[ "MIT" ]
zhk0603/abp-vue
src/aspnet-core/modules/Abp.VueTemplate.MenuManagement/src/Abp.VueTemplate.MenuManagement.Application/MenuManagementApplicationAutoMapperProfile.cs
1,635
C#
namespace NetworkOperation.Core { public struct Empty { public static readonly Empty value = new Empty(); } }
18.571429
57
0.646154
[ "Apache-2.0" ]
floatW0lf/NetworkOperation
NetworkOperation.Core/Empty.cs
132
C#
using UnityEngine; namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityParticleSystem { [TaskCategory("Basic/ParticleSystem")] [TaskDescription("Is the Particle System alive?")] public class IsAlive : Conditional { [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")] public SharedGameObject targetGameObject; private ParticleSystem particleSystem; private GameObject prevGameObject; public override void OnStart() { var currentGameObject = GetDefaultGameObject(targetGameObject.Value); if (currentGameObject != prevGameObject) { particleSystem = currentGameObject.GetComponent<ParticleSystem>(); prevGameObject = currentGameObject; } } public override TaskStatus OnUpdate() { if (particleSystem == null) { Debug.LogWarning("ParticleSystem is null"); return TaskStatus.Failure; } return particleSystem.IsAlive() ? TaskStatus.Success : TaskStatus.Failure; } public override void OnReset() { targetGameObject = null; } } }
32.692308
100
0.606275
[ "Apache-2.0" ]
brustlinker/unity_behaviortree_sk
Assets/Behavior Designer/Runtime/Basic Tasks/ParticleSystem/IsAlive.cs
1,275
C#
using System; using ValheimTooler.Utils; namespace ValheimTooler.Core.Extensions { public static class PlayerExtensions { public static bool VTInGodMode(this Player player) { if (player != null) { return player.InGodMode(); } return false; } public static void VTSetGodMode(this Player player, bool isGodMode) { if (player != null) { player.SetGodMode(isGodMode); } } public static bool VTInFlyMode(this Player player) { if (player != null) { return player.InDebugFlyMode(); } return false; } public static void VTSetFlyMode(this Player player, bool isFlyMode) { if (player != null) { player.SetFieldValue<bool>("m_debugFly", isFlyMode); ZNetView m_nview = player.GetFieldValue<ZNetView>("m_nview"); m_nview.GetZDO().Set("DebugFly", isFlyMode); } } public static bool VTInGhostMode(this Player player) { if (player != null) { return player.InGhostMode(); } return false; } public static void VTSetGhostMode(this Player player, bool isGhostMode) { if (player != null) { player.SetGhostMode(isGhostMode); } } public static bool VTIsNoPlacementCost(this Player player) { if (player != null) { return player.NoCostCheat(); } return false; } public static void VTSetNoPlacementCost(this Player player, bool isNoPlacementCost) { if (player != null) { player.SetFieldValue<bool>("m_noPlacementCost", isNoPlacementCost); player.CallMethod("UpdateAvailablePiecesList"); } } public static void VTSetMaxStamina(this Player player) { if (player == null || !player.GetFieldValue<ZNetView>("m_nview").IsValid()) { return; } player.UseStamina(- player.GetMaxStamina()); player.GetFieldValue<ZNetView>("m_nview").GetZDO().Set("stamina", player.GetMaxStamina()); } public static void VTSetNoStamina(this Player player) { if (player == null || !player.GetFieldValue<ZNetView>("m_nview").IsValid()) { return; } player.UseStamina(99999f); player.GetFieldValue<ZNetView>("m_nview").GetZDO().Set("stamina", 0); } public static void VTTeleportTo(this Player player, ZNet.PlayerInfo target) { if (player != null) { ZDOID characterID = target.m_characterID; if (!characterID.IsNone()) { player.TeleportTo(target.m_position, player.transform.rotation, true); } } } public static void VTHeal(this Player player) { if (player != null) { player.Heal(player.GetMaxHealth(), true); } } public static void VTActiveGuardianPower(this Player player, string guardianPower) { if (player != null) { player.GetSEMan().AddStatusEffect(guardianPower, true); } } public static void VTUpdateSkillLevel(this Player player, string skillName, int level) { if (player != null) { Skills.SkillType skillType = (Skills.SkillType)Enum.Parse(typeof(Skills.SkillType), skillName); Skills.Skill skill = (Skills.Skill)player.GetSkills().CallMethod("GetSkill", skillType); int offset = (int)Math.Ceiling(level - skill.m_level); player.GetSkills().CheatRaiseSkill(skillName.ToLower(), offset); } } public static void VTAddItemToInventory(this Player player, string itemPrefab, int quantity, int quality, int variant) { if (player != null && Game.instance != null) { long playerID = player.GetPlayerID(); string playerName = player.GetPlayerName(); player.GetInventory().AddItem(itemPrefab, quantity, quality, variant, playerID, playerName); } } public static void VTTameNearbyCreatures(this Player player) { if (player != null) { Tameable.TameAllInArea(player.transform.position, 20f); } } public static bool VTIsInventoryInfiniteWeight(this Player player) { if (player != null) { return player.m_maxCarryWeight != 300; } return false; } public static void VTInventoryInfiniteWeight(this Player player, bool isInventoryInfiniteWeight) { if (player != null) { if (isInventoryInfiniteWeight) { player.m_maxCarryWeight = 999999999; } else { player.m_maxCarryWeight = 300; } } } } }
29.684492
126
0.509998
[ "MIT" ]
Astropilot/ValheimTooler
ValheimTooler/Core/Extensions/PlayerExtensions.cs
5,551
C#
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; namespace SimpleRepository { public interface IRepository { Task<IEnumerable<T>> Get<T>(); Task<IEnumerable<T>> Get<T>(Expression<Func<T, bool>> predicate); Task<T> Get<T>(Expression<Func<T, bool>> predicate, bool isNullable); Task<T> Get<T>(Guid Id, bool isNullable = true) where T : IEntity; Task Post<T>(T entity); Task Put<T>(T entity); Task Delete<T>(Guid id) where T : IEntity; } }
31.444444
77
0.650177
[ "MIT-0" ]
kamabery/Slackers.Services.Bus
Samples/SimpleRepository/IRepository.cs
568
C#
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; using Dapper; using DotNetFramework.CAP.Infrastructure; using DotNetFramework.CAP.Models; namespace DotNetFramework.CAP.SqlServer { public class SqlServerStorageConnection : IStorageConnection { private readonly CapOptions _capOptions; public SqlServerStorageConnection(SqlServerOptions options, CapOptions capOptions) { _capOptions = capOptions; Options = options; } public SqlServerOptions Options { get; } public IStorageTransaction CreateTransaction() { return new SqlServerStorageTransaction(this); } public async Task<CapPublishedMessage> GetPublishedMessageAsync(long id) { var sql = $@"SELECT * FROM [{Options.Schema}].[Published] WITH (readpast) WHERE Id={id}"; using (var connection = new SqlConnection(Options.ConnectionString)) { return await connection.QueryFirstOrDefaultAsync<CapPublishedMessage>(sql); } } public async Task<IEnumerable<CapPublishedMessage>> GetPublishedMessagesOfNeedRetry() { var fourMinsAgo = DateTime.Now.AddMinutes(-4).ToString("O"); var sql = $"SELECT TOP (200) * FROM [{Options.Schema}].[Published] WITH (readpast) WHERE Retries<{_capOptions.FailedRetryCount} AND Version='{_capOptions.Version}' AND Added<'{fourMinsAgo}' AND (StatusName = '{StatusName.Failed}' OR StatusName = '{StatusName.Scheduled}')"; using (var connection = new SqlConnection(Options.ConnectionString)) { return await connection.QueryAsync<CapPublishedMessage>(sql); } } public void StoreReceivedMessage(CapReceivedMessage message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } var sql = $@" INSERT INTO [{Options.Schema}].[Received]([Id],[Version],[Name],[Group],[Content],[Retries],[Added],[ExpiresAt],[StatusName]) VALUES(@Id,'{_capOptions.Version}',@Name,@Group,@Content,@Retries,@Added,@ExpiresAt,@StatusName);"; using (var connection = new SqlConnection(Options.ConnectionString)) { connection.Execute(sql, message); } } public async Task<CapReceivedMessage> GetReceivedMessageAsync(long id) { var sql = $@"SELECT * FROM [{Options.Schema}].[Received] WITH (readpast) WHERE Id={id}"; using (var connection = new SqlConnection(Options.ConnectionString)) { return await connection.QueryFirstOrDefaultAsync<CapReceivedMessage>(sql); } } public async Task<IEnumerable<CapReceivedMessage>> GetReceivedMessagesOfNeedRetry() { var fourMinsAgo = DateTime.Now.AddMinutes(-4).ToString("O"); var sql = $"SELECT TOP (200) * FROM [{Options.Schema}].[Received] WITH (readpast) WHERE Retries<{_capOptions.FailedRetryCount} AND Version='{_capOptions.Version}' AND Added<'{fourMinsAgo}' AND (StatusName = '{StatusName.Failed}' OR StatusName = '{StatusName.Scheduled}')"; using (var connection = new SqlConnection(Options.ConnectionString)) { return await connection.QueryAsync<CapReceivedMessage>(sql); } } public bool ChangePublishedState(long messageId, string state) { var sql = $"UPDATE [{Options.Schema}].[Published] SET Retries=Retries+1,ExpiresAt=NULL,StatusName = '{state}' WHERE Id={messageId}"; using (var connection = new SqlConnection(Options.ConnectionString)) { return connection.Execute(sql) > 0; } } public bool ChangeReceivedState(long messageId, string state) { var sql = $"UPDATE [{Options.Schema}].[Received] SET Retries=Retries+1,ExpiresAt=NULL,StatusName = '{state}' WHERE Id={messageId}"; using (var connection = new SqlConnection(Options.ConnectionString)) { return connection.Execute(sql) > 0; } } } }
40.214286
279
0.624778
[ "MIT" ]
AssassinJay/DotNetFramework.CAP
src/DotNetFramework.CAP/DotNetFramework.CAP.SqlServer/IStorageConnection.SqlServer.cs
4,504
C#
namespace AncientMysteries.Items { [EditorGroup(group_Guns_Melees)] [MetaImage(tex_Melee_DeathBringer)] [MetaInfo(Lang.Default, "Death Bringer", "Looks cool, but not cool actually.")] [MetaInfo(Lang.schinese, "死亡收割者", "用起来没有想象中的好。")] [MetaType(MetaType.Melee)] public sealed partial class DeathBringer : AMMelee { public float cooldown = -2; public DeathBringer(float xval, float yval) : base(xval, yval) { this.ReadyToRun(tex_Melee_DeathBringer); } public override void Update() { base.Update(); if (owner is Duck) additionalHoldOffset = new Vec2(-8, this.jabStance ? -5 : 0); if (cooldown < 0) { cooldown += 0.1f; } else cooldown = 0; } public override void OnPressAction() { base.OnPressAction(); /* AT_Skull type = new AT_Skull(); if (duck != null && cooldown == 0) { cooldown = -2; if ((_crouchStance && _jabStance && !_swinging) || (!_crouchStance && !_swinging && _swing < 0.1f)) { var firedBullets = new List<Bullet>(1); if (base.duck.offDir != 1) { Bullet b = new Bullet_Skull(base.duck.x, base.duck.y, type, -180, true, base.duck, rbound: false, 300f); firedBullets.Add(b); Level.Add(b); } else { Bullet b = new Bullet_Skull(base.duck.x, base.duck.y, type, -180, true, base.duck, rbound: false, 300f); firedBullets.Add(b); Level.Add(b); } } } */ } } }
31.803279
128
0.457216
[ "MIT" ]
BThree496/AncientMysteriesMod
AncientMysteries/Items/Melee/DeathBringer.cs
1,974
C#
using System; using System.Collections.Generic; using Hl7.Fhir.Introspection; using Hl7.Fhir.Validation; using System.Linq; using System.Runtime.Serialization; using Hl7.Fhir.Utility; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma warning disable 1591 // suppress XML summary warnings // // Generated for FHIR v3.0.1 // namespace Hl7.Fhir.Model.STU3 { /// <summary> /// Key Object Selection /// </summary> [FhirType(Hl7.Fhir.Model.Version.STU3, "ImagingManifest", IsResource=true)] [DataContract] public partial class ImagingManifest : Hl7.Fhir.Model.DomainResource, System.ComponentModel.INotifyPropertyChanged { [NotMapped] public override ResourceType ResourceType { get { return ResourceType.ImagingManifest; } } [NotMapped] public override string TypeName { get { return "ImagingManifest"; } } [FhirType(Hl7.Fhir.Model.Version.STU3, "StudyComponent")] [DataContract] public partial class StudyComponent : Hl7.Fhir.Model.BackboneElement, System.ComponentModel.INotifyPropertyChanged, IComponent { [NotMapped] public override string TypeName { get { return "StudyComponent"; } } /// <summary> /// Study instance UID /// </summary> [FhirElement("uid", InSummary=Hl7.Fhir.Model.Version.All, Order=40)] [CLSCompliant(false)] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.Oid UidElement { get { return _UidElement; } set { _UidElement = value; OnPropertyChanged("UidElement"); } } private Hl7.Fhir.Model.Oid _UidElement; /// <summary> /// Study instance UID /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Uid { get { return UidElement != null ? UidElement.Value : null; } set { if (value == null) UidElement = null; else UidElement = new Hl7.Fhir.Model.Oid(value); OnPropertyChanged("Uid"); } } /// <summary> /// Reference to ImagingStudy /// </summary> [FhirElement("imagingStudy", InSummary=Hl7.Fhir.Model.Version.All, Order=50)] [CLSCompliant(false)] [References("ImagingStudy")] [DataMember] public Hl7.Fhir.Model.ResourceReference ImagingStudy { get { return _ImagingStudy; } set { _ImagingStudy = value; OnPropertyChanged("ImagingStudy"); } } private Hl7.Fhir.Model.ResourceReference _ImagingStudy; /// <summary> /// Study access service endpoint /// </summary> [FhirElement("endpoint", InSummary=Hl7.Fhir.Model.Version.All, Order=60)] [CLSCompliant(false)] [References("Endpoint")] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.ResourceReference> Endpoint { get { if(_Endpoint==null) _Endpoint = new List<Hl7.Fhir.Model.ResourceReference>(); return _Endpoint; } set { _Endpoint = value; OnPropertyChanged("Endpoint"); } } private List<Hl7.Fhir.Model.ResourceReference> _Endpoint; /// <summary> /// Series identity of the selected instances /// </summary> [FhirElement("series", InSummary=Hl7.Fhir.Model.Version.All, Order=70)] [CLSCompliant(false)] [Cardinality(Min=1,Max=-1)] [DataMember] public List<SeriesComponent> Series { get { if(_Series==null) _Series = new List<SeriesComponent>(); return _Series; } set { _Series = value; OnPropertyChanged("Series"); } } private List<SeriesComponent> _Series; internal override void Serialize(Serialization.SerializerSink sink) { sink.BeginDataType("StudyComponent"); base.Serialize(sink); sink.Element("uid", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, true, false); UidElement?.Serialize(sink); sink.Element("imagingStudy", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, false, false); ImagingStudy?.Serialize(sink); sink.BeginList("endpoint", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, false); foreach(var item in Endpoint) { item?.Serialize(sink); } sink.End(); sink.BeginList("series", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, true); foreach(var item in Series) { item?.Serialize(sink); } sink.End(); sink.End(); } public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as StudyComponent; if (dest != null) { base.CopyTo(dest); if(UidElement != null) dest.UidElement = (Hl7.Fhir.Model.Oid)UidElement.DeepCopy(); if(ImagingStudy != null) dest.ImagingStudy = (Hl7.Fhir.Model.ResourceReference)ImagingStudy.DeepCopy(); if(Endpoint != null) dest.Endpoint = new List<Hl7.Fhir.Model.ResourceReference>(Endpoint.DeepCopy()); if(Series != null) dest.Series = new List<SeriesComponent>(Series.DeepCopy()); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new StudyComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as StudyComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(UidElement, otherT.UidElement)) return false; if( !DeepComparable.Matches(ImagingStudy, otherT.ImagingStudy)) return false; if( !DeepComparable.Matches(Endpoint, otherT.Endpoint)) return false; if( !DeepComparable.Matches(Series, otherT.Series)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as StudyComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(UidElement, otherT.UidElement)) return false; if( !DeepComparable.IsExactly(ImagingStudy, otherT.ImagingStudy)) return false; if( !DeepComparable.IsExactly(Endpoint, otherT.Endpoint)) return false; if( !DeepComparable.IsExactly(Series, otherT.Series)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (UidElement != null) yield return UidElement; if (ImagingStudy != null) yield return ImagingStudy; foreach (var elem in Endpoint) { if (elem != null) yield return elem; } foreach (var elem in Series) { if (elem != null) yield return elem; } } } [NotMapped] internal override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (UidElement != null) yield return new ElementValue("uid", UidElement); if (ImagingStudy != null) yield return new ElementValue("imagingStudy", ImagingStudy); foreach (var elem in Endpoint) { if (elem != null) yield return new ElementValue("endpoint", elem); } foreach (var elem in Series) { if (elem != null) yield return new ElementValue("series", elem); } } } } [FhirType(Hl7.Fhir.Model.Version.STU3, "SeriesComponent")] [DataContract] public partial class SeriesComponent : Hl7.Fhir.Model.BackboneElement, System.ComponentModel.INotifyPropertyChanged, IComponent { [NotMapped] public override string TypeName { get { return "SeriesComponent"; } } /// <summary> /// Series instance UID /// </summary> [FhirElement("uid", InSummary=Hl7.Fhir.Model.Version.All, Order=40)] [CLSCompliant(false)] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.Oid UidElement { get { return _UidElement; } set { _UidElement = value; OnPropertyChanged("UidElement"); } } private Hl7.Fhir.Model.Oid _UidElement; /// <summary> /// Series instance UID /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Uid { get { return UidElement != null ? UidElement.Value : null; } set { if (value == null) UidElement = null; else UidElement = new Hl7.Fhir.Model.Oid(value); OnPropertyChanged("Uid"); } } /// <summary> /// Series access endpoint /// </summary> [FhirElement("endpoint", InSummary=Hl7.Fhir.Model.Version.All, Order=50)] [CLSCompliant(false)] [References("Endpoint")] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.ResourceReference> Endpoint { get { if(_Endpoint==null) _Endpoint = new List<Hl7.Fhir.Model.ResourceReference>(); return _Endpoint; } set { _Endpoint = value; OnPropertyChanged("Endpoint"); } } private List<Hl7.Fhir.Model.ResourceReference> _Endpoint; /// <summary> /// The selected instance /// </summary> [FhirElement("instance", InSummary=Hl7.Fhir.Model.Version.All, Order=60)] [CLSCompliant(false)] [Cardinality(Min=1,Max=-1)] [DataMember] public List<InstanceComponent> Instance { get { if(_Instance==null) _Instance = new List<InstanceComponent>(); return _Instance; } set { _Instance = value; OnPropertyChanged("Instance"); } } private List<InstanceComponent> _Instance; internal override void Serialize(Serialization.SerializerSink sink) { sink.BeginDataType("SeriesComponent"); base.Serialize(sink); sink.Element("uid", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, true, false); UidElement?.Serialize(sink); sink.BeginList("endpoint", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, false); foreach(var item in Endpoint) { item?.Serialize(sink); } sink.End(); sink.BeginList("instance", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, true); foreach(var item in Instance) { item?.Serialize(sink); } sink.End(); sink.End(); } public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as SeriesComponent; if (dest != null) { base.CopyTo(dest); if(UidElement != null) dest.UidElement = (Hl7.Fhir.Model.Oid)UidElement.DeepCopy(); if(Endpoint != null) dest.Endpoint = new List<Hl7.Fhir.Model.ResourceReference>(Endpoint.DeepCopy()); if(Instance != null) dest.Instance = new List<InstanceComponent>(Instance.DeepCopy()); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new SeriesComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as SeriesComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(UidElement, otherT.UidElement)) return false; if( !DeepComparable.Matches(Endpoint, otherT.Endpoint)) return false; if( !DeepComparable.Matches(Instance, otherT.Instance)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as SeriesComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(UidElement, otherT.UidElement)) return false; if( !DeepComparable.IsExactly(Endpoint, otherT.Endpoint)) return false; if( !DeepComparable.IsExactly(Instance, otherT.Instance)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (UidElement != null) yield return UidElement; foreach (var elem in Endpoint) { if (elem != null) yield return elem; } foreach (var elem in Instance) { if (elem != null) yield return elem; } } } [NotMapped] internal override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (UidElement != null) yield return new ElementValue("uid", UidElement); foreach (var elem in Endpoint) { if (elem != null) yield return new ElementValue("endpoint", elem); } foreach (var elem in Instance) { if (elem != null) yield return new ElementValue("instance", elem); } } } } [FhirType(Hl7.Fhir.Model.Version.STU3, "InstanceComponent")] [DataContract] public partial class InstanceComponent : Hl7.Fhir.Model.BackboneElement, System.ComponentModel.INotifyPropertyChanged, IComponent { [NotMapped] public override string TypeName { get { return "InstanceComponent"; } } /// <summary> /// SOP class UID of instance /// </summary> [FhirElement("sopClass", InSummary=Hl7.Fhir.Model.Version.All, Order=40)] [CLSCompliant(false)] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.Oid SopClassElement { get { return _SopClassElement; } set { _SopClassElement = value; OnPropertyChanged("SopClassElement"); } } private Hl7.Fhir.Model.Oid _SopClassElement; /// <summary> /// SOP class UID of instance /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string SopClass { get { return SopClassElement != null ? SopClassElement.Value : null; } set { if (value == null) SopClassElement = null; else SopClassElement = new Hl7.Fhir.Model.Oid(value); OnPropertyChanged("SopClass"); } } /// <summary> /// Selected instance UID /// </summary> [FhirElement("uid", InSummary=Hl7.Fhir.Model.Version.All, Order=50)] [CLSCompliant(false)] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.Oid UidElement { get { return _UidElement; } set { _UidElement = value; OnPropertyChanged("UidElement"); } } private Hl7.Fhir.Model.Oid _UidElement; /// <summary> /// Selected instance UID /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Uid { get { return UidElement != null ? UidElement.Value : null; } set { if (value == null) UidElement = null; else UidElement = new Hl7.Fhir.Model.Oid(value); OnPropertyChanged("Uid"); } } internal override void Serialize(Serialization.SerializerSink sink) { sink.BeginDataType("InstanceComponent"); base.Serialize(sink); sink.Element("sopClass", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, true, false); SopClassElement?.Serialize(sink); sink.Element("uid", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, true, false); UidElement?.Serialize(sink); sink.End(); } public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as InstanceComponent; if (dest != null) { base.CopyTo(dest); if(SopClassElement != null) dest.SopClassElement = (Hl7.Fhir.Model.Oid)SopClassElement.DeepCopy(); if(UidElement != null) dest.UidElement = (Hl7.Fhir.Model.Oid)UidElement.DeepCopy(); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new InstanceComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as InstanceComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(SopClassElement, otherT.SopClassElement)) return false; if( !DeepComparable.Matches(UidElement, otherT.UidElement)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as InstanceComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(SopClassElement, otherT.SopClassElement)) return false; if( !DeepComparable.IsExactly(UidElement, otherT.UidElement)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (SopClassElement != null) yield return SopClassElement; if (UidElement != null) yield return UidElement; } } [NotMapped] internal override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (SopClassElement != null) yield return new ElementValue("sopClass", SopClassElement); if (UidElement != null) yield return new ElementValue("uid", UidElement); } } } /// <summary> /// SOP Instance UID /// </summary> [FhirElement("identifier", InSummary=Hl7.Fhir.Model.Version.All, Order=90)] [CLSCompliant(false)] [DataMember] public Hl7.Fhir.Model.Identifier Identifier { get { return _Identifier; } set { _Identifier = value; OnPropertyChanged("Identifier"); } } private Hl7.Fhir.Model.Identifier _Identifier; /// <summary> /// Patient of the selected objects /// </summary> [FhirElement("patient", InSummary=Hl7.Fhir.Model.Version.All, Order=100)] [CLSCompliant(false)] [References("Patient")] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.ResourceReference Patient { get { return _Patient; } set { _Patient = value; OnPropertyChanged("Patient"); } } private Hl7.Fhir.Model.ResourceReference _Patient; /// <summary> /// Time when the selection of instances was made /// </summary> [FhirElement("authoringTime", InSummary=Hl7.Fhir.Model.Version.All, Order=110)] [CLSCompliant(false)] [DataMember] public Hl7.Fhir.Model.FhirDateTime AuthoringTimeElement { get { return _AuthoringTimeElement; } set { _AuthoringTimeElement = value; OnPropertyChanged("AuthoringTimeElement"); } } private Hl7.Fhir.Model.FhirDateTime _AuthoringTimeElement; /// <summary> /// Time when the selection of instances was made /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string AuthoringTime { get { return AuthoringTimeElement != null ? AuthoringTimeElement.Value : null; } set { if (value == null) AuthoringTimeElement = null; else AuthoringTimeElement = new Hl7.Fhir.Model.FhirDateTime(value); OnPropertyChanged("AuthoringTime"); } } /// <summary> /// Author (human or machine) /// </summary> [FhirElement("author", InSummary=Hl7.Fhir.Model.Version.All, Order=120)] [CLSCompliant(false)] [References("Practitioner","Device","Organization","Patient","RelatedPerson")] [DataMember] public Hl7.Fhir.Model.ResourceReference Author { get { return _Author; } set { _Author = value; OnPropertyChanged("Author"); } } private Hl7.Fhir.Model.ResourceReference _Author; /// <summary> /// Description text /// </summary> [FhirElement("description", InSummary=Hl7.Fhir.Model.Version.All, Order=130)] [CLSCompliant(false)] [DataMember] public Hl7.Fhir.Model.FhirString DescriptionElement { get { return _DescriptionElement; } set { _DescriptionElement = value; OnPropertyChanged("DescriptionElement"); } } private Hl7.Fhir.Model.FhirString _DescriptionElement; /// <summary> /// Description text /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Description { get { return DescriptionElement != null ? DescriptionElement.Value : null; } set { if (value == null) DescriptionElement = null; else DescriptionElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Description"); } } /// <summary> /// Study identity of the selected instances /// </summary> [FhirElement("study", InSummary=Hl7.Fhir.Model.Version.All, Order=140)] [CLSCompliant(false)] [Cardinality(Min=1,Max=-1)] [DataMember] public List<StudyComponent> Study { get { if(_Study==null) _Study = new List<StudyComponent>(); return _Study; } set { _Study = value; OnPropertyChanged("Study"); } } private List<StudyComponent> _Study; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as ImagingManifest; if (dest != null) { base.CopyTo(dest); if(Identifier != null) dest.Identifier = (Hl7.Fhir.Model.Identifier)Identifier.DeepCopy(); if(Patient != null) dest.Patient = (Hl7.Fhir.Model.ResourceReference)Patient.DeepCopy(); if(AuthoringTimeElement != null) dest.AuthoringTimeElement = (Hl7.Fhir.Model.FhirDateTime)AuthoringTimeElement.DeepCopy(); if(Author != null) dest.Author = (Hl7.Fhir.Model.ResourceReference)Author.DeepCopy(); if(DescriptionElement != null) dest.DescriptionElement = (Hl7.Fhir.Model.FhirString)DescriptionElement.DeepCopy(); if(Study != null) dest.Study = new List<StudyComponent>(Study.DeepCopy()); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new ImagingManifest()); } public override bool Matches(IDeepComparable other) { var otherT = other as ImagingManifest; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Identifier, otherT.Identifier)) return false; if( !DeepComparable.Matches(Patient, otherT.Patient)) return false; if( !DeepComparable.Matches(AuthoringTimeElement, otherT.AuthoringTimeElement)) return false; if( !DeepComparable.Matches(Author, otherT.Author)) return false; if( !DeepComparable.Matches(DescriptionElement, otherT.DescriptionElement)) return false; if( !DeepComparable.Matches(Study, otherT.Study)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as ImagingManifest; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Identifier, otherT.Identifier)) return false; if( !DeepComparable.IsExactly(Patient, otherT.Patient)) return false; if( !DeepComparable.IsExactly(AuthoringTimeElement, otherT.AuthoringTimeElement)) return false; if( !DeepComparable.IsExactly(Author, otherT.Author)) return false; if( !DeepComparable.IsExactly(DescriptionElement, otherT.DescriptionElement)) return false; if( !DeepComparable.IsExactly(Study, otherT.Study)) return false; return true; } internal override void Serialize(Serialization.SerializerSink sink) { sink.BeginResource("ImagingManifest"); base.Serialize(sink); sink.Element("identifier", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, false, false); Identifier?.Serialize(sink); sink.Element("patient", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, true, false); Patient?.Serialize(sink); sink.Element("authoringTime", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, false, false); AuthoringTimeElement?.Serialize(sink); sink.Element("author", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, false, false); Author?.Serialize(sink); sink.Element("description", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, false, false); DescriptionElement?.Serialize(sink); sink.BeginList("study", Hl7.Fhir.Model.Version.All, Hl7.Fhir.Model.Version.All, true); foreach(var item in Study) { item?.Serialize(sink); } sink.End(); sink.End(); } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Identifier != null) yield return Identifier; if (Patient != null) yield return Patient; if (AuthoringTimeElement != null) yield return AuthoringTimeElement; if (Author != null) yield return Author; if (DescriptionElement != null) yield return DescriptionElement; foreach (var elem in Study) { if (elem != null) yield return elem; } } } [NotMapped] internal override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Identifier != null) yield return new ElementValue("identifier", Identifier); if (Patient != null) yield return new ElementValue("patient", Patient); if (AuthoringTimeElement != null) yield return new ElementValue("authoringTime", AuthoringTimeElement); if (Author != null) yield return new ElementValue("author", Author); if (DescriptionElement != null) yield return new ElementValue("description", DescriptionElement); foreach (var elem in Study) { if (elem != null) yield return new ElementValue("study", elem); } } } } }
42.113184
151
0.543253
[ "BSD-3-Clause" ]
CareEvolution/fhir-net-api
src/Hl7.Fhir.Core/Model/Generated/STU3/ImagingManifest.cs
33,861
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace WRLDCWarehouse.Core.Entities { public class Transformer { public int TransformerId { get; set; } [Required] public string Name { get; set; } [Required] public string StationType { get; set; } public VoltLevel HighVoltLevel { get; set; } public int HighVoltLevelId { get; set; } public VoltLevel LowVoltLevel { get; set; } // using nullable low voltage levels due to vendor non compliance public int? LowVoltLevelId { get; set; } public MajorSubstation HvSubstation { get; set; } public int? HvSubstationId { get; set; } public GeneratingStation HvGeneratingStation { get; set; } public int? HvGeneratingStationId { get; set; } public int TransformerNumber { get; set; } public TransformerType TransformerType { get; set; } public int TransformerTypeId { get; set; } public State State { get; set; } public int StateId { get; set; } public decimal MVACapacity { get; set; } public DateTime CommDate { get; set; } public DateTime CodDate { get; set; } public DateTime DecommDate { get; set; } public IList<TransformerOwner> TransformerOwners { get; set; } public int WebUatId { get; set; } } }
30.212766
73
0.634507
[ "MIT" ]
POSOCO/wrldc_data_warehouse_csharp
WRLDCWarehouse.Core/Entities/Transformer.cs
1,422
C#
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Rise.DrawBatchTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
36.444444
82
0.742886
[ "MIT" ]
ChevyRay/Rise
Rise.DrawBatchTest/Properties/AssemblyInfo.cs
986
C#
/* License * ------------------------------------------------------------------------------ * Copyright (c) 2019 UX Digital Systems Ltd * * Permission is hereby granted, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software * for the continued use and development of the system on which it was installed, * and to permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * Any persons obtaining the software have no rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software without * written persmission from UX Digital Systems Ltd, if it is not for use on the * system on which it was originally installed. * ------------------------------------------------------------------------------ * UX.Digital * ---------- * http://ux.digital * support@ux.digital */ using System; using System.Text; using Crestron.SimplSharp; using Crestron.SimplSharp.CrestronAuthentication; using Crestron.SimplSharp.Cryptography; using Crestron.SimplSharp.Net.Http; namespace UX.Lib2.WebScripting2 { public class Session { private readonly Authentication.UserInformation _user; #region Fields private readonly string _sessionId; private DateTime _expiryTime; #endregion #region Constructors /// <summary> /// The default Constructor. /// </summary> internal Session(Authentication.UserInformation user) { _expiryTime = DateTime.Now.Add(TimeSpan.FromMinutes(120)); _user = user; var md5 = MD5.Create(); var hash = md5.ComputeHash(Encoding.ASCII.GetBytes(DateTime.Now + _user.UserName)); _sessionId = string.Empty; foreach (var b in hash) { _sessionId = _sessionId + b.ToString("x2"); } } #endregion #region Finalizers #endregion #region Events #endregion #region Delegates #endregion #region Properties public string SessionId { get { return _sessionId; } } public Authentication.UserInformation User { get { return _user; } } public DateTime ExpiryTime { get { return _expiryTime; } } #endregion #region Methods public HttpHeader Validate() { if (DateTime.Now >= _expiryTime || !_user.Authenticated) return null; _expiryTime = DateTime.Now.Add(TimeSpan.FromMinutes(120)); return new HttpHeader(string.Format("Set-Cookie: sessionid={0}; HttpOnly; Path=/; Expires={1}", SessionId, _expiryTime.ToUniversalTime().ToString("R"))); } #endregion } }
30.057143
108
0.575729
[ "Unlicense" ]
uxav/lib2
WebScripting2/Session.cs
3,156
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.LicenseManager")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS License Manager. AWS License Manager makes it easier to manage licenses in AWS and on premises when customers run applications using existing licenses from a variety of software vendors including Microsoft, SAP, Oracle, and IBM. AWS License Manager automatically tracks and controls license usage once administrators have created and enforced rules that emulate the terms of their licensing agreements. The capabilities of AWS License Manager are available through SDK and Tools, besides the management console and CLI.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS License Manager. AWS License Manager makes it easier to manage licenses in AWS and on premises when customers run applications using existing licenses from a variety of software vendors including Microsoft, SAP, Oracle, and IBM. AWS License Manager automatically tracks and controls license usage once administrators have created and enforced rules that emulate the terms of their licensing agreements. The capabilities of AWS License Manager are available through SDK and Tools, besides the management console and CLI.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWS License Manager. AWS License Manager makes it easier to manage licenses in AWS and on premises when customers run applications using existing licenses from a variety of software vendors including Microsoft, SAP, Oracle, and IBM. AWS License Manager automatically tracks and controls license usage once administrators have created and enforced rules that emulate the terms of their licensing agreements. The capabilities of AWS License Manager are available through SDK and Tools, besides the management console and CLI.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWS License Manager. AWS License Manager makes it easier to manage licenses in AWS and on premises when customers run applications using existing licenses from a variety of software vendors including Microsoft, SAP, Oracle, and IBM. AWS License Manager automatically tracks and controls license usage once administrators have created and enforced rules that emulate the terms of their licensing agreements. The capabilities of AWS License Manager are available through SDK and Tools, besides the management console and CLI.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- AWS License Manager. AWS License Manager makes it easier to manage licenses in AWS and on premises when customers run applications using existing licenses from a variety of software vendors including Microsoft, SAP, Oracle, and IBM. AWS License Manager automatically tracks and controls license usage once administrators have created and enforced rules that emulate the terms of their licensing agreements. The capabilities of AWS License Manager are available through SDK and Tools, besides the management console and CLI.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- AWS License Manager. AWS License Manager makes it easier to manage licenses in AWS and on premises when customers run applications using existing licenses from a variety of software vendors including Microsoft, SAP, Oracle, and IBM. AWS License Manager automatically tracks and controls license usage once administrators have created and enforced rules that emulate the terms of their licensing agreements. The capabilities of AWS License Manager are available through SDK and Tools, besides the management console and CLI.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.101.111")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
90.661017
614
0.802393
[ "Apache-2.0" ]
alefranz/aws-sdk-net
sdk/src/Services/LicenseManager/Properties/AssemblyInfo.cs
5,349
C#
using System; using System.Collections.Generic; using Xunit; namespace NCoreUtils.Extensions.Unit { public class ListTests { [Fact] public void Pop() { var list = new List<int> { 1, 2 }; var list0 = new List<int>(); Assert.Throws<ArgumentNullException>(() => ListExtensions.Pop<int>(null)); Assert.Throws<InvalidOperationException>(() => list0.Pop()); Assert.Equal(2, list.Pop()); Assert.Equal(new [] { 1 }, list); } } }
23.478261
86
0.55
[ "MIT" ]
artyomszasa/NCoreUtils.Extensions
NCoreUtils.Extensions.Unit/ListTests.cs
540
C#
using CoreAnimation; using CoreGraphics; using System; namespace ControlExplorer.iOS { public static class Gradient { public static CAGradientLayer GetGradientLayer (CGColor colorTop, CGColor colorBottom, nfloat width, nfloat height) { var gradLayer = new CAGradientLayer(); gradLayer.Frame = new CGRect(0, 0, width, height); gradLayer.Colors = new CGColor[] { colorTop, colorBottom }; gradLayer.StartPoint = new CGPoint(0, 0); gradLayer.EndPoint = new CGPoint(0, 1); return gradLayer; } } }
29.619048
124
0.614148
[ "MIT" ]
JunielKatarn/XAM330
Exercise 3/Completed/ControlExplorer/ControlExplorer.iOS/Gradient.iOS.cs
622
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Roslynator.CSharp.Refactorings.AddExceptionToDocumentationComment { internal class ThrowExpressionInfo : ThrowInfo { internal ThrowExpressionInfo(ThrowExpressionSyntax node, ExpressionSyntax expression, ITypeSymbol exceptionSymbol, ISymbol declarationSymbol) : base(node, expression, exceptionSymbol, declarationSymbol) { } protected override IParameterSymbol GetParameterSymbolCore( SemanticModel semanticModel, CancellationToken cancellationToken) { SyntaxNode parent = Node.Parent; if (parent?.IsKind(SyntaxKind.CoalesceExpression) == true) { parent = parent.Parent; if (parent?.IsKind(SyntaxKind.SimpleAssignmentExpression) == true) { var assignment = (AssignmentExpressionSyntax)parent; ExpressionSyntax left = assignment.Left; if (left != null) { ISymbol leftSymbol = semanticModel.GetSymbol(left, cancellationToken); if (leftSymbol?.IsParameter() == true && leftSymbol.ContainingSymbol?.Equals(DeclarationSymbol) == true) { return (IParameterSymbol)leftSymbol; } } } } return null; } } }
36.346939
160
0.595733
[ "Apache-2.0" ]
TechnoridersForks/Roslynator
source/Common/CSharp/Refactorings/AddExceptionToDocumentationComment/ThrowExpressionInfo.cs
1,783
C#
namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostCtrl { struct NvHostCtrlSyncptWaitEx { public int Id; public int Thresh; public int Timeout; public int Value; } }
21.6
62
0.643519
[ "Unlicense" ]
Dudejoe870/Ryujinx
Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostCtrl/Types/NvHostCtrlSyncPtWaitEx.cs
216
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\shared\ksmedia.h(4768,9) using System; using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct __struct_ksmedia_1136 { public int Property; public _VBICODECFILTERING_CC_SUBSTREAMS Substreams; } }
25.357143
88
0.735211
[ "MIT" ]
bbday/DirectN
DirectN/DirectN/Generated/__struct_ksmedia_1136.cs
357
C#
using System.Web; namespace CCCIntegration { public class Global : HttpApplication { protected void Application_Start() { } } }
13.833333
42
0.596386
[ "Apache-2.0" ]
MSU-Libraries/ccc-integration
CCCIntegration/Global.asax.cs
168
C#
// Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Build.Construction; using Microsoft.Build.Execution; using Microsoft.VisualStudio.Buffers.PooledObjects; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.Build { /// <summary> /// Utility class to manipulate MsBuild projects. /// </summary> internal static class BuildUtilities { /// <summary> /// Returns a value indicating whether the specified property has a condition that /// always evaluates to <see langword="true"/>. /// </summary> public static bool HasWellKnownConditionsThatAlwaysEvaluateToTrue(ProjectPropertyElement element) { Requires.NotNull(element, nameof(element)); // We look for known conditions that evaluate to true so that // projects can have patterns where they opt in/out of target // frameworks based on whether they are inside Visual Studio or not. // For example: // // <TargetFrameworks>net461;net452</TargetFrameworks> // <TargetFrameworks Condition = "'$(BuildingInsideVisualStudio)' == 'true'">net461</TargetFrameworks> switch (element.Condition) { case "": case "true": case "'$(OS)' == 'Windows_NT'": case "'$(BuildingInsideVisualStudio)' == 'true'": return true; } return false; } /// <summary> /// Gets a project property. /// </summary> /// <param name="project">Xml representation of the MsBuild project.</param> /// <param name="propertyName">Name of the property.</param> /// <returns>Requested project property. Null if the property is not present.</returns> public static ProjectPropertyElement? GetProperty(ProjectRootElement project, string propertyName) { Requires.NotNull(project, "project"); return project.Properties .FirstOrDefault(p => string.Equals(p.Name, propertyName, StringComparisons.PropertyNames)); } /// <summary> /// Gets the individual values of a delimited property. /// </summary> /// <param name="propertyValue">Value of the property to evaluate.</param> /// <param name="delimiter">Character used to delimit the property values.</param> /// <returns>Collection of individual values in the property.</returns> public static IEnumerable<string> GetPropertyValues(string propertyValue, char delimiter = ';') { HashSet<string>? seen = null; // We need to ensure that we return values in the specified order. foreach (string value in new LazyStringSplit(propertyValue, delimiter)) { string s = value.Trim(); if (!string.IsNullOrEmpty(s)) { if (seen == null) { seen = new HashSet<string>(StringComparers.PropertyValues) { s }; yield return s; } else { if (seen.Add(s)) { yield return s; } } } } } /// <summary> /// Appends a value to a delimited property. If the property does not exist it will be added. /// </summary> /// <param name="project">Xml representation of the MsBuild project.</param> /// <param name="evaluatedPropertyValue">Original evaluated value of the property.</param> /// <param name="propertyName">Property name.</param> /// <param name="valueToAppend">Value to add to the property.</param> /// <param name="delimiter">Character used to delimit the property values.</param> public static void AppendPropertyValue(ProjectRootElement project, string evaluatedPropertyValue, string propertyName, string valueToAppend, char delimiter = ';') { Requires.NotNull(project, nameof(project)); Requires.NotNull(evaluatedPropertyValue, nameof(evaluatedPropertyValue)); Requires.NotNullOrEmpty(propertyName, nameof(propertyName)); ProjectPropertyElement property = GetOrAddProperty(project, propertyName); var newValue = PooledStringBuilder.GetInstance(); foreach (string value in GetPropertyValues(evaluatedPropertyValue, delimiter)) { newValue.Append(value); newValue.Append(delimiter); } newValue.Append(valueToAppend); property.Value = newValue.ToStringAndFree(); } /// <summary> /// Renames a value inside a delimited property. /// </summary> /// <param name="project">Xml representation of the MsBuild project.</param> /// <param name="evaluatedPropertyValue">Original evaluated value of the property.</param> /// <param name="propertyName">Property name.</param> /// <param name="valueToRemove">Value to remove from the property.</param> /// <param name="delimiter">Character used to delimit the property values.</param> /// <remarks> /// If the property is not present it will be added. This means that the evaluated property /// value came from one of the project imports. /// </remarks> public static void RemovePropertyValue(ProjectRootElement project, string evaluatedPropertyValue, string propertyName, string valueToRemove, char delimiter = ';') { Requires.NotNull(project, nameof(project)); Requires.NotNull(evaluatedPropertyValue, nameof(evaluatedPropertyValue)); Requires.NotNullOrEmpty(propertyName, nameof(propertyName)); ProjectPropertyElement property = GetOrAddProperty(project, propertyName); var newValue = new StringBuilder(); bool valueFound = false; foreach (string value in GetPropertyValues(evaluatedPropertyValue, delimiter)) { if (!string.Equals(value, valueToRemove, StringComparisons.PropertyValues)) { if (newValue.Length != 0) { newValue.Append(delimiter); } newValue.Append(value); } else { valueFound = true; } } property.Value = newValue.ToString(); if (!valueFound) { throw new ArgumentException(string.Format(Resources.MsBuildMissingValueToRemove, valueToRemove, propertyName), nameof(valueToRemove)); } } /// <summary> /// Renames a value inside a delimited property. /// </summary> /// <param name="project">Xml representation of the MsBuild project.</param> /// <param name="evaluatedPropertyValue">Original evaluated value of the property.</param> /// <param name="propertyName">Property name.</param> /// <param name="oldValue">Current property value.</param> /// <param name="newValue">New property value.</param> /// <param name="delimiter">Character used to delimit the property values.</param> /// <remarks> /// If the property is not present it will be added. This means that the evaluated property /// value came from one of the project imports. /// </remarks> public static void RenamePropertyValue(ProjectRootElement project, string evaluatedPropertyValue, string propertyName, string? oldValue, string newValue, char delimiter = ';') { Requires.NotNull(project, nameof(project)); Requires.NotNull(evaluatedPropertyValue, nameof(evaluatedPropertyValue)); Requires.NotNullOrEmpty(propertyName, nameof(propertyName)); ProjectPropertyElement property = GetOrAddProperty(project, propertyName); var value = new StringBuilder(); bool valueFound = false; foreach (string propertyValue in GetPropertyValues(evaluatedPropertyValue, delimiter)) { if (value.Length != 0) { value.Append(delimiter); } if (string.Equals(propertyValue, oldValue, StringComparisons.PropertyValues)) { value.Append(newValue); valueFound = true; } else { value.Append(propertyValue); } } property.Value = value.ToString(); if (!valueFound) { throw new ArgumentException(string.Format(Resources.MsBuildMissingValueToRename, oldValue, propertyName), nameof(oldValue)); } } /// <summary> /// Adds a property to the first property group. If there are no property groups it will create one. /// </summary> /// <param name="project">Xml representation of the MsBuild project.</param> /// <param name="propertyName">Property name.</param> public static ProjectPropertyElement GetOrAddProperty(ProjectRootElement project, string propertyName) { Requires.NotNull(project, "project"); ProjectPropertyElement? property = GetProperty(project, propertyName); if (property != null) { return property; } else { ProjectPropertyGroupElement propertyGroup; if (project.PropertyGroups.Count == 0) { propertyGroup = project.AddPropertyGroup(); } else { propertyGroup = project.PropertyGroups.First(); } return propertyGroup.AddProperty(propertyName, string.Empty); } } /// <summary> /// Returns a value indicating if the specified <see cref="ProjectItemInstance"/> /// originated in an imported file. /// </summary> /// <returns> /// <see langword="true"/> if <paramref name="item"/> originated in an imported file; /// otherwise, <see langword="false"/> if it was defined in the project being built. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="item"/> is <see langword="null"/>. /// </exception> public static bool IsImported(this ProjectItemInstance item) { Requires.NotNull(item, nameof(item)); string definingProjectFullPath = item.GetMetadataValue("DefiningProjectFullPath"); string projectFullPath = item.Project.FullPath; // NOTE: This returns project being built, not owning target return !StringComparers.Paths.Equals(definingProjectFullPath, projectFullPath); } } }
44.172285
201
0.571901
[ "MIT" ]
77-A/.Net-Project
src/Microsoft.VisualStudio.ProjectSystem.Managed/Build/BuildUtilities.cs
11,530
C#
using System; using System.IO; using System.Threading; using Robotics.Serialization; #if MF_FRAMEWORK_VERSION_V4_3 using VariableList = System.Collections.ArrayList; using CommandList = System.Collections.ArrayList; #else using VariableList = System.Collections.Generic.List<Robotics.Messaging.Variable>; using CommandList = System.Collections.Generic.List<Robotics.Messaging.Command>; #endif namespace Robotics.Messaging { /// <summary> /// This is a global object that enables apps to publish or broadcast /// </summary> public class ControlServer { readonly ObjectReader reader; readonly ObjectWriter writer; readonly VariableList variables = new VariableList (); readonly CommandList commands = new CommandList (); public ControlServer (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); this.reader = new PortableBinaryObjectReader(stream); this.writer = new PortableBinaryObjectWriter(stream); Start (); } void SendVariable(Variable v) { SendHeaderAndMessage(new VariableMessage(v)); } void SendVariableValue(Variable v) { SendHeaderAndMessage(new VariableValueMessage(v)); } void SendCommand(Command c) { SendHeaderAndMessage(new CommandMessage(c)); } void SendCommandResult(Command c, int exeId, object result) { SendHeaderAndMessage(new CommandResultMessage(c, exeId, result)); } int id = 1; class ServerVariable : Variable { public ControlServer Server; public VariableChangedAction ChangedAction; public override void SetValue (object newVal) { if (Value != null && Value.Equals (newVal)) return; base.SetValue (newVal); if (ChangedAction != null) ChangedAction (this); Server.SendVariableValue (this); } } public Variable RegisterVariable (string name, object value, VariableChangedAction changedAction = null) { var v = new ServerVariable { Server = this, ChangedAction = changedAction, Id = id++, Name = name, Value = value, IsWriteable = changedAction != null, }; variables.Add (v); SendVariable (v); return v; } class ServerCommand : Command { public CommandFunc Function; } public Command RegisterCommand (string name, CommandFunc func) { if (name == null) throw new ArgumentNullException ("name"); if (func == null) throw new ArgumentNullException ("func"); var c = new ServerCommand { Id = id++, Name = name, Function = func, }; commands.Add (c); SendCommand (c); return c; } void SetVariableValue(Variable v, object value) { if (v == null) throw new ArgumentNullException("v"); v.Value = value; SendVariableValue(v); } void Start () { #if MF_FRAMEWORK_VERSION_V4_3 new Thread (Run).Start (); #else System.Threading.Tasks.Task.Factory.StartNew (Run, System.Threading.Tasks.TaskCreationOptions.LongRunning); #endif } void Run () { // Preallocate messages (not thread-safe) var header = new Header (); var getVariablesMessage = new GetVariablesMessage(); var setVariableValueMessage = new SetVariableValueMessage(); var getCommandsMessage = new GetCommandsMessage(); var executeCommandMessage = new ExecuteCommandMessage(); for (; ; ) { try { ReadHeader(header); DebugPrint("Received header: " + header.ToString()); switch (header.Operation) { case ControlOp.GetVariables: ReadMessage(getVariablesMessage); ProcessMessage(getVariablesMessage); break; case ControlOp.SetVariableValue: ReadMessage(setVariableValueMessage); ProcessMessage(setVariableValueMessage); break; case ControlOp.GetCommands: ReadMessage(getCommandsMessage); ProcessMessage(getCommandsMessage); break; case ControlOp.ExecuteCommand: ReadMessage(executeCommandMessage); ProcessMessage(executeCommandMessage); break; default: // Unrecognized operation UnknownMessage unknownMessage = new UnknownMessage(); ReadMessage(unknownMessage); break; } } catch (Exception ex) { DebugPrint ("!! " + ex + "\n"); throw; } } } void ProcessMessage(GetVariablesMessage m) { foreach (Variable v in variables) { SendVariable(v); DebugPrint("Sent Variable " + v.Name); #if MF_FRAMEWORK_VERSION_V4_3 Thread.Sleep (10); // Throttle #endif } } void ProcessMessage(SetVariableValueMessage m) { foreach (ServerVariable v in variables) { if (v.Id == m.Id) { v.Value = m.Value; DebugPrint("Set " + v.Name + " = " + m.Value); break; } } } void ProcessMessage(GetCommandsMessage m) { foreach (Command c in commands) { SendCommand(c); DebugPrint("Sent Command " + c.Name); #if MF_FRAMEWORK_VERSION_V4_3 Thread.Sleep (10); // Throttle #endif } } void ProcessMessage(ExecuteCommandMessage m) { foreach (ServerCommand c in commands) { if (c.Id == m.CommandId) { var result = c.Function(); SendCommandResult(c, m.ExecutionId, result); DebugPrint("Executed Command " + c.Name); } } } void SendHeaderAndMessage(Message m) { var header = new Header(m.Operation); header.Write(this.writer); m.Write(this.writer); } void ReadHeader(Header h) { h.Read(this.reader); DebugPrint("Received header: " + h.ToString()); } void ReadMessage(Message m) { m.Read(this.reader); DebugPrint("Received message: " + m.ToString()); } [System.Diagnostics.Conditional("DEBUG")] static void DebugPrint (string s) { #if MF_FRAMEWORK_VERSION_V4_3 Microsoft.SPOT.Debug.Print (s); #endif } } }
22.91635
111
0.642276
[ "Apache-2.0" ]
webmonger/Monkey.Robotics
Source/Platform Stacks/Robotics.Mobile.Core/Messaging/ControlServer.cs
6,029
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void XorSByte() { var test = new SimpleBinaryOpTest__XorSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__XorSByte { private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector256<SByte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<SByte> _fld1; private Vector256<SByte> _fld2; private SimpleBinaryOpTest__DataTable<SByte, SByte, SByte> _dataTable; static SimpleBinaryOpTest__XorSByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); } public SimpleBinaryOpTest__XorSByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<SByte, SByte, SByte>(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Xor( Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Xor( Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Xor( Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Xor( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__XorSByte(); var result = Avx2.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Xor(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<SByte> left, Vector256<SByte> right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { if ((sbyte)(left[0] ^ right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((sbyte)(left[i] ^ right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Xor)}<SByte>(Vector256<SByte>, Vector256<SByte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
42.888218
175
0.574669
[ "MIT" ]
AaronRobinsonMSFT/coreclr
tests/src/JIT/HardwareIntrinsics/X86/Avx2/Xor.SByte.cs
14,196
C#
using System.Collections.Generic; using System.Linq; namespace TopDownProteomics.Chemistry { /// <summary> /// Default implementation of an element. /// </summary> /// <seealso cref="IElement" /> public class Element : IElement { /// <summary> /// Initializes a new instance of the <see cref="Element"/> class. /// </summary> /// <param name="atomicNumber">The atomic number.</param> /// <param name="symbol">The symbol.</param> /// <param name="isotopes">The isotopes.</param> public Element(int atomicNumber, string symbol, IReadOnlyCollection<IIsotope> isotopes) { this.AtomicNumber = atomicNumber; this.Symbol = symbol; this.Isotopes = isotopes; } /// <summary> /// Get the element's atomic number /// </summary> public int AtomicNumber { get; } /// <summary> /// Gets the element's symbol /// </summary> public string Symbol { get; } /// <summary> /// Gets the Isotopes that make up the element /// </summary> public IReadOnlyCollection<IIsotope> Isotopes { get; } /// <summary> /// Gets the mass. /// </summary> /// <param name="massType">Type of the mass.</param> /// <returns></returns> public double GetMass(MassType massType) { return massType == MassType.Monoisotopic ? this.Isotopes.FirstWithMax(isotope => isotope.RelativeAbundance).AtomicMass // Should be most abundant, naturally occuring isotope : this.Isotopes.Sum(isotope => isotope.AtomicMass * isotope.RelativeAbundance); } /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns> public bool Equals(IElement other) { // Check for null. if (other == null) { return false; } // Check for object equality. if (this == other) { return true; } IReadOnlyCollection<IIsotope> otherIsotopes = other.Isotopes; // Check the number of isotopes. if (this.Isotopes.Count != otherIsotopes.Count) { return false; } // Check all isotopes. foreach (IIsotope isotope in this.Isotopes) { IIsotope otherIsotope = otherIsotopes.SingleOrDefault(i => i.NeutronCount == isotope.NeutronCount); // Make sure the other element has this isotope. if (otherIsotope == null) { return false; } // Check abundances. if (isotope.RelativeAbundance != otherIsotope.RelativeAbundance) { return false; } } return true; } } }
33.255102
148
0.534213
[ "MIT" ]
acesnik/TestLib
src/TopDownProteomics/Chemistry/Element.cs
3,261
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Datadog.Outputs { [OutputType] public sealed class DashboardWidgetToplistDefinitionRequestFormulaLimit { public readonly int? Count; public readonly string? Order; [OutputConstructor] private DashboardWidgetToplistDefinitionRequestFormulaLimit( int? count, string? order) { Count = count; Order = order; } } }
25.233333
88
0.667107
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-datadog
sdk/dotnet/Outputs/DashboardWidgetToplistDefinitionRequestFormulaLimit.cs
757
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the fsx-2018-03-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.FSx.Model { /// <summary> /// The configuration for this Microsoft Windows file system. /// </summary> public partial class WindowsFileSystemConfiguration { private string _activeDirectoryId; private List<Alias> _aliases = new List<Alias>(); private int? _automaticBackupRetentionDays; private bool? _copyTagsToBackups; private string _dailyAutomaticBackupStartTime; private WindowsDeploymentType _deploymentType; private List<string> _maintenanceOperationsInProgress = new List<string>(); private string _preferredFileServerIp; private string _preferredSubnetId; private string _remoteAdministrationEndpoint; private SelfManagedActiveDirectoryAttributes _selfManagedActiveDirectoryConfiguration; private int? _throughputCapacity; private string _weeklyMaintenanceStartTime; /// <summary> /// Gets and sets the property ActiveDirectoryId. /// <para> /// The ID for an existing Microsoft Active Directory instance that the file system should /// join when it's created. /// </para> /// </summary> [AWSProperty(Min=12, Max=12)] public string ActiveDirectoryId { get { return this._activeDirectoryId; } set { this._activeDirectoryId = value; } } // Check to see if ActiveDirectoryId property is set internal bool IsSetActiveDirectoryId() { return this._activeDirectoryId != null; } /// <summary> /// Gets and sets the property Aliases. /// </summary> [AWSProperty(Max=50)] public List<Alias> Aliases { get { return this._aliases; } set { this._aliases = value; } } // Check to see if Aliases property is set internal bool IsSetAliases() { return this._aliases != null && this._aliases.Count > 0; } /// <summary> /// Gets and sets the property AutomaticBackupRetentionDays. /// <para> /// The number of days to retain automatic backups. Setting this to 0 disables automatic /// backups. You can retain automatic backups for a maximum of 90 days. /// </para> /// </summary> [AWSProperty(Min=0, Max=90)] public int AutomaticBackupRetentionDays { get { return this._automaticBackupRetentionDays.GetValueOrDefault(); } set { this._automaticBackupRetentionDays = value; } } // Check to see if AutomaticBackupRetentionDays property is set internal bool IsSetAutomaticBackupRetentionDays() { return this._automaticBackupRetentionDays.HasValue; } /// <summary> /// Gets and sets the property CopyTagsToBackups. /// <para> /// A boolean flag indicating whether tags on the file system should be copied to backups. /// This value defaults to false. If it's set to true, all tags on the file system are /// copied to all automatic backups and any user-initiated backups where the user doesn't /// specify any tags. If this value is true, and you specify one or more tags, only the /// specified tags are copied to backups. If you specify one or more tags when creating /// a user-initiated backup, no tags are copied from the file system, regardless of this /// value. /// </para> /// </summary> public bool CopyTagsToBackups { get { return this._copyTagsToBackups.GetValueOrDefault(); } set { this._copyTagsToBackups = value; } } // Check to see if CopyTagsToBackups property is set internal bool IsSetCopyTagsToBackups() { return this._copyTagsToBackups.HasValue; } /// <summary> /// Gets and sets the property DailyAutomaticBackupStartTime. /// <para> /// The preferred time to take daily automatic backups, in the UTC time zone. /// </para> /// </summary> [AWSProperty(Min=5, Max=5)] public string DailyAutomaticBackupStartTime { get { return this._dailyAutomaticBackupStartTime; } set { this._dailyAutomaticBackupStartTime = value; } } // Check to see if DailyAutomaticBackupStartTime property is set internal bool IsSetDailyAutomaticBackupStartTime() { return this._dailyAutomaticBackupStartTime != null; } /// <summary> /// Gets and sets the property DeploymentType. /// <para> /// Specifies the file system deployment type, valid values are the following: /// </para> /// <ul> <li> /// <para> /// <code>MULTI_AZ_1</code> - Specifies a high availability file system that is configured /// for Multi-AZ redundancy to tolerate temporary Availability Zone (AZ) unavailability, /// and supports SSD and HDD storage. /// </para> /// </li> <li> /// <para> /// <code>SINGLE_AZ_1</code> - (Default) Specifies a file system that is configured for /// single AZ redundancy, only supports SSD storage. /// </para> /// </li> <li> /// <para> /// <code>SINGLE_AZ_2</code> - Latest generation Single AZ file system. Specifies a file /// system that is configured for single AZ redundancy and supports SSD and HDD storage. /// </para> /// </li> </ul> /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/fsx/latest/WindowsGuide/high-availability-multiAZ.html">Single-AZ /// and Multi-AZ File Systems</a>. /// </para> /// </summary> public WindowsDeploymentType DeploymentType { get { return this._deploymentType; } set { this._deploymentType = value; } } // Check to see if DeploymentType property is set internal bool IsSetDeploymentType() { return this._deploymentType != null; } /// <summary> /// Gets and sets the property MaintenanceOperationsInProgress. /// <para> /// The list of maintenance operations in progress for this file system. /// </para> /// </summary> [AWSProperty(Max=20)] public List<string> MaintenanceOperationsInProgress { get { return this._maintenanceOperationsInProgress; } set { this._maintenanceOperationsInProgress = value; } } // Check to see if MaintenanceOperationsInProgress property is set internal bool IsSetMaintenanceOperationsInProgress() { return this._maintenanceOperationsInProgress != null && this._maintenanceOperationsInProgress.Count > 0; } /// <summary> /// Gets and sets the property PreferredFileServerIp. /// <para> /// For <code>MULTI_AZ_1</code> deployment types, the IP address of the primary, or preferred, /// file server. /// </para> /// /// <para> /// Use this IP address when mounting the file system on Linux SMB clients or Windows /// SMB clients that are not joined to a Microsoft Active Directory. Applicable for all /// Windows file system deployment types. This IP address is temporarily unavailable when /// the file system is undergoing maintenance. For Linux and Windows SMB clients that /// are joined to an Active Directory, use the file system's DNSName instead. For more /// information on mapping and mounting file shares, see <a href="https://docs.aws.amazon.com/fsx/latest/WindowsGuide/accessing-file-shares.html">Accessing /// File Shares</a>. /// </para> /// </summary> [AWSProperty(Min=7, Max=15)] public string PreferredFileServerIp { get { return this._preferredFileServerIp; } set { this._preferredFileServerIp = value; } } // Check to see if PreferredFileServerIp property is set internal bool IsSetPreferredFileServerIp() { return this._preferredFileServerIp != null; } /// <summary> /// Gets and sets the property PreferredSubnetId. /// <para> /// For <code>MULTI_AZ_1</code> deployment types, it specifies the ID of the subnet where /// the preferred file server is located. Must be one of the two subnet IDs specified /// in <code>SubnetIds</code> property. Amazon FSx serves traffic from this subnet except /// in the event of a failover to the secondary file server. /// </para> /// /// <para> /// For <code>SINGLE_AZ_1</code> and <code>SINGLE_AZ_2</code> deployment types, this value /// is the same as that for <code>SubnetIDs</code>. For more information, see <a href="https://docs.aws.amazon.com/fsx/latest/WindowsGuide/high-availability-multiAZ.html#single-multi-az-resources">Availability /// and Durability: Single-AZ and Multi-AZ File Systems</a> /// </para> /// </summary> [AWSProperty(Min=15, Max=24)] public string PreferredSubnetId { get { return this._preferredSubnetId; } set { this._preferredSubnetId = value; } } // Check to see if PreferredSubnetId property is set internal bool IsSetPreferredSubnetId() { return this._preferredSubnetId != null; } /// <summary> /// Gets and sets the property RemoteAdministrationEndpoint. /// <para> /// For <code>MULTI_AZ_1</code> deployment types, use this endpoint when performing administrative /// tasks on the file system using Amazon FSx Remote PowerShell. /// </para> /// /// <para> /// For <code>SINGLE_AZ_1</code> and <code>SINGLE_AZ_2</code> deployment types, this is /// the DNS name of the file system. /// </para> /// /// <para> /// This endpoint is temporarily unavailable when the file system is undergoing maintenance. /// </para> /// </summary> [AWSProperty(Min=16, Max=275)] public string RemoteAdministrationEndpoint { get { return this._remoteAdministrationEndpoint; } set { this._remoteAdministrationEndpoint = value; } } // Check to see if RemoteAdministrationEndpoint property is set internal bool IsSetRemoteAdministrationEndpoint() { return this._remoteAdministrationEndpoint != null; } /// <summary> /// Gets and sets the property SelfManagedActiveDirectoryConfiguration. /// </summary> public SelfManagedActiveDirectoryAttributes SelfManagedActiveDirectoryConfiguration { get { return this._selfManagedActiveDirectoryConfiguration; } set { this._selfManagedActiveDirectoryConfiguration = value; } } // Check to see if SelfManagedActiveDirectoryConfiguration property is set internal bool IsSetSelfManagedActiveDirectoryConfiguration() { return this._selfManagedActiveDirectoryConfiguration != null; } /// <summary> /// Gets and sets the property ThroughputCapacity. /// <para> /// The throughput of an Amazon FSx file system, measured in megabytes per second. /// </para> /// </summary> [AWSProperty(Min=8, Max=2048)] public int ThroughputCapacity { get { return this._throughputCapacity.GetValueOrDefault(); } set { this._throughputCapacity = value; } } // Check to see if ThroughputCapacity property is set internal bool IsSetThroughputCapacity() { return this._throughputCapacity.HasValue; } /// <summary> /// Gets and sets the property WeeklyMaintenanceStartTime. /// <para> /// The preferred start time to perform weekly maintenance, formatted d:HH:MM in the UTC /// time zone. d is the weekday number, from 1 through 7, beginning with Monday and ending /// with Sunday. /// </para> /// </summary> [AWSProperty(Min=7, Max=7)] public string WeeklyMaintenanceStartTime { get { return this._weeklyMaintenanceStartTime; } set { this._weeklyMaintenanceStartTime = value; } } // Check to see if WeeklyMaintenanceStartTime property is set internal bool IsSetWeeklyMaintenanceStartTime() { return this._weeklyMaintenanceStartTime != null; } } }
39.522857
217
0.617726
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/FSx/Generated/Model/WindowsFileSystemConfiguration.cs
13,833
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "Always", menuName = "Mars Motion/Dependency Requisites/Always")] public class Always : DependencyRequisite { // methods // // method: determine the (boolean) state of this Dependency Requisite // public override bool state() { return true; } }
22.625
93
0.748619
[ "MIT" ]
MartianDust/MartianDust-Project
Assets/Plugins/Mars Motion Toolkit/Dependencies/Requisites/Always.cs
364
C#
using FuneralClientV2.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FuneralClientV2.Modules { public class VRCMod { public virtual string Name => "Example Module"; public virtual string Description => "Example Description"; public virtual bool RequiresUpdate { get; set; } public VRCMod() => ConsoleUtil.Info($"VRC Mod {this.Name} has Loaded. {this.Description}"); public virtual void OnStart() { } public virtual void OnUpdate() { } } }
20.193548
99
0.64377
[ "MIT" ]
Kila-Quack-Kila/Funeral_ClientV2
FuneralClientV2/Modules/VRCMod.cs
628
C#
using System.Collections.Generic; using SOLID.Entities; namespace SOLID.Repositories { public interface IOtherStaffRepository { IEnumerable<IOtherStaff> GetOtherStaffs(); IOtherStaff GetOtherStaff(int id); void CreateOtherStaff(IOtherStaff otherStaff); void UpdateOtherStaff(IOtherStaff otherStaff); void DeleteOtherStaff(int id); } }
27.928571
54
0.71867
[ "MIT" ]
nihalshahria/SOLID
Repositories/IOtherStaffRepository.cs
391
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MixERP.Net.FrontEnd.Setup.Policy { public partial class Store { protected System.Web.UI.WebControls.Content Content1; } }
28.421053
80
0.485185
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
gj86/mixerp2
MixERP.Net.FrontEnd/Setup/Policy/Store.aspx.designer.cs
540
C#
 namespace LCL.Domain.Model { /// <summary> /// 表示“地址”领域概念的值对象。 /// </summary> public class Address { #region Private Fields private string country; private string state; private string city; private string street; private string zip; #endregion #region Public Static Fields /// <summary> /// 获取一个<c>Address</c>类型的值,该值表示一个空地址。 /// </summary> public static readonly Address Emtpy = new Address(null, null, null, null, null); #endregion #region Ctor /// <summary> /// 初始化一个<c>Address</c>类型的实例。 /// </summary> public Address() { } /// <summary> /// 初始化一个<c>Address</c>类型的实例。 /// </summary> /// <param name="country">“地址”中的“国家”部分信息。</param> /// <param name="state">“地址”中的“省份/州”部分信息。</param> /// <param name="city">“地址”中的“市”部分信息。</param> /// <param name="street">“地址”中的“街道”部分信息。</param> /// <param name="zip">“地址”中的“邮政区码”部分信息。</param> public Address(string country, string state, string city, string street, string zip) { this.country = country; this.state = state; this.city = city; this.street = street; this.zip = zip; } #endregion #region Public Properties /// <summary> /// 获取或设置“地址”类型中“国家”部分的信息。 /// </summary> public string Country { get { return country; } set { this.country = value; } } /// <summary> /// 获取或设置“地址”类型中“省份/州”部分的信息。 /// </summary> public string State { get { return state; } set { this.state = value; } } /// <summary> /// 获取或设置“地址”类型中“市”部分的信息。 /// </summary> public string City { get { return city; } set { this.city = value; } } /// <summary> /// 获取或设置“地址”类型中“街道”部分的信息。 /// </summary> public string Street { get { return street; } set { this.street = value; } } /// <summary> /// 获取或设置“地址”类型中“邮政区码”部分的信息。 /// </summary> public string Zip { get { return zip; } set { this.zip = value; } } #endregion #region Public Methods /// <summary> /// 确定指定的Object是否等于当前的Object。 /// </summary> /// <param name="obj">要与当前对象进行比较的对象。</param> /// <returns>如果指定的Object与当前Object相等,则返回true,否则返回false。</returns> /// <remarks>有关此函数的更多信息,请参见:http://msdn.microsoft.com/zh-cn/library/system.object.equals。 /// </remarks> public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj == null) return false; Address other = obj as Address; if ((object)other == null) return false; return this.country.Equals(other.country) && this.state.Equals(other.state) && this.city.Equals(other.city) && this.street.Equals(other.street) && this.zip.Equals(other.zip); } /// <summary> /// 用作特定类型的哈希函数。 /// </summary> /// <returns>当前Object的哈希代码。</returns> /// <remarks>有关此函数的更多信息,请参见:http://msdn.microsoft.com/zh-cn/library/system.object.gethashcode。 /// </remarks> public override int GetHashCode() { return this.country.GetHashCode() ^ this.state.GetHashCode() ^ this.city.GetHashCode() ^ this.street.GetHashCode() ^ this.zip.GetHashCode(); } /// <summary> /// 返回表示当前Object的字符串。 /// </summary> /// <returns>表示当前对象的字符串。</returns> public override string ToString() { return string.Format("{0} {1}, {2}, {3}, {4}", zip, street, city, state, country); } #endregion #region Public Static Operator Overrides /// <summary> /// 确定两个“地址”对象是否相等。 /// </summary> /// <param name="a">待确定的第一个“地址”对象。</param> /// <param name="b">待确定的另一个“地址”对象。</param> /// <returns>如果两者相等,则返回true,否则返回false。</returns> public static bool operator ==(Address a, Address b) { if ((object)a == null) { return (object)b == null; } return a.Equals(b); } /// <summary> /// 确定两个“地址”对象是否不相等。 /// </summary> /// <param name="a">待确定的第一个“地址”对象。</param> /// <param name="b">待确定的另一个“地址”对象。</param> /// <returns>如果两者不相等,则返回true,否则返回false。</returns> public static bool operator !=(Address a, Address b) { return !(a == b); } #endregion } }
30.798817
103
0.466475
[ "Apache-2.0" ]
luomingui/LCLFramework
LCLDemo/LCL.Domain/Model/Address.cs
6,179
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Mono.Unix; using Mono.Unix.Native; namespace EventStore.Native.UnixSignalManager { public class UnixSignalManager { private static UnixSignalManager _instance; private const int MaxUnixSignals = 64; //max internal limit of UnixSignal instances per process private static readonly List<UnixSignal> _handledSignals = new List<UnixSignal>(); private static readonly object _handledSignalsLock = new object(); private readonly Dictionary<Signum, List<Action>> _actions = new Dictionary<Signum, List<Action>>(); private volatile bool _stop; public static UnixSignalManager GetInstance() => _instance ??= new UnixSignalManager(); private UnixSignalManager() { new Thread(HandleSignals) { IsBackground = true, Name = "UnixSignalManager" }.Start(); } public void Subscribe(Signum signum, Action action) { lock (_handledSignalsLock) { if (_handledSignals.All(x => x.Signum != signum)) { if (_handledSignals.Count >= MaxUnixSignals) { throw new ArgumentException($"Maximum limit of {MaxUnixSignals} reached for number of handled signals."); } _handledSignals.Add(new UnixSignal(signum)); } } if (_actions.TryGetValue(signum, out List<Action> actions)) { actions.Add(action); } else { _actions[signum] = new List<Action> { action }; } } public static void StopProcessing() { _instance?.Stop(); } private void Stop() { _stop = true; } private void HandleSignals() { const int timeoutMs = 1000; while (!_stop) { UnixSignal[] handledSignals; lock (_handledSignalsLock) { handledSignals = _handledSignals.ToArray(); } var index = UnixSignal.WaitAny(handledSignals, TimeSpan.FromMilliseconds(timeoutMs)); if (index == timeoutMs) continue; if (_actions.TryGetValue(handledSignals[index].Signum, out List<Action> actions)) { foreach (var action in actions) { action.Invoke(); } } handledSignals[index].Reset(); } } } }
28.226667
111
0.705243
[ "Apache-2.0", "CC0-1.0" ]
01100010011001010110010101110000/EventStore
src/EventStore.Native/UnixSignalManager/UnixSignalManager.cs
2,117
C#
#region Using directives using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #endregion namespace Blazorise.DataGrid { public abstract class _BaseDataGridDetailRow<TItem> : BaseDataGridComponent { #region Members #endregion #region Methods #endregion #region Properties protected bool HasCommandColumn => Columns.Any( x => x.ColumnType == DataGridColumnType.Command ); protected string CommandColumnLocation { get { if ( Columns.Count > 1 && HasCommandColumn ) { if ( Columns[0].ColumnType == DataGridColumnType.Command ) return "start"; else if ( Columns[Columns.Count - 1].ColumnType == DataGridColumnType.Command ) return "end"; } return string.Empty; } } /// <summary> /// Item associated with the data set. /// </summary> [Parameter] public TItem Item { get; set; } /// <summary> /// List of columns used to build this row. /// </summary> [Parameter] public IReadOnlyList<DataGridColumn<TItem>> Columns { get; set; } [CascadingParameter] protected DataGrid<TItem> ParentDataGrid { get; set; } [Parameter] public RenderFragment ChildContent { get; set; } #endregion } }
26.413793
106
0.57376
[ "MIT" ]
DarthPedro/Blazorise
Source/Extensions/Blazorise.DataGrid/_DataGridDetailRow.razor.cs
1,534
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Portal.RecoveryServices.Models.Common; using System; using System.Linq; using System.Management.Automation; using System.Security.Cryptography.X509Certificates; namespace Microsoft.Azure.Commands.SiteRecovery { /// <summary> /// Retrieves Azure Site Recovery Vault Settings File. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmSiteRecoveryVaultSettingsFile", DefaultParameterSetName = ASRParameterSets.ByParam)] [OutputType(typeof(VaultSettingsFilePath))] public class GetAzureSiteRecoveryVaultSettingsFile : SiteRecoveryCmdletBase { /// <summary> /// Expiry in hours for generated certificate. /// </summary> private const int VaultCertificateExpiryInHoursForHRM = 120; #region Parameters /// <summary> /// Gets or sets vault Object. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.Default, Mandatory = true, ValueFromPipeline = true)] [Parameter(ParameterSetName = ASRParameterSets.ForSite, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRVault Vault { get; set; } /// <summary> /// Gets or sets Site Identifier. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.ForSite, Mandatory = true)] [ValidateNotNullOrEmpty] public String SiteIdentifier { get; set; } /// <summary> /// Gets or sets SiteFriendlyName. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.ForSite, Mandatory = true)] [ValidateNotNullOrEmpty] public String SiteFriendlyName { get; set; } /// <summary> /// Gets or sets the path where the credential file is to be generated /// </summary> /// <summary> /// Gets or sets vault Object. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.Default)] [Parameter(ParameterSetName = ASRParameterSets.ForSite)] public string Path { get; set; } #endregion Parameters /// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); try { this.GetVaultSettingsFile(); } catch (AggregateException aggregateEx) { // if an exception is thrown from a task, it will be wrapped in AggregateException // and propagated to the main thread. Just throwing the first exception in the list. throw aggregateEx.InnerExceptions.First<Exception>(); } } /// <summary> /// Method to execute the command /// </summary> private void GetVaultSettingsFile() { AzureSubscription subscription = DefaultProfile.Context.Subscription; // Generate certificate X509Certificate2 cert = CertUtils.CreateSelfSignedCertificate(VaultCertificateExpiryInHoursForHRM, subscription.Id.ToString(), this.Vault.Name); ASRSite site = new ASRSite(); if (!string.IsNullOrEmpty(this.SiteIdentifier) && !string.IsNullOrEmpty(this.SiteFriendlyName)) { site.ID = this.SiteIdentifier; site.Name = this.SiteFriendlyName; } // Generate file. ASRVaultCreds vaultCreds = RecoveryServicesClient.GenerateVaultCredential( cert, this.Vault, site); string filePath = string.IsNullOrEmpty(this.Path) ? Utilities.GetDefaultPath() : this.Path; string fileName = this.GenerateFileName(); // write the content to a file. VaultSettingsFilePath output = new VaultSettingsFilePath() { FilePath = Utilities.WriteToFile<ASRVaultCreds>(vaultCreds, filePath, fileName) }; // print the path to the user. this.WriteObject(output, true); } /// <summary> /// Method to generate the file name /// </summary> /// <returns>file name as string.</returns> private string GenerateFileName() { string fileName; string format = "yyyy-MM-ddTHH-mm-ss"; if (string.IsNullOrEmpty(this.SiteIdentifier) || string.IsNullOrEmpty(this.SiteFriendlyName)) { fileName = string.Format("{0}_{1}.VaultCredentials", this.Vault.Name, DateTime.UtcNow.ToString(format)); } else { fileName = string.Format("{0}_{1}_{2}.VaultCredentials", this.SiteFriendlyName, this.Vault.Name, DateTime.UtcNow.ToString(format)); } return fileName; } } }
39.646667
157
0.58231
[ "MIT" ]
FosterMichelle/azure-powershell
src/ResourceManager/SiteRecovery/Commands.SiteRecovery/Vault/GetAzureSiteRecoveryVaultSettingsFile.cs
5,800
C#
namespace RTEditor { public enum BoxFace { Front = 0, Back, Top, Bottom, Left, Right } }
12.5
23
0.413333
[ "MIT" ]
zzf/ShaderProgramProj
Assets/Runtime_Transform_Gizmos/Scripts/Math/Box/BoxFace.cs
152
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Security.Authentication { public partial class AuthenticationException : System.SystemException { public AuthenticationException() { } protected AuthenticationException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public AuthenticationException(string message) { } public AuthenticationException(string message, System.Exception innerException) { } } public enum CipherAlgorithmType { Aes = 26129, Aes128 = 26126, Aes192 = 26127, Aes256 = 26128, Des = 26113, None = 0, Null = 24576, Rc2 = 26114, Rc4 = 26625, TripleDes = 26115, } public enum ExchangeAlgorithmType { DiffieHellman = 43522, None = 0, RsaKeyX = 41984, RsaSign = 9216, } public enum HashAlgorithmType { Md5 = 32771, None = 0, Sha1 = 32772, Sha256 = 32780, Sha384 = 32781, Sha512 = 32782, } public partial class InvalidCredentialException : System.Security.Authentication.AuthenticationException { public InvalidCredentialException() { } protected InvalidCredentialException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public InvalidCredentialException(string message) { } public InvalidCredentialException(string message, System.Exception innerException) { } } [System.FlagsAttribute] public enum SslProtocols { [System.ObsoleteAttribute("This value has been deprecated. It is no longer supported. http://go.microsoft.com/fwlink/?linkid=14202")] Default = 240, None = 0, [System.ObsoleteAttribute("This value has been deprecated. It is no longer supported. http://go.microsoft.com/fwlink/?linkid=14202")] Ssl2 = 12, [System.ObsoleteAttribute("This value has been deprecated. It is no longer supported. http://go.microsoft.com/fwlink/?linkid=14202")] Ssl3 = 48, Tls = 192, Tls11 = 768, Tls12 = 3072, } }
37.676923
178
0.667211
[ "MIT" ]
mmitche/standard
netstandard/ref/System.Security.Authentication.cs
2,449
C#
using Faker.Tests.Base; using NUnit.Framework; namespace Faker.Tests.en { [TestFixture] [SetUICulture("en")] [SetCulture("en")] [Category("Culture 'en'")] public class PhoneEnglishTests : PhoneTestsBase {} }
18
51
0.662393
[ "MIT" ]
AdmiringWorm/Faker.NET.Portable
tests/Faker.Tests/en_PhoneEnglishTests.cs
236
C#
namespace Microsoft.VisualStudio.Shell.Interop { public interface IVsPreviewChangesList { int GetFlags(out uint pFlags); int GetItemCount(out uint pCount); int GetExpandedList(uint index, out int pfCanRecurse, out object pptlNode); int LocateExpandedList(object ExpandedList, out uint iIndex); int OnClose(object[] ptca); int GetText(uint index, object tto, out string ppszText); int GetTipText(uint index, object eTipType, out string ppszText); int GetExpandable(uint index, out int pfExpandable); int GetDisplayData(uint index, object[] pData); int UpdateCounter(out uint pCurUpdate, out uint pgrfChanges); int GetListChanges(ref uint pcChanges, object[] prgListChanges); int ToggleState(uint index, out uint ptscr); int OnRequestSource(uint index, object pIUnknownTextView); } }
27.636364
83
0.691886
[ "Apache-2.0" ]
JetBrains/JetBrains.EnvDTE
Shell.Interop/Shell/Interop/IVsPreviewChangesList.cs
914
C#
// // Popover.cs // // Author: // Jérémie Laval <jeremie.laval@xamarin.com> // // Copyright (c) 2012 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Accessibility; using Xwt.Drawing; using Xwt.Backends; namespace Xwt { [BackendType (typeof(IPopoverBackend))] public class Popover : XwtComponent { public enum Position { Top, Bottom, /*Left, Right*/ } WidgetSpacing padding; Widget content; bool shown; Accessible accessible; public virtual bool StaysOpen { get { return this.Backend.StaysOpen; } set { this.Backend.StaysOpen = value; } } public bool IsVisible { get { return this.Backend.IsVisible; } } EventHandler closedEvent; protected class PopoverBackendHost: BackendHost<Popover,IPopoverBackend>, IPopoverEventSink { protected override void OnBackendCreated () { base.OnBackendCreated (); Backend.Initialize (this); } public void OnClosed () { ((Popover)Parent).OnClosed (); } } protected override BackendHost CreateBackendHost () { return new PopoverBackendHost (); } IPopoverBackend Backend { get { return ((PopoverBackendHost) BackendHost).Backend; } } public Popover () { } public Popover (Widget content) { VerifyConstructorCall (this); Content = content; } public Accessible Accessible { get { if (accessible == null) { accessible = new Accessible (this); } return accessible; } } public Widget Content { get { return content; } set { if (shown) throw new InvalidOperationException ("The content widget can't be changed while the popover is visible"); content = value; } } public WidgetSpacing Padding { get { return padding; } set { padding = value; UpdatePadding (); } } public double PaddingLeft { get { return padding.Left; } set { padding.Left = value; UpdatePadding (); } } public double PaddingRight { get { return padding.Right; } set { padding.Right = value; UpdatePadding (); } } public double PaddingTop { get { return padding.Top; } set { padding.Top = value; UpdatePadding (); } } public double PaddingBottom { get { return padding.Bottom; } set { padding.Bottom = value; UpdatePadding (); } } public Color BackgroundColor { get { return Backend.BackgroundColor; } set { Backend.BackgroundColor = value; } } void UpdatePadding () { } public void Show (Position arrowPosition, Widget referenceWidget) { Show (arrowPosition, referenceWidget, Xwt.Rectangle.Zero); } public void Show (Position arrowPosition, Widget referenceWidget, Xwt.Rectangle positionRect) { if (content == null) throw new InvalidOperationException ("A child widget source must be set before running the Popover"); Backend.Show (arrowPosition, referenceWidget, positionRect, content); shown = true; } public void Hide () { Backend.Hide (); } protected override void Dispose (bool disposing) { base.Dispose (disposing); // Don't dispose the backend if this object is being finalized // The backend has to handle the finalizing on its own if (disposing && BackendHost.BackendCreated) Backend.Dispose (); } [MappedEvent(PopoverEvent.Closed)] protected virtual void OnClosed () { shown = false; if (closedEvent != null) closedEvent (this, EventArgs.Empty); } public event EventHandler Closed { add { BackendHost.OnBeforeEventAdd (PopoverEvent.Closed, closedEvent); closedEvent += value; } remove { closedEvent -= value; BackendHost.OnAfterEventRemove (PopoverEvent.Closed, closedEvent); } } } }
22.509346
110
0.682167
[ "MIT" ]
TheBrainTech/xwt
Xwt/Xwt/Popover.cs
4,819
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace XNAPlatformerLevelEditor { class TileDisplay : GraphicsDeviceControl { public event EventHandler OnInitialize; public event EventHandler OnDraw; protected override void Initialize() { if (OnInitialize != null) OnInitialize(this, null); } protected override void Draw() { if (OnDraw != null) OnDraw(this, null); } } }
21.115385
47
0.590164
[ "Unlicense" ]
sndcode/jaxg
XNAPlatformerLevelEditor/Classes/TileDisplay.cs
551
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Send_and_Receive_Messages { class Quaternion { public double w, x, y, z; public Quaternion() { w = 1.0; x = y = z = 0.0; } public Quaternion(Vec3 v) { w = 0.0; x = v.x; y = v.y; z = v.z; } // Rotate "angle" around the vector "v" public Quaternion(double angle, Vec3 v) { w = Math.Cos(angle / 2); var s = Math.Sin(angle / 2); x = s * v.x; y = s * v.y; z = s * v.z; } public Quaternion Conjugate() { var r = new Quaternion { w = w, x = -x, y = -y, z = -z }; return r; } public Quaternion Product(Quaternion o) { var r = new Quaternion { w = w * o.w - x * o.x - y * o.y - z * o.z, x = w * o.x + x * o.w + y * o.z - z * o.y, y = w * o.y - x * o.z + y * o.w + z * o.x, z = w * o.z + x * o.y - y * o.x + z * o.w }; return r; } public Vec3 Rotate(Vec3 v) { var rv = new Vec3(); var vq = new Quaternion(v); var hq = this.Product(vq); var rq = hq.Product(this.Conjugate()); rv.x = rq.x; rv.y = rq.y; rv.z = rq.z; return rv; } } }
22.303797
59
0.34563
[ "MIT" ]
cupix-api/player
WinForms .NET sample/Quaternion.cs
1,764
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using EnsureThat; using Hl7.Fhir.Model; using Microsoft.Health.Fhir.Core.Extensions; using Microsoft.Health.Fhir.Core.Features.Conformance; using Microsoft.Health.Fhir.Core.Features.Persistence; namespace Microsoft.Health.Fhir.Core.Features.Resources { public abstract class BaseResourceHandler { private readonly IResourceWrapperFactory _resourceWrapperFactory; private readonly ResourceIdProvider _resourceIdProvider; protected BaseResourceHandler( IFhirDataStore fhirDataStore, Lazy<IConformanceProvider> conformanceProvider, IResourceWrapperFactory resourceWrapperFactory, ResourceIdProvider resourceIdProvider) { EnsureArg.IsNotNull(fhirDataStore, nameof(fhirDataStore)); EnsureArg.IsNotNull(conformanceProvider, nameof(conformanceProvider)); EnsureArg.IsNotNull(resourceWrapperFactory, nameof(resourceWrapperFactory)); EnsureArg.IsNotNull(resourceIdProvider, nameof(resourceIdProvider)); ConformanceProvider = conformanceProvider; FhirDataStore = fhirDataStore; _resourceWrapperFactory = resourceWrapperFactory; _resourceIdProvider = resourceIdProvider; } protected Lazy<IConformanceProvider> ConformanceProvider { get; } protected IFhirDataStore FhirDataStore { get; } protected ResourceWrapper CreateResourceWrapper(Resource resource, bool deleted) { if (string.IsNullOrEmpty(resource.Id)) { resource.Id = _resourceIdProvider.Create(); } if (resource.Meta == null) { resource.Meta = new Meta(); } // store with millisecond precision resource.Meta.LastUpdated = Clock.UtcNow.UtcDateTime.TruncateToMillisecond(); ResourceWrapper resourceWrapper = _resourceWrapperFactory.Create(resource.ToResourceElement(), deleted); return resourceWrapper; } } }
39.112903
116
0.633402
[ "MIT" ]
BoyaWu10/fhir-server
src/Microsoft.Health.Fhir.Shared.Core/Features/Resources/BaseResourceHandler.cs
2,425
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("07_CountNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("07_CountNumbers")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d1d614a2-31ab-4c00-aec8-c5b3edfc876f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.783784
84
0.748927
[ "MIT" ]
kr056/SoftUni
Programming Fundamentals May 2017/08_C# Lists Lab/07_CountNumbers/Properties/AssemblyInfo.cs
1,401
C#
using JCSoft.Core.Net.Http; using JCSoft.WX.Framework.Models.ApiResponses; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace JCSoft.WX.Framework.Models.ApiRequests { /// <summary> /// 创建个性化菜单 /// </summary> public class MenuAddConditionalRequest : ApiRequest<MenuAddConditionalResponse> { protected MenuAddConditionalRequest() { } internal override HttpRequestActionType Method => HttpRequestActionType.Content; protected override string UrlFormat => "/cgi-bin/menu/addconditional?access_token={0}"; protected override bool NeedToken => true; internal override string GetPostContent() { return JsonConvert.SerializeObject(this); } internal override string GetUrl() { return String.Format(UrlFormat, AccessToken); } [JsonProperty("button")] public List<ClickButton> Buttons { get; set; } [JsonProperty("matchrule")] public MatchRule MatchRule { get; set; } } public class MatchRule { [JsonProperty("tag_id")] public string TagId { get; set; } [JsonIgnore] public Sex Sex { get; set; } [JsonProperty("sex")] public string SexString { get { return Sex.ToInt32String(); } } [JsonProperty("country")] public string Country { get; set; } [JsonProperty("province")] public string Province { get; set; } [JsonProperty("city")] public string City { get; set; } [JsonIgnore] public ClientPlatform ClientPlatform { get; set; } [JsonProperty("client_platform_type")] public string ClientPlatformString { get { return ClientPlatform.ToInt32String(); } } [JsonProperty("language")] public string Language { get; set; } } public enum Sex { Male = 1, Female = 2, None = 99 } public enum ClientPlatform { IOS = 1, Android = 2, Other = 3 } }
22.36
95
0.567084
[ "MIT" ]
JamesYing/JCWXCore
src/JCSoft.WX.Framework/Models/ApiRequests/MenuAddConditionalRequest.cs
2,252
C#
using EventStore.ClientAPI.Exceptions; using EventStore.ClientAPI.SystemData; using EventStore.Core.Services; using NUnit.Framework; namespace EventStore.Core.Tests.ClientAPI.Security { [TestFixture, Category("LongRunning"), Category("Network")] public class system_stream_security: AuthenticationTestBase { [Test, Category("LongRunning"), Category("Network")] public void operations_on_system_stream_with_no_acl_set_fail_for_non_admin() { Expect<AccessDeniedException>(() => ReadEvent("$system-no-acl", "user1", "pa$$1")); Expect<AccessDeniedException>(() => ReadStreamForward("$system-no-acl", "user1", "pa$$1")); Expect<AccessDeniedException>(() => ReadStreamBackward("$system-no-acl", "user1", "pa$$1")); Expect<AccessDeniedException>(() => WriteStream("$system-no-acl", "user1", "pa$$1")); Expect<AccessDeniedException>(() => TransStart("$system-no-acl", "user1", "pa$$1")); { var transId = TransStart("$system-no-acl", "adm", "admpa$$").TransactionId; var trans = Connection.ContinueTransaction(transId, new UserCredentials("user1", "pa$$1")); ExpectNoException(() => trans.Write()); Expect<AccessDeniedException>(() => trans.Commit()); }; Expect<AccessDeniedException>(() => ReadMeta("$system-no-acl", "user1", "pa$$1")); Expect<AccessDeniedException>(() => WriteMeta("$system-no-acl", "user1", "pa$$1", null)); Expect<AccessDeniedException>(() => SubscribeToStream("$system-no-acl", "user1", "pa$$1")); } [Test, Category("LongRunning"), Category("Network")] public void operations_on_system_stream_with_no_acl_set_succeed_for_admin() { ExpectNoException(() => ReadEvent("$system-no-acl", "adm", "admpa$$")); ExpectNoException(() => ReadStreamForward("$system-no-acl", "adm", "admpa$$")); ExpectNoException(() => ReadStreamBackward("$system-no-acl", "adm", "admpa$$")); ExpectNoException(() => WriteStream("$system-no-acl", "adm", "admpa$$")); ExpectNoException(() => TransStart("$system-no-acl", "adm", "admpa$$")); { var transId = TransStart("$system-no-acl", "adm", "admpa$$").TransactionId; var trans = Connection.ContinueTransaction(transId, new UserCredentials("adm", "admpa$$")); ExpectNoException(() => trans.Write()); ExpectNoException(() => trans.Commit()); }; ExpectNoException(() => ReadMeta("$system-no-acl", "adm", "admpa$$")); ExpectNoException(() => WriteMeta("$system-no-acl", "adm", "admpa$$", null)); ExpectNoException(() => SubscribeToStream("$system-no-acl", "adm", "admpa$$")); } [Test, Category("LongRunning"), Category("Network")] public void operations_on_system_stream_with_acl_set_to_usual_user_fail_for_not_authorized_user() { Expect<AccessDeniedException>(() => ReadEvent("$system-acl", "user2", "pa$$2")); Expect<AccessDeniedException>(() => ReadStreamForward("$system-acl", "user2", "pa$$2")); Expect<AccessDeniedException>(() => ReadStreamBackward("$system-acl", "user2", "pa$$2")); Expect<AccessDeniedException>(() => WriteStream("$system-acl", "user2", "pa$$2")); Expect<AccessDeniedException>(() => TransStart("$system-acl", "user2", "pa$$2")); { var transId = TransStart("$system-acl", "user1", "pa$$1").TransactionId; var trans = Connection.ContinueTransaction(transId, new UserCredentials("user2", "pa$$2")); ExpectNoException(() => trans.Write()); Expect<AccessDeniedException>(() => trans.Commit()); }; Expect<AccessDeniedException>(() => ReadMeta("$system-acl", "user2", "pa$$2")); Expect<AccessDeniedException>(() => WriteMeta("$system-acl", "user2", "pa$$2", "user1")); Expect<AccessDeniedException>(() => SubscribeToStream("$system-acl", "user2", "pa$$2")); } [Test, Category("LongRunning"), Category("Network")] public void operations_on_system_stream_with_acl_set_to_usual_user_succeed_for_that_user() { ExpectNoException(() => ReadEvent("$system-acl", "user1", "pa$$1")); ExpectNoException(() => ReadStreamForward("$system-acl", "user1", "pa$$1")); ExpectNoException(() => ReadStreamBackward("$system-acl", "user1", "pa$$1")); ExpectNoException(() => WriteStream("$system-acl", "user1", "pa$$1")); ExpectNoException(() => TransStart("$system-acl", "user1", "pa$$1")); { var transId = TransStart("$system-acl", "adm", "admpa$$").TransactionId; var trans = Connection.ContinueTransaction(transId, new UserCredentials("user1", "pa$$1")); ExpectNoException(() => trans.Write()); ExpectNoException(() => trans.Commit()); }; ExpectNoException(() => ReadMeta("$system-acl", "user1", "pa$$1")); ExpectNoException(() => WriteMeta("$system-acl", "user1", "pa$$1", "user1")); ExpectNoException(() => SubscribeToStream("$system-acl", "user1", "pa$$1")); } [Test, Category("LongRunning"), Category("Network")] public void operations_on_system_stream_with_acl_set_to_usual_user_succeed_for_admin() { ExpectNoException(() => ReadEvent("$system-acl", "adm", "admpa$$")); ExpectNoException(() => ReadStreamForward("$system-acl", "adm", "admpa$$")); ExpectNoException(() => ReadStreamBackward("$system-acl", "adm", "admpa$$")); ExpectNoException(() => WriteStream("$system-acl", "adm", "admpa$$")); ExpectNoException(() => TransStart("$system-acl", "adm", "admpa$$")); { var transId = TransStart("$system-acl", "user1", "pa$$1").TransactionId; var trans = Connection.ContinueTransaction(transId, new UserCredentials("adm", "admpa$$")); ExpectNoException(() => trans.Write()); ExpectNoException(() => trans.Commit()); }; ExpectNoException(() => ReadMeta("$system-acl", "adm", "admpa$$")); ExpectNoException(() => WriteMeta("$system-acl", "adm", "admpa$$", "user1")); ExpectNoException(() => SubscribeToStream("$system-acl", "adm", "admpa$$")); } [Test, Category("LongRunning"), Category("Network")] public void operations_on_system_stream_with_acl_set_to_admins_fail_for_usual_user() { Expect<AccessDeniedException>(() => ReadEvent("$system-adm", "user1", "pa$$1")); Expect<AccessDeniedException>(() => ReadStreamForward("$system-adm", "user1", "pa$$1")); Expect<AccessDeniedException>(() => ReadStreamBackward("$system-adm", "user1", "pa$$1")); Expect<AccessDeniedException>(() => WriteStream("$system-adm", "user1", "pa$$1")); Expect<AccessDeniedException>(() => TransStart("$system-adm", "user1", "pa$$1")); { var transId = TransStart("$system-adm", "adm", "admpa$$").TransactionId; var trans = Connection.ContinueTransaction(transId, new UserCredentials("user1", "pa$$1")); ExpectNoException(() => trans.Write()); Expect<AccessDeniedException>(() => trans.Commit()); }; Expect<AccessDeniedException>(() => ReadMeta("$system-adm", "user1", "pa$$1")); Expect<AccessDeniedException>(() => WriteMeta("$system-adm", "user1", "pa$$1", SystemRoles.Admins)); Expect<AccessDeniedException>(() => SubscribeToStream("$system-adm", "user1", "pa$$1")); } [Test, Category("LongRunning"), Category("Network")] public void operations_on_system_stream_with_acl_set_to_admins_succeed_for_admin() { ExpectNoException(() => ReadEvent("$system-adm", "adm", "admpa$$")); ExpectNoException(() => ReadStreamForward("$system-adm", "adm", "admpa$$")); ExpectNoException(() => ReadStreamBackward("$system-adm", "adm", "admpa$$")); ExpectNoException(() => WriteStream("$system-adm", "adm", "admpa$$")); ExpectNoException(() => TransStart("$system-adm", "adm", "admpa$$")); { var transId = TransStart("$system-adm", "adm", "admpa$$").TransactionId; var trans = Connection.ContinueTransaction(transId, new UserCredentials("adm", "admpa$$")); ExpectNoException(() => trans.Write()); ExpectNoException(() => trans.Commit()); }; ExpectNoException(() => ReadMeta("$system-adm", "adm", "admpa$$")); ExpectNoException(() => WriteMeta("$system-adm", "adm", "admpa$$", SystemRoles.Admins)); ExpectNoException(() => SubscribeToStream("$system-adm", "adm", "admpa$$")); } [Test, Category("LongRunning"), Category("Network")] public void operations_on_system_stream_with_acl_set_to_all_succeed_for_not_authenticated_user() { ExpectNoException(() => ReadEvent("$system-all", null, null)); ExpectNoException(() => ReadStreamForward("$system-all", null, null)); ExpectNoException(() => ReadStreamBackward("$system-all", null, null)); ExpectNoException(() => WriteStream("$system-all", null, null)); ExpectNoException(() => TransStart("$system-all", null, null)); { var transId = TransStart("$system-all", null, null).TransactionId; var trans = Connection.ContinueTransaction(transId, null); ExpectNoException(() => trans.Write()); ExpectNoException(() => trans.Commit()); }; ExpectNoException(() => ReadMeta("$system-all", null, null)); ExpectNoException(() => WriteMeta("$system-all", null, null, SystemRoles.All)); ExpectNoException(() => SubscribeToStream("$system-all", null, null)); } [Test, Category("LongRunning"), Category("Network")] public void operations_on_system_stream_with_acl_set_to_all_succeed_for_usual_user() { ExpectNoException(() => ReadEvent("$system-all", "user1", "pa$$1")); ExpectNoException(() => ReadStreamForward("$system-all", "user1", "pa$$1")); ExpectNoException(() => ReadStreamBackward("$system-all", "user1", "pa$$1")); ExpectNoException(() => WriteStream("$system-all", "user1", "pa$$1")); ExpectNoException(() => TransStart("$system-all", "user1", "pa$$1")); { var transId = TransStart("$system-all", "user1", "pa$$1").TransactionId; var trans = Connection.ContinueTransaction(transId, new UserCredentials("user1", "pa$$1")); ExpectNoException(() => trans.Write()); ExpectNoException(() => trans.Commit()); }; ExpectNoException(() => ReadMeta("$system-all", "user1", "pa$$1")); ExpectNoException(() => WriteMeta("$system-all", "user1", "pa$$1", SystemRoles.All)); ExpectNoException(() => SubscribeToStream("$system-all", "user1", "pa$$1")); } [Test, Category("LongRunning"), Category("Network")] public void operations_on_system_stream_with_acl_set_to_all_succeed_for_admin() { ExpectNoException(() => ReadEvent("$system-all", "adm", "admpa$$")); ExpectNoException(() => ReadStreamForward("$system-all", "adm", "admpa$$")); ExpectNoException(() => ReadStreamBackward("$system-all", "adm", "admpa$$")); ExpectNoException(() => WriteStream("$system-all", "adm", "admpa$$")); ExpectNoException(() => TransStart("$system-all", "adm", "admpa$$")); { var transId = TransStart("$system-all", "adm", "admpa$$").TransactionId; var trans = Connection.ContinueTransaction(transId, new UserCredentials("adm", "admpa$$")); ExpectNoException(() => trans.Write()); ExpectNoException(() => trans.Commit()); }; ExpectNoException(() => ReadMeta("$system-all", "adm", "admpa$$")); ExpectNoException(() => WriteMeta("$system-all", "adm", "admpa$$", SystemRoles.All)); ExpectNoException(() => SubscribeToStream("$system-all", "adm", "admpa$$")); } } }
54.420601
112
0.575
[ "Apache-2.0" ]
bartelink/EventStore
src/EventStore.Core.Tests/ClientAPI/Security/system_stream_security.cs
12,682
C#
using CodeForDotNet.UI.Models; using Emlid.WindowsIot.Hardware.Boards.Navio; using Emlid.WindowsIot.Hardware.Boards.Navio.Internal; using Emlid.WindowsIot.Tools.Navio2RcioTerminal.Resources; using System; using System.Threading.Tasks; namespace Emlid.WindowsIot.Tools.Navio2RcioTerminal.Models { /// <summary> /// Application UI model. /// </summary> public class RcioTerminalApplicationUIModel : ApplicationUIModel { #region Lifetime /// <summary> /// Creates an instance. /// </summary> public RcioTerminalApplicationUIModel(TaskFactory uiTaskFactory) : base(uiTaskFactory) { // Run on background thread (necessary for C++/WinRT hardware access) Task.Run(() => { // Ensure we are running on a Navio 2 if (NavioDeviceProvider.Detect() != NavioHardwareModel.Navio2) throw new InvalidOperationException(Strings.UnsupportedModelError); // Initialize RCIO Rcio = new Navio2RcioDevice(); }) .Wait(); } #region IDisposable /// <summary> /// Frees resources owned by this instance. /// </summary> /// <param name="disposing"> /// True when called via <see cref="IDisposable.Dispose()"/>, false when called during finalization. /// </param> protected override void Dispose(bool disposing) { try { // Dispose resources when possible if (disposing) Rcio?.Dispose(); } finally { // Dispose base class base.Dispose(disposing); } } #endregion IDisposable #endregion Lifetime #region Properties /// <summary> /// RCIO device. /// </summary> public Navio2RcioDevice Rcio { get; private set; } #endregion Properties } }
28.486111
108
0.555826
[ "Apache-2.0" ]
emlid/Navio-SDK-Windows-IoT
Source/Tools/Navio 2 RCIO Terminal/Models/RcioTerminalApplicationUIModel.cs
2,053
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; //TODO: Fix the stupid dock height because of the scroller namespace JapWew { /// <summary> /// Interaction logic for DiagnosisPage.xaml /// </summary> public partial class DiagnosisPage : Page { public DiagnosisPage() { InitializeComponent(); } void ProcessString(string c) { UnicodeNumberTextBox.Text = HtmlHelper.GetUnicodeCodePoint(c); HtmlCodeTextBox.Text = HtmlHelper.GetHtmlCode(c); HtmlCodeHexTextBox.Text = HtmlHelper.GetHtmlHexCode(c); Utf16leTextBox.Text = HtmlHelper.GetUtf16leData(c); EntityTextBox.Text = c.Length > 0 ? HtmlHelper.GetHtmlEntity(c[0]) : "--"; } private void CharacterTextBox_TextChanged(object sender, TextChangedEventArgs e) { ProcessString(CharacterTextBox.Text); } } }
27.680851
88
0.664105
[ "MIT" ]
dd86k/JapWew
JapWew/DiagnosisPage.xaml.cs
1,303
C#
using System; using System.Configuration; using System.Collections; using System.Collections.Generic; namespace Nucleo.Configuration { /// <summary> /// Rpresents the core collection base class /// </summary> /// <typeparam name="T"></typeparam> public abstract class ConfigurationCollectionBase<T> : ConfigurationElementCollection, IEnumerable<T> where T:ConfigurationElementBase { #region " Properties " /// <summary> /// Gets the type of collection that's built into the .NET framework. By default, this supports using the &lt;add />, &lt;remove />, and &lt;clear /> element definitions to modify the collection. Override this method to change type of collection. /// </summary> public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.AddRemoveClearMap; } } /// <summary> /// Gets a configuration element by is index value. /// </summary> /// <param name="index">The index of the item.</param> /// <returns>The item found at that index, or null.</returns> public T this[int index] { get { return (T)this.BaseGet(index); } set { if (this.BaseGet(index) != null) this.BaseRemoveAt(index); this.BaseAdd(index, value); } } /// <summary> /// Gets the item using the specified key, which maps to the <see cref="ConfigurationElementBase.UniqueKey">unique key</see> of the ConfigurationElementBase class. /// </summary> /// <param name="key">The key of the entry.</param> /// <returns>The instance of the entry, or null if not found.</returns> new public T this[string key] { get { return (T)this.BaseGet(key); } } #endregion #region " Methods " /// <summary> /// Adds a new configuration item to the list. This comes in through the configuration file &lt;add /> statement. /// </summary> /// <param name="element">The element to add.</param> public void Add(T element) { if (element == null) throw new ArgumentNullException("element"); this.BaseAdd(element); } /// <summary> /// Adds a range of elements to the collection. /// </summary> /// <param name="elements">The elements to add to the list.</param> public void AddRange(IEnumerable<T> elements) { if (elements == null) throw new ArgumentNullException("elements"); this.AddRange(elements, false); } /// <summary> /// Adds a range of items that may or may not be duplicates. Ignoring duplicates allows someone to concatenate collections without having to worry about whether duplicate items exist. /// </summary> /// <param name="elements">The elements to add to the collection.</param> /// <param name="ignoreDuplicateKeys">Whether to ignore duplicate keys, which is a violation.</param> public void AddRange(IEnumerable<T> elements, bool ignoreDuplicateKeys) { if (elements == null) throw new ArgumentNullException("elements"); foreach (T element in elements) { if (!ignoreDuplicateKeys || !this.Contains(element.UniqueKey)) this.Add(element); } } /// <summary> /// Clears the entries from the list. This can be triggered from the configuration file's &lt;clear /> element. /// </summary> public void Clear() { this.BaseClear(); } /// <summary> /// Checks whether an item exists in the collection, using the specified key. /// </summary> /// <param name="key">The key of the item to check for existence.</param> /// <returns>Whether the item exists.</returns> /// <remarks>Uses the BaseGet method to check for existence, and if not null, returns true. May not be as efficent as getting the item directly and doing your own null check.</remarks> public bool Contains(string key) { return (this.BaseGet(key) != null); } /// <summary> /// Creates a new instance of the generic element. /// </summary> /// <returns></returns> protected override ConfigurationElement CreateNewElement() { return Activator.CreateInstance<T>(); } /// <summary> /// Gets the element's key using the configuration element. /// </summary> /// <param name="element">The element to get the key for.</param> /// <returns>The key value.</returns> protected override object GetElementKey(ConfigurationElement element) { return ((T)element).UniqueKey; } /// <summary> /// Gets the enumerated list of elements. /// </summary> /// <returns>The enumerator.</returns> public new IEnumerator<T> GetEnumerator() { List<T> items = new List<T>(); IEnumerator enumeratorList = base.GetEnumerator(); while (enumeratorList.MoveNext()) items.Add((T)enumeratorList.Current); return items.GetEnumerator(); } /// <summary> /// Removes an element from the base collection. /// </summary> /// <param name="element">The element to remove.</param> public void Remove(T element) { this.Remove(element.UniqueKey); } /// <summary> /// Removes an element using a key. /// </summary> /// <param name="key">The key to remove.</param> public void Remove(string key) { this.BaseRemove(key); } /// <summary> /// Removes an element using an index. /// </summary> /// <param name="index">The index.</param> public void RemoveAt(int index) { this.BaseRemoveAt(index); } #endregion } }
29.126374
250
0.675344
[ "MIT" ]
brianmains/Nucleo.NET
src/Nucleo/Configuration/ConfigurationCollectionBase.cs
5,301
C#
using System.Collections.Generic; using System; namespace ListaClientes { public class Clientes { //Atributos private string nome; private int idade; //Metodos acessores public string GetNome() { return nome; } public void SetNome(string n) { nome = n; } public int GetIdade() { return idade; } public void SetIdade(int i) { idade = i; } //Metodos public void MostraDados(List<string> j, List<int> data) { for(int i = 0; i < j.Count; i++){ Console.WriteLine($"nome: {j[i]}, e idade: {data[i]}"); } } } }
19.975
86
0.439299
[ "MIT" ]
henrique-artur/ExerciciosCSharp
ListaClientes/Clientes.cs
799
C#
using UnityEngine; public class InventoryHider : MonoBehaviour { private Canvas canvas; public PlayerController player; private void Start() { canvas = GetComponent<Canvas>(); canvas.enabled = false; TradeInterface.OnOpenInventory += OpenCloseRemote; } private void OpenCloseRemote() { if (!canvas.enabled) { canvas.enabled = true; } else { canvas.enabled = false; } } private void Update() { if (Input.GetKeyUp(KeyCode.I) && !player.inDialogue) { canvas.enabled = true; player.inDialogue = true; Time.timeScale = 0f; } else if (Input.GetKeyUp(KeyCode.I) && player.inDialogue) { canvas.enabled = false; player.inDialogue = false; Time.timeScale = 1f; } } }
17.756098
58
0.67033
[ "MIT" ]
Cecilija-Simic-Rihtnesberg/game21-2021-1129-arpg-team-3
Assets/ScriptableObjects/Inventory/InventoryScripts/InventoryHider.cs
728
C#
namespace UnityEngine.TestTools.Logging { internal class LogEvent { public string Message { get; set; } public string StackTrace { get; set; } public LogType LogType { get; set; } public bool IsHandled { get; set; } public override string ToString() { return string.Format("[{0}] {1}", LogType, Message); } } }
21.736842
65
0.539952
[ "MIT" ]
AI-Pree/Small-World
Library/PackageCache/com.unity.test-framework@1.1.24/UnityEngine.TestRunner/Assertions/LogScope/LogEvent.cs
413
C#
using Fluid; using Fluid.Values; using Microsoft.Extensions.DependencyInjection; using OrchardCore.DisplayManagement.Layout; using OrchardCore.Liquid; using System.Threading.Tasks; namespace StatCan.OrchardCore.DisplayHelpers.Filters { public class SectionIsNotEmpty : ILiquidFilter { public async ValueTask<FluidValue> ProcessAsync(FluidValue input, FilterArguments args, LiquidTemplateContext context) { var layoutAccessor = context.Services.GetRequiredService<ILayoutAccessor>(); var layout = await layoutAccessor.GetLayoutAsync(); return BooleanValue.Create(layout.Zones.IsNotEmpty(input.ToStringValue())); } } }
32.904762
126
0.749638
[ "MIT" ]
StatCan/StatCan.OrchardCore
src/Modules/StatCan.OrchardCore.DisplayHelpers/Filters/SectionIsNotEmpty.cs
691
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Outputs { [OutputType] public sealed class WebAclRuleStatementNotStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchAllQueryArguments { [OutputConstructor] private WebAclRuleStatementNotStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchAllQueryArguments() { } } }
32.818182
147
0.781163
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Outputs/WebAclRuleStatementNotStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchAllQueryArguments.cs
722
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; public class Program { static void Main(string[] args) { Family family = new Family(); string namePattern = @"[a-zA-Z0-9]+\s[a-zA-Z0-9]+"; string datePattern = @"\d{1,2}\/\d{1,2}\/\d{4}"; string pattern1 = $@"({namePattern})\s-\s({namePattern})"; string pattern2 = $@"({namePattern})\s-\s({datePattern})"; string pattern3 = $@"({datePattern})\s-\s({namePattern})"; string pattern4 = $@"({datePattern})\s-\s({datePattern})"; string pattern5 = $@"({namePattern})\s({datePattern})"; string mainPersonInput = Console.ReadLine(); string input; List<Person> people = new List<Person>(); List<string> connections = new List<string>(); while ((input = Console.ReadLine()) != "End") { if (Regex.IsMatch(input , pattern5)) { string name = Regex.Match(input, pattern5).Groups[1].Value; string date = Regex.Match(input, pattern5).Groups[2].Value; people.Add(new Person(name, date)); } else { connections.Add(input); } } family.MainPerson = people.FirstOrDefault(x => (x.Name == mainPersonInput) || x.DateOfBirth == mainPersonInput); foreach (var command in connections) { var match1 = Regex.Match(command, pattern1); var match2 = Regex.Match(command, pattern2); var match3 = Regex.Match(command, pattern3); var match4 = Regex.Match(command, pattern4); if (match1.Success) { string olderName = match1.Groups[1].Value; string youngerName = match1.Groups[2].Value; if (olderName == family.MainPerson.Name) { family.Children.Add(people.FirstOrDefault(x => x.Name == youngerName)); } else if (youngerName == family.MainPerson.Name) { family.Parents.Add(people.FirstOrDefault(x => x.Name == olderName)); } } else if (match2.Success) { string olderName = match2.Groups[1].Value; string youngerDate = match2.Groups[2].Value; if (olderName == family.MainPerson.Name) { family.Children.Add(people.FirstOrDefault(x => x.DateOfBirth == youngerDate)); } else if (youngerDate == family.MainPerson.DateOfBirth) { family.Parents.Add(people.FirstOrDefault(x => x.Name == olderName)); } } else if (match3.Success) { string olderDate = match3.Groups[1].Value; string youngerName = match3.Groups[2].Value; if (olderDate == family.MainPerson.DateOfBirth) { family.Children.Add(people.FirstOrDefault(x => x.Name == youngerName)); } else if (youngerName == family.MainPerson.Name) { family.Parents.Add(people.FirstOrDefault(x => x.DateOfBirth == olderDate)); } } else if (match4.Success) { string olderDate = match4.Groups[1].Value; string youngerDate = match4.Groups[2].Value; if (olderDate == family.MainPerson.DateOfBirth) { family.Children.Add(people.FirstOrDefault(x => x.DateOfBirth == youngerDate)); } else if (youngerDate == family.MainPerson.DateOfBirth) { family.Parents.Add(people.FirstOrDefault(x => x.DateOfBirth == olderDate)); } } } Console.WriteLine(family); } }
38.571429
120
0.509383
[ "MIT" ]
danieldamianov/C-OOP-Basics
Exercises Defining Classes/Problem13FamilyTree/Program.cs
4,052
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Singulink.Enums { /// <summary> /// Provides enumeration string conversion functionality. All operations are thread-safe. /// </summary> public sealed class EnumParser<T> where T : unmanaged, Enum { /// <summary> /// Gets the default enumeration parser. /// </summary> public static EnumParser<T> Default { get; } = new EnumParser<T>(); private readonly Dictionary<string, T> _valueLookup; private readonly Dictionary<T, string> _nameLookup; private readonly string _toStringSeparator; private readonly char[] _parseSeparatorArray; private readonly Type _underlyingType; /// <summary> /// Initializes a new instance of the <see cref="EnumParser{T}"/> class. /// </summary> /// <param name="customNameGetter">Optional function to customize enumeration member names.</param> /// <param name="separator">A string containing a separator character with an optional leading and trailing space. This parameter is required for /// flags enumerations and ignored for regular enumerations.</param> /// <param name="caseSensitive">True for case-sensitive names, otherwise false.</param> public EnumParser(Func<EnumMember<T>, string>? customNameGetter = null, string? separator = ", ", bool caseSensitive = true) { customNameGetter ??= m => m.Name; if (Enum<T>.IsFlagsEnum) { _toStringSeparator = separator ?? throw new ArgumentNullException(nameof(separator), "Separator is required for flags enumerations."); _parseSeparatorArray = new[] { GetSeparatorChar(separator) }; if (_parseSeparatorArray[0] == '-') throw new ArgumentException("Hyphen is not allowed as a separator character.", nameof(separator)); } else { _toStringSeparator = string.Empty; _parseSeparatorArray = Array.Empty<char>(); } _underlyingType = Enum.GetUnderlyingType(typeof(T)); _valueLookup = new Dictionary<string, T>(caseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); _nameLookup = new Dictionary<T, string>(); foreach (var member in Enum<T>.GetMembers()) { string name = customNameGetter.Invoke(member)?.Trim(); if (string.IsNullOrEmpty(name)) throw new ArgumentException("Null or empty enumeration member name."); var value = member.Value; if (Enum<T>.IsFlagsEnum && name.Contains(_parseSeparatorArray[0])) throw new ArgumentException($"Enumeration member name '{name}' contains the separator character."); if (_valueLookup.ContainsKey(name)) throw new ArgumentException($"Duplicate enumeration member name '{name}'."); _valueLookup.Add(name, value); _nameLookup[value] = name; } static char GetSeparatorChar(string separator) { if (separator.Length == 1) { return separator[0]; } else if (separator.Length == 2) { if (char.IsWhiteSpace(separator[0]) && !char.IsWhiteSpace(separator[1])) return separator[1]; if (!char.IsWhiteSpace(separator[0]) && char.IsWhiteSpace(separator[1])) return separator[0]; } else if (separator.Length == 3) { if (char.IsWhiteSpace(separator[0]) && !char.IsWhiteSpace(separator[1]) && char.IsWhiteSpace(separator[2])) return separator[1]; } throw new ArgumentException( "Separator must contain exactly 1 separator character with an optional leading and trailing space.", nameof(separator)); } } /// <summary> /// Gets a string representation of the specified enumeration value. /// </summary> /// <param name="value">The enumeration value.</param> /// <param name="allMatchingFlags">True if all matching flags should be included even if they are redundant, or false to only return a minimal set of /// flags. Ignored for non-flags enumerations.</param> public string ToString(T value, bool allMatchingFlags = false) { if (!Enum<T>.IsFlagsEnum) return GetNameOrNumericString(value); return string.Join(_toStringSeparator, value.SplitFlags(allMatchingFlags).Select(GetNameOrNumericString)); // Gets the name of the specified value if it is defined, otherwise gets a string representation of its numeric value: string GetNameOrNumericString(T value) { if (_nameLookup.TryGetValue(value, out string str)) return str; return Convert.ChangeType(value, _underlyingType, CultureInfo.InvariantCulture).ToString()!; } } /// <summary> /// Gets the enumeration value parsed from the specified string. /// </summary> /// <param name="s">The string to be parsed.</param> public T Parse(string s) { if (TryParse(s, out T value)) return value; throw new FormatException("Input string was not in a correct format."); } /// <summary> /// Parses the specified string into an enumeration value. /// </summary> /// <param name="s">The string to be parsed.</param> /// <param name="value">The resulting value.</param> /// <returns>True if parsing was successful, otherwise false.</returns> public bool TryParse(string s, out T value) { s = s.Trim(); if (!Enum<T>.IsFlagsEnum) return TryGetNamedOrNumericValue(s, out value); if (s.Length == 0) { value = default; return true; } var splitOptions = char.IsWhiteSpace(_parseSeparatorArray[0]) ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None; string[] parts = s.Split(_parseSeparatorArray, splitOptions); value = default; for (int i = 0; i < parts.Length; i++) { string part = parts[i].Trim(); if (part.Length > 0) { if (!TryGetNamedOrNumericValue(part, out T partValue)) return false; value = value.SetFlags(partValue); } else if (splitOptions == StringSplitOptions.None) { return false; } } return true; bool TryGetNamedOrNumericValue(string s, out T value) { if (_valueLookup.TryGetValue(s, out value)) return true; try { value = (T)Convert.ChangeType(s, _underlyingType, CultureInfo.InvariantCulture)!; return true; } catch (FormatException) { value = default; return false; } } } } }
41.567568
158
0.555137
[ "MIT" ]
Singulink/Singulink.Enums
Source/Singulink.Enums/EnumParser.cs
7,692
C#
namespace Tizen.NUI.XamlBinding { internal enum ToolbarItemOrder { Default, Primary, Secondary } }
14.888889
34
0.589552
[ "Apache-2.0" ]
sungraejo/TizenFX
src/Tizen.NUI.Xaml/src/internal/XamlBinding/ToolbarItemOrder.cs
134
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the pinpoint-2016-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Pinpoint.Model { /// <summary> /// This is the response object from the UpdateTemplateActiveVersion operation. /// </summary> public partial class UpdateTemplateActiveVersionResponse : AmazonWebServiceResponse { private MessageBody _messageBody; /// <summary> /// Gets and sets the property MessageBody. /// </summary> [AWSProperty(Required=true)] public MessageBody MessageBody { get { return this._messageBody; } set { this._messageBody = value; } } // Check to see if MessageBody property is set internal bool IsSetMessageBody() { return this._messageBody != null; } } }
30.636364
107
0.65816
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Pinpoint/Generated/Model/UpdateTemplateActiveVersionResponse.cs
1,685
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Web.Http; /// ****************************************************************************************************************** /// * Copyright (c) 2011 Dialect Software LLC * /// * This software is distributed under the terms of the Apache License http://www.apache.org/licenses/LICENSE-2.0 * /// * * /// ****************************************************************************************************************** namespace DialectSoftware.Registration { public class Contacts:IContacts { string _db; SharpCouch.DB _couch; public Contacts(SharpCouch.DB couch, string db) { _db = db; _couch = couch; } public Contact this[string id] { get { var doc = _couch.GetDocument(_db, id); LitJson.JsonMapper.RegisterImporter<string, Guid>((s) => { return Guid.Parse(s); }); return LitJson.JsonMapper.ToObject<Contact>(doc); } set { if(this[id]._rev == value._rev && id == value._id) Add(value); else throw new HttpResponseException(HttpStatusCode.Conflict); } } public void Add(Contact contact) { LitJson.JsonMapper.RegisterExporter<Guid>(new LitJson.ExporterFunc<Guid>((g, w) => { w.Write(g.ToString()); })); _couch.CreateDocument(_db, LitJson.JsonMapper.ToJson(contact)); } public void Remove(Contact contact) { Remove(contact._id); } public void Remove(string id) { string rev = _couch.GetRevision(_db, id); Remove(id, rev); } public void Remove(string id, string rev) { _couch.DeleteDocument(_db, id, rev); } public IEnumerator<Contact> GetEnumerator() { int total = 0; var docs = _couch.GetAllDocuments(_db, "contacts", "contacts_by_id", null, 2, out total, true); LitJson.JsonMapper.RegisterImporter<string, Guid>((s) => { return Guid.Parse(s); }); IEnumerable<Contact> contacts = docs.Select(doc => { var contact = LitJson.JsonMapper.ToObject<Contact>(doc.Document); /*contact._rev = doc.Revision;*/ return contact; }); yield return contacts.First(); total -= 1; while (total > 0) { int index = 0; docs = _couch.GetAllDocuments(_db, "contacts", "contacts_by_id", docs.ElementAt(1).Key, 2, out index, true); contacts = docs.Select(doc => { var contact = LitJson.JsonMapper.ToObject<Contact>(doc.Document); /*contact._rev = doc.Revision;*/ return contact; }); yield return contacts.First(); total -= 1; } } public IEnumerable<Contact> Next(string id, int count, out int totalRecords) { LitJson.JsonMapper.RegisterImporter<string, Guid>((s) => { return Guid.Parse(s); }); if(id == null) return _couch.GetAllDocuments(_db, "contacts", "contacts_by_id", id, count, out totalRecords, true).Skip(0).Select(doc => { var contact = LitJson.JsonMapper.ToObject<Contact>(doc.Document); /*contact._rev = doc.Revision;*/ return contact; }); else return _couch.GetAllDocuments(_db, "contacts", "contacts_by_id", id, count + 1, out totalRecords, true).Skip(1).Select(doc => { var contact = LitJson.JsonMapper.ToObject<Contact>(doc.Document); /*contact._rev = doc.Revision;*/ return contact; }); } public static Contacts Connect(SharpCouch.DB couch, string db) { return new Contacts(couch, db); } public Contact GetByEmailAddress(string email) { var docs = _couch.GetAllDocuments(_db, "contacts", "contacts_by_email", email, true); LitJson.JsonMapper.RegisterImporter<string, Guid>((s) => { return Guid.Parse(s); }); return docs.Select(doc => { var contact = LitJson.JsonMapper.ToObject<Contact>(doc.Document); /*contact._rev = doc.Revision;*/ return contact; }).DefaultIfEmpty(null).SingleOrDefault(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Create() { string view = null; var sys = Sys.Connect(_couch, _db); try { view = sys.GetView("contacts"); } finally { if (view == null) { sys.CreateView("contacts", "{\"_id\": \"_design/contacts\",\"language\": \"javascript\",\"views\": {\"contacts_by_id\": {\"map\": \"function(doc) { if ('Contact' == doc.type ) { emit(doc._id,{rev:doc._rev}); }}\"},\"contacts_by_email\": {\"map\": \"function(doc) { if ('Contact' == doc.type ) { for (var i in doc.emailAddresses) { emit(doc.emailAddresses[i].formattedEmailAddress,{rev:doc._rev});}}}\"}}}"); } } } } }
41.251852
416
0.510325
[ "Apache-2.0" ]
dialectsoftware/DialectSoftware.Registration
DialectSoftware.Registration.Document.Management/Context/Contacts.cs
5,571
C#
// <copyright file="SpanAttributes.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; namespace OpenTelemetry.Trace { /// <summary> /// A class that represents the span attributes. Read more here https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/common/common.md#attributes. /// </summary> public class SpanAttributes { /// <summary> /// Initializes a new instance of the <see cref="SpanAttributes"/> class. /// </summary> public SpanAttributes() { this.Attributes = new ActivityTagsCollection(); } /// <summary> /// Initializes a new instance of the <see cref="SpanAttributes"/> class. /// </summary> /// <param name="attributes">Initial attributes to store in the collection.</param> public SpanAttributes(IEnumerable<KeyValuePair<string, object>> attributes) : this() { if (attributes == null) { throw new ArgumentNullException(nameof(attributes)); } foreach (KeyValuePair<string, object> kvp in attributes) { this.AddInternal(kvp.Key, kvp.Value); } } internal ActivityTagsCollection Attributes { get; } /// <summary> /// Add entry to the attributes. /// </summary> /// <param name="key">Entry key.</param> /// <param name="value">Entry value.</param> public void Add(string key, long value) { this.AddInternal(key, value); } /// <summary> /// Add entry to the attributes. /// </summary> /// <param name="key">Entry key.</param> /// <param name="value">Entry value.</param> public void Add(string key, string value) { this.AddInternal(key, value); } /// <summary> /// Add entry to the attributes. /// </summary> /// <param name="key">Entry key.</param> /// <param name="value">Entry value.</param> public void Add(string key, bool value) { this.AddInternal(key, value); } /// <summary> /// Add entry to the attributes. /// </summary> /// <param name="key">Entry key.</param> /// <param name="value">Entry value.</param> public void Add(string key, double value) { this.AddInternal(key, value); } /// <summary> /// Add entry to the attributes. /// </summary> /// <param name="key">Entry key.</param> /// <param name="values">Entry value.</param> public void Add(string key, long[] values) { this.AddInternal(key, values); } /// <summary> /// Add entry to the attributes. /// </summary> /// <param name="key">Entry key.</param> /// <param name="values">Entry value.</param> public void Add(string key, string[] values) { this.AddInternal(key, values); } /// <summary> /// Add entry to the attributes. /// </summary> /// <param name="key">Entry key.</param> /// <param name="values">Entry value.</param> public void Add(string key, bool[] values) { this.AddInternal(key, values); } /// <summary> /// Add entry to the attributes. /// </summary> /// <param name="key">Entry key.</param> /// <param name="values">Entry value.</param> public void Add(string key, double[] values) { this.AddInternal(key, values); } private void AddInternal(string key, object value) { if (key == null) { throw new ArgumentNullException(key); } this.Attributes[key] = value; } } }
31.598639
184
0.555651
[ "Apache-2.0" ]
TopSwagCode/opentelemetry-dotnet
src/OpenTelemetry.Api/Trace/SpanAttributes.cs
4,645
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; [assembly: ActiveIssue("https://github.com/dotnet/runtime/issues/38433", TestPlatforms.Browser)]
42.166667
96
0.758893
[ "Apache-2.0" ]
DataDog/dd-shared-components-dotnet
shared/test/Vendored.System.Diagnostics.DiagnosticSource.Tests/TestWithConfigSwitches/AssemblyInfo.cs
253
C#
using Newtonsoft.Json; namespace DigitalOcean.API.Models.Requests { public class Domain { /// <summary> /// The domain name to add to the DigitalOcean DNS management interface. The name must be unique in DigitalOcean's DNS /// system. The request will fail if the name has already been taken. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// This attribute contains the IP address you want the domain to point to. /// </summary> [JsonProperty("ip_address")] public string IpAddress { get; set; } } }
35.444444
126
0.615987
[ "MIT" ]
JoshClose/DigitalOcean.API
DigitalOcean.API/Models/Requests/Domain.cs
640
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Threading.Tasks; using System.Web; using Luna.Clients.Exceptions; using Luna.Clients.Logging; using Luna.Data.Entities; using Luna.Data.Repository; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Logging; namespace Luna.Services.Data { /// <summary> /// Service class that handles basic CRUD functionality for the webhook resource. /// </summary> public class WebhookService : IWebhookService { private readonly ISqlDbContext _context; private readonly IOfferService _offerService; private readonly IWebhookParameterService _webhookParameterService; private readonly IWebhookWebhookParameterService _webhookWebhookParameterService; private readonly ILogger<WebhookService> _logger; /// <summary> /// Constructor that uses dependency injection. /// </summary> /// <param name="sqlDbContext">The context to inject.</param> /// <param name="offerService">The service to inject.</param> /// <param name="logger">The logger.</param> public WebhookService( ISqlDbContext sqlDbContext, IOfferService offerService, IWebhookParameterService webhookParameterService, IWebhookWebhookParameterService webhookWebhookParameterService , ILogger<WebhookService> logger) { _context = sqlDbContext ?? throw new ArgumentNullException(nameof(sqlDbContext)); _offerService = offerService ?? throw new ArgumentNullException(nameof(offerService)); _webhookParameterService = webhookParameterService ?? throw new ArgumentNullException(nameof(webhookParameterService)); _webhookWebhookParameterService = webhookWebhookParameterService ?? throw new ArgumentNullException(nameof(webhookWebhookParameterService)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// <summary> /// Gets all webhook within an offer. /// </summary> /// <param name="offerName">The name of the offer.</param> /// <returns>A list of webhook.</returns> public async Task<List<Webhook>> GetAllAsync(string offerName) { _logger.LogInformation(LoggingUtils.ComposeGetAllResourcesMessage(typeof(Webhook).Name, offerName: offerName)); // Get the offer associated with the offerName provided var offer = await _offerService.GetAsync(offerName); // Get all webhooks with a FK to the offer var webhooks = await _context.Webhooks.Where(a => a.OfferId == offer.Id).ToListAsync(); _logger.LogInformation(LoggingUtils.ComposeReturnCountMessage(typeof(Webhook).Name, webhooks.Count())); return webhooks; } /// <summary> /// Gets a webhook within an offer. /// </summary> /// <param name="offerName">The name of the offer.</param> /// <param name="webhookName">The name of the webhook to get.</param> /// <returns>The webhook.</returns> public async Task<Webhook> GetAsync(string offerName, string webhookName) { // Check that a webhook with the provided webhook exists within the given offer if (!(await ExistsAsync(offerName, webhookName))) { throw new LunaNotFoundUserException(LoggingUtils.ComposeNotFoundErrorMessage(typeof(Webhook).Name, webhookName, offerName: offerName)); } _logger.LogInformation(LoggingUtils.ComposeGetSingleResourceMessage(typeof(Webhook).Name, webhookName, offerName: offerName)); // Get the offer associated with the offerName provided var offer = await _offerService.GetAsync(offerName); // Find the webhook that matches the webhookName provided var webhook = await _context.Webhooks .SingleOrDefaultAsync(a => (a.OfferId == offer.Id) && (a.WebhookName == webhookName)); _logger.LogInformation(LoggingUtils.ComposeReturnValueMessage(typeof(Webhook).Name, webhookName, JsonSerializer.Serialize(webhook), offerName: offerName)); return webhook; } /// <summary> /// Creates a webhook within an offer. /// </summary> /// <param name="offerName">The name of the offer.</param> /// <param name="webhook">The webhook to create.</param> /// <returns>The created webhook.</returns> public async Task<Webhook> CreateAsync(string offerName, Webhook webhook) { if (webhook is null) { throw new LunaBadRequestUserException(LoggingUtils.ComposePayloadNotProvidedErrorMessage(typeof(Webhook).Name), UserErrorCode.PayloadNotProvided); } // Check that the offer does not already have a webhook with the same webhookName if (await ExistsAsync(offerName, webhook.WebhookName)) { throw new LunaConflictUserException(LoggingUtils.ComposeAlreadyExistsErrorMessage(typeof(Webhook).Name, webhook.WebhookName, offerName: offerName)); } _logger.LogInformation(LoggingUtils.ComposeCreateResourceMessage(typeof(Webhook).Name, webhook.WebhookName, offerName: offerName, payload: JsonSerializer.Serialize(webhook))); // Get the offer associated with the offerName provided var offer = await _offerService.GetAsync(offerName); // Set the FK to offer webhook.OfferId = offer.Id; // Add webhook to db _context.Webhooks.Add(webhook); await _context._SaveChangesAsync(); _logger.LogInformation(LoggingUtils.ComposeResourceCreatedMessage(typeof(Webhook).Name, webhook.WebhookName, offerName: offerName)); await CreateWebhookParameters(offerName, webhook); return webhook; } private async Task CreateWebhookParameters(string offerName, Webhook webhook) { List<WebhookParameter> webhookParameters = ParseWebhookParameters(webhook); foreach(WebhookParameter webhookParameter in webhookParameters) { await _webhookParameterService.CreateAsync(offerName, webhook.Id, webhookParameter); } } private List<WebhookParameter> ParseWebhookParameters(Webhook webhook) { List<WebhookParameter> webhookParameters = new List<WebhookParameter>(); Uri webhookUri = new Uri(webhook.WebhookUrl); _logger.LogInformation($"Parsing query string for uri {webhookUri}."); var parameters = HttpUtility.ParseQueryString(webhookUri.Query); foreach (var key in parameters.Keys) { string value = parameters[key.ToString()]; if (value.StartsWith("{") && value.EndsWith("}")) { //trim the brankets string parameterName = value.Substring(1, value.Length - 2); _logger.LogInformation($"Creating webhook parameter {parameterName} for webhook {webhook.WebhookName}."); WebhookParameter webhookParam = new WebhookParameter { OfferId = webhook.OfferId, Name = parameterName, // TODO: do we need to indicate an incomplete parameter? Value = string.Empty }; webhookParameters.Add(webhookParam); } } return webhookParameters; } private async Task UpdateWebhookParameters(Offer offer, Webhook webhook, long webhookId) { List<WebhookParameter> incompleteParams = ParseWebhookParameters(webhook); List<WebhookWebhookParameter> joinEntries = await _webhookWebhookParameterService.GetAllJoinEntries(webhookId); Dictionary<string, WebhookParameter> paramsDb = new Dictionary<string, WebhookParameter>(); HashSet<string> usedParamNames = new HashSet<string>(); // Populate paramsDb so that it maps the WebhookParameter name to the WebhookParameter object foreach (WebhookWebhookParameter entry in joinEntries) { WebhookParameter webhookParameter = await _context.WebhookParameters.FindAsync(entry.WebhookParameterId); if (!paramsDb.ContainsKey(webhookParameter.Name)) { paramsDb.Add(webhookParameter.Name, webhookParameter); } } foreach (WebhookParameter incompleteParam in incompleteParams) { // Check if a param with the same name as the incompleteParam already exists if (!paramsDb.ContainsKey(incompleteParam.Name)) { // A param with the same name as the incompleteParam does not exist, so create it await _webhookParameterService.CreateAsync(offer.OfferName, webhookId, incompleteParam); } // Keep track of all the new parameters we are using in usedParamNames if (!usedParamNames.Contains(incompleteParam.Name)) { usedParamNames.Add(incompleteParam.Name); } } foreach (KeyValuePair<string, WebhookParameter> paramDb in paramsDb) { // Check if there is a param in the db that we are no longer using if (!usedParamNames.Contains(paramDb.Key)) { WebhookWebhookParameter webhookWebhookParameter = await _context.WebhookWebhookParameters.FindAsync(webhookId, paramDb.Value.Id); // Remove the join entry for any unused params _context.WebhookWebhookParameters.Remove(webhookWebhookParameter); await _context._SaveChangesAsync(); _logger.LogInformation(LoggingUtils.ComposeResourceDeletedMessage( nameof(WebhookWebhookParameter), $"(webhookId={webhookId}, webhookParameterId={webhookWebhookParameter.WebhookParameter})", offerName: offer.OfferName)); } } } /// <summary> /// Updates a webhook within an offer. /// </summary> /// <param name="offerName">The name of the offer.</param> /// <param name="webhookName">The name of the webhook to update.</param> /// <param name="webhook">The new webhook.</param> /// <returns>The updated webhook.</returns> public async Task<Webhook> UpdateAsync(string offerName, string webhookName, Webhook webhook) { if (webhook is null) { throw new LunaBadRequestUserException(LoggingUtils.ComposePayloadNotProvidedErrorMessage(typeof(Webhook).Name), UserErrorCode.PayloadNotProvided); } // Check if (the webhookName has been updated) && // (a webhook with the same new webhookName does not already exist) if ((webhookName != webhook.WebhookName) && (await ExistsAsync(offerName, webhook.WebhookName))) { throw new LunaNotFoundUserException(LoggingUtils.ComposeNotFoundErrorMessage(typeof(Webhook).Name, webhook.WebhookName, offerName: offerName)); } _logger.LogInformation(LoggingUtils.ComposeUpdateResourceMessage(typeof(Webhook).Name, webhook.WebhookName, offerName: offerName, payload: JsonSerializer.Serialize(webhook))); // Get the webhook that matches the webhookName provided var webhookDb = await GetAsync(offerName, webhookName); // Copy over the changes webhookDb.Copy(webhook); // Update webhook values and save changes in db _context.Webhooks.Update(webhookDb); await _context._SaveChangesAsync(); _logger.LogInformation(LoggingUtils.ComposeResourceUpdatedMessage(nameof(Webhook), webhookName, offerName: offerName)); await UpdateWebhookParameters(await _offerService.GetAsync(offerName), webhookDb, webhookDb.Id); return webhook; } /// <summary> /// Deletes a webhook within an offer. /// </summary> /// <param name="offerName">The name of the offer.</param> /// <param name="webhookName">The name of the webhook to delete.</param> /// <returns>The deleted webhook.</returns> public async Task<Webhook> DeleteAsync(string offerName, string webhookName) { _logger.LogInformation(LoggingUtils.ComposeDeleteResourceMessage(typeof(Webhook).Name, webhookName, offerName: offerName)); // Get the webhook that matches the webhook provided var webhook = await GetAsync(offerName, webhookName); // Remove the webhook from the db _context.Webhooks.Remove(webhook); await _context._SaveChangesAsync(); _logger.LogInformation(LoggingUtils.ComposeResourceDeletedMessage(nameof(Webhook), webhookName, offerName: offerName)); return webhook; } /// <summary> /// Checks if a webhook exists within an offer. /// </summary> /// <param name="offerName">The name of the offer.</param> /// <param name="webhookName">The name of the webhook to check exists.</param> /// <returns>True if exists, false otherwise.</returns> public async Task<bool> ExistsAsync(string offerName, string webhookName) { _logger.LogInformation(LoggingUtils.ComposeCheckResourceExistsMessage(typeof(Webhook).Name, webhookName, offerName: offerName)); //Get the offer associated with the offerName provided var offer = await _offerService.GetAsync(offerName); // Check that only one webhook with this webhookName exists within the offer var count = await _context.Webhooks .CountAsync(a => (a.OfferId == offer.Id) && (a.WebhookName == webhookName)); // More than one instance of an object with the same name exists, this should not happen if (count > 1) { throw new NotSupportedException(LoggingUtils.ComposeFoundDuplicatesErrorMessage(typeof(Webhook).Name, webhookName, offerName: offerName)); } else if (count == 0) { _logger.LogInformation(LoggingUtils.ComposeResourceExistsOrNotMessage(typeof(Webhook).Name, webhookName, false, offerName: offerName)); return false; } else { // count = 1 _logger.LogInformation(LoggingUtils.ComposeResourceExistsOrNotMessage(typeof(Webhook).Name, webhookName, false, offerName: offerName)); return true; } } } }
46.575758
187
0.631685
[ "MIT" ]
Azure/ace-luna
src/Luna.Services/Data/WebhookService.cs
15,370
C#
// World Conquer Online Project 2.5517 - Phoenix Project Based // This project has been created by Felipe Vieira Vendramini // Source Infrastructure based on Phoenix Source, written by Gareth Jensen // This source is targeted to Conquer Online, client version 5517 // // Computer User: Felipe Vieira // File Created by: Felipe Vieira Vendramini // zfserver v2.5517 - DB - Totem.cs // Last Edit: 2016/11/25 02:12 // Created: 2016/11/25 02:11 using System.Collections.Generic; using DB.Entities; using NHibernate.Criterion; namespace DB.Repositories { public sealed class TotemPoleRepository : HibernateDataRow<DbSyntotem> { public IList<DbSyntotem> ListAllTotems(ushort syndicate) { return SessionFactory.GameDatabase.OpenSession() .CreateCriteria<DbSyntotem>() .Add(Restrictions.Eq("Synid", syndicate)) .List<DbSyntotem>(); } public void ClearUserTotem(uint userId) { SessionFactory.GameDatabase.OpenSession() .CreateSQLQuery("CALL SynTotemDeleteFromUser (?);") .AddEntity(typeof(DbSyntotem)) .SetParameter(0, userId) .ExecuteUpdate(); } public bool SaveOrUpdate(DbSyntotem obj) { return SaveOrUpdate(obj, SessionFactory.GameDatabase.OpenSession()); } public bool Delete(DbSyntotem obj) { return TryDelete(obj, SessionFactory.GameDatabase.OpenSession()); } } }
32.702128
80
0.644763
[ "MIT" ]
darkfoxdeveloper/FoxConquer5517
DB/Repositories/Totem.cs
1,539
C#
using Moq; namespace blueberry.Infrastructure; public class SearchTests { private readonly IReadOnlyCollection<UserDto> _mockUsers = new[] { new UserDto (1, "Jalle", new PrimitiveCollection<string> {"React"}), new UserDto (2, "Kobo", new PrimitiveCollection<string> {"Angular"}), }; private readonly IReadOnlyCollection<MaterialDto> _mockMaterials = new[]{ new MaterialDto(1, "Why Haskell is better than F#", new PrimitiveCollection<string> {"FP", "Haskell", "F#", "The truth"}, "", "Book", DateTime.Today, ""), new MaterialDto(2, "Typescript and react", new PrimitiveCollection<string> {"React", "Typescript", "Javascript"}, "", "Book", DateTime.Today, ""), new MaterialDto(3, "Why angular died", new PrimitiveCollection<string> {"Angular", "Typescript", "Javascript"}, "", "Book", DateTime.Today, ""), new MaterialDto(4, "Why typescript is the future of the web", new PrimitiveCollection<string> { "Typescript", "Javascript"}, "", "Book", DateTime.Today, ""), }; [Fact] public async void SearchGivenEmptyStringShouldReturnAllResuslts() { var mockedMaterialRepo = new Mock<IMaterialRepository>(); var mockedUserRepo = new Mock<IUserRepository>(); var searchOptions = new SearchOptions("", null, null, null); mockedMaterialRepo.Setup(mr => mr.Search(searchOptions)).ReturnsAsync(_mockMaterials); var search = new SearchProxy(mockedMaterialRepo.Object, mockedUserRepo.Object); var actual = await search.Search(""); Assert.Equal(_mockMaterials, actual); } [Theory] [InlineData("Why")] [InlineData("typescript")] [InlineData("bla bla")] [InlineData("React")] public async void SearchGivenAStringShouldReturnMaterialWithThatInTheTitle(string searchTerm) { var mockedMaterialRepo = new Mock<IMaterialRepository>(); var mockedUserRepo = new Mock<IUserRepository>(); var searchOptions = new SearchOptions(searchTerm, null, null, null); var filteredMockData = _mockMaterials.Where(md => md.Title.Contains(searchTerm)).ToList(); mockedMaterialRepo.Setup(mr => mr.Search(searchOptions)).ReturnsAsync(filteredMockData); var search = new SearchProxy(mockedMaterialRepo.Object, mockedUserRepo.Object); var actual = await search.Search(searchTerm); Assert.Equal(filteredMockData, actual); } [Fact] public async void SearchShouldForwardOptionsToTheRepo() { SearchOptions? receivedOptions = null; SearchOptions givenOptions = new SearchOptions(); var mockedRepo = new Mock<IMaterialRepository>(); var mockedUserRepo = new Mock<IUserRepository>(); mockedRepo.Setup(mr => mr.Search(It.IsAny<SearchOptions>())) .Callback<SearchOptions>(so => { receivedOptions = so; }); var search = new SearchProxy(mockedRepo.Object, mockedUserRepo.Object); await search.Search(givenOptions); Assert.Equal(givenOptions, receivedOptions); } [Fact] public async void ProxyShouldOnlyCallProxiedSearchOnceWhenCalledWithTheSameParams() { var mockedMaterialRepo = new Mock<IMaterialRepository>(); var mockedUserRepo = new Mock<IUserRepository>(); var searchOptions = new SearchOptions("Typescript", null, null, null); var filteredMockData = _mockMaterials.Where(md => md.Title.Contains("Typescript")).ToList(); mockedMaterialRepo.Setup(mr => mr.Search(searchOptions)).ReturnsAsync(filteredMockData); var search = new SearchProxy(mockedMaterialRepo.Object, mockedUserRepo.Object); await search.Search("Typescript"); var actual = await search.Search("Typescript"); Assert.Equal(filteredMockData, actual); mockedMaterialRepo.Verify(mock => mock.Search(searchOptions), Times.Exactly(1)); } [Fact] public async void SearchWithUserIdAndSearchOptionsReturnsFilteredMaterialsBasedOnSearch() { var mockedMaterialRepo = new Mock<IMaterialRepository>(); var mockedUserRepo = new Mock<IUserRepository>(); var mockSearchOptions = new SearchOptions("", new PrimitiveSet<string>() { "Typescript" }, null, null); var searchOptions = new SearchOptions("", new PrimitiveSet<string>() { "Typescript" }, null, null); var filteredMockData = _mockMaterials.Where(md => md.Tags.Contains("Typescript")).ToList(); var readUser = _mockUsers.Where(u => u.Id == 1).FirstOrDefault(); mockedMaterialRepo.Setup(mr => mr.Search(mockSearchOptions)).ReturnsAsync(filteredMockData); mockedUserRepo.Setup(u => u.Read(1)).ReturnsAsync(readUser); var search = new SearchProxy(mockedMaterialRepo.Object, mockedUserRepo.Object); var actual = await search.Search(searchOptions, 1); Assert.Equal(filteredMockData, actual); } [Fact] public async void SearchWithUserIdAndNoSearchOptionsReturnSearchBasedOnInterests() { var mockedMaterialRepo = new Mock<IMaterialRepository>(); var mockedUserRepo = new Mock<IUserRepository>(); var mockSearchOptions = new SearchOptions("", new PrimitiveSet<string>() { "Angular" }, null, null); var searchOptions = new SearchOptions("", null, null, null); var filteredMockData = _mockMaterials.Where(md => md.Id == 3).ToList(); var readUser = _mockUsers.Where(u => u.Id == 2).FirstOrDefault(); mockedMaterialRepo.Setup(mr => mr.Search(mockSearchOptions)).ReturnsAsync(filteredMockData); mockedUserRepo.Setup(u => u.Read(2)).ReturnsAsync(readUser); var search = new SearchProxy(mockedMaterialRepo.Object, mockedUserRepo.Object); var actual = await search.Search(searchOptions, 2); Assert.Equal(filteredMockData, actual); } }
41.70922
165
0.682537
[ "MIT" ]
toffernator/blueberry
Infrastructure.Tests/SearchTests.cs
5,881
C#
using System; namespace WindowSettings.Entities.Base { public interface IEntityBase { Int64 Id { get; set; } DateTime CreatedDate { get; set; } DateTime? UpdatedDate { get; set; } } }
16
43
0.602679
[ "MIT" ]
HasanShahjahan/Window-Settings
src/WindowSettings.Entities/Base/IEntityBase.cs
226
C#
/** * Copyright 2017-2021 Plexus Interop Deutsche Bank AG * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Plexus.Interop.Protobuf; using Plexus.Interop.Transport.Protocol.Serialization; using Plexus.Pools; namespace Plexus.Interop.Transport.Protocol.Protobuf.Internal { internal sealed class ProtobufTransportProtocolDeserializer : ITransportProtocolDeserializer { private readonly ILogger _log; private readonly ITransportHeaderFactory _headerFactory; public ProtobufTransportProtocolDeserializer(ITransportHeaderFactory headerFactory) { _log = LogManager.GetLogger<ProtobufTransportProtocolDeserializer>(); _headerFactory = headerFactory; } public ITransportHeader Deserialize(IPooledBuffer datagram) { using (var proto = Header.Rent()) { proto.MergeFrom(datagram); var contentCase = proto.ContentCase; ITransportHeader header; switch (contentCase) { case Header.ContentOneofCase.MessageFrame: header = ConvertFromProto(proto.MessageFrame); break; case Header.ContentOneofCase.ChannelOpen: header = ConvertFromProto(proto.ChannelOpen); break; case Header.ContentOneofCase.ChannelClose: header = ConvertFromProto(proto.ChannelClose); break; case Header.ContentOneofCase.Open: header = ConvertFromProto(proto.Open); break; case Header.ContentOneofCase.Close: header = ConvertFromProto(proto.Close); break; default: throw new ArgumentOutOfRangeException(); } return header; } } private ITransportFrameHeader ConvertFromProto(MessageFrameHeader frameHeader) { return _headerFactory.CreateFrameHeader( frameHeader.ChannelId.ConvertFromProtoStrict(), frameHeader.HasMore, (int)frameHeader.Length); } private ITransportChannelCloseHeader ConvertFromProto(ChannelCloseHeader proto) { return _headerFactory.CreateChannelCloseHeader(proto.ChannelId.ConvertFromProtoStrict(), proto.Completion.ConvertFromProto()); } private ITransportChannelOpenHeader ConvertFromProto(ChannelOpenHeader proto) { return _headerFactory.CreateChannelOpenHeader(proto.ChannelId.ConvertFromProtoStrict()); } private ITransportConnectionOpenHeader ConvertFromProto(ConnectionOpenHeader proto) { return _headerFactory.CreateConnectionOpenHeader(proto.ConnectionId.ConvertFromProtoStrict()); } private ITransportConnectionCloseHeader ConvertFromProto(ConnectionCloseHeader proto) { return _headerFactory.CreateConnectionCloseHeader(proto.Completion.ConvertFromProto()); } } }
39.53125
138
0.638208
[ "Apache-2.0" ]
deutschebank/Plexus-interop
desktop/src/Plexus.Interop.Transport.Protocol.Protobuf/Internal/ProtobufTransportProtocolDeserializer.cs
3,797
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.ApiManagement.V20180101 { public static class GetPolicy { /// <summary> /// Policy Contract details. /// </summary> public static Task<GetPolicyResult> InvokeAsync(GetPolicyArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetPolicyResult>("azure-nextgen:apimanagement/v20180101:getPolicy", args ?? new GetPolicyArgs(), options.WithVersion()); } public sealed class GetPolicyArgs : Pulumi.InvokeArgs { /// <summary> /// The identifier of the Policy. /// </summary> [Input("policyId", required: true)] public string PolicyId { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the API Management service. /// </summary> [Input("serviceName", required: true)] public string ServiceName { get; set; } = null!; public GetPolicyArgs() { } } [OutputType] public sealed class GetPolicyResult { /// <summary> /// Format of the policyContent. /// </summary> public readonly string? ContentFormat; /// <summary> /// Resource ID. /// </summary> public readonly string Id; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// Json escaped Xml Encoded contents of the Policy. /// </summary> public readonly string PolicyContent; /// <summary> /// Resource type for API Management resource. /// </summary> public readonly string Type; [OutputConstructor] private GetPolicyResult( string? contentFormat, string id, string name, string policyContent, string type) { ContentFormat = contentFormat; Id = id; Name = name; PolicyContent = policyContent; Type = type; } } }
28
174
0.571817
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/ApiManagement/V20180101/GetPolicy.cs
2,576
C#
using System; using System.Collections.Generic; using CQRSCode.ReadModel.Dtos; namespace CQRSCode.ReadModel { public interface IReadModelFacade { IEnumerable<InventoryItemListDto> GetInventoryItems(); InventoryItemDetailsDto GetInventoryItemDetails(Guid id); } }
24.333333
65
0.763699
[ "Apache-2.0" ]
al222cv/CQRSlite.NetCore
Sample/CQRSCode/ReadModel/IReadModelFacade.cs
294
C#
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.42 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal { public partial class SharePointGroups { protected WebsitePanel.Portal.UserControls.SpaceServiceItems itemsList; } }
50.044444
84
0.666963
[ "BSD-3-Clause" ]
9192939495969798/Websitepanel
WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SharePointGroups.ascx.designer.cs
2,252
C#
using UnityEngine; using System.Collections; public class ExpandDebuff : MonoBehaviour { public GameObject player1; public GameObject player2; public Camera cam; public ParticleSystem pickup; private Transform r1; private Transform r2; public float timer; private float innerTimer; public AudioClip sound; public float a; private int numOfTimes; // Use this for initialization void Start () { innerTimer = timer; r1 = player1.transform; r2 = player2.transform; numOfTimes = 0; } // Update is called once per frame void Update () { if (numOfTimes > 0) innerTimer--; if (innerTimer <= 0) { r1.localScale = new Vector3 (r1.localScale.x / a, r1.localScale.y / a, r1.localScale.z / a); r2.localScale = new Vector3 (r2.localScale.x / a, r2.localScale.y / a, r2.localScale.z / a); innerTimer = timer; numOfTimes -= 1; } } void OnTriggerEnter2D (Collider2D other) { if (other.tag == "SizeDebuff") { r1.localScale = new Vector3 (r1.localScale.x * a, r1.localScale.y * a, r1.localScale.z * a); r2.localScale = new Vector3 (r2.localScale.x * a, r2.localScale.y * a, r2.localScale.z * a); numOfTimes++; AudioSource.PlayClipAtPoint(sound, transform.position,100f); Instantiate (pickup, this.transform.position, this.transform.rotation); Destroy (other.gameObject); } } }
24.526316
96
0.668097
[ "MIT" ]
chanmatthew/Robert-In-Space
Assets/Scripts/ItemController/ExpandDebuff.cs
1,400
C#
using System.Security.Claims; using EduManagementLab.Core.Services; using EduManagementLab.IdentityServer4.Configuration; using IdentityModel; using IdentityServer4.EntityFramework.Interfaces; using IdentityServer4.Models; using IdentityServer4.Validation; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace LtiAdvantage.IdentityServer4.Validation { /// <inheritdoc /> /// <summary> /// Replace the subject in the authorize request, with a <see cref="T:System.Security.Claims.ClaimsPrincipal" /> /// for the person being impersonated. For example a student in a course. /// </summary> public class ImpersonationAuthorizeRequestValidator : ICustomAuthorizeRequestValidator { private readonly ILogger<ImpersonationAuthorizeRequestValidator> _logger; public const string AuthenticationType = @"Impersonation"; private readonly OAuthClientService _OAuthClientService; public ImpersonationAuthorizeRequestValidator(ILogger<ImpersonationAuthorizeRequestValidator> logger, OAuthClientService OAuthClientService) { _logger = logger; _OAuthClientService = OAuthClientService; } public Task ValidateAsync(CustomAuthorizeRequestValidationContext context) { var subject = context.Result.ValidatedRequest.Subject.Claims.SingleOrDefault(c => c.Type == "sub")?.Value; var loginHint = context.Result.ValidatedRequest.LoginHint; if (loginHint.IsPresent() && subject != loginHint) { _logger.LogInformation($"Impersonating subject {loginHint}."); // Replace the subject with the person being impersonated in login_hint context.Result.ValidatedRequest.Subject = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim> { new Claim("sub", loginHint), new Claim("auth_time", DateTime.UtcNow.ToEpochTime().ToString()), new Claim("idp", "local") }, AuthenticationType)); } return Task.CompletedTask; } } }
40.754717
148
0.687963
[ "MIT" ]
ve-backend-internship-spring2022/EduManagementLab
src/EduManagementLab.IdentityServer4/Validation/ImpersonationAuthorizeRequestValidator.cs
2,162
C#
namespace DotNetStandard.Specification { public sealed class XOrSpecification<T> : ISpecification<T> { private readonly ISpecification<T> _left; private readonly ISpecification<T> _right; public XOrSpecification(ISpecification<T> left, ISpecification<T> right) { _left = left; _right = right; } public bool IsSatisfiedBy(T o) { return _left.IsSatisfiedBy(o) ^ _right.IsSatisfiedBy(o); } } }
25.3
80
0.606719
[ "MIT" ]
Eraclys/DotNetStandard.Specification
src/DotNetStandard.Specification/XorSpecification.cs
508
C#
/* Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Android.App; using Android.Content; using Android.OS; using Android.Util; using Huawei.Hms.Core; using Huawei.Hms.Push; using Java.Lang; namespace XamarinHmsPushDemo.HMSPush { [Service] [IntentFilter(new[] { "com.huawei.push.action.MESSAGING_EVENT" })] public class HMSPushMessageService : HmsMessageService { static readonly string HMSPushAction = "PushReceiver"; public override void OnNewToken(string token, Bundle bundle) { // Obtain a token. string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Log.Info(MethodName, token); Intent intent = new Intent(); intent.SetAction(HMSPushAction); intent.PutExtra(HMSPushReceiver.Method, System.Reflection.MethodBase.GetCurrentMethod().Name); intent.PutExtra(HMSPushReceiver.Token, token); SendBroadcast(intent); } public override void OnMessageReceived(RemoteMessage message) { //It get triggered when data message comes or a notification comes which as foreground attributes false string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Log.Info(MethodName, RemoteMessageUtils.FromMap(message).DictionaryToString()); Intent intent = new Intent(); intent.SetAction(HMSPushAction); intent.PutExtra(HMSPushReceiver.Method, System.Reflection.MethodBase.GetCurrentMethod().Name); intent.PutExtra(HMSPushReceiver.Message, message); SendBroadcast(intent); } public override void OnMessageSent(string msgId) { // Obtain the message ID. string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Log.Info(MethodName, msgId); Intent intent = new Intent(); intent.SetAction(HMSPushAction); intent.PutExtra(HMSPushReceiver.Method, System.Reflection.MethodBase.GetCurrentMethod().Name); intent.PutExtra(HMSPushReceiver.MsgId, msgId); SendBroadcast(intent); } public override void OnSendError(string msgId, Exception exception) { // If the sending fails, obtain the error message. string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Log.Info(MethodName, $"msgId:{msgId}\nError/Exception:{exception.Message}"); Intent intent = new Intent(); intent.SetAction(HMSPushAction); intent.PutExtra(HMSPushReceiver.Method, System.Reflection.MethodBase.GetCurrentMethod().Name); intent.PutExtra(HMSPushReceiver.MsgId, msgId); Android.OS.Bundle bundle = new Android.OS.Bundle(); bundle.PutString(HMSPushReceiver.Message, exception.Message); bundle.PutInt(HMSPushReceiver.ErrorCode, ((BaseException)exception).ErrorCode); intent.PutExtra(HMSPushReceiver.Exception, bundle); SendBroadcast(intent); } public override void OnMessageDelivered(string msgId, Exception exception) { // Obtain the error code and description. string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Log.Info(MethodName, $"msgId:{msgId}\nSituation:{exception.Message}"); Intent intent = new Intent(); intent.SetAction(HMSPushAction); intent.PutExtra(HMSPushReceiver.Method, System.Reflection.MethodBase.GetCurrentMethod().Name); intent.PutExtra(HMSPushReceiver.MsgId, msgId); Android.OS.Bundle bundle = new Android.OS.Bundle(); bundle.PutString(HMSPushReceiver.Message, exception.Message); bundle.PutInt(HMSPushReceiver.ErrorCode, ((BaseException)exception).ErrorCode); intent.PutExtra(HMSPushReceiver.Exception, bundle); SendBroadcast(intent); } public override void OnTokenError(Exception exception, Bundle bundle) { string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Log.Info(MethodName, exception.Message); Intent intent = new Intent(); intent.SetAction(HMSPushAction); intent.PutExtra(HMSPushReceiver.Method, System.Reflection.MethodBase.GetCurrentMethod().Name); Android.OS.Bundle bundleException= new Android.OS.Bundle(); bundleException.PutString(HMSPushReceiver.Message, exception.Message); bundleException.PutInt(HMSPushReceiver.ErrorCode, ((BaseException)exception).ErrorCode); intent.PutExtra(HMSPushReceiver.Exception, bundleException); intent.PutExtra(HMSPushReceiver.Bundle, bundle); SendBroadcast(intent); } public override void OnDeletedMessages() { string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Log.Info(MethodName, $"{MethodName} has triggered."); Intent intent = new Intent(); intent.SetAction(HMSPushAction); intent.PutExtra(HMSPushReceiver.Method, System.Reflection.MethodBase.GetCurrentMethod().Name); SendBroadcast(intent); } } }
45.473282
115
0.667786
[ "Apache-2.0" ]
HMS-Core/hms-xamarin-bindings
android/samples/PushKitDemo/HMSPush/HMSPushMessageService.cs
5,959
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x100c_97a3-dc8e21da")] public void Method_100c_97a3() { ii(0x100c_97a3, 5); push(0x24); /* push 0x24 */ ii(0x100c_97a8, 5); call(Definitions.sys_check_available_stack_size, 0x9_c5a5);/* call 0x10165d52 */ ii(0x100c_97ad, 1); push(ebx); /* push ebx */ ii(0x100c_97ae, 1); push(ecx); /* push ecx */ ii(0x100c_97af, 1); push(edx); /* push edx */ ii(0x100c_97b0, 1); push(esi); /* push esi */ ii(0x100c_97b1, 1); push(edi); /* push edi */ ii(0x100c_97b2, 1); push(ebp); /* push ebp */ ii(0x100c_97b3, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x100c_97b5, 6); sub(esp, 8); /* sub esp, 0x8 */ ii(0x100c_97bb, 3); mov(memd[ss, ebp - 4], eax); /* mov [ebp-0x4], eax */ ii(0x100c_97be, 7); mov(memd[ss, ebp - 8], 4); /* mov dword [ebp-0x8], 0x4 */ ii(0x100c_97c5, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100c_97c8, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x100c_97ca, 1); pop(ebp); /* pop ebp */ ii(0x100c_97cb, 1); pop(edi); /* pop edi */ ii(0x100c_97cc, 1); pop(esi); /* pop esi */ ii(0x100c_97cd, 1); pop(edx); /* pop edx */ ii(0x100c_97ce, 1); pop(ecx); /* pop ecx */ ii(0x100c_97cf, 1); pop(ebx); /* pop ebx */ ii(0x100c_97d0, 1); ret(); /* ret */ } } }
61.828571
114
0.392329
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-100c-97a3.cs
2,164
C#
using FluentValidation; using Adnc.Usr.Application.Dtos; namespace Adnc.Usr.Application.DtoValidators { public class UserCreationDtoValidator : AbstractValidator<UserCreationDto> { public UserCreationDtoValidator() { Include(new UserCreationAndUpdationDtoValidator()); RuleFor(x => x.Password).NotEmpty().Length(5, 16); //RuleFor(x => x.Password).NotEmpty().When(x => x.Id < 1) // .Length(5, 16).When(x => x.Id < 1); } } }
31.294118
78
0.593985
[ "MIT" ]
Orlys/Adnc
src/ServerApi/Portal/Adnc.Usr/Adnc.Usr.Application/Services/User/DtoValidators/UserCreationDtoValidator.cs
534
C#
namespace Tavenem.HugeNumbers; public partial struct HugeNumber { /// <summary> /// Returns the larger of two <see cref="HugeNumber"/> values. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// The <paramref name="left"/> or <paramref name="right"/> parameter, whichever is larger. /// </returns> /// <remarks> /// If either value is <see cref="NaN"/>, the result is <see cref="NaN"/>. /// </remarks> public static HugeNumber Max(HugeNumber left, HugeNumber right) { if (left.IsNaN() || right.IsNaN()) { return NaN; } return left >= right ? left : right; } /// <summary> /// Returns the greater absolute value of two <see cref="HugeNumber"/> /// values. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// The <paramref name="left"/> or <paramref name="right"/> parameter, whichever has the /// larger absolute value (magnitude). /// </returns> /// <remarks> /// <para> /// If either value is <see cref="NaN"/>, the result is <see cref="NaN"/>. /// </para> /// <para> /// If the values have equal absolute values, but one is negative, the positive value is /// considered greater. /// </para> /// </remarks> public static HugeNumber MaxMagnitude(HugeNumber left, HugeNumber right) { if (left.IsNaN() || right.IsNaN()) { return NaN; } var leftAbs = left.Abs(); var rightAbs = right.Abs(); if (leftAbs > rightAbs) { return left; } if (leftAbs == rightAbs) { return left < 0 ? right : left; } return right; } /// <summary> /// Returns the smaller of two <see cref="HugeNumber"/> values. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// The <paramref name="left"/> or <paramref name="right"/> parameter, whichever is smaller. /// </returns> /// <remarks> /// If either value is <see cref="NaN"/>, the result is <see cref="NaN"/>. /// </remarks> public static HugeNumber Min(HugeNumber left, HugeNumber right) { if (left.IsNaN() || right.IsNaN()) { return NaN; } return left <= right ? left : right; } /// <summary> /// Returns the smaller absolute value of two <see cref="HugeNumber"/> /// values. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// The <paramref name="left"/> or <paramref name="right"/> parameter, whichever has the /// smaller absolute value (magnitude). /// </returns> /// <remarks> /// <para> /// If either value is <see cref="NaN"/>, the result is <see cref="NaN"/>. /// </para> /// <para> /// If the values have equal absolute values, but one is negative, the negative value is /// considered smaller. /// </para> /// </remarks> public static HugeNumber MinMagnitude(HugeNumber left, HugeNumber right) { if (left.IsNaN() || right.IsNaN()) { return NaN; } var leftAbs = left.Abs(); var rightAbs = right.Abs(); if (leftAbs < rightAbs) { return left; } if (leftAbs == rightAbs) { return left < 0 ? left : right; } return right; } /// <summary> /// Compares this instance to a specified object and returns an indication of their relative values. /// </summary> /// <param name="other">An object to compare, or <see langword="null"/>.</param> /// <returns> /// A signed integer value that indicates the relationship of this instance to <paramref /// name="other"/>, as shown in the following table. /// <list type="table"> /// <listheader> /// <term>Return value</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>Less than zero</term> /// <term>The current instance is less than <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Zero</term> /// <term>The current instance equals <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Greater than zero</term> /// <term>The current instance is greater than <paramref name="other"/>.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>If the current instance is <see cref="NaN"/>, -1 is returned.</para> /// <para>If <paramref name="other"/> is <see langword="null"/>, 1 is returned.</para> /// </remarks> public int CompareTo(decimal other) { if (IsNaN()) { return -1; } if (IsPositiveInfinity()) { return 1; } if (IsNegativeInfinity()) { return -1; } // When the value is zero, exponent can be disregarded; only the sign of the mantissa // matters for the purpose of comparison. if (Mantissa == 0) { return Mantissa.CompareTo(Math.Sign(other)); } // simple cases with opposite signs if (Mantissa < 0 && other > 0) { return -1; } if (other < 0 && Mantissa > 0) { return 1; } // in non-trivial cases, convert to a Number to compare return CompareTo((HugeNumber)other); } /// <summary> /// Compares this instance to a specified object and returns an indication of their relative values. /// </summary> /// <param name="other">An object to compare, or <see langword="null"/>.</param> /// <returns> /// A signed integer value that indicates the relationship of this instance to <paramref /// name="other"/>, as shown in the following table. /// <list type="table"> /// <listheader> /// <term>Return value</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>Less than zero</term> /// <term>The current instance is less than <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Zero</term> /// <term>The current instance equals <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Greater than zero</term> /// <term>The current instance is greater than <paramref name="other"/>.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>If the current instance is <see cref="NaN"/>, -1 is returned.</para> /// <para>If <paramref name="other"/> is <see langword="null"/>, 1 is returned.</para> /// </remarks> public int CompareTo(double other) { if (IsNaN()) { return double.IsNaN(other) ? 0 : -1; } if (double.IsNaN(other)) { return 1; } if (IsPositiveInfinity()) { return double.IsPositiveInfinity(other) ? 0 : 1; } if (double.IsPositiveInfinity(other)) { return -1; } if (IsNegativeInfinity()) { return double.IsNegativeInfinity(other) ? 0 : -1; } if (double.IsNegativeInfinity(other)) { return 1; } // When the value is zero, exponent can be disregarded; only the sign of the mantissa // matters for the purpose of comparison. if (Mantissa == 0) { return Mantissa.CompareTo(Math.Sign(other)); } // simple cases with opposite signs if (Mantissa < 0 && other > 0) { return -1; } if (other < 0 && Mantissa > 0) { return 1; } // in non-trivial cases, convert to a Number to compare return CompareTo((HugeNumber)other); } /// <summary> /// Compares this instance to a specified object and returns an indication of their relative values. /// </summary> /// <param name="other">An object to compare, or <see langword="null"/>.</param> /// <returns> /// A signed integer value that indicates the relationship of this instance to <paramref /// name="other"/>, as shown in the following table. /// <list type="table"> /// <listheader> /// <term>Return value</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>Less than zero</term> /// <term>The current instance is less than <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Zero</term> /// <term>The current instance equals <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Greater than zero</term> /// <term>The current instance is greater than <paramref name="other"/>.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>If the current instance is <see cref="NaN"/>, -1 is returned.</para> /// <para>If <paramref name="other"/> is <see langword="null"/>, 1 is returned.</para> /// </remarks> public int CompareTo(float other) { if (IsNaN()) { return float.IsNaN(other) ? 0 : -1; } if (float.IsNaN(other)) { return 1; } if (IsPositiveInfinity()) { return float.IsPositiveInfinity(other) ? 0 : 1; } if (float.IsPositiveInfinity(other)) { return -1; } if (IsNegativeInfinity()) { return float.IsNegativeInfinity(other) ? 0 : -1; } if (float.IsNegativeInfinity(other)) { return 1; } // When the value is zero, exponent can be disregarded; only the sign of the mantissa // matters for the purpose of comparison. if (Mantissa == 0) { return Mantissa.CompareTo(Math.Sign(other)); } // simple cases with opposite signs if (Mantissa < 0 && other > 0) { return -1; } if (other < 0 && Mantissa > 0) { return 1; } // in non-trivial cases, convert to a Number to compare return CompareTo((HugeNumber)other); } /// <summary> /// Compares this instance to a specified object and returns an indication of their relative values. /// </summary> /// <param name="other">An object to compare, or <see langword="null"/>.</param> /// <returns> /// A signed integer value that indicates the relationship of this instance to <paramref /// name="other"/>, as shown in the following table. /// <list type="table"> /// <listheader> /// <term>Return value</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>Less than zero</term> /// <term>The current instance is less than <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Zero</term> /// <term>The current instance equals <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Greater than zero</term> /// <term>The current instance is greater than <paramref name="other"/>.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>If the current instance is <see cref="NaN"/>, -1 is returned.</para> /// <para>If <paramref name="other"/> is <see langword="null"/>, 1 is returned.</para> /// </remarks> public int CompareTo(int other) { if (IsNaN()) { return -1; } if (IsPositiveInfinity()) { return 1; } if (IsNegativeInfinity()) { return -1; } // When the other value is zero, or this instance has no exponent, the exponent can be // disregarded. if (other == 0 || Exponent == 0) { return Mantissa.CompareTo(other); } // simple cases with opposite signs if (Mantissa < 0 && other > 0) { return -1; } if (other < 0 && Mantissa > 0) { return 1; } // account for comparisons involving negative exponents if (Exponent < -MantissaDigits) { return -1; } // in non-trivial cases, convert the other value to a Number, then compare return CompareTo(new HugeNumber(other)); } /// <summary> /// Compares this instance to a specified object and returns an indication of their relative values. /// </summary> /// <param name="other">An object to compare, or <see langword="null"/>.</param> /// <returns> /// A signed integer value that indicates the relationship of this instance to <paramref /// name="other"/>, as shown in the following table. /// <list type="table"> /// <listheader> /// <term>Return value</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>Less than zero</term> /// <term>The current instance is less than <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Zero</term> /// <term>The current instance equals <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Greater than zero</term> /// <term>The current instance is greater than <paramref name="other"/>.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>If the current instance is <see cref="NaN"/>, -1 is returned.</para> /// <para>If <paramref name="other"/> is <see langword="null"/>, 1 is returned.</para> /// </remarks> public int CompareTo(long other) { if (IsNaN()) { return -1; } if (IsPositiveInfinity()) { return 1; } if (IsNegativeInfinity()) { return -1; } // When the other value is zero, or this instance has no exponent, the exponent can be // disregarded. if (other == 0 || Exponent == 0) { return Mantissa.CompareTo(other); } // simple cases with opposite signs if (Mantissa < 0 && other > 0) { return -1; } if (other < 0 && Mantissa > 0) { return 1; } // account for comparisons involving negative exponents if (Exponent < -MantissaDigits) { return -1; } // in non-trivial cases, convert the other value to a Number, then compare return CompareTo((HugeNumber)other); } /// <summary> /// Compares this instance to a specified object and returns an indication of their relative values. /// </summary> /// <param name="other">An object to compare, or <see langword="null"/>.</param> /// <returns> /// A signed integer value that indicates the relationship of this instance to <paramref /// name="other"/>, as shown in the following table. /// <list type="table"> /// <listheader> /// <term>Return value</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>Less than zero</term> /// <term>The current instance is less than <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Zero</term> /// <term>The current instance equals <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Greater than zero</term> /// <term>The current instance is greater than <paramref name="other"/>.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>If the current instance is <see cref="NaN"/>, -1 is returned.</para> /// <para>If <paramref name="other"/> is <see langword="null"/>, 1 is returned.</para> /// </remarks> public int CompareTo(HugeNumber other) { if (IsNaN()) { return other.IsNaN() ? 0 : -1; } if (other.IsNaN()) { return 1; } // simple cases with opposite signs if (Mantissa < 0 && other.Mantissa > 0) { return -1; } if (other.Mantissa < 0 && Mantissa > 0) { return 1; } // When either value is zero, exponents can be disregarded; only the sign of the // mantissa matters for the purpose of comparison. if (Mantissa == 0 || other.Mantissa == 0) { var r = Mantissa.CompareTo(other.Mantissa); return r == 0 ? Exponent.CompareTo(other.Exponent) // permit comparing 0 to -0 : r; } if (IsPositiveInfinity()) { return other.IsPositiveInfinity() ? 0 : 1; } if (other.IsPositiveInfinity()) { return -1; } if (IsNegativeInfinity()) { return other.IsNegativeInfinity() ? 0 : -1; } if (other.IsNegativeInfinity()) { return 1; } // make the denominators agree (or remove them) // afterward they can be ignored var value = this; if ((Denominator > 1 || other.Denominator > 1) && Denominator != other.Denominator) { other = ToDenominator(other, Denominator); if (Denominator != other.Denominator) { value = ToDenominator(value, 1); } } var adjustedExponent = value.Exponent + (value.MantissaDigits - 1); var otherAdjustedExponent = other.Exponent + (other.MantissaDigits - 1); // comparison between equal exponents if (adjustedExponent == otherAdjustedExponent) { return value.Mantissa.CompareTo(other.Mantissa); } // comparison of exponents covers all other cases (mantissa comparison is // irrelevant when there is a difference in magnitude) if (adjustedExponent < 0) { if (otherAdjustedExponent < 0) { return adjustedExponent.CompareTo(otherAdjustedExponent); } return value.Mantissa > 0 ? -1 : 1; } if (otherAdjustedExponent < 0) { return value.Mantissa > 0 ? 1 : -1; } return adjustedExponent.CompareTo(otherAdjustedExponent) * (IsNegative() ? -1 : 1); } /// <summary> /// Compares this instance to a specified object and returns an indication of their relative values. /// </summary> /// <param name="other">An object to compare, or <see langword="null"/>.</param> /// <returns> /// A signed integer value that indicates the relationship of this instance to <paramref /// name="other"/>, as shown in the following table. /// <list type="table"> /// <listheader> /// <term>Return value</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>Less than zero</term> /// <term>The current instance is less than <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Zero</term> /// <term>The current instance equals <paramref name="other"/>.</term> /// </item> /// <item> /// <term>Greater than zero</term> /// <term>The current instance is greater than <paramref name="other"/>.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>If the current instance is <see cref="NaN"/>, -1 is returned.</para> /// <para>If <paramref name="other"/> is <see langword="null"/>, 1 is returned.</para> /// </remarks> public int CompareTo(ulong other) { if (IsNaN()) { return -1; } if (IsPositiveInfinity()) { return 1; } if (IsNegativeInfinity()) { return -1; } // When the other value is zero, or this instance has no exponent, the exponent can be // disregarded. if (other == 0 || Exponent == 0) { return Mantissa < 0 ? -1 : ((ulong)Mantissa).CompareTo(other); } // simple cases with opposite signs or negative exponents if (Mantissa < 0 || Exponent < -MantissaDigits) { return -1; } // in non-trivial cases convert the other value, then compare return CompareTo((HugeNumber)other); } /// <summary> /// Compares this instance to a specified object and returns an indication of their relative values. /// </summary> /// <param name="obj">An object to compare, or <see langword="null"/>.</param> /// <returns> /// A signed integer value that indicates the relationship of this instance to <paramref /// name="obj"/>, as shown in the following table. /// <list type="table"> /// <listheader> /// <term>Return value</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>Less than zero</term> /// <term>The current instance is less than <paramref name="obj"/>.</term> /// </item> /// <item> /// <term>Zero</term> /// <term>The current instance equals <paramref name="obj"/>.</term> /// </item> /// <item> /// <term>Greater than zero</term> /// <term>The current instance is greater than <paramref name="obj"/>.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>If the current instance is <see cref="NaN"/>, -1 is returned.</para> /// <para>If <paramref name="obj"/> is <see langword="null"/>, 1 is returned.</para> /// </remarks> public int CompareTo(object? obj) { if (obj is HugeNumber other) { return CompareTo(other); } if (obj is long lValue) { return CompareTo(lValue); } if (obj is int iValue) { return CompareTo(iValue); } if (obj is double dValue) { return CompareTo(dValue); } if (obj is float fValue) { return CompareTo(fValue); } if (obj is string s) { return TryParse(s, out var v) ? CompareTo(v) : 1; } return 1; } /// <summary>Indicates whether the current object is equal to another object.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns><see langword="true"/> if the current object is equal to the <paramref /// name="other">other</paramref> parameter; otherwise, <see langword="false"/>.</returns> public bool Equals(decimal other) { if (!IsFinite()) { return false; } if (other == 0) { return Mantissa == 0; } return Equals((HugeNumber)other); } /// <summary>Indicates whether the current object is equal to another object.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns><see langword="true"/> if the current object is equal to the <paramref /// name="other">other</paramref> parameter; otherwise, <see langword="false"/>.</returns> public bool Equals(double other) { if (IsNaN() || double.IsNaN(other)) { return false; } if (IsNegativeInfinity()) { return double.IsNegativeInfinity(other); } if (IsPositiveInfinity()) { return double.IsPositiveInfinity(other); } if (other == 0) { return Mantissa == 0; } return Equals((HugeNumber)other); } /// <summary>Indicates whether the current object is equal to another object.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns><see langword="true"/> if the current object is equal to the <paramref /// name="other">other</paramref> parameter; otherwise, <see langword="false"/>.</returns> public bool Equals(float other) { if (IsNaN() || float.IsNaN(other)) { return false; } if (IsNegativeInfinity()) { return float.IsNegativeInfinity(other); } if (IsPositiveInfinity()) { return float.IsPositiveInfinity(other); } if (other == 0) { return Mantissa == 0; } return Equals((HugeNumber)other); } /// <summary>Indicates whether the current object is equal to another object.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns><see langword="true"/> if the current object is equal to the <paramref /// name="other">other</paramref> parameter; otherwise, <see langword="false"/>.</returns> public bool Equals(int other) { if (!IsFinite()) { return false; } return Mantissa == other && Denominator == 1 && Exponent == 0; } /// <summary>Indicates whether the current object is equal to another object.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns><see langword="true"/> if the current object is equal to the <paramref /// name="other">other</paramref> parameter; otherwise, <see langword="false"/>.</returns> public bool Equals(long other) { if (!IsFinite()) { return false; } return Mantissa == other && Denominator == 1 && Exponent == 0; } /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns><see langword="true"/> if the current object is equal to the <paramref /// name="other">other</paramref> parameter; otherwise, <see langword="false"/>.</returns> public bool Equals(HugeNumber other) => !IsNaN() && !other.IsNaN() && Mantissa == other.Mantissa && Denominator == other.Denominator && Exponent == other.Exponent; /// <summary>Indicates whether the current object is equal to another object.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns><see langword="true"/> if the current object is equal to the <paramref /// name="other">other</paramref> parameter; otherwise, <see langword="false"/>.</returns> public bool Equals(ulong other) { if (!IsFinite()) { return false; } if (other == 0) { return Mantissa == 0; } return Equals((HugeNumber)other); } /// <summary>Indicates whether this instance and a specified object are equal.</summary> /// <param name="obj">The object to compare with the current instance.</param> /// <returns><see langword="true"/> if <paramref name="obj">obj</paramref> and this instance /// are the same type and represent the same value; otherwise, <see /// langword="false"/>.</returns> public override bool Equals(object? obj) { if (obj is HugeNumber other) { return Equals(other); } if (obj is long lValue) { return Equals(lValue); } if (obj is int iValue) { return Equals(iValue); } if (obj is double dValue) { return Equals(dValue); } if (obj is float fValue) { return Equals(fValue); } if (obj is byte bValue) { return Equals(bValue); } if (obj is short sValue) { return Equals(sValue); } if (obj is nint nValue) { return Equals(nValue); } if (obj is sbyte sbValue) { return Equals(sbValue); } if (obj is ushort usValue) { return Equals(usValue); } if (obj is uint uiValue) { return Equals(uiValue); } if (obj is ulong ulValue) { return Equals(ulValue); } if (obj is nuint nuValue) { return Equals(nuValue); } if (obj is string s) { return TryParse(s, out var sv) && Equals(sv); } if (obj is IFormattable f) { return TryParse(f.ToString(null, null), out var fv) && Equals(fv); } return TryParse(obj?.ToString(), out var v) && Equals(v); } /// <summary>Returns the hash code for this instance.</summary> /// <returns>A 32-bit signed integer that is the hash code for this instance.</returns> public override int GetHashCode() => HashCode.Combine(Mantissa, Denominator, Exponent); /// <summary> /// Returns a value that indicates whether a <see cref="decimal"/> value and an <see /// cref="HugeNumber"/> value are equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> /// parameters have the same value; otherwise, <see langword="false"/>. /// </returns> public static bool operator ==(decimal left, HugeNumber right) => right.Equals(left); /// <summary> /// Returns a value that indicates whether a <see cref="double"/> value and an <see /// cref="HugeNumber"/> value are equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> /// parameters have the same value; otherwise, <see langword="false"/>. /// </returns> public static bool operator ==(double left, HugeNumber right) => right.Equals(left); /// <summary> /// Returns a value that indicates whether a signed <see cref="long"/> integer value and /// an <see cref="HugeNumber"/> value are equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> /// parameters have the same value; otherwise, <see langword="false"/>. /// </returns> public static bool operator ==(long left, HugeNumber right) => right.Equals(left); /// <summary> /// Returns a value that indicates whether an unsigned <see cref="long"/> integer value and /// an <see cref="HugeNumber"/> value are equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> /// parameters have the same value; otherwise, <see langword="false"/>. /// </returns> public static bool operator ==(ulong left, HugeNumber right) => right.Equals(left); /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> and a <see /// cref="decimal"/> value are equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> /// parameters have the same value; otherwise, <see langword="false"/>. /// </returns> public static bool operator ==(HugeNumber left, decimal right) => left.Equals(right); /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> and a <see /// cref="double"/> value are equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> /// parameters have the same value; otherwise, <see langword="false"/>. /// </returns> public static bool operator ==(HugeNumber left, double right) => left.Equals(right); /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> and a signed <see /// cref="long"/> integer value are equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> /// parameters have the same value; otherwise, <see langword="false"/>. /// </returns> public static bool operator ==(HugeNumber left, long right) => left.Equals(right); /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> and an unsigned /// 64-bit integer value are equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> /// parameters have the same value; otherwise, <see langword="false"/>. /// </returns> public static bool operator ==(HugeNumber left, ulong right) => left.Equals(right); /// <summary> /// Returns a value that indicates whether the values of two <see cref="HugeNumber"/> objects are equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> /// parameters have the same value; otherwise, <see langword="false"/>. /// </returns> public static bool operator ==(HugeNumber left, HugeNumber right) => left.Equals(right); /// <summary> /// Returns a value that indicates whether a <see cref="decimal"/> and an <see /// cref="HugeNumber"/> value are not equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> are /// not equal; otherwise, <see langword="false"/>. /// </returns> public static bool operator !=(decimal left, HugeNumber right) => !right.Equals(left); /// <summary> /// Returns a value that indicates whether a <see cref="double"/> and an <see /// cref="HugeNumber"/> value are not equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> are /// not equal; otherwise, <see langword="false"/>. /// </returns> public static bool operator !=(double left, HugeNumber right) => !right.Equals(left); /// <summary> /// Returns a value that indicates whether a 64-bit signed integer and an <see /// cref="HugeNumber"/> value are not equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> are /// not equal; otherwise, <see langword="false"/>. /// </returns> public static bool operator !=(long left, HugeNumber right) => !right.Equals(left); /// <summary> /// Returns a value that indicates whether a 64-bit unsigned integer and an <see /// cref="HugeNumber"/> value are not equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> are /// not equal; otherwise, <see langword="false"/>. /// </returns> public static bool operator !=(ulong left, HugeNumber right) => !right.Equals(left); /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> and a <see /// cref="decimal"/> are not equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> are /// not equal; otherwise, <see langword="false"/>. /// </returns> public static bool operator !=(HugeNumber left, decimal right) => !left.Equals(right); /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> and a <see /// cref="double"/> are not equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> are /// not equal; otherwise, <see langword="false"/>. /// </returns> public static bool operator !=(HugeNumber left, double right) => !left.Equals(right); /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> and a 64-bit signed /// integer are not equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> are /// not equal; otherwise, <see langword="false"/>. /// </returns> public static bool operator !=(HugeNumber left, long right) => !left.Equals(right); /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> and a 64-bit unsigned /// integer are not equal. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> are /// not equal; otherwise, <see langword="false"/>. /// </returns> public static bool operator !=(HugeNumber left, ulong right) => !left.Equals(right); /// <summary> /// Returns a value that indicates whether the two <see cref="HugeNumber"/> objects have /// different values. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if the <paramref name="left"/> and <paramref name="right"/> are /// not equal; otherwise, <see langword="false"/>. /// </returns> public static bool operator !=(HugeNumber left, HugeNumber right) => !left.Equals(right); /// <summary> /// Returns a value that indicates whether a <see cref="decimal"/> is less than an <see /// cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator <(decimal left, HugeNumber right) => right.CompareTo(left) * -1 < 0; /// <summary> /// Returns a value that indicates whether a <see cref="double"/> is less than an <see /// cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator <(double left, HugeNumber right) => right.CompareTo(left) * -1 < 0; /// <summary> /// Returns a value that indicates whether a 64-bit signed integer is less than an <see /// cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator <(long left, HugeNumber right) => right.CompareTo(left) * -1 < 0; /// <summary> /// Returns a value that indicates whether a 64-bit unsigned integer is less than an <see /// cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator <(ulong left, HugeNumber right) => right.CompareTo(left) * -1 < 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is less than a <see cref="decimal"/>. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator <(HugeNumber left, decimal right) => left.CompareTo(right) < 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is less than a <see cref="double"/>. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator <(HugeNumber left, double right) => left.CompareTo(right) < 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is less than a 64-bit /// signed integer. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator <(HugeNumber left, long right) => left.CompareTo(right) < 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is less than a 64-bit /// unsigned integer. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator <(HugeNumber left, ulong right) => left.CompareTo(right) < 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> value is less than another /// <see cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator <(HugeNumber left, HugeNumber right) => left.CompareTo(right) < 0; /// <summary> /// Returns a value that indicates whether a <see cref="decimal"/> is greater than an <see /// cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator >(decimal left, HugeNumber right) => right.CompareTo(left) * -1 > 0; /// <summary> /// Returns a value that indicates whether a <see cref="double"/> is greater than an <see /// cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator >(double left, HugeNumber right) => right.CompareTo(left) * -1 > 0; /// <summary> /// Returns a value that indicates whether a 64-bit signed integer is greater than an <see /// cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator >(long left, HugeNumber right) => right.CompareTo(left) * -1 > 0; /// <summary> /// Returns a value that indicates whether a 64-bit unsigned integer is greater than an <see /// cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator >(ulong left, HugeNumber right) => right.CompareTo(left) * -1 > 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is greater than a /// <see cref="decimal"/>. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >(HugeNumber left, decimal right) => left.CompareTo(right) > 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is greater than a /// <see cref="double"/>. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >(HugeNumber left, double right) => left.CompareTo(right) > 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is greater than a 64-bit /// signed integer. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator >(HugeNumber left, long right) => left.CompareTo(right) > 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is greater than a /// 64-bit unsigned integer. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >(HugeNumber left, ulong right) => left.CompareTo(right) > 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> value is greater than /// another <see cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >(HugeNumber left, HugeNumber right) => left.CompareTo(right) > 0; /// <summary> /// Returns a value that indicates whether a <see cref="decimal"/> is less than or equal to an /// <see cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator <=(decimal left, HugeNumber right) => right.CompareTo(left) * -1 <= 0; /// <summary> /// Returns a value that indicates whether a <see cref="double"/> is less than or equal to an /// <see cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator <=(double left, HugeNumber right) => right.CompareTo(left) * -1 <= 0; /// <summary> /// Returns a value that indicates whether a 64-bit signed integer is less than or equal to an <see /// cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than or equal to <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator <=(long left, HugeNumber right) => right.CompareTo(left) * -1 <= 0; /// <summary> /// Returns a value that indicates whether a 64-bit unsigned integer is less than or equal to /// an <see cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator <=(ulong left, HugeNumber right) => right.CompareTo(left) * -1 <= 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is less than or equal /// to a <see cref="decimal"/>. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator <=(HugeNumber left, decimal right) => left.CompareTo(right) <= 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is less than or equal /// to a <see cref="double"/>. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator <=(HugeNumber left, double right) => left.CompareTo(right) <= 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is less than or equal /// to a 64-bit signed integer. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator <=(HugeNumber left, long right) => left.CompareTo(right) <= 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is less than or equal /// to a 64-bit unsigned integer. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator <=(HugeNumber left, ulong right) => left.CompareTo(right) <= 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> value is less than or /// equal to another <see cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is less than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator <=(HugeNumber left, HugeNumber right) => left.CompareTo(right) <= 0; /// <summary> /// Returns a value that indicates whether a <see cref="decimal"/> is greater than or equal /// to an <see cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >=(decimal left, HugeNumber right) => right.CompareTo(left) * -1 >= 0; /// <summary> /// Returns a value that indicates whether a <see cref="double"/> is greater than or equal /// to an <see cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >=(double left, HugeNumber right) => right.CompareTo(left) * -1 >= 0; /// <summary> /// Returns a value that indicates whether a 64-bit signed integer is greater than or equal /// to an <see cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >=(long left, HugeNumber right) => right.CompareTo(left) * -1 >= 0; /// <summary> /// Returns a value that indicates whether a 64-bit unsigned integer is greater than or equal /// to an <see cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >=(ulong left, HugeNumber right) => right.CompareTo(left) * -1 >= 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is greater than a /// <see cref="decimal"/>. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >=(HugeNumber left, decimal right) => left.CompareTo(right) >= 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is greater than a /// <see cref="double"/>. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >=(HugeNumber left, double right) => left.CompareTo(right) >= 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is greater than a 64-bit /// signed integer. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator >=(HugeNumber left, long right) => left.CompareTo(right) >= 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> is greater than or /// equal to a 64-bit unsigned integer. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >=(HugeNumber left, ulong right) => left.CompareTo(right) >= 0; /// <summary> /// Returns a value that indicates whether an <see cref="HugeNumber"/> value is greater than /// or equal to another <see cref="HugeNumber"/> value. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> is greater than or equal to <paramref /// name="right"/>; otherwise, <see langword="false"/>. /// </returns> public static bool operator >=(HugeNumber left, HugeNumber right) => left.CompareTo(right) >= 0; }
38.711649
112
0.578433
[ "MIT" ]
Tavenem/HugeNumber
src/Comparable.cs
60,818
C#
// using System; using System.Collections.Generic; using Autofac; using MbUnit.Framework; using SolrNet; namespace AutofacContrib.SolrNet.Tests { [TestFixture] [Category("Integration")] public class AutofacIntegrationFixture { [Test] public void Ping_And_Query() { var builder = new ContainerBuilder(); builder.RegisterModule(new SolrNetModule("http://localhost:8983/solr")); var container = builder.Build(); var solr = container.Resolve<ISolrOperations<AutofacFixture.Entity>>(); solr.Ping(); Console.WriteLine(solr.Query(SolrQuery.All).Count); } [Test] public void DictionaryDocument() { var builder = new ContainerBuilder(); builder.RegisterModule(new SolrNetModule("http://localhost:8983/solr")); var container = builder.Build(); var solr = container.Resolve<ISolrOperations<Dictionary<string, object>>>(); var results = solr.Query(SolrQuery.All); Assert.GreaterThan(results.Count, 0); foreach (var d in results) { Assert.GreaterThan(d.Count, 0); foreach (var kv in d) Console.WriteLine("{0}: {1}", kv.Key, kv.Value); } } [Test] public void DictionaryDocument_add() { var builder = new ContainerBuilder(); builder.RegisterModule(new SolrNetModule("http://localhost:8983/solr")); var container = builder.Build(); var solr = container.Resolve<ISolrOperations<Dictionary<string, object>>>(); solr.Add(new Dictionary<string, object> { {"id", "ababa"}, {"manu", "who knows"}, {"popularity", 55}, {"timestamp", DateTime.UtcNow}, }); } } }
35.321429
89
0.544995
[ "Apache-2.0" ]
Aaronontheweb/SolrNet
AutofacContrib.SolrNet.Tests/AutofacIntegrationFixture.cs
1,980
C#
using System; using Xamarin.Forms; using GifImageView.FormsPlugin.Abstractions; namespace GifViewer { public class App : Application { public App() { // The root page of your application MainPage = new ContentPage { Content = new GifImageViewControl { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, Source = ImageSource.FromResource("GifViewer.dogturtle.gif") // Source = ImageSource.FromUri(new Uri("http://dogoverflow.com/dRX5G8qK")) } }; } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
25.119048
102
0.51564
[ "MIT" ]
jamesmontemagno/Xamarin.Forms-Awesome-Controls
GifImageView/GifViewer/GifViewer.cs
1,057
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Inputs.Packages.V1Alpha1 { public class StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLifecyclePreStopHttpGetArgs : Pulumi.ResourceArgs { [Input("host")] public Input<string>? Host { get; set; } [Input("httpHeaders")] private InputList<Pulumi.Kubernetes.Types.Inputs.Packages.V1Alpha1.StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLifecyclePreStopHttpGetHttpHeadersArgs>? _httpHeaders; public InputList<Pulumi.Kubernetes.Types.Inputs.Packages.V1Alpha1.StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLifecyclePreStopHttpGetHttpHeadersArgs> HttpHeaders { get => _httpHeaders ?? (_httpHeaders = new InputList<Pulumi.Kubernetes.Types.Inputs.Packages.V1Alpha1.StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLifecyclePreStopHttpGetHttpHeadersArgs>()); set => _httpHeaders = value; } [Input("path")] public Input<string>? Path { get; set; } [Input("port", required: true)] public Input<Pulumi.Kubernetes.Types.Inputs.Packages.V1Alpha1.StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLifecyclePreStopHttpGetPortArgs> Port { get; set; } = null!; [Input("scheme")] public Input<string>? Scheme { get; set; } public StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLifecyclePreStopHttpGetArgs() { } } }
44.7
222
0.754474
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/crossplane/dotnet/Kubernetes/Crds/Operators/Crossplane/Packages/V1Alpha1/Inputs/StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLifecyclePreStopHttpGetArgs.cs
1,788
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; #if FEATURE_APPDOMAIN using System.Runtime.Remoting.Lifetime; using System.Runtime.Remoting; #endif using System.Threading; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Execution; using System.Diagnostics; using Microsoft.Build.Collections; using ElementLocation = Microsoft.Build.Construction.ElementLocation; using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem; using TaskLoggingContext = Microsoft.Build.BackEnd.Logging.TaskLoggingContext; using System.Threading.Tasks; using Microsoft.Build.BackEnd.Components.Caching; using System.Reflection; using Microsoft.Build.Eventing; #nullable disable namespace Microsoft.Build.BackEnd { /// <summary> /// The task host object which allows tasks to interface with the rest of the build system. /// Implementation of IBuildEngineX is thread-safe, so, for example, tasks can log concurrently on multiple threads. /// </summary> internal class TaskHost : #if FEATURE_APPDOMAIN MarshalByRefObject, #endif IBuildEngine10 { /// <summary> /// True if the "secret" environment variable MSBUILDNOINPROCNODE is set. /// </summary> private static bool s_disableInprocNodeByEnvironmentVariable = Environment.GetEnvironmentVariable("MSBUILDNOINPROCNODE") == "1"; /// <summary> /// Help diagnose tasks that log after they return. /// </summary> private static bool s_breakOnLogAfterTaskReturns = Environment.GetEnvironmentVariable("MSBUILDBREAKONLOGAFTERTASKRETURNS") == "1"; /// <summary> /// The build component host /// </summary> private IBuildComponentHost _host; /// <summary> /// The build request entry /// </summary> private BuildRequestEntry _requestEntry; /// <summary> /// Location of the task node in the original file /// </summary> private ElementLocation _taskLocation; /// <summary> /// The task logging context /// </summary> private TaskLoggingContext _taskLoggingContext; /// <summary> /// True if the task connected to this proxy is alive /// </summary> private bool _activeProxy; /// <summary> /// The callback used to invoke the target builder. /// </summary> private ITargetBuilderCallback _targetBuilderCallback; /// <summary> /// This reference type is used to block access to a single entry methods of the interface /// </summary> private object _callbackMonitor; #if FEATURE_APPDOMAIN /// <summary> /// A client sponsor is a class /// which will respond to a lease renewal request and will /// increase the lease time allowing the object to stay in memory /// </summary> private ClientSponsor _sponsor; #endif /// <summary> /// Legacy continue on error value per batch exposed via IBuildEngine /// </summary> private bool _continueOnError; /// <summary> /// Flag indicating if errors should be converted to warnings. /// </summary> private bool _convertErrorsToWarnings; /// <summary> /// The thread on which we yielded. /// </summary> private int _yieldThreadId = -1; private bool _disableInprocNode; /// <summary> /// Constructor /// </summary> /// <param name="host">The component host</param> /// <param name="requestEntry">The build request entry</param> /// <param name="taskLocation">The <see cref="ElementLocation"/> of the task.</param> /// <param name="targetBuilderCallback">An <see cref="ITargetBuilderCallback"/> to use to invoke targets and build projects.</param> public TaskHost(IBuildComponentHost host, BuildRequestEntry requestEntry, ElementLocation taskLocation, ITargetBuilderCallback targetBuilderCallback) { ErrorUtilities.VerifyThrowArgumentNull(host, nameof(host)); ErrorUtilities.VerifyThrowArgumentNull(requestEntry, nameof(requestEntry)); ErrorUtilities.VerifyThrowInternalNull(taskLocation, nameof(taskLocation)); _host = host; _requestEntry = requestEntry; _taskLocation = taskLocation; _targetBuilderCallback = targetBuilderCallback; _continueOnError = false; _activeProxy = true; _callbackMonitor = new object(); _disableInprocNode = ChangeWaves.AreFeaturesEnabled(ChangeWaves.Wave17_0) ? s_disableInprocNodeByEnvironmentVariable || host.BuildParameters.DisableInProcNode : s_disableInprocNodeByEnvironmentVariable; EngineServices = new EngineServicesImpl(this); } /// <summary> /// Returns true in the multiproc case /// </summary> /// <comment> /// If MSBUILDNOINPROCNODE is set, then even if there's only one node in the buildparameters, it will be an out-of-proc node. /// </comment> public bool IsRunningMultipleNodes { get { VerifyActiveProxy(); return _host.BuildParameters.MaxNodeCount > 1 || _disableInprocNode; } } /// <summary> /// Reflects the value of the ContinueOnError attribute. /// </summary> public bool ContinueOnError { get { VerifyActiveProxy(); return _continueOnError; } internal set { _continueOnError = value; } } /// <summary> /// The line number this task is on /// </summary> public int LineNumberOfTaskNode { get { return _taskLocation.Line; } } /// <summary> /// The column number this task is on /// </summary> public int ColumnNumberOfTaskNode { get { return _taskLocation.Column; } } /// <summary> /// The project file this task is in. /// Typically this is an imported .targets file. /// Unfortunately the interface has shipped with a poor name, so we cannot change it. /// </summary> public string ProjectFileOfTaskNode { get { return _taskLocation.File; } } /// <summary> /// Indicates whether or not errors should be converted to warnings. /// </summary> internal bool ConvertErrorsToWarnings { get { return _convertErrorsToWarnings; } set { _convertErrorsToWarnings = value; } } /// <summary> /// Sets or retrieves the logging context /// </summary> internal TaskLoggingContext LoggingContext { [DebuggerStepThrough] get { return _taskLoggingContext; } [DebuggerStepThrough] set { _taskLoggingContext = value; } } #if FEATURE_APPDOMAIN /// <summary> /// For configuring child AppDomains. /// </summary> internal AppDomainSetup AppDomainSetup { get { return _host.BuildParameters.AppDomainSetup; } } #endif /// <summary> /// Whether or not this is out of proc. /// </summary> internal bool IsOutOfProc { get { return _host.BuildParameters.IsOutOfProc; } } public bool BuildRequestsSucceeded { get; private set; } = true; #region IBuildEngine2 Members /// <summary> /// Builds a single project file /// Thread safe. /// </summary> /// <param name="projectFileName">The project file</param> /// <param name="targetNames">The list of targets to build</param> /// <param name="globalProperties">The global properties to use</param> /// <param name="targetOutputs">The outputs from the targets</param> /// <param name="toolsVersion">The tools version to use</param> /// <returns>True on success, false otherwise.</returns> public bool BuildProjectFile(string projectFileName, string[] targetNames, System.Collections.IDictionary globalProperties, System.Collections.IDictionary targetOutputs, string toolsVersion) { VerifyActiveProxy(); return BuildProjectFilesInParallel ( new string[] { projectFileName }, targetNames, new IDictionary[] { globalProperties }, new IDictionary[] { targetOutputs }, new string[] { toolsVersion }, true, false ); } /// <summary> /// Builds multiple project files in parallel. This is the method the old MSBuild task invokes. /// Thread safe. /// </summary> /// <param name="projectFileNames">The list of projects to build</param> /// <param name="targetNames">The set of targets to build</param> /// <param name="globalProperties">The global properties to use for each project</param> /// <param name="targetOutputsPerProject">The outputs for each target on each project</param> /// <param name="toolsVersion">The tools versions to use</param> /// <param name="useResultsCache">Whether to use the results cache</param> /// <param name="unloadProjectsOnCompletion">Whether to unload projects when we are done.</param> /// <returns>True on success, false otherwise.</returns> public bool BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, System.Collections.IDictionary[] globalProperties, System.Collections.IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion) { bool includeTargetOutputs = (targetOutputsPerProject != null); // If the caller supplies an array to put the target outputs in, it must have the same length as the array of project file names they provided, too. // "MSB3094: "{2}" refers to {0} item(s), and "{3}" refers to {1} item(s). They must have the same number of items." ErrorUtilities.VerifyThrowArgument((targetOutputsPerProject == null) || (projectFileNames.Length == targetOutputsPerProject.Length), "General.TwoVectorsMustHaveSameLength", projectFileNames.Length, targetOutputsPerProject?.Length ?? 0, "projectFileNames", "targetOutputsPerProject"); BuildEngineResult result = BuildProjectFilesInParallel(projectFileNames, targetNames, globalProperties, new List<String>[projectFileNames.Length], toolsVersion, includeTargetOutputs); if (includeTargetOutputs) { // Copy results from result.TargetOutputsPerProject to targetOutputsPerProject // We should always have the same number of entries - although an entry might be empty if a project failed. ErrorUtilities.VerifyThrow(targetOutputsPerProject.Length == result.TargetOutputsPerProject.Count, "{0} != {1}", targetOutputsPerProject.Length, result.TargetOutputsPerProject.Count); for (int i = 0; i < targetOutputsPerProject.Length; i++) { if (targetOutputsPerProject[i] != null) { foreach (KeyValuePair<string, ITaskItem[]> output in result.TargetOutputsPerProject[i]) { targetOutputsPerProject[i].Add(output.Key, output.Value); } } } } BuildRequestsSucceeded = result.Result; return result.Result; } #endregion #region IBuildEngine3 Members /// <summary> /// Builds multiple project files in parallel. /// Thread safe. /// </summary> /// <param name="projectFileNames">The list of projects to build</param> /// <param name="targetNames">The set of targets to build</param> /// <param name="globalProperties">The global properties to use for each project</param> /// <param name="undefineProperties">The list of global properties to undefine</param> /// <param name="toolsVersion">The tools versions to use</param> /// <param name="returnTargetOutputs">Should the target outputs be returned in the BuildEngineResult</param> /// <returns>A structure containing the result of the build, success or failure and the list of target outputs per project</returns> public BuildEngineResult BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, System.Collections.IDictionary[] globalProperties, IList<String>[] undefineProperties, string[] toolsVersion, bool returnTargetOutputs) { lock (_callbackMonitor) { return BuildProjectFilesInParallelAsync(projectFileNames, targetNames, globalProperties, undefineProperties, toolsVersion, returnTargetOutputs).Result; } } /// <summary> /// Requests to yield the node. /// Thread safe, however Yield cannot be called unless the /// last call to Yield or Reacquire was Reacquire. /// </summary> public void Yield() { lock (_callbackMonitor) { IRequestBuilderCallback builderCallback = _requestEntry.Builder as IRequestBuilderCallback; ErrorUtilities.VerifyThrow(_yieldThreadId == -1, "Cannot call Yield() while yielding."); _yieldThreadId = Thread.CurrentThread.ManagedThreadId; MSBuildEventSource.Log.ExecuteTaskYieldStart(_taskLoggingContext.TaskName, _taskLoggingContext.BuildEventContext.TaskId); builderCallback.Yield(); } } /// <summary> /// Requests to reacquire the node. /// Thread safe, however Reacquire cannot be called unless the /// last call to Yield or Reacquire was Yield. /// </summary> public void Reacquire() { // Release all cores on reacquire. The assumption here is that the task is done with CPU intensive work at this point and forgetting // to release explicitly granted cores when reacquiring the node may lead to deadlocks. ReleaseAllCores(); lock (_callbackMonitor) { IRequestBuilderCallback builderCallback = _requestEntry.Builder as IRequestBuilderCallback; ErrorUtilities.VerifyThrow(_yieldThreadId != -1, "Cannot call Reacquire() before Yield()."); ErrorUtilities.VerifyThrow(_yieldThreadId == Thread.CurrentThread.ManagedThreadId, "Cannot call Reacquire() on thread {0} when Yield() was called on thread {1}", Thread.CurrentThread.ManagedThreadId, _yieldThreadId); MSBuildEventSource.Log.ExecuteTaskYieldStop(_taskLoggingContext.TaskName, _taskLoggingContext.BuildEventContext.TaskId); MSBuildEventSource.Log.ExecuteTaskReacquireStart(_taskLoggingContext.TaskName, _taskLoggingContext.BuildEventContext.TaskId); builderCallback.Reacquire(); MSBuildEventSource.Log.ExecuteTaskReacquireStop(_taskLoggingContext.TaskName, _taskLoggingContext.BuildEventContext.TaskId); _yieldThreadId = -1; } } #endregion #region IBuildEngine Members /// <summary> /// Logs an error event for the current task /// Thread safe. /// </summary> /// <param name="e">The event args</param> public void LogErrorEvent(Microsoft.Build.Framework.BuildErrorEventArgs e) { lock (_callbackMonitor) { ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e)); if (!_activeProxy) { // The task has been logging on another thread, typically // because of logging a spawned process's output, and has // not terminated this logging before it returned. This is common // enough that we don't want to crash and break the entire build. But // we don't have any good way to log it any more, as not only has this task // finished, the whole build might have finished! The task author will // just have to figure out that their task has a bug by themselves. if (s_breakOnLogAfterTaskReturns) { Trace.Fail(String.Format(CultureInfo.CurrentUICulture, "Task at {0}, after already returning, attempted to log '{1}'", _taskLocation.ToString(), e.Message)); } return; } // If we are in building across process we need the events to be serializable. This method will // check to see if we are building with multiple process and if the event is serializable. It will // also log a warning if the event is not serializable and drop the logging message. if (IsRunningMultipleNodes && !IsEventSerializable(e)) { return; } if (_convertErrorsToWarnings) { // Convert the error into a warning. We do this because the whole point of // ContinueOnError is that a project author expects that the task might fail, // but wants to ignore the failures. This implies that we shouldn't be logging // errors either, because you should never have a successful build with errors. BuildWarningEventArgs warningEvent = new BuildWarningEventArgs ( e.Subcategory, e.Code, e.File, e.LineNumber, e.ColumnNumber, e.EndLineNumber, e.EndColumnNumber, e.Message, e.HelpKeyword, e.SenderName ); warningEvent.BuildEventContext = _taskLoggingContext.BuildEventContext; _taskLoggingContext.LoggingService.LogBuildEvent(warningEvent); // Log a message explaining why we converted the previous error into a warning. _taskLoggingContext.LoggingService.LogComment(_taskLoggingContext.BuildEventContext, MessageImportance.Normal, "ErrorConvertedIntoWarning"); } else { e.BuildEventContext = _taskLoggingContext.BuildEventContext; _taskLoggingContext.LoggingService.LogBuildEvent(e); } _taskLoggingContext.HasLoggedErrors = true; } } /// <summary> /// Logs a warning event for the current task /// Thread safe. /// </summary> /// <param name="e">The event args</param> public void LogWarningEvent(Microsoft.Build.Framework.BuildWarningEventArgs e) { lock (_callbackMonitor) { ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e)); if (!_activeProxy) { // The task has been logging on another thread, typically // because of logging a spawned process's output, and has // not terminated this logging before it returned. This is common // enough that we don't want to crash and break the entire build. But // we don't have any good way to log it any more, as not only has this task // finished, the whole build might have finished! The task author will // just have to figure out that their task has a bug by themselves. if (s_breakOnLogAfterTaskReturns) { Trace.Fail(String.Format(CultureInfo.CurrentUICulture, "Task at {0}, after already returning, attempted to log '{1}'", _taskLocation.ToString(), e.Message)); } return; } // If we are in building across process we need the events to be serializable. This method will // check to see if we are building with multiple process and if the event is serializable. It will // also log a warning if the event is not serializable and drop the logging message. if (IsRunningMultipleNodes && !IsEventSerializable(e)) { return; } e.BuildEventContext = _taskLoggingContext.BuildEventContext; _taskLoggingContext.LoggingService.LogBuildEvent(e); } } /// <summary> /// Logs a message event for the current task /// Thread safe. /// </summary> /// <param name="e">The event args</param> public void LogMessageEvent(Microsoft.Build.Framework.BuildMessageEventArgs e) { lock (_callbackMonitor) { ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e)); if (!_activeProxy) { // The task has been logging on another thread, typically // because of logging a spawned process's output, and has // not terminated this logging before it returned. This is common // enough that we don't want to crash and break the entire build. But // we don't have any good way to log it any more, as not only has this task // finished, the whole build might have finished! The task author will // just have to figure out that their task has a bug by themselves. if (s_breakOnLogAfterTaskReturns) { Trace.Fail(String.Format(CultureInfo.CurrentUICulture, "Task at {0}, after already returning, attempted to log '{1}'", _taskLocation.ToString(), e.Message)); } return; } // If we are in building across process we need the events to be serializable. This method will // check to see if we are building with multiple process and if the event is serializable. It will // also log a warning if the event is not serializable and drop the logging message. if (IsRunningMultipleNodes && !IsEventSerializable(e)) { return; } e.BuildEventContext = _taskLoggingContext.BuildEventContext; _taskLoggingContext.LoggingService.LogBuildEvent(e); } } /// <summary> /// Logs a custom event for the current task /// Thread safe. /// </summary> /// <param name="e">The event args</param> public void LogCustomEvent(Microsoft.Build.Framework.CustomBuildEventArgs e) { lock (_callbackMonitor) { ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e)); if (!_activeProxy) { // The task has been logging on another thread, typically // because of logging a spawned process's output, and has // not terminated this logging before it returned. This is common // enough that we don't want to crash and break the entire build. But // we don't have any good way to log it any more, as not only has this task // finished, the whole build might have finished! The task author will // just have to figure out that their task has a bug by themselves. if (s_breakOnLogAfterTaskReturns) { Trace.Fail(String.Format(CultureInfo.CurrentUICulture, "Task at {0}, after already returning, attempted to log '{1}'", _taskLocation.ToString(), e.Message)); } return; } // If we are in building across process we need the events to be serializable. This method will // check to see if we are building with multiple process and if the event is serializable. It will // also log a warning if the event is not serializable and drop the logging message. if (IsRunningMultipleNodes && !IsEventSerializable(e)) { return; } e.BuildEventContext = _taskLoggingContext.BuildEventContext; _taskLoggingContext.LoggingService.LogBuildEvent(e); } } /// <summary> /// Builds a single project file /// Thread safe. /// </summary> /// <param name="projectFileName">The project file name</param> /// <param name="targetNames">The set of targets to build.</param> /// <param name="globalProperties">The global properties to use</param> /// <param name="targetOutputs">The outputs from the targets</param> /// <returns>True on success, false otherwise.</returns> public bool BuildProjectFile(string projectFileName, string[] targetNames, System.Collections.IDictionary globalProperties, System.Collections.IDictionary targetOutputs) { VerifyActiveProxy(); return BuildProjectFile(projectFileName, targetNames, globalProperties, targetOutputs, null); } #endregion #region IBuildEngine4 Members /// <summary> /// Disposes of all of the objects with the specified lifetime. /// </summary> public void RegisterTaskObject(object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection) { var objectCache = (IRegisteredTaskObjectCache)_host.GetComponent(BuildComponentType.RegisteredTaskObjectCache); objectCache.RegisterTaskObject(key, obj, lifetime, allowEarlyCollection); } /// <summary> /// Gets a previously registered task object. /// </summary> public object GetRegisteredTaskObject(object key, RegisteredTaskObjectLifetime lifetime) { var objectCache = (IRegisteredTaskObjectCache)_host.GetComponent(BuildComponentType.RegisteredTaskObjectCache); return objectCache.GetRegisteredTaskObject(key, lifetime); } /// <summary> /// Unregisters a task object. /// </summary> public object UnregisterTaskObject(object key, RegisteredTaskObjectLifetime lifetime) { var objectCache = (IRegisteredTaskObjectCache)_host.GetComponent(BuildComponentType.RegisteredTaskObjectCache); return objectCache.UnregisterTaskObject(key, lifetime); } #endregion #region BuildEngine5 Members /// <summary> /// Logs a telemetry event for the current task. /// </summary> /// <param name="eventName">The event name.</param> /// <param name="properties">The list of properties associated with the event.</param> public void LogTelemetry(string eventName, IDictionary<string, string> properties) { lock (_callbackMonitor) { ErrorUtilities.VerifyThrowArgumentNull(eventName, nameof(eventName)); if (!_activeProxy) { // The task has been logging on another thread, typically // because of logging a spawned process's output, and has // not terminated this logging before it returned. This is common // enough that we don't want to crash and break the entire build. But // we don't have any good way to log it any more, as not only has this task // finished, the whole build might have finished! The task author will // just have to figure out that their task has a bug by themselves. if (s_breakOnLogAfterTaskReturns) { Trace.Fail(String.Format(CultureInfo.CurrentUICulture, "Task at {0}, after already returning, attempted to log telemetry event '{1}'", _taskLocation.ToString(), eventName)); } return; } _taskLoggingContext.LoggingService.LogTelemetry(_taskLoggingContext.BuildEventContext, eventName, properties); } } #endregion #region IBuildEngine6 Members /// <summary> /// Gets the global properties for the current project. /// </summary> /// <returns>An <see cref="IReadOnlyDictionary{String, String}" /> containing the global properties of the current project.</returns> public IReadOnlyDictionary<string, string> GetGlobalProperties() { return _requestEntry.RequestConfiguration.GlobalProperties.ToDictionary(); } #endregion #region IBuildEngine7 Members /// <summary> /// Enables or disables emitting a default error when a task fails without logging errors /// </summary> public bool AllowFailureWithoutError { get; set; } = false; #endregion #region IBuildEngine8 Members private ICollection<string> _warningsAsErrors; /// <summary> /// Contains all warnings that should be logged as errors. /// Non-null empty set when all warnings should be treated as errors. /// </summary> private ICollection<string> WarningsAsErrors { get { // Test compatibility if (_taskLoggingContext == null) { return null; } return _warningsAsErrors ??= _taskLoggingContext.GetWarningsAsErrors(); } } private ICollection<string> _warningsNotAsErrors; /// <summary> /// Contains all warnings that should be logged as errors. /// Non-null empty set when all warnings should be treated as errors. /// </summary> private ICollection<string> WarningsNotAsErrors { get { // Test compatibility if (_taskLoggingContext == null) { return null; } return _warningsNotAsErrors ??= _taskLoggingContext.GetWarningsNotAsErrors(); } } private ICollection<string> _warningsAsMessages; /// <summary> /// Contains all warnings that should be logged as errors. /// Non-null empty set when all warnings should be treated as errors. /// </summary> private ICollection<string> WarningsAsMessages { get { // Test compatibility if (_taskLoggingContext == null) { return null; } return _warningsAsMessages ??= _taskLoggingContext.GetWarningsAsMessages(); } } /// <summary> /// Determines if the given warning should be treated as an error. /// </summary> /// <param name="warningCode"></param> /// <returns>True if the warning should not be treated as a message and WarningsAsErrors is an empty set or contains the given warning code.</returns> public bool ShouldTreatWarningAsError(string warningCode) { // Warnings as messages overrides warnings as errors. if (WarningsAsErrors == null || WarningsAsMessages?.Contains(warningCode) == true) { return false; } // An empty set means all warnings are errors. return (WarningsAsErrors.Count == 0 && WarningAsErrorNotOverriden(warningCode)) || WarningsAsErrors.Contains(warningCode); } private bool WarningAsErrorNotOverriden(string warningCode) { return WarningsNotAsErrors?.Contains(warningCode) != true; } #endregion #region IBuildEngine9 Members /// <summary> /// Additional cores granted to the task by the scheduler. Does not include the one implicit core automatically granted to all tasks. /// </summary> private int _additionalAcquiredCores = 0; /// <summary> /// True if the one implicit core has been allocated by <see cref="RequestCores"/>, false otherwise. /// </summary> private bool _isImplicitCoreUsed = false; /// <summary> /// Total number of cores granted to the task, including the one implicit core. /// </summary> private int TotalAcquiredCores => _additionalAcquiredCores + (_isImplicitCoreUsed ? 1 : 0); /// <summary> /// Allocates shared CPU resources. Called by a task when it's about to do potentially multi-threaded/multi-process work. /// </summary> /// <param name="requestedCores">The number of cores the task wants to use.</param> /// <returns>The number of cores the task is allowed to use given the current state of the build. This number is always between /// 1 and <paramref name="requestedCores"/>. If the task has allocated its one implicit core, this call may block, waiting for /// at least one core to become available.</returns> public int RequestCores(int requestedCores) { ErrorUtilities.VerifyThrowArgumentOutOfRange(requestedCores > 0, nameof(requestedCores)); lock (_callbackMonitor) { IRequestBuilderCallback builderCallback = _requestEntry.Builder as IRequestBuilderCallback; int coresAcquired = 0; bool allocatingImplicitCore = false; if (_isImplicitCoreUsed) { coresAcquired = builderCallback.RequestCores(_callbackMonitor, requestedCores, waitForCores: true); } else { _isImplicitCoreUsed = true; allocatingImplicitCore = true; if (requestedCores > 1) { coresAcquired = builderCallback.RequestCores(_callbackMonitor, requestedCores - 1, waitForCores: false); } } _additionalAcquiredCores += coresAcquired; if (allocatingImplicitCore) { // Pad the result with the one implicit core if it was still available. // This ensures that first call never blocks and always returns >= 1. coresAcquired++; } Debug.Assert(coresAcquired >= 1); if (LoggingContext.IsValid) { LoggingContext.LogComment(MessageImportance.Low, "TaskAcquiredCores", _taskLoggingContext.TaskName, requestedCores, coresAcquired, TotalAcquiredCores); } return coresAcquired; } } /// <summary> /// Frees shared CPU resources. Called by a task when it's finished doing multi-threaded/multi-process work. /// </summary> /// <param name="coresToRelease">The number of cores the task wants to return. This number must be between 0 and the number of cores /// granted and not yet released.</param> public void ReleaseCores(int coresToRelease) { ErrorUtilities.VerifyThrowArgumentOutOfRange(coresToRelease > 0, nameof(coresToRelease)); lock (_callbackMonitor) { int coresBeingReleased = coresToRelease; int previousTotalAcquiredCores = TotalAcquiredCores; if (_isImplicitCoreUsed && coresBeingReleased > _additionalAcquiredCores) { // Release the implicit core last, i.e. only if we're asked to release everything. coresBeingReleased -= 1; _isImplicitCoreUsed = false; } coresBeingReleased = Math.Min(coresBeingReleased, _additionalAcquiredCores); if (coresBeingReleased >= 1) { IRequestBuilderCallback builderCallback = _requestEntry.Builder as IRequestBuilderCallback; builderCallback.ReleaseCores(coresBeingReleased); _additionalAcquiredCores -= coresBeingReleased; } if (LoggingContext.IsValid) { if (TotalAcquiredCores == previousTotalAcquiredCores - coresToRelease) { LoggingContext.LogComment(MessageImportance.Low, "TaskReleasedCores", _taskLoggingContext.TaskName, coresToRelease, TotalAcquiredCores); } else { LoggingContext.LogComment(MessageImportance.Low, "TaskReleasedCoresWarning", _taskLoggingContext.TaskName, coresToRelease, previousTotalAcquiredCores, TotalAcquiredCores); } } } } /// <summary> /// Frees all CPU resources granted so far. /// </summary> internal void ReleaseAllCores() { int coresToRelease = TotalAcquiredCores; if (coresToRelease > 0) { ReleaseCores(coresToRelease); } } #endregion #region IBuildEngine10 Members [Serializable] private sealed class EngineServicesImpl : EngineServices { private readonly TaskHost _taskHost; internal EngineServicesImpl(TaskHost taskHost) { _taskHost = taskHost; } /// <inheritdoc/> public override bool LogsMessagesOfImportance(MessageImportance importance) { #if FEATURE_APPDOMAIN if (RemotingServices.IsTransparentProxy(_taskHost)) { // If the check would be a cross-domain call, chances are that it wouldn't be worth it. // Simply disable the optimization in such a case. return true; } #endif MessageImportance minimumImportance = _taskHost._taskLoggingContext?.LoggingService.MinimumRequiredMessageImportance ?? MessageImportance.Low; return importance <= minimumImportance; } /// <inheritdoc/> public override bool IsTaskInputLoggingEnabled => _taskHost._host.BuildParameters.LogTaskInputs; } public EngineServices EngineServices { get; } #endregion /// <summary> /// Called by the internal MSBuild task. /// Does not take the lock because it is called by another request builder thread. /// </summary> public async Task<BuildEngineResult> InternalBuildProjects(string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList<String>[] undefineProperties, string[] toolsVersion, bool returnTargetOutputs, bool skipNonexistentTargets = false) { ErrorUtilities.VerifyThrowArgumentNull(projectFileNames, nameof(projectFileNames)); ErrorUtilities.VerifyThrowArgumentNull(globalProperties, nameof(globalProperties)); VerifyActiveProxy(); BuildEngineResult result; if (projectFileNames.Length == 1 && projectFileNames[0] == null && globalProperties[0] == null && (undefineProperties == null || undefineProperties[0] == null) && toolsVersion[0] == null) { bool overallSuccess = true; List<IDictionary<string, ITaskItem[]>> targetOutputsPerProject = null; // This is really a legacy CallTarget invocation ITargetResult[] results = await _targetBuilderCallback.LegacyCallTarget(targetNames, ContinueOnError, _taskLocation); if (returnTargetOutputs) { targetOutputsPerProject = new List<IDictionary<string, ITaskItem[]>>(1); targetOutputsPerProject.Add(new Dictionary<string, ITaskItem[]>(StringComparer.OrdinalIgnoreCase)); } for (int i = 0; i < targetNames.Length; i++) { targetOutputsPerProject[0][targetNames[i]] = results[i].Items; if (results[i].ResultCode == TargetResultCode.Failure) { overallSuccess = false; } } result = new BuildEngineResult(overallSuccess, targetOutputsPerProject); BuildRequestsSucceeded = overallSuccess; } else { // Post the request, then yield up the thread. result = await BuildProjectFilesInParallelAsync(projectFileNames, targetNames, globalProperties, undefineProperties, toolsVersion, true /* ask that target outputs are returned in the buildengineresult */, skipNonexistentTargets); } return result; } #if FEATURE_APPDOMAIN /// <inheritdoc /> /// <summary> /// InitializeLifetimeService is called when the remote object is activated. /// This method will determine how long the lifetime for the object will be. /// </summary> /// <returns>The lease object to control this object's lifetime.</returns> public override object InitializeLifetimeService() { lock (_callbackMonitor) { VerifyActiveProxy(); // Each MarshalByRef object has a reference to the service which // controls how long the remote object will stay around ILease lease = (ILease)base.InitializeLifetimeService(); // Set how long a lease should be initially. Once a lease expires // the remote object will be disconnected and it will be marked as being availiable // for garbage collection int initialLeaseTime = 1; string initialLeaseTimeFromEnvironment = Environment.GetEnvironmentVariable("MSBUILDENGINEPROXYINITIALLEASETIME"); if (!String.IsNullOrEmpty(initialLeaseTimeFromEnvironment)) { int leaseTimeFromEnvironment; if (int.TryParse(initialLeaseTimeFromEnvironment, out leaseTimeFromEnvironment) && leaseTimeFromEnvironment > 0) { initialLeaseTime = leaseTimeFromEnvironment; } } lease.InitialLeaseTime = TimeSpan.FromMinutes(initialLeaseTime); // Make a new client sponsor. A client sponsor is a class // which will respond to a lease renewal request and will // increase the lease time allowing the object to stay in memory _sponsor = new ClientSponsor(); // When a new lease is requested lets make it last 1 minutes longer. int leaseExtensionTime = 1; string leaseExtensionTimeFromEnvironment = Environment.GetEnvironmentVariable("MSBUILDENGINEPROXYLEASEEXTENSIONTIME"); if (!String.IsNullOrEmpty(leaseExtensionTimeFromEnvironment)) { int leaseExtensionFromEnvironment; if (int.TryParse(leaseExtensionTimeFromEnvironment, out leaseExtensionFromEnvironment) && leaseExtensionFromEnvironment > 0) { leaseExtensionTime = leaseExtensionFromEnvironment; } } _sponsor.RenewalTime = TimeSpan.FromMinutes(leaseExtensionTime); // Register the sponsor which will increase lease timeouts when the lease expires lease.Register(_sponsor); return lease; } } #endif /// <summary> /// Indicates to the TaskHost that it is no longer needed. /// Called by TaskBuilder when the task using the EngineProxy is done. /// </summary> internal void MarkAsInactive() { lock (_callbackMonitor) { VerifyActiveProxy(); _activeProxy = false; ReleaseAllCores(); // Since the task has a pointer to this class it may store it in a static field. Null out // internal data so the leak of this object doesn't lead to a major memory leak. _host = null; _requestEntry = null; // Don't bother clearing the tiny task location _taskLoggingContext = null; _targetBuilderCallback = null; #if FEATURE_APPDOMAIN // Clear out the sponsor (who is responsible for keeping the EngineProxy remoting lease alive until the task is done) // this will be null if the engine proxy was never sent across an AppDomain boundary. if (_sponsor != null) { ILease lease = (ILease)RemotingServices.GetLifetimeService(this); lease?.Unregister(_sponsor); _sponsor.Close(); _sponsor = null; } #endif } } /// <summary> /// Determine if the event is serializable. If we are running with multiple nodes we need to make sure the logging events are serializable. If not /// we need to log a warning. /// </summary> internal bool IsEventSerializable(BuildEventArgs e) { if (!e.GetType().GetTypeInfo().IsSerializable) { _taskLoggingContext.LogWarning(null, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name); return false; } return true; } /// <summary> /// Async version of BuildProjectFilesInParallel. /// </summary> /// <param name="projectFileNames">The list of projects to build</param> /// <param name="targetNames">The set of targets to build</param> /// <param name="globalProperties">The global properties to use for each project</param> /// <param name="undefineProperties">The list of global properties to undefine</param> /// <param name="toolsVersion">The tools versions to use</param> /// <param name="returnTargetOutputs">Should the target outputs be returned in the BuildEngineResult</param> /// <param name="skipNonexistentTargets">If set, skip targets that are not defined in the projects to be built.</param> /// <returns>A Task returning a structure containing the result of the build, success or failure and the list of target outputs per project</returns> private async Task<BuildEngineResult> BuildProjectFilesInParallelAsync(string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList<String>[] undefineProperties, string[] toolsVersion, bool returnTargetOutputs, bool skipNonexistentTargets = false) { ErrorUtilities.VerifyThrowArgumentNull(projectFileNames, nameof(projectFileNames)); ErrorUtilities.VerifyThrowArgumentNull(globalProperties, nameof(globalProperties)); VerifyActiveProxy(); List<IDictionary<string, ITaskItem[]>> targetOutputsPerProject = null; #if FEATURE_FILE_TRACKER using (FullTracking.Suspend()) #endif { bool overallSuccess = true; if (projectFileNames.Length == 1 && projectFileNames[0] == null && globalProperties[0] == null && (undefineProperties == null || undefineProperties[0] == null) && toolsVersion[0] == null) { // This is really a legacy CallTarget invocation ITargetResult[] results = await _targetBuilderCallback.LegacyCallTarget(targetNames, ContinueOnError, _taskLocation); if (returnTargetOutputs) { targetOutputsPerProject = new List<IDictionary<string, ITaskItem[]>>(1) { new Dictionary<string, ITaskItem[]>(StringComparer.OrdinalIgnoreCase) }; } for (int i = 0; i < targetNames.Length; i++) { targetOutputsPerProject[0][targetNames[i]] = results[i].Items; if (results[i].ResultCode == TargetResultCode.Failure) { overallSuccess = false; } } } else { // UNDONE: (Refactor) Investigate making this a ReadOnly collection of some sort. PropertyDictionary<ProjectPropertyInstance>[] propertyDictionaries = new PropertyDictionary<ProjectPropertyInstance>[projectFileNames.Length]; for (int i = 0; i < projectFileNames.Length; i++) { // Copy in the original project's global properties propertyDictionaries[i] = new PropertyDictionary<ProjectPropertyInstance>(_requestEntry.RequestConfiguration.Project.GlobalPropertiesDictionary); // Now add/replace any which may have been specified. if (globalProperties[i] != null) { foreach (DictionaryEntry entry in globalProperties[i]) { propertyDictionaries[i].Set(ProjectPropertyInstance.Create(entry.Key as string, entry.Value as string, _taskLocation)); } } // Finally, remove any which were requested to be removed. if (undefineProperties?[i] != null) { foreach (string property in undefineProperties[i]) { propertyDictionaries[i].Remove(property); } } } IRequestBuilderCallback builderCallback = _requestEntry.Builder as IRequestBuilderCallback; BuildResult[] results = await builderCallback.BuildProjects( projectFileNames, propertyDictionaries, toolsVersion ?? Array.Empty<string>(), targetNames ?? Array.Empty<string>(), waitForResults: true, skipNonexistentTargets: skipNonexistentTargets); // Even if one of the projects fails to build and therefore has no outputs, it should still have an entry in the results array (albeit with an empty list in it) ErrorUtilities.VerifyThrow(results.Length == projectFileNames.Length, "{0}!={1}.", results.Length, projectFileNames.Length); if (returnTargetOutputs) { targetOutputsPerProject = new List<IDictionary<string, ITaskItem[]>>(results.Length); } // Now walk through the results, and report that subset which was asked for. for (int i = 0; i < results.Length; i++) { targetOutputsPerProject?.Add(new Dictionary<string, ITaskItem[]>(StringComparer.OrdinalIgnoreCase)); foreach (KeyValuePair<string, TargetResult> resultEntry in results[i].ResultsByTarget) { if (targetOutputsPerProject != null) { // We need to clone the task items because if we did not then we would be passing live references // out to the caller of the msbuild callback and any modifications they make to those items // would appear in the results cache. ITaskItem[] clonedTaskItem = new ITaskItem[resultEntry.Value.Items.Length]; for (int j = 0; j < resultEntry.Value.Items.Length; j++) { clonedTaskItem[j] = ((TaskItem)resultEntry.Value.Items[j]).DeepClone(); } targetOutputsPerProject[i][resultEntry.Key] = clonedTaskItem; } } if (results[i].OverallResult == BuildResultCode.Failure) { overallSuccess = false; } if (!string.IsNullOrEmpty(results[i].SchedulerInducedError)) { LoggingContext.LogErrorFromText( subcategoryResourceName: null, errorCode: null, helpKeyword: null, file: new BuildEventFileInfo(ProjectFileOfTaskNode, LineNumberOfTaskNode, ColumnNumberOfTaskNode), message: results[i].SchedulerInducedError); } } ErrorUtilities.VerifyThrow(results.Length == projectFileNames.Length || !overallSuccess, "The number of results returned {0} cannot be less than the number of project files {1} unless one of the results indicated failure.", results.Length, projectFileNames.Length); } BuildRequestsSucceeded = overallSuccess; return new BuildEngineResult(overallSuccess, targetOutputsPerProject); } } /// <summary> /// Verify the task host is active or not /// Thread safe. /// </summary> private void VerifyActiveProxy() { ErrorUtilities.VerifyThrow(_activeProxy, "Attempted to use an inactive task host."); } } }
44.714856
295
0.58207
[ "MIT" ]
AlexanderSemenyak/msbuild
src/Build/BackEnd/Components/RequestBuilder/TaskHost.cs
55,985
C#
$MethodsForEachComponent #region ServiceComponent code for ##ServiceName## public bool Test##ServiceName##() { try { ServiceComponent component = new ServiceComponent(); ##DataEntity## dataEntity = Build##DataEntity##(); dataEntity = component.Execute##ServiceName##(dataEntity); bool isValid = Validate##DataEntity##(dataEntity); return isValid; } catch(Exception exc) { return false; } } ##DataEntity## Build##DataEntity##() { ##DataEntity## dataEntity= new ##DataEntity##(); /// The developer should build the data Entity here. return dataEntity; } bool Validate##DataEntity##(##DataEntity## dataEntity) { try { bool isValid = false; /// The developer should build the data Entity here. return isValid; } catch(Exception exc) { return false; } } #endregion ServiceComponent code for ##ServiceName## $NameSpaceOfEachDataEntity using ##DataEntityNameSpace##.##DataEntity##; $end using System; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using LifGenerated.ServiceComponents; ##NameSpaceOfDataEntities## namespace LifGenerated.ServiceComponents.TestCases { /// <summary> /// Summary description for WebService /// </summary> public partial class TestCases { public TestCases() { } ##GeneratedCodeForAllComponents## } }
25.014286
74
0.558538
[ "Apache-2.0" ]
Infosys/Intelligent-Bot-Management-
Data Integration Framework/ParserGen/ParserGenerator UI/Templates/UnitTestCases/UnitTestCase.cs
1,751
C#
using SharpReact.Core; using SharpReact.Core.Properties; using System.Collections.Generic; namespace SharpReact.Android.Props { public partial class ViewSwitcher: ViewAnimator { protected override ISharpStatefulComponent CreateComponent() { return new Components.ViewSwitcher<ViewSwitcher, global::Android.Widget.ViewSwitcher>(); } } }
23.266667
91
0.799427
[ "MIT" ]
MihaMarkic/SharpReact
src/Implementations/Android/SharpReact.Android.8_1/Props/ViewSwitcher.cs
349
C#
namespace Parquet.Data { /// <summary> /// List of supported data types /// </summary> public enum DataType { /// <summary> /// Type is not specified, shouldn't be used. /// </summary> Unspecified, /// <summary> /// Boolean /// </summary> Boolean, /// <summary> /// Byte /// </summary> Byte, /// <summary> /// Signed byte data type /// </summary> SignedByte, /// <summary> /// Unsigned byte /// </summary> UnsignedByte, /// <summary> /// Short /// </summary> Short, /// <summary> /// Unsigned short /// </summary> UnsignedShort, /// <summary> /// 16 bit integer /// </summary> Int16, /// <summary> /// 16 bit unsigned integer /// </summary> UnsignedInt16, /// <summary> /// 32 bit integer /// </summary> Int32, /// <summary> /// 32 bit unsigned integer /// </summary> UnsignedInt32, /// <summary> /// 64 bit integer /// </summary> Int64, /// <summary> /// 64 bit unsigned integer /// </summary> UnsignedInt64, /// <summary> /// 96 bit integer /// </summary> Int96, /// <summary> /// Array of bytes /// </summary> ByteArray, /// <summary> /// UTF-8 string /// </summary> String, /// <summary> /// Float /// </summary> Float, /// <summary> /// Double /// </summary> Double, /// <summary> /// Decimal /// </summary> Decimal, /// <summary> /// DateTimeOffset /// </summary> DateTimeOffset, /// <summary> /// Interval /// </summary> Interval, /// <summary> /// TimeSpan /// </summary> TimeSpan, } }
16.487395
51
0.426606
[ "MIT" ]
DBojsen/parquet-dotnet
src/Parquet/Data/DataType.cs
1,964
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MHRTalismanManager.Shared; using MoreLinq; namespace MHRTalismanManager.Client.Shared { public static class MhRiseWikiDbSerializer { private const byte SlotDataSignal = 26; private const byte SeparatorSignal = 10; private const byte TextPointSeparatorSignal = 16; private const byte Slot1Signal = 8; private const byte Slot2Signal = 16; private const byte Slot3Signal = 24; private const byte NoSlotsSignal = 0; public static string Serialize(IEnumerable<Talisman> talismans) { var byteData = talismans.SelectMany(SerializeTalisman) .ToArray(); return Convert.ToBase64String(byteData); } private static List<byte> SerializeTalisman(Talisman talisman) { var result = new List<byte>(); if (talisman.Slot3 != SlotType.None) { result.Add((byte)talisman.Slot3); result.Add(Slot3Signal); } if (talisman.Slot2 != SlotType.None) { result.Add((byte)talisman.Slot2); result.Add(Slot2Signal); } if (talisman.Slot1 != SlotType.None) { result.Add((byte)talisman.Slot1); result.Add(Slot1Signal); } if (talisman.Slot1 == SlotType.None && talisman.Slot2 == SlotType.None && talisman.Slot3 == SlotType.None) result.Add(NoSlotsSignal); else result.Add((byte)result.Count); result.Add(SlotDataSignal); if (talisman.Skill2.Points != null) result.AddRange(SerializeSkill(talisman.Skill2)); result.AddRange(SerializeSkill(talisman.Skill1)); result.Add((byte)result.Count); result.Add(SeparatorSignal); result.Reverse(); return result; } private static IEnumerable<byte> SerializeSkill(TalismanSkill skill) { var result = new List<byte>(); result.Add((byte)skill.Points); result.Add(TextPointSeparatorSignal); result.AddRange(skill.Name.Select(c => (byte)c) .Reverse()); result.Add((byte)skill.Name.Length); result.Add(SeparatorSignal); result.Add((byte)result.Count); result.Add(SeparatorSignal); return result; } public static IEnumerable<TalismanDto> Deserialize(string dataString) { var data = new Queue<byte>(Convert.FromBase64String(dataString)); var talismans = SplitIntoTalismanData(data) .Select(DeserializeTalismanData) .ToList(); return talismans; } private static TalismanDto DeserializeTalismanData(Queue<byte> data) { var result = new TalismanDto { Operation = TalismanOperation.Add }; var (text1, points1) = DeserializeSkill(data); result.Skill1 = new TalismanSkill { Name = text1, Points = points1 }; if (data.Peek() != SlotDataSignal) { var (text2, points2) = DeserializeSkill(data); result.Skill2 = new TalismanSkill { Name = text2, Points = points2 }; } var (slot1, slot2, slot3) = DeserializeSlots(data); result.Slot1 = slot1; result.Slot2 = slot2; result.Slot3 = slot3; return result; } private static (SlotType slot1, SlotType slot2, SlotType slot3) DeserializeSlots(Queue<byte> data) { if (data.Dequeue() != SlotDataSignal) throw new Exception("error in data"); var slotDataLength = data.Dequeue(); var slots = Enumerable.Repeat(0, slotDataLength) .Select(_ => data.Dequeue()) .Where(x => x is > 0 and <= 3) .Select(x => (SlotType)x) .Pad(3, SlotType.None) .ToList(); return (slots[0], slots[1], slots[2]); } private static (string text, byte points) DeserializeSkill(Queue<byte> data) { if (data.Dequeue() != SeparatorSignal) throw new Exception("error in data"); var skillLength = data.Dequeue(); if (data.Dequeue() != SeparatorSignal) throw new Exception("error in data"); var textLength = data.Dequeue(); if (textLength != skillLength - 4) throw new Exception("error in data"); var text = Encoding.ASCII.GetString(Enumerable.Range(0, textLength) .Select(_ => data.Dequeue()) .ToArray()); if (data.Dequeue() != TextPointSeparatorSignal) throw new Exception("error in data"); var points = data.Dequeue(); return (text, points); } private static IEnumerable<Queue<byte>> SplitIntoTalismanData(Queue<byte> data) { var result = new List<Queue<byte>>(); while (data.Count > 0) { if (data.Dequeue() != SeparatorSignal) throw new Exception("error in data"); var dataLength = data.Dequeue(); var talisman = new Queue<byte>(Enumerable.Range(0, dataLength) .Select(_ => data.Dequeue()) .ToList()); result.Add(talisman); } return result; } } }
33.364641
118
0.516642
[ "MIT" ]
Sephiroth018/MHRTalismanManager
MHRTalismanManager/Client/Shared/MhRiseWikiDbSerializer.cs
6,041
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Azure.Storage.Blobs.Models { /// <summary> /// Specifies options for listing blob containers with the /// <see cref="BlobServiceClient.GetBlobContainersAsync"/> operation. /// </summary> // this can also be an enum just for parity with getblobsoptions public struct GetBlobContainersOptions : IEquatable<GetBlobContainersOptions> { /// <summary> /// Gets or sets a string that filters the results to return only /// blob containers whose name begins with the specified prefix. /// </summary> public string Prefix { get; set; } /// <summary> /// Gets or sets a flag specifing that the container's metadata should /// be included. /// </summary> public bool IncludeMetadata { get; set; } /// <summary> /// Convert the details into a ListBlobContainersIncludeType value. /// </summary> /// <returns>A ListBlobContainersIncludeType value.</returns> internal ListBlobContainersIncludeType? AsIncludeType() => IncludeMetadata ? ListBlobContainersIncludeType.Metadata : (ListBlobContainersIncludeType?)null; /// <summary> /// Check if two GetBlobContainersOptions instances are equal. /// </summary> /// <param name="obj">The instance to compare to.</param> /// <returns>True if they're equal, false otherwise.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is GetBlobContainersOptions other && Equals(other); /// <summary> /// Get a hash code for the GetBlobContainersOptions. /// </summary> /// <returns>Hash code for the GetBlobContainersOptions.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => IncludeMetadata.GetHashCode() ^ Prefix.GetHashCode(); /// <summary> /// Check if two GetBlobContainersOptions instances are equal. /// </summary> /// <param name="left">The first instance to compare.</param> /// <param name="right">The second instance to compare.</param> /// <returns>True if they're equal, false otherwise.</returns> public static bool operator ==(GetBlobContainersOptions left, GetBlobContainersOptions right) => left.Equals(right); /// <summary> /// Check if two GetBlobContainersOptions instances are not equal. /// </summary> /// <param name="left">The first instance to compare.</param> /// <param name="right">The second instance to compare.</param> /// <returns>True if they're not equal, false otherwise.</returns> public static bool operator !=(GetBlobContainersOptions left, GetBlobContainersOptions right) => !(left == right); /// <summary> /// Check if two GetBlobContainersOptions instances are equal. /// </summary> /// <param name="other">The instance to compare to.</param> /// <returns>True if they're equal, false otherwise.</returns> public bool Equals(GetBlobContainersOptions other) => IncludeMetadata == other.IncludeMetadata && Prefix == other.Prefix; } }
40.534091
104
0.634427
[ "MIT" ]
SanjayHukumRana/azure-sdk-for-net
sdk/storage/Azure.Storage.Blobs/src/Models/GetBlobContainersOptions.cs
3,569
C#
namespace KeyPay.DomainModels.V2.PayRun { public class SubmitDeductionModel { public string ExternalId { get; set; } public string LocationId { get; set; } public string LocationName { get; set; } public string EmployeeId { get; set; } public string EmployeeName { get; set; } public string DeductionCategoryId { get; set; } public string DeductionCategoryName { get; set; } public decimal Amount { get; set; } public string Notes { get; set; } public string PayToBankAccountBSB { get; set; } public string PayToBankAccountNumber { get; set; } public string PayToSuperFundName { get; set; } public string PayToSuperFundMemberNumber { get; set; } public string PayTo { get; set; } } }
40.35
62
0.636927
[ "MIT" ]
KeyPay/keypay-dotnet
src/keypay-dotnet/DomainModels/V2/PayRun/SubmitDeductionModel.cs
807
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CSGOMusicController.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CSGOMusicController.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.819444
185
0.605367
[ "MIT" ]
DiNitride/CSGOAutoMusicVolume
CSGOMusicController/Properties/Resources.Designer.cs
2,797
C#
/* * Payment Gateway API Specification. * * The documentation here is designed to provide all of the technical guidance required to consume and integrate with our APIs for payment processing. To learn more about our APIs please visit https://docs.firstdata.com/org/gateway. * * The version of the OpenAPI document: 21.2.0.20210406.001 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// DecryptedApplePayWalletPaymentMethodAllOf /// </summary> [DataContract] public partial class DecryptedApplePayWalletPaymentMethodAllOf : IEquatable<DecryptedApplePayWalletPaymentMethodAllOf>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DecryptedApplePayWalletPaymentMethodAllOf" /> class. /// </summary> [JsonConstructorAttribute] protected DecryptedApplePayWalletPaymentMethodAllOf() { } /// <summary> /// Initializes a new instance of the <see cref="DecryptedApplePayWalletPaymentMethodAllOf" /> class. /// </summary> /// <param name="decryptedApplePay">decryptedApplePay (required).</param> public DecryptedApplePayWalletPaymentMethodAllOf(DecryptedApplePay decryptedApplePay = default(DecryptedApplePay)) { // to ensure "decryptedApplePay" is required (not null) this.DecryptedApplePay = decryptedApplePay ?? throw new ArgumentNullException("decryptedApplePay is a required property for DecryptedApplePayWalletPaymentMethodAllOf and cannot be null"); } /// <summary> /// Gets or Sets DecryptedApplePay /// </summary> [DataMember(Name = "decryptedApplePay", EmitDefaultValue = false)] public DecryptedApplePay DecryptedApplePay { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DecryptedApplePayWalletPaymentMethodAllOf {\n"); sb.Append(" DecryptedApplePay: ").Append(DecryptedApplePay).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DecryptedApplePayWalletPaymentMethodAllOf); } /// <summary> /// Returns true if DecryptedApplePayWalletPaymentMethodAllOf instances are equal /// </summary> /// <param name="input">Instance of DecryptedApplePayWalletPaymentMethodAllOf to be compared</param> /// <returns>Boolean</returns> public bool Equals(DecryptedApplePayWalletPaymentMethodAllOf input) { if (input == null) return false; return ( this.DecryptedApplePay == input.DecryptedApplePay || (this.DecryptedApplePay != null && this.DecryptedApplePay.Equals(input.DecryptedApplePay)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.DecryptedApplePay != null) hashCode = hashCode * 59 + this.DecryptedApplePay.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
38.244275
232
0.638523
[ "MIT" ]
D4mo/DotNet
src/Org.OpenAPITools/Model/DecryptedApplePayWalletPaymentMethodAllOf.cs
5,010
C#
using System.IO.Abstractions; using System.Text.RegularExpressions; using UnityEngine; using System.IO; namespace MLAgents { /// <summary> /// Demonstration Recorder Component. /// </summary> [RequireComponent(typeof(Agent))] [AddComponentMenu("ML Agents/Demonstration Recorder", (int)MenuGroup.Default)] public class DemonstrationRecorder : MonoBehaviour { [Tooltip("Whether or not to record demonstrations.")] public bool record; [Tooltip("Base demonstration file name. Will have numbers appended to make unique.")] public string demonstrationName; [Tooltip("Base directory to write the demo files. If null, will use {Application.dataPath}/Demonstrations.")] public string demonstrationDirectory; DemonstrationStore m_DemoStore; internal const int MaxNameLength = 16; const string k_ExtensionType = ".demo"; IFileSystem m_FileSystem; Agent m_Agent; void OnEnable() { m_Agent = GetComponent<Agent>(); } void Update() { if (record) { LazyInitialize(); } } /// <summary> /// Creates demonstration store for use in recording. /// Has no effect if the demonstration store was already created. /// </summary> internal DemonstrationStore LazyInitialize(IFileSystem fileSystem = null) { if (m_DemoStore != null) { return m_DemoStore; } if (m_Agent == null) { m_Agent = GetComponent<Agent>(); } m_FileSystem = fileSystem ?? new FileSystem(); var behaviorParams = GetComponent<BehaviorParameters>(); if (string.IsNullOrEmpty(demonstrationName)) { demonstrationName = behaviorParams.behaviorName; } if (string.IsNullOrEmpty(demonstrationDirectory)) { demonstrationDirectory = Path.Combine(Application.dataPath, "Demonstrations"); } demonstrationName = SanitizeName(demonstrationName, MaxNameLength); var filePath = MakeDemonstrationFilePath(m_FileSystem, demonstrationDirectory, demonstrationName); var stream = m_FileSystem.File.Create(filePath); m_DemoStore = new DemonstrationStore(stream); m_DemoStore.Initialize( demonstrationName, behaviorParams.brainParameters, behaviorParams.fullyQualifiedBehaviorName ); AddDemonstrationStoreToAgent(m_DemoStore); return m_DemoStore; } /// <summary> /// Removes all characters except alphanumerics from demonstration name. /// Shorten name if it is longer than the maxNameLength. /// </summary> internal static string SanitizeName(string demoName, int maxNameLength) { var rgx = new Regex("[^a-zA-Z0-9 -]"); demoName = rgx.Replace(demoName, ""); // If the string is too long, it will overflow the metadata. if (demoName.Length > maxNameLength) { demoName = demoName.Substring(0, maxNameLength); } return demoName; } /// <summary> /// Gets a unique path for the demonstrationName in the demonstrationDirectory. /// </summary> /// <param name="fileSystem"></param> /// <param name="demonstrationDirectory"></param> /// <param name="demonstrationName"></param> /// <returns></returns> internal static string MakeDemonstrationFilePath( IFileSystem fileSystem, string demonstrationDirectory, string demonstrationName ) { // Create the directory if it doesn't already exist if (!fileSystem.Directory.Exists(demonstrationDirectory)) { fileSystem.Directory.CreateDirectory(demonstrationDirectory); } var literalName = demonstrationName; var filePath = Path.Combine(demonstrationDirectory, literalName + k_ExtensionType); var uniqueNameCounter = 0; while (fileSystem.File.Exists(filePath)) { // TODO should we use a timestamp instead of a counter here? This loops an increasing number of times // as the number of demos increases. literalName = demonstrationName + "_" + uniqueNameCounter; filePath = Path.Combine(demonstrationDirectory, literalName + k_ExtensionType); uniqueNameCounter++; } return filePath; } /// <summary> /// Close the DemonstrationStore and remove it from the Agent. /// Has no effect if the DemonstrationStore is already closed (or wasn't opened) /// </summary> public void Close() { if (m_DemoStore != null) { RemoveDemonstrationStoreFromAgent(m_DemoStore); m_DemoStore.Close(); m_DemoStore = null; } } /// <summary> /// Clean up the DemonstrationStore when shutting down or destroying the Agent. /// </summary> void OnDestroy() { Close(); } /// <summary> /// Add additional DemonstrationStore to the Agent. It is still up to the user to Close this /// DemonstrationStores when recording is done. /// </summary> /// <param name="demoStore"></param> public void AddDemonstrationStoreToAgent(DemonstrationStore demoStore) { m_Agent.DemonstrationStores.Add(demoStore); } /// <summary> /// Remove additional DemonstrationStore to the Agent. It is still up to the user to Close this /// DemonstrationStores when recording is done. /// </summary> /// <param name="demoStore"></param> public void RemoveDemonstrationStoreFromAgent(DemonstrationStore demoStore) { m_Agent.DemonstrationStores.Remove(demoStore); } } }
34.9
117
0.58787
[ "Apache-2.0" ]
fd4124983399/ml-agents
com.unity.ml-agents/Runtime/DemonstrationRecorder.cs
6,282
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Diagnostics; using System.Collections.Generic; namespace Microsoft.Xml { using System; internal partial class XmlWellFormedWriter : XmlWriter { // // Private types // private class NamespaceResolverProxy : IXmlNamespaceResolver { private XmlWellFormedWriter _wfWriter; internal NamespaceResolverProxy(XmlWellFormedWriter wfWriter) { _wfWriter = wfWriter; } IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { throw new NotImplementedException(); } string IXmlNamespaceResolver.LookupNamespace(string prefix) { return _wfWriter.LookupNamespace(prefix); } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return _wfWriter.LookupPrefix(namespaceName); } } private partial struct ElementScope { internal int prevNSTop; internal string prefix; internal string localName; internal string namespaceUri; internal XmlSpace xmlSpace; internal string xmlLang; internal void Set(string prefix, string localName, string namespaceUri, int prevNSTop) { this.prevNSTop = prevNSTop; this.prefix = prefix; this.namespaceUri = namespaceUri; this.localName = localName; this.xmlSpace = (Microsoft.Xml.XmlSpace)(int)-1; this.xmlLang = null; } internal void WriteEndElement(XmlRawWriter rawWriter) { rawWriter.WriteEndElement(prefix, localName, namespaceUri); } internal void WriteFullEndElement(XmlRawWriter rawWriter) { rawWriter.WriteFullEndElement(prefix, localName, namespaceUri); } } private enum NamespaceKind { Written, NeedToWrite, Implied, Special, } private partial struct Namespace { internal string prefix; internal string namespaceUri; internal NamespaceKind kind; internal int prevNsIndex; internal void Set(string prefix, string namespaceUri, NamespaceKind kind) { this.prefix = prefix; this.namespaceUri = namespaceUri; this.kind = kind; this.prevNsIndex = -1; } internal void WriteDecl(XmlWriter writer, XmlRawWriter rawWriter) { Debug.Assert(kind == NamespaceKind.NeedToWrite); if (null != rawWriter) { rawWriter.WriteNamespaceDeclaration(prefix, namespaceUri); } else { if (prefix.Length == 0) { writer.WriteStartAttribute(string.Empty, "xmlns", XmlReservedNs.NsXmlNs); } else { writer.WriteStartAttribute("xmlns", prefix, XmlReservedNs.NsXmlNs); } writer.WriteString(namespaceUri); writer.WriteEndAttribute(); } } } private struct AttrName { internal string prefix; internal string namespaceUri; internal string localName; internal int prev; internal void Set(string prefix, string localName, string namespaceUri) { this.prefix = prefix; this.namespaceUri = namespaceUri; this.localName = localName; this.prev = 0; } internal bool IsDuplicate(string prefix, string localName, string namespaceUri) { return ((this.localName == localName) && ((this.prefix == prefix) || (this.namespaceUri == namespaceUri))); } } private enum SpecialAttribute { No = 0, DefaultXmlns, PrefixedXmlns, XmlSpace, XmlLang } private partial class AttributeValueCache { private enum ItemType { EntityRef, CharEntity, SurrogateCharEntity, Whitespace, String, StringChars, Raw, RawChars, ValueString, } private class Item { internal ItemType type; internal object data; internal Item() { } internal void Set(ItemType type, object data) { this.type = type; this.data = data; } } private class BufferChunk { internal char[] buffer; internal int index; internal int count; internal BufferChunk(char[] buffer, int index, int count) { this.buffer = buffer; this.index = index; this.count = count; } } private StringBuilder _stringValue = new StringBuilder(); private string _singleStringValue; // special-case for a single WriteString call private Item[] _items; private int _firstItem; private int _lastItem = -1; internal string StringValue { get { if (_singleStringValue != null) { return _singleStringValue; } else { return _stringValue.ToString(); } } } internal void WriteEntityRef(string name) { if (_singleStringValue != null) { StartComplexValue(); } switch (name) { case "lt": _stringValue.Append('<'); break; case "gt": _stringValue.Append('>'); break; case "quot": _stringValue.Append('"'); break; case "apos": _stringValue.Append('\''); break; case "amp": _stringValue.Append('&'); break; default: _stringValue.Append('&'); _stringValue.Append(name); _stringValue.Append(';'); break; } AddItem(ItemType.EntityRef, name); } internal void WriteCharEntity(char ch) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(ch); AddItem(ItemType.CharEntity, ch); } internal void WriteSurrogateCharEntity(char lowChar, char highChar) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(highChar); _stringValue.Append(lowChar); AddItem(ItemType.SurrogateCharEntity, new char[] { lowChar, highChar }); } internal void WriteWhitespace(string ws) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(ws); AddItem(ItemType.Whitespace, ws); } internal void WriteString(string text) { if (_singleStringValue != null) { StartComplexValue(); } else { // special-case for a single WriteString if (_lastItem == -1) { _singleStringValue = text; return; } } _stringValue.Append(text); AddItem(ItemType.String, text); } internal void WriteChars(char[] buffer, int index, int count) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(buffer, index, count); AddItem(ItemType.StringChars, new BufferChunk(buffer, index, count)); } internal void WriteRaw(char[] buffer, int index, int count) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(buffer, index, count); AddItem(ItemType.RawChars, new BufferChunk(buffer, index, count)); } internal void WriteRaw(string data) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(data); AddItem(ItemType.Raw, data); } internal void WriteValue(string value) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(value); AddItem(ItemType.ValueString, value); } internal void Replay(XmlWriter writer) { if (_singleStringValue != null) { writer.WriteString(_singleStringValue); return; } BufferChunk bufChunk; for (int i = _firstItem; i <= _lastItem; i++) { Item item = _items[i]; switch (item.type) { case ItemType.EntityRef: writer.WriteEntityRef((string)item.data); break; case ItemType.CharEntity: writer.WriteCharEntity((char)item.data); break; case ItemType.SurrogateCharEntity: char[] chars = (char[])item.data; writer.WriteSurrogateCharEntity(chars[0], chars[1]); break; case ItemType.Whitespace: writer.WriteWhitespace((string)item.data); break; case ItemType.String: writer.WriteString((string)item.data); break; case ItemType.StringChars: bufChunk = (BufferChunk)item.data; writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count); break; case ItemType.Raw: writer.WriteRaw((string)item.data); break; case ItemType.RawChars: bufChunk = (BufferChunk)item.data; writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count); break; case ItemType.ValueString: writer.WriteValue((string)item.data); break; default: Debug.Assert(false, "Unexpected ItemType value."); break; } } } // This method trims whitespaces from the beginnig and the end of the string and cached writer events internal void Trim() { // if only one string value -> trim the write spaces directly if (_singleStringValue != null) { _singleStringValue = XmlConvert.TrimString(_singleStringValue); return; } // trim the string in StringBuilder string valBefore = _stringValue.ToString(); string valAfter = XmlConvert.TrimString(valBefore); if (valBefore != valAfter) { _stringValue = new StringBuilder(valAfter); } // trim the beginning of the recorded writer events XmlCharType xmlCharType = XmlCharType.Instance; int i = _firstItem; while (i == _firstItem && i <= _lastItem) { Item item = _items[i]; switch (item.type) { case ItemType.Whitespace: _firstItem++; break; case ItemType.String: case ItemType.Raw: case ItemType.ValueString: item.data = XmlConvert.TrimStringStart((string)item.data); if (((string)item.data).Length == 0) { // no characters left -> move the firstItem index to exclude it from the Replay _firstItem++; } break; case ItemType.StringChars: case ItemType.RawChars: BufferChunk bufChunk = (BufferChunk)item.data; int endIndex = bufChunk.index + bufChunk.count; while (bufChunk.index < endIndex && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index])) { bufChunk.index++; bufChunk.count--; } if (bufChunk.index == endIndex) { // no characters left -> move the firstItem index to exclude it from the Replay _firstItem++; } break; } i++; } // trim the end of the recorded writer events i = _lastItem; while (i == _lastItem && i >= _firstItem) { Item item = _items[i]; switch (item.type) { case ItemType.Whitespace: _lastItem--; break; case ItemType.String: case ItemType.Raw: case ItemType.ValueString: item.data = XmlConvert.TrimStringEnd((string)item.data); if (((string)item.data).Length == 0) { // no characters left -> move the lastItem index to exclude it from the Replay _lastItem--; } break; case ItemType.StringChars: case ItemType.RawChars: BufferChunk bufChunk = (BufferChunk)item.data; while (bufChunk.count > 0 && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index + bufChunk.count - 1])) { bufChunk.count--; } if (bufChunk.count == 0) { // no characters left -> move the lastItem index to exclude it from the Replay _lastItem--; } break; } i--; } } internal void Clear() { _singleStringValue = null; _lastItem = -1; _firstItem = 0; _stringValue.Length = 0; } private void StartComplexValue() { Debug.Assert(_singleStringValue != null); Debug.Assert(_lastItem == -1); _stringValue.Append(_singleStringValue); AddItem(ItemType.String, _singleStringValue); _singleStringValue = null; } private void AddItem(ItemType type, object data) { int newItemIndex = _lastItem + 1; if (_items == null) { _items = new Item[4]; } else if (_items.Length == newItemIndex) { Item[] newItems = new Item[newItemIndex * 2]; Array.Copy(_items, newItems, newItemIndex); _items = newItems; } if (_items[newItemIndex] == null) { _items[newItemIndex] = new Item(); } _items[newItemIndex].Set(type, data); _lastItem = newItemIndex; } } } }
34.99435
136
0.426811
[ "MIT" ]
Bencargs/wcf
src/dotnet-svcutil/lib/src/FrameworkFork/Microsoft.Xml/Xml/Core/XmlWellformedWriterHelpers.cs
18,582
C#
using System.Collections.Specialized; using System.Globalization; using Xunit; using Assert = Microsoft.TestCommon.AssertEx; namespace System.Web.Mvc.Test { public class NameValueCollectionValueProviderTest { private static readonly NameValueCollection _backingStore = new NameValueCollection() { { "foo", "fooValue1" }, { "foo", "fooValue2" }, { "bar.baz", "someOtherValue" } }; [Fact] public void Constructor_ThrowsIfCollectionIsNull() { // Act & assert Assert.ThrowsArgumentNull( delegate { new NameValueCollectionValueProvider(null, CultureInfo.InvariantCulture); }, "collection"); } [Fact] public void ContainsPrefix() { // Arrange NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, null); // Act bool result = valueProvider.ContainsPrefix("bar"); // Assert Assert.True(result); } [Fact] public void ContainsPrefix_DoesNotContainEmptyPrefixIfBackingStoreIsEmpty() { // Arrange NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(new NameValueCollection(), null); // Act bool result = valueProvider.ContainsPrefix(""); // Assert Assert.False(result); } [Fact] public void ContainsPrefix_ThrowsIfPrefixIsNull() { // Arrange NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, null); // Act & assert Assert.ThrowsArgumentNull( delegate { valueProvider.ContainsPrefix(null); }, "prefix"); } [Fact] public void GetValue() { // Arrange CultureInfo culture = CultureInfo.GetCultureInfo("fr-FR"); NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, culture); // Act ValueProviderResult vpResult = valueProvider.GetValue("foo"); // Assert Assert.NotNull(vpResult); Assert.Equal(_backingStore.GetValues("foo"), (string[])vpResult.RawValue); Assert.Equal("fooValue1,fooValue2", vpResult.AttemptedValue); Assert.Equal(culture, vpResult.Culture); } [Fact] public void GetValue_NonValidating() { // Arrange NameValueCollection unvalidatedCollection = new NameValueCollection() { { "foo", "fooValue3" }, { "foo", "fooValue4" } }; CultureInfo culture = CultureInfo.GetCultureInfo("fr-FR"); NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, unvalidatedCollection, culture); // Act ValueProviderResult vpResult = valueProvider.GetValue("foo", skipValidation: true); // Assert Assert.NotNull(vpResult); Assert.Equal(new[] { "fooValue3", "fooValue4" }, (string[])vpResult.RawValue); Assert.Equal("fooValue3,fooValue4", vpResult.AttemptedValue); Assert.Equal(culture, vpResult.Culture); } [Fact] public void GetValue_NonValidating_NoUnvalidatedCollectionSpecified_UsesDefaultCollectionValue() { // Arrange CultureInfo culture = CultureInfo.GetCultureInfo("fr-FR"); NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, null, culture); // Act ValueProviderResult vpResult = valueProvider.GetValue("foo", skipValidation: true); // Assert Assert.NotNull(vpResult); Assert.Equal(_backingStore.GetValues("foo"), (string[])vpResult.RawValue); Assert.Equal("fooValue1,fooValue2", vpResult.AttemptedValue); Assert.Equal(culture, vpResult.Culture); } [Fact] public void GetValue_ReturnsNullIfKeyNotFound() { // Arrange NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, null); // Act ValueProviderResult vpResult = valueProvider.GetValue("bar"); // Assert Assert.Null(vpResult); } [Fact] public void GetValue_ThrowsIfKeyIsNull() { // Arrange NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, null); // Act & assert Assert.ThrowsArgumentNull( delegate { valueProvider.GetValue(null); }, "key"); } } }
34.402778
145
0.607994
[ "Apache-2.0" ]
douchedetector/mvc-razor
test/System.Web.Mvc.Test/Test/NameValueCollectionValueProviderTest.cs
4,956
C#
using System.Collections.Generic; using ASP.NET_Core_Fundamentals.Models; namespace ASP.NET_Core_Fundamentals.ViewModels { public class HomeIndexViewModel { public IEnumerable<Restaurant> Restaurants { get; set; } public string CurrentMessage { get; set; } } }
26.272727
64
0.733564
[ "MIT" ]
bokjo/ASP.NET-Core-Fundamentals
ViewModels/HomeIndexViewModel.cs
289
C#
using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace Famoser.LectureSync.Presentation.Universal.Pages { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class EditCoursePage : Page { public EditCoursePage() { this.InitializeComponent(); } } }
26.111111
94
0.657447
[ "MIT" ]
famoser/Famoser.Study
Famoser.LectureSync.Presentation.Universal/Pages/EditCoursePage.xaml.cs
472
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementOrStatementStatementAndStatementStatementOrStatementStatementXssMatchStatementFieldToMatchSingleQueryArgumentGetArgs : Pulumi.ResourceArgs { /// <summary> /// Name of the query header to inspect. This setting must be provided as lower case characters. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; public WebAclRuleStatementOrStatementStatementAndStatementStatementOrStatementStatementXssMatchStatementFieldToMatchSingleQueryArgumentGetArgs() { } } }
37.269231
181
0.74097
[ "ECL-2.0", "Apache-2.0" ]
chivandikwa/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementOrStatementStatementAndStatementStatementOrStatementStatementXssMatchStatementFieldToMatchSingleQueryArgumentGetArgs.cs
969
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org) // Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net) // Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp) // See the LICENSE.md file in the project root for full license information. using System.Threading.Tasks; using Stride.Core.BuildEngine; using Stride.Core.Annotations; using Stride.Core.Serialization.Contents; namespace Stride.Core.Assets.Compiler { /// <summary> /// An <see cref="AssetCommand"/> that will create a default instance of the content type for a given asset, rather than compiling it. /// </summary> /// <typeparam name="TAsset">The type of asset for which to generate a default instance of content.</typeparam> /// <typeparam name="TContent">The type of content to generate.</typeparam> public class DummyAssetCommand<TAsset, TContent> : AssetCommand<TAsset> where TAsset : Asset where TContent : new() { /// <summary> /// Initializes a new instance of the <see cref="DummyAssetCommand{TAsset, TContent}"/> class. /// </summary> /// <param name="assetItem">The asset to compile.</param> public DummyAssetCommand([NotNull] AssetItem assetItem) : base(assetItem.Location, (TAsset)assetItem.Asset, assetItem.Package) { } protected override Task<ResultStatus> DoCommandOverride(ICommandContext commandContext) { var contentManager = new ContentManager(MicrothreadLocalDatabases.ProviderService); var dummyObject = new TContent(); contentManager.Save(Url, dummyObject); return Task.FromResult(ResultStatus.Successful); } } }
44.948718
138
0.694238
[ "MIT" ]
Ethereal77/stride
sources/assets/Stride.Core.Assets/Compiler/DummyAssetCommand.cs
1,753
C#