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 2013 Canada Health Infoway, Inc. * * 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. * * Author: $LastChangedBy: gng $ * Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $ * Revision: $LastChangedRevision: 9755 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Diagnosticimagingreport { using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Datatype; using Ca.Infoway.Messagebuilder.Datatype.Impl; using Ca.Infoway.Messagebuilder.Datatype.Lang; using Ca.Infoway.Messagebuilder.Model; using Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Basemodel; using Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Domainvalue; using System.Collections.Generic; [Hl7PartTypeMappingAttribute(new string[] {"DiagnosticImagingReport.RelatedDocument"})] public class RelatedDocument : MessagePartBean, Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Diagnosticimagingreport.IRelatedDocumentChoice { private CS_R2<Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Domainvalue.x_ActRelationshipDocument> typeCode; private II typeId; private LIST<II, Identifier> templateId; private Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Basemodel.ParentDocument parentDocument; public RelatedDocument() { this.typeCode = new CS_R2Impl<Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Domainvalue.x_ActRelationshipDocument>(); this.typeId = new IIImpl(); this.templateId = new LISTImpl<II, Identifier>(typeof(IIImpl)); } /** * <summary>Relationship: * DiagnosticImagingReport.RelatedDocument.typeCode</summary> * * <remarks>Conformance/Cardinality: MANDATORY (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"typeCode"})] public CodedTypeR2<Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Domainvalue.x_ActRelationshipDocument> TypeCode { get { return (CodedTypeR2<Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Domainvalue.x_ActRelationshipDocument>) this.typeCode.Value; } set { this.typeCode.Value = value; } } /** * <summary>Relationship: * DiagnosticImagingReport.RelatedDocument.typeId</summary> * * <remarks>Conformance/Cardinality: OPTIONAL (0-1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"typeId"})] public Identifier TypeId { get { return this.typeId.Value; } set { this.typeId.Value = value; } } /** * <summary>Relationship: * DiagnosticImagingReport.RelatedDocument.templateId</summary> * * <remarks>Conformance/Cardinality: OPTIONAL (0-*)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"templateId"})] public IList<Identifier> TemplateId { get { return this.templateId.RawList(); } } /** * <summary>Relationship: * DiagnosticImagingReport.RelatedDocument.parentDocument</summary> * * <remarks>Conformance/Cardinality: POPULATED (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"parentDocument"})] public Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Basemodel.ParentDocument ParentDocument { get { return this.parentDocument; } set { this.parentDocument = value; } } } }
43.114583
143
0.663928
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-ccda-r1_1/Main/Ca/Infoway/Messagebuilder/Model/Ccda_r1_1/Diagnosticimagingreport/RelatedDocument.cs
4,139
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 s3outposts-2017-07-25.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.S3Outposts.Model { /// <summary> /// There was a conflict with this action, and it could not be completed. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class ConflictException : AmazonS3OutpostsException { /// <summary> /// Constructs a new ConflictException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public ConflictException(string message) : base(message) {} /// <summary> /// Construct instance of ConflictException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public ConflictException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of ConflictException /// </summary> /// <param name="innerException"></param> public ConflictException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of ConflictException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ConflictException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of ConflictException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ConflictException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the ConflictException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected ConflictException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
46.459677
178
0.675056
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/S3Outposts/Generated/Model/ConflictException.cs
5,761
C#
namespace GifDirectEditor { partial class GifWrapperFrm { /// <summary> /// Erforderliche Designervariable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Vom Windows Form-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GifWrapperFrm)); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.lstParts = new System.Windows.Forms.ListView(); this.colPart = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.picPreview = new System.Windows.Forms.PictureBox(); this.pnlPart = new System.Windows.Forms.Panel(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuFileOpen = new System.Windows.Forms.ToolStripMenuItem(); this.menuFileSave = new System.Windows.Forms.ToolStripMenuItem(); this.menuFileSaveAs = new System.Windows.Forms.ToolStripMenuItem(); this.batchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuBatchSetAllDelayTime = new System.Windows.Forms.ToolStripMenuItem(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picPreview)).BeginInit(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 24); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.splitContainer2); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.pnlPart); this.splitContainer1.Size = new System.Drawing.Size(782, 480); this.splitContainer1.SplitterDistance = 316; this.splitContainer1.TabIndex = 0; // // splitContainer2 // this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point(0, 0); this.splitContainer2.Name = "splitContainer2"; this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.lstParts); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add(this.picPreview); this.splitContainer2.Size = new System.Drawing.Size(316, 480); this.splitContainer2.SplitterDistance = 322; this.splitContainer2.TabIndex = 0; // // lstParts // this.lstParts.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.colPart, this.colSize}); this.lstParts.Dock = System.Windows.Forms.DockStyle.Fill; this.lstParts.FullRowSelect = true; this.lstParts.Location = new System.Drawing.Point(0, 0); this.lstParts.MultiSelect = false; this.lstParts.Name = "lstParts"; this.lstParts.Size = new System.Drawing.Size(316, 322); this.lstParts.TabIndex = 0; this.lstParts.UseCompatibleStateImageBehavior = false; this.lstParts.View = System.Windows.Forms.View.Details; this.lstParts.SelectedIndexChanged += new System.EventHandler(this.lstParts_SelectedIndexChanged); // // colPart // this.colPart.Text = "Part"; this.colPart.Width = 180; // // colSize // this.colSize.Text = "Size"; this.colSize.Width = 80; // // picPreview // this.picPreview.Dock = System.Windows.Forms.DockStyle.Fill; this.picPreview.Location = new System.Drawing.Point(0, 0); this.picPreview.Name = "picPreview"; this.picPreview.Size = new System.Drawing.Size(316, 154); this.picPreview.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.picPreview.TabIndex = 0; this.picPreview.TabStop = false; // // pnlPart // this.pnlPart.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlPart.Location = new System.Drawing.Point(0, 0); this.pnlPart.Name = "pnlPart"; this.pnlPart.Size = new System.Drawing.Size(462, 480); this.pnlPart.TabIndex = 0; // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.batchToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(782, 24); this.menuStrip1.TabIndex = 1; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuFileOpen, this.menuFileSave, this.menuFileSaveAs}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "&File"; // // menuFileOpen // this.menuFileOpen.Name = "menuFileOpen"; this.menuFileOpen.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.menuFileOpen.Size = new System.Drawing.Size(180, 22); this.menuFileOpen.Text = "&Open..."; this.menuFileOpen.Click += new System.EventHandler(this.menuFileOpen_Click); // // menuFileSave // this.menuFileSave.Name = "menuFileSave"; this.menuFileSave.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.menuFileSave.Size = new System.Drawing.Size(180, 22); this.menuFileSave.Text = "&Save"; this.menuFileSave.Click += new System.EventHandler(this.menuFileSave_Click); // // menuFileSaveAs // this.menuFileSaveAs.Name = "menuFileSaveAs"; this.menuFileSaveAs.Size = new System.Drawing.Size(180, 22); this.menuFileSaveAs.Text = "Save &As..."; this.menuFileSaveAs.Click += new System.EventHandler(this.menuFileSaveAs_Click); // // batchToolStripMenuItem // this.batchToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuBatchSetAllDelayTime}); this.batchToolStripMenuItem.Name = "batchToolStripMenuItem"; this.batchToolStripMenuItem.Size = new System.Drawing.Size(49, 20); this.batchToolStripMenuItem.Text = "&Batch"; // // menuBatchSetAllDelayTime // this.menuBatchSetAllDelayTime.Name = "menuBatchSetAllDelayTime"; this.menuBatchSetAllDelayTime.Size = new System.Drawing.Size(177, 22); this.menuBatchSetAllDelayTime.Text = "Set all delay times..."; this.menuBatchSetAllDelayTime.Click += new System.EventHandler(this.menuBatchSetAllDelayTime_Click); // // GifWrapperFrm // this.AllowDrop = true; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(782, 504); this.Controls.Add(this.splitContainer1); this.Controls.Add(this.menuStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.Name = "GifWrapperFrm"; this.Text = "GIF Direct Editor"; this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false); this.splitContainer2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.picPreview)).EndInit(); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.ListView lstParts; private System.Windows.Forms.PictureBox picPreview; private System.Windows.Forms.Panel pnlPart; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem menuFileOpen; private System.Windows.Forms.ToolStripMenuItem menuFileSave; private System.Windows.Forms.ToolStripMenuItem menuFileSaveAs; private System.Windows.Forms.ColumnHeader colPart; private System.Windows.Forms.ColumnHeader colSize; private System.Windows.Forms.ToolStripMenuItem batchToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem menuBatchSetAllDelayTime; } }
50.183761
146
0.604616
[ "MIT" ]
TheNeoBurn/GifWrapper
GifDirectEditor/GifWrapperFrm.Designer.cs
11,749
C#
using Promitor.Core.Scraping.Configuration.Serialization; using Promitor.Core.Scraping.Configuration.Serialization.v1.Model; using Promitor.Core.Scraping.Configuration.Serialization.v1.Model.ResourceTypes; using Promitor.Core.Scraping.Configuration.Serialization.v1.Providers; using Xunit; namespace Promitor.Tests.Unit.Serialization.v1.Providers { public class ApiManagementDeserializerTests : ResourceDeserializerTest<ApiManagementDeserializer> { private readonly ApiManagementDeserializer _deserializer; public ApiManagementDeserializerTests() { _deserializer = new ApiManagementDeserializer(Logger); } [Fact] public void Deserialize_InstanceNameSupplied_SetsInstanceName() { const string instanceName = "promitor-gateway"; YamlAssert.PropertySet<ApiManagementResourceV1, AzureResourceDefinitionV1, string>( _deserializer, $"instanceName: {instanceName}", instanceName, r => r.InstanceName); } [Fact] public void Deserialize_InstanceNameNotSupplied_Null() { YamlAssert.PropertyNull<ApiManagementResourceV1, AzureResourceDefinitionV1>( _deserializer, "resourceGroupName: promitor-group", r => r.InstanceName); } [Fact] public void Deserialize_LocationNameSupplied_SetsLocationName() { const string locationName = "West Europe"; YamlAssert.PropertySet<ApiManagementResourceV1, AzureResourceDefinitionV1, string>( _deserializer, $"locationName: '{locationName}'", locationName, r => r.LocationName); } [Fact] public void Deserialize_LocationNameNotSupplied_Null() { YamlAssert.PropertyNull<ApiManagementResourceV1, AzureResourceDefinitionV1>( _deserializer, "resourceGroupName: promitor-group", r => r.LocationName); } protected override IDeserializer<AzureResourceDefinitionV1> CreateDeserializer() { return new ApiManagementDeserializer(Logger); } } }
36.142857
101
0.648221
[ "MIT" ]
3lvia/promitor
src/Promitor.Tests.Unit/Serialization/v1/Providers/ApiManagementDeserializerTests.cs
2,279
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Off-Sync.com. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; using NUnit.Framework; using OffSync.Mapping.Mappert.MappingRules; using OffSync.Mapping.Mappert.Practises; using OffSync.Mapping.Mappert.Practises.MappingRules; using OffSync.Mapping.Mappert.Tests.Models; namespace OffSync.Mapping.Mappert.Reflection.Tests { [TestFixture] public class ReflectionMappingDelegateBuilderTest { private ReflectionMappingDelegateBuilder _sut; [SetUp] public void SetUp() { ReflectionMappingDelegateBuilder.SetAsDefault(); _sut = new ReflectionMappingDelegateBuilder(); } [Test] public void IsRegistered() { var builder = MappingDelegateBuilderRegistry.Default; Assert.That( builder, Is.TypeOf<ReflectionMappingDelegateBuilder>()); } [Test] public void CreateMappingDelegateShouldCheckPreConditions() { Assert.That( () => _sut.CreateMappingDelegate<SourceModel, TargetModel>(null), Throws.ArgumentNullException); } [Test] public void CreateMappingDelegateForDirectAssignment() { var mappingRules = new IMappingRule[] { new MappingRule() .WithSource(typeof(SourceModel).GetProperty(nameof(SourceModel.Id))) .WithTarget(typeof(TargetModel).GetProperty(nameof(TargetModel.Id))), }; var mappingDelegate = _sut.CreateMappingDelegate<SourceModel, TargetModel>(mappingRules); var source = new SourceModel() { Id = 1, }; var target = new TargetModel(); mappingDelegate( source, target); Assert.That( target.Id, Is.EqualTo(1)); } [Test] public void CreateMappingDelegateForSingleValueAssignment() { Func<int, int> builder = i => i * 2; var mappingRules = new IMappingRule[] { new MappingRule() .WithSource(typeof(SourceModel).GetProperty(nameof(SourceModel.Id))) .WithTarget(typeof(TargetModel).GetProperty(nameof(TargetModel.Id))) .WithBuilder(builder), }; var mappingDelegate = _sut.CreateMappingDelegate<SourceModel, TargetModel>(mappingRules); var source = new SourceModel() { Id = 1, }; var target = new TargetModel(); mappingDelegate( source, target); Assert.That( target.Id, Is.EqualTo(2)); } [Test] public void CreateMappingDelegateForValueTupleAssignment() { Func<string, (int, string)> builder = TupleSplitter; var mappingRules = new IMappingRule[] { new MappingRule() .WithSource(typeof(SourceModel).GetProperty(nameof(SourceModel.Values))) .WithTarget(typeof(TargetModel).GetProperty(nameof(TargetModel.Id))) .WithTarget(typeof(TargetModel).GetProperty(nameof(TargetModel.Value1))) .WithBuilder(builder), }; var mappingDelegate = _sut.CreateMappingDelegate<SourceModel, TargetModel>(mappingRules); var source = new SourceModel() { Values = "1,2", }; var target = new TargetModel(); mappingDelegate( source, target); Assert.That( target.Id, Is.EqualTo(1)); Assert.That( target.Value1, Is.EqualTo("2")); } private (int, string) TupleSplitter( string values) { var splitted = values.Split(','); return (int.Parse(splitted[0]), splitted[1]); } [Test] public void CreateMappingDelegateForObjectArrayAssignment() { Func<string, object[]> builder = ArraySplitter; var mappingRules = new IMappingRule[] { new MappingRule() .WithSource(typeof(SourceModel).GetProperty(nameof(SourceModel.Values))) .WithTarget(typeof(TargetModel).GetProperty(nameof(TargetModel.Id))) .WithTarget(typeof(TargetModel).GetProperty(nameof(TargetModel.Value1))) .WithBuilder(builder), }; var mappingDelegate = _sut.CreateMappingDelegate<SourceModel, TargetModel>(mappingRules); var source = new SourceModel() { Values = "1,2", }; var target = new TargetModel(); mappingDelegate( source, target); Assert.That( target.Id, Is.EqualTo(1)); Assert.That( target.Value1, Is.EqualTo("2")); } private object[] ArraySplitter( string values) { var splitted = values.Split(','); return new object[] { int.Parse(splitted[0]), splitted[1], }; } } }
29.144279
101
0.50495
[ "MIT" ]
off-sync/mapping-mappert
test/OffSync.Mapping.Mappert.Reflection.Tests/ReflectionMappingDelegateBuilderTest.cs
5,860
C#
namespace CurrentUserService.Tests { using System; using ICSSoft.Services; using Xunit; /// <summary> /// Class of unit test for <see cref="CurrentUserService"/>. /// </summary> public class CurrentUserServiceTest { /// <summary> /// Test implementation of <see cref="CurrentUserService.IUser"/>. /// </summary> private class CustomUser : CurrentUserService.IUser { public string FriendlyName { get { return "custom user name"; } set { throw new NotImplementedException(); } } public string Domain { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string Login { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } /// <summary> /// Test method for <see cref="CurrentUserService.CurrentUser"/> /// Checks existence of the default user (Windows authorization is used in test runner). /// </summary> [Fact] public void TestDefaultUser() { Assert.False(string.IsNullOrEmpty(CurrentUserService.CurrentUser.FriendlyName)); } /// <summary> /// Test method for <see cref="CurrentUserService.ResolveUser{T}"/>. /// Checks registering custom user for current. /// </summary> [Fact] public void TestCustomUser() { CurrentUserService.ResolveUser<CustomUser>(); var myUser = new CustomUser(); Assert.Equal(myUser.FriendlyName, CurrentUserService.CurrentUser.FriendlyName); CurrentUserService.ResolveUser<CurrentUser>(); } /// <summary> /// Test method for <see cref="CurrentUserService.CurrentUser"/>. /// Checks getters and setter for data of current user. /// </summary> [Fact] public void TestCustomUserName() { const string fn = "friendly name"; const string login = "login"; CurrentUserService.CurrentUser.Login = login; Assert.Equal(login, CurrentUserService.CurrentUser.Login); CurrentUserService.CurrentUser.FriendlyName = fn; Assert.Equal(fn, CurrentUserService.CurrentUser.FriendlyName); } } }
30.670732
96
0.5666
[ "MIT" ]
AlexBurmatov/NewPlatform.Flexberry.ORM
NewPlatform.Flexberry.ORM.Tests/CurrentUserService/CurrentUserServiceTest.cs
2,517
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("Task03BiggerNumber")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Task03BiggerNumber")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("708d2c10-fe42-4ae0-bd18-7953c5a33d82")] // 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")]
38.081081
84
0.747339
[ "MIT" ]
andreykata/SoftUni
Programming Basics/2016 June/CSharpProgrammingBasic03SimpleConditions/Task03BiggerNumber/Properties/AssemblyInfo.cs
1,412
C#
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using System.Xml; using System.IO; namespace ASTool.ISMHelper { public enum IsmTrackType { audio, video, text, textstream } public class QualityLevel { public QualityLevel(XmlNode n) { if (n.Attributes["Index"] != null) Index = int.Parse(n.Attributes["Index"].Value); else Index = 0; Bitrate = int.Parse(n.Attributes["Bitrate"].Value); FourCC = n.Attributes["FourCC"].Value; if(n.Attributes["CodecPrivateData"] != null) CodecPrivateData = n.Attributes["CodecPrivateData"].Value; else CodecPrivateData = string.Empty; } public int Index; public int Bitrate; public string FourCC; public string CodecPrivateData; } public class VideoQualityLevel : QualityLevel { public VideoQualityLevel(XmlNode n): base(n) { MaxWidth = int.Parse(n.Attributes["MaxWidth"].Value); MaxHeight = int.Parse(n.Attributes["MaxHeight"].Value); } // video public int MaxWidth; public int MaxHeight; } public class AudioQualityLevel : QualityLevel { public AudioQualityLevel(XmlNode n): base (n) { SamplingRate = int.Parse(n.Attributes["SamplingRate"].Value); Channels = int.Parse(n.Attributes["Channels"].Value); BitsPerSample = int.Parse(n.Attributes["BitsPerSample"].Value); PacketSize = int.Parse(n.Attributes["PacketSize"].Value); AudioTag = n.Attributes["AudioTag"].Value; } //audio public int SamplingRate; public int Channels; public int BitsPerSample; public int PacketSize; public string AudioTag; } public class TextQualityLevel : QualityLevel { public TextQualityLevel(XmlNode n) : base(n) { } //text } public class Chunk { public Chunk(XmlNode n, int Ind = 0) { if (n.Attributes["n"] != null) Index = long.Parse(n.Attributes["n"].Value); else Index = Ind; duration = long.Parse(n.Attributes["d"].Value); } public long Index; public long duration; } public class StreamIndex { internal StreamIndex(XmlNode n) { MediaType = (IsmTrackType)Enum.Parse(typeof(IsmTrackType), n.Attributes["Type"].Value); if(n.Attributes["TimeScale"]!=null) TimeScale = long.Parse(n.Attributes["TimeScale"].Value); else TimeScale = 10000000; Chunks = long.Parse(n.Attributes["Chunks"].Value); var Val = n.Attributes["QualityLevels"]; if(Val != null) QualityLevelCount = int.Parse(n.Attributes["QualityLevels"].Value); else QualityLevelCount = 1; Name = n.Attributes["Name"].Value; if(n.Attributes["Language"]!=null) Lang = n.Attributes["Language"].Value; else Lang = "eng"; XmlNodeList QualityLevels = n.SelectNodes("QualityLevel"); if (MediaType == IsmTrackType.audio) { AudioLevel = new AudioQualityLevel[QualityLevels.Count]; for (int i = 0; i < QualityLevels.Count; i++) { AudioLevel[i] = new AudioQualityLevel(QualityLevels[i]); } } if (MediaType == IsmTrackType.video) { VideoLevel = new VideoQualityLevel[QualityLevels.Count]; for (int i = 0; i < QualityLevels.Count; i++) { VideoLevel[i] = new VideoQualityLevel(QualityLevels[i]); } } if (MediaType == IsmTrackType.text) { TextLevel = new TextQualityLevel[QualityLevels.Count]; for (int i = 0; i < QualityLevels.Count; i++) { TextLevel[i] = new TextQualityLevel(QualityLevels[i]); } } } public IsmTrackType MediaType; public long TimeScale; public long Chunks; public AudioQualityLevel[] AudioLevel; public VideoQualityLevel[] VideoLevel; public TextQualityLevel[] TextLevel; public string Name; public int QualityLevelCount; public string Lang; static XmlNode GetParam(XmlNode n, string name) { for (int i = 0; i < n.ChildNodes.Count; i++) { if (n.ChildNodes[i].Name == "param" && n.ChildNodes[i].Attributes["name"].Value == name) { return n.ChildNodes[i]; } } return null; } } public class IsmcFile { private XmlDocument _doc = new XmlDocument(); public IsmcFile(Stream s) { _doc.Load(s); XmlNodeList SmoothStreamingMediaNodeList = SelectNodes("SmoothStreamingMedia"); if (SmoothStreamingMediaNodeList != null) { if(SmoothStreamingMediaNodeList[0].Attributes["TimeScale"]!=null) TimeScale = long.Parse(SmoothStreamingMediaNodeList[0].Attributes["TimeScale"].Value); else TimeScale = 10000000; Duration = long.Parse(SmoothStreamingMediaNodeList[0].Attributes["Duration"].Value); Version = SmoothStreamingMediaNodeList[0].Attributes["MajorVersion"].Value + "." + SmoothStreamingMediaNodeList[0].Attributes["MinorVersion"].Value; } XmlNodeList StreamIndexNodeList = SelectNodes("SmoothStreamingMedia/StreamIndex"); StreamIndexs = new StreamIndex[StreamIndexNodeList.Count]; ChunkIndexs = new Chunk[StreamIndexNodeList.Count][]; for (int i = 0; i < StreamIndexNodeList.Count; i++) { StreamIndexs[i] = new StreamIndex(StreamIndexNodeList[i]); XmlNodeList ChunkNodeList = StreamIndexNodeList[i].SelectNodes("c"); if (ChunkNodeList != null) { if ((ChunkNodeList.Count > 0) && (ChunkNodeList.Count == StreamIndexs[i].Chunks)) { Chunk[] ChunkArray = new Chunk[ChunkNodeList.Count]; for (int j = 0; j < ChunkNodeList.Count; j++) { ChunkArray[j] = new Chunk(ChunkNodeList[j], j); } ChunkIndexs[i] = ChunkArray; } } } } protected XmlNodeList SelectNodes(string xpath) { return _doc.SelectNodes(xpath); } public override string ToString() { return _doc.OuterXml; } public StreamIndex[] StreamIndexs; public Chunk[][] ChunkIndexs; string Version; long TimeScale; long Duration; } public class IsmFile : SMIL20Stream { public IsmFile(Stream s) : base(s) { XmlNodeList videoTracks = SelectNodes("smil:smil/smil:body/smil:switch/smil:video"); XmlNodeList audioTracks = SelectNodes("smil:smil/smil:body/smil:switch/smil:audio"); XmlNodeList textTracks = SelectNodes("smil:smil/smil:body/smil:switch/smil:textstream"); Tracks = new IsmFileTrack[videoTracks.Count + audioTracks.Count + textTracks.Count]; for (int i = 0; i < videoTracks.Count; i++) { Tracks[i] = new IsmFileTrack(videoTracks[i]); } for (int i = 0; i < audioTracks.Count; i++) { Tracks[i + videoTracks.Count] = new IsmFileTrack(audioTracks[i]); } for (int i = 0; i < textTracks.Count; i++) { Tracks[i + videoTracks.Count + audioTracks.Count] = new IsmFileTrack(textTracks[i]); } IsmcFilePath = string.Empty; XmlNodeList metas = SelectNodes("smil:smil/smil:head/smil:meta"); if (metas != null) { for(int i = 0 ; i < metas.Count; i++) { if (metas[i].Attributes["name"].Value == "clientManifestRelativePath") { IsmcFilePath = metas[i].Attributes["content"].Value; break; } } } } static string VideoLiveManifestTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\r\n <head>\r\n <meta name=\"creator\" content=\"pushEncoder\" />\r\n </head>\r\n <body>\r\n <switch>\r\n <video src=\"<ismvfile>\" systemBitrate=\"<bitrate>\">\r\n <param name=\"trackID\" value=\"<trackid>\" valuetype=\"data\" />\r\n <param name=\"trackName\" value=\"<trackname>\" valuetype=\"data\" />\r\n <param name=\"timescale\" value=\"<timescale>\" valuetype=\"data\" />\r\n <param name=\"FourCC\" value=\"<fourcc>\" valuetype=\"data\" />\r\n <param name=\"CodecPrivateData\" value=\"<codecprivatedata>\" valuetype=\"data\" />\r\n <param name=\"MaxWidth\" value=\"<width>\" valuetype=\"data\" />\r\n <param name=\"MaxHeight\" value=\"<height>\" valuetype=\"data\" />\r\n <param name=\"DisplayWidth\" value=\"<width>\" valuetype=\"data\" />\r\n <param name=\"DisplayHeight\" value=\"<height>\" valuetype=\"data\" />\r\n <param name=\"Subtype\" value=\"\" valuetype=\"data\" />\r\n </video>\r\n </switch>\r\n </body>\r\n</smil>\r\n"; public string GetVideoManifest(int TrackID, string TrackName, int Bitrate, string source, IsmcFile ismc) { string manifest = string.Empty; if(ismc.StreamIndexs != null) { for(int i= 0 ; i < ismc.StreamIndexs.Length; i++) { if ((ismc.StreamIndexs[i].Name == TrackName) && (ismc.StreamIndexs[i].MediaType == IsmTrackType.video)) { if(ismc.StreamIndexs[i].VideoLevel != null) { if(ismc.StreamIndexs[i].VideoLevel.Length>0) { for(int j = 0; j<ismc.StreamIndexs[i].VideoLevel.Length;j++) { if(ismc.StreamIndexs[i].VideoLevel[j].Bitrate == Bitrate) { manifest = VideoLiveManifestTemplate; manifest = manifest.Replace("<ismvfile>",source); manifest = manifest.Replace("<bitrate>",Bitrate.ToString()); manifest = manifest.Replace("<trackid>",TrackID.ToString()); manifest = manifest.Replace("<trackname>",TrackName.ToString()); manifest = manifest.Replace("<timescale>",ismc.StreamIndexs[i].TimeScale.ToString()); manifest = manifest.Replace("<fourcc>",ismc.StreamIndexs[i].VideoLevel[j].FourCC.ToString()); manifest = manifest.Replace("<codecprivatedata>",ismc.StreamIndexs[i].VideoLevel[j].CodecPrivateData.ToString()); manifest = manifest.Replace("<width>",ismc.StreamIndexs[i].VideoLevel[j].MaxWidth.ToString()); manifest = manifest.Replace("<height>",ismc.StreamIndexs[i].VideoLevel[j].MaxHeight.ToString()); return manifest; } } } } } } } return manifest; } static string TextLiveManifestTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\r\n <head>\r\n <meta name=\"creator\" content=\"pushEncoder\" />\r\n </head>\r\n <body>\r\n <switch>\r\n <textstream src=\"<ismtfile>\" systemBitrate=\"<bitrate>\" systemLanguage=\"<lang>\">\r\n <param name=\"trackID\" value=\"<trackid>\" valuetype=\"data\" />\r\n <param name=\"trackName\" value=\"<trackname>\" valuetype=\"data\" />\r\n <param name=\"timescale\" value=\"<timescale>\" valuetype=\"data\" />\r\n </textstream>\r\n </switch>\r\n </body>\r\n</smil>\r\n"; public string GetTextManifest(int TrackID, string TrackName, int Bitrate, string source, IsmcFile ismc) { string manifest = string.Empty; if (ismc.StreamIndexs != null) { for (int i = 0; i < ismc.StreamIndexs.Length; i++) { if ((ismc.StreamIndexs[i].Name == TrackName) && (ismc.StreamIndexs[i].MediaType == IsmTrackType.text)) { if (ismc.StreamIndexs[i].TextLevel != null) { if (ismc.StreamIndexs[i].TextLevel.Length > 0) { for (int j = 0; j < ismc.StreamIndexs[i].TextLevel.Length; j++) { if (ismc.StreamIndexs[i].TextLevel[j].Bitrate == Bitrate) { manifest = TextLiveManifestTemplate; manifest = manifest.Replace("<ismtfile>", source); manifest = manifest.Replace("<bitrate>", Bitrate.ToString()); manifest = manifest.Replace("<lang>", ismc.StreamIndexs[i].Lang); manifest = manifest.Replace("<trackid>", TrackID.ToString()); manifest = manifest.Replace("<trackname>", TrackName.ToString()); manifest = manifest.Replace("<timescale>", ismc.StreamIndexs[i].TimeScale.ToString()); manifest = manifest.Replace("<fourcc>", ismc.StreamIndexs[i].TextLevel[j].FourCC.ToString()); return manifest; } } } } } } } return manifest; } public Chunk[] GetChunkList(string TrackName, IsmcFile ismc) { string manifest = string.Empty; if (ismc.StreamIndexs != null) { for (int i = 0; i < ismc.StreamIndexs.Length; i++) { if (ismc.StreamIndexs[i].Name == TrackName) { return ismc.ChunkIndexs[i]; } } } return null; } /* <?xml version="1.0" encoding="utf-8"?> <smil xmlns="http://www.w3.org/2001/SMIL20/Language"> <head> <meta name="creator" content="pushEncoder" /> </head> <body> <switch> <video src="165258_3500000_1.ismv" systemBitrate="3500000"> <param name="trackID" value="1" valuetype="data" /> <param name="trackName" value="video" valuetype="data" /> <param name="timescale" value="10000000" valuetype="data" /> <param name="FourCC" value="H264" valuetype="data" /> <param name="CodecPrivateData" value="000000012764001FAC2CA5014016EC04400000FA40003" valuetype="data" /> <param name="MaxWidth" value="1280" valuetype="data" /> <param name="MaxHeight" value="720" valuetype="data" /> <param name="DisplayWidth" value="1280" valuetype="data" /> <param name="DisplayHeight" value="720" valuetype="data" /> <param name="Subtype" value="" valuetype="data" /> </video> </switch> </body> </smil> */ static string AudioLiveManifestTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\r\n <head>\r\n <meta name=\"creator\" content=\"pushEncoder\" />\r\n </head>\r\n <body>\r\n <switch>\r\n <audio src=\"<ismafile>\" systemBitrate=\"<bitrate>\" systemLanguage=\"<lang>\">\r\n <param name=\"trackID\" value=\"<trackid>\" valuetype=\"data\" />\r\n <param name=\"trackName\" value=\"<trackname>\" valuetype=\"data\" />\r\n <param name=\"timescale\" value=\"<timescale>\" valuetype=\"data\" />\r\n <param name=\"FourCC\" value=\"<fourcc>\" valuetype=\"data\" />\r\n <param name=\"CodecPrivateData\" value=\"<codecprivatedata>\" valuetype=\"data\" />\r\n <param name=\"AudioTag\" value=\"<audiotag>\" valuetype=\"data\" />\r\n <param name=\"Channels\" value=\"<channels>\" valuetype=\"data\" />\r\n <param name=\"SamplingRate\" value=\"<samplingrate>\" valuetype=\"data\" />\r\n <param name=\"BitsPerSample\" value=\"<bitpersample>\" valuetype=\"data\" />\r\n <param name=\"PacketSize\" value=\"<packetsize>\" valuetype=\"data\" />\r\n <param name=\"Subtype\" value=\"\" valuetype=\"data\" />\r\n </audio>\r\n </switch>\r\n </body>\r\n</smil>\r\n"; public string GetAudioManifest(int TrackID, string TrackName, int Bitrate, string source, IsmcFile ismc) { string manifest = string.Empty; if (ismc.StreamIndexs != null) { for (int i = 0; i < ismc.StreamIndexs.Length; i++) { if ((ismc.StreamIndexs[i].Name == TrackName) && (ismc.StreamIndexs[i].MediaType == IsmTrackType.audio)) { if (ismc.StreamIndexs[i].AudioLevel != null) { if (ismc.StreamIndexs[i].AudioLevel.Length > 0) { for (int j = 0; j < ismc.StreamIndexs[i].AudioLevel.Length; j++) { if (ismc.StreamIndexs[i].AudioLevel[j].Bitrate == Bitrate) { manifest = AudioLiveManifestTemplate; manifest = manifest.Replace("<ismafile>",source); manifest = manifest.Replace("<bitrate>",Bitrate.ToString()); manifest = manifest.Replace("<lang>",ismc.StreamIndexs[i].Lang); manifest = manifest.Replace("<trackid>",TrackID.ToString()); manifest = manifest.Replace("<trackname>",TrackName.ToString()); manifest = manifest.Replace("<timescale>", ismc.StreamIndexs[i].TimeScale.ToString()); manifest = manifest.Replace("<fourcc>", ismc.StreamIndexs[i].AudioLevel[j].FourCC.ToString()); manifest = manifest.Replace("<codecprivatedata>", ismc.StreamIndexs[i].AudioLevel[j].CodecPrivateData.ToString()); manifest = manifest.Replace("<audiotag>",ismc.StreamIndexs[i].AudioLevel[j].AudioTag.ToString()); manifest = manifest.Replace("<channels>",ismc.StreamIndexs[i].AudioLevel[j].Channels.ToString()); manifest = manifest.Replace("<samplingrate>",ismc.StreamIndexs[i].AudioLevel[j].SamplingRate.ToString()); manifest = manifest.Replace("<bitpersample>",ismc.StreamIndexs[i].AudioLevel[j].BitsPerSample.ToString()); manifest = manifest.Replace("<packetsize>",ismc.StreamIndexs[i].AudioLevel[j].PacketSize.ToString()); return manifest; } } } } } } } return manifest; } /* <smil xmlns="http://www.w3.org/2001/SMIL20/Language"> <head> <meta name="creator" content="pushEncoder" /> </head> <body> <switch> <audio src="165258_64000_1.isma" systemBitrate="64000" systemLanguage="eng"> <param name="trackID" value="1" valuetype="data" /> <param name="trackName" value="audio_eng" valuetype="data" /> <param name="timescale" value="10000000" valuetype="data" /> <param name="FourCC" value="AACH" valuetype="data" /> <param name="CodecPrivateData" value="131056E598" valuetype="data" /> <param name="AudioTag" value="255" valuetype="data" /> <param name="Channels" value="2" valuetype="data" /> <param name="SamplingRate" value="24000" valuetype="data" /> <param name="BitsPerSample" value="16" valuetype="data" /> <param name="PacketSize" value="4" valuetype="data" /> <param name="Subtype" value="" valuetype="data" /> </audio> </switch> </body> </smil>*/ public IsmFileTrack[] Tracks; public string IsmcFilePath; } public class IsmFileTrack { internal IsmFileTrack(XmlNode n) { MediaType = (IsmTrackType)Enum.Parse(typeof(IsmTrackType), n.Name); Bitrate = int.Parse(n.Attributes["systemBitrate"].Value); Source = n.Attributes["src"].Value; TrackName = GetParam(n, "trackName").Attributes["value"].Value; TrackId = int.Parse(GetParam(n, "trackID").Attributes["value"].Value); } public IsmTrackType MediaType; public string Source; public int Bitrate; public int TrackId; public string TrackName; static XmlNode GetParam(XmlNode n, string name) { for (int i = 0; i < n.ChildNodes.Count; i++) { if (n.ChildNodes[i].Name == "param" && n.ChildNodes[i].Attributes["name"].Value == name) { return n.ChildNodes[i]; } } return null; } } }
47.732653
1,310
0.506606
[ "MIT" ]
flecoqui/ASTool
cs/ASTool/ASTool.Core/ISMHelper/IsmFile.cs
23,391
C#
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ namespace Apache.Ignite.Core.Cache.Configuration { using Apache.Ignite.Core.Cache; /// <summary> /// Cache atomicity mode. /// </summary> public enum CacheAtomicityMode { /// <summary> /// Specifies fully ACID-compliant transactional cache behavior. /// <para /> /// <b>Note!</b> In this mode, transactional consistency is guaranteed for key-value API operations only. /// To enable ACID capabilities for SQL transactions, use TRANSACTIONAL_SNAPSHOT mode. /// <para /> /// <b>Note!</b> This atomicity mode is not compatible with the other atomicity modes within the same transaction. /// If a transaction is executed over multiple caches, all caches must have the same atomicity mode, /// either TRANSACTIONAL_SNAPSHOT or TRANSACTIONAL. /// </summary> Transactional, /// <summary> /// Specifies atomic-only cache behaviour. In this mode distributed transactions and distributed /// locking are not supported. Disabling transactions and locking allows to achieve much higher /// performance and throughput ratios. /// <para/> /// In addition to transactions and locking, one of the main differences to <see cref="Atomic"/> mode /// is that bulk writes, such as <see cref="ICache{TK,TV}.PutAll"/> /// and <see cref="ICache{TK,TV}.RemoveAll(System.Collections.Generic.IEnumerable{TK})"/> methods, /// become simple batch operations which can partially fail. In case of partial /// failure, <see cref="CachePartialUpdateException"/>will be thrown which will contain a list of keys /// for which the update failed. It is recommended that bulk writes are used /// whenever multiple keys need to be inserted or updated in cache, as they reduce number of network trips and /// provide better performance. /// <para/> /// Note that even without locking and transactions, <see cref="Atomic"/> mode still provides /// full consistency guarantees across all cache nodes. /// <para/> /// Also note that all data modifications in <see cref="Atomic"/> mode are guaranteed to be atomic /// and consistent with writes to the underlying persistent store, if one is configured. /// </summary> Atomic, /// <summary> /// Specifies fully ACID-compliant transactional cache behavior for both key-value API and SQL transactions. /// <para/> /// This atomicity mode enables multiversion concurrency control (MVCC) for the cache. In MVCC-enabled caches, /// when a transaction updates a row, it creates a new version of that row instead of overwriting it. /// Other users continue to see the old version of the row until the transaction is committed. /// In this way, readers and writers do not conflict with each other and always work with a consistent dataset. /// The old version of data is cleaned up when it's no longer accessed by anyone. /// <para /> /// With this mode enabled, one node is elected as an MVCC coordinator. This node tracks all in-flight transactions /// and queries executed in the cluster. Each transaction or query executed over the cache with /// TRANSACTIONAL_SNAPSHOT mode works with a current snapshot of data generated for this transaction or query /// by the coordinator. This snapshot ensures that the transaction works with a consistent database state /// during its execution period. /// <para /> /// <b>Note!</b> This atomicity mode is not compatible with the other atomicity modes within the same transaction. /// If a transaction is executed over multiple caches, all caches must have the same atomicity mode, /// either TRANSACTIONAL_SNAPSHOT or TRANSACTIONAL. /// </summary> TransactionalSnapshot, } }
58.256098
123
0.685158
[ "Apache-2.0" ]
Antholoj/ignite
modules/platforms/dotnet/Apache.Ignite.Core/Cache/Configuration/CacheAtomicityMode.cs
4,777
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Qwiq.Identity { [Serializable] public class MultipleIdentitiesFoundException : ApplicationException { public MultipleIdentitiesFoundException(string displayName, IEnumerable<string> matches) : this($"Multiple identities found matching '{displayName}'. Please specify one of the following identities:\r\n- {string.Join("\r\n- ", matches)}") { } public MultipleIdentitiesFoundException(string message) : base(message) { } public MultipleIdentitiesFoundException() : base() { } public MultipleIdentitiesFoundException(string message, Exception innerException) : base(message, innerException) { } protected MultipleIdentitiesFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
30.4375
160
0.673511
[ "MIT" ]
rjmurillo/Qwiq
src/Qwiq.Identity/MultipleIdentitiesFoundException.cs
974
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("EvenPowersOf2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EvenPowersOf2")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("d8230598-9c2e-46c5-9ed0-cb2a8553fec9")] // 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.675676
84
0.748207
[ "MIT" ]
Karamihova/Programming-Basics
LoopLab/EvenPowersOf2/Properties/AssemblyInfo.cs
1,397
C#
namespace NCubeSolvers.Core { public enum Axis { X, Y, Z } }
10.777778
28
0.43299
[ "MIT" ]
EdwardSalter/NCubeSolver
src/Core/Axis.cs
99
C#
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.Networking; public class LevelLoader : MonoBehaviour { private static string gameDataProjectLocation = "/gameData.json"; GameData gameData; public static LevelLoader instance; void Awake() { if(instance == null) { instance = this; } else if(instance != this) { Destroy(gameObject); } LoadGameData(); } private static string getAppDataPath() { #if UNITY_EDITOR return Application.dataPath + "/StreamingAssets"; #elif UNITY_IOS return Application.dataPath + "/Raw"; #elif UNITY_ANDROID return Application.streamingAssetsPath; #else return Application.dataPath; #endif } private void LoadGameData() { if (Application.platform == RuntimePlatform.Android) { // WWW reader = new WWW(getAppDataPath() + gameDataProjectLocation); // IEnumerator enumerator = GetRequest(getAppDataPath() + gameDataProjectLocation); // enumerator. // Coroutine loading = StartCoroutine(GetRequest(getAppDataPath() + gameDataProjectLocation)); // while (loading.) // { // } GetRequest(getAppDataPath() + gameDataProjectLocation); // while (!reader.isDone) { } // string jsonDataString = reader.text; //gameData = JsonUtility.FromJson<GameData>(jsonDataString); } else { string filePath = getAppDataPath() + gameDataProjectLocation; if (File.Exists(filePath)) { string jsonDataString = File.ReadAllText(filePath); gameData = JsonUtility.FromJson<GameData>(jsonDataString); } else { Debug.LogWarning("No Game Data Found, Cannot Load"); // fail gracefully here }; } } public LevelData LoadLevelData(int levelId, DataTypes.BiomeType biome) { if(levelId == -1) { levelId = 1; } // Load in the gameData if we haven't before if(gameData == null) { LoadGameData(); } //Get Data for selected level ID LevelData levelData = gameData.allLevelData.Find(x => x.levelId == levelId && x.biomeType == biome); return copyLevelData(levelData); } LevelData copyLevelData(LevelData levelData) { LevelData returnable = new LevelData(); returnable.levelId = levelData.levelId; returnable.levelName = levelData.levelName; returnable.biomeType = levelData.biomeType; returnable.gridCellSize = new Vector3(levelData.gridCellSize.x, levelData.gridCellSize.y, levelData.gridCellSize.z); returnable.gridCellPosition = new Vector3(levelData.gridCellPosition.x, levelData.gridCellPosition.y, levelData.gridCellPosition.z); returnable.pointMultiplier = levelData.pointMultiplier; returnable.isBossLevel = levelData.isBossLevel; returnable.movementType = levelData.movementType; foreach (HexData hexData in levelData.hexData) { returnable.hexData.Add(copyHexData(hexData)); } return returnable; } HexData copyHexData(HexData hexData) { HexData returnable = new HexData(); returnable.hexType = hexData.hexType; returnable.health = hexData.health; returnable.points = hexData.points; returnable.hexScaleFactor = new Vector2(hexData.hexScaleFactor.x, hexData.hexScaleFactor.y); returnable.cellLocation = new Vector3Int(hexData.cellLocation.x, hexData.cellLocation.y, hexData.cellLocation.z); return returnable; } public List<int> getLevelList(DataTypes.BiomeType biome) { if(gameData == null) { LoadGameData(); } List<int> levelIds = new List<int>(); foreach (LevelData data in gameData.allLevelData) { if(data.biomeType == biome) { levelIds.Add(data.levelId); } } levelIds.Sort(); return levelIds; } // void newRequest(string uri) { // StartCoroutine(GetRequest(uri)); // } // IEnumerator GetRequest(string uri) { // using (UnityWebRequest webRequest = UnityWebRequest.Get(uri)) // { // // Request and wait for the desired page. // yield return webRequest.SendWebRequest(); // string[] pages = uri.Split('/'); // int page = pages.Length - 1; // if (webRequest.isNetworkError) // { // Debug.Log(pages[page] + ": Error: " + webRequest.error); // } // else // { // gameData = JsonUtility.FromJson<GameData>(webRequest.downloadHandler.text); // Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text); // } // } // } // IEnumerator SendWebRequest(UnityWebRequest webRequest) { // yield return webRequest.SendWebRequest(); // } // Returns true on success bool GetRequest(string uri) { UnityWebRequest webRequest = UnityWebRequest.Get(uri); webRequest.SendWebRequest(); float timeToFinish = Time.realtimeSinceStartup + 5; // stall until the webrequest is done or 5 seconds have elapsed while(!webRequest.isDone) { if(timeToFinish - Time.realtimeSinceStartup < 0) { throw new FileLoadException("LevelLoader: Couldn't load Game Data in 5 seconds"); } } string[] pages = uri.Split('/'); int page = pages.Length - 1; if (webRequest.isNetworkError) { //Debug.Log(pages[page] + ": Error: " + webRequest.error); throw new FileLoadException("LevelLoader: webRequest network error"); } else { gameData = JsonUtility.FromJson<GameData>(webRequest.downloadHandler.text); //Debug.Log("webRequest.text: " + webRequest.downloadHandler.text); } return true; } }
26.741463
134
0.683327
[ "MIT" ]
Nomadjackalope/elemental-breakout
Assets/Scripts/Game/LevelLoader.cs
5,484
C#
using System; using System.IO; using System.Threading.Tasks; using System.Xml.Serialization; using Osma.Mobile.App.Services.Interfaces; using Xamarin.Forms; namespace Osma.Mobile.App.Services { public class KeyValueStoreService : IKeyValueStoreService { public bool IsInitialized() => Application.Current != null; public Task SetDataAsync<T>(string key, T data, Serializer type = Serializer.Xml) { switch (type) { case Serializer.Xml: return SetDataAsyncXml(key, data); } return Task.FromResult(false); } private async Task SetDataAsyncXml<T>(string key, T data) { try { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (TextWriter writer = new StringWriter()) { serializer.Serialize(writer, data); await SetDataAsync(key, writer.ToString()); } } catch (Exception) { } } public Task SetDataAsync(string key, string data) { Application.Current.Properties[key] = data; return Application.Current.SavePropertiesAsync(); } public void SetData(string key, string data) => Application.Current.Properties[key] = data; public void SetData<T>(string key, T data, Serializer type = Serializer.Xml) { switch (type) { case Serializer.Xml: SetDataAsyncXml(key, data).Wait(); break; } } public string GetData(string key) => Application.Current.Properties[key] as string; public T GetData<T>(string key, Serializer type = Serializer.Xml) { switch (type) { case Serializer.Xml: return GetDataXml<T>(key); } return default(T); } private T GetDataXml<T>(string key) { try { string userXml = GetData(key); XmlSerializer serializer = new XmlSerializer(typeof(T)); using (TextReader reader = new StringReader(userXml)) { return (T)serializer.Deserialize(reader); } } catch (Exception) { return default(T); } } public bool DeleteData(string key) { if (!KeyExists(key)) return false; return Application.Current.Properties.Remove(key); } public async Task<bool> DeleteDataAsync(string key) { if (!KeyExists(key)) return false; if (Application.Current.Properties.Remove(key)) { await Application.Current.SavePropertiesAsync(); return true; } return false; } public bool KeyExists(string key) => Application.Current.Properties.ContainsKey(key); } }
28.990826
99
0.517722
[ "Apache-2.0" ]
Arsh-Sandhu/aries-mobileagent-xamarin
src/Osma.Mobile.App/Services/KeyValueStoreService.cs
3,162
C#
using Godot; using System; public class PlayerTrail : CPUParticles2D { // Called when the node enters the scene tree for the first time. public override void _Ready() { GD.Print("PlayerTrail::_Ready()"); } // Called every frame. 'delta' is the elapsed time since the previous frame. public override void _Process(float delta) { Player player = (Player)this.Owner; if (player.IsOnFloor()) { this.Emitting = true; // Note: we also turn off the trail in some state changes } else { this.Emitting = false; } // you can change gravity to pull the trail in different directions // this.Gravity = new Vector2(0, 0); } }
25.533333
80
0.587467
[ "Apache-2.0" ]
CodeCafeOpenShiftGame/PodEscape
src/Actors/Player/PlayerTrail.cs
766
C#
using System.Collections.Generic; using System.Linq; using System.Text; namespace SpeedrunComSharp { internal static class StringHelpers { internal static string ToParameters(this string parameters) { if (string.IsNullOrEmpty(parameters)) return ""; else return "?" + parameters; } internal static string ToParameters(this IEnumerable<string> parameters) { var list = parameters.Where(x => !string.IsNullOrEmpty(x)).ToList(); if (list.Any()) return "?" + list.Aggregate("&"); else return ""; } internal static string Aggregate(this IEnumerable<string> list, string combiner) { var builder = new StringBuilder(); foreach (var element in list) { builder.Append(element); builder.Append(combiner); } builder.Length -= combiner.Length; return builder.ToString(); } } }
25.809524
88
0.535978
[ "MIT" ]
Deecellar/Lessplit
SpeedrunDotComSharpStandard/StringHelpers.cs
1,086
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; namespace Microsoft.Azure.Functions.Worker.Diagnostics { internal class FunctionInvocationScope : IReadOnlyList<KeyValuePair<string, object>> { internal const string FunctionInvocationIdKey = "AzureFunctions_InvocationId"; internal const string FunctionNameKey = "AzureFunctions_FunctionName"; private readonly string _invocationId; private readonly string _functionName; private string? _cachedToString; public FunctionInvocationScope(string functionName, string invocationid) { _functionName = functionName; _invocationId = invocationid; } public KeyValuePair<string, object> this[int index] { get { return index switch { 0 => new KeyValuePair<string, object>(FunctionInvocationIdKey, _invocationId), 1 => new KeyValuePair<string, object>(FunctionNameKey, _functionName), _ => throw new ArgumentOutOfRangeException(nameof(index)), }; } } public int Count => 2; public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { for (var i = 0; i < Count; ++i) { yield return this[i]; } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public override string ToString() { if (_cachedToString == null) { _cachedToString = FormattableString.Invariant($"{FunctionNameKey}:{_functionName} {FunctionInvocationIdKey}:{_invocationId}"); } return _cachedToString; } } }
31.629032
142
0.608363
[ "MIT" ]
Azure/azure-functions-dotnet-worker
src/DotNetWorker.Core/Diagnostics/FunctionInvocationScope.cs
1,963
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Seclusion.Models; using Windows.UI.Xaml.Data; namespace Seclusion.Views { public class FromAbilityToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { if (value == null) { return ""; } switch((Ability)value) { case Ability.Deathtouch: return "Death Touch"; case Ability.Evolve: return "Evolve"; case Ability.FirstStrike: return "First Strike"; case Ability.Flying: return "Flying"; case Ability.Hexproof: return "Hexproof"; case Ability.Indestructible: return "Indestructible"; case Ability.Lifelink: return "Lifelink"; case Ability.Vigilence: return "Vigilence"; default: return ""; } } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotSupportedException(); } } }
24.842105
99
0.509181
[ "MIT" ]
slimCODE/slim-lib
src/samples/Seclusion/Seclusion.Shared/Views/FromAbilityToStringConverter.cs
1,418
C#
using System; using System.IO; using System.Linq; using System.Threading.Tasks; using LinqToTwitter; using LinqToTwitter.Common; namespace ConsoleDemo.CSharp { class AccountActivityDemos { internal static async Task RunAsync(TwitterContext twitterCtx) { char key; do { ShowMenu(); key = Console.ReadKey(true).KeyChar; switch (key) { case '0': Console.WriteLine("\n\tAdding Webhook...\n"); await AddWebhookAsync(twitterCtx); break; case '1': Console.WriteLine("\n\tListing Webhooks....\n"); await ListWebhooksAsync(twitterCtx); break; case '2': Console.WriteLine("\n\tDeleting Webhook...\n"); await DeleteWebhookAsync(twitterCtx); break; case '3': Console.WriteLine("\n\tSending Challenge Response Check...\n"); await SendChallengeResponseCheckAsync(twitterCtx); break; case '4': Console.WriteLine("\n\tAdding subscription...\n"); await AddSubscriptionAsync(twitterCtx); break; case '5': Console.WriteLine("\n\tShowing subscriptions...\n"); await ShowSubscriptionsAsync(twitterCtx); break; case '6': Console.WriteLine("\n\tDeleting subscription...\n"); await DeleteSubscriptionAsync(twitterCtx); break; case 'q': case 'Q': Console.WriteLine("\nReturning...\n"); break; default: Console.WriteLine(key + " is unknown"); break; } } while (char.ToUpper(key) != 'Q'); } static void ShowMenu() { Console.WriteLine("\nAccount Demos - Please select:\n"); Console.WriteLine("\t 0. Add Webhook"); Console.WriteLine("\t 1. List Webhooks"); Console.WriteLine("\t 2. Delete Webhook"); Console.WriteLine("\t 3. Send Challenge Response Check"); Console.WriteLine("\t 4. Add Subscription"); Console.WriteLine("\t 5. List Subscriptions"); Console.WriteLine("\t 6. Delete Subscription"); Console.WriteLine(); Console.Write("\t Q. Return to Main menu"); } static async Task AddWebhookAsync(TwitterContext twitterCtx) { try { Console.Write("What is the Webhook URL? "); string url = Console.ReadLine() ?? ""; AccountActivity? accAct = await twitterCtx.AddAccountActivityWebhookAsync(url); Webhook? webhook = accAct?.WebhooksValue?.Webhooks?.SingleOrDefault(); Console.WriteLine( $"Webhook for '{webhook?.Url}' " + $"added with ID: {webhook?.ID}, " + $"created at {webhook?.CreatedTimestamp}"); } catch (TwitterQueryException tqe) { Console.WriteLine(tqe.Message); } } static async Task ListWebhooksAsync(TwitterContext twitterCtx) { var webhooksResponse = await (from acct in twitterCtx.AccountActivity where acct.Type == AccountActivityType.Webhooks select acct) .SingleOrDefaultAsync(); if (webhooksResponse?.WebhooksValue?.Webhooks != null) { Console.WriteLine("Webhooks:"); if (webhooksResponse.WebhooksValue.Webhooks.Any()) foreach (var webhook in webhooksResponse.WebhooksValue.Webhooks) Console.WriteLine( $"ID: {webhook?.ID}, " + $"Created: {webhook?.CreatedTimestamp}, " + $"Valid: {webhook?.Valid}, " + $"URL: {webhook?.Url}"); else Console.WriteLine("No webhooks registered"); } } static async Task DeleteWebhookAsync(TwitterContext twitterCtx) { ulong webhookID = GetWebhook(); var acctActivity = await twitterCtx.DeleteAccountActivityWebhookAsync(webhookID); Console.WriteLine($"Webhook, {acctActivity?.WebhookID}, has been deleted."); } static async Task SendChallengeResponseCheckAsync(TwitterContext twitterCtx) { ulong webhookID = GetWebhook(); try { AccountActivity? accAct = await twitterCtx.SendAccountActivityCrcAsync(webhookID); Console.WriteLine("Challenge response check succeeded."); } catch (TwitterQueryException tqEx) // Twitter returns a 3XX when it can't delete, which throws { Console.WriteLine($"Challenge response check failed: {tqEx.Message}"); } } static async Task AddSubscriptionAsync(TwitterContext twitterCtx) { ulong webhookID = GetWebhook(); try { AccountActivity? accAct = await twitterCtx.AddAccountActivitySubscriptionAsync(webhookID); Console.WriteLine("Subscription added."); } catch (TwitterQueryException tqEx) // Twitter returns a 3XX or 4XX when it can't add, which throws { Console.WriteLine($"Unable to add subscription: {tqEx.Message}"); } } static async Task ShowSubscriptionsAsync(TwitterContext twitterCtx) { ulong webhookID = GetWebhook(); bool isSubscribed = false; try { var accAct = await (from act in twitterCtx.AccountActivity where act.Type == AccountActivityType.Subscriptions && act.WebhookID == webhookID select act) .SingleOrDefaultAsync(); isSubscribed = accAct?.SubscriptionValue?.IsSubscribed ?? false; Console.WriteLine($"IsSubscribed: {isSubscribed}"); } catch (TwitterQueryException) // Twitter returns a 4XX when not subscribed, which throws { Console.WriteLine("Your user account is not subscribed."); } } static async Task DeleteSubscriptionAsync(TwitterContext twitterCtx) { ulong webhookID = GetWebhook(); try { AccountActivity? accAct = await twitterCtx.DeleteAccountActivitySubscriptionAsync(webhookID); Console.WriteLine("Subscription deleted."); } catch (TwitterQueryException tqEx) // Twitter returns a 3XX when it can't delete, which throws { Console.WriteLine($"Unable to delete subscription: {tqEx.Message}"); } } /// <summary> /// Asks user for a webhook /// </summary> /// <remarks> /// Tip: Do AccountActivtyType.Webhooks query for a list of webhooks. /// </remarks> /// <returns>Webhook as ulong</returns> static ulong GetWebhook() { Console.Write("Webhook ID? "); string? webhookIDString = Console.ReadLine(); ulong.TryParse(webhookIDString, out ulong webhookID); return webhookID; } } }
36.147321
110
0.506113
[ "Apache-2.0" ]
JoeMayo/LinqToTwitter
Samples/LinqToTwitter6/Console/ConsoleDemo.CSharp/ConsoleDemo.CSharp/AccountActivityDemos.cs
8,099
C#
using System; namespace RI.Framework.Bus.Internals { /// <summary> /// Describes the state of a send operation. /// </summary> [Serializable] public enum SendOperationItemState { /// <summary> /// The send operation is newly created and is not yet processed. /// </summary> New = 0, /// <summary> /// The message has been sent and the send operation is waiting for response. /// </summary> Waiting = 1, /// <summary> /// The send operation finished successfully. /// </summary> Finished = 3, /// <summary> /// The send operation timed out. /// </summary> TimedOut = 4, /// <summary> /// The send operation was cancelled. /// </summary> Cancelled = 5, /// <summary> /// The send operation failed because at least one connection is broken and the message was intended to be sent globally. /// </summary> Broken = 6, /// <summary> /// The send operation failed because the receiver threw an exception during message processing and forwarded it to the sender. /// </summary> ForwardedException = 7, } }
22.1
133
0.630769
[ "Apache-2.0" ]
gosystemsgmbh/RI_Framework
RI.Framework.Common/Bus/Internals/SendOperationItemState.cs
1,107
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.VisualStudio.Web.CodeGeneration.Templating; using Microsoft.VisualStudio.Web.CodeGeneration.Test.Sources; using Moq; using Xunit; namespace Microsoft.VisualStudio.Web.CodeGeneration.Core.Test { public class CodeGeneratorActionsServiceTests { [Fact] public async Task AddFileFromTemplateAsync_Throws_If_Template_Is_Not_Found() { var mockFilesLocator = new Mock<IFilesLocator>(); var mockTemplating = new Mock<ITemplating>(); var codeGeneratorActionService = new CodeGeneratorActionsService( mockTemplating.Object, mockFilesLocator.Object, DefaultFileSystem.Instance); var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await codeGeneratorActionService.AddFileFromTemplateAsync("Dummy", "Template", new[] { "TemplateFolder1", "TemplateFolder2" }, null)); Assert.Equal("Template file Template not found within search paths TemplateFolder1;TemplateFolder2", ex.Message); } [Fact] public async Task AddFileFromTemplateAsync_Throws_If_Template_Processing_Has_Exceptions() { var mockFilesLocator = new Mock<IFilesLocator>(); var mockTemplating = new Mock<ITemplating>(); var mockFileSystem = new MockFileSystem(); var templateName = "TemplateName"; var templatePath = "C:\template.cshtml"; var templateContent = "TemplateContent"; var processingException = new TemplateProcessingException(new[] { "Error1" }, string.Empty); mockFilesLocator.Setup(fl => fl.GetFilePath(templateName, It.IsAny<IEnumerable<string>>())) .Returns(templatePath); mockFileSystem.WriteAllText(templatePath, templateContent); mockTemplating.Setup(templating => templating.RunTemplateAsync(templateContent, null)) .Returns(Task.FromResult(new TemplateResult() { ProcessingException = processingException })); var codeGeneratorActionService = new CodeGeneratorActionsService( mockTemplating.Object, mockFilesLocator.Object, mockFileSystem); var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await codeGeneratorActionService.AddFileFromTemplateAsync("Dummy", templateName, new[] { "TemplateFolder1", "TemplateFolder2" }, null)); Assert.Equal("There was an error running the template " + templatePath + ": Template Processing Failed:Error1", ex.Message); } [Fact] public async Task AddFileFromTemplateAsync_Writes_If_Template_Processing_Is_Successful() { var mockFilesLocator = new Mock<IFilesLocator>(); var mockTemplating = new Mock<ITemplating>(); var mockFileSystem = new MockFileSystem(); var templateName = "TemplateName"; var templatePath = "C:\template.cshtml"; var templateContent = "TemplateContent"; var outputPath = @"C:\Output.txt"; var generatedText = "GeneratedText"; mockFilesLocator.Setup(fl => fl.GetFilePath(templateName, It.IsAny<IEnumerable<string>>())) .Returns(templatePath); mockFileSystem.WriteAllText(templatePath, templateContent); mockTemplating.Setup(templating => templating.RunTemplateAsync(templateContent, null)) .Returns(Task.FromResult(new TemplateResult() { ProcessingException = null, GeneratedText = generatedText })); var codeGeneratorActionService = new CodeGeneratorActionsService( mockTemplating.Object, mockFilesLocator.Object, mockFileSystem); await codeGeneratorActionService.AddFileFromTemplateAsync(outputPath, templateName, new[] { "TemplateFolder1", "TemplateFolder2" }, null); Assert.True(mockFileSystem.FileExists(outputPath)); Assert.Equal(generatedText, mockFileSystem.ReadAllText(outputPath)); } } }
45.643564
136
0.643167
[ "Apache-2.0" ]
Arvinds-ds/Scaffolding
test/VS.Web.CG.Core.Test/CodeGeneratorActionsServiceTests.cs
4,610
C#
#region License // The PostgreSQL License // // Copyright (C) 2017 The Npgsql Development Team // // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose, without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph and the following two paragraphs appear in all copies. // // IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY // FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, // INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS // DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // // THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS // ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. #endregion using System; using System.Numerics; using System.Security.Cryptography; namespace Npgsql.Tls { internal static class RsaPKCS1 { public static bool VerifyRsaPKCS1(RSA key, byte[] signature, byte[] hash, bool allowNoPadding) { var parameters = key.ExportParameters(false); var e = Utils.BigIntegerFromBigEndian(parameters.Exponent, 0, parameters.Exponent.Length); var mod = Utils.BigIntegerFromBigEndian(parameters.Modulus, 0, parameters.Modulus.Length); var m = Utils.BigIntegerFromBigEndian(signature, 0, signature.Length); var decryptedArr = Utils.BigEndianFromBigInteger(BigInteger.ModPow(m, e, mod)); /* PKCS padding used in TLS 1.0/TLS 1.1: 00 01 [k-3-hashlen 0xff bytes] 00 (hash) OR, for only TLS 1.0, there may be no padding (or equivalently, 00 00 [k-3-hashlen 00 bytes] 00 (hash)) where k is the keylen */ if (allowNoPadding && decryptedArr.Length <= hash.Length) { var zeros = hash.Length - decryptedArr.Length; for (var i = 0; i < zeros; i++) { if (hash[i] != 0) return false; } return Utils.ArraysEqual(decryptedArr, 0, hash, zeros, hash.Length - zeros); } if (decryptedArr.Length != parameters.Modulus.Length - 1) return false; if (decryptedArr[0] != 1) return false; for (var i = 1; i < decryptedArr.Length - hash.Length - 1; i++) { if (decryptedArr[i] != 0xff) return false; } if (decryptedArr[decryptedArr.Length - hash.Length - 1] != 0) return false; return Utils.ArraysEqual(decryptedArr, decryptedArr.Length - hash.Length, hash, 0, hash.Length); } public static byte[] SignRsaPKCS1(RSA key, byte[] hash) { // NOTE: The X509Certificate2 must be initialized with the X509KeyStorageFlags.Exportable flag var parameters = key.ExportParameters(true); var dp = Utils.BigIntegerFromBigEndian(parameters.DP, 0, parameters.DP.Length); var dq = Utils.BigIntegerFromBigEndian(parameters.DQ, 0, parameters.DQ.Length); var qinv = Utils.BigIntegerFromBigEndian(parameters.InverseQ, 0, parameters.InverseQ.Length); var p = Utils.BigIntegerFromBigEndian(parameters.P, 0, parameters.P.Length); var q = Utils.BigIntegerFromBigEndian(parameters.Q, 0, parameters.Q.Length); var data = new byte[parameters.D.Length - 1]; data[0] = 1; for (var i = 1; i < data.Length - hash.Length - 1; i++) { data[i] = 0xff; } data[data.Length - hash.Length - 1] = 0; Buffer.BlockCopy(hash, 0, data, data.Length - hash.Length, hash.Length); var m = Utils.BigIntegerFromBigEndian(data, 0, data.Length); var m1 = BigInteger.ModPow(m, dp, p); var m2 = BigInteger.ModPow(m, dq, q); var h = qinv * (m1 - m2) % p; if (h.Sign == -1) h += p; var signature = Utils.BigEndianFromBigInteger(m2 + h * q); Utils.ClearArray(parameters.D); Utils.ClearArray(parameters.DP); Utils.ClearArray(parameters.DQ); Utils.ClearArray(parameters.InverseQ); Utils.ClearArray(parameters.P); Utils.ClearArray(parameters.Q); return signature; } } }
41.73913
115
0.6125
[ "MIT" ]
muhammet-kandemir-95/MA.Dal.Dao
MA.Dao.Generate.VSIX/MA.Dao.Generate.VSIX.App/Other Databases/Npgsql/Tls/RsaPKCS1.cs
4,800
C#
#region Licence /* The MIT License (MIT) Copyright © 2015 Ian Cooper <ian_hammond_cooper@yahoo.co.uk> 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. */ #endregion using System.Linq; using NUnit.Framework; using paramore.brighter.commandprocessor.tests.nunit.CommandProcessors.TestDoubles; using TinyIoC; namespace paramore.brighter.commandprocessor.tests.nunit.CommandProcessors { [TestFixture] public class PipelineBuilderAsyncTests { private PipelineBuilder<MyCommand> _pipelineBuilder; private IHandleRequestsAsync<MyCommand> _pipeline; [SetUp] public void Establish () { var registry = new SubscriberRegistry(); registry.RegisterAsync<MyCommand, MyImplicitHandlerAsync>(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIocHandlerFactoryAsync(container); container.Register<IHandleRequestsAsync<MyCommand>, MyImplicitHandlerAsync>(); container.Register<IHandleRequestsAsync<MyCommand>, MyLoggingHandlerAsync<MyCommand>>(); _pipelineBuilder = new PipelineBuilder<MyCommand>(registry, handlerFactory); } [Test] public void When_A_Handler_Is_Part_Of_An_Async_Pipeline() { _pipeline = _pipelineBuilder.BuildAsync(new RequestContext(), false).First(); Assert.True(TracePipeline().ToString().Contains("MyImplicitHandlerAsync")); Assert.True(TracePipeline().ToString().Contains("MyLoggingHandlerAsync")); } private PipelineTracer TracePipeline() { var pipelineTracer = new PipelineTracer(); _pipeline.DescribePath(pipelineTracer); return pipelineTracer; } } }
39.73913
100
0.731947
[ "MIT" ]
uQr/Paramore.Brighter
paramore.brighter.commandprocessor.tests.nunit/CommandProcessors/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs
2,753
C#
// <copyright file="Weibull.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2013 Math.NET // // 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. // </copyright> using System; using System.Collections.Generic; using System.Linq; using MathNet.Numerics.Random; using MathNet.Numerics.Threading; namespace MathNet.Numerics.Distributions { /// <summary> /// Continuous Univariate Weibull distribution. /// For details about this distribution, see /// <a href="http://en.wikipedia.org/wiki/Weibull_distribution">Wikipedia - Weibull distribution</a>. /// </summary> /// <remarks> /// The Weibull distribution is parametrized by a shape and scale parameter. /// </remarks> public class Weibull : IContinuousDistribution { System.Random _random; readonly double _shape; readonly double _scale; /// <summary> /// Reusable intermediate result 1 / (_scale ^ _shape) /// </summary> /// <remarks> /// By caching this parameter we can get slightly better numerics precision /// in certain constellations without any additional computations. /// </remarks> readonly double _scalePowShapeInv; /// <summary> /// Initializes a new instance of the Weibull class. /// </summary> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> public Weibull(double shape, double scale) { if (!IsValidParameterSet(shape, scale)) { throw new ArgumentException("Invalid parametrization for the distribution."); } _random = SystemRandomSource.Default; _shape = shape; _scale = scale; _scalePowShapeInv = Math.Pow(scale, -shape); } /// <summary> /// Initializes a new instance of the Weibull class. /// </summary> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> /// <param name="randomSource">The random number generator which is used to draw random samples.</param> public Weibull(double shape, double scale, System.Random randomSource) { if (!IsValidParameterSet(shape, scale)) { throw new ArgumentException("Invalid parametrization for the distribution."); } _random = randomSource ?? SystemRandomSource.Default; _shape = shape; _scale = scale; _scalePowShapeInv = Math.Pow(scale, -shape); } /// <summary> /// A string representation of the distribution. /// </summary> /// <returns>a string representation of the distribution.</returns> public override string ToString() { return $"Weibull(k = {_shape}, λ = {_scale})"; } /// <summary> /// Tests whether the provided values are valid parameters for this distribution. /// </summary> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> public static bool IsValidParameterSet(double shape, double scale) { return shape > 0.0 && scale > 0.0; } /// <summary> /// Gets the shape (k) of the Weibull distribution. Range: k > 0. /// </summary> public double Shape => _shape; /// <summary> /// Gets the scale (λ) of the Weibull distribution. Range: λ > 0. /// </summary> public double Scale => _scale; /// <summary> /// Gets or sets the random number generator which is used to draw random samples. /// </summary> public System.Random RandomSource { get => _random; set => _random = value ?? SystemRandomSource.Default; } /// <summary> /// Gets the mean of the Weibull distribution. /// </summary> public double Mean => _scale*SpecialFunctions.Gamma(1.0 + (1.0/_shape)); /// <summary> /// Gets the variance of the Weibull distribution. /// </summary> public double Variance => (_scale*_scale*SpecialFunctions.Gamma(1.0 + (2.0/_shape))) - (Mean*Mean); /// <summary> /// Gets the standard deviation of the Weibull distribution. /// </summary> public double StdDev => Math.Sqrt(Variance); /// <summary> /// Gets the entropy of the Weibull distribution. /// </summary> public double Entropy => (Constants.EulerMascheroni*(1.0 - (1.0/_shape))) + Math.Log(_scale/_shape) + 1.0; /// <summary> /// Gets the skewness of the Weibull distribution. /// </summary> public double Skewness { get { double mu = Mean; double sigma = StdDev; double sigma2 = sigma*sigma; double sigma3 = sigma2*sigma; return ((_scale*_scale*_scale*SpecialFunctions.Gamma(1.0 + (3.0/_shape))) - (3.0*sigma2*mu) - (mu*mu*mu))/sigma3; } } /// <summary> /// Gets the mode of the Weibull distribution. /// </summary> public double Mode { get { if (_shape <= 1.0) { return 0.0; } return _scale*Math.Pow((_shape - 1.0)/_shape, 1.0/_shape); } } /// <summary> /// Gets the median of the Weibull distribution. /// </summary> public double Median => _scale*Math.Pow(Constants.Ln2, 1.0/_shape); /// <summary> /// Gets the minimum of the Weibull distribution. /// </summary> public double Minimum => 0.0; /// <summary> /// Gets the maximum of the Weibull distribution. /// </summary> public double Maximum => double.PositiveInfinity; /// <summary> /// Computes the probability density of the distribution (PDF) at x, i.e. ∂P(X ≤ x)/∂x. /// </summary> /// <param name="x">The location at which to compute the density.</param> /// <returns>the density at <paramref name="x"/>.</returns> public double Density(double x) { if (x >= 0.0) { if (x == 0.0 && _shape == 1.0) { return _shape/_scale; } return _shape*Math.Pow(x/_scale, _shape - 1.0)*Math.Exp(-Math.Pow(x, _shape)*_scalePowShapeInv)/_scale; } return 0.0; } /// <summary> /// Computes the log probability density of the distribution (lnPDF) at x, i.e. ln(∂P(X ≤ x)/∂x). /// </summary> /// <param name="x">The location at which to compute the log density.</param> /// <returns>the log density at <paramref name="x"/>.</returns> public double DensityLn(double x) { if (x >= 0.0) { if (x == 0.0 && _shape == 1.0) { return Math.Log(_shape) - Math.Log(_scale); } return Math.Log(_shape) + ((_shape - 1.0)*Math.Log(x/_scale)) - (Math.Pow(x, _shape)*_scalePowShapeInv) - Math.Log(_scale); } return double.NegativeInfinity; } /// <summary> /// Computes the cumulative distribution (CDF) of the distribution at x, i.e. P(X ≤ x). /// </summary> /// <param name="x">The location at which to compute the cumulative distribution function.</param> /// <returns>the cumulative distribution at location <paramref name="x"/>.</returns> public double CumulativeDistribution(double x) { if (x < 0.0) { return 0.0; } return -SpecialFunctions.Expm1(-Math.Pow(x, _shape)*_scalePowShapeInv); } /// <summary> /// Generates a sample from the Weibull distribution. /// </summary> /// <returns>a sample from the distribution.</returns> public double Sample() { return SampleUnchecked(_random, _shape, _scale); } /// <summary> /// Fills an array with samples generated from the distribution. /// </summary> public void Samples(double[] values) { SamplesUnchecked(_random, values, _shape, _scale); } /// <summary> /// Generates a sequence of samples from the Weibull distribution. /// </summary> /// <returns>a sequence of samples from the distribution.</returns> public IEnumerable<double> Samples() { return SamplesUnchecked(_random, _shape, _scale); } static double SampleUnchecked(System.Random rnd, double shape, double scale) { var x = rnd.NextDouble(); return scale*Math.Pow(-Math.Log(x), 1.0/shape); } static IEnumerable<double> SamplesUnchecked(System.Random rnd, double shape, double scale) { var exponent = 1.0/shape; return rnd.NextDoubleSequence().Select(x => scale*Math.Pow(-Math.Log(x), exponent)); } static void SamplesUnchecked(System.Random rnd, double[] values, double shape, double scale) { var exponent = 1.0/shape; rnd.NextDoubles(values); CommonParallel.For(0, values.Length, 4096, (a, b) => { for (int i = a; i < b; i++) { values[i] = scale*Math.Pow(-Math.Log(values[i]), exponent); } }); } /// <summary> /// Computes the probability density of the distribution (PDF) at x, i.e. ∂P(X ≤ x)/∂x. /// </summary> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> /// <param name="x">The location at which to compute the density.</param> /// <returns>the density at <paramref name="x"/>.</returns> /// <seealso cref="Density"/> public static double PDF(double shape, double scale, double x) { if (shape <= 0.0 || scale <= 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } if (x >= 0.0) { if (x == 0.0 && shape == 1.0) { return shape/scale; } return shape *Math.Pow(x/scale, shape - 1.0) *Math.Exp(-Math.Pow(x, shape)*Math.Pow(scale, -shape)) /scale; } return 0.0; } /// <summary> /// Computes the log probability density of the distribution (lnPDF) at x, i.e. ln(∂P(X ≤ x)/∂x). /// </summary> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> /// <param name="x">The location at which to compute the density.</param> /// <returns>the log density at <paramref name="x"/>.</returns> /// <seealso cref="DensityLn"/> public static double PDFLn(double shape, double scale, double x) { if (shape <= 0.0 || scale <= 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } if (x >= 0.0) { if (x == 0.0 && shape == 1.0) { return Math.Log(shape) - Math.Log(scale); } return Math.Log(shape) + ((shape - 1.0)*Math.Log(x/scale)) - (Math.Pow(x, shape)*Math.Pow(scale, -shape)) - Math.Log(scale); } return double.NegativeInfinity; } /// <summary> /// Computes the cumulative distribution (CDF) of the distribution at x, i.e. P(X ≤ x). /// </summary> /// <param name="x">The location at which to compute the cumulative distribution function.</param> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> /// <returns>the cumulative distribution at location <paramref name="x"/>.</returns> /// <seealso cref="CumulativeDistribution"/> public static double CDF(double shape, double scale, double x) { if (shape <= 0.0 || scale <= 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } if (x < 0.0) { return 0.0; } return -SpecialFunctions.Expm1(-Math.Pow(x, shape)*Math.Pow(scale, -shape)); } /// <summary> /// Implemented according to: Parameter estimation of the Weibull probability distribution, 1994, Hongzhu Qiao, Chris P. Tsokos /// </summary> /// <param name="samples"></param> /// <param name="randomSource"></param> /// <returns>Returns a Weibull distribution.</returns> public static Weibull Estimate(IEnumerable<double> samples, System.Random randomSource = null) { var samp = samples as double[] ?? samples.ToArray(); double n = samp.Length, s1, s2, s3, previousC = int.MinValue, QofC; if (n <= 1) throw new Exception("Observations not sufficient"); // Start values double c = 10; double b = 0; while (Math.Abs(c - previousC) >= 0.0001) { s1 = s2 = s3 = 0; foreach (double x in samp) { if (x > 0) { s1 += Math.Log(x); s2 += Math.Pow(x, c); s3 += Math.Pow(x, c) * Math.Log(x); } } QofC = n * s2 / (n * s3 - s1 * s2); previousC = c; c = (c + QofC) / 2; } foreach (double x in samp) { if (x > 0) { b += Math.Pow(x, c); } } b = Math.Pow(b / n, 1 / c); return new Weibull(c, b, randomSource); } /// <summary> /// Generates a sample from the Weibull distribution. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> /// <returns>a sample from the distribution.</returns> public static double Sample(System.Random rnd, double shape, double scale) { if (shape <= 0.0 || scale <= 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } return SampleUnchecked(rnd, shape, scale); } /// <summary> /// Generates a sequence of samples from the Weibull distribution. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> /// <returns>a sequence of samples from the distribution.</returns> public static IEnumerable<double> Samples(System.Random rnd, double shape, double scale) { if (shape <= 0.0 || scale <= 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } return SamplesUnchecked(rnd, shape, scale); } /// <summary> /// Fills an array with samples generated from the distribution. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="values">The array to fill with the samples.</param> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> /// <returns>a sequence of samples from the distribution.</returns> public static void Samples(System.Random rnd, double[] values, double shape, double scale) { if (shape <= 0.0 || scale <= 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } SamplesUnchecked(rnd, values, shape, scale); } /// <summary> /// Generates a sample from the Weibull distribution. /// </summary> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> /// <returns>a sample from the distribution.</returns> public static double Sample(double shape, double scale) { if (shape <= 0.0 || scale <= 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } return SampleUnchecked(SystemRandomSource.Default, shape, scale); } /// <summary> /// Generates a sequence of samples from the Weibull distribution. /// </summary> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> /// <returns>a sequence of samples from the distribution.</returns> public static IEnumerable<double> Samples(double shape, double scale) { if (shape <= 0.0 || scale <= 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } return SamplesUnchecked(SystemRandomSource.Default, shape, scale); } /// <summary> /// Fills an array with samples generated from the distribution. /// </summary> /// <param name="values">The array to fill with the samples.</param> /// <param name="shape">The shape (k) of the Weibull distribution. Range: k > 0.</param> /// <param name="scale">The scale (λ) of the Weibull distribution. Range: λ > 0.</param> /// <returns>a sequence of samples from the distribution.</returns> public static void Samples(double[] values, double shape, double scale) { if (shape <= 0.0 || scale <= 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } SamplesUnchecked(SystemRandomSource.Default, values, shape, scale); } } }
38.620626
139
0.545897
[ "MIT" ]
WeihanLi/mathnet-numerics
src/Numerics/Distributions/Weibull.cs
21,028
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; namespace Amazon.PowerShell.Cmdlets.SNS { /// <summary> /// Subscribes an endpoint to an Amazon SNS topic. If the endpoint type is HTTP/S or email, /// or if the endpoint and the topic are not in the same account, the endpoint owner must /// run the <code>ConfirmSubscription</code> action to confirm the subscription. /// /// /// <para> /// You call the <code>ConfirmSubscription</code> action with the token from the subscription /// response. Confirmation tokens are valid for three days. /// </para><para> /// This action is throttled at 100 transactions per second (TPS). /// </para> /// </summary> [Cmdlet("Connect", "SNSNotification", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("System.String")] [AWSCmdlet("Calls the Amazon Simple Notification Service (SNS) Subscribe API operation.", Operation = new[] {"Subscribe"}, SelectReturnType = typeof(Amazon.SimpleNotificationService.Model.SubscribeResponse))] [AWSCmdletOutput("System.String or Amazon.SimpleNotificationService.Model.SubscribeResponse", "This cmdlet returns a System.String object.", "The service call response (type Amazon.SimpleNotificationService.Model.SubscribeResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class ConnectSNSNotificationCmdlet : AmazonSimpleNotificationServiceClientCmdlet, IExecutor { #region Parameter Attribute /// <summary> /// <para> /// <para>A map of attributes with their corresponding values.</para><para>The following lists the names, descriptions, and values of the special request parameters /// that the <code>Subscribe</code> action uses:</para><ul><li><para><code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries failed /// deliveries to HTTP/S endpoints.</para></li><li><para><code>FilterPolicy</code> – The simple JSON object that lets your subscriber receive /// only a subset of messages, rather than receiving every message published to the topic.</para></li><li><para><code>RawMessageDelivery</code> – When set to <code>true</code>, enables raw message /// delivery to Amazon SQS or HTTP/S endpoints. This eliminates the need for the endpoints /// to process JSON formatting, which is otherwise created for Amazon SNS metadata.</para></li><li><para><code>RedrivePolicy</code> – When specified, sends undeliverable messages to the /// specified Amazon SQS dead-letter queue. Messages that can't be delivered due to client /// errors (for example, when the subscribed endpoint is unreachable) or server errors /// (for example, when the service that powers the subscribed endpoint becomes unavailable) /// are held in the dead-letter queue for further analysis or reprocessing.</para></li></ul><para>The following attribute applies only to Amazon Kinesis Data Firehose delivery stream /// subscriptions:</para><ul><li><para><code>SubscriptionRoleArn</code> – The ARN of the IAM role that has the following:</para><ul><li><para>Permission to write to the Kinesis Data Firehose delivery stream</para></li><li><para>Amazon SNS listed as a trusted entity</para></li></ul><para>Specifying a valid ARN for this attribute is required for Kinesis Data Firehose delivery /// stream subscriptions. For more information, see <a href="https://docs.aws.amazon.com/sns/latest/dg/sns-firehose-as-subscriber.html">Fanout /// to Kinesis Data Firehose delivery streams</a> in the <i>Amazon SNS Developer Guide</i>.</para></li></ul> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Attributes")] public System.Collections.Hashtable Attribute { get; set; } #endregion #region Parameter Endpoint /// <summary> /// <para> /// <para>The endpoint that you want to receive notifications. Endpoints vary by protocol:</para><ul><li><para>For the <code>http</code> protocol, the (public) endpoint is a URL beginning with /// <code>http://</code>.</para></li><li><para>For the <code>https</code> protocol, the (public) endpoint is a URL beginning with /// <code>https://</code>.</para></li><li><para>For the <code>email</code> protocol, the endpoint is an email address.</para></li><li><para>For the <code>email-json</code> protocol, the endpoint is an email address.</para></li><li><para>For the <code>sms</code> protocol, the endpoint is a phone number of an SMS-enabled /// device.</para></li><li><para>For the <code>sqs</code> protocol, the endpoint is the ARN of an Amazon SQS queue.</para></li><li><para>For the <code>application</code> protocol, the endpoint is the EndpointArn of a mobile /// app and device.</para></li><li><para>For the <code>lambda</code> protocol, the endpoint is the ARN of an Lambda function.</para></li><li><para>For the <code>firehose</code> protocol, the endpoint is the ARN of an Amazon Kinesis /// Data Firehose delivery stream.</para></li></ul> /// </para> /// </summary> [System.Management.Automation.Parameter(Position = 2, ValueFromPipelineByPropertyName = true)] public System.String Endpoint { get; set; } #endregion #region Parameter Protocol /// <summary> /// <para> /// <para>The protocol that you want to use. Supported protocols include:</para><ul><li><para><code>http</code> – delivery of JSON-encoded message via HTTP POST</para></li><li><para><code>https</code> – delivery of JSON-encoded message via HTTPS POST</para></li><li><para><code>email</code> – delivery of message via SMTP</para></li><li><para><code>email-json</code> – delivery of JSON-encoded message via SMTP</para></li><li><para><code>sms</code> – delivery of message via SMS</para></li><li><para><code>sqs</code> – delivery of JSON-encoded message to an Amazon SQS queue</para></li><li><para><code>application</code> – delivery of JSON-encoded message to an EndpointArn for /// a mobile app and device</para></li><li><para><code>lambda</code> – delivery of JSON-encoded message to an Lambda function</para></li><li><para><code>firehose</code> – delivery of JSON-encoded message to an Amazon Kinesis Data /// Firehose delivery stream.</para></li></ul> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(Position = 1, ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String Protocol { get; set; } #endregion #region Parameter ReturnSubscriptionArn /// <summary> /// <para> /// <para>Sets whether the response from the <code>Subscribe</code> request includes the subscription /// ARN, even if the subscription is not yet confirmed.</para><para>If you set this parameter to <code>true</code>, the response includes the ARN in all /// cases, even if the subscription is not yet confirmed. In addition to the ARN for confirmed /// subscriptions, the response also includes the <code>pending subscription</code> ARN /// value for subscriptions that aren't yet confirmed. A subscription becomes confirmed /// when the subscriber calls the <code>ConfirmSubscription</code> action with a confirmation /// token.</para><para>The default value is <code>false</code>.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Boolean? ReturnSubscriptionArn { get; set; } #endregion #region Parameter TopicArn /// <summary> /// <para> /// <para>The ARN of the topic you want to subscribe to.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String TopicArn { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'SubscriptionArn'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.SimpleNotificationService.Model.SubscribeResponse). /// Specifying the name of a property of type Amazon.SimpleNotificationService.Model.SubscribeResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "SubscriptionArn"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the TopicArn parameter. /// The -PassThru parameter is deprecated, use -Select '^TopicArn' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^TopicArn' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.TopicArn), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Connect-SNSNotification (Subscribe)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.SimpleNotificationService.Model.SubscribeResponse, ConnectSNSNotificationCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.TopicArn; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute if (this.Attribute != null) { context.Attribute = new Dictionary<System.String, System.String>(StringComparer.Ordinal); foreach (var hashKey in this.Attribute.Keys) { context.Attribute.Add((String)hashKey, (String)(this.Attribute[hashKey])); } } context.Endpoint = this.Endpoint; context.Protocol = this.Protocol; #if MODULAR if (this.Protocol == null && ParameterWasBound(nameof(this.Protocol))) { WriteWarning("You are passing $null as a value for parameter Protocol which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.ReturnSubscriptionArn = this.ReturnSubscriptionArn; context.TopicArn = this.TopicArn; #if MODULAR if (this.TopicArn == null && ParameterWasBound(nameof(this.TopicArn))) { WriteWarning("You are passing $null as a value for parameter TopicArn which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.SimpleNotificationService.Model.SubscribeRequest(); if (cmdletContext.Attribute != null) { request.Attributes = cmdletContext.Attribute; } if (cmdletContext.Endpoint != null) { request.Endpoint = cmdletContext.Endpoint; } if (cmdletContext.Protocol != null) { request.Protocol = cmdletContext.Protocol; } if (cmdletContext.ReturnSubscriptionArn != null) { request.ReturnSubscriptionArn = cmdletContext.ReturnSubscriptionArn.Value; } if (cmdletContext.TopicArn != null) { request.TopicArn = cmdletContext.TopicArn; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.SimpleNotificationService.Model.SubscribeResponse CallAWSServiceOperation(IAmazonSimpleNotificationService client, Amazon.SimpleNotificationService.Model.SubscribeRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Simple Notification Service (SNS)", "Subscribe"); try { #if DESKTOP return client.Subscribe(request); #elif CORECLR return client.SubscribeAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public Dictionary<System.String, System.String> Attribute { get; set; } public System.String Endpoint { get; set; } public System.String Protocol { get; set; } public System.Boolean? ReturnSubscriptionArn { get; set; } public System.String TopicArn { get; set; } public System.Func<Amazon.SimpleNotificationService.Model.SubscribeResponse, ConnectSNSNotificationCmdlet, object> Select { get; set; } = (response, cmdlet) => response.SubscriptionArn; } } }
56.029762
685
0.636088
[ "Apache-2.0" ]
aws/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/SimpleNotificationService/Basic/Connect-SNSNotification-Cmdlet.cs
18,854
C#
// ===================================================================== // <copyright file="Program.cs" company="Advanced Micro Devices, Inc."> // Copyright (c) 2011-2019 Advanced Micro Devices, Inc. All rights reserved. // </copyright> // <author> // AMD Developer Tools Team // </author> // <summary> // Given an ordered internal counter definition file and the derived (e.g.: public) // definitions, produces c++ code to define them for the run-time. // </summary> // ===================================================================== namespace PublicCounterCompiler { using System; using System.Collections.Generic; using System.IO; using System.Windows.Forms; using System.Diagnostics; /// <summary> /// A program which compiles the derived counters definitions into C++ files. /// </summary> public class Program { /// <summary> /// The main entry point to the program. /// </summary> /// <param name="args">cmd line arguments</param> [STAThread] public static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // set output paths const string compilerOutputFolder = "output\\"; int endPath = Application.StartupPath.IndexOf(compilerOutputFolder) + compilerOutputFolder.Length; if (compilerOutputFolder.Length == endPath) { MessageBox.Show(Application.ProductName + " was started out of unexpected folder.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string gpaPath = GPATools.Gpa.GetGpuPerfApiPath(); // Derived counter definition input var counterCompiler = new CounterCompiler(); CounterCompiler.DerivedCounterFileInput counterPath = new CounterCompiler.DerivedCounterFileInput { rootFilename = GPATools.Gpa.public_file_prefix, compiler_type_str = GPATools.Gpa.PublicStr, compilerInputPath = gpaPath + GPATools.Gpa.CounterDefDir, autoGenCompilerInputFilePath = gpaPath + GPATools.Gpa.AutoGenPublicCounterInputDir, outputDirectory = gpaPath + GPATools.Gpa.AutoGenCounterGeneratorOutDir, counterListOutputDirectory = gpaPath + GPATools.Gpa.CounterListOutDir, testOutputDirectory = gpaPath + GPATools.Gpa.AutoGenTestOutDir }; counterCompiler.derivedCounterFileInput = counterPath; var form = Form1.Instance(counterCompiler); // handle operational mode if (args.Length == 0) { counterCompiler.isConsoleApp = false; Application.Run(form); GPATools.CMakeGenerator.Init = GPATools.CounterDefCMakeGenerator.Init; GPATools.CMakeGenerator.ProcessFile = GPATools.CounterDefCMakeGenerator.ProcessFiles; GPATools.CMakeGenerator.CMakeWriter = GPATools.CounterDefCMakeGenerator.CMakeWriter; GPATools.CMakeGenerator.AddDirectory(GPATools.Gpa.GetGpuPerfApiPath() + "GPA\\source\\auto_generated"); GPATools.CMakeGenerator.GenerateCMakeFiles(); return; } if (args.Length == 2 || args.Length == 7 || args.Length == 8) { // We can do this! } else { Console.WriteLine("Usage: PublicCounterCompiler.exe"); Console.WriteLine(" - using no parameters will open the user interface"); Console.WriteLine("Usage: PublicCounterCompiler [API] [HW generation]"); Console.WriteLine( " opens the user interface and populates the input fields with the following parameters:"); Console.WriteLine(" [API] - the API to compile counters for (ex: GL, CL, DX11, etc)"); Console.WriteLine( " [HW generation] - the generation to compile counters for (ex: R10xx, R11xx, R12xx, etc)"); Console.WriteLine( "Usage: PublicCounterCompiler [counter names file] [Public counter definition file] [output dir] [API] [GPU]"); Console.WriteLine( " [counter names file] - text file containing hardware counter names and type (CounterNames[API][GEN].txt)"); Console.WriteLine( " [Public counter definition file] - text file defining how the public counters are calculated (PublicCounterDefinitions*.txt)"); Console.WriteLine( " [Output Dir] - the directory to generate the output in (Ex: the path to the Src/GPUPerfAPICounterGenerator directory)"); Console.WriteLine( " [Counter List Output Dir] - the directory to generate the counter list text files in (Ex: the path to the Output/CounterListFiles directory)"); Console.WriteLine( " [Test output Dir] - the directory to generate the test output in (Ex: the path to the Src/GPUPerfAPIUnitTests/counters directory)"); Console.WriteLine( " [API] - the API to compile counters for (ex: GL, CL, DX11, etc)"); Console.WriteLine( " [HW generation] - the generation to compile counters for (ex: R10xx, R11xx, R12xx, etc)"); Console.WriteLine( " {ASIC} - name of the ASIC (ex: baffin)"); return; } if (args.Length == 2) { counterCompiler.isConsoleApp = false; form.apiName.Text = args[0]; form.GPUFamily.Text = args[1]; Application.Run(form); GPATools.CMakeGenerator.Init = GPATools.CounterDefCMakeGenerator.Init; GPATools.CMakeGenerator.ProcessFile = GPATools.CounterDefCMakeGenerator.ProcessFiles; GPATools.CMakeGenerator.CMakeWriter = GPATools.CounterDefCMakeGenerator.CMakeWriter; GPATools.CMakeGenerator.AddDirectory(GPATools.Gpa.GetGpuPerfApiPath() + "GPA\\source\\auto_generated"); GPATools.CMakeGenerator.GenerateCMakeFiles(); } else if (args.Length == 7) { counterCompiler.LoadFilesAndGenerateOutput("Public", args[0], args[1], args[2], args[3], args[4], args[5], args[6], string.Empty, form.DisplayMessageHandler, form.ErrorHandler); } else if (args.Length == 8) { counterCompiler.LoadFilesAndGenerateOutput("Public", args[0], args[1], args[2], args[3], args[4], args[5], args[6], "_" + args[7], form.DisplayMessageHandler, form.ErrorHandler); } } } }
49.609929
194
0.586991
[ "MIT" ]
jdrouan-goog/gpu_performance_api
source/public_counter_compiler/program.cs
6,995
C#
using System; using OSharp.Data.Entity; using OSharp.Core.Security; namespace OSharp.Demo.Consoles.EntityConfigurations { public class FunctionConfiguration : EntityConfigurationBase<Function, Guid> { } }
17
80
0.764706
[ "Apache-2.0" ]
VictorTzeng/osharp
samples/OSharp.Demo.Consoles/EntityConfigurations/FunctionConfiguration.cs
223
C#
namespace WarMachine.Engine { using Interfaces; using Models; public class MachineFactory : IMachineFactory { public IPilot HirePilot(string name) { var pilot = new Pilot(name); return pilot; } public IFighter ManufactureFighter(string name, double attackPoints, double defensePoints, bool stealthMode) { IFighter fighter = new Fighter(name, attackPoints, defensePoints, stealthMode); return fighter; } public ITank ManufactureTank(string name, double attackPoints, double defensePoints) { var tank = new Tank(name, attackPoints, defensePoints); return tank; } } }
27.148148
116
0.61528
[ "MIT" ]
VVoev/Telerik-Academy
05.C#ObjectOrientedProgramming/ExamPreparation/OOP12Dec2013/WarMachine/Engine/MachineFactory.cs
735
C#
using System.Runtime.Serialization; using System.Text.Json.Serialization; #pragma warning disable 1591 namespace Plotly.Models.Traces.ScatterMapBoxs.Markers.ColorBars { /// <summary> /// Same as <c>showtickprefix</c> but for tick suffixes. /// </summary> [JsonConverter(typeof(EnumConverter))] public enum ShowTickSuffixEnum { [EnumMember(Value = @"all")] All = 0, [EnumMember(Value = @"first")] First, [EnumMember(Value = @"last")] Last, [EnumMember(Value = @"none")] None } }
21.444444
64
0.606218
[ "MIT" ]
trmcnealy/Plotly.WPF
Plotly/Models/Traces/ScatterMapBoxs/Markers/ColorBars/ShowTickSuffixEnum.cs
579
C#
namespace VaporStore.Data.Models.Enums { public enum CardType { Debit, Credit } }
13.75
39
0.572727
[ "MIT" ]
BorisLechev/C-DB
Entity Framework Core/Exams/01.09.2018/VaporStore/Data/Models/Enums/CardType.cs
112
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Quaver.API.Enums; using Quaver.Shared.Config; using Quaver.Shared.Database.Maps; using Quaver.Shared.Graphics; using Quaver.Shared.Graphics.Form.Dropdowns; using Quaver.Shared.Graphics.Form.Dropdowns.Custom; using Quaver.Shared.Helpers; using Quaver.Shared.Scheduling; using Wobble.Bindables; using Wobble.Graphics; namespace Quaver.Shared.Screens.Selection.UI.FilterPanel.Dropdowns { public class FilterDropdownGroupBy : LabelledDropdown { /// <summary> /// The mapsets that are available to select /// </summary> private Bindable<List<Mapset>> AvailableMapsets { get; } /// <inheritdoc /> /// <summary> /// </summary> /// <param name="availableMapsets"></param> public FilterDropdownGroupBy(Bindable<List<Mapset>> availableMapsets) : base("GROUP BY: ", 22, new Dropdown(GetDropdownItems(), new ScalableVector2(125, 38), 22, ColorHelper.HexToColor($"#10C8F6"), GetSelectedIndex())) { AvailableMapsets = availableMapsets; Dropdown.ItemSelected += OnItemSelected; ConfigManager.SelectGroupMapsetsBy.ValueChanged += OnGroupingChanged; } /// <inheritdoc /> /// <summary> /// </summary> public override void Destroy() { // ReSharper disable once DelegateSubtraction ConfigManager.SelectGroupMapsetsBy.ValueChanged -= OnGroupingChanged; base.Destroy(); } /// <summary> /// </summary> /// <returns></returns> private static List<string> GetDropdownItems() => new List<string> { "None", "Playlists", }; /// <summary> /// Retrieves the index of the selected value /// </summary> /// <returns></returns> private static int GetSelectedIndex() { if (ConfigManager.SelectGroupMapsetsBy == null) return 0; return (int) ConfigManager.SelectGroupMapsetsBy.Value; } /// <summary> /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnItemSelected(object sender, DropdownClickedEventArgs e) { if (ConfigManager.SelectGroupMapsetsBy == null) return; ConfigManager.SelectGroupMapsetsBy.Value = (GroupMapsetsBy) e.Index; } /// <summary> /// Called when <see cref="ConfigManager.SelectGroupMapsetsBy"/> has changed, so the state /// of the dropdown can be updated. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <exception cref="NotImplementedException"></exception> private void OnGroupingChanged(object sender, BindableValueChangedEventArgs<GroupMapsetsBy> e) { Dropdown.SelectedIndex = (int) e.Value; Dropdown.SelectedText.Text = Dropdown.Options[(int) e.Value]; Dropdown.Close(); } } }
33.515789
135
0.602701
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Adrriii/Quaver
Quaver.Shared/Screens/Selection/UI/FilterPanel/Dropdowns/FilterDropdownGroupBy.cs
3,184
C#
namespace Logger.Interfaces { public interface ILayout { string FormatError(IError error); } }
14.5
41
0.646552
[ "MIT" ]
DimchoLakov/CSharpOOPAdvanced
01.SOLID - Exercise/Logger/Interfaces/ILayout.cs
118
C#
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using System; using System.Collections.Generic; using ClearCanvas.Common.Utilities; using ClearCanvas.Desktop; using ClearCanvas.Desktop.Tables; using ClearCanvas.Desktop.Trees; namespace ClearCanvas.Ris.Client { /// <summary> /// Represents a node in a folder explorer tree. /// </summary> internal class FolderTreeNode { #region ContainerFolder /// <summary> /// A folder that acts strictly as a parent for other folders, and does not itself contain any items. /// </summary> internal class ContainerFolder : Folder { private readonly Table<object> _itemsTable; public ContainerFolder(Path path, bool startExpanded) : base(path, startExpanded) { _itemsTable = new Table<object>(); } protected override bool IsItemCountKnown { get { return true; } } public override string Text { get { return this.FolderPath.LastSegment.LocalizedText; } } protected override bool UpdateCore() { return false; } protected override void InvalidateCore() { } public override ITable ItemsTable { get { return _itemsTable; } } public override DragDropKind CanAcceptDrop(object[] items, DragDropKind kind) { // can't drop items into a container folder, since it contains only other folders return DragDropKind.None; } public override DragDropKind AcceptDrop(object[] items, DragDropKind kind) { // can't drop items into a container folder, since it contains only other folders return DragDropKind.None; } protected override IconSet OpenIconSet { get { return new IconSet(IconScheme.Colour, "ContainerFolderOpenSmall.png", "ContainerFolderOpenMedium.png", "ContainerFolderOpenMedium.png"); } } protected override IconSet ClosedIconSet { get { return new IconSet(IconScheme.Colour, "ContainerFolderClosedSmall.png", "ContainerFolderClosedMedium.png", "ContainerFolderClosedMedium.png"); } } } #endregion private readonly FolderExplorerComponent _explorer; private readonly Tree<FolderTreeNode> _subTree; private readonly FolderTreeNode _parent; private bool _expanded; private IFolder _folder; /// <summary> /// Constructor. /// </summary> /// <param name="explorer"></param> /// <param name="parent"></param> /// <param name="path"></param> public FolderTreeNode(FolderExplorerComponent explorer, FolderTreeNode parent, Path path) { _explorer = explorer; _parent = parent; _subTree = new Tree<FolderTreeNode>(GetBinding(_explorer)); // always start with container folder SetFolder(new ContainerFolder(path, true)); } #region Public API /// <summary> /// Gets the folder at this node. /// </summary> public IFolder Folder { get { return _folder; } } /// <summary> /// Gets the subtree at this node. /// </summary> /// <returns></returns> public Tree<FolderTreeNode> GetSubTree() { return _subTree; } /// <summary> /// Finds a descendant node (not necessarily an immediate child) associated with the specified folder, /// or returns null if no such node exists. /// </summary> /// <param name="folder"></param> /// <returns></returns> public FolderTreeNode FindNode(IFolder folder) { if (_folder == folder) return this; foreach (var child in _subTree.Items) { var node = child.FindNode(folder); if (node != null) return node; } return null; } /// <summary> /// Ensures that this node is up to date with respect to the folder count and/or contents. /// Applies recursively to all descendants of this node. /// </summary> public void Update() { // update this node _folder.Update(); if (!_expanded) return; // only update the child nodes if this node is expanded foreach (var child in _subTree.Items) { child.Update(); } } #endregion #region Protected API /// <summary> /// Removes the specified node from the subtree of this node, assuming the specified node is /// a descendant (not necessarily an immediate child) of this node. Also removes any empty /// parent container nodes of the specified node. /// </summary> /// <param name="node"></param> /// <returns></returns> protected bool RemoveNode(FolderTreeNode node) { if (_subTree.Items.Contains(node)) { // important to null out the folder, to unsubscribe from events, etc. before removing from the collection node.SetFolder(null); _subTree.Items.Remove(node); return true; } foreach (var child in _subTree.Items) { if (!child.RemoveNode(node)) continue; if (child.IsEmptyContainer()) RemoveNode(child); return true; } return false; } /// <summary> /// Inserts the specified folder into the tree, based on its path, recursively creating /// container nodes where necessary. /// </summary> /// <param name="folder"></param> /// <param name="depth"></param> /// <param name="alphabetical"></param> protected void InsertFolder(IFolder folder, int depth, bool alphabetical) { if (depth == folder.FolderPath.Segments.Count) { SetFolder(folder); } else { var segment = folder.FolderPath.Segments[depth]; // find an existing node at this path point var node = CollectionUtils.SelectFirst(_subTree.Items, n => Equals(n.Folder.FolderPath.Segments[depth], segment)); var isAddingLeafNode = (depth == folder.FolderPath.Segments.Count - 1); var existingNodeIsAContainer = node != null && node.Folder is ContainerFolder; if (node == null || (isAddingLeafNode && !existingNodeIsAContainer)) { // create the node if it doesn't exist, or if this is the leaf node node = new FolderTreeNode(_explorer, this, folder.FolderPath.SubPath(0, depth + 1)); if(alphabetical) InsertChildAlphabetical(node, depth); else _subTree.Items.Add(node); } node.InsertFolder(folder, depth + 1, alphabetical); } } /// <summary> /// Gets or sets a value indicating whether this node is currently expanded. /// </summary> protected bool Expanded { get { return _expanded; } set { _expanded = value; if(_expanded) { Update(); } } } /// <summary> /// Notifies the tree to update the display. /// </summary> protected internal void NotifyItemUpdated() { // parent may be null iff this is a root node // parent item may not yet contain this node, if this is node has not yet been added to the parent's // item collection (a transient state that occurs while the tree is being built) if (_parent != null && _parent.GetSubTree().Items.Contains(this)) _parent.GetSubTree().Items.NotifyItemUpdated(this); } #endregion #region Private Helpers /// <summary> /// Gets a value indicating whether this node has a sub-tree. /// </summary> private bool CanHaveSubTree { get { if (this.Folder is ContainerFolder) return true; return this.GetSubTree().Items.Count > 0; } } /// <summary> /// Sets the folder associatd with this node. /// </summary> /// <param name="folder"></param> private void SetFolder(IFolder folder) { if(_folder != null) { _folder.TextChanged -= FolderTextOrIconChangedEventHandler; _folder.IconChanged -= FolderTextOrIconChangedEventHandler; } _folder = folder; if (_folder == null) return; _folder.TextChanged += FolderTextOrIconChangedEventHandler; _folder.IconChanged += FolderTextOrIconChangedEventHandler; _expanded = _folder.StartExpanded; // since the folder has changed, need to immediately notify the tree that this item is updated. NotifyItemUpdated(); } /// <summary> /// Gets a value indicating whether this node is an empty container. /// </summary> /// <returns></returns> private bool IsEmptyContainer() { return _folder is ContainerFolder && _subTree.Items.Count == 0; } /// <summary> /// Listens for changes from the folder. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FolderTextOrIconChangedEventHandler(object sender, EventArgs e) { NotifyItemUpdated(); } /// <summary> /// Inserts the specified node alphabetically as a child of this node. /// </summary> /// <param name="node"></param> /// <param name="pathDepth"></param> private void InsertChildAlphabetical(FolderTreeNode node, int pathDepth) { var segment = node.Folder.FolderPath.Segments[pathDepth]; // find the insertion point - the first node greater/equalto the node to be inserted var insertPoint = _subTree.Items.FindIndex( n => n.Folder.FolderPath.Segments[pathDepth].LocalizedText.CompareTo(segment.LocalizedText) >= 0); if (insertPoint > -1) _subTree.Items.Insert(insertPoint, node); else _subTree.Items.Add(node); } /// <summary> /// Constructs a tree item binding. /// </summary> /// <param name="explorer"></param> /// <returns></returns> private static TreeItemBinding<FolderTreeNode> GetBinding(FolderExplorerComponent explorer) { var binding = new TreeItemBinding<FolderTreeNode> { NodeTextProvider = node => node.Folder.Text, IconSetProvider = node => node.Folder.IconSet, TooltipTextProvider = node => node.Folder.Tooltip, ResourceResolverProvider = node => node.Folder.ResourceResolver, CanAcceptDropHandler = explorer.CanFolderAcceptDrop, AcceptDropHandler = explorer.FolderAcceptDrop, CanHaveSubTreeHandler = node => node.CanHaveSubTree, IsExpandedGetter = node => node.Expanded, IsExpandedSetter = (node, expanded) => node.Expanded = expanded, SubTreeProvider = node => node.GetSubTree() }; return binding; } #endregion } /// <summary> /// Represents the root node in a folder explorer tree. /// </summary> internal class FolderTreeRoot : FolderTreeNode { /// <summary> /// Constructor. /// </summary> /// <param name="explorer"></param> public FolderTreeRoot(FolderExplorerComponent explorer) : base(explorer, null, new Path("", null)) { } /// <summary> /// Inserts the specified folders into the tree. /// </summary> /// <param name="folders"></param> /// <param name="alphabetical"></param> public void InsertFolders(IEnumerable<IFolder> folders, bool alphabetical) { foreach (var folder in folders) { InsertFolder(folder, 0, alphabetical); } } /// <summary> /// Inserts the specified folder into the tree. /// </summary> /// <param name="folder"></param> /// <param name="alphabetical"></param> public void InsertFolder(IFolder folder, bool alphabetical) { InsertFolder(folder, 0, alphabetical); } /// <summary> /// Removes the specified folder from the tree. /// </summary> /// <param name="folder"></param> public void RemoveFolder(IFolder folder) { var node = FindNode(folder); if (node != null) { RemoveNode(node); } } /// <summary> /// Notifies the view that properties of the folder, such as its text or icon, have changed. /// </summary> /// <param name="folder"></param> public void NotifyFolderPropertiesUpdated(IFolder folder) { var node = FindNode(folder); if (node != null) { node.NotifyItemUpdated(); } } } }
26.966368
155
0.649871
[ "Apache-2.0" ]
SNBnani/Xian
Ris/Client/FolderTreeNode.cs
12,027
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using EventStore.Client.Users; using Grpc.Core; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; #nullable enable namespace EventStore.Client { /// <summary> /// The client used for operations on internal users. /// </summary> public class EventStoreUserManagementClient : EventStoreClientBase { private readonly Users.Users.UsersClient _client; private readonly ILogger _log; /// <summary> /// Constructs a new <see cref="EventStoreUserManagementClient"/>. /// </summary> /// <param name="settings"></param> public EventStoreUserManagementClient(EventStoreClientSettings? settings = null) : base(settings, ExceptionMap) { _client = new Users.Users.UsersClient(CallInvoker); _log = Settings.LoggerFactory?.CreateLogger<EventStoreUserManagementClient>() ?? new NullLogger<EventStoreUserManagementClient>(); } /// <summary> /// Creates an internal user. /// </summary> /// <param name="loginName"></param> /// <param name="fullName"></param> /// <param name="groups"></param> /// <param name="password"></param> /// <param name="userCredentials"></param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> public async Task CreateUserAsync(string loginName, string fullName, string[] groups, string password, UserCredentials? userCredentials = null, CancellationToken cancellationToken = default) { if (loginName == null) throw new ArgumentNullException(nameof(loginName)); if (fullName == null) throw new ArgumentNullException(nameof(fullName)); if (groups == null) throw new ArgumentNullException(nameof(groups)); if (password == null) throw new ArgumentNullException(nameof(password)); if (loginName == string.Empty) throw new ArgumentOutOfRangeException(nameof(loginName)); if (fullName == string.Empty) throw new ArgumentOutOfRangeException(nameof(fullName)); if (password == string.Empty) throw new ArgumentOutOfRangeException(nameof(password)); await _client.CreateAsync(new CreateReq { Options = new CreateReq.Types.Options { LoginName = loginName, FullName = fullName, Password = password, Groups = {groups} } }, EventStoreCallOptions.Create(Settings, Settings.OperationOptions, userCredentials, cancellationToken)); } /// <summary> /// Gets the <see cref="UserDetails"/> of an internal user. /// </summary> /// <param name="loginName"></param> /// <param name="userCredentials"></param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> public async Task<UserDetails> GetUserAsync(string loginName, UserCredentials? userCredentials = null, CancellationToken cancellationToken = default) { if (loginName == null) { throw new ArgumentNullException(nameof(loginName)); } if (loginName == string.Empty) { throw new ArgumentOutOfRangeException(nameof(loginName)); } using var call = _client.Details(new DetailsReq { Options = new DetailsReq.Types.Options { LoginName = loginName } }, EventStoreCallOptions.Create(Settings, Settings.OperationOptions, userCredentials, cancellationToken)); await call.ResponseStream.MoveNext().ConfigureAwait(false); var userDetails = call.ResponseStream.Current.UserDetails; return ConvertUserDetails(userDetails); } private static UserDetails ConvertUserDetails(DetailsResp.Types.UserDetails userDetails) => new UserDetails(userDetails.LoginName, userDetails.FullName, userDetails.Groups.ToArray(), userDetails.Disabled, userDetails.LastUpdated?.TicksSinceEpoch.FromTicksSinceEpoch()); /// <summary> /// Deletes an internal user. /// </summary> /// <param name="loginName"></param> /// <param name="userCredentials"></param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> public async Task DeleteUserAsync(string loginName, UserCredentials? userCredentials = null, CancellationToken cancellationToken = default) { if (loginName == null) { throw new ArgumentNullException(nameof(loginName)); } if (loginName == string.Empty) { throw new ArgumentOutOfRangeException(nameof(loginName)); } await _client.DeleteAsync(new DeleteReq { Options = new DeleteReq.Types.Options { LoginName = loginName } }, EventStoreCallOptions.Create(Settings, Settings.OperationOptions, userCredentials, cancellationToken)); } /// <summary> /// Enables a previously disabled internal user. /// </summary> /// <param name="loginName"></param> /// <param name="userCredentials"></param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> public async Task EnableUserAsync(string loginName, UserCredentials? userCredentials = null, CancellationToken cancellationToken = default) { if (loginName == null) { throw new ArgumentNullException(nameof(loginName)); } if (loginName == string.Empty) { throw new ArgumentOutOfRangeException(nameof(loginName)); } await _client.EnableAsync(new EnableReq { Options = new EnableReq.Types.Options { LoginName = loginName } }, EventStoreCallOptions.Create(Settings, Settings.OperationOptions, userCredentials, cancellationToken)); } /// <summary> /// Disables an internal user. /// </summary> /// <param name="loginName"></param> /// <param name="userCredentials"></param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public async Task DisableUserAsync(string loginName, UserCredentials? userCredentials = null, CancellationToken cancellationToken = default) { if (loginName == string.Empty) throw new ArgumentOutOfRangeException(nameof(loginName)); await _client.DisableAsync(new DisableReq { Options = new DisableReq.Types.Options { LoginName = loginName } }, EventStoreCallOptions.Create(Settings, Settings.OperationOptions, userCredentials, cancellationToken)); } /// <summary> /// Lists the <see cref="UserDetails"/> of all internal users. /// </summary> /// <param name="userCredentials"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async IAsyncEnumerable<UserDetails> ListAllAsync(UserCredentials? userCredentials = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { using var call = _client.Details(new DetailsReq(), EventStoreCallOptions.Create(Settings, Settings.OperationOptions, userCredentials, cancellationToken)); await foreach (var userDetail in call.ResponseStream .ReadAllAsync(cancellationToken) .Select(x => ConvertUserDetails(x.UserDetails)) .WithCancellation(cancellationToken) .ConfigureAwait(false)) { yield return userDetail; } } /// <summary> /// Changes the password of an internal user. /// </summary> /// <param name="loginName"></param> /// <param name="currentPassword"></param> /// <param name="newPassword"></param> /// <param name="userCredentials"></param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> public async Task ChangePasswordAsync(string loginName, string currentPassword, string newPassword, UserCredentials? userCredentials = null, CancellationToken cancellationToken = default) { if (loginName == null) throw new ArgumentNullException(nameof(loginName)); if (currentPassword == null) throw new ArgumentNullException(nameof(currentPassword)); if (newPassword == null) throw new ArgumentNullException(nameof(newPassword)); if (loginName == string.Empty) throw new ArgumentOutOfRangeException(nameof(loginName)); if (currentPassword == string.Empty) throw new ArgumentOutOfRangeException(nameof(currentPassword)); if (newPassword == string.Empty) throw new ArgumentOutOfRangeException(nameof(newPassword)); await _client.ChangePasswordAsync(new ChangePasswordReq { Options = new ChangePasswordReq.Types.Options { CurrentPassword = currentPassword, NewPassword = newPassword, LoginName = loginName } }, EventStoreCallOptions.Create(Settings, Settings.OperationOptions, userCredentials, cancellationToken)); } /// <summary> /// Resets the password of an internal user. /// </summary> /// <param name="loginName"></param> /// <param name="newPassword"></param> /// <param name="userCredentials"></param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> public async Task ResetPasswordAsync(string loginName, string newPassword, UserCredentials? userCredentials = null, CancellationToken cancellationToken = default) { if (loginName == null) throw new ArgumentNullException(nameof(loginName)); if (newPassword == null) throw new ArgumentNullException(nameof(newPassword)); if (loginName == string.Empty) throw new ArgumentOutOfRangeException(nameof(loginName)); if (newPassword == string.Empty) throw new ArgumentOutOfRangeException(nameof(newPassword)); await _client.ResetPasswordAsync(new ResetPasswordReq { Options = new ResetPasswordReq.Types.Options { NewPassword = newPassword, LoginName = loginName } }, EventStoreCallOptions.Create(Settings, Settings.OperationOptions, userCredentials, cancellationToken)); } private static readonly IDictionary<string, Func<RpcException, Exception>> ExceptionMap = new Dictionary<string, Func<RpcException, Exception>> { [Constants.Exceptions.UserNotFound] = ex => new UserNotFoundException( ex.Trailers.First(x => x.Key == Constants.Exceptions.LoginName).Value), }; } }
42.016
109
0.730293
[ "Apache-2.0" ]
BrunoZell/EventStore-Client-Dotnet
src/EventStore.Client.UserManagement/EventStoreUserManagementClient.cs
10,504
C#
using System.Windows.Controls; namespace ForgeModGenerator.TextureGenerator.Views { /// <summary> SoundGenerator UI View-ViewModel </summary> public partial class TextureGeneratorPage : Page { public TextureGeneratorPage() => InitializeComponent(); } }
25.363636
63
0.727599
[ "MIT" ]
Prastiwar/ForgeModGenerator
ForgeModGenerator/app/ForgeModGenerator.Wpf/Source/Modules/TextureGenerator/TextureGeneratorPage.xaml.cs
281
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using TygaSoft.Model; using TygaSoft.BLL; using TygaSoft.WebHelper; namespace TygaSoft.Web.Admin.ActivityNew { public partial class AddActivityPush : System.Web.UI.Page { Guid Id; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Request.QueryString["Id"] != null) { Guid.TryParse(Request.QueryString["Id"], out Id); } Bind(); } } private void Bind() { if (!Id.Equals(Guid.Empty)) { ActivitySubjectNew bll = new ActivitySubjectNew(); DataSet ds = bll.GetModelOW(Id); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows != null && ds.Tables[0].Rows.Count > 0) { DataTable dt = ds.Tables[0]; txtTitle.Value = dt.Rows[0]["Title"].ToString(); hId.Value = Id.ToString(); } } } } }
27.577778
114
0.506849
[ "MIT" ]
qq283335746/Infoztc
src/Team12/TygaSoft/Web/Admin/ActivityNew/AddActivityPush.aspx.cs
1,243
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 NodaTime; using NUnit.Framework; using QuantConnect.Algorithm; using QuantConnect.Algorithm.Framework.Alphas; using QuantConnect.Algorithm.Framework.Portfolio; using QuantConnect.Data.UniverseSelection; using QuantConnect.Securities; using QuantConnect.Securities.Equity; using QuantConnect.Tests.Engine.DataFeeds; using System; using System.Collections.Generic; using System.Linq; namespace QuantConnect.Tests.Algorithm.Framework.Portfolio { [TestFixture] public abstract class BaseWeightingPortfolioConstructionModelTests { protected decimal StartingCash => 100000; protected QCAlgorithm Algorithm { get; set; } public virtual double? Weight => Algorithm.Securities.Count == 0 ? default(double) : 1d / Algorithm.Securities.Count; [TestFixtureSetUp] public virtual void SetUp() { Algorithm = new QCAlgorithm(); Algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(Algorithm)); } [Test] [TestCase(Language.CSharp)] [TestCase(Language.Python)] public void AutomaticallyRemoveInvestedWithoutNewInsights(Language language) { SetPortfolioConstruction(language); // Let's create a position for SPY var insights = new[] { GetInsight(Symbols.SPY, InsightDirection.Up, Algorithm.UtcTime) }; foreach (var target in Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights)) { var holding = Algorithm.Portfolio[target.Symbol]; holding.SetHoldings(holding.Price, target.Quantity); Algorithm.Portfolio.SetCash(StartingCash - holding.HoldingsValue); } SetUtcTime(Algorithm.UtcTime.AddDays(2)); var expectedTargets = new List<IPortfolioTarget> { new PortfolioTarget(Symbols.SPY, 0) }; // Create target from an empty insights array var actualTargets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, new Insight[0]); AssertTargets(expectedTargets, actualTargets); } [Test] [TestCase(Language.CSharp)] [TestCase(Language.Python)] public void DelistedSecurityEmitsFlatTargetWithoutNewInsights(Language language) { SetPortfolioConstruction(language); var insights = new[] { GetInsight(Symbols.SPY, InsightDirection.Down, Algorithm.UtcTime) }; var targets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights).ToList(); Assert.AreEqual(1, targets.Count); var changes = SecurityChanges.Removed(Algorithm.Securities[Symbols.SPY]); Algorithm.PortfolioConstruction.OnSecuritiesChanged(Algorithm, changes); var expectedTargets = new List<IPortfolioTarget> { new PortfolioTarget(Symbols.SPY, 0) }; // Create target from an empty insights array var actualTargets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, new Insight[0]); AssertTargets(expectedTargets, actualTargets); } [Test] [TestCase(Language.CSharp)] [TestCase(Language.Python)] public void DoesNotReturnTargetsIfSecurityPriceIsZero(Language language) { var algorithm = new QCAlgorithm(); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); algorithm.AddEquity(Symbols.SPY.Value); algorithm.SetDateTime(DateTime.MinValue.ConvertToUtc(Algorithm.TimeZone)); SetPortfolioConstruction(language); var insights = new[] { GetInsight(Symbols.SPY, InsightDirection.Up, algorithm.UtcTime) }; var actualTargets = algorithm.PortfolioConstruction.CreateTargets(algorithm, insights); Assert.AreEqual(0, actualTargets.Count()); } [Test] [TestCase(Language.CSharp)] [TestCase(Language.Python)] public void DoesNotThrowWithAlternativeOverloads(Language language) { Assert.DoesNotThrow(() => SetPortfolioConstruction(language, Resolution.Minute)); Assert.DoesNotThrow(() => SetPortfolioConstruction(language, TimeSpan.FromDays(1))); Assert.DoesNotThrow(() => SetPortfolioConstruction(language, Expiry.EndOfWeek)); } [Test] [TestCase(Language.CSharp)] [TestCase(Language.Python)] public void EmptyInsightsReturnsEmptyTargets(Language language) { SetPortfolioConstruction(language); var actualTargets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, new Insight[0]); Assert.AreEqual(0, actualTargets.Count()); } [Test] [TestCase(Language.CSharp)] [TestCase(Language.Python)] public void LongTermInsightPreservesPosition(Language language) { SetPortfolioConstruction(language); // First emit long term insight var insights = new[] { GetInsight(Symbols.SPY, InsightDirection.Down, Algorithm.UtcTime) }; var targets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights).ToList(); Assert.AreEqual(1, targets.Count); // One minute later, emits short term insight SetUtcTime(Algorithm.UtcTime.AddMinutes(1)); insights = new[] { GetInsight(Symbols.SPY, InsightDirection.Up, Algorithm.UtcTime, Time.OneMinute) }; targets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights).ToList(); Assert.AreEqual(1, targets.Count); // One minute later, emit empty insights array SetUtcTime(Algorithm.UtcTime.AddMinutes(1.1)); var expectedTargets = GetTargetsForSPY(); // Create target from an empty insights array var actualTargets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, new Insight[0]); AssertTargets(expectedTargets, actualTargets); } [Test] [TestCase(Language.CSharp, InsightDirection.Up)] [TestCase(Language.CSharp, InsightDirection.Down)] [TestCase(Language.CSharp, InsightDirection.Flat)] [TestCase(Language.Python, InsightDirection.Up)] [TestCase(Language.Python, InsightDirection.Down)] [TestCase(Language.Python, InsightDirection.Flat)] public abstract void AutomaticallyRemoveInvestedWithNewInsights(Language language, InsightDirection direction); [Test] [TestCase(Language.CSharp, InsightDirection.Up)] [TestCase(Language.CSharp, InsightDirection.Down)] [TestCase(Language.CSharp, InsightDirection.Flat)] [TestCase(Language.Python, InsightDirection.Up)] [TestCase(Language.Python, InsightDirection.Down)] [TestCase(Language.Python, InsightDirection.Flat)] public abstract void DelistedSecurityEmitsFlatTargetWithNewInsights(Language language, InsightDirection direction); [TestCase(Language.CSharp, InsightDirection.Up)] [TestCase(Language.CSharp, InsightDirection.Down)] [TestCase(Language.CSharp, InsightDirection.Flat)] [TestCase(Language.Python, InsightDirection.Up)] [TestCase(Language.Python, InsightDirection.Down)] [TestCase(Language.Python, InsightDirection.Flat)] public abstract void FlatDirectionNotAccountedToAllocation(Language language, InsightDirection direction); public abstract IPortfolioConstructionModel GetPortfolioConstructionModel(Language language, dynamic paramenter = null); public abstract Insight GetInsight(Symbol symbol, InsightDirection direction, DateTime generatedTimeUtc, TimeSpan? period = null, double? weight = 0.01); public void AssertTargets(IEnumerable<IPortfolioTarget> expectedTargets, IEnumerable<IPortfolioTarget> actualTargets) { var list = actualTargets.ToList(); Assert.AreEqual(expectedTargets.Count(), list.Count); foreach (var expected in expectedTargets) { var actual = list.FirstOrDefault(x => x.Symbol == expected.Symbol); Assert.IsNotNull(actual); Assert.AreEqual(expected.Quantity, actual.Quantity); } } protected Security GetSecurity(Symbol symbol) => new Equity( symbol, SecurityExchangeHours.AlwaysOpen(DateTimeZone.Utc), new Cash(Currencies.USD, 0, 1), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); public virtual List<IPortfolioTarget> GetTargetsForSPY() { return new List<IPortfolioTarget> { PortfolioTarget.Percent(Algorithm, Symbols.SPY, -1m) }; } protected void SetPortfolioConstruction(Language language, dynamic paramenter = null) { var model = GetPortfolioConstructionModel(language, paramenter ?? Resolution.Daily); Algorithm.SetPortfolioConstruction(model); foreach (var kvp in Algorithm.Portfolio) { kvp.Value.SetHoldings(kvp.Value.Price, 0); } Algorithm.Portfolio.SetCash(StartingCash); SetUtcTime(new DateTime(2018, 7, 31)); var changes = SecurityChanges.Added(Algorithm.Securities.Values.ToArray()); Algorithm.PortfolioConstruction.OnSecuritiesChanged(Algorithm, changes); } protected void SetUtcTime(DateTime dateTime) => Algorithm.SetDateTime(dateTime.ConvertToUtc(Algorithm.TimeZone)); } }
43.679167
161
0.679863
[ "Apache-2.0" ]
CanerIrfanoglu/Lean
Tests/Algorithm/Framework/Portfolio/BaseWeightingPortfolioConstructionModelTests.cs
10,485
C#
// Copyright © 2015 Dmitry Sikorsky. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Platformus.Globalization.Frontend.ViewModels; namespace Platformus.Forms.Frontend.ViewModels.Shared { public class FieldOptionViewModel : ViewModelBase { public string Value { get; set; } } }
31.666667
111
0.771053
[ "Apache-2.0" ]
5118234/Platformus
src/Platformus.Forms.Frontend/ViewModels/Shared/FieldOption/FieldOptionViewModel.cs
383
C#
namespace MappingSPO.Project.DL.Entities { public partial class BibUserEntity { public BibUserEntity() { InitializePartial(); } public long CalcId { get; set; } public int UserId { get; set; } public CalculationEntity Calculation { get; set; } partial void InitializePartial(); } }
20.333333
58
0.584699
[ "MIT" ]
hmohcine/MappingSPO
MappingSPO.Project.DL/Entities/BibUserEntity.cs
366
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RelevantFileDetectorTests.cs" company="PicklesDoc"> // Copyright 2011 Jeffrey Cameron // Copyright 2012-present PicklesDoc team and community contributors // // // 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.IO.Abstractions.TestingHelpers; using NUnit.Framework; using PicklesDoc.Pickles.DirectoryCrawler; using Should; namespace PicklesDoc.Pickles.Test.DirectoryCrawlers { [TestFixture] public class RelevantFileDetectorTests { [Test] public void IsRelevant_ImageFileInfo_ReturnsTrue() { var fileDetector = new RelevantFileDetector(); var fileSystem = new MockFileSystem(); var file = fileSystem.FileInfo.FromFileName("image.png"); bool isRelevant = fileDetector.IsRelevant(file); isRelevant.ShouldBeTrue(); } } }
35.12766
121
0.601454
[ "Apache-2.0" ]
Jaykul/pickles
src/Pickles/Pickles.Test/DirectoryCrawlers/RelevantFileDetectorTests.cs
1,653
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 greengrassv2-2020-11-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.GreengrassV2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.GreengrassV2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for IoTJobRateIncreaseCriteria Object /// </summary> public class IoTJobRateIncreaseCriteriaUnmarshaller : IUnmarshaller<IoTJobRateIncreaseCriteria, XmlUnmarshallerContext>, IUnmarshaller<IoTJobRateIncreaseCriteria, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> IoTJobRateIncreaseCriteria IUnmarshaller<IoTJobRateIncreaseCriteria, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public IoTJobRateIncreaseCriteria Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; IoTJobRateIncreaseCriteria unmarshalledObject = new IoTJobRateIncreaseCriteria(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("numberOfNotifiedThings", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.NumberOfNotifiedThings = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("numberOfSucceededThings", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.NumberOfSucceededThings = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static IoTJobRateIncreaseCriteriaUnmarshaller _instance = new IoTJobRateIncreaseCriteriaUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static IoTJobRateIncreaseCriteriaUnmarshaller Instance { get { return _instance; } } } }
37.387755
192
0.632915
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/GreengrassV2/Generated/Model/Internal/MarshallTransformations/IoTJobRateIncreaseCriteriaUnmarshaller.cs
3,664
C#
using System; using System.Windows; using System.Windows.Data; namespace WPFDevelopers.Converts { class AngleToPointConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { double angle = (double)value; double radius = 50; double piang = angle * Math.PI / 180; double px = Math.Sin(piang) * radius + radius; double py = -Math.Cos(piang) * radius + radius; return new Point(px, py); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
29
124
0.628352
[ "MIT" ]
WPFDevelopersOrg/WPFDevelopers
src/WPFDevelopers/Converts/AngleToPointConverter.cs
785
C#
using System.Threading.Tasks; using Meziantou.Analyzer.Rules; using TestHelper; using Xunit; namespace Meziantou.Analyzer.Test.Rules { public sealed class DoNotUseBlockingCallInAsyncContextAnalyzer_AsyncContextTests { private static ProjectBuilder CreateProjectBuilder() { return new ProjectBuilder() .WithTargetFramework(TargetFramework.NetStandard2_1) .WithAnalyzer<DoNotUseBlockingCallInAsyncContextAnalyzer>(id: "MA0042"); } [Fact] public async Task Async_Wait_Diagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { [||]Task.Delay(1).Wait(); } }") .ValidateAsync(); } [Fact] public async Task Async_Result_Diagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { _ = [||]Task.FromResult(1).Result; } }") .ValidateAsync(); } [Fact] public async Task Async_ValueTask_Result_Diagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { _ = [||]new ValueTask<int>(10).Result; } }") .ValidateAsync(); } [Fact] public async Task Async_ValueTask_GetAwaiter_Diagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { _ = [||]new ValueTask<int>(10).GetAwaiter().GetResult(); } }") .ValidateAsync(); } [Fact] public async Task Async_ThreadSleep_Diagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { [||]System.Threading.Thread.Sleep(1); } }") .ValidateAsync(); } [Fact] public async Task Async_SuggestOverload_Diagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { [||]Write(); } public void Write() => throw null; public Task Write(System.Threading.CancellationToken cancellationToken) => throw null; }") .ValidateAsync(); } [Fact] public async Task Async_AsyncSuffix_Diagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { [||]Write(); } public void Write() => throw null; public Task WriteAsync() => throw null; }") .ValidateAsync(); } [Fact] public async Task Async_NoOverload_NoDiagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { Write(); } public void Write() => throw null; public void WriteAsync() => throw null; }") .ValidateAsync(); } [Fact] public async Task AsyncLambda_Overload_NoDiagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { System.Func<Task> a = async () => [||]Write(); } public void Write() => throw null; public Task WriteAsync() => throw null; }") .ValidateAsync(); } [Fact] public async Task AsyncLocalFunction_Overload_NoDiagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public void A() { Local(); async Task Local() => [||]Write(); } public void Write() => throw null; public Task WriteAsync() => throw null; }") .ValidateAsync(); } [Fact] public async Task AsyncLocalFunction_Overload_ValueTask_NoDiagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public void A() { Local(); async Task Local() => [||]Write(); } public void Write() => throw null; public ValueTask WriteAsync() => throw null; }") .ValidateAsync(); } [Fact] [Trait("Issue", "https://github.com/meziantou/Meziantou.Analyzer/issues/169")] public async Task AsyncMethodWithAsyncOverload() { await CreateProjectBuilder() .AddSystemTextJson() .WithSourceCode(@" using System; using System.IO; using System.Text.Json; using System.Threading; using System.Threading.Tasks; class Program { static async Task Main() { var responseStream = new MemoryStream(); var SerializerOptions = new JsonSerializerOptions(); var ct = CancellationToken.None; await JsonSerializer.DeserializeAsync<Program>(responseStream, SerializerOptions, ct).ConfigureAwait(false); } } ") .ValidateAsync(); } [Fact] public async Task Method_NoOverload_NoDiagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { Write(); } public void Write() => throw null; public void Write(System.Threading.CancellationToken cancellationToken) => throw null; }") .ValidateAsync(); } [Fact] public async Task Method_NoOverloadWithSameParameters_NoDiagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { Write(); } public void Write() => throw null; public Task Write(int a) => throw null; }") .ValidateAsync(); } [Fact] public async Task Console_NoDiagnostic() { await CreateProjectBuilder() .WithSourceCode(@"using System.Threading.Tasks; class Test { public async Task A() { System.Console.Out.WriteLine(); System.Console.Out.Write(' '); System.Console.Out.Flush(); System.Console.Error.WriteLine(); System.Console.Error.Write(' '); System.Console.Error.Flush(); } }") .ValidateAsync(); } [Fact] public async Task ProcessWaitForExit_NET5() { await CreateProjectBuilder() .WithTargetFramework(TargetFramework.Net5_0) .WithSourceCode(@" using System.Threading.Tasks; using System.Diagnostics; class Test { public async Task A() { var process = new Process(); process.WaitForExit(); } }") .ValidateAsync(); } [Fact] public async Task ProcessWaitForExit_NET6() { await CreateProjectBuilder() .WithTargetFramework(TargetFramework.Net6_0_rc2) .WithSourceCode(@" using System.Threading.Tasks; using System.Diagnostics; class Test { public async Task A() { var process = new Process(); [||]process.WaitForExit(); } }") .ValidateAsync(); } [Fact] public async Task Using_NoDiagnostic() { await CreateProjectBuilder() .WithLanguageVersion(Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp9) .WithSourceCode(@" using System; using System.Threading.Tasks; using System.Diagnostics; class Test { public async Task A() { using var a = new Sample(); using (var b = new Sample()) { } } private class Sample : IDisposable { public void Dispose() => throw null; } }") .ValidateAsync(); } [Fact] public async Task Using_Diagnostic() { await CreateProjectBuilder() .WithSourceCode(@" using System; using System.Threading.Tasks; using System.Diagnostics; class Test { public async Task A() { [||]using var a = new Sample(); [||]using (var b = new Sample()) { } var sample = new Sample(); [||]using (sample) { } await using var c = new Sample(); await using (var d = new Sample()) { } } private class Sample : IDisposable { public void Dispose() => throw null; public ValueTask DisposeAsync() => throw null; } }") .ValidateAsync(); } [Fact] public async Task ExtensionMethod() { await CreateProjectBuilder() .WithSourceCode(@" using System; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; class Test { public void A() { } } static class TestExtensions { public static async Task AAsync(this Test test, CancellationToken token) { } } class demo { public async Task a() { [||]new Test().A(); } } ") .ValidateAsync(); } [Fact] public async Task CreateAsyncScope() { await CreateProjectBuilder() .WithTargetFramework(TargetFramework.AspNetCore6_0_rc2) .WithSourceCode(@" using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; class demo { public async Task a() { IServiceProvider provider = null; await using var scope1 = provider.CreateAsyncScope(); using var scope2 = [||]provider.CreateScope(); } } ") .ValidateAsync(); } [Fact] public async Task CreateAsyncScope_net5() { await CreateProjectBuilder() .WithTargetFramework(TargetFramework.AspNetCore5_0) .WithSourceCode(@" using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; class demo { public async Task a() { IServiceProvider provider = null; using var scope = provider.CreateScope(); } } ") .ValidateAsync(); } } }
23.032051
116
0.558493
[ "MIT" ]
meziantou/Meziantou.Analyzer
tests/Meziantou.Analyzer.Test/Rules/DoNotUseBlockingCallInAsyncContextAnalyzer_AsyncContextTests.cs
10,781
C#
namespace BenchProcessor { partial class Output { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.outputTextBox = new System.Windows.Forms.RichTextBox(); this.progress = new System.Windows.Forms.ProgressBar(); this.SuspendLayout(); // // outputTextBox // this.outputTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.outputTextBox.Location = new System.Drawing.Point(0, 0); this.outputTextBox.Name = "outputTextBox"; this.outputTextBox.ReadOnly = true; this.outputTextBox.Size = new System.Drawing.Size(1009, 352); this.outputTextBox.TabIndex = 0; this.outputTextBox.Text = ""; // // progress // this.progress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.progress.Location = new System.Drawing.Point(12, 358); this.progress.Name = "progress"; this.progress.Size = new System.Drawing.Size(985, 23); this.progress.TabIndex = 3; // // Output // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1009, 386); this.Controls.Add(this.progress); this.Controls.Add(this.outputTextBox); this.Name = "Output"; this.ShowIcon = false; this.Text = "Durum Penceresi"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Output_FormClosing); this.Load += new System.EventHandler(this.Output_Load); this.ResumeLayout(false); } #endregion private System.Windows.Forms.RichTextBox outputTextBox; private System.Windows.Forms.ProgressBar progress; } }
40.532468
162
0.588273
[ "Apache-2.0" ]
abutun/bench-processor
BenchProcessor/Output.Designer.cs
3,123
C#
using System.Collections.Generic; using Abc.Zebus.Persistence; using Abc.Zebus.Serialization; using Abc.Zebus.Testing; using Abc.Zebus.Testing.Extensions; using Abc.Zebus.Tests.Messages; using NUnit.Framework; namespace Abc.Zebus.Tests.Serialization { [TestFixture] public class MessageSerializerTests { private MessageSerializer _messageSerializer; private Peer _self; [SetUp] public void SetUp() { _messageSerializer = new MessageSerializer(); _self = new Peer(new PeerId("Abc.Testing.Self"), "tcp://testing:123"); } [Test] public void should_serialize_persist_message_command() { var transportMessage = new FakeEvent(42).ToTransportMessage(_self); var persistMessageCommand = new PersistMessageCommand(transportMessage, new PeerId("Abc.Testing.A"), new PeerId("Abc.Testing.B")); var serializedTransportMessage = _messageSerializer.ToTransportMessage(persistMessageCommand, _self.Id, _self.EndPoint); serializedTransportMessage.Id.ShouldEqual(transportMessage.Id); serializedTransportMessage.MessageTypeId.ShouldEqual(transportMessage.MessageTypeId); serializedTransportMessage.Content.ShouldEqual(transportMessage.Content); serializedTransportMessage.Originator.ShouldEqual(transportMessage.Originator); serializedTransportMessage.Environment.ShouldEqual(transportMessage.Environment); serializedTransportMessage.WasPersisted.ShouldEqual(transportMessage.WasPersisted); serializedTransportMessage.PersistentPeerIds.ShouldBeEquivalentTo(persistMessageCommand.Targets); } [Test] public void should_deserialize_persist_message_command() { var transportMessage = new FakeEvent(42).ToTransportMessage(_self); transportMessage.PersistentPeerIds = new List<PeerId> { new PeerId("Abc.Testing.A"), new PeerId("Abc.Testing.B") }; var message = _messageSerializer.ToMessage(transportMessage).ShouldBe<PersistMessageCommand>(); var deserializedTransportMessage = message.TransportMessage; deserializedTransportMessage.Id.ShouldEqual(transportMessage.Id); deserializedTransportMessage.MessageTypeId.ShouldEqual(transportMessage.MessageTypeId); deserializedTransportMessage.Content.ShouldEqual(transportMessage.Content); deserializedTransportMessage.Originator.ShouldEqual(transportMessage.Originator); deserializedTransportMessage.Environment.ShouldEqual(transportMessage.Environment); deserializedTransportMessage.WasPersisted.ShouldEqual(transportMessage.WasPersisted); message.Targets.ShouldBeEquivalentTo(transportMessage.PersistentPeerIds); } } }
47.583333
142
0.734501
[ "MIT" ]
biarne-a/Zebus
src/Abc.Zebus.Tests/Serialization/MessageSerializerTests.cs
2,857
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 ("vpm-server")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("nathan")] [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("")]
35.357143
81
0.736364
[ "MIT" ]
nathanial/vgk-package-manager
vpm-server/Properties/AssemblyInfo.cs
992
C#
using System.Web; using System.Web.Optimization; using Camalot.Common.Extensions; using Camalot.Common.Mvc.Extensions; namespace Madb.Site { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.LoadFromWebConfiguration(); } } }
26.857143
90
0.779255
[ "Apache-2.0" ]
camalot/madb
Madb.Site/App_Start/BundleConfig.cs
378
C#
using System.Collections.Generic; using ValkyrieTools; namespace Assets.Scripts.Content { /// <summary> /// Class to define a dictionary of KEYS, Strings in all available languages /// </summary> public class DictionaryI18n { private const char QUOTES = '\"'; private const char COMMA = ','; /// <summary> /// Default initial language is English /// </summary> public string defaultLanguage = "English"; public string currentLanguage = "English"; // Each language has it's own dictionary private Dictionary<string, Dictionary<string, string>> data; // And each language has it's own raw data private Dictionary<string, List<string>> rawData; // must be loaded to Dictionaries and not raw for edit protected bool loadedForEdit = false; /// <summary> /// Construct a new empty dictionary /// </summary> public DictionaryI18n() { data = new Dictionary<string, Dictionary<string, string>>(); rawData = new Dictionary<string, List<string>>(); currentLanguage = Game.Get().currentLang; } /// <summary> /// Construct a new empty dictionary with a default language /// </summary> /// <param name="newDefaultLanguage">Language to use as default</param> public DictionaryI18n(string newDefaultLanguage) { data = new Dictionary<string, Dictionary<string, string>>(); rawData = new Dictionary<string, List<string>>(); currentLanguage = Game.Get().currentLang; } /// <summary> /// Construct a dictionary and add language data /// </summary> public DictionaryI18n(string[] languageData) { data = new Dictionary<string, Dictionary<string, string>>(); rawData = new Dictionary<string, List<string>>(); currentLanguage = Game.Get().currentLang; AddData(languageData); } /// <summary> /// Construct a dictionary with a default language and add language data /// </summary> /// <param name="languageData">Language data</param> /// <param name="newDefaultLanguage">Language to use as default</param> public DictionaryI18n(string[] languageData, string newDefaultLanguage) { data = new Dictionary<string, Dictionary<string, string>>(); rawData = new Dictionary<string, List<string>>(); defaultLanguage = newDefaultLanguage; currentLanguage = Game.Get().currentLang; AddData(languageData); } /// <summary> /// Add language data to dictionary from file path. /// </summary> /// <param name="file">Language file to add</param> public void AddDataFromFile(string file) { string[] lines; // Read the whole file try { lines = System.IO.File.ReadAllLines(file); AddData(lines); } catch (System.IO.IOException e) { ValkyrieDebug.Log("Error loading localization file " + file + ":" + e.Message); } } /// <summary> /// Add language data to dictionary /// </summary> /// <param name="languageData">Language data</param> public void AddData(string[] languageData) { List<string> textToAdd = new List<string>(); string partialLine = ""; // Remove extra new lines foreach (string rawLine in languageData) { int sections = rawLine.Split('\"').Length; // Even number of " characters, self contained line // Or middle of quote block if ((sections % 2) == 1) { // No current block, self contained entry if (partialLine.Length == 0) { textToAdd.Add(rawLine); } // Current quote block, add line else { partialLine += "\\n" + rawLine; } } // Odd number of quotes *should* mean start or end of multi line block else { // Start of a new block if (partialLine.Length == 0) { // We need to support old data which may have " characters without a starting quote // These are always single line and do not have " as the first character string[] components = rawLine.Split(",".ToCharArray(), 2); // Text starts with ", it is a normal multi line block if (components.Length > 1 && components[1].Length > 0 && components[1][0] == '\"') { partialLine = rawLine; } else { // Text does not start with ", support for 1.6.1 and earlier which may have uneven single lines textToAdd.Add(rawLine); } } else // Block has started, this is the last line { partialLine += "\\n" + rawLine; textToAdd.Add(partialLine); partialLine = ""; } } } string newLanguage = languageData[0].Split(COMMA)[1].Trim('"'); if (!rawData.ContainsKey(newLanguage)) { rawData.Add(newLanguage, new List<string>()); } rawData[newLanguage].AddRange(textToAdd); } /// <summary> /// Loads all raw data into Dictionaries. Must be called before any edits are made. /// </summary> protected void MakeEditable() { // Already loaded if (loadedForEdit) { return; } // Remove all existing entries (helps maintain order) data = new Dictionary<string, Dictionary<string, string>>(); // For all languages foreach (KeyValuePair<string, List<string>> kv in rawData) { // Create a Dictionary for each language data.Add(kv.Key, new Dictionary<string, string>()); // Check each line for (int i = 1; i < kv.Value.Count; i++) { // Ignore comments if (kv.Value[i].Trim().IndexOf("//") == 0) { continue; } // Split out key string[] components = kv.Value[i].Split(",".ToCharArray(), 2); if (components.Length != 2) { continue; } // Only store the first occurance of a key if (!data[kv.Key].ContainsKey(components[0])) { data[kv.Key].Add(components[0], ParseEntry(components[1])); } } } loadedForEdit = true; } /// <summary> /// Add an entry with the current language, replace if exists /// </summary> /// <param name="key">Entry key</param> /// <param name="value">Data to add</param> public void AddEntry(string key, string value) { AddEntry(key, value, currentLanguage); } /// <summary> /// Add an entry to a language, replace if exists /// </summary> /// <param name="key">Entry key</param> /// <param name="value">Data to add</param> /// <param name="language">Language to use</param> public void AddEntry(string key, string value, string language) { MakeEditable(); // Create language Dictionary if missing if (!data.ContainsKey(language)) { data.Add(language, new Dictionary<string, string>()); } if (data[language].ContainsKey(key)) { data[language][key] = value; } else { data[language].Add(key, value); } } /// <summary> /// Remove an entry from all languages /// </summary> /// <param name="key">Entry key</param> public void Remove(string key) { MakeEditable(); foreach (string lang in data.Keys) { if (data[lang].ContainsKey(key)) { data[lang].Remove(key); } } } /// <summary> /// Remove all entries starting with prefix from all languages /// </summary> /// <param name="prefix">prefix to match</param> public void RemoveKeyPrefix(string prefix) { MakeEditable(); foreach (Dictionary<string, string> languageData in data.Values) { // Build list of keys to remove List<string> toRemove = new List<string>(); foreach (string key in languageData.Keys) { if (key.IndexOf(prefix) == 0) { toRemove.Add(key); } } // Remove all keys foreach (string key in toRemove) { languageData.Remove(key); } } } /// <summary> /// Rename key for all entries starting with prefix from all languages /// </summary> /// <param name="oldPrefix">prefix to match</param> /// <param name="newPrefix">text to replace prefix</param> public void RenamePrefix(string oldPrefix, string newPrefix) { MakeEditable(); foreach (Dictionary<string, string> languageData in data.Values) { // Build list of keys to rename Dictionary<string, string> toRename = new Dictionary<string, string>(); foreach (string key in languageData.Keys) { if (key.IndexOf(oldPrefix) == 0) { toRename.Add(key, newPrefix + key.Substring(oldPrefix.Length)); } } // Replace with new key name foreach (KeyValuePair<string, string> kv in toRename) { languageData.Add(kv.Value, languageData[kv.Key]); languageData.Remove(kv.Key); } } } /// <summary> /// Check if a key exists in any language, also ensures all matching values are loaded into Dictionary objects /// </summary> /// <param name="key">key to check</param> public bool KeyExists(string key) { // Check loaded Dictionary data foreach (Dictionary<string, string> languageData in data.Values) { if (languageData.ContainsKey(key)) { return true; } } // If in edit mode don't check raw data, may be outdated if (loadedForEdit) { return false; } // Check raw data bool found = false; // Check all languages foreach (KeyValuePair<string, List<string>> kv in rawData) { // Check all lines foreach (string raw in kv.Value) { if (raw.IndexOf(key + ',') == 0) { // Add this language to Dictionary data if (!data.ContainsKey(kv.Key)) { data.Add(kv.Key, new Dictionary<string, string>()); } // If already present log warning if (data[kv.Key].ContainsKey(key)) { ValkyrieDebug.Log("Duplicate Key in " + kv.Key + " Dictionary: " + key); } else { data[kv.Key].Add(key, ParseEntry(raw.Substring(raw.IndexOf(',') + 1))); } // Continue after found to ensure all languages are loaded found = true; } } } if (!found) { ValkyrieDebug.Log("Key not found: " + key); } return found; } /// <summary> /// Get the value for a key. First check current language, then default, then any. Returns key if not found. /// </summary> /// <param name="key">key to retreive</param> /// <returns>Value found or 'key' if not found</returns> public string GetValue(string key) { // KeyExists ensures any matches are loaded to Dictionary data if (!KeyExists(key)) { return key; } // Check current language first if (data.ContainsKey(currentLanguage) && data[currentLanguage].ContainsKey(key) && data[currentLanguage][key].Length > 0) { return data[currentLanguage][key]; } // Then check default language if (data.ContainsKey(defaultLanguage) && data[defaultLanguage].ContainsKey(key)) { return data[defaultLanguage][key]; } // Not in current or default, find any match foreach (Dictionary<string, string> langData in data.Values) { if (langData.ContainsKey(key)) { return langData[key]; } } // Should never happen return ""; } /// <summary> /// Get the raw language data for this dictionary /// </summary> /// <returns>raw data by language</returns> public Dictionary<string, List<string>> SerializeMultiple() { // If we haven't edited can return what we were given if (!loadedForEdit) { return rawData; } // If we have edited we can replace the rawData rawData = new Dictionary<string, List<string>>(); foreach (KeyValuePair<string, Dictionary<string, string>> kv in data) { rawData.Add(kv.Key, new List<string>()); rawData[kv.Key].Add(".," + kv.Key); foreach (KeyValuePair<string, string> entry in kv.Value) { string entryDiskFormat = entry.Value.Replace("\r\n", "\n"); entryDiskFormat = entryDiskFormat.Replace("\r", "\n").Replace("\n", "\\n"); if (entryDiskFormat.Contains("\"")) { entryDiskFormat = "\"" + entryDiskFormat.Replace("\"", "\"\"") + "\""; } rawData[kv.Key].Add(entry.Key + ',' + entryDiskFormat); } } return rawData; } /// <summary> /// Parse raw value entry /// </summary> /// <param name="entry">entry from raw text</param> /// <returns>Entry with newlines and quotes handled</returns> protected string ParseEntry(string entry) { string parsedReturn = entry.Replace("\\n", "\n"); // If entry is in quotes if (parsedReturn.Length > 2 && parsedReturn[0] == '\"') { // Trim leading and trailing quotes parsedReturn = parsedReturn.Substring(1, parsedReturn.Length - 2); // Handle escaped quotes parsedReturn = parsedReturn.Replace("\"\"", "\""); } return parsedReturn; } /// <summary> /// Get matches to a key for all languages /// </summary> /// <param name="key">key to check</param> /// <returns>Dictionary of results for each language</returns> public Dictionary<string, string> ExtractAllMatches(string key) { // Load into data KeyExists(key); Dictionary<string, string> returnData = new Dictionary<string, string>(); foreach (KeyValuePair<string, Dictionary<string, string>> kv in data) { if (kv.Value.ContainsKey(key)) { returnData.Add(kv.Key, kv.Value[key]); } } return returnData; } /// <summary> /// Get list of languages /// </summary> /// <returns>List of all available languages</returns> public List<string> GetLanguagesList() { return new List<string>(data.Keys); } } }
35.347305
133
0.472246
[ "Apache-2.0", "MIT" ]
trinithy2000/valkyrie
unity/Assets/Scripts/Content/DictionaryI18n.cs
17,711
C#
/* * Copyright 2010-2014 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 elasticache-2015-02-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElastiCache.Model { /// <summary> /// This is the response object from the CreateSnapshot operation. /// </summary> public partial class CreateSnapshotResponse : AmazonWebServiceResponse { private Snapshot _snapshot; /// <summary> /// Gets and sets the property Snapshot. /// </summary> public Snapshot Snapshot { get { return this._snapshot; } set { this._snapshot = value; } } // Check to see if Snapshot property is set internal bool IsSetSnapshot() { return this._snapshot != null; } } }
28.981132
109
0.670573
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/ElastiCache/Generated/Model/CreateSnapshotResponse.cs
1,536
C#
namespace EnvironmentAssessment.Common.VimApi { public class KmipServerInfo : DynamicData { protected string _name; protected string _address; protected int _port; protected string _proxyAddress; protected int? _proxyPort; protected int? _reconnect; protected string _protocol; protected int? _nbio; protected int? _timeout; protected string _userName; public string Name { get { return this._name; } set { this._name = value; } } public string Address { get { return this._address; } set { this._address = value; } } public int Port { get { return this._port; } set { this._port = value; } } public string ProxyAddress { get { return this._proxyAddress; } set { this._proxyAddress = value; } } public int? ProxyPort { get { return this._proxyPort; } set { this._proxyPort = value; } } public int? Reconnect { get { return this._reconnect; } set { this._reconnect = value; } } public string Protocol { get { return this._protocol; } set { this._protocol = value; } } public int? Nbio { get { return this._nbio; } set { this._nbio = value; } } public int? Timeout { get { return this._timeout; } set { this._timeout = value; } } public string UserName { get { return this._userName; } set { this._userName = value; } } } }
12.322835
45
0.566134
[ "MIT" ]
octansIt/environmentassessment
EnvironmentAssessment.Wizard/Common/VimApi/K/KmipServerInfo.cs
1,565
C#
using UnityEngine; using System.Collections; using EasyMobile.Internal; namespace EasyMobile { [System.Serializable] public class RatingDialogContent { // Placeholders for replacable strings. public const string PRODUCT_NAME_PLACEHOLDER = "$PRODUCT_NAME"; public readonly static RatingDialogContent Default = new RatingDialogContent(); public string Title { get { return mTitle; } set { mTitle = value; } } public string Message { get { return mMessage; } set { mMessage = value; } } public string LowRatingMessage { get { return mLowRatingMessage; } set { mLowRatingMessage = value; } } public string HighRatingMessage { get { return mHighRatingMessage; } set { mHighRatingMessage = value; } } public string PostponeButtonText { get { return mPostponeButtonText; } set { mPostponeButtonText = value; } } public string RefuseButtonText { get { return mRefuseButtonText; } set { mRefuseButtonText = value; } } public string RateButtonText { get { return mRateButtonText; } set { mRateButtonText = value; } } public string CancelButtonText { get { return mCancelButtonText; } set { mCancelButtonText = value; } } public string FeedbackButtonText { get { return mFeedbackButtonText; } set { mFeedbackButtonText = value; } } [SerializeField][Rename("Title")] private string mTitle = "Rate " + PRODUCT_NAME_PLACEHOLDER; [SerializeField][Rename("Message")] private string mMessage = "How would you rate " + PRODUCT_NAME_PLACEHOLDER + "?"; [SerializeField][Rename("Low Rating Message")] private string mLowRatingMessage = "That's bad. Would you like to give us some feedback instead?"; [SerializeField][Rename("High Rating Message")] private string mHighRatingMessage = "Awesome! Let's do it!"; [SerializeField][Rename("Postpone Button Title")] private string mPostponeButtonText = "Not Now"; [SerializeField][Rename("Refuse Button Title")] private string mRefuseButtonText = "Don't Ask Again"; [SerializeField][Rename("Rate Button Title")] private string mRateButtonText = "Rate Now!"; [SerializeField][Rename("Cancel Button Title")] private string mCancelButtonText = "Cancel"; [SerializeField][Rename("Feedback Button Title")] private string mFeedbackButtonText = "Send Feedback"; public RatingDialogContent() { } public RatingDialogContent( string title, string message, string lowRatingMessage, string highRatingMessage, string postponeButtonText, string refuseButtonText, string rateButtonText, string cancelButtonText, string feedbackButtonText) { this.mTitle = title == null ? "" : title; this.mMessage = message == null ? "" : message; this.mLowRatingMessage = lowRatingMessage == null ? "" : lowRatingMessage; this.mHighRatingMessage = highRatingMessage == null ? "" : highRatingMessage; this.mPostponeButtonText = postponeButtonText == null ? "" : postponeButtonText; this.mRefuseButtonText = refuseButtonText == null ? "" : refuseButtonText; this.mRateButtonText = rateButtonText == null ? "" : rateButtonText; this.mCancelButtonText = cancelButtonText == null ? "" : cancelButtonText; this.mFeedbackButtonText = feedbackButtonText == null ? "" : feedbackButtonText; } } }
34.344828
106
0.595131
[ "MIT" ]
AndreeBurlamaqui/HyperBeatMIX
Assets/EasyMobile/Scripts/Modules/Utilities/StoreReview/RatingDialogContent.cs
3,986
C#
namespace SaaSPOCModel.Security { public class VMLogin { public string UserName { get; set; } public string Password { get; set; } } }
18.222222
44
0.603659
[ "MIT" ]
POCProjects-22/SaaSPOC2
SaaSPOCModel/Security/VMLogin.cs
166
C#
// ReSharper disable once CheckNamespace namespace Binance.Cache { /// <summary> /// Depth of market updated event. /// </summary> public class OrderBookCacheEventArgs : CacheEventArgs { #region Public Properties /// <summary> /// The depth of market snapshot (order book). /// </summary> public OrderBook OrderBook { get; } #endregion Public Properties #region Constructors /// <summary> /// Constructor. /// </summary> /// <param name="orderBook"></param> public OrderBookCacheEventArgs(OrderBook orderBook) { Throw.IfNull(orderBook, nameof(orderBook)); OrderBook = orderBook; } #endregion Constructors } }
23.058824
59
0.57398
[ "MIT" ]
MyJetWallet/Binance
src/Binance/Cache/Events/OrderBookCacheEventArgs.cs
786
C#
namespace UblTr.Common { [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] [System.Xml.Serialization.XmlRootAttribute("TestMethod", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", IsNullable = false)] public partial class TestMethodType : TextType1 { } }
50.454545
165
0.765766
[ "MIT" ]
enisgurkann/UblTr
Ubl-Tr/Common/CommonBasicComponents/TestMethodType.cs
555
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace SA { [CreateAssetMenu(menuName = "Conditions/IsPlayerEscapeExitAggroTransition")] public class IsPlayerEscapeExitAggroTransition : Condition { public override bool CheckAICondition(AIStateManager aiState) { return aiState.aiManager.IsExitAggroTransition_ByDistance(); } public override bool CheckCondition(StateManager state) { return false; } } }
26.35
80
0.694497
[ "MIT" ]
Amulet-Games/VolunsTale-Codes-Repository
Assets/Scripts/AI/AI_Transitions/IsPlayerEscapeExitAggroTransition.cs
529
C#
namespace CoolNameGenerator.Forms { partial class CoolNameResultForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CoolNameResultForm)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); this.menuStrip = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator(); this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.printPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.finglishConverterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.persianToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.searchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tabExtraTools = new System.Windows.Forms.TabControl(); this.tabBestChromosomes = new System.Windows.Forms.TabPage(); this.gbBestWords = new System.Windows.Forms.GroupBox(); this.dgvBestResults = new System.Windows.Forms.DataGridView(); this.colWord = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colFitness = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.tabWordDictionaries = new System.Windows.Forms.TabPage(); this.gbWordDic = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.btnAddWordDictionaries = new System.Windows.Forms.Button(); this.panelExtraWordsDic = new System.Windows.Forms.FlowLayoutPanel(); this.containerMain = new System.Windows.Forms.SplitContainer(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.gbGAToolbox = new System.Windows.Forms.GroupBox(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.btnStart = new System.Windows.Forms.Button(); this.panel4 = new System.Windows.Forms.Panel(); this.lblFitness = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.panel7 = new System.Windows.Forms.Panel(); this.bestChromosomeWord = new CoolNameGenerator.Graphics.WordLabel(); this.panel6 = new System.Windows.Forms.Panel(); this.lblTimeEvolving = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.panel5 = new System.Windows.Forms.Panel(); this.lblGeneration = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.panelWordToolbox = new System.Windows.Forms.FlowLayoutPanel(); this.chkHasHyphen = new System.Windows.Forms.CheckBox(); this.chkHasNumeric = new System.Windows.Forms.CheckBox(); this.panel2 = new System.Windows.Forms.Panel(); this.lblWordMaxLen = new System.Windows.Forms.Label(); this.numWordLen = new System.Windows.Forms.NumericUpDown(); this.chkDisplayRealtime = new System.Windows.Forms.CheckBox(); this.panel13 = new System.Windows.Forms.Panel(); this.label16 = new System.Windows.Forms.Label(); this.label17 = new System.Windows.Forms.Label(); this.numMinimumThread = new System.Windows.Forms.NumericUpDown(); this.panel14 = new System.Windows.Forms.Panel(); this.label18 = new System.Windows.Forms.Label(); this.label19 = new System.Windows.Forms.Label(); this.numMaximumThread = new System.Windows.Forms.NumericUpDown(); this.panelGAToolbox = new System.Windows.Forms.FlowLayoutPanel(); this.panel3 = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.numPopulationSize = new System.Windows.Forms.NumericUpDown(); this.panel10 = new System.Windows.Forms.Panel(); this.label11 = new System.Windows.Forms.Label(); this.numGenerationKeepingNumber = new System.Windows.Forms.NumericUpDown(); this.panel1 = new System.Windows.Forms.Panel(); this.label8 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.numCrossoverProbability = new System.Windows.Forms.NumericUpDown(); this.cbCrossover = new System.Windows.Forms.ComboBox(); this.panel8 = new System.Windows.Forms.Panel(); this.cbMutation = new System.Windows.Forms.ComboBox(); this.label9 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.numMutationProbability = new System.Windows.Forms.NumericUpDown(); this.panel9 = new System.Windows.Forms.Panel(); this.cbSelection = new System.Windows.Forms.ComboBox(); this.label10 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.numEliteSelection = new System.Windows.Forms.NumericUpDown(); this.panel11 = new System.Windows.Forms.Panel(); this.label12 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.numTimeEvolvingTermination = new System.Windows.Forms.NumericUpDown(); this.panel12 = new System.Windows.Forms.Panel(); this.label14 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.numFitnessThresholdTermination = new System.Windows.Forms.NumericUpDown(); this.gbResult = new System.Windows.Forms.GroupBox(); this.wpResults = new CoolNameGenerator.Graphics.WordsPanel(); this.menuStrip.SuspendLayout(); this.tabExtraTools.SuspendLayout(); this.tabBestChromosomes.SuspendLayout(); this.gbBestWords.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvBestResults)).BeginInit(); this.tabWordDictionaries.SuspendLayout(); this.gbWordDic.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.containerMain)).BeginInit(); this.containerMain.Panel1.SuspendLayout(); this.containerMain.Panel2.SuspendLayout(); this.containerMain.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.gbGAToolbox.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.panel4.SuspendLayout(); this.panel7.SuspendLayout(); this.panel6.SuspendLayout(); this.panel5.SuspendLayout(); this.panelWordToolbox.SuspendLayout(); this.panel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numWordLen)).BeginInit(); this.panel13.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numMinimumThread)).BeginInit(); this.panel14.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numMaximumThread)).BeginInit(); this.panelGAToolbox.SuspendLayout(); this.panel3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numPopulationSize)).BeginInit(); this.panel10.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numGenerationKeepingNumber)).BeginInit(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numCrossoverProbability)).BeginInit(); this.panel8.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numMutationProbability)).BeginInit(); this.panel9.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numEliteSelection)).BeginInit(); this.panel11.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numTimeEvolvingTermination)).BeginInit(); this.panel12.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numFitnessThresholdTermination)).BeginInit(); this.gbResult.SuspendLayout(); this.SuspendLayout(); // // menuStrip // this.menuStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible; this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20); this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem1, this.toolsToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; this.menuStrip.Padding = new System.Windows.Forms.Padding(4, 2, 0, 2); this.menuStrip.Size = new System.Drawing.Size(1188, 24); this.menuStrip.TabIndex = 2; this.menuStrip.Text = "menuStrip1"; // // fileToolStripMenuItem1 // this.fileToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripMenuItem, this.openToolStripMenuItem, this.toolStripSeparator, this.saveToolStripMenuItem, this.saveAsToolStripMenuItem, this.toolStripSeparator1, this.printToolStripMenuItem, this.printPreviewToolStripMenuItem, this.toolStripSeparator2, this.exitToolStripMenuItem}); this.fileToolStripMenuItem1.Name = "fileToolStripMenuItem1"; this.fileToolStripMenuItem1.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem1.Text = "&File"; // // newToolStripMenuItem // this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image"))); this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.newToolStripMenuItem.Name = "newToolStripMenuItem"; this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newToolStripMenuItem.Size = new System.Drawing.Size(146, 22); this.newToolStripMenuItem.Text = "&New"; // // openToolStripMenuItem // this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image"))); this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openToolStripMenuItem.Size = new System.Drawing.Size(146, 22); this.openToolStripMenuItem.Text = "&Open"; // // toolStripSeparator // this.toolStripSeparator.Name = "toolStripSeparator"; this.toolStripSeparator.Size = new System.Drawing.Size(143, 6); // // saveToolStripMenuItem // this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image"))); this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveToolStripMenuItem.Size = new System.Drawing.Size(146, 22); this.saveToolStripMenuItem.Text = "&Save"; // // saveAsToolStripMenuItem // this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(146, 22); this.saveAsToolStripMenuItem.Text = "Save &As"; // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(143, 6); // // printToolStripMenuItem // this.printToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripMenuItem.Image"))); this.printToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.printToolStripMenuItem.Name = "printToolStripMenuItem"; this.printToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.printToolStripMenuItem.Size = new System.Drawing.Size(146, 22); this.printToolStripMenuItem.Text = "&Print"; // // printPreviewToolStripMenuItem // this.printPreviewToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printPreviewToolStripMenuItem.Image"))); this.printPreviewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.printPreviewToolStripMenuItem.Name = "printPreviewToolStripMenuItem"; this.printPreviewToolStripMenuItem.Size = new System.Drawing.Size(146, 22); this.printPreviewToolStripMenuItem.Text = "Print Pre&view"; // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(143, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(146, 22); this.exitToolStripMenuItem.Text = "E&xit"; // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.finglishConverterToolStripMenuItem, this.optionsToolStripMenuItem}); this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; this.toolsToolStripMenuItem.Size = new System.Drawing.Size(48, 20); this.toolsToolStripMenuItem.Text = "&Tools"; // // finglishConverterToolStripMenuItem // this.finglishConverterToolStripMenuItem.Name = "finglishConverterToolStripMenuItem"; this.finglishConverterToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.finglishConverterToolStripMenuItem.Text = "FinglishConverter"; this.finglishConverterToolStripMenuItem.Click += new System.EventHandler(this.finglishConverterToolStripMenuItem_Click); // // optionsToolStripMenuItem // this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; this.optionsToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.optionsToolStripMenuItem.Text = "&Options"; // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem1, this.searchToolStripMenuItem, this.toolStripSeparator5, this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "&Help"; // // toolStripMenuItem1 // this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem2, this.persianToolStripMenuItem}); this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(126, 22); this.toolStripMenuItem1.Text = "Language"; // // toolStripMenuItem2 // this.toolStripMenuItem2.Checked = true; this.toolStripMenuItem2.CheckState = System.Windows.Forms.CheckState.Checked; this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(112, 22); this.toolStripMenuItem2.Text = "English"; // // persianToolStripMenuItem // this.persianToolStripMenuItem.Name = "persianToolStripMenuItem"; this.persianToolStripMenuItem.Size = new System.Drawing.Size(112, 22); this.persianToolStripMenuItem.Text = "Persian"; // // searchToolStripMenuItem // this.searchToolStripMenuItem.Name = "searchToolStripMenuItem"; this.searchToolStripMenuItem.Size = new System.Drawing.Size(126, 22); this.searchToolStripMenuItem.Text = "&Search"; // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(123, 6); // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(126, 22); this.aboutToolStripMenuItem.Text = "&About..."; // // tabExtraTools // this.tabExtraTools.Alignment = System.Windows.Forms.TabAlignment.Right; this.tabExtraTools.Controls.Add(this.tabBestChromosomes); this.tabExtraTools.Controls.Add(this.tabWordDictionaries); this.tabExtraTools.Dock = System.Windows.Forms.DockStyle.Fill; this.tabExtraTools.HotTrack = true; this.tabExtraTools.Location = new System.Drawing.Point(0, 0); this.tabExtraTools.Multiline = true; this.tabExtraTools.Name = "tabExtraTools"; this.tabExtraTools.SelectedIndex = 0; this.tabExtraTools.ShowToolTips = true; this.tabExtraTools.Size = new System.Drawing.Size(317, 556); this.tabExtraTools.SizeMode = System.Windows.Forms.TabSizeMode.Fixed; this.tabExtraTools.TabIndex = 3; // // tabBestChromosomes // this.tabBestChromosomes.Controls.Add(this.gbBestWords); this.tabBestChromosomes.Location = new System.Drawing.Point(4, 4); this.tabBestChromosomes.Name = "tabBestChromosomes"; this.tabBestChromosomes.Padding = new System.Windows.Forms.Padding(3); this.tabBestChromosomes.Size = new System.Drawing.Size(290, 548); this.tabBestChromosomes.TabIndex = 0; this.tabBestChromosomes.Text = "BestChromosomes"; this.tabBestChromosomes.UseVisualStyleBackColor = true; // // gbBestWords // this.gbBestWords.Controls.Add(this.dgvBestResults); this.gbBestWords.Dock = System.Windows.Forms.DockStyle.Fill; this.gbBestWords.Location = new System.Drawing.Point(3, 3); this.gbBestWords.Margin = new System.Windows.Forms.Padding(2); this.gbBestWords.Name = "gbBestWords"; this.gbBestWords.Padding = new System.Windows.Forms.Padding(2); this.gbBestWords.Size = new System.Drawing.Size(284, 542); this.gbBestWords.TabIndex = 0; this.gbBestWords.TabStop = false; this.gbBestWords.Text = "BestResults"; // // dgvBestResults // this.dgvBestResults.AllowUserToAddRows = false; this.dgvBestResults.AllowUserToDeleteRows = false; this.dgvBestResults.AllowUserToOrderColumns = true; dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255))))); this.dgvBestResults.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle2; this.dgvBestResults.ColumnHeadersHeight = 40; this.dgvBestResults.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colWord, this.colFitness}); this.dgvBestResults.Dock = System.Windows.Forms.DockStyle.Fill; this.dgvBestResults.Location = new System.Drawing.Point(2, 15); this.dgvBestResults.Margin = new System.Windows.Forms.Padding(2); this.dgvBestResults.Name = "dgvBestResults"; this.dgvBestResults.ReadOnly = true; this.dgvBestResults.RowHeadersWidth = 15; this.dgvBestResults.RowTemplate.Height = 24; this.dgvBestResults.Size = new System.Drawing.Size(280, 525); this.dgvBestResults.TabIndex = 0; // // colWord // this.colWord.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colWord.HeaderText = "Word"; this.colWord.Name = "colWord"; this.colWord.ReadOnly = true; // // colFitness // this.colFitness.FillWeight = 120F; this.colFitness.HeaderText = "Fitness"; this.colFitness.Name = "colFitness"; this.colFitness.ReadOnly = true; this.colFitness.Width = 120; // // tabWordDictionaries // this.tabWordDictionaries.Controls.Add(this.gbWordDic); this.tabWordDictionaries.Location = new System.Drawing.Point(4, 4); this.tabWordDictionaries.Name = "tabWordDictionaries"; this.tabWordDictionaries.Padding = new System.Windows.Forms.Padding(3); this.tabWordDictionaries.Size = new System.Drawing.Size(290, 548); this.tabWordDictionaries.TabIndex = 1; this.tabWordDictionaries.Text = "WordDictionaries"; this.tabWordDictionaries.UseVisualStyleBackColor = true; // // gbWordDic // this.gbWordDic.Controls.Add(this.tableLayoutPanel1); this.gbWordDic.Dock = System.Windows.Forms.DockStyle.Fill; this.gbWordDic.Location = new System.Drawing.Point(3, 3); this.gbWordDic.Margin = new System.Windows.Forms.Padding(2); this.gbWordDic.Name = "gbWordDic"; this.gbWordDic.Padding = new System.Windows.Forms.Padding(2); this.gbWordDic.Size = new System.Drawing.Size(284, 542); this.gbWordDic.TabIndex = 0; this.gbWordDic.TabStop = false; this.gbWordDic.Text = "WordDictionaries"; // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 1; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Controls.Add(this.btnAddWordDictionaries, 0, 0); this.tableLayoutPanel1.Controls.Add(this.panelExtraWordsDic, 0, 1); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(2, 15); this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(2); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 2; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.399076F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 90.60092F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 16F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(280, 525); this.tableLayoutPanel1.TabIndex = 2; // // btnAddWordDictionaries // this.btnAddWordDictionaries.Anchor = System.Windows.Forms.AnchorStyles.Top; this.btnAddWordDictionaries.Location = new System.Drawing.Point(53, 2); this.btnAddWordDictionaries.Margin = new System.Windows.Forms.Padding(2); this.btnAddWordDictionaries.Name = "btnAddWordDictionaries"; this.btnAddWordDictionaries.Size = new System.Drawing.Size(173, 39); this.btnAddWordDictionaries.TabIndex = 0; this.btnAddWordDictionaries.Text = "AddWordDic"; this.btnAddWordDictionaries.UseVisualStyleBackColor = true; this.btnAddWordDictionaries.Click += new System.EventHandler(this.btnAddWordDictionaries_Click); // // panelExtraWordsDic // this.panelExtraWordsDic.AutoScroll = true; this.panelExtraWordsDic.Dock = System.Windows.Forms.DockStyle.Fill; this.panelExtraWordsDic.Location = new System.Drawing.Point(2, 51); this.panelExtraWordsDic.Margin = new System.Windows.Forms.Padding(2); this.panelExtraWordsDic.Name = "panelExtraWordsDic"; this.panelExtraWordsDic.Size = new System.Drawing.Size(276, 472); this.panelExtraWordsDic.TabIndex = 1; // // containerMain // this.containerMain.Dock = System.Windows.Forms.DockStyle.Fill; this.containerMain.Location = new System.Drawing.Point(0, 24); this.containerMain.Name = "containerMain"; // // containerMain.Panel1 // this.containerMain.Panel1.Controls.Add(this.splitContainer2); // // containerMain.Panel2 // this.containerMain.Panel2.Controls.Add(this.tabExtraTools); this.containerMain.Size = new System.Drawing.Size(1188, 556); this.containerMain.SplitterDistance = 867; this.containerMain.TabIndex = 4; // // splitContainer2 // this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point(0, 0); this.splitContainer2.Name = "splitContainer2"; this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.gbGAToolbox); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add(this.gbResult); this.splitContainer2.Size = new System.Drawing.Size(867, 556); this.splitContainer2.SplitterDistance = 241; this.splitContainer2.TabIndex = 0; // // gbGAToolbox // this.gbGAToolbox.Controls.Add(this.flowLayoutPanel1); this.gbGAToolbox.Dock = System.Windows.Forms.DockStyle.Fill; this.gbGAToolbox.Location = new System.Drawing.Point(0, 0); this.gbGAToolbox.Margin = new System.Windows.Forms.Padding(2); this.gbGAToolbox.Name = "gbGAToolbox"; this.gbGAToolbox.Padding = new System.Windows.Forms.Padding(2); this.gbGAToolbox.Size = new System.Drawing.Size(867, 241); this.gbGAToolbox.TabIndex = 2; this.gbGAToolbox.TabStop = false; this.gbGAToolbox.Text = "PGAToolbox"; // // flowLayoutPanel1 // this.flowLayoutPanel1.AutoScroll = true; this.flowLayoutPanel1.Controls.Add(this.btnStart); this.flowLayoutPanel1.Controls.Add(this.panel4); this.flowLayoutPanel1.Controls.Add(this.panel7); this.flowLayoutPanel1.Controls.Add(this.panel6); this.flowLayoutPanel1.Controls.Add(this.panel5); this.flowLayoutPanel1.Controls.Add(this.panelWordToolbox); this.flowLayoutPanel1.Controls.Add(this.panelGAToolbox); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.TopDown; this.flowLayoutPanel1.Location = new System.Drawing.Point(2, 15); this.flowLayoutPanel1.Margin = new System.Windows.Forms.Padding(2); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Padding = new System.Windows.Forms.Padding(4); this.flowLayoutPanel1.Size = new System.Drawing.Size(863, 224); this.flowLayoutPanel1.TabIndex = 3; // // btnStart // this.btnStart.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnStart.Cursor = System.Windows.Forms.Cursors.Hand; this.btnStart.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnStart.Location = new System.Drawing.Point(6, 6); this.btnStart.Margin = new System.Windows.Forms.Padding(2); this.btnStart.Name = "btnStart"; this.btnStart.Size = new System.Drawing.Size(302, 32); this.btnStart.TabIndex = 0; this.btnStart.Text = "Start"; this.btnStart.UseVisualStyleBackColor = true; this.btnStart.Click += new System.EventHandler(this.btnStart_Click); // // panel4 // this.panel4.Controls.Add(this.lblFitness); this.panel4.Controls.Add(this.label2); this.panel4.Location = new System.Drawing.Point(6, 42); this.panel4.Margin = new System.Windows.Forms.Padding(2); this.panel4.Name = "panel4"; this.panel4.Size = new System.Drawing.Size(302, 26); this.panel4.TabIndex = 10; // // lblFitness // this.lblFitness.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblFitness.Location = new System.Drawing.Point(110, 5); this.lblFitness.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblFitness.Name = "lblFitness"; this.lblFitness.Size = new System.Drawing.Size(187, 14); this.lblFitness.TabIndex = 10; this.lblFitness.Text = "Fitness No"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(2, 5); this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(40, 13); this.label2.TabIndex = 9; this.label2.Text = "Fitness"; // // panel7 // this.panel7.Controls.Add(this.bestChromosomeWord); this.panel7.Location = new System.Drawing.Point(6, 72); this.panel7.Margin = new System.Windows.Forms.Padding(2); this.panel7.Name = "panel7"; this.panel7.Size = new System.Drawing.Size(302, 60); this.panel7.TabIndex = 11; // // bestChromosomeWord // this.bestChromosomeWord.AutoWordSelection = true; this.bestChromosomeWord.BackColor = System.Drawing.Color.WhiteSmoke; this.bestChromosomeWord.BorderStyle = System.Windows.Forms.BorderStyle.None; this.bestChromosomeWord.DetectUrls = false; this.bestChromosomeWord.Dock = System.Windows.Forms.DockStyle.Fill; this.bestChromosomeWord.Fitness = 0D; this.bestChromosomeWord.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bestChromosomeWord.Location = new System.Drawing.Point(0, 0); this.bestChromosomeWord.Margin = new System.Windows.Forms.Padding(2); this.bestChromosomeWord.Name = "bestChromosomeWord"; this.bestChromosomeWord.ReadOnly = true; this.bestChromosomeWord.Size = new System.Drawing.Size(302, 60); this.bestChromosomeWord.TabIndex = 0; this.bestChromosomeWord.Text = ""; // // panel6 // this.panel6.Controls.Add(this.lblTimeEvolving); this.panel6.Controls.Add(this.label6); this.panel6.Location = new System.Drawing.Point(6, 136); this.panel6.Margin = new System.Windows.Forms.Padding(2); this.panel6.Name = "panel6"; this.panel6.Size = new System.Drawing.Size(302, 26); this.panel6.TabIndex = 12; // // lblTimeEvolving // this.lblTimeEvolving.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblTimeEvolving.Location = new System.Drawing.Point(112, 5); this.lblTimeEvolving.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblTimeEvolving.Name = "lblTimeEvolving"; this.lblTimeEvolving.Size = new System.Drawing.Size(184, 14); this.lblTimeEvolving.TabIndex = 10; this.lblTimeEvolving.Text = "TimeEvolving"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(2, 5); this.label6.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(71, 13); this.label6.TabIndex = 9; this.label6.Text = "TimeEvolving"; // // panel5 // this.panel5.Controls.Add(this.lblGeneration); this.panel5.Controls.Add(this.label4); this.panel5.Location = new System.Drawing.Point(6, 166); this.panel5.Margin = new System.Windows.Forms.Padding(2); this.panel5.Name = "panel5"; this.panel5.Size = new System.Drawing.Size(302, 26); this.panel5.TabIndex = 13; // // lblGeneration // this.lblGeneration.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblGeneration.Location = new System.Drawing.Point(110, 5); this.lblGeneration.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblGeneration.Name = "lblGeneration"; this.lblGeneration.Size = new System.Drawing.Size(187, 14); this.lblGeneration.TabIndex = 10; this.lblGeneration.Text = "Generation No"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(2, 5); this.label4.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(59, 13); this.label4.TabIndex = 9; this.label4.Text = "Generation"; // // panelWordToolbox // this.panelWordToolbox.Controls.Add(this.chkHasHyphen); this.panelWordToolbox.Controls.Add(this.chkHasNumeric); this.panelWordToolbox.Controls.Add(this.panel2); this.panelWordToolbox.Controls.Add(this.chkDisplayRealtime); this.panelWordToolbox.Controls.Add(this.panel13); this.panelWordToolbox.Controls.Add(this.panel14); this.panelWordToolbox.Location = new System.Drawing.Point(312, 6); this.panelWordToolbox.Margin = new System.Windows.Forms.Padding(2); this.panelWordToolbox.Name = "panelWordToolbox"; this.panelWordToolbox.Size = new System.Drawing.Size(207, 156); this.panelWordToolbox.TabIndex = 14; // // chkHasHyphen // this.chkHasHyphen.AutoSize = true; this.chkHasHyphen.Location = new System.Drawing.Point(2, 2); this.chkHasHyphen.Margin = new System.Windows.Forms.Padding(2); this.chkHasHyphen.Name = "chkHasHyphen"; this.chkHasHyphen.Size = new System.Drawing.Size(82, 17); this.chkHasHyphen.TabIndex = 1; this.chkHasHyphen.Text = "HasHyphen"; this.chkHasHyphen.UseVisualStyleBackColor = true; // // chkHasNumeric // this.chkHasNumeric.AutoSize = true; this.chkHasNumeric.Location = new System.Drawing.Point(88, 2); this.chkHasNumeric.Margin = new System.Windows.Forms.Padding(2); this.chkHasNumeric.Name = "chkHasNumeric"; this.chkHasNumeric.Size = new System.Drawing.Size(84, 17); this.chkHasNumeric.TabIndex = 2; this.chkHasNumeric.Text = "HasNumeric"; this.chkHasNumeric.UseVisualStyleBackColor = true; // // panel2 // this.panel2.Controls.Add(this.lblWordMaxLen); this.panel2.Controls.Add(this.numWordLen); this.panel2.Location = new System.Drawing.Point(2, 23); this.panel2.Margin = new System.Windows.Forms.Padding(2); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(173, 24); this.panel2.TabIndex = 5; // // lblWordMaxLen // this.lblWordMaxLen.AutoSize = true; this.lblWordMaxLen.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblWordMaxLen.Location = new System.Drawing.Point(2, 5); this.lblWordMaxLen.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblWordMaxLen.Name = "lblWordMaxLen"; this.lblWordMaxLen.Size = new System.Drawing.Size(58, 13); this.lblWordMaxLen.TabIndex = 4; this.lblWordMaxLen.Text = "WordLen"; // // numWordLen // this.numWordLen.Location = new System.Drawing.Point(115, 3); this.numWordLen.Margin = new System.Windows.Forms.Padding(2); this.numWordLen.Maximum = new decimal(new int[] { 67, 0, 0, 0}); this.numWordLen.Minimum = new decimal(new int[] { 2, 0, 0, 0}); this.numWordLen.Name = "numWordLen"; this.numWordLen.Size = new System.Drawing.Size(56, 20); this.numWordLen.TabIndex = 3; this.numWordLen.Value = new decimal(new int[] { 8, 0, 0, 0}); // // chkDisplayRealtime // this.chkDisplayRealtime.AutoSize = true; this.chkDisplayRealtime.Checked = true; this.chkDisplayRealtime.CheckState = System.Windows.Forms.CheckState.Checked; this.chkDisplayRealtime.Location = new System.Drawing.Point(2, 51); this.chkDisplayRealtime.Margin = new System.Windows.Forms.Padding(2); this.chkDisplayRealtime.Name = "chkDisplayRealtime"; this.chkDisplayRealtime.Size = new System.Drawing.Size(101, 17); this.chkDisplayRealtime.TabIndex = 6; this.chkDisplayRealtime.Text = "DisplayRealtime"; this.chkDisplayRealtime.UseVisualStyleBackColor = true; // // panel13 // this.panel13.Controls.Add(this.label16); this.panel13.Controls.Add(this.label17); this.panel13.Controls.Add(this.numMinimumThread); this.panel13.Location = new System.Drawing.Point(2, 72); this.panel13.Margin = new System.Windows.Forms.Padding(2); this.panel13.Name = "panel13"; this.panel13.Size = new System.Drawing.Size(173, 24); this.panel13.TabIndex = 14; // // label16 // this.label16.AutoSize = true; this.label16.Location = new System.Drawing.Point(210, 5); this.label16.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(0, 13); this.label16.TabIndex = 6; // // label17 // this.label17.AutoSize = true; this.label17.Location = new System.Drawing.Point(2, 5); this.label17.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(82, 13); this.label17.TabIndex = 4; this.label17.Text = "MinimumThread"; // // numMinimumThread // this.numMinimumThread.Location = new System.Drawing.Point(114, 3); this.numMinimumThread.Margin = new System.Windows.Forms.Padding(2); this.numMinimumThread.Maximum = new decimal(new int[] { 1215752191, 23, 0, 0}); this.numMinimumThread.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.numMinimumThread.Name = "numMinimumThread"; this.numMinimumThread.Size = new System.Drawing.Size(57, 20); this.numMinimumThread.TabIndex = 3; this.numMinimumThread.Value = new decimal(new int[] { 30, 0, 0, 0}); // // panel14 // this.panel14.Controls.Add(this.label18); this.panel14.Controls.Add(this.label19); this.panel14.Controls.Add(this.numMaximumThread); this.panel14.Location = new System.Drawing.Point(2, 100); this.panel14.Margin = new System.Windows.Forms.Padding(2); this.panel14.Name = "panel14"; this.panel14.Size = new System.Drawing.Size(173, 24); this.panel14.TabIndex = 15; // // label18 // this.label18.AutoSize = true; this.label18.Location = new System.Drawing.Point(210, 5); this.label18.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(0, 13); this.label18.TabIndex = 6; // // label19 // this.label19.AutoSize = true; this.label19.Location = new System.Drawing.Point(2, 5); this.label19.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(85, 13); this.label19.TabIndex = 4; this.label19.Text = "MaximumThread"; // // numMaximumThread // this.numMaximumThread.Location = new System.Drawing.Point(114, 3); this.numMaximumThread.Margin = new System.Windows.Forms.Padding(2); this.numMaximumThread.Maximum = new decimal(new int[] { 99999999, 0, 0, 0}); this.numMaximumThread.Name = "numMaximumThread"; this.numMaximumThread.Size = new System.Drawing.Size(57, 20); this.numMaximumThread.TabIndex = 3; this.numMaximumThread.Value = new decimal(new int[] { 50, 0, 0, 0}); // // panelGAToolbox // this.panelGAToolbox.Controls.Add(this.panel3); this.panelGAToolbox.Controls.Add(this.panel10); this.panelGAToolbox.Controls.Add(this.panel1); this.panelGAToolbox.Controls.Add(this.panel8); this.panelGAToolbox.Controls.Add(this.panel9); this.panelGAToolbox.Controls.Add(this.panel11); this.panelGAToolbox.Controls.Add(this.panel12); this.panelGAToolbox.Location = new System.Drawing.Point(523, 6); this.panelGAToolbox.Margin = new System.Windows.Forms.Padding(2); this.panelGAToolbox.Name = "panelGAToolbox"; this.panelGAToolbox.Size = new System.Drawing.Size(338, 199); this.panelGAToolbox.TabIndex = 15; // // panel3 // this.panel3.Controls.Add(this.label1); this.panel3.Controls.Add(this.numPopulationSize); this.panel3.Location = new System.Drawing.Point(2, 2); this.panel3.Margin = new System.Windows.Forms.Padding(2); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(336, 24); this.panel3.TabIndex = 6; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(2, 5); this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(77, 13); this.label1.TabIndex = 4; this.label1.Text = "PopulationSize"; // // numPopulationSize // this.numPopulationSize.Location = new System.Drawing.Point(239, 3); this.numPopulationSize.Margin = new System.Windows.Forms.Padding(2); this.numPopulationSize.Maximum = new decimal(new int[] { 9999999, 0, 0, 0}); this.numPopulationSize.Minimum = new decimal(new int[] { 10, 0, 0, 0}); this.numPopulationSize.Name = "numPopulationSize"; this.numPopulationSize.Size = new System.Drawing.Size(74, 20); this.numPopulationSize.TabIndex = 3; this.numPopulationSize.Value = new decimal(new int[] { 100, 0, 0, 0}); // // panel10 // this.panel10.Controls.Add(this.label11); this.panel10.Controls.Add(this.numGenerationKeepingNumber); this.panel10.Location = new System.Drawing.Point(2, 30); this.panel10.Margin = new System.Windows.Forms.Padding(2); this.panel10.Name = "panel10"; this.panel10.Size = new System.Drawing.Size(336, 24); this.panel10.TabIndex = 7; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(2, 5); this.label11.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(135, 13); this.label11.TabIndex = 4; this.label11.Text = "GenerationKeepingNumber"; // // numGenerationKeepingNumber // this.numGenerationKeepingNumber.Location = new System.Drawing.Point(239, 3); this.numGenerationKeepingNumber.Margin = new System.Windows.Forms.Padding(2); this.numGenerationKeepingNumber.Maximum = new decimal(new int[] { 1215752191, 23, 0, 0}); this.numGenerationKeepingNumber.Minimum = new decimal(new int[] { 10, 0, 0, 0}); this.numGenerationKeepingNumber.Name = "numGenerationKeepingNumber"; this.numGenerationKeepingNumber.Size = new System.Drawing.Size(74, 20); this.numGenerationKeepingNumber.TabIndex = 3; this.numGenerationKeepingNumber.Value = new decimal(new int[] { 10, 0, 0, 0}); // // panel1 // this.panel1.Controls.Add(this.label8); this.panel1.Controls.Add(this.label3); this.panel1.Controls.Add(this.numCrossoverProbability); this.panel1.Controls.Add(this.cbCrossover); this.panel1.Location = new System.Drawing.Point(2, 58); this.panel1.Margin = new System.Windows.Forms.Padding(2); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(336, 24); this.panel1.TabIndex = 9; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(313, 5); this.label8.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(15, 13); this.label8.TabIndex = 5; this.label8.Text = "%"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(194, 5); this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(55, 13); this.label3.TabIndex = 4; this.label3.Text = "Probability"; // // numCrossoverProbability // this.numCrossoverProbability.DecimalPlaces = 2; this.numCrossoverProbability.Location = new System.Drawing.Point(253, 2); this.numCrossoverProbability.Margin = new System.Windows.Forms.Padding(2); this.numCrossoverProbability.Name = "numCrossoverProbability"; this.numCrossoverProbability.Size = new System.Drawing.Size(60, 20); this.numCrossoverProbability.TabIndex = 3; this.numCrossoverProbability.Value = new decimal(new int[] { 70, 0, 0, 0}); // // cbCrossover // this.cbCrossover.FormattingEnabled = true; this.cbCrossover.Location = new System.Drawing.Point(2, 2); this.cbCrossover.Name = "cbCrossover"; this.cbCrossover.Size = new System.Drawing.Size(187, 21); this.cbCrossover.TabIndex = 16; // // panel8 // this.panel8.Controls.Add(this.cbMutation); this.panel8.Controls.Add(this.label9); this.panel8.Controls.Add(this.label5); this.panel8.Controls.Add(this.numMutationProbability); this.panel8.Location = new System.Drawing.Point(2, 86); this.panel8.Margin = new System.Windows.Forms.Padding(2); this.panel8.Name = "panel8"; this.panel8.Size = new System.Drawing.Size(336, 24); this.panel8.TabIndex = 10; // // cbMutation // this.cbMutation.FormattingEnabled = true; this.cbMutation.Location = new System.Drawing.Point(2, 1); this.cbMutation.Name = "cbMutation"; this.cbMutation.Size = new System.Drawing.Size(187, 21); this.cbMutation.TabIndex = 17; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(313, 5); this.label9.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(15, 13); this.label9.TabIndex = 6; this.label9.Text = "%"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(194, 5); this.label5.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(55, 13); this.label5.TabIndex = 4; this.label5.Text = "Probability"; // // numMutationProbability // this.numMutationProbability.DecimalPlaces = 2; this.numMutationProbability.Location = new System.Drawing.Point(253, 2); this.numMutationProbability.Margin = new System.Windows.Forms.Padding(2); this.numMutationProbability.Name = "numMutationProbability"; this.numMutationProbability.Size = new System.Drawing.Size(60, 20); this.numMutationProbability.TabIndex = 3; this.numMutationProbability.Value = new decimal(new int[] { 50, 0, 0, 0}); // // panel9 // this.panel9.Controls.Add(this.cbSelection); this.panel9.Controls.Add(this.label10); this.panel9.Controls.Add(this.label7); this.panel9.Controls.Add(this.numEliteSelection); this.panel9.Location = new System.Drawing.Point(2, 114); this.panel9.Margin = new System.Windows.Forms.Padding(2); this.panel9.Name = "panel9"; this.panel9.Size = new System.Drawing.Size(336, 24); this.panel9.TabIndex = 11; // // cbSelection // this.cbSelection.FormattingEnabled = true; this.cbSelection.Location = new System.Drawing.Point(2, 1); this.cbSelection.Name = "cbSelection"; this.cbSelection.Size = new System.Drawing.Size(198, 21); this.cbSelection.TabIndex = 18; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(313, 5); this.label10.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(15, 13); this.label10.TabIndex = 6; this.label10.Text = "%"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(205, 5); this.label7.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(44, 13); this.label7.TabIndex = 4; this.label7.Text = "Percent"; // // numEliteSelection // this.numEliteSelection.Location = new System.Drawing.Point(253, 2); this.numEliteSelection.Margin = new System.Windows.Forms.Padding(2); this.numEliteSelection.Maximum = new decimal(new int[] { 276447231, 23283, 0, 0}); this.numEliteSelection.Minimum = new decimal(new int[] { 4, 0, 0, 0}); this.numEliteSelection.Name = "numEliteSelection"; this.numEliteSelection.Size = new System.Drawing.Size(60, 20); this.numEliteSelection.TabIndex = 3; this.numEliteSelection.Value = new decimal(new int[] { 40, 0, 0, 0}); // // panel11 // this.panel11.Controls.Add(this.label12); this.panel11.Controls.Add(this.label13); this.panel11.Controls.Add(this.numTimeEvolvingTermination); this.panel11.Location = new System.Drawing.Point(2, 142); this.panel11.Margin = new System.Windows.Forms.Padding(2); this.panel11.Name = "panel11"; this.panel11.Size = new System.Drawing.Size(336, 24); this.panel11.TabIndex = 12; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(313, 5); this.label12.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(24, 13); this.label12.TabIndex = 6; this.label12.Text = "Min"; // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(2, 5); this.label13.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(126, 13); this.label13.TabIndex = 4; this.label13.Text = "TimeEvolvingTermination"; // // numTimeEvolvingTermination // this.numTimeEvolvingTermination.Location = new System.Drawing.Point(253, 2); this.numTimeEvolvingTermination.Margin = new System.Windows.Forms.Padding(2); this.numTimeEvolvingTermination.Maximum = new decimal(new int[] { 9999999, 0, 0, 0}); this.numTimeEvolvingTermination.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.numTimeEvolvingTermination.Name = "numTimeEvolvingTermination"; this.numTimeEvolvingTermination.Size = new System.Drawing.Size(60, 20); this.numTimeEvolvingTermination.TabIndex = 3; this.numTimeEvolvingTermination.Value = new decimal(new int[] { 180, 0, 0, 0}); // // panel12 // this.panel12.Controls.Add(this.label14); this.panel12.Controls.Add(this.label15); this.panel12.Controls.Add(this.numFitnessThresholdTermination); this.panel12.Location = new System.Drawing.Point(2, 170); this.panel12.Margin = new System.Windows.Forms.Padding(2); this.panel12.Name = "panel12"; this.panel12.Size = new System.Drawing.Size(336, 24); this.panel12.TabIndex = 13; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(210, 5); this.label14.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(0, 13); this.label14.TabIndex = 6; // // label15 // this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(2, 5); this.label15.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(142, 13); this.label15.TabIndex = 4; this.label15.Text = "FitnessThresholdTermination"; // // numFitnessThresholdTermination // this.numFitnessThresholdTermination.DecimalPlaces = 7; this.numFitnessThresholdTermination.Increment = new decimal(new int[] { 1, 0, 0, 458752}); this.numFitnessThresholdTermination.Location = new System.Drawing.Point(239, 2); this.numFitnessThresholdTermination.Margin = new System.Windows.Forms.Padding(2); this.numFitnessThresholdTermination.Maximum = new decimal(new int[] { 1, 0, 0, 0}); this.numFitnessThresholdTermination.Minimum = new decimal(new int[] { 1874919423, 2328306, 0, -2147483648}); this.numFitnessThresholdTermination.Name = "numFitnessThresholdTermination"; this.numFitnessThresholdTermination.Size = new System.Drawing.Size(74, 20); this.numFitnessThresholdTermination.TabIndex = 3; this.numFitnessThresholdTermination.Value = new decimal(new int[] { 999995, 0, 0, 393216}); // // gbResult // this.gbResult.Controls.Add(this.wpResults); this.gbResult.Dock = System.Windows.Forms.DockStyle.Fill; this.gbResult.Location = new System.Drawing.Point(0, 0); this.gbResult.Margin = new System.Windows.Forms.Padding(2); this.gbResult.Name = "gbResult"; this.gbResult.Padding = new System.Windows.Forms.Padding(2); this.gbResult.Size = new System.Drawing.Size(867, 311); this.gbResult.TabIndex = 1; this.gbResult.TabStop = false; this.gbResult.Text = "Result"; // // wpResults // this.wpResults.AutoScroll = true; this.wpResults.AutoSize = true; this.wpResults.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.wpResults.Dock = System.Windows.Forms.DockStyle.Fill; this.wpResults.Location = new System.Drawing.Point(2, 15); this.wpResults.Margin = new System.Windows.Forms.Padding(2); this.wpResults.Name = "wpResults"; this.wpResults.Size = new System.Drawing.Size(863, 294); this.wpResults.TabIndex = 0; this.wpResults.WordsLabels = null; // // CoolNameResultForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1188, 580); this.Controls.Add(this.containerMain); this.Controls.Add(this.menuStrip); this.MainMenuStrip = this.menuStrip; this.Margin = new System.Windows.Forms.Padding(2); this.Name = "CoolNameResultForm"; this.Text = "CoolNameGenerator_PGA"; this.menuStrip.ResumeLayout(false); this.menuStrip.PerformLayout(); this.tabExtraTools.ResumeLayout(false); this.tabBestChromosomes.ResumeLayout(false); this.gbBestWords.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dgvBestResults)).EndInit(); this.tabWordDictionaries.ResumeLayout(false); this.gbWordDic.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); this.containerMain.Panel1.ResumeLayout(false); this.containerMain.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.containerMain)).EndInit(); this.containerMain.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit(); this.splitContainer2.ResumeLayout(false); this.gbGAToolbox.ResumeLayout(false); this.flowLayoutPanel1.ResumeLayout(false); this.panel4.ResumeLayout(false); this.panel4.PerformLayout(); this.panel7.ResumeLayout(false); this.panel6.ResumeLayout(false); this.panel6.PerformLayout(); this.panel5.ResumeLayout(false); this.panel5.PerformLayout(); this.panelWordToolbox.ResumeLayout(false); this.panelWordToolbox.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numWordLen)).EndInit(); this.panel13.ResumeLayout(false); this.panel13.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numMinimumThread)).EndInit(); this.panel14.ResumeLayout(false); this.panel14.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numMaximumThread)).EndInit(); this.panelGAToolbox.ResumeLayout(false); this.panel3.ResumeLayout(false); this.panel3.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numPopulationSize)).EndInit(); this.panel10.ResumeLayout(false); this.panel10.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numGenerationKeepingNumber)).EndInit(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numCrossoverProbability)).EndInit(); this.panel8.ResumeLayout(false); this.panel8.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numMutationProbability)).EndInit(); this.panel9.ResumeLayout(false); this.panel9.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numEliteSelection)).EndInit(); this.panel11.ResumeLayout(false); this.panel11.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numTimeEvolvingTermination)).EndInit(); this.panel12.ResumeLayout(false); this.panel12.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numFitnessThresholdTermination)).EndInit(); this.gbResult.ResumeLayout(false); this.gbResult.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator; private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem printPreviewToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem finglishConverterToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem searchToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem persianToolStripMenuItem; private System.Windows.Forms.TabControl tabExtraTools; private System.Windows.Forms.TabPage tabBestChromosomes; private System.Windows.Forms.TabPage tabWordDictionaries; private System.Windows.Forms.SplitContainer containerMain; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.GroupBox gbResult; private Graphics.WordsPanel wpResults; private System.Windows.Forms.GroupBox gbGAToolbox; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button btnStart; private System.Windows.Forms.Panel panel4; private System.Windows.Forms.Label lblFitness; private System.Windows.Forms.Label label2; private System.Windows.Forms.Panel panel7; private Graphics.WordLabel bestChromosomeWord; private System.Windows.Forms.Panel panel6; private System.Windows.Forms.Label lblTimeEvolving; private System.Windows.Forms.Label label6; private System.Windows.Forms.Panel panel5; private System.Windows.Forms.Label lblGeneration; private System.Windows.Forms.Label label4; private System.Windows.Forms.FlowLayoutPanel panelWordToolbox; private System.Windows.Forms.CheckBox chkHasHyphen; private System.Windows.Forms.CheckBox chkHasNumeric; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Label lblWordMaxLen; private System.Windows.Forms.NumericUpDown numWordLen; private System.Windows.Forms.CheckBox chkDisplayRealtime; private System.Windows.Forms.FlowLayoutPanel panelGAToolbox; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.Label label1; private System.Windows.Forms.NumericUpDown numPopulationSize; private System.Windows.Forms.Panel panel10; private System.Windows.Forms.Label label11; private System.Windows.Forms.NumericUpDown numGenerationKeepingNumber; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label3; private System.Windows.Forms.NumericUpDown numCrossoverProbability; private System.Windows.Forms.Panel panel8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label5; private System.Windows.Forms.NumericUpDown numMutationProbability; private System.Windows.Forms.Panel panel9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label7; private System.Windows.Forms.NumericUpDown numEliteSelection; private System.Windows.Forms.GroupBox gbBestWords; private System.Windows.Forms.DataGridView dgvBestResults; private System.Windows.Forms.DataGridViewTextBoxColumn colWord; private System.Windows.Forms.DataGridViewTextBoxColumn colFitness; private System.Windows.Forms.GroupBox gbWordDic; private System.Windows.Forms.Button btnAddWordDictionaries; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.FlowLayoutPanel panelExtraWordsDic; private System.Windows.Forms.Panel panel11; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label13; private System.Windows.Forms.NumericUpDown numTimeEvolvingTermination; private System.Windows.Forms.Panel panel12; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label15; private System.Windows.Forms.NumericUpDown numFitnessThresholdTermination; private System.Windows.Forms.Panel panel13; private System.Windows.Forms.Label label16; private System.Windows.Forms.Label label17; private System.Windows.Forms.NumericUpDown numMinimumThread; private System.Windows.Forms.Panel panel14; private System.Windows.Forms.Label label18; private System.Windows.Forms.Label label19; private System.Windows.Forms.NumericUpDown numMaximumThread; private System.Windows.Forms.ComboBox cbCrossover; private System.Windows.Forms.ComboBox cbMutation; private System.Windows.Forms.ComboBox cbSelection; } }
51.561737
172
0.612694
[ "Apache-2.0" ]
Behzadkhosravifar/CoolNameGenerator
src/CoolNameGenerator/Forms/CoolNameResultForm.Designer.cs
76,004
C#
// <auto-generated/> #pragma warning disable 1591 #pragma warning disable 0414 #pragma warning disable 0649 #pragma warning disable 0169 namespace Radzen.Blazor { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #line 1 "D:\c#\blazor\vtl-nvp\Radzen.Blazor\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #line 1 "D:\c#\blazor\vtl-nvp\Radzen.Blazor\RadzenFileInput.razor" using Radzen; #line default #line hidden #line 2 "D:\c#\blazor\vtl-nvp\Radzen.Blazor\RadzenFileInput.razor" using Radzen.Blazor.Rendering; #line default #line hidden #line 3 "D:\c#\blazor\vtl-nvp\Radzen.Blazor\RadzenFileInput.razor" using Microsoft.JSInterop; #line default #line hidden #line 4 "D:\c#\blazor\vtl-nvp\Radzen.Blazor\RadzenFileInput.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden public partial class RadzenFileInput<TValue> : FormComponent<TValue> { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { } #pragma warning restore 1998 } } #pragma warning restore 1591
25.88
118
0.751932
[ "MIT" ]
longvutam/vtl-nvp
Radzen.Blazor/obj/Debug/net5.0/RazorDeclaration/RadzenFileInput.razor.g.cs
1,294
C#
namespace DS4Windows { public class HidDeviceCapabilities { internal HidDeviceCapabilities(NativeMethods.HIDP_CAPS capabilities) { Usage = capabilities.Usage; UsagePage = capabilities.UsagePage; InputReportByteLength = capabilities.InputReportByteLength; OutputReportByteLength = capabilities.OutputReportByteLength; FeatureReportByteLength = capabilities.FeatureReportByteLength; Reserved = capabilities.Reserved; NumberLinkCollectionNodes = capabilities.NumberLinkCollectionNodes; NumberInputButtonCaps = capabilities.NumberInputButtonCaps; NumberInputValueCaps = capabilities.NumberInputValueCaps; NumberInputDataIndices = capabilities.NumberInputDataIndices; NumberOutputButtonCaps = capabilities.NumberOutputButtonCaps; NumberOutputValueCaps = capabilities.NumberOutputValueCaps; NumberOutputDataIndices = capabilities.NumberOutputDataIndices; NumberFeatureButtonCaps = capabilities.NumberFeatureButtonCaps; NumberFeatureValueCaps = capabilities.NumberFeatureValueCaps; NumberFeatureDataIndices = capabilities.NumberFeatureDataIndices; } public ushort Usage { get; private set; } public ushort UsagePage { get; private set; } public short InputReportByteLength { get; private set; } public short OutputReportByteLength { get; private set; } public short FeatureReportByteLength { get; private set; } public short[] Reserved { get; private set; } public short NumberLinkCollectionNodes { get; private set; } public short NumberInputButtonCaps { get; private set; } public short NumberInputValueCaps { get; private set; } public short NumberInputDataIndices { get; private set; } public short NumberOutputButtonCaps { get; private set; } public short NumberOutputValueCaps { get; private set; } public short NumberOutputDataIndices { get; private set; } public short NumberFeatureButtonCaps { get; private set; } public short NumberFeatureValueCaps { get; private set; } public short NumberFeatureDataIndices { get; private set; } } }
52.204545
79
0.707444
[ "MIT" ]
Adminixtrator/DS4Windows
DS4Windows/HidLibrary/HidDeviceCapabilities.cs
2,299
C#
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CAIActionBruxaFriendlyAttackAction : CAINpcActionSubtree { public CAIActionBruxaFriendlyAttackAction(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAIActionBruxaFriendlyAttackAction(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
32.434783
146
0.760054
[ "MIT" ]
DerinHalil/CP77Tools
CP77.CR2W/Types/W3/RTTIConvert/CAIActionBruxaFriendlyAttackAction.cs
724
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V231.Segment; using NHapi.Model.V231.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V231.Group { ///<summary> ///Represents the RRD_O02_RESPONSE Group. A Group is an ordered collection of message /// segments that can repeat together or be optionally in/excluded together. /// This Group contains the following elements: ///<ol> ///<li>0: RRD_O02_PATIENT (a Group object) optional </li> ///<li>1: RRD_O02_ORDER (a Group object) repeating</li> ///</ol> ///</summary> [Serializable] public class RRD_O02_RESPONSE : AbstractGroup { ///<summary> /// Creates a new RRD_O02_RESPONSE Group. ///</summary> public RRD_O02_RESPONSE(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(RRD_O02_PATIENT), false, false); this.add(typeof(RRD_O02_ORDER), true, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating RRD_O02_RESPONSE - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns RRD_O02_PATIENT (a Group object) - creates it if necessary ///</summary> public RRD_O02_PATIENT PATIENT { get{ RRD_O02_PATIENT ret = null; try { ret = (RRD_O02_PATIENT)this.GetStructure("PATIENT"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of RRD_O02_ORDER (a Group object) - creates it if necessary ///</summary> public RRD_O02_ORDER GetORDER() { RRD_O02_ORDER ret = null; try { ret = (RRD_O02_ORDER)this.GetStructure("ORDER"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of RRD_O02_ORDER /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public RRD_O02_ORDER GetORDER(int rep) { return (RRD_O02_ORDER)this.GetStructure("ORDER", rep); } /** * Returns the number of existing repetitions of RRD_O02_ORDER */ public int ORDERRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("ORDER").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the RRD_O02_ORDER results */ public IEnumerable<RRD_O02_ORDER> ORDERs { get { for (int rep = 0; rep < ORDERRepetitionsUsed; rep++) { yield return (RRD_O02_ORDER)this.GetStructure("ORDER", rep); } } } ///<summary> ///Adds a new RRD_O02_ORDER ///</summary> public RRD_O02_ORDER AddORDER() { return this.AddStructure("ORDER") as RRD_O02_ORDER; } ///<summary> ///Removes the given RRD_O02_ORDER ///</summary> public void RemoveORDER(RRD_O02_ORDER toRemove) { this.RemoveStructure("ORDER", toRemove); } ///<summary> ///Removes the RRD_O02_ORDER at the given index ///</summary> public void RemoveORDERAt(int index) { this.RemoveRepetition("ORDER", index); } } }
29.428571
155
0.66326
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
afaonline/nHapi
src/NHapi.Model.V231/Group/RRD_O02_RESPONSE.cs
3,914
C#
using System.Collections.Generic; using System.Linq; using Moq; namespace Casino.Tests.DSL { public class GameBuilder { private readonly List<Player> _players = new List<Player>(); private IDice _dice; public GameBuilder WithDiceWhichAlwaysDropsOne() { var dice = new Mock<IDice>(); dice.Setup(x => x.GetDiceDropNumber()).Returns(1); _dice = dice.Object; return this; } public GameBuilder WithPlayer(Player player) { _players.Add(player); return this; } public GameBuilder WithSixJoinedPlayers() { _players.AddRange(Enumerable.Range(0, 6).Select(s => new Player())); return this; } public Game Build() { var game = _dice != null ? new Game(_dice) : new Game(); foreach (var player in _players) { player.Join(game); } return game; } } }
23.613636
80
0.525505
[ "MIT" ]
Ceridan/Casino
Casino.Tests/DSL/GameBuilder.cs
1,041
C#
using System; using System.Collections.Generic; using Public.Common.Lib.Visuals; namespace Eshunna.Lib { /// <summary> /// Scales an image down to a maximum allowable size. The maximum size is given in terms of a maximum dimension size, such that whether landscape or portrait oriented (whether height or width respectively is the maximum dimension), the maximum dimension will be as specified. /// Images for which the maximum dimension size is already smaller than the desired maximum dimension size will remain the same size (scale factor of 1). I.e., these images will NOT be scaled up. /// </summary> public class MaximumDimensionSizeImageScaler { #region Static public static readonly int MaximumAllowedImageDimension = 800; /// <summary> /// Gets the scale factor required to shrink an image from its current size to a size that has a largest dimension equal to the maximum allowed dimension size. /// </summary> /// <param name="imageSize"></param> /// <returns></returns> public static double ScaleFactorToMaximumAllowedImageDimension(ImageSize imageSize) { int largestImageDimension = imageSize.Width > imageSize.Height ? imageSize.Width : imageSize.Height; double maximumAllowedImageDimension = Convert.ToDouble(MaximumDimensionSizeImageScaler.MaximumAllowedImageDimension); double largestImageDimensionDouble = Convert.ToDouble(largestImageDimension); double output; if(largestImageDimensionDouble > maximumAllowedImageDimension) { output = largestImageDimension / maximumAllowedImageDimension; } else { output = 1; } return output; } public static double ScaleFactorFromMaximumAllowedImageDimension(ImageSize current, ImageSize original) { int largestCurrentImageDimension = current.Width > current.Height ? current.Width : current.Height; int largestOriginalImageDimension = original.Width > original.Height ? original.Width : original.Height; double largestCurrentImageDimensionDbl = Convert.ToDouble(largestCurrentImageDimension); double largestOriginalImageDimensionDbl = Convert.ToDouble(largestOriginalImageDimension); double output = largestOriginalImageDimensionDbl / largestCurrentImageDimensionDbl; return output; } #endregion } }
44.084746
280
0.677432
[ "MIT" ]
MinexAutomation/Public
Source/Malachite/Scripts/Eshunna/Eshunna.Lib/Code/Classes/MaximumDimensionSizeImageScaler.cs
2,603
C#
using AutoMapper; using CloudConsult.Identity.Domain.Entities; using CloudConsult.Identity.Domain.Events; using CloudConsult.Identity.Domain.Responses; namespace CloudConsult.Identity.Infrastructure.Mappers { public class IdentityMapper : Profile { public IdentityMapper() { CreateMap<User, CreateUserResponse>() .ForMember(x => x.Roles, y => y.MapFrom(z => string.Join(',', z.UserRoles.Select(r => r.Role.RoleName)))); CreateMap<UserOtp, OtpGenerated>().ConstructUsing(x => OtpGeneratedMapper(x)); } private static OtpGenerated OtpGeneratedMapper(UserOtp userOtp) { return new OtpGenerated { EventId = userOtp.Id, EmailId = userOtp.User.EmailId, FullName = userOtp.User.FullName, IdentityId = userOtp.UserId, Otp = userOtp.Otp }; } } }
31.866667
122
0.600418
[ "MIT" ]
devntofficial/CloudConsultRC
NET Microservices/identity-service/CloudConsult.Identity.Infrastructure/Mappers/IdentityMapper.cs
958
C#
/***************************************************************************** Copyright 2018 The TensorFlow.NET Authors. 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 Tensorflow.Keras.ArgsDefinition; using Tensorflow.Keras.Layers; using static Tensorflow.Binding; namespace Tensorflow.Keras.Engine { public class Sequential : Model, ITensorFlowObject { #pragma warning disable CS0649 // Field 'Sequential._is_graph_network' is never assigned to, and will always have its default value false bool _is_graph_network; #pragma warning restore CS0649 // Field 'Sequential._is_graph_network' is never assigned to, and will always have its default value false Tensor outputs; bool computeOutputAndMaskJointly; bool autoTrackSubLayers; TensorShape inferredInputShape; bool hasExplicitInputShape; TF_DataType inputDType; Layer[] layers; public Sequential(Layer[] layers = null, string name = null) : base(new ModelArgs { Name = name}) { this.layers = layers ?? new Layer[0]; SupportsMasking = true; computeOutputAndMaskJointly = true; autoTrackSubLayers = false; hasExplicitInputShape = false; } public void __enter__() { } public void add(Tensor layer) { } /// <summary> /// Adds a layer instance on top of the layer stack. /// </summary> /// <param name="layer"></param> public void add(Layer layer) { built = false; var set_inputs = false; if(layers.Length == 0) { if(layer is InputLayer) { set_inputs = true; } else { if (layer.BatchInputShape != null) { // Instantiate an input layer. var x = tf.keras.Input( shape: layer.BatchInputShape, dtype: layer.DType, name: layer.Name + "_input"); // This will build the current layer // and create the node connecting the current layer // to the input layer we just created. layer.Apply(x); set_inputs = true; } } if (set_inputs) { // If an input layer (placeholder) is available. outputs = layer.InboundNodes[^1].Outputs; } } if (set_inputs || _is_graph_network) { } } public void __exit__() { } public void Dispose() { } public void __init__() { } public void __del__() { } } }
29.814516
137
0.503652
[ "Apache-2.0" ]
BlueCode2019/TensorFlow.NET
src/TensorFlowNET.Core/Keras/Engine/Sequential.cs
3,699
C#
using System; using MongoDB.Driver; namespace QuizBotCore.Database { public class MessageTextRepository { public const string CollectionName = "telegramMessages"; private readonly IMongoCollection<DialogMessages> textCollection; public DialogMessages Messages { get; private set; } public MessageTextRepository(IMongoDatabase database) { textCollection = database.GetCollection<DialogMessages>(CollectionName); var result = textCollection.Find(_ => true); if (result.Any()) { Messages = result.First(); } else { Messages = new DialogMessages(Guid.Empty); textCollection.InsertOne(Messages); } } public bool SetMessages(Guid id) { var result = textCollection.Find(m => m.Id == id); if (result.Any()) { Messages = result.First(); return true; } return false; } public bool UpdateMessages() => SetMessages(Messages.Id); } }
26
84
0.542735
[ "Apache-2.0" ]
742PM/Quiz
Quiz/QuizBotCore/Database/MessageTextRepository.cs
1,172
C#
using System.Collections.Generic; namespace DynamicsCrm.DevKit.Shared.Models.Cli { public class JsonGenerator { public string profile { get; set; } public string rootfolder { get; set; } public string rootnamespace { get; set; } public string type { get; set; } public string crmversion { get; set; } public string debug { get; set; } } }
26.733333
49
0.625935
[ "MIT" ]
allandecastro/Dynamics-Crm-DevKit
v2/DynamicsCrm.DevKit.Shared/Models/Cli/JsonGenerator.cs
403
C#
using System; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; namespace AbpTailwindBlazor { public class Program { public static int Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG .MinimumLevel.Debug() #else .MinimumLevel.Information() #endif .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG .WriteTo.Async(c => c.Console()) #endif .CreateLogger(); try { Log.Information("Starting AbpTailwindBlazor.HttpApi.Host."); CreateHostBuilder(args).Build().Run(); return 0; } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly!"); return 1; } finally { Log.CloseAndFlush(); } } internal static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .AddAppSettingsSecretsJson() .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .UseAutofac() .UseSerilog(); } }
28.824561
94
0.531345
[ "MIT" ]
antosubash/AbpTailwindBlazor
src/AbpTailwindBlazor.HttpApi.Host/Program.cs
1,645
C#
using System; using System.Collections; using System.Collections.Generic; using SkyFramework; using UnityEngine; using UnityEngine.Events; namespace SkyFramework { /// <summary> /// 事件中心 /// </summary> public class EventSystem : SingletonMono<EventSystem> { private Dictionary<string, UnityAction<IEventArgs>> eventDic = new Dictionary<string, UnityAction<IEventArgs>>(); /// <summary> /// 添加事件监听 /// </summary> /// <param name="eventID"></param> /// <param name="action"></param> public void AddEvent(string eventID, UnityAction<IEventArgs> action) { if (eventDic.ContainsKey(eventID)) { eventDic[eventID] += action; } else { eventDic[eventID] = action; } } /// <summary> /// 发送事件 /// </summary> /// <param name="eventID"></param> /// <param name="args"></param> public void SendEvent(string eventID, IEventArgs args = null) { if (eventDic.ContainsKey(eventID)) { eventDic[eventID].Invoke(args); } } /// <summary> /// 移除事件监听 /// </summary> /// <param name="eventID"></param> /// <param name="action"></param> public void RemoveEvent(string eventID, UnityAction<IEventArgs> action) { if (eventDic.ContainsKey(eventID)) { eventDic[eventID] -= action; } } /// <summary> /// 清空事件中心 /// </summary> public void Clear() { eventDic.Clear(); } } }
25.173913
121
0.498561
[ "MIT" ]
magicskysword/SkyFramework
Assets/SkyFramework/Runtime/Event/EventSystem.cs
1,789
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101 { using static Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Extensions; /// <summary>Additional details of Sub Tasks</summary> public partial class JobSubTaskAdditionalDetails : Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.IJobSubTaskAdditionalDetails, Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.IJobSubTaskAdditionalDetailsInternal { /// <summary>Creates an new <see cref="JobSubTaskAdditionalDetails" /> instance.</summary> public JobSubTaskAdditionalDetails() { } } /// Additional details of Sub Tasks public partial interface IJobSubTaskAdditionalDetails : Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.IJsonSerializable, Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.IAssociativeArray<string> { } /// Additional details of Sub Tasks internal partial interface IJobSubTaskAdditionalDetailsInternal { } }
37.266667
112
0.734347
[ "MIT" ]
AverageDesigner/azure-powershell
src/DataProtection/generated/api/Models/Api202101/JobSubTaskAdditionalDetails.cs
1,089
C#
namespace DragonSpark.Identity.DeviantArt.Claims; public sealed class Website : DeviantArtClaim { public static Website Default { get; } = new (); Website() : base(nameof(Website).ToLower()) {} }
25
50
0.73
[ "MIT" ]
DragonSpark/Framework
DragonSpark.Identity.DeviantArt/Claims/Website.cs
202
C#
using System.Drawing; using SpaceSim.Kernels; using SpaceSim.Orbits; using VectorMath; namespace SpaceSim.SolarSystem.Moons { class Moon : MassiveBodyBase { public override string ApoapsisName { get { return "Aposelene"; } } public override string PeriapsisName { get { return "Periselene"; } } public override double Mass { get { return 7.3477e22; } } public override double SurfaceRadius { get { return BaseKernel.MOON_RADIUS; } } public override double AtmosphereHeight { get { return 0.0; } } public override double RotationRate { get { return -2.6616665019555815474155301717917e-6; } } public override double RotationPeriod { get { return 2332800; } } public override Color IconColor { get { return Color.LightGray; } } public override Color IconAtmopshereColor { get { return Color.White; } } public Moon(DVector2 parentPositon, DVector2 parentVelocity) : base(OrbitHelper.FromJplEphemeris(-1.275488485528684E+05, -3.756609087364946E+05) + parentPositon, OrbitHelper.FromJplEphemeris(9.291844409239249E-01, -2.857101216046916E-01) + parentVelocity, new MoonKernel()) { } public override double GetAtmosphericDensity(double height) { return 0.0; } public override string ToString() { return "Moon"; } } }
28.086207
131
0.577655
[ "MIT" ]
JohnnyOneSpeed/SpaceSim
src/SpaceSim/SolarSystem/Moons/Moon.cs
1,631
C#
using System.Collections.Generic; using NBitcoin.BitcoinCore; namespace NBitcoin { public interface IStandardScriptsRegistry { void RegisterStandardScriptTemplate(ScriptTemplate scriptTemplate); bool IsStandardTransaction(Transaction tx, Network network); bool AreOutputsStandard(Network network, Transaction tx); ScriptTemplate GetTemplateFromScriptPubKey(Script script); bool IsStandardScriptPubKey(Network network, Script scriptPubKey); bool AreInputsStandard(Network network, Transaction tx, CoinsView coinsView); List<ScriptTemplate> GetScriptTemplates { get; } } }
28.130435
85
0.75425
[ "MIT" ]
zeptin/StratisFullNode
src/NBitcoin/IStandardScriptsRegistry.cs
649
C#
#pragma checksum "C:\c-\Lab_90_MVC_core\Views\Home\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "335f069dd332764f947c3abb0ad5753f2ffa084e" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Index), @"mvc.1.0.view", @"/Views/Home/Index.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Home/Index.cshtml", typeof(AspNetCore.Views_Home_Index))] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "C:\c-\Lab_90_MVC_core\Views\_ViewImports.cshtml" using Lab_90_MVC_core; #line default #line hidden #line 2 "C:\c-\Lab_90_MVC_core\Views\_ViewImports.cshtml" using Lab_90_MVC_core.Models; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"335f069dd332764f947c3abb0ad5753f2ffa084e", @"/Views/Home/Index.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"4d3d9bb11ccac9ff3b314639d421168605c640b9", @"/Views/_ViewImports.cshtml")] public class Views_Home_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/images/banner1.svg"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("alt", new global::Microsoft.AspNetCore.Html.HtmlString("ASP.NET"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("img-responsive"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/images/banner2.svg"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("alt", new global::Microsoft.AspNetCore.Html.HtmlString("Visual Studio"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/images/banner3.svg"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("alt", new global::Microsoft.AspNetCore.Html.HtmlString("Microsoft Azure"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #line 1 "C:\c-\Lab_90_MVC_core\Views\Home\Index.cshtml" ViewData["Title"] = "Home Page"; #line default #line hidden BeginContext(45, 746, true); WriteLiteral(@" <h1 style=""margin-bottom:200px""></h1> <h2 id=""defaultheader"">You will see this when you open the website</h2> <style> #defaultheader{ margin-bottom: 100px; margin-top: 50px; padding-left: 20%; background-color: azure; height: 5vh; } </style> <div id=""myCarousel"" class=""carousel slide"" data-ride=""carousel"" data-interval=""6000""> <ol class=""carousel-indicators""> <li data-target=""#myCarousel"" data-slide-to=""0"" class=""active""></li> <li data-target=""#myCarousel"" data-slide-to=""1""></li> <li data-target=""#myCarousel"" data-slide-to=""2""></li> </ol> <div class=""carousel-inner"" role=""listbox""> <div class=""item active""> "); EndContext(); BeginContext(791, 71, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "e89ebd6e6114439c99a7894831c84008", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(862, 432, true); WriteLiteral(@" <div class=""carousel-caption"" role=""option""> <p> Learn how to build ASP.NET apps that can run anywhere. <a class=""btn btn-default"" href=""https://go.microsoft.com/fwlink/?LinkID=525028&clcid=0x409""> Learn More </a> </p> </div> </div> <div class=""item""> "); EndContext(); BeginContext(1294, 77, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea05d428061741a596edffc48b3f3e94", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1371, 456, true); WriteLiteral(@" <div class=""carousel-caption"" role=""option""> <p> There are powerful new features in Visual Studio for building modern web apps. <a class=""btn btn-default"" href=""https://go.microsoft.com/fwlink/?LinkID=525030&clcid=0x409""> Learn More </a> </p> </div> </div> <div class=""item""> "); EndContext(); BeginContext(1827, 79, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "e217d7924d5a48ce93e618c4f13be445", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1906, 3236, true); WriteLiteral(@" <div class=""carousel-caption"" role=""option""> <p> Learn how Microsoft's Azure cloud platform allows you to build, deploy, and scale web apps. <a class=""btn btn-default"" href=""https://go.microsoft.com/fwlink/?LinkID=525027&clcid=0x409""> Learn More </a> </p> </div> </div> </div> <a class=""left carousel-control"" href=""#myCarousel"" role=""button"" data-slide=""prev""> <span class=""glyphicon glyphicon-chevron-left"" aria-hidden=""true""></span> <span class=""sr-only"">Previous</span> </a> <a class=""right carousel-control"" href=""#myCarousel"" role=""button"" data-slide=""next""> <span class=""glyphicon glyphicon-chevron-right"" aria-hidden=""true""></span> <span class=""sr-only"">Next</span> </a> </div> <div class=""row""> <div class=""col-md-3""> <h2>Application uses</h2> <ul> <li>Sam"); WriteLiteral(@"ple pages using ASP.NET Core MVC</li> <li>Theming using <a href=""https://go.microsoft.com/fwlink/?LinkID=398939"">Bootstrap</a></li> </ul> </div> <div class=""col-md-3""> <h2>How to</h2> <ul> <li><a href=""https://go.microsoft.com/fwlink/?LinkID=398600"">Add a Controller and View</a></li> <li><a href=""https://go.microsoft.com/fwlink/?LinkId=699315"">Manage User Secrets using Secret Manager.</a></li> <li><a href=""https://go.microsoft.com/fwlink/?LinkId=699316"">Use logging to log a message.</a></li> <li><a href=""https://go.microsoft.com/fwlink/?LinkId=699317"">Add packages using NuGet.</a></li> <li><a href=""https://go.microsoft.com/fwlink/?LinkId=699319"">Target development, staging or production environment.</a></li> </ul> </div> <div class=""col-md-3""> <h2>Overview</h2> <ul> <li><a href=""https://go.microsoft.com/fwlink/?LinkId=518008"">Conceptual overview o"); WriteLiteral(@"f what is ASP.NET Core</a></li> <li><a href=""https://go.microsoft.com/fwlink/?LinkId=699320"">Fundamentals of ASP.NET Core such as Startup and middleware.</a></li> <li><a href=""https://go.microsoft.com/fwlink/?LinkId=398602"">Working with Data</a></li> <li><a href=""https://go.microsoft.com/fwlink/?LinkId=398603"">Security</a></li> <li><a href=""https://go.microsoft.com/fwlink/?LinkID=699321"">Client side development</a></li> <li><a href=""https://go.microsoft.com/fwlink/?LinkID=699322"">Develop on different platforms</a></li> <li><a href=""https://go.microsoft.com/fwlink/?LinkID=699323"">Read more on the documentation site</a></li> </ul> </div> <div class=""col-md-3""> <h2>Run &amp; Deploy</h2> <ul> <li><a href=""https://go.microsoft.com/fwlink/?LinkID=517851"">Run your app</a></li> <li><a href=""https://go.microsoft.com/fwlink/?LinkID=517853"">Run tools such as EF migrations and more<"); WriteLiteral("/a></li>\r\n <li><a href=\"https://go.microsoft.com/fwlink/?LinkID=398609\">Publish to Microsoft Azure Web Apps</a></li>\r\n </ul>\r\n </div>\r\n</div>\r\n"); EndContext(); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
62.776423
356
0.684517
[ "MIT" ]
SebastianTrifa/c-
Lab_90_MVC_core/obj/Debug/netcoreapp2.1/Razor/Views/Home/Index.g.cshtml.cs
15,443
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using WPF.DataForms.Mapping.FieldDescriptions.Base; namespace WPF.DataForms.Mapping.FieldDescriptions { /// <summary> /// CustomPropertyDefinition /// </summary> public class CustomDescription : FieldDescription { public CustomDescription(String displayName, Type controlType, Action<FrameworkElementFactory> action) : base(displayName) { CustomControlType = controlType; Action = action; } /// <summary> /// /// </summary> public Action<FrameworkElementFactory> Action { get; private set; } /// <summary> /// ControlType /// </summary> public Type CustomControlType { get; private set; } } }
25.542857
110
0.630872
[ "MIT" ]
usercode/WPF.DataForms
src/WPF.DataForms/Mapping/FieldDescriptions/CustomDescription.cs
896
C#
using KAMI.Cameras; using KAMI.Utilities; using System; namespace KAMI.Games { public class Killzone3PS3 : Game<HVecVACamera> { DerefChain m_hor; DerefChain m_vert; public Killzone3PS3(IntPtr ipc, string version) : base(ipc) { var baseChain = version switch { "01.00" => DerefChain.CreateDerefChain(ipc, 0x1587880 + 0x760, 0x38, 0x0, 0x68), "01.14" => DerefChain.CreateDerefChain(ipc, 0x15fcf80 + 0x770, 0x40, 0x68), _ => throw new NotImplementedException($"{nameof(Killzone3PS3)} with version '{version}' not implemented"), }; m_vert = baseChain.Chain(0x150).Chain(0xA0); m_hor = baseChain.Chain(0xFC).Chain(0x14).Chain(0xB0); } public override void UpdateCamera(int diffX, int diffY) { if (DerefChain.VerifyChains(m_hor, m_vert)) { m_camera.HorY = IPCUtils.ReadFloat(m_ipc, (uint)m_hor.Value); m_camera.HorX = IPCUtils.ReadFloat(m_ipc, (uint)(m_hor.Value + 4)); m_camera.Vert = IPCUtils.ReadFloat(m_ipc, (uint)m_vert.Value); m_camera.Update(diffX * SensModifier, -diffY * SensModifier); IPCUtils.WriteFloat(m_ipc, (uint)m_hor.Value, m_camera.HorY); IPCUtils.WriteFloat(m_ipc, (uint)(m_hor.Value + 4), m_camera.HorX); IPCUtils.WriteFloat(m_ipc, (uint)m_vert.Value, m_camera.Vert); } } } }
39.128205
123
0.589122
[ "MIT" ]
AphelionWasTaken/KAMI
KAMI/Games/Killzone3PS3.cs
1,528
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using NetOffice; namespace NetOffice.MSHTMLApi { ///<summary> /// DispatchInterface IHTMLEventObj4 /// SupportByVersion MSHTML, 4 ///</summary> [SupportByVersionAttribute("MSHTML", 4)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class IHTMLEventObj4 : IHTMLEventObj3 { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IHTMLEventObj4); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public IHTMLEventObj4(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLEventObj4(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLEventObj4(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLEventObj4(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLEventObj4(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLEventObj4() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLEventObj4(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 wheelDelta { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "wheelDelta", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } #endregion #region Methods #endregion #pragma warning restore } }
32.215517
169
0.677281
[ "MIT" ]
NetOffice/NetOffice
Source/MSHTML/DispatchInterfaces/IHTMLEventObj4.cs
3,737
C#
using System; using System.Windows.Forms; namespace TimeTracker { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
17.7
56
0.694915
[ "Unlicense" ]
nelsonlaquet/time-tracker
TimeTracker/Program.cs
356
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.VisualStudio.Language.Intellisense; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek { internal class DefinitionPeekableItem : PeekableItem { private readonly Workspace _workspace; private readonly ProjectId _projectId; private readonly SymbolKey _symbolKey; private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; public DefinitionPeekableItem( Workspace workspace, ProjectId projectId, SymbolKey symbolKey, IPeekResultFactory peekResultFactory, IMetadataAsSourceFileService metadataAsSourceService) : base(peekResultFactory) { _workspace = workspace; _projectId = projectId; _symbolKey = symbolKey; _metadataAsSourceFileService = metadataAsSourceService; } public override IEnumerable<IPeekRelationship> Relationships { get { return SpecializedCollections.SingletonEnumerable(PredefinedPeekRelationships.Definitions); } } public override IPeekResultSource GetOrCreateResultSource(string relationshipName) { return new ResultSource(this); } private sealed class ResultSource : IPeekResultSource { private readonly DefinitionPeekableItem _peekableItem; public ResultSource(DefinitionPeekableItem peekableItem) { _peekableItem = peekableItem; } public void FindResults(string relationshipName, IPeekResultCollection resultCollection, CancellationToken cancellationToken, IFindPeekResultsCallback callback) { if (relationshipName != PredefinedPeekRelationships.Definitions.Name) { return; } // Note: this is called on a background thread, but we must block the thread since the API doesn't support proper asynchrony. var workspace = _peekableItem._workspace; var solution = workspace.CurrentSolution; var project = solution.GetProject(_peekableItem._projectId); var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var symbol = _peekableItem._symbolKey.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken).Symbol; if (symbol == null) { callback.ReportFailure(new Exception(EditorFeaturesResources.No_information_found)); return; } var sourceLocations = symbol.Locations.Where(l => l.IsInSource).ToList(); if (!sourceLocations.Any()) { // It's a symbol from metadata, so we want to go produce it from metadata var declarationFile = _peekableItem._metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, cancellationToken).WaitAndGetResult(cancellationToken); var peekDisplayInfo = new PeekResultDisplayInfo(declarationFile.DocumentTitle, declarationFile.DocumentTitle, declarationFile.DocumentTitle, declarationFile.DocumentTitle); var identifierSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; var entityOfInterestSpan = PeekHelpers.GetEntityOfInterestSpan(symbol, workspace, declarationFile.IdentifierLocation, cancellationToken); resultCollection.Add(PeekHelpers.CreateDocumentPeekResult(declarationFile.FilePath, identifierSpan, entityOfInterestSpan, peekDisplayInfo, _peekableItem.PeekResultFactory, isReadOnly: true)); } int processedSourceLocations = 0; foreach (var declaration in sourceLocations) { var declarationLocation = declaration.GetLineSpan(); var entityOfInterestSpan = PeekHelpers.GetEntityOfInterestSpan(symbol, workspace, declaration, cancellationToken); resultCollection.Add(PeekHelpers.CreateDocumentPeekResult(declarationLocation.Path, declarationLocation.Span, entityOfInterestSpan, _peekableItem.PeekResultFactory)); callback.ReportProgress(100 * ++processedSourceLocations / sourceLocations.Count); } } } } }
49.125
211
0.677269
[ "Apache-2.0" ]
ElanHasson/roslyn
src/EditorFeatures/Core/Implementation/Peek/DefinitionPeekableItem.cs
4,718
C#
/* Copyright 2009-2021 Intel 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 System; using System.Windows.Forms; namespace MeshCentralRouter { public partial class SettingsForm : Form { public SettingsForm() { InitializeComponent(); Translate.TranslateControl(this); } public bool BindAllInterfaces { get { return allInterfacesCheckBox.Checked; } set { allInterfacesCheckBox.Checked = value; } } public bool ShowSystemTray { get { return systemTrayCheckBox.Checked; } set { systemTrayCheckBox.Checked = value; } } private void okButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; } private void cancelButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } } }
27.226415
72
0.661123
[ "Apache-2.0" ]
SPEMoorthy/MeshCentralRouter
SettingsForm.cs
1,445
C#
// <copyright file="IOutputPort.cs" company="Ivan Paulovich"> // Copyright © Ivan Paulovich. All rights reserved. // </copyright> namespace Application.UseCases.Withdraw { using Domain; using Domain.Debits; /// <summary> /// Output Port. /// </summary> public interface IOutputPort { /// <summary> /// Informs it is out of balance. /// </summary> void OutOfFunds(); /// <summary> /// Invalid input. /// </summary> void Invalid(); /// <summary> /// Resource not closed. /// </summary> void NotFound(); /// <summary> /// Withdraw success. /// </summary> /// <param name="debit">Debit Transaction.</param> /// <param name="account">Account Transaction</param> void Ok(Debit debit, Account account); } }
24.684211
62
0.503198
[ "Apache-2.0" ]
Borhan-az/CleanArchitecture-manga
accounts-api/src/Application/UseCases/Withdraw/IOutputPort.cs
939
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.17929 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ShellAbout_dialog.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.580645
151
0.583955
[ "Apache-2.0" ]
coderserdar/CSharpExamples
SourceCode/ShellAbout dialog/ShellAbout dialog/Properties/Settings.Designer.cs
1,074
C#
namespace Microsoft.Research.SpeechWriter.Core { internal interface ITokenTileFilter : ITileFilter { bool IsTokenVisible(int token); } }
22.428571
53
0.713376
[ "MIT" ]
MSREnable/Hands-Free-Keyboard
Microsoft.Research.SpeechWriter/Microsoft.Research.SpeechWriter.Core/ITokenTileFilter.cs
159
C#
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Text; using IPioneerReceiverControl.Rx.Model; using PioneerReceiverControl.Rx.Model; namespace PioneerReceiverControl.Rx.ExtensionMethod { public static class ByteStreamEx { private const byte CR = 0x0D; //Carriage Return private const byte LF = 0x0A; //Line Feed public static IObservable<IRawResponseData> ToResponseObservable(this IObservable<byte> observableByteStream, bool ignoreMissingLineFeed = true) { return Observable.Create<IRawResponseData>(obs => { var buffer = new List<byte>(); var crReceived = false; var disposableByteStream = observableByteStream .Subscribe(b => { if (b != CR && b != LF && !crReceived) { buffer.Add(b); } else switch (b) { case CR when !crReceived: crReceived = true; break; case CR when crReceived: //ignore additional CR's after first CR is received break; case LF when crReceived: Update(false); break; default: { if (b != LF && crReceived && ignoreMissingLineFeed) { Update(true); } break; } } void Update(bool hasErrors) { var str = Encoding.UTF8.GetString(buffer.ToArray()); obs.OnNext(new RawResponseData(str, hasErrors)); buffer.Clear(); crReceived = false; } }, ex => { obs.OnError(ex); }, () => { obs.OnCompleted(); }); return disposableByteStream; }); } } }
36.426667
152
0.354685
[ "MIT" ]
1iveowl/PioneerReceiverControl.Rx
src/main/PioneerReceiverControl.Rx/ExtensionMethod/ByteStreamEx.cs
2,734
C#
using System; using EPiServer.DataAbstraction; using EPiServer.ServiceLocation; namespace AlloyAngularJS.Business { /// <summary> /// Provides extension methods for types intended to be used when working with page types /// </summary> public static class PageTypeExtensions { /// <summary> /// Returns the definition for a specific page type /// </summary> /// <param name="pageType"></param> /// <returns></returns> public static PageType GetPageType(this Type pageType) { var pageTypeRepository = ServiceLocator.Current.GetInstance<IContentTypeRepository<PageType>>(); return pageTypeRepository.Load(pageType); } } }
29.32
108
0.65075
[ "Apache-2.0" ]
episerver/AlloyAngularJS
AlloyAngularJS/Business/PageTypeExtensions.cs
733
C#
using System; using System.Data; using System.Data.SqlClient; namespace Marten.Integration.Tests.TestsInfrasructure { public abstract class DapperTest : IDisposable { protected bool wasDisposed = false; protected readonly IDbConnection DbConnection; protected readonly string SchemaName = "sch" + Guid.NewGuid().ToString().Replace("-", string.Empty); public static string ConnectionString = "Server=(local)\\SQL2017;Database=master;User ID=sa;Password=Password12!"; // "Server=localhost;Database=master;User ID=sa;Password=Password12!"; protected DapperTest() : this(true) { } protected DapperTest(bool shouldCreateSession) { if (shouldCreateSession) { DbConnection = CreateDbConnection(); //Execute($"CREATE SCHEMA IF NOT EXISTS {SchemaName};"); //Execute($"SET search_path TO {SchemaName}, public"); } } protected virtual IDbConnection CreateDbConnection() { var connection = new SqlConnection(ConnectionString); connection.Open(); return connection; } protected void Execute(string sql) { using (var tran = DbConnection.BeginTransaction(IsolationLevel.ReadCommitted)) { var command = DbConnection.CreateCommand(); command.CommandText = sql; command.Transaction = tran; command.ExecuteNonQuery(); tran.Commit(); } } public void Dispose() { if (wasDisposed) { return; } wasDisposed = true; //Execute($"DROP SCHEMA IF EXISTS {SchemaName} CASCADE;"); DbConnection?.Dispose(); } } }
27.985294
108
0.561745
[ "MIT" ]
amarish-kumar/GoldenEye
src/Core/Backend.Core.Dapper.Integration.Tests/Infrastructure/DapperTest.cs
1,905
C#
using NSubstitute; using Xunit; namespace xUnit2.Demo.Tests.NSubstitute.Demo.LessonBase { /// <summary> /// 自动递归模拟 /// </summary> public class Lesson15 { //替代实例一旦被设置属性或方法,则将自动返回非NULL值。 //例如,任何属性或方法如果返回接口、委托或纯虚类*,则将自动的返回替代实例自身。 //通常这被称为递归模拟技术,而且是非常实用的。 //比如其可以避免显式地设置每个替代实例,也就意味着更少量的代码。诸如String和Array等类型,默认会返回空值而不是NULL。 //*注:一个纯虚类是指一个类,其所有的公有方法和属性都被定义为virtual或abstract,并且其具有一个默认公有或受保护地无参构造函数。 #region 递归模拟 public interface INumberParser { int[] Parse(string expression); } public interface INumberParserFactory { INumberParser Create(char delimiter); } //我们想配置 INumberParserFactory 来创建一个解析器,该解析器会为一个 expression 返回一定数量的 int 类型的值。我们可以手工创建每个替代实例: [Fact] public void Test_AutoRecursiveMocks_ManuallyCreateSubstitutes() { var factory = Substitute.For<INumberParserFactory>(); var parser = Substitute.For<INumberParser>(); factory.Create(',').Returns(parser); parser.Parse("an expression").Returns(new int[] { 1, 2, 3 }); var actual = factory.Create(',').Parse("an expression"); Assert.Equal(new int[] { 1, 2, 3 }, actual); } //或者可以应用递归模拟功能,INumberParserFactory.Create() 会自动返回 INumberParser 类型的替代实例。 [Fact] public void Test_AutoRecursiveMocks_AutomaticallyCreateSubstitutes() { var factory = Substitute.For<INumberParserFactory>(); factory.Create(',').Parse("an expression").Returns(new int[] { 1, 2, 3 }); var actual = factory.Create(',').Parse("an expression"); Assert.Equal(new int[] { 1, 2, 3 }, actual); } //每次当使用相同参数调用一个被递归模拟的属性或方法时,都会返回相同的替代实例。如果使用不同参数调用,则将会返回一个新的替代实例。 [Fact] public void Test_AutoRecursiveMocks_CallRecursivelySubbed() { var factory = Substitute.For<INumberParserFactory>(); factory.Create(',').Parse("an expression").Returns(new int[] { 1, 2, 3 }); var firstCall = factory.Create(','); var secondCall = factory.Create(','); var thirdCallWithDiffArg = factory.Create('x'); Assert.Same(firstCall, secondCall); Assert.NotSame(firstCall, thirdCallWithDiffArg); } //注:不会为类创建递归的替代实例,因为创建和使用类可能有潜在的或多余的副作用。因此,有必要显式地创建和返回类的替代实例。 #endregion #region 替代链 //当需要时,我们可以使用递归模拟来简单地设置替代链,但这并不是一个理想的做法。例如: public interface IContext { IRequest CurrentRequest { get; } } public interface IRequest { IIdentity Identity { get; } IIdentity NewIdentity(string name); } public interface IIdentity { string Name { get; } string[] Roles(); } //如果要获取 CurrentRequest 中的 Identity 并返回一个名字,我们可以手工为 IContext、IRequest 和 IIdentity 创建替代品,然后使用 Returns() 将这些替代实例链接到一起。 //或者我们可以使用为属性和方法自动创建的替代实例。 [Fact] public void Test_AutoRecursiveMocks_SubstituteChains() { var context = Substitute.For<IContext>(); context.CurrentRequest.Identity.Name.Returns("My pet fish Eric"); Assert.Equal( "My pet fish Eric", context.CurrentRequest.Identity.Name); } //在这里 CurrentReques t是自动返回一个 IRequest 的替代实例,IRequest 替代实例会自动返回一个 IIdentity 替代实例。 //注:类似于这种设置很长的替代实例链,一般被认为是代码臭味:我们打破了 Law of Demeter 原则,对象只应该与其直接关系的临近对象打交道,而不与临近对象的临近对象打交道。 //如果你写的测试用例中没有使用递归模拟,设置的过程可能会明显的变复杂,所以如果要使用递归模式,则需要格外的注意类似的类型耦合。 #endregion #region 自动值 //当属性或方法返回 String 或 Array 类型的值时,默认会返回空或者非 NULL 值。比如在你仅需要返回一个对象引用,但并不关心其特定的属性时,这个功能可以帮你避免空引用异常。 [Fact] public void Test_AutoRecursiveMocks_AutoValues() { var identity = Substitute.For<IIdentity>(); Assert.Equal(string.Empty, identity.Name); Assert.Empty(identity.Roles()); } #endregion #region Lesson16 设置out和ref参数 //通过使用 Returns() 回调或者 When..Do 语法可以设置 out 和 ref 的参数。 public interface ILookup { bool TryLookup(string key, out string value); } //对于上面的接口,我们可以配置其返回值,并设置第二个参数的输出: [Fact] public void Test_SetOutRefArgs_SetOutArg() { // Arrange var value = ""; var lookup = Substitute.For<ILookup>(); lookup .TryLookup("hello", out value) .Returns(x => { x[1] = "world!"; //设置第二个参数的输出 return true; }); // Act var result = lookup.TryLookup("hello", out value); // Assert Assert.True(result); Assert.Equal("world!", value); } #endregion } }
29.592814
123
0.583569
[ "MIT" ]
AtwindYu/DotNet.Quick.AllInOne
sources/UnitTest/xUnit2.Demo.Tests/NSubstitute.Demo/LessonBase/Lesson15.cs
6,574
C#
using EFBot.Launcher.ViewModels; namespace EFBot.Launcher { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow { public MainWindow() { InitializeComponent(); } } }
18.466667
45
0.577617
[ "MIT" ]
iXab3r/EndlessFrontierBot
Sources/EFBot.Launcher/MainWindow.xaml.cs
279
C#
using System; using TheGarden.DataAccess.Model; using System.Linq; namespace TheGarden.DataAccess { public class CheckTables { public void CheckCustomer(string first_name) { using (var db = new LimsGardenContext()) { var customerData = db.Customer .FirstOrDefault(p => p.FirstName == first_name); Console.WriteLine("The customer's last name is: " + customerData.LastName); } } public void CheckOrder(string plant_name) { using (var db = new LimsGardenContext()) { var plantData = db.Plant .FirstOrDefault(p => p. PlantName == plant_name); Console.WriteLine("There are " + plantData.InventoryCount + " left in stock."); } } } }
24.657143
95
0.544612
[ "MIT" ]
2002-feb24-net/dianalim-project0
TheGarden/TheGarden.DataAccess/CheckTables.cs
863
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web.WebPages; using Microsoft.TestCommon; using Moq; namespace System.Web.Mvc.Test { public class RazorViewTest { [Fact] public void Constructor_RunViewStartPagesParam() { var context = new ControllerContext(); Assert.True(new RazorView(context, "~/view", "~/master", runViewStartPages: true, viewStartFileExtensions: null).RunViewStartPages); Assert.False(new RazorView(context, "~/view", "~/master", runViewStartPages: false, viewStartFileExtensions: null).RunViewStartPages); Assert.True(new RazorView(context, "~/view", "~/master", runViewStartPages: true, viewStartFileExtensions: null, viewPageActivator: new Mock<IViewPageActivator>().Object).RunViewStartPages); Assert.False(new RazorView(context, "~/view", "~/master", runViewStartPages: false, viewStartFileExtensions: null, viewPageActivator: new Mock<IViewPageActivator>().Object).RunViewStartPages); } [Fact] public void ConstructorWithEmptyViewPathThrows() { // Act & Assert Assert.ThrowsArgumentNullOrEmpty( () => new RazorView(new ControllerContext(), String.Empty, "~/master", false, Enumerable.Empty<string>()), "viewPath" ); } [Fact] public void ConstructorWithNullViewPathThrows() { // Act & Assert Assert.ThrowsArgumentNullOrEmpty( () => new RazorView(new ControllerContext(), null, "~/master", false, Enumerable.Empty<string>()), "viewPath" ); } [Fact] public void ConstructorWithNullControllerContextThrows() { // Act & Assert Assert.ThrowsArgumentNull( () => new RazorView(null, "view path", "~/master", false, Enumerable.Empty<string>()), "controllerContext" ); } [Fact] public void LayoutPathProperty() { //Arrange ControllerContext controllerContext = new ControllerContext(); // Act RazorView view = new RazorView(new ControllerContext(), "view path", "master path", false, Enumerable.Empty<string>()); // Assert Assert.Equal("master path", view.LayoutPath); } [Fact] public void LayoutPathPropertyReturnsEmptyStringIfNullLayoutSpecified() { // Act RazorView view = new RazorView(new ControllerContext(), "view path", null, false, Enumerable.Empty<string>()); // Assert Assert.Equal(String.Empty, view.LayoutPath); } [Fact] public void LayoutPathPropertyReturnsEmptyStringIfLayoutNotSpecified() { // Act RazorView view = new RazorView(new ControllerContext(), "view path", null, false, Enumerable.Empty<string>()); // Assert Assert.Equal(String.Empty, view.LayoutPath); } [Fact] public void RenderWithNullWriterThrows() { // Arrange RazorView view = new RazorView(new ControllerContext(), "~/viewPath", null, false, Enumerable.Empty<string>()); Mock<ViewContext> viewContextMock = new Mock<ViewContext>(); MockBuildManager buildManager = new MockBuildManager("~/viewPath", typeof(object)); view.BuildManager = buildManager; // Act & Assert Assert.ThrowsArgumentNull( () => view.Render(viewContextMock.Object, null), "writer" ); } [Fact] public void RenderWithUnsupportedTypeThrows() { // Arrange ViewContext context = new Mock<ViewContext>().Object; MockBuildManager buildManagerMock = new MockBuildManager("view path", typeof(object)); RazorView view = new RazorView(new ControllerContext(), "view path", null, false, Enumerable.Empty<string>()); view.BuildManager = buildManagerMock; // Act & Assert Assert.Throws<InvalidOperationException>( () => view.Render(context, new Mock<TextWriter>().Object), "The view at 'view path' must derive from WebViewPage, or WebViewPage<TModel>." ); } [Fact] public void RenderWithViewPageAndNoStartPageLookupRendersView() { // Arrange StubWebViewPage viewPage = new StubWebViewPage(); Mock<ViewContext> viewContextMock = new Mock<ViewContext>(); viewContextMock.Setup(vc => vc.HttpContext.Items).Returns(new Dictionary<object, object>()); viewContextMock.Setup(vc => vc.HttpContext.Request.IsLocal).Returns(false); MockBuildManager buildManager = new MockBuildManager("~/viewPath", typeof(object)); Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>(MockBehavior.Strict); ControllerContext controllerContext = new ControllerContext(); activator.Setup(l => l.Create(controllerContext, typeof(object))).Returns(viewPage); RazorView view = new RazorView(controllerContext, "~/viewPath", null, false, Enumerable.Empty<string>(), activator.Object); view.StartPageLookup = (WebPageRenderingBase p, string n, IEnumerable<string> e) => { Assert.True(false, "ViewStart page lookup should not be called"); return null; }; view.BuildManager = buildManager; // Act view.Render(viewContextMock.Object, new Mock<TextWriter>().Object); // Assert Assert.Null(viewPage.Layout); Assert.Equal("", viewPage.OverridenLayoutPath); Assert.Same(viewContextMock.Object, viewPage.ViewContext); Assert.Equal("~/viewPath", viewPage.VirtualPath); } [Fact] public void RenderWithViewPageAndStartPageLookupExecutesStartPage() { // Arrange StubWebViewPage viewPage = new StubWebViewPage(); Mock<ViewContext> viewContextMock = new Mock<ViewContext>(); viewContextMock.Setup(vc => vc.HttpContext.Items).Returns(new Dictionary<object, object>()); MockBuildManager buildManager = new MockBuildManager("~/viewPath", typeof(object)); Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>(MockBehavior.Strict); ControllerContext controllerContext = new ControllerContext(); activator.Setup(l => l.Create(controllerContext, typeof(object))).Returns(viewPage); RazorView view = new RazorView(controllerContext, "~/viewPath", null, true, new[] { "cshtml" }, activator.Object); Mock<ViewStartPage> startPage = new Mock<ViewStartPage>(); startPage.Setup(sp => sp.ExecutePageHierarchy()).Verifiable(); view.StartPageLookup = (WebPageRenderingBase page, string fileName, IEnumerable<string> extensions) => { Assert.Equal(viewPage, page); Assert.Equal("_ViewStart", fileName); Assert.Equal(new[] { "cshtml" }, extensions.ToArray()); return startPage.Object; }; view.BuildManager = buildManager; // Act view.Render(viewContextMock.Object, new Mock<TextWriter>().Object); // Assert startPage.Verify(sp => sp.ExecutePageHierarchy(), Times.Once()); } // TODO: This throws in WebPages and needs to be tracked down. [Fact] public void RenderWithViewPageAndLayoutPageRendersView() { // Arrange StubWebViewPage viewPage = new StubWebViewPage(); Mock<ViewContext> viewContext = new Mock<ViewContext>(); Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>(); Mock<HttpRequestBase> httpRequest = new Mock<HttpRequestBase>(); httpRequest.SetupGet(r => r.IsLocal).Returns(false); httpRequest.SetupGet(r => r.Browser.IsMobileDevice).Returns(false); httpRequest.SetupGet(r => r.Cookies).Returns(new HttpCookieCollection()); httpContext.SetupGet(c => c.Request).Returns(httpRequest.Object); httpContext.SetupGet(c => c.Response.Cookies).Returns(new HttpCookieCollection()); httpContext.SetupGet(c => c.Items).Returns(new Hashtable()); viewContext.SetupGet(v => v.HttpContext).Returns(httpContext.Object); MockBuildManager buildManager = new MockBuildManager("~/viewPath", typeof(object)); Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>(MockBehavior.Strict); Mock<WebPage> layoutPage = new Mock<WebPage> { CallBase = true }; layoutPage.Setup(c => c.Execute()).Callback(() => layoutPage.Object.RenderBody()); Mock<IVirtualPathFactory> virtualPathFactory = new Mock<IVirtualPathFactory>(MockBehavior.Strict); virtualPathFactory.Setup(f => f.Exists("~/layoutPath")).Returns(true); virtualPathFactory.Setup(f => f.CreateInstance("~/layoutPath")).Returns(layoutPage.Object); ControllerContext controllerContext = new ControllerContext(); activator.Setup(l => l.Create(controllerContext, typeof(object))).Returns(viewPage); RazorView view = new RazorView(controllerContext, "~/viewPath", "~/layoutPath", false, Enumerable.Empty<string>(), activator.Object); view.BuildManager = buildManager; view.VirtualPathFactory = virtualPathFactory.Object; view.DisplayModeProvider = DisplayModeProvider.Instance; // Act view.Render(viewContext.Object, TextWriter.Null); // Assert Assert.Equal("~/layoutPath", viewPage.Layout); Assert.Equal("~/layoutPath", viewPage.OverridenLayoutPath); Assert.Same(viewContext.Object, viewPage.ViewContext); Assert.Equal("~/viewPath", viewPage.VirtualPath); } public class StubWebViewPage : WebViewPage { public bool InitHelpersCalled; public string ResultLayoutPage; public string ResultOverridenLayoutPath; public ViewContext ResultViewContext; public string ResultVirtualPath; public override void Execute() { ResultLayoutPage = Layout; ResultOverridenLayoutPath = OverridenLayoutPath; ResultViewContext = ViewContext; ResultVirtualPath = VirtualPath; } public override void InitHelpers() { base.InitHelpers(); InitHelpersCalled = true; } } } }
44.692
204
0.616218
[ "Apache-2.0" ]
Darth-Fx/AspNetMvcStack
test/System.Web.Mvc.Test/Test/RazorViewTest.cs
11,175
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.451/blob/master/LICENSE * */ #endregion using ComponentFactory.Krypton.Toolkit; using ExtendedControls.ExtendedToolkit.Utilities.Controls; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.Design; namespace ExtendedControls.ExtendedToolkit.Controls.KryptonControls { [ToolboxBitmap(typeof(Button)), ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.All)] public class KryptonColourButtonToolStripMenuItem : ToolStripControlHostFixed { // Constants ========================================================= // Attributes ======================================================== // Properties ======================================================== /// <summary> /// Gets the KryptonColorButton control. /// </summary> /// <value>The KryptonColorButton control.</value> [RefreshProperties(RefreshProperties.All), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonColorButton KryptonColorButtonControl { get { return Control as KryptonColorButton; } } // Constructor ======================================================== /// <summary> /// Initializes a new instance of the <see cref="KryptonComboBoxToolStripMenuItem"/> class. /// </summary> public KryptonColourButtonToolStripMenuItem() : base(new KryptonColorButton()) { this.AutoSize = false; } /// <summary> /// Retrieves the size of a rectangular area into which a control can be fitted. /// </summary> /// <param name="constrainingSize">The custom-sized area for a control.</param> /// <returns> /// An ordered pair of type <see cref="T:System.Drawing.Size"></see> representing the width and height of a rectangle. /// </returns> /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> public override Size GetPreferredSize(Size constrainingSize) { //return base.GetPreferredSize(constrainingSize); return this.KryptonColorButtonControl.GetPreferredSize(constrainingSize); } /// <summary> /// Subscribes events from the hosted control. /// </summary> /// <param name="control">The control from which to subscribe events.</param> protected override void OnSubscribeControlEvents(Control control) { base.OnSubscribeControlEvents(control); //Add your code here to subsribe to Control Events } /// <summary> /// Unsubscribes events from the hosted control. /// </summary> /// <param name="control">The control from which to unsubscribe events.</param> protected override void OnUnsubscribeControlEvents(Control control) { base.OnUnsubscribeControlEvents(control); //Add your code here to unsubscribe from control events. } } }
47.678571
786
0.652185
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-Toolkit-Suite-Extended-NET-5.451
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/ExtendedToolkit/Controls/Krypton Controls/KryptonColourButtonToolStripMenuItem.cs
4,007
C#
using System.Linq; using JollySamurai.UnrealEngine4.T3D; using JollySamurai.UnrealEngine4.T3D.Map; using UnityEngine; namespace JollySamurai.UnrealEngine4.Import.Map.Converters { public class StaticMeshComponentConverter : ComponentConverter<StaticMeshComponent> { protected override void CreateComponent(SceneBuilder builder, StaticMeshComponent unrealNode, Node parentUnrealNode, GameObject parentGameObject) { var actorNode = parentUnrealNode as BaseActorNode; var containingGameObject = parentGameObject; if(actorNode.RootComponentName != unrealNode.Name) { containingGameObject = StaticMeshActorConverter.CreateGameObjectImpl(builder, unrealNode.StaticMesh.FileName); containingGameObject.name = unrealNode.Name; containingGameObject.transform.parent = parentGameObject.transform; } containingGameObject.transform.localPosition = Helper.ConvertUnrealVector3(unrealNode.Location, true); containingGameObject.transform.localRotation = Helper.ConvertUnrealRotator(unrealNode.Rotation); containingGameObject.transform.localScale = Helper.ConvertUnrealVector3(unrealNode.Scale3D, false); var meshRenderer = containingGameObject.GetComponent<MeshRenderer>(); var overrideMaterials = unrealNode.OverrideMaterials .Where(reference => "None" != reference.FileName) .Select(reference => Helper.LoadMaterial(reference.FileName)) .ToArray(); if(overrideMaterials.Length > 0) { meshRenderer.materials = overrideMaterials; } } } }
43.846154
153
0.704678
[ "MIT" ]
iainmckay/com.jollysamurai.unrealengine4-import
Editor/Map/Converters/StaticMeshComponentConverter.cs
1,712
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ADProject_Team10.Store { public partial class UpdateReorderLevelAndQuantity { /// <summary> /// ddlCatDes control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlCatDes; /// <summary> /// tbSearch control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox tbSearch; /// <summary> /// btnSearch control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnSearch; /// <summary> /// lblError control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblError; /// <summary> /// gvUpadateReorderLevelQuantity control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.GridView gvUpadateReorderLevelQuantity; } }
34.57377
91
0.531532
[ "MIT" ]
kylerlee/Stationery-Store-Inventory-System-Web-App
ADProject_Team10/Store/UpdateReorderLevelAndQuantity.aspx.designer.cs
2,111
C#
namespace COL.UnityGameWheels.Core.Asset { /// <summary> /// Asset index in the remote server. /// </summary> public class AssetIndexForRemote : AssetIndexAugmented { public override string Header => Constant.RemoteIndexFileHeader; public override string ObsoleteHeader => Constant.RemoteIndexFileHeader_Obsolete; } }
29.916667
89
0.704735
[ "MIT" ]
GarfieldJiang/UnityGameWheels.Core
Core/Asset/AssetIndexForRemote.cs
361
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using Ionic.Zip; using System.IO; namespace SeriesNamer.tvdb { public class Database { private readonly string apikey; private readonly string mirror; public Database(string apikey) { this.apikey = apikey; mirror = new MirrorList(GetXml("http://www.thetvdb.com/api/" + apikey + "/mirrors.xml", "Mirrors")) .suggest(YesNo.DontCare, YesNo.DontCare, YesNo.Yes); // string servertime = GetServerTime(GetXml("http://www.thetvdb.com/api/Updates.php?type=none")); readLoacalDatabase(); } private static XmlElement GetXml(string p, string root) { string source = Web.FetchString(p); return Xml.Open(Xml.FromSource(source), root); } internal string suggestTitle(string series, int season, int episode, out string newName) { Series s = getSeries(series); if (s == null) throw new Exception("No series named " + series); Season sa = s.getSeason(season); if (sa == null) throw new Exception("No season " + season.ToString() + " for " + series); Episode e = sa.getEpisode(episode); if (e == null) throw new Exception("No episode " + episode + " in season " + season.ToString() + " for " + series); newName = s.Name; return e.Title; } private string getSeriesId(string series, out string newName) { XmlElement root = GetXml("http://www.thetvdb.com/api/GetSeries.php?seriesname=" + Safe(series), "Data"); List<KeyValuePair<string, string>> id = new List<KeyValuePair<string, string>>(); foreach (XmlElement el in Xml.ElementsNamed(root, "Series")) { string iid = Xml.GetTextOfSubElement(el, "seriesid"); string actualName = Xml.GetTextOfSubElement(el, "SeriesName"); if (actualName.ToLower().Trim() == series.ToLower().Trim()) { newName = actualName; return iid; } id.Add(new KeyValuePair<string, string>(iid, actualName)); } if (id.Count > 1) throw new Exception("More than one series... dont know what to do"); if( id.Count == 0 ) throw new Exception("Show unknown"); newName = id[0].Value; return id[0].Key; } private static string Safe(string series) { return series.Trim().Replace(" ", "%20"); } Dictionary<string, Series> sDict = new Dictionary<string, Series>(); const string kLocalDatabaseFile = "db.xml"; private void readLoacalDatabase() { string path = getDtabaseDir(); string filename = Path.Combine(path, kLocalDatabaseFile); if (false == File.Exists(filename)) return; XmlElement root = Xml.Open(Xml.FromFile(filename), "db"); foreach(XmlElement seriesElement in Xml.ElementsNamed(root, "series") ) { string seriesName = Xml.GetAttributeString(seriesElement, "name"); string seriesId = Xml.GetAttributeString(seriesElement, "id"); string ttl = seriesName.Trim().ToLower(); Series series = new Series(seriesId, seriesName); foreach (XmlElement seasonElement in Xml.ElementsNamed(seriesElement, "season")) { string idstr = Xml.GetAttributeString(seasonElement, "id"); int seasonId = int.Parse(idstr); Season season = new Season(seasonId); foreach (XmlElement episodeElement in Xml.ElementsNamed(seasonElement, "episode")) { string eidstr = Xml.GetAttributeString(episodeElement, "id"); int episodeId = int.Parse(eidstr); string episodeTitle = Xml.GetAttributeString(episodeElement, "title"); string overview = Xml.GetTextOfSubElementOrNull(episodeElement, "overview"); Episode episode = new Episode(episodeId, episodeTitle, overview); season.add(episode); } series.add(season); } sDict[ttl] = series; } } private string getDtabaseDir() { string cad = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); return Path.Combine(Path.Combine(cad, "seriesnamer"), "db"); } public void saveLocalDatabase() { ElementBuilder root = new ElementBuilder().child("db"); foreach (KeyValuePair<string, Series> k in sDict) { ElementBuilder series = root.child("series").attribute("name", k.Value.Name).attribute("id", k.Value.Id); foreach (Season s in k.Value.Seasons) { ElementBuilder season = series.child("season").attribute("id", s.Index.ToString()); foreach (Episode e in s.Episodes) { season.child("episode") .attribute("id", e.Index.ToString()) .attribute("title", e.Title) .child("overview").text(e.Overview); } } } string dir = getDtabaseDir(); FileUtil.MakeSureDirectoryExist(dir); root.Document.Save( Path.Combine(dir, kLocalDatabaseFile) ); } private Series getSeries(string series) { string ttl = series.Trim().ToLower(); if (sDict.ContainsKey(ttl)) return sDict[ttl]; string name; string id = getSeriesId(series, out name); string language = "en"; string basedir = Path.Combine(getDtabaseDir(), "downloaded"); FileUtil.MakeSureDirectoryExist(basedir); string zipfile = Path.Combine(basedir, id + ".zip"); string targetxml = Path.Combine(basedir, id + ".xml"); string url = mirror + "/api/"+ apikey + "/series/" + id + "/all/" + language + ".zip"; if (false == File.Exists(zipfile)) Web.DownloadTo(url, zipfile); ExtractZipfile(zipfile, language+".xml", targetxml); Series s = new Series(id, name); s.parse(Xml.Open(Xml.FromFile(targetxml), "Data")); sDict.Add(ttl, s); // we're done File.Delete(zipfile); return s; } private void ExtractZipfile(string zipfile, string fileInZip, string targetXml) { if( File.Exists(targetXml) ) File.Delete(targetXml); using (ZipFile zf = ZipFile.Read(zipfile)) { using (Stream s = File.OpenWrite(targetXml)) { ZipEntry ze = zf[fileInZip]; ze.Extract(s); } } } } }
41.636872
128
0.528109
[ "MIT" ]
madeso/PrettyGood.net
SeriesNamer/SeriesNamer/tvdb/Database.cs
7,455
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; public class AudioReverbData { public AudioReverbData() { } public AudioReverbData(AudioReverbData a) { hfReference = a.hfReference; density = a.density; diffusion = a.diffusion; reverbDelay = a.reverbDelay; reverb = a.reverb; reflectDelay = a.reflectDelay; reflections = a.reflections; decayHFRatio = a.decayHFRatio; decayTime = a.decayTime; roomHF = a.roomHF; room = a.room; roomLF = a.roomLF; lfReference = a.lfReference; } public AudioReverbData(AudioReverbZone a) { hfReference = a.HFReference; density = a.density; diffusion = a.diffusion; reverbDelay = a.reverbDelay; reverb = a.reverb; reflectDelay = a.reflectionsDelay; reflections = a.reflections; decayHFRatio = a.decayHFRatio; decayTime = a.decayTime; roomHF = a.roomHF; room = a.room; roomLF = a.roomLF; lfReference = a.LFReference; } public int priority; public Collider shape; public float fadeDistance; public float hfReference; public float density; public float diffusion; public float reverbDelay; public float reverb; public float reflectDelay; public float reflections; public float decayHFRatio; public float decayTime; public float roomHF; public float room; public float roomLF; public float lfReference; public static AudioReverbData Lerp(AudioReverbData a, AudioReverbData b, float t) { AudioReverbData c = new AudioReverbData(); c.hfReference = Mathf.Lerp(a.hfReference, b.hfReference, t); c.density = Mathf.Lerp(a.density, b.density, t); c.diffusion = Mathf.Lerp(a.diffusion, b.diffusion, t); c.reverbDelay = Mathf.Lerp(a.reverbDelay, b.reverbDelay, t); c.reverb = Mathf.Lerp(a.reverb, b.reverb, t); c.reflectDelay = Mathf.Lerp(a.reflectDelay, b.reflectDelay, t); c.reflections = Mathf.Lerp(a.reflections, b.reflections, t); c.decayHFRatio = Mathf.Lerp(a.decayHFRatio, b.decayHFRatio, t); c.decayTime = Mathf.Lerp(a.decayTime, b.decayTime, t); c.roomHF = Mathf.Lerp(a.roomHF, b.roomHF, t); c.room = Mathf.Lerp(a.room, b.room, t); c.roomLF = Mathf.Lerp(a.roomLF, b.roomLF, t); c.lfReference = Mathf.Lerp(a.lfReference, b.lfReference, t); return c; } } public class AudioReverbConsumer : MonoBehaviour { public LayerMask reverbLayer; public AudioMixer target; public AudioReverbData defaultSettings; private void Start() { defaultSettings = new AudioReverbData(); bool check = true; check = check && target.GetFloat("HF Reference", out defaultSettings.hfReference); check = check && target.GetFloat("Density", out defaultSettings.density); check = check && target.GetFloat("Diffusion", out defaultSettings.diffusion); check = check && target.GetFloat("Reverb Delay", out defaultSettings.reverbDelay); check = check && target.GetFloat("Reflections", out defaultSettings.reflections); check = check && target.GetFloat("Decay HF Ratio", out defaultSettings.decayHFRatio); check = check && target.GetFloat("Decay Time", out defaultSettings.decayTime); check = check && target.GetFloat("Room HF", out defaultSettings.roomLF); check = check && target.GetFloat("Room", out defaultSettings.room); check = check && target.GetFloat("Room LF", out defaultSettings.roomLF); check = check && target.GetFloat("LF Reference", out defaultSettings.lfReference); if (!check) { throw new UnityException("Audio reverb variables need to be exposed within the target mixer! (They are not.)"); } } Collider[] colliders = new Collider[10]; void FixedUpdate() { AudioReverbData data = new AudioReverbData(defaultSettings); List<AudioReverbData> l = new List<AudioReverbData>(); Physics.OverlapSphereNonAlloc(transform.position, 10f, colliders, reverbLayer, QueryTriggerInteraction.Collide); foreach (Collider c in colliders) { if (c == null) break; AudioReverbArea d = c.GetComponent<AudioReverbArea>(); if (d == null) continue; l.Add(d.data); } l.Sort((a, b) => a.priority.CompareTo(b.priority)); foreach (AudioReverbData d in l) { Vector3 closestPoint = d.shape.ClosestPoint(transform.position); float dist = Vector3.Distance(closestPoint, transform.position); data = AudioReverbData.Lerp(data, d, Mathf.Clamp01((d.fadeDistance - dist) / d.fadeDistance)); } target.SetFloat("HF Reference", data.hfReference); target.SetFloat("Density", data.density); target.SetFloat("Diffusion", data.diffusion); target.SetFloat("Reverb Delay", data.reverbDelay); target.SetFloat("Reverb", data.reverb); target.SetFloat("Reflect Delay", data.reflectDelay); target.SetFloat("Reflections", data.reflections); target.SetFloat("Decay HF Ratio", data.decayHFRatio); target.SetFloat("Decay Time", data.decayTime); target.SetFloat("Room HF", data.roomHF); target.SetFloat("Room", data.room); //target.SetFloat("Dry Level", data); target.SetFloat("Room LF", data.roomLF); target.SetFloat("LF Reference", data.lfReference); } }
38.493243
123
0.640688
[ "MIT" ]
naelstrof/ShapedAudioReverbZones
Assets/ShapedAudioReverbZones/Plugins/AudioReverbConsumer.cs
5,699
C#
using System; using System.Runtime.Serialization; namespace Grasews.Domain.Exceptions { public class OntologyTermNotFoundException : Exception { public OntologyTermNotFoundException() : base("Ontology Term not found with given Id.") { } public OntologyTermNotFoundException(string message) : base(message) { } public OntologyTermNotFoundException(string message, Exception innerException) : base(message, innerException) { } protected OntologyTermNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
27.375
119
0.677321
[ "MIT" ]
mlcalache/grasews
Grasews.Domain/Exceptions/OntologyTermNotFoundException.cs
659
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MainViewModel.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace FileLoadDemo { using HelixToolkit.SharpDX.Core; using HelixToolkit.Wpf.SharpDX; using HelixToolkit.SharpDX.Core.Animations; using HelixToolkit.SharpDX.Core.Assimp; using HelixToolkit.SharpDX.Core.Model; using HelixToolkit.SharpDX.Core.Model.Scene; using HelixToolkit.Wpf.SharpDX.Controls; using Microsoft.Win32; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using ObservableObject = GalaSoft.MvvmLight.ObservableObject; public class MainViewModel : ObservableObject { private string OpenFileFilter = $"{HelixToolkit.SharpDX.Core.Assimp.Importer.SupportedFormatsString}"; private string ExportFileFilter = $"{HelixToolkit.SharpDX.Core.Assimp.Exporter.SupportedFormatsString}"; private bool showWireframe = false; public bool ShowWireframe { set { if (Set(ref showWireframe, value)) { ShowWireframeFunct(value); } } get { return showWireframe; } } private bool renderFlat = false; public bool RenderFlat { set { if(Set(ref renderFlat, value)) { RenderFlatFunct(value); } } get { return renderFlat; } } private bool renderEnvironmentMap = true; public bool RenderEnvironmentMap { set { if(Set(ref renderEnvironmentMap, value) && scene!=null && scene.Root != null) { foreach(var node in scene.Root.Traverse()) { if(node is MaterialGeometryNode m && m.Material is PBRMaterialCore material) { material.RenderEnvironmentMap = value; } } } } get => renderEnvironmentMap; } public ICommand OpenFileCommand { get; set; } public ICommand ResetCameraCommand { set; get; } public ICommand ExportCommand { private set; get; } private bool isLoading = false; public bool IsLoading { private set => Set(ref isLoading, value); get => isLoading; } private bool enableAnimation = false; public bool EnableAnimation { set { if (Set(ref enableAnimation, value)) { if (value) { StartAnimation(); } else { StopAnimation(); } } } get { return enableAnimation; } } public ObservableCollection<Animation> Animations { get; } = new ObservableCollection<Animation>(); public SceneNodeGroupModel3D GroupModel { get; } = new SceneNodeGroupModel3D(); private Animation selectedAnimation = null; public Animation SelectedAnimation { set { if(Set(ref selectedAnimation, value)) { StopAnimation(); if (value != null) { animationUpdater = new NodeAnimationUpdater(value); } else { animationUpdater = null; } if (enableAnimation) { StartAnimation(); } } } get { return selectedAnimation; } } public TextureModel EnvironmentMap { get; } public EffectsManager EffectsManager { get; } public Camera Camera { get; } private SynchronizationContext context = SynchronizationContext.Current; private HelixToolkitScene scene; private NodeAnimationUpdater animationUpdater; private List<BoneSkinMeshNode> boneSkinNodes = new List<BoneSkinMeshNode>(); private List<BoneSkinMeshNode> skeletonNodes = new List<BoneSkinMeshNode>(); private CompositionTargetEx compositeHelper = new CompositionTargetEx(); public MainViewModel() { this.OpenFileCommand = new DelegateCommand(this.OpenFile); EffectsManager = new DefaultEffectsManager(); Camera = new OrthographicCamera() { LookDirection = new System.Windows.Media.Media3D.Vector3D(0, -10, -10), Position = new System.Windows.Media.Media3D.Point3D(0, 10, 10), UpDirection = new System.Windows.Media.Media3D.Vector3D(0, 1, 0), FarPlaneDistance = 5000, NearPlaneDistance = 0.1f }; ResetCameraCommand = new DelegateCommand(() => { (Camera as OrthographicCamera).Reset(); (Camera as OrthographicCamera).FarPlaneDistance = 5000; (Camera as OrthographicCamera).NearPlaneDistance = 0.1f; }); ExportCommand = new DelegateCommand(() => { ExportFile(); }); EnvironmentMap = LoadFileToMemory("Cubemap_Grandcanyon.dds"); } private void OpenFile() { if (isLoading) { return; } string path = OpenFileDialog(OpenFileFilter); if (path == null) { return; } StopAnimation(); IsLoading = true; Task.Run(() => { var loader = new Importer(); return loader.Load(path); }).ContinueWith((result) => { IsLoading = false; if (result.IsCompleted) { scene = result.Result; Animations.Clear(); GroupModel.Clear(); if (scene != null) { if (scene.Root != null) { foreach (var node in scene.Root.Traverse()) { if (node is MaterialGeometryNode m) { if (m.Material is PBRMaterialCore pbr) { pbr.RenderEnvironmentMap = RenderEnvironmentMap; } else if(m.Material is PhongMaterialCore phong) { phong.RenderEnvironmentMap = RenderEnvironmentMap; } } } } GroupModel.AddNode(scene.Root); if(scene.HasAnimation) { foreach(var ani in scene.Animations) { Animations.Add(ani); } } foreach(var n in scene.Root.Traverse()) { n.Tag = new AttachedNodeViewModel(n); } } } else if (result.IsFaulted && result.Exception != null) { MessageBox.Show(result.Exception.Message); } }, TaskScheduler.FromCurrentSynchronizationContext()); } public void StartAnimation() { compositeHelper.Rendering += CompositeHelper_Rendering; } public void StopAnimation() { compositeHelper.Rendering -= CompositeHelper_Rendering; } private void CompositeHelper_Rendering(object sender, System.Windows.Media.RenderingEventArgs e) { if(animationUpdater != null) { animationUpdater.Update(Stopwatch.GetTimestamp(), Stopwatch.Frequency); } } private void ExportFile() { var index = SaveFileDialog(ExportFileFilter, out var path); if (!string.IsNullOrEmpty(path) && index >= 0) { var id = HelixToolkit.SharpDX.Core.Assimp.Exporter.SupportedFormats[index].FormatId; var exporter = new HelixToolkit.SharpDX.Core.Assimp.Exporter(); exporter.ExportToFile(path, scene, id); return; } } private string OpenFileDialog(string filter) { var d = new OpenFileDialog(); d.CustomPlaces.Clear(); d.Filter = filter; if (!d.ShowDialog().Value) { return null; } return d.FileName; } private int SaveFileDialog(string filter, out string path) { var d = new SaveFileDialog(); d.Filter = filter; if (d.ShowDialog() == true) { path = d.FileName; return d.FilterIndex - 1;//This is tarting from 1. So must minus 1 } else { path = ""; return -1; } } private void ShowWireframeFunct(bool show) { foreach(var node in GroupModel.GroupNode.Items.PreorderDFT((node) => { return node.IsRenderable; })) { if (node is MeshNode m) { m.RenderWireframe = show; } } } private void RenderFlatFunct(bool show) { foreach (var node in GroupModel.GroupNode.Items.PreorderDFT((node) => { return node.IsRenderable; })) { if (node is MeshNode m) { if (m.Material is PhongMaterialCore phong) { phong.EnableFlatShading = show; } else if (m.Material is PBRMaterialCore pbr) { pbr.EnableFlatShading = show; } } } } public static MemoryStream LoadFileToMemory(string filePath) { using (var file = new FileStream(filePath, FileMode.Open)) { var memory = new MemoryStream(); file.CopyTo(memory); return memory; } } } }
32.566667
120
0.450444
[ "MIT" ]
B3zaleel/helix-toolkit
Source/Examples/SharpDX.Core/CoreWpfTest/MainViewModel.cs
11,726
C#
using FluentAssertions; using Kros.KORM.Converter; using Kros.KORM.Injection; using Kros.KORM.Materializer; using Kros.KORM.Metadata; using Kros.KORM.Metadata.Attribute; using Kros.KORM.UnitTests.Helper; using NSubstitute; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using Xunit; namespace Kros.KORM.UnitTests.Materializer { public class MethodModelFactoryShould { #region Tests [Fact] public void CreateFactoryWhichKnowFillingObjectsWithPrimitiveTypes() { DynamicMethodModelFactory factory = CreateFactory(); IDataReader data = new InMemoryDataReader(CreateData()); data.Read(); var fact = factory.GetFactory<Foo>(data); var foo = fact(data); foo.Id.Should().Be(1); foo.PropertyString.Should().Be("Hello"); foo.PropertyDouble.Should().Be(45.78); foo.PropertyDecimal.Should().Be(785.78M); foo.PropertyDateTime.Should().Be(new DateTime(1980, 7, 24)); foo.Is.Should().BeTrue(); foo.PropertyGuid.Should().Be(new Guid("ddc995d7-4dda-41ca-abab-7f45e651784a")); } [Fact] public void CreateFactoryWhichKnowFillingObjectsWithNullValues() { DynamicMethodModelFactory factory = CreateFactory(); var rows = CreateData(); InMemoryDataReader data = new InMemoryDataReader(rows); data.Read(); data.CurrentValues[1] = DBNull.Value; data.CurrentValues[2] = DBNull.Value; data.CurrentValues[6] = DBNull.Value; var fact = factory.GetFactory<Foo>(data); var foo = fact(data); foo.PropertyString.Should().BeNull(); foo.PropertyDouble.Should().Be(0); foo.PropertyGuid.Should().BeEmpty(); } [Fact] public void CreateFactoryWhichKnowFillingObjectsWithEnums() { DynamicMethodModelFactory factory = CreateFactory(); var rows = CreateData(); rows[0].Add("PropertyEnum", 3); IDataReader data = new InMemoryDataReader(rows); data.Read(); var fact = factory.GetFactory<Foo>(data); var foo = fact(data); foo.PropertyEnum.Should().Be(TestEnum.Value3); } [Fact] public void CreateFactoryWhichUseConverter() { DynamicMethodModelFactory factory = CreateFactory(); var rows = CreateData(); rows[0].Add("PropertyEnumConv", "V2"); IDataReader data = new InMemoryDataReader(rows); data.Read(); var fact = factory.GetFactory<Foo>(data); var foo = fact(data); foo.PropertyEnumConv.Should().Be(TestEnum.Value2); } [Fact] public void CreateFactoryWhichUseStandardTypeConverter() { DynamicMethodModelFactory factory = CreateFactory(); var rows = CreateData(); InMemoryDataReader data = new InMemoryDataReader(rows); data.Read(); data.CurrentTypes[0] = typeof(double); data.CurrentValues[0] = 25.45; var fact = factory.GetFactory<Foo>(data); var foo = fact(data); foo.Id.Should().Be(25); } [Fact] public void CreateFactoryWhichConvertNullableType() { DynamicMethodModelFactory factory = CreateFactory(); var rows = CreateData(); InMemoryDataReader data = new InMemoryDataReader(rows); data.Read(); var fact = factory.GetFactory<Foo>(data); var foo = fact(data); foo.Age.Should().Be(18.5); } [Fact] public void IgnoreNonMapFields() { DynamicMethodModelFactory factory = CreateFactory(); var rows = CreateData(); rows[0].Add("Bar", 3); IDataReader data = new InMemoryDataReader(rows); data.Read(); var fact = factory.GetFactory<Foo>(data); var foo = fact(data); foo.Bar.Should().Be(0); } [Fact] public void IgnoreNonExistingProperties() { DynamicMethodModelFactory factory = CreateFactory(); var rows = CreateData(); rows[0].Add("XXX", 3); IDataReader data = new InMemoryDataReader(rows); data.Read(); var fact = factory.GetFactory<Foo>(data); var foo = fact(data); } [Fact] public void NonNullableTypeMaterializeToNullable() { DynamicMethodModelFactory factory = CreateFactory(); var rows = CreateData(); rows[0].Add("PropertyDateTimeNullable", new DateTime(2005, 1, 5)); InMemoryDataReader data = new InMemoryDataReader(rows); data.Read(); data.CurrentTypes[7] = typeof(DateTime); var fact = factory.GetFactory<Foo>(data); var foo = fact(data); foo.PropertyDateTimeNullable.Should().Be(new DateTime(2005, 1, 5)); } [Fact] public void MaterializeValueType() { DynamicMethodModelFactory factory = CreateFactory(); var reader = new ValueTypesReader<int>(new List<int>() { 2, 5, 9, 15, 3 }); var actual = new List<int>(); while (reader.Read()) { var fact = factory.GetFactory<int>(reader); actual.Add(fact(reader)); } actual.Should().BeEquivalentTo(new List<int>() { 2, 5, 9, 15, 3 }); } [Fact] public void CallOnAfterMaterializeWhenModelImplementIMaterialize() { var modelMapper = CreateModelMapperForBar(); DynamicMethodModelFactory factory = new DynamicMethodModelFactory(new DatabaseMapper(modelMapper)); var rows = new List<Dictionary<string, object>> { new Dictionary<string, object>() }; rows[0].Add("Prop1", 2); rows[0].Add("Prop2", 1); rows[0].Add("Prop4", 111); InMemoryDataReader data = new InMemoryDataReader(rows); data.Read(); var fact = factory.GetFactory<Bar>(data); var bar = fact(data); bar.Prop3.Should().Be(6); bar.Prop4.Should().Be(111); } [Fact] public void MaterializeByteArray() { var modelMapper = CreateModelMapperForBar(); DynamicMethodModelFactory factory = new DynamicMethodModelFactory(new DatabaseMapper(modelMapper)); var rows = new List<Dictionary<string, object>> { new Dictionary<string, object>() }; var image = new byte[] { 0x20, 0x20, 0x20 }; rows[0].Add("Prop1", 2); rows[0].Add("Prop2", 1); rows[0].Add("Prop4", 111); rows[0].Add("Image", image); InMemoryDataReader data = new InMemoryDataReader(rows); data.Read(); var fact = factory.GetFactory<Bar>(data); var bar = fact(data); bar.Image.Should().BeEquivalentTo(image); } [Fact] public void MaterializeByteArrayInvalidCast() { var modelMapper = CreateModelMapperForBar(); DynamicMethodModelFactory factory = new DynamicMethodModelFactory(new DatabaseMapper(modelMapper)); var rows = new List<Dictionary<string, object>> { new Dictionary<string, object>() }; var image = new byte[] { 0x20, 0x20, 0x20 }; rows[0].Add("Prop1", 2); rows[0].Add("Prop2", 1); rows[0].Add("Prop4", image); // Bar.Prop4 => integer rows[0].Add("Image", image); InMemoryDataReader data = new InMemoryDataReader(rows); data.Read(); var fact = factory.GetFactory<Bar>(data); Bar bar; Action act = () => bar = fact(data); act.Should().Throw<InvalidCastException>(); } [Fact] public void InjectServiceToProperty() { var service = new TestService(); var factory = CreateFactory(CreateModelMapperWithInjection(service)); var rows = CreateData(); rows[0].Add("XXX", 3); IDataReader data = new InMemoryDataReader(rows); data.Read(); var fact = factory.GetFactory<Foo>(data); var foo = fact(data); foo.Service.Should().Be(service); data.Read(); foo = fact(data); foo.Service.Should().Be(service); } #endregion #region Helpers private IModelMapper CreateModelMapperWithInjection(TestService service) { var modelMapper = Substitute.For<IModelMapper>(); IModelMapper mapper = new ConventionModelMapper(); var injecter = mapper.InjectionConfigurator<Foo>() .FillProperty(p => p.Service, () => service); var tableInfo = CreateTableInfo(); modelMapper.GetTableInfo<Foo>().Returns(tableInfo); modelMapper.GetTableInfo(Arg.Any<Type>()).Returns(tableInfo); modelMapper.GetInjector<Foo>().Returns(injecter as IInjector); return modelMapper; } private DynamicMethodModelFactory CreateFactory() { return CreateFactory(CreateModelMapper(CreateTableInfo())); } private DynamicMethodModelFactory CreateFactory(IModelMapper modelMapper) { DynamicMethodModelFactory factory = new DynamicMethodModelFactory(new DatabaseMapper(modelMapper)); return factory; } private IModelMapper CreateModelMapper(TableInfo tableInfo) { var modelMapper = Substitute.For<IModelMapper>(); modelMapper.GetTableInfo<Foo>().Returns(tableInfo); modelMapper.GetTableInfo(Arg.Any<Type>()).Returns(tableInfo); return modelMapper; } private TableInfo CreateTableInfo() { List<ColumnInfo> columns = new List<ColumnInfo>() { new ColumnInfo(){ Name = "Id", PropertyInfo = GetPropertyInfo<Foo>("Id"), IsPrimaryKey = true }, new ColumnInfo(){ Name = "FirstName", PropertyInfo = GetPropertyInfo<Foo>("PropertyString")}, new ColumnInfo(){ Name = "Something", PropertyInfo = GetPropertyInfo<Foo>("PropertyDouble")}, new ColumnInfo(){ Name = "Salary", PropertyInfo = GetPropertyInfo<Foo>("PropertyDecimal")}, new ColumnInfo(){ Name = "Birthday", PropertyInfo = GetPropertyInfo<Foo>("PropertyDateTime")}, new ColumnInfo(){ Name = "Is", PropertyInfo = GetPropertyInfo<Foo>("Is")}, new ColumnInfo(){ Name = "PropertyGuid", PropertyInfo = GetPropertyInfo<Foo>("PropertyGuid")}, new ColumnInfo(){ Name = "PropertyEnum", PropertyInfo = GetPropertyInfo<Foo>("PropertyEnum")}, new ColumnInfo(){ Name = "PropertyDateTimeNullable", PropertyInfo = GetPropertyInfo<Foo>("PropertyDateTimeNullable")}, new ColumnInfo(){ Name = "PropertyEnumConv", PropertyInfo = GetPropertyInfo<Foo>("PropertyEnumConv"), Converter = new TestEnumConverter()}, new ColumnInfo(){ Name = "Age", PropertyInfo = GetPropertyInfo<Foo>("Age")}, new ColumnInfo(){ Name = "Service", PropertyInfo = GetPropertyInfo<Foo>("Service")} }; TableInfo tableInfo = new TableInfo(columns, columns.Select(p => p.PropertyInfo), null); return tableInfo; } private PropertyInfo GetPropertyInfo<T>(string propertyName) { return typeof(T).GetProperty(propertyName); } private List<Dictionary<string, object>> CreateData() { List<Dictionary<string, object>> ret = new List<Dictionary<string, object>>(); AddRow(ret, 1, "Hello", 45.78, (decimal)785.78, new DateTime(1980, 7, 24), true, new Guid("ddc995d7-4dda-41ca-abab-7f45e651784a"), 18.5F); return ret; } private static void AddRow(List<Dictionary<string, object>> ret, int id, string firstName, double something, decimal salary, DateTime birthday, bool iS, Guid guid, Single? age) { Dictionary<string, object> row = new Dictionary<string, object>() { { "Id", id }, { "FirstName", firstName }, { "Something", something}, { "Salary",salary}, { "Birthday", birthday}, { "Is", iS}, { "PropertyGuid", guid}, { "Age", age} }; ret.Add(row); } private IModelMapper CreateModelMapperForBar() { var modelMapper = Substitute.For<IModelMapper>(); List<ColumnInfo> columns = new List<ColumnInfo>() { new ColumnInfo(){ Name = "Prop1", PropertyInfo = GetPropertyInfo<Bar>("Prop1"), IsPrimaryKey = true }, new ColumnInfo(){ Name = "Prop2", PropertyInfo = GetPropertyInfo<Bar>("Prop2")}, new ColumnInfo(){ Name = "Prop4", PropertyInfo = GetPropertyInfo<Bar>("Prop4")}, new ColumnInfo(){ Name = "Image", PropertyInfo = GetPropertyInfo<Bar>("Image")} }; TableInfo tableInfo = new TableInfo(columns, columns.Select(p => p.PropertyInfo), typeof(Bar).GetMethod("OnAfterMaterialize")); modelMapper.GetTableInfo<Bar>().Returns(tableInfo); modelMapper.GetTableInfo(Arg.Any<Type>()).Returns(tableInfo); return modelMapper; } #endregion #region Test classes private class Foo { public int Id { get; set; } [Alias("FirstName")] public string PropertyString { get; set; } [Alias("Something")] public double PropertyDouble { get; set; } [Alias("Salary")] public decimal PropertyDecimal { get; set; } [Alias("Birthday")] public DateTime PropertyDateTime { get; set; } public DateTime? PropertyDateTimeNullable { get; set; } public bool Is { get; set; } [NoMap] public int Bar { get; set; } public Guid PropertyGuid { get; set; } public TestEnum PropertyEnum { get; set; } [Converter(typeof(TestEnumConverter))] public TestEnum PropertyEnumConv { get; set; } public double? Age { get; set; } [NoMap()] public TestService Service { get; set; } } public class TestService { } private enum TestEnum { Value1 = 1, Value2 = 2, Value3 = 3, } private class TestEnumConverter : IConverter { public object Convert(object value) { var val = value.ToString(); if (val == "V1") { return TestEnum.Value1; } else if (val == "V2") { return TestEnum.Value2; } else { return TestEnum.Value3; } } public object ConvertBack(object value) { throw new NotImplementedException(); } } private class Bar : IMaterialize { public int Prop1 { get; set; } public int Prop2 { get; set; } [NoMap] public int Prop3 { get; set; } [NoMap] public int Prop4 { get; set; } public byte[] Image { get; set; } public void OnAfterMaterialize(IDataRecord source) { Prop3 = 2 * (Prop1 + Prop2); Prop4 = source.GetInt32(source.GetOrdinal("Prop4")); } } private class ValueTypesReader<T> : IDataReader { private readonly IEnumerator<T> _values; public ValueTypesReader(IEnumerable<T> values) { this._values = values.GetEnumerator(); } public object this[int i] => _values.Current; public object this[string name] => throw new NotImplementedException(); public int Depth => throw new NotImplementedException(); public bool IsClosed => throw new NotImplementedException(); public int RecordsAffected => throw new NotImplementedException(); public int FieldCount => 1; public void Close() { } public void Dispose() { } public bool GetBoolean(int i) => (bool)this[i]; public byte GetByte(int i) => (byte)this[i]; public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { throw new NotImplementedException(); } public char GetChar(int i) { throw new NotImplementedException(); } public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { throw new NotImplementedException(); } public IDataReader GetData(int i) { throw new NotImplementedException(); } public string GetDataTypeName(int i) { throw new NotImplementedException(); } public DateTime GetDateTime(int i) => (DateTime)this[i]; public decimal GetDecimal(int i) => (decimal)this[i]; public double GetDouble(int i) => (double)this[i]; public Type GetFieldType(int i) => typeof(T); public float GetFloat(int i) => (float)this[i]; public Guid GetGuid(int i) { throw new NotImplementedException(); } public short GetInt16(int i) { throw new NotImplementedException(); } public int GetInt32(int i) => (int)this[i]; public long GetInt64(int i) { throw new NotImplementedException(); } public string GetName(int i) => "Id"; public int GetOrdinal(string name) { throw new NotImplementedException(); } public DataTable GetSchemaTable() { throw new NotImplementedException(); } public string GetString(int i) => (string)this[i]; public object GetValue(int i) => this[i]; public int GetValues(object[] values) { throw new NotImplementedException(); } public bool IsDBNull(int i) { throw new NotImplementedException(); } public bool NextResult() { throw new NotImplementedException(); } public bool Read() => _values.MoveNext(); } #endregion } }
32.418239
155
0.519643
[ "MIT" ]
Mikado3780/Kros.Libs
Kros.KORM/tests/Kros.KORM.UnitTests/Materializer/MethodModelFactoryShould.cs
20,620
C#
// // Copyright (c) 2019-2020 Ryujinx // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // using Ryujinx.Audio.Renderer.Common; using System; using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter; namespace Ryujinx.Audio.Renderer.Dsp.Command { public class PcmFloatDataSourceCommandVersion1 : ICommand { public bool Enabled { get; set; } public int NodeId { get; } public CommandType CommandType => CommandType.PcmFloatDataSourceVersion1; public ulong EstimatedProcessingTime { get; set; } public ushort OutputBufferIndex { get; } public uint SampleRate { get; } public uint ChannelIndex { get; } public uint ChannelCount { get; } public float Pitch { get; } public WaveBuffer[] WaveBuffers { get; } public Memory<VoiceUpdateState> State { get; } public DecodingBehaviour DecodingBehaviour { get; } public PcmFloatDataSourceCommandVersion1(ref Server.Voice.VoiceState serverState, Memory<VoiceUpdateState> state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { Enabled = true; NodeId = nodeId; OutputBufferIndex = (ushort)(channelIndex + outputBufferIndex); SampleRate = serverState.SampleRate; ChannelIndex = channelIndex; ChannelCount = serverState.ChannelsCount; Pitch = serverState.Pitch; WaveBuffers = new WaveBuffer[RendererConstants.VoiceWaveBufferCount]; for (int i = 0; i < WaveBuffers.Length; i++) { ref Server.Voice.WaveBuffer voiceWaveBuffer = ref serverState.WaveBuffers[i]; WaveBuffers[i] = voiceWaveBuffer.ToCommon(1); } State = state; DecodingBehaviour = serverState.DecodingBehaviour; } public void Process(CommandList context) { Span<float> outputBuffer = context.GetBuffer(OutputBufferIndex); DataSourceHelper.WaveBufferInformation info = new DataSourceHelper.WaveBufferInformation() { State = State, SourceSampleRate = SampleRate, SampleFormat = SampleFormat.PcmInt16, Pitch = Pitch, DecodingBehaviour = DecodingBehaviour, WaveBuffers = WaveBuffers, ExtraParameter = 0, ExtraParameterSize = 0, ChannelIndex = (int)ChannelIndex, ChannelCount = (int)ChannelCount, }; DataSourceHelper.ProcessWaveBuffers(context.MemoryManager, outputBuffer, info, context.SampleRate, (int)context.SampleCount); } } }
35.946237
180
0.652109
[ "MIT" ]
AkechiShiro/Ryujinx
Ryujinx.Audio.Renderer/Dsp/Command/PcmFloatDataSourceCommandVersion1.cs
3,343
C#
using System.Collections.Generic; using System.Text; using JetBrains.Annotations; using TestableFileSystem.Interfaces; namespace TestableFileSystem.Analyzer.Tests.TestDataBuilders { /// <summary /> internal sealed class TypeSourceCodeBuilder : SourceCodeBuilder { [NotNull] [ItemNotNull] private readonly List<string> types = new List<string>(); protected override string GetSourceCode() { var builder = new StringBuilder(); AppendTypes(builder); return builder.ToString(); } private void AppendTypes([NotNull] StringBuilder builder) { int index = 0; foreach (string type in types) { if (index > 0) { builder.AppendLine(); } builder.AppendLine(type.Trim()); index++; } } [NotNull] public TypeSourceCodeBuilder InGlobalScope([NotNull] string typeCode) { Guard.NotNull(typeCode, nameof(typeCode)); types.Add(typeCode); return this; } } }
24.183673
77
0.547679
[ "Apache-2.0" ]
sankarpraveen02/sample
src/Analyzer.Tests/TestDataBuilders/TypeSourceCodeBuilder.cs
1,187
C#