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
using System.Resources; using System.Reflection; // 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("PillarDemo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PillarDemo")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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")]
34.413793
84
0.733467
[ "Apache-2.0" ]
JTOne123/Pillar
demo/PillarDemo/PillarDemo/Properties/AssemblyInfo.cs
1,001
C#
// Generated on 03/23/2022 09:50:14 using System; using System.Collections.Generic; using System.Linq; using AmaknaProxy.API.Protocol.Types; using AmaknaProxy.API.IO; using AmaknaProxy.API.Network; namespace AmaknaProxy.API.Protocol.Messages { public class BasicLatencyStatsMessage : NetworkMessage { public const uint Id = 7345; public override uint MessageId { get { return Id; } } public ushort latency; public uint sampleCount; public uint max; public BasicLatencyStatsMessage() { } public BasicLatencyStatsMessage(ushort latency, uint sampleCount, uint max) { this.latency = latency; this.sampleCount = sampleCount; this.max = max; } public override void Serialize(IDataWriter writer) { writer.WriteUShort(latency); writer.WriteVarShort((short)sampleCount); writer.WriteVarShort((short)max); } public override void Deserialize(IDataReader reader) { latency = reader.ReadUShort(); sampleCount = reader.ReadVarUShort(); max = reader.ReadVarUShort(); } } }
25.076923
83
0.582055
[ "MIT" ]
ImNotARobot742/DofusProtocol
DofusProtocol/D2Parser/Protocol/Messages/game/basic/BasicLatencyStatsMessage.cs
1,304
C#
using System; using System.Runtime.InteropServices; using System.Security; namespace BulletSharp { public class Convex2DShape : ConvexShape { private ConvexShape _childShape; public Convex2DShape(ConvexShape convexChildShape) : base(btConvex2dShape_new(convexChildShape._native)) { _childShape = convexChildShape; } public ConvexShape ChildShape { get { return _childShape; } } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btConvex2dShape_new(IntPtr convexChildShape); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern IntPtr btConvex2dShape_getChildShape(IntPtr obj); } }
26.964286
91
0.762914
[ "BSD-3-Clause" ]
OneYoungMean/libmmd-for-unity
Assets/LibMmd/Plugins/BulletUnity/BulletSharp/Collision/Convex2DShape.cs
755
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using DefaultDocumentation.Api; using DefaultDocumentation.Markdown.Internal; using DefaultDocumentation.Models; namespace DefaultDocumentation.Markdown.FileNameFactories { /// <summary> /// Base implementation of the <see cref="IFileNameFactory"/> to generate file with a <c>.md</c> extension. /// It will also replace invalid char that may be present with the <see href="https://github.com/Doraku/DefaultDocumentation#invalidcharreplacement">Markdown.InvalidCharReplacement</see> setting. /// </summary> public abstract class AMarkdownFactory : IFileNameFactory { /// <inheritdoc/> public abstract string Name { get; } /// <summary> /// Gets the file name to use for the given <see cref="DocItem"/>. /// </summary> /// <param name="context">The <see cref="IGeneralContext"/> of the current documentation generation process.</param> /// <param name="item">The <see cref="DocItem"/> for which to get the documentation file name.</param> /// <returns>The file name to use.</returns> protected abstract string GetMarkdownFileName(IGeneralContext context, DocItem item); /// <inheritdoc/> public void Clean(IGeneralContext context) { context.Settings.Logger.Debug($"Cleaning output folder \"{context.Settings.OutputDirectory}\""); if (context.Settings.OutputDirectory.Exists) { IEnumerable<FileInfo> files = context.Settings.OutputDirectory.EnumerateFiles("*.md").Where(f => !string.Equals(f.Name, "readme.md", StringComparison.OrdinalIgnoreCase)); int i; foreach (FileInfo file in files) { i = 3; start: try { file.Delete(); } catch { if (--i > 0) { Thread.Sleep(100); goto start; } throw; } } i = 3; while (files.Any() && i-- > 0) { Thread.Sleep(1000); } } } /// <inheritdoc/> public string GetFileName(IGeneralContext context, DocItem item) => PathCleaner.Clean(item is AssemblyDocItem ? item.FullName : GetMarkdownFileName(context, item), context.GetInvalidCharReplacement()) + ".md"; } }
37.5
217
0.555185
[ "MIT-0" ]
Doraku/DefaultApiDocumentation
source/DefaultDocumentation.Markdown/FileNameFactories/AMarkdownFactory.cs
2,702
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Juice : MonoBehaviour { [SerializeField] MeshRenderer m_JuiceMeshRenderer; const string k_URPListShader = "Universal Render Pipeline/Lit"; public void SetJuiceColor(Color juiceColor) { Material newMat = new Material(Shader.Find(k_URPListShader)); newMat.color = juiceColor; if (m_JuiceMeshRenderer != null) { m_JuiceMeshRenderer.material = newMat; } } }
23.217391
69
0.674157
[ "MIT" ]
DanMillerDev/JuiceMaker
Assets/Scripts/Juice.cs
534
C#
using System.Drawing; using System.Threading; using GHIElectronics.TinyCLR.Devices.Spi; using GHIElectronics.TinyCLR.Drivers.ShijiLighting.APA102C; using GHIElectronics.TinyCLR.Pins; namespace APA102CLedStrip { public static class Program { public static void Main() { var spi1Controller = SpiController.FromName(FEZ.SpiBus.Spi1); var ledCount = 10; var apa102c = new APA102CController(spi1Controller.GetDevice(APA102CController.GetConnectionSettings()), ledCount); while (true) { for (var i = 0; i < ledCount; i++) { apa102c.Set(i, Color.Blue); apa102c.Flush(); Thread.Sleep(125); apa102c.Set(i, Color.Black); apa102c.Flush(); Thread.Sleep(125); } Thread.Sleep(2500); } } } }
31.16129
127
0.541408
[ "Apache-2.0" ]
RoSchmi/TinyCLR-Samples
Old/Components/APA102CLedStrip/Program.cs
966
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 glacier-2012-06-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Glacier.Model { /// <summary> /// Contains the Amazon S3 Glacier response to your request. /// </summary> public partial class UploadMultipartPartResponse : AmazonWebServiceResponse { private string _checksum; /// <summary> /// Gets and sets the property Checksum. /// <para> /// The SHA256 tree hash that Amazon S3 Glacier computed for the uploaded part. /// </para> /// </summary> public string Checksum { get { return this._checksum; } set { this._checksum = value; } } // Check to see if Checksum property is set internal bool IsSetChecksum() { return this._checksum != null; } } }
29.280702
105
0.659676
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Glacier/Generated/Model/UploadMultipartPartResponse.cs
1,669
C#
using Microsoft.AspNetCore.Mvc; namespace MvcClient.Controllers { public class AuthorizationController: Controller { public IActionResult AccessDenied() { return View(); } } }
19.333333
52
0.607759
[ "MIT" ]
xcodexnet/ASP.NET-Core-REST-API-Starter-Template
src/MvcClient/Controllers/AuthorizationController.cs
232
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementAndStatementGetArgs : Pulumi.ResourceArgs { [Input("statements", required: true)] private InputList<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementAndStatementStatementGetArgs>? _statements; /// <summary> /// Statements to combine with `AND` logic. You can use any statements that can be nested. See Statement above for details. /// </summary> public InputList<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementAndStatementStatementGetArgs> Statements { get => _statements ?? (_statements = new InputList<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementAndStatementStatementGetArgs>()); set => _statements = value; } public WebAclRuleStatementRateBasedStatementScopeDownStatementAndStatementGetArgs() { } } }
40.71875
158
0.741366
[ "ECL-2.0", "Apache-2.0" ]
chivandikwa/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementAndStatementGetArgs.cs
1,303
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DataFactory.V20170901Preview.Outputs { [OutputType] public sealed class MultiplePipelineTriggerResponse { /// <summary> /// Trigger description. /// </summary> public readonly string? Description; /// <summary> /// Pipelines that need to be started. /// </summary> public readonly ImmutableArray<Outputs.TriggerPipelineReferenceResponse> Pipelines; /// <summary> /// Indicates if trigger is running or not. Updated when Start/Stop APIs are called on the Trigger. /// </summary> public readonly string RuntimeState; /// <summary> /// Trigger type. /// Expected value is 'MultiplePipelineTrigger'. /// </summary> public readonly string Type; [OutputConstructor] private MultiplePipelineTriggerResponse( string? description, ImmutableArray<Outputs.TriggerPipelineReferenceResponse> pipelines, string runtimeState, string type) { Description = description; Pipelines = pipelines; RuntimeState = runtimeState; Type = type; } } }
30.137255
107
0.629798
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/DataFactory/V20170901Preview/Outputs/MultiplePipelineTriggerResponse.cs
1,537
C#
using System.Collections.Generic; using HamzaBank.Api.Models; using HamzaBank.Api.Repositories; namespace HamzaBank.Api.Services { public class MenuItemService : IMenuItemService { private readonly IMenuItemRepository _menuItemRepository; public MenuItemService(IMenuItemRepository menuItemRepository) { _menuItemRepository = menuItemRepository; } public void Add(MenuItem menuItem) { _menuItemRepository.Add(menuItem); } public MenuItem Get(long id) { return _menuItemRepository.Get(id); } public IList<MenuItem> GetAll() { return _menuItemRepository.GetAll(); } } }
24.633333
70
0.633288
[ "MIT" ]
hamzaak/hamzabank
backend/Services/MenuItemService.cs
739
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEngine; namespace ReactiveConsole { public interface IHttpRequestSolver { bool Match(HttpRequest request); void Solve(Stream s, HttpSession session, HttpRequest request); } public class OkSolver : IHttpRequestSolver { Utf8Bytes m_body = Utf8Bytes.From("Hello"); public bool Match(HttpRequest _) { return true; } public void Solve(Stream s, HttpSession session, HttpRequest request) { Logging.Info(string.Format("[{0}] 200 <= {1}", session.ID, request)); // header Http10StatusLine.Ok.WriteTo(s); s.CRLF(); // body m_body.WriteTo(s); } } public class FolderMounter : IHttpRequestSolver { Utf8Bytes m_mountPoint; string m_path; public delegate Utf8Bytes PathFilter(Utf8Bytes src); PathFilter m_filter; static readonly Utf8Bytes s_js = Utf8Bytes.From(".js"); static readonly Utf8Bytes s_css = Utf8Bytes.From(".css"); static readonly Utf8Bytes s_txt = Utf8Bytes.From(".txt"); public static Utf8Bytes JsTxtFilter(Utf8Bytes src) { if (src.EndsWith(s_js) || src.EndsWith(s_css)) { src = src.Concat(s_txt); } return src; } public FolderMounter(string mountPoint, string path, PathFilter pathFilter) { m_mountPoint = Utf8Bytes.From(mountPoint); m_path = path; m_filter = pathFilter; } public bool Match(HttpRequest request) { var path = request.Path; return path.StartsWith(m_mountPoint); } public void Solve(Stream s, HttpSession session, HttpRequest request) { var path = m_filter != null ? m_filter(request.IndexPath) : request.IndexPath ; var fullPath = Path.Combine(m_path, path.Subbytes(1).ToString()); if (!File.Exists(fullPath)) { // 404 Logging.Info(string.Format("[{0}] 404 <= {1}", session.ID, request)); Http10StatusLine.NotFound.WriteTo(s); s.CRLF(); s.CRLF(); return; } // 200 Logging.Info(string.Format("[{0}] 200 <= {1}", session.ID, request)); Http10StatusLine.Ok.WriteTo(s); s.CRLF(); s.CRLF(); // body using (var r = File.Open(fullPath, FileMode.Open, FileAccess.Read)) { r.CopyTo(s); } } } [Serializable] public struct AssetMount { public string MountPoint; public TextAsset Asset; public Byte[] Bytes { get; private set; } public AssetMount(string mountPoint, string resourceName) { MountPoint = mountPoint; Asset = Resources.Load<TextAsset>(resourceName); Bytes = null; } public void Initialize() { #if UNITY_EDITOR #else Bytes = Asset.bytes; #endif } public Func<Byte[]> Loader { get { #if UNITY_EDITOR var assetPath = UnityEditor.AssetDatabase.GetAssetPath(Asset); return () => File.ReadAllBytes(assetPath); #else var bytes = Bytes; return () => bytes; #endif } } } public class FileMounter : IHttpRequestSolver { Utf8Bytes m_mountPoint; Func<Byte[]> m_content; public FileMounter(AssetMount mount) : this(mount.MountPoint, mount.Loader) { } public FileMounter(String mountPoint, Func<Byte[]> content) { m_mountPoint = Utf8Bytes.From(mountPoint); m_content = content; } public bool Match(HttpRequest request) { var path = request.IndexPath; return m_mountPoint == path; } public void Solve(Stream s, HttpSession session, HttpRequest request) { // 200 Logging.Info(string.Format("[{0}] 200 <= {1}", session.ID, request)); Http10StatusLine.Ok.WriteTo(s); s.CRLF(); s.CRLF(); var bytes = m_content(); new Utf8Bytes(bytes).WriteTo(s); } } public class DispatchSolver : IHttpRequestSolver { List<IHttpRequestSolver> m_solvers = new List<IHttpRequestSolver>(); public List<IHttpRequestSolver> Solvers { get { return m_solvers; } } IHttpRequestSolver m_defaultSolver = new OkSolver(); public bool Match(HttpRequest request) { throw new System.NotImplementedException(); } public void Solve(Stream s, HttpSession session, HttpRequest request) { var solver = m_solvers.FirstOrDefault(x => x.Match(request)); if (solver == null) { solver = m_defaultSolver; } solver.Solve(s, session, request); } } }
26.542289
85
0.535333
[ "MIT" ]
ousttrue/ReactiveConsole
Scripts/Http/HttpRequestSolver.cs
5,335
C#
namespace KrmKantar2013 { partial class FrmYanLiman { /// <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(FrmYanLiman)); this.grpArac = new DevExpress.XtraEditors.GroupControl(); this.txtSapFisNo = new DevExpress.XtraEditors.TextEdit(); this.txtT02 = new DevExpress.XtraEditors.SpinEdit(); this.txtT01 = new DevExpress.XtraEditors.SpinEdit(); this.lbNetTutar = new DevExpress.XtraEditors.LabelControl(); this.txtNet = new DevExpress.XtraEditors.TextEdit(); this.lbMalzeme = new DevExpress.XtraEditors.LabelControl(); this.txtMalzeme = new DevExpress.XtraEditors.TextEdit(); this.lbPlakaSap = new DevExpress.XtraEditors.LabelControl(); this.txtPlakaNo = new DevExpress.XtraEditors.TextEdit(); this.btnSave = new DevExpress.XtraEditors.SimpleButton(); this.btnCancel = new DevExpress.XtraEditors.SimpleButton(); this.lbTitle = new DevExpress.XtraEditors.LabelControl(); ((System.ComponentModel.ISupportInitialize)(this.grpArac)).BeginInit(); this.grpArac.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.txtSapFisNo.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtT02.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtT01.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtNet.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtMalzeme.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtPlakaNo.Properties)).BeginInit(); this.SuspendLayout(); // // grpArac // this.grpArac.Controls.Add(this.txtSapFisNo); this.grpArac.Controls.Add(this.txtT02); this.grpArac.Controls.Add(this.txtT01); this.grpArac.Controls.Add(this.lbNetTutar); this.grpArac.Controls.Add(this.txtNet); this.grpArac.Controls.Add(this.lbMalzeme); this.grpArac.Controls.Add(this.txtMalzeme); this.grpArac.Controls.Add(this.lbPlakaSap); this.grpArac.Controls.Add(this.txtPlakaNo); this.grpArac.Location = new System.Drawing.Point(20, 56); this.grpArac.Name = "grpArac"; this.grpArac.ShowCaption = false; this.grpArac.Size = new System.Drawing.Size(510, 170); this.grpArac.TabIndex = 0; // // txtSapFisNo // this.txtSapFisNo.EditValue = ""; this.txtSapFisNo.EnterMoveNextControl = true; this.txtSapFisNo.Location = new System.Drawing.Point(304, 24); this.txtSapFisNo.Name = "txtSapFisNo"; this.txtSapFisNo.Properties.Appearance.BackColor = System.Drawing.Color.Black; this.txtSapFisNo.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.txtSapFisNo.Properties.Appearance.ForeColor = System.Drawing.Color.Aqua; this.txtSapFisNo.Properties.Appearance.Options.UseBackColor = true; this.txtSapFisNo.Properties.Appearance.Options.UseFont = true; this.txtSapFisNo.Properties.Appearance.Options.UseForeColor = true; this.txtSapFisNo.Properties.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper; this.txtSapFisNo.Properties.MaxLength = 10; this.txtSapFisNo.Properties.ReadOnly = true; this.txtSapFisNo.Size = new System.Drawing.Size(177, 26); this.txtSapFisNo.TabIndex = 1; // // txtT02 // this.txtT02.EditValue = new decimal(new int[] { 116500, 0, 0, 0}); this.txtT02.EnterMoveNextControl = true; this.txtT02.Location = new System.Drawing.Point(244, 118); this.txtT02.Name = "txtT02"; this.txtT02.Properties.Appearance.BackColor = System.Drawing.Color.Black; this.txtT02.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.txtT02.Properties.Appearance.ForeColor = System.Drawing.Color.White; this.txtT02.Properties.Appearance.Options.UseBackColor = true; this.txtT02.Properties.Appearance.Options.UseFont = true; this.txtT02.Properties.Appearance.Options.UseForeColor = true; this.txtT02.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.txtT02.Properties.DisplayFormat.FormatString = "0,0"; this.txtT02.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; this.txtT02.Properties.EditFormat.FormatString = "0,0"; this.txtT02.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric; this.txtT02.Properties.IsFloatValue = false; this.txtT02.Properties.Mask.EditMask = "N00"; this.txtT02.Properties.MaxValue = new decimal(new int[] { 100000, 0, 0, 0}); this.txtT02.Properties.MinValue = new decimal(new int[] { 1, 0, 0, 0}); this.txtT02.Size = new System.Drawing.Size(114, 26); this.txtT02.TabIndex = 4; this.txtT02.EditValueChanged += new System.EventHandler(this.txtALL_EditValueChanged); // // txtT01 // this.txtT01.EditValue = new decimal(new int[] { 122500, 0, 0, 0}); this.txtT01.EnterMoveNextControl = true; this.txtT01.Location = new System.Drawing.Point(121, 118); this.txtT01.Name = "txtT01"; this.txtT01.Properties.Appearance.BackColor = System.Drawing.Color.Black; this.txtT01.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.txtT01.Properties.Appearance.ForeColor = System.Drawing.Color.White; this.txtT01.Properties.Appearance.Options.UseBackColor = true; this.txtT01.Properties.Appearance.Options.UseFont = true; this.txtT01.Properties.Appearance.Options.UseForeColor = true; this.txtT01.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.txtT01.Properties.DisplayFormat.FormatString = "0,0"; this.txtT01.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; this.txtT01.Properties.EditFormat.FormatString = "0,0"; this.txtT01.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric; this.txtT01.Properties.IsFloatValue = false; this.txtT01.Properties.Mask.EditMask = "N00"; this.txtT01.Properties.MaxValue = new decimal(new int[] { 100000, 0, 0, 0}); this.txtT01.Properties.MinValue = new decimal(new int[] { 1, 0, 0, 0}); this.txtT01.Size = new System.Drawing.Size(114, 26); this.txtT01.TabIndex = 3; this.txtT01.EditValueChanged += new System.EventHandler(this.txtALL_EditValueChanged); // // lbNetTutar // this.lbNetTutar.Appearance.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.lbNetTutar.Location = new System.Drawing.Point(23, 125); this.lbNetTutar.Name = "lbNetTutar"; this.lbNetTutar.Size = new System.Drawing.Size(90, 14); this.lbNetTutar.TabIndex = 31; this.lbNetTutar.Text = "T1 / T2 / NET :"; // // txtNet // this.txtNet.EditValue = 65500; this.txtNet.EnterMoveNextControl = true; this.txtNet.Location = new System.Drawing.Point(367, 118); this.txtNet.Name = "txtNet"; this.txtNet.Properties.Appearance.BackColor = System.Drawing.Color.Black; this.txtNet.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.txtNet.Properties.Appearance.ForeColor = System.Drawing.Color.Aqua; this.txtNet.Properties.Appearance.Options.UseBackColor = true; this.txtNet.Properties.Appearance.Options.UseFont = true; this.txtNet.Properties.Appearance.Options.UseForeColor = true; this.txtNet.Properties.Appearance.Options.UseTextOptions = true; this.txtNet.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; this.txtNet.Properties.DisplayFormat.FormatString = "0,0 Kg"; this.txtNet.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; this.txtNet.Properties.EditFormat.FormatString = "0,0 Kg"; this.txtNet.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric; this.txtNet.Properties.MaxLength = 10; this.txtNet.Properties.ReadOnly = true; this.txtNet.Size = new System.Drawing.Size(114, 26); this.txtNet.TabIndex = 5; // // lbMalzeme // this.lbMalzeme.Appearance.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.lbMalzeme.Location = new System.Drawing.Point(29, 63); this.lbMalzeme.Name = "lbMalzeme"; this.lbMalzeme.Size = new System.Drawing.Size(84, 14); this.lbMalzeme.TabIndex = 29; this.lbMalzeme.Text = "Malzeme Adı :"; // // txtMalzeme // this.txtMalzeme.EditValue = ""; this.txtMalzeme.EnterMoveNextControl = true; this.txtMalzeme.Location = new System.Drawing.Point(121, 56); this.txtMalzeme.Name = "txtMalzeme"; this.txtMalzeme.Properties.Appearance.BackColor = System.Drawing.Color.Black; this.txtMalzeme.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.txtMalzeme.Properties.Appearance.ForeColor = System.Drawing.Color.Aqua; this.txtMalzeme.Properties.Appearance.Options.UseBackColor = true; this.txtMalzeme.Properties.Appearance.Options.UseFont = true; this.txtMalzeme.Properties.Appearance.Options.UseForeColor = true; this.txtMalzeme.Properties.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper; this.txtMalzeme.Properties.MaxLength = 10; this.txtMalzeme.Properties.ReadOnly = true; this.txtMalzeme.Size = new System.Drawing.Size(360, 26); this.txtMalzeme.TabIndex = 2; // // lbPlakaSap // this.lbPlakaSap.Appearance.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.lbPlakaSap.Location = new System.Drawing.Point(33, 31); this.lbPlakaSap.Name = "lbPlakaSap"; this.lbPlakaSap.Size = new System.Drawing.Size(80, 14); this.lbPlakaSap.TabIndex = 27; this.lbPlakaSap.Text = "Plaka / SAP :"; // // txtPlakaNo // this.txtPlakaNo.EditValue = ""; this.txtPlakaNo.EnterMoveNextControl = true; this.txtPlakaNo.Location = new System.Drawing.Point(121, 24); this.txtPlakaNo.Name = "txtPlakaNo"; this.txtPlakaNo.Properties.Appearance.BackColor = System.Drawing.Color.Black; this.txtPlakaNo.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.txtPlakaNo.Properties.Appearance.ForeColor = System.Drawing.Color.Aqua; this.txtPlakaNo.Properties.Appearance.Options.UseBackColor = true; this.txtPlakaNo.Properties.Appearance.Options.UseFont = true; this.txtPlakaNo.Properties.Appearance.Options.UseForeColor = true; this.txtPlakaNo.Properties.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper; this.txtPlakaNo.Properties.MaxLength = 10; this.txtPlakaNo.Properties.ReadOnly = true; this.txtPlakaNo.Size = new System.Drawing.Size(179, 26); this.txtPlakaNo.TabIndex = 0; // // btnSave // this.btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnSave.Appearance.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.btnSave.Appearance.ForeColor = System.Drawing.Color.Black; this.btnSave.Appearance.Options.UseFont = true; this.btnSave.Appearance.Options.UseForeColor = true; this.btnSave.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnSave.Location = new System.Drawing.Point(334, 242); this.btnSave.LookAndFeel.SkinName = "Glass Oceans"; this.btnSave.LookAndFeel.UseDefaultLookAndFeel = false; this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(100, 30); this.btnSave.TabIndex = 0; this.btnSave.Text = "Kaydet"; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnCancel.Appearance.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.btnCancel.Appearance.ForeColor = System.Drawing.Color.Black; this.btnCancel.Appearance.Options.UseFont = true; this.btnCancel.Appearance.Options.UseForeColor = true; this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(450, 242); this.btnCancel.LookAndFeel.SkinName = "DevExpress Dark Style"; this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(80, 28); this.btnCancel.TabIndex = 1; this.btnCancel.Text = "İptal"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // lbTitle // this.lbTitle.Appearance.BackColor = System.Drawing.Color.Navy; this.lbTitle.Appearance.Font = new System.Drawing.Font("Tahoma", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.lbTitle.Appearance.ForeColor = System.Drawing.Color.White; this.lbTitle.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; this.lbTitle.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None; this.lbTitle.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder; this.lbTitle.Dock = System.Windows.Forms.DockStyle.Top; this.lbTitle.Location = new System.Drawing.Point(0, 0); this.lbTitle.LookAndFeel.UseDefaultLookAndFeel = false; this.lbTitle.Name = "lbTitle"; this.lbTitle.Size = new System.Drawing.Size(554, 40); this.lbTitle.TabIndex = 3; this.lbTitle.Text = "YAN LİMAN TARTIMLARI"; // // FrmYanLiman // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(554, 284); this.Controls.Add(this.lbTitle); this.Controls.Add(this.btnSave); this.Controls.Add(this.btnCancel); this.Controls.Add(this.grpArac); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FrmYanLiman"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Tartım Formu"; this.Shown += new System.EventHandler(this.FrmTartim_Shown); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmTartim_KeyDown); ((System.ComponentModel.ISupportInitialize)(this.grpArac)).EndInit(); this.grpArac.ResumeLayout(false); this.grpArac.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.txtSapFisNo.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtT02.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtT01.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtNet.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtMalzeme.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtPlakaNo.Properties)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraEditors.GroupControl grpArac; private DevExpress.XtraEditors.SimpleButton btnSave; private DevExpress.XtraEditors.SimpleButton btnCancel; private DevExpress.XtraEditors.LabelControl lbNetTutar; private DevExpress.XtraEditors.TextEdit txtNet; private DevExpress.XtraEditors.LabelControl lbMalzeme; private DevExpress.XtraEditors.TextEdit txtMalzeme; private DevExpress.XtraEditors.LabelControl lbPlakaSap; private DevExpress.XtraEditors.TextEdit txtPlakaNo; private DevExpress.XtraEditors.LabelControl lbTitle; private DevExpress.XtraEditors.SpinEdit txtT01; private DevExpress.XtraEditors.SpinEdit txtT02; private DevExpress.XtraEditors.TextEdit txtSapFisNo; } }
58.660969
179
0.627829
[ "MIT" ]
hy2015tr/Kantar2013
Forms/FrmYanLiman.Designer.cs
20,596
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.Build.Framework; using Microsoft.NET.TestFramework; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Xunit; using Xunit.Abstractions; using static Microsoft.NET.Build.Tasks.ResolveTargetingPackAssets; namespace Microsoft.NET.Build.Tasks.UnitTests { public class GivenAResolveTargetingPackAssetsTask : SdkTest { public GivenAResolveTargetingPackAssetsTask(ITestOutputHelper log) : base(log) { } [Fact] public void Given_ResolvedTargetingPacks_with_valid_PATH_in_PlatformManifest_It_resolves_TargetingPack() { ResolveTargetingPackAssets task = InitializeMockTargetingPackAssetsDirectory(out string mockPackageDirectory); task.Execute().Should().BeTrue(); task.ReferencesToAdd[0].ItemSpec.Should().Be(Path.Combine(mockPackageDirectory, "lib/Microsoft.Windows.SDK.NET.dll")); task.PlatformManifests[0].ItemSpec.Should().Be(Path.Combine(mockPackageDirectory, $"data{Path.DirectorySeparatorChar}PlatformManifest.txt")); task.AnalyzersToAdd.Length.Should().Be(2); task.AnalyzersToAdd[0].ItemSpec.Should().Be(Path.Combine(mockPackageDirectory, "analyzers/dotnet/anyAnalyzer.dll")); task.AnalyzersToAdd[1].ItemSpec.Should().Be(Path.Combine(mockPackageDirectory, "analyzers/dotnet/cs/csAnalyzer.dll")); ((MockBuildEngine4)task.BuildEngine).RegisteredTaskObjectsQueries.Should().Be(2, because: "There should be a lookup for the overall and the specific targeting pack"); ((MockBuildEngine4)task.BuildEngine).RegisteredTaskObjects.Count.Should().Be(2, because: "There should be a cache entry for the overall lookup and for the specific targeting pack"); } [Fact] public void It_Uses_Multiple_Frameworks() { ResolveTargetingPackAssets task = InitializeMockTargetingPackAssetsDirectory(out string mockPackageDirectory); // Add two RuntimeFrameworks that both point to the default targeting pack. task.RuntimeFrameworks = new[] { new MockTaskItem("RuntimeFramework1", new Dictionary<string, string>{ ["FrameworkName"] = "Microsoft.Windows.SDK.NET.Ref"}), new MockTaskItem("RuntimeFramework2", new Dictionary<string, string>{ ["FrameworkName"] = "Microsoft.Windows.SDK.NET.Ref"}), }; task.Execute().Should().BeTrue(); task.UsedRuntimeFrameworks.Select(item => item.ItemSpec) .Should().BeEquivalentTo(new[] { "RuntimeFramework1", "RuntimeFramework2", }); } [Fact] public void Given_Passing_ResolvedTargetingPacks_It_Passes_Again_With_Cached_Results() { ResolveTargetingPackAssets task1 = InitializeMockTargetingPackAssetsDirectory(out string packageDirectory); // Save off that build engine to inspect and reuse MockBuildEngine4 buildEngine = (MockBuildEngine4)task1.BuildEngine; task1.Execute().Should().BeTrue(); buildEngine.RegisteredTaskObjectsQueries.Should().Be(2, because: "there should be a lookup for the overall and the specific targeting pack"); buildEngine.RegisteredTaskObjects.Count.Should().Be(2, because: "there should be a cache entry for the overall lookup and for the specific targeting pack"); ResolveTargetingPackAssets task2 = InitializeTask(packageDirectory, buildEngine); task2.Execute().Should().BeTrue(); buildEngine.RegisteredTaskObjectsQueries.Should().Be(3, because: "there should be a hit on the overall lookup this time through"); buildEngine.RegisteredTaskObjects.Count.Should().Be(2, because: "the cache keys should match"); } [Fact] public void Given_Passing_ResolvedTargetingPacks_A_Different_Language_Parses_Again() { ResolveTargetingPackAssets task1 = InitializeMockTargetingPackAssetsDirectory(out string packageDirectory); // Save off that build engine to inspect and reuse MockBuildEngine4 buildEngine = (MockBuildEngine4)task1.BuildEngine; task1.Execute().Should().BeTrue(); buildEngine.RegisteredTaskObjectsQueries.Should().Be(2, because: "there should be a lookup for the overall and the specific targeting pack"); buildEngine.RegisteredTaskObjects.Count.Should().Be(2, because: "there should be a cache entry for the overall lookup and for the specific targeting pack"); ResolveTargetingPackAssets task2 = InitializeTask(packageDirectory, buildEngine); task2.ProjectLanguage = "F#"; task2.Execute().Should().BeTrue(); buildEngine.RegisteredTaskObjectsQueries.Should().Be(4, because: "there should be no hits on the overall or targeting pack lookup this time through"); buildEngine.RegisteredTaskObjects.Count.Should().Be(4, because: "there should be distinct results for C# and F#"); } private ResolveTargetingPackAssets InitializeMockTargetingPackAssetsDirectory(out string mockPackageDirectory, [CallerMemberName] string testName = nameof(GivenAResolvePackageAssetsTask)) { mockPackageDirectory = _testAssetsManager.CreateTestDirectory(testName: testName).Path; string dataDir = Path.Combine(mockPackageDirectory, "data"); Directory.CreateDirectory(dataDir); File.WriteAllText(Path.Combine(dataDir, "FrameworkList.xml"), _frameworkList); File.WriteAllText(Path.Combine(dataDir, "PlatformManifest.txt"), ""); return InitializeTask(mockPackageDirectory, new MockBuildEngine4()); } private ResolveTargetingPackAssets InitializeTask(string mockPackageDirectory, IBuildEngine buildEngine) { var task = new ResolveTargetingPackAssets() { BuildEngine = buildEngine, }; task.FrameworkReferences = DefaultFrameworkReferences(); task.ResolvedTargetingPacks = DefaultTargetingPacks(mockPackageDirectory); task.ProjectLanguage = "C#"; return task; } private static MockTaskItem[] DefaultTargetingPacks(string mockPackageDirectory) => new[] { new MockTaskItem("Microsoft.Windows.SDK.NET.Ref", new Dictionary<string, string>() { {MetadataKeys.NuGetPackageId, "Microsoft.Windows.SDK.NET.Ref"}, {MetadataKeys.NuGetPackageVersion, "5.0.0-preview1"}, {MetadataKeys.PackageConflictPreferredPackages, "Microsoft.Windows.SDK.NET.Ref;"}, {MetadataKeys.PackageDirectory, mockPackageDirectory}, {MetadataKeys.Path, mockPackageDirectory}, {"TargetFramework", "net5.0"} }) }; private static MockTaskItem[] DefaultFrameworkReferences() => new[] { new MockTaskItem("Microsoft.Windows.SDK.NET.Ref", new Dictionary<string, string>()) }; private readonly string _frameworkList = @"<FileList Name=""cswinrt .NET Core 5.0""> <File Type=""Managed"" Path=""lib/Microsoft.Windows.SDK.NET.dll"" PublicKeyToken=""null"" AssemblyName=""Microsoft.Windows.SDK.NET"" AssemblyVersion=""10.0.18362.3"" FileVersion=""10.0.18362.3"" /> <File Type=""Analyzer"" Path=""analyzers/dotnet/anyAnalyzer.dll"" PublicKeyToken=""null"" AssemblyName=""anyAnalyzer"" AssemblyVersion=""10.0.18362.3"" FileVersion=""10.0.18362.3"" /> <File Type=""Analyzer"" Language=""cs"" Path=""analyzers/dotnet/cs/csAnalyzer.dll"" PublicKeyToken=""null"" AssemblyName=""csAnalyzer"" AssemblyVersion=""10.0.18362.3"" FileVersion=""10.0.18362.3"" /> <File Type=""Analyzer"" Language=""vb"" Path=""analyzers/dotnet/vb/vbAnalyzer.dll"" PublicKeyToken=""null"" AssemblyName=""vbAnalyzer"" AssemblyVersion=""10.0.18362.3"" FileVersion=""10.0.18362.3"" /> </FileList>"; private class MockBuildEngine4 : MockBuildEngine, IBuildEngine4 { public bool IsRunningMultipleNodes => throw new NotImplementedException(); public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs, string toolsVersion) => throw new NotImplementedException(); public BuildEngineResult BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList<string>[] removeGlobalProperties, string[] toolsVersion, bool returnTargetOutputs) => throw new NotImplementedException(); public bool BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion) => throw new NotImplementedException(); public void Reacquire() => throw new NotImplementedException(); public object UnregisterTaskObject(object key, RegisteredTaskObjectLifetime lifetime) => throw new NotImplementedException(); public void Yield() => throw new NotImplementedException(); public object GetRegisteredTaskObject(object key, RegisteredTaskObjectLifetime lifetime) { RegisteredTaskObjectsQueries++; RegisteredTaskObjects.TryGetValue(key, out object ret); return ret; } public void RegisterTaskObject(object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection) { RegisteredTaskObjects.Add(key, obj); } public Dictionary<object, object> RegisteredTaskObjects { get; } = new Dictionary<object, object>(); public int RegisteredTaskObjectsQueries = 0; } [Fact] public void It_Hashes_All_Inputs() { IEnumerable<PropertyInfo> inputProperties; var task = InitializeTaskForHashTesting(out inputProperties); string oldHash; try { oldHash = task.GetInputs().CacheKey(); } catch (ArgumentNullException) { Assert.True( false, nameof(StronglyTypedInputs) + " is likely not correctly handling null value of one or more optional task parameters"); throw; // unreachable } foreach (var property in inputProperties) { switch (property.PropertyType) { case var t when t == typeof(bool): property.SetValue(task, !(bool)property.GetValue(task)); break; case var t when t == typeof(string): property.SetValue(task, property.Name); break; case var t when t == typeof(ITaskItem[]): property.SetValue(task, new[] { new MockTaskItem() { ItemSpec = property.Name } }); // TODO: ideally this would also mutate the relevant metadata per item break; default: Assert.True(false, $"{property.Name} is not a bool or string or ITaskItem[]. Update the test code to handle that."); throw null; // unreachable } string newHash = task.GetInputs().CacheKey(); newHash.Should().NotBe( oldHash, because: $"{property.Name} should be included in hash"); oldHash = newHash; } } private ResolveTargetingPackAssets InitializeTaskForHashTesting(out IEnumerable<PropertyInfo> inputProperties) { inputProperties = typeof(ResolveTargetingPackAssets) .GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) .Where(p => !p.IsDefined(typeof(OutputAttribute)) && p.Name != nameof(ResolvePackageAssets.DesignTimeBuild)) .OrderBy(p => p.Name, StringComparer.Ordinal); var requiredProperties = inputProperties .Where(p => p.IsDefined(typeof(RequiredAttribute))); ResolveTargetingPackAssets task = new(); // Initialize all required properties as a genuine task invocation would. We do this // because HashSettings need not defend against required parameters being null. foreach (var property in requiredProperties) { property.PropertyType.Should().Be( typeof(string), because: $"this test hasn't been updated to handle non-string required task parameters like {property.Name}"); property.SetValue(task, "_"); } return task; } [Fact] public static void It_Hashes_All_Inputs_To_FrameworkList() { var constructor = typeof(FrameworkListDefinition).GetConstructors().Single(); var parameters = constructor.GetParameters(); var args = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { args[i] = parameters[i].ParameterType switch { var t when t == typeof(string) => string.Empty, _ => throw new NotImplementedException($"{parameters[i].ParameterType} is an unknown type. Update the test code to handle that.") }; } FrameworkListDefinition defaultObject = (FrameworkListDefinition)constructor.Invoke(args); List<string> seenKeys = new List<string>(args.Length + 1); seenKeys.Add(defaultObject.CacheKey()); for (int i = 0; i < args.Length; i++) { args[i] = parameters[i].ParameterType switch { var t when t == typeof(string) => "newValue", var t when t == typeof(ITaskItem) => new MockTaskItem() { ItemSpec = "NewSpec" }, _ => throw new NotImplementedException($"{parameters[i].ParameterType} is an unknown type. Update the test code to handle that.") }; string newKey = ((FrameworkListDefinition)constructor.Invoke(args)).CacheKey(); seenKeys.Should().NotContain(newKey); seenKeys.Add(newKey); } } [Fact] public static void StronglyTypedInputs_Includes_All_Inputs_In_CacheKey() { StronglyTypedInputs defaultObject = new( frameworkReferences: DefaultFrameworkReferences(), resolvedTargetingPacks: DefaultTargetingPacks(Path.GetTempPath()), runtimeFrameworks: new[] {new MockTaskItem("RuntimeFramework1", new Dictionary<string, string>()) }, generateErrorForMissingTargetingPacks: true, nuGetRestoreSupported: true, disableTransitiveFrameworkReferences: false, netCoreTargetingPackRoot: "netCoreTargetingPackRoot", projectLanguage: "C#"); List<string> seenKeys = new(); seenKeys.Add(defaultObject.CacheKey()); foreach (var permutation in Permutations(defaultObject)) { string newKey = permutation.Inputs.CacheKey(); seenKeys.Should().NotContain(newKey, because: $"The input {permutation.LastFieldChanged} should be included in the cache key"); seenKeys.Add(newKey); } static IEnumerable<(string LastFieldChanged, StronglyTypedInputs Inputs)> Permutations(StronglyTypedInputs input) { var properties = typeof(StronglyTypedInputs).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { if (property.PropertyType == typeof(FrameworkReference[])) { var currentValue = (FrameworkReference[])property.GetValue(input); foreach (var subfield in typeof(FrameworkReference).GetProperties()) { if (subfield.PropertyType == typeof(string)) { subfield.SetValue(currentValue[0], $"{subfield.Name}_changed"); yield return ($"{property.Name}.{subfield.Name}", input); continue; } Assert.True(false, $"update test to understand fields of type {subfield.PropertyType} in {nameof(FrameworkReference)}"); } } else if (property.PropertyType == typeof(TargetingPack[])) { var currentValue = (TargetingPack[])property.GetValue(input); foreach (var subproperty in typeof(TargetingPack).GetProperties()) { if (subproperty.PropertyType == typeof(string)) { subproperty.SetValue(currentValue[0], $"{subproperty.Name}_changed"); yield return ($"{property.Name}.{subproperty.Name}", input); continue; } Assert.True(false, $"update test to understand fields of type {subproperty.PropertyType} in {nameof(TargetingPack)}"); } } else if (property.PropertyType == typeof(RuntimeFramework[])) { var currentValue = (RuntimeFramework[])property.GetValue(input); foreach (var subproperty in typeof(RuntimeFramework).GetProperties()) { if (subproperty.PropertyType == typeof(string)) { subproperty.SetValue(currentValue[0], $"{subproperty.Name}_changed"); yield return ($"{property.Name}.{subproperty.Name}", input); continue; } if (subproperty.PropertyType == typeof(ITaskItem)) { // Used to store original items but not cache-relevant continue; } Assert.True(false, $"update test to understand fields of type {subproperty.PropertyType} in {nameof(RuntimeFramework)}"); } } else if (property.PropertyType == typeof(string)) { property.SetValue(input, $"{property.Name}_changed"); yield return (property.Name, input); } else if (property.PropertyType == typeof(bool)) { property.SetValue(input, !(bool)property.GetValue(input)); yield return (property.Name, input); } else { Assert.True(false, $"Unknown type {property.PropertyType} for field {property.Name}"); } } } } } }
46.751142
289
0.593349
[ "MIT" ]
Nirmal4G/sdk
src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/GivenAResolveTargetingPackAssetsTask.cs
20,479
C#
/* _BEGIN_TEMPLATE_ { "id": "ICC_829t4", "name": [ "检察官怀特迈恩", "Inquisitor Whitemane" ], "text": [ null, null ], "cardClass": "PALADIN", "type": "MINION", "cost": 2, "rarity": null, "set": "ICECROWN", "collectible": null, "dbfId": 45620 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_ICC_829t4 : SimTemplate { } }
13.851852
37
0.561497
[ "MIT" ]
chi-rei-den/Silverfish
cards/ICECROWN/ICC/Sim_ICC_829t4.cs
388
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 iot-2015-05-28.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.IoT.Model { /// <summary> /// This is the response object from the AttachSecurityProfile operation. /// </summary> public partial class AttachSecurityProfileResponse : AmazonWebServiceResponse { } }
29.657895
101
0.734694
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/AttachSecurityProfileResponse.cs
1,127
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using ZeroChaos.TimesheetPOC.IServices; using ZeroChaos.TimesheetPOC.Models.Request.Timesheet; using ZeroChaos.TimesheetPOC.Models.Response.Timesheet; using ZeroChaos.TimesheetPOC.Services; using ZeroChaos.TimesheetPOC.Views; using ZeroChaos.TimesheetPOC.Views.Timesheet; namespace ZeroChaos.TimesheetPOC.ViewModel.Timesheet { public class DetailTimesheetViewModel : BaseViewModel, INotifyPropertyChanged { IServiceCaller service; public event PropertyChangedEventHandler PropertyChanged; public int TimesheetID { get; set; } public TimesheetEntry TimeshetEntrySeleted { get; set; } public TimesheetDetailsResponse Tres { get; set; } public SaveOrSubmitTimesheetResponse SaveSubmitResponse { get; set; } public List<PayCodeInfoList> PayCodeInfoList { get; set; } public List<ProjectTrackCode> ProjectTrackCode { get; set; } public int SelectedManager { get; set; } private bool saveSubmitButtonVisibility = true; public bool SaveSubmitButtonVisibility { get { return saveSubmitButtonVisibility; } set { saveSubmitButtonVisibility = value; OnPropertyChanged(); } } private AddTimeSheet _AddTimesheetEntrySelected; public AddTimeSheet AddTimesheetEntrySelected { get { return _AddTimesheetEntrySelected ?? (_AddTimesheetEntrySelected=new AddTimeSheet()); } set { _AddTimesheetEntrySelected = value; } } public DetailTimesheetViewModel() { App.Current.Resources["DateColor"] = Color.FromHex("#3c9ece"); App.Current.Resources["PayCode"] = Color.FromHex("#c1eaf6"); App.Current.Resources["TrackCode"] = Color.FromHex("#c1eaf6"); } public async void GetDetail(Action<TimesheetDetailsResponse> Callback) { service = new Services.ServiceCaller(); await service.CallHostService<TimesheetDetailsRequest, TimesheetDetailsResponse>(new TimesheetDetailsRequest { loggedonUser = App.UserSession.LoggedonUser, timesheetID = TimesheetID }, "GetTimesheetDetailsRequest", (res) => { Tres = res; Callback(res); }); } public async void SaveSubmitTimesheet(int action, Action<SaveOrSubmitTimesheetResponse> callback) { service = new ServiceCaller(); var request = PrepareSaveOrSubmitTimesheetRequest(action); await service.CallHostService<SaveOrSubmitTimesheetRequest, SaveOrSubmitTimesheetResponse>(request, "SaveOrSubmitTimesheetRequest", (res) => { SaveSubmitResponse = res; callback(res); }); } public async void OpentheApproveManager() { service = new Services.ServiceCaller(); ApproveManager ap = new ApproveManager(); ap.BindingContext = this; await service.CallHostService<ApprovalManagersRequest, ApprovalManagerResponse>(new ApprovalManagersRequest { loggedonUser = App.UserSession.LoggedonUser, projectID = Tres.ProjectID }, "GetApprovalManagersRequest", res => { if(res.ResultSuccess) { ap.ItemSource = res.Managers; MasterDetailViewModel.Detail = ap; } else { MasterDetailViewModel.Detail.DisplayAlert("Error", res.ResultMessages.FirstOrDefault().Message, "ok"); } }); } public void LoadSelectionPage(string value) { IServiceCaller service = new Services.ServiceCaller(); switch (value) { case "Date": var request = new TimesheetEndingDatesRequest { projectID = Tres.ProjectID, loggedonUser = App.UserSession.LoggedonUser, timesheetEndingDate =Tres.EndDt.ToString()}; service.CallHostService<TimesheetEndingDatesRequest, TimesheetEndingDatesResponse>(request, "GetTimesheetEntryDatesRequest", (r) => { SingleItemSelectionPage page = new SingleItemSelectionPage(); page.SelectionPageCollection = r.timesheetEntryDates; page.Option = value; page.BindingContext = this; MasterDetailViewModel.Detail = page; }); break; case "Paycode": var req = new TimesheetPayCodeRequest { timesheetTypeID = Tres.TimesheetTypeID.Value, projectID = Tres.ProjectID, loggedonUser = App.UserSession.LoggedonUser, timesheetEndingDate = Tres.EndDt.ToString() }; service.CallHostService<TimesheetPayCodeRequest, TimesheetPayCodeResponse>(req, "GetPayCodesRequest", (r) => { PayCodeInfoList = r.payCodeInfoList; SingleItemSelectionPage page = new SingleItemSelectionPage(); page.BindingContext = this; page.Option = value; page.SelectionPageCollection = r.payCodeInfoList.Select(p=>p.payCodeName).ToList(); MasterDetailViewModel.Detail = page; }); break; case "Trackcode": ProjectTrackCodesRequest trackReq = new ProjectTrackCodesRequest(); trackReq.ProjectID = Tres.ProjectID; trackReq.TimesheetEndingDate = Tres.EndDt; trackReq.TimesheetID = Tres.TimesheetID; trackReq.Offset = 0; trackReq.PageSize = 10; trackReq.loggedonUser = App.UserSession.LoggedonUser; service.CallHostService<ProjectTrackCodesRequest, ProjectTrackCodeResponse>(trackReq, "GetProjectTrackCodesRequest", (r) => { ProjectTrackCode = r.ProjectTrackCodes.ToList(); SingleItemSelectionPage page = new SingleItemSelectionPage(); page.BindingContext = this; page.Option = value; page.SelectionPageCollection = r.ProjectTrackCodes.Select(p => p.TrackCodeName).ToList(); MasterDetailViewModel.Detail = page; }); break; default: break; } } public void OpenAddEntryPage() { AddTimesheetEntryDetailPage ad = new AddTimesheetEntryDetailPage(); MasterDetailViewModel.Header="Timesheet Entry"; MasterDetailViewModel.RightButton=""; ad.BindingContext = this; MasterDetailViewModel.Detail = ad; ad.OnAppearing(); } void OnPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private SaveOrSubmitTimesheetRequest PrepareSaveOrSubmitTimesheetRequest(int action) { var request = new SaveOrSubmitTimesheetRequest { PrimaryApprovalManagerID = (SelectedManager != 0 ? SelectedManager : Tres.ApprovalManagerId), ActionTypeID = action, EndDate = Tres.EndDt, ProjectID = Tres.ProjectID, ResourceID = Tres.ResourceID, TimesheetID = Tres.TimesheetID, timesheetEntries = Tres.TimeSheetEntryList, loggedonUser = App.UserSession.LoggedonUser }; return request; } } public class AddTimeSheet { public string SelectedEntryDate { get; set; } public string SelectedPaycode { get; set; } public string TrackCode { get; set; } public int Units { get; set; } } }
40.086124
235
0.596324
[ "MIT" ]
Dhaval8087/TimesheetPOCNew
ZeroChaos.TimesheetPOC/ZeroChaos.TimesheetPOC/ViewModel/Timesheet/DetailTimesheetViewModel.cs
8,380
C#
/////////////////////////////////////////////////////////////// // This is generated code. ////////////////////////////////////////////////////////////// // Code is generated using LLBLGen Pro version: 4.2 // Code is generated using templates: SD.TemplateBindings.SharedTemplates // Templates vendor: Solutions Design. // Templates version: ////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Collections.Generic; using NinjaSoftware.EnioNg.CoolJ; using NinjaSoftware.EnioNg.CoolJ.FactoryClasses; using NinjaSoftware.EnioNg.CoolJ.HelperClasses; using SD.LLBLGen.Pro.ORMSupportClasses; namespace NinjaSoftware.EnioNg.CoolJ.RelationClasses { /// <summary>Implements the relations factory for the entity: EntityRo. </summary> public partial class EntityRoRelations { /// <summary>CTor</summary> public EntityRoRelations() { } /// <summary>Gets all relations of the EntityRoEntity as a list of IEntityRelation objects.</summary> /// <returns>a list of IEntityRelation objects</returns> public virtual List<IEntityRelation> GetAllRelations() { List<IEntityRelation> toReturn = new List<IEntityRelation>(); toReturn.Add(this.AuditInfoEntityUsingEntityId); return toReturn; } #region Class Property Declarations /// <summary>Returns a new IEntityRelation object, between EntityRoEntity and AuditInfoEntity over the 1:n relation they have, using the relation between the fields: /// EntityRo.EntityId - AuditInfo.EntityId /// </summary> public virtual IEntityRelation AuditInfoEntityUsingEntityId { get { IEntityRelation relation = new EntityRelation(SD.LLBLGen.Pro.ORMSupportClasses.RelationType.OneToMany, "AuditInfoCollection" , true); relation.AddEntityFieldPair(EntityRoFields.EntityId, AuditInfoFields.EntityId); relation.InheritanceInfoPkSideEntity = InheritanceInfoProviderSingleton.GetInstance().GetInheritanceInfo("EntityRoEntity", true); relation.InheritanceInfoFkSideEntity = InheritanceInfoProviderSingleton.GetInstance().GetInheritanceInfo("AuditInfoEntity", false); return relation; } } /// <summary>stub, not used in this entity, only for TargetPerEntity entities.</summary> public virtual IEntityRelation GetSubTypeRelation(string subTypeEntityName) { return null; } /// <summary>stub, not used in this entity, only for TargetPerEntity entities.</summary> public virtual IEntityRelation GetSuperTypeRelation() { return null;} #endregion #region Included Code #endregion } /// <summary>Static class which is used for providing relationship instances which are re-used internally for syncing</summary> internal static class StaticEntityRoRelations { internal static readonly IEntityRelation AuditInfoEntityUsingEntityIdStatic = new EntityRoRelations().AuditInfoEntityUsingEntityId; /// <summary>CTor</summary> static StaticEntityRoRelations() { } } }
38.657895
167
0.73179
[ "Apache-2.0" ]
malininja/NinjaSoftware.EnioNg
CoolJ/DatabaseGeneric/RelationClasses/EntityRoRelations.cs
2,940
C#
using System; using FubuCore.Conversion; using NUnit.Framework; namespace FubuCore.Testing.Conversion { [TestFixture] public class TimeSpanConverterTester { [Test] public void happily_converts_timespans_in_4_digit_format() { TimeSpanConverter.GetTimeSpan("1230").ShouldEqual(new TimeSpan(12, 30, 0)); } [Test] public void happily_converts_timespans_in_5_digit_format() { TimeSpanConverter.GetTimeSpan("12:30").ShouldEqual(new TimeSpan(12, 30, 0)); } } }
26.363636
89
0.631034
[ "Apache-2.0" ]
DovetailSoftware/fubucore
src/FubuCore.Testing/Conversion/TimeSpanConverterTester.cs
580
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; using eIVOGo.Helper; using Uxnet.Web.WebUI; using Utility; using Model.Security.MembershipManagement; using Business.Helper; using Model.DataEntity; namespace eIVOGo.Module.EIVO.RelativeBuyer { public partial class ReceiveInvoice : System.Web.UI.UserControl { private int[] _invoiceID; private UserProfileMember _userProfile; protected void Page_Load(object sender, EventArgs e) { var items = Request.GetItemSelection(); if (items != null && items.Count() > 0) { _invoiceID = items.Select(s => int.Parse(s)).ToArray(); } _userProfile = WebPageUtility.UserProfile; } protected override void OnInit(EventArgs e) { base.OnInit(e); inquiryAction.Done += new EventHandler(inquiryAction_Done); inquiryAction.afterQuery += new EventHandler(inquiryAction_afterQuery); signContext.BeforeSign += new EventHandler(signContext_BeforeSign); signContext.Launcher = btnReceive; } void inquiryAction_afterQuery(object sender, EventArgs e) { if (inquiryAction.dataCount > 0) { tblAction.Visible = true; } else { tblAction.Visible = false; } } void signContext_BeforeSign(object sender, EventArgs e) { if (_invoiceID != null && _invoiceID.Count() > 0) { //var invoices = dsEntity.CreateDataManager().EntityList.Where(i => _invoiceID.Contains(i.InvoiceID)); var ds=dsEntity.CreateDataManager(); StringBuilder sb = new StringBuilder(); if (inquiryAction.isInvoice) { var invoices = ds.GetTable<CDS_Document>().Where(i => _invoiceID.Contains(i.InvoiceItem.InvoiceID)); sb.Append("您欲接收的資料如下\r\n"); sb.Append("接收營業人ID:").Append(_userProfile.UID).Append("\r\n"); sb.Append("接收營業人名稱:").Append(_userProfile.UserName).Append("\r\n"); sb.Append("接收時間:").Append(DateTime.Now.ToString()).Append("\r\n"); sb.Append("發票號碼\t\t發票日期\t\t發票接收人\r\n"); foreach (var invoice in invoices) { sb.Append(invoice.InvoiceItem.TrackCode).Append(invoice.InvoiceItem.No).Append("\t") .Append(ValueValidity.ConvertChineseDateString(invoice.InvoiceItem.InvoiceDate.Value)).Append("\t") .Append(invoice.InvoiceItem.InvoiceBuyer.Organization.CompanyName).Append("\r\n"); } } else { var invoices = ds.GetTable<CDS_Document>().Where(i => _invoiceID.Contains(i.InvoiceAllowance.AllowanceID)); sb.Append("您欲開立的資料如下\r\n"); sb.Append("開立營業人ID:").Append(_userProfile.UID).Append("\r\n"); sb.Append("開立營業人名稱:").Append(_userProfile.UserName).Append("\r\n"); sb.Append("開立時間:").Append(DateTime.Now.ToString()).Append("\r\n"); sb.Append("折讓號碼\t\t折讓日期\t\t折讓開立人\r\n"); foreach (var invoice in invoices) { sb.Append(invoice.InvoiceAllowance.AllowanceNumber).Append("\t") .Append(ValueValidity.ConvertChineseDateString(invoice.InvoiceAllowance.AllowanceDate.Value)).Append("\t") .Append(invoice.InvoiceAllowance.InvoiceAllowanceSeller.Organization.CompanyName).Append("\r\n"); } } signContext.DataToSign = sb.ToString(); } } void inquiryAction_Done(object sender, EventArgs e) { if (inquiryAction.DoQuery) { //tblAction.Visible = true; if (inquiryAction.isInvoice) this.btnReceive.Text = "接收"; else this.btnReceive.Text = "開立"; } else { tblAction.Visible = false; } } protected void btnReceive_Click(object sender, EventArgs e) { if (_invoiceID != null && _invoiceID.Count() > 0) { if (signContext.Verify() && _userProfile.CheckTokenIdentity(dsEntity.CreateDataManager(), signContext)) { doReceive(); this.AjaxAlert("接收/開立完成!!"); } else { this.AjaxAlert("簽章失敗!!"); } } else { this.AjaxAlert("請選擇項目!!"); } } private void doReceive() { var mgr = dsEntity.CreateDataManager(); //var items = mgr.EntityList.Where(i => _invoiceID.Contains(i.InvoiceID)); if (inquiryAction.isInvoice) { var cds = mgr.GetTable<CDS_Document>().Where(i => _invoiceID.Contains(i.InvoiceItem.InvoiceID)); foreach (var item in cds) { //_userProfile.ReceiveInvoiceItem(mgr, item); item.MoveToNextStep(mgr); } } else { var cds = mgr.GetTable<CDS_Document>().Where(i => _invoiceID.Contains(i.InvoiceAllowance.AllowanceID)); foreach (var item in cds) { //_userProfile.ReceiveInvoiceItem(mgr, item); item.MoveToNextStep(mgr); } } } } }
37.161491
134
0.519639
[ "MIT" ]
uxb2bralph/IFS-EIVO03
eIVOGo/Module/EIVO/RelativeBuyer/ReceiveInvoice.ascx.cs
6,175
C#
namespace EmployeesManagement.Services.Interfaces { using EmployeesManagement.Common.BindingModels; using EmployeesManagement.Common.ViewModels; using EmployeesManagement.Models; using System.Collections.Generic; using System.Threading.Tasks; public interface IEmployeesSecrvice { Task<Employee> AddEmployeeAsync(EmployeeCreationBindingModel model); Task<IEnumerable<EmployeeConciseViewModel>> GetAllEmployeesAsync(int companyId); Task<EmployeeDetailsViewModel> GetEmployeeDetailsAsync(int id); Task<EmployeeEditBindingModel> GetEmployeeEditAsync(int id); Task<Employee> EditEmployeeAsync(EmployeeEditBindingModel model); Task DeleteEmployee(int id); } }
30.916667
88
0.765499
[ "Apache-2.0" ]
svetliub/Employee-Management
EmployeesManagement.Services/Interfaces/IEmployeesSecrvice.cs
744
C#
using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media; namespace ConfuserEx { public class BrushToColorConverter : IValueConverter { public static readonly BrushToColorConverter Instance = new BrushToColorConverter(); BrushToColorConverter() { } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var brush = value as SolidColorBrush; if (brush != null) return brush.Color; return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
26.08
99
0.760736
[ "MIT" ]
Deltafox79/ConfuserEx
ConfuserEx/BrushToColorConverter.cs
654
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("f617610f-9ef7-4bea-be86-81e8bdfaa6a4")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
28.486486
57
0.739089
[ "MIT" ]
stackprobe/HTT
WHTT/WHTT/Properties/AssemblyInfo.cs
1,578
C#
using System; using System.Collections.Generic; using System.Text; using DotNetCore_BeehooeServer.Infrastructure.Jwt; using DotNetCore_BeehooeServer.Model.Authentication; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DotNetCore_BeehooeServer.Test { [TestClass] public class JwtTest { [TestMethod] public void GenerateToken() { var token= new JwtManager().GenerateToken(new JwtClaimModel() {RoleId = "TheRoleID", RoleName = "TheRoleName"}); } } }
26.2
124
0.717557
[ "Apache-2.0" ]
shunchuan/DotNetCore_BeehooeServer
DotNetCore_BeehooeServer.Test/JwtTest.cs
526
C#
using UnityEngine; namespace Phantom { [RequireComponent(typeof(Kvant.SprayMV))] public class SprayController : MonoBehaviour { [SerializeField] Transform _target; [SerializeField, Range(0, 2)] float _applyVelocity; Kvant.SprayMV _spray; void Start() { _spray = GetComponent<Kvant.SprayMV>(); } void Update() { var delta = _target.position - _spray.emitterCenter; _spray.emitterCenter = _target.position; if (_applyVelocity > 0) _spray.initialVelocity = delta * (_applyVelocity / Time.deltaTime); } } }
20.558824
64
0.555079
[ "MIT" ]
gomez-addams/Phantom
Assets/Phantom/Script/SprayController.cs
699
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("晨曦小竹常用工具集")] [assembly: AssemblyDescription("本产品由“蟑螂·魂”在长期的开发实践工作奋战中,或创作、或摘抄、或优化、或改善、或封装、或集成、或切面等等综合而成,如有雷同,纯属他人抄袭(^_^),不然就是我在抄袭(>_<);本产品经过了精心的优化改良,同时还进行了适当的完善处理,对所有归集的成品进行了分门别类放置,以供不同场景的便利使用;本产品涵盖之广,运用之丰,可以满足大、中、小等项目的自由支配使用,方便快捷、合理舒心,在使用的过程中还请注重作者劳动成果,保留必要的注释或文字标识,谢谢。")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("晨曦小竹企业集团有限公司")] [assembly: AssemblyProduct("数据分页展示工具集")] [assembly: AssemblyCopyright("Copyright © DawnXZ.com 2014")] [assembly: AssemblyTrademark("DawnXZ")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("16219d7c-55ad-404d-ba1c-654b4ffea50d")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")]
32.297297
259
0.743096
[ "MIT" ]
cockroach888/DawnTools
DawnXZ.PagerUtility20/Properties/AssemblyInfo.cs
2,049
C#
/* Copyright (c) 2018, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.Collections; using System.Linq; using MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.VectorMath; namespace MatterHackers.MatterControl.CustomWidgets { public class TreeView : ScrollableWidget { protected ThemeConfig theme; public TreeView(ThemeConfig theme) : this(0, 0, theme) { } public TreeView(int width, int height, ThemeConfig theme) : base(width, height) { this.theme = theme; this.AutoScroll = true; this.HAnchor = HAnchor.Stretch; this.VAnchor = VAnchor.Stretch; } #region Events public event EventHandler AfterCheck; public event EventHandler AfterCollapse; public event EventHandler AfterExpand; public event EventHandler AfterLabelEdit; public event EventHandler<TreeNode> AfterSelect; public event EventHandler BeforeCheck; internal void NotifyItemClicked(GuiWidget sourceWidget, MouseEventArgs e) { this.NodeMouseClick?.Invoke(sourceWidget, e); } internal void NotifyItemDoubleClicked(GuiWidget sourceWidget, MouseEventArgs e) { this.NodeMouseDoubleClick?.Invoke(sourceWidget, e); } public event EventHandler BeforeCollapse; public event EventHandler BeforeExpand; public event EventHandler BeforeLabelEdit; public event EventHandler<TreeNode> BeforeSelect; public event EventHandler NodeMouseClick; public event EventHandler NodeMouseDoubleClick; public event EventHandler NodeMouseHover; #endregion Events #region Properties // Summary: // Gets or sets a value indicating whether check boxes are displayed next to the // tree nodes in the tree view control. // // Returns: // true if a check box is displayed next to each tree node in the tree view control; // otherwise, false. The default is false. public bool CheckBoxes { get; set; } // Summary: // Gets or sets a value indicating whether the selection highlight spans the width // of the tree view control. // // Returns: // true if the selection highlight spans the width of the tree view control; otherwise, // false. The default is false. public bool FullRowSelect { get; set; } // Summary: // Gets or sets a value indicating whether the selected tree node remains highlighted // even when the tree view has lost the focus. // // Returns: // true if the selected tree node is not highlighted when the tree view has lost // the focus; otherwise, false. The default is true. public bool HideSelection { get; set; } // Summary: // Gets or sets the distance to indent each child tree node level. // // Returns: // The distance, in pixels, to indent each child tree node level. The default value // is 19. // // Exceptions: // T:System.ArgumentOutOfRangeException: // The assigned value is less than 0 (see Remarks).-or- The assigned value is greater // than 32,000. public int Indent { get; set; } // Summary: // Gets or sets the height of each tree node in the tree view control. // // Returns: // The height, in pixels, of each tree node in the tree view. // // Exceptions: // T:System.ArgumentOutOfRangeException: // The assigned value is less than one.-or- The assigned value is greater than the // System.Int16.MaxValue value. public int ItemHeight { get; set; } // Summary: // Gets or sets a value indicating whether the label text of the tree nodes can // be edited. // // Returns: // true if the label text of the tree nodes can be edited; otherwise, false. The // default is false. public bool LabelEdit { get; set; } // Summary: // Gets or sets the color of the lines connecting the nodes of the TreeView // control. // // Returns: // The System.Drawing.Color of the lines connecting the tree nodes. public Color LineColor { get; set; } // Summary: // Gets or sets the delimiter string that the tree node path uses. // // Returns: // The delimiter string that the tree node TreeNode.FullPath // property uses. The default is the backslash character (\). public string PathSeparator { get; set; } public Color TextColor { get; set; } = Color.Black; public double PointSize { get; set; } = 12; // Summary: // Gets or sets a value indicating whether the tree view control displays scroll // bars when they are needed. // // Returns: // true if the tree view control displays scroll bars when they are needed; otherwise, // false. The default is true. public bool Scrollable { get; set; } // Summary: // Gets or sets the tree node that is currently selected in the tree view control. // // Returns: // The TreeNode that is currently selected in the tree view // control. private TreeNode _selectedNode; public void Clear() { this.ScrollArea.CloseChildren(); // Release held reference _selectedNode = null; } public override void OnKeyDown(KeyEventArgs keyEvent) { if (!keyEvent.Handled) { switch (keyEvent.KeyCode) { case Keys.Up: var prev = PreviousVisibleTreeNode(SelectedNode); if (prev != null) { SelectedNode = prev; keyEvent.Handled = true; prev.TreeView.NotifyItemClicked(prev.TreeView, new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0)); } break; case Keys.Down: var next = NextVisibleTreeNode(SelectedNode); if (next != null) { SelectedNode = next; keyEvent.Handled = true; next.TreeView.NotifyItemClicked(next.TreeView, new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0)); } break; } } base.OnKeyDown(keyEvent); } private TreeNode NextVisibleTreeNode(TreeNode treeNode) { var nodes = this.Descendants<TreeNode>((child) => child.Visible).ToList(); var selectedIndex = nodes.IndexOf(SelectedNode); if (selectedIndex < nodes.Count - 1) { return nodes[selectedIndex + 1]; } return null; } private TreeNode PreviousVisibleTreeNode(TreeNode treeNode) { var nodes = this.Descendants<TreeNode>((child) => child.Visible).ToList(); var selectedIndex = nodes.IndexOf(SelectedNode); if (selectedIndex > 0) { return nodes[selectedIndex - 1]; } return null; } public TreeNode SelectedNode { get => _selectedNode; set { if (value != _selectedNode) { OnBeforeSelect(null); var hadFocus = false; // if the current selection (before change) is !null than clear its background color if (_selectedNode != null) { hadFocus = _selectedNode.ContainsFocus; _selectedNode.HighlightRegion.BackgroundColor = Color.Transparent; } // change the selection _selectedNode = value; if (_selectedNode != null) { // Ensure tree is expanded, walk backwards to the root, reverse, expand back to this node foreach (var ancestor in _selectedNode.Ancestors().Reverse()) { ancestor.Expanded = true; } } if (_selectedNode != null) { _selectedNode.HighlightRegion.BackgroundColor = theme.AccentMimimalOverlay; } this.ScrollIntoView(_selectedNode);//, ScrollAmount.Minimum); if (hadFocus) { _selectedNode?.Focus(); } OnAfterSelect(null); } } } public bool ShowLines { get; set; } public bool ShowNodeToolTips { get; set; } public bool ShowPlusMinus { get; set; } public bool ShowRootLines { get; set; } public bool Sorted { get; set; } public IComparer TreeViewNodeSorter { get; set; } // Summary: // Gets the number of tree nodes that can be fully visible in the tree view control. // // Returns: // The number of TreeNode items that can be fully visible in // the TreeView control. public int VisibleCount { get; } #endregion Properties // Summary: // Disables any redrawing of the tree view. public void BeginUpdate() { throw new NotImplementedException(); } // Summary: // Collapses all the tree nodes. public void CollapseAll() { throw new NotImplementedException(); } // Summary: // Enables the redrawing of the tree view. public void EndUpdate() { throw new NotImplementedException(); } // Summary: // Expands all the tree nodes. public void ExpandAll() { throw new NotImplementedException(); } // Summary: // Retrieves the tree node that is at the specified point. // // Parameters: // pt: // The System.Drawing.Point to evaluate and retrieve the node from. // // Returns: // The TreeNode at the specified point, in tree view (client) // coordinates, or null if there is no node at that location. public TreeNode GetNodeAt(Vector2 pt) { throw new NotImplementedException(); } /// <summary> /// Retrieves the number of tree nodes, optionally including those in all subtrees, /// assigned to the tree view control. /// </summary> /// <param name="includeSubTrees">true to count the TreeNode items that the subtrees contain; /// otherwise, false.</param> /// <returns>The number of tree nodes, optionally including those in all subtrees, assigned /// to the tree view control.</returns> public int GetNodeCount(bool includeSubTrees) { throw new NotImplementedException(); } public void Sort() { throw new NotImplementedException(); } protected internal virtual void OnAfterCollapse(EventArgs e) { throw new NotImplementedException(); } protected internal virtual void OnBeforeCollapse(EventArgs e) { throw new NotImplementedException(); } protected virtual void OnAfterCheck(EventArgs e) { throw new NotImplementedException(); } protected virtual void OnAfterExpand(EventArgs e) { throw new NotImplementedException(); } protected virtual void OnAfterLabelEdit(EventArgs e) { throw new NotImplementedException(); } protected virtual void OnAfterSelect(TreeNode e) { AfterSelect?.Invoke(this, e); } protected virtual void OnBeforeCheck(EventArgs e) { throw new NotImplementedException(); } protected virtual void OnBeforeExpand(EventArgs e) { throw new NotImplementedException(); } protected virtual void OnBeforeLabelEdit(EventArgs e) { throw new NotImplementedException(); } protected virtual void OnBeforeSelect(TreeNode e) { BeforeSelect?.Invoke(this, e); } protected virtual void OnNodeMouseClick(EventArgs e) { throw new NotImplementedException(); } protected virtual void OnNodeMouseDoubleClick(EventArgs e) { throw new NotImplementedException(); } } }
26.964835
105
0.694026
[ "BSD-2-Clause" ]
Bhalddin/MatterControl
MatterControlLib/CustomWidgets/TreeView/TreeView.cs
12,271
C#
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1649:File name must match first type name", Justification = "Pre-existing condition")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1652:Enable XML documentation output", Justification = "Pre-existing condition")]
88.285714
186
0.800971
[ "MIT" ]
KaixunYao/ApplicationInsights-dotnet-server
Src/Web/Web.Nuget.Tests/GlobalSuppressions.cs
620
C#
using System; using System.Text.RegularExpressions; namespace MooGet { /// <summary>Represents the name of a version of the .NET framework, eg. .NET 1.1 or Silverlight 4.0</summary> public class FrameworkName { public static string DefaultName = ".NETFramework"; public static string SilverlightName = "Silverlight"; public FrameworkName() {} public FrameworkName(string name, string version) { _name = name; _version = version; } string _name; string _version; public string Name { get { if (_name == null) return DefaultName; var name = _name.ToLower().Replace(" ", "").Replace(".", ""); if (name.Length == 0 || name.Contains("net")) return DefaultName; if (name.Contains("sl") || name.Contains("silverlight")) return SilverlightName; throw new Exception("Unknown FrameworkName Name: " + _name); } } public string Version { get { var version = _version.ToLower().Replace(" ", "").Replace(".", ""); switch (version.Length) { case 1: return version + ".0"; break; case 2: return version.Substring(0,1) + "." + version.Substring(1); break; default: throw new Exception("Unknown FrameworkName Version: " + _version); } } } public string FullName { get { return string.Format("{0} {1}", Name, Version); } } public static FrameworkName Parse(string name) { var match = Regex.Match(name.Replace(".", "").Replace(" ", "").ToLower(), @"^([a-z]*)([0-9]*)$"); return new FrameworkName(match.Groups[1].Value, match.Groups[2].Value); } public override string ToString() { return FullName; } public static bool operator != (FrameworkName a, FrameworkName b) { return (a == b) == false; } public static bool operator == (FrameworkName a, FrameworkName b) { if ((object) b == null) return ((object) a == null); else return a.Equals(b); } public override bool Equals(object o) { if (o == null || o.GetType() != GetType()) return false; return (o as FrameworkName).FullName == FullName; } } }
28.133333
111
0.620379
[ "MIT" ]
beccasaurus/mooget
src/misc/FrameworkName.cs
2,110
C#
// <copyright file="MatrixTests.Arithmetic.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-2016 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 MathNet.Numerics.Distributions; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Single; using NUnit.Framework; namespace MathNet.Numerics.Tests.LinearAlgebraTests.Single { /// <summary> /// Abstract class with the common set of matrix tests /// </summary> public abstract partial class MatrixTests { /// <summary> /// Can multiply with a scalar. /// </summary> /// <param name="scalar">Scalar value.</param> [TestCase(0)] [TestCase(1)] [TestCase(2.2f)] public void CanMultiplyWithScalar(float scalar) { var matrix = TestMatrices["Singular3x3"]; var clone = matrix.Clone(); clone = clone.Multiply(scalar); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrix[i, j] * scalar, clone[i, j]); } } } /// <summary> /// Can multiply with a vector. /// </summary> [Test] public void CanMultiplyWithVector() { var matrix = TestMatrices["Singular3x3"]; var x = new DenseVector(new[] { 1.0f, 2.0f, 3.0f }); var y = matrix * x; Assert.AreEqual(matrix.RowCount, y.Count); for (var i = 0; i < matrix.RowCount; i++) { var ar = matrix.Row(i); var dot = ar * x; Assert.AreEqual(dot, y[i]); } } /// <summary> /// Can multiply with a vector into a result. /// </summary> [Test] public void CanMultiplyWithVectorIntoResult() { var matrix = TestMatrices["Singular3x3"]; var x = new DenseVector(new[] { 1.0f, 2.0f, 3.0f }); var y = new DenseVector(3); matrix.Multiply(x, y); for (var i = 0; i < matrix.RowCount; i++) { var ar = matrix.Row(i); var dot = ar * x; Assert.AreEqual(dot, y[i]); } } /// <summary> /// Can multiply with a vector into result when updating input argument. /// </summary> [Test] public void CanMultiplyWithVectorIntoResultWhenUpdatingInputArgument() { var matrix = TestMatrices["Singular3x3"]; var x = new DenseVector(new[] { 1.0f, 2.0f, 3.0f }); var y = x; matrix.Multiply(x, x); Assert.AreSame(y, x); y = new DenseVector(new[] { 1.0f, 2.0f, 3.0f }); for (var i = 0; i < matrix.RowCount; i++) { var ar = matrix.Row(i); var dot = ar * y; Assert.AreEqual(dot, x[i]); } } /// <summary> /// Multiply with a vector into too large result throws <c>ArgumentException</c>. /// </summary> [Test] public void MultiplyWithVectorIntoLargerResultThrowsArgumentException() { var matrix = TestMatrices["Singular3x3"]; var x = new DenseVector(new[] { 1.0f, 2.0f, 3.0f }); Vector<float> y = new DenseVector(4); Assert.That(() => matrix.Multiply(x, y), Throws.ArgumentException); } /// <summary> /// Can left multiply with a scalar. /// </summary> /// <param name="scalar">Scalar value.</param> [TestCase(0)] [TestCase(1)] [TestCase(2.2f)] public void CanOperatorLeftMultiplyWithScalar(float scalar) { var matrix = TestMatrices["Singular3x3"]; var clone = scalar * matrix; for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(scalar * matrix[i, j], clone[i, j]); } } } /// <summary> /// Can right multiply with a scalar. /// </summary> /// <param name="scalar">Scalar value.</param> [TestCase(0)] [TestCase(1)] [TestCase(2.2f)] public void CanOperatorRightMultiplyWithScalar(float scalar) { var matrix = TestMatrices["Singular3x3"]; var clone = matrix * scalar; for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrix[i, j] * scalar, clone[i, j]); } } } /// <summary> /// Can multiply with a scalar into result. /// </summary> /// <param name="scalar">Scalar value.</param> [TestCase(0)] [TestCase(1)] [TestCase(2.2f)] public void CanMultiplyWithScalarIntoResult(float scalar) { var matrix = TestMatrices["Singular3x3"]; var result = matrix.Clone(); matrix.Multiply(scalar, result); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrix[i, j] * scalar, result[i, j]); } } } /// <summary> /// Multiply with a scalar when result has more rows throws <c>ArgumentException</c>. /// </summary> [Test] public void MultiplyWithScalarWhenResultHasMoreRowsThrowsArgumentException() { var matrix = TestMatrices["Singular3x3"]; var result = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount); Assert.That(() => matrix.Multiply(2.3f, result), Throws.ArgumentException); } /// <summary> /// Multiply with a scalar when result has more columns throws <c>ArgumentException</c>. /// </summary> [Test] public void MultiplyWithScalarWhenResultHasMoreColumnsThrowsArgumentException() { var matrix = TestMatrices["Singular3x3"]; var result = CreateMatrix(matrix.RowCount, matrix.ColumnCount + 1); Assert.That(() => matrix.Multiply(2.3f, result), Throws.ArgumentException); } /// <summary> /// Can add a matrix. /// </summary> /// <param name="mtxA">Matrix A name.</param> /// <param name="mtxB">Matrix B name.</param> [TestCase("Singular3x3", "Square3x3")] [TestCase("Singular4x4", "Square4x4")] public void CanAddMatrix(string mtxA, string mtxB) { var matrixA = TestMatrices[mtxA]; var matrixB = TestMatrices[mtxB]; var matrix = matrixA.Clone(); matrix = matrix.Add(matrixB); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrix[i, j], matrixA[i, j] + matrixB[i, j]); } } } /// <summary> /// Can add a matrix. /// </summary> /// <param name="mtx">Matrix name.</param> [TestCase("Square3x3")] [TestCase("Tall3x2")] public void CanAddMatrixToSelf(string mtx) { var matrix = TestMatrices[mtx].Clone(); var result = matrix.Add(matrix); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(result[i, j], 2*matrix[i, j]); } } } /// <summary> /// Can subtract a matrix. /// </summary> /// <param name="mtx">Matrix name.</param> [TestCase("Square3x3")] [TestCase("Tall3x2")] public void CanSubtractMatrixFromSelf(string mtx) { var matrix = TestMatrices[mtx].Clone(); var result = matrix.Subtract(matrix); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(result[i, j], 0f); } } } /// <summary> /// Adding a matrix with fewer columns throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void AddMatrixWithFewerColumnsThrowsArgumentOutOfRangeException() { var matrix = TestMatrices["Singular3x3"]; var other = TestMatrices["Tall3x2"]; Assert.That(() => matrix.Add(other), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Adding a matrix with fewer rows throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void AddMatrixWithFewerRowsThrowsArgumentOutOfRangeException() { var matrix = TestMatrices["Singular3x3"]; var other = TestMatrices["Wide2x3"]; Assert.That(() => matrix.Add(other), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Add matrices using "+" operator. /// </summary> /// <param name="mtxA">Matrix A name.</param> /// <param name="mtxB">Matrix B name.</param> [TestCase("Singular3x3", "Square3x3")] [TestCase("Singular4x4", "Square4x4")] public void CanAddUsingOperator(string mtxA, string mtxB) { var matrixA = TestMatrices[mtxA]; var matrixB = TestMatrices[mtxB]; var result = matrixA + matrixB; for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(result[i, j], matrixA[i, j] + matrixB[i, j]); } } } /// <summary> /// Add operator when right side has fewer columns throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void AddOperatorWhenRightSideHasFewerColumnsThrowsArgumentOutOfRangeException() { var matrix = TestMatrices["Singular3x3"]; var other = TestMatrices["Tall3x2"]; Assert.Throws<ArgumentOutOfRangeException>(() => { var result = matrix + other; }); } /// <summary> /// Add operator when right side has fewer rows throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void AddOperatorWhenRightSideHasFewerRowsThrowsArgumentOutOfRangeException() { var matrix = TestMatrices["Singular3x3"]; var other = TestMatrices["Wide2x3"]; Assert.Throws<ArgumentOutOfRangeException>(() => { var result = matrix + other; }); } /// <summary> /// Can subtract a matrix. /// </summary> /// <param name="mtxA">Matrix A name.</param> /// <param name="mtxB">Matrix B name.</param> [TestCase("Singular3x3", "Square3x3")] [TestCase("Singular4x4", "Square4x4")] public void CanSubtractMatrix(string mtxA, string mtxB) { var matrixA = TestMatrices[mtxA]; var matrixB = TestMatrices[mtxB]; var matrix = matrixA.Clone(); matrix = matrix.Subtract(matrixB); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrix[i, j], matrixA[i, j] - matrixB[i, j]); } } } /// <summary> /// Subtract a matrix when right side has fewer columns throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void SubtractMatrixWithFewerColumnsThrowsArgumentOutOfRangeException() { var matrix = TestMatrices["Singular3x3"]; var other = TestMatrices["Tall3x2"]; Assert.That(() => matrix.Subtract(other), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Subtract a matrix when right side has fewer rows throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void SubtractMatrixWithFewerRowsThrowsArgumentOutOfRangeException() { var matrix = TestMatrices["Singular3x3"]; var other = TestMatrices["Wide2x3"]; Assert.That(() => matrix.Subtract(other), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can subtract a matrix using "-" operator. /// </summary> /// <param name="mtxA">Matrix A name.</param> /// <param name="mtxB">Matrix B name.</param> [TestCase("Singular3x3", "Square3x3")] [TestCase("Singular4x4", "Square4x4")] public void CanSubtractUsingOperator(string mtxA, string mtxB) { var matrixA = TestMatrices[mtxA]; var matrixB = TestMatrices[mtxB]; var result = matrixA - matrixB; for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(result[i, j], matrixA[i, j] - matrixB[i, j]); } } } /// <summary> /// Subtract operator when right side has fewer columns throws <c>ArgumentOutOfRangeException</c> /// </summary> [Test] public void SubtractOperatorWhenRightSideHasFewerColumnsThrowsArgumentOutOfRangeException() { var matrix = TestMatrices["Singular3x3"]; var other = TestMatrices["Tall3x2"]; Assert.Throws<ArgumentOutOfRangeException>(() => { var result = matrix - other; }); } /// <summary> /// Subtract operator when right side has fewer rows throws <c>ArgumentOutOfRangeException</c> /// </summary> [Test] public void SubtractOperatorWhenRightSideHasFewerRowsThrowsArgumentOutOfRangeException() { var matrix = TestMatrices["Singular3x3"]; var other = TestMatrices["Wide2x3"]; Assert.Throws<ArgumentOutOfRangeException>(() => { var result = matrix - other; }); } /// <summary> /// Can multiply a matrix with matrix. /// </summary> /// <param name="nameA">Matrix A name.</param> /// <param name="nameB">Matrix B name.</param> [TestCase("Singular3x3", "Square3x3")] [TestCase("Singular4x4", "Square4x4")] [TestCase("Wide2x3", "Square3x3")] [TestCase("Wide2x3", "Tall3x2")] [TestCase("Tall3x2", "Wide2x3")] public void CanMultiplyMatrixWithMatrix(string nameA, string nameB) { var matrixA = TestMatrices[nameA]; var matrixB = TestMatrices[nameB]; var matrixC = matrixA * matrixB; Assert.AreEqual(matrixC.RowCount, matrixA.RowCount); Assert.AreEqual(matrixC.ColumnCount, matrixB.ColumnCount); for (var i = 0; i < matrixC.RowCount; i++) { for (var j = 0; j < matrixC.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixA.Row(i) * matrixB.Column(j), matrixC[i, j], 5); } } } /// <summary> /// Can transpose and multiply a matrix with matrix. /// </summary> /// <param name="nameA">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Wide2x3")] [TestCase("Tall3x2")] public void CanTransposeAndMultiplyMatrixWithMatrix(string nameA) { var matrixA = TestMatrices[nameA]; var matrixB = TestMatrices[nameA]; var matrixC = matrixA.TransposeAndMultiply(matrixB); Assert.AreEqual(matrixC.RowCount, matrixA.RowCount); Assert.AreEqual(matrixC.ColumnCount, matrixB.RowCount); for (var i = 0; i < matrixC.RowCount; i++) { for (var j = 0; j < matrixC.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixA.Row(i) * matrixB.Row(j), matrixC[i, j], 5); } } } /// <summary> /// Can transpose and multiply a matrix with differing dimensions. /// </summary> [Test] public void CanTransposeAndMultiplyWithDifferingDimensions() { var matrixA = TestMatrices["Tall3x2"]; var matrixB = CreateMatrix(5, 2); var count = 1; for (var row = 0; row < matrixB.RowCount; row++) { for (var col = 0; col < matrixB.ColumnCount; col++) { if (row == col) { matrixB[row, col] = count++; } } } var matrixC = matrixA.TransposeAndMultiply(matrixB); Assert.AreEqual(matrixC.RowCount, matrixA.RowCount); Assert.AreEqual(matrixC.ColumnCount, matrixB.RowCount); for (var i = 0; i < matrixC.RowCount; i++) { for (var j = 0; j < matrixC.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixA.Row(i) * matrixB.Row(j), matrixC[i, j], 6); } } } /// <summary> /// Transpose and multiply a matrix with matrix of incompatible size throws <c>ArgumentException</c>. /// </summary> [Test] public void TransposeAndMultiplyMatrixMatrixWithIncompatibleSizesThrowsArgumentException() { var matrix = TestMatrices["Singular3x3"]; var other = TestMatrices["Tall3x2"]; Assert.That(() => matrix.TransposeAndMultiply(other), Throws.ArgumentException); } /// <summary> /// Can transpose and multiply a matrix with matrix into a result matrix. /// </summary> /// <param name="nameA">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Wide2x3")] [TestCase("Tall3x2")] public void CanTransposeAndMultiplyMatrixWithMatrixIntoResult(string nameA) { var matrixA = TestMatrices[nameA]; var matrixB = TestMatrices[nameA]; var matrixC = CreateMatrix(matrixA.RowCount, matrixB.RowCount); matrixA.TransposeAndMultiply(matrixB, matrixC); Assert.AreEqual(matrixC.RowCount, matrixA.RowCount); Assert.AreEqual(matrixC.ColumnCount, matrixB.RowCount); for (var i = 0; i < matrixC.RowCount; i++) { for (var j = 0; j < matrixC.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixA.Row(i) * matrixB.Row(j), matrixC[i, j], 5); } } } /// <summary> /// Multiply a matrix with incompatible size matrix throws <c>ArgumentException</c>. /// </summary> [Test] public void MultiplyMatrixMatrixWithIncompatibleSizesThrowsArgumentException() { var matrix = TestMatrices["Singular3x3"]; var other = TestMatrices["Wide2x3"]; Assert.Throws<ArgumentException>(() => { var result = matrix * other; }); } /// <summary> /// Can multiply a matrix with matrix into a result matrix. /// </summary> /// <param name="nameA">Matrix A name.</param> /// <param name="nameB">Matrix B name.</param> [TestCase("Singular3x3", "Square3x3")] [TestCase("Singular4x4", "Square4x4")] [TestCase("Wide2x3", "Square3x3")] [TestCase("Wide2x3", "Tall3x2")] [TestCase("Tall3x2", "Wide2x3")] public virtual void CanMultiplyMatrixWithMatrixIntoResult(string nameA, string nameB) { var matrixA = TestMatrices[nameA]; var matrixB = TestMatrices[nameB]; var matrixC = CreateMatrix(matrixA.RowCount, matrixB.ColumnCount); matrixA.Multiply(matrixB, matrixC); Assert.AreEqual(matrixC.RowCount, matrixA.RowCount); Assert.AreEqual(matrixC.ColumnCount, matrixB.ColumnCount); for (var i = 0; i < matrixC.RowCount; i++) { for (var j = 0; j < matrixC.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixA.Row(i) * matrixB.Column(j), matrixC[i, j], 5); } } } /// <summary> /// Can multiply transposed matrix with a vector. /// </summary> [Test] public void CanTransposeThisAndMultiplyWithVector() { var matrix = TestMatrices["Singular3x3"]; var x = new DenseVector(new[] { 1.0f, 2.0f, 3.0f }); var y = matrix.TransposeThisAndMultiply(x); Assert.AreEqual(matrix.ColumnCount, y.Count); for (var j = 0; j < matrix.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrix.Column(j) * x, y[j], 6); } } /// <summary> /// Can multiply transposed matrix with a vector into a result. /// </summary> [Test] public void CanTransposeThisAndMultiplyWithVectorIntoResult() { var matrix = TestMatrices["Singular3x3"]; var x = new DenseVector(new[] { 1.0f, 2.0f, 3.0f }); var y = new DenseVector(3); matrix.TransposeThisAndMultiply(x, y); for (var j = 0; j < matrix.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrix.Column(j) * x, y[j], 6); } } /// <summary> /// Can multiply transposed matrix with a vector into result when updating input argument. /// </summary> [Test] public void CanTransposeThisAndMultiplyWithVectorIntoResultWhenUpdatingInputArgument() { var matrix = TestMatrices["Singular3x3"]; var x = new DenseVector(new[] { 1.0f, 2.0f, 3.0f }); var y = x; matrix.TransposeThisAndMultiply(x, x); Assert.AreSame(y, x); y = new DenseVector(new[] { 1.0f, 2.0f, 3.0f }); for (var j = 0; j < matrix.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrix.Column(j) * y, x[j], 6); } } /// <summary> /// Multiply transposed matrix with a vector into too large result throws <c>ArgumentException</c>. /// </summary> [Test] public void TransposeThisAndMultiplyWithVectorIntoLargerResultThrowsArgumentException() { var matrix = TestMatrices["Singular3x3"]; var x = new DenseVector(new[] { 1.0f, 2.0f, 3.0f }); Vector<float> y = new DenseVector(4); Assert.That(() => matrix.TransposeThisAndMultiply(x, y), Throws.ArgumentException); } /// <summary> /// Can multiply transposed matrix with another matrix. /// </summary> /// <param name="nameA">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Wide2x3")] [TestCase("Tall3x2")] public void CanTransposeThisAndMultiplyMatrixWithMatrix(string nameA) { var matrixA = TestMatrices[nameA]; var matrixB = TestMatrices[nameA]; var matrixC = matrixA.TransposeThisAndMultiply(matrixB); Assert.AreEqual(matrixC.RowCount, matrixA.ColumnCount); Assert.AreEqual(matrixC.ColumnCount, matrixB.ColumnCount); for (var i = 0; i < matrixC.RowCount; i++) { for (var j = 0; j < matrixC.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixA.Column(i) * matrixB.Column(j), matrixC[i, j], 5); } } } /// <summary> /// Multiply the transpose of matrix with another matrix of incompatible size throws <c>ArgumentException</c>. /// </summary> [Test] public void TransposeThisAndMultiplyMatrixMatrixWithIncompatibleSizesThrowsArgumentException() { var matrix = TestMatrices["Wide2x3"]; var other = TestMatrices["Singular3x3"]; Assert.That(() => matrix.TransposeThisAndMultiply(other), Throws.ArgumentException); } /// <summary> /// Multiply transpose of this matrix with another matrix into a result matrix. /// </summary> /// <param name="nameA">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Wide2x3")] [TestCase("Tall3x2")] public void CanTransposeThisAndMultiplyMatrixWithMatrixIntoResult(string nameA) { var matrixA = TestMatrices[nameA]; var matrixB = TestMatrices[nameA]; var matrixC = CreateMatrix(matrixA.ColumnCount, matrixB.ColumnCount); matrixA.TransposeThisAndMultiply(matrixB, matrixC); Assert.AreEqual(matrixC.RowCount, matrixA.ColumnCount); Assert.AreEqual(matrixC.ColumnCount, matrixB.ColumnCount); for (var i = 0; i < matrixC.RowCount; i++) { for (var j = 0; j < matrixC.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixA.Column(i) * matrixB.Column(j), matrixC[i, j], 5); } } } /// <summary> /// Can negate a matrix. /// </summary> /// <param name="name">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Wide2x3")] [TestCase("Wide2x3")] [TestCase("Tall3x2")] public void CanNegate(string name) { var matrix = TestMatrices[name]; var copy = matrix.Clone(); copy = copy.Negate(); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(-matrix[i, j], copy[i, j]); } } } /// <summary> /// Can negate a matrix into a result matrix. /// </summary> /// <param name="name">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Wide2x3")] [TestCase("Wide2x3")] [TestCase("Tall3x2")] public void CanNegateIntoResult(string name) { var matrix = TestMatrices[name]; var copy = matrix.Clone(); matrix.Negate(copy); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(-matrix[i, j], copy[i, j]); } } } /// <summary> /// Negate into a result matrix with more rows throws <c>ArgumentException</c>. /// </summary> [Test] public void NegateIntoResultWithMoreRowsThrowsArgumentException() { var matrix = TestMatrices["Singular3x3"]; var target = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount); Assert.That(() => matrix.Negate(target), Throws.ArgumentException); } /// <summary> /// Negate into a result matrix with more rows throws <c>ArgumentException</c>. /// </summary> [Test] public void NegateIntoResultWithMoreColumnsThrowsArgumentException() { var matrix = TestMatrices["Singular3x3"]; var target = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount); Assert.That(() => matrix.Negate(target), Throws.ArgumentException); } /// <summary> /// Can compute Moore-Penrose Pseudo-Inverse. /// </summary> [TestCase("Square3x3")] [TestCase("Wide2x3")] [TestCase("Tall3x2")] public virtual void CanComputePseudoInverse(string name) { var matrix = TestMatrices[name]; var inverse = matrix.PseudoInverse(); // Testing for Moore–Penrose conditions 1: A*A^+*A = A AssertHelpers.AlmostEqual(matrix, matrix * (inverse * matrix), 5); } /// <summary> /// Can calculate Kronecker product. /// </summary> [Test] public void CanKroneckerProduct() { var matrixA = TestMatrices["Wide2x3"]; var matrixB = TestMatrices["Square3x3"]; var result = CreateMatrix(matrixA.RowCount * matrixB.RowCount, matrixA.ColumnCount * matrixB.ColumnCount); matrixA.KroneckerProduct(matrixB, result); for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { for (var ii = 0; ii < matrixB.RowCount; ii++) { for (var jj = 0; jj < matrixB.ColumnCount; jj++) { Assert.AreEqual(result[(i * matrixB.RowCount) + ii, (j * matrixB.ColumnCount) + jj], matrixA[i, j] * matrixB[ii, jj]); } } } } } /// <summary> /// Can calculate Kronecker product into a result matrix. /// </summary> [Test] public void CanKroneckerProductIntoResult() { var matrixA = TestMatrices["Wide2x3"]; var matrixB = TestMatrices["Square3x3"]; var result = matrixA.KroneckerProduct(matrixB); for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { for (var ii = 0; ii < matrixB.RowCount; ii++) { for (var jj = 0; jj < matrixB.ColumnCount; jj++) { Assert.AreEqual(result[(i * matrixB.RowCount) + ii, (j * matrixB.ColumnCount) + jj], matrixA[i, j] * matrixB[ii, jj]); } } } } } /// <summary> /// Can normalize columns of a matrix. /// </summary> /// <param name="p">The norm under which to normalize the columns under.</param> [TestCase(1)] [TestCase(2)] public void CanNormalizeColumns(int p) { var matrix = TestMatrices["Square4x4"]; var result = matrix.NormalizeColumns(p); for (var j = 0; j < result.ColumnCount; j++) { var col = result.Column(j); Assert.AreEqual(1.0f, col.Norm(p), 10e-6f); } } /// <summary> /// Normalize columns with wrong parameter throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void NormalizeColumnsWithWrongParameterThrowsArgumentOutOfRangeException() { Assert.That(() => TestMatrices["Square4x4"].NormalizeColumns(-4), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can normalize rows of a matrix. /// </summary> /// <param name="p">The norm under which to normalize the rows under.</param> [TestCase(1)] [TestCase(2)] public void CanNormalizeRows(int p) { var matrix = TestMatrices["Square4x4"].NormalizeRows(p); for (var i = 0; i < matrix.RowCount; i++) { var row = matrix.Row(i); Assert.AreEqual(1.0f, row.Norm(p), 10e-6f); } } /// <summary> /// Normalize rows with wrong parameter throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void NormalizeRowsWithWrongParameterThrowsArgumentOutOfRangeException() { Assert.That(() => TestMatrices["Square4x4"].NormalizeRows(-4), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can pointwise multiply matrices into a result matrix. /// </summary> [Test] public void CanPointwiseMultiplyIntoResult() { foreach (var data in TestMatrices.Values) { var other = data.Clone(); var result = data.Clone(); data.PointwiseMultiply(other, result); for (var i = 0; i < data.RowCount; i++) { for (var j = 0; j < data.ColumnCount; j++) { Assert.AreEqual(data[i, j] * other[i, j], result[i, j]); } } result = data.PointwiseMultiply(other); for (var i = 0; i < data.RowCount; i++) { for (var j = 0; j < data.ColumnCount; j++) { Assert.AreEqual(data[i, j] * other[i, j], result[i, j]); } } } } /// <summary> /// Pointwise multiply matrices with invalid dimensions into a result throws <c>ArgumentException</c>. /// </summary> [Test] public void PointwiseMultiplyWithInvalidDimensionsIntoResultThrowsArgumentException() { var matrix = TestMatrices["Wide2x3"]; var other = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount); var result = matrix.Clone(); Assert.That(() => matrix.PointwiseMultiply(other, result), Throws.ArgumentException); } /// <summary> /// Pointwise multiply matrices with invalid result dimensions throws <c>ArgumentException</c>. /// </summary> [Test] public void PointwiseMultiplyWithInvalidResultDimensionsThrowsArgumentException() { var matrix = TestMatrices["Wide2x3"]; var other = matrix.Clone(); var result = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount); Assert.That(() => matrix.PointwiseMultiply(other, result), Throws.ArgumentException); } /// <summary> /// Can pointwise divide matrices into a result matrix. /// </summary> [Test] public virtual void CanPointwiseDivideIntoResult() { var data = TestMatrices["Singular3x3"]; var other = data.Clone(); var result = data.Clone(); data.PointwiseDivide(other, result); for (var i = 0; i < data.RowCount; i++) { for (var j = 0; j < data.ColumnCount; j++) { Assert.AreEqual(data[i, j] / other[i, j], result[i, j]); } } result = data.PointwiseDivide(other); for (var i = 0; i < data.RowCount; i++) { for (var j = 0; j < data.ColumnCount; j++) { Assert.AreEqual(data[i, j] / other[i, j], result[i, j]); } } } /// <summary> /// Pointwise divide matrices with invalid dimensions into a result throws <c>ArgumentException</c>. /// </summary> [Test] public void PointwiseDivideWithInvalidDimensionsIntoResultThrowsArgumentException() { var matrix = TestMatrices["Wide2x3"]; var other = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount); var result = matrix.Clone(); Assert.That(() => matrix.PointwiseDivide(other, result), Throws.ArgumentException); } /// <summary> /// Pointwise divide matrices with invalid result dimensions throws <c>ArgumentException</c>. /// </summary> [Test] public void PointwiseDivideWithInvalidResultDimensionsThrowsArgumentException() { var matrix = TestMatrices["Wide2x3"]; var other = matrix.Clone(); var result = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount); Assert.That(() => matrix.PointwiseDivide(other, result), Throws.ArgumentException); } /// <summary> /// Create random matrix with non-positive number of rows throw <c>ArgumentException</c>. /// </summary> /// <param name="numberOfRows">Number of rows.</param> [TestCase(-1)] [TestCase(-2)] public void RandomWithNonPositiveNumberOfRowsThrowsArgumentException(int numberOfRows) { Assert.That(() => DenseMatrix.CreateRandom(numberOfRows, 4, new ContinuousUniform()), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can trace. /// </summary> [Test] public void CanTrace() { var matrix = TestMatrices["Square3x3"]; var trace = matrix.Trace(); Assert.AreEqual(6.6f, trace); } /// <summary> /// Trace of non-square matrix throws <c>ArgumentException</c>. /// </summary> [Test] public void TraceOfNonSquareMatrixThrowsArgumentException() { var matrix = TestMatrices["Wide2x3"]; Assert.That(() => matrix.Trace(), Throws.ArgumentException); } [Test] public void CanComputeRemainderUsingOperator() { var matrix = TestMatrices["Square3x3"]; var mod = matrix%(-3.2f); for (var row = 0; row < matrix.RowCount; row++) { for (var column = 0; column < matrix.ColumnCount; column++) { AssertHelpers.AlmostEqual(Euclid.Remainder(matrix[row, column], -3.2f), mod[row, column], 14); } } } [Test] public void CanComputeRemainder() { var matrix = TestMatrices["Square3x3"]; var mod = matrix.Remainder(-3.2f); for (var row = 0; row < matrix.RowCount; row++) { for (var column = 0; column < matrix.ColumnCount; column++) { AssertHelpers.AlmostEqual(Euclid.Remainder(matrix[row, column], -3.2f), mod[row, column], 14); } } } [Test] public void CanComputeRemainderUsingResultVector() { var matrix = TestMatrices["Square3x3"]; var mod = CreateMatrix(matrix.RowCount, matrix.ColumnCount); matrix.Remainder(-3.2f, mod); for (var row = 0; row < matrix.RowCount; row++) { for (var column = 0; column < matrix.ColumnCount; column++) { AssertHelpers.AlmostEqual(Euclid.Remainder(matrix[row, column], -3.2f), mod[row, column], 14); } } } [Test] public void CanComputeRemainderUsingSameResultVector() { var matrix = TestMatrices["Square3x3"].Clone(); matrix.Remainder(-3.2f, matrix); var data = TestMatrices["Square3x3"]; for (var row = 0; row < matrix.RowCount; row++) { for (var column = 0; column < matrix.ColumnCount; column++) { AssertHelpers.AlmostEqual(Euclid.Remainder(data[row, column], -3.2f), matrix[row, column], 14); } } } [Test] public void CanComputeModulus() { var matrix = TestMatrices["Square3x3"]; var mod = matrix.Modulus(-3.2f); for (var row = 0; row < matrix.RowCount; row++) { for (var column = 0; column < matrix.ColumnCount; column++) { AssertHelpers.AlmostEqual(Euclid.Modulus(matrix[row, column], -3.2f), mod[row, column], 14); } } } [Test] public void CanComputeModulusUsingResultVector() { var matrix = TestMatrices["Square3x3"]; var mod = CreateMatrix(matrix.RowCount, matrix.ColumnCount); matrix.Modulus(-3.2f, mod); for (var row = 0; row < matrix.RowCount; row++) { for (var column = 0; column < matrix.ColumnCount; column++) { AssertHelpers.AlmostEqual(Euclid.Modulus(matrix[row, column], -3.2f), mod[row, column], 14); } } } [Test] public void CanComputeModulusUsingSameResultVector() { var matrix = TestMatrices["Square3x3"].Clone(); matrix.Modulus(-3.2f, matrix); var data = TestMatrices["Square3x3"]; for (var row = 0; row < matrix.RowCount; row++) { for (var column = 0; column < matrix.ColumnCount; column++) { AssertHelpers.AlmostEqual(Euclid.Modulus(data[row, column], -3.2f), matrix[row, column], 14); } } } } }
36.929674
146
0.528216
[ "MIT" ]
WeihanLi/mathnet-numerics
src/Numerics.Tests/LinearAlgebraTests/Single/MatrixTests.Arithmetic.cs
43,062
C#
using System; namespace Shane32.ExcelLinq.Tests.Models { class Class1 { public string StringColumn; public int IntColumn; public float FloatColumn; public double DoubleColumn; public DateTime DateTimeColumn; public TimeSpan TimeSpanColumn; public bool BooleanColumn; public Uri UriColumn; public Guid GuidColumn; public decimal DecimalColumn; public int? NullableIntColumn; } }
23.95
40
0.65762
[ "MIT" ]
Shane32/ExcelLinq
src/Shane32.ExcelLinq.Tests/Models/Class1.cs
479
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OopProperties { public class Address { public string Country { get; set; } = string.Empty; public string State { get; set; } = string.Empty; public string City { get; set; } = string.Empty; public string this[string part] { get { if (string.Equals(part, nameof(Country), StringComparison.OrdinalIgnoreCase)) { return Country; } else if (string.Equals(part, nameof(State), StringComparison.OrdinalIgnoreCase)) { return State; } else if (string.Equals(part, nameof(City), StringComparison.OrdinalIgnoreCase)) { return City; } return string.Empty; } } public string this[AddressPart partIndex] { get { switch(partIndex) { case AddressPart.Country: return Country; case AddressPart.State: return State; case AddressPart.City: return City; default: return string.Empty; } } } } }
24.786885
96
0.453704
[ "MIT" ]
FastTrackIT-WON-3/oop-properties
OopProperties/OopProperties/Address.cs
1,514
C#
using System; using System.Collections.Generic; using System.Text; namespace RevivingSun.Messages { public class AuthOut : AbstractMessage { public override string _Name { get => "auth"; } public string TOS { get; set; } public string NAME { get; set; } public string MAIL { get; set; } = "tsbo@freeso.net"; public string BORN { get; set; } = "19800325"; public string GEND { get; set; } = "M"; public string FROM { get; set; } = "US"; public string LANG { get; set; } = "en"; public string SPAM { get; set; } = "NN"; public string PERSONAS { get; set; } //comma separated list public string LAST { get; set; } = "2003.12.8 15:51:38"; } }
32.26087
67
0.579515
[ "Apache-2.0" ]
xxCUBSxx/RevivingSun
RevivingSun/Messages/AuthOut.cs
744
C#
// // ReplaceWithLastOrDefaultIssue.cs // // Author: // Mike Krüger <mkrueger@xamarin.com> // // Copyright (c) 2013 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.PatternMatching; using ICSharpCode.NRefactory.Refactoring; namespace ICSharpCode.NRefactory.CSharp.Refactoring { [IssueDescription("Replace with LastOrDefault<T>()", Description = "Replace with call to LastOrDefault<T>()", Category = IssueCategories.PracticesAndImprovements, Severity = Severity.Suggestion, AnalysisDisableKeyword = "ReplaceWithLastOrDefault")] public class ReplaceWithLastOrDefaultIssue : GatherVisitorCodeIssueProvider { protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context) { return new GatherVisitor(context); } class GatherVisitor : GatherVisitorBase<ReplaceWithLastOrDefaultIssue> { public GatherVisitor (BaseRefactoringContext ctx) : base (ctx) { } readonly AstNode pattern = new ConditionalExpression( new InvocationExpression( new MemberReferenceExpression(new AnyNode("expr"), "Any"), new AnyNodeOrNull("param") ), new InvocationExpression( new MemberReferenceExpression(new Backreference("expr"), "Last"), new Backreference("param") ), new Choice { new NullReferenceExpression(), new DefaultValueExpression(new AnyNode()) } ); public override void VisitConditionalExpression(ConditionalExpression conditionalExpression) { base.VisitConditionalExpression(conditionalExpression); var match = pattern.Match(conditionalExpression); if (!match.Success) return; var expression = match.Get<Expression>("expr").First(); var param = match.Get<Expression>("param").First(); AddIssue(new CodeIssue( conditionalExpression, ctx.TranslateString("Expression can be simlified to 'LastOrDefault<T>()'"), ctx.TranslateString("Replace with 'LastOrDefault<T>()'"), script => { var invocation = new InvocationExpression(new MemberReferenceExpression(expression.Clone(), "LastOrDefault")); if (param != null && !param.IsNull) invocation.Arguments.Add(param.Clone()); script.Replace( conditionalExpression, invocation ); } )); } } } }
36.520408
116
0.721431
[ "MIT" ]
Jenkin0603/myvim
bundle/omnisharp-vim/server/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/PracticesAndImprovements/ReplaceWithLastOrDefaultIssue.cs
3,580
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DayNight : MonoBehaviour { [SerializeField] public int time = 5000; [SerializeField] Transform food = null; // Update is called once per frame void FixedUpdate() { time --; GlobalData.avgspeed = GlobalData.totspeed / GlobalData.numagents; Debug.Log(GlobalData.avgspeed); if(time <= 0){ GlobalData.currentDay++; FoodSpawner.SpawnFood(10, food); time = 5000; } } }
22.730769
74
0.588832
[ "MIT" ]
Jackson-Stitzel/EvolutionSimulation
EvolutionTestTest/Assets/Scripts/DayNight.cs
591
C#
namespace StrumskaSlava.Data.Common.Repositories { using System.Linq; using System.Threading.Tasks; using StrumskaSlava.Data.Common.Models; public interface IDeletableEntityRepository<TEntity> : IRepository<TEntity> where TEntity : class, IDeletableEntity { IQueryable<TEntity> AllWithDeleted(); IQueryable<TEntity> AllAsNoTrackingWithDeleted(); Task<TEntity> GetByIdWithDeletedAsync(params object[] id); void HardDelete(TEntity entity); void Undelete(TEntity entity); } }
25.090909
79
0.708333
[ "MIT" ]
DanailY/StrumskaSlava
Data/StrumskaSlava.Data.Common/Repositories/IDeletableEntityRepository.cs
554
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/WinUser.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.Versioning; namespace TerraFX.Interop.Windows; /// <include file='POINTER_DEVICE_INFO.xml' path='doc/member[@name="POINTER_DEVICE_INFO"]/*' /> [SupportedOSPlatform("windows8.0")] public unsafe partial struct POINTER_DEVICE_INFO { /// <include file='POINTER_DEVICE_INFO.xml' path='doc/member[@name="POINTER_DEVICE_INFO.displayOrientation"]/*' /> [NativeTypeName("DWORD")] public uint displayOrientation; /// <include file='POINTER_DEVICE_INFO.xml' path='doc/member[@name="POINTER_DEVICE_INFO.device"]/*' /> public HANDLE device; /// <include file='POINTER_DEVICE_INFO.xml' path='doc/member[@name="POINTER_DEVICE_INFO.pointerDeviceType"]/*' /> public POINTER_DEVICE_TYPE pointerDeviceType; /// <include file='POINTER_DEVICE_INFO.xml' path='doc/member[@name="POINTER_DEVICE_INFO.monitor"]/*' /> public HMONITOR monitor; /// <include file='POINTER_DEVICE_INFO.xml' path='doc/member[@name="POINTER_DEVICE_INFO.startingCursorId"]/*' /> [NativeTypeName("ULONG")] public uint startingCursorId; /// <include file='POINTER_DEVICE_INFO.xml' path='doc/member[@name="POINTER_DEVICE_INFO.maxActiveContacts"]/*' /> public ushort maxActiveContacts; /// <include file='POINTER_DEVICE_INFO.xml' path='doc/member[@name="POINTER_DEVICE_INFO.productString"]/*' /> [NativeTypeName("WCHAR [520]")] public fixed ushort productString[520]; }
44.736842
145
0.737059
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/WinUser/POINTER_DEVICE_INFO.cs
1,702
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.Threading; using System.Threading.Tasks; namespace Roslyn.Utilities { internal static class SemaphoreSlimExtensions { public static SemaphoreDisposer DisposableWait(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default(CancellationToken)) { semaphore.Wait(cancellationToken); return new SemaphoreDisposer(semaphore); } public async static Task<SemaphoreDisposer> DisposableWaitAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default(CancellationToken)) { await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); return new SemaphoreDisposer(semaphore); } internal struct SemaphoreDisposer : IDisposable { private readonly SemaphoreSlim _semaphore; public SemaphoreDisposer(SemaphoreSlim semaphore) { _semaphore = semaphore; } public void Dispose() { _semaphore.Release(); } } } }
32.871795
167
0.663807
[ "Apache-2.0" ]
0x53A/roslyn
src/Compilers/Core/Portable/InternalUtilities/SemaphoreSlimExtensions.cs
1,284
C#
using System; using Microsoft.AspNetCore.Components; using MudBlazor.Services; namespace MudBlazor { public partial class MudPortalProvider : IDisposable { private PortalItem _itemToRender; [Inject] internal IPortal Portal { get; set; } protected override void OnInitialized() => Portal.OnChange += HandleChange; /// <summary> /// This is called when the portal adds or removes an item /// </summary> private void HandleChange(object _, PortalEventsArg e) { //this is the only item that changed, so the only that is going to rerender _itemToRender = e.Item; InvokeAsync(StateHasChanged); } protected virtual void Dispose(bool disposing) { if (!disposing) return; Portal.OnChange -= HandleChange; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } }
25.897436
87
0.60099
[ "MIT" ]
KamilBugnoKrk/MudBlazor
src/MudBlazor/Components/Portal/MudPortalProvider.razor.cs
1,012
C#
using UnityEngine; using UnityEngine.UI; namespace OpenTibiaUnity.Modules.Skills { public class SkillProgressPanel : SkillPanel { [SerializeField] private TMPro.TextMeshProUGUI _labelText = null; [SerializeField] private TMPro.TextMeshProUGUI _labelValue = null; [SerializeField] private Slider _progressBar = null; [SerializeField] private RawImage _fillAreaImage = null; public override TMPro.TextMeshProUGUI labelText { get => _labelText; } public override TMPro.TextMeshProUGUI labelValue { get => _labelValue; } protected override void Start() { base.Start(); _progressBar.minValue = 0; _progressBar.maxValue = 100; } public override void SetProgressColor(Color color) => _fillAreaImage.color = color; public override void SetText(string text) => _labelText.SetText(text); public override void SetValue(long value) => SetValue(value, 0); public override void SetValue(string value) => SetValue(value, 0); public override void SetValue(long value, float percent) => SetValueInternal(Core.Utils.Utility.Commafy(value), percent); public override void SetValue(string value, float percent) => SetValueInternal(value, percent); private void SetValueInternal(string value, float percent) { _labelValue.SetText(value); _progressBar.value = percent; } } }
40.777778
129
0.680518
[ "MIT" ]
DwarvenSoft/OpenTibia-Unity
OpenTibia/Assets/Scripts/Modules/Skills/SkillProgressPanel.cs
1,470
C#
using System; namespace ReverseArray { class Program { static void Main(string[] args) { ArrayReverse(); } public static void ArrayReverse() { int[] GivenArray = new int[] { 3, 2, 1 }; int[] ReverseArray = new int[GivenArray.Length]; //for loop to iterate from the last value of the array to the front for (var i = GivenArray.Length - 1; i >= 0; i--) { ReverseArray[i] = GivenArray[i]; Console.WriteLine(ReverseArray[i]); } } } }
24.36
79
0.490969
[ "MIT" ]
IndigoShock/data-structures-and-algorithms
Challenges/ReverseArray/ReverseArray/Program.cs
611
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from shared/dxgi1_2.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using TerraFX.Interop.Windows; namespace TerraFX.Interop.DirectX; /// <include file='IDXGIOutput1.xml' path='doc/member[@name="IDXGIOutput1"]/*' /> [Guid("00CDDEA8-939B-4B83-A340-A685226666CC")] [NativeTypeName("struct IDXGIOutput1 : IDXGIOutput")] [NativeInheritance("IDXGIOutput")] public unsafe partial struct IDXGIOutput1 : IDXGIOutput1.Interface { public void** lpVtbl; /// <inheritdoc cref="IUnknown.QueryInterface" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(0)] public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) { return ((delegate* unmanaged<IDXGIOutput1*, Guid*, void**, int>)(lpVtbl[0]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), riid, ppvObject); } /// <inheritdoc cref="IUnknown.AddRef" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(1)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<IDXGIOutput1*, uint>)(lpVtbl[1]))((IDXGIOutput1*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IUnknown.Release" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(2)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<IDXGIOutput1*, uint>)(lpVtbl[2]))((IDXGIOutput1*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IDXGIObject.SetPrivateData" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(3)] public HRESULT SetPrivateData([NativeTypeName("const GUID &")] Guid* Name, uint DataSize, [NativeTypeName("const void *")] void* pData) { return ((delegate* unmanaged<IDXGIOutput1*, Guid*, uint, void*, int>)(lpVtbl[3]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), Name, DataSize, pData); } /// <inheritdoc cref="IDXGIObject.SetPrivateDataInterface" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(4)] public HRESULT SetPrivateDataInterface([NativeTypeName("const GUID &")] Guid* Name, [NativeTypeName("const IUnknown *")] IUnknown* pUnknown) { return ((delegate* unmanaged<IDXGIOutput1*, Guid*, IUnknown*, int>)(lpVtbl[4]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), Name, pUnknown); } /// <inheritdoc cref="IDXGIObject.GetPrivateData" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(5)] public HRESULT GetPrivateData([NativeTypeName("const GUID &")] Guid* Name, uint* pDataSize, void* pData) { return ((delegate* unmanaged<IDXGIOutput1*, Guid*, uint*, void*, int>)(lpVtbl[5]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), Name, pDataSize, pData); } /// <inheritdoc cref="IDXGIObject.GetParent" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(6)] public HRESULT GetParent([NativeTypeName("const IID &")] Guid* riid, void** ppParent) { return ((delegate* unmanaged<IDXGIOutput1*, Guid*, void**, int>)(lpVtbl[6]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), riid, ppParent); } /// <inheritdoc cref="IDXGIOutput.GetDesc" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(7)] public HRESULT GetDesc(DXGI_OUTPUT_DESC* pDesc) { return ((delegate* unmanaged[SuppressGCTransition]<IDXGIOutput1*, DXGI_OUTPUT_DESC*, int>)(lpVtbl[7]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pDesc); } /// <inheritdoc cref="IDXGIOutput.GetDisplayModeList" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(8)] public HRESULT GetDisplayModeList(DXGI_FORMAT EnumFormat, uint Flags, uint* pNumModes, DXGI_MODE_DESC* pDesc) { return ((delegate* unmanaged<IDXGIOutput1*, DXGI_FORMAT, uint, uint*, DXGI_MODE_DESC*, int>)(lpVtbl[8]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), EnumFormat, Flags, pNumModes, pDesc); } /// <inheritdoc cref="IDXGIOutput.FindClosestMatchingMode" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(9)] public HRESULT FindClosestMatchingMode([NativeTypeName("const DXGI_MODE_DESC *")] DXGI_MODE_DESC* pModeToMatch, DXGI_MODE_DESC* pClosestMatch, IUnknown* pConcernedDevice) { return ((delegate* unmanaged<IDXGIOutput1*, DXGI_MODE_DESC*, DXGI_MODE_DESC*, IUnknown*, int>)(lpVtbl[9]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pModeToMatch, pClosestMatch, pConcernedDevice); } /// <inheritdoc cref="IDXGIOutput.WaitForVBlank" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(10)] public HRESULT WaitForVBlank() { return ((delegate* unmanaged<IDXGIOutput1*, int>)(lpVtbl[10]))((IDXGIOutput1*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IDXGIOutput.TakeOwnership" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(11)] public HRESULT TakeOwnership(IUnknown* pDevice, BOOL Exclusive) { return ((delegate* unmanaged<IDXGIOutput1*, IUnknown*, BOOL, int>)(lpVtbl[11]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pDevice, Exclusive); } /// <inheritdoc cref="IDXGIOutput.ReleaseOwnership" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(12)] public void ReleaseOwnership() { ((delegate* unmanaged<IDXGIOutput1*, void>)(lpVtbl[12]))((IDXGIOutput1*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IDXGIOutput.GetGammaControlCapabilities" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(13)] public HRESULT GetGammaControlCapabilities(DXGI_GAMMA_CONTROL_CAPABILITIES* pGammaCaps) { return ((delegate* unmanaged<IDXGIOutput1*, DXGI_GAMMA_CONTROL_CAPABILITIES*, int>)(lpVtbl[13]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pGammaCaps); } /// <inheritdoc cref="IDXGIOutput.SetGammaControl" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(14)] public HRESULT SetGammaControl([NativeTypeName("const DXGI_GAMMA_CONTROL *")] DXGI_GAMMA_CONTROL* pArray) { return ((delegate* unmanaged<IDXGIOutput1*, DXGI_GAMMA_CONTROL*, int>)(lpVtbl[14]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pArray); } /// <inheritdoc cref="IDXGIOutput.GetGammaControl" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(15)] public HRESULT GetGammaControl(DXGI_GAMMA_CONTROL* pArray) { return ((delegate* unmanaged<IDXGIOutput1*, DXGI_GAMMA_CONTROL*, int>)(lpVtbl[15]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pArray); } /// <inheritdoc cref="IDXGIOutput.SetDisplaySurface" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(16)] public HRESULT SetDisplaySurface(IDXGISurface* pScanoutSurface) { return ((delegate* unmanaged<IDXGIOutput1*, IDXGISurface*, int>)(lpVtbl[16]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pScanoutSurface); } /// <inheritdoc cref="IDXGIOutput.GetDisplaySurfaceData" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(17)] public HRESULT GetDisplaySurfaceData(IDXGISurface* pDestination) { return ((delegate* unmanaged<IDXGIOutput1*, IDXGISurface*, int>)(lpVtbl[17]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pDestination); } /// <inheritdoc cref="IDXGIOutput.GetFrameStatistics" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(18)] public HRESULT GetFrameStatistics(DXGI_FRAME_STATISTICS* pStats) { return ((delegate* unmanaged<IDXGIOutput1*, DXGI_FRAME_STATISTICS*, int>)(lpVtbl[18]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pStats); } /// <include file='IDXGIOutput1.xml' path='doc/member[@name="IDXGIOutput1.GetDisplayModeList1"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(19)] public HRESULT GetDisplayModeList1(DXGI_FORMAT EnumFormat, uint Flags, uint* pNumModes, DXGI_MODE_DESC1* pDesc) { return ((delegate* unmanaged<IDXGIOutput1*, DXGI_FORMAT, uint, uint*, DXGI_MODE_DESC1*, int>)(lpVtbl[19]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), EnumFormat, Flags, pNumModes, pDesc); } /// <include file='IDXGIOutput1.xml' path='doc/member[@name="IDXGIOutput1.FindClosestMatchingMode1"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(20)] public HRESULT FindClosestMatchingMode1([NativeTypeName("const DXGI_MODE_DESC1 *")] DXGI_MODE_DESC1* pModeToMatch, DXGI_MODE_DESC1* pClosestMatch, IUnknown* pConcernedDevice) { return ((delegate* unmanaged<IDXGIOutput1*, DXGI_MODE_DESC1*, DXGI_MODE_DESC1*, IUnknown*, int>)(lpVtbl[20]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pModeToMatch, pClosestMatch, pConcernedDevice); } /// <include file='IDXGIOutput1.xml' path='doc/member[@name="IDXGIOutput1.GetDisplaySurfaceData1"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(21)] public HRESULT GetDisplaySurfaceData1(IDXGIResource* pDestination) { return ((delegate* unmanaged<IDXGIOutput1*, IDXGIResource*, int>)(lpVtbl[21]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pDestination); } /// <include file='IDXGIOutput1.xml' path='doc/member[@name="IDXGIOutput1.DuplicateOutput"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(22)] public HRESULT DuplicateOutput(IUnknown* pDevice, IDXGIOutputDuplication** ppOutputDuplication) { return ((delegate* unmanaged<IDXGIOutput1*, IUnknown*, IDXGIOutputDuplication**, int>)(lpVtbl[22]))((IDXGIOutput1*)Unsafe.AsPointer(ref this), pDevice, ppOutputDuplication); } public interface Interface : IDXGIOutput.Interface { [VtblIndex(19)] HRESULT GetDisplayModeList1(DXGI_FORMAT EnumFormat, uint Flags, uint* pNumModes, DXGI_MODE_DESC1* pDesc); [VtblIndex(20)] HRESULT FindClosestMatchingMode1([NativeTypeName("const DXGI_MODE_DESC1 *")] DXGI_MODE_DESC1* pModeToMatch, DXGI_MODE_DESC1* pClosestMatch, IUnknown* pConcernedDevice); [VtblIndex(21)] HRESULT GetDisplaySurfaceData1(IDXGIResource* pDestination); [VtblIndex(22)] HRESULT DuplicateOutput(IUnknown* pDevice, IDXGIOutputDuplication** ppOutputDuplication); } public partial struct Vtbl<TSelf> where TSelf : unmanaged, Interface { [NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> AddRef; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> Release; [NativeTypeName("HRESULT (const GUID &, UINT, const void *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, uint, void*, int> SetPrivateData; [NativeTypeName("HRESULT (const GUID &, const IUnknown *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, IUnknown*, int> SetPrivateDataInterface; [NativeTypeName("HRESULT (const GUID &, UINT *, void *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, uint*, void*, int> GetPrivateData; [NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, void**, int> GetParent; [NativeTypeName("HRESULT (DXGI_OUTPUT_DESC *) __attribute__((stdcall))")] public delegate* unmanaged[SuppressGCTransition]<TSelf*, DXGI_OUTPUT_DESC*, int> GetDesc; [NativeTypeName("HRESULT (DXGI_FORMAT, UINT, UINT *, DXGI_MODE_DESC *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, DXGI_FORMAT, uint, uint*, DXGI_MODE_DESC*, int> GetDisplayModeList; [NativeTypeName("HRESULT (const DXGI_MODE_DESC *, DXGI_MODE_DESC *, IUnknown *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, DXGI_MODE_DESC*, DXGI_MODE_DESC*, IUnknown*, int> FindClosestMatchingMode; [NativeTypeName("HRESULT () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, int> WaitForVBlank; [NativeTypeName("HRESULT (IUnknown *, BOOL) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, IUnknown*, BOOL, int> TakeOwnership; [NativeTypeName("void () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, void> ReleaseOwnership; [NativeTypeName("HRESULT (DXGI_GAMMA_CONTROL_CAPABILITIES *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, DXGI_GAMMA_CONTROL_CAPABILITIES*, int> GetGammaControlCapabilities; [NativeTypeName("HRESULT (const DXGI_GAMMA_CONTROL *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, DXGI_GAMMA_CONTROL*, int> SetGammaControl; [NativeTypeName("HRESULT (DXGI_GAMMA_CONTROL *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, DXGI_GAMMA_CONTROL*, int> GetGammaControl; [NativeTypeName("HRESULT (IDXGISurface *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, IDXGISurface*, int> SetDisplaySurface; [NativeTypeName("HRESULT (IDXGISurface *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, IDXGISurface*, int> GetDisplaySurfaceData; [NativeTypeName("HRESULT (DXGI_FRAME_STATISTICS *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, DXGI_FRAME_STATISTICS*, int> GetFrameStatistics; [NativeTypeName("HRESULT (DXGI_FORMAT, UINT, UINT *, DXGI_MODE_DESC1 *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, DXGI_FORMAT, uint, uint*, DXGI_MODE_DESC1*, int> GetDisplayModeList1; [NativeTypeName("HRESULT (const DXGI_MODE_DESC1 *, DXGI_MODE_DESC1 *, IUnknown *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, DXGI_MODE_DESC1*, DXGI_MODE_DESC1*, IUnknown*, int> FindClosestMatchingMode1; [NativeTypeName("HRESULT (IDXGIResource *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, IDXGIResource*, int> GetDisplaySurfaceData1; [NativeTypeName("HRESULT (IUnknown *, IDXGIOutputDuplication **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, IUnknown*, IDXGIOutputDuplication**, int> DuplicateOutput; } }
49.986441
208
0.712532
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/DirectX/shared/dxgi1_2/IDXGIOutput1.cs
14,748
C#
using System.Text; using System.Collections.Generic; using OdeToFood.Core; namespace OdeToFood.Data { public interface IRestaurantData { IEnumerable<Restaurant> GetRestaurantByName(string name); Restaurant GetById(int id); Restaurant Update(Restaurant restaurant); Restaurant Add(Restaurant restaurant); Restaurant Delete(int Id); int Commit(); } }
25.5
65
0.698529
[ "MIT" ]
ntang-flexera/OdeToFood
OdeToFood/OdeToFood.Data/IRestaurantData.cs
408
C#
using System.Collections.Generic; namespace Snowflake.Parsing { public class ListNode : ExpressionNode, IEnumerable<ExpressionNode> { public SyntaxNodeCollection<ExpressionNode> ValueExpressions { get; private set; } public ListNode() : base() { this.ValueExpressions = new SyntaxNodeCollection<ExpressionNode>(this); } public override IEnumerable<T> Find<T>() { foreach (T node in base.Find<T>()) { yield return node; } foreach (var expression in this.ValueExpressions) { foreach (T node in expression.Find<T>()) { yield return node; } } } public IEnumerator<ExpressionNode> GetEnumerator() { return this.ValueExpressions.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.ValueExpressions.GetEnumerator(); } } }
19
79
0.693364
[ "MIT" ]
smack0007/Snowflake
src/Snowflake/Parsing/ListNode.cs
876
C#
/* * kabuステーションAPI * * # 定義情報 REST APIのコード一覧、エンドポイントは下記リンク参照 - [REST APIコード一覧](../ptal/error.html) * * The version of the OpenAPI document: 1.5 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// 買気配数量4本目 /// </summary> [DataContract(Name = "BoardSuccess_Buy4")] public partial class BoardSuccessBuy4 : IEquatable<BoardSuccessBuy4>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="BoardSuccessBuy4" /> class. /// </summary> /// <param name="price">値段&lt;br&gt;※株式・先物・オプション銘柄の場合のみ.</param> /// <param name="qty">数量&lt;br&gt;※株式・先物・オプション銘柄の場合のみ.</param> public BoardSuccessBuy4(double price = default(double), double qty = default(double)) { this.Price = price; this.Qty = qty; } /// <summary> /// 値段&lt;br&gt;※株式・先物・オプション銘柄の場合のみ /// </summary> /// <value>値段&lt;br&gt;※株式・先物・オプション銘柄の場合のみ</value> [DataMember(Name = "Price", EmitDefaultValue = true)] public double Price { get; set; } /// <summary> /// 数量&lt;br&gt;※株式・先物・オプション銘柄の場合のみ /// </summary> /// <value>数量&lt;br&gt;※株式・先物・オプション銘柄の場合のみ</value> [DataMember(Name = "Qty", EmitDefaultValue = true)] public double Qty { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class BoardSuccessBuy4 {\n"); sb.Append(" Price: ").Append(Price).Append("\n"); sb.Append(" Qty: ").Append(Qty).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as BoardSuccessBuy4); } /// <summary> /// Returns true if BoardSuccessBuy4 instances are equal /// </summary> /// <param name="input">Instance of BoardSuccessBuy4 to be compared</param> /// <returns>Boolean</returns> public bool Equals(BoardSuccessBuy4 input) { if (input == null) return false; return ( this.Price == input.Price || this.Price.Equals(input.Price) ) && ( this.Qty == input.Qty || this.Qty.Equals(input.Qty) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; hashCode = hashCode * 59 + this.Price.GetHashCode(); hashCode = hashCode * 59 + this.Qty.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
32.714286
140
0.568996
[ "MIT" ]
HolyMartianEmpire/kabusapi
sample/DotNetCore/Org.OpenAPITools/src/Org.OpenAPITools/Model/BoardSuccessBuy4.cs
4,920
C#
namespace NoOrangeTrees.Redirection { public class Tuple<T1, T2> { public T1 First { get; private set; } public T2 Second { get; private set; } internal Tuple(T1 first, T2 second) { First = first; Second = second; } } public static class Tuple { public static Tuple<T1, T2> New<T1, T2>(T1 first, T2 second) { var tuple = new Tuple<T1, T2>(first, second); return tuple; } } }
23.272727
68
0.513672
[ "MIT" ]
bloodypenguin/Skylines-NoOrangeTrees
NoOrangeTrees/Redirection/Tuple.cs
514
C#
using MediatR; namespace Ordering.Application.Features.Orders.Commands.DeleteOrder { public class DeleteOrderCommand: IRequest { public int Id { get; set; } } }
17.8
67
0.713483
[ "MIT" ]
jimmyayo/AspNetMicroservices
src/Services/Ordering/Ordering.Application/Features/Orders/Commands/DeleteOrder/DeleteOrderCommand.cs
180
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Synapse.V20201201.Outputs { [OutputType] public sealed class VulnerabilityAssessmentRecurringScansPropertiesResponse { /// <summary> /// Specifies that the schedule scan notification will be is sent to the subscription administrators. /// </summary> public readonly bool? EmailSubscriptionAdmins; /// <summary> /// Specifies an array of e-mail addresses to which the scan notification is sent. /// </summary> public readonly ImmutableArray<string> Emails; /// <summary> /// Recurring scans state. /// </summary> public readonly bool? IsEnabled; [OutputConstructor] private VulnerabilityAssessmentRecurringScansPropertiesResponse( bool? emailSubscriptionAdmins, ImmutableArray<string> emails, bool? isEnabled) { EmailSubscriptionAdmins = emailSubscriptionAdmins; Emails = emails; IsEnabled = isEnabled; } } }
31.55814
109
0.658806
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Synapse/V20201201/Outputs/VulnerabilityAssessmentRecurringScansPropertiesResponse.cs
1,357
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 route53-2013-04-01.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.Route53.Model { ///<summary> /// Route53 exception /// </summary> #if !PCL && !CORECLR [Serializable] #endif public class InvalidPaginationTokenException : AmazonRoute53Exception { /// <summary> /// Constructs a new InvalidPaginationTokenException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public InvalidPaginationTokenException(string message) : base(message) {} /// <summary> /// Construct instance of InvalidPaginationTokenException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public InvalidPaginationTokenException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of InvalidPaginationTokenException /// </summary> /// <param name="innerException"></param> public InvalidPaginationTokenException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of InvalidPaginationTokenException /// </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 InvalidPaginationTokenException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of InvalidPaginationTokenException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidPaginationTokenException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !CORECLR /// <summary> /// Constructs a new instance of the InvalidPaginationTokenException 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 InvalidPaginationTokenException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
43.793814
178
0.655367
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Route53/Generated/Model/InvalidPaginationTokenException.cs
4,248
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Umbraco.Core.Models; namespace Umbraco.Web.PublishedCache { /// <summary> /// Provides access to cached medias in a specified context. /// </summary> public class ContextualPublishedMediaCache : ContextualPublishedCache<IPublishedMediaCache> { /// <summary> /// Initializes a new instance of the <see cref="ContextualPublishedMediaCache"/> class with a published media cache and a context. /// </summary> /// <param name="cache">A published media cache.</param> /// <param name="umbracoContext">A context.</param> internal ContextualPublishedMediaCache(IPublishedMediaCache cache, UmbracoContext umbracoContext) : base(umbracoContext, cache) { } } }
35.791667
140
0.670547
[ "MIT" ]
Abhith/Umbraco-CMS
src/Umbraco.Web/PublishedCache/ContextualPublishedMediaCache.cs
861
C#
// <copyright file="WeightedSnapshot.cs" company="App Metrics Contributors"> // Copyright (c) App Metrics Contributors. All rights reserved. // </copyright> using System; using System.Collections.Generic; using System.Linq; // Originally Written by Iulian Margarintescu https://github.com/etishor/Metrics.NET and will retain the same license // Ported/Refactored to .NET Standard Library by Allan Hardy namespace App.Metrics.ReservoirSampling.ExponentialDecay { public sealed class WeightedSnapshot : IReservoirSnapshot { private readonly double[] _normWeights; private readonly double[] _quantiles; private readonly long[] _values; /// <summary> /// Initializes a new instance of the <see cref="WeightedSnapshot" /> class. /// </summary> /// <param name="count">The count of all observed values.</param> /// <param name="sum">The sum of all observed values.</param> /// <param name="values">The values within the sample set.</param> public WeightedSnapshot(long count, double sum, IEnumerable<WeightedSample> values) { Count = count; Sum = sum; var sample = values.ToArray(); Array.Sort(sample, WeightedSampleComparer.Instance); var sumWeight = sample.Sum(s => s.Weight); _values = new long[sample.Length]; _normWeights = new double[sample.Length]; _quantiles = new double[sample.Length]; for (var i = 0; i < sample.Length; i++) { _values[i] = sample[i].Value; _normWeights[i] = Math.Abs(sumWeight) < 0.0001 ? 0.0d : sample[i].Weight / sumWeight; if (i > 0) { _quantiles[i] = _quantiles[i - 1] + _normWeights[i - 1]; } } MinUserValue = sample.Select(s => s.UserValue).FirstOrDefault(); MaxUserValue = sample.Select(s => s.UserValue).LastOrDefault(); } /// <inheritdoc /> public long Count { get; } public double Sum { get; } /// <inheritdoc /> public long Max => _values.LastOrDefault(); /// <inheritdoc /> public string MaxUserValue { get; } /// <inheritdoc /> public double Mean { get { if (_values.Length == 0) { return 0.0; } double sum = 0; for (var i = 0; i < _values.Length; i++) { sum += _values[i] * _normWeights[i]; } return sum; } } /// <inheritdoc /> public double Median => GetValue(0.5d); /// <inheritdoc /> public long Min => _values.FirstOrDefault(); /// <inheritdoc /> public string MinUserValue { get; } /// <inheritdoc /> public double Percentile75 => GetValue(0.75d); /// <inheritdoc /> public double Percentile95 => GetValue(0.95d); /// <inheritdoc /> public double Percentile98 => GetValue(0.98d); /// <inheritdoc /> public double Percentile99 => GetValue(0.99d); /// <inheritdoc /> public double Percentile999 => GetValue(0.999d); /// <inheritdoc /> public int Size => _values.Length; /// <inheritdoc /> public double StdDev { get { if (Size <= 1) { return 0; } var mean = Mean; double variance = 0; for (var i = 0; i < _values.Length; i++) { var diff = _values[i] - mean; variance += _normWeights[i] * diff * diff; } return Math.Sqrt(variance); } } /// <inheritdoc /> public IEnumerable<long> Values => _values; /// <inheritdoc /> public double GetValue(double quantile) { if (quantile < 0.0 || quantile > 1.0 || double.IsNaN(quantile)) { throw new ArgumentException($"{quantile} is not in [0..1]"); } if (Size == 0) { return 0; } var posx = Array.BinarySearch(_quantiles, quantile); if (posx < 0) { posx = ~posx - 1; } if (posx < 1) { return _values[0]; } return posx >= _values.Length ? _values[_values.Length - 1] : _values[posx]; } private sealed class WeightedSampleComparer : IComparer<WeightedSample> { public static readonly IComparer<WeightedSample> Instance = new WeightedSampleComparer(); public int Compare(WeightedSample x, WeightedSample y) { return Comparer<long>.Default.Compare(x.Value, y.Value); } } } }
29.725146
127
0.506
[ "Apache-2.0" ]
8adre/AppMetrics
src/Core/src/App.Metrics.Core/ReservoirSampling/ExponentialDecay/WeightedSnapshot.cs
5,085
C#
using System; using System.Data; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using ClickHouse.Client.ADO; using ClickHouse.Client.Utility; using NUnit.Framework; namespace ClickHouse.Client.Tests { public class ConnectionTests : AbstractConnectionTestFixture { [Test] public async Task ShouldCreateConnectionWithProvidedHttpClient() { using var httpClientHandler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; using var httpClient = new HttpClient(httpClientHandler); using var connection = new ClickHouseConnection(TestUtilities.GetConnectionStringBuilder().ToString(), httpClient); await connection.OpenAsync(); Assert.IsNotEmpty(connection.ServerVersion); } [Test] public void ShouldThrowExceptionOnInvalidHttpClient() { using var httpClient = new HttpClient(); // No decompression handler using var connection = new ClickHouseConnection(TestUtilities.GetConnectionStringBuilder().ToString(), httpClient); Assert.Throws<InvalidOperationException>(() => connection.Open()); } [Test] public void ShouldParseCustomParameter() { using var connection = new ClickHouseConnection("set_my_parameter=aaa"); Assert.AreEqual("aaa", connection.CustomSettings["my_parameter"]); } [Test] public void ShouldEmitCustomParameter() { using var connection = new ClickHouseConnection(); connection.CustomSettings.Add("my_parameter", "aaa"); Assert.That(connection.ConnectionString, Contains.Substring("set_my_parameter=aaa")); } [Test] public void ShouldConnectToServer() { using var connection = TestUtilities.GetTestClickHouseConnection(); connection.Open(); Assert.IsNotEmpty(connection.ServerVersion); Assert.AreEqual(ConnectionState.Open, connection.State); connection.Close(); Assert.AreEqual(ConnectionState.Closed, connection.State); } [Test] public async Task ShouldPostQueryAsync() { using var response = await connection.PostSqlQueryAsync("SELECT 1 FORMAT TabSeparated", CancellationToken.None); var result = await response.Content.ReadAsStringAsync(); Assert.AreEqual("1", result.Trim()); } [Test] public async Task TimeoutShouldCancelConnection() { var builder = TestUtilities.GetConnectionStringBuilder(); builder.UseSession = false; builder.Compression = true; builder.Timeout = TimeSpan.FromMilliseconds(5); var connection = new ClickHouseConnection(builder.ToString()); try { var task = connection.ExecuteScalarAsync("SELECT sleep(1)"); _ = await task; Assert.Fail("The task should have been cancelled before completion"); } catch (TaskCanceledException) { /* Expected: task cancelled */ } } [Test] [Ignore("TODO")] public void ShouldFetchSchema() { var schema = connection.GetSchema(); Assert.IsNotNull(schema); } [Test] [Ignore("TODO")] public void ShouldFetchSchemaTables() { var schema = connection.GetSchema("Tables"); Assert.IsNotNull(schema); } [Test] public void ShouldFetchSchemaDatabaseColumns() { var schema = connection.GetSchema("Columns", new[] { "system" }); Assert.IsNotNull(schema); CollectionAssert.IsSubsetOf(new[] { "Database", "Table", "DataType", "ProviderType" }, GetColumnNames(schema)); } [Test] public void ShouldFetchSchemaTableColumns() { var schema = connection.GetSchema("Columns", new[] { "system", "functions" }); Assert.IsNotNull(schema); CollectionAssert.IsSubsetOf(new[] { "Database", "Table", "DataType", "ProviderType" }, GetColumnNames(schema)); } [Test] public void ChangeDatabaseShouldChangeDatabase() { // Using separate connection instance here to avoid conflicting with other tests using var conn = TestUtilities.GetTestClickHouseConnection(); conn.ChangeDatabase("system"); Assert.AreEqual("system", conn.Database); conn.ChangeDatabase("default"); Assert.AreEqual("default", conn.Database); } private static string[] GetColumnNames(DataTable table) => table.Columns.Cast<DataColumn>().Select(dc => dc.ColumnName).ToArray(); } }
37.261194
152
0.618466
[ "MIT" ]
YahuiWong/ClickHouse.Client
ClickHouse.Client.Tests/ConnectionTests.cs
4,993
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Framework.Threading; using osu.Game.Beatmaps; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Rulesets; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays.BeatmapListing { public class BeatmapListingFilterControl : CompositeDrawable { /// <summary> /// Fired when a search finishes. Contains only new items in the case of pagination. /// </summary> public Action<List<BeatmapSetInfo>> SearchFinished; /// <summary> /// Fired when search criteria change. /// </summary> public Action SearchStarted; /// <summary> /// True when pagination has reached the end of available results. /// </summary> private bool noMoreResults; /// <summary> /// The current page fetched of results (zero index). /// </summary> public int CurrentPage { get; private set; } private readonly BeatmapListingSearchControl searchControl; private readonly BeatmapListingSortTabControl sortControl; private readonly Box sortControlBackground; private ScheduledDelegate queryChangedDebounce; private SearchBeatmapSetsRequest getSetsRequest; private SearchBeatmapSetsResponse lastResponse; [Resolved] private IAPIProvider api { get; set; } [Resolved] private RulesetStore rulesets { get; set; } public BeatmapListingFilterControl() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChild = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(0, 10), Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Masking = true, EdgeEffect = new EdgeEffectParameters { Colour = Color4.Black.Opacity(0.25f), Type = EdgeEffectType.Shadow, Radius = 3, Offset = new Vector2(0f, 1f), }, Child = searchControl = new BeatmapListingSearchControl(), }, new Container { RelativeSizeAxes = Axes.X, Height = 40, Children = new Drawable[] { sortControlBackground = new Box { RelativeSizeAxes = Axes.Both }, sortControl = new BeatmapListingSortTabControl { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Margin = new MarginPadding { Left = 20 } } } } } }; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { sortControlBackground.Colour = colourProvider.Background5; } protected override void LoadComplete() { base.LoadComplete(); var sortCriteria = sortControl.Current; var sortDirection = sortControl.SortDirection; searchControl.Query.BindValueChanged(query => { sortCriteria.Value = string.IsNullOrEmpty(query.NewValue) ? SortCriteria.Ranked : SortCriteria.Relevance; sortDirection.Value = SortDirection.Descending; queueUpdateSearch(true); }); searchControl.Ruleset.BindValueChanged(_ => queueUpdateSearch()); searchControl.Category.BindValueChanged(_ => queueUpdateSearch()); searchControl.Genre.BindValueChanged(_ => queueUpdateSearch()); searchControl.Language.BindValueChanged(_ => queueUpdateSearch()); sortCriteria.BindValueChanged(_ => queueUpdateSearch()); sortDirection.BindValueChanged(_ => queueUpdateSearch()); } public void TakeFocus() => searchControl.TakeFocus(); /// <summary> /// Fetch the next page of results. May result in a no-op if a fetch is already in progress, or if there are no results left. /// </summary> public void FetchNextPage() { // there may be no results left. if (noMoreResults) return; // there may already be an active request. if (getSetsRequest != null) return; if (lastResponse != null) CurrentPage++; performRequest(); } private void queueUpdateSearch(bool queryTextChanged = false) { SearchStarted?.Invoke(); resetSearch(); queryChangedDebounce = Scheduler.AddDelayed(() => { resetSearch(); FetchNextPage(); }, queryTextChanged ? 500 : 100); } private void performRequest() { getSetsRequest = new SearchBeatmapSetsRequest( searchControl.Query.Value, searchControl.Ruleset.Value, lastResponse?.Cursor, searchControl.Category.Value, sortControl.Current.Value, sortControl.SortDirection.Value, searchControl.Genre.Value, searchControl.Language.Value); getSetsRequest.Success += response => { var sets = response.BeatmapSets.Select(responseJson => responseJson.ToBeatmapSet(rulesets)).ToList(); if (sets.Count == 0) noMoreResults = true; if (CurrentPage == 0) searchControl.BeatmapSet = sets.FirstOrDefault(); lastResponse = response; getSetsRequest = null; SearchFinished?.Invoke(sets); }; api.Queue(getSetsRequest); } private void resetSearch() { noMoreResults = false; CurrentPage = 0; lastResponse = null; getSetsRequest?.Cancel(); getSetsRequest = null; queryChangedDebounce?.Cancel(); } protected override void Dispose(bool isDisposing) { resetSearch(); base.Dispose(isDisposing); } } }
33.897321
134
0.521006
[ "MIT" ]
BananeVolante/osu
osu.Game/Overlays/BeatmapListing/BeatmapListingFilterControl.cs
7,372
C#
using SimpleRPG.Core; using SimpleRPG.GameObjects.Characters; using System; using System.Text; namespace SimpleRPG { class Program { private GODataBase dataBase; private World mainWorld; static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; Program game = new Program(); game.Run(); } public void Run() { DrawingBuffer mainBuffer = new DrawingBuffer(); dataBase = new GODataBase(); dataBase.Load(); mainWorld = new World("world1", dataBase); mainWorld.Load(); mainWorld.player = new Player(); mainWorld.player.SetCurrentRoom(mainWorld.GetRoomAt(0, 0)); mainWorld.player.SetPosition(30, 11); ConsoleKey input; while ((input = Console.ReadKey(true).Key) != ConsoleKey.Q) { mainWorld.player.Step(input); mainBuffer.Clear(); mainBuffer.DrawAreaAt(mainWorld.BuildRoomImage(mainWorld.player.GetCurrentRoom()), 0, 0); mainBuffer.DrawTextAt("Name: " + mainWorld.player.GetName(), 35, 2); mainBuffer.DrawTextAt("Position X: " + mainWorld.player.GetPosition().X, 35, 3); mainBuffer.DrawTextAt("Position Y: " + mainWorld.player.GetPosition().Y, 35, 4); mainBuffer.Render(); } } } }
27.773585
105
0.560462
[ "Apache-2.0" ]
QuantMad/SimpleRPG
SimpleRPG/Program.cs
1,474
C#
using System.Collections; using UnityEngine; [CreateAssetMenu(fileName = "New Skill", menuName = "Skill/Spawn Object Skill")] public class SpawnObjectSkill : Skill, ImplosionListener { public float distanceToTeleport; public bool isInmediate = false; public GameObject[] targetObjects; public GameObject targetParticles; private Vector3 parentObjectPosition; private Vector2 targetPosition; public override void initSkill(GameObject skillObject) { } public override void performSkill(int direction) { targetPosition = parentObjectPosition; targetPosition.x = targetPosition.x + distanceToTeleport * direction; ImplosionEffect implosionEffect = Instantiate(targetParticles, targetPosition, Quaternion.identity).GetComponent<ImplosionEffect>(); if (implosionEffect != null) { implosionEffect.callback = this; } SoundManager.instance.Play("Wall_1"); } public override IEnumerator performCorroutineSkill(int direction) { yield return null; } public override void setPosition(Vector3 position) { parentObjectPosition = position; } public void onStartImplosion() { } public void onFinishImplosion() { foreach (var targetObject in targetObjects) { Instantiate(targetObject, targetPosition, Quaternion.identity); SoundManager.instance.Play("Wall_2"); } } }
25.79661
140
0.669514
[ "MIT" ]
betomaluje/unity-experiments
Kirby Clone/Kirby Clone/Assets/Scripts/Skills/SpawnObjectSkill.cs
1,524
C#
/** * Copyright 2015 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: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_imm.Domainvalue { public interface GISPositionAccuracyTierCode : Code { } }
38.071429
83
0.714822
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab-r02_04_03_imm/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_imm/Domainvalue/GISPositionAccuracyTierCode.cs
1,066
C#
using System; using System.Collections.Generic; using System.Text; using System.IO; using LUA_NUMBER = System.Double; namespace SharpLua { partial class Lua { /// <summary> /// Class used to simulate/emulate fscanf(f, "%lf", ...) /// </summary> class NumberReader { readonly Stream s; LUA_NUMBER result; readonly StringBuilder sb = new StringBuilder(10); // a reasonable default, I'd say bool neg = false; int inchar_skipws() { int ch; do { ch = fgetc(s); } while (ch >= 0 && char.IsWhiteSpace((char)ch)); return ch; } int inchar() { int ch = fgetc(s); return ch; } /// <summary> /// Attempts to read a number from 's' with the same semantics as /// fscanf(s, "%lf", &n) /// </summary> /// <param name="s">Stream to read from</param> /// <param name="n">Where to store </param> /// <returns>1 if a value was successfully read /// 0 if no value was successfully read /// -1 if no value was successfuly read *and* we hit EOF</returns> public static int ReadNumber(Stream s, out LUA_NUMBER n) { if (!s.CanRead) { n = default(LUA_NUMBER); return -1; } NumberReader nr = new NumberReader(s); int answer = nr.ReadNumber(); n = nr.result; return answer; } /// <summary> /// Constructs a NumberReader object that will attempt to read 's' with the same semantics as /// fscanf(s, "%lf", &foo) /// </summary> /// <param name="s"></param> private NumberReader(Stream s) { this.s = s; } int ReadNumber() { return ReadNumberImpl(); } /// <summary> /// Reads NAN and returns 1 (if it was actually NAN) or 0 (if it wasn't, like NAx) /// </summary> /// <returns></returns> int ReadNAN() { int ch = inchar(); if (ch < 0 || char.ToLower((char)ch) != 'a') return 0; ch = inchar(); if (ch < 0 || char.ToLower((char)ch) != 'n') return 0; result = double.NaN; return 1; } /// <summary> /// Reads INF and returns 1 (if it was actually INF) or 0 (if it wasn't, like INx) /// </summary> /// <returns></returns> int ReadINF() { int ch = inchar(); if (ch < 0 || char.ToLower((char)ch) != 'n') return 0; ch = inchar(); if (ch < 0 || char.ToLower((char)ch) != 'f') return 0; ch = inchar(); // this bit is tricky: it might be INF or it might be spelled out as INFINITY if (ch >= 0) { if (char.ToLower((char)ch) == 'i') { ch = inchar(); if (ch < 0 || char.ToLower((char)ch) != 'n') return 0; ch = inchar(); if (ch < 0 || char.ToLower((char)ch) != 'i') return 0; ch = inchar(); if (ch < 0 || char.ToLower((char)ch) != 't') return 0; ch = inchar(); if (ch < 0 || char.ToLower((char)ch) != 'y') return 0; } else ungetc(ch, s); } result = neg ? double.NegativeInfinity : double.PositiveInfinity; return 1; } static bool isdigit(int ch) { return (ch >= '0' && ch < '9'); } static bool isdigit(char ch) { return (ch >= '0' && ch < '9'); } static bool isxdigit(int ch) { return (ch >= '0' && ch < '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'); } static bool isxdigit(char ch) { return (ch >= '0' && ch < '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'); } static double getdigitvalue(char ch) { if (ch >= '0' && ch < '9') return ch - '0'; if (ch >= 'A' && ch <= 'Z') return ch - ('A' - 10); if (ch >= 'a' && ch <= 'z') return ch - ('a' - 10); return double.NaN; } /// <summary> /// Given that ch is '0'..'9', returns ch. /// </summary> /// <param name="ch"></param> /// <returns></returns> static int getintvalue(char ch) { return (int)(ch & 0x0F); } enum ReadState { /// <summary> /// Expecting: digit or '.' /// </summary> FirstDigit, /// <summary> /// Expecting: digit, '.', or 'E'/'e' /// </summary> IntPart, /// <summary> /// Expecting digit or 'E'/'e' /// </summary> FracPart, /// <summary> /// Expecting digit or '+' or '-' /// </summary> ExpFirstDigit, /// <summary> /// Expecting digit /// </summary> Exponent, } int ReadNumberImpl() { int ch1 = inchar_skipws(); if (ch1 < 0) return -1; char ch = (char)ch1; // read a possible sign if (ch == '+' || ch == '-') { neg = (ch == '-'); ch1 = inchar(); if (ch1 < 0) return 0; ch = (char)ch1; } // handle NAN and INF if (char.ToLower(ch) == 'n') return ReadNAN(); if (char.ToLower(ch) == 'i') return ReadINF(); // okay, at this point, I am expecting one of the following: // decimal point ('.') or digit ('0'-'9') if (!(ch == '.' || isdigit(ch))) { // wait, this character is no good! // We must pretend we never actually read it... ungetc(ch, s); return 0; } bool hex = false; bool any_digits = false; ReadState state = ReadState.FirstDigit; double radix = 10.0; double value = 0.0; double frac_multiplier = 0.1; int exp = 0; bool expneg = false; if (ch == '0') { any_digits = true; state = ReadState.IntPart; // consider it a valid read at this point // Well, this won't have any effect on the *value*, although that changes our expectation of the rest // of the string... ch1 = inchar(); ch = (char)ch1; if (tolower(ch) == 'x') { frac_multiplier = 1f / 16; // activate hexadecimal magic hex = true; radix = 16.0; ch1 = inchar(); ch = (char)ch1; any_digits = false; state = ReadState.FirstDigit; } } for (; ch1 >= 0; ch1 = inchar(), ch = (char)ch1) { if (state == ReadState.FirstDigit) { if (ch == '.') { state = ReadState.FracPart; continue; } if (isdigit(ch) || (hex && isxdigit(ch))) { state = ReadState.IntPart; any_digits = true; value = value * radix + getdigitvalue(ch); continue; } break; // out of for } else if (state == ReadState.IntPart) { if (ch == '.') { state = ReadState.FracPart; continue; } if (isdigit(ch) || (hex && isxdigit(ch))) { any_digits = true; value = value * radix + getdigitvalue(ch); continue; } // note that the following will NEVER trigger if 'hex' is set, because the 'isxdigit' check // above will eat it if (tolower(ch) == 'e') { state = ReadState.ExpFirstDigit; continue; } break; } else if (state == ReadState.FracPart) { if (isdigit(ch) || (hex && isxdigit(ch))) { any_digits = true; value = value + frac_multiplier * getdigitvalue(ch); frac_multiplier /= radix; continue; } // note that the following will NEVER trigger if 'hex' is set, because the 'isxdigit' check // above will eat it if (tolower(ch) == 'e') { state = ReadState.ExpFirstDigit; continue; } break; } else if (state == ReadState.ExpFirstDigit) { if (ch == '+' || ch == '-') { expneg = (ch == '-'); state = ReadState.Exponent; continue; } if (isdigit(ch)) { state = ReadState.Exponent; exp = getintvalue(ch); continue; } break; } else /* if (state == ReadState.Exponent) */ { if (isdigit(ch)) { exp = exp * 10 + getintvalue(ch); continue; } break; } } // for // un-get the last character we read, assuming there was one // (this will be ignored if the last "character" we read was EOF) ungetc(ch1, s); if (!any_digits) return 0; // uhh, no good, man if (exp != 0) { if (expneg) exp = -exp; value *= Math.Pow(10f, exp); } if (neg) value = -value; result = value; return 1; // success! } // ReadNumberImpl } // class NumberReader } // (partial) class Lua }
37.750809
133
0.363138
[ "MIT" ]
Stevie-O/SharpLua
SharpLua/Support/NumberReader.cs
11,667
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------ using System.Linq; using Microsoft.OData.Edm; using Microsoft.OpenApi.OData.Edm; using Microsoft.OpenApi.OData.Tests; using Xunit; namespace Microsoft.OpenApi.OData.Operation.Tests; public class ODataTypeCastGetOperationHandlerTests { private readonly ODataTypeCastGetOperationHandler _operationHandler = new (); [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] public void CreateODataTypeCastGetOperationReturnsCorrectOperationForCollectionNavigationProperty(bool enableOperationId, bool enablePagination) {// ../People/{id}/Friends/Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee // Arrange IEdmModel model = EdmModelHelper.TripServiceModel; OpenApiConvertSettings settings = new() { EnableOperationId = enableOperationId, EnablePagination = enablePagination, }; ODataContext context = new(model, settings); IEdmEntitySet people = model.EntityContainer.FindEntitySet("People"); Assert.NotNull(people); IEdmEntityType person = model.SchemaElements.OfType<IEdmEntityType>().First(c => c.Name == "Person"); IEdmEntityType employee = model.SchemaElements.OfType<IEdmEntityType>().First(c => c.Name == "Employee"); IEdmNavigationProperty navProperty = person.DeclaredNavigationProperties().First(c => c.Name == "Friends"); ODataPath path = new(new ODataNavigationSourceSegment(people), new ODataKeySegment(people.EntityType()), new ODataNavigationPropertySegment(navProperty), new ODataTypeCastSegment(employee)); // Act var operation = _operationHandler.CreateOperation(context, path); // Assert Assert.NotNull(operation); Assert.Equal("Get the items of type Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee in the Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person collection", operation.Summary); Assert.NotNull(operation.Tags); var tag = Assert.Single(operation.Tags); Assert.Equal("Person.Employee", tag.Name); Assert.Single(tag.Extensions); Assert.NotNull(operation.Parameters); Assert.Equal(9, operation.Parameters.Count); Assert.Null(operation.RequestBody); if(enablePagination) Assert.Single(operation.Extensions); Assert.Equal(2, operation.Responses.Count); Assert.Equal(new string[] { "200", "default" }, operation.Responses.Select(e => e.Key)); if (enableOperationId) { Assert.Equal("Get.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person.Items.As.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee-11bf", operation.OperationId); } else { Assert.Null(operation.OperationId); } Assert.True(operation.Responses["200"].Content["application/json"].Schema.Properties.ContainsKey("value")); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] public void CreateODataTypeCastGetOperationReturnsCorrectOperationForCollectionNavigationPropertyId(bool enableOperationId, bool enablePagination) {// ../People/{id}/Friends/{id}/Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee/ // Arrange IEdmModel model = EdmModelHelper.TripServiceModel; OpenApiConvertSettings settings = new() { EnableOperationId = enableOperationId, EnablePagination = enablePagination, }; ODataContext context = new(model, settings); IEdmEntitySet people = model.EntityContainer.FindEntitySet("People"); Assert.NotNull(people); IEdmEntityType person = model.SchemaElements.OfType<IEdmEntityType>().First(c => c.Name == "Person"); IEdmEntityType employee = model.SchemaElements.OfType<IEdmEntityType>().First(c => c.Name == "Employee"); IEdmNavigationProperty navProperty = person.DeclaredNavigationProperties().First(c => c.Name == "Friends"); ODataPath path = new(new ODataNavigationSourceSegment(people), new ODataKeySegment(people.EntityType()), new ODataNavigationPropertySegment(navProperty), new ODataKeySegment(people.EntityType()), new ODataTypeCastSegment(employee)); // Act var operation = _operationHandler.CreateOperation(context, path); // Assert Assert.NotNull(operation); Assert.Equal("Get the item of type Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person as Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee", operation.Summary); Assert.NotNull(operation.Tags); var tag = Assert.Single(operation.Tags); Assert.Equal("Person.Employee", tag.Name); Assert.Empty(tag.Extensions); Assert.NotNull(operation.Parameters); Assert.Equal(4, operation.Parameters.Count); //select, expand, id, id Assert.Null(operation.RequestBody); if(enablePagination) Assert.Empty(operation.Extensions); Assert.Equal(2, operation.Responses.Count); Assert.Equal(new string[] { "200", "default" }, operation.Responses.Select(e => e.Key)); if (enableOperationId) { Assert.Equal("Get.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person.Item.As.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee-11bf", operation.OperationId); } else { Assert.Null(operation.OperationId); } Assert.False(operation.Responses["200"].Content["application/json"].Schema.Properties.ContainsKey("value")); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] public void CreateODataTypeCastGetOperationReturnsCorrectOperationForEntitySet(bool enableOperationId, bool enablePagination) {// .../People/Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee // Arrange IEdmModel model = EdmModelHelper.TripServiceModel; OpenApiConvertSettings settings = new() { EnableOperationId = enableOperationId, EnablePagination = enablePagination, }; ODataContext context = new(model, settings); IEdmEntitySet people = model.EntityContainer.FindEntitySet("People"); Assert.NotNull(people); IEdmEntityType employee = model.SchemaElements.OfType<IEdmEntityType>().First(c => c.Name == "Employee"); ODataPath path = new(new ODataNavigationSourceSegment(people), new ODataTypeCastSegment(employee)); // Act var operation = _operationHandler.CreateOperation(context, path); // Assert Assert.NotNull(operation); Assert.Equal("Get the items of type Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee in the Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person collection", operation.Summary); Assert.NotNull(operation.Tags); var tag = Assert.Single(operation.Tags); Assert.Equal("Person.Employee", tag.Name); Assert.Single(tag.Extensions); Assert.NotNull(operation.Parameters); Assert.Equal(8, operation.Parameters.Count); Assert.Null(operation.RequestBody); if(enablePagination) Assert.Single(operation.Extensions); Assert.Equal(2, operation.Responses.Count); Assert.Equal(new string[] { "200", "default" }, operation.Responses.Select(e => e.Key)); if (enableOperationId) { Assert.Equal("Get.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person.Items.As.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee-013a", operation.OperationId); } else { Assert.Null(operation.OperationId); } Assert.True(operation.Responses["200"].Content["application/json"].Schema.Properties.ContainsKey("value")); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] public void CreateODataTypeCastGetOperationReturnsCorrectOperationForEntitySetId(bool enableOperationId, bool enablePagination) {// .../People/{id}/Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee // Arrange IEdmModel model = EdmModelHelper.TripServiceModel; OpenApiConvertSettings settings = new() { EnableOperationId = enableOperationId, EnablePagination = enablePagination, }; ODataContext context = new(model, settings); IEdmEntitySet people = model.EntityContainer.FindEntitySet("People"); Assert.NotNull(people); IEdmEntityType person = model.SchemaElements.OfType<IEdmEntityType>().First(c => c.Name == "Person"); IEdmEntityType employee = model.SchemaElements.OfType<IEdmEntityType>().First(c => c.Name == "Employee"); ODataPath path = new(new ODataNavigationSourceSegment(people), new ODataKeySegment(people.EntityType()), new ODataTypeCastSegment(employee)); // Act var operation = _operationHandler.CreateOperation(context, path); // Assert Assert.NotNull(operation); Assert.Equal("Get the item of type Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person as Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee", operation.Summary); Assert.NotNull(operation.Tags); var tag = Assert.Single(operation.Tags); Assert.Equal("Person.Employee", tag.Name); Assert.Empty(tag.Extensions); Assert.NotNull(operation.Parameters); Assert.Equal(3, operation.Parameters.Count); //select, expand, id Assert.Null(operation.RequestBody); if(enablePagination) Assert.Empty(operation.Extensions); Assert.Equal(2, operation.Responses.Count); Assert.Equal(new string[] { "200", "default" }, operation.Responses.Select(e => e.Key)); if (enableOperationId) { Assert.Equal("Get.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person.Item.As.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee-317b", operation.OperationId); } else { Assert.Null(operation.OperationId); } Assert.False(operation.Responses["200"].Content["application/json"].Schema.Properties.ContainsKey("value")); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] public void CreateODataTypeCastGetOperationReturnsCorrectOperationForSingleNavigationproperty(bool enableOperationId, bool enablePagination) {// .../People/{id}/BestFriend/Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee // Arrange IEdmModel model = EdmModelHelper.TripServiceModel; OpenApiConvertSettings settings = new() { EnableOperationId = enableOperationId, EnablePagination = enablePagination, }; ODataContext context = new(model, settings); IEdmEntitySet people = model.EntityContainer.FindEntitySet("People"); Assert.NotNull(people); IEdmEntityType person = model.SchemaElements.OfType<IEdmEntityType>().First(c => c.Name == "Person"); IEdmEntityType employee = model.SchemaElements.OfType<IEdmEntityType>().First(c => c.Name == "Employee"); IEdmNavigationProperty navProperty = person.DeclaredNavigationProperties().First(c => c.Name == "BestFriend"); ODataPath path = new(new ODataNavigationSourceSegment(people), new ODataKeySegment(people.EntityType()), new ODataNavigationPropertySegment(navProperty), new ODataTypeCastSegment(employee)); // Act var operation = _operationHandler.CreateOperation(context, path); // Assert Assert.NotNull(operation); Assert.Equal("Get the item of type Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person as Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee", operation.Summary); Assert.NotNull(operation.Tags); var tag = Assert.Single(operation.Tags); Assert.Equal("Person.Employee", tag.Name); Assert.Empty(tag.Extensions); Assert.NotNull(operation.Parameters); Assert.Equal(3, operation.Parameters.Count); //select, expand, id Assert.Null(operation.RequestBody); if(enablePagination) Assert.Empty(operation.Extensions); Assert.Equal(2, operation.Responses.Count); Assert.Equal(new string[] { "200", "default" }, operation.Responses.Select(e => e.Key)); if (enableOperationId) { Assert.Equal("Get.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person.Item.As.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee-7188", operation.OperationId); } else { Assert.Null(operation.OperationId); } Assert.False(operation.Responses["200"].Content["application/json"].Schema.Properties.ContainsKey("value")); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] public void CreateODataTypeCastGetOperationReturnsCorrectOperationForSingleton(bool enableOperationId, bool enablePagination) {// .../Me/Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee // Arrange IEdmModel model = EdmModelHelper.TripServiceModel; OpenApiConvertSettings settings = new() { EnableOperationId = enableOperationId, EnablePagination = enablePagination, }; ODataContext context = new(model, settings); IEdmSingleton me = model.EntityContainer.FindSingleton("Me"); Assert.NotNull(me); IEdmEntityType employee = model.SchemaElements.OfType<IEdmEntityType>().First(c => c.Name == "Employee"); ODataPath path = new(new ODataNavigationSourceSegment(me), new ODataTypeCastSegment(employee)); // Act var operation = _operationHandler.CreateOperation(context, path); // Assert Assert.NotNull(operation); Assert.Equal("Get the item of type Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person as Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee", operation.Summary); Assert.NotNull(operation.Tags); var tag = Assert.Single(operation.Tags); Assert.Equal("Person.Employee", tag.Name); Assert.Empty(tag.Extensions); Assert.NotNull(operation.Parameters); Assert.Equal(2, operation.Parameters.Count); //select, expand Assert.Null(operation.RequestBody); if(enablePagination) Assert.Empty(operation.Extensions); Assert.Equal(2, operation.Responses.Count); Assert.Equal(new string[] { "200", "default" }, operation.Responses.Select(e => e.Key)); if (enableOperationId) { Assert.Equal("Get.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Person.Item.As.Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee-bd18", operation.OperationId); } else { Assert.Null(operation.OperationId); } Assert.False(operation.Responses["200"].Content["application/json"].Schema.Properties.ContainsKey("value")); } }
47.985755
207
0.644363
[ "MIT" ]
nickmcummins/OpenAPI.NET.OData
test/Microsoft.OpenAPI.OData.Reader.Tests/Operation/ODataTypeCastGetOperationHandlerTests.cs
16,845
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("viewer_csharp_custom.properties")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("viewer_csharp_custom.properties")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0f6c21ac-c908-4778-ab23-295acf2aa0da")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.722222
85
0.735664
[ "MIT" ]
augustogoncalves/viewer-csharp-custom.properties
viewer-csharp-custom.properties/Properties/AssemblyInfo.cs
1,433
C#
namespace EnoCore.Models { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection.Metadata.Ecma335; using System.Text; using System.Text.Json.Serialization; public record EnoLogMessage( string? Tool, string Severity, long SeverityLevel, string? Timestamp, string? Module, string? Function, string? Flag, long? VariantId, string? TaskChainId, long? TaskId, long? CurrentRoundId, long? RelatedRoundId, string Message, string? TeamName, long? TeamId, string? ServiceName, string? Method, string? Type = "infrastructure"); }
25.566667
46
0.586701
[ "MIT" ]
DanielHabenicht/EnoEngine
EnoCore/Models/EnoLogMessage.cs
769
C#
using System; using System.Globalization; using System.Windows.Data; using System.Windows.Markup; namespace SpectrumAnalyzer.Converters { /// <summary> /// A base value converter that allows direct xaml usage /// </summary> /// <typeparam name="T"></typeparam> public abstract class BaseValueConverter<T> : MarkupExtension, IValueConverter where T : class, new() { private static T mConverter = null; //a static single instance of this value converter public override object ProvideValue(IServiceProvider serviceProvider) { return mConverter ?? (mConverter = new T()); } public abstract object Convert(object value, Type targetType, object parameter, CultureInfo culture); public abstract object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture); } }
31.607143
113
0.694915
[ "MIT" ]
Grahmification/SpectrumAnalyzer
SpectrumAnalyzer/Converters/BaseValueConverter.cs
887
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 medialive-2017-10-14.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.MediaLive.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MediaLive.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for OutputGroup Object /// </summary> public class OutputGroupUnmarshaller : IUnmarshaller<OutputGroup, XmlUnmarshallerContext>, IUnmarshaller<OutputGroup, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> OutputGroup IUnmarshaller<OutputGroup, 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 OutputGroup Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; OutputGroup unmarshalledObject = new OutputGroup(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Name = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("outputGroupSettings", targetDepth)) { var unmarshaller = OutputGroupSettingsUnmarshaller.Instance; unmarshalledObject.OutputGroupSettings = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("outputs", targetDepth)) { var unmarshaller = new ListUnmarshaller<Output, OutputUnmarshaller>(OutputUnmarshaller.Instance); unmarshalledObject.Outputs = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static OutputGroupUnmarshaller _instance = new OutputGroupUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static OutputGroupUnmarshaller Instance { get { return _instance; } } } }
35.557692
146
0.621958
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/MediaLive/Generated/Model/Internal/MarshallTransformations/OutputGroupUnmarshaller.cs
3,698
C#
using System; namespace SpotiFire.SpotifyLib { public interface ITrackAndOffset { ITrack Track { get; } TimeSpan Offset { get; } } }
14.818182
36
0.613497
[ "MIT" ]
Jono120/PlayMe
SpotiFire.SpotifyLib/Interfaces/ITrackAndOffset.cs
165
C#
using CalendarPlus.API.Middlewares; using FluentValidation.AspNetCore; using Microsoft.Extensions.DependencyInjection; namespace CalendarPlus.Registers.Validators { public static class LoadValidators { public static void Load(IServiceCollection services) { services .AddMvc(options => { options.Filters.Add(new ModelValidationFilter()); }) .AddFluentValidation(setup => { setup.RegisterValidatorsFromAssemblyContaining<Startup>(); }); } } }
28.409091
78
0.576
[ "MIT" ]
luca0898/calendar-plus
new_project/backend/CalendarPlus.API/Registers/Validators/LoadValidators.cs
625
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Collections; namespace nin { class Program { static void Main(string[] args) { StreamReader in_f = new StreamReader("input.txt"); StreamWriter out_f = new StreamWriter("output.txt"); int matrix = Convert.ToInt32(in_f.ReadLine()); string matrix_zna = in_f.ReadLine(); string[] words = matrix_zna.Split(' '); int[] mas = new int[matrix+1]; int b = 0; for(int i = 1; i <= matrix; i++) { mas[i] = Convert.ToInt32(words[b]); b++; } for (int i = matrix;i >= 2;) { if (mas[i / 2] <= mas[i]) { i--; } else { out_f.WriteLine("No"); out_f.Close(); Environment.Exit(0); } } out_f.WriteLine("Yes"); out_f.Close(); } } }
26.734694
65
0.39084
[ "Unlicense" ]
godnoTA/acm.bsu.by
3. Структуры данных/55. Бинарная куча #3565/[OK]189303.cs
1,310
C#
/* * @(#)Function3Arg.cs 5.0.0 2022-03-20 * * You may use this software under the condition of "Simplified BSD License" * * Copyright 2010-2022 MARIUSZ GROMADA. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of MARIUSZ GROMADA. * * If you have any questions/bugs feel free to contact: * * Mariusz Gromada * mariuszgromada.org@gmail.com * http://mathparser.org * http://mathspace.pl * http://janetsudoku.mariuszgromada.org * http://github.com/mariuszgromada/MathParser.org-mXparser * http://mariuszgromada.github.io/MathParser.org-mXparser * http://mxparser.sourceforge.net * http://bitbucket.org/mariuszgromada/mxparser * http://mxparser.codeplex.com * http://github.com/mariuszgromada/Janet-Sudoku * http://janetsudoku.codeplex.com * http://sourceforge.net/projects/janetsudoku * http://bitbucket.org/mariuszgromada/janet-sudoku * http://github.com/mariuszgromada/MathParser.org-mXparser * http://scalarmath.org/ * https://play.google.com/store/apps/details?id=org.mathparser.scalar.lite * https://play.google.com/store/apps/details?id=org.mathparser.scalar.pro * * Asked if he believes in one God, a mathematician answered: * "Yes, up to isomorphism." */ using System; namespace org.mariuszgromada.math.mxparser.parsertokens { /** * Functions with 3 arguments - mXparser tokens definition. * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br> * <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br> * <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br> * <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br> * <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br> * <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br> * <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br> * <a href="https://play.google.com/store/apps/details?id=org.mathparser.scalar.lite" target="_blank">Scalar Free</a><br> * <a href="https://play.google.com/store/apps/details?id=org.mathparser.scalar.pro" target="_blank">Scalar Pro</a><br> * <a href="http://scalarmath.org/" target="_blank">ScalarMath.org</a><br> * * @version 5.0.0 */ [CLSCompliant(true)] public sealed class Function3Arg { /* * 3-args Function - token type id. */ public const int TYPE_ID = 6; public const String TYPE_DESC = "3-args Function"; /* * 3-args Function - tokens id. */ public const int IF_CONDITION_ID = 1; public const int IF_ID = 2; public const int CHI_ID = 3; public const int CHI_LR_ID = 4; public const int CHI_L_ID = 5; public const int CHI_R_ID = 6; public const int PDF_UNIFORM_CONT_ID = 7; public const int CDF_UNIFORM_CONT_ID = 8; public const int QNT_UNIFORM_CONT_ID = 9; public const int PDF_NORMAL_ID = 10; public const int CDF_NORMAL_ID = 11; public const int QNT_NORMAL_ID = 12; public const int DIGIT_ID = 13; public const int INC_BETA_ID = 14; public const int REG_BETA_ID = 15; /* * 3-args Function - tokens key words. */ public const String IF_STR = "if"; public const String CHI_STR = "chi"; public const String CHI_LR_STR = "CHi"; public const String CHI_L_STR = "Chi"; public const String CHI_R_STR = "cHi"; public const String PDF_UNIFORM_CONT_STR = "pUni"; public const String CDF_UNIFORM_CONT_STR = "cUni"; public const String QNT_UNIFORM_CONT_STR = "qUni"; public const String PDF_NORMAL_STR = "pNor"; public const String CDF_NORMAL_STR = "cNor"; public const String QNT_NORMAL_STR = "qNor"; public const String DIGIT_STR = "dig"; public const String INC_BETA_STR = "BetaInc"; public const String REG_BETA_STR = "BetaReg"; public const String REG_BETA_I_STR = "BetaI"; /* * 3-args Function - syntax. */ public static readonly String IF_SYN = SyntaxStringBuilder.function3Arg(IF_STR, SyntaxStringBuilder.cond, SyntaxStringBuilder.exprIfTrue, SyntaxStringBuilder.exprIfFalse); public static readonly String CHI_SYN = SyntaxStringBuilder.function3Arg(CHI_STR, SyntaxStringBuilder.x, SyntaxStringBuilder.a, SyntaxStringBuilder.b); public static readonly String CHI_LR_SYN = SyntaxStringBuilder.function3Arg(CHI_LR_STR, SyntaxStringBuilder.x, SyntaxStringBuilder.a, SyntaxStringBuilder.b); public static readonly String CHI_L_SYN = SyntaxStringBuilder.function3Arg(CHI_L_STR, SyntaxStringBuilder.x, SyntaxStringBuilder.a, SyntaxStringBuilder.b); public static readonly String CHI_R_SYN = SyntaxStringBuilder.function3Arg(CHI_R_STR, SyntaxStringBuilder.x, SyntaxStringBuilder.a, SyntaxStringBuilder.b); public static readonly String PDF_UNIFORM_CONT_SYN = SyntaxStringBuilder.function3Arg(PDF_UNIFORM_CONT_STR, SyntaxStringBuilder.x, SyntaxStringBuilder.a, SyntaxStringBuilder.b); public static readonly String CDF_UNIFORM_CONT_SYN = SyntaxStringBuilder.function3Arg(CDF_UNIFORM_CONT_STR, SyntaxStringBuilder.a, SyntaxStringBuilder.a, SyntaxStringBuilder.b); public static readonly String QNT_UNIFORM_CONT_SYN = SyntaxStringBuilder.function3Arg(QNT_UNIFORM_CONT_STR, SyntaxStringBuilder.q, SyntaxStringBuilder.a, SyntaxStringBuilder.b); public static readonly String PDF_NORMAL_SYN = SyntaxStringBuilder.function3Arg(PDF_NORMAL_STR, SyntaxStringBuilder.x, SyntaxStringBuilder.mean, SyntaxStringBuilder.stdv); public static readonly String CDF_NORMAL_SYN = SyntaxStringBuilder.function3Arg(CDF_NORMAL_STR, SyntaxStringBuilder.x, SyntaxStringBuilder.mean, SyntaxStringBuilder.stdv); public static readonly String QNT_NORMAL_SYN = SyntaxStringBuilder.function3Arg(QNT_NORMAL_STR, SyntaxStringBuilder.q, SyntaxStringBuilder.mean, SyntaxStringBuilder.stdv); public static readonly String DIGIT_SYN = SyntaxStringBuilder.function3Arg(DIGIT_STR, SyntaxStringBuilder.num, SyntaxStringBuilder.pos, SyntaxStringBuilder.basestr); public static readonly String INC_BETA_SYN = SyntaxStringBuilder.function3Arg(INC_BETA_STR, SyntaxStringBuilder.x, SyntaxStringBuilder.a, SyntaxStringBuilder.b); public static readonly String REG_BETA_SYN = SyntaxStringBuilder.function3Arg(REG_BETA_STR, SyntaxStringBuilder.x, SyntaxStringBuilder.a, SyntaxStringBuilder.b); public static readonly String REG_BETA_I_SYN = SyntaxStringBuilder.function3Arg(REG_BETA_I_STR, SyntaxStringBuilder.x, SyntaxStringBuilder.a, SyntaxStringBuilder.b); /* * 3-args Function - tokens description. */ public const String IF_DESC = "If function"; public const String CHI_DESC = "Characteristic function for x in (a,b)"; public const String CHI_LR_DESC = "Characteristic function for x in [a,b]"; public const String CHI_L_DESC = "Characteristic function for x in [a,b)"; public const String CHI_R_DESC = "Characteristic function for x in (a,b]"; public const String PDF_UNIFORM_CONT_DESC = "Probability distribution function - Uniform continuous distribution U(a,b)"; public const String CDF_UNIFORM_CONT_DESC = "Cumulative distribution function - Uniform continuous distribution U(a,b)"; public const String QNT_UNIFORM_CONT_DESC = "Quantile function (inverse cumulative distribution function) - Uniform continuous distribution U(a,b)"; public const String PDF_NORMAL_DESC = "Probability distribution function - Normal distribution N(m,s)"; public const String CDF_NORMAL_DESC = "Cumulative distribution function - Normal distribution N(m,s)"; public const String QNT_NORMAL_DESC = "Quantile function (inverse cumulative distribution function)"; public const String DIGIT_DESC = "Digit at position 1 ... n (left -> right) or 0 ... -(n-1) (right -> left) - numeral system with given base"; public const String INC_BETA_DESC = "The incomplete beta special function B(x; a, b), also called the incomplete Euler integral of the first kind"; public const String REG_BETA_DESC = "The regularized incomplete beta (or regularized beta) special function I(x; a, b), also called the regularized incomplete Euler integral of the first kind"; /* * 3-args Function - since. */ public const String IF_SINCE = mXparser.NAMEv10; public const String CHI_SINCE = mXparser.NAMEv10; public const String CHI_LR_SINCE = mXparser.NAMEv10; public const String CHI_L_SINCE = mXparser.NAMEv10; public const String CHI_R_SINCE = mXparser.NAMEv10; public const String PDF_UNIFORM_CONT_SINCE = mXparser.NAMEv30; public const String CDF_UNIFORM_CONT_SINCE = mXparser.NAMEv30; public const String QNT_UNIFORM_CONT_SINCE = mXparser.NAMEv30; public const String PDF_NORMAL_SINCE = mXparser.NAMEv30; public const String CDF_NORMAL_SINCE = mXparser.NAMEv30; public const String QNT_NORMAL_SINCE = mXparser.NAMEv30; public const String DIGIT_SINCE = mXparser.NAMEv41; public const String INC_BETA_SINCE = mXparser.NAMEv42; public const String REG_BETA_SINCE = mXparser.NAMEv42; public const String REG_BETA_I_SINCE = mXparser.NAMEv42; } }
65.050279
198
0.7281
[ "BSD-2-Clause" ]
workgroupengineering/MathParser.org-mXparser
CURRENT/c-sharp/src/org/mariuszgromada/math/mxparser/parsertokens/Function3Arg.cs
11,644
C#
// // System.Security.Cryptography.X509Certificates.X509CertificateCollection // // Authors: // Lawrence Pit (loz@cable.a2000.nl) // Sebastien Pouliot (spouliot@motus.com) // // Copyright (C) 2004 Novell (http://www.novell.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Globalization; using System.Security.Cryptography; namespace System.Security.Cryptography.X509Certificates { [Serializable] public class X509CertificateCollection : CollectionBase { public X509CertificateCollection () { } public X509CertificateCollection (X509Certificate [] value) { AddRange (value); } public X509CertificateCollection (X509CertificateCollection value) { AddRange (value); } // Properties public X509Certificate this [int index] { get { return (X509Certificate) InnerList [index]; } set { InnerList [index] = value; } } // Methods public int Add (X509Certificate value) { if (value == null) throw new ArgumentNullException ("value"); return InnerList.Add (value); } public void AddRange (X509Certificate [] value) { if (value == null) throw new ArgumentNullException ("value"); for (int i = 0; i < value.Length; i++) InnerList.Add (value [i]); } public void AddRange (X509CertificateCollection value) { if (value == null) throw new ArgumentNullException ("value"); for (int i = 0; i < value.InnerList.Count; i++) InnerList.Add (value [i]); } public bool Contains (X509Certificate value) { if (value == null) return false; byte[] hash = value.GetCertHash (); for (int i=0; i < InnerList.Count; i++) { X509Certificate x509 = (X509Certificate) InnerList [i]; if (Compare (x509.GetCertHash (), hash)) return true; } return false; } public void CopyTo (X509Certificate[] array, int index) { InnerList.CopyTo (array, index); } public new X509CertificateEnumerator GetEnumerator () { return new X509CertificateEnumerator (this); } public override int GetHashCode () { return InnerList.GetHashCode (); } public int IndexOf (X509Certificate value) { return InnerList.IndexOf (value); } public void Insert (int index, X509Certificate value) { InnerList.Insert (index, value); } public void Remove (X509Certificate value) { if (value == null) throw new ArgumentNullException ("value"); if (IndexOf (value) == -1) { throw new ArgumentException ("value", Locale.GetText ("Not part of the collection.")); } InnerList.Remove (value); } // private stuff private bool Compare (byte[] array1, byte[] array2) { if ((array1 == null) && (array2 == null)) return true; if ((array1 == null) || (array2 == null)) return false; if (array1.Length != array2.Length) return false; for (int i=0; i < array1.Length; i++) { if (array1 [i] != array2 [i]) return false; } return true; } // Inner Class public class X509CertificateEnumerator : IEnumerator { private IEnumerator enumerator; // Constructors public X509CertificateEnumerator (X509CertificateCollection mappings) { enumerator = ((IEnumerable) mappings).GetEnumerator (); } // Properties public X509Certificate Current { get { return (X509Certificate) enumerator.Current; } } object IEnumerator.Current { get { return enumerator.Current; } } // Methods bool IEnumerator.MoveNext () { return enumerator.MoveNext (); } void IEnumerator.Reset () { enumerator.Reset (); } public bool MoveNext () { return enumerator.MoveNext (); } public void Reset () { enumerator.Reset (); } } } }
23.629808
75
0.663683
[ "MIT" ]
GrapeCity/pagefx
mono/mcs/class/System/System.Security.Cryptography.X509Certificates/X509CertificateCollection.cs
4,915
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// AlipayFinanceQuotationDtcrawlerSendModel Data Structure. /// </summary> [Serializable] public class AlipayFinanceQuotationDtcrawlerSendModel : AopObject { /// <summary> /// 爬虫平台推送数据,为json字符串,bizNo 为推送流水号,taskName为任务名,业务数据包含在bizData中 /// </summary> [XmlElement("content")] public string Content { get; set; } } }
25.789474
72
0.628571
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/AlipayFinanceQuotationDtcrawlerSendModel.cs
558
C#
using System; using System.Collections.Generic; using FINT.Model.Administrasjon.Kodeverk; namespace FINT.Model.Administrasjon.Kodeverk { public class Ansvar : Kontodimensjon { public enum Relasjonsnavn { OVERORDNET, UNDERORDNET, ORGANISASJONSELEMENT } } }
14.285714
44
0.703333
[ "MIT" ]
FINTmodels/FINT.Information.Model
FINT.Model.Administrasjon/Kodeverk/Ansvar.cs
300
C#
namespace android.hardware { [global::MonoJavaBridge.JavaClass()] public partial class GeomagneticField : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static GeomagneticField() { InitJNI(); } protected GeomagneticField(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getY4356; public virtual float getY() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField._getY4356); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField.staticClass, global::android.hardware.GeomagneticField._getY4356); } internal static global::MonoJavaBridge.MethodId _getX4357; public virtual float getX() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField._getX4357); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField.staticClass, global::android.hardware.GeomagneticField._getX4357); } internal static global::MonoJavaBridge.MethodId _getZ4358; public virtual float getZ() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField._getZ4358); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField.staticClass, global::android.hardware.GeomagneticField._getZ4358); } internal static global::MonoJavaBridge.MethodId _getDeclination4359; public virtual float getDeclination() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField._getDeclination4359); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField.staticClass, global::android.hardware.GeomagneticField._getDeclination4359); } internal static global::MonoJavaBridge.MethodId _getInclination4360; public virtual float getInclination() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField._getInclination4360); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField.staticClass, global::android.hardware.GeomagneticField._getInclination4360); } internal static global::MonoJavaBridge.MethodId _getHorizontalStrength4361; public virtual float getHorizontalStrength() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField._getHorizontalStrength4361); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField.staticClass, global::android.hardware.GeomagneticField._getHorizontalStrength4361); } internal static global::MonoJavaBridge.MethodId _getFieldStrength4362; public virtual float getFieldStrength() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField._getFieldStrength4362); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.hardware.GeomagneticField.staticClass, global::android.hardware.GeomagneticField._getFieldStrength4362); } internal static global::MonoJavaBridge.MethodId _GeomagneticField4363; public GeomagneticField(float arg0, float arg1, float arg2, long arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.hardware.GeomagneticField.staticClass, global::android.hardware.GeomagneticField._GeomagneticField4363, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.hardware.GeomagneticField.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/GeomagneticField")); global::android.hardware.GeomagneticField._getY4356 = @__env.GetMethodIDNoThrow(global::android.hardware.GeomagneticField.staticClass, "getY", "()F"); global::android.hardware.GeomagneticField._getX4357 = @__env.GetMethodIDNoThrow(global::android.hardware.GeomagneticField.staticClass, "getX", "()F"); global::android.hardware.GeomagneticField._getZ4358 = @__env.GetMethodIDNoThrow(global::android.hardware.GeomagneticField.staticClass, "getZ", "()F"); global::android.hardware.GeomagneticField._getDeclination4359 = @__env.GetMethodIDNoThrow(global::android.hardware.GeomagneticField.staticClass, "getDeclination", "()F"); global::android.hardware.GeomagneticField._getInclination4360 = @__env.GetMethodIDNoThrow(global::android.hardware.GeomagneticField.staticClass, "getInclination", "()F"); global::android.hardware.GeomagneticField._getHorizontalStrength4361 = @__env.GetMethodIDNoThrow(global::android.hardware.GeomagneticField.staticClass, "getHorizontalStrength", "()F"); global::android.hardware.GeomagneticField._getFieldStrength4362 = @__env.GetMethodIDNoThrow(global::android.hardware.GeomagneticField.staticClass, "getFieldStrength", "()F"); global::android.hardware.GeomagneticField._GeomagneticField4363 = @__env.GetMethodIDNoThrow(global::android.hardware.GeomagneticField.staticClass, "<init>", "(FFFJ)V"); } } }
63.232323
403
0.801597
[ "MIT" ]
beachmiles/androidmono
jni/MonoJavaBridge/android/generated/android/hardware/GeomagneticField.cs
6,260
C#
/* * Copyright 2018 JDCLOUD.COM * * 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. * * Attack Log APIs * Anti DDoS Protection Package Attack Log APIs * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; namespace JDCloudSDK.Antipro.Apis { /// <summary> /// 查询公网 IP 的监控流量 /// </summary> public class DescribeIpMonitorFlowResponse : JdcloudResponse<DescribeIpMonitorFlowResult> { } }
26.682927
93
0.726691
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Antipro/Apis/DescribeIpMonitorFlowResponse.cs
1,112
C#
/* *Author:jxx *Contact:283591387@qq.com *Date:2018-07-01 * 此代码由框架生成,请勿随意更改 */ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; using VOL.Entity.SystemModels; namespace VOL.Entity.DomainModels { [EntityAttribute(TableCnName = "菜单配置")] public class Sys_Menu:BaseEntity { /// <summary> ///ID /// </summary> [Key] [Display(Name ="ID")] [DisplayFormat(DataFormatString="10,0")] [Column(TypeName="int")] [Editable(true)] [Required(AllowEmptyStrings=false)] public int Menu_Id { get; set; } /// <summary> ///父级ID /// </summary> [Display(Name ="父级ID")] [DisplayFormat(DataFormatString="10,0")] [Column(TypeName="int")] [Editable(true)] [Required(AllowEmptyStrings=false)] public int ParentId { get; set; } /// <summary> ///菜单名称 /// </summary> [Display(Name ="菜单名称")] [MaxLength(50)] [Column(TypeName="nvarchar(50)")] [Editable(true)] [Required(AllowEmptyStrings=false)] public string MenuName { get; set; } /// <summary> /// /// </summary> [Display(Name = "TableName")] [MaxLength(200)] [Column(TypeName = "nvarchar(200)")] [Editable(true)] public string TableName { get; set; } /// <summary> /// /// </summary> [Display(Name ="Url")] [MaxLength(10000)] [Column(TypeName="nvarchar(10000)")] [Editable(true)] public string Url { get; set; } /// <summary> ///权限 /// </summary> [Display(Name ="权限")] [MaxLength(10000)] [Column(TypeName="nvarchar(10000)")] [Editable(true)] public string Auth { get; set; } /// <summary> /// /// </summary> [Display(Name ="Description")] [MaxLength(200)] [Column(TypeName="nvarchar(200)")] [Editable(true)] public string Description { get; set; } /// <summary> ///图标 /// </summary> [Display(Name ="图标")] [MaxLength(50)] [Column(TypeName="nvarchar(50)")] [Editable(true)] public string Icon { get; set; } /// <summary> ///排序号 /// </summary> [Display(Name ="排序号")] [DisplayFormat(DataFormatString="10,0")] [Column(TypeName="int")] [Editable(true)] public int? OrderNo { get; set; } /// <summary> ///创建人 /// </summary> [Display(Name ="创建人")] [MaxLength(50)] [Column(TypeName="nvarchar(50)")] [Editable(true)] public string Creator { get; set; } /// <summary> ///创建时间 /// </summary> [Display(Name ="创建时间")] [Column(TypeName="datetime")] [Editable(true)] public DateTime? CreateDate { get; set; } /// <summary> /// /// </summary> [Display(Name ="Modifier")] [MaxLength(50)] [Column(TypeName="nvarchar(50)")] [Editable(true)] public string Modifier { get; set; } /// <summary> /// /// </summary> [Display(Name ="ModifyDate")] [Column(TypeName="datetime")] [Editable(true)] public DateTime? ModifyDate { get; set; } /// <summary> ///是否启用 /// </summary> [Display(Name ="是否启用")] [DisplayFormat(DataFormatString="3,0")] [Column(TypeName="tinyint")] [Editable(true)] public byte? Enable { get; set; } public List<Sys_Actions> Actions { get; set; } } }
24.11465
53
0.522979
[ "MIT" ]
1426463237/Vue.NetCore
Vue.Net/VOL.Entity/DomainModels/System/Sys_Menu.cs
3,926
C#
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// Operations for managing Policy Snippets. /// </summary> internal partial class PolicySnippetsOperations : IServiceOperations<ApiManagementClient>, IPolicySnippetsOperations { /// <summary> /// Initializes a new instance of the PolicySnippetsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PolicySnippetsOperations(ApiManagementClient client) { this._client = client; } private ApiManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiManagement.ApiManagementClient. /// </summary> public ApiManagementClient Client { get { return this._client; } } /// <summary> /// List all policy snippets. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='scope'> /// Required. Polisy scope. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List policy snippets operation response details. /// </returns> public async Task<PolicySnippetListResponse> ListAsync(string resourceGroupName, string serviceName, PolicyScopeContract scope, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("scope", scope); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/policySnippets"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); queryParameters.Add("scope=" + Uri.EscapeDataString(scope.ToString())); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PolicySnippetListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PolicySnippetListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valuesArray = responseDoc; if (valuesArray != null && valuesArray.Type != JTokenType.Null) { foreach (JToken valuesValue in ((JArray)valuesArray)) { PolicySnippetContract policySnippetContractInstance = new PolicySnippetContract(); result.Values.Add(policySnippetContractInstance); JToken nameValue = valuesValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); policySnippetContractInstance.Name = nameInstance; } JToken contentValue = valuesValue["content"]; if (contentValue != null && contentValue.Type != JTokenType.Null) { string contentInstance = ((string)contentValue); policySnippetContractInstance.Content = contentInstance; } JToken toolTipValue = valuesValue["toolTip"]; if (toolTipValue != null && toolTipValue.Type != JTokenType.Null) { string toolTipInstance = ((string)toolTipValue); policySnippetContractInstance.ToolTip = toolTipInstance; } JToken scopeValue = valuesValue["scope"]; if (scopeValue != null && scopeValue.Type != JTokenType.Null) { PolicyScopeContract scopeInstance = ((PolicyScopeContract)Enum.Parse(typeof(PolicyScopeContract), ((string)scopeValue), true)); policySnippetContractInstance.Scope = scopeInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
43.379699
172
0.489384
[ "Apache-2.0" ]
farazsid/Sample
src/ResourceManagement/ApiManagement/ApiManagementManagement/Generated/PolicySnippetsOperations.cs
11,539
C#
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace HigherArithmetics.Numerics { //------------------------------------------------------------------------------------------------------------------- // /// <summary> /// Real Value Matrix /// </summary> // //------------------------------------------------------------------------------------------------------------------- public sealed class RationalMatrix : ICloneable, IEquatable<RationalMatrix>, IFormattable, IEnumerable<BigRational> { #region Private Data // Items internal BigRational[][] m_Items; private BigRational m_Determinant = BigRational.NaN; private int m_Rank = -1; private BigRational[] m_LinearSolutions; #endregion Private Data #region Algorithm #endregion Algorithm #region Create // Empty Constructor private RationalMatrix() { } // Low level constructor private RationalMatrix(BigRational[][] items) : this() { m_Items = items; } // Standard Constructor private RationalMatrix(int lines, int columns) : this() { if (lines <= 0) throw new ArgumentOutOfRangeException(nameof(lines)); else if (columns <= 0) throw new ArgumentOutOfRangeException(nameof(columns)); m_Items = Enumerable .Range(0, lines) .Select(_ => new BigRational[columns]) .ToArray(); } // Standard Constructor (square matrix) private RationalMatrix(int size) : this(size, size) { } /// <summary> /// Union matrix /// </summary> /// <param name="size">Size</param> public static RationalMatrix Union(int size) { RationalMatrix result = new(size); for (int i = result.LineCount - 1; i >= 0; --i) result.m_Items[i][i] = 1; return result; } /// <summary> /// Zero matrix /// </summary> /// <param name="size">Size</param> public static RationalMatrix Zero(int size) => new(size); /// <summary> /// Create Matrix /// </summary> /// <param name="lines">Lines</param> /// <param name="columns">Columns</param> /// <param name="createItem">Item at line and column</param> /// <returns></returns> public static RationalMatrix Create(int lines, int columns, Func<int, int, BigRational> createItem) { if (lines <= 0) throw new ArgumentOutOfRangeException(nameof(lines)); else if (columns <= 0) throw new ArgumentOutOfRangeException(nameof(columns)); else if (createItem is null) throw new ArgumentNullException(nameof(createItem)); RationalMatrix result = new(lines, columns); for (int r = 0; r < lines; ++r) for (int c = 0; c < columns; ++c) result.m_Items[r][c] = createItem(r, c); return result; } /// <summary> /// Create Square Matrix /// </summary> /// <param name="size">Size</param> /// <param name="createItem">Item at line and column</param> /// <returns></returns> public static RationalMatrix Create(int size, Func<int, int, BigRational> createItem) => Create(size, size, createItem); /// <summary> /// Create /// </summary> public static RationalMatrix Create(IEnumerable<IEnumerable<BigRational>> data) { if (data is null) throw new ArgumentNullException(nameof(data)); var copy = data .Select(line => line.ToArray()) .ToArray(); return new RationalMatrix(copy); } #endregion Create #region Public #region General /// <summary> /// Perform a func and create a new matrix /// </summary> /// <param name="func">func: value, line, column returns a new value</param> /// <returns>New Matrix</returns> public RationalMatrix Perform(Func<BigRational, int, int, BigRational> func) { if (func is null) throw new ArgumentNullException(nameof(func)); RationalMatrix result = new(LineCount, ColumnCount); for (int r = 0; r < m_Items.Length; ++r) for (int c = 0; c < m_Items[r].Length; ++c) result.m_Items[r][c] = func(m_Items[r][c], r, c); return result; } /// <summary> /// Perform a func and create a new matrix /// </summary> /// <param name="func">func: line, column returns a new value</param> /// <returns>New Matrix</returns> public RationalMatrix Perform(Func<int, int, BigRational> func) { if (func is null) throw new ArgumentNullException(nameof(func)); RationalMatrix result = new(LineCount, ColumnCount); for (int r = 0; r < m_Items.Length; ++r) for (int c = 0; c < m_Items[r].Length; ++c) result.m_Items[r][c] = func(r, c); return result; } /// <summary> /// Perform a func and create a new matrix /// </summary> /// <param name="func">func: value returns a new value</param> /// <returns>New Matrix</returns> public RationalMatrix Perform(Func<BigRational, BigRational> func) { if (func is null) throw new ArgumentNullException(nameof(func)); RationalMatrix result = new(LineCount, ColumnCount); for (int r = 0; r < m_Items.Length; ++r) for (int c = 0; c < m_Items[r].Length; ++c) result.m_Items[r][c] = func(m_Items[r][c]); return result; } /// <summary> /// Lines /// </summary> public int LineCount => m_Items.Length; /// <summary> /// Columns /// </summary> public int ColumnCount => m_Items[0].Length; /// <summary> /// Item Count /// </summary> public int ItemCount => m_Items.Length * m_Items[0].Length; /// <summary> /// Lines /// </summary> public IEnumerable<BigRational[]> Lines { get { foreach (var line in m_Items) yield return line.ToArray(); } } /// <summary> /// Lines /// </summary> public IEnumerable<BigRational[]> Columns { get { int N = ColumnCount; for (int i = 0; i < N; ++i) { BigRational[] result = new BigRational[m_Items.Length]; for (int j = 0; j < result.Length; ++j) result[j] = m_Items[i][j]; yield return result; } } } /// <summary> /// Items /// </summary> public IEnumerable<BigRational> Items { get { foreach (var line in m_Items) foreach (var item in line) yield return item; } } /// <summary> /// Cell /// </summary> /// <param name="line">Line</param> /// <param name="column">Column</param> public BigRational Cell(int line, int column) => m_Items[line][column]; /// <summary> /// Cell /// </summary> /// <param name="line">Line</param> /// <param name="column">Column</param> public BigRational this[int line, int column] => Cell(line, column); #endregion General #region Standard /// <summary> /// Transpose /// </summary> public RationalMatrix Transpose() { RationalMatrix result = new(ColumnCount, LineCount); for (int r = result.m_Items.Length - 1; r >= 0; --r) for (int c = result.m_Items[0].Length - 1; c >= 0; --c) result.m_Items[r][c] = m_Items[c][r]; return result; } /// <summary> /// Determinant /// </summary> public BigRational Determinant { get { if (m_Determinant.IsNaN) m_Determinant = MatrixLowLevel.Determinant(m_Items); return m_Determinant; } } /// <summary> /// Rank /// </summary> public int Rank { get { if (m_Rank < 0) m_Rank = MatrixLowLevel.Rank(m_Items); return m_Rank; } } /// <summary> /// Inverse /// </summary> public RationalMatrix Inverse() { if (ColumnCount != LineCount) throw new InvalidOperationException("Only square matrix can be inversed."); try { return new RationalMatrix(MatrixLowLevel.Inverse(m_Items)); } catch (ArgumentException) { throw new InvalidOperationException("Degenerated matrix can't be inversed."); } } /// <summary> /// Pseudo Inverse /// </summary> public RationalMatrix PseudoInverse() { BigRational[][] tran = MatrixLowLevel.Transpose(m_Items); BigRational[][] result = MatrixLowLevel.Multiply(MatrixLowLevel.Inverse(MatrixLowLevel.Multiply(tran, m_Items)), tran); return new RationalMatrix(result); } /// <summary> /// Linear Solutions /// </summary> public BigRational[] LinearSoution { get { if (m_LinearSolutions is null) m_LinearSolutions = MatrixLowLevel.Solve(m_Items); return m_LinearSolutions; } } #endregion Standard #endregion Public #region Operators #region Comparison /// <summary> /// Equals /// </summary> public static bool operator ==(RationalMatrix left, RationalMatrix right) { if (ReferenceEquals(left, right)) return true; else if (right is null) return false; else if (left is null) return false; return left.Equals(right); } /// <summary> /// Not Equals /// </summary> public static bool operator !=(RationalMatrix left, RationalMatrix right) { if (ReferenceEquals(left, right)) return false; else if (right is null) return true; else if (left is null) return true; return !left.Equals(right); } #endregion Comparison #region Arithmetics /// <summary> /// Unary + /// </summary> public static RationalMatrix operator +(RationalMatrix value) { if (value is null) throw new ArgumentNullException(nameof(value)); return value; } /// <summary> /// Unary - /// </summary> public static RationalMatrix operator -(RationalMatrix value) { if (value is null) throw new ArgumentNullException(nameof(value)); RationalMatrix result = value.Clone(); foreach (BigRational[] line in result.m_Items) for (int i = line.Length; i >= 0; --i) line[i] = -line[i]; return result; } /// <summary> /// Multiplication by number /// </summary> public static RationalMatrix operator *(RationalMatrix matrix, BigRational value) { if (matrix is null) throw new ArgumentNullException(nameof(matrix)); if (value == 1) return matrix; RationalMatrix result = matrix.Clone(); foreach (BigRational[] line in result.m_Items) for (int i = line.Length; i >= 0; --i) line[i] = line[i] * value; return result; } /// <summary> /// Multiplication by number /// </summary> public static RationalMatrix operator *(BigRational value, RationalMatrix matrix) => matrix * value; /// <summary> /// Division by number /// </summary> public static RationalMatrix operator /(RationalMatrix matrix, BigRational value) { if (matrix is null) throw new ArgumentNullException(nameof(matrix)); if (value == 1) return matrix; RationalMatrix result = matrix.Clone(); foreach (BigRational[] line in result.m_Items) for (int i = line.Length; i >= 0; --i) line[i] = line[i] / value; return result; } /// <summary> /// Matrix Addition /// </summary> public static RationalMatrix operator +(RationalMatrix left, RationalMatrix right) { if (left is null) throw new ArgumentNullException(nameof(left)); else if (right is null) throw new ArgumentNullException(nameof(right)); if (left.LineCount != right.LineCount) throw new ArgumentException($"Right matrix must have {left.LineCount} lines, actual {right.LineCount}", nameof(right)); else if (left.ColumnCount != right.ColumnCount) throw new ArgumentException($"Right matrix must have {left.ColumnCount} columns, actual {right.ColumnCount}", nameof(right)); RationalMatrix result = new(left.LineCount, left.LineCount); for (int r = right.LineCount - 1; r >= 0; --r) for (int c = right.ColumnCount - 1; c >= 0; --c) result.m_Items[r][c] = left.m_Items[r][c] + right.m_Items[r][c]; return result; } /// <summary> /// Matrix Subtractions /// </summary> public static RationalMatrix operator -(RationalMatrix left, RationalMatrix right) { if (left is null) throw new ArgumentNullException(nameof(left)); else if (right is null) throw new ArgumentNullException(nameof(right)); if (left.LineCount != right.LineCount) throw new ArgumentException($"Right matrix must have {left.LineCount} lines, actual {right.LineCount}", nameof(right)); else if (left.ColumnCount != right.ColumnCount) throw new ArgumentException($"Right matrix must have {left.ColumnCount} columns, actual {right.ColumnCount}", nameof(right)); RationalMatrix result = new(left.LineCount, left.LineCount); for (int r = right.LineCount - 1; r >= 0; --r) for (int c = right.ColumnCount - 1; c >= 0; --c) result.m_Items[r][c] = left.m_Items[r][c] - right.m_Items[r][c]; return result; } /// <summary> /// Matrix Mutiplication /// </summary> public static RationalMatrix operator *(RationalMatrix left, RationalMatrix right) { if (left is null) throw new ArgumentNullException(nameof(left)); else if (right is null) throw new ArgumentNullException(nameof(right)); if (left.ColumnCount != right.LineCount) throw new ArgumentException($"Right matrix must have {left.ColumnCount} liness, actual {right.LineCount}", nameof(right)); RationalMatrix result = new(left.LineCount, right.ColumnCount); for (int r = result.m_Items.Length - 1; r >= 0; --r) for (int c = result.m_Items[0].Length - 1; c >= 0; --c) { BigRational v = 0; for (int i = right.LineCount - 1; i >= 0; --i) v += left.m_Items[r][i] * right.m_Items[i][c]; result.m_Items[r][c] = v; } return result; } /// <summary> /// Matrix Division /// </summary> public static RationalMatrix operator /(RationalMatrix left, RationalMatrix right) { if (left is null) throw new ArgumentNullException(nameof(left)); else if (right is null) throw new ArgumentNullException(nameof(right)); if (left.ColumnCount != right.LineCount) throw new ArgumentException($"Right matrix must have {left.ColumnCount} liness, actual {right.LineCount}", nameof(right)); else if (right.ColumnCount != right.LineCount) throw new ArgumentException("Divisor must be a square matrix.", nameof(right)); return new RationalMatrix(MatrixLowLevel.Multiply(left.m_Items, MatrixLowLevel.Inverse(right.m_Items))); } /// <summary> /// Matrix Division /// </summary> public static RationalMatrix operator /(BigRational left, RationalMatrix right) { if (right is null) throw new ArgumentNullException(nameof(right)); if (right.ColumnCount != right.LineCount) throw new ArgumentException("Divisor must be a square matrix.", nameof(right)); BigRational[][] result = MatrixLowLevel.Inverse(right.m_Items); for (int i = result.Length - 1; i >= 0; --i) { BigRational[] line = result[i]; for (int j = line.Length - 1; j >= 0; --j) line[j] = left * line[j]; } return new RationalMatrix(result); } #endregion Arithmetics #endregion Operators #region ICloneable /// <summary> /// Deep copy /// </summary> public RationalMatrix Clone() => new() { m_Items = m_Items .Select(line => { BigRational[] result = new BigRational[line.Length]; Array.Copy(line, 0, result, 0, line.Length); return result; }) .ToArray() }; /// <summary> /// Deep Copy /// </summary> object ICloneable.Clone() => this.Clone(); #endregion ICloneable #region IEquatable<Matrix> /// <summary> /// Equals /// </summary> public bool Equals(RationalMatrix other, BigRational tolerance) { if (tolerance < 0) throw new ArgumentOutOfRangeException(nameof(tolerance)); if (ReferenceEquals(this, other)) return true; else if (other is null) return false; if (this.ColumnCount != other.ColumnCount || this.LineCount != other.LineCount) return false; for (int r = LineCount - 1; r >= 0; --r) for (int c = ColumnCount - 1; c >= 0; --c) if ((m_Items[r][c] - other.m_Items[r][c]).Abs() < tolerance) continue; // for BigRational.NaN case or alike else return false; return true; } /// <summary> /// Equals /// </summary> public bool Equals(RationalMatrix other) { if (ReferenceEquals(this, other)) return true; else if (other is null) return false; if (this.ColumnCount != other.ColumnCount || this.LineCount != other.LineCount) return false; return m_Items .Zip(other.m_Items, (left, right) => left.SequenceEqual(right)) .All(item => item); } /// <summary> /// Equals /// </summary> public override bool Equals(object obj) => Equals(obj as RationalMatrix); /// <summary> /// Hash Code /// </summary> public override int GetHashCode() => unchecked((LineCount << 16) ^ ColumnCount ^ m_Items[0][0].GetHashCode()); #endregion IEquatable<Matrix> #region IFormattable /// <summary> /// To String /// </summary> public string ToString(string format, IFormatProvider formatProvider) { if (formatProvider is null) formatProvider = CultureInfo.InvariantCulture; if (string.IsNullOrEmpty(format) || "g".Equals(format, StringComparison.OrdinalIgnoreCase)) return ToString(); int p = format.IndexOf('|'); string delimiter = p >= 0 ? format[(p + 1)..] : "\t"; if (p > 0) format = format[0..p]; return string.Join(Environment.NewLine, m_Items .Select(line => string.Join(delimiter, line.Select(item => item.ToString())))); } /// <summary> /// To String /// </summary> public override string ToString() => string.Join(Environment.NewLine, m_Items .Select(line => string.Join("\t", line.Select(item => item.ToString())))); #endregion IFormattable #region IEnumerable<BigRational> /// <summary> /// Enumerator /// </summary> /// <returns></returns> public IEnumerator<BigRational> GetEnumerator() => Items.GetEnumerator(); /// <summary> /// Enumerator /// </summary> IEnumerator IEnumerable.GetEnumerator() => Items.GetEnumerator(); #endregion IEnumerable<BigRational> } }
27.700719
133
0.588406
[ "MIT" ]
Dmitry-Bychenko/HigherArithmetics
Numerics/HigherArithmetics.Numerics.RationalMatrix.cs
19,254
C#
using System; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Support.Design.Widget; using Android.Support.V7.App; using Android.Views; using Android.Widget; namespace DWGettingStartedXamarin { [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true, LaunchMode =Android.Content.PM.LaunchMode.SingleTop)] [IntentFilter(new[] { "com.darryncampbell.datawedge.xamarin.ACTION" }, Categories = new[] { Intent.CategoryDefault})] public class MainActivity : AppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); SetContentView(Resource.Layout.activity_main); Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar); DWUtilities.CreateDWProfile(this); Button btnScan = (Button)FindViewById(Resource.Id.btnScan); btnScan.Touch += (s, e) => { if (e.Event.Action == MotionEventActions.Down) { // Button pressed, start scan Intent dwIntent = new Intent(); dwIntent.SetAction("com.symbol.datawedge.api.ACTION"); dwIntent.PutExtra("com.symbol.datawedge.api.SOFT_SCAN_TRIGGER", "START_SCANNING"); SendBroadcast(dwIntent); } else if (e.Event.Action == MotionEventActions.Up) { // Button released, end scan Intent dwIntent = new Intent(); dwIntent.SetAction("com.symbol.datawedge.api.ACTION"); dwIntent.PutExtra("com.symbol.datawedge.api.SOFT_SCAN_TRIGGER", "STOP_SCANNING"); SendBroadcast(dwIntent); } e.Handled = true; }; } protected override void OnNewIntent(Intent intent) { base.OnNewIntent(intent); DisplayScanResult(intent); } private void DisplayScanResult(Intent scanIntent) { String decodedSource = scanIntent.GetStringExtra(Resources.GetString(Resource.String.datawedge_intent_key_source)); String decodedData = scanIntent.GetStringExtra(Resources.GetString(Resource.String.datawedge_intent_key_data)); String decodedLabelType = scanIntent.GetStringExtra(Resources.GetString(Resource.String.datawedge_intent_key_label_type)); String scan = decodedData + " [" + decodedLabelType + "]\n\n"; TextView output = FindViewById<TextView>(Resource.Id.txtOutput); output.Text = scan + output.Text; } } }
42.897059
155
0.627014
[ "MIT" ]
darryncampbell/DataWedge-GettingStarted-Samples
Xamarin/MainActivity.cs
2,919
C#
using System; using Prism.Navigation; using Prism; using MyFormsLibrary.Navigation; using Prism.AppModel; using System.Threading.Tasks; namespace MyFormsLibrary.Tests.Mocks.ViewModels { public class PageAlphaViewModel:ContentPageAllActionViewModel,INavigationAware,IInitializeAsync,IActiveAware,IDestructible { public PageAlphaViewModel(INavigationServiceEx navigationService) { NavigationService = navigationService; } private bool _IsActive; public bool IsActive { get { return _IsActive; } set { _IsActive = value; if (value) { OnActive(); } else { OnNonActive(); } } } void OnActive() { DoneOnActive = true; OnActiveCount++; } void OnNonActive() { DoneOnNonActive = true; OnNonActiveCount++; } public event EventHandler IsActiveChanged; public void OnNavigatedFrom(INavigationParameters parameters) { DoneNavigatedFrom = true; NavigatedFromCount++; } public void OnNavigatedTo(INavigationParameters parameters) { DoneNavigatedTo = true; NavigatedToCount++; } public void Destroy() { DoneDestroy = true; DestroyCount++; } public async Task InitializeAsync(INavigationParameters parameters) { Param = parameters; DoneInitialize = true; NavigatingCount++; } } }
25.208955
126
0.553582
[ "MIT" ]
muak/MyFormsLibrary
MyFormsLibrary.Tests/Mocks/ViewModels/PageAlphaViewModel.cs
1,691
C#
using System.ComponentModel; using P42.Utils; using P42.Utils.Uno; using System; namespace P42.Utils.Uno { /// <summary> /// P42.Utils.Uno FormattedString Span /// </summary> abstract class Span : NotifiableObject, ICopiable<Span> { #region Fields internal string Key; int _start = -1; #endregion #region Properties /// <summary> /// Gets or sets the span's start. /// </summary> /// <value>The start.</value> public int Start { get => _start; set { if (_start == value) return; _start = value; OnPropertyChanged(nameof(Start)); } } // use int.MaxValue to indicate that the span is unterminated (goes to the end of the string) int _end = -1; /// <summary> /// Gets or sets the span's end. /// </summary> /// <value>The end.</value> public int End { get => _end; set { if (_end == value) return; _end = value; OnPropertyChanged(nameof(End)); } } /// <summary> /// Gets or sets the length. /// </summary> /// <value>The length. int.MaxValue to indicate that the span is unterminated (goes to the end of the string)</value> public int Length { get { if (_end == int.MaxValue) return int.MaxValue; return _end - _start + 1; } set { if ((_end - _start + 1) == value) return; if (value == int.MaxValue) _end = int.MaxValue; else _end = _start + value - 1; OnPropertyChanged(nameof(End)); } } #endregion #region Construction / Diposal /// <summary> /// Initializes a new instance of the <see cref="P42.Utils.Uno.Span"/> class. /// </summary> /// <param name="start">Start.</param> /// <param name="end">End.</param> protected Span(int start, int end) { _start = start; _end = end; } #endregion #region public void PropertiesFrom(Span source) { Key = source.Key; Start = source.Start; End = source.End; } public virtual Span Copy() { throw new NotImplementedException(); } #endregion } }
24.327434
126
0.444162
[ "MIT" ]
baskren/P42.Utils
P42.Utils.Uno/HtmlString/Span.cs
2,751
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace DotNetAsync.ParallelFramework { public class TaskContinuationsExample { private readonly EventWaitHandle _waitHandle = new AutoResetEvent(false); public void Run() { var cts = new CancellationTokenSource(); var task = Task.Factory.StartNew(() => GenerateRandomNumbers(50, cts.Token), cts.Token); task.ContinueWith(_ => { Console.WriteLine("The operation was cancelled."); }, TaskContinuationOptions.OnlyOnCanceled); var validator = task.ContinueWith(ValidateNumbers, TaskContinuationOptions.NotOnCanceled); validator.ContinueWith(OnValidationFailure, TaskContinuationOptions.OnlyOnFaulted); validator.ContinueWith(OnValidationSuccess, TaskContinuationOptions.OnlyOnRanToCompletion); cts.CancelAfter(TimeSpan.FromSeconds(5)); _waitHandle.WaitOne(); } private static IEnumerable<int> ValidateNumbers(Task<IEnumerable<int>> predecessor) { var invalid = predecessor.Result.Where(num => num % 21 == 0); if (invalid.Any()) { var message = string.Format("Invalid numbers are: [{0}].", string.Join(",", invalid)); throw new ArgumentException(message); } return predecessor.Result; } private void OnValidationSuccess(Task<IEnumerable<int>> predecessor) { var numbers = string.Join(",", predecessor.Result); Console.WriteLine("Generated numbers are: [{0}].", numbers); _waitHandle.Set(); } private void OnValidationFailure(Task<IEnumerable<int>> predecessor) { Console.WriteLine("Some of the generated numbers are invalid."); predecessor.Exception.Handle(ex => { if (ex is ArgumentException) { Console.WriteLine(ex.Message); } return true; }); _waitHandle.Set(); } private IEnumerable<int> GenerateRandomNumbers(int maxNumbers, CancellationToken cancellationToken) { Console.WriteLine("Generating random numbers."); var random = new Random(); var results = new List<int>(); while (!cancellationToken.IsCancellationRequested && results.Count < maxNumbers) { results.Add(random.Next()); Thread.Sleep(TimeSpan.FromMilliseconds(100)); } Console.WriteLine("{0} numbers were generated.", results.Count); return results; } } }
36.701299
107
0.595188
[ "MIT" ]
RePierre/dot-net-async
4.ParallelFramework/TaskContinuationsExample.cs
2,828
C#
using System.Drawing; namespace LianLianXuan_Prj.View { public abstract class BackGroundPictureView : View { private readonly Bitmap _bgp; // Guide background picture private Rectangle _drawSize; protected BackGroundPictureView(Model.Model model, Rectangle drawSize, string picPath) : base(model) { _bgp = new Bitmap(picPath); _drawSize = drawSize; } protected void PaintBGP(Graphics g) { g.DrawImage(_bgp, _drawSize); } } }
23.565217
108
0.621771
[ "MIT" ]
marklang1993/LianLianXuan_Prj
LianLianXuan_Prj/View/BackGroundPictureView.cs
544
C#
/* Copyright (c) 2017, Nokia All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using net.nuagenetworks.bambou; using net.nuagenetworks.vspk.v6; namespace net.nuagenetworks.vspk.v6.fetchers { public class VNFCatalogsFetcher: RestFetcher<VNFCatalog> { private const long serialVersionUID = 1L; public VNFCatalogsFetcher(RestObject parentRestObj) : base(parentRestObj, typeof(VNFCatalog)) { } } }
41.553191
86
0.747568
[ "BSD-3-Clause" ]
nuagenetworks/vspk-csharp
vspk/vspk/VNFCatalogsFetcher.cs
1,953
C#
/* https://github.com/mattbenic/Numeric Copyright(c) 2014 Matt Benic Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Numeric; namespace UnitTests { [TestClass] public class DecimalNumericTests { [TestMethod] public void TestAddMethod() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); decimal expected = input1 + input2; decimal actual = Numeric<decimal>.Add(input1, input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestAddOperator() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); decimal expected = input1 + input2; decimal actual = ((Numeric<decimal>)input1) + ((Numeric<decimal>)input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestSubtractMethod() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); decimal expected = input1 - input2; decimal actual = Numeric<decimal>.Subtract(input1, input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestSubtractOperator() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); decimal expected = input1 - input2; decimal actual = ((Numeric<decimal>)input1) - ((Numeric<decimal>)input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestMultiplyMethod() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); decimal expected = input1 * input2; decimal actual = Numeric<decimal>.Multiply(input1, input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestMultiplyOperator() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); decimal expected = input1 * input2; decimal actual = ((Numeric<decimal>)input1) * ((Numeric<decimal>)input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestDivisionMethod() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); decimal expected = input1 / input2; decimal actual = Numeric<decimal>.Division(input1, input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestDivisionOperator() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); decimal expected = input1 / input2; decimal actual = ((Numeric<decimal>)input1) / ((Numeric<decimal>)input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestUnaryNegationMethod() { var rand = new Random(); decimal input = rand.Next(); decimal expected = -input; decimal actual = Numeric<decimal>.UnaryNegation(input); Assert.AreEqual(expected, actual); } [TestMethod] public void TestUnaryNegationOperator() { var rand = new Random(); decimal input = rand.Next(); decimal expected = -input; decimal actual = -((Numeric<decimal>)input); Assert.AreEqual(expected, actual); } [TestMethod] public void TestEqualsMethod() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 == input2; bool actual = ((Numeric<decimal>)input1).Equals(input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestEqualityMethod() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 == input2; bool actual = Numeric<decimal>.Equality(input1, input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestEqualityOperator() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 == input2; bool actual = ((Numeric<decimal>)input1) == ((Numeric<decimal>)input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestInequalityMethod() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 != input2; bool actual = Numeric<decimal>.Inequality(input1, input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestInequalityOperator() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 != input2; bool actual = ((Numeric<decimal>)input1) != ((Numeric<decimal>)input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestLessThanMethod() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 < input2; bool actual = Numeric<decimal>.LessThan(input1, input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestLessThanOperator() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 < input2; bool actual = ((Numeric<decimal>)input1) < ((Numeric<decimal>)input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestGreaterThanMethod() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 > input2; bool actual = Numeric<decimal>.GreaterThan(input1, input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestGreaterThanOperator() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 > input2; bool actual = ((Numeric<decimal>)input1) > ((Numeric<decimal>)input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestLessThanOrEqualMethod() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 <= input2; bool actual = Numeric<decimal>.LessThanOrEqual(input1, input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestLessThanOrEqualOperator() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 <= input2; bool actual = ((Numeric<decimal>)input1) <= ((Numeric<decimal>)input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestGreaterThanOrEqualMethod() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 >= input2; bool actual = Numeric<decimal>.GreaterThanOrEqual(input1, input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestGreaterThanOrEqualOperator() { var rand = new Random(); decimal input1 = rand.Next(); decimal input2 = rand.Next(); bool expected = input1 >= input2; bool actual = ((Numeric<decimal>)input1) >= ((Numeric<decimal>)input2); Assert.AreEqual(expected, actual); } [TestMethod] public void TestGetHashCodeMethodIsConsistent() { var rand = new Random(); decimal input = rand.Next(); int expected = ((Numeric<decimal>)input).GetHashCode(); int actual = ((Numeric<decimal>)input).GetHashCode(); Assert.AreEqual(expected, actual); } [TestMethod] public void TestToStringMethod() { var rand = new Random(); decimal input = rand.Next(); string expected = input.ToString(); string actual = ((Numeric<decimal>)input).ToString(); Assert.AreEqual(expected, actual); } } [TestClass] public class DecimalMathTests { [TestMethod] public void TestAbsMethodPositive() { var rand = new Random(); decimal input = rand.Next(0, int.MaxValue); decimal expected = input; decimal actual = Math<decimal>.Abs(input); Assert.AreEqual(expected, actual); } [TestMethod] public void TestAbsMethodNegative() { var rand = new Random(); decimal input = rand.Next(int.MinValue, -1); decimal expected = -input; decimal actual = Math<decimal>.Abs(input); Assert.AreEqual(expected, actual); } [TestMethod] public void TestClampMethodLessThan() { var rand = new Random(); decimal min = rand.Next(); decimal max = rand.Next((int)min, int.MaxValue); decimal input = rand.Next(int.MinValue, (int)min); decimal expected = min; decimal actual = Math<decimal>.Clamp(input, min, max); Assert.AreEqual(expected, actual); } [TestMethod] public void TestClampMethodMoreThan() { var rand = new Random(); decimal min = rand.Next(); decimal max = rand.Next((int)min, int.MaxValue); decimal input = rand.Next((int)max, int.MaxValue); decimal expected = max; decimal actual = Math<decimal>.Clamp(input, min, max); Assert.AreEqual(expected, actual); } [TestMethod] public void TestClampMethodInside() { var rand = new Random(); decimal min = rand.Next(); decimal max = rand.Next((int)min, int.MaxValue); decimal input = rand.Next((int)min, (int)max); decimal expected = input; decimal actual = Math<decimal>.Clamp(input, min, max); Assert.AreEqual(expected, actual); } } }
29.611765
85
0.554946
[ "MIT" ]
mattbenic/Numeric
UnitTests/DecimalTests.cs
12,587
C#
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.Collections.Generic; using System.Runtime.Serialization; namespace ASC.Mail.Data.Contracts { [Serializable] [DataContract(Namespace = "", Name = "Filter")] public class MailSieveFilterData { [DataMember(Name = "id")] public int Id { get; set; } [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "position")] public int Position { get; set; } [DataMember(Name = "enabled")] public bool Enabled { get; set; } [DataMember(Name = "conditions")] public List<MailSieveFilterConditionData> Conditions { get; set; } [DataMember(Name = "actions")] public List<MailSieveFilterActionData> Actions { get; set; } [DataMember(Name = "options")] public MailSieveFilterOptionsData Options { get; set; } public MailSieveFilterData() { Actions = new List<MailSieveFilterActionData>(); Conditions = new List<MailSieveFilterConditionData>(); Options = new MailSieveFilterOptionsData(); } } }
30.596491
75
0.658257
[ "ECL-2.0", "Apache-2.0", "MIT" ]
ONLYOFFICE/CommunityServer
module/ASC.Mail/ASC.Mail/Data/Contracts/MailSieveFilterData.cs
1,746
C#
using System; using System.IO; using UnityEditor; using UnityEngine; namespace Ripgrep.Editor { public class Installer { public const string InstallRoot = "Library/com.random-poison.ripgrep-unity"; public const string RipgrepVersion = "12.1.1"; public static readonly string WindowsDownloadUrl = $"https://github.com/BurntSushi/ripgrep/releases/download/{RipgrepVersion}/ripgrep-{RipgrepVersion}-x86_64-pc-windows-msvc.zip"; public static readonly string MacosDownloadUrl = $"https://github.com/BurntSushi/ripgrep/releases/download/{RipgrepVersion}/ripgrep-{RipgrepVersion}-x86_64-apple-darwin.tar.gz"; public static readonly string LinuxDownloadUrl = $"https://github.com/BurntSushi/ripgrep/releases/download/{RipgrepVersion}/ripgrep-{RipgrepVersion}-x86_64-unknown-linux-musl.tar.gz"; public static readonly string WindowsBinPath = $"ripgrep-{RipgrepVersion}-x86_64-pc-windows-msvc/rg.exe"; public static readonly string MacosBinPath = $"ripgrep-{RipgrepVersion}-x86_64-apple-darwin/rg"; public static readonly string LinuxBinPath = $"ripgrep-{RipgrepVersion}-x86_64-unknown-linux-musl/rg"; /// <summary> /// Path to the installed Ripgrep binary. /// </summary> /// /// <remarks> /// The path is platform-specific, and will point to the correct path for the current /// editor platform. /// </remarks> public static string BinPath { get { switch (Application.platform) { case RuntimePlatform.WindowsEditor: return Path.Combine(InstallRoot, WindowsBinPath); case RuntimePlatform.OSXEditor: return Path.Combine(InstallRoot, MacosBinPath); case RuntimePlatform.LinuxEditor: return Path.Combine(InstallRoot, LinuxBinPath); default: throw new InvalidOperationException( $"Invalid install platform {Application.platform}"); } } } /// <summary> /// Checks if the Ripgrep binary has been installed. /// </summary> public static bool IsInstalled => File.Exists(BinPath); // TODO: Add a more script-friendly way to perform the install, that way other // scripts can trigger the install if they need ripgrep. [MenuItem("Tools/Ripgrep/Install Ripgrep")] public static void InstallMenuItem() { // TODO: Probably log any errors since there's no user code to handle them. Install(); } public static InstallOperation Install() { // TODO: Check to see if it's already installed and skip the installation // process if it is. // // TODO: Provide an option to force-install, which would mean deleting any // existing installation before doing the install. // // TODO: Determine the correct download URL for the current platform. InstallOperation installOp; switch (Application.platform) { case RuntimePlatform.WindowsEditor: installOp = new InstallOperation(WindowsDownloadUrl, InstallRoot, ArchiveType.Zip); break; case RuntimePlatform.OSXEditor: installOp = new InstallOperation(MacosDownloadUrl, InstallRoot, ArchiveType.Tgz); break; case RuntimePlatform.LinuxEditor: installOp = new InstallOperation(LinuxDownloadUrl, InstallRoot, ArchiveType.Tgz); break; default: throw new InvalidOperationException( $"Invalid install platform {Application.platform}"); } installOp.Start(); return installOp; } } }
40.66
191
0.598869
[ "MIT" ]
randomPoison/ripgrep-unity
com.random-poison.ripgrep-unity/Editor/Installer.cs
4,066
C#
using System.Xml.Serialization; namespace Uroskur.Shared.Models; [XmlRoot(ElementName = "trkpt", Namespace = "http://www.topografix.com/GPX/1/1")] public class Trkpt { [XmlAttribute("lat")] public double Lat { get; set; } [XmlAttribute("lon")] public double Lon { get; set; } } [XmlRoot(ElementName = "trkseg", Namespace = "http://www.topografix.com/GPX/1/1")] public class Trkseg { [XmlElement("trkpt")] public List<Trkpt>? TrksegTrkpt { get; set; } } [XmlRoot(ElementName = "trk", Namespace = "http://www.topografix.com/GPX/1/1")] public class Trk { [XmlElement("trkseg")] public Trkseg? Trkseg { get; set; } } [XmlRoot(ElementName = "gpx", Namespace = "http://www.topografix.com/GPX/1/1")] public class Gpx { [XmlElement("trk")] public Trk? Trk { get; set; } }
28.178571
82
0.673004
[ "MIT" ]
ahaggqvist/uroskur
src/Shared/Models/Gpx.cs
791
C#
using System; using System.Threading; using TicTacToe.Game; namespace GameRunner { internal class Program { public static void Main(string[] args) { int gameId = 0; while (true) { gameId++; // var game = gameId%2==0? new Game(new IPlayer[] { new NetworkPlayer(), new MinMaxPlayer(), }) : new Game(new IPlayer[] { new MinMaxPlayer(), new NetworkPlayer() }); var game = new Game(new IPlayer[] {new MinMaxPlayer(), new NetworkPlayer()}); //var game = new Game(new IPlayer[] {new NetworkPlayer(), new ConsolePlayer()}); //var game = new Game(new IPlayer[] {new ConsolePlayer(), new NetworkPlayer()}); var winner = game.PlayGame(); Console.Error.WriteLine(); Console.Error.WriteLine("GAME OVER, WINNER IS: " + winner + " - " + gameId); if (winner != 0) { game._game.PrintBoard(); Thread.Sleep(5000); } } } public static void PrintGame(TicTacToe.Game.TicTacToe ticTacToe) { ticTacToe.PrintBoard(); } } }
34.583333
181
0.506024
[ "MIT" ]
Illedan/SharpNN
SharpNetwork/GameRunner/Program.cs
1,247
C#
namespace AllegroExtended.Web { using System.Data.Entity; using System.Reflection; using System.Web.Mvc; using Autofac; using Autofac.Integration.Mvc; using Controllers; using Data; using Data.Common; using Services.Data; using Services.Web; public static class AutofacConfig { public static void RegisterAutofac() { var builder = new ContainerBuilder(); // Register your MVC controllers. builder.RegisterControllers(typeof(MvcApplication).Assembly); // OPTIONAL: Register model binders that require DI. builder.RegisterModelBinders(Assembly.GetExecutingAssembly()); builder.RegisterModelBinderProvider(); // OPTIONAL: Register web abstractions like HttpContextBase. builder.RegisterModule<AutofacWebTypesModule>(); // OPTIONAL: Enable property injection in view pages. builder.RegisterSource(new ViewRegistrationSource()); // OPTIONAL: Enable property injection into action filters. builder.RegisterFilterProvider(); // Register services RegisterServices(builder); // Set the dependency resolver to be Autofac. var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } private static void RegisterServices(ContainerBuilder builder) { builder.Register(x => new ApplicationDbContext()) .As<DbContext>() .InstancePerRequest(); builder.Register(x => new HttpCacheService()) .As<ICacheService>() .InstancePerRequest(); builder.Register(x => new IdentifierProvider()) .As<IIdentifierProvider>() .InstancePerRequest(); var servicesAssembly = Assembly.GetAssembly(typeof(IAccountRequestService)); builder.RegisterAssemblyTypes(servicesAssembly).AsImplementedInterfaces(); builder.RegisterGeneric(typeof(DbRepository<>)) .As(typeof(IDbRepository<>)) .InstancePerRequest(); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .AssignableTo<BaseController>().PropertiesAutowired(); } } }
33.180556
88
0.627459
[ "MIT" ]
mdraganov/AllegroExtended
Web/AllegroExtended.Web/App_Start/AutofacConfig.cs
2,391
C#
using Content.Server.Xenoarchaeology.XenoArtifacts.Events; using Content.Server.Xenoarchaeology.XenoArtifacts.Effects.Components; using Content.Shared.Disease; using Content.Server.Disease; using Content.Server.Disease.Components; using Robust.Shared.Random; using Robust.Shared.Prototypes; using Content.Shared.Interaction; namespace Content.Server.Xenoarchaeology.XenoArtifacts.Effects.Systems { /// <summary> /// Handles disease-producing artifacts /// </summary> public sealed class DiseaseArtifactSystem : EntitySystem { [Dependency] private readonly IPrototypeManager _prototypeManager = default!; [Dependency] private readonly IRobustRandom _random = default!; [Dependency] private readonly DiseaseSystem _disease = default!; [Dependency] private readonly EntityLookupSystem _lookup = default!; [Dependency] private readonly SharedInteractionSystem _interactionSystem = default!; // TODO: YAML Serializer won't catch this. [ViewVariables(VVAccess.ReadWrite)] public readonly IReadOnlyList<string> ArtifactDiseases = new[] { "VanAusdallsRobovirus", "OwOnavirus", "BleedersBite", "Ultragigacancer", "AMIV" }; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<DiseaseArtifactComponent, MapInitEvent>(OnMapInit); SubscribeLocalEvent<DiseaseArtifactComponent, ArtifactActivatedEvent>(OnActivate); } /// <summary> /// Makes sure this artifact is assigned a disease /// </summary> private void OnMapInit(EntityUid uid, DiseaseArtifactComponent component, MapInitEvent args) { if (component.SpawnDisease != null || ArtifactDiseases.Count == 0) return; var diseaseName = _random.Pick(ArtifactDiseases); if (!_prototypeManager.TryIndex<DiseasePrototype>(diseaseName, out var disease)) { Logger.ErrorS("disease", $"Invalid disease {diseaseName} selected from random diseases."); return; } component.SpawnDisease = disease; } /// <summary> /// When activated, blasts everyone in LOS within n tiles /// with a high-probability disease infection attempt /// </summary> private void OnActivate(EntityUid uid, DiseaseArtifactComponent component, ArtifactActivatedEvent args) { if (component.SpawnDisease == null) return; var xform = Transform(uid); var carrierQuery = GetEntityQuery<DiseaseCarrierComponent>(); foreach (var entity in _lookup.GetEntitiesInRange(xform.Coordinates, component.Range)) { if (!carrierQuery.TryGetComponent(entity, out var carrier)) continue; if (!_interactionSystem.InRangeUnobstructed(uid, entity, component.Range)) continue; _disease.TryInfect(carrier, component.SpawnDisease, forced: true); } } } }
38.170732
111
0.654313
[ "MIT" ]
14th-Batallion-Marine-Corps/14-Marine-Corps
Content.Server/Xenoarchaeology/XenoArtifacts/Effects/Systems/DiseaseArtifactSystem.cs
3,130
C#
namespace Kephas.Model.Tests.Models.ConflictingBaseMembersModel { using Kephas.Model.AttributedModel; [Mixin] public interface IIdentifiable { int Id { get; set; } } [Mixin] public interface INamed : IIdentifiable { string Name { get; set; } } public class EntityBase : IIdentifiable { public int Id { get; set; } } public class NamedEntityBase : EntityBase, INamed { public string Name { get; set; } } }
19.269231
64
0.60479
[ "MIT" ]
kephas-software/kephas
src/Tests/Kephas.Model.Tests/Models/ConflictingBaseMembersModel/ConflictingBaseMembers.cs
503
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("02. Numbers Ending in 7")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02. Numbers Ending in 7")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("d8a05e36-9aa7-472c-b325-8a7eaa8b5af7")] // 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.216216
84
0.744696
[ "MIT" ]
donded/soft-uni-zadachi
Solution2/02. Numbers Ending in 7/Properties/AssemblyInfo.cs
1,417
C#
#if (implement_database || implement_entityframework) using Beef.Database.Core; #endif #if (implement_cosmos) using Beef.Data.Cosmos; #endif using Beef.Test.NUnit; #if (implement_cosmos) using Microsoft.Extensions.Configuration; using Cosmos = Microsoft.Azure.Cosmos; #endif using NUnit.Framework; #if (implement_database || implement_entityframework) using System.Reflection; #endif using System.Threading.Tasks; using Company.AppName.Api; using Company.AppName.Common.Agents; using Company.AppName.Common.Entities; #if (implement_cosmos) using Company.AppName.Business.Data; #endif namespace Company.AppName.Test { [SetUpFixture] public class FixtureSetUp { #if (implement_database || implement_entityframework) [OneTimeSetUp] public void OneTimeSetUp() { TestSetUp.DefaultEnvironmentVariablePrefix = "AppName"; TestSetUp.SetDefaultLocalReferenceData<IReferenceData, ReferenceDataAgentProvider, IReferenceDataAgent, ReferenceDataAgent>(); TestSetUp.AddWebApiAgentArgsType<IAppNameWebApiAgentArgs, AppNameWebApiAgentArgs>(); TestSetUp.DefaultExpectNoEvents = false; var config = AgentTester.BuildConfiguration<Startup>("AppName"); TestSetUp.RegisterSetUp(async (count, _) => { var args = new DatabaseExecutorArgs( count == 0 ? DatabaseExecutorCommand.ResetAndDatabase : DatabaseExecutorCommand.ResetAndData, config["ConnectionStrings:Database"], typeof(Database.Program).Assembly, Assembly.GetExecutingAssembly()) { UseBeefDbo = true }; return await DatabaseExecutor.RunAsync(args).ConfigureAwait(false) == 0; }); } #endif #if (implement_cosmos) private bool _removeAfterUse; private AppNameCosmosDb? _cosmosDb; [OneTimeSetUp] public void OneTimeSetUp() { TestSetUp.DefaultEnvironmentVariablePrefix = "AppName"; TestSetUp.SetDefaultLocalReferenceData<IReferenceData, ReferenceDataAgentProvider, IReferenceDataAgent, ReferenceDataAgent>(); TestSetUp.AddWebApiAgentArgsType<IAppNameWebApiAgentArgs, AppNameWebApiAgentArgs>(); TestSetUp.DefaultExpectNoEvents = false; var config = AgentTester.BuildConfiguration<Startup>("AppName"); TestSetUp.RegisterSetUp(async (count, _) => { var cc = config.GetSection("CosmosDb"); _removeAfterUse = config.GetValue<bool>("RemoveAfterUse"); _cosmosDb = new AppNameCosmosDb(new Cosmos.CosmosClient(cc.GetValue<string>("EndPoint"), cc.GetValue<string>("AuthKey")), cc.GetValue<string>("Database"), createDatabaseIfNotExists: true); var rc = await _cosmosDb.ReplaceOrCreateContainerAsync( new Cosmos.ContainerProperties { Id = "Person", PartitionKeyPath = "/_partitionKey" }, 400).ConfigureAwait(false); await rc.ImportBatchAsync<PersonTest, Person>("Person.yaml", "Person").ConfigureAwait(false); var rdc = await _cosmosDb.ReplaceOrCreateContainerAsync( new Cosmos.ContainerProperties { Id = "RefData", PartitionKeyPath = "/_partitionKey", UniqueKeyPolicy = new Cosmos.UniqueKeyPolicy { UniqueKeys = { new Cosmos.UniqueKey { Paths = { "/type", "/value/code" } } } } }, 400).ConfigureAwait(false); await rdc.ImportValueRefDataBatchAsync<PersonTest, ReferenceData>("RefData.yaml").ConfigureAwait(false); return true; }); } [OneTimeTearDown] public async Task OneTimeTearDown() { if (_cosmosDb != null && _removeAfterUse) await _cosmosDb.Database.DeleteAsync().ConfigureAwait(false); } #endif } }
39.466019
204
0.640836
[ "MIT" ]
ualehosaini/Beef
templates/Beef.Template.Solution/content/Company.AppName.Test/FixtureSetup.cs
4,067
C#
// Copyright 2009 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Reflection; using System.Reflection.Emit; using System.Collections.Generic; using DBus; using org.freedesktop.DBus; public class ManagedDBusTestRental { public static void Main () { Bus bus = Bus.Session; string bus_name = "org.ndesk.test"; ObjectPath path = new ObjectPath ("/org/ndesk/test"); ObjectPath cppath = new ObjectPath ("/org/ndesk/CodeProvider"); IDemoOne demo; if (bus.RequestName (bus_name) == RequestNameReply.PrimaryOwner) { //create a new instance of the object to be exported demo = new Demo (); bus.Register (path, demo); DCodeProvider dcp = new DCodeProvider(); bus.Register (cppath, dcp); //run the main loop while (true) bus.Iterate (); } else { //import a remote to a local proxy //demo = bus.GetObject<IDemo> (bus_name, path); demo = bus.GetObject<DemoProx> (bus_name, path); //RunTest (demo); ICodeProvider idcp = bus.GetObject<ICodeProvider> (bus_name, cppath); DMethodInfo dmi = idcp.GetMethod ("DemoProx", "SayRepeatedly"); DArgumentInfo[] fields = idcp.GetFields ("DemoProx"); foreach (DArgumentInfo field in fields) Console.WriteLine("Field: " + field.Name); //DynamicMethod dm = new DynamicMethod (dmi.Name, typeof(void), new Type[] { typeof(object), typeof(int), typeof(string) }, typeof(DemoBase)); //ILGenerator ilg = dm.GetILGenerator (); //dmi.Implement (ilg); DynamicMethod dm = dmi.GetDM (); SayRepeatedlyHandler cb = (SayRepeatedlyHandler)dm.CreateDelegate (typeof (SayRepeatedlyHandler), demo); int retVal; retVal = cb (12, "Works!"); Console.WriteLine("retVal: " + retVal); /* for (int i = 0 ; i != dmi.Code.Length ; i++) { if (!dmi.Code[i].Emit(ilg)) throw new Exception(String.Format("Code gen failure at i={0} {1}", i, dmi.Code[i].opCode)); } */ //SayRepeatedlyHandler } } public static void RunTest (IDemoOne demo) { Console.WriteLine (); demo.SomeEvent += HandleSomeEventA; demo.FireOffSomeEvent (); Console.WriteLine (); demo.SomeEvent -= HandleSomeEventA; demo.FireOffSomeEvent (); Console.WriteLine (); demo.SomeEvent += delegate (string arg1, object arg2, double arg3, MyTuple mt) {Console.WriteLine ("SomeEvent handler: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B);}; demo.SomeEvent += delegate (string arg1, object arg2, double arg3, MyTuple mt) {Console.WriteLine ("SomeEvent handler two: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B);}; demo.FireOffSomeEvent (); Console.WriteLine (); Console.WriteLine (demo.GetSomeVariant ()); Console.WriteLine (); demo.Say2 ("demo.Say2"); ((IDemoTwo)demo).Say2 ("((IDemoTwo)demo).Say2"); demo.SayEnum (DemoEnum.Bar, DemoEnum.Foo); /* uint n; string ostr; demo.WithOutParameters (out n, "21", out ostr); Console.WriteLine ("n: " + n); Console.WriteLine ("ostr: " + ostr); */ /* IDemoOne[] objs = demo.GetObjArr (); foreach (IDemoOne obj in objs) obj.Say ("Some obj"); */ Console.WriteLine("SomeProp: " + demo.SomeProp); demo.SomeProp = 321; DemoProx demoProx = demo as DemoProx; if (demoProx != null) { //demoProx.SayRepeatedly(5, "Repetition"); //demoProx.GetType().InvokeMember("RepProx", System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, null, new object[] {demoProx, 5, "Lala"}); //demoProx.GetType().GetMethod("RepProx").Invoke(null, new object[] {demoProx, 5, "Lala"}); demoProx.GetType().GetMethod("RepProx", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static).Invoke(null, new object[] {demoProx, 5, "Lala"}); //demoProx.GetType().InvokeMember("RepProx", System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, demoProx, new object[] {5, "Lala"}); } demo.ThrowSomeException (); } public static void HandleSomeEventA (string arg1, object arg2, double arg3, MyTuple mt) { Console.WriteLine ("SomeEvent handler A: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B); } public static void HandleSomeEventB (string arg1, object arg2, double arg3, MyTuple mt) { Console.WriteLine ("SomeEvent handler B: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B); } } public delegate int SayRepeatedlyHandler (int count, string str); [Interface ("org.ndesk.CodeProvider")] public interface ICodeProvider { //DTypeInfo GetInterface (string iface); DArgumentInfo[] GetFields (string iface); DMethodInfo GetMethod (string iface, string name); } [Interface ("org.ndesk.CodeProvider2")] public interface ICodeProvider2 { DMethodInfo GetMethod (string name); } public struct DMethodBody { public string[] Locals; public ILReader2.ILOp[] Code; public void DeclareLocals(ILGenerator ilg) { foreach (string local in Locals) { Type t; if (!ILReader2.TryGetType(local, out t)) break; ilg.DeclareLocal(t); } } } public struct DMethodInfo { public string Name; public DTypeInfo DeclaringInterface; public DTypeInfo[] Parameters; //public DArgumentInfo[] Arguments; public DTypeInfo ReturnType; public DMethodBody Body; public void Implement(ILGenerator ilg) { DMethodBody body = Body; body.DeclareLocals(ilg); for (int i = 0 ; i != body.Code.Length ; i++) { if (!body.Code[i].Emit(ilg)) throw new Exception(String.Format("Code gen failure at i={0} {1}", i, body.Code[i].opCode)); } } public DynamicMethod GetDM () { List<Type> parms = new List<Type>(); parms.Add(typeof(object)); foreach (DTypeInfo dti in Parameters) parms.Add(dti.ToType()); DynamicMethod dm = new DynamicMethod (Name, ReturnType.ToType(), parms.ToArray(), typeof(DemoBase)); ILGenerator ilg = dm.GetILGenerator(); Implement(ilg); return dm; } } public enum DArgumentDirection { In, Out, } public struct DArgumentInfo { public DArgumentInfo(DTypeInfo argType) : this(String.Empty, argType) { } public DArgumentInfo(string name, DTypeInfo argType) : this(name, argType, DArgumentDirection.In) { } public DArgumentInfo(string name, DTypeInfo argType, DArgumentDirection direction) { this.Name = name; this.ArgType = argType; this.Direction = direction; } public string Name; public DTypeInfo ArgType; public DArgumentDirection Direction; } public struct DTypeInfo : ICodeProvider2 { public DTypeInfo(string name) { this.Name = name; //this.Fields = new DArgumentInfo[0]; } public Type ToType() { Type t; if (!ILReader2.TryGetType(Name, out t)) return null; return t; } public string Name; //public DMethodInfo[] Methods; //public DArgumentInfo[] Fields; public DMethodInfo GetMethod (string name) { throw new NotImplementedException(); } } public class DCodeProvider : ICodeProvider { //public DTypeInfo GetInterface (string iface) public DArgumentInfo[] GetFields (string iface) { DTypeInfo dti = new DTypeInfo (iface); Type declType = dti.ToType(); List<DArgumentInfo> fields = new List<DArgumentInfo>(); foreach (FieldInfo fi in declType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)) fields.Add (new DArgumentInfo(fi.Name, new DTypeInfo(fi.FieldType.FullName))); //return dti; return fields.ToArray(); } public DMethodInfo GetMethod (string iface, string name) { DMethodInfo dmi = new DMethodInfo (); dmi.Name = name; dmi.DeclaringInterface = new DTypeInfo(iface); Type declType = dmi.DeclaringInterface.ToType(); MethodInfo mi = declType.GetMethod(name); List<string> locals = new List<string>(); MethodBody body = mi.GetMethodBody (); foreach (LocalVariableInfo lvar in body.LocalVariables) locals.Add(lvar.LocalType.FullName); dmi.Body.Locals = locals.ToArray(); List<DTypeInfo> parms = new List<DTypeInfo>(); foreach (ParameterInfo parm in mi.GetParameters()) parms.Add(new DTypeInfo(parm.ParameterType.FullName)); dmi.Parameters = parms.ToArray(); dmi.ReturnType = new DTypeInfo(mi.ReturnType.FullName); ILReader2 ilr = new ILReader2(mi); dmi.Body.Code = ilr.Iterate(); return dmi; } } [Interface ("org.ndesk.test")] public interface IDemoOne { event SomeEventHandler SomeEvent; void FireOffSomeEvent (); void Say (object var); void SayEnum (DemoEnum a, DemoEnum b); void Say2 (string str); object GetSomeVariant (); void ThrowSomeException (); void WithOutParameters (out uint n, string str, out string ostr); IDemoOne[] GetEmptyObjArr (); IDemoOne[] GetObjArr (); int SomeProp { get; set; } } [Interface ("org.ndesk.test2")] public interface IDemoTwo { int Say (string str); void Say2 (string str); } public interface IDemo : IDemoOne, IDemoTwo { } public abstract class DemoProx : DemoBase { public int cache = 0; public virtual int SayRepeatedly (int count, string str) { Say2(cache.ToString()); for (int i = 0 ; i != count ; i++) //Say2("Woo! " + str); Say2(str); //Console.WriteLine("This is a local CWL"); //Say2("FIXED"); //Console.WriteLine(); //Console.WriteLine(str); // /* { string fa = "lala"; fa += "bar"; Say2(fa); } */ return 12; } } public class Demo : DemoBase { public override void Say2 (string str) { Console.WriteLine ("Subclassed IDemoOne.Say2: " + str); } } public class DemoBase : IDemo { public event SomeEventHandler SomeEvent; public void Say (object var) { Console.WriteLine ("variant: " + var); } public int Say (string str) { Console.WriteLine ("string: " + str); return str.Length; } public void SayEnum (DemoEnum a, DemoEnum b) { Console.WriteLine ("SayEnum: " + a + ", " + b); } public virtual void Say2 (string str) { Console.WriteLine ("IDemoOne.Say2: " + str); } void IDemoTwo.Say2 (string str) { Console.WriteLine ("IDemoTwo.Say2: " + str); } public void FireOffSomeEvent () { Console.WriteLine ("Asked to fire off SomeEvent"); MyTuple mt; mt.A = "a"; mt.B = "b"; if (SomeEvent != null) { SomeEvent ("some string", 21, 19.84, mt); Console.WriteLine ("Fired off SomeEvent"); } } public object GetSomeVariant () { Console.WriteLine ("GetSomeVariant()"); return new byte[0]; } public void ThrowSomeException () { throw new Exception ("Some exception"); } public void WithOutParameters (out uint n, string str, out string ostr) { n = UInt32.Parse (str); ostr = "." + str + "."; } public IDemoOne[] GetEmptyObjArr () { return new Demo[] {}; } public IDemoOne[] GetObjArr () { return new IDemoOne[] {this}; } public int SomeProp { get { return 123; } set { Console.WriteLine ("Set SomeProp: " + value); } } } public enum DemoEnum : byte { Foo, Bar, } public struct MyTuple { public string A; public string B; } public delegate void SomeEventHandler (string arg1, object arg2, double arg3, MyTuple mt);
24.012987
221
0.683252
[ "MIT" ]
AaltoNEPPI/dbus-sharp
examples/TestRental.cs
11,094
C#
using System.Runtime.CompilerServices; namespace System.Html.Media.Graphics.SVG { [IgnoreNamespace, Imported(ObeysTypeSystem = true)] public partial class SVGForeignObjectElement : SVGGraphicsElement { internal SVGForeignObjectElement() { } public void AddEventListener(string type, HtmlEventHandlerWithTarget<SVGForeignObjectElement> listener) { } public void AddEventListener(string type, HtmlEventHandlerWithTarget<SVGForeignObjectElement> listener, bool capture) { } public void AddEventListener(SVGForeignObjectElementEvents type, Action listener) { } public void AddEventListener(SVGForeignObjectElementEvents type, Action listener, bool capture) { } public void AddEventListener(SVGForeignObjectElementEvents type, HtmlEventHandler listener) { } public void AddEventListener(SVGForeignObjectElementEvents type, HtmlEventHandler listener, bool capture) { } public void AddEventListener(SVGForeignObjectElementEvents type, HtmlEventHandlerWithTarget<SVGForeignObjectElement> listener) { } public void AddEventListener(SVGForeignObjectElementEvents type, HtmlEventHandlerWithTarget<SVGForeignObjectElement> listener, bool capture) { } public void AddEventListener(SVGForeignObjectElementEvents type, IEventListener listener) { } public void AddEventListener(SVGForeignObjectElementEvents type, IEventListener listener, bool capture) { } [IntrinsicProperty] public SVGAnimatedLength Height { get { return default(SVGAnimatedLength); } } public void RemoveEventListener(string type, HtmlEventHandlerWithTarget<SVGForeignObjectElement> listener) { } public void RemoveEventListener(string type, HtmlEventHandlerWithTarget<SVGForeignObjectElement> listener, bool capture) { } public void RemoveEventListener(SVGForeignObjectElementEvents type, Action listener) { } public void RemoveEventListener(SVGForeignObjectElementEvents type, Action listener, bool capture) { } public void RemoveEventListener(SVGForeignObjectElementEvents type, HtmlEventHandler listener) { } public void RemoveEventListener(SVGForeignObjectElementEvents type, HtmlEventHandler listener, bool capture) { } public void RemoveEventListener(SVGForeignObjectElementEvents type, HtmlEventHandlerWithTarget<SVGForeignObjectElement> listener) { } public void RemoveEventListener(SVGForeignObjectElementEvents type, HtmlEventHandlerWithTarget<SVGForeignObjectElement> listener, bool capture) { } public void RemoveEventListener(SVGForeignObjectElementEvents type, IEventListener listener) { } public void RemoveEventListener(SVGForeignObjectElementEvents type, IEventListener listener, bool capture) { } [IntrinsicProperty] public SVGAnimatedLength Width { get { return default(SVGAnimatedLength); } } [IntrinsicProperty] public SVGAnimatedLength X { get { return default(SVGAnimatedLength); } } [IntrinsicProperty] public SVGAnimatedLength Y { get { return default(SVGAnimatedLength); } } } }
30.989796
147
0.800132
[ "Apache-2.0" ]
Saltarelle/SaltarelleWeb
Web/Generated/Html/Media/Graphics/SVG/SVGForeignObjectElement.cs
3,039
C#
 using ChakraCore.NET.API; using System; using System.Collections.Generic; using System.Text; namespace ChakraCore.NET { public partial class JSValueBinding : ServiceConsumerBase { IJSValueConverterService Converter => this.ServiceNode.GetService<IJSValueConverterService>(); IJSValueService ValueService => this.ServiceNode.GetService<IJSValueService>(); readonly JavaScriptValue _jsValue; public JSValueBinding(IServiceNode parentNode, JavaScriptValue value) : base(parentNode, "JSValueBinding") { this._jsValue = value; } public void SetMethod(string name, Delegate a) { this.Converter.RegisterMethodConverter(a); this.ValueService.WriteProperty(this._jsValue, name, a.GetType(), a); } } }
31.384615
114
0.692402
[ "MIT" ]
michaelcoxon/ChakraCore.NET
source/ChakraCore.NET.Core/JSValueBinding.cs
818
C#
using System; using System.Xml.Serialization; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; using JdSdk.Request; using JdSdk.Response.Im; namespace JdSdk.Request.Im {  public class ImPopChatlogFuzzyQueryRequest : JdRequestBase<ImPopChatlogFuzzyQueryResponse> { public String Waiter { get; set; } public String Customer { get; set; } public String KeyWord { get; set; } public Nullable<DateTime> StartTime { get; set; } public Nullable<DateTime> EndTime { get; set; } public Nullable<Int32> Page { get; set; } public Nullable<Int32> PageSize { get; set; } public override String ApiName { get{ return "jingdong.im.pop.chatlog.fuzzy.query"; } } protected override void PrepareParam(IDictionary<String, Object> paramters) { paramters.Add("waiter" ,this.Waiter); paramters.Add("customer" ,this.Customer); paramters.Add("keyWord" ,this.KeyWord); paramters.Add("startTime" ,this.StartTime); paramters.Add("endTime" ,this.EndTime); paramters.Add("page" ,this.Page); paramters.Add("pageSize" ,this.PageSize); } } }
20.932432
95
0.517108
[ "Apache-2.0" ]
starpeng/JdSdk2
Source/JdSdk/request/im/ImPopChatlogFuzzyQueryRequest.cs
1,555
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace EventCore { public abstract class DelegateEventStore : IEventStore { private readonly IEventStore _eventStore; protected DelegateEventStore(IEventStore eventStore) { _eventStore = eventStore; } public virtual Task AppendAsync(IEnumerable<UncommittedEvent> uncommitted) { return _eventStore.AppendAsync(uncommitted); } public virtual IEnumerable<Event> GetEnumerable(long minId = 1, long maxId = long.MaxValue) { return _eventStore.GetEnumerable(minId, maxId); } public virtual IEnumerable<Event> GetEnumerableStream(Guid streamId, int minSequenceNumber = 1, int maxSequenceNumber = int.MaxValue) { return _eventStore.GetEnumerableStream(streamId, minSequenceNumber, maxSequenceNumber); } } }
29.6875
141
0.678947
[ "MIT" ]
tessin/event-store
SqlEventStore/DelegateEventStore.cs
952
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime:4.0.30319.42000 // // Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si // se vuelve a generar el código. // </auto-generated> //------------------------------------------------------------------------------ namespace Farmacia.Properties { using System; /// <summary> /// Clase de recurso fuertemente tipado, para buscar cadenas traducidas, etc. /// </summary> // StronglyTypedResourceBuilder generó automáticamente esta clase // a través de una herramienta como ResGen o Visual Studio. // Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen // con la opción /str o recompile su proyecto de VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Devuelve la instancia de ResourceManager almacenada en caché utilizada por esta clase. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Farmacia.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Reemplaza la propiedad CurrentUICulture del subproceso actual para todas las /// búsquedas de recursos mediante esta clase de recurso fuertemente tipado. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Busca un recurso adaptado de tipo System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap logo_farmacia { get { object obj = ResourceManager.GetObject("logo farmacia", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
44.391892
174
0.614612
[ "MIT" ]
Checha504/Farmacia
Farmacia/Properties/Resources.Designer.cs
3,299
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace CheckMvc { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
23.75
63
0.562105
[ "Apache-2.0" ]
BruceCowan-AI/ServiceStack
tests/CheckMvc/App_Start/WebApiConfig.cs
458
C#
using Godot; using System; using System.Collections.Generic; public class DitherTool : Tool { public override KeyList shortcut { get { return KeyList.D; } } public override bool NeedsUpdate() { return Input.IsActionJustPressed("Mouse1") || Input.IsActionJustReleased("Mouse1"); } public DitherTool() { } public DitherTool(Main m, ToolsPopUp p) : base(m, p) { } public override Button GetButton() { Button Output = Button.Instance<Button>(); Output.Text = "I"; Output.HintTooltip = "(D)ither Tool"; return Output; } List<PencilUndo> Undos = new List<PencilUndo>(); Control Toolbar; OptionButton intensity; Label posLabel; public override Control GetHelpBar() { if (Toolbar is null) { Toolbar = GD.Load<PackedScene>("res://Tools/DitherToolbar.tscn").Instance<Control>(); intensity = Toolbar.GetNode<OptionButton>("Intensity"); posLabel = Toolbar.GetNode<Label>("Pos"); } return Toolbar; } public override void DestroyOrphans() { if (Toolbar != null) Toolbar.QueueFree(); } bool Active = false; Vector2 lastPix = Vector2.Zero; public override void Process(Layer Layer, Vector2 pix, BrushInfo info) { if (Input.IsActionJustPressed("Mouse1") && Layer.Canvas.HasPoint(pix * Layer.Canvas.RectSize / Layer.Img.GetSize()) && !Active) { Active = true; lastPix = pix; Undos.Insert(0, new PencilUndo() { FocusLayer = Layer, UndoState = new Dictionary<Vector2, Color>() }); } if (Input.IsActionJustReleased("Mouse1") && Active) { if (Undos[0].UndoState.Count > 0) Layer.AddUndoable(this); else Undos.RemoveAt(0); Active = false; } if (Active) { Layer.Lock(); DitherDraw(Layer.Img, pix, info); Layer.Unlock(); if ((lastPix - pix).Length() > 1.9f) { Layer.Lock(); foreach (Vector2 v in Utils.GetBresenhamLine(lastPix, pix)) { DitherDraw(Layer.Img, v, info); } Layer.Unlock(); } } lastPix = pix; } public override void PreviewProcess(TextureRect Overlay, Image OverlayImg, Vector2 pix, BrushInfo info) { posLabel.Text = "" + pix; OverlayImg.SetPixelv(Utils.ClampV(Vector2.Zero, pix, OverlayImg.GetSize() - Vector2.One), GetColor(pix, info)); } private void DitherDraw(Image To, Vector2 pix, BrushInfo info) { if (Utils.VecHasPoint(To.GetSize(), pix)) { Color Old = To.GetPixelv(pix); Color New = GetColor(pix, info); To.SetPixelv(pix, New); if (!Undos[0].UndoState.ContainsKey(pix)) Undos[0].UndoState[pix] = Old; } } static Dictionary<int, ushort> ditherPatterns = new Dictionary<int, ushort>() { {0, 32768}, {1, 32800}, {2, 41120}, {3, 42145}, {4, 42405} }; private Color GetColor(Vector2 pix, BrushInfo info) { int mode = intensity.Selected; bool flip = mode > 4; mode = 4-Utils.AbsI(mode - 4); ushort pos = (ushort)(((ushort)pix.x) % 4); pos = (ushort)(pos + ((((ushort)pix.y) % 4)*4)); flip = ((ditherPatterns[mode] >> pos) & 1) == 1 == flip; return flip ? info.Albedo1 : info.Albedo2; } public override bool Undo(Layer target) { int LastAction = -1; for (int i = 0; i < Undos.Count; i++) { if (Undos[i].FocusLayer == target) { LastAction = i; break; } } if (LastAction == -1) return true; foreach (Vector2 v in Undos[LastAction].UndoState.Keys) { target.Img.SetPixelv(v, Undos[LastAction].UndoState[v]); } Undos.RemoveAt(LastAction); return true; } const string key = "dither"; public override void SaveSettings(Dictionary<string, Dictionary<string, float>> dict) { if (Toolbar == null) return; dict.Add(key, new Dictionary<string, float>()); dict[key].Add("amt_index", intensity.Selected); } public override void LoadSettings(Dictionary<string, Dictionary<string, float>> dict) { if (!dict.ContainsKey(key)) return; float amountIndex; if (dict[key].TryGetValue("amt_index", out amountIndex)) { GetHelpBar(); intensity.Selected = (int)amountIndex; } } }
28.233533
135
0.553977
[ "MIT" ]
AnotherPompousDunmer/ChimeraSpriteEditor
Tools/DitherTool.cs
4,717
C#
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; namespace XmlSerialization { // this is something called "POCO" plain old clr object // a class with just public get-set properties and a default constructor // "DTO" data transfer object public class Person { private int _id; [XmlAttribute] // will do "Id="15"" instead of "<Id>15</Id>" public int Id { get => _id; set => _id = value; } [XmlElement(ElementName = "FirstName")] // change the name of the element used in the XML public string Name { get; set; } //[XmlIgnore] hide this property from XMLSerializer entirely public Address Address { get; set; } } }
29.88
97
0.65328
[ "MIT" ]
200106-UTA-PRS-NET/training-code
01CSharp/XmlSerialization/XmlSerialization/Person.cs
749
C#
using Autofac; using JetBrains.Annotations; using SharpLab.Server.Caching.Internal; using SharpLab.Server.Common; namespace SharpLab.Server.Caching { [UsedImplicitly] public class CachingModule : Module { protected override void Load(ContainerBuilder builder) { var webAppName = EnvironmentHelper.GetRequiredEnvironmentVariable("SHARPLAB_WEBAPP_NAME"); var branchId = webAppName.StartsWith("sl-") ? webAppName : null; builder.RegisterType<ResultCacheBuilder>() .As<IResultCacheBuilder>() .WithParameter("branchId", branchId) .SingleInstance(); builder.RegisterType<ResultCacher>() .As<IResultCacher>() .SingleInstance(); } } }
35.73913
103
0.615572
[ "BSD-2-Clause" ]
Fantoom/SharpLab
source/Server/Caching/CachingModule.cs
822
C#