content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alexis Kochetov // Created: 2009.05.08 using System; using System.Globalization; using NUnit.Framework; namespace Xtensive.Orm.Tests.Core.Comparison { [TestFixture] public class StringComparisonTest { [Ignore("")] [Test] public void StringCompare() { // var x = "X" + char.MaxValue + char.MaxValue; int z = char.MaxValue; int z1 = short.MaxValue; int z2 = ushort.MaxValue; string x = "X" + (char) 0xDBFF + (char) 0xDFFF; string y = "X"; string a = "" + (char)0xDBFF + (char)0xDFFF + (char)0xDBFF + (char)0xDFFF; string b = "" + (char)0xDBFF + (char)0xDFFF; var ordinal = string.CompareOrdinal(a, b); var ordinal2 = CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.None); // CultureInfo.CurrentCulture.TextInfo. foreach (CultureInfo cultureInfo in CultureInfo.GetCultures(CultureTypes.AllCultures)) { TestLog.Info(cultureInfo.EnglishName); int result = cultureInfo.CompareInfo.Compare(x, y, CompareOptions.None); Assert.Greater(result, 0); result = cultureInfo.CompareInfo.Compare(x, y, CompareOptions.IgnoreKanaType); Assert.Greater(result, 0); result = cultureInfo.CompareInfo.Compare(x, y, CompareOptions.Ordinal); Assert.Greater(result, 0); result = cultureInfo.CompareInfo.Compare(x, y, CompareOptions.OrdinalIgnoreCase); Assert.Greater(result, 0); result = cultureInfo.CompareInfo.Compare(x, y, CompareOptions.StringSort); Assert.Greater(result, 0); } Func<string, string, int> compare0 = CultureInfo.GetCultureInfo(0x7c04).CompareInfo.Compare; Func<string, string, int> compare1 = CultureInfo.CurrentCulture.CompareInfo.Compare; Func<string, string, int> compare2 = CultureInfo.InvariantCulture.CompareInfo.Compare; Func<string, string, CompareOptions, int> compare3 = CultureInfo.CurrentCulture.CompareInfo.Compare; Func<string, string, CompareOptions, int> compare4 = CultureInfo.CurrentCulture.CompareInfo.Compare; Func<string, string, int> compare5 = string.Compare; int actual0 = compare0(x, y); int actual1 = compare1(x, y); int actual2 = compare2(x, y); int actual3 = compare3(x, y, CompareOptions.None); int actual4 = compare4(x, y, CompareOptions.None); int actual5 = compare3(x, y, CompareOptions.Ordinal); int actual6 = compare4(x, y, CompareOptions.Ordinal); int actual7 = compare5(x, y); int i = 0; Assert.Greater(actual0, 0); Assert.Greater(actual1, 0); Assert.Greater(actual2, 0); Assert.Greater(actual3, 0); Assert.Greater(actual4, 0); Assert.Greater(actual5, 0); Assert.Greater(actual6, 0); Assert.Greater(actual7, 0); } [Test] public void PerformanceTest() { const int iterationCount = 10000000; var a = "ASDFGHJK KQ WE RTYUI ZXCV BNDFGHJTY UI XCV BNDF GHJRTYVBNV BN"; var b = "ASDFGHJK KQ WE RTYUI ZXCV BNDFGHJTY UI KJHFVB<J BNDFGHJTY UI XCV BNDF GHJRTYVBNV BN"; Func<string, string, CompareOptions, int> cultureCompare = CultureInfo.CurrentCulture.CompareInfo.Compare; Func<string, string, CompareOptions, int> invariantCompare = CultureInfo.CurrentCulture.CompareInfo.Compare; Func<string, string, int> ordinalCompare = string.CompareOrdinal; TestLog.Info("Testing performance of string comparison..."); using (new Measurement("string.CompareOrdinal", iterationCount)) for (int i = 0; i < iterationCount; i++) ordinalCompare(a, b); using (new Measurement("CurrentCulture Compare default", iterationCount)) for (int i = 0; i < iterationCount; i++) cultureCompare(a, b, CompareOptions.None); using (new Measurement("CurrentCulture Compare ordinal", iterationCount)) for (int i = 0; i < iterationCount; i++) cultureCompare(a, b, CompareOptions.Ordinal); using (new Measurement("InvariantCulture Compare default", iterationCount)) for (int i = 0; i < iterationCount; i++) invariantCompare(a, b, CompareOptions.None); using (new Measurement("InvariantCulture Compare ordinal", iterationCount)) for (int i = 0; i < iterationCount; i++) invariantCompare(a, b, CompareOptions.Ordinal); } } }
42.093458
114
0.674067
[ "MIT" ]
NekrasovSt/dataobjects-net
Orm/Xtensive.Orm.Tests.Core/Comparison/StringComparisonTest.cs
4,504
C#
namespace FlockingBirds.Configurator.Dependencies { using ViewModels; public class ViewModelsLocator { private readonly Container container; public ViewModelsLocator() { this.container = new Container(); } public IMainWindowViewModel MainWindowViewModel { get { return this.container.Resolve<IMainWindowViewModel>(); } } } }
21.25
74
0.621176
[ "MIT" ]
pwasiewicz/flockingbirds
FlockingBirds.Configurator/Dependencies/ViewModelsLocator.cs
427
C#
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.Recognizers.Definitions.Spanish; using Microsoft.Recognizers.Text.DateTime.Spanish.Utilities; using Microsoft.Recognizers.Text.DateTime.Utilities; using Microsoft.Recognizers.Text.Number; using Microsoft.Recognizers.Text.Utilities; namespace Microsoft.Recognizers.Text.DateTime.Spanish { public class SpanishTimePeriodExtractorConfiguration : BaseDateTimeOptionsConfiguration, ITimePeriodExtractorConfiguration { public static readonly string ExtractorName = Constants.SYS_DATETIME_TIMEPERIOD; // "TimePeriod"; public static readonly Regex HourNumRegex = new Regex(DateTimeDefinitions.TimeHourNumRegex, RegexFlags); public static readonly Regex PureNumFromTo = new Regex(DateTimeDefinitions.PureNumFromTo, RegexFlags); public static readonly Regex PureNumBetweenAnd = new Regex(DateTimeDefinitions.PureNumBetweenAnd, RegexFlags); public static readonly Regex SpecificTimeFromTo = new Regex(DateTimeDefinitions.SpecificTimeFromTo, RegexFlags); public static readonly Regex SpecificTimeBetweenAnd = new Regex(DateTimeDefinitions.SpecificTimeBetweenAnd, RegexFlags); public static readonly Regex UnitRegex = new Regex(DateTimeDefinitions.TimeUnitRegex, RegexFlags); public static readonly Regex FollowedUnit = new Regex(DateTimeDefinitions.TimeFollowedUnit, RegexFlags); public static readonly Regex NumberCombinedWithUnit = new Regex(DateTimeDefinitions.TimeNumberCombinedWithUnit, RegexFlags); public static readonly Regex TimeOfDayRegex = new Regex(DateTimeDefinitions.TimeOfDayRegex, RegexFlags); public static readonly Regex GeneralEndingRegex = new Regex(DateTimeDefinitions.GeneralEndingRegex, RegexFlags); public static readonly Regex TillRegex = new Regex(DateTimeDefinitions.TillRegex, RegexFlags); private const RegexOptions RegexFlags = RegexOptions.Singleline | RegexOptions.ExplicitCapture; private static readonly Regex FromRegex = new Regex(DateTimeDefinitions.FromRegex, RegexFlags); private static readonly Regex RangeConnectorRegex = new Regex(DateTimeDefinitions.RangeConnectorRegex, RegexFlags); private static readonly Regex BetweenRegex = new Regex(DateTimeDefinitions.BetweenRegex, RegexFlags); public SpanishTimePeriodExtractorConfiguration(IDateTimeOptionsConfiguration config) : base(config) { TokenBeforeDate = DateTimeDefinitions.TokenBeforeDate; SingleTimeExtractor = new BaseTimeExtractor(new SpanishTimeExtractorConfiguration(this)); UtilityConfiguration = new SpanishDatetimeUtilityConfiguration(); var numOptions = NumberOptions.None; if ((config.Options & DateTimeOptions.NoProtoCache) != 0) { numOptions = NumberOptions.NoProtoCache; } var numConfig = new BaseNumberOptionsConfiguration(config.Culture, numOptions); IntegerExtractor = Number.Spanish.IntegerExtractor.GetInstance(numConfig); TimeZoneExtractor = new BaseTimeZoneExtractor(new SpanishTimeZoneExtractorConfiguration(this)); } public string TokenBeforeDate { get; } public IDateTimeUtilityConfiguration UtilityConfiguration { get; } public IDateTimeExtractor SingleTimeExtractor { get; } public IExtractor IntegerExtractor { get; } public IDateTimeExtractor TimeZoneExtractor { get; } public IEnumerable<Regex> SimpleCasesRegex => new Regex[] { PureNumFromTo, PureNumBetweenAnd, SpecificTimeFromTo, SpecificTimeBetweenAnd }; public IEnumerable<Regex> PureNumberRegex => new Regex[] { PureNumFromTo, PureNumBetweenAnd }; bool ITimePeriodExtractorConfiguration.CheckBothBeforeAfter => DateTimeDefinitions.CheckBothBeforeAfter; Regex ITimePeriodExtractorConfiguration.TillRegex => TillRegex; Regex ITimePeriodExtractorConfiguration.TimeOfDayRegex => TimeOfDayRegex; Regex ITimePeriodExtractorConfiguration.GeneralEndingRegex => GeneralEndingRegex; public bool GetFromTokenIndex(string text, out int index) { index = -1; var fromMatch = FromRegex.Match(text); if (fromMatch.Success) { index = fromMatch.Index; } return fromMatch.Success; } public bool GetBetweenTokenIndex(string text, out int index) { index = -1; var match = BetweenRegex.Match(text); if (match.Success) { index = match.Index; } return match.Success; } public bool IsConnectorToken(string text) { return RangeConnectorRegex.IsExactMatch(text, true); } // In Spanish "mañana" can mean both "tomorrow" and "morning". This method filters the isolated occurrences of "mañana" from the // TimePeriodExtractor results as it is more likely to mean "tomorrow" in these cases (unless it is preceded by "la"). public List<ExtractResult> ApplyPotentialPeriodAmbiguityHotfix(string text, List<ExtractResult> timePeriodErs) { { var tomorrowStr = DateTimeDefinitions.MorningTermList[0]; var morningStr = DateTimeDefinitions.MorningTermList[1]; List<ExtractResult> timePeriodErsResult = new List<ExtractResult>(); foreach (var timePeriodEr in timePeriodErs) { if (timePeriodEr.Text.Equals(tomorrowStr, StringComparison.Ordinal)) { if (text.Substring(0, (int)timePeriodEr.Start + (int)timePeriodEr.Length).EndsWith(morningStr, StringComparison.Ordinal)) { timePeriodErsResult.Add(timePeriodEr); } } else { timePeriodErsResult.Add(timePeriodEr); } } return timePeriodErsResult; } } } }
41.1125
148
0.65339
[ "MIT" ]
QPC-database/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DateTime/Spanish/Extractors/SpanishTimePeriodExtractorConfiguration.cs
6,582
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.Payroll { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Put_Tax_Levy_Deduction_Restriction_ResponseType : INotifyPropertyChanged { private Tax_LevyObjectType tax_Levy_ReferenceField; private Tax_Levy_Deduction_Restriction_DataType[] tax_Levy_Deduction_Restriction_DataField; private string versionField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement(Order = 0)] public Tax_LevyObjectType Tax_Levy_Reference { get { return this.tax_Levy_ReferenceField; } set { this.tax_Levy_ReferenceField = value; this.RaisePropertyChanged("Tax_Levy_Reference"); } } [XmlElement("Tax_Levy_Deduction_Restriction_Data", Order = 1)] public Tax_Levy_Deduction_Restriction_DataType[] Tax_Levy_Deduction_Restriction_Data { get { return this.tax_Levy_Deduction_Restriction_DataField; } set { this.tax_Levy_Deduction_Restriction_DataField = value; this.RaisePropertyChanged("Tax_Levy_Deduction_Restriction_Data"); } } [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string version { get { return this.versionField; } set { this.versionField = value; this.RaisePropertyChanged("version"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
24.311688
136
0.762286
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.Payroll/Put_Tax_Levy_Deduction_Restriction_ResponseType.cs
1,872
C#
using Newtonsoft.Json; using Okex.Net.Converters; using Okex.Net.Enums; namespace Okex.Net.RestObjects.Funding { public class OkexTransferResponse { [JsonProperty("ccy")] public string Currency { get; set; } [JsonProperty("transId")] public long? TransferId { get; set; } [JsonProperty("amt")] public decimal Amount { get; set; } [JsonProperty("from"), JsonConverter(typeof(AccountConverter))] public OkexAccount From { get; set; } [JsonProperty("to"), JsonConverter(typeof(AccountConverter))] public OkexAccount To { get; set; } } }
26.291667
71
0.635499
[ "MIT" ]
EricGarnier/OKEx.Net
Okex.Net/RestObjects/Funding/OkexTransferResponse.cs
633
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using System.Collections.Generic; using Microsoft.PowerFx.Core.Binding; using Microsoft.PowerFx.Core.Functions.Delegation; using Microsoft.PowerFx.Core.Localization; using Microsoft.PowerFx.Core.Syntax.Nodes; using Microsoft.PowerFx.Core.Utils; namespace Microsoft.PowerFx.Core.Texl.Builtins { // StartsWith(text:s, start:s):b // Checks if the text starts with the start string. internal sealed class StartsWithFunction : StringTwoArgFunction { public override DelegationCapability FunctionDelegationCapability => DelegationCapability.StartsWith; public StartsWithFunction() : base("StartsWith", TexlStrings.AboutStartsWith) { } public override bool IsRowScopedServerDelegatable(CallNode callNode, TexlBinding binding, OperationCapabilityMetadata metadata) { Contracts.AssertValue(callNode); Contracts.AssertValue(binding); Contracts.AssertValue(metadata); return IsRowScopedServerDelegatableHelper(callNode, binding, metadata); } public override IEnumerable<TexlStrings.StringGetter[]> GetSignatures() { yield return new[] { TexlStrings.StartsWithArg1, TexlStrings.StartsWithArg2 }; } // TASK: 856362 // Add overload for single-column table as the input. } }
34.878049
135
0.71049
[ "MIT" ]
Grant-Archibald-MS/Power-Fx
src/libraries/Microsoft.PowerFx.Core/Texl/Builtins/StartsWith.cs
1,432
C#
// ---------------------------------------------------------------------------- // <copyright file="PunSceneSettings.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2018 Exit Games GmbH // </copyright> // <summary> // Optional lowest-viewID setting per-scene. So PhotonViews don't get the same ID. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; namespace Photon.Pun { [Serializable] public class SceneSetting { public SceneAsset sceneAsset; public string sceneName; public int minViewId; } public class PunSceneSettings : ScriptableObject { #if UNITY_EDITOR // Suppressing compiler warning "this variable is never used". Only used in the CustomEditor, only in Editor #pragma warning disable 0414 [SerializeField] bool SceneSettingsListFoldoutOpen = true; #pragma warning restore 0414 #endif [SerializeField] public List<SceneSetting> MinViewIdPerScene = new List<SceneSetting>(); private const string SceneSettingsFileName = "PunSceneSettingsFile.asset"; // we use the path to PunSceneSettings.cs as path to create a scene settings file private static string punSceneSettingsCsPath; public static string PunSceneSettingsCsPath { get { if (!string.IsNullOrEmpty(punSceneSettingsCsPath)) { return punSceneSettingsCsPath; } // Unity 4.3.4 does not yet have AssetDatabase.FindAssets(). Would be easier. var result = Directory.GetFiles(Application.dataPath, "PunSceneSettings.cs", SearchOption.AllDirectories); if (result.Length >= 1) { punSceneSettingsCsPath = Path.GetDirectoryName(result[0]); punSceneSettingsCsPath = punSceneSettingsCsPath.Replace('\\', '/'); punSceneSettingsCsPath = punSceneSettingsCsPath.Replace(Application.dataPath, "Assets"); // AssetDatabase paths have to use '/' and are relative to the project's folder. Always. punSceneSettingsCsPath = punSceneSettingsCsPath + "/" + SceneSettingsFileName; } return punSceneSettingsCsPath; } } private static PunSceneSettings instanceField; public static PunSceneSettings Instance { get { if (instanceField != null) { return instanceField; } instanceField = (PunSceneSettings) AssetDatabase.LoadAssetAtPath(PunSceneSettingsCsPath, typeof(PunSceneSettings)); if (instanceField == null) { instanceField = ScriptableObject.CreateInstance<PunSceneSettings>(); AssetDatabase.CreateAsset(instanceField, PunSceneSettingsCsPath); } return instanceField; } } public static int MinViewIdForScene(string sceneName) { if (string.IsNullOrEmpty(sceneName)) { return 1; } PunSceneSettings pss = Instance; if (pss == null) { Debug.LogError("pss cant be null"); return 1; } foreach (SceneSetting setting in pss.MinViewIdPerScene) { if (setting.sceneName.Equals(sceneName)) { return setting.minViewId; } } return 1; } public static void SanitizeSettings() { if (Instance == null) { return; } #if UNITY_EDITOR foreach (SceneSetting sceneSetting in Instance.MinViewIdPerScene) { if (sceneSetting.sceneAsset == null && !string.IsNullOrEmpty(sceneSetting.sceneName)) { string[] guids = AssetDatabase.FindAssets(sceneSetting.sceneName + " t:SceneAsset"); foreach (string guid in guids) { string path = AssetDatabase.GUIDToAssetPath(guid); if (Path.GetFileNameWithoutExtension(path) == sceneSetting.sceneName) { sceneSetting.sceneAsset = AssetDatabase.LoadAssetAtPath<SceneAsset>( AssetDatabase.GUIDToAssetPath(guid)); // Debug.Log("SceneSettings : ''"+sceneSetting.sceneName+"'' scene is missing: Issue corrected",Instance); break; } } //Debug.Log("SceneSettings : ''"+sceneSetting.sceneName+"'' scene is missing",Instance); continue; } if (sceneSetting.sceneAsset != null && sceneSetting.sceneName!= sceneSetting.sceneAsset.name ) { // Debug.Log("SceneSettings : '"+sceneSetting.sceneName+"' mismatch with sceneAsset: '"+sceneSetting.sceneAsset.name+"' : Issue corrected",Instance); sceneSetting.sceneName = sceneSetting.sceneAsset.name; continue; } } #endif } } }
35.060241
168
0.523024
[ "MIT" ]
AcquaWh/App-Multiplayer
Assets/Photon/PhotonUnityNetworking/Code/Editor/PunSceneSettings.cs
5,820
C#
/* * Copyright 2013 Alastair Wyse (http://www.oraclepermissiongenerator.net/methodinvocationremoting/) * * 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.Text; namespace OperatingSystemAbstraction { //****************************************************************************** // // Class: ExtendedTcpListener // //****************************************************************************** /// <summary> /// An extended version of the System.Net.Sockets.TcpListener class, which exposes protected methods on that class. /// </summary> public class ExtendedTcpListener : System.Net.Sockets.TcpListener { //****************************************************************************** // // Method: ExtendedTcpListener (constructor) // //****************************************************************************** /// <summary> /// Initialises a new instance of the OperatingSystemAbstraction.ExtendedTcpListener class. /// </summary> /// <param name="ipAddress">An IPAddress that represents the local IP address.</param> /// <param name="port">The port on which to listen for incoming connection attempts. </param> public ExtendedTcpListener(System.Net.IPAddress ipAddress, int port) : base(ipAddress, port) { } /// <summary> /// Gets a value that indicates whether TcpListener is actively listening for client connections. /// </summary> public bool Active { get { return base.Active; } } } }
37.383333
119
0.55506
[ "Apache-2.0" ]
alastairwyse/MethodInvocationRemoting
C#/OperatingSystemAbstraction/ExtendedTcpListener.cs
2,243
C#
// // System.OperationCanceledException.cs // // Authors: // Zoltan Varga <vargaz@freemail.hu> // Jérémie Laval <jeremie.laval@gmail.com> // // Copyright (C) 2004 Novell, Inc (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.Runtime.Serialization; using System.Runtime.InteropServices; using System.Threading; namespace System.Couchbase { [Serializable] [ComVisible (true)] public class OperationCanceledException : System.OperationCanceledException { const int Result = unchecked ((int)0x8013153b); readonly CancellationToken? token; // Constructors public OperationCanceledException () : base ("The operation was canceled.") { } public OperationCanceledException (string message) : base (message) { } public OperationCanceledException (string message, Exception innerException) : base (message, innerException) { } protected OperationCanceledException (SerializationInfo info, StreamingContext context) : base (info, context) { } public OperationCanceledException (CancellationToken token) : this () { this.token = token; } public OperationCanceledException (string message, CancellationToken token) : this (message) { this.token = token; } public OperationCanceledException (string message, Exception innerException, CancellationToken token) : base (message, innerException) { this.token = token; } public CancellationToken CancellationToken { get { if (token == null) return CancellationToken.None; return token.Value; } } } }
28.784946
109
0.723945
[ "MIT" ]
Badca52/LunaMultiplayer
TPL/System/OperationCanceledException.cs
2,679
C#
using System; namespace AvaloniaReactorUI.Animations { public class Animatable { private readonly Action<RxAnimation> _animateAction; public Animatable(object key, RxAnimation animation, Action<RxAnimation> action) { Key = key ?? throw new ArgumentNullException(nameof(key)); Animation = animation ?? throw new ArgumentNullException(nameof(animation)); _animateAction = action ?? throw new ArgumentNullException(nameof(action)); } public RxAnimation Animation { get; } public bool? IsEnabled { get; internal set; } public object Key { get; } internal void Animate() { _animateAction(Animation); } } }
29.8
88
0.632215
[ "MIT" ]
adospace/reactorui-avalonia
src/AvaloniaReactorUI/Animations/Animatable.cs
747
C#
 namespace ScooTeqBooking.Pages { partial class TimeDistanceChoice { /// <summary> /// Erforderliche Designervariable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Vom Komponenten-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.logoutButton = new System.Windows.Forms.ToolStripButton(); this.adminMenu = new System.Windows.Forms.ToolStripDropDownButton(); this.openUserManagementButton = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.usernameLabel = new System.Windows.Forms.ToolStripLabel(); this.welcomeMessageLabel = new System.Windows.Forms.ToolStripLabel(); this.mainGridLayoutTablePanel = new System.Windows.Forms.TableLayoutPanel(); this.label1 = new System.Windows.Forms.Label(); this.buttonTablePanel = new System.Windows.Forms.TableLayoutPanel(); this.bookByTimeButton = new System.Windows.Forms.Button(); this.bookByDistanceButton = new System.Windows.Forms.Button(); this.toolStrip1.SuspendLayout(); this.mainGridLayoutTablePanel.SuspendLayout(); this.buttonTablePanel.SuspendLayout(); this.SuspendLayout(); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.logoutButton, this.adminMenu, this.toolStripSeparator1, this.usernameLabel, this.welcomeMessageLabel}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(583, 25); this.toolStrip1.TabIndex = 0; this.toolStrip1.Text = "toolStrip1"; // // logoutButton // this.logoutButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.logoutButton.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.logoutButton.Image = global::ScooTeqBooking.Properties.Resources.exit_16px; this.logoutButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.logoutButton.Name = "logoutButton"; this.logoutButton.Size = new System.Drawing.Size(65, 22); this.logoutButton.Text = "Logout"; this.logoutButton.Click += new System.EventHandler(this.logoutButton_Click); // // adminMenu // this.adminMenu.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.adminMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openUserManagementButton}); this.adminMenu.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.adminMenu.Image = global::ScooTeqBooking.Properties.Resources.user_shield_16px; this.adminMenu.ImageTransparentColor = System.Drawing.Color.Magenta; this.adminMenu.Name = "adminMenu"; this.adminMenu.Size = new System.Drawing.Size(95, 22); this.adminMenu.Text = "Verwaltung"; // // openUserManagementButton // this.openUserManagementButton.Image = global::ScooTeqBooking.Properties.Resources.registration_16px; this.openUserManagementButton.Name = "openUserManagementButton"; this.openUserManagementButton.Size = new System.Drawing.Size(179, 22); this.openUserManagementButton.Text = "Benutzerverwaltung"; this.openUserManagementButton.Click += new System.EventHandler(this.openUserManagementButton_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // usernameLabel // this.usernameLabel.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.usernameLabel.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.usernameLabel.Image = global::ScooTeqBooking.Properties.Resources.user_16px; this.usernameLabel.Name = "usernameLabel"; this.usernameLabel.Size = new System.Drawing.Size(92, 22); this.usernameLabel.Text = "<Username>"; // // welcomeMessageLabel // this.welcomeMessageLabel.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.welcomeMessageLabel.Name = "welcomeMessageLabel"; this.welcomeMessageLabel.Size = new System.Drawing.Size(222, 22); this.welcomeMessageLabel.Text = "Willkommen, <Firstname> <Lastname>!"; // // mainGridLayoutTablePanel // this.mainGridLayoutTablePanel.BackColor = System.Drawing.Color.Transparent; this.mainGridLayoutTablePanel.ColumnCount = 3; this.mainGridLayoutTablePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.mainGridLayoutTablePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 350F)); this.mainGridLayoutTablePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.mainGridLayoutTablePanel.Controls.Add(this.label1, 1, 0); this.mainGridLayoutTablePanel.Controls.Add(this.buttonTablePanel, 1, 1); this.mainGridLayoutTablePanel.Dock = System.Windows.Forms.DockStyle.Fill; this.mainGridLayoutTablePanel.Location = new System.Drawing.Point(0, 25); this.mainGridLayoutTablePanel.Name = "mainGridLayoutTablePanel"; this.mainGridLayoutTablePanel.RowCount = 3; this.mainGridLayoutTablePanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.mainGridLayoutTablePanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 60F)); this.mainGridLayoutTablePanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.mainGridLayoutTablePanel.Size = new System.Drawing.Size(583, 321); this.mainGridLayoutTablePanel.TabIndex = 1; // // label1 // this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Font = new System.Drawing.Font("Segoe UI Semibold", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(119, 0); this.label1.Name = "label1"; this.label1.Padding = new System.Windows.Forms.Padding(0, 40, 0, 0); this.label1.Size = new System.Drawing.Size(344, 130); this.label1.TabIndex = 1; this.label1.Text = "Wähle eine Buchungsart für deine Fahrt aus:"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // buttonTablePanel // this.buttonTablePanel.ColumnCount = 2; this.buttonTablePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.buttonTablePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.buttonTablePanel.Controls.Add(this.bookByTimeButton, 0, 0); this.buttonTablePanel.Controls.Add(this.bookByDistanceButton, 1, 0); this.buttonTablePanel.Dock = System.Windows.Forms.DockStyle.Fill; this.buttonTablePanel.Location = new System.Drawing.Point(116, 130); this.buttonTablePanel.Margin = new System.Windows.Forms.Padding(0); this.buttonTablePanel.Name = "buttonTablePanel"; this.buttonTablePanel.RowCount = 1; this.buttonTablePanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.buttonTablePanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.buttonTablePanel.Size = new System.Drawing.Size(350, 60); this.buttonTablePanel.TabIndex = 3; // // bookByTimeButton // this.bookByTimeButton.Dock = System.Windows.Forms.DockStyle.Fill; this.bookByTimeButton.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bookByTimeButton.Location = new System.Drawing.Point(3, 3); this.bookByTimeButton.Name = "bookByTimeButton"; this.bookByTimeButton.Size = new System.Drawing.Size(169, 54); this.bookByTimeButton.TabIndex = 0; this.bookByTimeButton.Text = "Scooter nach verstrichener Zeit buchen"; this.bookByTimeButton.UseVisualStyleBackColor = true; this.bookByTimeButton.Click += new System.EventHandler(this.bookByTimeButton_Click); // // bookByDistanceButton // this.bookByDistanceButton.Dock = System.Windows.Forms.DockStyle.Fill; this.bookByDistanceButton.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bookByDistanceButton.Location = new System.Drawing.Point(178, 3); this.bookByDistanceButton.Name = "bookByDistanceButton"; this.bookByDistanceButton.Size = new System.Drawing.Size(169, 54); this.bookByDistanceButton.TabIndex = 1; this.bookByDistanceButton.Text = "Scooter nach fester Strecke buchen"; this.bookByDistanceButton.UseVisualStyleBackColor = true; this.bookByDistanceButton.Click += new System.EventHandler(this.bookByDistanceButton_Click); // // TimeDistanceChoice // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.BackgroundImage = global::ScooTeqBooking.Properties.Resources.skyline2; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.Controls.Add(this.mainGridLayoutTablePanel); this.Controls.Add(this.toolStrip1); this.Name = "TimeDistanceChoice"; this.Size = new System.Drawing.Size(583, 346); this.Load += new System.EventHandler(this.TimeDistanceChoice_Load); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.mainGridLayoutTablePanel.ResumeLayout(false); this.buttonTablePanel.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton logoutButton; private System.Windows.Forms.ToolStripLabel usernameLabel; private System.Windows.Forms.TableLayoutPanel mainGridLayoutTablePanel; private System.Windows.Forms.ToolStripLabel welcomeMessageLabel; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripDropDownButton adminMenu; private System.Windows.Forms.ToolStripMenuItem openUserManagementButton; private System.Windows.Forms.Label label1; private System.Windows.Forms.TableLayoutPanel buttonTablePanel; private System.Windows.Forms.Button bookByTimeButton; private System.Windows.Forms.Button bookByDistanceButton; } }
60.554545
167
0.663264
[ "MIT" ]
jonasluehrig/MooveTeq-Booking
MooveTeq-Booking/Pages/TimeDistanceChoice.Designer.cs
13,330
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareEqualInt64() { var test = new SimpleBinaryOpTest__CompareEqualInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualInt64 { private struct TestStruct { public Vector128<Int64> _fld1; public Vector128<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqualInt64 testClass) { var result = Sse41.CompareEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64, Int64, Int64> _dataTable; static SimpleBinaryOpTest__CompareEqualInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public SimpleBinaryOpTest__CompareEqualInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int64, Int64, Int64>(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.CompareEqual( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.CompareEqual( Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.CompareEqual( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.CompareEqual), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.CompareEqual), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.CompareEqual), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = Sse41.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Sse41.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Sse41.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualInt64(); var result = Sse41.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { var result = Sse41.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { var test = TestStruct.Create(); var result = Sse41.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int64> left, Vector128<Int64> right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] == right[0]) ? unchecked((long)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((long)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.CompareEqual)}<Int64>(Vector128<Int64>, Vector128<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } } }
43.756684
187
0.585457
[ "MIT" ]
MSHOY/coreclr
tests/src/JIT/HardwareIntrinsics/X86/Sse41/CompareEqual.Int64.cs
16,365
C#
/********************************************* 作者:曹旭升 QQ:279060597 访问博客了解详细介绍及更多内容: http://blog.shengxunwei.com **********************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Manageability; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Manageability.Adm; namespace Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.Manageability.TraceListeners { public class WmiTraceListenerDataManageabilityProvider : TraceListenerDataManageabilityProvider<WmiTraceListenerData> { public WmiTraceListenerDataManageabilityProvider() { WmiTraceListenerDataWmiMapper.RegisterWmiTypes(); } protected override void AddElementAdministrativeTemplateParts(AdmContentBuilder contentBuilder, WmiTraceListenerData configurationObject, IConfigurationSource configurationSource, String elementPolicyKeyName) { AddTraceOptionsPart(contentBuilder, configurationObject.TraceOutputOptions); AddFilterPart(contentBuilder, configurationObject.Filter); } protected override void GenerateWmiObjects(WmiTraceListenerData configurationObject, ICollection<ConfigurationSetting> wmiSettings) { WmiTraceListenerDataWmiMapper.GenerateWmiObjects(configurationObject, wmiSettings); } protected override void OverrideWithGroupPolicies(WmiTraceListenerData configurationObject, IRegistryKey policyKey) { TraceOptions? traceOutputOptionsOverride = policyKey.GetEnumValue<TraceOptions>(TraceOutputOptionsPropertyName); SourceLevels? filterOverride = policyKey.GetEnumValue<SourceLevels>(FilterPropertyName); configurationObject.TraceOutputOptions = traceOutputOptionsOverride.Value; configurationObject.Filter = filterOverride.Value; } } }
52.733333
125
0.641382
[ "MIT" ]
ckalvin-hub/Sheng.Winform.IDE
SourceCode/Source/EnterpriseLibrary/Logging/Src/Logging/Configuration/Manageability/TraceListeners/WmiTraceListenerDataManageabilityProvider.cs
2,421
C#
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using SDKTemplate; using Windows.ApplicationModel.Background; using Windows.Storage; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.Networking.Connectivity; namespace NetworkStatusApp { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class NetworkStatusWithInternetPresent : Page { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() MainPage rootPage = MainPage.Current; private CoreDispatcher NetworkStatusWithInternetPresentDispatcher; //Save current internet profile and network adapter ID globally string internetProfile = "Not connected to Internet"; string networkAdapter = "Not connected to Internet"; public NetworkStatusWithInternetPresent() { this.InitializeComponent(); NetworkStatusWithInternetPresentDispatcher = Window.Current.CoreWindow.Dispatcher; } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == BackgroundTaskSample.SampleBackgroundTaskWithConditionName) { //Associate background task completed event handler with background task var isTaskRegistered = RegisterCompletedHandlerforBackgroundTask(task.Value); UpdateButton(isTaskRegistered); } } } #if WINDOWS_PHONE_APP private async void RequestBackgroundAccess() { await BackgroundExecutionManager.RequestAccessAsync(); } #endif /// <summary> /// Register a SampleBackgroundTaskWithCondition. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RegisterButton_Click(object sender, RoutedEventArgs e) { try { //Save current internet profile and network adapter ID globally var connectionProfile = NetworkInformation.GetInternetConnectionProfile(); if (connectionProfile != null) { internetProfile = connectionProfile.ProfileName; var networkAdapterInfo = connectionProfile.NetworkAdapter; if (networkAdapterInfo != null) { networkAdapter = networkAdapterInfo.NetworkAdapterId.ToString(); } else { networkAdapter = "Not connected to Internet"; } } else { internetProfile = "Not connected to Internet"; networkAdapter = "Not connected to Internet"; } #if WINDOWS_PHONE_APP // On Windows Phone, we need to request access from the BackgroundExecutionManager in order for our background task to run RequestBackgroundAccess(); #endif var task = BackgroundTaskSample.RegisterBackgroundTask(BackgroundTaskSample.SampleBackgroundTaskEntryPoint, BackgroundTaskSample.SampleBackgroundTaskWithConditionName, new SystemTrigger(SystemTriggerType.NetworkStateChange, false), new SystemCondition(SystemConditionType.InternetAvailable)); //Associate background task completed event handler with background task. task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted); rootPage.NotifyUser("Registered for NetworkStatusChange background task with Internet present condition\n", NotifyType.StatusMessage); UpdateButton(true); } catch (Exception ex) { rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage); } } /// <summary> /// Unregister a SampleBackgroundTaskWithCondition. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UnregisterButton_Click(object sender, RoutedEventArgs e) { BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.SampleBackgroundTaskWithConditionName); rootPage.NotifyUser("Unregistered for NetworkStatusChange background task with Internet present condition\n", NotifyType.StatusMessage); UpdateButton(false); } /// <summary> /// Register completion handler for registered background task on application startup. /// </summary> /// <param name="task">The task to attach progress and completed handlers to.</param> private bool RegisterCompletedHandlerforBackgroundTask(IBackgroundTaskRegistration task) { bool taskRegistered = false; try { //Associate background task completed event handler with background task. task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted); taskRegistered = true; } catch (Exception ex) { rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage); } return taskRegistered; } /// <summary> /// Handle background task completion. /// </summary> /// <param name="task">The task that is reporting completion.</param> /// <param name="e">Arguments of the completion report.</param> private async void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) { ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; Object profile = localSettings.Values["InternetProfile"]; Object adapter = localSettings.Values["NetworkAdapterId"]; Object hasNewConnectionCost = localSettings.Values["HasNewConnectionCost"]; Object hasNewDomainConnectivityLevel = localSettings.Values["HasNewDomainConnectivityLevel"]; Object hasNewHostNameList = localSettings.Values["HasNewHostNameList"]; Object hasNewInternetConnectionProfile = localSettings.Values["HasNewInternetConnectionProfile"]; Object hasNewNetworkConnectivityLevel = localSettings.Values["HasNewNetworkConnectivityLevel"]; await NetworkStatusWithInternetPresentDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { string outputText = string.Empty; if ((profile != null) && (adapter != null)) { //If internet profile has changed, display the new internet profile if ((string.Equals(profile.ToString(), internetProfile, StringComparison.Ordinal) == false) || (string.Equals(adapter.ToString(), networkAdapter, StringComparison.Ordinal) == false)) { internetProfile = profile.ToString(); networkAdapter = adapter.ToString(); outputText += "Internet Profile changed\n" + "=================\n" + "Current Internet Profile : " + internetProfile + "\n\n"; if (hasNewConnectionCost != null) { outputText += hasNewConnectionCost.ToString() + "\n"; } if (hasNewDomainConnectivityLevel != null) { outputText += hasNewDomainConnectivityLevel.ToString() + "\n"; } if (hasNewHostNameList != null) { outputText += hasNewHostNameList.ToString() + "\n"; } if (hasNewInternetConnectionProfile != null) { outputText += hasNewInternetConnectionProfile.ToString() + "\n"; } if (hasNewNetworkConnectivityLevel != null) { outputText += hasNewNetworkConnectivityLevel.ToString() + "\n"; } rootPage.NotifyUser(outputText, NotifyType.StatusMessage); } } }); } /// <summary> /// Update the Register/Unregister button. /// </summary> private void UpdateButton(bool registered) { RegisterButton.IsEnabled = !registered; UnregisterButton.IsEnabled = registered; } } }
43.733333
150
0.574898
[ "MIT" ]
Ranin26/msdn-code-gallery-microsoft
Official Windows Platform Sample/Universal Windows app samples/111487-Universal Windows app samples/Network status background sample/C#/Shared/Scenario1_NetworkStatusWithInternetPresent.xaml.cs
9,842
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Diagnostics.Tracing; using Xunit; namespace System.Linq.Parallel.Tests { public class EtwTests { [Fact] public void TestEtw() { using (var listener = new TestEventListener(new Guid("159eeeec-4a14-4418-a8fe-faabcd987887"), EventLevel.Verbose)) { var events = new ConcurrentQueue<int>(); listener.RunWithCallback(ev => events.Enqueue(ev.EventId), () => { Enumerable.Range(0, 10000).AsParallel().Select(i => i).ToArray(); }); const int BeginEventId = 1; Assert.Equal(expected: 1, actual: events.Count(i => i == BeginEventId)); const int EndEventId = 2; Assert.Equal(expected: 1, actual: events.Count(i => i == EndEventId)); const int ForkEventId = 3; const int JoinEventId = 4; Assert.True(events.Count(i => i == ForkEventId) > 0); Assert.Equal(events.Count(i => i == ForkEventId), events.Count(i => i == JoinEventId)); } } } }
36.184211
126
0.573091
[ "MIT" ]
benjamin-bader/corefx
src/System.Linq.Parallel/tests/EtwTests.cs
1,375
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Collections.Tests { public class SortedSet_Generic_Tests_string : SortedSet_Generic_Tests<string> { protected override string CreateT(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes = new byte[stringLength]; rand.NextBytes(bytes); return Convert.ToBase64String(bytes); } } public class SortedSet_Generic_Tests_int : SortedSet_Generic_Tests<int> { protected override int CreateT(int seed) { Random rand = new Random(seed); return rand.Next(); } protected override bool DefaultValueAllowed { get { return true; } } } [OuterLoop] public class SortedSet_Generic_Tests_EquatableBackwardsOrder : SortedSet_Generic_Tests<EquatableBackwardsOrder> { protected override EquatableBackwardsOrder CreateT(int seed) { Random rand = new Random(seed); return new EquatableBackwardsOrder(rand.Next()); } protected override ISet<EquatableBackwardsOrder> GenericISetFactory() { return new SortedSet<EquatableBackwardsOrder>(); } } [OuterLoop] public class SortedSet_Generic_Tests_int_With_Comparer_SameAsDefaultComparer : SortedSet_Generic_Tests<int> { protected override IEqualityComparer<int> GetIEqualityComparer() { return new Comparer_SameAsDefaultComparer(); } protected override IComparer<int> GetIComparer() { return new Comparer_SameAsDefaultComparer(); } protected override int CreateT(int seed) { Random rand = new Random(seed); return rand.Next(); } protected override ISet<int> GenericISetFactory() { return new SortedSet<int>(new Comparer_SameAsDefaultComparer()); } } [OuterLoop] public class SortedSet_Generic_Tests_int_With_Comparer_HashCodeAlwaysReturnsZero : SortedSet_Generic_Tests<int> { protected override IEqualityComparer<int> GetIEqualityComparer() { return new Comparer_HashCodeAlwaysReturnsZero(); } protected override IComparer<int> GetIComparer() { return new Comparer_HashCodeAlwaysReturnsZero(); } protected override int CreateT(int seed) { Random rand = new Random(seed); return rand.Next(); } protected override ISet<int> GenericISetFactory() { return new SortedSet<int>(new Comparer_HashCodeAlwaysReturnsZero()); } } [OuterLoop] public class SortedSet_Generic_Tests_int_With_Comparer_ModOfInt : SortedSet_Generic_Tests<int> { protected override IEqualityComparer<int> GetIEqualityComparer() { return new Comparer_ModOfInt(15000); } protected override IComparer<int> GetIComparer() { return new Comparer_ModOfInt(15000); } protected override int CreateT(int seed) { Random rand = new Random(seed); return rand.Next(); } protected override ISet<int> GenericISetFactory() { return new SortedSet<int>(new Comparer_ModOfInt(15000)); } } [OuterLoop] public class SortedSet_Generic_Tests_int_With_Comparer_AbsOfInt : SortedSet_Generic_Tests<int> { protected override IEqualityComparer<int> GetIEqualityComparer() { return new Comparer_AbsOfInt(); } protected override IComparer<int> GetIComparer() { return new Comparer_AbsOfInt(); } protected override int CreateT(int seed) { Random rand = new Random(seed); return rand.Next(); } protected override ISet<int> GenericISetFactory() { return new SortedSet<int>(new Comparer_AbsOfInt()); } } }
28.584416
115
0.616084
[ "MIT" ]
Priya91/corefx-1
src/System.Collections/tests/Generic/SortedSet/SortedSet.Generic.cs
4,404
C#
using System.IO; using MediaDashboard.Common.Config.Entities; using Newtonsoft.Json; namespace MediaDashboard.Common.Config.ConfigReaders { public class FileConfigReader : IConfigReader { private readonly string _configFilePath; public FileConfigReader(string configFilePath) { _configFilePath = System.Environment.ExpandEnvironmentVariables(configFilePath); } public MediaDashboardConfig ReadConfig() { var config = File.ReadAllText(_configFilePath); return JsonConvert.DeserializeObject<MediaDashboardConfig>(config); } } }
27.521739
92
0.701422
[ "MIT" ]
Azure-Samples/media-services-dotnet-live-monitoring-dashboard
MediaDashboard.Common/Config/ConfigReaders/FileConfigReader.cs
633
C#
using System; using System.Collections.Generic; using Elasticsearch.Net; using Nest; using Tests.Framework; using Tests.Framework.Integration; using Tests.Framework.MockData; using Xunit; using static Nest.Infer; using System.Threading.Tasks; using FluentAssertions; using System.Linq; namespace Tests.Document.Single.Update { [Collection(IntegrationContext.Indexing)] public class UpdateWithSourceApiTests : ApiIntegrationTestBase<IUpdateResponse<Project>, IUpdateRequest<Project, Project>, UpdateDescriptor<Project, Project>, UpdateRequest<Project, Project>> { public UpdateWithSourceApiTests(IndexingCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override void BeforeAllCalls(IElasticClient client, IDictionary<ClientMethod, string> values) { foreach (var id in values.Values) this.Client.Index(Project.Instance, i=>i.Id(id)); } protected override LazyResponses ClientUsage() => Calls( fluent: (client, f) => client.Update<Project>(CallIsolatedValue, f), fluentAsync: (client, f) => client.UpdateAsync<Project>(CallIsolatedValue, f), request: (client, r) => client.Update<Project>(r), requestAsync: (client, r) => client.UpdateAsync<Project>(r) ); protected override bool ExpectIsValid => true; protected override int ExpectStatusCode => 200; protected override HttpMethod HttpMethod => HttpMethod.POST; protected override string UrlPath => $"/project/project/{CallIsolatedValue}/_update?fields=name%2C_source"; protected override bool SupportsDeserialization => false; protected override object ExpectJson { get; } = new { doc = Project.InstanceAnonymous, doc_as_upsert = true }; protected override UpdateDescriptor<Project, Project> NewDescriptor() => new UpdateDescriptor<Project, Project>(DocumentPath<Project>.Id(CallIsolatedValue)); protected override Func<UpdateDescriptor<Project,Project>, IUpdateRequest<Project, Project>> Fluent => d=>d .Doc(Project.Instance) .Fields(Field<Project>(p=>p.Name).And("_source")) .DocAsUpsert(); protected override UpdateRequest<Project, Project> Initializer => new UpdateRequest<Project, Project>(CallIsolatedValue) { Doc = Project.Instance, DocAsUpsert = true, Fields = Field<Project>(p=>p.Name).And("_source") }; [I] public Task ReturnsSourceAndFields() => this.AssertOnAllResponses(r => { r.Get.Should().NotBeNull(); r.Get.Found.Should().BeTrue(); r.Get.Source.Should().NotBeNull(); var name = Project.Projects.First().Name; r.Get.Source.Name.Should().Be(name); r.Get.Fields.Should().NotBeEmpty().And.ContainKey("name"); r.Get.Fields.Value<string>("name").Should().Be(name); }); } }
36.726027
192
0.74599
[ "Apache-2.0" ]
RossLieberman/NEST
src/Tests/Document/Single/Update/UpdateWithSourceApiTests.cs
2,683
C#
using System; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Formatters; namespace SpanJson.AspNetCore.Formatter { public class SpanJsonInputFormatter<TResolver> : TextInputFormatter where TResolver : IJsonFormatterResolver<byte, TResolver>, new() { public SpanJsonInputFormatter() { SupportedMediaTypes.Add("application/json"); SupportedMediaTypes.Add("text/json"); SupportedMediaTypes.Add("application/*+json"); SupportedEncodings.Add(UTF8EncodingWithoutBOM); } public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding) { try { var model = await JsonSerializer.NonGeneric.Utf8.DeserializeAsync<TResolver>(context.HttpContext.Request.Body, context.ModelType) .ConfigureAwait(false); if (model is null && !context.TreatEmptyInputAsDefaultValue) { return InputFormatterResult.NoValue(); } return InputFormatterResult.Success(model); } catch (Exception ex) { context.ModelState.AddModelError("JSON", ex.Message); return InputFormatterResult.Failure(); } } } }
36.526316
145
0.621758
[ "MIT" ]
cuteant/SpanJson
src/SpanJson.AspNetCore.Formatter/SpanJsonInputFormatter.cs
1,390
C#
using DevelopmentInProgress.TradeView.Core.Extensions; using DevelopmentInProgress.TradeView.Wpf.Common.Command; using DevelopmentInProgress.TradeView.Wpf.Common.Events; using DevelopmentInProgress.TradeView.Wpf.Common.Model; using DevelopmentInProgress.TradeView.Wpf.Common.Services; using DevelopmentInProgress.TradeView.Wpf.Common.ViewModel; using DevelopmentInProgress.TradeView.Wpf.Configuration.Utility; using Prism.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Input; namespace DevelopmentInProgress.TradeView.Wpf.Configuration.ViewModel { [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "General exceptions are reported to subscribers.")] public class StrategyViewModel : BaseViewModel { private readonly IStrategyService strategyService; private readonly IStrategyFileManager strategyFileManager; private Strategy strategy; bool disposed = false; public StrategyViewModel(Strategy strategy, IStrategyService strategyService, IStrategyFileManager strategyFileManager, ILoggerFacade logger) : base(logger) { this.strategy = strategy; this.strategyService = strategyService; this.strategyFileManager = strategyFileManager; AddStrategySubscriptionCommand = new ViewModelCommand(AddStrategySubscription); DeleteStrategySubscriptionCommand = new ViewModelCommand(DeleteStrategySubscription); DeleteStrategyDependencyCommand = new ViewModelCommand(DeleteStrategyDependency); AddParameterSchemaCommand = new ViewModelCommand(AddParameterSchema); DisplayDependenciesCommand = new ViewModelCommand(DisplayDependencies); DisplayAssemblyCommand = new ViewModelCommand(DisplayAssembly); TargetAssemblyCommand = new ViewModelCommand(TargetAssembly); DependenciesCommand = new ViewModelCommand(Dependencies); OnPropertyChanged(string.Empty); } public event EventHandler<StrategyEventArgs> OnStrategyNotification; public ICommand AddStrategySubscriptionCommand { get; set; } public ICommand DeleteStrategySubscriptionCommand { get; set; } public ICommand DeleteStrategyDependencyCommand { get; set; } public ICommand AddParameterSchemaCommand { get; set; } public ICommand DisplayDependenciesCommand { get; set; } public ICommand DisplayAssemblyCommand { get; set; } public ICommand TargetAssemblyCommand { get; set; } public ICommand DependenciesCommand { get; set; } public Strategy Strategy { get { return strategy; } set { if (strategy != value) { strategy = value; OnPropertyChanged(nameof(Strategy)); } } } public static List<string> Exchanges { get { return ExchangeExtensions.Exchanges().ToList(); } } public static List<string> CandlestickIntervals { get { return CandlestickIntervalExtensions.GetCandlestickIntervalNames().ToList(); } } protected override void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { // dispose stuff... } disposed = true; } private void DisplayAssembly(object arg) { if (arg is IEnumerable<string> files) { if (Strategy != null) { if (files.Any()) { var file = files.First(); Strategy.DisplayAssembly = new StrategyFile { File = file }; if (!Strategy.DisplayDependencies.Any(d => d.File.Equals(file, StringComparison.Ordinal))) { Strategy.DisplayDependencies.Insert(0, new StrategyFile { File = file, FileType = StrategyFileType.DisplayFile }); } } } } } private void DisplayDependencies(object arg) { if (arg is IEnumerable<string> files) { if (Strategy != null) { if (files.Any()) { foreach (string file in files) { Strategy.DisplayDependencies.Insert(0, new StrategyFile { File = file, FileType = StrategyFileType.DisplayFile }); } } } } } private void TargetAssembly(object arg) { if (arg is IEnumerable<string> files) { if (Strategy != null) { if (files.Any()) { var file = files.First(); Strategy.TargetAssembly = new StrategyFile { File = file }; if (!Strategy.Dependencies.Any(d => d.File.Equals(file, StringComparison.Ordinal))) { Strategy.Dependencies.Insert(0, new StrategyFile { File = file, FileType = StrategyFileType.StrategyFile }); } } } } } private void Dependencies(object arg) { if (arg is IEnumerable<string> files) { if (Strategy != null) { if (files.Any()) { foreach (string file in files) { Strategy.Dependencies.Insert(0, new StrategyFile { File = file, FileType = StrategyFileType.StrategyFile }); } } } } } private async void AddStrategySubscription(object param) { if (Strategy == null || string.IsNullOrEmpty(param.ToString())) { return; } var symbol = param.ToString(); try { Strategy.StrategySubscriptions.Insert(0, new StrategySubscription { Symbol = symbol }); await strategyService.SaveStrategy(Strategy).ConfigureAwait(false); } catch (Exception ex) { OnStrategyException(ex); } } private async void DeleteStrategySubscription(object param) { if (Strategy == null) { return; } if (param is StrategySubscription subscription) { try { Strategy.StrategySubscriptions.Remove(subscription); await strategyService.SaveStrategy(Strategy).ConfigureAwait(false); } catch (Exception ex) { OnStrategyException(ex); } } } private async void DeleteStrategyDependency(object param) { if (Strategy == null) { return; } if (param is StrategyFile file) { try { if(file.FileType.Equals(StrategyFileType.StrategyFile)) { Strategy.Dependencies.Remove(file); } else if(file.FileType.Equals(StrategyFileType.DisplayFile)) { Strategy.DisplayDependencies.Remove(file); } await strategyService.SaveStrategy(Strategy).ConfigureAwait(false); } catch (Exception ex) { OnStrategyException(ex); } } } private async void AddParameterSchema(object param) { if(Strategy == null) { return; } if(Strategy.TargetAssembly == null || string.IsNullOrWhiteSpace(Strategy.TargetAssembly.File)) { OnNotification($"{Strategy.Name}'s {nameof(Strategy.TargetAssembly)} must be specified."); return; } try { var strategyTypeJson = strategyFileManager.GetStrategyTypeAsJson(strategy.TargetAssembly); if(string.IsNullOrWhiteSpace(strategyTypeJson)) { return; } Strategy.Parameters = strategyTypeJson; await strategyService.SaveStrategy(Strategy).ConfigureAwait(false); } catch (Exception ex) { OnStrategyException(ex); } } private void OnStrategyException(Exception exception) { OnNotification(exception.Message, exception); } private void OnNotification(string message) { OnNotification(message, null); } private void OnNotification(string message, Exception exception) { var onStrategyNotification = OnStrategyNotification; onStrategyNotification?.Invoke(this, new StrategyEventArgs { Value = Strategy, Message = message, Exception = exception }); } } }
34.125436
177
0.529406
[ "Apache-2.0" ]
CasparsTools/tradeview
src/DevelopmentInProgress.TradeView.Wpf.Configuration/ViewModel/StrategyViewModel.cs
9,796
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace TPC_UPC.Resources { public class SaveAccountResource { [Required] [StringLength(50)] public string AccountName { get; set; } //dudas [Required] [StringLength(30, MinimumLength = 5)] public string Password { get; set; } //dudas [Required] public SaveUniversityResource University { get; set; } } }
24.045455
62
0.661626
[ "BSD-3-Clause" ]
lucas1619/TPC-BACKEND
TPC-UPC/Resources/SaveAccountResource.cs
531
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using NewLife; using NewLife.Data; using NewLife.Serialization; using Stardust.Data; using Stardust.Data.Configs; using Stardust.Models; using Stardust.Server.Common; using Stardust.Server.Services; namespace Stardust.Server.Controllers { [Route("[action]")] public class DustController : ControllerBase { /// <summary>用户主机</summary> public String UserHost => HttpContext.GetUserHost(); private readonly TokenService _tokenService; public DustController(TokenService tokenService) => _tokenService = tokenService; #region 发布、消费 private Service GetService(String serviceName) { var info = Service.FindByName(serviceName); if (info == null) { info = new Service { Name = serviceName, Enable = true }; info.Insert(); } if (!info.Enable) throw new InvalidOperationException($"服务[{serviceName}]已停用!"); return info; } [ApiFilter] [HttpPost] public AppService RegisterService([FromBody] PublishServiceInfo service, String token) { var app = _tokenService.DecodeToken(token, Setting.Current); var info = GetService(service.ServiceName); // 所有服务 var services = AppService.FindAllByService(info.Id); var svc = services.FirstOrDefault(e => e.AppId == app.Id && e.Client == service.Client); if (svc == null) { svc = new AppService { AppId = app.Id, ServiceId = info.Id, ServiceName = service.ServiceName, Client = service.Client, //Enable = app.AutoActive, CreateIP = UserHost, }; services.Add(svc); var history = AppHistory.Create(app, "RegisterService", true, $"注册服务[{service.ServiceName}] {service.Client}", Environment.MachineName, UserHost); history.Client = service.Client; history.SaveAsync(); } // 作用域 svc.Scope = AppRule.CheckScope(-1, UserHost); // 地址处理。本地任意地址,更换为IP地址 var ip = service.IP; if (ip.IsNullOrEmpty()) ip = service.Client.Substring(null, ":"); if (ip.IsNullOrEmpty()) ip = UserHost; var addrs = service.Address ?.Replace("://*", $"://{ip}") .Replace("://0.0.0.0", $"://{ip}") .Replace("://[::]", $"://{ip}"); svc.Enable = app.AutoActive; svc.PingCount++; svc.Tag = service.Tag; svc.Version = service.Version; svc.Address = addrs; svc.Save(); info.Providers = services.Count; info.Save(); return svc; } [ApiFilter] [HttpPost] public AppService UnregisterService([FromBody] PublishServiceInfo service, String token) { var app = _tokenService.DecodeToken(token, Setting.Current); var info = GetService(service.ServiceName); // 所有服务 var services = AppService.FindAllByService(info.Id); var svc = services.FirstOrDefault(e => e.AppId == app.Id && e.Client == service.Client); if (svc != null) { //svc.Delete(); svc.Enable = false; svc.Update(); services.Remove(svc); var history = AppHistory.Create(app, "UnregisterService", true, $"服务[{service.ServiceName}]下线 {svc.Client}", Environment.MachineName, UserHost); history.Client = svc.Client; history.SaveAsync(); } info.Providers = services.Count; info.Save(); return svc; } [ApiFilter] [HttpPost] public ServiceModel[] ResolveService([FromBody] ConsumeServiceInfo model, String token) { var app = _tokenService.DecodeToken(token, Setting.Current); var info = GetService(model.ServiceName); // 所有消费 var consumes = AppConsume.FindAllByService(info.Id); var svc = consumes.FirstOrDefault(e => e.AppId == app.Id && e.Client == model.Client); if (svc == null) { svc = new AppConsume { AppId = app.Id, ServiceId = info.Id, ServiceName = model.ServiceName, Client = model.Client, Enable = true, CreateIP = UserHost, }; consumes.Add(svc); var history = AppHistory.Create(app, "ResolveService", true, $"消费服务[{model.ServiceName}] {model.ToJson()}", Environment.MachineName, UserHost); history.Client = svc.Client; history.SaveAsync(); } // 作用域 svc.Scope = AppRule.CheckScope(-1, UserHost); svc.PingCount++; svc.Tag = model.Tag; svc.MinVersion = model.MinVersion; svc.Save(); info.Consumers = consumes.Count; info.Save(); // 该服务所有生产 var services = AppService.FindAllByService(info.Id); services = services.Where(e => e.Enable).ToList(); // 匹配minversion和tag services = services.Where(e => e.Match(model.MinVersion, svc.Scope, model.Tag?.Split(","))).ToList(); return services.Select(e => new ServiceModel { ServiceName = e.ServiceName, DisplayName = info.DisplayName, Client = e.Client, Version = e.Version, Address = e.Address, Scope = e.Scope, Tag = e.Tag, Weight = e.Weight, CreateTime = e.CreateTime, UpdateTime = e.UpdateTime, }).ToArray(); } #endregion [ApiFilter] public IList<AppService> SearchService(String serviceName, String key) { var svc = Service.FindByName(serviceName); if (svc == null) return null; return AppService.Search(-1, svc.Id, true, key, new PageParameter { PageSize = 100 }); } } }
33.126263
162
0.522946
[ "MIT" ]
NewLifeX/Stardust
Stardust.Server/Controllers/DustController.cs
6,705
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CodeWars { /// <see cref="https://www.codewars.com/kata/541c8630095125aba6000c00/train/csharp"/> [TestClass] public class SumOfDigitsDigitalRoot { [TestMethod] public void Test() { Assert.AreEqual(7, DigitalRoot(16)); Assert.AreEqual(6, DigitalRoot(456)); } public int DigitalRoot(long n) { var stringNum = n.ToString(); while (stringNum.Length > 1) { var sum = 0; foreach (var num in stringNum) sum += int.Parse(num.ToString()); stringNum = sum.ToString(); } return int.Parse(stringNum); } } }
23.264706
89
0.523388
[ "MIT" ]
Hyolog/CodeWars
CodeWars/CodeWars/SumOfDigitsDigitalRoot.cs
791
C#
using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; namespace Thenewboston.Validator.Models { internal class ConnectionRequest { [JsonProperty(PropertyName = "message")] public ConnectionRequestMessage Message { get; set; } [JsonProperty(PropertyName = "node_identifier")] public string NodeIdentifier { get; set; } [JsonProperty(PropertyName = "signature")] public string Signature { get; set; } } }
26.1
62
0.66092
[ "MIT" ]
Mirch/dotnetcore-sdk
src/Thenewboston/Validator/Models/ConnectionRequest.cs
524
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// koubei.advert.delivery.item.apply /// </summary> public class KoubeiAdvertDeliveryItemApplyRequest : IAlipayRequest<KoubeiAdvertDeliveryItemApplyResponse> { /// <summary> /// 口碑外部投放授权领券接口 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "koubei.advert.delivery.item.apply"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public void PutOtherTextParam(string key, string value) { if (udfParams == null) { udfParams = new Dictionary<string, string>(); } udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; if (udfParams != null) { parameters.AddAll(udfParams); } return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.528986
109
0.539267
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Request/KoubeiAdvertDeliveryItemApplyRequest.cs
3,273
C#
using GymWare.Entities; using GymWare.Logic; using GymWare.Entities.DTO; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using System.Web.Http.Cors; namespace GymWare.API.Controllers { public class MembresiasController : ApiController { private MembresiaLogic _me = new MembresiaLogic(); // POST: api/Membresias/CreateRenovateMembresia [ResponseType(typeof(Membresia))] [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "POST")] public IHttpActionResult CreateRenovateMembresia(MembresiaCuotaDTO membresiaCuotaDTO) { if (!ModelState.IsValid) { return BadRequest(ModelState); } Membresia membresia = _me.CreateRenovateMembresia(membresiaCuotaDTO); if (membresia != null) { return Json(membresia); } else { return Json("Error al intentar crear/renovar la Membresia!"); } } } }
28.097561
93
0.626736
[ "MIT" ]
GMM-UTN/GymWare
GymWare-Backend/GymWare.API/Controllers/MembresiasController.cs
1,154
C#
using UnityEngine; namespace ET { public class SceneChangeComponent: Entity { public AsyncOperation loadMapOperation; public ETTaskCompletionSource tcs; } }
18.6
47
0.704301
[ "MIT" ]
AnotherEnd15/ET_NetcodeDemo
Unity/Assets/ModelView/Scene/SceneChangeComponent.cs
188
C#
// // Copyright (c) Seal Report (sealreport@gmail.com), http://www.sealreport.org. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. http://www.apache.org/licenses/LICENSE-2.0.. // using Seal.Helpers; using System; using System.IO; using System.Xml.Serialization; namespace Seal.Model { /// <summary> /// OutputFolderDevice is an implementation of device that save the report result to a file. /// </summary> public class OutputFolderDevice : OutputDevice { /// <summary> /// Default device identifier /// </summary> public static string DefaultGUID = "c428a6ba-061b-4a47-b9bc-f3f02442ab4b"; /// <summary> /// Create a basic OutputFolderDevice /// </summary> static public OutputFolderDevice Create() { OutputFolderDevice result = new OutputFolderDevice() { GUID = DefaultGUID }; result.Name = "Folder Device"; return result; } /// <summary> /// Full name /// </summary> [XmlIgnore] public override string FullName { get { return "Folder Device"; } } /// <summary> /// Check that the report result has been saved and set information /// </summary> public override void Process(Report report) { ReportOutput output = report.OutputToExecute; if (string.IsNullOrEmpty(output.FolderPath)) throw new Exception("The output folder path is not specified in the report output."); if (string.IsNullOrEmpty(output.FileName)) throw new Exception("The file name is not specified in the report output."); if (output.ZipResult) { var zipPath = Path.Combine(report.OutputFolderDeviceResultFolder, Path.GetFileNameWithoutExtension(report.ResultFileName) + ".zip"); FileHelper.CreateZIP(report.ResultFilePath, Path.GetFileNameWithoutExtension(report.ResultFileName) + Path.GetExtension(report.ResultFilePath), zipPath, output.ZipPassword); File.Delete(report.ResultFilePath); report.ResultFilePath = zipPath; } output.Information = report.Translate("Report result generated in '{0}'", report.DisplayResultFilePath); report.LogMessage("Report result generated in '{0}'", report.DisplayResultFilePath); } /// <summary> /// Dummy function /// </summary> public override void SaveToFile() { throw new Exception("No need so far..."); } /// <summary> /// Dummy function /// </summary> public override void SaveToFile(string path) { throw new Exception("No need so far..."); } /// <summary> /// Dummy function /// </summary> public override void Validate() { } } }
35.081395
189
0.600597
[ "Apache-2.0" ]
destevetewis/Seal-Report
Projects/SealLibrary/Model/OutputFolderDevice.cs
3,019
C#
// Copyright (C) 2004-2005 MySQL AB // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as published by // the Free Software Foundation // // There are special exceptions to the terms and conditions of the GPL // as it is applied to this software. View the full text of the // exception in file EXCEPTIONS in the directory of this software // distribution. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Threading; using System.Runtime.InteropServices; namespace MySql.Data.Common { class NativeMethods { // Keep the compiler from generating a default ctor private NativeMethods() { } [StructLayout(LayoutKind.Sequential)] public class SecurityAttributes { public SecurityAttributes() { Length = Marshal.SizeOf(typeof(SecurityAttributes)); } public int Length; public IntPtr securityDescriptor = IntPtr.Zero; public bool inheritHandle; } [DllImport("Kernel32")] static extern public int CreateFile(String fileName, uint desiredAccess, uint shareMode, SecurityAttributes securityAttributes, uint creationDisposition, uint flagsAndAttributes, uint templateFile); [return:MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", EntryPoint="PeekNamedPipe", SetLastError=true)] static extern public bool PeekNamedPipe(IntPtr handle, byte[] buffer, uint nBufferSize, ref uint bytesRead, ref uint bytesAvail, ref uint BytesLeftThisMessage); [return:MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", SetLastError=true)] static extern internal bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped); [return:MarshalAs(UnmanagedType.Bool)] [DllImport("Kernel32")] static extern internal bool WriteFile(IntPtr hFile, [In]byte[] buffer, uint numberOfBytesToWrite, out uint numberOfBytesWritten, IntPtr lpOverlapped); [return:MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", SetLastError=true)] public static extern bool CloseHandle(IntPtr handle); [return:MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", SetLastError=true)] public static extern bool FlushFileBuffers(IntPtr handle); //Constants for dwDesiredAccess: public const UInt32 GENERIC_READ = 0x80000000; public const UInt32 GENERIC_WRITE = 0x40000000; //Constants for return value: public const Int32 INVALIDpipeHandle_VALUE = -1; //Constants for dwFlagsAndAttributes: public const UInt32 FILE_FLAG_OVERLAPPED = 0x40000000; public const UInt32 FILE_FLAG_NO_BUFFERING = 0x20000000; //Constants for dwCreationDisposition: public const UInt32 OPEN_EXISTING = 3; #region Winsock functions // SOcket routines [DllImport("ws2_32.dll", SetLastError=true)] static extern public IntPtr socket(int af, int type, int protocol); [DllImport("ws2_32.dll", SetLastError=true)] static extern public int ioctlsocket(IntPtr socket, uint cmd, ref UInt32 arg); [DllImport("ws2_32.dll", SetLastError=true)] public static extern int WSAIoctl(IntPtr s, uint dwIoControlCode, byte[] inBuffer, uint cbInBuffer, byte[] outBuffer, uint cbOutBuffer, IntPtr lpcbBytesReturned, IntPtr lpOverlapped, IntPtr lpCompletionRoutine); [DllImport("ws2_32.dll", SetLastError=true)] static extern public int WSAGetLastError(); [DllImport("ws2_32.dll", SetLastError=true)] static extern public int connect(IntPtr socket, byte[] addr, int addrlen); [DllImport("ws2_32.dll", SetLastError=true)] static extern public int recv(IntPtr socket, byte[] buff, int len, int flags); [DllImport("ws2_32.Dll", SetLastError=true)] static extern public int send(IntPtr socket, byte[] buff, int len, int flags); #endregion } }
33.551181
102
0.754518
[ "MIT" ]
silvath/siscobras
mdlDataBaseAccess/mdlDataBaseAccess/MySqlClient/Common/NativeMethods.cs
4,261
C#
// World Conquer Online Project 2.5517 - Phoenix Project Based // This project has been created by Felipe Vieira Vendramini // Source Infrastructure based on Phoenix Source, written by Gareth Jensen // This source is targeted to Conquer Online, client version 5517 // // Computer User: Felipe Vieira // File Created by: Felipe Vieira Vendramini // zfserver v2.5517 - MsgServer - IQuenchDrop.cs // Last Edit: 2016/12/13 08:43 // Created: 2016/12/13 07:19 using System.Collections.Generic; namespace MsgServer.Structures.Interfaces { public class SpecialDrop { public uint MonsterIdentity { get; set; } public string MonsterName { get; set; } public byte DropNum { get; set; } public byte Level { get; set; } public byte LevelTolerance { get; set; } public uint DefaultAction { get; set; } public List<KeyValuePair<uint, ushort>> Actions { get; set; } } }
35.653846
74
0.692557
[ "MIT" ]
darkfoxdeveloper/FoxConquer5517
MsgServer/Structures/Interfaces/IQuenchDrop.cs
929
C#
/** * Copyright 2018 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IBM.WatsonDeveloperCloud.Conversation.v1.Model { /// <summary> /// CreateDialogNode. /// </summary> public class CreateDialogNode : BaseModel { /// <summary> /// How the dialog node is processed. /// </summary> /// <value>How the dialog node is processed.</value> [JsonConverter(typeof(StringEnumConverter))] public enum NodeTypeEnum { /// <summary> /// Enum STANDARD for standard /// </summary> [EnumMember(Value = "standard")] STANDARD, /// <summary> /// Enum EVENT_HANDLER for event_handler /// </summary> [EnumMember(Value = "event_handler")] EVENT_HANDLER, /// <summary> /// Enum FRAME for frame /// </summary> [EnumMember(Value = "frame")] FRAME, /// <summary> /// Enum SLOT for slot /// </summary> [EnumMember(Value = "slot")] SLOT, /// <summary> /// Enum RESPONSE_CONDITION for response_condition /// </summary> [EnumMember(Value = "response_condition")] RESPONSE_CONDITION, /// <summary> /// Enum FOLDER for folder /// </summary> [EnumMember(Value = "folder")] FOLDER } /// <summary> /// How an `event_handler` node is processed. /// </summary> /// <value>How an `event_handler` node is processed.</value> [JsonConverter(typeof(StringEnumConverter))] public enum EventNameEnum { /// <summary> /// Enum FOCUS for focus /// </summary> [EnumMember(Value = "focus")] FOCUS, /// <summary> /// Enum INPUT for input /// </summary> [EnumMember(Value = "input")] INPUT, /// <summary> /// Enum FILLED for filled /// </summary> [EnumMember(Value = "filled")] FILLED, /// <summary> /// Enum VALIDATE for validate /// </summary> [EnumMember(Value = "validate")] VALIDATE, /// <summary> /// Enum FILLED_MULTIPLE for filled_multiple /// </summary> [EnumMember(Value = "filled_multiple")] FILLED_MULTIPLE, /// <summary> /// Enum GENERIC for generic /// </summary> [EnumMember(Value = "generic")] GENERIC, /// <summary> /// Enum NOMATCH for nomatch /// </summary> [EnumMember(Value = "nomatch")] NOMATCH, /// <summary> /// Enum NOMATCH_RESPONSES_DEPLETED for nomatch_responses_depleted /// </summary> [EnumMember(Value = "nomatch_responses_depleted")] NOMATCH_RESPONSES_DEPLETED } /// <summary> /// Whether this top-level dialog node can be digressed into. /// </summary> /// <value>Whether this top-level dialog node can be digressed into.</value> [JsonConverter(typeof(StringEnumConverter))] public enum DigressInEnum { /// <summary> /// Enum NOT_AVAILABLE for not_available /// </summary> [EnumMember(Value = "not_available")] NOT_AVAILABLE, /// <summary> /// Enum RETURNS for returns /// </summary> [EnumMember(Value = "returns")] RETURNS, /// <summary> /// Enum DOES_NOT_RETURN for does_not_return /// </summary> [EnumMember(Value = "does_not_return")] DOES_NOT_RETURN } /// <summary> /// Whether this dialog node can be returned to after a digression. /// </summary> /// <value>Whether this dialog node can be returned to after a digression.</value> [JsonConverter(typeof(StringEnumConverter))] public enum DigressOutEnum { /// <summary> /// Enum ALLOW_RETURNING for allow_returning /// </summary> [EnumMember(Value = "allow_returning")] ALLOW_RETURNING, /// <summary> /// Enum ALLOW_ALL for allow_all /// </summary> [EnumMember(Value = "allow_all")] ALLOW_ALL, /// <summary> /// Enum ALLOW_ALL_NEVER_RETURN for allow_all_never_return /// </summary> [EnumMember(Value = "allow_all_never_return")] ALLOW_ALL_NEVER_RETURN } /// <summary> /// Whether the user can digress to top-level nodes while filling out slots. /// </summary> /// <value>Whether the user can digress to top-level nodes while filling out slots.</value> [JsonConverter(typeof(StringEnumConverter))] public enum DigressOutSlotsEnum { /// <summary> /// Enum NOT_ALLOWED for not_allowed /// </summary> [EnumMember(Value = "not_allowed")] NOT_ALLOWED, /// <summary> /// Enum ALLOW_RETURNING for allow_returning /// </summary> [EnumMember(Value = "allow_returning")] ALLOW_RETURNING, /// <summary> /// Enum ALLOW_ALL for allow_all /// </summary> [EnumMember(Value = "allow_all")] ALLOW_ALL } /// <summary> /// How the dialog node is processed. /// </summary> /// <value>How the dialog node is processed.</value> [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] public NodeTypeEnum? NodeType { get; set; } /// <summary> /// How an `event_handler` node is processed. /// </summary> /// <value>How an `event_handler` node is processed.</value> [JsonProperty("event_name", NullValueHandling = NullValueHandling.Ignore)] public EventNameEnum? EventName { get; set; } /// <summary> /// Whether this top-level dialog node can be digressed into. /// </summary> /// <value>Whether this top-level dialog node can be digressed into.</value> [JsonProperty("digress_in", NullValueHandling = NullValueHandling.Ignore)] public DigressInEnum? DigressIn { get; set; } /// <summary> /// Whether this dialog node can be returned to after a digression. /// </summary> /// <value>Whether this dialog node can be returned to after a digression.</value> [JsonProperty("digress_out", NullValueHandling = NullValueHandling.Ignore)] public DigressOutEnum? DigressOut { get; set; } /// <summary> /// Whether the user can digress to top-level nodes while filling out slots. /// </summary> /// <value>Whether the user can digress to top-level nodes while filling out slots.</value> [JsonProperty("digress_out_slots", NullValueHandling = NullValueHandling.Ignore)] public DigressOutSlotsEnum? DigressOutSlots { get; set; } /// <summary> /// The dialog node ID. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 1024 characters. /// </summary> /// <value>The dialog node ID. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 1024 characters.</value> [JsonProperty("dialog_node", NullValueHandling = NullValueHandling.Ignore)] public string DialogNode { get; set; } /// <summary> /// The description of the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. /// </summary> /// <value>The description of the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters.</value> [JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)] public string Description { get; set; } /// <summary> /// The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. /// </summary> /// <value>The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters.</value> [JsonProperty("conditions", NullValueHandling = NullValueHandling.Ignore)] public string Conditions { get; set; } /// <summary> /// The ID of the parent dialog node. /// </summary> /// <value>The ID of the parent dialog node.</value> [JsonProperty("parent", NullValueHandling = NullValueHandling.Ignore)] public string Parent { get; set; } /// <summary> /// The ID of the previous dialog node. /// </summary> /// <value>The ID of the previous dialog node.</value> [JsonProperty("previous_sibling", NullValueHandling = NullValueHandling.Ignore)] public string PreviousSibling { get; set; } /// <summary> /// The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://console.bluemix.net/docs/services/conversation/dialog-overview.html#complex). /// </summary> /// <value>The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://console.bluemix.net/docs/services/conversation/dialog-overview.html#complex).</value> [JsonProperty("output", NullValueHandling = NullValueHandling.Ignore)] public object Output { get; set; } /// <summary> /// The context for the dialog node. /// </summary> /// <value>The context for the dialog node.</value> [JsonProperty("context", NullValueHandling = NullValueHandling.Ignore)] public object Context { get; set; } /// <summary> /// The metadata for the dialog node. /// </summary> /// <value>The metadata for the dialog node.</value> [JsonProperty("metadata", NullValueHandling = NullValueHandling.Ignore)] public object Metadata { get; set; } /// <summary> /// The next step to be executed in dialog processing. /// </summary> /// <value>The next step to be executed in dialog processing.</value> [JsonProperty("next_step", NullValueHandling = NullValueHandling.Ignore)] public DialogNodeNextStep NextStep { get; set; } /// <summary> /// An array of objects describing any actions to be invoked by the dialog node. /// </summary> /// <value>An array of objects describing any actions to be invoked by the dialog node.</value> [JsonProperty("actions", NullValueHandling = NullValueHandling.Ignore)] public List<DialogNodeAction> Actions { get; set; } /// <summary> /// The alias used to identify the dialog node. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 64 characters. /// </summary> /// <value>The alias used to identify the dialog node. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 64 characters.</value> [JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)] public string Title { get; set; } /// <summary> /// The location in the dialog context where output is stored. /// </summary> /// <value>The location in the dialog context where output is stored.</value> [JsonProperty("variable", NullValueHandling = NullValueHandling.Ignore)] public string Variable { get; set; } } }
42.600629
262
0.579612
[ "Apache-2.0" ]
thiagoloureiro/dotnet-standard-sdk
src/IBM.WatsonDeveloperCloud.Conversation.v1/Model/CreateDialogNode.cs
13,547
C#
using System.CodeDom.Compiler; using System.Web.Razor.Parser.SyntaxTree; using ServiceStack.Razor.Templating; using ServiceStack.Text; using System; using System.CodeDom; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Web.Razor; using System.Web.Razor.Generator; using System.Web.Razor.Parser; namespace ServiceStack.Razor.Compilation { /// <summary> /// Provides a base implementation of a compiler service. /// </summary> public abstract class CompilerServiceBase { private readonly CodeDomProvider CodeDomProvider; protected CompilerServiceBase( CodeDomProvider codeDomProvider, RazorCodeLanguage codeLanguage) { if (codeLanguage == null) throw new ArgumentNullException("codeLanguage"); CodeDomProvider = codeDomProvider; CodeLanguage = codeLanguage; } /// <summary> /// Gets the code language. /// </summary> public RazorCodeLanguage CodeLanguage { get; private set; } /// <summary> /// Builds a type name for the specified template type and model type. /// </summary> /// <param name="templateType">The template type.</param> /// <param name="modelType">The model type.</param> /// <returns>The string type name (including namespace).</returns> public virtual string BuildTypeName(Type templateType, Type modelType) { if (templateType == null) throw new ArgumentNullException("templateType"); if (!templateType.IsGenericTypeDefinition && !templateType.IsGenericType) return templateType.FullName; if (modelType == null) throw new ArgumentException("The template type is a generic defintion, and no model type has been supplied."); bool @dynamic = CompilerServices.IsDynamicType(modelType); Type genericType = templateType.MakeGenericType(modelType); return BuildTypeNameInternal(genericType, @dynamic); } /// <summary> /// Builds a type name for the specified generic type. /// </summary> /// <param name="type">The type.</param> /// <param name="isDynamic">Is the model type dynamic?</param> /// <returns>The string typename (including namespace and generic type parameters).</returns> public abstract string BuildTypeNameInternal(Type type, bool isDynamic); static string[] DuplicatedAssmebliesInMono = new string[] { "mscorlib.dll", "System/4.0.0.0__b77a5c561934e089/System.dll", "System.Xml/4.0.0.0__b77a5c561934e089/System.Xml.dll", "System.Core/4.0.0.0__b77a5c561934e089/System.Core.dll", "Microsoft.CSharp/4.0.0.0__b03f5f7f11d50a3a/Microsoft.CSharp.dll", }; /// <summary> /// Creates the compile results for the specified <see cref="TypeContext"/>. /// </summary> /// <param name="context">The type context.</param> /// <returns>The compiler results.</returns> private CompilerResults Compile(TypeContext context) { var compileUnit = GetCodeCompileUnit( context.ClassName, context.TemplateContent, context.Namespaces, context.TemplateType, context.ModelType); var @params = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false, IncludeDebugInformation = false, CompilerOptions = "/target:library /optimize", }; var assemblies = CompilerServices .GetLoadedAssemblies() .Where(a => !a.IsDynamic) .Select(a => a.Location) .ToArray(); @params.ReferencedAssemblies.AddRange(assemblies); if (Env.IsMono) { for (var i=@params.ReferencedAssemblies.Count-1; i>=0; i--) { var assembly = @params.ReferencedAssemblies[i]; foreach (var filterAssembly in DuplicatedAssmebliesInMono) { if (assembly.Contains(filterAssembly)) { @params.ReferencedAssemblies.RemoveAt(i); } } } } return CodeDomProvider.CompileAssemblyFromDom(@params, compileUnit); } public Type CompileType(TypeContext context) { var results = Compile(context); if (results.Errors != null && results.Errors.Count > 0) { throw new TemplateCompilationException(results.Errors); } return results.CompiledAssembly.GetType("CompiledRazorTemplates.Dynamic." + context.ClassName); } /// <summary> /// Generates any required contructors for the specified type. /// </summary> /// <param name="constructors">The set of constructors.</param> /// <param name="codeType">The code type declaration.</param> private static void GenerateConstructors(IEnumerable<ConstructorInfo> constructors, CodeTypeDeclaration codeType) { if (constructors == null || !constructors.Any()) return; var existingConstructors = codeType.Members.OfType<CodeConstructor>().ToArray(); foreach (var existingConstructor in existingConstructors) codeType.Members.Remove(existingConstructor); foreach (var constructor in constructors) { var ctor = new CodeConstructor { Attributes = MemberAttributes.Public }; foreach (var param in constructor.GetParameters()) { ctor.Parameters.Add(new CodeParameterDeclarationExpression(param.ParameterType, param.Name)); ctor.BaseConstructorArgs.Add(new CodeSnippetExpression(param.Name)); } codeType.Members.Add(ctor); } } /// <summary> /// Gets the code compile unit used to compile a type. /// </summary> /// <param name="className">The class name.</param> /// <param name="template">The template to compile.</param> /// <param name="namespaceImports">The set of namespace imports.</param> /// <param name="templateType">The template type.</param> /// <param name="modelType">The model type.</param> /// <returns>A <see cref="CodeCompileUnit"/> used to compile a type.</returns> public CodeCompileUnit GetCodeCompileUnit(string className, string template, ISet<string> namespaceImports, Type templateType, Type modelType) { if (string.IsNullOrEmpty(className)) throw new ArgumentException("Class name is required."); if (string.IsNullOrEmpty(template)) throw new ArgumentException("Template is required."); templateType = templateType ?? ((modelType == null) ? typeof(TemplateBase) : typeof(TemplateBase<>)); var host = new RazorEngineHost(CodeLanguage) { DefaultBaseClass = BuildTypeName(templateType, modelType), DefaultClassName = className, DefaultNamespace = "CompiledRazorTemplates.Dynamic", GeneratedClassContext = new GeneratedClassContext( "Execute", "Write", "WriteLiteral", "WriteTo", "WriteLiteralTo", "ServiceStack.Razor.Templating.TemplateWriter", "WriteSection") { ResolveUrlMethodName = "Href" } }; var templateNamespaces = templateType.GetCustomAttributes(typeof(RequireNamespacesAttribute), true) .Cast<RequireNamespacesAttribute>() .SelectMany(att => att.Namespaces); foreach (string ns in templateNamespaces) namespaceImports.Add(ns); foreach (string @namespace in namespaceImports) host.NamespaceImports.Add(@namespace); var engine = new RazorTemplateEngine(host); GeneratorResults result; using (var reader = new StringReader(template)) { result = engine.GenerateCode(reader); } var type = result.GeneratedCode.Namespaces[0].Types[0]; if (modelType != null) { if (CompilerServices.IsAnonymousType(modelType)) { type.CustomAttributes.Add(new CodeAttributeDeclaration( new CodeTypeReference(typeof(HasDynamicModelAttribute)))); } } GenerateConstructors(CompilerServices.GetConstructors(templateType), type); var statement = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Clear"); foreach (CodeTypeMember member in type.Members) { if (member.Name.Equals("Execute")) { ((CodeMemberMethod)member).Statements.Insert(0, new CodeExpressionStatement(statement)); break; } } return result.GeneratedCode; } public IEnumerable<T> AllNodesOfType<T>(Block block) { if (block is T) yield return (T)(object)block; foreach (var syntaxTreeNode in block.Children) { if (syntaxTreeNode is T) yield return (T)(object)syntaxTreeNode; var childBlock = syntaxTreeNode as Block; if (childBlock == null) continue; foreach (var variable in AllNodesOfType<T>(childBlock)) { yield return variable; } } } } }
38.85283
151
0.573038
[ "BSD-3-Clause" ]
denza/ServiceStack
src/ServiceStack.Razor2/Compilation/CompilerServiceBase.cs
10,034
C#
namespace ExchangeRateResolver.Models { public interface IParsedObject { string OriginalCommand { get; set; } } }
19.142857
44
0.671642
[ "MIT" ]
oatcrunch/ExchangeRateResolverDotNET
ExchangeRateResolver/Models/IParsedObject.cs
136
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using HotChocolate; using HotChocolate.Language; using HotChocolate.Types; using StrawberryShake.CodeGeneration.Analyzers; using static StrawberryShake.CodeGeneration.Utilities.DocumentHelper; namespace StrawberryShake.CodeGeneration.Utilities { public static class SchemaHelper { public static ISchema Load( IEnumerable<GraphQLFile> files, bool strictValidation = true) { if (files is null) { throw new ArgumentNullException(nameof(files)); } var lookup = new Dictionary<ISyntaxNode, string>(); IndexSyntaxNodes(files, lookup); var builder = SchemaBuilder.New(); builder.ModifyOptions(o => o.StrictValidation = strictValidation); var leafTypes = new Dictionary<NameString, LeafTypeInfo>(); var globalEntityPatterns = new List<SelectionSetNode>(); var typeEntityPatterns = new Dictionary<NameString, SelectionSetNode>(); foreach (DocumentNode document in files.Select(f => f.Document)) { if (document.Definitions.Any(t => t is ITypeSystemExtensionNode)) { CollectScalarInfos( document.Definitions.OfType<ScalarTypeExtensionNode>(), leafTypes); CollectEnumInfos( document.Definitions.OfType<EnumTypeExtensionNode>(), leafTypes); CollectGlobalEntityPatterns( document.Definitions.OfType<SchemaExtensionNode>(), globalEntityPatterns); CollectTypeEntityPatterns( document.Definitions.OfType<ObjectTypeExtensionNode>(), typeEntityPatterns); AddDefaultScalarInfos(leafTypes); } else { foreach (var scalar in document.Definitions.OfType<ScalarTypeDefinitionNode>()) { if (!BuiltInScalarNames.IsBuiltInScalar(scalar.Name.Value)) { builder.AddType(new AnyType( scalar.Name.Value, scalar.Description?.Value)); } } builder.AddDocument(document); } } return builder .TryAddTypeInterceptor( new LeafTypeInterceptor(leafTypes)) .TryAddTypeInterceptor( new EntityTypeInterceptor(globalEntityPatterns, typeEntityPatterns)) .Use(_ => _ => throw new NotSupportedException()) .Create(); } private static void CollectScalarInfos( IEnumerable<ScalarTypeExtensionNode> scalarTypeExtensions, Dictionary<NameString, LeafTypeInfo> leafTypes) { foreach (ScalarTypeExtensionNode scalarTypeExtension in scalarTypeExtensions) { if (!leafTypes.TryGetValue( scalarTypeExtension.Name.Value, out LeafTypeInfo scalarInfo)) { scalarInfo = new LeafTypeInfo( scalarTypeExtension.Name.Value, GetDirectiveValue(scalarTypeExtension, "runtimeType"), GetDirectiveValue(scalarTypeExtension, "serializationType")); leafTypes.Add(scalarInfo.TypeName, scalarInfo); } } } private static void CollectEnumInfos( IEnumerable<EnumTypeExtensionNode> enumTypeExtensions, Dictionary<NameString, LeafTypeInfo> leafTypes) { foreach (EnumTypeExtensionNode scalarTypeExtension in enumTypeExtensions) { if (!leafTypes.TryGetValue( scalarTypeExtension.Name.Value, out LeafTypeInfo scalarInfo)) { scalarInfo = new LeafTypeInfo( scalarTypeExtension.Name.Value, GetDirectiveValue(scalarTypeExtension, "runtimeType"), GetDirectiveValue(scalarTypeExtension, "serializationType")); leafTypes.Add(scalarInfo.TypeName, scalarInfo); } } } private static string? GetDirectiveValue( HotChocolate.Language.IHasDirectives hasDirectives, NameString directiveName) { DirectiveNode? directive = hasDirectives.Directives.FirstOrDefault( t => directiveName.Equals(t.Name.Value)); if (directive is { Arguments: { Count: > 0 } }) { ArgumentNode? argument = directive.Arguments.FirstOrDefault( t => t.Name.Value.Equals("name")); if (argument is { Value: StringValueNode stringValue }) { return stringValue.Value; } } return null; } private static void CollectGlobalEntityPatterns( IEnumerable<SchemaExtensionNode> schemaExtensions, List<SelectionSetNode> entityPatterns) { foreach (var schemaExtension in schemaExtensions) { foreach (var directive in schemaExtension.Directives) { if (TryGetKeys(directive, out SelectionSetNode? selectionSet)) { entityPatterns.Add(selectionSet); } } } } private static void CollectTypeEntityPatterns( IEnumerable<ObjectTypeExtensionNode> objectTypeExtensions, Dictionary<NameString, SelectionSetNode> entityPatterns) { foreach (ObjectTypeExtensionNode objectTypeExtension in objectTypeExtensions) { if (TryGetKeys(objectTypeExtension, out SelectionSetNode? selectionSet) && !entityPatterns.ContainsKey(objectTypeExtension.Name.Value)) { entityPatterns.Add( objectTypeExtension.Name.Value, selectionSet); } } } private static void AddDefaultScalarInfos( Dictionary<NameString, LeafTypeInfo> leafTypes) { TryAddLeafType(leafTypes, ScalarNames.String, TypeNames.String); TryAddLeafType(leafTypes, ScalarNames.ID, TypeNames.String); TryAddLeafType(leafTypes, ScalarNames.Boolean, TypeNames.Boolean, TypeNames.Boolean); TryAddLeafType(leafTypes, ScalarNames.Byte, TypeNames.Byte, TypeNames.Byte); TryAddLeafType(leafTypes, ScalarNames.Short, TypeNames.Int16, TypeNames.Int16); TryAddLeafType(leafTypes, ScalarNames.Int, TypeNames.Int32, TypeNames.Int32); TryAddLeafType(leafTypes, ScalarNames.Long, TypeNames.Int64, TypeNames.Int64); TryAddLeafType(leafTypes, ScalarNames.Float, TypeNames.Double, TypeNames.Double); TryAddLeafType(leafTypes, ScalarNames.Decimal, TypeNames.Decimal, TypeNames.Decimal); TryAddLeafType(leafTypes, ScalarNames.Url, TypeNames.Uri); TryAddLeafType(leafTypes, ScalarNames.Uuid, TypeNames.Guid, TypeNames.Guid); TryAddLeafType(leafTypes, "Guid", TypeNames.Guid, TypeNames.Guid); TryAddLeafType(leafTypes, ScalarNames.DateTime, TypeNames.DateTimeOffset); TryAddLeafType(leafTypes, ScalarNames.Date, TypeNames.DateTime); TryAddLeafType(leafTypes, ScalarNames.TimeSpan, TypeNames.TimeSpan); TryAddLeafType(leafTypes, ScalarNames.ByteArray, TypeNames.ByteArray); } private static bool TryGetKeys( HotChocolate.Language.IHasDirectives directives, [NotNullWhen(true)] out SelectionSetNode? selectionSet) { DirectiveNode? directive = directives.Directives.FirstOrDefault(IsKeyDirective); if (directive is not null) { return TryGetKeys(directive, out selectionSet); } selectionSet = null; return false; } private static bool TryGetKeys( DirectiveNode directive, [NotNullWhen(true)] out SelectionSetNode? selectionSet) { if (directive is { Arguments: { Count: 1 } } && directive.Arguments[0] is { Name: { Value: "fields" }, Value: StringValueNode sv }) { selectionSet = Utf8GraphQLParser.Syntax.ParseSelectionSet($"{{{sv.Value}}}"); return true; } selectionSet = null; return false; } private static bool IsKeyDirective(DirectiveNode directive) => directive.Name.Value.Equals("key", StringComparison.Ordinal); private static void TryAddLeafType( Dictionary<NameString, LeafTypeInfo> leafTypes, NameString typeName, string runtimeType, string serializationType = TypeNames.String) { if (!leafTypes.TryGetValue(typeName, out LeafTypeInfo leafType)) { leafType = new LeafTypeInfo(typeName, runtimeType, serializationType); leafTypes.Add(typeName, leafType); } } } }
40.473029
99
0.574739
[ "MIT" ]
VarunSaiTeja/hotchocolate
src/StrawberryShake/CodeGeneration/src/CodeGeneration/Utilities/SchemaHelper.cs
9,754
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hl7-org:v3")] public enum UKCT_MT140701UK03SourceOfTemplateIdRoot { /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("2.16.840.1.113883.2.1.3.2.4.18.2")] Item216840111388321324182, } }
83.535714
1,358
0.752031
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/UKCT_MT140701UK03SourceOfTemplateIdRoot.cs
2,339
C#
using Core.Entities; using System; using System.Collections.Generic; using System.Text; namespace Entities.Concrete { public class Order:IEntity { public int OrderID { get; set; } public int CustomerID { get; set; } public int EmployeeID { get; set; } public DateTime OrderDate { get; set; } public string ShipCity { get; set; } } }
22.764706
47
0.638243
[ "MIT" ]
CerenSusuz/NorthwindProject
Entities/Concrete/Order.cs
389
C#
// <copyright file="AuthenticatorClientShould.cs" company="Okta, Inc"> // Copyright (c) 2020 - present Okta, Inc. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. // </copyright> using System; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using NSubstitute; using Okta.Sdk.Internal; using Okta.Sdk.UnitTests.Internal; using Xunit; namespace Okta.Sdk.UnitTests { public class AuthenticatorClientShould { [Fact] public async Task ActivateAuthenticatorAsync() { var rawResponse = @"{ ""type"": ""security_key"", ""id"": ""aut1nd8PQhGcQtSxB0g4"", ""key"": ""webauthn"", ""status"": ""ACTIVE"", ""name"": ""Security Key or Biometric"", ""created"": ""2020-07-26T21:16:37.000Z"", ""lastUpdated"": ""2020-07-26T21:59:33.000Z"", ""_links"": { ""self"": { ""href"": ""https://${yourOktaDomain}/api/v1/authenticators/aut1nd8PQhGcQtSxB0g4"", ""hints"": { ""allow"": [ ""GET"", ""PUT"" ] } }, ""methods"": { ""href"": ""https://${yourOktaDomain}/api/v1/authenticators/aut1nd8PQhGcQtSxB0g4/methods"", ""hints"": { ""allow"": [ ""GET"" ] } }, ""deactivate"": { ""href"": ""https://${yourOktaDomain}/api/v1/authenticators/aut1nd8PQhGcQtSxB0g4/lifecycle/deactivate"", ""hints"": { ""allow"": [ ""POST"" ] } } } }"; var mockRequestExecutor = new MockedStringRequestExecutor(rawResponse); var client = new TestableOktaClient(mockRequestExecutor); var authenticator = await client.Authenticators.ActivateAuthenticatorAsync("aut1nd8PQhGcQtSxB0g4"); authenticator.Id.Should().Be("aut1nd8PQhGcQtSxB0g4"); authenticator.Status.Should().Be(AuthenticatorStatus.Active); authenticator.Key.Should().Be("webauthn"); authenticator.Name.Should().Be("Security Key or Biometric"); mockRequestExecutor.ReceivedHref.Should().Be("/api/v1/authenticators/aut1nd8PQhGcQtSxB0g4/lifecycle/activate"); } [Fact] public async Task DeactivateAuthenticatorAsync() { var rawResponse = @"{ ""type"": ""security_key"", ""id"": ""aut1nd8PQhGcQtSxB0g4"", ""key"": ""webauthn"", ""status"": ""INACTIVE"", ""name"": ""Security Key or Biometric"", ""created"": ""2020-07-26T21:16:37.000Z"", ""lastUpdated"": ""2020-07-26T21:59:33.000Z"", ""_links"": { ""self"": { ""href"": ""https://${yourOktaDomain}/api/v1/authenticators/aut1nd8PQhGcQtSxB0g4"", ""hints"": { ""allow"": [ ""GET"", ""PUT"" ] } }, ""methods"": { ""href"": ""https://${yourOktaDomain}/api/v1/authenticators/aut1nd8PQhGcQtSxB0g4/methods"", ""hints"": { ""allow"": [ ""GET"" ] } }, ""deactivate"": { ""href"": ""https://${yourOktaDomain}/api/v1/authenticators/aut1nd8PQhGcQtSxB0g4/lifecycle/deactivate"", ""hints"": { ""allow"": [ ""POST"" ] } } } }"; var mockRequestExecutor = new MockedStringRequestExecutor(rawResponse); var client = new TestableOktaClient(mockRequestExecutor); var authenticator = await client.Authenticators.DeactivateAuthenticatorAsync("aut1nd8PQhGcQtSxB0g4"); authenticator.Id.Should().Be("aut1nd8PQhGcQtSxB0g4"); authenticator.Status.Should().Be(AuthenticatorStatus.Inactive); authenticator.Key.Should().Be("webauthn"); authenticator.Name.Should().Be("Security Key or Biometric"); mockRequestExecutor.ReceivedHref.Should().Be("/api/v1/authenticators/aut1nd8PQhGcQtSxB0g4/lifecycle/deactivate"); } } }
49.920635
144
0.374245
[ "Apache-2.0" ]
okta/okta-sdk-dotnet
src/Okta.Sdk.UnitTests/AuthenticatorClientShould.cs
6,292
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ecs-2014-11-13.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.ECS.Model { /// <summary> /// The task placement strategy for a task or service. For more information, see <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-strategies.html">Task /// Placement Strategies</a> in the <i>Amazon Elastic Container Service Developer Guide</i>. /// </summary> public partial class PlacementStrategy { private string _field; private PlacementStrategyType _type; /// <summary> /// Gets and sets the property Field. /// <para> /// The field to apply the placement strategy against. For the <code>spread</code> placement /// strategy, valid values are <code>instanceId</code> (or <code>host</code>, which has /// the same effect), or any platform or custom attribute that is applied to a container /// instance, such as <code>attribute:ecs.availability-zone</code>. For the <code>binpack</code> /// placement strategy, valid values are <code>cpu</code> and <code>memory</code>. For /// the <code>random</code> placement strategy, this field is not used. /// </para> /// </summary> public string Field { get { return this._field; } set { this._field = value; } } // Check to see if Field property is set internal bool IsSetField() { return this._field != null; } /// <summary> /// Gets and sets the property Type. /// <para> /// The type of placement strategy. The <code>random</code> placement strategy randomly /// places tasks on available candidates. The <code>spread</code> placement strategy spreads /// placement across available candidates evenly based on the <code>field</code> parameter. /// The <code>binpack</code> strategy places tasks on available candidates that have the /// least available amount of the resource that is specified with the <code>field</code> /// parameter. For example, if you binpack on memory, a task is placed on the instance /// with the least amount of remaining memory (but still enough to run the task). /// </para> /// </summary> public PlacementStrategyType Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } } }
40.011364
191
0.628799
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ECS/Generated/Model/PlacementStrategy.cs
3,521
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the workspaces-2015-04-08.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.WorkSpaces.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.WorkSpaces.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DescribeTags operation /// </summary> public class DescribeTagsResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DescribeTagsResponse response = new DescribeTagsResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("TagList", targetDepth)) { var unmarshaller = new ListUnmarshaller<Tag, TagUnmarshaller>(TagUnmarshaller.Instance); response.TagList = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonWorkSpacesException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DescribeTagsResponseUnmarshaller _instance = new DescribeTagsResponseUnmarshaller(); internal static DescribeTagsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeTagsResponseUnmarshaller Instance { get { return _instance; } } } }
37.772727
194
0.633694
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/WorkSpaces/Generated/Model/Internal/MarshallTransformations/DescribeTagsResponseUnmarshaller.cs
4,155
C#
 namespace Gimela.Net.Http.Sessions { /// <summary> /// Stores sessions in your favorite store /// </summary> /// <remarks> /// /// </remarks> public interface ISessionStore { /// <summary> /// Saves the specified session. /// </summary> /// <param name="session">The session.</param> void Save(Session session); /// <summary> /// Touches the specified session /// </summary> /// <param name="id">Session id.</param> /// <remarks> /// Used to prevent sessions from expiring. /// </remarks> void Touch(string id); /// <summary> /// Loads a session /// </summary> /// <param name="id">Session id.</param> /// <returns>Session if found; otherwise <c>null</c>.</returns> Session Load(string id); /// <summary> /// Delete a session /// </summary> /// <param name="id">Id of session</param> void Delete(string id); } }
22.238095
67
0.563169
[ "MIT" ]
J-W-Chan/Gimela
src/Foundation/Net/Gimela.Net.Http/Sessions/ISessionStore.cs
936
C#
using System.Threading.Tasks; namespace Abp.Application.Features { /// <summary> /// Most simple implementation of <see cref="IFeatureDependency"/>. /// It checks one or more features if they are enabled. /// </summary> public class SimpleFeatureDependency : IFeatureDependency { /// <summary> /// A list of features to be checked if they are enabled. /// </summary> public string[] Features { get; set; } /// <summary> /// If this property is set to true, all of the <see cref="Features"/> must be enabled. /// If it's false, at least one of the <see cref="Features"/> must be enabled. /// Default: false. /// </summary> public bool RequiresAll { get; set; } /// <summary> /// Initializes a new instance of the <see cref="SimpleFeatureDependency"/> class. /// </summary> /// <param name="features">The features.</param> public SimpleFeatureDependency(params string[] features) { Features = features; } /// <summary> /// Initializes a new instance of the <see cref="SimpleFeatureDependency"/> class. /// </summary> /// <param name="requiresAll"> /// If this is set to true, all of the <see cref="Features"/> must be enabled. /// If it's false, at least one of the <see cref="Features"/> must be enabled. /// </param> /// <param name="features">The features.</param> public SimpleFeatureDependency(bool requiresAll, params string[] features) : this(features) { RequiresAll = requiresAll; } /// <inheritdoc/> public Task<bool> IsSatisfiedAsync(IFeatureDependencyContext context) { return context.FeatureChecker.IsEnabledAsync(RequiresAll, Features); } } }
36.519231
95
0.583992
[ "MIT" ]
nandotech/aspnetboilerplate
src/Abp/Application/Features/SimpleFeatureDependency.cs
1,901
C#
using System; using System.Windows.Forms; namespace GUI.Forms { public partial class SearchForm : Form { /// <summary> /// Gets whatever text was entered by the user in the search textbox. /// </summary> public string SearchText => findTextBox.Text; /// <summary> /// Gets whatever options was selected by the user in the search type combobox. /// </summary> public SearchType SelectedSearchType => ((SearchTypeItem)searchTypeComboBox.SelectedItem).Type; public SearchForm() { InitializeComponent(); searchTypeComboBox.ValueMember = "Id"; searchTypeComboBox.DisplayMember = "Name"; searchTypeComboBox.Items.Add(new SearchTypeItem("File Name (Partial Match)", SearchType.FileNamePartialMatch)); searchTypeComboBox.Items.Add(new SearchTypeItem("File Name (Exact Match)", SearchType.FileNameExactMatch)); searchTypeComboBox.Items.Add(new SearchTypeItem("File Full Path", SearchType.FullPath)); searchTypeComboBox.Items.Add(new SearchTypeItem("Regex", SearchType.Regex)); searchTypeComboBox.SelectedIndex = 0; } private void FindButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } private void CancelButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } /// <summary> /// On form load, setup the combo box search options and set the textbox as the focused control. /// </summary> /// <param name="sender">Object which raised event.</param> /// <param name="e">Event data.</param> private void SearchForm_Load(object sender, EventArgs e) { ActiveControl = findTextBox; } } }
35.462963
123
0.620366
[ "MIT" ]
John-Chan/ValveResourceFormat
GUI/Forms/SearchForm.cs
1,915
C#
using System.Threading.Tasks; using AssasApi.Request; using AssasApi.Model.Customer; using AssasApi.Model.Response; using AssasApi.Filter; namespace AssasApi.Data.BLL { public class CustomersBLL : BaseRequest { public CustomersBLL(ApiSettings settings) : base(settings) { } public async Task<ResponseRequest<CustomerModel>> CreatAsync(CreateCustomerModel create) { return await PostAsync<CustomerModel>(custormersRoute, create); } public async Task<ResponseRequest<CustomerModel>> UpdateAsync(UpdateCustomerModel update) { return await PostAsync<CustomerModel>($"{custormersRoute}/{update.CustomerId}", update); } public async Task<ResponseRequest<CustomerModel>> LoadAsync(string id) { return await GetAsync<CustomerModel>(custormersRoute, id); } public async Task<ResponseRequest<CustomerModel>> ListAsync(CustomerFilter filter = null) { string queryFilter = filter != null ? filter.GetFilter() : null; return await ListAsync<CustomerModel>(custormersRoute, queryFilter); } public async Task DeleteAsync(string id = null) { await DeleteAsync(custormersRoute,id); } } }
31.463415
100
0.670543
[ "MIT" ]
augusto-ar/AssasApi
AssasApi/AssasApi/Data/BLL/CustomersBLL.cs
1,292
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.Web.UI; using System.Collections.Generic; using System.Net.NetworkInformation; public class CGeneralFunction { public static DataTable filldata(string vqry) { SqlDataAdapter da = new SqlDataAdapter(vqry, CGLOBAL.getConnectionString()); DataTable dt = new DataTable(); da.Fill(dt); da = null; return dt; } public static DataTable filldataattendance(string vqry) { SqlDataAdapter da = new SqlDataAdapter(vqry, CGLOBAL.getConnectionStringattendance()); DataTable dt = new DataTable(); da.Fill(dt); da = null; return dt; } public static string NumberToWords(int number) { if (number == 0) return "zero"; if (number < 0) return "minus " + NumberToWords(Math.Abs(number)); string words = ""; if ((number / 1000000) > 0) { words += NumberToWords(number / 1000000) + " million "; number %= 1000000; } if ((number / 1000) > 0) { words += NumberToWords(number / 1000) + " thousand "; number %= 1000; } if ((number / 100) > 0) { words += NumberToWords(number / 100) + " hundred "; number %= 100; } if (number > 0) { if (words != "") words += "and "; var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; if (number < 20) words += unitsMap[number]; else { words += tensMap[number / 10]; if ((number % 10) > 0) words += "-" + unitsMap[number % 10]; } } return words; } public static DataTable fillACSDBdata(string vqry) { SqlDataAdapter da = new SqlDataAdapter(vqry, CGLOBAL.getNewConnectionString()); DataTable dt = new DataTable(); da.Fill(dt); da = null; return dt; } public static bool isvaliddata(string vquery) { try { SqlConnection con = new SqlConnection(CGLOBAL.getConnectionString()); SqlCommand cmd = new SqlCommand(); SqlDataReader dr; con.Open(); cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = vquery; dr = cmd.ExecuteReader(); if (dr.Read()) { return true; } else { return false; } con.Close(); } catch (Exception ex) { return false; } } public static int isExisting(string vquery) { int lid = 0; SqlConnection con = new SqlConnection(CGLOBAL.getConnectionString()); SqlCommand cmd = new SqlCommand(); con.Open(); cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = vquery; SqlDataReader reader = default(SqlDataReader); reader = cmd.ExecuteReader(); while (reader.Read()) { lid = int.Parse(reader[0].ToString()); //lid = lid + 1; } reader.Close(); if ((lid <= 0)) { con.Close(); cmd.Dispose(); return lid; } con.Close(); cmd.Dispose(); return lid; } public static bool delete(string vquery) { try { SqlConnection con = new SqlConnection(CGLOBAL.getConnectionString()); SqlCommand cmd = new SqlCommand(); con.Open(); cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = vquery; cmd.ExecuteNonQuery(); con.Close(); return true; } catch (Exception ex) { return false; } } public static bool save(string vquery) { try { SqlConnection con = new SqlConnection(CGLOBAL.getConnectionString()); SqlCommand cmd = new SqlCommand(); con.Open(); cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = vquery.ToUpper(); cmd.ExecuteNonQuery(); con.Close(); return true; } catch (Exception ex) { return false; } } public static string GetString(string vquery) { string Value = ""; SqlConnection con = new SqlConnection(CGLOBAL.getConnectionString()); SqlCommand cmd = new SqlCommand(); con.Open(); cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = vquery; SqlDataReader reader = default(SqlDataReader); reader = cmd.ExecuteReader(); while (reader.Read()) { Value = reader[0].ToString(); //lid = lid + 1; } reader.Close(); con.Close(); cmd.Dispose(); return Value; } public static bool saveolderp(string vquery, int @personid) { try { SqlConnection con = new SqlConnection(CGLOBAL.getConnectionString()); SqlCommand cmd = new SqlCommand(); con.Open(); cmd.Connection = con; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = vquery; cmd.Parameters.Add("@personid", SqlDbType.Int).Value = @personid; cmd.ExecuteNonQuery(); con.Close(); return true; } catch (Exception ex) { return false; } } public DataTable BindSemester() { DataAccessLayer da = new DataAccessLayer(); DataSet ds = da.getDataByParam("GetSem"); if (ds != null && ds.Tables.Count > 0) return ds.Tables[0]; else return null; } public DataSet GetEmailDetails(int contid) { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@EmpContractID", contid); DataAccessLayer da = new DataAccessLayer(); DataSet ds = da.getDataByParam(param, "[PrintContract]"); return ds; } public string GetMacAddress() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet && nic.OperationalStatus == OperationalStatus.Up) { return Convert.ToString(nic.GetPhysicalAddress()); } } return null; } public DataSet GetEmailsent(int contid) { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@EmpContractID", contid); DataAccessLayer da = new DataAccessLayer(); DataSet ds = da.getDataByParam(param, "[sp_GetEmailsent]"); return ds; } public static int isPTPayrollRunExist(string vquery) { int lid = 0; SqlConnection con = new SqlConnection(CGLOBAL.getConnectionString()); SqlCommand cmd = new SqlCommand(); con.Open(); cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = vquery; SqlDataReader reader = default(SqlDataReader); reader = cmd.ExecuteReader(); while (reader.Read()) { lid = int.Parse(reader[0].ToString()); //lid = lid + 1; } reader.Close(); if ((lid <= 0)) { con.Close(); cmd.Dispose(); return lid; } con.Close(); cmd.Dispose(); return lid; } public DataTable BindFilterationAcadamicYear() { DataAccessLayer da = new DataAccessLayer(); DataSet ds = da.AdminExamgetDataByParam("GetAcademicYear"); if (ds != null && ds.Tables.Count > 0) return ds.Tables[0]; else return null; } public DataTable BindFilterationContract() { DataAccessLayer da = new DataAccessLayer(); DataSet ds = da.getDataByParam("SP_ContractMaster"); if (ds != null && ds.Tables.Count > 0) return ds.Tables[0]; else return null; } public DataTable BindFilterationEmpName() { DataAccessLayer da = new DataAccessLayer(); DataSet ds = da.getDataByParam("SP_ContractEmpName"); if (ds != null && ds.Tables.Count > 0) return ds.Tables[0]; else return null; } public DataTable BindEmployeeDetails(int EmpNumber, int AcadamicYear, int SemesterID, int ContractType) { SqlParameter[] param = new SqlParameter[4]; param[0] = new SqlParameter("@EmpNumber", EmpNumber); param[1] = new SqlParameter("@AcadamicYear", AcadamicYear); param[2] = new SqlParameter("@SemesterID", SemesterID); param[3] = new SqlParameter("@ContractType", ContractType); DataAccessLayer da = new DataAccessLayer(); DataSet ds = da.getDataByParam(param, "[SP_FilterEmpContractDetails]"); if (ds != null && ds.Tables.Count > 0) return ds.Tables[0]; else return null; } public DataTable BindFilterationSemester(int AcyearID) { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@AcyearID", AcyearID); DataAccessLayer da = new DataAccessLayer(); DataSet ds = da.getDataByParam(param, "[SP_GetFilterationSemester]"); if (ds != null && ds.Tables.Count > 0) return ds.Tables[0]; else return null; } public string InsertJobdescriptionmaster(int JobID, string Jobtitle, string Reporting_To, string Leave_Guidelines, string Leave_Replace, string Educational_Req, string Know_Skills, string Key_Areas , string strategic_res, string operation_res, string Yearly_planning, string Reporting_Res, string Coord_Res, string calendar_checklist, string presentation, string orientation, string training, string audit , string policy_manual, string handbook, string created_by, string created_Ip) { try { // SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SkyLineConnection"].ToString()); SqlConnection conn = new SqlConnection(CGLOBAL.getConnectionString()); conn.Open(); SqlCommand cmd = new SqlCommand("[SP_INSERT_JOBDESC]", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@JOB_ID", JobID); cmd.Parameters.AddWithValue("@JOB_TITLE", Jobtitle); cmd.Parameters.AddWithValue("@Reporting_to", Reporting_To); cmd.Parameters.AddWithValue("@Leave_Guidelines", Leave_Guidelines); cmd.Parameters.AddWithValue("@Leave_Replacement", Leave_Replace); cmd.Parameters.AddWithValue("@Educational_req", Educational_Req); cmd.Parameters.AddWithValue("@Know_Skills", Know_Skills); cmd.Parameters.AddWithValue("@Key_areas", Key_Areas); cmd.Parameters.AddWithValue("@Strategic_res", strategic_res); cmd.Parameters.AddWithValue("@Operation_res", operation_res); cmd.Parameters.AddWithValue("@Yearly_planning", Yearly_planning); cmd.Parameters.AddWithValue("@Reporting_res", Reporting_Res); cmd.Parameters.AddWithValue("@CoOrd_Res", Coord_Res); cmd.Parameters.AddWithValue("@Calendar_Checklist", calendar_checklist); cmd.Parameters.AddWithValue("@Presentation", presentation); cmd.Parameters.AddWithValue("@Orientation", orientation); cmd.Parameters.AddWithValue("@Training", training); cmd.Parameters.AddWithValue("@Audit", audit); cmd.Parameters.AddWithValue("@Policy_Manual", policy_manual); cmd.Parameters.AddWithValue("@handbook", handbook); cmd.Parameters.AddWithValue("@CreatedBy", created_by); cmd.Parameters.AddWithValue("@createdIP", created_Ip); using (conn) cmd.ExecuteNonQuery(); conn.Close(); return "RegisterNo"; } catch { return "error"; } } public static DataTable Fill_JobDesc_Details() { SqlConnection con = new SqlConnection(CGLOBAL.getConnectionString()); SqlCommand cmd = new SqlCommand(); SqlDataAdapter da = new SqlDataAdapter(); DataTable dt = new DataTable(); try { //cmd = new SqlCommand("sp_DailyPresent", con); cmd = new SqlCommand("SP_GETJOBDESC_DETAILS", con); cmd.CommandType = CommandType.StoredProcedure; da.SelectCommand = cmd; da.Fill(dt); return dt; } catch (Exception ex) { return null; } } public static DataTable FillDesignation() { SqlConnection con = new SqlConnection(CGLOBAL.getConnectionString()); SqlCommand cmd = new SqlCommand(); SqlDataAdapter da = new SqlDataAdapter(); DataTable dt = new DataTable(); try { //cmd = new SqlCommand("sp_DailyPresent", con); cmd = new SqlCommand("SP_GETDESIGNATION", con); cmd.CommandType = CommandType.StoredProcedure; da.SelectCommand = cmd; da.Fill(dt); return dt; } catch (Exception ex) { return null; } } public static DataTable ReportingDepartment() { SqlConnection con = new SqlConnection(CGLOBAL.getConnectionString()); SqlCommand cmd = new SqlCommand(); SqlDataAdapter da = new SqlDataAdapter(); DataTable dt = new DataTable(); try { //cmd = new SqlCommand("sp_DailyPresent", con); cmd = new SqlCommand("SP_REPORTINGTO", con); cmd.CommandType = CommandType.StoredProcedure; da.SelectCommand = cmd; da.Fill(dt); return dt; } catch (Exception ex) { return null; } } public static DataTable Load_JobDesc_Details(int Jobdesc_ID) { SqlConnection con = new SqlConnection(CGLOBAL.getConnectionString()); SqlCommand cmd = new SqlCommand(); SqlDataAdapter da = new SqlDataAdapter(); DataTable dt = new DataTable(); try { //cmd = new SqlCommand("sp_DailyPresent", con); cmd = new SqlCommand("SP_LOAD_JOBDESC_DETAILS", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@JOBDESC_ID", Jobdesc_ID); da.SelectCommand = cmd; da.Fill(dt); return dt; } catch (Exception ex) { return null; } } }
31.821138
226
0.561127
[ "MIT" ]
daynet/LIBRARYPROGRAMSYSTEM
App_Code/CGeneralFunction.cs
15,658
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using NodaTime; using QuantConnect.Brokerages.Zerodha; using QuantConnect.Brokerages.Zerodha.Messages; using QuantConnect.Configuration; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Logging; using QuantConnect.Util; namespace QuantConnect.ToolBox.ZerodhaDownloader { public class ZerodhaDataDownloaderProgram { private static readonly string _apiKey = Config.Get("zerodha-api-key"); private static readonly string _accessToken = Config.Get("zerodha-access-token"); /// <summary> /// Zerodha Historical Data Downloader Toolbox Project For LEAN Algorithmic Trading Engine. /// By @itsbalamurali /// </summary> public static void ZerodhaDataDownloader(IList<string> tickers, string market, string resolution, string securityType, DateTime startDate, DateTime endDate) { if (resolution.IsNullOrEmpty() || tickers.IsNullOrEmpty()) { Console.WriteLine("ZerodhaDataDownloader ERROR: '--tickers=', --securityType, '--market' or '--resolution=' parameter is missing"); Console.WriteLine("--tickers=eg JSWSTEEL,TCS,INFY"); Console.WriteLine("--market=MCX/NSE/NFO/CDS/BSE"); Console.WriteLine("--security-type=Equity/Future/Option/Commodity"); Console.WriteLine("--resolution=Minute/Hour/Daily/Tick"); Environment.Exit(1); } try { var _kite = new Kite(_apiKey, _accessToken); var castResolution = (Resolution)Enum.Parse(typeof(Resolution), resolution); var castSecurityType = (SecurityType)Enum.Parse(typeof(SecurityType), securityType); // Load settings from config.json and create downloader var dataDirectory = Config.Get("data-directory", "../../../Data"); foreach (var pair in tickers) { var quoteTicker = market + ":" + pair; var instrumentQuotes = _kite.GetQuote(new string[] { quoteTicker }); var quote = instrumentQuotes[quoteTicker]; // Download data var pairObject = Symbol.Create(pair, castSecurityType, market); if (pairObject.ID.SecurityType != SecurityType.Forex || pairObject.ID.SecurityType != SecurityType.Cfd || pairObject.ID.SecurityType != SecurityType.Crypto || pairObject.ID.SecurityType == SecurityType.Base) { if (pairObject.ID.SecurityType == SecurityType.Forex || pairObject.ID.SecurityType == SecurityType.Cfd || pairObject.ID.SecurityType == SecurityType.Crypto || pairObject.ID.SecurityType == SecurityType.Base) { throw new ArgumentException("Invalid security type: " + pairObject.ID.SecurityType); } if (startDate >= endDate) { throw new ArgumentException("Invalid date range specified"); } var start = startDate.ConvertTo(DateTimeZone.Utc, TimeZones.Kolkata); var end = endDate.ConvertTo(DateTimeZone.Utc, TimeZones.Kolkata); // Write data var writer = new LeanDataWriter(castResolution, pairObject, dataDirectory); IList<TradeBar> fileEnum = new List<TradeBar>(); var history = new List<Historical>(); var timeSpan = new TimeSpan(); switch (castResolution) { case Resolution.Tick: throw new ArgumentException("Zerodha Doesn't support tick resolution"); case Resolution.Minute: if ((end - start).Days > 60) throw new ArgumentOutOfRangeException("For minutes data Zerodha support 60 days data download"); history = _kite.GetHistoricalData(quote.InstrumentToken.ToStringInvariant(), start, end, "minute").ToList(); timeSpan = Time.OneMinute; break; case Resolution.Hour: if ((end - start).Days > 400) throw new ArgumentOutOfRangeException("For daily data Zerodha support 400 days data download"); history = _kite.GetHistoricalData(quote.InstrumentToken.ToStringInvariant(), start, end, "60minute").ToList(); timeSpan = Time.OneHour; break; case Resolution.Daily: if ((end - start).Days > 400) throw new ArgumentOutOfRangeException("For daily data Zerodha support 400 days data download"); history = _kite.GetHistoricalData(quote.InstrumentToken.ToStringInvariant(), start, end, "day").ToList(); timeSpan = Time.OneDay; break; } foreach (var bar in history) { var linedata = new TradeBar(bar.TimeStamp, pairObject, bar.Open, bar.High, bar.Low, bar.Close, bar.Volume, timeSpan); fileEnum.Add(linedata); } writer.Write(fileEnum); } } } catch (Exception err) { Log.Error($"ZerodhaDataDownloadManager.OnError(): Message: {err.Message} Exception: {err.InnerException}"); } } } }
49.881481
231
0.56341
[ "Apache-2.0" ]
RhnSharma/Lean
ToolBox/ZerodhaDownloader/ZerodhaDataDownloaderProgram.cs
6,734
C#
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // 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 ICSharpCode.ILSpy.Properties; namespace ICSharpCode.ILSpy { [ExportMainMenuCommand(Menu = nameof(Resources._File), Header = nameof(Resources.ManageAssemblyLists), MenuIcon = "Images/AssemblyList", MenuCategory = nameof(Resources.Open), MenuOrder = 1.7)] sealed class ManageAssemblyListsCommand : SimpleCommand { public override void Execute(object parameter) { ManageAssemblyListsDialog dlg = new ManageAssemblyListsDialog(); dlg.Owner = MainWindow.Instance; dlg.ShowDialog(); } } }
47.171429
197
0.769836
[ "MIT" ]
zer0Kerbal/ILSpy
ILSpy/Commands/ManageAssemblyListsCommand.cs
1,653
C#
using System.Collections; using System.Collections.Generic; using UnityEditor; #if UNITY_EDITOR using UnityEngine; #endif namespace QuestSystem { public abstract class BaseInfo : ScriptableObject { public int ID; #if UNITY_EDITOR [MenuItem("QuestSystem/Generate IDs")] static void GenerateIDs() { var items = Resources.LoadAll<BaseInfo>(""); for (var i = 0; i < items.Length; i++) { var item = items[i]; item.ID = i + 1; EditorUtility.SetDirty(item); Debug.LogFormat("{0} > {1}", item.name, item.ID); } } #endif } public abstract class GoalTypeInfo : BaseInfo { } }
20.777778
65
0.553476
[ "MIT" ]
farlenkov/unity-dots-samples
unity-packages/com.unity-practice.quest-system/Runtime/Config/BaseInfo.cs
750
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using CppSharp.AST; using CppSharp.AST.Extensions; using CppSharp.Extensions; using CppSharp.Types; using ParserTargetInfo = CppSharp.Parser.ParserTargetInfo; using Type = CppSharp.AST.Type; namespace CppSharp.Generators.CSharp { public class CSharpTypePrinter : TypePrinter { public string IntPtrType => "__IntPtr"; public DriverOptions Options => Context.Options; public TypeMapDatabase TypeMapDatabase => Context.TypeMaps; public bool PrintModuleOutputNamespace = true; public CSharpTypePrinter() { } public CSharpTypePrinter(BindingContext context) { Context = context; } public string QualifiedType(string name) { return IsGlobalQualifiedScope ? $"global::{name}" : name; } public override TypePrinterResult VisitTagType(TagType tag, TypeQualifiers quals) { if (tag.Declaration == null) return string.Empty; TypeMap typeMap; if (TypeMapDatabase.FindTypeMap(tag, out typeMap)) { typeMap.Type = tag; var typePrinterContext = new TypePrinterContext() { Kind = ContextKind, MarshalKind = MarshalKind, Type = tag }; return typeMap.CSharpSignatureType(typePrinterContext).ToString(); } return base.VisitTagType(tag, quals); } public override TypePrinterResult VisitArrayType(ArrayType array, TypeQualifiers quals) { Type arrayType = array.Type.Desugar(); if ((MarshalKind == MarshalKind.NativeField || (ContextKind == TypePrinterContextKind.Native && MarshalKind == MarshalKind.ReturnVariableArray)) && array.SizeType == ArrayType.ArraySize.Constant) { if (array.Size == 0) { var pointer = new PointerType(array.QualifiedType); return pointer.Visit(this); } PrimitiveType primitiveType; if ((arrayType.IsPointerToPrimitiveType(out primitiveType) && !(arrayType is FunctionType)) || (arrayType.IsPrimitiveType() && MarshalKind != MarshalKind.NativeField)) { if (primitiveType == PrimitiveType.Void) return "void*"; return array.QualifiedType.Visit(this); } if (Parameter != null) return IntPtrType; Enumeration @enum; if (arrayType.TryGetEnum(out @enum)) { return new TypePrinterResult($"fixed {@enum.BuiltinType}", $"[{array.Size}]"); } if (arrayType.IsClass()) return new TypePrinterResult($"fixed byte", $"[{array.GetSizeInBytes()}]"); TypePrinterResult arrayElemType = array.QualifiedType.Visit(this); // C# does not support fixed arrays of machine pointer type (void* or IntPtr). // In that case, replace it by a pointer to an integer type of the same size. if (arrayElemType == IntPtrType) arrayElemType = Context.TargetInfo.PointerWidth == 64 ? "long" : "int"; // Do not write the fixed keyword multiple times for nested array types var fixedKeyword = arrayType is ArrayType ? string.Empty : "fixed "; return new TypePrinterResult(fixedKeyword + arrayElemType.Type, $"[{array.Size}]"); } // const char* and const char[] are the same so we can use a string if (array.SizeType == ArrayType.ArraySize.Incomplete && arrayType.IsPrimitiveType(PrimitiveType.Char) && array.QualifiedType.Qualifiers.IsConst) return "string"; if (arrayType.IsPointerToPrimitiveType(PrimitiveType.Char)) { var prefix = ContextKind == TypePrinterContextKind.Managed ? string.Empty : "[MarshalAs(UnmanagedType.LPArray)] "; return $"{prefix}string[]"; } var arraySuffix = array.SizeType != ArrayType.ArraySize.Constant && MarshalKind == MarshalKind.ReturnVariableArray ? (ContextKind == TypePrinterContextKind.Managed && arrayType.IsPrimitiveType() ? "*" : string.Empty) : "[]"; return $"{arrayType.Visit(this)}{arraySuffix}"; } public override TypePrinterResult VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals) { TypeMap typeMap; if (TypeMapDatabase.FindTypeMap(builtin, out typeMap)) { var typePrinterContext = new TypePrinterContext() { Kind = ContextKind, MarshalKind = MarshalKind, Type = builtin, Parameter = Parameter }; return typeMap.CSharpSignatureType(typePrinterContext).Visit(this); } return base.VisitBuiltinType(builtin, quals); } public override TypePrinterResult VisitFunctionType(FunctionType function, TypeQualifiers quals) => IntPtrType; private bool allowStrings = true; public override TypePrinterResult VisitPointerType(PointerType pointer, TypeQualifiers quals) { if (MarshalKind == MarshalKind.NativeField && !pointer.Pointee.IsEnumType()) return IntPtrType; if (pointer.Pointee is FunctionType) return pointer.Pointee.Visit(this, quals); var isManagedContext = ContextKind == TypePrinterContextKind.Managed; if (allowStrings && pointer.IsConstCharString()) { TypeMap typeMap; TypeMapDatabase.FindTypeMap(pointer, out typeMap); var typePrinterContext = new TypePrinterContext() { Kind = ContextKind, MarshalKind = MarshalKind, Type = pointer.Pointee, Parameter = Parameter }; return typeMap.CSharpSignatureType(typePrinterContext).Visit(this); } var pointee = pointer.Pointee.Desugar(); if (isManagedContext && new QualifiedType(pointer, quals).IsConstRefToPrimitive()) return pointee.Visit(this); // From http://msdn.microsoft.com/en-us/library/y31yhkeb.aspx // Any of the following types may be a pointer type: // * sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, // decimal, or bool. // * Any enum type. // * Any pointer type. // * Any user-defined struct type that contains fields of unmanaged types only. var finalPointee = (pointee.GetFinalPointee() ?? pointee).Desugar(); Enumeration @enum; if (finalPointee.IsPrimitiveType() || finalPointee.TryGetEnum(out @enum)) { // Skip one indirection if passed by reference bool isRefParam = Parameter != null && (Parameter.IsOut || Parameter.IsInOut); if (isManagedContext && isRefParam) return pointer.QualifiedPointee.Visit(this); if (pointee.IsPrimitiveType(PrimitiveType.Void)) return IntPtrType; if (pointee.IsConstCharString() && isRefParam) return IntPtrType + "*"; // Do not allow strings inside primitive arrays case, else we'll get invalid types // like string* for const char **. allowStrings = isRefParam; var result = pointer.QualifiedPointee.Visit(this); allowStrings = true; string @ref = Parameter != null && Parameter.IsIndirect ? string.Empty : "*"; return !isRefParam && result.Type == this.IntPtrType ? "void**" : result + @ref; } Class @class; if ((pointee.IsDependent || pointee.TryGetClass(out @class)) && ContextKind == TypePrinterContextKind.Native) { return IntPtrType; } return pointer.QualifiedPointee.Visit(this); } public override TypePrinterResult VisitMemberPointerType(MemberPointerType member, TypeQualifiers quals) { FunctionType functionType; if (member.IsPointerTo(out functionType)) return functionType.Visit(this, quals); // TODO: Non-function member pointer types are tricky to support. // Re-visit this. return IntPtrType; } public override TypePrinterResult VisitTypedefType(TypedefType typedef, TypeQualifiers quals) { var decl = typedef.Declaration; TypeMap typeMap; if (TypeMapDatabase.FindTypeMap(typedef, out typeMap)) { typeMap.Type = typedef; var typePrinterContext = new TypePrinterContext { Kind = ContextKind, MarshalKind = MarshalKind, Type = typedef, Parameter = Parameter }; return typeMap.CSharpSignatureType(typePrinterContext).ToString(); } FunctionType func; if (decl.Type.IsPointerTo(out func)) { if (MarshalKind == MarshalKind.GenericDelegate && ContextKind == TypePrinterContextKind.Native) return VisitDeclaration(decl); } func = decl.Type as FunctionType; if (func != null || decl.Type.IsPointerTo(out func)) { if (ContextKind == TypePrinterContextKind.Native) return IntPtrType; // TODO: Use SafeIdentifier() return VisitDeclaration(decl); } return decl.Type.Visit(this); } public override TypePrinterResult VisitTemplateSpecializationType( TemplateSpecializationType template, TypeQualifiers quals) { var decl = template.GetClassTemplateSpecialization() ?? template.Template.TemplatedDecl; TypeMap typeMap; if (!TypeMapDatabase.FindTypeMap(template, out typeMap)) { if (ContextKind == TypePrinterContextKind.Managed && decl == template.Template.TemplatedDecl && template.Arguments.All(IsValid)) { List<TemplateArgument> args = template.Arguments; var @class = (Class) template.Template.TemplatedDecl; TemplateArgument lastArg = args.Last(); TypePrinterResult typePrinterResult = VisitDeclaration(decl); typePrinterResult.NameSuffix.Append($@"<{string.Join(", ", args.Concat(Enumerable.Range(0, @class.TemplateParameters.Count - args.Count).Select( i => lastArg)).Select(this.VisitTemplateArgument))}>"); return typePrinterResult; } if (ContextKind == TypePrinterContextKind.Native) return template.Desugared.Visit(this); return decl.Visit(this); } typeMap.Type = template; var typePrinterContext = new TypePrinterContext { Type = template, Kind = ContextKind, MarshalKind = MarshalKind }; return typeMap.CSharpSignatureType(typePrinterContext).ToString(); } public override TypePrinterResult VisitDependentTemplateSpecializationType( DependentTemplateSpecializationType template, TypeQualifiers quals) { if (template.Desugared.Type != null) return template.Desugared.Visit(this); return string.Empty; } public override TypePrinterResult VisitTemplateParameterType( TemplateParameterType param, TypeQualifiers quals) { return param.Parameter.Name; } public override TypePrinterResult VisitTemplateParameterSubstitutionType( TemplateParameterSubstitutionType param, TypeQualifiers quals) { var type = param.Replacement.Type; return type.Visit(this, param.Replacement.Qualifiers); } public override TypePrinterResult VisitInjectedClassNameType( InjectedClassNameType injected, TypeQualifiers quals) { return injected.InjectedSpecializationType.Type != null ? injected.InjectedSpecializationType.Visit(this) : injected.Class.Visit(this); } public override TypePrinterResult VisitDependentNameType(DependentNameType dependent, TypeQualifiers quals) { if (dependent.Qualifier.Type == null) return dependent.Identifier; return $"{dependent.Qualifier.Visit(this)}.{dependent.Identifier}"; } public override TypePrinterResult VisitPackExpansionType(PackExpansionType type, TypeQualifiers quals) { return string.Empty; } public override TypePrinterResult VisitCILType(CILType type, TypeQualifiers quals) { switch (System.Type.GetTypeCode(type.Type)) { case TypeCode.Boolean: return "bool"; case TypeCode.Char: return "char"; case TypeCode.SByte: return "sbyte"; case TypeCode.Byte: return "byte"; case TypeCode.Int16: return "short"; case TypeCode.UInt16: return "ushort"; case TypeCode.Int32: return "int"; case TypeCode.UInt32: return "uint"; case TypeCode.Int64: return "long"; case TypeCode.UInt64: return "ulong"; case TypeCode.Single: return "float"; case TypeCode.Double: return "double"; case TypeCode.Decimal: return "decimal"; case TypeCode.String: return "string"; } return QualifiedType(type.Type.FullName); } public static void GetPrimitiveTypeWidth(PrimitiveType primitive, ParserTargetInfo targetInfo, out uint width, out bool signed) { width = primitive.GetInfo(targetInfo, out signed).Width; } static string GetIntString(PrimitiveType primitive, ParserTargetInfo targetInfo) { uint width; bool signed; GetPrimitiveTypeWidth(primitive, targetInfo, out width, out signed); switch (width) { case 8: return signed ? "sbyte" : "byte"; case 16: return signed ? "short" : "ushort"; case 32: return signed ? "int" : "uint"; case 64: return signed ? "long" : "ulong"; default: throw new NotImplementedException(); } } public override TypePrinterResult VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals) { switch (primitive) { case PrimitiveType.Bool: // returned structs must be blittable and bool isn't return MarshalKind == MarshalKind.NativeField ? "byte" : "bool"; case PrimitiveType.Void: return "void"; case PrimitiveType.Char16: case PrimitiveType.Char32: case PrimitiveType.WideChar: return "char"; case PrimitiveType.Char: // returned structs must be blittable and char isn't return Options.MarshalCharAsManagedChar && ContextKind != TypePrinterContextKind.Native ? "char" : "sbyte"; case PrimitiveType.SChar: return "sbyte"; case PrimitiveType.UChar: return "byte"; case PrimitiveType.Short: case PrimitiveType.UShort: case PrimitiveType.Int: case PrimitiveType.UInt: case PrimitiveType.Long: case PrimitiveType.ULong: case PrimitiveType.LongLong: case PrimitiveType.ULongLong: return GetIntString(primitive, Context.TargetInfo); case PrimitiveType.Int128: return new TypePrinterResult("fixed byte", "[16]"); // The type is always 128 bits wide case PrimitiveType.UInt128: return new TypePrinterResult("fixed byte", "[16]"); // The type is always 128 bits wide case PrimitiveType.Half: return new TypePrinterResult("fixed byte", $"[{Context.TargetInfo.HalfWidth}]"); case PrimitiveType.Float: return "float"; case PrimitiveType.Double: return "double"; case PrimitiveType.LongDouble: return new TypePrinterResult("fixed byte", $"[{Context.TargetInfo.LongDoubleWidth}]"); case PrimitiveType.IntPtr: return IntPtrType; case PrimitiveType.UIntPtr: return QualifiedType("System.UIntPtr"); case PrimitiveType.Null: return "void*"; case PrimitiveType.String: return "string"; case PrimitiveType.Float128: return "__float128"; } throw new NotSupportedException(); } public override TypePrinterResult VisitDeclaration(Declaration decl) { return GetName(decl); } public override TypePrinterResult VisitClassDecl(Class @class) { if (ContextKind == TypePrinterContextKind.Native) return $@"{VisitDeclaration(@class.OriginalClass ?? @class)}.{ Helpers.InternalStruct}{Helpers.GetSuffixForInternal(@class)}"; TypePrinterResult printed = VisitDeclaration(@class); if (@class.IsTemplate) printed.NameSuffix.Append($@"<{string.Join(", ", @class.TemplateParameters.Select(p => p.Name))}>"); return printed; } public override TypePrinterResult VisitClassTemplateSpecializationDecl( ClassTemplateSpecialization specialization) { TypePrinterResult typePrinterResult = VisitClassDecl(specialization); if (ContextKind != TypePrinterContextKind.Native) typePrinterResult.NameSuffix.Append($@"<{string.Join(", ", specialization.Arguments.Select(VisitTemplateArgument))}>"); return typePrinterResult; } public TypePrinterResult VisitTemplateArgument(TemplateArgument a) { if (a.Type.Type == null) return a.Integral.ToString(CultureInfo.InvariantCulture); var type = a.Type.Type; PrimitiveType pointee; if (type.IsPointerToPrimitiveType(out pointee) && !type.IsConstCharString()) { return $@"CppSharp.Runtime.Pointer<{(pointee == PrimitiveType.Void ? IntPtrType : VisitPrimitiveType(pointee, new TypeQualifiers()).Type)}>"; } return type.IsPrimitiveType(PrimitiveType.Void) ? new TypePrinterResult("object") : type.Visit(this); } public override TypePrinterResult VisitParameterDecl(Parameter parameter) { var paramType = parameter.Type; if (parameter.Kind == ParameterKind.IndirectReturnType) return IntPtrType; Parameter = parameter; var ret = paramType.Visit(this); Parameter = null; return ret; } string GetName(Declaration decl) { var names = new Stack<string>(); Declaration ctx; var specialization = decl as ClassTemplateSpecialization; if (specialization != null && ContextKind == TypePrinterContextKind.Native) { ctx = specialization.TemplatedDecl.TemplatedClass.Namespace; if (specialization.OriginalNamespace is Class && !(specialization.OriginalNamespace is ClassTemplateSpecialization)) { names.Push(string.Format("{0}_{1}", decl.OriginalNamespace.Name, decl.Name)); ctx = ctx.Namespace ?? ctx; } else { names.Push(decl.Name); } } else { names.Push(decl.Name); ctx = decl.Namespace; } if (decl is Variable && !(decl.Namespace is Class)) names.Push(decl.TranslationUnit.FileNameWithoutExtension); while (!(ctx is TranslationUnit)) { AddContextName(names, ctx); ctx = ctx.Namespace; } if (PrintModuleOutputNamespace) { var unit = ctx.TranslationUnit; if (!unit.IsSystemHeader && unit.IsValid && !string.IsNullOrWhiteSpace(unit.Module.OutputNamespace)) names.Push(unit.Module.OutputNamespace); } return QualifiedType(string.Join(".", names)); } public override TypePrinterResult VisitParameters(IEnumerable<Parameter> @params, bool hasNames) { @params = @params.Where( p => ContextKind == TypePrinterContextKind.Native || (p.Kind != ParameterKind.IndirectReturnType && !p.Ignore)); return base.VisitParameters(@params, hasNames); } public override TypePrinterResult VisitParameter(Parameter param, bool hasName) { var typeBuilder = new StringBuilder(); if (param.Type.Desugar().IsPrimitiveType(PrimitiveType.Bool) && MarshalKind == MarshalKind.GenericDelegate) typeBuilder.Append("[MarshalAs(UnmanagedType.I1)] "); var printedType = param.Type.Visit(this, param.QualifiedType.Qualifiers); typeBuilder.Append(printedType); var type = typeBuilder.ToString(); if (ContextKind == TypePrinterContextKind.Native) return $"{type} {param.Name}"; var extension = param.Kind == ParameterKind.Extension ? "this " : string.Empty; var usage = GetParameterUsage(param.Usage); if (param.DefaultArgument == null || !Options.GenerateDefaultValuesForArguments) return $"{extension}{usage}{type} {param.Name}"; var defaultValue = expressionPrinter.VisitParameter(param); return $"{extension}{usage}{type} {param.Name} = {defaultValue}"; } public override TypePrinterResult VisitDelegate(FunctionType function) { PushMarshalKind(MarshalKind.GenericDelegate); var functionRetType = function.ReturnType.Visit(this); var @params = VisitParameters(function.Parameters, hasNames: true); PopMarshalKind(); return $"delegate {functionRetType} {{0}}({@params})"; } public override string ToString(Type type) { return type.Visit(this).Type; } public override TypePrinterResult VisitTemplateTemplateParameterDecl( TemplateTemplateParameter templateTemplateParameter) { return templateTemplateParameter.Name; } public override TypePrinterResult VisitTemplateParameterDecl( TypeTemplateParameter templateParameter) { return templateParameter.Name; } public override TypePrinterResult VisitNonTypeTemplateParameterDecl( NonTypeTemplateParameter nonTypeTemplateParameter) { return nonTypeTemplateParameter.Name; } public override TypePrinterResult VisitUnaryTransformType( UnaryTransformType unaryTransformType, TypeQualifiers quals) { if (unaryTransformType.Desugared.Type != null) return unaryTransformType.Desugared.Visit(this); return unaryTransformType.BaseType.Visit(this); } public override TypePrinterResult VisitVectorType(VectorType vectorType, TypeQualifiers quals) { return vectorType.ElementType.Visit(this); } public override TypePrinterResult VisitUnsupportedType(UnsupportedType type, TypeQualifiers quals) { return type.Description; } private static string GetParameterUsage(ParameterUsage usage) { switch (usage) { case ParameterUsage.Out: return "out "; case ParameterUsage.InOut: return "ref "; default: return string.Empty; } } public override TypePrinterResult VisitFieldDecl(Field field) { PushMarshalKind(MarshalKind.NativeField); var fieldTypePrinted = field.QualifiedType.Visit(this); PopMarshalKind(); var returnTypePrinter = new TypePrinterResult(); returnTypePrinter.NameSuffix.Append(fieldTypePrinted.NameSuffix); returnTypePrinter.Type = $"{fieldTypePrinted.Type} {field.Name}"; return returnTypePrinter; } public TypePrinterResult PrintNative(Declaration declaration) { PushContext(TypePrinterContextKind.Native); var typePrinterResult = declaration.Visit(this); PopContext(); return typePrinterResult; } public TypePrinterResult PrintNative(Type type) { PushContext(TypePrinterContextKind.Native); var typePrinterResult = type.Visit(this); PopContext(); return typePrinterResult; } public TypePrinterResult PrintNative(QualifiedType type) { PushContext(TypePrinterContextKind.Native); var typePrinterResult = type.Visit(this); PopContext(); return typePrinterResult; } public static Type GetSignedType(uint width) { switch (width) { case 8: return new CILType(typeof(sbyte)); case 16: return new CILType(typeof(short)); case 32: return new CILType(typeof(int)); case 64: return new CILType(typeof(long)); default: throw new System.NotSupportedException(); } } public static Type GetUnsignedType(uint width) { switch (width) { case 8: return new CILType(typeof(byte)); case 16: return new CILType(typeof(ushort)); case 32: return new CILType(typeof(uint)); case 64: return new CILType(typeof(ulong)); default: throw new System.NotSupportedException(); } } private static bool IsValid(TemplateArgument a) { if (a.Type.Type == null) return true; var templateParam = a.Type.Type.Desugar() as TemplateParameterType; // HACK: TemplateParameterType.Parameter is null in some corner cases, see the parser return templateParam == null || templateParam.Parameter != null; } private void AddContextName(Stack<string> names, Declaration ctx) { var isInlineNamespace = ctx is Namespace && ((Namespace) ctx).IsInline; if (string.IsNullOrWhiteSpace(ctx.Name) || isInlineNamespace) return; if (ContextKind != TypePrinterContextKind.Managed) { names.Push(ctx.Name); return; } string name = null; var @class = ctx as Class; if (@class != null) { if (@class.IsTemplate) name = $@"{ctx.Name}<{string.Join(", ", @class.TemplateParameters.Select(p => p.Name))}>"; else { var specialization = @class as ClassTemplateSpecialization; if (specialization != null) { name = $@"{ctx.Name}<{string.Join(", ", specialization.Arguments.Select(VisitTemplateArgument))}>"; } } } names.Push(name ?? ctx.Name); } private CSharpExpressionPrinter expressionPrinter => new CSharpExpressionPrinter(this); } }
38.190955
135
0.552697
[ "MIT" ]
P-i-N/CppSharp
src/Generator/Generators/CSharp/CSharpTypePrinter.cs
30,402
C#
using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace VoiceTrigger { public class TriggerDispatcher : ITriggerDispatcher { private Dictionary<string, TriggerOption> triggers; private static string lastText = string.Empty; private static bool playing = false; private readonly IHubContext<VoiceTriggerHub> hubContext; private readonly ILogger<TriggerDispatcher> logger; public TriggerDispatcher(IOptions<Dictionary<string, TriggerOption>> options, IHubContext<VoiceTriggerHub> hubContext, ILogger<TriggerDispatcher> logger) { this.triggers = options.Value; this.hubContext = hubContext; this.logger = logger; } public async Task Dispatch(string text) { try { if (lastText != string.Empty) { text = text.Replace(lastText, string.Empty); } var trigger = triggers.SingleOrDefault(t => text.ToLower().Contains(t.Key.ToLower())); if (trigger.Value != null && !playing) { logger.LogDebug(trigger.Key); await hubContext.Clients.All.SendAsync("TriggerReceived", trigger.Key, trigger.Value); } lastText = text; } catch (Exception ex) { logger.LogError(ex, ex.Message); } } } }
31.698113
161
0.578571
[ "MIT" ]
faniereynders/VoiceTrigger
src/VoiceTrigger/TriggerDispatcher.cs
1,682
C#
using GizmoFort.Connector.ERPNext.PublicInterfaces; using GizmoFort.Connector.ERPNext.PublicInterfaces.SubServices; using GizmoFort.Connector.ERPNext.PublicTypes; namespace GizmoFort.Connector.ERPNext.ERPTypes.Quality_meeting_agenda { public class Quality_meeting_agendaService : SubServiceBase<ERPQuality_meeting_agenda> { public Quality_meeting_agendaService(ERPNextClient client) : base(DocType.Quality_meeting_agenda, client) { } protected override ERPQuality_meeting_agenda fromERPObject(ERPObject obj) { return new ERPQuality_meeting_agenda(obj); } } }
36.941176
90
0.770701
[ "MIT" ]
dmequus/gizmofort.connector.erpnext
Libs/GizmoFort.Connector.ERPNext/ERPTypes/Quality_meeting_agenda/Quality_meeting_agendaService.cs
628
C#
using System; using System.Collections.Generic; using System.Linq; namespace Eumel.Dj.Mobile.Data { public static class Randomized { private static readonly Random randomNumbers = new Random(DateTime.UtcNow.Millisecond); public static T Random<T>(this IEnumerable<T> source) { if (source == null) throw new ArgumentNullException(nameof(source)); var sourceArray = source as T[] ?? source.ToArray(); if (!sourceArray.Any()) throw new ArgumentOutOfRangeException(nameof(source), "source does not contain elements"); var index = randomNumbers.Next(0, sourceArray.Length); return sourceArray.Skip(index).First(); } public static string Random(this Type sourceStatus) { var sourceArray = Enum.GetNames(sourceStatus); if (!sourceArray.Any()) throw new ArgumentOutOfRangeException(nameof(sourceStatus), "source does not contain elements"); var index = randomNumbers.Next(0, sourceArray.Length); return sourceArray.Skip(index).First(); } } }
37.166667
132
0.655605
[ "MIT" ]
EUMEL-Suite/EUMEL.Dj
Eumel.Dj.Mobile/Data/Randomized.cs
1,117
C#
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Org.OpenAPITools.Model { /// <summary> /// /// </summary> [DataContract] public class Pipelines : List<Pipeline> { /// <summary> /// Get 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 Pipelines {\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public new string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
23.972973
68
0.651635
[ "MIT" ]
PankTrue/swaggy-jenkins
clients/csharp-dotnet2/generated/src/main/CsharpDotNet2/Org/OpenAPITools/Model/Pipelines.cs
887
C#
using Application.Common.Models; using Application.Users.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Application.Auth.Dtos { public class RegisterDto { public UserRegisterDto UserRegisterDto { get; set; } public string ClientUrl { get; set; } } }
19.315789
60
0.72752
[ "MIT" ]
BinaryStudioAcademy/bsa-2021-scout
backend/src/Application/Auth/Dtos/RegisterDto.cs
369
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace NewsFocusApp { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. [ServiceContract] public interface IService1 { [OperationContract] string GetData(int value); [OperationContract] CompositeType GetDataUsingDataContract(CompositeType composite); // TODO: Add your service operations here } // Use a data contract as illustrated in the sample below to add composite types to service operations. [DataContract] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } } }
24.75
148
0.639731
[ "MIT" ]
ivanmartinezmorales/cse-445-project-3
NewsFocusService/IService1.cs
1,190
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using Xunit; public class TupleTests { private class TupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> { private int _nItems; private readonly object Tuple; private readonly Tuple<T1> Tuple1; private readonly Tuple<T1, T2> Tuple2; private readonly Tuple<T1, T2, T3> Tuple3; private readonly Tuple<T1, T2, T3, T4> Tuple4; private readonly Tuple<T1, T2, T3, T4, T5> Tuple5; private readonly Tuple<T1, T2, T3, T4, T5, T6> Tuple6; private readonly Tuple<T1, T2, T3, T4, T5, T6, T7> Tuple7; private readonly Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Tuple8; private readonly Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> Tuple9; private readonly Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> Tuple10; internal TupleTestDriver(params object[] values) { if (values.Length == 0) throw new ArgumentOutOfRangeException("values", "You must provide at least one value"); _nItems = values.Length; switch (_nItems) { case 1: Tuple1 = new Tuple<T1>((T1)values[0]); Tuple = Tuple1; break; case 2: Tuple2 = new Tuple<T1, T2>((T1)values[0], (T2)values[1]); Tuple = Tuple2; break; case 3: Tuple3 = new Tuple<T1, T2, T3>((T1)values[0], (T2)values[1], (T3)values[2]); Tuple = Tuple3; break; case 4: Tuple4 = new Tuple<T1, T2, T3, T4>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3]); Tuple = Tuple4; break; case 5: Tuple5 = new Tuple<T1, T2, T3, T4, T5>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4]); Tuple = Tuple5; break; case 6: Tuple6 = new Tuple<T1, T2, T3, T4, T5, T6>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5]); Tuple = Tuple6; break; case 7: Tuple7 = new Tuple<T1, T2, T3, T4, T5, T6, T7>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6]); Tuple = Tuple7; break; case 8: Tuple8 = new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], new Tuple<T8>((T8)values[7])); Tuple = Tuple8; break; case 9: Tuple9 = new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], new Tuple<T8, T9>((T8)values[7], (T9)values[8])); Tuple = Tuple9; break; case 10: Tuple10 = new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], new Tuple<T8, T9, T10>((T8)values[7], (T9)values[8], (T10)values[9])); Tuple = Tuple10; break; default: Assert.True(false, "Must specify between 1 and 10 values (inclusive)."); break; } } private void VerifyItem(int itemPos, object Item1, object Item2) { if (!object.Equals(Item1, Item2)) { Assert.True(false, string.Format("Tuple{0}.{1} has unexpected value {2}, expected {3}", _nItems, itemPos, Item1.ToString(), Item2.ToString())); } } public void TestConstructor(params object[] expectedValue) { if (expectedValue.Length != _nItems) throw new ArgumentOutOfRangeException("expectedValues", "You must provide " + _nItems + " expectedvalues"); switch (_nItems) { case 1: VerifyItem(1, Tuple1.Item1, expectedValue[0]); break; case 2: VerifyItem(1, Tuple2.Item1, expectedValue[0]); VerifyItem(2, Tuple2.Item2, expectedValue[1]); break; case 3: VerifyItem(1, Tuple3.Item1, expectedValue[0]); VerifyItem(2, Tuple3.Item2, expectedValue[1]); VerifyItem(3, Tuple3.Item3, expectedValue[2]); break; case 4: VerifyItem(1, Tuple4.Item1, expectedValue[0]); VerifyItem(2, Tuple4.Item2, expectedValue[1]); VerifyItem(3, Tuple4.Item3, expectedValue[2]); VerifyItem(4, Tuple4.Item4, expectedValue[3]); break; case 5: VerifyItem(1, Tuple5.Item1, expectedValue[0]); VerifyItem(2, Tuple5.Item2, expectedValue[1]); VerifyItem(3, Tuple5.Item3, expectedValue[2]); VerifyItem(4, Tuple5.Item4, expectedValue[3]); VerifyItem(5, Tuple5.Item5, expectedValue[4]); break; case 6: VerifyItem(1, Tuple6.Item1, expectedValue[0]); VerifyItem(2, Tuple6.Item2, expectedValue[1]); VerifyItem(3, Tuple6.Item3, expectedValue[2]); VerifyItem(4, Tuple6.Item4, expectedValue[3]); VerifyItem(5, Tuple6.Item5, expectedValue[4]); VerifyItem(6, Tuple6.Item6, expectedValue[5]); break; case 7: VerifyItem(1, Tuple7.Item1, expectedValue[0]); VerifyItem(2, Tuple7.Item2, expectedValue[1]); VerifyItem(3, Tuple7.Item3, expectedValue[2]); VerifyItem(4, Tuple7.Item4, expectedValue[3]); VerifyItem(5, Tuple7.Item5, expectedValue[4]); VerifyItem(6, Tuple7.Item6, expectedValue[5]); VerifyItem(7, Tuple7.Item7, expectedValue[6]); break; case 8: // Extended Tuple VerifyItem(1, Tuple8.Item1, expectedValue[0]); VerifyItem(2, Tuple8.Item2, expectedValue[1]); VerifyItem(3, Tuple8.Item3, expectedValue[2]); VerifyItem(4, Tuple8.Item4, expectedValue[3]); VerifyItem(5, Tuple8.Item5, expectedValue[4]); VerifyItem(6, Tuple8.Item6, expectedValue[5]); VerifyItem(7, Tuple8.Item7, expectedValue[6]); VerifyItem(8, Tuple8.Rest.Item1, expectedValue[7]); break; case 9: // Extended Tuple VerifyItem(1, Tuple9.Item1, expectedValue[0]); VerifyItem(2, Tuple9.Item2, expectedValue[1]); VerifyItem(3, Tuple9.Item3, expectedValue[2]); VerifyItem(4, Tuple9.Item4, expectedValue[3]); VerifyItem(5, Tuple9.Item5, expectedValue[4]); VerifyItem(6, Tuple9.Item6, expectedValue[5]); VerifyItem(7, Tuple9.Item7, expectedValue[6]); VerifyItem(8, Tuple9.Rest.Item1, expectedValue[7]); VerifyItem(9, Tuple9.Rest.Item2, expectedValue[8]); break; case 10: // Extended Tuple VerifyItem(1, Tuple10.Item1, expectedValue[0]); VerifyItem(2, Tuple10.Item2, expectedValue[1]); VerifyItem(3, Tuple10.Item3, expectedValue[2]); VerifyItem(4, Tuple10.Item4, expectedValue[3]); VerifyItem(5, Tuple10.Item5, expectedValue[4]); VerifyItem(6, Tuple10.Item6, expectedValue[5]); VerifyItem(7, Tuple10.Item7, expectedValue[6]); VerifyItem(8, Tuple10.Rest.Item1, expectedValue[7]); VerifyItem(9, Tuple10.Rest.Item2, expectedValue[8]); VerifyItem(10, Tuple10.Rest.Item3, expectedValue[9]); break; default: Assert.True(false, "Must specify between 1 and 10 expected values (inclusive)."); break; } } public void TestToString(string expected) { Assert.Equal(expected, Tuple.ToString()); } public void TestEquals_GetHashCode(TupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, bool expectEqual, bool expectStructuallyEqual) { if (expectEqual) { Assert.True(Tuple.Equals(other.Tuple)); Assert.Equal(Tuple.GetHashCode(), other.Tuple.GetHashCode()); } if (expectStructuallyEqual) { var equatable = ((IStructuralEquatable)Tuple); var otherEquatable = ((IStructuralEquatable)other.Tuple); Assert.True(equatable.Equals(other.Tuple, TestEqualityComparer.Instance)); Assert.Equal(equatable.GetHashCode(TestEqualityComparer.Instance), otherEquatable.GetHashCode(TestEqualityComparer.Instance)); } Assert.False(Tuple.Equals(null)); } public void TestCompareTo(TupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, int expectedResult, int expectedStructuralResult) { Assert.Equal(expectedResult, ((IComparable)Tuple).CompareTo(other.Tuple)); Assert.Equal(expectedStructuralResult, ((IStructuralComparable)Tuple).CompareTo(other.Tuple, TestComparer.Instance)); Assert.Equal(1, ((IComparable)Tuple).CompareTo(null)); } public void TestNotEqual() { Tuple<Int32> tupleB = new Tuple<Int32>((Int32)10000); Assert.NotEqual(Tuple, tupleB); } internal void TestCompareToThrows() { Tuple<Int32> tupleB = new Tuple<Int32>((Int32)10000); Assert.Throws<ArgumentException>(() => ((IComparable)Tuple).CompareTo(tupleB)); } } [Fact] public static void TestConstructor() { TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan> tupleDriverA; //Tuple-1 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MaxValue); tupleDriverA.TestConstructor(Int16.MaxValue); //Tuple-2 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MinValue, Int32.MaxValue); tupleDriverA.TestConstructor(Int16.MinValue, Int32.MaxValue); //Tuple-3 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)0, (Int32)0, Int64.MaxValue); tupleDriverA.TestConstructor((Int16)0, (Int32)0, Int64.MaxValue); //Tuple-4 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)1, (Int32)1, Int64.MinValue, "This"); tupleDriverA.TestConstructor((Int16)1, (Int32)1, Int64.MinValue, "This"); //Tuple-5 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-1), (Int32)(-1), (Int64)0, "is", 'A'); tupleDriverA.TestConstructor((Int16)(-1), (Int32)(-1), (Int64)0, "is", 'A'); //Tuple-6 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10, (Int32)100, (Int64)1, "testing", 'Z', Single.MaxValue); tupleDriverA.TestConstructor((Int16)10, (Int32)100, (Int64)1, "testing", 'Z', Single.MaxValue); //Tuple-7 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-100), (Int32)(-1000), (Int64)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverA.TestConstructor((Int16)(-100), (Int32)(-1000), (Int64)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); Object myObj = new Object(); //Tuple-10 DateTime now = DateTime.Now; tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); tupleDriverA.TestConstructor((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); } [Fact] public static void TestToString() { TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan> tupleDriverA; //Tuple-1 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MaxValue); tupleDriverA.TestToString("(" + Int16.MaxValue + ")"); //Tuple-2 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MinValue, Int32.MaxValue); tupleDriverA.TestToString("(" + Int16.MinValue + ", " + Int32.MaxValue + ")"); //Tuple-3 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)0, (Int32)0, Int64.MaxValue); tupleDriverA.TestToString("(" + ((Int16)0) + ", " + ((Int32)0) + ", " + Int64.MaxValue + ")"); //Tuple-4 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)1, (Int32)1, Int64.MinValue, "This"); tupleDriverA.TestConstructor((Int16)1, (Int32)1, Int64.MinValue, "This"); tupleDriverA.TestToString("(" + ((Int16)1) + ", " + ((Int32)1) + ", " + Int64.MinValue + ", This)"); //Tuple-5 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-1), (Int32)(-1), (Int64)0, "is", 'A'); tupleDriverA.TestToString("(" + ((Int16)(-1)) + ", " + ((Int32)(-1)) + ", " + ((Int64)0) + ", is, A)"); //Tuple-6 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10, (Int32)100, (Int64)1, "testing", 'Z', Single.MaxValue); tupleDriverA.TestToString("(" + ((Int16)10) + ", " + ((Int32)100) + ", " + ((Int64)1) + ", testing, Z, " + Single.MaxValue + ")"); //Tuple-7 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-100), (Int32)(-1000), (Int64)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverA.TestToString("(" + ((Int16)(-100)) + ", " + ((Int32)(-1000)) + ", " + ((Int64)(-1)) + ", Tuples, , " + Single.MinValue + ", " + Double.MaxValue + ")"); Object myObj = new Object(); //Tuple-10 DateTime now = DateTime.Now; tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); // .NET Native bug 438149 - object.ToString in incorrect tupleDriverA.TestToString("(" + ((Int16)10000) + ", " + ((Int32)1000000) + ", " + ((Int64)10000000) + ", 2008年7月2日, 0, " + ((Single)0.0001) + ", " + ((Double)0.0000001) + ", " + now + ", (False, System.Object), " + TimeSpan.Zero + ")"); } [Fact] public static void TestEquals_GetHashCode() { TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan> tupleDriverA, tupleDriverB, tupleDriverC; //Tuple-1 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MaxValue); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MaxValue); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MinValue); tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true); tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false); //Tuple-2 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MinValue, Int32.MaxValue); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MinValue, Int32.MaxValue); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MinValue, Int32.MinValue); tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true); tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false); //Tuple-3 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)0, (Int32)0, Int64.MaxValue); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)0, (Int32)0, Int64.MaxValue); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-1), (Int32)(-1), Int64.MinValue); tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true); tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false); //Tuple-4 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)1, (Int32)1, Int64.MinValue, "This"); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)1, (Int32)1, Int64.MinValue, "This"); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)1, (Int32)1, Int64.MinValue, "this"); tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true); tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false); //Tuple-5 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-1), (Int32)(-1), (Int64)0, "is", 'A'); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-1), (Int32)(-1), (Int64)0, "is", 'A'); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)0, (Int32)0, (Int64)1, "IS", 'a'); tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true); tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false); //Tuple-6 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10, (Int32)100, (Int64)1, "testing", 'Z', Single.MaxValue); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10, (Int32)100, (Int64)1, "testing", 'Z', Single.MaxValue); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10, (Int32)100, (Int64)1, "testing", 'Z', Single.MinValue); tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true); tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false); //Tuple-7 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-100), (Int32)(-1000), (Int64)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-100), (Int32)(-1000), (Int64)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-101), (Int32)(-1001), (Int64)(-2), "tuples", ' ', Single.MinValue, (Double)0.0); tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true); tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false); Object myObj = new Object(); //Tuple-10 DateTime now = DateTime.Now; tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10001, (Int32)1000001, (Int64)10000001, "2008年7月3日", '1', (Single)0.0002, (Double)0.0000002, now.AddMilliseconds(1), Tuple.Create(true, myObj), TimeSpan.MaxValue); tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true); tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false); } [Fact] [ActiveIssue(846, PlatformID.AnyUnix)] public static void TestCompareTo() { TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan> tupleDriverA, tupleDriverB, tupleDriverC; //Tuple-1 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MaxValue); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MaxValue); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MinValue); tupleDriverA.TestCompareTo(tupleDriverB, 0, 5); tupleDriverA.TestCompareTo(tupleDriverC, 65535, 5); //Tuple-2 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MinValue, Int32.MaxValue); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MinValue, Int32.MaxValue); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>(Int16.MinValue, Int32.MinValue); tupleDriverA.TestCompareTo(tupleDriverB, 0, 5); tupleDriverA.TestCompareTo(tupleDriverC, 1, 5); //Tuple-3 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)0, (Int32)0, Int64.MaxValue); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)0, (Int32)0, Int64.MaxValue); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-1), (Int32)(-1), Int64.MinValue); tupleDriverA.TestCompareTo(tupleDriverB, 0, 5); tupleDriverA.TestCompareTo(tupleDriverC, 1, 5); //Tuple-4 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)1, (Int32)1, Int64.MinValue, "This"); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)1, (Int32)1, Int64.MinValue, "This"); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)1, (Int32)1, Int64.MinValue, "this"); tupleDriverA.TestCompareTo(tupleDriverB, 0, 5); tupleDriverA.TestCompareTo(tupleDriverC, 1, 5); //Tuple-5 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-1), (Int32)(-1), (Int64)0, "is", 'A'); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-1), (Int32)(-1), (Int64)0, "is", 'A'); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)0, (Int32)0, (Int64)1, "IS", 'a'); tupleDriverA.TestCompareTo(tupleDriverB, 0, 5); tupleDriverA.TestCompareTo(tupleDriverC, -1, 5); //Tuple-6 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10, (Int32)100, (Int64)1, "testing", 'Z', Single.MaxValue); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10, (Int32)100, (Int64)1, "testing", 'Z', Single.MaxValue); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10, (Int32)100, (Int64)1, "testing", 'Z', Single.MinValue); tupleDriverA.TestCompareTo(tupleDriverB, 0, 5); tupleDriverA.TestCompareTo(tupleDriverC, 1, 5); //Tuple-7 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-100), (Int32)(-1000), (Int64)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-100), (Int32)(-1000), (Int64)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)(-101), (Int32)(-1001), (Int64)(-2), "tuples", ' ', Single.MinValue, (Double)0.0); tupleDriverA.TestCompareTo(tupleDriverB, 0, 5); tupleDriverA.TestCompareTo(tupleDriverC, 1, 5); Object myObj = new Object(); //Tuple-10 DateTime now = DateTime.Now; tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); tupleDriverB = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); tupleDriverC = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Tuple<Boolean, Object>, TimeSpan>((Int16)10001, (Int32)1000001, (Int64)10000001, "2008年7月3日", '1', (Single)0.0002, (Double)0.0000002, now.AddMilliseconds(1), Tuple.Create(true, myObj), TimeSpan.MaxValue); tupleDriverA.TestCompareTo(tupleDriverB, 0, 5); tupleDriverA.TestCompareTo(tupleDriverC, -1, 5); } [Fact] public static void TestNotEqual() { TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan> tupleDriverA; //Tuple-1 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000); tupleDriverA.TestNotEqual(); // This is for code coverage purposes //Tuple-2 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000); tupleDriverA.TestNotEqual(); //Tuple-3 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000); tupleDriverA.TestNotEqual(); //Tuple-4 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日"); tupleDriverA.TestNotEqual(); //Tuple-5 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0'); tupleDriverA.TestNotEqual(); //Tuple-6 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', Single.NaN); tupleDriverA.TestNotEqual(); //Tuple-7 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', Single.NaN, Double.NegativeInfinity); tupleDriverA.TestNotEqual(); //Tuple-8, extended tuple tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', Single.NaN, Double.NegativeInfinity, DateTime.Now); tupleDriverA.TestNotEqual(); //Tuple-9 and Tuple-10 are not necesary because they use the same code path as Tuple-8 } [Fact] public static void IncomparableTypes() { TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan> tupleDriverA; //Tuple-1 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000); tupleDriverA.TestCompareToThrows(); // This is for code coverage purposes //Tuple-2 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000); tupleDriverA.TestCompareToThrows(); //Tuple-3 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000); tupleDriverA.TestCompareToThrows(); //Tuple-4 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日"); tupleDriverA.TestCompareToThrows(); //Tuple-5 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0'); tupleDriverA.TestCompareToThrows(); //Tuple-6 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', Single.NaN); tupleDriverA.TestCompareToThrows(); //Tuple-7 tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', Single.NaN, Double.NegativeInfinity); tupleDriverA.TestCompareToThrows(); //Tuple-8, extended tuple tupleDriverA = new TupleTestDriver<Int16, Int32, Int64, String, Char, Single, Double, DateTime, Boolean, TimeSpan>((Int16)10000, (Int32)1000000, (Int64)10000000, "2008年7月2日", '0', Single.NaN, Double.NegativeInfinity, DateTime.Now); tupleDriverA.TestCompareToThrows(); //Tuple-9 and Tuple-10 are not necesary because they use the same code path as Tuple-8 } [Fact] public static void FloatingPointNaNCases() { var a = Tuple.Create(Double.MinValue, Double.NaN, Single.MinValue, Single.NaN); var b = Tuple.Create(Double.MinValue, Double.NaN, Single.MinValue, Single.NaN); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void TestCustomTypeParameter1() { // Special case of Tuple<T1> where T1 is a custom type var testClass = new TestClass(); var a = Tuple.Create(testClass); var b = Tuple.Create(testClass); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void TestCustomTypeParameter2() { // Special case of Tuple<T1, T2> where T2 is a custom type var testClass = new TestClass(1); var a = Tuple.Create(1, testClass); var b = Tuple.Create(1, testClass); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void TestCustomTypeParameter3() { // Special case of Tuple<T1, T2> where T1 and T2 are custom types var testClassA = new TestClass(100); var testClassB = new TestClass(101); var a = Tuple.Create(testClassA, testClassB); var b = Tuple.Create(testClassB, testClassA); Assert.False(a.Equals(b)); Assert.Equal(-1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); // Equals(IEqualityComparer) is false, ignore hash code } [Fact] public static void TestCustomTypeParameter4() { // Special case of Tuple<T1, T2> where T1 and T2 are custom types var testClassA = new TestClass(100); var testClassB = new TestClass(101); var a = Tuple.Create(testClassA, testClassB); var b = Tuple.Create(testClassA, testClassA); Assert.False(a.Equals(b)); Assert.Equal(1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); // Equals(IEqualityComparer) is false, ignore hash code } [Fact] public static void NestedTuples1() { var a = Tuple.Create(1, 2, Tuple.Create(31, 32), 4, 5, 6, 7, Tuple.Create(8, 9)); var b = Tuple.Create(1, 2, Tuple.Create(31, 32), 4, 5, 6, 7, Tuple.Create(8, 9)); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); Assert.Equal("(1, 2, (31, 32), 4, 5, 6, 7, (8, 9))", a.ToString()); Assert.Equal("(31, 32)", a.Item3.ToString()); Assert.Equal("((8, 9))", a.Rest.ToString()); } [Fact] public static void NestedTuples2() { var a = Tuple.Create(0, 1, 2, 3, 4, 5, 6, Tuple.Create(7, 8, 9, 10, 11, 12, 13, Tuple.Create(14, 15))); var b = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16))); Assert.False(a.Equals(b)); Assert.Equal(-1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal("(0, 1, 2, 3, 4, 5, 6, (7, 8, 9, 10, 11, 12, 13, (14, 15)))", a.ToString()); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, (8, 9, 10, 11, 12, 13, 14, (15, 16)))", b.ToString()); Assert.Equal("((7, 8, 9, 10, 11, 12, 13, (14, 15)))", a.Rest.ToString()); } [Fact] public static void IncomparableTypesSpecialCase() { // Special case when T does not implement IComparable var testClassA = new TestClass2(100); var testClassB = new TestClass2(100); var a = Tuple.Create(testClassA); var b = Tuple.Create(testClassB); Assert.True(a.Equals(b)); Assert.Throws<ArgumentException>(() => ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); Assert.Equal("([100])", a.ToString()); } private class TestClass : IComparable { private readonly int _value; internal TestClass() : this(0) { } internal TestClass(int value) { this._value = value; } public override string ToString() { return "{" + _value.ToString() + "}"; } public int CompareTo(object x) { TestClass tmp = x as TestClass; if (tmp != null) return this._value.CompareTo(tmp._value); else return 1; } } private class TestClass2 { private readonly int _value; internal TestClass2() : this(0) { } internal TestClass2(int value) { this._value = value; } public override string ToString() { return "[" + _value.ToString() + "]"; } public override bool Equals(object x) { TestClass2 tmp = x as TestClass2; if (tmp != null) return _value.Equals(tmp._value); else return false; } public override int GetHashCode() { return _value.GetHashCode(); } } private class TestComparer : IComparer { public static readonly TestComparer Instance = new TestComparer(); public int Compare(object x, object y) { return 5; } } private class TestEqualityComparer : IEqualityComparer { public static readonly TestEqualityComparer Instance = new TestEqualityComparer(); public new bool Equals(object x, object y) { return x.Equals(y); } public int GetHashCode(object x) { return x.GetHashCode(); } } }
60.517143
308
0.623176
[ "MIT" ]
bpschoch/corefx
src/System.Runtime/tests/System/Tuple.cs
42,482
C#
using Avalonia; namespace NP.Demos.Brushes { class Program { // Initialization code. Don't use any Avalonia, third-party APIs or any // SynchronizationContext-reliant code before AppMain is called: things aren't initialized // yet and stuff might break. public static void Main(string[] args) => BuildAvaloniaApp() .StartWithClassicDesktopLifetime(args); // Avalonia configuration, don't remove; also used by visual designer. public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<App>() .UsePlatformDetect() .LogToTrace(); } }
32.95
98
0.641882
[ "MIT" ]
npolyak/NP.CodeForAvaloniaInEasySampleArticle
NP.Demos.Brushes/Program.cs
659
C#
// <copyright file="VariableRepository.cs" company="Peter Ibbotson"> // (C) Copyright 2017 Peter Ibbotson // </copyright> namespace ClassicBasic.Interpreter { using System.Collections.Generic; using System.Linq; /// <summary> /// Repository of variables. /// </summary> public class VariableRepository : IVariableRepository { private readonly Dictionary<string, Variable> _variables = new Dictionary<string, Variable>(); /// <summary> /// Clears the repository. /// </summary> public void Clear() { _variables.Clear(); } /// <summary> /// Creates an array variable. /// </summary> /// <param name="name">Name of the variable (without array brackets).</param> /// <param name="dimensions">Dimensions to create array with.</param> public void DimensionArray(string name, short[] dimensions) { var nameKey = ShortenName(name) + "("; if (_variables.ContainsKey(nameKey)) { throw new Exceptions.RedimensionedArrayException(); } var variable = new Variable(name, dimensions); _variables.Add(variable.Name, variable); } /// <summary> /// Gets a reference to a variable using the indexes if the variable is an array. /// If the varible is unknown, the variable is created, arrays are created /// with dimensions of ten. Arrays variables have an index range starting of /// 0 .. size inclusive i.e. an default array has 11 elements. /// </summary> /// <param name="name">Name of the variable (without array brackets).</param> /// <param name="indexes">Indexes to use if the variable is an array.</param> /// <returns>Reference to variable.</returns> public VariableReference GetOrCreateVariable(string name, short[] indexes) { var nameKey = ShortenName(name); if (!_variables.TryGetValue(nameKey + ((indexes.Length == 0) ? string.Empty : "("), out Variable variable)) { if (indexes.Length == 0) { variable = new Variable(nameKey, indexes); } else { var dimensions = Enumerable.Repeat<short>(10, indexes.Length).ToArray(); variable = new Variable(nameKey, dimensions); } _variables.Add(variable.Name, variable); } return new VariableReference(variable, indexes); } /// <summary> /// Shortens a name to two characters plus optional type character. /// </summary> /// <param name="name">Name of the variable.</param> /// <returns>Shorten version of the variable.</returns> private string ShortenName(string name) { string nameKey = name; if (name.Length > 2) { nameKey = name.Substring(0, 2); var lastChar = name[name.Length - 1]; if ((lastChar == '$') || (lastChar == '%')) { nameKey += lastChar; } } return nameKey; } } }
34.329897
119
0.543243
[ "MIT" ]
Thraka/ClassicBasic
ClassicBasic.Interpreter/VariableRepository.cs
3,332
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Terraria.Graphics; using Terraria.Localization; using Terraria.UI; using Terraria.WorldBuilding; namespace Terraria.ModLoader { /// <summary> /// This is where all <see cref="ModSystem"/> hooks are gathered and called. /// </summary> public static partial class SystemLoader { internal static readonly List<ModSystem> Systems = new List<ModSystem>(); internal static ModSystem[] NetSystems { get; private set; } internal static void Add(ModSystem modSystem) => Systems.Add(modSystem); internal static void Unload() => Systems.Clear(); internal static void ResizeArrays() { NetSystems = ModLoader.BuildGlobalHook<ModSystem, Action<BinaryWriter>>(Systems, s => s.NetSend); RebuildHooks(); } internal static void WriteNetSystemOrder(BinaryWriter w) { w.Write((short)NetSystems.Length); foreach (var netWorld in NetSystems) { w.Write(netWorld.Mod.netID); w.Write(netWorld.Name); } } internal static void ReadNetSystemOrder(BinaryReader r) { short n = r.ReadInt16(); NetSystems = new ModSystem[n]; for (short i = 0; i < n; i++) { NetSystems[i] = ModContent.Find<ModSystem>(ModNet.GetMod(r.ReadInt16()).Name, r.ReadString()); } } internal static void OnModLoad(Mod mod) { foreach (var system in Systems.Where(s => s.Mod == mod)) { system.OnModLoad(); } } internal static void PostSetupContent(Mod mod) { foreach (var system in Systems.Where(s => s.Mod == mod)) { system.PostSetupContent(); } } public static void OnWorldLoad() { foreach (var system in HookOnWorldLoad.arr) { system.OnWorldLoad(); } } public static void OnWorldUnload() { foreach (var system in HookOnWorldUnload.arr) { system.OnWorldUnload(); } } public static void ModifyScreenPosition() { foreach (var system in HookModifyScreenPosition.arr) { system.ModifyScreenPosition(); } } public static void ModifyTransformMatrix(ref SpriteViewMatrix Transform) { foreach (var system in HookModifyTransformMatrix.arr) { system.ModifyTransformMatrix(ref Transform); } } public static void ModifySunLightColor(ref Color tileColor, ref Color backgroundColor) { if (Main.gameMenu) return; foreach (var system in HookModifySunLightColor.arr) { system.ModifySunLightColor(ref tileColor, ref backgroundColor); } } public static void ModifyLightingBrightness(ref float negLight, ref float negLight2) { float scale = 1f; foreach (var system in HookModifyLightingBrightness.arr) { system.ModifyLightingBrightness(ref scale); } if (Lighting.NotRetro) { negLight *= scale; negLight2 *= scale; } else { negLight -= (scale - 1f) / 2.307692307692308f; negLight2 -= (scale - 1f) / 0.75f; } negLight = Math.Max(negLight, 0.001f); negLight2 = Math.Max(negLight2, 0.001f); } public static void PostDrawFullscreenMap(ref string mouseText) { foreach (var system in HookPostDrawFullscreenMap.arr) { system.PostDrawFullscreenMap(ref mouseText); } } public static void UpdateUI(GameTime gameTime) { if (Main.gameMenu) return; foreach (var system in HookUpdateUI.arr) { system.UpdateUI(gameTime); } } public static void PreUpdateEntities() { foreach (var system in HookPreUpdateEntities.arr) { system.PreUpdateEntities(); } } public static void PreUpdatePlayers() { foreach (var system in HookPreUpdatePlayers.arr) { system.PreUpdatePlayers(); } } public static void PostUpdatePlayers() { foreach (var system in HookPostUpdatePlayers.arr) { system.PostUpdatePlayers(); } } public static void PreUpdateNPCs() { foreach (var system in HookPreUpdateNPCs.arr) { system.PreUpdateNPCs(); } } public static void PostUpdateNPCs() { foreach (var system in HookPostUpdateNPCs.arr) { system.PostUpdateNPCs(); } } public static void PreUpdateGores() { foreach (var system in HookPreUpdateGores.arr) { system.PreUpdateGores(); } } public static void PostUpdateGores() { foreach (var system in HookPostUpdateGores.arr) { system.PostUpdateGores(); } } public static void PreUpdateProjectiles() { foreach (var system in HookPreUpdateProjectiles.arr) { system.PreUpdateProjectiles(); } } public static void PostUpdateProjectiles() { foreach (var system in HookPostUpdateProjectiles.arr) { system.PostUpdateProjectiles(); } } public static void PreUpdateItems() { foreach (var system in HookPreUpdateItems.arr) { system.PreUpdateItems(); } } public static void PostUpdateItems() { foreach (var system in HookPostUpdateItems.arr) { system.PostUpdateItems(); } } public static void PreUpdateDusts() { foreach (var system in HookPreUpdateDusts.arr) { system.PreUpdateDusts(); } } public static void PostUpdateDusts() { foreach (var system in HookPostUpdateDusts.arr) { system.PostUpdateDusts(); } } public static void PreUpdateTime() { foreach (var system in HookPreUpdateTime.arr) { system.PreUpdateTime(); } } public static void PostUpdateTime() { foreach (var system in HookPostUpdateTime.arr) { system.PostUpdateTime(); } } public static void PreUpdateWorld() { foreach (var system in HookPreUpdateWorld.arr) { system.PreUpdateWorld(); } } public static void PostUpdateWorld() { foreach (var system in HookPostUpdateWorld.arr) { system.PostUpdateWorld(); } } public static void PreUpdateInvasions() { foreach (var system in HookPreUpdateInvasions.arr) { system.PreUpdateInvasions(); } } public static void PostUpdateInvasions() { foreach (var system in HookPostUpdateInvasions.arr) { system.PostUpdateInvasions(); } } public static void PostUpdateEverything() { foreach (var system in HookPostUpdateEverything.arr) { system.PostUpdateEverything(); } } public static void ModifyInterfaceLayers(List<GameInterfaceLayer> layers) { foreach (GameInterfaceLayer layer in layers) { layer.Active = true; } foreach (var system in HookModifyInterfaceLayers.arr) { system.ModifyInterfaceLayers(layers); } } public static void PostDrawInterface(SpriteBatch spriteBatch) { foreach (var system in HookPostDrawInterface.arr) { system.PostDrawInterface(spriteBatch); } } public static void PostUpdateInput() { foreach (var system in HookPostUpdateInput.arr) { system.PostUpdateInput(); } } public static void PreSaveAndQuit() { foreach (var system in HookPreSaveAndQuit.arr) { system.PreSaveAndQuit(); } } public static void PostDrawTiles() { foreach (var system in HookPostDrawTiles.arr) { system.PostDrawTiles(); } } public static void ModifyTimeRate(ref double timeRate, ref double tileUpdateRate, ref double eventUpdateRate) { foreach (var system in HookModifyTimeRate.arr) { system.ModifyTimeRate(ref timeRate, ref tileUpdateRate, ref eventUpdateRate); } } public static void PreWorldGen() { foreach (var system in HookPreWorldGen.arr) { system.PreWorldGen(); } } public static void ModifyWorldGenTasks(List<GenPass> passes, ref float totalWeight) { foreach (var system in HookModifyWorldGenTasks.arr) { system.ModifyWorldGenTasks(passes, ref totalWeight); } } public static void PostWorldGen() { foreach (var system in HookPostWorldGen.arr) { system.PostWorldGen(); } } public static void ResetNearbyTileEffects() { foreach (var system in HookResetNearbyTileEffects.arr) { system.ResetNearbyTileEffects(); } } public static void TileCountsAvailable(ReadOnlySpan<int> tileCounts) { foreach (var system in HookTileCountsAvailable.arr) { system.TileCountsAvailable(tileCounts); } } public static void ModifyHardmodeTasks(List<GenPass> passes) { foreach (var system in HookModifyHardmodeTasks.arr) { system.ModifyHardmodeTasks(passes); } } internal static bool HijackGetData(ref byte messageType, ref BinaryReader reader, int playerNumber) { bool hijacked = false; long readerPos = reader.BaseStream.Position; long biggestReaderPos = readerPos; foreach (var system in HookHijackGetData.arr) { if (system.HijackGetData(ref messageType, ref reader, playerNumber)) { hijacked = true; biggestReaderPos = Math.Max(reader.BaseStream.Position, biggestReaderPos); } reader.BaseStream.Position = readerPos; } if (hijacked) { reader.BaseStream.Position = biggestReaderPos; } return hijacked; } internal static bool HijackSendData(int whoAmI, int msgType, int remoteClient, int ignoreClient, NetworkText text, int number, float number2, float number3, float number4, int number5, int number6, int number7) { bool result = false; foreach (var system in HookHijackSendData.arr) { result |= system.HijackSendData(whoAmI, msgType, remoteClient, ignoreClient, text, number, number2, number3, number4, number5, number6, number7); } return result; } } }
25.763231
214
0.70786
[ "MIT" ]
chi-rei-den/tModLoader
patches/tModLoader/Terraria/ModLoader/SystemLoader.cs
9,251
C#
using System; using System.Threading; using System.Threading.Tasks; using Ctf4e.Server.Data; using Ctf4e.Server.Data.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; namespace Ctf4e.Server.Services { public interface IConfigurationService { Task<int> GetFlagMinimumPointsDivisorAsync(CancellationToken cancellationToken = default); Task SetFlagMinimumPointsDivisorAsync(int value, CancellationToken cancellationToken = default); Task<int> GetFlagHalfPointsSubmissionCountAsync(CancellationToken cancellationToken = default); Task SetFlagHalfPointsSubmissionCountAsync(int value, CancellationToken cancellationToken = default); Task<int> GetScoreboardEntryCountAsync(CancellationToken cancellationToken = default); Task SetScoreboardEntryCountAsync(int value, CancellationToken cancellationToken = default); Task<int> GetScoreboardCachedSecondsAsync(CancellationToken cancellationToken = default); Task<bool> GetPassAsGroupAsync(CancellationToken cancellationToken = default); Task SetPassAsGroupAsync(bool value, CancellationToken cancellationToken = default); Task SetScoreboardCachedSecondsAsync(int value, CancellationToken cancellationToken = default); Task<string> GetNavbarTitleAsync(CancellationToken cancellationToken = default); Task SetNavbarTitleAsync(string value, CancellationToken cancellationToken = default); Task<string> GetPageTitleAsync(CancellationToken cancellationToken = default); Task SetPageTitleAsync(string value, CancellationToken cancellationToken = default); Task SetGroupSizeMinAsync(int value, CancellationToken cancellationToken = default); Task<int> GetGroupSizeMinAsync(CancellationToken cancellationToken = default); Task SetGroupSizeMaxAsync(int value, CancellationToken cancellationToken = default); Task<int> GetGroupSizeMaxAsync(CancellationToken cancellationToken = default); Task<string> GetGroupSelectionPageTextAsync(CancellationToken cancellationToken = default); Task SetGroupSelectionPageTextAsync(string value, CancellationToken cancellationToken = default); } public class ConfigurationService : IConfigurationService { private readonly CtfDbContext _dbContext; private readonly IMemoryCache _cache; private const string ConfigKeyFlagMinimumPointsDivisor = "FlagMinimumPointsDivisor"; private const string ConfigKeyFlagHalfPointsSubmissionCount = "FlagHalfPointsSubmissionCount"; private const string ConfigKeyScoreboardEntryCount = "ScoreboardEntryCount"; private const string ConfigKeyScoreboardCachedSeconds = "ScoreboardCachedSeconds"; private const string ConfigKeyPassAsGroup = "PassAsGroup"; private const string ConfigKeyNavbarTitle = "NavbarTitle"; private const string ConfigKeyPageTitle = "PageTitle"; private const string ConfigKeyGroupSizeMin = "GroupSizeMin"; private const string ConfigKeyGroupSizeMax = "GroupSizeMax"; private const string ConfigKeyGroupSelectionPageText = "GroupSelectionPageText"; public ConfigurationService(CtfDbContext dbContext, IMemoryCache cache) { _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); _cache = cache ?? throw new ArgumentNullException(nameof(cache)); } public Task<int> GetFlagMinimumPointsDivisorAsync(CancellationToken cancellationToken = default) => GetConfigItemAsync(ConfigKeyFlagMinimumPointsDivisor, s => s == null ? 1 : int.Parse(s), cancellationToken); public Task SetFlagMinimumPointsDivisorAsync(int value, CancellationToken cancellationToken = default) => AddOrUpdateConfigItem(ConfigKeyFlagMinimumPointsDivisor, value, cancellationToken); public Task<int> GetFlagHalfPointsSubmissionCountAsync(CancellationToken cancellationToken = default) => GetConfigItemAsync(ConfigKeyFlagHalfPointsSubmissionCount, s => s == null ? 1 : int.Parse(s), cancellationToken); public Task SetFlagHalfPointsSubmissionCountAsync(int value, CancellationToken cancellationToken = default) => AddOrUpdateConfigItem(ConfigKeyFlagHalfPointsSubmissionCount, value, cancellationToken); public Task<int> GetScoreboardEntryCountAsync(CancellationToken cancellationToken = default) => GetConfigItemAsync(ConfigKeyScoreboardEntryCount, s => s == null ? 3 : int.Parse(s), cancellationToken); public Task SetScoreboardEntryCountAsync(int value, CancellationToken cancellationToken = default) => AddOrUpdateConfigItem(ConfigKeyScoreboardEntryCount, value, cancellationToken); public Task<int> GetScoreboardCachedSecondsAsync(CancellationToken cancellationToken = default) => GetConfigItemAsync(ConfigKeyScoreboardCachedSeconds, s => s == null ? 10 : int.Parse(s), cancellationToken); public Task<bool> GetPassAsGroupAsync(CancellationToken cancellationToken = default) => GetConfigItemAsync(ConfigKeyPassAsGroup, s => s != null && bool.Parse(s), cancellationToken); public Task SetPassAsGroupAsync(bool value, CancellationToken cancellationToken = default) => AddOrUpdateConfigItem(ConfigKeyPassAsGroup, value, cancellationToken); public Task SetScoreboardCachedSecondsAsync(int value, CancellationToken cancellationToken = default) => AddOrUpdateConfigItem(ConfigKeyScoreboardCachedSeconds, value, cancellationToken); public Task<string> GetNavbarTitleAsync(CancellationToken cancellationToken = default) => GetConfigItemAsync(ConfigKeyNavbarTitle, s => s ?? "CTF4E", cancellationToken); public Task SetNavbarTitleAsync(string value, CancellationToken cancellationToken = default) => AddOrUpdateConfigItem(ConfigKeyNavbarTitle, value, cancellationToken); public Task<string> GetPageTitleAsync(CancellationToken cancellationToken = default) => GetConfigItemAsync(ConfigKeyPageTitle, s => s ?? "CTF4E", cancellationToken); public Task SetPageTitleAsync(string value, CancellationToken cancellationToken = default) => AddOrUpdateConfigItem(ConfigKeyPageTitle, value, cancellationToken); public Task SetGroupSizeMinAsync(int value, CancellationToken cancellationToken = default) => AddOrUpdateConfigItem(ConfigKeyGroupSizeMin, value, cancellationToken); public Task<int> GetGroupSizeMinAsync(CancellationToken cancellationToken = default) => GetConfigItemAsync(ConfigKeyGroupSizeMin, s => s == null ? 1 : int.Parse(s), cancellationToken); public Task SetGroupSizeMaxAsync(int value, CancellationToken cancellationToken = default) => AddOrUpdateConfigItem(ConfigKeyGroupSizeMax, value, cancellationToken); public Task<int> GetGroupSizeMaxAsync(CancellationToken cancellationToken = default) => GetConfigItemAsync(ConfigKeyGroupSizeMax, s => s == null ? 2 : int.Parse(s), cancellationToken); public Task<string> GetGroupSelectionPageTextAsync(CancellationToken cancellationToken = default) => GetConfigItemAsync(ConfigKeyGroupSelectionPageText, s => s ?? string.Empty, cancellationToken); public Task SetGroupSelectionPageTextAsync(string value, CancellationToken cancellationToken = default) => AddOrUpdateConfigItem(ConfigKeyGroupSelectionPageText, value, cancellationToken); private async Task<TValue> GetConfigItemAsync<TValue>(string key, Func<string, TValue> valueConverter, CancellationToken cancellationToken) { // Try to retrieve from config cache string cacheKey = "config-" + key; if(!_cache.TryGetValue(cacheKey, out string value)) { // Retrieve from database var config = await _dbContext.ConfigurationItems.AsNoTracking() .FirstOrDefaultAsync(c => c.Key == key, cancellationToken); value = config?.Value; // Update cache _cache.Set(cacheKey, value); } return valueConverter(value); } private async Task AddOrUpdateConfigItem<TValue>(string key, TValue value, CancellationToken cancellationToken) { // Write updated config to database string cacheKey = "config-" + key; var config = await _dbContext.ConfigurationItems.FindAsync(new object[] { key }, cancellationToken); if(config == null) await _dbContext.ConfigurationItems.AddAsync(new ConfigurationItemEntity { Key = key, Value = value.ToString() }, cancellationToken); else config.Value = value.ToString(); await _dbContext.SaveChangesAsync(cancellationToken); // Update cache _cache.Set(cacheKey, value.ToString()); } } }
60.333333
149
0.735912
[ "MIT" ]
JanWichelmann/ctf4e
src/Ctf4e.Server/Services/ConfigurationService.cs
9,052
C#
namespace RecompressPng.VRM { /// <summary> /// Element of an array of "images" node. /// </summary> public struct ImageIndex { /// <summary> /// Index of buffer view. /// </summary> public int Index { get; set; } /// <summary> /// Name of an image. /// </summary> public string Name { get; set; } /// <summary> /// MIME type string. /// </summary> public string MimeType { get; set; } /// <summary> /// Initialize all properties. /// </summary> /// <param name="index">Index of buffer view.</param> /// <param name="name">Name of an image.</param> /// <param name="mimeType">MIME type string.</param> public ImageIndex(int index, string name, string mimeType) { Index = index; Name = name; MimeType = mimeType; } } }
28.057143
67
0.473523
[ "MIT" ]
koturn/RecompressPng
RecompressPng/VRM/ImageIndex.cs
984
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using NLog; using NLog.Config; using NLog.Targets; namespace BuyEngine.WebApi { public class Program { public static void Main(string[] args) { try { LogManager.Configuration = ConfigureNLog(); CreateHostBuilder(args).Build().Run(); } finally { LogManager.Shutdown(); } } public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } public static LoggingConfiguration ConfigureNLog() { var loggingConfig = new LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new FileTarget("logfile") { FileName = "../../../../../logs/BuyEngine.WebApi/log.txt", ArchiveFileName = "log-{#}.txt", ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = "yyyyMMdd-HH", Layout = "${longDate}|${level:uppercase=true}|${logger}|${callsite}|${message}" }; var logconsole = new ConsoleTarget("logconsole"); // Rules for mapping loggers to targets loggingConfig.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); loggingConfig.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); return loggingConfig; } } }
32.372549
129
0.563901
[ "Apache-2.0" ]
wamplerj/BuyEngine
src/BuyEngine.WebApi/Program.cs
1,651
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x17_9195-173a431")] public void Method_0017_9195() { ii(0x17_9195, 2); mov(ah, 0x40); /* mov ah, 0x40 */ ii(0x17_9197, 2); jmp_func(0x17_9177, -0x22); /* jmp 0x9177 */ } } }
28
90
0.535714
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-0017-9195.cs
448
C#
using System; using System.Collections.Generic; using System.Text; namespace Integrator.Models.Domain.EnumClasses { public enum EnumKbSkillType { HardSkill = 1, SoftSkill = 2 } }
16.076923
46
0.679426
[ "Apache-2.0" ]
Speedie007/Intergrator
Integrator.Web/Integrator.Models/Domain/EnumClasses/EnumKbSkillType.cs
211
C#
using Microsoft.AspNetCore.Authentication; namespace NextApi.Testing.Security.Auth { /// <inheritdoc /> public class TestAuthOptions: AuthenticationSchemeOptions { } }
17.636364
61
0.701031
[ "MIT" ]
DotNetNomads/NextApi
src/base/NextApi.Testing/Security/Auth/TestAuthOptions.cs
194
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ssm-2014-11-06.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.SimpleSystemsManagement.Model { /// <summary> /// Container for the parameters to the UpdateAssociationStatus operation. /// Updates the status of the Amazon Web Services Systems Manager document (SSM document) /// associated with the specified instance. /// /// /// <para> /// <code>UpdateAssociationStatus</code> is primarily used by the Amazon Web Services /// Systems Manager Agent (SSM Agent) to report status updates about your associations /// and is only used for associations created with the <code>InstanceId</code> legacy /// parameter. /// </para> /// </summary> public partial class UpdateAssociationStatusRequest : AmazonSimpleSystemsManagementRequest { private AssociationStatus _associationStatus; private string _instanceId; private string _name; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public UpdateAssociationStatusRequest() { } /// <summary> /// Instantiates UpdateAssociationStatusRequest with the parameterized properties /// </summary> /// <param name="associationStatus">The association status.</param> /// <param name="instanceId">The instance ID.</param> /// <param name="name">The name of the SSM document.</param> public UpdateAssociationStatusRequest(AssociationStatus associationStatus, string instanceId, string name) { _associationStatus = associationStatus; _instanceId = instanceId; _name = name; } /// <summary> /// Gets and sets the property AssociationStatus. /// <para> /// The association status. /// </para> /// </summary> [AWSProperty(Required=true)] public AssociationStatus AssociationStatus { get { return this._associationStatus; } set { this._associationStatus = value; } } // Check to see if AssociationStatus property is set internal bool IsSetAssociationStatus() { return this._associationStatus != null; } /// <summary> /// Gets and sets the property InstanceId. /// <para> /// The instance ID. /// </para> /// </summary> [AWSProperty(Required=true)] public string InstanceId { get { return this._instanceId; } set { this._instanceId = value; } } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this._instanceId != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the SSM document. /// </para> /// </summary> [AWSProperty(Required=true)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } } }
32.674603
114
0.618897
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/UpdateAssociationStatusRequest.cs
4,117
C#
using System; using UnityEngine; using UnityEngine.Events; namespace DevLocker.Animations.AnimatorExpositor { /// <summary> /// Generic event listener. The response is an UnityEvent that can be used in the UI to link action directly. /// Use with AnimStateEventsTrigger. /// </summary> public class AnimEventListener : MonoBehaviour { [Serializable] public struct EventListenerBind { public string Name; public UnityEvent Target; } public EventListenerBind[] Listeners; public void TriggerEvent(string eventName) { int foundIndex = Array.FindIndex(Listeners, f => f.Name == eventName); if (foundIndex == -1) { Debug.LogWarning($"Trying to trigger animation event \"{eventName}\", but there are no handlers.", this); return; } Listeners[foundIndex].Target.Invoke(); } } }
21.789474
110
0.71256
[ "MIT" ]
NibbleByte/DevLocker
Assets/DevLocker/Animations/AnimatorExpositor/AnimEventListener.cs
828
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.AspNetCore.SignalR.Protocol; using Microsoft.AspNetCore.SignalR.Microbenchmarks.Shared; using Microsoft.Extensions.Logging.Abstractions; namespace Microsoft.AspNetCore.SignalR.Microbenchmarks { public class DefaultHubLifetimeManagerBenchmark { private DefaultHubLifetimeManager<Hub> _hubLifetimeManager; private List<string> _connectionIds; private List<string> _subsetConnectionIds; private List<string> _groupNames; private List<string> _userIdentifiers; [Params(true, false)] public bool ForceAsync { get; set; } [GlobalSetup] public void GlobalSetup() { _hubLifetimeManager = new DefaultHubLifetimeManager<Hub>(NullLogger<DefaultHubLifetimeManager<Hub>>.Instance); _connectionIds = new List<string>(); _subsetConnectionIds = new List<string>(); _groupNames = new List<string>(); _userIdentifiers = new List<string>(); var jsonHubProtocol = new NewtonsoftJsonHubProtocol(); for (int i = 0; i < 100; i++) { string connectionId = "connection-" + i; string groupName = "group-" + i % 10; string userIdentifier = "user-" + i % 20; AddUnique(_connectionIds, connectionId); AddUnique(_groupNames, groupName); AddUnique(_userIdentifiers, userIdentifier); if (i % 3 == 0) { _subsetConnectionIds.Add(connectionId); } var connectionContext = new TestConnectionContext { ConnectionId = connectionId, Transport = new TestDuplexPipe(ForceAsync) }; var contextOptions = new HubConnectionContextOptions() { KeepAliveInterval = TimeSpan.Zero, }; var hubConnectionContext = new HubConnectionContext(connectionContext, contextOptions, NullLoggerFactory.Instance); hubConnectionContext.UserIdentifier = userIdentifier; hubConnectionContext.Protocol = jsonHubProtocol; _hubLifetimeManager.OnConnectedAsync(hubConnectionContext).GetAwaiter().GetResult(); _hubLifetimeManager.AddToGroupAsync(connectionId, groupName); } } private void AddUnique(List<string> list, string connectionId) { if (!list.Contains(connectionId)) { list.Add(connectionId); } } [Benchmark] public Task SendAllAsync() { return _hubLifetimeManager.SendAllAsync("MethodName", Array.Empty<object>()); } [Benchmark] public Task SendGroupAsync() { return _hubLifetimeManager.SendGroupAsync(_groupNames[0], "MethodName", Array.Empty<object>()); } [Benchmark] public Task SendGroupsAsync() { return _hubLifetimeManager.SendGroupsAsync(_groupNames, "MethodName", Array.Empty<object>()); } [Benchmark] public Task SendGroupExceptAsync() { return _hubLifetimeManager.SendGroupExceptAsync(_groupNames[0], "MethodName", Array.Empty<object>(), _subsetConnectionIds); } [Benchmark] public Task SendAllExceptAsync() { return _hubLifetimeManager.SendAllExceptAsync("MethodName", Array.Empty<object>(), _subsetConnectionIds); } [Benchmark] public Task SendConnectionAsync() { return _hubLifetimeManager.SendConnectionAsync(_connectionIds[0], "MethodName", Array.Empty<object>()); } [Benchmark] public Task SendConnectionsAsync() { return _hubLifetimeManager.SendConnectionsAsync(_subsetConnectionIds, "MethodName", Array.Empty<object>()); } [Benchmark] public Task SendUserAsync() { return _hubLifetimeManager.SendUserAsync(_userIdentifiers[0], "MethodName", Array.Empty<object>()); } [Benchmark] public Task SendUsersAsync() { return _hubLifetimeManager.SendUsersAsync(_userIdentifiers, "MethodName", Array.Empty<object>()); } } }
35.623077
135
0.612611
[ "MIT" ]
48355746/AspNetCore
src/SignalR/perf/Microbenchmarks/DefaultHubLifetimeManagerBenchmark.cs
4,631
C#
using System; using Microsoft.Office.Interop.Excel; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using linqXl; using glpkXl; namespace glpkModelXLL { public class scenario { private string _wbPath; private string _ws; private string _list; private string _dest; public string workbook { get { return _wbPath; } set { if (value == null) _wbPath = ""; else _wbPath = value.Trim(); } } public string worksheet { get { return _ws; } set { if (value == null) _ws = ""; else _ws = value.Trim(); } } public string list { get { return _list; } set { if (value == null) _list = ""; else _list = value.Trim(); } } public string destination { get { return _dest; } set { if (value == null) _dest = ""; else _dest = value.Trim(); } } } public static class scenariosSheet { private static List<scenario> scenarios(this Workbook wb) { try { List<scenario> scenarios = wb.WorksheetList<scenario>("scenarios", "scenariosTable"); scenarios = scenarios.Where(s => s.workbook != "").Where(s => s.worksheet != "").Where(s => s.list != "").Where(s => s.destination != "").ToList(); return scenarios; } catch (Exception) { return null; } } private static bool hasScenarios(this Workbook wb) => wb.scenarios() != null; public static void refreshScenarios(this Workbook wb) { glpkExcelAddIn.disableSheetChange(); if ( wb.hasScenarios()) { var sceDest = wb.scenarios().GroupBy(s => s.destination); foreach (var s in sceDest) refreshScenarios(wb, s.ToList(), s.Key); } if (!wb.hasScenarios()) { createScenariosSheet(wb); } glpkExcelAddIn.enableSheetChange(); } private static void refreshScenarios(this Workbook wb, List<scenario> scenarios, string destination) { List<glpkColumn> columns = new List<glpkColumn>(); try { foreach (scenario s in scenarios) { try { Workbook wb1 = glpkExcelAddIn.Application.Workbooks.Open(s.workbook); List<glpkColumn> columns1 = wb1.WorksheetList<glpkColumn>(s.worksheet, s.list); if (wb1!=wb) wb1.Close(false); columns = columns.Union(columns1).ToList(); } catch { /* Ignored */ } } wb.Activate(); if (columns.Count > 0) columns.write(wb, destination, destination); } catch { /* Ignored */ } } private static void createScenariosSheet(this Workbook wb) { DialogResult yn = MessageBox.Show("Do you want to create a scenario sheet?", "Scenario sheet missing.", MessageBoxButtons.YesNo); if (yn != DialogResult.Yes) return; try { List<scenario> scenarios = new List<scenario>(); //scenario scenario = new scenario() { workbook = @"C:\folder\aa\scenario1.xls", worksheet = @"worksheet", list = "list", destination = "scenarioList" }; scenario scenario = new scenario() { workbook = wb.FullName, worksheet = @"worksheet", list = "list", destination = "scenarioList" }; scenarios.Add(scenario); scenario = new scenario(); for (int i = 0; i < 40; i++) scenarios.Add(scenario); Worksheet ws = scenarios.write(wb, "scenarios", "scenariosTable"); } catch { /* Ignored */ } } } }
40.639175
169
0.526129
[ "MIT" ]
maajdl/glpkModelXLL
glpkModelXLL32/glpkModelXLL/scenariosSheet.cs
3,944
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Wrapperator.Wrappers.Xml.Linq { /// <summary>Represents an XML element.</summary> public class XElementStaticWrapper : Wrapperator.Interfaces.Xml.Linq.IXElementStatic { internal XElementStaticWrapper() { } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> EmptySequence { get { return System.Xml.Linq.XElement.EmptySequence; } } /// <summary>Loads an <see cref="T:System.Xml.Linq.XElement" /> from a file.</summary> /// <returns>An <see cref="T:System.Xml.Linq.XElement" /> that contains the contents of the specified file.</returns> /// <param name="uri">A URI string referencing the file to load into a new <see cref="T:System.Xml.Linq.XElement" />.</param> public Wrapperator.Interfaces.Xml.Linq.IXElement Load(string uri) { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(System.Xml.Linq.XElement.Load(uri)); } /// <summary>Loads an <see cref="T:System.Xml.Linq.XElement" /> from a file, optionally preserving white space, setting the base URI, and retaining line information.</summary> /// <returns>An <see cref="T:System.Xml.Linq.XElement" /> that contains the contents of the specified file.</returns> /// <param name="uri">A URI string referencing the file to load into an <see cref="T:System.Xml.Linq.XElement" />.</param> /// <param name="options">A <see cref="T:System.Xml.Linq.LoadOptions" /> that specifies white space behavior, and whether to load base URI and line information.</param> public Wrapperator.Interfaces.Xml.Linq.IXElement Load(string uri, System.Xml.Linq.LoadOptions options) { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(System.Xml.Linq.XElement.Load(uri, options)); } /// <summary>Creates a new <see cref="T:System.Xml.Linq.XElement" /> instance by using the specified stream.</summary> /// <returns>An <see cref="T:System.Xml.Linq.XElement" /> object used to read the data that is contained in the stream.</returns> /// <param name="stream">The stream that contains the XML data.</param> public Wrapperator.Interfaces.Xml.Linq.IXElement Load(Wrapperator.Interfaces.IO.IStream stream) { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(System.Xml.Linq.XElement.Load(stream == null ? default(System.IO.Stream) : stream._Stream)); } /// <summary>Creates a new <see cref="T:System.Xml.Linq.XElement" /> instance by using the specified stream, optionally preserving white space, setting the base URI, and retaining line information.</summary> /// <returns>An <see cref="T:System.Xml.Linq.XElement" /> object used to read the data that the stream contains.</returns> /// <param name="stream">The stream containing the XML data.</param> /// <param name="options">A <see cref="T:System.Xml.Linq.LoadOptions" /> object that specifies whether to load base URI and line information.</param> public Wrapperator.Interfaces.Xml.Linq.IXElement Load(Wrapperator.Interfaces.IO.IStream stream, System.Xml.Linq.LoadOptions options) { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(System.Xml.Linq.XElement.Load(stream == null ? default(System.IO.Stream) : stream._Stream, options)); } /// <summary>Loads an <see cref="T:System.Xml.Linq.XElement" /> from a <see cref="T:System.IO.TextReader" />. </summary> /// <returns>An <see cref="T:System.Xml.Linq.XElement" /> that contains the XML that was read from the specified <see cref="T:System.IO.TextReader" />.</returns> /// <param name="textReader">A <see cref="T:System.IO.TextReader" /> that will be read for the <see cref="T:System.Xml.Linq.XElement" /> content.</param> public Wrapperator.Interfaces.Xml.Linq.IXElement Load(Wrapperator.Interfaces.IO.ITextReader textReader) { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(System.Xml.Linq.XElement.Load(textReader == null ? default(System.IO.TextReader) : textReader._TextReader)); } /// <summary>Loads an <see cref="T:System.Xml.Linq.XElement" /> from a <see cref="T:System.IO.TextReader" />, optionally preserving white space and retaining line information. </summary> /// <returns>An <see cref="T:System.Xml.Linq.XElement" /> that contains the XML that was read from the specified <see cref="T:System.IO.TextReader" />.</returns> /// <param name="textReader">A <see cref="T:System.IO.TextReader" /> that will be read for the <see cref="T:System.Xml.Linq.XElement" /> content.</param> /// <param name="options">A <see cref="T:System.Xml.Linq.LoadOptions" /> that specifies white space behavior, and whether to load base URI and line information.</param> public Wrapperator.Interfaces.Xml.Linq.IXElement Load(Wrapperator.Interfaces.IO.ITextReader textReader, System.Xml.Linq.LoadOptions options) { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(System.Xml.Linq.XElement.Load(textReader == null ? default(System.IO.TextReader) : textReader._TextReader, options)); } /// <summary>Loads an <see cref="T:System.Xml.Linq.XElement" /> from an <see cref="T:System.Xml.XmlReader" />. </summary> /// <returns>An <see cref="T:System.Xml.Linq.XElement" /> that contains the XML that was read from the specified <see cref="T:System.Xml.XmlReader" />.</returns> /// <param name="reader">A <see cref="T:System.Xml.XmlReader" /> that will be read for the content of the <see cref="T:System.Xml.Linq.XElement" />.</param> public Wrapperator.Interfaces.Xml.Linq.IXElement Load(Wrapperator.Interfaces.Xml.IXmlReader reader) { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(System.Xml.Linq.XElement.Load(reader == null ? default(System.Xml.XmlReader) : reader._XmlReader)); } /// <summary>Loads an <see cref="T:System.Xml.Linq.XElement" /> from an <see cref="T:System.Xml.XmlReader" />, optionally preserving white space, setting the base URI, and retaining line information.</summary> /// <returns>An <see cref="T:System.Xml.Linq.XElement" /> that contains the XML that was read from the specified <see cref="T:System.Xml.XmlReader" />.</returns> /// <param name="reader">A <see cref="T:System.Xml.XmlReader" /> that will be read for the content of the <see cref="T:System.Xml.Linq.XElement" />.</param> /// <param name="options">A <see cref="T:System.Xml.Linq.LoadOptions" /> that specifies white space behavior, and whether to load base URI and line information.</param> public Wrapperator.Interfaces.Xml.Linq.IXElement Load(Wrapperator.Interfaces.Xml.IXmlReader reader, System.Xml.Linq.LoadOptions options) { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(System.Xml.Linq.XElement.Load(reader == null ? default(System.Xml.XmlReader) : reader._XmlReader, options)); } /// <summary>Load an <see cref="T:System.Xml.Linq.XElement" /> from a string that contains XML.</summary> /// <returns>An <see cref="T:System.Xml.Linq.XElement" /> populated from the string that contains XML.</returns> /// <param name="text">A <see cref="T:System.String" /> that contains XML.</param> public Wrapperator.Interfaces.Xml.Linq.IXElement Parse(string text) { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(System.Xml.Linq.XElement.Parse(text)); } /// <summary>Load an <see cref="T:System.Xml.Linq.XElement" /> from a string that contains XML, optionally preserving white space and retaining line information.</summary> /// <returns>An <see cref="T:System.Xml.Linq.XElement" /> populated from the string that contains XML.</returns> /// <param name="text">A <see cref="T:System.String" /> that contains XML.</param> /// <param name="options">A <see cref="T:System.Xml.Linq.LoadOptions" /> that specifies white space behavior, and whether to load base URI and line information.</param> public Wrapperator.Interfaces.Xml.Linq.IXElement Parse(string text, System.Xml.Linq.LoadOptions options) { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(System.Xml.Linq.XElement.Parse(text, options)); } } }
73.034188
213
0.699707
[ "MIT" ]
chrischu/Wrapperator
src/Wrapperator.Wrappers/Xml/Linq/XElementStaticWrapper.cs
8,545
C#
using MSCLoader; using UnityEngine; namespace MiniMap { public class MiniMap : Mod { public override string ID => "MiniMap"; //Your mod ID (unique) public override string Name => "MiniMap"; //You mod name public override string Author => "BrennFuchS"; //Your Username public override string Version => "1.0"; //Version GameObject MiniMAP; Transform PLAYER; Transform MiniMAPCamera; Transform GUI; GameObject MiniMAPArrow; float Zoom; public override bool UseAssetsFolder => true; public override void OnLoad() { AssetBundle AB = LoadAssets.LoadBundle(this, "mscminimap"); GameObject Prefab = AB.LoadAsset<GameObject>("MINIMAPOBJECTS.prefab"); MiniMAP = GameObject.Instantiate<GameObject>(Prefab); GameObject.Destroy(Prefab); PLAYER = GameObject.Find("PLAYER").transform; MiniMAPCamera = MiniMAP.transform.Find("MAPCAMERA"); GUI = GameObject.Find("GUI").transform; MiniMAPArrow = MiniMAPCamera.Find("PLAYERMARKER").gameObject; MiniMAP.transform.Find("MINIMAP").SetParent(GUI.transform.Find("HUD")); AB.Unload(false); } public override void Update() { if (PLAYER.parent != null) { if(shouldZoomBool == true) { if (PLAYER.parent.parent.parent.GetComponent<Rigidbody>() != null) { Zoom = PLAYER.parent.parent.parent.GetComponent<Rigidbody>().velocity.x + PLAYER.parent.parent.parent.GetComponent<Rigidbody>().velocity.z / 2f + -40f; } } PLAYER.parent.parent.localEulerAngles = new Vector3(PLAYER.parent.parent.localEulerAngles.x , 180f, PLAYER.parent.parent.localEulerAngles.z); MiniMAPCamera.GetComponent<Camera>().orthographicSize = Zoom; MiniMAPArrow.SetActive(false); MiniMAPCamera.eulerAngles = new Vector3(90f, PLAYER.parent.eulerAngles.y, 0f); MiniMAPCamera.position = new Vector3(PLAYER.parent.position.x, 15, PLAYER.parent.position.z); } else { MiniMAPCamera.GetComponent<Camera>().orthographicSize = 40f; MiniMAPArrow.SetActive(true); MiniMAPCamera.eulerAngles = new Vector3(90f, PLAYER.eulerAngles.y, 0f); MiniMAPCamera.position = new Vector3(PLAYER.position.x, 15f, PLAYER.position.z); } } static void changeBool() { shouldZoomBool = !shouldZoomBool; } static bool shouldZoomBool = true; static Settings shouldZoom = new Settings("zoom", "Zoom", true, changeBool); public override void ModSettings() { // All settings should be created here. // DO NOT put anything else here that settings. Settings.AddCheckBox(this, shouldZoom); } } }
37.73494
175
0.579183
[ "MIT" ]
Krutonium/MiniMap
MiniMap/MiniMap.cs
3,134
C#
using System; using System.Collections.Generic; using System.Text; using static Xamarin.Forms.Platform.LibUI.Interop.NativeMethods; namespace Xamarin.Forms.Platform.LibUI.Controls { public class Group : Control { public string Title { get { return uiGroupTitle(Handle); } set { uiGroupSetTitle(Handle, value); } } public bool Margined { get { return uiGroupMargined(Handle); } set { uiGroupSetMargined(Handle, value); } } private Control _child; public Control Child { get { return _child; } set { _child = value; uiGroupSetChild(Handle, value.Handle); } } public Group(string title) { Handle = uiNewGroup(title); } } }
20.377358
64
0.436111
[ "MIT" ]
zhongzf/Xamarin.Forms.Platform.LibUI
Xamarin.Forms.Platform.LibUI/Controls/Group.cs
1,082
C#
using System; using System.Globalization; namespace Microsoft.Maui.Controls { [Xaml.TypeConversion(typeof(Rect))] public class RectTypeConverter : TypeConverter { public override object ConvertFromInvariantString(string value) { if (value != null) { string[] xywh = value.Split(','); if (xywh.Length == 4 && double.TryParse(xywh[0], NumberStyles.Number, CultureInfo.InvariantCulture, out double x) && double.TryParse(xywh[1], NumberStyles.Number, CultureInfo.InvariantCulture, out double y) && double.TryParse(xywh[2], NumberStyles.Number, CultureInfo.InvariantCulture, out double w) && double.TryParse(xywh[3], NumberStyles.Number, CultureInfo.InvariantCulture, out double h)) return new Rect(x, y, w, h); } throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", value, typeof(Rect))); } public override string ConvertToInvariantString(object value) { if (!(value is Rect r)) throw new NotSupportedException(); return $"{r.X.ToString(CultureInfo.InvariantCulture)}, {r.Y.ToString(CultureInfo.InvariantCulture)}, {r.Width.ToString(CultureInfo.InvariantCulture)}, {r.Height.ToString(CultureInfo.InvariantCulture)}"; } } }
37.121212
205
0.724898
[ "MIT" ]
Eilon/maui
src/Controls/src/Core/RectTypeConverter.cs
1,225
C#
using System.Globalization; using DeltaEngine.Content; using DeltaEngine.Datatypes; using DeltaEngine.Rendering2D.Fonts; namespace FindTheWord { public class CharacterButton : GameButton { public CharacterButton(float xCenter, float yCenter, GameScreen screen) : base("CharBackground", GetDrawArea(xCenter, yCenter)) { this.screen = screen; letter = NoCharacter; var font = ContentLoader.Load<Font>("Tahoma30"); currentFontText = new FontText(font, "", Rectangle.FromCenter(Vector2D.Half, new Size(0.5f))); currentFontText.RenderLayer = 4; } private readonly GameScreen screen; private static Rectangle GetDrawArea(float xCenter, float yCenter) { return Rectangle.FromCenter(xCenter, yCenter, Dimension, Dimension); } internal const float Dimension = 65.0f / 1280.0f; private char letter; internal const char NoCharacter = '\0'; private readonly FontText currentFontText; public char Letter { get { return letter; } set { letter = value; currentFontText.Text = letter.ToString(CultureInfo.InvariantCulture); SetNewCenter(DrawArea.Center); } } private void SetNewCenter(Vector2D newCenter) { Center = newCenter; var newLetterArea = DrawArea; newLetterArea.Left += Dimension * 0.05f; currentFontText.DrawArea = newLetterArea; } public void RemoveLetter() { currentFontText.Text = ""; } public void ShowLetter() { currentFontText.Text = letter.ToString(CultureInfo.InvariantCulture); } public int Index { get; set; } public override string ToString() { return GetType().Name + "(" + Index + " - " + Letter + ")"; } public bool IsClickable() { return IsVisible && currentFontText.Text != ""; } public override void Dispose() { currentFontText.Text = ""; currentFontText.IsActive = false; IsActive = false; base.Dispose(); } public void OnDisplayCharButtonClicked() { if (!IsClickable()) return; screen.OnDisplayCharButtonClicked(this); } public void OnSolutionCharButtonClicked() { screen.OnSolutionCharButtonClicked(this); } } }
23.731183
98
0.673312
[ "Apache-2.0" ]
DeltaEngine/DeltaEngine
Samples/FindTheWord/CharacterButton.cs
2,209
C#
using AirVinyl.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AirVinyl.Web.Models { public class AirVinylViewModel { public IEnumerable<Person> People { get; set; } public Person Person { get; set; } public string AdditionalData { get; set; } public AirVinylViewModel() { People = new List<Person>(); } } }
21.8
55
0.62844
[ "MIT" ]
mcampulla/AirVinyl
AirVinyl.Web/Models/AirVinylViewModel.cs
438
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.AwsNative.KinesisAnalyticsV2.Inputs { public sealed class ApplicationRecordFormatArgs : Pulumi.ResourceArgs { [Input("mappingParameters")] public Input<Inputs.ApplicationMappingParametersArgs>? MappingParameters { get; set; } [Input("recordFormatType", required: true)] public Input<string> RecordFormatType { get; set; } = null!; public ApplicationRecordFormatArgs() { } } }
29.346154
94
0.705111
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/KinesisAnalyticsV2/Inputs/ApplicationRecordFormatArgs.cs
763
C#
using System; using System.Collections.Generic; using System.Linq; using Hai.ExpressionsEditor.Scripts.Components; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; namespace Hai.ExpressionsEditor.Scripts.Editor.Internal.Modules { public class EeRenderingCommands { private readonly Dictionary<EePriority, List<Action>> _priorityQueues = new Dictionary<EePriority, List<Action>>(); private bool _isProcessing; private Action _queueEmptied; public enum EeDummyAutoHide { Default, DoNotHide } public enum EePriority { High, Normal, Low } public EeRenderingCommands() { _priorityQueues[EePriority.High] = new List<Action>(); _priorityQueues[EePriority.Normal] = new List<Action>(); _priorityQueues[EePriority.Low] = new List<Action>(); } public void SetQueueEmptiedAction(Action action) { // FIXME: bad pattern _queueEmptied = action; } public void GenerateSpecific( List<EeRenderingSample> animationsPreviews, EePreviewAvatar previewSetup, EeDummyAutoHide autoHide = EeDummyAutoHide.Default, EePriority priority = EePriority.Normal) { _priorityQueues[priority].Add(() => new EeRenderingJob(previewSetup, 0, animationsPreviews, true, OnQueueTaskComplete, autoHide).Capture()); WakeQueue(); } public Action GenerateSpecificFastMode( List<EeRenderingSample> animationsPreviews, EePreviewAvatar previewSetup, int cameraIndex, EeDummyAutoHide autoHide = EeDummyAutoHide.Default, EePriority priority = EePriority.Normal) { List<EeRenderingJob> jobs = new List<EeRenderingJob>(); for (int startIndex = 0; startIndex < animationsPreviews.Count; startIndex += 15) { var finalIndex = startIndex; var job = new EeRenderingJob(previewSetup, cameraIndex, animationsPreviews.GetRange(finalIndex, Math.Min(15, animationsPreviews.Count - finalIndex)), false, OnQueueTaskComplete, autoHide); jobs.Add(job); _priorityQueues[priority].Add(() => job.Capture()); } WakeQueue(); // FIXME: Obscure drop callback return () => { foreach (var job in jobs) { job.Drop(); } }; } private void WakeQueue() { if (_isProcessing || QueueIsEmpty()) { return; } _isProcessing = true; ExecuteNextInQueue(); } private void ExecuteNextInQueue() { if (QueueIsEmpty()) return; var queue = new[] {_priorityQueues[EePriority.High], _priorityQueues[EePriority.Normal], _priorityQueues[EePriority.Low]} .First(list => list.Count > 0); var first = queue[0]; queue.RemoveAt(0); first.Invoke(); } private bool QueueIsEmpty() { return new[] {_priorityQueues[EePriority.High], _priorityQueues[EePriority.Normal], _priorityQueues[EePriority.Low]} .SelectMany(list => list) .FirstOrDefault() == null; } private void OnQueueTaskComplete() { if (QueueIsEmpty()) { _queueEmptied(); _isProcessing = false; } else { ExecuteNextInQueue(); } } } public static class EeRenderingSupport { private const int Border = 4; private static Color ComputeGrayscaleValue(Texture2D tex, int x, int y) { var value = tex.GetPixel(x, y); var gsv = (value.r + value.g + value.b) / 3f; var actualGsv = value * 0.3f + new Color(gsv, gsv, gsv, value.a) * 0.7f; return actualGsv; } public static void MutateMultilevelHighlightDifferences(Texture2D mutableTexture, Texture2D shapekeys, Texture2D noShapekeys) { var width = mutableTexture.width; var height = mutableTexture.height; var major = new bool[width * height]; var hasAnyMajorDifference = MutateGetComputeDifference(major, shapekeys, noShapekeys, 0.05f); var minor = new bool[width * height]; MutateGetComputeDifference(minor, shapekeys, noShapekeys, 0.0015f); var boundaries = hasAnyMajorDifference ? DifferenceAsBoundaries(major, width, height) : DifferenceAsBoundaries(minor, width, height); if (boundaries.IsEmpty()) { for (var y = 0; y < height; y++) for (var x = 0; x < width; x++) mutableTexture.SetPixel(x, y, ComputeGrayscaleValue(shapekeys, x, y) * 0.2f); mutableTexture.Apply(); } else { MutateBoundariesGrayscale(mutableTexture, shapekeys, boundaries); } } private static void MutateBoundariesGrayscale(Texture2D mutaTexture, Texture2D shapekeys, PreviewBoundaries boundaries) { var width = mutaTexture.width; var height = mutaTexture.height; for (var y = 0; y < height; y++) for (var x = 0; x < width; x++) { var isIn = x >= boundaries.MinX - Border && x <= boundaries.MaxX + Border && y >= boundaries.MinY - Border && y <= boundaries.MaxY + Border; mutaTexture.SetPixel(x, y, isIn ? shapekeys.GetPixel(x, y) : ComputeGrayscaleValue(shapekeys, x, y) * 0.5f); } mutaTexture.Apply(false); } private static bool MutateGetComputeDifference(bool[] mutated, Texture2D shapekeys, Texture2D noShapekeys, float threshold) { bool hasAnyDifference = false; var width = shapekeys.width; var height = shapekeys.height; for (var y = 0; y < height; y++) for (var x = 0; x < width; x++) { var a = shapekeys.GetPixel(x, y); var b = noShapekeys.GetPixel(x, y); var isDifferent = a != b && MeasureDifference(a, b) > threshold; if (!hasAnyDifference && isDifferent) { hasAnyDifference = true; } mutated[x + y * width] = isDifferent; } return hasAnyDifference; } private static float MeasureDifference(Color a, Color b) { return Mathf.Abs((a.r + a.g + a.b) - (b.r + b.g + b.b)) / 3f; } public static void MutateHighlightHotspots(Texture2D mutableTexture, Texture2D blendshapeTexture, Texture2D noShapekeys) { var tex = mutableTexture; var width = mutableTexture.width; var height = mutableTexture.height; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var blendShapePixel = blendshapeTexture.GetPixel(x, y); var other = noShapekeys.GetPixel(x, y); if (blendShapePixel != other) { var difference = MeasureDifference(blendShapePixel, other) * 10; tex.SetPixel(x, y, Color.Lerp(Color.blue, Color.red, Mathf.SmoothStep(0f, 1f, difference))); } else { tex.SetPixel(x, y, Color.green); } } } tex.Apply(false); } // ReSharper disable once UnusedMember.Global public static void MutateHighlightHotspots2(Texture2D mutableTexture, Texture2D blendshapeTexture, Texture2D noShapekeys) { var tex = mutableTexture; var width = mutableTexture.width; var height = mutableTexture.height; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var blendShapePixel = blendshapeTexture.GetPixel(x, y); var other = noShapekeys.GetPixel(x, y); var bg = (x / 10 + y / 10) % 2 == 0 ? Color.white : new Color(0.95f, 0.95f, 0.95f, 0.35f); if (blendShapePixel != other) { var difference = MeasureDifference(blendShapePixel, other) * 10; var target = new Color(blendShapePixel.r, blendShapePixel.g, blendShapePixel.b, 1f); tex.SetPixel(x, y, Color.Lerp(bg, target, Mathf.SmoothStep(0.7f, 1f, difference))); } else { tex.SetPixel(x, y, bg); } } } tex.Apply(false); } private static PreviewBoundaries DifferenceAsBoundaries(bool[] mutableDiff, int width, int height) { var minX = -1; var maxX = -1; var minY = -1; var maxY = -1; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { if (mutableDiff[x + y * width]) { if (minX == -1 || x < minX) { minX = x; } if (minY == -1 || y < minY) { minY = y; } if (x > maxX) { maxX = x; } if (y > maxY) { maxY = y; } } } } return new PreviewBoundaries(minX, maxX, minY, maxY); } private readonly struct PreviewBoundaries { public PreviewBoundaries(int minX, int maxX, int minY, int maxY) { MinX = minX; MaxX = maxX; MinY = minY; MaxY = maxY; } public readonly int MinX; public readonly int MaxX; public readonly int MinY; public readonly int MaxY; public bool IsEmpty() { return MinX == -1 && MaxX == -1 && MinY == -1 && MaxY == -1; } } } internal class EeRenderingJob { private readonly EePreviewAvatar _previewSetup; private readonly List<EeRenderingSample> _renderingSamples; private readonly Action _onQueueTaskComplete; private RenderTexture _renderTexture; private readonly bool _includeTransformsMode; private readonly EeRenderingCommands.EeDummyAutoHide _autoHide; private readonly int _cameraIndex; private bool StopGenerating { get; set; } public EeRenderingJob(EePreviewAvatar previewSetup, int cameraIndex, List<EeRenderingSample> renderingSamples, bool includeTransformsMode, Action onQueueTaskComplete = null, EeRenderingCommands.EeDummyAutoHide autoHide = EeRenderingCommands.EeDummyAutoHide.Default) { _previewSetup = previewSetup; _cameraIndex = cameraIndex; _renderingSamples = renderingSamples; _includeTransformsMode = includeTransformsMode; _autoHide = autoHide; _onQueueTaskComplete = onQueueTaskComplete ?? (() => {}); } public void Capture() { if (!AnimationMode.InAnimationMode()) { AnimationMode.StartAnimationMode(); } var generatedCamera = GenerateCamera(); _previewSetup.Dummy.gameObject.SetActive(true); DoGenerationProcess(generatedCamera); } public void Drop() { StopGenerating = true; } private void DoGenerationProcess(Camera generatedCamera) { var queue = new Queue<Action>(); for (var index = 0; index < _renderingSamples.Count; index++) { var currentPreview = _renderingSamples[index]; if (_includeTransformsMode || _renderingSamples.Count <= 1) { queue.Enqueue(() => { SampleClip(currentPreview); }); queue.Enqueue(() => { RenderToTexture(generatedCamera, currentPreview); }); } else if (index == 0) { queue.Enqueue(() => { SampleClip(currentPreview); }); } else if (index == _renderingSamples.Count - 1) { var previousPreview = _renderingSamples[index - 1]; queue.Enqueue(() => { RenderToTexture(generatedCamera, previousPreview); SampleClip(currentPreview); }); queue.Enqueue(() => { RenderToTexture(generatedCamera, currentPreview); }); } else { var previousPreview = _renderingSamples[index - 1]; queue.Enqueue(() => { RenderToTexture(generatedCamera, previousPreview); SampleClip(currentPreview); }); } } var cleanupQueue = new Queue<Action>(); cleanupQueue.Enqueue(() => Terminate(generatedCamera)); cleanupQueue.Enqueue(() => _onQueueTaskComplete.Invoke()); EeRenderingProcessorUnityCycle.AddToQueue(() => RunAsync(queue, cleanupQueue)); } private void SampleClip(EeRenderingSample eeRenderingSample) { WorkaroundAnimatedMaterialPropertiesIgnoredOnThirdSampling(); AnimationMode.BeginSampling(); PoseDummyUsing(eeRenderingSample.Clip); AnimationMode.EndSampling(); } private static void WorkaroundAnimatedMaterialPropertiesIgnoredOnThirdSampling() { // https://github.com/hai-vr/combo-gesture-expressions-av3/issues/268 // When in animation mode, for some reason the 3rd sampling will fail to apply any animated material properties // Waiting a for a certain number of frames will not help. // The workaround is to sample nothing in the same frame (why does that work?!) AnimationMode.BeginSampling(); AnimationMode.EndSampling(); } private void RenderToTexture(Camera generatedCamera, EeRenderingSample eeRenderingSample) { CaptureDummy(eeRenderingSample.RenderTexture, generatedCamera); eeRenderingSample.Callback.Invoke(eeRenderingSample); } private void RunAsync(Queue<Action> actions, Queue<Action> cleanupActions) { try { actions.Dequeue().Invoke(); if (actions.Count > 0 && !StopGenerating) { EeRenderingProcessorUnityCycle.AddToQueue(() => RunAsync(actions, cleanupActions)); } else { StartCleanupActions(cleanupActions); } } catch (Exception) { StartCleanupActions(cleanupActions); } } private void StartCleanupActions(Queue<Action> cleanupActions) { if (cleanupActions.Count > 0) { EeRenderingProcessorUnityCycle.AddToQueue(() => Cleanup(cleanupActions)); } } private void Cleanup(Queue<Action> cleanupActions) { try { cleanupActions.Dequeue().Invoke(); } finally { if (cleanupActions.Count > 0) { EeRenderingProcessorUnityCycle.AddToQueue(() => Cleanup(cleanupActions)); } } } private void PoseDummyUsing(AnimationClip clip) { AnimationMode.SampleAnimationClip(_previewSetup.Dummy.gameObject, clip, 1/60f); } private void CaptureDummy(Texture2D element, Camera generatedCamera) { _renderTexture = new RenderTexture(element.width, element.height, 24); RenderCamera(_renderTexture, generatedCamera); RenderTextureTo(_renderTexture, element); } private static void RenderCamera(RenderTexture renderTexture, Camera camera) { var originalRenderTexture = camera.targetTexture; var originalAspect = camera.aspect; try { camera.targetTexture = renderTexture; camera.aspect = (float) renderTexture.width / renderTexture.height; camera.Render(); } finally { camera.targetTexture = originalRenderTexture; camera.aspect = originalAspect; } } private static void RenderTextureTo(RenderTexture renderTexture, Texture2D texture2D) { RenderTexture.active = renderTexture; texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0); texture2D.Apply(); RenderTexture.active = null; } private void Terminate(Camera generatedCamera) { SceneView.RepaintAll(); AnimationMode.StopAnimationMode(); Object.DestroyImmediate(generatedCamera.gameObject); if (_autoHide != EeRenderingCommands.EeDummyAutoHide.DoNotHide && _previewSetup.AutoHide) { _previewSetup.Dummy.gameObject.SetActive(false); } } private Camera GenerateCamera() { var parentNullable = MaybeResolveAttachedParent(_previewSetup.GetEffectiveCameraConfig(_cameraIndex)); var effectiveCamera = _previewSetup.GetEffectiveCamera(_cameraIndex); var generatedCamera = Object.Instantiate(effectiveCamera, parentNullable == null ? effectiveCamera.transform : parentNullable, true); generatedCamera.gameObject.SetActive(true); return generatedCamera; } private Transform MaybeResolveAttachedParent(EePreviewAvatarCamera config) { if (!config.autoAttachToBone) return null; var possibleBone = _previewSetup.Dummy.GetBoneTransform(config.optionalAttachToBone); return possibleBone == null ? _previewSetup.Dummy.transform : possibleBone; } } public readonly struct EeRenderingSample { public readonly AnimationClip Clip; public readonly Texture2D RenderTexture; public readonly Action<EeRenderingSample> Callback; public EeRenderingSample(AnimationClip clip, Texture2D renderTexture, Action<EeRenderingSample> callback) { Clip = clip; RenderTexture = renderTexture; Callback = callback; } } internal static class EeRenderingProcessorUnityCycle { private static readonly Queue<Action> InternalActionQueue = new Queue<Action>(); private static bool _isInternalActionQueueRunning; private static bool _isEditorUpdateHooked; public static void AddToQueue(Action action) { if (!_isInternalActionQueueRunning) { if (!_isEditorUpdateHooked) { EditorApplication.update += OnEditorUpdate; _isEditorUpdateHooked = true; } _isInternalActionQueueRunning = true; } InternalActionQueue.Enqueue(action); } private static void OnEditorUpdate() { if (!_isInternalActionQueueRunning) return; // Animation sampling will not affect the blendshapes when the window is not focused. if (!IsUnityEditorWindowFocused()) return; if (InternalActionQueue.Count == 0) { _isInternalActionQueueRunning = false; return; } var action = InternalActionQueue.Dequeue(); action.Invoke(); } private static bool IsUnityEditorWindowFocused() { return UnityEditorInternal.InternalEditorUtility.isApplicationActive; } } }
35.397993
273
0.538265
[ "MIT" ]
SpiralP/combo-gesture-expressions-av3
Assets/Hai/ExpressionsEditor/Scripts/Editor/Internal/Modules/EeRendering.cs
21,168
C#
using System.Collections; using UnityEngine; using UnityEngine.AI; using WizardsCode.Ink; namespace WizardsCode.Character { /// <summary> /// A basic actor cue contains details of what an actor should do at upon a signal from the director. /// </summary> [CreateAssetMenu(fileName = "ActorCue", menuName = "Wizards Code/Actor/Cue")] public class ActorCue : ScriptableObject { [TextArea, SerializeField, Tooltip("A description of this actor cue.")] string m_Description; [SerializeField, Tooltip("Duration of this phase of this cue action. If 0 then it is unlimited.")] public float Duration = 5; [Header("Movement")] [SerializeField, Tooltip("The name of the mark the actor should move to on this cue.")] string markName; [SerializeField, Tooltip("Stop movement upon recieving this cue. Note that this will override the markName setting above, that is if this is set and markName is set then no movement will occur.")] bool m_StopMovement = false; [Header("Sound")] [SerializeField, Tooltip("Audio files for spoken lines")] public AudioClip audioClip; //TODO remove Ink sections to an InkActorCue object #if INK_PRESENT [Header("Ink")] [SerializeField, Tooltip("The name of the knot to jump to on this cue.")] string m_KnotName; [SerializeField, Tooltip("The name of the stitch to jump to on this cue.")] string m_StitchName; #endif internal BaseActorController m_Actor; internal NavMeshAgent m_Agent; internal bool m_AgentEnabled; /// <summary> /// Get or set the mark name, that is the name of an object in the scene the character should move to when this cue is prompted. /// Note that changing the Mark during execution of this cue will /// have no effect until it is prompted the next time. /// </summary> public string Mark { get { return markName; } set { markName = value; } } /// <summary> /// Prompt and actor to enact the actions identified in this cue. /// </summary> /// <returns>An optional coroutine that shouold be started by the calling MonoBehaviour</returns> public virtual IEnumerator Prompt(BaseActorController actor) { m_Actor = actor; ProcessMove(); ProcessAudio(); #if INK_PRESENT ProcessInk(); #endif return UpdateCoroutine(); } #if INK_PRESENT internal void ProcessInk() { if (!string.IsNullOrEmpty(m_KnotName) || !string.IsNullOrEmpty(m_StitchName)) { InkManager.Instance.ChoosePath(m_KnotName, m_StitchName); } } #endif internal virtual IEnumerator UpdateCoroutine() { if (m_Agent != null) { while (m_Agent.pathPending || (m_Agent.hasPath && m_Agent.remainingDistance > m_Agent.stoppingDistance)) { yield return new WaitForSeconds(0.3f); } m_Agent.enabled = m_AgentEnabled; } } /// <summary> /// If this cue has a mark defined move to it. /// </summary> void ProcessMove() { if (m_StopMovement) { m_Actor.StopMoving(); return; } if (!string.IsNullOrWhiteSpace(markName)) { m_Agent = m_Actor.GetComponent<NavMeshAgent>(); m_AgentEnabled = m_Agent.enabled; m_Agent.enabled = true; GameObject go = GameObject.Find(markName); if (go != null) { m_Agent.SetDestination(go.transform.position); } else { Debug.LogWarning(m_Actor.name + " has a mark set, but the mark doesn't exist in the scene. The name set is " + markName); } } } void ProcessAudio() { if (audioClip != null) { AudioSource source = m_Actor.GetComponent<AudioSource>(); source.clip = audioClip; source.Play(); } } } }
34.503817
205
0.550885
[ "MIT" ]
TheWizardsCode/Character
Assets/_Character/Character/Scripts/Runtime/ScriptableObjects/ActorCue.cs
4,520
C#
namespace Caliburn.Micro.Extras { using System; using System.Threading.Tasks; using Windows.UI.Popups; internal enum MessageBoxButton { OK = 0, OKCancel = 1, YesNoCancel = 3, YesNo = 4, } internal enum MessageBoxResult { None = 0, OK = 1, Cancel = 2, Yes = 6, No = 7, } internal static class MessageBox { public static async Task<MessageBoxResult> ShowAsync(string message, string caption = "", MessageBoxButton button = MessageBoxButton.OK) { var result = MessageBoxResult.None; var messageDialog = new MessageDialog(message, caption); if (button == MessageBoxButton.OK || button == MessageBoxButton.OKCancel) { messageDialog.Commands.Add(new UICommand("OK", cmd => result = MessageBoxResult.OK)); } if (button == MessageBoxButton.YesNo || button == MessageBoxButton.YesNoCancel) { messageDialog.Commands.Add(new UICommand("Yes", cmd => result = MessageBoxResult.Yes)); messageDialog.Commands.Add(new UICommand("No", cmd => result = MessageBoxResult.No)); } if (button == MessageBoxButton.OKCancel || button == MessageBoxButton.YesNoCancel) { messageDialog.Commands.Add(new UICommand("Cancel", cmd => result = MessageBoxResult.Cancel)); messageDialog.CancelCommandIndex = (uint) messageDialog.Commands.Count - 1; } await messageDialog.ShowAsync(); return result; } } }
35.6
146
0.600499
[ "MIT" ]
sokolinivan/Caliburn.Micro.Extras
src/Caliburn.Micro.Extras.WinRT45/MessageBox.cs
1,604
C#
using System; using System.Collections.Generic; using Highbyte.DotNet6502; namespace ConsoleTestPrograms { public class RunSimple { public static void Run() { // Test program // - adds values from two memory location // - divides it by 2 (rotate right one bit position) // - stores it in another memory location // Load input data into memory byte value1 = 12; byte value2 = 30; ushort value1Address = 0xd000; ushort value2Address = 0xd001; ushort resultAddress = 0xd002; var mem = new Memory(); mem[value1Address] = value1; mem[value2Address] = value2; // Load machine code into memory ushort codeAddress = 0xc000; ushort codeInsAddress = codeAddress; mem[codeInsAddress++] = 0xad; // LDA (Load Accumulator) mem[codeInsAddress++] = 0x00; // |-Lowbyte of $d000 mem[codeInsAddress++] = 0xd0; // |-Highbyte of $d000 mem[codeInsAddress++] = 0x18; // CLC (Clear Carry flag) mem[codeInsAddress++] = 0x6d; // ADC (Add with Carry, adds memory to accumulator) mem[codeInsAddress++] = 0x01; // |-Lowbyte of $d001 mem[codeInsAddress++] = 0xd0; // |-Highbyte of $d001 mem[codeInsAddress++] = 0x6a; // ROR (Rotate Right, rotates accumulator right one bit position) mem[codeInsAddress++] = 0x8d; // STA (Store Accumulator, store to accumulator to memory) mem[codeInsAddress++] = 0x02; // |-Lowbyte of $d002 mem[codeInsAddress++] = 0xd0; // |-Highbyte of $d002 mem[codeInsAddress++] = 0x00; // BRK (Break/Force Interrupt) - emulator configured to stop execution when reaching this instruction // Initialize emulator with CPU, memory, and execution parameters var computerBuilder = new ComputerBuilder(); computerBuilder .WithCPU() .WithStartAddress(codeAddress) .WithMemory(mem) .WithInstructionExecutedEventHandler( (s, e) => Console.WriteLine(OutputGen.GetLastInstructionDisassembly(e.CPU, e.Mem))) .WithExecOptions(options => { options.ExecuteUntilInstruction = OpCodeId.BRK; // Emulator will stop executing when a BRK instruction is reached. }); var computer = computerBuilder.Build(); // Run program computer.Run(); Console.WriteLine($"Execution stopped"); Console.WriteLine($"CPU state: {OutputGen.GetProcessorState(computer.CPU)}"); Console.WriteLine($"Stats: {computer.CPU.ExecState.InstructionsExecutionCount} instruction(s) processed, and used {computer.CPU.ExecState.CyclesConsumed} cycles."); // Print result byte result = mem[resultAddress]; Console.WriteLine($"Result: ({value1} + {value2}) / 2 = {result}"); } } }
46.970588
176
0.566061
[ "MIT" ]
highbyte/dotnet-6502
Examples/ConsoleTestPrograms/RunSimple.cs
3,196
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Rozamac.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool SignedIn { get { return ((bool)(this["SignedIn"])); } set { this["SignedIn"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool Admin { get { return ((bool)(this["Admin"])); } set { this["Admin"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string Port { get { return ((string)(this["Port"])); } set { this["Port"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string Ip { get { return ((string)(this["Ip"])); } set { this["Ip"] = value; } } } }
36.013333
151
0.543132
[ "MIT" ]
SymCors/HMI-Y.A
Rozamac/Properties/Settings.Designer.cs
2,703
C#
namespace CrudeObservatory.Abstractions.Models { public enum IntervalType { Periodic, } }
13.875
47
0.657658
[ "MPL-2.0" ]
jkoplo/CrudeObservatory
src/Libraries/CrudeObservatory.Abstractions/Models/IntervalType.cs
113
C#
// Copyright (c) 2020, Phoenix Contact GmbH & Co. KG // Licensed under the Apache License, Version 2.0 using System.ComponentModel; using System.Runtime.Serialization; namespace Moryx.Configuration { /// <summary> /// Base implementation of IConfig to reduce redundant code /// </summary> [DataContract] public class ConfigBase : UpdatableEntry, IConfig, IPersistentConfig { /// <inheritdoc /> bool IPersistentConfig.PersistDefaultConfig => PersistDefaultConfig; /// <see cref="IPersistentConfig"/> protected virtual bool PersistDefaultConfig => true; /// <summary> /// Current state of the config object /// </summary> [DataMember] public ConfigState ConfigState { get; set; } /// <summary> /// Exception message if load failed /// </summary> [ReadOnly(true)] public string LoadError { get; set; } /// <summary> /// Method called if no file was found and the config was generated /// </summary> protected internal virtual void Initialize() { } } }
27.878049
76
0.613298
[ "Apache-2.0" ]
1nf0rmagician/MORYX-Core
src/Moryx/Configuration/ConfigBase.cs
1,143
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using ZerochSharp.Models.Attributes; using ZerochSharp.Models.Boards.Restrictions; namespace ZerochSharp.Models.Boards { public class Board { internal const string BoardSettingPath = "boards"; [Key] public int Id { get; set; } [Required] public string BoardKey { get; set; } [Required] [SettingTxt("BBS_TITLE")] public string BoardName { get; set; } public string BoardCategory { get; set; } [NotMapped] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public List<Thread> Children { get; set; } [Required] [SettingTxt("BBS_NONAME_NAME")] public string BoardDefaultName { get; set; } [SettingTxt("BBS_SAMBATIME")] public string BoardSambaTime => 30.ToString(); [SettingTxt("BBS_SUBTITLE")] public string BoardSubTitle { get; set; } [SettingTxt("BBS_DELETE_NAME")] public string BoardDeleteName => "あぼーん"; [JsonIgnore] public string AutoRemovingPredicate { get; set; } [NotMapped] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string[] AutoArchivingPredicates => AutoRemovingPredicate?.Split(';', StringSplitOptions.RemoveEmptyEntries) ?? new string[] { }; [NotMapped] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public bool? IsArchivedChild { get; set; } [NotMapped] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public int? Page { get; set; } [NotMapped] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public int? ChildrenCount { get; set; } [JsonIgnore] [NotMapped] public IEnumerable<NgWord> ProhibitedWordCollection { get; private set; } [JsonIgnore] [NotMapped] public IEnumerable<RestrictedUser> RestrictedUserCollection { get; set; } public async Task InitializeForValidation(MainContext context) { ProhibitedWordCollection = await context.NgWords.Where(x => x.BoardKey == BoardKey || x.BoardKey == null).ToListAsync(); RestrictedUserCollection = await context.RestrictedUsers .Where(x => x.BoardKey == BoardKey || x.BoardKey == null) .ToListAsync(); } internal string GetLocalRule() { var path = $"{BoardSettingPath}/{BoardKey}/localrule.txt"; if (!File.Exists(path)) { return null; } return File.ReadAllText(path); } public bool IsRestricted(IEnumerable<string> ipAddress) { if (RestrictedUserCollection == null) { return false; } return RestrictedUserCollection.Any(x => x.IsMatchPattern(ipAddress)); } public bool HasProhibitedWords(string text) { if (ProhibitedWordCollection == null) { return false; } var splitTextLines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries); return ProhibitedWordCollection.Any(x => x.IsMatchPattern(splitTextLines)); } private bool CheckRegexPattern(IEnumerable<string> targetLines, string pattern) { var regexLine = pattern.Remove(0, "regex:".Length); if (!regexLine.StartsWith('/')) { return false; } regexLine = regexLine.Substring(1); var lastSepInd = regexLine.LastIndexOf('/'); if (lastSepInd < 0) { return false; } var options = regexLine.Substring(lastSepInd + 1); regexLine = regexLine.Substring(0, lastSepInd); var regex = new Regex(regexLine, CreateRegexOptions(options)); foreach (var line in targetLines) { if (regex.IsMatch(line)) { return true; } } return false; } private bool CheckTextRestricted(IEnumerable<string> ipAddress, string pattern) { var split = pattern.Split(new[] { '.', ':' }, StringSplitOptions.None); foreach (var ip in ipAddress) { var splitIp = ip.Split(new[] { '.', ':' }, StringSplitOptions.None); var length = Math.Min(splitIp.Length, split.Length); var isRestricted = true; for (int i = 0; i < length; i++) { if (split[i] != splitIp[i] && split[i] != "*") { isRestricted = false; } } if (isRestricted) { return true; } } return false; } private RegexOptions CreateRegexOptions(string options) { var opt = RegexOptions.ECMAScript; foreach (var item in options) { if (item == 'i') { opt |= RegexOptions.IgnoreCase; } } return opt; } } }
35.632911
144
0.555595
[ "MIT" ]
MysteryJump/zerochsharp
src/ZerochSharp/Models/Boards/Board.cs
5,640
C#
using System; using System.Xml.Serialization; namespace Microsoft.Crm.Sdk { [XmlType(Namespace = "http://schemas.microsoft.com/crm/2006/WebServices")] [Serializable] public class CrmFloat { private bool isNullField; private bool isNullFieldSpecified; private string formattedvalueField; private double valueField; public CrmFloat() { } public CrmFloat(double value) { this.Value = value; } public static CrmFloat Null { get { return new CrmFloat() { IsNull = true, IsNullSpecified = true }; } } public override bool Equals(object obj) { return obj is CrmFloat crmFloat && this.IsNull == crmFloat.IsNull && this.IsNullSpecified == crmFloat.IsNullSpecified && this.Value.Equals(crmFloat.Value); } public override int GetHashCode() { return this.Value.GetHashCode(); } [XmlAttribute] public bool IsNull { get { return this.isNullField; } set { this.isNullField = value; } } [XmlIgnore] public bool IsNullSpecified { get { return this.isNullFieldSpecified; } set { this.isNullFieldSpecified = value; } } [XmlAttribute] public string formattedvalue { get { return this.formattedvalueField; } set { this.formattedvalueField = value; } } [XmlText] public double Value { get { return this.valueField; } set { this.valueField = value; } } } }
21.918367
167
0.435754
[ "MIT" ]
develmax/Crm.Sdk.Core
Microsoft.Crm.Sdk/Sdk/CrmFloat.cs
2,150
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Windows.Media; using Microsoft.VisualStudio.Text; using NuGet; namespace NuGetConsole.Implementation.Console { internal interface IPrivateConsoleDispatcher : IConsoleDispatcher, IDisposable { event EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> ExecuteInputLine; void PostInputLine(InputLine inputLine); void PostKey(VsKeyInfo key); void CancelWaitKey(); } /// <summary> /// This class handles input line posting and command line dispatching/execution. /// </summary> internal class ConsoleDispatcher : IPrivateConsoleDispatcher { private readonly BlockingCollection<VsKeyInfo> _keyBuffer = new BlockingCollection<VsKeyInfo>(); private CancellationTokenSource _cancelWaitKeySource; private bool _isExecutingReadKey; /// <summary> /// The IPrivateWpfConsole instance this dispatcher works with. /// </summary> private IPrivateWpfConsole WpfConsole { get; set; } /// <summary> /// Child dispatcher based on host type. Its creation is postponed to Start(), so that /// a WpfConsole's dispatcher can be accessed while inside a host construction. /// </summary> private Dispatcher _dispatcher; private readonly object _lockObj = new object(); public event EventHandler StartCompleted; public event EventHandler StartWaitingKey; public ConsoleDispatcher(IPrivateWpfConsole wpfConsole) { UtilityMethods.ThrowIfArgumentNull(wpfConsole); this.WpfConsole = wpfConsole; } public bool IsExecutingCommand { get { return (_dispatcher != null) && _dispatcher.IsExecuting; } } public void PostKey(VsKeyInfo key) { if (key == null) { throw new ArgumentNullException("key"); } _keyBuffer.Add(key); } public bool IsExecutingReadKey { get { return _isExecutingReadKey; } } public bool IsKeyAvailable { get { // In our BlockingCollection<T> producer/consumer this is // not critical so no need for locking. return _keyBuffer.Count > 0; } } public void CancelWaitKey() { if (_isExecutingReadKey && !_cancelWaitKeySource.IsCancellationRequested) { _cancelWaitKeySource.Cancel(); } } public void AcceptKeyInput() { Debug.Assert(_dispatcher != null); if (_dispatcher != null && WpfConsole != null) { WpfConsole.BeginInputLine(); } } public VsKeyInfo WaitKey() { try { // raise the StartWaitingKey event on main thread RaiseEventSafe(StartWaitingKey); // set/reset the cancellation token _cancelWaitKeySource = new CancellationTokenSource(); _isExecutingReadKey = true; // blocking call VsKeyInfo key = _keyBuffer.Take(_cancelWaitKeySource.Token); return key; } catch (OperationCanceledException) { return null; } finally { _isExecutingReadKey = false; } } private void RaiseEventSafe(EventHandler handler) { if (handler != null) { Microsoft.VisualStudio.Shell.ThreadHelper.Generic.Invoke(() => handler(this, EventArgs.Empty)); } } public bool IsStartCompleted { get; private set; } #region IConsoleDispatcher public void Start() { // Only Start once lock (_lockObj) { if (_dispatcher == null) { IHost host = WpfConsole.Host; if (host == null) { throw new InvalidOperationException("Can't start Console dispatcher. Host is null."); } if (host is IAsyncHost) { _dispatcher = new AsyncHostConsoleDispatcher(this); } else { _dispatcher = new SyncHostConsoleDispatcher(this); } Task.Factory.StartNew( // gives the host a chance to do initialization works before the console starts accepting user inputs () => host.Initialize(WpfConsole) ).ContinueWith( task => { if (task.IsFaulted) { var exception = ExceptionUtility.Unwrap(task.Exception); WriteError(exception.Message); } if (host.IsCommandEnabled) { Microsoft.VisualStudio.Shell.ThreadHelper.Generic.Invoke(_dispatcher.Start); } RaiseEventSafe(StartCompleted); IsStartCompleted = true; }, TaskContinuationOptions.NotOnCanceled ); } } } private void WriteError(string message) { if (WpfConsole != null) { WpfConsole.Write(message + Environment.NewLine, Colors.Red, null); } } public void ClearConsole() { Debug.Assert(_dispatcher != null); if (_dispatcher != null) { _dispatcher.ClearConsole(); } } #endregion #region IPrivateConsoleDispatcher public event EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> ExecuteInputLine; void OnExecute(SnapshotSpan inputLineSpan, bool isComplete) { ExecuteInputLine.Raise(this, Tuple.Create(inputLineSpan, isComplete)); } public void PostInputLine(InputLine inputLine) { Debug.Assert(_dispatcher != null); if (_dispatcher != null) { _dispatcher.PostInputLine(inputLine); } } #endregion private abstract class Dispatcher { protected ConsoleDispatcher ParentDispatcher { get; private set; } protected IPrivateWpfConsole WpfConsole { get; private set; } private bool _isExecuting; public bool IsExecuting { get { return _isExecuting; } protected set { _isExecuting = value; WpfConsole.SetExecutionMode(_isExecuting); } } protected Dispatcher(ConsoleDispatcher parentDispatcher) { ParentDispatcher = parentDispatcher; WpfConsole = parentDispatcher.WpfConsole; } /// <summary> /// Process a input line. /// </summary> /// <param name="inputLine"></param> protected Tuple<bool, bool> Process(InputLine inputLine) { SnapshotSpan inputSpan = inputLine.SnapshotSpan; if (inputLine.Flags.HasFlag(InputLineFlag.Echo)) { WpfConsole.BeginInputLine(); if (inputLine.Flags.HasFlag(InputLineFlag.Execute)) { WpfConsole.WriteLine(inputLine.Text); inputSpan = WpfConsole.EndInputLine(true).Value; } else { WpfConsole.Write(inputLine.Text); } } if (inputLine.Flags.HasFlag(InputLineFlag.Execute)) { string command = inputLine.Text; bool isExecuted = WpfConsole.Host.Execute(WpfConsole, command, null); WpfConsole.InputHistory.Add(command); ParentDispatcher.OnExecute(inputSpan, isExecuted); return Tuple.Create(true, isExecuted); } return Tuple.Create(false, false); } public void PromptNewLine() { WpfConsole.Write(WpfConsole.Host.Prompt + (char)32); // 32 is the space WpfConsole.BeginInputLine(); } public void ClearConsole() { // When inputting commands if (WpfConsole.InputLineStart != null) { WpfConsole.Host.Abort(); // Clear constructing multi-line command WpfConsole.Clear(); PromptNewLine(); } else { WpfConsole.Clear(); } } public abstract void Start(); public abstract void PostInputLine(InputLine inputLine); } /// <summary> /// This class dispatches inputs for synchronous hosts. /// </summary> private class SyncHostConsoleDispatcher : Dispatcher { public SyncHostConsoleDispatcher(ConsoleDispatcher parentDispatcher) : base(parentDispatcher) { } public override void Start() { PromptNewLine(); } public override void PostInputLine(InputLine inputLine) { IsExecuting = true; try { if (Process(inputLine).Item1) { PromptNewLine(); } } finally { IsExecuting = false; } } } /// <summary> /// This class dispatches inputs for asynchronous hosts. /// </summary> private class AsyncHostConsoleDispatcher : Dispatcher { private Queue<InputLine> _buffer; private Marshaler _marshaler; public AsyncHostConsoleDispatcher(ConsoleDispatcher parentDispatcher) : base(parentDispatcher) { _marshaler = new Marshaler(this); } private bool IsStarted { get { return _buffer != null; } } public override void Start() { if (IsStarted) { // Can only start once... ConsoleDispatcher is already protecting this. throw new InvalidOperationException(); } _buffer = new Queue<InputLine>(); IAsyncHost asyncHost = WpfConsole.Host as IAsyncHost; if (asyncHost == null) { // ConsoleDispatcher is already checking this. throw new InvalidOperationException(); } asyncHost.ExecuteEnd += _marshaler.AsyncHost_ExecuteEnd; PromptNewLine(); } public override void PostInputLine(InputLine inputLine) { // The editor should be completely readonly unless started. Debug.Assert(IsStarted); if (IsStarted) { _buffer.Enqueue(inputLine); ProcessInputs(); } } private void ProcessInputs() { if (IsExecuting) { return; } if (_buffer.Count > 0) { InputLine inputLine = _buffer.Dequeue(); Tuple<bool, bool> executeState = Process(inputLine); if (executeState.Item1) { IsExecuting = true; if (!executeState.Item2) { // If NOT really executed, processing the same as ExecuteEnd event OnExecuteEnd(); } } } } private void OnExecuteEnd() { if (IsStarted) { // Filter out noise. A host could execute private commands. Debug.Assert(IsExecuting); IsExecuting = false; PromptNewLine(); ProcessInputs(); } } /// <summary> /// This private Marshaler marshals async host event to main thread so that the dispatcher /// doesn't need to worry about threading. /// </summary> private class Marshaler : Marshaler<AsyncHostConsoleDispatcher> { public Marshaler(AsyncHostConsoleDispatcher impl) : base(impl) { } public void AsyncHost_ExecuteEnd(object sender, EventArgs e) { Invoke(() => _impl.OnExecuteEnd()); } } } protected virtual void Dispose(bool disposing) { if (disposing) { if (_keyBuffer != null) { _keyBuffer.Dispose(); } if (_cancelWaitKeySource != null) { _cancelWaitKeySource.Dispose(); } } } void IDisposable.Dispose() { try { Dispose(true); } finally { GC.SuppressFinalize(this); } } ~ConsoleDispatcher() { Dispose(false); } } [Flags] internal enum InputLineFlag { Echo = 1, Execute = 2 } internal class InputLine { public SnapshotSpan SnapshotSpan { get; private set; } public string Text { get; private set; } public InputLineFlag Flags { get; private set; } public InputLine(string text, bool execute) { this.Text = text; this.Flags = InputLineFlag.Echo; if (execute) { this.Flags |= InputLineFlag.Execute; } } public InputLine(SnapshotSpan snapshotSpan) { this.SnapshotSpan = snapshotSpan; this.Text = snapshotSpan.GetText(); this.Flags = InputLineFlag.Execute; } } }
29.961612
125
0.474119
[ "Apache-2.0" ]
monoman/NugetCracker
Nuget/src/VsConsole/Console/Console/ConsoleDispatcher.cs
15,610
C#
 namespace DotNet.Core.SignalR.Models { public interface IPostRepository { System.Collections.Generic.List<Post> GetAll(); Post GetPost(int id); void AddPost(Post post); }}
23.222222
55
0.645933
[ "MIT" ]
moljac/Samples.DotNet.Core
JetBrains.IntelliJ.Rider/DotNet.Core/DotNet.Core.SignalRwithMVC/Models/IPostRepository.cs
211
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ApiViet.Helpers { class ParameterUtils { } }
14.230769
33
0.740541
[ "MIT" ]
TienDuyNGUYEN/APIViet
ApiViet/ApiViet/Helpers/ParameterUtils.cs
187
C#
using System; using System.Runtime.Serialization; using Melanchall.DryWetMidi.Common; namespace Melanchall.DryWetMidi.Smf { /// <summary> /// The exception that is thrown when the reading engine has encountered an invalid MIDI time /// code component (i.e. a value that doesn't belong to values of <see cref="MidiTimeCodeComponent"/>) /// during reading <see cref="MidiTimeCodeEvent"/>. /// </summary> [Serializable] public sealed class InvalidMidiTimeCodeComponentException : MidiException { #region Constants private const string ValueSerializationPropertyName = "Value"; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="InvalidMidiTimeCodeComponentException"/>. /// </summary> public InvalidMidiTimeCodeComponentException() { } /// <summary> /// Initializes a new instance of the <see cref="InvalidMidiTimeCodeComponentException"/> with /// the specified error message and invalid value that represents MIDI time code component. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="value">The value representing MIDI time code component that caused this exception.</param> public InvalidMidiTimeCodeComponentException(string message, byte value) : base(message) { Value = value; } /// <summary> /// Initializes a new instance of the <see cref="InvalidMidiTimeCodeComponentException"/> /// with serialized data. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized /// object data about the exception being thrown.</param> /// <param name="context">The <see cref="StreamingContext"/> that contains contextual information /// about the source or destination.</param> private InvalidMidiTimeCodeComponentException(SerializationInfo info, StreamingContext context) : base(info, context) { Value = info.GetByte(ValueSerializationPropertyName); } #endregion #region Properties /// <summary> /// Gets the value representing MIDI time code component that caused this exception. /// </summary> public byte Value { get; } #endregion #region Overrides /// <summary> /// Sets the <see cref="SerializationInfo"/> with information about the exception. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized /// object data about the exception being thrown.</param> /// <param name="context">The <see cref="StreamingContext"/> that contains contextual information /// about the source or destination.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { ThrowIfArgument.IsNull(nameof(info), info); info.AddValue(ValueSerializationPropertyName, Value); base.GetObjectData(info, context); } #endregion } }
36.954545
115
0.642989
[ "MIT" ]
Amalgam-Cloud/drywetmidi
DryWetMidi/Smf/Exceptions/InvalidMidiTimeCodeComponentException.cs
3,254
C#
using BlazorMobile.Common.Helpers; using BlazorMobile.Helper; using BlazorMobile.Interop; using BlazorMobile.Services; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Web; using Xamarin.Forms; [assembly: InternalsVisibleTo("BlazorMobile.UWP")] namespace BlazorMobile.Components { public class BlazorWebView : WebView, IBlazorWebView, IWebViewIdentity { private int _identity = -1; private EventHandler _onBlazorAppLaunched; event EventHandler IWebViewIdentity.OnBlazorAppLaunched { add { _onBlazorAppLaunched += value; } remove { _onBlazorAppLaunched -= value; } } void IWebViewIdentity.SendOnBlazorAppLaunched() { _onBlazorAppLaunched?.Invoke(this, EventArgs.Empty); } bool IWebViewIdentity.BlazorAppLaunched { get; set; } int IWebViewIdentity.GetWebViewIdentity() { return _identity; } ~BlazorWebView() { WebViewHelper.UnregisterWebView(this); WebApplicationFactory.BlazorAppNeedReload -= ReloadBlazorAppEvent; WebApplicationFactory.EnsureBlazorAppLaunchedOrReload -= EnsureBlazorAppLaunchedOrReload; } public BlazorWebView() { WebApplicationFactory.BlazorAppNeedReload += ReloadBlazorAppEvent; WebApplicationFactory.EnsureBlazorAppLaunchedOrReload += EnsureBlazorAppLaunchedOrReload; _identity = WebViewHelper.GenerateWebViewIdentity(); WebViewHelper.RegisterWebView(this); } private void ReloadBlazorAppEvent(object sender, EventArgs e) { WebViewHelper.InternalLaunchBlazorApp(this, true); } private void EnsureBlazorAppLaunchedOrReload(object sender, EventArgs e) { if (!((IWebViewIdentity)this).BlazorAppLaunched) { ReloadBlazorAppEvent(sender, e); } } public void LaunchBlazorApp() { WebViewHelper.LaunchBlazorApp(this); } public View GetView() { return this; } public void CallJSInvokableMethod(string assembly,string method, params object[] args) { WebViewHelper.CallJSInvokableMethod(assembly, method, args); } public void PostMessage<TArgs>(string messageName, TArgs args) { WebViewHelper.PostMessage(messageName, typeof(TArgs), new object[] { args }); } } }
27.958763
101
0.629794
[ "MIT" ]
Appizeo/Blazor.Xamarin
src/BlazorMobile/Components/BlazorWebView.cs
2,714
C#
using Android.App; using Android.Content.PM; using Android.OS; using System.Net; using System.Net.Sockets; namespace LagoaVista.DeviceSimulator.Droid { [Activity(Label = "@string/app_name", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; TcpClient _client; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } } }
30.230769
166
0.680662
[ "MIT" ]
LagoVista/MobileApps
src/LagoaVista.DeviceSimulator/LagoaVista.DeviceSimulator/LagoaVista.DeviceSimulator.Android/MainActivity.cs
788
C#
namespace NetMicro.Queues.Kafka.NFlags { public static class KafkaOptions { public const string GroupId = "kafka-group-id"; public const string BootstrapServers = "kafka-bootstrap-servers"; } }
27.75
73
0.689189
[ "MIT" ]
NetMicro/NetMicro
NetMicro.Queues.Kafka.NFlags/KafkaOptions.cs
224
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.AccessAnalyzer; using Amazon.AccessAnalyzer.Model; namespace Amazon.PowerShell.Cmdlets.IAMAA { /// <summary> /// Creates an archive rule for the specified analyzer. Archive rules automatically archive /// new findings that meet the criteria you define when you create the rule. /// /// /// <para> /// To learn about filter keys that you can use to create an archive rule, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-reference-filter-keys.html">IAM /// Access Analyzer filter keys</a> in the <b>IAM User Guide</b>. /// </para> /// </summary> [Cmdlet("New", "IAMAAArchiveRule", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("None")] [AWSCmdlet("Calls the AWS IAM Access Analyzer CreateArchiveRule API operation.", Operation = new[] {"CreateArchiveRule"}, SelectReturnType = typeof(Amazon.AccessAnalyzer.Model.CreateArchiveRuleResponse))] [AWSCmdletOutput("None or Amazon.AccessAnalyzer.Model.CreateArchiveRuleResponse", "This cmdlet does not generate any output." + "The service response (type Amazon.AccessAnalyzer.Model.CreateArchiveRuleResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class NewIAMAAArchiveRuleCmdlet : AmazonAccessAnalyzerClientCmdlet, IExecutor { #region Parameter AnalyzerName /// <summary> /// <para> /// <para>The name of the created analyzer.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String AnalyzerName { get; set; } #endregion #region Parameter Filter /// <summary> /// <para> /// <para>The criteria for the rule.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyCollection] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.Collections.Hashtable Filter { get; set; } #endregion #region Parameter RuleName /// <summary> /// <para> /// <para>The name of the rule to create.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String RuleName { get; set; } #endregion #region Parameter ClientToken /// <summary> /// <para> /// <para>A client token.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String ClientToken { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.AccessAnalyzer.Model.CreateArchiveRuleResponse). /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the RuleName parameter. /// The -PassThru parameter is deprecated, use -Select '^RuleName' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^RuleName' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.RuleName), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "New-IAMAAArchiveRule (CreateArchiveRule)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.AccessAnalyzer.Model.CreateArchiveRuleResponse, NewIAMAAArchiveRuleCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.RuleName; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.AnalyzerName = this.AnalyzerName; #if MODULAR if (this.AnalyzerName == null && ParameterWasBound(nameof(this.AnalyzerName))) { WriteWarning("You are passing $null as a value for parameter AnalyzerName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.ClientToken = this.ClientToken; if (this.Filter != null) { context.Filter = new Dictionary<System.String, Amazon.AccessAnalyzer.Model.Criterion>(StringComparer.Ordinal); foreach (var hashKey in this.Filter.Keys) { context.Filter.Add((String)hashKey, (Criterion)(this.Filter[hashKey])); } } #if MODULAR if (this.Filter == null && ParameterWasBound(nameof(this.Filter))) { WriteWarning("You are passing $null as a value for parameter Filter which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.RuleName = this.RuleName; #if MODULAR if (this.RuleName == null && ParameterWasBound(nameof(this.RuleName))) { WriteWarning("You are passing $null as a value for parameter RuleName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.AccessAnalyzer.Model.CreateArchiveRuleRequest(); if (cmdletContext.AnalyzerName != null) { request.AnalyzerName = cmdletContext.AnalyzerName; } if (cmdletContext.ClientToken != null) { request.ClientToken = cmdletContext.ClientToken; } if (cmdletContext.Filter != null) { request.Filter = cmdletContext.Filter; } if (cmdletContext.RuleName != null) { request.RuleName = cmdletContext.RuleName; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.AccessAnalyzer.Model.CreateArchiveRuleResponse CallAWSServiceOperation(IAmazonAccessAnalyzer client, Amazon.AccessAnalyzer.Model.CreateArchiveRuleRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS IAM Access Analyzer", "CreateArchiveRule"); try { #if DESKTOP return client.CreateArchiveRule(request); #elif CORECLR return client.CreateArchiveRuleAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String AnalyzerName { get; set; } public System.String ClientToken { get; set; } public Dictionary<System.String, Amazon.AccessAnalyzer.Model.Criterion> Filter { get; set; } public System.String RuleName { get; set; } public System.Func<Amazon.AccessAnalyzer.Model.CreateArchiveRuleResponse, NewIAMAAArchiveRuleCmdlet, object> Select { get; set; } = (response, cmdlet) => null; } } }
45.112211
283
0.608896
[ "Apache-2.0" ]
aws/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/AccessAnalyzer/Basic/New-IAMAAArchiveRule-Cmdlet.cs
13,669
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Runtime.CompilerServices; [assembly: Azure.Core.AzureResourceProviderNamespace("Microsoft.AppService")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] [assembly: InternalsVisibleTo("Azure.ResourceManager.AppService.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")]
101.2
404
0.93083
[ "MIT" ]
AikoBB/azure-sdk-for-net
sdk/websites/Azure.ResourceManager.AppService/src/Properties/AssemblyInfo.cs
1,012
C#
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation.Validators { using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; using FluentValidation.Internal; using Resources; using Results; public abstract class NoopPropertyValidator : IPropertyValidator { public IStringSource ErrorMessageSource { get { return null; } set { } } public virtual bool IsAsync { get { return false; } } public abstract IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context); public virtual Task<IEnumerable<ValidationFailure>> ValidateAsync(PropertyValidatorContext context) { return TaskHelpers.FromResult(Validate(context)); } public virtual ICollection<Func<object, object, object>> CustomMessageFormatArguments { get { return new List<Func<object, object, object>>(); } } public virtual bool SupportsStandaloneValidation { get { return false; } } public Func<object, object> CustomStateProvider { get { return null; } set { } } } }
32.192982
104
0.723161
[ "Apache-2.0" ]
Rocketmakers/FluentValidation
src/FluentValidation/Validators/NoopPropertyValidator.cs
1,835
C#
using System; using System.Collections.Generic; using System.Text; using Alexa.NET.Management.Api; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace Alexa.NET.Management.Skills { public class SkillSummary { [JsonProperty("lastUpdated")] public DateTime LastUpdated { get; set; } [JsonProperty("nameByLocale")] public Dictionary<string,string> NameByLocale { get; set; } [JsonProperty("stage"),JsonConverter(typeof(StringEnumConverter))] public SkillStage Stage { get; set; } [JsonProperty("apis")] public string[] Apis { get; set; } [JsonProperty("publicationStatus"),JsonConverter(typeof(StringEnumConverter))] public PublicationStatus Status { get; set; } [JsonProperty("skillId")] public string SkillId { get; set; } [JsonProperty("_links")] public Dictionary<string, SkillSummaryLink> Links { get; set; } } }
29.147059
96
0.680121
[ "MIT" ]
gberk/Alexa.NET.Management
Alexa.NET.Management/Skills/SkillSummary.cs
993
C#
using System; namespace Nucleo.EventArguments { [CLSCompliant(true)] public class DataCancelEventArgs<T> : DataEventArgs<T> { private bool _cancel = false; #region " Properties " public bool Cancel { get { return _cancel; } set { _cancel = value; } } #endregion #region " Constructors " public DataCancelEventArgs(T data) : base(data) { } public DataCancelEventArgs(T data, bool cancel) : base(data) { _cancel = cancel; } #endregion } [CLSCompliant(true)] public delegate void DataCancelEventHandler<T>(object sender, DataCancelEventArgs<T> e); }
14.452381
89
0.678748
[ "MIT" ]
brianmains/Nucleo.NET
src/Nucleo/EventArguments/DataCancelEventArgs.cs
607
C#
using System.Collections.Generic; /* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace org.camunda.bpm.model.bpmn.instance { /// <summary> /// @author Sebastian Menski /// </summary> public class ExpressionTest : BpmnModelElementInstanceTest { public virtual TypeAssumption TypeAssumption { get { return new TypeAssumption(typeof(BaseElement), false); } } public virtual ICollection<ChildElementAssumption> ChildElementAssumptions { get { return null; } } public virtual ICollection<AttributeAssumption> AttributesAssumptions { get { return null; } } } }
26.490566
80
0.729345
[ "Apache-2.0" ]
luizfbicalho/Camunda.NET
camunda-bpmn-model-net/src/test/java/org/camunda/bpm/model/bpmn/instance/ExpressionTest.cs
1,406
C#
// * // * Copyright (C) 2008 Roger Alsing : http://www.RogerAlsing.com // * // * This library is free software; you can redistribute it and/or modify it // * under the terms of the GNU Lesser General Public License 2.1 or later, as // * published by the Free Software Foundation. See the included license.txt // * or http://www.gnu.org/copyleft/lesser.html for details. // * // * using System; using System.Collections; namespace Alsing.SourceCode { /// <summary> /// A List containing patterns. /// this could be for example a list of keywords or operators /// </summary> public sealed class PatternList : IEnumerable { private readonly PatternCollection patterns = new PatternCollection(); /// <summary> /// Gets or Sets if this list contains case seinsitive patterns /// </summary> public bool CaseSensitive; /// <summary> /// For public use only /// </summary> public PatternCollection ComplexPatterns = new PatternCollection(); /// <summary> /// The name of the pattern list /// </summary> public string Name = ""; /// <summary> /// Gets or Sets if the patterns in this list should be case normalized /// </summary> public bool NormalizeCase; /// <summary> /// /// </summary> public PatternListList Parent; /// <summary> /// The parent spanDefinition of this list /// </summary> public SpanDefinition parentSpanDefinition; /// <summary> /// for public use only /// </summary> public Hashtable SimplePatterns = new Hashtable(); /// <summary> /// /// </summary> public Hashtable SimplePatterns1Char = new Hashtable(); /// <summary> /// For public use only /// </summary> public Hashtable SimplePatterns2Char = new Hashtable(); /// <summary> /// Gets or Sets the TextStyle that should be assigned to patterns in this list /// </summary> public TextStyle Style = new TextStyle(); /// <summary> /// /// </summary> public PatternList() { SimplePatterns = new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); } #region IEnumerable Members /// <summary> /// /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return patterns.GetEnumerator(); } #endregion /// <summary> /// /// </summary> /// <param name="Pattern"></param> /// <returns></returns> public Pattern Add(Pattern Pattern) { if (Parent != null && Parent.Parent != null && Parent.Parent.Parent != null) { Pattern.Separators = Parent.Parent.Parent.Separators; Parent.Parent.Parent.ChangeVersion(); } if (!Pattern.IsComplex && !Pattern.ContainsSeparator) { //store pattern in lookuptable if it is a simple pattern string s; if (Pattern.StringPattern.Length >= 2) s = Pattern.StringPattern.Substring(0, 2); else s = Pattern.StringPattern.Substring(0, 1) + " "; s = s.ToLowerInvariant(); if (Pattern.StringPattern.Length == 1) { SimplePatterns1Char[Pattern.StringPattern] = Pattern; } else { if (SimplePatterns2Char[s] == null) SimplePatterns2Char[s] = new PatternCollection(); var ar = (PatternCollection) SimplePatterns2Char[s]; ar.Add(Pattern); } if (CaseSensitive) SimplePatterns[Pattern.LowerStringPattern] = Pattern; else SimplePatterns[Pattern.StringPattern] = Pattern; } else { ComplexPatterns.Add(Pattern); } patterns.Add(Pattern); if (Pattern.Parent == null) Pattern.Parent = this; else { throw (new Exception("Pattern already assigned to another PatternList")); } return Pattern; } /// <summary> /// /// </summary> public void Clear() { patterns.Clear(); } } }
29.32716
89
0.511892
[ "MIT" ]
TrevorDArcyEvans/EllieWare
code/SyntaxBox/Alsing.SyntaxBox/Document/SyntaxDefinition/Pattern/PatternList.cs
4,751
C#
using System; using System.Collections.Generic; namespace ClassLibrary1 { public class Person { public Guid Id { get; set; } public string Title { get; set; } public string GivenNames { get; set; } public string FamilyName { get; set; } public string Spouse { get; set; } public List<string> Children { get; set; } public Address Address { get; set; } } }
25.117647
51
0.599532
[ "MIT" ]
moerwald/VerifyPlayground
ClassLibrary1/Person.cs
429
C#
/* _BEGIN_TEMPLATE_ { "id": "ULDA_Brann_HP3", "name": [ "恐龙追踪", "Dino Tracking" ], "text": [ "<b>被动英雄技能</b>\n在你的回合开始时,<b>发现</b>你要抽\n的牌。", "[x]<b>Passive Hero Power</b>\nAt the start of your turn,\n<b>Discover</b> which card\nyou draw." ], "cardClass": "HUNTER", "type": "HERO_POWER", "cost": 2, "rarity": null, "set": "ULDUM", "collectible": null, "dbfId": 57645 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_ULDA_Brann_HP3 : SimTemplate //* 恐龙追踪 Dino Tracking { //[x]<b>Passive Hero Power</b>At the start of your turn,<b>Discover</b> which cardyou draw. //<b>被动英雄技能</b>在你的回合开始时,<b>发现</b>你要抽的牌。 } }
23.344828
101
0.595273
[ "MIT" ]
chi-rei-den/Silverfish
cards/ULDUM/ULDA/Sim_ULDA_Brann_HP3.cs
785
C#