content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using Antlr4.Runtime; using LibProtection.Injections.Internals; namespace LibProtection.Injections { public sealed class Sql : AntlrLanguageProvider { private Sql() { } protected override Enum ConvertAntlrTokenType(int antlrTokenType) { return (SqlTokenType)antlrTokenType; } protected override Lexer CreateLexer(string text) { return new SQLLexer(new AntlrInputStream(text)); } public override bool TrySanitize(string text, Token context, out string sanitized) { switch (context.LanguageProvider) { case Sql _: if (TrySqlEncode(text, (SqlTokenType) context.Type, out sanitized)) { return true; } break; default: throw new ArgumentException($"Unsupported SQL island: {context}"); } sanitized = null; return false; } protected override bool IsTrivial(Enum type, string text) { switch ((SqlTokenType) type) { case SqlTokenType.Space: case SqlTokenType.NullLiteral: case SqlTokenType.FilesizeLiteral: case SqlTokenType.StartNationalStringLiteral: case SqlTokenType.StringLiteral: case SqlTokenType.DecimalLiteral: case SqlTokenType.HexadecimalLiteral: case SqlTokenType.RealLiteral: case SqlTokenType.NullSpecLiteral: return true; } return false; } private static bool TrySqlEncode(string text, SqlTokenType tokenType, out string encoded) { encoded = null; switch (tokenType) { case SqlTokenType.StringLiteral: encoded = text.Replace("'", "''"); return true; } return false; } } }
28.810811
97
0.522045
[ "MIT" ]
Daerius-rs/libprotection-dotnet
sources/LibProtection.Injections/LibProtection.Injections/Languages/Sql/Sql.cs
2,134
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="HtmlPreformatted.cs" company=""> // // </copyright> // <summary> // The html div. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace UX.Testing.Core.Controls { using System; /// <summary>The html div.</summary> public class HtmlPreformatted : HtmlControl { #region Public Properties /// <summary>Gets the html tag.</summary> public override HtmlTag HtmlTag { get { return HtmlTag.pre; } } /// <summary>Gets or sets Width.</summary> [Obsolete("Not supported in HTML5. Deprecated in HTML 4.01.")] public string Width { get { return this.GetAttribute("width"); } set { this.AddAttribute("width", value); } } #endregion } }
22.090909
121
0.443416
[ "MIT" ]
athlete1/UXTestingFrameworks
UX.Testing.Core/Controls/HtmlPreformatted.cs
974
C#
using System; namespace MAVN.Service.Referral.Contract.Events { /// <summary> /// Represents an event sent when property is purchased /// </summary> public class PropertyPurchaseReferralEvent { /// <summary> /// Represents the Id of the referrer /// </summary> public string ReferrerId { get; set; } /// <summary> /// Represents a timestamp of the referral /// </summary> public DateTime TimeStamp { get; set; } /// <summary> /// Represents a Vat Amount /// </summary> public decimal? VatAmount { get; set; } /// <summary> /// Represents a Selling Property Price /// </summary> public decimal? SellingPropertyPrice { get; set; } /// <summary> /// Represents a Net Property Price /// </summary> public decimal? NetPropertyPrice { get; set; } /// <summary> /// Represents a Discount Amount /// </summary> public decimal? DiscountAmount { get; set; } /// <summary> /// Represents a Calculated Commission Amount /// </summary> public decimal CalculatedCommissionAmount { get; set; } /// <summary> /// Represents a Currency Code of the amounts /// </summary> public string CurrencyCode { get; set; } /// <summary> /// Represents a referral's id /// </summary> public string ReferralId { get; set; } } }
27.125
63
0.546412
[ "MIT" ]
IliyanIlievPH/MAVN.Service.Referral
contract/MAVN.Service.Referral.Contract/Events/PropertyPurchaseReferralEvent.cs
1,519
C#
#if UNITY_2019_4_OR_NEWER using UnityEditor; using UnityEngine; using UnityEngine.UIElements; namespace StansAssets.Foundation.Editor { /// <summary> /// Editor related UI Toolkit utility methods. /// </summary> public static class UIToolkitEditorUtility { /// <summary> /// Helper method to Clone VisualTreeAsset into the target and apply uss styles including the skin. /// For example if you provide path `Assets/MyWindow/AwesomeTab` the following will happen: /// * The `Assets/MyWindow/AwesomeTab.uxml` cloned into the `target` /// * The `Assets/MyWindow/AwesomeTab.uss` style is applied for the `target` if file exists. /// * The `Assets/MyWindow/AwesomeDark.uss` or `Assets/MyWindow/AwesomeLight.uss` (depends on current editor skin option) /// style is applied for the `target` if file exists. /// </summary> /// <param name="target">The target to clone visual tree and apply styles to.</param> /// <param name="path">The VisualTreeAsset path without extension. </param> public static void CloneTreeAndApplyStyle(VisualElement target, string path) { var uxmlPath = $"{path}.uxml"; var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxmlPath); if (visualTree == null) { Debug.LogError($"Failed to load VisualTreeAsset at path: {uxmlPath}"); return; } visualTree.CloneTree(target); ApplyStyle(target, path); } /// <summary> /// Helper method to Apply Style & Skin style to the target. /// For example if you provide path `Assets/MyWindow/AwesomeTab` the following styles will apply: /// * `Assets/MyWindow/AwesomeTab.uss` if file exists. /// * `Assets/MyWindow/AwesomeDark.uss` or `Assets/MyWindow/AwesomeLight.uss` (depends on current editor skin option) if file exists. /// </summary> /// <param name="target">The target to apply styles to.</param> /// <param name="path">The StyleSheet path without extension. </param> public static void ApplyStyle(VisualElement target, string path) { var stylesheet = AssetDatabase.LoadAssetAtPath<StyleSheet>($"{path}.uss"); var ussSkinPath = EditorGUIUtility.isProSkin ? $"{path}Dark.uss" : $"{path}Light.uss"; var skitStylesheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(ussSkinPath); if(stylesheet != null) target.styleSheets.Add(stylesheet); if(skitStylesheet != null) target.styleSheets.Add(skitStylesheet); } internal static void ApplyStyleForInternalControl<T>(T target) where T : VisualElement { var name = typeof(T).Name; ApplyStyleForInternalControl(target, name); } internal static void ApplyStyleForInternalControl(VisualElement target, string name) { ApplyStyle(target, $"{FoundationPackage.UIToolkitControlsPath}/{name}/{name}"); } } } #endif
43.342466
141
0.630531
[ "MIT" ]
StansAssets/com.stansassets.foundation
Editor/EditorUtilities/UIToolkitEditorUtility.cs
3,164
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Automation.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Automation; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// The parameters supplied to the create or update automation account /// operation. /// </summary> [Rest.Serialization.JsonTransformation] public partial class AutomationAccountCreateOrUpdateParameters { /// <summary> /// Initializes a new instance of the /// AutomationAccountCreateOrUpdateParameters class. /// </summary> public AutomationAccountCreateOrUpdateParameters() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// AutomationAccountCreateOrUpdateParameters class. /// </summary> /// <param name="sku">Gets or sets account SKU.</param> /// <param name="name">Gets or sets name of the resource.</param> /// <param name="location">Gets or sets the location of the /// resource.</param> /// <param name="tags">Gets or sets the tags attached to the /// resource.</param> public AutomationAccountCreateOrUpdateParameters(Sku sku = default(Sku), string name = default(string), string location = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>)) { Sku = sku; Name = name; Location = location; Tags = tags; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets account SKU. /// </summary> [JsonProperty(PropertyName = "properties.sku")] public Sku Sku { get; set; } /// <summary> /// Gets or sets name of the resource. /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Gets or sets the location of the resource. /// </summary> [JsonProperty(PropertyName = "location")] public string Location { get; set; } /// <summary> /// Gets or sets the tags attached to the resource. /// </summary> [JsonProperty(PropertyName = "tags")] public IDictionary<string, string> Tags { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Sku != null) { Sku.Validate(); } } } }
33.2
219
0.594578
[ "MIT" ]
AzureAutomationTeam/azure-sdk-for-net
src/SDKs/Automation/Management.Automation/Generated/Models/AutomationAccountCreateOrUpdateParameters.cs
3,320
C#
namespace Sim1 { partial class WobblerTestFrame { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.label1 = new System.Windows.Forms.Label(); this.Speed = new System.Windows.Forms.TrackBar(); this.label2 = new System.Windows.Forms.Label(); this.Shape = new System.Windows.Forms.TrackBar(); this.label3 = new System.Windows.Forms.Label(); this.Mod = new System.Windows.Forms.TrackBar(); this.label4 = new System.Windows.Forms.Label(); this.Phase = new System.Windows.Forms.TrackBar(); this.button1 = new System.Windows.Forms.Button(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.DispUpdate = new System.Windows.Forms.Timer(this.components); this.EnvUpdate = new System.Windows.Forms.Timer(this.components); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.Speed)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.Shape)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.Mod)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.Phase)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.flowLayoutPanel1); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.pictureBox1); this.splitContainer1.Size = new System.Drawing.Size(763, 635); this.splitContainer1.SplitterDistance = 412; this.splitContainer1.TabIndex = 0; // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.label1); this.flowLayoutPanel1.Controls.Add(this.Speed); this.flowLayoutPanel1.Controls.Add(this.label2); this.flowLayoutPanel1.Controls.Add(this.Shape); this.flowLayoutPanel1.Controls.Add(this.label3); this.flowLayoutPanel1.Controls.Add(this.Mod); this.flowLayoutPanel1.Controls.Add(this.label4); this.flowLayoutPanel1.Controls.Add(this.Phase); this.flowLayoutPanel1.Controls.Add(this.button1); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.TopDown; this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(412, 635); this.flowLayoutPanel1.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(3, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(49, 17); this.label1.TabIndex = 1; this.label1.Text = "Speed"; this.label1.Click += new System.EventHandler(this.label1_Click); // // Speed // this.Speed.AutoSize = false; this.Speed.Location = new System.Drawing.Point(3, 20); this.Speed.Maximum = 255; this.Speed.Name = "Speed"; this.Speed.Size = new System.Drawing.Size(358, 25); this.Speed.TabIndex = 0; this.Speed.TickStyle = System.Windows.Forms.TickStyle.None; this.Speed.Value = 220; this.Speed.Scroll += new System.EventHandler(this.Attack_Scroll); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(3, 48); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(49, 17); this.label2.TabIndex = 9; this.label2.Text = "Shape"; // // Shape // this.Shape.AutoSize = false; this.Shape.Location = new System.Drawing.Point(3, 68); this.Shape.Maximum = 255; this.Shape.Name = "Shape"; this.Shape.Size = new System.Drawing.Size(358, 25); this.Shape.TabIndex = 1; this.Shape.TickStyle = System.Windows.Forms.TickStyle.None; this.Shape.Value = 170; this.Shape.Scroll += new System.EventHandler(this.Decay_Scroll); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(3, 96); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(35, 17); this.label3.TabIndex = 10; this.label3.Text = "Mod"; // // Mod // this.Mod.AutoSize = false; this.Mod.Location = new System.Drawing.Point(3, 116); this.Mod.Maximum = 255; this.Mod.Name = "Mod"; this.Mod.Size = new System.Drawing.Size(358, 25); this.Mod.TabIndex = 2; this.Mod.TickStyle = System.Windows.Forms.TickStyle.None; this.Mod.Value = 50; this.Mod.Scroll += new System.EventHandler(this.Sustain_Scroll); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(3, 144); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(48, 17); this.label4.TabIndex = 11; this.label4.Text = "Phase"; // // Phase // this.Phase.AutoSize = false; this.Phase.Location = new System.Drawing.Point(3, 164); this.Phase.Maximum = 255; this.Phase.Name = "Phase"; this.Phase.Size = new System.Drawing.Size(358, 25); this.Phase.TabIndex = 3; this.Phase.TickStyle = System.Windows.Forms.TickStyle.None; this.Phase.Value = 60; this.Phase.Scroll += new System.EventHandler(this.Release_Scroll); // // button1 // this.button1.Location = new System.Drawing.Point(10, 202); this.button1.Margin = new System.Windows.Forms.Padding(10); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(325, 39); this.button1.TabIndex = 8; this.button1.Text = "Reset"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); this.button1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.button1_MouseDown); this.button1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.button1_MouseUp); // // pictureBox1 // this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(347, 635); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint); this.pictureBox1.Resize += new System.EventHandler(this.pictureBox1_Resize); // // DispUpdate // this.DispUpdate.Enabled = true; this.DispUpdate.Interval = 30; this.DispUpdate.Tick += new System.EventHandler(this.DispUpdate_Tick); // // EnvUpdate // this.EnvUpdate.Enabled = true; this.EnvUpdate.Interval = 10; this.EnvUpdate.Tick += new System.EventHandler(this.EnvUpdate_Tick); // // WobblerTestFrame // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(763, 635); this.CloseButton = false; this.CloseButtonVisible = false; this.Controls.Add(this.splitContainer1); this.Name = "WobblerTestFrame"; this.Text = "TINRS EdgeCutter Test Framework"; this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.Speed)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.Shape)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.Mod)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.Phase)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.TrackBar Speed; private System.Windows.Forms.TrackBar Shape; private System.Windows.Forms.TrackBar Mod; private System.Windows.Forms.TrackBar Phase; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Timer DispUpdate; private System.Windows.Forms.Timer EnvUpdate; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; } }
46.29845
107
0.590289
[ "MIT" ]
ThisIsNotRocketScience/Eurorack-KDS
VIsualStudio_EuroRackSimulator/Sim1/TINRS Wobbler TestFrame.Designer.cs
11,947
C#
// AbstractGateController using ClubPenguin.Analytics; using ClubPenguin.ContentGates; using ClubPenguin.Core; using ClubPenguin.UI; using Disney.Kelowna.Common; using Disney.LaunchPadFramework; using Disney.MobileNetwork; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class AbstractGateController : IContentInterruption { private GameObject instantiatedPrefab; internal GatePrefabController gatePrefabController; private Transform parentTransform; private GateData gateData; protected abstract PrefabContentKey GateContentKey { get; } public event System.Action OnReturn; public event System.Action OnContinue; protected abstract void prepGate(); protected abstract void onValueChanged(string strAnswer); protected abstract void onSubmitClicked(); protected abstract string getAnalyticsContext(); public void Show(Transform parentTransform = null) { CPDataEntityCollection cPDataEntityCollection = Service.Get<CPDataEntityCollection>(); if (!cPDataEntityCollection.TryGetComponent(cPDataEntityCollection.LocalPlayerHandle, out gateData)) { gateData = cPDataEntityCollection.AddComponent<GateData>(cPDataEntityCollection.LocalPlayerHandle); gateData.GateStatus = new Dictionary<Type, bool>(); } bool value = false; gateData.GateStatus.TryGetValue(GetType(), out value); this.parentTransform = parentTransform; if (value) { Continue(); } else { initializePopup(GateContentKey); } } private void initializePopup(PrefabContentKey popupKey) { CoroutineRunner.Start(loadPopupFromPrefab(popupKey), this, "loadPopupFromPrefab"); } private IEnumerator loadPopupFromPrefab(PrefabContentKey popupKey) { AssetRequest<GameObject> assetRequest = Content.LoadAsync(popupKey); yield return assetRequest; instantiatedPrefab = UnityEngine.Object.Instantiate(assetRequest.Asset); if (parentTransform != null) { instantiatedPrefab.transform.SetParent(parentTransform, worldPositionStays: false); } gatePrefabController = instantiatedPrefab.GetComponent<GatePrefabController>(); try { gatePrefabController.SubmitButton.onClick.AddListener(onSubmitClicked); gatePrefabController.CloseButton.onClick.AddListener(onCloseClicked); gatePrefabController.ErrorIcon.gameObject.SetActive(value: false); prepGate(); gatePrefabController.AnswerInputField.onValueChanged.AddListener(onValueChanged); if ((bool)GameObject.Find("TopCanvas")) { Service.Get<EventDispatcher>().DispatchEvent(new PopupEvents.ShowTopPopup(instantiatedPrefab, destroyPopupOnBackPressed: false, scaleToFit: true, "Accessibility.Popup.Title.AgeGate")); } else { Service.Get<EventDispatcher>().DispatchEvent(new PopupEvents.ShowPopup(instantiatedPrefab, destroyPopupOnBackPressed: false, scaleToFit: true, "Accessibility.Popup.Title.AgeGate")); } } catch { Log.LogErrorFormatted(this, "Missing key elements from prefab for {0}\n CloseButton: {1}\n SubmitButton: {2}\n ErrorIcon: {3}", popupKey, gatePrefabController.CloseButton, gatePrefabController.SubmitButton, gatePrefabController.ErrorIcon); Return(); } yield return null; } protected void handleGateSuccess() { if (gateData.GateStatus.ContainsKey(GetType())) { gateData.GateStatus[GetType()] = true; } else { gateData.GateStatus.Add(GetType(), value: true); } UnityEngine.Object.Destroy(instantiatedPrefab); Continue(); } protected void handleGateFailure() { UnityEngine.Object.Destroy(instantiatedPrefab); Return(); } private void onCloseClicked() { Service.Get<ICPSwrveService>().Action("game." + getAnalyticsContext(), "cancelled"); UnityEngine.Object.Destroy(instantiatedPrefab); Return(); } protected void Continue() { if (this.OnContinue != null) { this.OnContinue(); } } protected void Return() { if (this.OnReturn != null) { this.OnReturn(); } } }
27.375
242
0.771689
[ "MIT" ]
smdx24/CPI-Source-Code
ClubPenguin.ContentGates/AbstractGateController.cs
3,942
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// GameObject Grid /// this is not a good OO design /// it is designed to show what the ECS version is doing in way that is readable /// for people who do ECS yet /// </summary> public class GOGrid : MonoBehaviour { public Vector2Int size = new Vector2Int(10,10); public float zLive = -1; public Transform holder; public GOCell prefabCell; public Vector2 _offset; public Vector2 _scale ; GOCell[,] _cells; public bool[] stay = new bool[10]; public bool[] born = new bool[10]; void Start() { _scale = Vector2.one / size; _offset = ((-1 * Vector2.one) + _scale)/2; _cells = new GOCell[size.x+2,size.y+2]; var cellLocalScale = new Vector3(_scale.x,_scale.y,_scale.x); for (int i = 0; i < size.x+2; i++) { for (int j = 0; j < size.y+2; j++) { var c = Instantiate(prefabCell, holder); var pos = new Vector3((i-1) * _scale.x + _offset.x, (j-1) * _scale.y + _offset.y, zLive); c.transform.localScale = cellLocalScale; c.transform.localPosition = pos; c.name += new Vector2Int(i, j); c.live = false; _cells[i, j] = c; } } RPentonomio((size+2*Vector2Int.one)/2); stay[3] = stay[4] = true; // includes self in count born[3] = true; } void RPentonomio(Vector2Int center) { _cells[center.x, center.y].live = true; _cells[center.x, center.y+1].live = true; _cells[center.x+1, center.y+1].live = true; _cells[center.x, center.y-1].live = true; _cells[center.x-1, center.y].live = true; } void Update() { //this is done by GenerateNextStateSystem in ECS version for (int i = 1; i < size.x + 1; i++) { for (int j = 1; j < size.y + 1; j++) { int count = 0; for (int k = -1; k < 2; k++) { for (int l = -1; l < 2; l++) { if (_cells[i + k, j + l].live) count++; } } _cells[i, j].nextState = _cells[i, j].live ? stay[count] : born[count]; } } //this is done by UpdateLiveSystem in ECS version for (int i = 1; i < size.x + 1; i++) { for (int j = 1; j < size.y + 1; j++) { _cells[i, j].live = _cells[i, j].nextState; } } } }
35.191781
105
0.50798
[ "MIT" ]
ryuuguu/Unity-ECS-Life
Assets/Life/GOLife/GOGrid.cs
2,571
C#
namespace coreLearn.Protocol { public class Customer { public string EmailAddress { get; set; } public string FirstName { get; set; } public int Id { get; set; } public string LastName { get; set; } public string TelephoneNumber { get; set; } } }
27.090909
51
0.597315
[ "MIT" ]
sanketss84/coreLearn
coreLearn.Protocol/Customer.cs
298
C#
using System; using Microsoft.Practices.Unity; using System.Collections.Generic; namespace Alphamosaik.Common.UI.Infrastructure { public class ScreenFactoryRegistry : IScreenFactoryRegistry { #region Properties protected IUnityContainer Container { get; set; } protected IDictionary<ScreenKeyType, Type> ScreenFactoryCollection { get; set; } #endregion #region Constructors public ScreenFactoryRegistry(IUnityContainer container) { this.Container = container; this.ScreenFactoryCollection = new Dictionary<ScreenKeyType, Type>(); } #endregion #region Get public IScreenFactory Get(ScreenKeyType screenType) { IScreenFactory screenFactory = null; if (this.HasFactory(screenType)) { Type registeredScreenFactory = ScreenFactoryCollection[screenType]; screenFactory = (IScreenFactory)Container.Resolve(registeredScreenFactory); } return screenFactory; } #endregion #region Register public void Register(ScreenKeyType screenType, Type registeredScreenFactoryType) { if (!HasFactory(screenType)) this.ScreenFactoryCollection.Add(screenType, registeredScreenFactoryType); } #endregion #region HasFactory public bool HasFactory(ScreenKeyType screenType) { return (this.ScreenFactoryCollection.ContainsKey(screenType)); } #endregion } }
26.295082
91
0.637781
[ "MIT" ]
enriqueescobar-askida/Kinito.Mosaik.Common
Alphamosaik.Common.UI.Infrastructure/Screen Framework/ScreenFactoryRegistry.cs
1,604
C#
using Novacta.Documentation.CodeExamples; using System; namespace Novacta.Analytics.CodeExamples { public class AdditionExample0 : ICodeExample { public void Main() { // Create the left operand. var data = new double[6] { 0, 2, 4, 1, 3, 5, }; var left = DoubleMatrix.Dense(2, 3, data, StorageOrder.RowMajor); Console.WriteLine("left ="); Console.WriteLine(left); // Create the right operand. data = new double[6] { 0, 20, 40, 10, 30, 50, }; var right = DoubleMatrix.Dense(2, 3, data, StorageOrder.RowMajor); Console.WriteLine("right ="); Console.WriteLine(right); // Compute the sum of left and right. var result = left + right; Console.WriteLine(); Console.WriteLine("left + right ="); Console.WriteLine(result); // In .NET languages that do not support overloaded operators, // you can use the alternative methods named Add. result = DoubleMatrix.Add(left, right); Console.WriteLine(); Console.WriteLine("DoubleMatrix.Add(left, right) returns"); Console.WriteLine(); Console.WriteLine(result); // Both operators and alternative methods are overloaded to // support read-only matrix arguments. // Compute the sum using a read-only wrapper of left. ReadOnlyDoubleMatrix readOnlyLeft = left.AsReadOnly(); result = readOnlyLeft + right; Console.WriteLine(); Console.WriteLine("readOnlyLeft + right ="); Console.WriteLine(result); } } }
33.345455
78
0.54253
[ "MIT" ]
Novacta/analytics
src/Novacta.Analytics.CodeExamples/AdditionExample0.cs
1,836
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using EnvDTE; using Microsoft.VisualStudio.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Threading; using NuGet.Common; using NuGet.Configuration; using NuGet.PackageManagement; using NuGet.PackageManagement.VisualStudio; using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Packaging.PackageExtraction; using NuGet.Packaging.Signing; using NuGet.ProjectManagement; using NuGet.Protocol.Core.Types; using NuGet.Resolver; using NuGet.Versioning; using NuGet.VisualStudio.Implementation.Resources; using NuGet.VisualStudio.Telemetry; using Task = System.Threading.Tasks.Task; namespace NuGet.VisualStudio { [Export(typeof(IVsPackageInstaller))] [Export(typeof(IVsPackageInstaller2))] public class VsPackageInstaller : IVsPackageInstaller2 { private readonly ISourceRepositoryProvider _sourceRepositoryProvider; private readonly ISettings _settings; private readonly IVsSolutionManager _solutionManager; private readonly IDeleteOnRestartManager _deleteOnRestartManager; private bool _isCPSJTFLoaded; private readonly INuGetTelemetryProvider _telemetryProvider; // Reason it's lazy<object> is because we don't want to load any CPS assemblies until // we're really going to use any of CPS api. Which is why we also don't use nameof or typeof apis. [Import("Microsoft.VisualStudio.ProjectSystem.IProjectServiceAccessor")] private Lazy<object> ProjectServiceAccessor { get; set; } private JoinableTaskFactory PumpingJTF { get; set; } [ImportingConstructor] public VsPackageInstaller( ISourceRepositoryProvider sourceRepositoryProvider, ISettings settings, IVsSolutionManager solutionManager, IDeleteOnRestartManager deleteOnRestartManager, INuGetTelemetryProvider telemetryProvider) { _sourceRepositoryProvider = sourceRepositoryProvider; _settings = settings; _solutionManager = solutionManager; _deleteOnRestartManager = deleteOnRestartManager; _isCPSJTFLoaded = false; _telemetryProvider = telemetryProvider; PumpingJTF = new PumpingJTF(NuGetUIThreadHelper.JoinableTaskFactory); } private void RunJTFWithCorrectContext(Project project, Func<Task> asyncTask) { if (!_isCPSJTFLoaded) { NuGetUIThreadHelper.JoinableTaskFactory.Run(async () => { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); IVsHierarchy vsHierarchy = await project.ToVsHierarchyAsync(); if (vsHierarchy != null && VsHierarchyUtility.IsCPSCapabilityCompliant(vsHierarchy)) { // Lazy load the CPS enabled JoinableTaskFactory for the UI. NuGetUIThreadHelper.SetJoinableTaskFactoryFromService(ProjectServiceAccessor.Value as IProjectServiceAccessor); PumpingJTF = new PumpingJTF(NuGetUIThreadHelper.JoinableTaskFactory); _isCPSJTFLoaded = true; } }); } PumpingJTF.Run(asyncTask); } public void InstallLatestPackage( string source, Project project, string packageId, bool includePrerelease, bool ignoreDependencies) { try { RunJTFWithCorrectContext(project, () => InstallPackageAsync( source, project, packageId, version: null, includePrerelease: includePrerelease, ignoreDependencies: ignoreDependencies)); } catch (Exception exception) { _telemetryProvider.PostFault(exception, typeof(VsPackageInstaller).FullName); throw; } } public void InstallPackage(string source, Project project, string packageId, Version version, bool ignoreDependencies) { try { NuGetVersion semVer = null; if (version != null) { semVer = new NuGetVersion(version); } RunJTFWithCorrectContext(project, () => InstallPackageAsync( source, project, packageId, version: semVer, includePrerelease: false, ignoreDependencies: ignoreDependencies)); } catch (Exception exception) { _telemetryProvider.PostFault(exception, typeof(VsPackageInstaller).FullName); throw; } } public void InstallPackage(string source, Project project, string packageId, string version, bool ignoreDependencies) { try { NuGetVersion semVer = null; if (!string.IsNullOrEmpty(version)) { NuGetVersion.TryParse(version, out semVer); } RunJTFWithCorrectContext(project, () => InstallPackageAsync( source, project, packageId, version: semVer, includePrerelease: false, ignoreDependencies: ignoreDependencies)); } catch (Exception exception) { _telemetryProvider.PostFault(exception, typeof(VsPackageInstaller).FullName); throw; } } private Task InstallPackageAsync(string source, Project project, string packageId, NuGetVersion version, bool includePrerelease, bool ignoreDependencies) { IEnumerable<string> sources = null; if (!string.IsNullOrEmpty(source) && !StringComparer.OrdinalIgnoreCase.Equals("All", source)) // "All" was supported in V2 { sources = new[] { source }; } var toInstall = new List<PackageIdentity> { new PackageIdentity(packageId, version) }; var projectContext = new VSAPIProjectContext { PackageExtractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv2, PackageExtractionBehavior.XmlDocFileSaveMode, ClientPolicyContext.GetClientPolicy(_settings, NullLogger.Instance), NullLogger.Instance) }; return InstallInternalAsync(project, toInstall, GetSources(sources), projectContext, includePrerelease, ignoreDependencies, CancellationToken.None); } public void InstallPackage(IPackageRepository repository, Project project, string packageId, string version, bool ignoreDependencies, bool skipAssemblyReferences) { // It would be really difficult for anyone to use this method throw new NotSupportedException(); } public void InstallPackagesFromRegistryRepository(string keyName, bool isPreUnzipped, bool skipAssemblyReferences, Project project, IDictionary<string, string> packageVersions) { InstallPackagesFromRegistryRepository(keyName, isPreUnzipped, skipAssemblyReferences, ignoreDependencies: true, project: project, packageVersions: packageVersions); } public void InstallPackagesFromRegistryRepository(string keyName, bool isPreUnzipped, bool skipAssemblyReferences, bool ignoreDependencies, Project project, IDictionary<string, string> packageVersions) { if (string.IsNullOrEmpty(keyName)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(keyName)); } if (project == null) { throw new ArgumentNullException(nameof(project)); } if (packageVersions == null || !packageVersions.Any()) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(packageVersions)); } try { RunJTFWithCorrectContext(project, async () => { // HACK !!! : This is a hack for PCL projects which send isPreUnzipped = true, but their package source // (located at C:\Program Files (x86)\Microsoft SDKs\NuGetPackages) follows the V3 // folder version format. if (isPreUnzipped) { var isProjectJsonProject = await EnvDTEProjectUtility.HasBuildIntegratedConfig(project); isPreUnzipped = isProjectJsonProject ? false : isPreUnzipped; } // create a repository provider with only the registry repository var repoProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider); repoProvider.AddFromRegistry(keyName, isPreUnzipped); var toInstall = GetIdentitiesFromDict(packageVersions); // Skip assembly references and disable binding redirections should be done together var disableBindingRedirects = skipAssemblyReferences; var projectContext = new VSAPIProjectContext(skipAssemblyReferences, disableBindingRedirects) { PackageExtractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv2, PackageExtractionBehavior.XmlDocFileSaveMode, ClientPolicyContext.GetClientPolicy(_settings, NullLogger.Instance), NullLogger.Instance) }; await InstallInternalAsync( project, toInstall, repoProvider, projectContext, includePrerelease: false, ignoreDependencies: ignoreDependencies, token: CancellationToken.None); }); } catch (Exception exception) { _telemetryProvider.PostFault(exception, typeof(VsPackageInstaller).FullName); throw; } } public void InstallPackagesFromVSExtensionRepository(string extensionId, bool isPreUnzipped, bool skipAssemblyReferences, Project project, IDictionary<string, string> packageVersions) { InstallPackagesFromVSExtensionRepository( extensionId, isPreUnzipped, skipAssemblyReferences, ignoreDependencies: true, project: project, packageVersions: packageVersions); } public void InstallPackagesFromVSExtensionRepository(string extensionId, bool isPreUnzipped, bool skipAssemblyReferences, bool ignoreDependencies, Project project, IDictionary<string, string> packageVersions) { if (string.IsNullOrEmpty(extensionId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(extensionId)); } if (project == null) { throw new ArgumentNullException(nameof(project)); } if (!packageVersions.Any()) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(packageVersions)); } try { RunJTFWithCorrectContext(project, () => { var repoProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider); repoProvider.AddFromExtension(_sourceRepositoryProvider, extensionId); var toInstall = GetIdentitiesFromDict(packageVersions); // Skip assembly references and disable binding redirections should be done together var disableBindingRedirects = skipAssemblyReferences; var projectContext = new VSAPIProjectContext(skipAssemblyReferences, disableBindingRedirects) { PackageExtractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv2, PackageExtractionBehavior.XmlDocFileSaveMode, ClientPolicyContext.GetClientPolicy(_settings, NullLogger.Instance), NullLogger.Instance) }; return InstallInternalAsync( project, toInstall, repoProvider, projectContext, includePrerelease: false, ignoreDependencies: ignoreDependencies, token: CancellationToken.None); }); } catch (Exception exception) { _telemetryProvider.PostFault(exception, typeof(VsPackageInstaller).FullName); throw; } } private static List<PackageIdentity> GetIdentitiesFromDict(IDictionary<string, string> packageVersions) { var toInstall = new List<PackageIdentity>(); // create identities foreach (var pair in packageVersions) { // TODO: versions can be null today, should this continue? NuGetVersion version = null; if (!string.IsNullOrEmpty(pair.Value)) { NuGetVersion.TryParse(pair.Value, out version); } toInstall.Add(new PackageIdentity(pair.Key, version)); } return toInstall; } private Action<string> ErrorHandler => msg => { // We don't log anything }; /// <summary> /// Creates a repo provider for the given sources. If null is passed all sources will be returned. /// </summary> private ISourceRepositoryProvider GetSources(IEnumerable<string> sources) { ISourceRepositoryProvider provider = null; // add everything enabled if null if (sources == null) { // Use the default set of sources provider = _sourceRepositoryProvider; } else { // Create a custom source provider for the VS API install var customProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider); // Create sources using the given set of sources foreach (var source in sources) { customProvider.AddFromSource(GetSource(source)); } provider = customProvider; } return provider; } /// <summary> /// Convert a source string to a SourceRepository. If one already exists that will be used. /// </summary> private SourceRepository GetSource(string source) { var repo = _sourceRepositoryProvider.GetRepositories() .Where(e => StringComparer.OrdinalIgnoreCase.Equals(e.PackageSource.Source, source)).FirstOrDefault(); if (repo == null) { Uri result; if (!Uri.TryCreate(source, UriKind.Absolute, out result)) { throw new ArgumentException( string.Format(VsResources.InvalidSource, source), nameof(source)); } var newSource = new Configuration.PackageSource(source); repo = _sourceRepositoryProvider.CreateRepository(newSource); } return repo; } /// <summary> /// Internal install method. All installs from the VS API and template wizard end up here. /// </summary> internal async Task InstallInternalAsync( Project project, List<PackageIdentity> packages, ISourceRepositoryProvider repoProvider, VSAPIProjectContext projectContext, bool includePrerelease, bool ignoreDependencies, CancellationToken token) { // Go off the UI thread. This may be called from the UI thread. Only switch to the UI thread where necessary // This method installs multiple packages and can likely take more than a few secs // So, go off the UI thread explicitly to improve responsiveness await TaskScheduler.Default; var gatherCache = new GatherCache(); var sources = repoProvider.GetRepositories().ToList(); // store expanded node state var expandedNodes = await VsHierarchyUtility.GetAllExpandedNodesAsync(); try { var depBehavior = ignoreDependencies ? DependencyBehavior.Ignore : DependencyBehavior.Lowest; var packageManager = CreatePackageManager(repoProvider); // find the project var nuGetProject = await _solutionManager.GetOrCreateProjectAsync(project, projectContext); var packageManagementFormat = new PackageManagementFormat(_settings); // 1 means PackageReference var preferPackageReference = packageManagementFormat.SelectedPackageManagementFormat == 1; // Check if default package format is set to `PackageReference` and project has no // package installed yet then upgrade it to `PackageReference` based project. if (preferPackageReference && (nuGetProject is MSBuildNuGetProject) && !(await nuGetProject.GetInstalledPackagesAsync(token)).Any() && await NuGetProjectUpgradeUtility.IsNuGetProjectUpgradeableAsync(nuGetProject, project, needsAPackagesConfig: false)) { nuGetProject = await _solutionManager.UpgradeProjectToPackageReferenceAsync(nuGetProject); } // install the package foreach (var package in packages) { var installedPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token); // Check if the package is already installed if (package.Version != null && PackageServiceUtilities.IsPackageInList(installedPackageReferences, package.Id, package.Version)) { continue; } // Perform the install await InstallInternalCoreAsync( packageManager, gatherCache, nuGetProject, package, sources, projectContext, includePrerelease, ignoreDependencies, token); } } finally { // collapse nodes await VsHierarchyUtility.CollapseAllNodesAsync(expandedNodes); } } /// <summary> /// Core install method. All installs from the VS API and template wizard end up here. /// This does not check for already installed packages /// </summary> internal async Task InstallInternalCoreAsync( NuGetPackageManager packageManager, GatherCache gatherCache, NuGetProject nuGetProject, PackageIdentity package, IEnumerable<SourceRepository> sources, VSAPIProjectContext projectContext, bool includePrerelease, bool ignoreDependencies, CancellationToken token) { await TaskScheduler.Default; var depBehavior = ignoreDependencies ? DependencyBehavior.Ignore : DependencyBehavior.Lowest; using (var sourceCacheContext = new SourceCacheContext()) { var resolution = new ResolutionContext( depBehavior, includePrerelease, includeUnlisted: false, versionConstraints: VersionConstraints.None, gatherCache: gatherCache, sourceCacheContext: sourceCacheContext); // install the package if (package.Version == null) { await packageManager.InstallPackageAsync(nuGetProject, package.Id, resolution, projectContext, sources, Enumerable.Empty<SourceRepository>(), token); } else { await packageManager.InstallPackageAsync(nuGetProject, package, resolution, projectContext, sources, Enumerable.Empty<SourceRepository>(), token); } } } /// <summary> /// Create a new NuGetPackageManager with the IVsPackageInstaller settings. /// </summary> internal NuGetPackageManager CreatePackageManager(ISourceRepositoryProvider repoProvider) { return new NuGetPackageManager( repoProvider, _settings, _solutionManager, _deleteOnRestartManager); } } }
41.268116
216
0.576778
[ "Apache-2.0" ]
BlackGad/NuGet.Client
src/NuGet.Clients/NuGet.VisualStudio.Implementation/Extensibility/VsPackageInstaller.cs
22,780
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.Management.IotHub.Common { using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Microsoft.Azure.Commands.Management.IotHub.Models; using Microsoft.Azure.Management.IotHub.Models; using Newtonsoft.Json; public static class IotHubUtils { const string TotalDeviceCountMetricName = "TotalDeviceCount"; const string UnlimitedString = "Unlimited"; const string IotHubConnectionStringTemplate = "HostName={0};SharedAccessKeyName={1};SharedAccessKey={2}"; public static T2 ConvertObject<T1, T2>(T1 iotHubObject) { return JsonConvert.DeserializeObject<T2>(JsonConvert.SerializeObject(iotHubObject)); } public static IEnumerable<PSIotHub> ToPSIotHubs(IEnumerable<IotHubDescription> iotHubDescriptions) { return ConvertObject<IEnumerable<IotHubDescription>, IEnumerable<PSIotHub>>(iotHubDescriptions.ToList()); } public static PSIotHub ToPSIotHub(IotHubDescription iotHubDescription) { return ConvertObject<IotHubDescription, PSIotHub>(iotHubDescription); } public static IotHubProperties ToIotHubProperties(PSIotHubInputProperties psIotHubInputProperties) { return ConvertObject<PSIotHubInputProperties, IotHubProperties>(psIotHubInputProperties); } public static IEnumerable<PSSharedAccessSignatureAuthorizationRule> ToPSSharedAccessSignatureAuthorizationRules(IEnumerable<SharedAccessSignatureAuthorizationRule> authorizationPolicies) { return ConvertObject<IEnumerable<SharedAccessSignatureAuthorizationRule>, IEnumerable<PSSharedAccessSignatureAuthorizationRule>>(authorizationPolicies.ToList()); } public static PSSharedAccessSignatureAuthorizationRule ToPSSharedAccessSignatureAuthorizationRule(SharedAccessSignatureAuthorizationRule authorizationPolicy) { return ConvertObject<SharedAccessSignatureAuthorizationRule, PSSharedAccessSignatureAuthorizationRule>(authorizationPolicy); } public static IEnumerable<SharedAccessSignatureAuthorizationRule> ToSharedAccessSignatureAuthorizationRules(IEnumerable<PSSharedAccessSignatureAuthorizationRule> authorizationPolicies) { return ConvertObject<IEnumerable<PSSharedAccessSignatureAuthorizationRule>, IEnumerable<SharedAccessSignatureAuthorizationRule>>(authorizationPolicies.ToList()); } public static SharedAccessSignatureAuthorizationRule ToSharedAccessSignatureAuthorizationRule(PSSharedAccessSignatureAuthorizationRule authorizationPolicy) { return ConvertObject<PSSharedAccessSignatureAuthorizationRule, SharedAccessSignatureAuthorizationRule>(authorizationPolicy); } public static IEnumerable<PSIotHubJobResponse> ToPSIotHubJobResponseList(IEnumerable<JobResponse> jobResponseList) { return ConvertObject<IEnumerable<JobResponse>, IEnumerable<PSIotHubJobResponse>>(jobResponseList.ToList()); } public static PSIotHubJobResponse ToPSIotHubJobResponse(JobResponse jobResponse) { return ConvertObject<JobResponse, PSIotHubJobResponse>(jobResponse); } public static ExportDevicesRequest ToExportDevicesRequest(PSExportDevicesRequest psExportDevicesRequest) { return ConvertObject<PSExportDevicesRequest, ExportDevicesRequest>(psExportDevicesRequest); } public static ImportDevicesRequest ToImportDevicesRequest(PSImportDevicesRequest psImportDevicesRequest) { return ConvertObject<PSImportDevicesRequest, ImportDevicesRequest>(psImportDevicesRequest); } public static PSIotHubRegistryStatistics ToPSIotHubRegistryStatistics(RegistryStatistics registryStats) { return ConvertObject<RegistryStatistics, PSIotHubRegistryStatistics>(registryStats); } public static IEnumerable<PSIotHubSkuDescription> ToPSIotHubSkuDescriptions(IEnumerable<IotHubSkuDescription> iotHubSkuDescriptions) { return ConvertObject<IEnumerable<IotHubSkuDescription>, IEnumerable<PSIotHubSkuDescription>>(iotHubSkuDescriptions.ToList()); } public static IDictionary<string, EventHubProperties> ToEventHubEndpointProperties(IDictionary<string, PSEventHubInputProperties> psEventHubEndpointProperties) { return ConvertObject<IDictionary<string, PSEventHubInputProperties>, IDictionary<string, EventHubProperties>>(psEventHubEndpointProperties); } public static IDictionary<string, MessagingEndpointProperties> ToMessagingEndpoints(IDictionary<string, PSMessagingEndpointProperties> psMessagingEndpointProperties) { return ConvertObject<IDictionary<string, PSMessagingEndpointProperties>, IDictionary<string, MessagingEndpointProperties>>(psMessagingEndpointProperties); } public static IDictionary<string, StorageEndpointProperties> ToStorageEndpoints(IDictionary<string, PSStorageEndpointProperties> psStorageEndpointProperties) { return ConvertObject<IDictionary<string, PSStorageEndpointProperties>, IDictionary<string, StorageEndpointProperties>>(psStorageEndpointProperties); } public static CloudToDeviceProperties ToCloudToDeviceProperties(PSCloudToDeviceProperties psCloudToDeviceProperties) { return ConvertObject<PSCloudToDeviceProperties, CloudToDeviceProperties>(psCloudToDeviceProperties); } public static IotHubSkuInfo ToIotHubSku(PSIotHubSkuInfo psIotHubSkuInfo) { return ConvertObject<PSIotHubSkuInfo, IotHubSkuInfo>(psIotHubSkuInfo); } public static RoutingProperties ToRoutingProperties(PSRoutingProperties psRoutingProperties) { return ConvertObject<PSRoutingProperties, RoutingProperties>(psRoutingProperties); } public static List<RouteProperties> ToRouteProperties(List<PSRouteMetadata> psRouteProperties) { return ConvertObject<List<PSRouteMetadata>, List<RouteProperties>>(psRouteProperties); } public static RouteProperties ToRouteProperty(PSRouteMetadata psRouteProperty) { return ConvertObject<PSRouteMetadata, RouteProperties>(psRouteProperty); } public static IEnumerable<PSRouteProperties> ToPSRouteProperties(IEnumerable<RouteProperties> routeProperties) { return ConvertObject<IEnumerable<RouteProperties>, IEnumerable<PSRouteProperties>>(routeProperties); } public static IEnumerable<PSRouteProperties> ToPSRouteProperties(IEnumerable<MatchedRoute> routes) { var psRouteProperties = new List<PSRouteProperties>(); foreach (var route in routes) { psRouteProperties.Add(ConvertObject<RouteProperties, PSRouteProperties>(route.Properties)); } return psRouteProperties; } public static PSRouteMetadata ToPSRouteMetadata(RouteProperties routeProperties) { return ConvertObject<RouteProperties, PSRouteMetadata>(routeProperties); } public static FallbackRouteProperties ToFallbackRouteProperty(PSFallbackRouteMetadata psRouteProperty) { return ConvertObject<PSFallbackRouteMetadata, FallbackRouteProperties>(psRouteProperty); } public static IList<PSIotHubConnectionString> ToPSIotHubConnectionStrings(IEnumerable<SharedAccessSignatureAuthorizationRule> authorizationPolicies, string hostName) { var psConnectionStrings = new List<PSIotHubConnectionString>(); if (psConnectionStrings != null) { foreach (var authorizationPolicy in authorizationPolicies) { psConnectionStrings.Add(authorizationPolicy.ToPSIotHubConnectionString(hostName)); } } return psConnectionStrings; } public static PSIotHubConnectionString ToPSIotHubConnectionString(this SharedAccessSignatureAuthorizationRule authorizationPolicy, string hostName) { return new PSIotHubConnectionString() { KeyName = authorizationPolicy.KeyName, PrimaryConnectionString = String.Format(IotHubConnectionStringTemplate, hostName, authorizationPolicy.KeyName, authorizationPolicy.PrimaryKey), SecondaryConnectionString = String.Format(IotHubConnectionStringTemplate, hostName, authorizationPolicy.KeyName, authorizationPolicy.SecondaryKey) }; } public static IList<PSIotHubQuotaMetric> ToPSIotHubQuotaMetrics(IEnumerable<IotHubQuotaMetricInfo> iotHubQuotaMetrics) { var psIotHubQuotaMetrics = new List<PSIotHubQuotaMetric>(); foreach (var iotHubQuotaMetric in iotHubQuotaMetrics) { psIotHubQuotaMetrics.Add(iotHubQuotaMetric.ToPSIotHubQuotaMetric()); } return psIotHubQuotaMetrics; } public static PSIotHubQuotaMetric ToPSIotHubQuotaMetric(this IotHubQuotaMetricInfo iotHubQuotaMetric) { return new PSIotHubQuotaMetric() { Name = iotHubQuotaMetric.Name, CurrentValue = ((long)iotHubQuotaMetric.CurrentValue).ToString(), MaxValue = iotHubQuotaMetric.Name.Equals(TotalDeviceCountMetricName, StringComparison.OrdinalIgnoreCase) ? UnlimitedString : ((long)iotHubQuotaMetric.MaxValue).ToString() }; } public static PSCertificateDescription ToPSCertificateDescription(CertificateDescription certificateDescription) { return ConvertObject<CertificateDescription, PSCertificateDescription>(certificateDescription); } public static IEnumerable<PSCertificate> ToPSCertificates(CertificateListDescription certificateListDescription) { return ConvertObject<IEnumerable<CertificateDescription>, IEnumerable<PSCertificate>>(certificateListDescription.Value); } public static PSCertificateWithNonceDescription ToPSCertificateWithNonceDescription(CertificateWithNonceDescription certificateWithNonceDescription) { return ConvertObject<CertificateWithNonceDescription, PSCertificateWithNonceDescription>(certificateWithNonceDescription); } public static IEnumerable<PSEventHubConsumerGroupInfo> ToPSEventHubConsumerGroupInfo(IEnumerable<EventHubConsumerGroupInfo> eventHubConsumerGroupInfo) { return ConvertObject<IEnumerable<EventHubConsumerGroupInfo>, IEnumerable<PSEventHubConsumerGroupInfo>>(eventHubConsumerGroupInfo.ToList()); } public static TagsResource ToTagsResource(IDictionary<string, string> tags) { return new TagsResource(tags); } public static PSRoutingEventHubEndpoint ToPSRoutingEventHubEndpoint(RoutingEventHubProperties routingEventHubProperties) { return ConvertObject<RoutingEventHubProperties, PSRoutingEventHubEndpoint>(routingEventHubProperties); } public static PSRoutingServiceBusQueueEndpoint ToPSRoutingServiceBusQueueEndpoint(RoutingServiceBusQueueEndpointProperties routingServiceBusQueueEndpointProperties) { return ConvertObject<RoutingServiceBusQueueEndpointProperties, PSRoutingServiceBusQueueEndpoint>(routingServiceBusQueueEndpointProperties); } public static PSRoutingServiceBusTopicEndpoint ToPSRoutingServiceBusTopicEndpoint(RoutingServiceBusTopicEndpointProperties routingServiceBusTopicEndpointProperties) { return ConvertObject<RoutingServiceBusTopicEndpointProperties, PSRoutingServiceBusTopicEndpoint>(routingServiceBusTopicEndpointProperties); } public static PSRoutingStorageContainerEndpoint ToPSRoutingStorageContainerEndpoint(RoutingStorageContainerProperties routingStorageContainerProperties) { return ConvertObject<RoutingStorageContainerProperties, PSRoutingStorageContainerEndpoint>(routingStorageContainerProperties); } public static IEnumerable<PSRoutingEventHubProperties> ToPSRoutingEventHubProperties(IEnumerable<RoutingEventHubProperties> routingEventHubProperties) { return ConvertObject<IEnumerable<RoutingEventHubProperties>, IEnumerable<PSRoutingEventHubProperties>>(routingEventHubProperties.ToList()); } public static IEnumerable<PSRoutingServiceBusQueueEndpointProperties> ToPSRoutingServiceBusQueueEndpointProperties(IEnumerable<RoutingServiceBusQueueEndpointProperties> routingServiceBusQueueEndpointProperties) { return ConvertObject<IEnumerable<RoutingServiceBusQueueEndpointProperties>, IEnumerable<PSRoutingServiceBusQueueEndpointProperties>>(routingServiceBusQueueEndpointProperties.ToList()); } public static IEnumerable<PSRoutingServiceBusTopicEndpointProperties> ToPSRoutingServiceBusTopicEndpointProperties(IEnumerable<RoutingServiceBusTopicEndpointProperties> routingServiceBusTopicEndpointProperties) { return ConvertObject<IEnumerable<RoutingServiceBusTopicEndpointProperties>, IEnumerable<PSRoutingServiceBusTopicEndpointProperties>>(routingServiceBusTopicEndpointProperties.ToList()); } public static IEnumerable<PSRoutingStorageContainerProperties> ToPSRoutingStorageContainerProperties(IEnumerable<RoutingStorageContainerProperties> routingStorageContainerProperties) { return ConvertObject<IEnumerable<RoutingStorageContainerProperties>, IEnumerable<PSRoutingStorageContainerProperties>>(routingStorageContainerProperties.ToList()); } public static PSTestRouteResult ToPSTestRouteResult(TestRouteResult testRouteResult) { return ConvertObject<TestRouteResult, PSTestRouteResult>(testRouteResult); } public static string GetResourceGroupName(string Id) { if (string.IsNullOrEmpty(Id)) return null; Regex r = new Regex(@"(.*?)/resourcegroups/(?<rgname>\S+)/providers/(.*?)", RegexOptions.IgnoreCase); Match m = r.Match(Id); return m.Success ? m.Groups["rgname"].Value : null; } public static string GetIotHubName(string Id) { if (string.IsNullOrEmpty(Id)) return null; Regex r = new Regex(@"(.*?)/IotHubs/(?<iothubname>\S+)/certificates/(.*?)", RegexOptions.IgnoreCase); Match m = r.Match(Id); return m.Success ? m.Groups["iothubname"].Value : null; } public static string GetIotHubCertificateName(string Id) { if (string.IsNullOrEmpty(Id)) return null; Regex r = new Regex(@"(.*?)/certificates/(?<iothubcertificatename>\S+)", RegexOptions.IgnoreCase); Match m = r.Match(Id); return m.Success ? m.Groups["iothubcertificatename"].Value : null; } public static string GetAzureResource(PSEndpointType psEndpointType, string connectionString, string containerName) { if (string.IsNullOrEmpty(connectionString)) return null; Regex r = null; string azureResource = string.Empty; switch (psEndpointType) { case PSEndpointType.EventHub: case PSEndpointType.ServiceBusQueue: case PSEndpointType.ServiceBusTopic: r = new Regex(@"(.*?)sb://(?<resourceType>\S+).servicebus.windows.net(.*?)EntityPath=(?<name>\S+)", RegexOptions.IgnoreCase); Match match1 = r.Match(connectionString); azureResource = match1.Success ? string.Format("{0}/{1}", match1.Groups["resourceType"].Value, match1.Groups["name"].Value) : null; break; case PSEndpointType.AzureStorageContainer: r = new Regex(@"(.*?)AccountName=(?<resourceType>\S+);AccountKey=(.*?)", RegexOptions.IgnoreCase); Match match2 = r.Match(connectionString); azureResource = match2.Success ? string.Format("{0}/{1}", match2.Groups["resourceType"].Value, containerName) : null; break; } return azureResource; } } }
52.945946
219
0.710056
[ "MIT" ]
Tarvinder91/azure-powershell
src/IotHub/IotHub/Common/IotHubUtils.cs
17,301
C#
using System; namespace ApplicationForRunners.AplicationPages { public class MDMenuItem { public MDMenuItem() { TargetType = typeof(MapPage); OlwaysActive = false; } public int Id { get; set; } public string Title { get; set; } public Type TargetType { get; set; } public bool OlwaysActive { get; set; } } }
23.588235
47
0.566085
[ "MIT" ]
MateuszKapusta/ApplicationForRunners
ApplicationForRunners_Xamarin_Forms/ApplicationForRunners/AplicationPages/MDMenuItem.cs
403
C#
using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Lykke.Service.MarketProfile.Core.Services; using Lykke.Service.MarketProfile.Models; using Lykke.Service.MarketProfile.Models.MarketProfile; using Microsoft.AspNetCore.Mvc; namespace Lykke.Service.MarketProfile.Controllers { [Route("api/[controller]")] public class MarketProfileController : Controller { private readonly IRedisService _redisService; public MarketProfileController(IRedisService redisService) { _redisService = redisService; } [HttpGet("")] public async Task<IEnumerable<AssetPairModel>> GetAll() { var pairs = await _redisService.GetMarketProfilesAsync(); return pairs.Select(p => p.ToApiModel()); } [HttpGet("{pairCode}")] [ProducesResponseType(typeof(AssetPairModel), (int)HttpStatusCode.OK)] [ProducesResponseType(typeof(ErrorModel), (int)HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorModel), (int)HttpStatusCode.BadRequest)] public async Task<IActionResult> Get(string pairCode) { if (string.IsNullOrWhiteSpace(pairCode)) { return BadRequest(new ErrorModel { Code = ErrorCode.InvalidInput, Message = "Pair code is required" }); } var pair = await _redisService.GetMarketProfileAsync(pairCode); if (pair == null) { return NotFound(new ErrorModel { Code = ErrorCode.PairNotFound, Message = "Pair not found" }); } return Ok(pair.ToApiModel()); } } }
31.716667
83
0.581713
[ "MIT" ]
LykkeCity/Lykke.AssetsApi
src/Lykke.Service.MarketProfile/Controllers/MarketProfileController.cs
1,905
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using essentialMix.Data.Model; using essentialMix.Extensions; namespace MatchNBuy.Model; [DebuggerDisplay("{Name}")] [Serializable] public class Interest : IEntity { private string _name; [Key] public Guid Id { get; set; } [Required] [StringLength(255)] public string Name { get => _name; set => _name = value.ToNullIfEmpty(); } public virtual ICollection<UserInterest> UserInterests { get; set; } }
19.142857
69
0.75
[ "MIT" ]
asm2025/DatingApp
MatchNBuy.Model/Interest.cs
536
C#
using System; using System.Collections.Generic; using System.Linq; using Moq; using NUnit.Framework; using Our.ModelsBuilder.Tests.Testing; using Umbraco.Core.Composing; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Web; using Umbraco.Web.Models.PublishedContent; namespace Our.ModelsBuilder.Tests.Model { [TestFixture] public class PropertyValueTests { private IVariationContextAccessor _variationContextAccessor; [SetUp] public void SetUp() { Current.Reset(); var factory = Mock.Of<IFactory>(); var variationContext = new VariationContext("fr", "s"); _variationContextAccessor = Mock.Of<IVariationContextAccessor>(); Mock.Get(_variationContextAccessor).Setup(x => x.VariationContext).Returns(variationContext); var localizationService = Mock.Of<ILocalizationService>(); var langs = new[] { new Language("fr") { Id = 1 }, new Language("en") { Id = 2 }, new Language("de") { Id = 3, FallbackLanguageId = 2 }, new Language("dk") { Id = 4 } }; Mock.Get(localizationService).Setup(x => x.GetLanguageByIsoCode(It.IsAny<string>())) .Returns<string>(isoCode => langs.FirstOrDefault(x => x.IsoCode == isoCode)); Mock.Get(localizationService).Setup(x => x.GetLanguageById(It.IsAny<int>())) .Returns<int>(id => langs.FirstOrDefault(x => x.Id == id)); var serviceContext = ServiceContext.CreatePartial(localizationService: localizationService); var fallback = new TestPublishedValueFallback(serviceContext, _variationContextAccessor); Mock.Get(factory).Setup(x => x.GetInstance(typeof(IPublishedValueFallback))).Returns(fallback); Current.Factory = factory; } private Thing CreateThing() { var valueConverters = new PropertyValueConverterCollection(Enumerable.Empty<IPropertyValueConverter>()); var publishedModelFactory = Mock.Of<IPublishedModelFactory>(); var publishedContentTypeFactory = Mock.Of<IPublishedContentTypeFactory>(); var somePropertyType = new PublishedPropertyType("someValue", 1, false, ContentVariation.CultureAndSegment, valueConverters, publishedModelFactory, publishedContentTypeFactory); var otherPropertyType = new PublishedPropertyType("otherValue", 1, false, ContentVariation.Nothing, valueConverters, publishedModelFactory, publishedContentTypeFactory); var propertyTypes = new[] { somePropertyType, otherPropertyType }; var contentType = new PublishedContentType(1, "thing", PublishedItemType.Content, Enumerable.Empty<string>(), propertyTypes, ContentVariation.CultureAndSegment); var contentItem = new TestObjects.PublishedContent(contentType) .WithProperty(new TestObjects.PublishedProperty(somePropertyType, _variationContextAccessor) .WithValue("fr", "s", "val-fr") .WithValue("en", "s", "val-en") .WithValue("de", "alt", "segment")) .WithProperty(new TestObjects.PublishedProperty(otherPropertyType, _variationContextAccessor) .WithValue("", "", "other")); return new Thing(contentItem); } [Test] public void ClassicFallback() { var thing = CreateThing(); Assert.AreEqual("val-fr", ClassicThingExtensions.SomeValue(thing)); Assert.AreEqual("val-fr", ClassicThingExtensions.SomeValue(thing, culture: "fr")); Assert.AreEqual("val-en", ClassicThingExtensions.SomeValue(thing, culture: "en")); Assert.AreEqual(null, ClassicThingExtensions.SomeValue(thing, culture: "de")); Assert.AreEqual("default", ClassicThingExtensions.SomeValue(thing, culture: "de", fallback: Fallback.ToDefaultValue, defaultValue: "default")); Assert.AreEqual("other", ClassicThingExtensions.SomeValue(thing, culture: "de", fallback: Fallback.ToDefaultValue, defaultValue: ClassicThingExtensions.OtherValue(thing))); Assert.AreEqual("val-en", ClassicThingExtensions.SomeValue(thing, culture: "de", fallback: Fallback.ToLanguage)); Assert.AreEqual("default", ClassicThingExtensions.SomeValue(thing, culture: "dk", fallback: Fallback.To(Fallback.Language, Fallback.DefaultValue), defaultValue: "default")); Assert.AreEqual("segment", ClassicThingExtensions.SomeValue(thing, culture: "de", fallback: Fallback.To(FallbackToSegment))); } [Test] public void ModernFallback() { var thing = CreateThing(); Assert.AreEqual("val-fr", ModernThingExtensions.SomeValue(thing)); Assert.AreEqual("val-fr", ModernThingExtensions.SomeValue(thing, culture: "fr")); Assert.AreEqual("val-en", ModernThingExtensions.SomeValue(thing, culture: "en")); Assert.AreEqual(null, ModernThingExtensions.SomeValue(thing, culture: "de")); Assert.AreEqual("default", ModernThingExtensions.SomeValue(thing, culture: "de", fallback: x => "default")); Assert.AreEqual("default", ModernThingExtensions.SomeValue(thing, culture: "de", fallback: x => x.Default("default"))); Assert.AreEqual("other", ModernThingExtensions.SomeValue(thing, culture: "de", fallback: x => ModernThingExtensions.OtherValue(thing))); Assert.AreEqual("val-en", ModernThingExtensions.SomeValue(thing, culture: "de", fallback: x => x.Languages())); Assert.AreEqual("default", ModernThingExtensions.SomeValue(thing, culture: "dk", fallback: x => x.Languages().Default("default"))); Assert.AreEqual("segment", ModernThingExtensions.SomeValue(thing, culture: "de", fallback: x => Segments(x))); } [Test] public void PropertyGetters() { var thing = CreateThing(); Assert.AreEqual("val-fr", thing.SomeValue); Assert.AreEqual("val-fr", thing.Value(x => x.SomeValue)); } public const int FallbackToSegment = 666; // this thing is practically impossible to override ;( public class TestPublishedValueFallback : IPublishedValueFallback { private readonly ILocalizationService _localizationService; private readonly IVariationContextAccessor _variationContextAccessor; /// <summary> /// Initializes a new instance of the <see cref="PublishedValueFallback"/> class. /// </summary> public TestPublishedValueFallback(ServiceContext serviceContext, IVariationContextAccessor variationContextAccessor) { _localizationService = serviceContext.LocalizationService; _variationContextAccessor = variationContextAccessor; } /// <inheritdoc /> public bool TryGetValue(IPublishedProperty property, string culture, string segment, Fallback fallback, object defaultValue, out object value) { return TryGetValue<object>(property, culture, segment, fallback, defaultValue, out value); } /// <inheritdoc /> public bool TryGetValue<T>(IPublishedProperty property, string culture, string segment, Fallback fallback, T defaultValue, out T value) { _variationContextAccessor.ContextualizeVariation(property.PropertyType.Variations, ref culture, ref segment); foreach (var f in fallback) { switch (f) { case Fallback.None: continue; case Fallback.DefaultValue: value = defaultValue; return true; case Fallback.Language: if (TryGetValueWithLanguageFallback(property, culture, segment, out value)) return true; break; default: throw NotSupportedFallbackMethod(f, "property"); } } value = default; return false; } /// <inheritdoc /> public bool TryGetValue(IPublishedElement content, string alias, string culture, string segment, Fallback fallback, object defaultValue, out object value) { return TryGetValue<object>(content, alias, culture, segment, fallback, defaultValue, out value); } /// <inheritdoc /> public bool TryGetValue<T>(IPublishedElement content, string alias, string culture, string segment, Fallback fallback, T defaultValue, out T value) { var propertyType = content.ContentType.GetPropertyType(alias); if (propertyType == null) { value = default; return false; } _variationContextAccessor.ContextualizeVariation(propertyType.Variations, ref culture, ref segment); foreach (var f in fallback) { switch (f) { case Fallback.None: continue; case Fallback.DefaultValue: value = defaultValue; return true; case Fallback.Language: if (TryGetValueWithLanguageFallback(content, alias, culture, segment, out value)) return true; break; case FallbackToSegment: // hack our own! if (content.HasValue(alias, culture, "alt")) { value = content.Value<T>(alias, "alt", segment); return true; } break; default: throw NotSupportedFallbackMethod(f, "element"); } } value = default; return false; } /// <inheritdoc /> public bool TryGetValue(IPublishedContent content, string alias, string culture, string segment, Fallback fallback, object defaultValue, out object value, out IPublishedProperty noValueProperty) { return TryGetValue<object>(content, alias, culture, segment, fallback, defaultValue, out value, out noValueProperty); } /// <inheritdoc /> public virtual bool TryGetValue<T>(IPublishedContent content, string alias, string culture, string segment, Fallback fallback, T defaultValue, out T value, out IPublishedProperty noValueProperty) { noValueProperty = default; var propertyType = content.ContentType.GetPropertyType(alias); if (propertyType != null) { _variationContextAccessor.ContextualizeVariation(propertyType.Variations, ref culture, ref segment); noValueProperty = content.GetProperty(alias); } // note: we don't support "recurse & language" which would walk up the tree, // looking at languages at each level - should someone need it... they'll have // to implement it. foreach (var f in fallback) { switch (f) { case Fallback.None: continue; case Fallback.DefaultValue: value = defaultValue; return true; case Fallback.Language: if (propertyType == null) continue; if (TryGetValueWithLanguageFallback(content, alias, culture, segment, out value)) return true; break; case Fallback.Ancestors: if (TryGetValueWithAncestorsFallback(content, alias, culture, segment, out value, ref noValueProperty)) return true; break; case FallbackToSegment: // hack our own! if (content.HasValue(alias, culture, "alt")) { value = content.Value<T>(alias, culture, "alt"); return true; } break; default: throw NotSupportedFallbackMethod(f, "content"); } } value = default; return false; } private NotSupportedException NotSupportedFallbackMethod(int fallback, string level) { return new NotSupportedException($"Fallback {GetType().Name} does not support fallback code '{fallback}' at {level} level."); } // tries to get a value, recursing the tree // because we recurse, content may not even have the a property with the specified alias (but only some ancestor) // in case no value was found, noValueProperty contains the first property that was found (which does not have a value) private bool TryGetValueWithAncestorsFallback<T>(IPublishedContent content, string alias, string culture, string segment, out T value, ref IPublishedProperty noValueProperty) { IPublishedProperty property; // if we are here, content's property has no value do { content = content.Parent; var propertyType = content?.ContentType.GetPropertyType(alias); if (propertyType != null) { culture = null; segment = null; _variationContextAccessor.ContextualizeVariation(propertyType.Variations, ref culture, ref segment); } property = content?.GetProperty(alias); if (property != null && noValueProperty == null) { noValueProperty = property; } } while (content != null && (property == null || property.HasValue(culture, segment) == false)); // if we found a content with the property having a value, return that property value if (property != null && property.HasValue(culture, segment)) { value = property.Value<T>(culture, segment); return true; } value = default; return false; } // tries to get a value, falling back onto other languages private bool TryGetValueWithLanguageFallback<T>(IPublishedProperty property, string culture, string segment, out T value) { value = default; if (string.IsNullOrWhiteSpace(culture)) return false; var visited = new HashSet<int>(); var language = _localizationService.GetLanguageByIsoCode(culture); if (language == null) return false; while (true) { if (language.FallbackLanguageId == null) return false; var language2Id = language.FallbackLanguageId.Value; if (visited.Contains(language2Id)) return false; visited.Add(language2Id); var language2 = _localizationService.GetLanguageById(language2Id); if (language2 == null) return false; var culture2 = language2.IsoCode; if (property.HasValue(culture2, segment)) { value = property.Value<T>(culture2, segment); return true; } language = language2; } } // tries to get a value, falling back onto other languages private bool TryGetValueWithLanguageFallback<T>(IPublishedElement content, string alias, string culture, string segment, out T value) { value = default; if (string.IsNullOrWhiteSpace(culture)) return false; var visited = new HashSet<int>(); var language = _localizationService.GetLanguageByIsoCode(culture); if (language == null) return false; while (true) { if (language.FallbackLanguageId == null) return false; var language2Id = language.FallbackLanguageId.Value; if (visited.Contains(language2Id)) return false; visited.Add(language2Id); var language2 = _localizationService.GetLanguageById(language2Id); if (language2 == null) return false; var culture2 = language2.IsoCode; if (content.HasValue(alias, culture2, segment)) { value = content.Value<T>(alias, culture2, segment); return true; } language = language2; } } // tries to get a value, falling back onto other languages private bool TryGetValueWithLanguageFallback<T>(IPublishedContent content, string alias, string culture, string segment, out T value) { value = default; if (string.IsNullOrWhiteSpace(culture)) return false; var visited = new HashSet<int>(); // TODO: _localizationService.GetXxx() is expensive, it deep clones objects // we want _localizationService.GetReadOnlyXxx() returning IReadOnlyLanguage which cannot be saved back = no need to clone var language = _localizationService.GetLanguageByIsoCode(culture); if (language == null) return false; while (true) { if (language.FallbackLanguageId == null) return false; var language2Id = language.FallbackLanguageId.Value; if (visited.Contains(language2Id)) return false; visited.Add(language2Id); var language2 = _localizationService.GetLanguageById(language2Id); if (language2 == null) return false; var culture2 = language2.IsoCode; if (content.HasValue(alias, culture2, segment)) { value = content.Value<T>(alias, culture2, segment); return true; } language = language2; } } } // in real life this would be an extension method public FallbackValue<TModel, TValue> Segments<TModel, TValue>(FallbackInfos<TModel, TValue> fallbackInfos) where TModel : IPublishedElement { return fallbackInfos.CreateFallbackValue().To(FallbackToSegment); } // in real life this would be an extension method public FallbackValue<TModel, TValue> Segments<TModel, TValue>(FallbackValue<TModel, TValue> fallbackValue) where TModel : IPublishedElement { return fallbackValue.To(FallbackToSegment); } // generated extensions for Classic style public static class ClassicThingExtensions { public static string SomeValue(Thing model, string culture = null, string segment = null, Fallback fallback = default, string defaultValue = default) { return model.Value("someValue", culture, segment, fallback, defaultValue); } public static string OtherValue(Thing model, string culture = null, string segment = null, Fallback fallback = default, string defaultValue = default) { return model.Value("otherValue", culture, segment, fallback, defaultValue); } } // generated extensions for Modern style public static class ModernThingExtensions { public static string SomeValue(Thing model, string culture = null, string segment = null, Func<FallbackInfos<Thing, string>, string> fallback = null) { return model.Value("someValue", culture, segment, fallback); } public static string OtherValue(Thing model, string culture = null, string segment = null, Func<FallbackInfos<Thing, string>, string> fallback = null) { return model.Value("otherValue", culture, segment, fallback); } } public class Thing : PublishedContentModel { public Thing(IPublishedContent content) : base(content) { } // use our own attribute - we should know nothing about the embedded MB [ImplementPropertyType("someValue")] public string SomeValue => ClassicThingExtensions.SomeValue(this); } } }
45.623188
207
0.564304
[ "MIT" ]
Arlanet/ModelsBuilder.Original
src/Our.ModelsBuilder.Tests/Model/PropertyValueTests.cs
22,038
C#
 // // Time Class // Created 02/07/2021 // // WinForms PacMan v0.0.1 // Aardhyn Lavender 2021 // // A group of constants to reference time // steps in terms of milliseconds. // // NOTE : This is not an emum as that would require // excessive casting from Time to Int. // namespace FormsPixelGameEngine.Utility { public static class Time { public const int HALF_SECOND = 500; public const int QUARTER_SECOND = 250; public const int TENTH_SECOND = 100; public const int TWENTYTH_SECOND = 50; public const int HUNDREDTH_SECOND = 10; public const int TWO_HUNDREDTH_SECOND = 5; public const int SECOND = 1000; public const int TWO_SECOND = SECOND * 2; public const int THREE_SECOND = SECOND * 3; public const int FOUR_SECOND = SECOND * 4; public const int FIVE_SECOND = SECOND * 5; public const int SEVEN_SECOND = SECOND * 7; public const int TWENTY_SECOND = SECOND * 20; } }
30.567568
62
0.572944
[ "MIT" ]
AardhynLavender/WinFormsPacman
Pacman/Utility/Time.cs
1,133
C#
using System; using System.Runtime.CompilerServices; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using NumSharp.UnitTest.Utilities; using static NumSharp.Slice; namespace NumSharp.UnitTest.Manipulation { [TestClass] public class NdArrayReShapeTest { [TestMethod] public void ReShape() { var nd = np.arange(6); var n1 = np.reshape(nd, 3, 2); var n = n1.MakeGeneric<int>(); Assert.IsTrue(n[0, 0] == 0); Assert.IsTrue(n[1, 1] == 3); Assert.IsTrue(n[2, 1] == 5); n = np.reshape(np.arange(6), 2, 3, 1).MakeGeneric<int>(); Assert.IsTrue(n[1, 1, 0] == 4); Assert.IsTrue(n[1, 2, 0] == 5); n = np.reshape(np.arange(12), 2, 3, 2).MakeGeneric<int>(); Assert.IsTrue(n[0, 0, 1] == 1); Assert.IsTrue(n[1, 0, 1] == 7); Assert.IsTrue(n[1, 1, 0] == 8); n = np.reshape(np.arange(12), 3, 4).MakeGeneric<int>(); Assert.IsTrue(n[1, 1] == 5); Assert.IsTrue(n[2, 0] == 8); n = np.reshape(n, 2, 6).MakeGeneric<int>(); Assert.IsTrue(n[1, 0] == 6); } /// <summary> /// numpy allow us to give one of new shape parameter as -1 (eg: (2,-1) or (-1,3) but not (-1, -1)). /// It simply means that it is an unknown dimension and we want numpy to figure it out. /// And numpy will figure this by looking at the 'length of the array and remaining dimensions' and making sure it satisfies the above mentioned criteria /// </summary> [TestMethod] public void ReshapeNegative() { NDArray nd; nd = np.arange(12).reshape(-1, 2); Assert.IsTrue(nd.shape[0] == 6); Assert.IsTrue(nd.shape[1] == 2); nd = np.arange(12).reshape(new Shape(-1, 2)); Assert.IsTrue(nd.shape[0] == 6); Assert.IsTrue(nd.shape[1] == 2); nd = np.arange(12).reshape(2, -1); Assert.IsTrue(nd.shape[0] == 2); Assert.IsTrue(nd.shape[1] == 6); nd = np.arange(12).reshape(1, 3, 4); nd = nd.reshape(-1, 3); Assert.IsTrue(nd.shape[0] == 4); Assert.IsTrue(nd.shape[1] == 3); nd = np.arange(12).MakeGeneric<int>(); nd = nd.reshape(1, 3, 4); nd = nd.reshape(3, -1); Assert.IsTrue(nd.shape[0] == 3); Assert.IsTrue(nd.shape[1] == 4); nd = np.arange(100 * 100 * 3).MakeGeneric<int>(); nd = nd.reshape(100, 100, 3); nd = nd.reshape(-1, 3); Assert.IsTrue(nd.shape[0] == 10000); Assert.IsTrue(nd.shape[1] == 3); /*np.arange(15801033); np.reshape(2531, 2081, 3); np.reshape(-1, 3); Assert.IsTrue(np.shape[0] == 5267011); Assert.IsTrue(np.shape[1] == 3);*/ } [TestMethod] public void ValueTest() { var x = np.arange(4).MakeGeneric<int>(); var y = x.reshape(2, 2).MakeGeneric<int>(); y[0, 1] = 8; Assert.AreEqual(x[1], y[0, 1]); } [TestMethod] public void TwoNegativeMinusOne() { var x = np.arange(9).reshape(3, 1, 1, 3); new Action(() => x.reshape(-1, 3, -1)).Should().Throw<ArgumentException>(); } [TestMethod] public void Case1_negativeone() { var x = np.full(2, (3, 3, 1, 1, 3)); x.reshape((-1, 3)).shape.Should().BeEquivalentTo(9, 3); } [TestMethod] public void Case2_Slice() { var a = arange((3, 2, 2)); a = a[0, All]; a.Should().BeShaped(2, 2).And.BeOfValues(0, 1, 2, 3); a = a.reshape(1, 4); a.Should().BeShaped(1, 4).And.BeOfValues(0, 1, 2, 3); a[0, 2].Should().BeScalar(2); } [TestMethod] public void Case2_Slice_Broadcast() { //alloc var a = arange((3, 2, 2)); //ends up 2, 2 var b = arange((2, 2, 2)); //slice a = a[0, All]; a.Should().BeShaped(2, 2).And.BeOfValues(0, 1, 2, 3); //broadcast (a, b) = np.broadcast_arrays(a, b); a.Should().BeShaped(2, 2, 2).And.BeOfValues(0, 1, 2, 3, 0, 1, 2, 3); b.Should().BeShaped(2, 2, 2); //reshape new Action(() => a.reshape(1, -1)).Should().Throw<NotSupportedException>().WithMessage("Reshaping an already broadcasted shape is not supported."); } [TestMethod] public void Case3_Slice_Broadcast() { //alloc var a = arange((2, 2, 2)); //ends up 2, 2 var b = arange((1, 2, 2)); Console.WriteLine(a.ToString(true)); Console.WriteLine(b.ToString(true)); //broadcast (a, b) = np.broadcast_arrays(a, b); a.Should().BeShaped(2, 2, 2).And.BeOfValues(0, 1, 2, 3, 4, 5, 6, 7); b.Should().BeShaped(2, 2, 2).And.BeOfValues(0, 1, 2, 3, 0, 1, 2, 3); //slice a = a[0, All]; b = b[0, All]; a.Should().BeShaped(2, 2).And.BeOfValues(0, 1, 2, 3); b.Should().BeShaped(2, 2).And.BeOfValues(0, 1, 2, 3); //reshape var resh = a.reshape_unsafe(1, 4); resh.Should().BeShaped(1, 4).And.BeOfValues(0, 1, 2, 3); } [TestMethod] public void Case4_Slice_Broadcast() { //alloc var a = arange((2, 2, 2)); //ends up 2, 2 var b = arange((1, 2, 2)); Console.WriteLine(a.ToString(true)); Console.WriteLine(b.ToString(true)); //broadcast (a, b) = np.broadcast_arrays(a, b); a.Should().BeShaped(2, 2, 2).And.BeOfValues(0, 1, 2, 3, 4, 5, 6, 7); b.Should().BeShaped(2, 2, 2).And.BeOfValues(0, 1, 2, 3, 0, 1, 2, 3); //slice a = a[1, All]; b = b[0, All]; a.Should().BeShaped(2, 2).And.BeOfValues(4, 5, 6, 7); b.Should().BeShaped(2, 2).And.BeOfValues(0, 1, 2, 3); var resh = a.reshape_unsafe(1, 4); resh.Should().BeShaped(1, 4).And.BeOfValues(4, 5, 6, 7); } [TestMethod] public void Case5_Slice_Broadcast() { //alloc var a = arange((2, 2, 2)); //ends up 2, 2 var b = arange((1, 2, 2)); Console.WriteLine(a.ToString(true)); Console.WriteLine(b.ToString(true)); //broadcast (a, b) = np.broadcast_arrays(a, b); a.Should().BeShaped(2, 2, 2).And.BeOfValues(0, 1, 2, 3, 4, 5, 6, 7); b.Should().BeShaped(2, 2, 2).And.BeOfValues(0, 1, 2, 3, 0, 1, 2, 3); //slice a = a[0, All]; b = b[1, All]; a.Should().BeShaped(2, 2).And.BeOfValues(0, 1, 2, 3); b.Should().BeShaped(2, 2).And.BeOfValues(0, 1, 2, 3); var resh = b.reshape_unsafe(1, 4); resh.Should().BeShaped(1, 4).And.BeOfValues(0, 1, 2, 3); } private NDArray arange(ITuple tuple) { var dims = new int[tuple.Length]; var size = 1; for (int i = 0; i < tuple.Length; i++) { dims[i] = Convert.ToInt32(tuple[i]); size *= dims[i]; } return np.arange(size).reshape(dims); } } }
34.818182
161
0.474021
[ "Apache-2.0" ]
deepakkumar1984/NumSharp
test/NumSharp.UnitTest/Manipulation/NdArray.ReShape.Test.cs
7,662
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the servicecatalog-2015-12-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ServiceCatalog.Model { /// <summary> /// Container for the parameters to the DeleteConstraint operation. /// Deletes the specified constraint. /// </summary> public partial class DeleteConstraintRequest : AmazonServiceCatalogRequest { private string _acceptLanguage; private string _id; /// <summary> /// Gets and sets the property AcceptLanguage. /// <para> /// The language code. /// </para> /// <ul> <li> /// <para> /// <code>en</code> - English (default) /// </para> /// </li> <li> /// <para> /// <code>jp</code> - Japanese /// </para> /// </li> <li> /// <para> /// <code>zh</code> - Chinese /// </para> /// </li> </ul> /// </summary> public string AcceptLanguage { get { return this._acceptLanguage; } set { this._acceptLanguage = value; } } // Check to see if AcceptLanguage property is set internal bool IsSetAcceptLanguage() { return this._acceptLanguage != null; } /// <summary> /// Gets and sets the property Id. /// <para> /// The identifier of the constraint. /// </para> /// </summary> public string Id { get { return this._id; } set { this._id = value; } } // Check to see if Id property is set internal bool IsSetId() { return this._id != null; } } }
28.168539
112
0.572397
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/ServiceCatalog/Generated/Model/DeleteConstraintRequest.cs
2,507
C#
#pragma checksum "C:\Users\38850490828\Documents\Projetos SENAI\senai\projetos\PontoDigitaFinal\SENAI-ponto-digital\Views\Shared\Sucesso.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8e1623727968d11d352661284238ae21bd816c78" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared_Sucesso), @"mvc.1.0.view", @"/Views/Shared/Sucesso.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Shared/Sucesso.cshtml", typeof(AspNetCore.Views_Shared_Sucesso))] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "C:\Users\38850490828\Documents\Projetos SENAI\senai\projetos\PontoDigitaFinal\SENAI-ponto-digital\Views\_ViewImports.cshtml" using SENAI_ponto_digital; #line default #line hidden #line 2 "C:\Users\38850490828\Documents\Projetos SENAI\senai\projetos\PontoDigitaFinal\SENAI-ponto-digital\Views\_ViewImports.cshtml" using SENAI_ponto_digital.Models; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"8e1623727968d11d352661284238ae21bd816c78", @"/Views/Shared/Sucesso.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c151f02c7981a822c9ded3eeda28f24f5ac5989b", @"/Views/_ViewImports.cshtml")] public class Views_Shared_Sucesso : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/css/style-pedidos-flex.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("stylesheet"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("text/css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(0, 97, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d48bb2dcd8c44764989e4bfbfd844911", async() => { BeginContext(6, 7, true); WriteLiteral("\r\n "); EndContext(); BeginContext(13, 75, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "1de50a2ee9c4448986a621a41115029a", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(88, 2, true); WriteLiteral("\r\n"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(97, 18, true); WriteLiteral("\r\n\r\n <header>\r\n"); EndContext(); #line 6 "C:\Users\38850490828\Documents\Projetos SENAI\senai\projetos\PontoDigitaFinal\SENAI-ponto-digital\Views\Shared\Sucesso.cshtml" Html.RenderPartial("_HeaderNavBar"); #line default #line hidden BeginContext(188, 126, true); WriteLiteral(" <hgroup>\r\n <h1>Agora vai</h1>\r\n </hgroup>\r\n </header>\r\n\r\n <main class=\"sucesso\">\r\n <h2>"); EndContext(); BeginContext(315, 18, false); #line 15 "C:\Users\38850490828\Documents\Projetos SENAI\senai\projetos\PontoDigitaFinal\SENAI-ponto-digital\Views\Shared\Sucesso.cshtml" Write(ViewData["Action"]); #line default #line hidden EndContext(); BeginContext(333, 46, true); WriteLiteral(" efetuado com sucesso!</h2>\r\n </main>\r\n\r\n\r\n"); EndContext(); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
66.725191
365
0.726576
[ "MIT" ]
GikaRodrigues/PontoDigitaFinal
SENAI-ponto-digital/obj/Debug/netcoreapp2.1/Razor/Views/Shared/Sucesso.g.cshtml.cs
8,741
C#
namespace TenantBShippingInformation.Models { public enum Priority { Low, Medium, High } }
14
44
0.642857
[ "MIT" ]
Espent1004/eShopOnContainersCustomised
src/Services/TenantCustomisations/TenantBShippingInformation/Models/Priority.cs
114
C#
using System; using MO.Common.Lang; namespace MO.Common.Geom { //============================================================ // <T>整数可变尺寸。</T> //============================================================ public class SIntVarSize : SIntSize { public const int WIDTH_VALID = 0x01; public const int HEIGHT_VALID = 0x02; public const int WIDTH_ANY = 0x10; public const int HEIGHT_ANY = 0x20; public const string VAL_ANY = "*"; int _flag = WIDTH_VALID + HEIGHT_VALID; //============================================================ // <T>构造整数可变尺寸。</T> //============================================================ public SIntVarSize() { } //============================================================ // <T>构造整数可变尺寸。</T> // // @param value 字符串 //============================================================ public SIntVarSize(string value) : base(value) { } //============================================================ // <T>构造整数可变尺寸。</T> // // @param width 宽度 // @param height 高度 //============================================================ public SIntVarSize(int width, int height) : base(width, height) { } //============================================================ // <T>测试宽度是否合法。</T> // // @return 是否合法 //============================================================ public bool IsWidthValid() { return WIDTH_VALID == (_flag & WIDTH_VALID); } //============================================================ // <T>测试宽度是否可变。</T> // // @return 是否可变 //============================================================ public bool IsWidthAny() { return WIDTH_ANY == (_flag & WIDTH_ANY); } //============================================================ // <T>测试宽度是否合法。</T> // // @return 是否合法 //============================================================ public bool IsHeightValid() { return HEIGHT_VALID == (_flag & HEIGHT_VALID); } //============================================================ // <T>测试高度是否可变。</T> // // @return 是否可变 //============================================================ public bool IsHeightAny() { return HEIGHT_ANY == (_flag & HEIGHT_ANY); } //============================================================ // <T>解析字符串。</T> // // @param value 字符串 //============================================================ public override void Parse(string value) { string[] data = value.Split(','); if(data.Length == 2) { _flag = 0; // 解析宽度 string width = data[0].Trim(); if(!VAL_ANY.Equals(width)) { _flag |= Int32.TryParse(width, out Width) ? WIDTH_VALID : 0; } else { _flag |= WIDTH_ANY; } // 解析高度 string height = data[1].Trim(); if(!VAL_ANY.Equals(height)) { _flag |= Int32.TryParse(height, out Height) ? HEIGHT_VALID : 0; } else { _flag |= HEIGHT_ANY; } } else { throw new FFatalException("Invalid size format ({0})", value); } } } }
30.699115
78
0.311329
[ "Apache-2.0" ]
favedit/MoCross
Tools/1 - Common/MoCommon/Geom/SIntVarSize.cs
3,691
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Dwell.Editor { [CustomEditor(typeof(DwellHandler), true)] public class DwellHandlerInspector : UnityEditor.Editor { private UnityEditor.Editor _editor; public override void OnInspectorGUI() { var dwellProfileAsset = this.serializedObject.FindProperty("dwellProfile"); EditorGUILayout.PropertyField(dwellProfileAsset, true); EditorGUILayout.Foldout(true, "Dwell Profile Properties", true); EditorGUI.indentLevel++; if (dwellProfileAsset.objectReferenceValue != null) { CreateCachedEditor(dwellProfileAsset.objectReferenceValue, null, ref _editor); _editor.OnInspectorGUI(); } EditorGUI.indentLevel--; EditorGUILayout.PropertyField(this.serializedObject.FindProperty("dwellIntended"), true); EditorGUILayout.PropertyField(this.serializedObject.FindProperty("dwellStarted"), true); EditorGUILayout.PropertyField(this.serializedObject.FindProperty("dwellCompleted"), true); EditorGUILayout.PropertyField(this.serializedObject.FindProperty("dwellCanceled"), true); this.serializedObject.ApplyModifiedProperties(); } } }
39.666667
103
0.668768
[ "MIT" ]
HyperLethalVector/ProjectEsky-UnityIntegration
Assets/MRTK/SDK/Editor/Inspectors/Dwell/DwellHandlerInspector.cs
1,430
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Train : MonoBehaviour, IMovableObstacleMessage { private Transform _transform = null; private Vector3 _spawnPosition = Vector3.zero; private float _moveSpeed = 0f; private void Update() { Vector3 moveVec = _moveSpeed * Time.deltaTime * _transform.forward; _transform.position += moveVec; if (_spawnPosition.x > 0) { if (_transform.position.x < -_spawnPosition.x) { _transform.position += _spawnPosition * 2; } } else if (_spawnPosition.x < 0) { if (_transform.position.x > -_spawnPosition.x) { _transform.position += _spawnPosition * 2; } } } public void SetMovableObstacleInfomations(float moveSpeed, Vector3 spawnPosition, Transform transform) { _moveSpeed = moveSpeed; _spawnPosition = spawnPosition; Vector3 adjustVec = new Vector3(0f, _spawnPosition.y, 0f); _spawnPosition -= adjustVec; _transform = transform; } }
24.3125
106
0.608398
[ "MIT" ]
Zziroo/From_Street
FromStreet/Assets/Scripts/Obstacle/Train.cs
1,167
C#
using Newtonsoft.Json; namespace Binance.API.Csharp.Client.Models.Account { public class NewOrder { [JsonProperty("symbol")] public string Symbol { get; set; } [JsonProperty("orderId")] public int OrderId { get; set; } [JsonProperty("clientOrderId")] public string ClientOrderId { get; set; } [JsonProperty("transactTime")] public long TransactTime { get; set; } } }
26.176471
50
0.613483
[ "MIT" ]
Khazmadu/Binance.API.Csharp.Client
Binance.API.Csharp.Client.Models/Account/NewOrder.cs
447
C#
using System; using System.Configuration; using System.Web.Script.Serialization; using System.Web.Security; using Portal.Caching; using Portal.DataAccess.Interfaces; using Portal.Web.Enums.Authentication; using Portal.Web.Interfaces; using Portal.Web.Logics.AuthenticationModels; using Portal.Web.ViewModels.Authentication; namespace Portal.Web.Logics { public class AuthenticationLogic : IAuthentication { //private readonly UpaCarConfiguration upaCarConfiguration = new UpaCarConfiguration(); private readonly IAccountRepository accountRepository; private readonly IAdminRepository adminRepository; public AuthenticationLogic(IAccountRepository accountRepository, IAdminRepository adminRepository) { this.accountRepository = accountRepository; this.adminRepository = adminRepository; } public LoginResponse Login(string username, string password, bool isAdmin = false) { var cacheKey = GlobalCachingProvider.Instance.GetCacheKey("AuthenticationLogic", "Login", username, password, isAdmin.ToString()); if (GlobalCachingProvider.Instance.ItemExist(cacheKey)) { // return (LoginResponse)GlobalCachingProvider.Instance.GetItem(cacheKey); } var asscId = Convert.ToInt32(ConfigurationManager.AppSettings["asscid"]); var userAccount = isAdmin ? this.adminRepository.Login(username, password, asscId) : this.accountRepository.Login(username, password, asscId); if (userAccount != null) { var serializeModel = new CustomPrincipalSerializeModel { Id = userAccount.AccountId, AsscId = userAccount.AsscId, FirstName = userAccount.FirstName, LastName = userAccount.LastName, Email = userAccount.EmailAddress, UserLoginRole = userAccount.LoginRole, MembershipType = userAccount.MembershipType, CanInvest = userAccount.CanInvest, CanDoChildBenefit = userAccount.CanDoChildBenefit, IsAdmin = userAccount.IsAdmin }; var response = new LoginResponse(); if (userAccount.LoginRole == 0) { response.AuthenticationStatus = AuthenticationStatus.Failed; response.Message = "Your information has been received, waiting for approval."; return response; } var serializer = new JavaScriptSerializer(); var userData = serializer.Serialize(serializeModel); var authTicket = new FormsAuthenticationTicket( 1, username, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData); response = new LoginResponse { AuthenticationStatus = AuthenticationStatus.Successful, AccountKey = userAccount.AccountId.ToString(), FirstName = userAccount.FirstName, LastName = userAccount.LastName, EmailAddress = userAccount.EmailAddress, FormsAuthCookieName = FormsAuthentication.FormsCookieName, FormsAuthCookieValue = FormsAuthentication.Encrypt(authTicket) }; GlobalCachingProvider.Instance.AddItem(cacheKey, response); return response; } return null; } public ChangePasswordResponse ChangePassword(ChangePasswordRequest request) { var oldpwd = this.accountRepository.GetPassword(request.AccountKey); var response = new ChangePasswordResponse { Status = AuthenticationStatus.Failed }; if (oldpwd != request.OldPassword) { return response; } var res = this.accountRepository.ChangePassword(request.AccountKey, request.NewPassword); if (res > 0) { response.Status = AuthenticationStatus.Successful; } return response; } } }
38.5
142
0.577812
[ "MIT" ]
isboat/ibunionportal
src/PortalWeb/Portal.Web.Logics/AuthenticationLogic.cs
4,545
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.AppService.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.AppService.Fluent.Models; using Microsoft.Azure.Management.AppService.Fluent.WebDeployment.Definition; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using System.Collections.Generic; using System; using System.IO; /// <summary> /// An immutable client-side representation of an Azure Web App or deployment slot. /// </summary> public interface IWebAppBase : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta, Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName, Microsoft.Azure.Management.ResourceManager.Fluent.Core.IGroupableResource<Microsoft.Azure.Management.AppService.Fluent.IAppServiceManager,Models.SiteInner> { /// <summary> /// Gets the version of Python. /// </summary> Microsoft.Azure.Management.AppService.Fluent.PythonVersion PythonVersion { get; } /// <summary> /// Gets list of IP addresses that this web app uses for /// outbound connections. Those can be used when configuring firewall /// rules for databases accessed by this web app. /// </summary> System.Collections.Generic.ISet<string> OutboundIPAddresses { get; } /// <return>The zipped archive of docker logs for a Linux web app.</return> Stream GetContainerLogsZip(); /// <return>The authentication configuration defined on the web app.</return> Task<Microsoft.Azure.Management.AppService.Fluent.IWebAppAuthentication> GetAuthenticationConfigAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <return>The last lines of docker logs for a Linux web app.</return> Stream GetContainerLogs(); /// <summary> /// Gets list of Azure Traffic manager host names associated with web /// app. /// </summary> System.Collections.Generic.ISet<string> TrafficManagerHostNames { get; } /// <summary> /// Gets list of SSL states used to manage the SSL bindings for site's hostnames. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string,Models.HostNameSslState> HostNameSslStates { get; } /// <summary> /// Gets the operating system the web app is running on. /// </summary> Microsoft.Azure.Management.AppService.Fluent.OperatingSystem OperatingSystem { get; } /// <summary> /// First step specifying the parameters to make a web deployment (MS Deploy) to the web app. /// </summary> /// <return>A stage to create web deployment.</return> WebDeployment.Definition.IWithPackageUri Deploy(); /// <summary> /// Gets if the client certificate is enabled for the web app. /// </summary> bool ClientCertEnabled { get; } /// <summary> /// Gets state indicating whether web app has exceeded its quota usage. /// </summary> Models.UsageState UsageState { get; } /// <summary> /// Gets if the remote eebugging is enabled. /// </summary> bool RemoteDebuggingEnabled { get; } /// <summary> /// Gets the Linux app framework and version if this is a Linux web app. /// </summary> string LinuxFxVersion { get; } /// <summary> /// Gets if the client affinity is enabled when load balancing http /// request for multiple instances of the web app. /// </summary> bool ClientAffinityEnabled { get; } /// <summary> /// Stops the web app or deployment slot. /// </summary> /// <return>A representation of the deferred computation of this call.</return> Task StopAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <return>The URL and credentials for publishing through FTP or Git.</return> Microsoft.Azure.Management.AppService.Fluent.IPublishingProfile GetPublishingProfile(); /// <return>The source control information for the web app.</return> Task<Microsoft.Azure.Management.AppService.Fluent.IWebAppSourceControl> GetSourceControlAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets state of the web app. /// </summary> string State { get; } /// <summary> /// Gets the .NET Framework version. /// </summary> Microsoft.Azure.Management.AppService.Fluent.NetFrameworkVersion NetFrameworkVersion { get; } /// <summary> /// Gets size of a function container. /// </summary> int ContainerSize { get; } /// <summary> /// Gets Java container version. /// </summary> string JavaContainerVersion { get; } /// <summary> /// Gets default hostname of the web app. /// </summary> string DefaultHostName { get; } /// <summary> /// Gets host names for the web app that are enabled. /// </summary> System.Collections.Generic.ISet<string> EnabledHostNames { get; } /// <summary> /// Swaps the app running in the current web app / slot with the app /// running in the specified slot. /// </summary> /// <param name="slotName"> /// The target slot to swap with. Use 'production' for /// the production slot. /// </param> void Swap(string slotName); /// <summary> /// Swaps the app running in the current web app / slot with the app /// running in the specified slot. /// </summary> /// <param name="slotName"> /// The target slot to swap with. Use 'production' for /// the production slot. /// </param> /// <return>A representation of the deferred computation of this call.</return> Task SwapAsync(string slotName, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the version of Node.JS. /// </summary> string NodeVersion { get; } /// <return>The last lines of docker logs for a Linux web app.</return> Task<Stream> GetContainerLogsAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Starts the web app or deployment slot. /// </summary> /// <return>A representation of the deferred computation of this call.</return> Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the auto swap slot name. /// </summary> string AutoSwapSlotName { get; } /// <summary> /// Gets the System Assigned (Local) Managed Service Identity specific Active Directory service principal ID /// assigned to the web app. /// </summary> string SystemAssignedManagedServiceIdentityPrincipalId { get; } /// <summary> /// Verifies the ownership of the domain for a certificate order by verifying a hostname /// of the domain is bound to this web app. /// </summary> /// <param name="certificateOrderName">The name of the certificate order.</param> /// <param name="domainVerificationToken">The domain verification token for the certificate order.</param> /// <return>A representation of the deferred computation of this call.</return> Task VerifyDomainOwnershipAsync(string certificateOrderName, string domainVerificationToken, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets management information availability state for the web app. /// </summary> Models.SiteAvailabilityState AvailabilityState { get; } /// <summary> /// Stops the web app or deployment slot. /// </summary> void Stop(); /// <summary> /// Gets The resource ID of the app service plan. /// </summary> string AppServicePlanId { get; } /// <return>The source control information for the web app.</return> Microsoft.Azure.Management.AppService.Fluent.IWebAppSourceControl GetSourceControl(); /// <summary> /// Gets if the public hostnames are disabled the web app. /// If set to true the app is only accessible via API /// Management process. /// </summary> bool HostNamesDisabled { get; } /// <summary> /// Gets Java container. /// </summary> string JavaContainer { get; } /// <summary> /// Gets the remote debugging version. /// </summary> Microsoft.Azure.Management.AppService.Fluent.RemoteVisualStudioVersion RemoteDebuggingVersion { get; } /// <summary> /// Gets the System Assigned (Local) Managed Service Identity specific Active Directory tenant ID assigned /// to the web app. /// </summary> string SystemAssignedManagedServiceIdentityTenantId { get; } /// <return>The connection strings defined on the web app.</return> Task<System.Collections.Generic.IReadOnlyDictionary<string,Microsoft.Azure.Management.AppService.Fluent.IConnectionString>> GetConnectionStringsAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <return>The authentication configuration defined on the web app.</return> Microsoft.Azure.Management.AppService.Fluent.IWebAppAuthentication GetAuthenticationConfig(); /// <summary> /// Gets Last time web app was modified in UTC. /// </summary> System.DateTime LastModifiedTime { get; } /// <return>The app settings defined on the web app.</return> System.Collections.Generic.IReadOnlyDictionary<string,Microsoft.Azure.Management.AppService.Fluent.IAppSetting> GetAppSettings(); /// <summary> /// Apply the slot (or sticky) configurations from the specified slot /// to the current one. This is useful for "Swap with Preview". /// </summary> /// <param name="slotName">The target slot to apply configurations from.</param> void ApplySlotConfigurations(string slotName); /// <summary> /// Gets the default documents. /// </summary> System.Collections.Generic.IReadOnlyList<string> DefaultDocuments { get; } /// <summary> /// Gets name of repository site. /// </summary> string RepositorySiteName { get; } /// <summary> /// Gets Java version. /// </summary> Microsoft.Azure.Management.AppService.Fluent.JavaVersion JavaVersion { get; } /// <return>The zipped archive of docker logs for a Linux web app.</return> Task<Stream> GetContainerLogsZipAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets hostnames associated with web app. /// </summary> System.Collections.Generic.ISet<string> HostNames { get; } /// <summary> /// Restarts the web app or deployment slot. /// </summary> /// <return>A representation of the deferred computation of this call.</return> Task RestartAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Reset the slot to its original configurations. /// </summary> void ResetSlotConfigurations(); /// <summary> /// Reset the slot to its original configurations. /// </summary> /// <return>A representation of the deferred computation of this call.</return> Task ResetSlotConfigurationsAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets true if the site is enabled; otherwise, false. /// </summary> bool Enabled { get; } /// <return>The URL and credentials for publishing through FTP or Git.</return> Task<Microsoft.Azure.Management.AppService.Fluent.IPublishingProfile> GetPublishingProfileAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets site is a default container. /// </summary> bool IsDefaultContainer { get; } /// <return>The connection strings defined on the web app.</return> System.Collections.Generic.IReadOnlyDictionary<string,Microsoft.Azure.Management.AppService.Fluent.IConnectionString> GetConnectionStrings(); /// <summary> /// Gets whether to stop SCM (KUDU) site when the web app is /// stopped. Default is false. /// </summary> bool ScmSiteAlsoStopped { get; } /// <return>The mapping from host names and the host name bindings.</return> System.Collections.Generic.IReadOnlyDictionary<string,Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding> GetHostNameBindings(); /// <summary> /// Gets if web socket is enabled. /// </summary> bool WebSocketsEnabled { get; } /// <summary> /// Apply the slot (or sticky) configurations from the specified slot /// to the current one. This is useful for "Swap with Preview". /// </summary> /// <param name="slotName">The target slot to apply configurations from.</param> /// <return>A representation of the deferred computation of this call.</return> Task ApplySlotConfigurationsAsync(string slotName, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets if the web app is always on. /// </summary> bool AlwaysOn { get; } /// <summary> /// Gets the version of PHP. /// </summary> Microsoft.Azure.Management.AppService.Fluent.PhpVersion PhpVersion { get; } /// <summary> /// Gets information about whether the web app is cloned from another. /// </summary> Models.CloningInfo CloningInfo { get; } /// <summary> /// Restarts the web app or deployment slot. /// </summary> void Restart(); /// <summary> /// Starts the web app or deployment slot. /// </summary> void Start(); /// <return>The mapping from host names and the host name bindings.</return> Task<System.Collections.Generic.IReadOnlyDictionary<string,Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding>> GetHostNameBindingsAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets managed pipeline mode. /// </summary> Models.ManagedPipelineMode ManagedPipelineMode { get; } /// <summary> /// Gets the architecture of the platform, either 32 bit (x86) or 64 bit (x64). /// </summary> Microsoft.Azure.Management.AppService.Fluent.PlatformArchitecture PlatformArchitecture { get; } /// <return>The app settings defined on the web app.</return> Task<System.Collections.Generic.IReadOnlyDictionary<string,Microsoft.Azure.Management.AppService.Fluent.IAppSetting>> GetAppSettingsAsync(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Verifies the ownership of the domain for a certificate order by verifying a hostname /// of the domain is bound to this web app. /// </summary> /// <param name="certificateOrderName">The name of the certificate order.</param> /// <param name="domainVerificationToken">The domain verification token for the certificate order.</param> void VerifyDomainOwnership(string certificateOrderName, string domainVerificationToken); /// <summary> /// Gets which slot this app will swap into. /// </summary> string TargetSwapSlot { get; } } }
42.657068
224
0.641853
[ "MIT" ]
abharath27/azure-libraries-for-net
src/ResourceManagement/AppService/Domain/IWebAppBase.cs
16,295
C#
// <auto-generated /> namespace VideoRental.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] public sealed partial class PopulateGenre : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(PopulateGenre)); string IMigrationMetadata.Id { get { return "202003221224513_PopulateGenre"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
27.4
96
0.622871
[ "MIT" ]
davinceleecode/VideoRental
VideoRental/Migrations/202003221224513_PopulateGenre.Designer.cs
822
C#
using Calendar.Services; using System; using Xunit; namespace Calendar.Tests { public class CalendarTests { [Fact] public void Calendar_should_be_constructed_with_default_date_passed() { var calendar = new CalendarService(0, 0); DateTime now = DateTime.Now; Assert.Equal(now.Year, calendar.Year); Assert.Equal(now.Month, calendar.Month); } [Fact] public void Calendar_should_be_constructed_with_date_passed() { var calendar = new CalendarService(2018, 11); Assert.Equal(2018, calendar.Year); Assert.Equal(11, calendar.Month); } [Theory] [InlineData(2015, 2010, 2019)] [InlineData(2019, 2010, 2019)] [InlineData(2010, 2010, 2019)] public void Should_calculate_correct_decade(int year, int expectedBeginYear, int expectedEndYear) { var calendar = new CalendarService(year, 1); (int actualBeginYear, int actualEndYear) = calendar.CalculateDecade(); Assert.Equal(expectedBeginYear, actualBeginYear); Assert.Equal(expectedEndYear, actualEndYear); } [Fact] public void Calendar_should_create_correct_month() { // Arrange CalendarService calendar = new CalendarService(2018, 11); // Act int [,] actual = calendar.GetMonthArray(); int[,] expected = { { 0, 0, 0, 0, 1, 2, 3 }, { 4, 5, 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15, 16, 17 }, { 18, 19, 20, 21, 22, 23, 24 }, { 25, 26, 27, 28, 29, 30, 0 }, { 0, 0, 0, 0, 0, 0, 0 }, }; // Assert Assert.Equal<int[,]>(expected, actual); } [Theory] [InlineData(int.MinValue,int.MinValue)] [InlineData(int.MaxValue,int.MaxValue)] [InlineData(2019,int.MinValue)] [InlineData(2019,int.MaxValue)] public void Calendar_should_throw_ArgumentOutOfRangeException(int year, int month) { Assert.Throws<ArgumentOutOfRangeException>(new Action(() => { var calendarService = new CalendarService(year, month); })); } [Fact] public void Should_not_throw_any_exception() { var calendarService = new CalendarService(0, 0); calendarService.GetMonthArray(); } [Theory] [InlineData(2019, 1, "January")] [InlineData(2019, 2, "February")] [InlineData(2019, 3, "March")] [InlineData(2019, 4, "April")] [InlineData(2019, 5, "May")] [InlineData(2019, 6, "June")] [InlineData(2019, 7, "July")] [InlineData(2019, 8, "August")] [InlineData(2019, 9, "September")] [InlineData(2019, 10, "October")] [InlineData(2019, 11, "November")] [InlineData(2019, 12, "December")] public void Should_convert_month_number_to_text(int year, int month, string expected) { var calendarService = new CalendarService(year, month); string actual = calendarService.GetMonthName(); Assert.Equal(expected, actual); } [Theory] [InlineData(2019, 1, 2019, 2)] [InlineData(2019, 12, 2020, 1)] [InlineData(2239, 12, 1940, 1)] public void Should_get_next_month(int year, int month, int expectedYear, int expectedMonth) { var calendarService = new CalendarService(year, month); (int actualYear, int actualMonth) = calendarService.GetNextMonth(); Assert.Equal(expectedYear, actualYear); Assert.Equal(expectedMonth, actualMonth); } [Theory] [InlineData(2019, 1, 2018, 12)] [InlineData(2019, 2, 2019, 1)] [InlineData(1940, 1, 2239, 12)] public void Should_get_previous_month(int year, int month, int expectedYear, int expectedMonth) { var calendarService = new CalendarService(year, month); (int actualYear, int actualMonth) = calendarService.GetPreviousMonth(); Assert.Equal(expectedYear, actualYear); Assert.Equal(expectedMonth, actualMonth); } [Theory] [InlineData(2019, 2020)] [InlineData(2239, 1940)] public void Should_get_next_year(int year, int expectedYear) { var calendarService = new CalendarService(year, 1); int actualYear = calendarService.GetNextYear(); Assert.Equal(expectedYear, actualYear); } [Theory] [InlineData(2019, 2018)] [InlineData(1940, 2239)] public void Should_get_previous_year(int year, int expectedYear) { var calendarService = new CalendarService(year, 1); int actualYear = calendarService.GetPreviousYear(); Assert.Equal(expectedYear, actualYear); } } }
34.040268
105
0.570584
[ "MIT" ]
telebovich/Calendar
Calendar.Tests/CalendarTests.cs
5,072
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Xml.XPath; namespace MS.Internal.Xml.Cache { /// <summary> /// Implementation of a Node in the XPath/XQuery data model. /// 1. All nodes are stored in variable-size pages (max 65536 nodes/page) of XPathNode structuSR. /// 2. Pages are sequentially numbered. Nodes are allocated in strict document order. /// 3. Node references take the form of a (page, index) pair. /// 4. Each node explicitly stores a parent and a sibling reference. /// 5. If a node has one or more attributes and/or non-collapsed content children, then its first /// child is stored in the next slot. If the node is in the last slot of a page, then its first /// child is stored in the first slot of the next page. /// 6. Attributes are linked together at the start of the child list. /// 7. Namespaces are allocated in totally separate pages. Elements are associated with /// declared namespaces via a hashtable map in the document. /// 8. Name parts are always non-null (string.Empty for nodes without names) /// 9. XPathNodeInfoAtom contains all information that is common to many nodes in a /// document, and therefore is atomized to save space. This includes the document, the name, /// the child, sibling, parent, and value pages, and the schema type. /// 10. The node structure is 20 bytes in length. Out-of-line overhead is typically 2-4 bytes per node. /// </summary> internal struct XPathNode { private XPathNodeInfoAtom _info; // Atomized node information private ushort _idxSibling; // Page index of sibling node private ushort _idxParent; // Page index of parent node private ushort _idxSimilar; // Page index of next node in document order that has local name with same hashcode private ushort _posOffset; // Line position offset of node (added to LinePositionBase) private uint _props; // Node properties (broken down into bits below) private string _value; // String value of node private const uint NodeTypeMask = 0xF; private const uint HasAttributeBit = 0x10; private const uint HasContentChildBit = 0x20; private const uint HasElementChildBit = 0x40; private const uint HasCollapsedTextBit = 0x80; private const uint AllowShortcutTagBit = 0x100; // True if this is an element that allows shortcut tag syntax private const uint HasNmspDeclsBit = 0x200; // True if this is an element with namespace declarations declared on it private const uint LineNumberMask = 0x00FFFC00; // 14 bits for line number offset (0 - 16K) private const int LineNumberShift = 10; private const int CollapsedPositionShift = 24; // 8 bits for collapsed text position offset (0 - 256) #if DEBUG public const int MaxLineNumberOffset = 0x20; public const int MaxLinePositionOffset = 0x20; public const int MaxCollapsedPositionOffset = 0x10; #else public const int MaxLineNumberOffset = 0x3FFF; public const int MaxLinePositionOffset = 0xFFFF; public const int MaxCollapsedPositionOffset = 0xFF; #endif /// <summary> /// Returns the type of this node /// </summary> public XPathNodeType NodeType { get { return (XPathNodeType)(_props & NodeTypeMask); } } /// <summary> /// Returns the namespace prefix of this node. If this node has no prefix, then the empty string /// will be returned (never null). /// </summary> public string Prefix { get { return _info.Prefix; } } /// <summary> /// Returns the local name of this node. If this node has no name, then the empty string /// will be returned (never null). /// </summary> public string LocalName { get { return _info.LocalName; } } /// <summary> /// Returns the name of this node. If this node has no name, then the empty string /// will be returned (never null). /// </summary> public string Name { get { if (Prefix.Length == 0) { return LocalName; } else { return string.Concat(Prefix, ":", LocalName); } } } /// <summary> /// Returns the namespace part of this node's name. If this node has no name, then the empty string /// will be returned (never null). /// </summary> public string NamespaceUri { get { return _info.NamespaceUri; } } /// <summary> /// Returns this node's document. /// </summary> public XPathDocument Document { get { return _info.Document; } } /// <summary> /// Returns this node's base Uri. This is string.Empty for all node kinds except Element, Root, and PI. /// </summary> public string BaseUri { get { return _info.BaseUri; } } /// <summary> /// Returns this node's source line number. /// </summary> public int LineNumber { get { return _info.LineNumberBase + (int)((_props & LineNumberMask) >> LineNumberShift); } } /// <summary> /// Return this node's source line position. /// </summary> public int LinePosition { get { return _info.LinePositionBase + (int)_posOffset; } } /// <summary> /// If this node is an element with collapsed text, then return the source line position of the node (the /// source line number is the same as LineNumber). /// </summary> public int CollapsedLinePosition { get { Debug.Assert(HasCollapsedText, "Do not call CollapsedLinePosition unless HasCollapsedText is true."); return LinePosition + (int)(_props >> CollapsedPositionShift); } } /// <summary> /// Returns information about the node page. Only the 0th node on each page has this property defined. /// </summary> public XPathNodePageInfo PageInfo { get { return _info.PageInfo; } } /// <summary> /// Returns the root node of the current document. This always succeeds. /// </summary> public int GetRoot(out XPathNode[] pageNode) { return _info.Document.GetRootNode(out pageNode); } /// <summary> /// Returns the parent of this node. If this node has no parent, then 0 is returned. /// </summary> public int GetParent(out XPathNode[] pageNode) { pageNode = _info.ParentPage; return _idxParent; } /// <summary> /// Returns the next sibling of this node. If this node has no next sibling, then 0 is returned. /// </summary> public int GetSibling(out XPathNode[] pageNode) { pageNode = _info.SiblingPage; return _idxSibling; } /// <summary> /// Returns the next element in document order that has the same local name hashcode as this element. /// If there are no similar elements, then 0 is returned. /// </summary> public int GetSimilarElement(out XPathNode[] pageNode) { pageNode = _info.SimilarElementPage; return _idxSimilar; } /// <summary> /// Returns true if this node's name matches the specified localName and namespaceName. Assume /// that localName has been atomized, but namespaceName has not. /// </summary> public bool NameMatch(string localName, string namespaceName) { Debug.Assert(localName == null || (object)Document.NameTable.Get(localName) == (object)localName, "localName must be atomized."); return (object)_info.LocalName == (object)localName && _info.NamespaceUri == namespaceName; } /// <summary> /// Returns true if this is an Element node with a name that matches the specified localName and /// namespaceName. Assume that localName has been atomized, but namespaceName has not. /// </summary> public bool ElementMatch(string localName, string namespaceName) { Debug.Assert(localName == null || (object)Document.NameTable.Get(localName) == (object)localName, "localName must be atomized."); return NodeType == XPathNodeType.Element && (object)_info.LocalName == (object)localName && _info.NamespaceUri == namespaceName; } /// <summary> /// Return true if this node is an xmlns:xml node. /// </summary> public bool IsXmlNamespaceNode { get { string localName = _info.LocalName; return NodeType == XPathNodeType.Namespace && localName.Length == 3 && localName == "xml"; } } /// <summary> /// Returns true if this node has a sibling. /// </summary> public bool HasSibling { get { return _idxSibling != 0; } } /// <summary> /// Returns true if this node has a collapsed text node as its only content-typed child. /// </summary> public bool HasCollapsedText { get { return (_props & HasCollapsedTextBit) != 0; } } /// <summary> /// Returns true if this node has at least one attribute. /// </summary> public bool HasAttribute { get { return (_props & HasAttributeBit) != 0; } } /// <summary> /// Returns true if this node has at least one content-typed child (attributes and namespaces /// don't count). /// </summary> public bool HasContentChild { get { return (_props & HasContentChildBit) != 0; } } /// <summary> /// Returns true if this node has at least one element child. /// </summary> public bool HasElementChild { get { return (_props & HasElementChildBit) != 0; } } /// <summary> /// Returns true if this is an attribute or namespace node. /// </summary> public bool IsAttrNmsp { get { XPathNodeType xptyp = NodeType; return xptyp == XPathNodeType.Attribute || xptyp == XPathNodeType.Namespace; } } /// <summary> /// Returns true if this is a text or whitespace node. /// </summary> public bool IsText { get { return XPathNavigator.IsText(NodeType); } } /// <summary> /// Returns true if this node has local namespace declarations associated with it. Since all /// namespace declarations are stored out-of-line in the owner Document, this property /// can be consulted in order to avoid a lookup in the common case where this node has no /// local namespace declarations. /// </summary> public bool HasNamespaceDecls { get { return (_props & HasNmspDeclsBit) != 0; } set { if (value) _props |= HasNmspDeclsBit; else unchecked { _props &= (byte)~((uint)HasNmspDeclsBit); } } } /// <summary> /// Returns true if this node is an empty element that allows shortcut tag syntax. /// </summary> public bool AllowShortcutTag { get { return (_props & AllowShortcutTagBit) != 0; } } /// <summary> /// Cached hashcode computed over the local name of this element. /// </summary> public int LocalNameHashCode { get { return _info.LocalNameHashCode; } } /// <summary> /// Return the precomputed String value of this node (null if no value exists, i.e. document node, element node with complex content, etc). /// </summary> public string Value { get { return _value; } } //----------------------------------------------- // Node construction //----------------------------------------------- /// <summary> /// Constructs the 0th XPathNode in each page, which contains only page information. /// </summary> public void Create(XPathNodePageInfo pageInfo) { _info = new XPathNodeInfoAtom(pageInfo); } /// <summary> /// Constructs a XPathNode. Later, the idxSibling and value fields may be fixed up. /// </summary> public void Create(XPathNodeInfoAtom info, XPathNodeType xptyp, int idxParent) { Debug.Assert(info != null && idxParent <= ushort.MaxValue); _info = info; _props = (uint)xptyp; _idxParent = (ushort)idxParent; } /// <summary> /// Set this node's line number information. /// </summary> public void SetLineInfoOffsets(int lineNumOffset, int linePosOffset) { Debug.Assert(lineNumOffset >= 0 && lineNumOffset <= MaxLineNumberOffset, "Line number offset too large or small: " + lineNumOffset); Debug.Assert(linePosOffset >= 0 && linePosOffset <= MaxLinePositionOffset, "Line position offset too large or small: " + linePosOffset); _props |= ((uint)lineNumOffset << LineNumberShift); _posOffset = (ushort)linePosOffset; } /// <summary> /// Set the position offset of this element's collapsed text. /// </summary> public void SetCollapsedLineInfoOffset(int posOffset) { Debug.Assert(posOffset >= 0 && posOffset <= MaxCollapsedPositionOffset, "Collapsed text line position offset too large or small: " + posOffset); _props |= ((uint)posOffset << CollapsedPositionShift); } /// <summary> /// Set this node's value. /// </summary> public void SetValue(string value) { _value = value; } /// <summary> /// Create an empty element value. /// </summary> public void SetEmptyValue(bool allowShortcutTag) { Debug.Assert(NodeType == XPathNodeType.Element); _value = string.Empty; if (allowShortcutTag) _props |= AllowShortcutTagBit; } /// <summary> /// Create a collapsed text node on this element having the specified value. /// </summary> public void SetCollapsedValue(string value) { Debug.Assert(NodeType == XPathNodeType.Element); _value = value; _props |= HasContentChildBit | HasCollapsedTextBit; } /// <summary> /// This method is called when a new child is appended to this node's list of attributes and children. /// The type of the new child is used to determine how various parent properties should be set. /// </summary> public void SetParentProperties(XPathNodeType xptyp) { if (xptyp == XPathNodeType.Attribute) { _props |= HasAttributeBit; } else { _props |= HasContentChildBit; if (xptyp == XPathNodeType.Element) _props |= HasElementChildBit; } } /// <summary> /// Link this node to its next sibling. If "pageSibling" is different than the one stored in the InfoAtom, re-atomize. /// </summary> public void SetSibling(XPathNodeInfoTable infoTable, XPathNode[] pageSibling, int idxSibling) { Debug.Assert(pageSibling != null && idxSibling != 0 && idxSibling <= ushort.MaxValue, "Bad argument"); Debug.Assert(_idxSibling == 0, "SetSibling should not be called more than once."); _idxSibling = (ushort)idxSibling; if (pageSibling != _info.SiblingPage) { // Re-atomize the InfoAtom _info = infoTable.Create(_info.LocalName, _info.NamespaceUri, _info.Prefix, _info.BaseUri, _info.ParentPage, pageSibling, _info.SimilarElementPage, _info.Document, _info.LineNumberBase, _info.LinePositionBase); } } /// <summary> /// Link this element to the next element in document order that shares a local name having the same hash code. /// If "pageSimilar" is different than the one stored in the InfoAtom, re-atomize. /// </summary> public void SetSimilarElement(XPathNodeInfoTable infoTable, XPathNode[] pageSimilar, int idxSimilar) { Debug.Assert(pageSimilar != null && idxSimilar != 0 && idxSimilar <= ushort.MaxValue, "Bad argument"); Debug.Assert(_idxSimilar == 0, "SetSimilarElement should not be called more than once."); _idxSimilar = (ushort)idxSimilar; if (pageSimilar != _info.SimilarElementPage) { // Re-atomize the InfoAtom _info = infoTable.Create(_info.LocalName, _info.NamespaceUri, _info.Prefix, _info.BaseUri, _info.ParentPage, _info.SiblingPage, pageSimilar, _info.Document, _info.LineNumberBase, _info.LinePositionBase); } } } /// <summary> /// A reference to a XPathNode is composed of two values: the page on which the node is located, and the node's /// index in the page. /// </summary> internal struct XPathNodeRef { private readonly XPathNode[] _page; private readonly int _idx; public XPathNodeRef(XPathNode[] page, int idx) { _page = page; _idx = idx; } public XPathNode[] Page { get { return _page; } } public int Index { get { return _idx; } } public override int GetHashCode() { return XPathNodeHelper.GetLocation(_page, _idx); } } }
38.053678
156
0.565906
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNode.cs
19,141
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Coimbra.BuildManagement.Editor.Global")] [assembly: InternalsVisibleTo("Coimbra.BuildManagement.Editor.Local")]
36.6
71
0.836066
[ "MIT" ]
coimbrastudios/buildmanagement
Coimbra.BuildManagement.Editor/AssemblyInfo.cs
183
C#
namespace WpfApp1 { public class PageFourViewModel { } }
11.5
34
0.637681
[ "MIT" ]
hamgeorge/MvvmResearch
src/MvvmResearch/NavigationIoC/ViewModel/PageFourViewModel.cs
71
C#
using NUnit.Framework; namespace WindowsPrometheusSync.Test { [TestFixture(Category = "Unit")] public class KubernetesClientFactoryTests { /// <summary> /// CYA test to hopefully keep us from checking this in with the local config enabled /// </summary> [Test] public void EnsureWereNotUsingLocalK8SConfig() { Assert.IsFalse(new KubernetesClientFactory().UseLocalConfig); } } }
25.777778
93
0.635776
[ "MIT" ]
aidapsibr/aks-prometheus-windows-exporter
WindowsPrometheusSync.Test/KubernetesClientFactoryTests.cs
466
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using BusinessLayer; using ExceptionLayer; public partial class sayfalar_yoneticiWuc_emlakEkle_Basla : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { DDdoldur(); EmlakTipGetir(); IsitmaTipGetir(); kategoriGetirTum(); if (Session["eGuncelleId"] != null) { lblEmlakBaslik.Text = "Emlak Güncelle"; btnEmlakEkleBasla.Text = "Emlak Güncelle Adım 1"; btnEmlakEkleBasla.Width = 160; int emlakId = Convert.ToInt32(Session["eGuncelleId"].ToString()); GuncelleEmlakGetirId(emlakId); } } } public void GuncelleEmlakGetirId(int emlakId) { emlakGetir egg = new emlakGetir(); emlak e = new emlak(); e = egg.emlakGetirId(emlakId); txtAidat.Text = e.Aidat; txtBalkonSayisi.Text = e.BalkonSayisi.ToString(); txtBanyoSayisi.Text = e.BanyoSayisi.ToString(); txtBinadakiKatSayisi.Text = e.BinadakiKatSayisi.ToString(); txtBinaYasi.Text = e.BinaYasi.ToString(); txtBulunduguKat.Text = e.BulunduguKat.ToString(); txtDeposit.Text = e.Deposit.ToString(); txtDurumu.Text = e.Durumu; txtEmlakAciklamasi.Text = e.EmlakAciklama; txtEmlakBaslik.Text = e.EmlakBaslik; txtEmlakM2.Text = e.EmlakM2; txtEmlakReferansNo.Text = e.EmlakReferansNo.ToString(); txtOdaSayisi.Text = e.OdaSayisi; txtTapuDurumu.Text = e.TapuDurumu; cbKrediyeUygunMu.Checked = e.KrediyeUygun; int indeks = 0; foreach (ListItem kategori in ddEmlakKategori.Items) { if (kategori.Value.ToString() == e.KategoriId.ToString()) { ddEmlakKategori.SelectedIndex = indeks; indeks = 0; break; } indeks++; } foreach (ListItem emlakTip in ddEmlakTipi.Items) { if (emlakTip.Value.ToString() == e.EmlakTipId.ToString()) { ddEmlakTipi.SelectedIndex = indeks; indeks = 0; break; } indeks++; } foreach (ListItem isitmaTip in ddIsitmaTipi.Items) { if (isitmaTip.Value.ToString() == e.IsitmaTipId.ToString()) { ddIsitmaTipi.SelectedIndex = indeks; indeks = 0; break; } indeks++; } } public void DDdoldur() { ListItem li = new ListItem(); li.Text = "Emlak tipini Seçiniz..."; ddEmlakTipi.Items.Add(li); ListItem li2 = new ListItem(); li2.Text = "Isıtma tipini Seçiniz..."; ddIsitmaTipi.Items.Add(li2); ListItem li3 = new ListItem(); li3.Text = "Kategori Seçiniz..."; ddEmlakKategori.Items.Add(li3); } public void EmlakTipGetir() { try { emlakTipGetir etg = new emlakTipGetir(); foreach (emlakTip item in etg.emlakTipGetirTum()) { ListItem li = new ListItem(); li.Text = item.EmlakTipAd; li.Value = item.EmlakTipId.ToString(); ddEmlakTipi.Items.Add(li); } } catch (Exception ex) { hDepo.HataYakalaTUM(ex); } } HataDEPOSU hDepo = new HataDEPOSU(); public void IsitmaTipGetir() { try { isitmaTipGetir itg = new isitmaTipGetir(); foreach (isitmaTip item in itg.isitmaTipGetirTum()) { ListItem li = new ListItem(); li.Text = item.IsitmaTipAd; li.Value = item.IsitmaTipId.ToString(); ddIsitmaTipi.Items.Add(li); } } catch (Exception ex) { hDepo.HataYakalaTUM(ex); } } public void kategoriGetirTum() { try { kategoriGetir kg = new kategoriGetir(); foreach (kategori item in kg.kategoriGetirTum()) { ListItem li = new ListItem(); li.Text = item.KategoriAd.ToString(); li.Value = item.KategoriId.ToString(); ddEmlakKategori.Items.Add(li); } } catch (Exception ex) { hDepo.HataYakalaTUM(ex); } } protected void btnEmlakEkleBasla_Click(object sender, EventArgs e) { try { if (ddEmlakKategori.SelectedIndex != 0 && ddEmlakTipi.SelectedIndex != 0 && ddIsitmaTipi.SelectedIndex != 0) { emlak emlk = new emlak(); emlk.Aidat = txtAidat.Text; emlk.BanyoSayisi = txtBanyoSayisi.Text; emlk.BinadakiKatSayisi = Convert.ToInt32(txtBanyoSayisi.Text); emlk.BinaYasi = Convert.ToInt32(txtBinaYasi.Text); emlk.BulunduguKat = Convert.ToInt32(txtBulunduguKat.Text); emlk.Deposit = txtDeposit.Text; emlk.Durumu = txtDurumu.Text; emlk.EmlakAciklama = txtEmlakAciklamasi.Text; emlk.EmlakBaslik = txtEmlakBaslik.Text; emlk.EmlakM2 = txtEmlakM2.Text; emlk.EmlakReferansNo = Convert.ToInt32(txtEmlakReferansNo.Text); emlk.EmlakTipId = Convert.ToInt32(ddEmlakTipi.SelectedValue); emlk.IsitmaTipId = Convert.ToInt32(ddIsitmaTipi.SelectedValue); emlk.KrediyeUygun = Convert.ToBoolean(cbKrediyeUygunMu.Checked); emlk.OdaSayisi = txtOdaSayisi.Text; emlk.TapuDurumu = txtTapuDurumu.Text; emlk.KategoriId = Convert.ToInt32(ddEmlakKategori.SelectedValue); emlk.BalkonSayisi = Convert.ToInt32(txtBalkonSayisi.Text); if (btnEmlakEkleBasla.Text == "Emlak Ekle Adım 1") { emlakEkle ee = new emlakEkle(); int sonuc = ee.emlakEkleString(emlk); if (sonuc > 0) { lblSonuc.Text = "Emlak Eklendi."; SonEmlakIdGetir(); btnEmlakEkleBasla.Enabled = false; } else { lblSonuc.Text = "Ekleme başarısız!"; } } else { emlk.EmlakId = Convert.ToInt32(Session["eGuncelleId"]); emlakGuncelle eggg = new emlakGuncelle(); int sonuc = eggg.emlakGuncelleMetod(emlk); if (sonuc > 0) { lblSonuc.Text = "Emlak Güncellendi."; } else { lblSonuc.Text = "Güncelleme Başarısız!"; } } } else { lblSonuc.Text = "Lütfen Kategori, EmlakTip, IsıtmaTip bölümlerini doldurunuz."; } } catch (Exception ex) { hDepo.HataYakalaTUM(ex); } } public void SonEmlakIdGetir() { emlakGetir eg = new emlakGetir(); Session["sonEmlakId"] = eg.emlakIdGetirSonEklenen(); } protected void lbSonrakiAdim_Click(object sender, EventArgs e) { Response.Redirect("emlakEkle_Fiyat.aspx"); } }
34.074561
120
0.520015
[ "MIT" ]
fatihyildizhan/csharp-2010-older-projects
DoxaEmlak/DoxaTuranEmlak/sayfalar/yoneticiWuc/emlakEkle_Basla.ascx.cs
7,791
C#
//------------------------------------------------------------------------------ // <copyright file="StatusBarPanelStyle.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.Windows.Forms { using System.Diagnostics; using System; using System.ComponentModel; using System.Drawing; using Microsoft.Win32; /// <include file='doc\StatusBarPanelStyle.uex' path='docs/doc[@for="StatusBarPanelStyle"]/*' /> /// <devdoc> /// <para> /// Specifies whether a panel on /// a status bar is owner drawn or system drawn. /// </para> /// </devdoc> public enum StatusBarPanelStyle { /// <include file='doc\StatusBarPanelStyle.uex' path='docs/doc[@for="StatusBarPanelStyle.Text"]/*' /> /// <devdoc> /// <para> /// The panel is /// drawn by the system. /// </para> /// </devdoc> Text = 1, /// <include file='doc\StatusBarPanelStyle.uex' path='docs/doc[@for="StatusBarPanelStyle.OwnerDraw"]/*' /> /// <devdoc> /// <para> /// The panel is /// drawn by the owner. /// </para> /// </devdoc> OwnerDraw = 2, } }
31.520833
115
0.437541
[ "Unlicense" ]
bestbat/Windows-Server
com/netfx/src/framework/winforms/managed/system/winforms/statusbarpanelstyle.cs
1,513
C#
using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace NetFabric.Hyperlinq { public static partial class AsyncValueEnumerableExtensions { [GeneratorMapping("TSelector", "NetFabric.Hyperlinq.AsyncFunctionWrapper<TSource, TResult>")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static SelectEnumerable<TEnumerable, TEnumerator, TSource, TResult, AsyncFunctionWrapper<TSource, TResult>> Select<TEnumerable, TEnumerator, TSource, TResult>(this TEnumerable source, Func<TSource, CancellationToken, ValueTask<TResult>> selector) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> => source.Select<TEnumerable, TEnumerator, TSource, TResult, AsyncFunctionWrapper<TSource, TResult>>(new AsyncFunctionWrapper<TSource, TResult>(selector)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static SelectEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector> Select<TEnumerable, TEnumerator, TSource, TResult, TSelector>(this TEnumerable source, TSelector selector = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, TResult> => new(in source, selector); [GeneratorMapping("TSource", "TResult")] [StructLayout(LayoutKind.Auto)] public readonly partial struct SelectEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector> : IAsyncValueEnumerable<TResult, SelectEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector>.Enumerator> where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, TResult> { internal readonly TEnumerable source; internal readonly TSelector selector; internal SelectEnumerable(in TEnumerable source, TSelector selector) => (this.source, this.selector) = (source, selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Enumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) => new(in this, cancellationToken); IAsyncEnumerator<TResult> IAsyncEnumerable<TResult>.GetAsyncEnumerator(CancellationToken cancellationToken) // ReSharper disable once HeapView.BoxingAllocation => new Enumerator(in this, cancellationToken); [StructLayout(LayoutKind.Auto)] public struct Enumerator : IAsyncEnumerator<TResult> , IAsyncStateMachine { #pragma warning disable IDE0044 // Add readonly modifier TEnumerator enumerator; TSelector selector; #pragma warning restore IDE0044 // Add readonly modifier readonly CancellationToken cancellationToken; int state; AsyncValueTaskMethodBuilder<bool> builder; #pragma warning disable IDE1006 // Naming Styles bool s__1; TResult? s__2; #pragma warning restore IDE1006 // Naming Styles ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter u__1; ConfiguredValueTaskAwaitable<TResult>.ConfiguredValueTaskAwaiter u__2; ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter u__3; internal Enumerator(in SelectEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector> enumerable, CancellationToken cancellationToken) { enumerator = enumerable.source.GetAsyncEnumerator(cancellationToken); selector = enumerable.selector; this.cancellationToken = cancellationToken; Current = default!; state = -1; builder = default; s__1 = default; s__2 = default; u__1 = default; u__2 = default; u__3 = default; } public TResult Current { get; private set; } readonly TResult IAsyncEnumerator<TResult>.Current => Current; //public async ValueTask<bool> MoveNextAsync() //{ // if (await enumerator.MoveNextAsync().ConfigureAwait(false)) // { // Current = await selector(enumerator.Current, cancellationToken).ConfigureAwait(false); // return true; // } // await DisposeAsync().ConfigureAwait(false); // return false; //} public ValueTask<bool> MoveNextAsync() { state = -1; builder = AsyncValueTaskMethodBuilder<bool>.Create(); builder.Start(ref this); return builder.Task; } public ValueTask DisposeAsync() => enumerator.DisposeAsync(); void IAsyncStateMachine.MoveNext() { var num = state; bool result; try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter3; ConfiguredValueTaskAwaitable<TResult>.ConfiguredValueTaskAwaiter awaiter2; ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter; switch (num) { default: awaiter3 = enumerator.MoveNextAsync().ConfigureAwait(false).GetAwaiter(); if (!awaiter3.IsCompleted) { num = state = 0; u__1 = awaiter3; builder.AwaitUnsafeOnCompleted(ref awaiter3, ref this); return; } goto IL_0099; case 0: awaiter3 = u__1; u__1 = default; num = state = -1; goto IL_0099; case 1: awaiter2 = u__2; u__2 = default; num = state = -1; goto IL_0143; case 2: { awaiter = u__3; u__3 = default; num = state = -1; break; } IL_0143: s__2 = awaiter2.GetResult(); Current = s__2; s__2 = default; result = true; goto end_IL_0007; IL_0099: s__1 = awaiter3.GetResult(); if (!s__1) { awaiter = DisposeAsync().ConfigureAwait(false).GetAwaiter(); if (!awaiter.IsCompleted) { num = state = 2; u__3 = awaiter; builder.AwaitUnsafeOnCompleted(ref awaiter, ref this); return; } break; } awaiter2 = selector.InvokeAsync(enumerator.Current, cancellationToken).ConfigureAwait(false).GetAwaiter(); if (!awaiter2.IsCompleted) { num = state = 1; u__2 = awaiter2; builder.AwaitUnsafeOnCompleted(ref awaiter2, ref this); return; } goto IL_0143; } awaiter.GetResult(); result = false; end_IL_0007: ; } catch (Exception exception) { state = -2; builder.SetException(exception); return; } state = -2; builder.SetResult(result); } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { } } #region Aggregation [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask<int> CountAsync(CancellationToken cancellationToken = default) => source.CountAsync<TEnumerable, TEnumerator, TSource>(cancellationToken); #endregion #region Quantifier [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask<bool> AnyAsync(CancellationToken cancellationToken = default) => source.AnyAsync<TEnumerable, TEnumerator, TSource>(cancellationToken); #endregion #region Filtering #endregion #region Projection [MethodImpl(MethodImplOptions.AggressiveInlining)] public SelectEnumerable<TEnumerable, TEnumerator, TSource, TResult2, AsyncSelectorSelectorCombination<TSelector, AsyncFunctionWrapper<TResult, TResult2>, TSource, TResult, TResult2>> Select<TResult2>(Func<TResult, CancellationToken, ValueTask<TResult2>> selector) => Select<TResult2, AsyncFunctionWrapper<TResult, TResult2>>(new AsyncFunctionWrapper<TResult, TResult2>(selector)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public SelectEnumerable<TEnumerable, TEnumerator, TSource, TResult2, AsyncSelectorSelectorCombination<TSelector, TSelector2, TSource, TResult, TResult2>> Select<TResult2, TSelector2>(TSelector2 selector = default) where TSelector2 : struct, IAsyncFunction<TResult, TResult2> => source.Select<TEnumerable, TEnumerator, TSource, TResult2, AsyncSelectorSelectorCombination<TSelector, TSelector2, TSource, TResult, TResult2>>(new AsyncSelectorSelectorCombination<TSelector, TSelector2, TSource, TResult, TResult2>(this.selector, selector)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult2, AsyncSelectorSelectorAtCombination<TSelector, AsyncFunctionWrapper<TResult, int, TResult2>, TSource, TResult, TResult2>> Select<TResult2>(Func<TResult, int, CancellationToken, ValueTask<TResult2>> selector) => SelectAt<TResult2, AsyncFunctionWrapper<TResult, int, TResult2>>(new AsyncFunctionWrapper<TResult, int, TResult2>(selector)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult2, AsyncSelectorSelectorAtCombination<TSelector, TSelector2, TSource, TResult, TResult2>> SelectAt<TResult2, TSelector2>(TSelector2 selector = default) where TSelector2 : struct, IAsyncFunction<TResult, int, TResult2> => source.SelectAt<TEnumerable, TEnumerator, TSource, TResult2, AsyncSelectorSelectorAtCombination<TSelector, TSelector2, TSource, TResult, TResult2>>(new AsyncSelectorSelectorAtCombination<TSelector, TSelector2, TSource, TResult, TResult2>(this.selector, selector)); #endregion #region Element [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask<Option<TResult>> ElementAtAsync(int index, CancellationToken cancellationToken = default) => source.ElementAtAsync<TEnumerable, TEnumerator, TSource, TResult, TSelector>(index, cancellationToken, selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask<Option<TResult>> FirstAsync(CancellationToken cancellationToken = default) => source.FirstAsync<TEnumerable, TEnumerator, TSource, TResult, TSelector>(cancellationToken, selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask<Option<TResult>> SingleAsync(CancellationToken cancellationToken = default) => source.SingleAsync<TEnumerable, TEnumerator, TSource, TResult, TSelector>(cancellationToken, selector); #endregion #region Conversion [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken = default) => source.ToArrayAsync<TEnumerable, TEnumerator, TSource, TResult, TSelector>(cancellationToken, selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask<Lease<TResult>> ToArrayAsync(ArrayPool<TResult> pool, CancellationToken cancellationToken = default, bool clearOnDispose = default) => source.ToArrayAsync<TEnumerable, TEnumerator, TSource, TResult, TSelector>(pool, cancellationToken, clearOnDispose, selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken = default) => source.ToListAsync<TEnumerable, TEnumerator, TSource, TResult, TSelector>(cancellationToken, selector); #endregion } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<int> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, int, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, int> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, int, int, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<int> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, int?, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, int?> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, int?, int, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<nint> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, nint, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, nint> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, nint, nint, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<nint> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, nint?, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, nint?> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, nint?, nint, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<nuint> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, nuint, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, nuint> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, nuint, nuint, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<nuint> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, nuint?, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, nuint?> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, nuint?, nuint, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<long> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, long, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, long> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, long, long, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<long> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, long?, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, long?> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, long?, long, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<float> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, float, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, float> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, float, float, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<float> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, float?, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, float?> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, float?, float, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<double> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, double, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, double> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, double, double, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<double> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, double?, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, double?> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, double?, double, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<decimal> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, decimal, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, decimal> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, decimal, decimal, TSelector>(cancellationToken, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ValueTask<decimal> SumAsync<TEnumerable, TEnumerator, TSource, TSelector>(this SelectEnumerable<TEnumerable, TEnumerator, TSource, decimal?, TSelector> source, CancellationToken cancellationToken = default) where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator> where TEnumerator : struct, IAsyncEnumerator<TSource> where TSelector : struct, IAsyncFunction<TSource, decimal?> => source.source.SumAsync<TEnumerable, TEnumerator, TSource, decimal?, decimal, TSelector>(cancellationToken, source.selector); } }
63.334232
289
0.634379
[ "MIT" ]
NetFabric/Hyperlinq
NetFabric.Hyperlinq/Projection/Select/Select/Select.AsyncValueEnumerable.cs
23,499
C#
using System.IO; using System.Xml; using System.Text; using System.Xml.Serialization; using UnityEngine; namespace GPVUDK { /// <summary> /// Utility for XML serialization. /// </summary> public class XmlUtil { /// <summary> /// Read an object from an XML file. /// </summary> /// <typeparam name="T">Serializable type.</typeparam> /// <param name="dataHolder">Object to be read.</param> /// <param name="filePath">Path to the XML file.</param> /// <returns>true on success or false on error.</returns> static public bool ReadFromFile<T>(ref T dataHolder, string filePath) { if (string.IsNullOrEmpty(filePath)) { Debug.LogErrorFormat("Empty input file path"); return false; } try { // Load XmlSceneData from XML XmlSerializer serializer = new XmlSerializer(typeof(T)); FileStream stream = new FileStream(filePath, FileMode.Open); dataHolder = (T)serializer.Deserialize(stream); stream.Dispose(); } catch (IOException) { Debug.LogErrorFormat("Unable to read XML file {0}", filePath); return false; } return true; } /// <summary> /// Serialize an object to an XML file. /// </summary> /// <typeparam name="T">Serializable type.</typeparam> /// <param name="dataHolder">Object to be serialized.</param> /// <param name="filePath">Path to the XML file.</param> /// <returns>true on success or false on error.</returns> static public bool WriteToFile<T>(T dataHolder, string filePath) { if (string.IsNullOrEmpty(filePath)) { Debug.LogErrorFormat("Empty output file path"); return false; } try { // Setup XML output settings XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; settings.Encoding = Encoding.UTF8; settings.CheckCharacters = true; // Write data to XML XmlSerializer serializer = new XmlSerializer(typeof(T)); FileStream stream = new FileStream(filePath, FileMode.Create); XmlWriter w = XmlWriter.Create(stream, settings); serializer.Serialize(w, dataHolder); stream.Dispose(); } catch (IOException e) { Debug.LogErrorFormat("Unable to write XML file {0}\n{1}", filePath, e); return false; } return true; } } }
34.164706
87
0.524105
[ "MIT" ]
gpvigano/GPVUDK
UnityProjects/GPVUDK/Assets/GPVUDK/Common/Scripts/Data/XmlUtil.cs
2,906
C#
using System.Runtime.CompilerServices; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.StyleSheets; [assembly: InternalsVisibleTo("iOSUnitTests")] [assembly: InternalsVisibleTo("Xamarin.Forms.Controls")] [assembly: InternalsVisibleTo("Xamarin.Forms.Core.Design")] [assembly: InternalsVisibleTo("Xamarin.Forms.Core.UnitTests")] [assembly: InternalsVisibleTo("Xamarin.Forms.Core.Android.UnitTests")] [assembly: InternalsVisibleTo("Xamarin.Forms.Xaml")] [assembly: InternalsVisibleTo("Xamarin.Forms.Maps")] [assembly: InternalsVisibleTo("Xamarin.Forms.Maps.iOS")] [assembly: InternalsVisibleTo("Xamarin.Forms.Maps.iOS.Classic")] [assembly: InternalsVisibleTo("Xamarin.Forms.Maps.Android")] [assembly: InternalsVisibleTo("Xamarin.Forms.Xaml.UnitTests")] [assembly: InternalsVisibleTo("Xamarin.Forms.UITests")] [assembly: InternalsVisibleTo("Xamarin.Forms.FlexLayout.UnitTests")] <<<<<<< HEAD [assembly: InternalsVisibleTo("Xamarin.Forms.Material")] ======= [assembly: InternalsVisibleTo("Xamarin.Forms.Material.iOS")] >>>>>>> Update (#12) [assembly: InternalsVisibleTo("Xamarin.Forms.Core.iOS.UITests")] [assembly: InternalsVisibleTo("Xamarin.Forms.Core.Android.UITests")] [assembly: InternalsVisibleTo("Xamarin.Forms.Core.Windows.UITests")] [assembly: InternalsVisibleTo("Xamarin.Forms.Core.macOS.UITests")] [assembly: InternalsVisibleTo("Xamarin.Forms.iOS.UITests")] [assembly: InternalsVisibleTo("Xamarin.Forms.Android.UITests")] [assembly: InternalsVisibleTo("Xamarin.Forms.Loader")] // Xamarin.Forms.Loader.dll, Xamarin.Forms.Internals.ResourceLoader.ResourceProvider, kzu@microsoft.com [assembly: InternalsVisibleTo("Xamarin.HotReload.Forms")] [assembly: InternalsVisibleTo("Xamarin.Forms.UITest.Validator")] [assembly: InternalsVisibleTo("Xamarin.Forms.Build.Tasks")] [assembly: InternalsVisibleTo("Xamarin.Forms.Platform")] [assembly: InternalsVisibleTo("Xamarin.Forms.Pages")] [assembly: InternalsVisibleTo("Xamarin.Forms.Pages.UnitTests")] [assembly: InternalsVisibleTo("Xamarin.Forms.CarouselView")] [assembly: Preserve] [assembly: XmlnsDefinition("http://xamarin.com/schemas/2014/forms", "Xamarin.Forms")] [assembly: XmlnsDefinition("http://xamarin.com/schemas/2014/forms/design", "Xamarin.Forms")] [assembly: XmlnsPrefix("http://xamarin.com/schemas/2014/forms", "xf")] [assembly: XmlnsPrefix("http://xamarin.com/schemas/2014/forms/design", "d")] [assembly: StyleProperty("background-color", typeof(VisualElement), nameof(VisualElement.BackgroundColorProperty))] [assembly: StyleProperty("background-image", typeof(Page), nameof(Page.BackgroundImageSourceProperty))] [assembly: StyleProperty("border-color", typeof(IBorderElement), nameof(BorderElement.BorderColorProperty))] [assembly: StyleProperty("border-radius", typeof(ICornerElement), nameof(CornerElement.CornerRadiusProperty))] [assembly: StyleProperty("border-radius", typeof(IBorderElement), nameof(BorderElement.CornerRadiusProperty))] [assembly: StyleProperty("border-width", typeof(IBorderElement), nameof(BorderElement.BorderWidthProperty))] [assembly: StyleProperty("color", typeof(IColorElement), nameof(ColorElement.ColorProperty), Inherited = true)] [assembly: StyleProperty("color", typeof(ITextElement), nameof(TextElement.TextColorProperty), Inherited = true)] [assembly: StyleProperty("color", typeof(ProgressBar), nameof(ProgressBar.ProgressColorProperty))] [assembly: StyleProperty("color", typeof(Switch), nameof(Switch.OnColorProperty))] <<<<<<< HEAD <<<<<<< HEAD [assembly: StyleProperty("column-gap", typeof(Grid), nameof(Grid.ColumnSpacingProperty))] ======= [assembly: StyleProperty("column-gap", typeof(Grid), nameof(Grid.RowSpacingProperty))] >>>>>>> Update from origin (#8) ======= [assembly: StyleProperty("column-gap", typeof(Grid), nameof(Grid.ColumnSpacingProperty))] >>>>>>> Update from origin (#11) [assembly: StyleProperty("direction", typeof(VisualElement), nameof(VisualElement.FlowDirectionProperty), Inherited = true)] [assembly: StyleProperty("font-family", typeof(IFontElement), nameof(FontElement.FontFamilyProperty), Inherited = true)] [assembly: StyleProperty("font-size", typeof(IFontElement), nameof(FontElement.FontSizeProperty), Inherited = true)] [assembly: StyleProperty("font-style", typeof(IFontElement), nameof(FontElement.FontAttributesProperty), Inherited = true)] [assembly: StyleProperty("height", typeof(VisualElement), nameof(VisualElement.HeightRequestProperty))] [assembly: StyleProperty("margin", typeof(View), nameof(View.MarginProperty))] [assembly: StyleProperty("margin-left", typeof(View), nameof(View.MarginLeftProperty))] [assembly: StyleProperty("margin-top", typeof(View), nameof(View.MarginTopProperty))] [assembly: StyleProperty("margin-right", typeof(View), nameof(View.MarginRightProperty))] [assembly: StyleProperty("margin-bottom", typeof(View), nameof(View.MarginBottomProperty))] [assembly: StyleProperty("max-lines", typeof(Label), nameof(Label.MaxLinesProperty))] [assembly: StyleProperty("min-height", typeof(VisualElement), nameof(VisualElement.MinimumHeightRequestProperty))] [assembly: StyleProperty("min-width", typeof(VisualElement), nameof(VisualElement.MinimumWidthRequestProperty))] [assembly: StyleProperty("opacity", typeof(VisualElement), nameof(VisualElement.OpacityProperty))] [assembly: StyleProperty("padding", typeof(IPaddingElement), nameof(PaddingElement.PaddingProperty))] [assembly: StyleProperty("padding-left", typeof(IPaddingElement), nameof(PaddingElement.PaddingLeftProperty), PropertyOwnerType = typeof(PaddingElement))] [assembly: StyleProperty("padding-top", typeof(IPaddingElement), nameof(PaddingElement.PaddingTopProperty), PropertyOwnerType = typeof(PaddingElement))] [assembly: StyleProperty("padding-right", typeof(IPaddingElement), nameof(PaddingElement.PaddingRightProperty), PropertyOwnerType = typeof(PaddingElement))] [assembly: StyleProperty("padding-bottom", typeof(IPaddingElement), nameof(PaddingElement.PaddingBottomProperty), PropertyOwnerType = typeof(PaddingElement))] [assembly: StyleProperty("row-gap", typeof(Grid), nameof(Grid.RowSpacingProperty))] [assembly: StyleProperty("text-align", typeof(ITextAlignmentElement), nameof(TextAlignmentElement.HorizontalTextAlignmentProperty), Inherited = true)] [assembly: StyleProperty("text-decoration", typeof(IDecorableTextElement), nameof(DecorableTextElement.TextDecorationsProperty))] [assembly: StyleProperty("transform", typeof(VisualElement), nameof(VisualElement.TransformProperty))] [assembly: StyleProperty("transform-origin", typeof(VisualElement), nameof(VisualElement.TransformOriginProperty))] <<<<<<< HEAD //[assembly: StyleProperty("vertical-align", /*typeof(Label), nameof(Label.VerticalTextAlignmentProperty)*/)] ======= [assembly: StyleProperty("vertical-align", typeof(Label), nameof(Label.VerticalTextAlignment))] >>>>>>> Update from origin (#8) [assembly: StyleProperty("visibility", typeof(VisualElement), nameof(VisualElement.IsVisibleProperty), Inherited = true)] [assembly: StyleProperty("width", typeof(VisualElement), nameof(VisualElement.WidthRequestProperty))] [assembly: StyleProperty("line-height", typeof(ILineHeightElement), nameof(LineHeightElement.LineHeightProperty), Inherited = true)] //flex [assembly: StyleProperty("align-content", typeof(FlexLayout), nameof(FlexLayout.AlignContentProperty))] [assembly: StyleProperty("align-items", typeof(FlexLayout), nameof(FlexLayout.AlignItemsProperty))] [assembly: StyleProperty("align-self", typeof(VisualElement), nameof(FlexLayout.AlignSelfProperty), PropertyOwnerType = typeof(FlexLayout))] [assembly: StyleProperty("flex-direction", typeof(FlexLayout), nameof(FlexLayout.DirectionProperty))] [assembly: StyleProperty("flex-basis", typeof(VisualElement), nameof(FlexLayout.BasisProperty), PropertyOwnerType = typeof(FlexLayout))] [assembly: StyleProperty("flex-grow", typeof(VisualElement), nameof(FlexLayout.GrowProperty), PropertyOwnerType = typeof(FlexLayout))] [assembly: StyleProperty("flex-shrink", typeof(VisualElement), nameof(FlexLayout.ShrinkProperty), PropertyOwnerType = typeof(FlexLayout))] [assembly: StyleProperty("flex-wrap", typeof(VisualElement), nameof(FlexLayout.WrapProperty), PropertyOwnerType = typeof(FlexLayout))] [assembly: StyleProperty("justify-content", typeof(FlexLayout), nameof(FlexLayout.JustifyContentProperty))] [assembly: StyleProperty("order", typeof(VisualElement), nameof(FlexLayout.OrderProperty), PropertyOwnerType = typeof(FlexLayout))] [assembly: StyleProperty("position", typeof(FlexLayout), nameof(FlexLayout.PositionProperty))] //xf specific [assembly: StyleProperty("-xf-placeholder", typeof(IPlaceholderElement), nameof(PlaceholderElement.PlaceholderProperty))] [assembly: StyleProperty("-xf-placeholder-color", typeof(IPlaceholderElement), nameof(PlaceholderElement.PlaceholderColorProperty))] [assembly: StyleProperty("-xf-max-length", typeof(InputView), nameof(InputView.MaxLengthProperty))] [assembly: StyleProperty("-xf-bar-background-color", typeof(IBarElement), nameof(BarElement.BarBackgroundColorProperty))] [assembly: StyleProperty("-xf-bar-text-color", typeof(IBarElement), nameof(BarElement.BarTextColorProperty))] [assembly: StyleProperty("-xf-orientation", typeof(ScrollView), nameof(ScrollView.OrientationProperty))] [assembly: StyleProperty("-xf-horizontal-scroll-bar-visibility", typeof(ScrollView), nameof(ScrollView.HorizontalScrollBarVisibilityProperty))] [assembly: StyleProperty("-xf-vertical-scroll-bar-visibility", typeof(ScrollView), nameof(ScrollView.VerticalScrollBarVisibilityProperty))] [assembly: StyleProperty("-xf-min-track-color", typeof(Slider), nameof(Slider.MinimumTrackColorProperty))] [assembly: StyleProperty("-xf-max-track-color", typeof(Slider), nameof(Slider.MaximumTrackColorProperty))] [assembly: StyleProperty("-xf-thumb-color", typeof(Slider), nameof(Slider.ThumbColorProperty))] [assembly: StyleProperty("-xf-spacing", typeof(StackLayout), nameof(StackLayout.SpacingProperty))] <<<<<<< HEAD [assembly: StyleProperty("-xf-orientation", typeof(StackLayout), nameof(StackLayout.OrientationProperty))] [assembly: StyleProperty("-xf-visual", typeof(VisualElement), nameof(VisualElement.VisualProperty))] [assembly: StyleProperty("-xf-vertical-text-alignment", typeof(Label), nameof(Label.VerticalTextAlignmentProperty))] //shell [assembly: StyleProperty("-xf-flyout-background", typeof(Shell), nameof(Shell.FlyoutBackgroundColorProperty))] [assembly: StyleProperty("-xf-shell-background", typeof(Element), nameof(Shell.BackgroundColorProperty), PropertyOwnerType = typeof(Shell))] [assembly: StyleProperty("-xf-shell-disabled", typeof(Element), nameof(Shell.DisabledColorProperty), PropertyOwnerType = typeof(Shell))] [assembly: StyleProperty("-xf-shell-foreground", typeof(Element), nameof(Shell.ForegroundColorProperty), PropertyOwnerType = typeof(Shell))] [assembly: StyleProperty("-xf-shell-tabbar-background", typeof(Element), nameof(Shell.TabBarBackgroundColorProperty), PropertyOwnerType = typeof(Shell))] [assembly: StyleProperty("-xf-shell-tabbar-disabled", typeof(Element), nameof(Shell.TabBarDisabledColorProperty), PropertyOwnerType = typeof(Shell))] [assembly: StyleProperty("-xf-shell-tabbar-foreground", typeof(Element), nameof(Shell.TabBarForegroundColorProperty), PropertyOwnerType = typeof(Shell))] [assembly: StyleProperty("-xf-shell-tabbar-title", typeof(Element), nameof(Shell.TabBarTitleColorProperty), PropertyOwnerType = typeof(Shell))] [assembly: StyleProperty("-xf-shell-tabbar-unselected", typeof(Element), nameof(Shell.TabBarUnselectedColorProperty), PropertyOwnerType = typeof(Shell))] [assembly: StyleProperty("-xf-shell-title", typeof(Element), nameof(Shell.TitleColorProperty), PropertyOwnerType = typeof(Shell))] [assembly: StyleProperty("-xf-shell-unselected", typeof(Element), nameof(Shell.UnselectedColorProperty), PropertyOwnerType = typeof(Shell))] ======= [assembly: StyleProperty("-xf-orientation", typeof(StackLayout), nameof(StackLayout.OrientationProperty))] >>>>>>> Update from origin (#8)
83.180556
158
0.799633
[ "MIT" ]
jfversluis/Xamarin.Forms
Xamarin.Forms.Core/Properties/AssemblyInfo.cs
11,978
C#
using System; using System.Runtime.Serialization; namespace DoubleTap.Email { [Serializable] public class EmailClientException : Exception { public EmailClientException() { } protected EmailClientException(SerializationInfo info, StreamingContext context) : base(info, context) { } public EmailClientException(string message) : base(message) { } public EmailClientException(string message, Exception innerException) : base(message, innerException) { } } }
22.88
110
0.643357
[ "MIT" ]
doubletaptech/email
DoubleTap.Email/EmailClientException.cs
574
C#
using System.Linq; using Content.Server.Chemistry.EntitySystems; using Content.Server.Weapon.Ranged.Components; using Content.Shared.Chemistry.Components; using Content.Shared.Weapons.Ranged.Events; namespace Content.Server.Weapon.Ranged.Systems { public sealed class ChemicalAmmoSystem : EntitySystem { [Dependency] private readonly SolutionContainerSystem _solutionSystem = default!; public override void Initialize() { SubscribeLocalEvent<ChemicalAmmoComponent, AmmoShotEvent>(OnFire); } private void OnFire(EntityUid uid, ChemicalAmmoComponent component, AmmoShotEvent args) { if (!_solutionSystem.TryGetSolution(uid, component.SolutionName, out var ammoSolution)) return; var projectiles = args.FiredProjectiles; var projectileSolutionContainers = new List<(EntityUid, Solution)>(); foreach (var projectile in projectiles) { if (_solutionSystem .TryGetSolution(projectile, component.SolutionName, out var projectileSolutionContainer)) { projectileSolutionContainers.Add((uid, projectileSolutionContainer)); } } if (!projectileSolutionContainers.Any()) return; var solutionPerProjectile = ammoSolution.CurrentVolume * (1 / projectileSolutionContainers.Count); foreach (var (projectileUid, projectileSolution) in projectileSolutionContainers) { var solutionToTransfer = _solutionSystem.SplitSolution(uid, ammoSolution, solutionPerProjectile); _solutionSystem.TryAddSolution(projectileUid, projectileSolution, solutionToTransfer); } _solutionSystem.RemoveAllSolution(uid, ammoSolution); } } }
37.6
113
0.664894
[ "MIT" ]
EmoGarbage404/space-station-14
Content.Server/Weapon/Ranged/Systems/ChemicalAmmoSystem.cs
1,880
C#
using System; using Newtonsoft.Json; namespace ScryfallApi.Client.Models { public class Set : BaseItem { /// <summary> /// The unique three or four-letter code for this set. /// </summary> [JsonProperty("code")] public string Code { get; set; } /// <summary> /// The unique code for this set on MTGO, which may differ from the regular code. /// </summary> [JsonProperty("mtgo_code")] public string MtgoCode { get; set; } /// <summary> /// The English name of the set. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// A computer-readable classification for this set. See below. /// </summary> [JsonProperty("set_type")] public string SetType { get; set; } /// <summary> /// The date the set was released (in GMT-8 Pacific time). Not all sets have a known release date. /// </summary> [JsonProperty("released_at")] public DateTime? ReleaseDate { get; set; } /// <summary> /// The block code for this set, if any. /// </summary> [JsonProperty("block_code")] public string BlockCode { get; set; } /// <summary> /// The block or group name code for this set, if any. /// </summary> [JsonProperty("block")] public string Block { get; set; } /// <summary> /// The set code for the parent set, if any. promo and token sets often have a parent set. /// </summary> [JsonProperty("parent_set_code")] public string ParentSetCode { get; set; } /// <summary> /// The number of cards in this set. /// </summary> [JsonProperty("card_count")] public int card_count { get; set; } /// <summary> /// True if this set was only released on Magic Online. /// </summary> [JsonProperty("digital")] public bool IsDigital { get; set; } /// <summary> /// True if this set contains only foil cards. /// </summary> [JsonProperty("foil_only")] public bool IsFoilOnly { get; set; } /// <summary> /// A URI to an SVG file for this set’s icon on Scryfall’s CDN. Hotlinking this image isn’t /// recommended, because it may change slightly over time. You should download it and use it /// locally for your particular user interface needs. /// </summary> [JsonProperty("icon_svg_uri")] public Uri IconSvgUri { get; set; } /// <summary> /// A Scryfall API URI that you can request to begin paginating over the cards in this set. /// </summary> [JsonProperty("search_uri")] public Uri SsearchUri { get; set; } public override string ToString() => $"{Name} ({Code})"; } }
32.688889
106
0.554385
[ "MIT" ]
Sigurdur42/Scryfall-API-Client
src/ScryfallApi.Client/Models/Set.cs
2,954
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 iotwireless-2020-11-22.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.IoTWireless.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.IoTWireless.Model.Internal.MarshallTransformations { /// <summary> /// CreateWirelessGatewayTask Request Marshaller /// </summary> public class CreateWirelessGatewayTaskRequestMarshaller : IMarshaller<IRequest, CreateWirelessGatewayTaskRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreateWirelessGatewayTaskRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateWirelessGatewayTaskRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.IoTWireless"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2020-11-22"; request.HttpMethod = "POST"; if (!publicRequest.IsSetId()) throw new AmazonIoTWirelessException("Request object does not have required field Id set"); request.AddPathResource("{Id}", StringUtils.FromString(publicRequest.Id)); request.ResourcePath = "/wireless-gateways/{Id}/tasks"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetWirelessGatewayTaskDefinitionId()) { context.Writer.WritePropertyName("WirelessGatewayTaskDefinitionId"); context.Writer.Write(publicRequest.WirelessGatewayTaskDefinitionId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreateWirelessGatewayTaskRequestMarshaller _instance = new CreateWirelessGatewayTaskRequestMarshaller(); internal static CreateWirelessGatewayTaskRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateWirelessGatewayTaskRequestMarshaller Instance { get { return _instance; } } } }
38.603774
166
0.632209
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/IoTWireless/Generated/Model/Internal/MarshallTransformations/CreateWirelessGatewayTaskRequestMarshaller.cs
4,092
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 storagegateway-2013-06-30.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.StorageGateway.Model { /// <summary> /// UpdateVTLDeviceTypeOutput /// </summary> public partial class UpdateVTLDeviceTypeResponse : AmazonWebServiceResponse { private string _vtlDeviceARN; /// <summary> /// Gets and sets the property VTLDeviceARN. /// <para> /// The Amazon Resource Name (ARN) of the medium changer you have selected. /// </para> /// </summary> [AWSProperty(Min=50, Max=500)] public string VTLDeviceARN { get { return this._vtlDeviceARN; } set { this._vtlDeviceARN = value; } } // Check to see if VTLDeviceARN property is set internal bool IsSetVTLDeviceARN() { return this._vtlDeviceARN != null; } } }
30.448276
113
0.642129
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/StorageGateway/Generated/Model/UpdateVTLDeviceTypeResponse.cs
1,766
C#
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.IO; using ThirdParty.Json.LitJson; using Amazon.SimpleWorkflow.Model; using Amazon.Runtime.Internal.Transform; namespace Amazon.SimpleWorkflow.Model.Internal.MarshallTransformations { /// <summary> /// WorkflowExecutionCountUnmarshaller /// </summary> internal class WorkflowExecutionCountUnmarshaller : IUnmarshaller<WorkflowExecutionCount, XmlUnmarshallerContext>, IUnmarshaller<WorkflowExecutionCount, JsonUnmarshallerContext> { WorkflowExecutionCount IUnmarshaller<WorkflowExecutionCount, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } public WorkflowExecutionCount Unmarshall(JsonUnmarshallerContext context) { if (context.CurrentTokenType == JsonToken.Null) return null; WorkflowExecutionCount workflowExecutionCount = new WorkflowExecutionCount(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; while (context.Read()) { if (context.TestExpression("count", targetDepth)) { context.Read(); workflowExecutionCount.Count = IntUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("truncated", targetDepth)) { context.Read(); workflowExecutionCount.Truncated = BoolUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.CurrentDepth <= originalDepth) { return workflowExecutionCount; } } return workflowExecutionCount; } private static WorkflowExecutionCountUnmarshaller instance; public static WorkflowExecutionCountUnmarshaller GetInstance() { if (instance == null) instance = new WorkflowExecutionCountUnmarshaller(); return instance; } } }
34.792683
183
0.631265
[ "Apache-2.0" ]
virajs/aws-sdk-net
AWSSDK_DotNet35/Amazon.SimpleWorkflow/Model/Internal/MarshallTransformations/WorkflowExecutionCountUnmarshaller.cs
2,853
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using BSTU.FileCabinet.BLL.Interfaces; using BSTU.FileCabinet.DAL.Interfaces; using BSTU.FileCabinet.Domain.Models; using BSTU.FileCabinet.WPF.Commands; using Microsoft.Win32; using PropertyChanged; namespace BSTU.FileCabinet.WPF.ViewModels { [AddINotifyPropertyChangedInterface] public class AuthorizationViewModel : BaseViewModel { private readonly IRepository<Authorization, string> repository; private readonly IFileRecordService<Authorization> service; public AuthorizationViewModel(IRepository<Authorization, string> repository, IFileRecordService<Authorization> service) { this.repository = repository ?? throw new NullReferenceException(); this.service = service ?? throw new NullReferenceException(); UpdateCollection(); } public Authorization SelectedValue { get; set; } public string SearchText { get; set; } public ObservableCollection<Authorization> Authorizations { get; set; } public ICommand Create => new BaseCommand(CreateAuthorization); public ICommand Update => new BaseCommand(UpdateAuthorization); public ICommand Delete => new BaseCommand(DeleteAuthorization); public ICommand Export => new BaseCommand(ExportRecords); public ICommand Import => new BaseCommand(ImportRecords); public ICommand Search => new BaseCommand(SearchRecords); private void CreateAuthorization(object parameter) { if (this.SelectedValue is null) return; var value = new Authorization() { Login = SelectedValue.Login, Password = SelectedValue.Password, Role = SelectedValue.Role, UserId = SelectedValue.UserId, }; try { this.repository.Create(value); UpdateCollection(); } catch (Exception) { MessageBox.Show("Wrong instance key parameter!", "Create", MessageBoxButton.OK, MessageBoxImage.Error); } } private void UpdateAuthorization(object parameter) { if (this.SelectedValue is null) return; try { this.repository.Update(SelectedValue.Login, SelectedValue); UpdateCollection(); } catch (Exception) { MessageBox.Show("Wrong instance key parameter!", "Update", MessageBoxButton.OK, MessageBoxImage.Error); } } private void DeleteAuthorization(object parameter) { if (this.SelectedValue is null) return; this.repository.Delete(SelectedValue.Login); UpdateCollection(); } private void UpdateCollection() { this.Authorizations = new ObservableCollection<Authorization>(this.repository.GetAll()); } private void ExportRecords(object parameter) { OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == true) { try { var path = openFileDialog.FileName; this.service.ExportRecords(this.repository.GetAll(), path); MessageBox.Show($"Record(s) were exported to {path}.", "File", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception) { MessageBox.Show("Wrong file format!", "File", MessageBoxButton.OK, MessageBoxImage.Error); } } } private void ImportRecords(object parameter) { OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == true) { try { var path = openFileDialog.FileName; var records = this.service.ImportRecords(path); var count = FillRecord(records); MessageBox.Show($"{count} record(s) were imported.", "File", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception) { MessageBox.Show("Wrong file format!", "File", MessageBoxButton.OK, MessageBoxImage.Error); } } UpdateCollection(); } private int FillRecord(IEnumerable<Authorization> records) { var count = 0; foreach (var record in records) { try { if (this.repository.Get(record.Login) is null) { this.repository.Create(record); count++; } } catch (Exception) { continue; } } return count; } private void SearchRecords(object parameter) { this.Authorizations = string.IsNullOrEmpty(this.SearchText) ? new ObservableCollection<Authorization>(this.repository.GetAll()) : new ObservableCollection<Authorization>(this.repository.GetAll() .Where(i => i.Login.ToUpper() .Contains(SearchText.ToUpper()))); } } }
35.71875
133
0.567104
[ "MIT" ]
DenisStolyarov/BSTU.COURSE.PROJECT.WPF
BSTU.FileCabinet/BSTU.FileCabinet.WPF/ViewModels/AuthorizationViewModel.cs
5,717
C#
using System.Xml.Serialization; namespace TE.FileWatcher.Configuration.Notifications { /// <summary> /// Contains the data used to send the request. /// </summary> public class Data { // The MIME type private string _mimeType = Request.JSON_NAME; /// <summary> /// Gets or sets the headers for the request. /// </summary> [XmlElement("headers")] public Headers? Headers { get; set; } /// <summary> /// Gets or sets the body for the request. /// </summary> [XmlElement("body")] public string? Body { get; set; } /// <summary> /// Gets or sets the MIME type string value. /// </summary> [XmlElement("type")] public string MimeTypeString { get { return _mimeType; } set { _mimeType = (value == Request.JSON_NAME || value == Request.XML_NAME) ? value : Request.JSON_NAME; } } /// <summary> /// Gets the MIME type from the string value. /// </summary> [XmlIgnore] internal Request.MimeType MimeType { get { if (_mimeType == Request.XML_NAME) { return Request.MimeType.Xml; } else { return Request.MimeType.Json; } } } } }
25.098361
114
0.460483
[ "MIT" ]
gilby125/FileWatcher
FileWatcher/Configuration/Notifications/Data.cs
1,533
C#
using Microsoft.Extensions.Hosting; using System.Collections.Generic; using System.Linq; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; namespace FastGithub.PacketIntercept { /// <summary> /// tcp拦截后台服务 /// </summary> [SupportedOSPlatform("windows")] sealed class TcpInterceptHostedService : BackgroundService { private readonly IEnumerable<ITcpInterceptor> tcpInterceptors; /// <summary> /// tcp拦截后台服务 /// </summary> /// <param name="tcpInterceptors"></param> public TcpInterceptHostedService(IEnumerable<ITcpInterceptor> tcpInterceptors) { this.tcpInterceptors = tcpInterceptors; } /// <summary> /// https后台 /// </summary> /// <param name="stoppingToken"></param> /// <returns></returns> protected override Task ExecuteAsync(CancellationToken stoppingToken) { var tasks = this.tcpInterceptors.Select(item => item.InterceptAsync(stoppingToken)); return Task.WhenAll(tasks); } } }
28.692308
96
0.637176
[ "MIT" ]
HaloXie/FastGithub
FastGithub.PacketIntercept/TcpInterceptHostedService.cs
1,149
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Core.UnitTests { [TestClass] public class ExcludedClassTest { [TestMethod] public void SomeTest() { // Arrange, var target = new ExcludedClass(); // Act, target.IncludedProperty = target.ExcludedProperty; target.ExcludedProperty = target.IncludedProperty; target.IncludedMethod(target.IncludedProperty); target.ExcludedMethod(target.IncludedProperty); } } }
24.173913
62
0.611511
[ "MIT" ]
fhnaseer/CSharping
CSharp/Core.UnitTests/ExcludedClassTest.cs
558
C#
namespace IbFlexReader { using System; using System.Collections.Generic; using System.Linq; using IbFlexReader.Contracts.Enums; using IbFlexReader.Contracts.Ib; using IbFlexReader.Utils; internal class Logic { public static void ProcessStatement(FlexStatement statement, Options options) { if (statement != null && options != null && options.SplitUpOpenCloseTrades) { statement.Trades.Trade = SplitUpOpenCloseTrades(statement.Trades.Trade, statement.Trades.Lot); } } private static List<Trade> SplitUpOpenCloseTrades(List<Trade> trades, List<Lot> lots) { var ocTrades = trades .Where(t => t.OpenCloseIndicator.HasValue && t.OpenCloseIndicator.Value.Matches(x => x.HasFlag(OpenClose.C) && x.HasFlag(OpenClose.O))); var remainingTrades = trades.Where(x => !ocTrades.Contains(x)).ToList(); foreach (var ocTrade in ocTrades) { var lot = lots.First(x => x.TradeDateTime == ocTrade.TradeDateTime && x.BuySell == ocTrade.BuySell && x.Description == ocTrade.Description); var copy = ocTrade.Clone(); // ocTrade must be the "close" and the copy the "open" var newQ = Math.Sign(ocTrade.Quantity.Value) * Math.Abs(lot.Quantity.Value); ocTrade.OpenCloseIndicator = OpenClose.C; ocTrade.TradeMoney = (ocTrade.TradeMoney / Math.Abs(ocTrade.Quantity.Value)) * Math.Abs(newQ); ocTrade.Proceeds = (ocTrade.Proceeds / Math.Abs(ocTrade.Quantity.Value)) * Math.Abs(newQ); ocTrade.IbCommission = (ocTrade.IbCommission / Math.Abs(ocTrade.Quantity.Value)) * Math.Abs(newQ); ocTrade.Quantity = newQ; copy.OpenCloseIndicator = OpenClose.O; copy.FifoPnlRealized = 0; copy.Quantity = Math.Sign(copy.Quantity.Value) * (Math.Abs(copy.Quantity.Value) - Math.Abs(ocTrade.Quantity.Value)); copy.TradeMoney = copy.TradeMoney - ocTrade.TradeMoney; copy.Proceeds = copy.Proceeds - ocTrade.Proceeds; copy.IbCommission = copy.IbCommission - ocTrade.IbCommission; remainingTrades.Add(ocTrade); remainingTrades.Add(copy); } return remainingTrades; } } }
44
156
0.609917
[ "MIT" ]
JueMueller/ib-flex-reader
IbFlexReader/IbFlexReader/Logic.cs
2,422
C#
using Xunit; namespace MySuperStats.Tests { public sealed class MultiTenantFactAttribute : FactAttribute { public MultiTenantFactAttribute() { if (!MySuperStatsConsts.MultiTenancyEnabled) { Skip = "MultiTenancy is disabled."; } } } }
20.25
64
0.570988
[ "MIT" ]
ykirkanahtar/MySuperStats
aspnet-core/test/MySuperStats.Tests/MultiTenantFactAttribute.cs
326
C#
using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json; namespace Citrina { /// <summary> /// Type of online status of group. /// </summary> public enum GroupsOnlineStatusType { [EnumMember(Value = "none")] None, [EnumMember(Value = "online")] Online, [EnumMember(Value = "answer_mark")] AnswerMark, } }
21.35
44
0.576112
[ "MIT" ]
khrabrovart/Citrina
src/Citrina/gen/Objects/Groups/GroupsOnlineStatusType.cs
427
C#
using OpenCvSharp.Text; using Xunit; namespace OpenCvSharp.Tests.Text { public class DetectTextSWTTest : TestBase { [Fact] public void Test() { using var src = new Mat("_data/image/imageText.png"); using var draw = new Mat(); var rects = CvText.DetectTextSWT(src, true, draw); Assert.NotEmpty(rects); ShowImagesWhenDebugMode(src, draw); } } }
21.47619
65
0.569845
[ "Apache-2.0" ]
5118234/opencvsharp
test/OpenCvSharp.Tests/text/DetectTextSWTTest.cs
453
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.ComponentModel; using Pulumi; namespace Pulumi.AzureNextGen.NetApp.V20190601 { /// <summary> /// The service level of the file system /// </summary> [EnumType] public readonly struct ServiceLevel : IEquatable<ServiceLevel> { private readonly string _value; private ServiceLevel(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// Standard service level /// </summary> public static ServiceLevel Standard { get; } = new ServiceLevel("Standard"); /// <summary> /// Premium service level /// </summary> public static ServiceLevel Premium { get; } = new ServiceLevel("Premium"); /// <summary> /// Ultra service level /// </summary> public static ServiceLevel Ultra { get; } = new ServiceLevel("Ultra"); public static bool operator ==(ServiceLevel left, ServiceLevel right) => left.Equals(right); public static bool operator !=(ServiceLevel left, ServiceLevel right) => !left.Equals(right); public static explicit operator string(ServiceLevel value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ServiceLevel other && Equals(other); public bool Equals(ServiceLevel other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } }
36.117647
112
0.645494
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/NetApp/V20190601/Enums.cs
1,842
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("09. Extract Middle Elements")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("09. Extract Middle Elements")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("240c8a20-5eee-4a20-a535-3ba569d8b420")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.485714
84
0.744573
[ "MIT" ]
thelad43/Programming-Fundamentals-SoftUni
09. Arrays - Lab/09. Extract Middle Elements/Properties/AssemblyInfo.cs
1,385
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 QuantConnect.Data.UniverseSelection; namespace QuantConnect.Lean.Engine.DataFeeds { /// <summary> /// Provides the ability to synchronize subscriptions into time slices /// </summary> public class SubscriptionSynchronizer : ISubscriptionSynchronizer, ITimeProvider { private readonly UniverseSelection _universeSelection; private TimeSliceFactory _timeSliceFactory; private ITimeProvider _timeProvider; private ManualTimeProvider _frontierTimeProvider; /// <summary> /// Event fired when a <see cref="Subscription"/> is finished /// </summary> public event EventHandler<Subscription> SubscriptionFinished; /// <summary> /// Initializes a new instance of the <see cref="SubscriptionSynchronizer"/> class /// </summary> /// <param name="universeSelection">The universe selection instance used to handle universe /// selection subscription output</param> /// <returns>A time slice for the specified frontier time</returns> public SubscriptionSynchronizer(UniverseSelection universeSelection) { _universeSelection = universeSelection; } /// <summary> /// Sets the time provider. If already set will throw. /// </summary> /// <param name="timeProvider">The time provider, used to obtain the current frontier UTC value</param> public void SetTimeProvider(ITimeProvider timeProvider) { if (_timeProvider != null) { throw new Exception("SubscriptionSynchronizer.SetTimeProvider(): can only be called once"); } _timeProvider = timeProvider; _frontierTimeProvider = new ManualTimeProvider(_timeProvider.GetUtcNow()); } /// <summary> /// Sets the <see cref="TimeSliceFactory"/> instance to use /// </summary> /// <param name="timeSliceFactory">Used to create the new <see cref="TimeSlice"/></param> public void SetTimeSliceFactory(TimeSliceFactory timeSliceFactory) { if (_timeSliceFactory != null) { throw new Exception("SubscriptionSynchronizer.SetTimeSliceFactory(): can only be called once"); } _timeSliceFactory = timeSliceFactory; } /// <summary> /// Syncs the specified subscriptions. The frontier time used for synchronization is /// managed internally and dependent upon previous synchronization operations. /// </summary> /// <param name="subscriptions">The subscriptions to sync</param> public TimeSlice Sync(IEnumerable<Subscription> subscriptions) { var delayedSubscriptionFinished = false; var changes = SecurityChanges.None; var data = new List<DataFeedPacket>(1); // NOTE: Tight coupling in UniverseSelection.ApplyUniverseSelection var universeData = new Dictionary<Universe, BaseDataCollection>(); var universeDataForTimeSliceCreate = new Dictionary<Universe, BaseDataCollection>(); _frontierTimeProvider.SetCurrentTimeUtc(_timeProvider.GetUtcNow()); var frontierUtc = _frontierTimeProvider.GetUtcNow(); SecurityChanges newChanges; do { newChanges = SecurityChanges.None; foreach (var subscription in subscriptions) { if (subscription.EndOfStream) { OnSubscriptionFinished(subscription); continue; } // prime if needed if (subscription.Current == null) { if (!subscription.MoveNext()) { OnSubscriptionFinished(subscription); continue; } } DataFeedPacket packet = null; while (subscription.Current != null && subscription.Current.EmitTimeUtc <= frontierUtc) { if (packet == null) { // for performance, lets be selfish about creating a new instance packet = new DataFeedPacket( subscription.Security, subscription.Configuration, subscription.RemovedFromUniverse ); } packet.Add(subscription.Current.Data); if (!subscription.MoveNext()) { delayedSubscriptionFinished = true; break; } } if (packet?.Count > 0) { // we have new universe data to select based on, store the subscription data until the end if (!subscription.IsUniverseSelectionSubscription) { data.Add(packet); } else { // assume that if the first item is a base data collection then the enumerator handled the aggregation, // otherwise, load all the the data into a new collection instance var packetBaseDataCollection = packet.Data[0] as BaseDataCollection; var packetData = packetBaseDataCollection == null ? packet.Data : packetBaseDataCollection.Data; BaseDataCollection collection; if (universeData.TryGetValue(subscription.Universes.Single(), out collection)) { collection.Data.AddRange(packetData); } else { if (packetBaseDataCollection is OptionChainUniverseDataCollection) { var current = packetBaseDataCollection as OptionChainUniverseDataCollection; collection = new OptionChainUniverseDataCollection(frontierUtc, subscription.Configuration.Symbol, packetData, current?.Underlying); } else if (packetBaseDataCollection is FuturesChainUniverseDataCollection) { collection = new FuturesChainUniverseDataCollection(frontierUtc, subscription.Configuration.Symbol, packetData); } else { collection = new BaseDataCollection(frontierUtc, subscription.Configuration.Symbol, packetData); } universeData[subscription.Universes.Single()] = collection; } } } if (subscription.IsUniverseSelectionSubscription && subscription.Universes.Single().DisposeRequested || delayedSubscriptionFinished) { delayedSubscriptionFinished = false; // we need to do this after all usages of subscription.Universes OnSubscriptionFinished(subscription); } } foreach (var kvp in universeData) { var universe = kvp.Key; var baseDataCollection = kvp.Value; universeDataForTimeSliceCreate[universe] = baseDataCollection; newChanges += _universeSelection.ApplyUniverseSelection(universe, frontierUtc, baseDataCollection); } universeData.Clear(); changes += newChanges; } while (newChanges != SecurityChanges.None || _universeSelection.AddPendingCurrencyDataFeeds(frontierUtc)); var timeSlice = _timeSliceFactory.Create(frontierUtc, data, changes, universeDataForTimeSliceCreate); return timeSlice; } /// <summary> /// Event invocator for the <see cref="SubscriptionFinished"/> event /// </summary> protected virtual void OnSubscriptionFinished(Subscription subscription) { var handler = SubscriptionFinished; if (handler != null) handler(this, subscription); } /// <summary> /// Returns the current UTC frontier time /// </summary> public DateTime GetUtcNow() { return _frontierTimeProvider.GetUtcNow(); } } }
44.238938
168
0.543009
[ "Apache-2.0" ]
alexotsu/Lean
Engine/DataFeeds/SubscriptionSynchronizer.cs
10,000
C#
using Xamarin.Forms; namespace XF.Material.Forms.Resources.Typography { /// <summary> /// Class that provides typography theme configuration based on https://material.io/design/typography. /// </summary> public sealed class MaterialFontConfiguration : BindableObject { /// <summary> /// Backing field for the bindable property <see cref="Body1"/>. /// </summary> public static readonly BindableProperty Body1Property = BindableProperty.Create(nameof(Body1), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="Body2"/>. /// </summary> public static readonly BindableProperty Body2Property = BindableProperty.Create(nameof(Body2), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="Button"/>. /// </summary> public static readonly BindableProperty ButtonProperty = BindableProperty.Create(nameof(Button), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="Caption"/>. /// </summary> public static readonly BindableProperty CaptionProperty = BindableProperty.Create(nameof(Caption), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="H1"/>. /// </summary> public static readonly BindableProperty H1Property = BindableProperty.Create(nameof(H1), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="H2"/>. /// </summary> public static readonly BindableProperty H2Property = BindableProperty.Create(nameof(H2), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="H3"/>. /// </summary> public static readonly BindableProperty H3Property = BindableProperty.Create(nameof(H3), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="H4"/>. /// </summary> public static readonly BindableProperty H4Property = BindableProperty.Create(nameof(H4), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="H5"/>. /// </summary> public static readonly BindableProperty H5Property = BindableProperty.Create(nameof(H5), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="H6"/>. /// </summary> public static readonly BindableProperty H6Property = BindableProperty.Create(nameof(H6), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="Overline"/>. /// </summary> public static readonly BindableProperty OverlineProperty = BindableProperty.Create(nameof(Overline), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="Subtitle1"/>. /// </summary> public static readonly BindableProperty Subtitle1Property = BindableProperty.Create(nameof(Subtitle1), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Backing field for the bindable property <see cref="Subtitle2"/>. /// </summary> public static readonly BindableProperty Subtitle2Property = BindableProperty.Create(nameof(Subtitle2), typeof(string), typeof(MaterialFontConfiguration), Font.Default.FontFamily); /// <summary> /// Body 1 font family, used for long-form writing and small text sizes. /// </summary> public string Body1 { get => this.GetValue(Body1Property)?.ToString(); set => this.SetValue(Body1Property, value); } /// <summary> /// Body 2 font family, used for long-form writing and small text sizes. /// </summary> public string Body2 { get => this.GetValue(H1Property)?.ToString(); set => this.SetValue(H1Property, value); } /// <summary> /// Button font family, used by different types of buttons. /// </summary> public string Button { get => this.GetValue(ButtonProperty)?.ToString(); set => this.SetValue(ButtonProperty, value); } /// <summary> /// Caption font family, used for annotations or to introduce a headline text. /// </summary> public string Caption { get => this.GetValue(CaptionProperty)?.ToString(); set => this.SetValue(CaptionProperty, value); } /// <summary> /// Headline 1 font family, used by large text on the screen. /// </summary> public string H1 { get => this.GetValue(H1Property)?.ToString(); set => this.SetValue(H1Property, value); } /// <summary> /// Headline 2 font family, used by large text on the screen. /// </summary> public string H2 { get => this.GetValue(H2Property)?.ToString(); set => this.SetValue(H2Property, value); } /// <summary> /// Headline 3 font family, used by large text on the screen. /// </summary> public string H3 { get => this.GetValue(H3Property)?.ToString(); set => this.SetValue(H3Property, value); } /// <summary> /// Headline 4 font family, used by large text on the screen. /// </summary> public string H4 { get => this.GetValue(H4Property)?.ToString(); set => this.SetValue(H4Property, value); } /// <summary> /// Headline 5 font family, used by large text on the screen. /// </summary> public string H5 { get => this.GetValue(H5Property)?.ToString(); set => this.SetValue(H5Property, value); } /// <summary> /// Headline 6 font family, used by large text on the screen. /// </summary> public string H6 { get => this.GetValue(H6Property)?.ToString(); set => this.SetValue(H6Property, value); } /// <summary> /// Overline font family, used for annotations or to introduce a headline text. /// </summary> public string Overline { get => this.GetValue(OverlineProperty)?.ToString(); set => this.SetValue(OverlineProperty, value); } /// <summary> /// Subtitle 1 font family, used by medium-emphasis text. /// </summary> public string Subtitle1 { get => this.GetValue(Subtitle1Property)?.ToString(); set => this.SetValue(Subtitle1Property, value); } /// <summary> /// Subtitle 2 font family, used by medium-emphasis text. /// </summary> public string Subtitle2 { get => this.GetValue(Subtitle2Property)?.ToString(); set => this.SetValue(Subtitle2Property, value); } } }
40.90625
187
0.610262
[ "MIT" ]
AndreaMinato/XF-Material-Library
XF.Material/XF.Material.Forms/Resources/Typography/MaterialFontConfiguration.cs
7,856
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.WebSites.Models { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Microsoft.Rest.Azure; /// <summary> /// Body of the error response returned from the API. /// </summary> public partial class ErrorEntity { /// <summary> /// Initializes a new instance of the ErrorEntity class. /// </summary> public ErrorEntity() { } /// <summary> /// Initializes a new instance of the ErrorEntity class. /// </summary> public ErrorEntity(string code = default(string), string message = default(string), string extendedCode = default(string), string messageTemplate = default(string), IList<string> parameters = default(IList<string>), IList<ErrorEntity> innerErrors = default(IList<ErrorEntity>)) { Code = code; Message = message; ExtendedCode = extendedCode; MessageTemplate = messageTemplate; Parameters = parameters; InnerErrors = innerErrors; } /// <summary> /// Basic error code /// </summary> [JsonProperty(PropertyName = "code")] public string Code { get; set; } /// <summary> /// Any details of the error /// </summary> [JsonProperty(PropertyName = "message")] public string Message { get; set; } /// <summary> /// Type of error /// </summary> [JsonProperty(PropertyName = "extendedCode")] public string ExtendedCode { get; set; } /// <summary> /// Message template /// </summary> [JsonProperty(PropertyName = "messageTemplate")] public string MessageTemplate { get; set; } /// <summary> /// Parameters for the template /// </summary> [JsonProperty(PropertyName = "parameters")] public IList<string> Parameters { get; set; } /// <summary> /// Inner errors /// </summary> [JsonProperty(PropertyName = "innerErrors")] public IList<ErrorEntity> InnerErrors { get; set; } } }
32.2625
285
0.601317
[ "MIT" ]
samtoubia/azure-sdk-for-net
src/ResourceManagement/WebSite/Microsoft.Azure.Management.Websites/Generated/Models/ErrorEntity.cs
2,581
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.XLANGs.BaseTypes; using Microsoft.BizTalk.XLANGs.BTXEngine; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Aim.FtpPassthru")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Aim.FtpPassthru")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: Microsoft.XLANGs.BaseTypes.BizTalkAssemblyAttribute(typeof(BTXService))] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4215b796-e53d-4575-8605-99b3071c73d6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.97619
84
0.756261
[ "MIT" ]
345James/aimbiztalk
scenarios/001-FtpPassthru/src/Aim.FtpPassthru/Properties/AssemblyInfo.cs
1,638
C#
using Microsoft.AspNetCore.Mvc; using NetStackBeautifier.Services; using System.Runtime.CompilerServices; namespace NetStackBeautifier.WebAPI.Controllers; [ApiController] [Route("[controller]")] public class BeautifiedController : ControllerBase { private readonly IBeautifierService _beautifierService; public BeautifiedController(IBeautifierService beautifierService) { _beautifierService = beautifierService ?? throw new ArgumentNullException(nameof(beautifierService)); } [HttpPost] public IAsyncEnumerable<IFrameLine> Post([FromBody] string body, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(body)) { throw new ArgumentNullException(nameof(body)); } return _beautifierService.BeautifyAsync(body, cancellationToken); } }
30.777778
109
0.753309
[ "MIT" ]
xiaomi7732/StackBeauty
src/NetStackBeautifier.WebAPI/Controllers/BeautifiedController.cs
831
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DDD.Domain.Commands; using DDD.Domain.Commands.Anuncio; namespace DDD.Domain.Validations.Anuncio { class RemoveAnuncioCommandValidation : AnuncioValidation<RemoveAnuncioCommand> { public RemoveAnuncioCommandValidation() { ValidateId(); } } }
21.736842
82
0.726392
[ "MIT" ]
nilsonluizk/TesteWebMotorDDD
Src/DDD.Domain/Validations/Anuncio/RemoveAnuncioCommandValidation.cs
413
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Gcp.CertificateAuthority.Inputs { public sealed class AuthorityConfigX509ConfigKeyUsageUnknownExtendedKeyUsageArgs : Pulumi.ResourceArgs { [Input("objectIdPaths", required: true)] private InputList<int>? _objectIdPaths; /// <summary> /// An ObjectId specifies an object identifier (OID). These provide context and describe types in ASN.1 messages. /// </summary> public InputList<int> ObjectIdPaths { get => _objectIdPaths ?? (_objectIdPaths = new InputList<int>()); set => _objectIdPaths = value; } public AuthorityConfigX509ConfigKeyUsageUnknownExtendedKeyUsageArgs() { } } }
32.40625
121
0.681774
[ "ECL-2.0", "Apache-2.0" ]
la3mmchen/pulumi-gcp
sdk/dotnet/CertificateAuthority/Inputs/AuthorityConfigX509ConfigKeyUsageUnknownExtendedKeyUsageArgs.cs
1,037
C#
using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; namespace Babalu.rProxy { /// <summary> /// main class of the Babalu rProxy service /// </summary> static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new TestService() }; ServiceBase.Run(ServicesToRun); } } }
20.714286
53
0.577586
[ "MIT" ]
CalypsoSys/Babalu_rProxy
TestService/Program.cs
582
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Laser.Orchard.Vimeo.Models { public class VimeoAccessTokenRecord { public virtual int Id { get; set; } public virtual string AccessToken { get; set; } public virtual int RateLimitLimit { get; set; } public virtual int RateLimitRemaining { get; set; } public virtual double RateAvailableRatio { get; set; } public virtual DateTime? RateLimitReset { get; set; } } }
34.4
62
0.686047
[ "Apache-2.0" ]
INVA-Spa/Laser.Orchard.Platform
src/Modules/Laser.Orchard.Vimeo/Models/VimeoAccessTokenRecord.cs
518
C#
using Microsoft.EntityFrameworkCore; using RecipeStorage.Data.Entities; using System; namespace RecipeStorage.Data { public class RecipeStorageDbContext : DbContext { public RecipeStorageDbContext(DbContextOptions options) : base(options) { } public DbSet<Ingredient> Ingredients { get; set; } public DbSet<Recipe> Recipes { get; set; } public DbSet<RecipeIngredient> RecipeIngredients { get; set; } public DbSet<RecipeRating> RecipeRatings { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Ingredient>().HasIndex(e => e.Name).IsUnique(); // unique name modelBuilder.Entity<Recipe>().HasIndex(e => e.Name).IsUnique(); // unique name modelBuilder.Entity<RecipeRating>().HasIndex(e => new { e.RecipeId, e.UserId }).IsUnique(); // user has one rating per recipe } } }
33.733333
137
0.65415
[ "Apache-2.0" ]
divayo/recipe-api
RecipeStorage.Data/RecipeStorageDbContext.cs
1,014
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // </auto-generated> namespace Microsoft.Azure.Management.ContainerInstance.Fluent.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// The name object of the resource /// </summary> public partial class UsageName { /// <summary> /// Initializes a new instance of the UsageName class. /// </summary> public UsageName() { CustomInit(); } /// <summary> /// Initializes a new instance of the UsageName class. /// </summary> /// <param name="value">The name of the resource</param> /// <param name="localizedValue">The localized name of the /// resource</param> public UsageName(string value = default(string), string localizedValue = default(string)) { Value = value; LocalizedValue = localizedValue; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets the name of the resource /// </summary> [JsonProperty(PropertyName = "value")] public string Value { get; private set; } /// <summary> /// Gets the localized name of the resource /// </summary> [JsonProperty(PropertyName = "localizedValue")] public string LocalizedValue { get; private set; } } }
29.677966
97
0.591662
[ "MIT" ]
AntoineGa/azure-libraries-for-net
src/ResourceManagement/ContainerInstance/Generated/Models/UsageName.cs
1,751
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Notifications { using System; using System.Collections.Generic; using System.Linq; using System.Text; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; using DotNetNuke.Framework; using DotNetNuke.Security; using DotNetNuke.Security.Roles; using DotNetNuke.Services.Cache; using DotNetNuke.Services.Social.Messaging; using DotNetNuke.Services.Social.Messaging.Internal; using DotNetNuke.Services.Social.Notifications.Data; using Localization = DotNetNuke.Services.Localization.Localization; /// <summary> /// Provides the methods to work with Notifications, NotificationTypes, NotificationTypeActions and NotificationActions. /// </summary> public class NotificationsController : ServiceLocator<INotificationsController, NotificationsController>, INotificationsController { internal const int ConstMaxSubject = 400; internal const int ConstMaxTo = 2000; private const string ToastsCacheKey = "GetToasts_{0}"; private readonly IDataService _dataService; private readonly Messaging.Data.IDataService _messagingDataService; /// <summary> /// Initializes a new instance of the <see cref="NotificationsController"/> class. /// Default constructor. /// </summary> public NotificationsController() : this(DataService.Instance, Messaging.Data.DataService.Instance) { } /// <summary> /// Initializes a new instance of the <see cref="NotificationsController"/> class. /// Constructor from specifict data service. /// </summary> /// <param name="dataService">Class with methods to do CRUD in database for the entities of types <see cref="NotificationType"></see>, <see cref="NotificationTypeAction"></see> and <see cref="Notification"></see>.</param> /// <param name="messagingDataService">Class with methods to do CRUD in database for the entities of types <see cref="Message"></see>, <see cref="MessageRecipient"></see> and <see cref="MessageAttachment"></see> and to interact with the stored procedures regarding messaging.</param> public NotificationsController(IDataService dataService, Messaging.Data.IDataService messagingDataService) { Requires.NotNull("dataService", dataService); Requires.NotNull("messagingDataService", messagingDataService); this._dataService = dataService; this._messagingDataService = messagingDataService; } /// <inheritdoc/> public void SetNotificationTypeActions(IList<NotificationTypeAction> actions, int notificationTypeId) { Requires.NotNull("actions", actions); if (!actions.Any()) { throw new ArgumentException("Actions must contain at least one item."); } if (actions.Any(x => string.IsNullOrEmpty(x.APICall))) { throw new ArgumentException("All actions must specify an APICall"); } if (actions.Any(x => string.IsNullOrEmpty(x.NameResourceKey))) { throw new ArgumentException("All actions must specify a NameResourceKey"); } foreach (var action in actions) { action.NotificationTypeActionId = this._dataService.AddNotificationTypeAction( notificationTypeId, action.NameResourceKey, action.DescriptionResourceKey, action.ConfirmResourceKey, action.APICall, this.GetCurrentUserId()); action.NotificationTypeId = notificationTypeId; } } /// <inheritdoc/> public virtual int CountNotifications(int userId, int portalId) { if (userId <= 0) { return 0; } var cacheKey = string.Format(DataCache.UserNotificationsCountCacheKey, portalId, userId); var cache = CachingProvider.Instance(); var cacheObject = cache.GetItem(cacheKey); if (cacheObject is int) { return (int)cacheObject; } var count = this._dataService.CountNotifications(userId, portalId); cache.Insert(cacheKey, count, (DNNCacheDependency)null, DateTime.Now.AddSeconds(DataCache.NotificationsCacheTimeInSec), System.Web.Caching.Cache.NoSlidingExpiration); return count; } /// <inheritdoc/> public virtual void SendNotification(Notification notification, int portalId, IList<RoleInfo> roles, IList<UserInfo> users) { Requires.NotNull("notification", notification); var pid = portalId; if (PortalController.IsMemberOfPortalGroup(portalId)) { pid = PortalController.GetEffectivePortalId(portalId); } if (notification.SenderUserID < 1) { notification.SenderUserID = this.GetAdminUser().UserID; } if (string.IsNullOrEmpty(notification.Subject) && string.IsNullOrEmpty(notification.Body)) { throw new ArgumentException(Localization.GetString("MsgSubjectOrBodyRequiredError", Localization.ExceptionsResourceFile)); } if (roles == null && users == null) { throw new ArgumentException(Localization.GetString("MsgRolesOrUsersRequiredError", Localization.ExceptionsResourceFile)); } if (!string.IsNullOrEmpty(notification.Subject) && notification.Subject.Length > ConstMaxSubject) { throw new ArgumentException(string.Format(Localization.GetString("MsgSubjectTooBigError", Localization.ExceptionsResourceFile), ConstMaxSubject, notification.Subject.Length)); } var sbTo = new StringBuilder(); if (roles != null) { foreach (var role in roles.Where(role => !string.IsNullOrEmpty(role.RoleName))) { sbTo.Append(role.RoleName + ","); } } if (users != null) { foreach (var user in users.Where(user => !string.IsNullOrEmpty(user.DisplayName))) { sbTo.Append(user.DisplayName + ","); } } if (sbTo.Length == 0) { throw new ArgumentException(Localization.GetString("MsgEmptyToListFoundError", Localization.ExceptionsResourceFile)); } if (sbTo.Length > ConstMaxTo) { throw new ArgumentException(string.Format(Localization.GetString("MsgToListTooBigError", Localization.ExceptionsResourceFile), ConstMaxTo, sbTo.Length)); } notification.To = sbTo.ToString().Trim(','); if (notification.ExpirationDate != default(DateTime)) { notification.ExpirationDate = this.GetExpirationDate(notification.NotificationTypeID); } notification.NotificationID = this._dataService.SendNotification(notification, pid); // send message to Roles if (roles != null) { var roleIds = string.Empty; roleIds = roles .Select(r => r.RoleID) .Aggregate(roleIds, (current, roleId) => current + (roleId + ",")) .Trim(','); this._messagingDataService.CreateMessageRecipientsForRole( notification.NotificationID, roleIds, UserController.Instance.GetCurrentUserInfo().UserID); } // send message to each User - this should be called after CreateMessageRecipientsForRole. if (users == null) { users = new List<UserInfo>(); } var recipients = from user in users where InternalMessagingController.Instance.GetMessageRecipient(notification.NotificationID, user.UserID) == null select new MessageRecipient { MessageID = notification.NotificationID, UserID = user.UserID, Read = false, RecipientID = Null.NullInteger, }; foreach (var recipient in recipients) { this._messagingDataService.SaveMessageRecipient( recipient, UserController.Instance.GetCurrentUserInfo().UserID); } // if sendToast is true, then mark all recipients' as ready for toast. if (notification.SendToast) { foreach (var messageRecipient in InternalMessagingController.Instance.GetMessageRecipients(notification.NotificationID)) { this.MarkReadyForToast(notification, messageRecipient.UserID); } } } /// <inheritdoc/> public void CreateNotificationType(NotificationType notificationType) { Requires.NotNull("notificationType", notificationType); Requires.NotNullOrEmpty("notificationType.Name", notificationType.Name); if (notificationType.DesktopModuleId <= 0) { notificationType.DesktopModuleId = Null.NullInteger; } notificationType.NotificationTypeId = this._dataService.CreateNotificationType( notificationType.Name, notificationType.Description, (int)notificationType.TimeToLive.TotalMinutes == 0 ? Null.NullInteger : (int)notificationType.TimeToLive.TotalMinutes, notificationType.DesktopModuleId, this.GetCurrentUserId(), notificationType.IsTask); } /// <inheritdoc/> public virtual void DeleteNotification(int notificationId) { var recipients = InternalMessagingController.Instance.GetMessageRecipients(notificationId); foreach (var recipient in recipients) { DataCache.RemoveCache(string.Format(ToastsCacheKey, recipient.UserID)); } this._dataService.DeleteNotification(notificationId); } /// <inheritdoc/> public int DeleteUserNotifications(UserInfo user) { DataCache.RemoveCache(string.Format(ToastsCacheKey, user.UserID)); return this._dataService.DeleteUserNotifications(user.UserID, user.PortalID); } /// <inheritdoc/> public virtual void DeleteNotificationRecipient(int notificationId, int userId) { DataCache.RemoveCache(string.Format(ToastsCacheKey, userId)); InternalMessagingController.Instance.DeleteMessageRecipient(notificationId, userId); var recipients = InternalMessagingController.Instance.GetMessageRecipients(notificationId); if (recipients.Count == 0) { this.DeleteNotification(notificationId); } } /// <inheritdoc/> public virtual void DeleteAllNotificationRecipients(int notificationId) { foreach (var recipient in InternalMessagingController.Instance.GetMessageRecipients(notificationId)) { this.DeleteNotificationRecipient(notificationId, recipient.UserID); } } /// <inheritdoc/> public virtual void DeleteNotificationRecipient(int notificationTypeId, string context, int userId) { foreach (var notification in this.GetNotificationByContext(notificationTypeId, context)) { this.DeleteNotificationRecipient(notification.NotificationID, userId); } } /// <inheritdoc/> public Notification GetNotification(int notificationId) { return CBO.FillObject<Notification>(this._dataService.GetNotification(notificationId)); } /// <inheritdoc/> public virtual IList<Notification> GetNotificationByContext(int notificationTypeId, string context) { return CBO.FillCollection<Notification>(this._dataService.GetNotificationByContext(notificationTypeId, context)); } /// <inheritdoc/> public virtual void DeleteNotificationType(int notificationTypeId) { this._dataService.DeleteNotificationType(notificationTypeId); this.RemoveNotificationTypeCache(); } /// <inheritdoc/> public virtual void DeleteNotificationTypeAction(int notificationTypeActionId) { this._dataService.DeleteNotificationTypeAction(notificationTypeActionId); this.RemoveNotificationTypeActionCache(); } /// <inheritdoc/> public virtual IList<Notification> GetNotifications(int userId, int portalId, int afterNotificationId, int numberOfRecords) { var pid = portalId; if (PortalController.IsMemberOfPortalGroup(portalId)) { pid = PortalController.GetEffectivePortalId(portalId); } return userId <= 0 ? new List<Notification>(0) : CBO.FillCollection<Notification>(this._dataService.GetNotifications(userId, pid, afterNotificationId, numberOfRecords)); } /// <inheritdoc/> public virtual NotificationType GetNotificationType(int notificationTypeId) { var notificationTypeCacheKey = string.Format(DataCache.NotificationTypesCacheKey, notificationTypeId); var cacheItemArgs = new CacheItemArgs(notificationTypeCacheKey, DataCache.NotificationTypesTimeOut, DataCache.NotificationTypesCachePriority, notificationTypeId); return CBO.GetCachedObject<NotificationType>(cacheItemArgs, this.GetNotificationTypeCallBack); } /// <inheritdoc/> public virtual NotificationType GetNotificationType(string name) { Requires.NotNullOrEmpty("name", name); var notificationTypeCacheKey = string.Format(DataCache.NotificationTypesCacheKey, name); var cacheItemArgs = new CacheItemArgs(notificationTypeCacheKey, DataCache.NotificationTypesTimeOut, DataCache.NotificationTypesCachePriority, name); return CBO.GetCachedObject<NotificationType>(cacheItemArgs, this.GetNotificationTypeByNameCallBack); } /// <inheritdoc/> public virtual NotificationTypeAction GetNotificationTypeAction(int notificationTypeActionId) { var notificationTypeActionCacheKey = string.Format(DataCache.NotificationTypeActionsCacheKey, notificationTypeActionId); var cacheItemArgs = new CacheItemArgs(notificationTypeActionCacheKey, DataCache.NotificationTypeActionsTimeOut, DataCache.NotificationTypeActionsPriority, notificationTypeActionId); return CBO.GetCachedObject<NotificationTypeAction>(cacheItemArgs, this.GetNotificationTypeActionCallBack); } /// <inheritdoc/> public virtual NotificationTypeAction GetNotificationTypeAction(int notificationTypeId, string name) { Requires.NotNullOrEmpty("name", name); var notificationTypeActionCacheKey = string.Format(DataCache.NotificationTypeActionsByNameCacheKey, notificationTypeId, name); var cacheItemArgs = new CacheItemArgs(notificationTypeActionCacheKey, DataCache.NotificationTypeActionsTimeOut, DataCache.NotificationTypeActionsPriority, notificationTypeId, name); return CBO.GetCachedObject<NotificationTypeAction>(cacheItemArgs, this.GetNotificationTypeActionByNameCallBack); } /// <inheritdoc/> public virtual IList<NotificationTypeAction> GetNotificationTypeActions(int notificationTypeId) { return CBO.FillCollection<NotificationTypeAction>(this._dataService.GetNotificationTypeActions(notificationTypeId)); } /// <inheritdoc/> public bool IsToastPending(int notificationId) { return this._dataService.IsToastPending(notificationId); } /// <inheritdoc/> public void MarkReadyForToast(Notification notification, UserInfo userInfo) { this.MarkReadyForToast(notification, userInfo.UserID); } public void MarkReadyForToast(Notification notification, int userId) { DataCache.RemoveCache(string.Format(ToastsCacheKey, userId)); this._dataService.MarkReadyForToast(notification.NotificationID, userId); } /// <inheritdoc/> public void MarkToastSent(int notificationId, int userId) { this._dataService.MarkToastSent(notificationId, userId); } /// <inheritdoc/> public IList<Notification> GetToasts(UserInfo userInfo) { var cacheKey = string.Format(ToastsCacheKey, userInfo.UserID); var toasts = DataCache.GetCache<IList<Notification>>(cacheKey); if (toasts == null) { toasts = CBO.FillCollection<Notification>(this._dataService.GetToasts(userInfo.UserID, userInfo.PortalID)); foreach (var message in toasts) { this._dataService.MarkToastSent(message.NotificationID, userInfo.UserID); } // Set the cache to empty toasts object because we don't want to make calls to database everytime for empty objects. // This empty object cache would be cleared by MarkReadyForToast emthod when a new notification arrives for the user. DataCache.SetCache(cacheKey, new List<Notification>()); } return toasts; } internal virtual UserInfo GetAdminUser() { var current = PortalSettings.Current; return current == null ? new UserInfo() : UserController.GetUserById(current.PortalId, current.AdministratorId); } internal virtual int GetCurrentUserId() { return UserController.Instance.GetCurrentUserInfo().UserID; } internal virtual DateTime GetExpirationDate(int notificationTypeId) { var notificationType = this.GetNotificationType(notificationTypeId); return notificationType.TimeToLive.TotalMinutes > 0 ? DateTime.UtcNow.AddMinutes(notificationType.TimeToLive.TotalMinutes) : DateTime.MinValue; } internal virtual object GetNotificationTypeActionCallBack(CacheItemArgs cacheItemArgs) { var notificationTypeActionId = (int)cacheItemArgs.ParamList[0]; return CBO.FillObject<NotificationTypeAction>(this._dataService.GetNotificationTypeAction(notificationTypeActionId)); } internal virtual object GetNotificationTypeActionByNameCallBack(CacheItemArgs cacheItemArgs) { var notificationTypeId = (int)cacheItemArgs.ParamList[0]; var name = cacheItemArgs.ParamList[1].ToString(); return CBO.FillObject<NotificationTypeAction>(this._dataService.GetNotificationTypeActionByName(notificationTypeId, name)); } internal virtual object GetNotificationTypeByNameCallBack(CacheItemArgs cacheItemArgs) { var notificationName = cacheItemArgs.ParamList[0].ToString(); return CBO.FillObject<NotificationType>(this._dataService.GetNotificationTypeByName(notificationName)); } internal virtual object GetNotificationTypeCallBack(CacheItemArgs cacheItemArgs) { var notificationTypeId = (int)cacheItemArgs.ParamList[0]; return CBO.FillObject<NotificationType>(this._dataService.GetNotificationType(notificationTypeId)); } internal virtual string GetPortalSetting(string settingName, int portalId, string defaultValue) { return PortalController.GetPortalSetting(settingName, portalId, defaultValue); } internal virtual string InputFilter(string input) { var ps = PortalSecurity.Instance; return ps.InputFilter(input, PortalSecurity.FilterFlag.NoProfanity); } internal virtual void RemoveNotificationTypeActionCache() { DataCache.ClearCache("NotificationTypeActions:"); } internal virtual void RemoveNotificationTypeCache() { DataCache.ClearCache("NotificationTypes:"); } /// <inheritdoc/> protected override Func<INotificationsController> GetFactory() { return () => new NotificationsController(); } } }
42.727273
291
0.632424
[ "MIT" ]
Acidburn0zzz/Dnn.Platform
DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs
21,622
C#
namespace Essensoft.AspNetCore.Payment.Alipay.Response { /// <summary> /// AlipayOpenServicemarketCommodityChangeNotifyResponse. /// </summary> public class AlipayOpenServicemarketCommodityChangeNotifyResponse : AlipayResponse { } }
25.8
86
0.744186
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Response/AlipayOpenServicemarketCommodityChangeNotifyResponse.cs
260
C#
using System.Collections.Generic; using SimpleECS.Core.Components; using SimpleECS.Core.Configs; namespace SimpleECS.Core.States { public sealed class DebugState : IComponent { DebugConfig _config; public bool IsTriggered { get; set; } List<string> _contents = new List<string>(); public DebugState Init(DebugConfig config) { _config = config; return this; } public void Log(string line) { _contents.Add(line); if ( _contents.Count == _config.MaxLogSize ) { _contents.RemoveAt(0); } } public List<string> GetContent() { return new List<string>(_contents); } } }
21
49
0.702791
[ "MIT" ]
KonH/PiLedGame
SimpleECS.Core/States/DebugState.cs
609
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Notus")] [assembly: AssemblyDescription("Provides a notification object that collects errors and warnings.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alexander Forbes Group Services (Pty) Ltd.")] [assembly: AssemblyProduct("Notus")] [assembly: AssemblyCopyright("Copyright (c) 2021 Alexander Forbes Group Services (Pty) Ltd.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("071aa51b-fefb-48c7-9a48-3ded1085555f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.1")] [assembly: AssemblyFileVersion("2.0.1")]
41.216216
100
0.754098
[ "MIT" ]
alexander-forbes/notus
src/Notus/Properties/AssemblyInfo.cs
1,527
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using Microsoft.ReverseProxy.Abstractions.Telemetry; using Microsoft.ReverseProxy.Utilities; namespace Microsoft.ReverseProxy.Service.Metrics { internal class ProxyMetrics { private readonly Action<long, string, string, string, string, string> _streamCopyBytes; private readonly Action<long, string, string, string, string, string> _streamCopyIops; public ProxyMetrics(IMetricCreator metricCreator) { _ = metricCreator ?? throw new ArgumentNullException(nameof(metricCreator)); _streamCopyBytes = metricCreator.Create("StreamCopyBytes", "direction", "clusterId", "routeId", "destinationId", "protocol"); _streamCopyIops = metricCreator.Create("StreamCopyIops", "direction", "clusterId", "routeId", "destinationId", "protocol"); } public void StreamCopyBytes(long value, string direction, string clusterId, string routeId, string destinationId, string protocol) { _streamCopyBytes(value, direction, clusterId, routeId, destinationId, protocol); } public void StreamCopyIops(long value, string direction, string clusterId, string routeId, string destinationId, string protocol) { _streamCopyIops(value, direction, clusterId, routeId, destinationId, protocol); } } }
41.735294
138
0.710359
[ "MIT" ]
JasonCoombs/reverse-proxy
src/ReverseProxy/Service/Metrics/ProxyMetrics.cs
1,419
C#
// Copyright (c) Terence Parr, Sam Harwell. All Rights Reserved. // Licensed under the BSD License. See LICENSE.txt in the project root for license information. using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime.Tree.Pattern { /// <summary> /// A chunk is either a token tag, a rule tag, or a span of literal text within a /// tree pattern. /// </summary> /// <remarks> /// A chunk is either a token tag, a rule tag, or a span of literal text within a /// tree pattern. /// <p>The method /// <see cref="ParseTreePatternMatcher.Split(string)"/> /// returns a list of /// chunks in preparation for creating a token stream by /// <see cref="ParseTreePatternMatcher.Tokenize(string)"/> /// . From there, we get a parse /// tree from with /// <see cref="ParseTreePatternMatcher.Compile(string, int)"/> /// . These /// chunks are converted to /// <see cref="RuleTagToken"/> /// , /// <see cref="TokenTagToken"/> /// , or the /// regular tokens of the text surrounding the tags.</p> /// </remarks> internal abstract class Chunk { } }
32.485714
95
0.628848
[ "BSD-3-Clause" ]
ProphetLamb-Organistion/antlr4cs
runtime/CSharp/Antlr4.Runtime/Tree/Pattern/Chunk.cs
1,137
C#
using System; using System.Collections.Generic; #nullable disable namespace Injection.DbModels { public partial class VVendorWithAddress { public int BusinessEntityId { get; set; } public string Name { get; set; } public string AddressType { get; set; } public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string StateProvinceName { get; set; } public string PostalCode { get; set; } public string CountryRegionName { get; set; } } }
28.142857
53
0.641286
[ "MIT" ]
Flavia31/ac-league-timisoara
application_security/owasp-top-10/1-injection/after/DbModels/VVendorWithAddress.cs
593
C#
namespace ClassLib067 { public class Class085 { public static string Property => "ClassLib067"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib067/Class085.cs
120
C#
// Copyright (c) ZHAW, Marco Bertschi, Patrick Stadler. All rights reserved. namespace Watra.Api.DataAccess.DbContext { /// <summary> /// Interface from which any database entity must inherit. /// </summary> public interface IDbEntity { /// <summary> /// Gets or sets the entities ID. /// </summary> public int Id { get; set; } } }
24.375
77
0.594872
[ "MIT" ]
OpenWatra/OpenWatra-Core
src/Watra.Api/DataAccess/DbContext/IDbEntity.cs
392
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.AspNet.Mvc.ModelBinding { /// <summary> /// A value provider which can filter its contents based on <see cref="BindingSource"/>. /// </summary> /// <remarks> /// Value providers are by-default included. If a model does not specify a <see cref="BindingSource"/> /// then all value providers are valid. /// </remarks> public interface IBindingSourceValueProvider : IValueProvider { /// <summary> /// Filters the value provider based on <paramref name="bindingSource"/>. /// </summary> /// <param name="bindingSource">The <see cref="BindingSource"/> associated with a model.</param> /// <returns> /// The filtered value provider, or <c>null</c> if the value provider does not match /// <paramref name="bindingSource"/>. /// </returns> IValueProvider Filter(BindingSource bindingSource); } }
41.846154
111
0.651654
[ "Apache-2.0" ]
VGGeorgiev/Mvc
src/Microsoft.AspNet.Mvc.Core/ModelBinding/IBindingSourceValueProvider.cs
1,088
C#
namespace RecipeApplication.ViewComponents { using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using RecipeApplication.Data; using RecipeApplication.Models; using System.Linq; using System.Threading.Tasks; public class MyRecipesViewComponent : ViewComponent { private readonly AppDbContext _context; private readonly UserManager<ApplicationUser> _userManager; public MyRecipesViewComponent(AppDbContext context, UserManager<ApplicationUser> userManager) { this._context = context; this._userManager = userManager; } public async Task<IViewComponentResult> InvokeAsync(int numberOfRecipes) { if (!this.User.Identity.IsAuthenticated) { return this.View("Unauthenticated"); } var userId = this._userManager.GetUserId(this.HttpContext.User); var recipes = await this._context.Recipes .Where(x => x.CreatedById == userId) .OrderBy(x => x.LastModified) .Take(numberOfRecipes) .Select(x => new RecipeSummaryViewModel { Id = x.RecipeId, Name = x.Name, }) .ToListAsync(); return this.View(recipes); } } }
31.688889
101
0.596774
[ "MIT" ]
pirocorp/ASP.NET-Core-Playground
02. ASP.NET Core In Action/Chapter23/B_RecipeApplication/src/RecipeApplication/ViewComponents/MyRecipesViewComponent.cs
1,428
C#
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using SDKTemplate; using System; using Windows.Devices.Sensors; using Windows.Foundation; using System.Threading.Tasks; using Windows.UI.Core; namespace RelativeInclinometerCS { public sealed partial class Scenario1_DataEvents : 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 Inclinometer Sensor; private uint DesiredReportInterval; public Scenario1_DataEvents() { this.InitializeComponent(); Sensor = Inclinometer.GetDefaultForRelativeReadings(); if (Sensor != null) { // Select a report interval that is both suitable for the purposes of the app and supported by the sensor. // This value will be used later to activate the sensor. uint minReportInterval = Sensor.MinimumReportInterval; DesiredReportInterval = minReportInterval > 16 ? minReportInterval : 16; } else { rootPage.NotifyUser("No relative inclinometer found", NotifyType.ErrorMessage); } } /// <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) { ScenarioEnableButton.IsEnabled = true; ScenarioDisableButton.IsEnabled = false; } /// <summary> /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame. /// </summary> /// <param name="e"> /// Event data that can be examined by overriding code. The event data is representative /// of the navigation that will unload the current Page unless canceled. The /// navigation can potentially be canceled by setting Cancel. /// </param> protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { if (ScenarioDisableButton.IsEnabled) { Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged); Sensor.ReadingChanged -= new TypedEventHandler<Inclinometer, InclinometerReadingChangedEventArgs>(ReadingChanged); // Restore the default report interval to release resources while the sensor is not in use Sensor.ReportInterval = 0; } base.OnNavigatingFrom(e); } /// <summary> /// This is the event handler for VisibilityChanged events. You would register for these notifications /// if handling sensor data when the app is not visible could cause unintended actions in the app. /// </summary> /// <param name="sender"></param> /// <param name="e"> /// Event data that can be examined for the current visibility state. /// </param> private void VisibilityChanged(object sender, VisibilityChangedEventArgs e) { if (ScenarioDisableButton.IsEnabled) { if (e.Visible) { // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume) Sensor.ReadingChanged += new TypedEventHandler<Inclinometer, InclinometerReadingChangedEventArgs>(ReadingChanged); } else { // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension) Sensor.ReadingChanged -= new TypedEventHandler<Inclinometer, InclinometerReadingChangedEventArgs>(ReadingChanged); } } } /// <summary> /// This is the event handler for ReadingChanged events. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> async private void ReadingChanged(object sender, InclinometerReadingChangedEventArgs e) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { InclinometerReading reading = e.Reading; ScenarioOutput_X.Text = String.Format("{0,5:0.00}", reading.PitchDegrees); ScenarioOutput_Y.Text = String.Format("{0,5:0.00}", reading.RollDegrees); ScenarioOutput_Z.Text = String.Format("{0,5:0.00}", reading.YawDegrees); }); } /// <summary> /// This is the click handler for the 'Enable' button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ScenarioEnable(object sender, RoutedEventArgs e) { if (Sensor != null) { // Establish the report interval Sensor.ReportInterval = DesiredReportInterval; Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged); Sensor.ReadingChanged += new TypedEventHandler<Inclinometer, InclinometerReadingChangedEventArgs>(ReadingChanged); ScenarioEnableButton.IsEnabled = false; ScenarioDisableButton.IsEnabled = true; } else { rootPage.NotifyUser("No relative inclinometer found", NotifyType.ErrorMessage); } } /// <summary> /// This is the click handler for the 'Disable' button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ScenarioDisable(object sender, RoutedEventArgs e) { Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged); Sensor.ReadingChanged -= new TypedEventHandler<Inclinometer, InclinometerReadingChangedEventArgs>(ReadingChanged); // Restore the default report interval to release resources while the sensor is not in use Sensor.ReportInterval = 0; ScenarioEnableButton.IsEnabled = true; ScenarioDisableButton.IsEnabled = false; } } }
43.185629
142
0.595119
[ "MIT" ]
035/Windows-universal-samples
relativeinclinometer/cs/scenario1_dataevents.xaml.cs
7,048
C#
using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Roslyn.Services.Internal.Log { [ExcludeFromCodeCoverage] internal sealed class CodeMarkers { // Singleton access public static readonly CodeMarkers Instance = new CodeMarkers(); public static class NativeMethods { // Code markers' functions (imported from the code markers dll) #if Codemarkers_IncludeAppEnum [DllImport(DllName, EntryPoint = "InitPerf")] public static extern void DllInitPerf(System.Int32 iApp); [DllImport(DllName, EntryPoint = "UnInitPerf")] public static extern void DllUnInitPerf(System.Int32 iApp); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments")] public static extern System.UInt16 AddAtom(string lpString); [DllImport("kernel32.dll")] public static extern System.UInt16 DeleteAtom(System.UInt16 atom); #endif //Codemarkers_IncludeAppEnum [DllImport(DllName, EntryPoint = "PerfCodeMarker")] public static extern void DllPerfCodeMarker(int nTimerID, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] aUserParams, int cbParams); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments")] public static extern short FindAtom(string lpString); } // Atom name. This ATOM will be set by the host application when code markers are enabled // in the registry. private const string AtomName = "VSCodeMarkersEnabled"; // CodeMarkers DLL name private const string DllName = "Microsoft.Internal.Performance.CodeMarkers.dll"; // Do we want to use code markers? private bool useCodeMarkers; // Constructor. Do not call directly. Use CodeMarkers.Instance to access the singleton // Checks to see if code markers are enabled by looking for a named ATOM private CodeMarkers() { // This ATOM will be set by the native Code Markers host useCodeMarkers = NativeMethods.FindAtom(AtomName) != 0; } // Implements sending the code marker value nTimerID. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void CodeMarker(CodeMarkerId timerID) { if (!useCodeMarkers) { return; } try { NativeMethods.DllPerfCodeMarker((int)timerID, null, 0); } catch (DllNotFoundException) { // If the DLL doesn't load or the entry point doesn't exist, then abandon all // further attempts to send code markers. useCodeMarkers = false; } } // Implements sending the code marker value nTimerID with additional user data [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void CodeMarkerEx(CodeMarkerId timerID, byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("aBuff"); } if (!useCodeMarkers) { return; } try { NativeMethods.DllPerfCodeMarker((int)timerID, buffer, buffer.Length); } catch (DllNotFoundException) { // If the DLL doesn't load or the entry point doesn't exist, then abandon all // further attempts to send code markers. useCodeMarkers = false; } } // Implements sending the code marker value nTimerID with additional Guid user data [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void CodeMarkerEx(CodeMarkerId timerID, Guid guidData) { CodeMarkerEx(timerID, guidData.ToByteArray()); } #if Codemarkers_IncludeAppEnum // Check the registry and, if appropriate, loads and initializes the code markers dll. // Must be used only if your code is called from outside of VS. public void InitPerformanceDll(CodeMarkerApp iApp, string strRegRoot) { fUseCodeMarkers = false; if (!UseCodeMarkers(strRegRoot)) { return; } try { // Add an ATOM so that other CodeMarker enabled code in this process // knows that CodeMarkers are enabled NativeMethods.AddAtom(AtomName); NativeMethods.DllInitPerf((int)iApp); fUseCodeMarkers = true; } catch (DllNotFoundException) { ; // Ignore, but note that fUseCodeMarkers is false } } // Checks the registry to see if code markers are enabled static bool UseCodeMarkers(string strRegRoot) { // SECURITY: We no longer check HKCU because that might lead to a DLL spoofing attack via // the code markers DLL. Check only HKLM since that has a strong ACL. You therefore need // admin rights to enable/disable code markers. // It doesn't matter what the value is, if it's present and not empty, code markers are enabled return !String.IsNullOrEmpty(GetPerformanceSubKey(Registry.LocalMachine, strRegRoot)); } // Reads the Performance subkey from the appropriate registry key // Returns: the Default value from the subkey (null if not found) static string GetPerformanceSubKey(RegistryKey hKey, string strRegRoot) { if (hKey == null) return null; // does the subkey exist string str = null; using (RegistryKey key = hKey.OpenSubKey(strRegRoot + "\\Performance")) { if (key != null) { // reads the default value str = key.GetValue("").ToString(); } } return str; } // Opposite of InitPerformanceDLL. Call it when your app does not need the code markers dll. public void UninitializePerformanceDLL(CodeMarkerApp iApp) { if (!fUseCodeMarkers) { return; } fUseCodeMarkers = false; // Delete the atom created during the initialization if it exists System.UInt16 atom = NativeMethods.FindAtom(AtomName); if (atom != 0) { NativeMethods.DeleteAtom(atom); } try { NativeMethods.DllUnInitPerf((int)iApp); } catch (DllNotFoundException) { // Swallow exception } } #endif //Codemarkers_IncludeAppEnum #if !Codemarkers_NoCodeMarkerStartEnd /// <summary> /// Use CodeMarkerStartEnd in a using clause when you need to bracket an /// operation with a start/end CodeMarker event pair. /// </summary> internal sealed class CodeMarkerStartEnd : IDisposable { private CodeMarkerId end; public CodeMarkerStartEnd(CodeMarkerId begin, CodeMarkerId end) { Debug.Assert(end != (CodeMarkerId)0); Instance.CodeMarker(begin); this.end = end; } public void Dispose() { if (this.end != (CodeMarkerId)0) { // Protect against multiple Dispose calls Instance.CodeMarker(this.end); this.end = (CodeMarkerId)0; } } } /// <summary> /// Use CodeMarkerExStartEnd in a using clause when you need to bracket an /// operation with a start/end CodeMarker event pair. /// </summary> internal sealed class CodeMarkerExStartEnd : IDisposable { private CodeMarkerId end; private byte[] buffer; public CodeMarkerExStartEnd(CodeMarkerId begin, CodeMarkerId end, byte[] buffer) { Debug.Assert(end != (CodeMarkerId)0); Instance.CodeMarkerEx(begin, buffer); this.end = end; this.buffer = buffer; } // Specialization to use Guids for the code marker data public CodeMarkerExStartEnd(CodeMarkerId begin, CodeMarkerId end, Guid guidData) : this(begin, end, guidData.ToByteArray()) { } public void Dispose() { if (this.end != (CodeMarkerId)0) { // Protect against multiple Dispose calls Instance.CodeMarkerEx(this.end, this.buffer); this.end = (CodeMarkerId)0; this.buffer = null; } } } #endif } }
36.641221
159
0.576563
[ "Apache-2.0" ]
enginekit/copy_of_roslyn
Src/Workspaces/Core/Log/ManagedCodeMarkers.cs
9,600
C#
// // Copyright (c) 2008-2019 the Urho3D project. // Copyright (c) 2017-2020 the rbfx project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Urho3DNet { /// Three-dimensional vector. [StructLayout(LayoutKind.Sequential)] public struct Vector3 : IEquatable<Vector3> { ///ruct from a two-dimensional vector and the Z coordinate. public Vector3(in Vector2 vector, float z = 0) { X = vector.X; Y = vector.Y; Z = z; } ///ruct from an IntVector3. public Vector3(in IntVector3 vector) { X = vector.X; Y = vector.Y; Z = vector.Z; } ///ruct from coordinates. public Vector3(float x = 0, float y = 0, float z = 0) { X = x; Y = y; Z = z; } ///ruct from a float array. public Vector3(IReadOnlyList<float> data) { X = data[0]; Y = data[1]; Z = data[2]; } /// Construct from 2D vector in X0Z plane. public static Vector3 FromXZ(Vector2 vector, float y = 0.0f) { return new Vector3(vector.X, y, vector.Y); } /// Test for equality with another vector without epsilon. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(in Vector3 lhs, in Vector3 rhs) { return lhs.X == rhs.X && lhs.Y == rhs.Y && lhs.Z == rhs.Z; } /// Test for inequality with another vector without epsilon. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(in Vector3 lhs, in Vector3 rhs) { return lhs.X != rhs.X || lhs.Y != rhs.Y || lhs.Z != rhs.Z; } /// Add a vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator +(in Vector3 lhs, in Vector3 rhs) { return new Vector3(lhs.X + rhs.X, lhs.Y + rhs.Y, lhs.Z + rhs.Z); } /// Return negation. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator -(in Vector3 rhs) { return new Vector3(-rhs.X, -rhs.Y, -rhs.Z); } /// Subtract a vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator -(in Vector3 lhs, in Vector3 rhs) { return new Vector3(lhs.X - rhs.X, lhs.Y - rhs.Y, lhs.Z - rhs.Z); } /// Multiply with a scalar. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator *(in Vector3 lhs, float rhs) { return new Vector3(lhs.X * rhs, lhs.Y * rhs, lhs.Z * rhs); } /// Multiply with a vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator *(in Vector3 lhs, in Vector3 rhs) { return new Vector3(lhs.X * rhs.X, lhs.Y * rhs.Y, lhs.Z * rhs.Z); } /// Divide by a scalar. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator /(in Vector3 lhs, float rhs) { return new Vector3(lhs.X / rhs, lhs.Y / rhs, lhs.Z / rhs); } /// Divide by a vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator /(in Vector3 lhs, in Vector3 rhs) { return new Vector3(lhs.X / rhs.X, lhs.Y / rhs.Y, lhs.Z / rhs.Z); } /// Multiply Vector3 with a scalar. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator *(float lhs, in Vector3 rhs) { return rhs * lhs; } /// Normalize to unit length. public void Normalize() { float lenSquared = LengthSquared; if (!MathDefs.Equals(lenSquared, 1.0f) && lenSquared > 0.0f) { float invLen = 1.0f / (float) Math.Sqrt(lenSquared); X *= invLen; Y *= invLen; Z *= invLen; } } /// Return length. public float Length => (float) Math.Sqrt(LengthSquared); /// Return squared length. public float LengthSquared => X * X + Y * Y + Z * Z; /// Calculate dot product. [MethodImpl(MethodImplOptions.AggressiveInlining)] public float DotProduct(in Vector3 rhs) { return X * rhs.X + Y * rhs.Y + Z * rhs.Z; } /// Calculate absolute dot product. [MethodImpl(MethodImplOptions.AggressiveInlining)] public float AbsDotProduct(in Vector3 rhs) { return Math.Abs(X * rhs.X) + Math.Abs(Y * rhs.Y) + Math.Abs(Z * rhs.Z); } /// Project direction vector onto axis. [MethodImpl(MethodImplOptions.AggressiveInlining)] public float ProjectOntoAxis(in Vector3 axis) { return DotProduct(axis.Normalized); } /// Project position vector onto plane with given origin and normal. public Vector3 ProjectOntoPlane(in Vector3 origin, in Vector3 normal) { Vector3 delta = this - origin; return this - normal.Normalized * delta.ProjectOntoAxis(normal); } /// Project position vector onto line segment. public Vector3 ProjectOntoLine(in Vector3 from, in Vector3 to, bool clamped = false) { Vector3 direction = to - from; float lengthSquared = direction.LengthSquared; float factor = (this - from).DotProduct(direction) / lengthSquared; if (clamped) factor = MathDefs.Clamp(factor, 0.0f, 1.0f); return from + direction * factor; } /// Calculate distance to another position vector. public float DistanceToPoint(in Vector3 point) { return (this - point).Length; } /// Calculate distance to the plane with given origin and normal. public float DistanceToPlane(in Vector3 origin, in Vector3 normal) { return (this - origin).ProjectOntoAxis(normal); } /// Make vector orthogonal to the axis. public Vector3 Orthogonalize(in Vector3 axis) { return axis.CrossProduct(this).CrossProduct(axis).Normalized; } /// Calculate cross product. public Vector3 CrossProduct(in Vector3 rhs) { return new Vector3( Y * rhs.Z - Z * rhs.Y, Z * rhs.X - X * rhs.Z, X * rhs.Y - Y * rhs.X ); } /// Return absolute vector. public Vector3 Abs => new Vector3(Math.Abs(X), Math.Abs(Y), Math.Abs(Z)); /// Linear interpolation with another vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector3 Lerp(in Vector3 rhs, float t) { return this * (1.0f - t) + rhs * t; } /// Test for equality with another vector with epsilon. public bool Equals(Vector3 rhs) { return MathDefs.Equals(X, rhs.X) && MathDefs.Equals(Y, rhs.Y) && MathDefs.Equals(Z, rhs.Z); } /// Test for equality with another vector with epsilon. public override bool Equals(object obj) { return obj is Vector3 other && Equals(other); } /// Returns the angle between this vector and another vector in degrees. public float Angle(in Vector3 rhs) { return MathDefs.Acos(DotProduct(rhs) / (Length * rhs.Length)); } /// Return whether is NaN. public bool IsNaN => float.IsNaN(X) || float.IsNaN(Y) || float.IsNaN(Z); /// Return normalized to unit length. public Vector3 Normalized { get { float lenSquared = LengthSquared; if (!MathDefs.Equals(lenSquared, 1.0f) && lenSquared > 0.0f) { float invLen = 1.0f / (float) Math.Sqrt(lenSquared); return this * invLen; } else return this; } } /// Return normalized to unit length or zero if length is too small. public Vector3 NormalizedOrDefault { get { float lenSquared = LengthSquared; if (lenSquared < MathDefs.LargeEpsilon * MathDefs.LargeEpsilon) return Vector3.Zero; float invLen = 1.0f / (float)Math.Sqrt(lenSquared); return this * invLen; } } /// Return float data. public float[] Data => new[] {X, Y, Z}; /// Return as string. public override string ToString() { return $"{X} {Y} {Z}"; } /// Return hash value for HashSet & HashMap. public override int GetHashCode() { uint hash = 37; hash = 37 * hash + MathDefs.FloatToRawIntBits(X); hash = 37 * hash + MathDefs.FloatToRawIntBits(Y); hash = 37 * hash + MathDefs.FloatToRawIntBits(Z); return (int) hash; } /// Per-component linear interpolation between two 3-vectors. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Lerp(in Vector3 lhs, in Vector3 rhs, in Vector3 t) { return lhs + (rhs - lhs) * t; } /// Per-component min of two 3-vectors. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Min(in Vector3 lhs, in Vector3 rhs) { return new Vector3(Math.Min(lhs.X, rhs.X), Math.Min(lhs.Y, rhs.Y), Math.Min(lhs.Z, rhs.Z)); } /// Per-component max of two 3-vectors. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Max(in Vector3 lhs, in Vector3 rhs) { return new Vector3(Math.Max(lhs.X, rhs.X), Math.Max(lhs.Y, rhs.Y), Math.Max(lhs.Z, rhs.Z)); } /// Per-component floor of 3-vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Floor(in Vector3 vec) { return new Vector3((float)Math.Floor(vec.X), (float)Math.Floor(vec.Y), (float)Math.Floor(vec.Z)); } /// Per-component round of 3-vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Round(in Vector3 vec) { return new Vector3((float)Math.Round(vec.X), (float)Math.Round(vec.Y), (float)Math.Round(vec.Z)); } /// Per-component ceil of 3-vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Ceil(in Vector3 vec) { return new Vector3((float)Math.Ceiling(vec.X), (float)Math.Ceiling(vec.Y), (float)Math.Ceiling(vec.Z)); } /// Per-component floor of 3-vector. Returns IntVector3. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IntVector3 FloorToInt(in Vector3 vec) { return new IntVector3((int)Math.Floor(vec.X), (int)Math.Floor(vec.Y), (int)Math.Floor(vec.Z)); } /// Per-component round of 3-vector. Returns IntVector3. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IntVector3 RoundToInt(in Vector3 vec) { return new IntVector3((int)Math.Round(vec.X), (int)Math.Round(vec.Y), (int)Math.Round(vec.Z)); } /// Per-component ceil of 3-vector. Returns IntVector3. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IntVector3 CeilToInt(in Vector3 vec) { return new IntVector3((int)Math.Ceiling(vec.X), (int)Math.Ceiling(vec.Y), (int)Math.Ceiling(vec.Z)); } /// Return a random value from [0, 1) from 3-vector seed. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float StableRandom(in Vector3 seed) { return Vector2.StableRandom(new Vector2(Vector2.StableRandom(new Vector2(seed.X, seed.Y)), seed.Z)); } /// Return 2D vector (z component is ignored). [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector2 ToVector2() { return new Vector2(X, Y); } /// Return x and z components as 2D vector (y component is ignored). [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector2 ToXZ() { return new Vector2(X, Z); } /// X coordinate. public float X; /// Y coordinate. public float Y; /// Z coordinate. public float Z; /// Zero vector. public static readonly Vector3 Zero; /// (-1,0,0) vector. public static readonly Vector3 Left = new Vector3(-1, 0, 0); /// (1,0,0) vector. public static readonly Vector3 Right = new Vector3(1, 0, 0); /// (0,1,0) vector. public static readonly Vector3 Up = new Vector3(0, 1, 0); /// (0,-1,0) vector. public static readonly Vector3 Down = new Vector3(0, -1, 0); /// (0,0,1) vector. public static readonly Vector3 Forward = new Vector3(0, 0, 1); /// (0,0,-1) vector. public static readonly Vector3 Back = new Vector3(0, 0, -1); /// (1,1,1) vector. public static readonly Vector3 One = new Vector3(1, 1, 1); }; }
34.694639
115
0.576525
[ "MIT" ]
crystaldev3d/rbfx
Source/Urho3D/CSharp/Managed/Math/Vector3.cs
14,884
C#
using Microsoft.AspNetCore.Mvc; namespace WingTipUserJourneyPlayerWebApplication.Controllers { public class TraceController : Controller { public IActionResult Index() { return View(); } } }
18.461538
60
0.645833
[ "MIT" ]
Azure-Samples/active-directory-b2c-advanced-policies
wingtipgamesb2c/src/WingTipUserJourneyPlayerWebApplication/Controllers/TraceController.cs
240
C#
namespace CCode.Roles.Dto { public class FlatPermissionDto { public string Name { get; set; } public string DisplayName { get; set; } public string Description { get; set; } } }
21.090909
47
0.560345
[ "MIT" ]
AmayerGogh/CCode
aspnet-core/src/CCode.Application/Roles/Dto/FlatPermissionDto.cs
234
C#
using Akka.Actor; using AkkaEventStore.Actors.Messages.Commands; using AkkaEventStore.Messages; using AkkaEventStore.Messages.Commands; using EventStore.ClientAPI; using System; using System.Collections.Generic; using System.Net; using System.Text; namespace AkkaEventStore.Actors { public class BasketCoordinatorActor : ReceiveActor { private IDictionary<string, IActorRef> baskets = new Dictionary<string, IActorRef>(); int counter = 0; public BasketCoordinatorActor() { /* fromCategory('basket') .when({ $init : function() { return { count: 1 } }, "AkkaEventStore.Messages.Events.CreatedBasketEvent": function(s, e) { var count = s.count++; emit("basketsCounter", "Increment", count) } }) */ // initialize directly from database var connection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 1113)); //var connection = EventStoreConnection.Create( // ConnectionSettings.Create().KeepReconnecting(), // ClusterSettings.Create().DiscoverClusterViaGossipSeeds() // .SetGossipTimeout(TimeSpan.FromMilliseconds(500)) // .SetGossipSeedEndPoints(new IPEndPoint[] { // new IPEndPoint(IPAddress.Loopback, 1114), // new IPEndPoint(IPAddress.Loopback, 2114), // new IPEndPoint(IPAddress.Loopback, 3114), // })); connection.ConnectAsync().Wait(); var streamEvents = connection.ReadStreamEventsBackwardAsync("basketsCounter", StreamPosition.End, 1, false).Result; if (streamEvents.Events.Length > 0) { var number = Convert.ToInt32(Encoding.UTF8.GetString(streamEvents.Events[0].Event.Data)); for (int i = number; i > 0; i--) { var basketId = "basket-" + i; baskets.Add(basketId, Context.ActorOf(Props.Create<BasketActor>(basketId), basketId)); } counter = number; } Console.WriteLine($"[{DateTime.Now}] Basket Coordinator Recovered."); Receive<CreateNewBasketMessage>(message => { var basketId = "basket-" + ++counter; baskets.Add(basketId, Context.ActorOf(Props.Create<BasketActor>(basketId), basketId)); baskets[basketId].Tell(new CreateBasketCommand(basketId)); }); Receive<AddLineItemToBasketMessage>(message => { if (baskets.ContainsKey(message.BasketId)) baskets[message.BasketId].Forward(new AddLineItemToBasketCommand(message.LineItem)); else Console.WriteLine("No such basket"); }); Receive<RemoveLineItemFromBasketMessage>(message => { if (baskets.ContainsKey(message.BasketId)) baskets[message.BasketId].Forward(new RemoveLineItemFromBasketCommand(message.LineItem)); else Console.WriteLine("No such basket"); }); Receive<string>(message => { if ((message as string).StartsWith("peekBasket ")) { var tokens = (message as string).Split(' '); var basketId = tokens[1]; if (baskets.ContainsKey(basketId)) { baskets[basketId].Tell("peek"); } else { Console.WriteLine("No such basket"); } } }); } } }
38.707547
113
0.506702
[ "MIT" ]
vladkosarev/Akka.net-EventSourcePersistence
src/AkkaEventStore/Actors/BasketCoordinatorActor.cs
4,105
C#
using System; using System.Globalization; using MoonSharp.Interpreter.Compatibility; namespace MoonSharp.Interpreter.Interop.Converters { internal static class ScriptToClrConversions { internal const int WEIGHT_MAX_VALUE = 100; internal const int WEIGHT_CUSTOM_CONVERTER_MATCH = 100; internal const int WEIGHT_EXACT_MATCH = 100; internal const int WEIGHT_STRING_TO_STRINGBUILDER = 99; internal const int WEIGHT_STRING_TO_CHAR = 98; internal const int WEIGHT_NIL_TO_NULLABLE = 100; internal const int WEIGHT_NIL_TO_REFTYPE = 100; internal const int WEIGHT_VOID_WITH_DEFAULT = 50; internal const int WEIGHT_VOID_WITHOUT_DEFAULT = 25; internal const int WEIGHT_NIL_WITH_DEFAULT = 25; internal const int WEIGHT_BOOL_TO_STRING = 5; internal const int WEIGHT_NUMBER_TO_STRING = 50; internal const int WEIGHT_NUMBER_TO_ENUM = 90; internal const int WEIGHT_USERDATA_TO_STRING = 5; internal const int WEIGHT_TABLE_CONVERSION = 90; internal const int WEIGHT_NUMBER_DOWNCAST = 99; internal const int WEIGHT_NO_MATCH = 0; internal const int WEIGHT_NO_EXTRA_PARAMS_BONUS = 100; internal const int WEIGHT_EXTRA_PARAMS_MALUS = 2; internal const int WEIGHT_BYREF_BONUSMALUS = -10; internal const int WEIGHT_VARARGS_MALUS = 1; internal const int WEIGHT_VARARGS_EMPTY = 40; /// <summary> /// Converts a DynValue to a CLR object [simple conversion] /// </summary> internal static object DynValueToObject(DynValue value) { var converter = Script.GlobalOptions.CustomConverters.GetScriptToClrCustomConversion(value.Type, typeof(object)); if (converter != null) { var v = converter(value); if (v != null) { return v; } } switch (value.Type) { case DataType.Void: case DataType.Nil: return null; case DataType.Boolean: return value.Boolean; case DataType.Number: return value.Number; case DataType.String: return value.String; case DataType.Function: return value.Function; case DataType.Table: return value.Table; case DataType.Tuple: return value.Tuple; case DataType.UserData: if (value.UserData.Object != null) { return value.UserData.Object; } else if (value.UserData.Descriptor != null) { return value.UserData.Descriptor.Type; } else { return null; } case DataType.ClrFunction: return value.Callback; default: throw ScriptRuntimeException.ConvertObjectFailed(value.Type); } } /// <summary> /// Converts a DynValue to a CLR object of a specific type /// </summary> internal static object DynValueToObjectOfType(DynValue value, Type desiredType, object defaultValue, bool isOptional) { if (desiredType.IsByRef) { desiredType = desiredType.GetElementType(); } var converter = Script.GlobalOptions.CustomConverters.GetScriptToClrCustomConversion(value.Type, desiredType); if (converter != null) { var v = converter(value); if (v != null) { return v; } } if (desiredType == typeof(DynValue)) { return value; } if (desiredType == typeof(object)) { return DynValueToObject(value); } var stringSubType = StringConversions.GetStringSubtype(desiredType); string str = null; var nt = Nullable.GetUnderlyingType(desiredType); Type nullableType = null; if (nt != null) { nullableType = desiredType; desiredType = nt; } switch (value.Type) { case DataType.Void: if (isOptional) { return defaultValue; } else if ((!Framework.Do.IsValueType(desiredType)) || (nullableType != null)) { return null; } break; case DataType.Nil: if (Framework.Do.IsValueType(desiredType)) { if (nullableType != null) { return null; } if (isOptional) { return defaultValue; } } else { return null; } break; case DataType.Boolean: if (desiredType == typeof(bool)) { return value.Boolean; } if (stringSubType != StringConversions.StringSubtype.None) { str = value.Boolean.ToString(); } break; case DataType.Number: if (Framework.Do.IsEnum(desiredType)) { // number to enum conv var underType = Enum.GetUnderlyingType(desiredType); return NumericConversions.DoubleToType(underType, value.Number); } if (NumericConversions.NumericTypes.Contains(desiredType)) { return NumericConversions.DoubleToType(desiredType, value.Number); } if (stringSubType != StringConversions.StringSubtype.None) { str = value.Number.ToString(CultureInfo.InvariantCulture); } break; case DataType.String: if (stringSubType != StringConversions.StringSubtype.None) { str = value.String; } break; case DataType.Function: if (desiredType == typeof(Closure)) { return value.Function; } else if (desiredType == typeof(ScriptFunctionDelegate)) { return value.Function.GetDelegate(); } break; case DataType.ClrFunction: if (desiredType == typeof(CallbackFunction)) { return value.Callback; } else if (desiredType == typeof(Func<ScriptExecutionContext, CallbackArguments, DynValue>)) { return value.Callback.ClrCallback; } break; case DataType.UserData: if (value.UserData.Object != null) { var udObj = value.UserData.Object; var udDesc = value.UserData.Descriptor; if (udDesc.IsTypeCompatible(desiredType, udObj)) { return udObj; } if (stringSubType != StringConversions.StringSubtype.None) { str = udDesc.AsString(udObj); } } break; case DataType.Table: if (desiredType == typeof(Table) || Framework.Do.IsAssignableFrom(desiredType, typeof(Table))) { return value.Table; } else { var o = TableConversions.ConvertTableToType(value.Table, desiredType); if (o != null) { return o; } } break; case DataType.Tuple: break; } if (stringSubType != StringConversions.StringSubtype.None && str != null) { return StringConversions.ConvertString(stringSubType, str, desiredType, value.Type); } throw ScriptRuntimeException.ConvertObjectFailed(value.Type, desiredType); } /// <summary> /// Gets a relative weight of how much the conversion is matching the given types. /// Implementation must follow that of DynValueToObjectOfType.. it's not very DRY in that sense. /// However here we are in perf-sensitive path.. TODO : double-check the gain and see if a DRY impl is better. /// </summary> internal static int DynValueToObjectOfTypeWeight(DynValue value, Type desiredType, bool isOptional) { if (desiredType.IsByRef) { desiredType = desiredType.GetElementType(); } var customConverter = Script.GlobalOptions.CustomConverters.GetScriptToClrCustomConversion(value.Type, desiredType); if (customConverter != null) { return WEIGHT_CUSTOM_CONVERTER_MATCH; } if (desiredType == typeof(DynValue)) { return WEIGHT_EXACT_MATCH; } if (desiredType == typeof(object)) { return WEIGHT_EXACT_MATCH; } var stringSubType = StringConversions.GetStringSubtype(desiredType); var nt = Nullable.GetUnderlyingType(desiredType); Type nullableType = null; if (nt != null) { nullableType = desiredType; desiredType = nt; } switch (value.Type) { case DataType.Void: if (isOptional) { return WEIGHT_VOID_WITH_DEFAULT; } else if ((!Framework.Do.IsValueType(desiredType)) || (nullableType != null)) { return WEIGHT_VOID_WITHOUT_DEFAULT; } break; case DataType.Nil: if (Framework.Do.IsValueType(desiredType)) { if (nullableType != null) { return WEIGHT_NIL_TO_NULLABLE; } if (isOptional) { return WEIGHT_NIL_WITH_DEFAULT; } } else { return WEIGHT_NIL_TO_REFTYPE; } break; case DataType.Boolean: if (desiredType == typeof(bool)) { return WEIGHT_EXACT_MATCH; } if (stringSubType != StringConversions.StringSubtype.None) { return WEIGHT_BOOL_TO_STRING; } break; case DataType.Number: if (Framework.Do.IsEnum(desiredType)) { // number to enum conv return WEIGHT_NUMBER_TO_ENUM; } if (NumericConversions.NumericTypes.Contains(desiredType)) { return GetNumericTypeWeight(desiredType); } if (stringSubType != StringConversions.StringSubtype.None) { return WEIGHT_NUMBER_TO_STRING; } break; case DataType.String: if (stringSubType == StringConversions.StringSubtype.String) { return WEIGHT_EXACT_MATCH; } else if (stringSubType == StringConversions.StringSubtype.StringBuilder) { return WEIGHT_STRING_TO_STRINGBUILDER; } else if (stringSubType == StringConversions.StringSubtype.Char) { return WEIGHT_STRING_TO_CHAR; } break; case DataType.Function: if (desiredType == typeof(Closure)) { return WEIGHT_EXACT_MATCH; } else if (desiredType == typeof(ScriptFunctionDelegate)) { return WEIGHT_EXACT_MATCH; } break; case DataType.ClrFunction: if (desiredType == typeof(CallbackFunction)) { return WEIGHT_EXACT_MATCH; } else if (desiredType == typeof(Func<ScriptExecutionContext, CallbackArguments, DynValue>)) { return WEIGHT_EXACT_MATCH; } break; case DataType.UserData: if (value.UserData.Object != null) { var udObj = value.UserData.Object; var udDesc = value.UserData.Descriptor; if (udDesc.IsTypeCompatible(desiredType, udObj)) { return WEIGHT_EXACT_MATCH; } if (stringSubType != StringConversions.StringSubtype.None) { return WEIGHT_USERDATA_TO_STRING; } } break; case DataType.Table: if (desiredType == typeof(Table) || Framework.Do.IsAssignableFrom(desiredType, typeof(Table))) { return WEIGHT_EXACT_MATCH; } else if (TableConversions.CanConvertTableToType(value.Table, desiredType)) { return WEIGHT_TABLE_CONVERSION; } break; case DataType.Tuple: break; } return WEIGHT_NO_MATCH; } private static int GetNumericTypeWeight(Type desiredType) { if (desiredType == typeof(double) || desiredType == typeof(decimal)) { return WEIGHT_EXACT_MATCH; } return WEIGHT_NUMBER_DOWNCAST; } } }
35.320796
118
0.44441
[ "MIT" ]
blakepell/AvalonMudClient
src/Avalon.MoonSharp/Interop/Converters/ScriptToClrConversions.cs
15,967
C#
namespace SamplePrism.Services.Implementations.PrinterModule.Formatters { public interface ILineFormatter { int FontWidth { get; set; } int FontHeight { get; set; } FormatTag Tag { get; set; } string GetFormattedLine(); string GetFormattedLineWithoutTags(); } }
26.25
72
0.650794
[ "Apache-2.0" ]
XYRYTeam/SimplePrism
SamplePrism.Presentation.Services/CommonServices/Implementations/PrinterModule/Formatters/ILineFormatter.cs
317
C#
// // Authors: // Ben Motmans <ben.motmans@gmail.com> // // Copyright (c) 2007 Ben Motmans // // 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 Gtk; using System; using System.Data; using System.Collections; using System.Collections.Generic; using Mono.Addins; using MonoDevelop.Core; namespace MonoDevelop.Database.Components { public class DataGridColumn : TreeViewColumn { private DataGrid grid; private DataColumn column; private int columnIndex; private IDataGridContentRenderer contentRenderer; private static IDataGridContentRenderer nullRenderer; static DataGridColumn () { nullRenderer = new NullContentRenderer (); } public DataGridColumn (DataGrid grid, DataColumn column, int columnIndex) { this.grid = grid; this.column = column; this.columnIndex = columnIndex; contentRenderer = grid.GetDataGridContentRenderer (column.DataType); Title = column.ColumnName.Replace ("_", "__"); //underscores are normally used for underlining, so needs escape char Clickable = true; CellRendererText textRenderer = new CellRendererText (); PackStart (textRenderer, true); SetCellDataFunc (textRenderer, new CellLayoutDataFunc (ContentDataFunc)); } public int ColumnIndex { get { return columnIndex; } } public IComparer ContentComparer { get { return contentRenderer; } } public Type DataType { get { return column.DataType; } } private void ContentDataFunc (CellLayout layout, CellRenderer cell, TreeModel model, TreeIter iter) { object dataObject = model.GetValue (iter, columnIndex); if (dataObject == null) nullRenderer.SetContent (cell as CellRendererText, dataObject); else contentRenderer.SetContent (cell as CellRendererText, dataObject); } protected override void OnClicked () { base.OnClicked (); grid.Sort (this); } } }
31.451613
119
0.73641
[ "MIT" ]
mono/linux-packaging-monodevelop-database
MonoDevelop.Database.Components/Widgets/DataGrid/DataGridColumn.cs
2,927
C#
using System; using System.Collections.Generic; using System.Text; namespace Galaxy.Domain { public class InstanceEventRouter : IEventRouter { private readonly Dictionary<Type, Action<object>> _handlers; public InstanceEventRouter() => _handlers = new Dictionary<Type, Action<object>>(); private void ConfigureRoute(Type @event, Action<object> handler) { if (@event == null) { throw new ArgumentNullException(nameof(@event)); } if (handler == null) { throw new ArgumentNullException(nameof(handler)); } _handlers.Add(@event, handler); } private void ConfigureRoute<TEvent>(Action<TEvent> handler) { if (handler == null) { throw new ArgumentNullException(nameof(handler)); } _handlers.Add(typeof(TEvent), @event => handler((TEvent)@event)); } public void Register<TEvent>(Action<TEvent> handler) { if (handler == null) { throw new ArgumentNullException(nameof(handler)); } this.ConfigureRoute(handler); } public void Register(Type @event, Action<object> handler) { if (handler == null) { throw new ArgumentNullException(nameof(handler)); } this.ConfigureRoute(@event, handler); } public void Route(object @event) { if (@event == null) throw new ArgumentNullException(nameof(@event)); Action<object> handler; if (_handlers.TryGetValue(@event.GetType(), out handler)) { handler(@event); } } public void Apply(object @event) { this.Route(@event); } } }
26.28
91
0.513445
[ "MIT" ]
eyazici90/Galaxy
src/Galaxy/Domain/InstanceEventRouter.cs
1,973
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace fanyi { public partial class Form1 : Form { public Form1() { InitializeComponent(); //加载句型集合列表 LoadJuxing(); BindJuxingEditList(); } private void Form1_Load(object sender, EventArgs e) { } #region 翻译 private void btnMSZ2E_Click(object sender, EventArgs e) { ITranFac fac = new MsFac(); string re = ""; if (CommonFun.HasChinese(txtOrign.Text)) { re = fac.TranTxt(txtOrign.Text, "zh-CHS", "en"); } else { re = fac.TranTxt(txtOrign.Text, "en", "zh-CHS"); } txtBing.Text = re; } private void btnGoogle_Click(object sender, EventArgs e) { ITranFac fac = new GoogleDotNetFac(); if (CommonFun.HasChinese(txtOrign.Text)) { txtGoogle.Text = fac.TranTxt(txtOrign.Text.Trim(), "zh-CN", "en"); } else { txtGoogle.Text = fac.TranTxt(txtOrign.Text.Trim(), "en", "zh-CN"); } } private void btnAutoTranBaidu_Click(object sender, EventArgs e) { ITranFac fac = new BaiDuFac(); string re = ""; if (CommonFun.HasChinese(txtOrign.Text)) { re = fac.TranTxt(txtOrign.Text, "zh-CHS", "en"); } else { re = fac.TranTxt(txtOrign.Text, "en", "zh"); } txtBaidu.Text = re; } private void btnAutoTranYouDao_Click(object sender, EventArgs e) { ITranFac fac = new YouDaoFac(); string re = ""; if (CommonFun.HasChinese(txtOrign.Text)) { re = fac.TranTxt(txtOrign.Text, "auto", "EN"); } else { re = fac.TranTxt(txtOrign.Text, "auto", "zh-CHS"); } txtYoudao.Text = re; } #endregion #region 添加正文 private void addGoogle_Click(object sender, EventArgs e) { txtAfterTran.Text += txtGoogle.Text + "\r\n\r\n"; } private void addBing_Click(object sender, EventArgs e) { txtAfterTran.Text += txtBing.Text + "\r\n\r\n"; } private void addYoudao_Click(object sender, EventArgs e) { txtAfterTran.Text += txtYoudao.Text + "\r\n\r\n"; } private void addBaidu_Click(object sender, EventArgs e) { txtAfterTran.Text += txtBaidu.Text + "\r\n\r\n"; } #endregion private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e) { } #region 清空 private void btnClsZW_Click(object sender, EventArgs e) { txtAfterTran.Text = ""; } private void btnClsGoogle_Click(object sender, EventArgs e) { txtGoogle.Clear(); } private void btnClsMs_Click(object sender, EventArgs e) { txtBing.Clear(); } private void btnClsYouDao_Click(object sender, EventArgs e) { txtYoudao.Clear(); } private void btnClsBaidu_Click(object sender, EventArgs e) { txtBaidu.Clear(); } private void button1_Click(object sender, EventArgs e) { this.txtOrign.Text = ""; } #endregion //保存文件 private void btnSaveFile_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = ""; sfd.InitialDirectory = @"C:\"; sfd.Filter = "文本文件| *.txt"; sfd.ShowDialog(); string path = sfd.FileName; if (path == "") { return; } using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) { byte[] buffer = Encoding.Default.GetBytes(txtAfterTran.Text); fsWrite.Write(buffer, 0, buffer.Length); MessageBox.Show("保存成功"); } } #region 句型切换选择 //句型双击 private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e) { txtAfterTran.Text += this.juxingcollist.Text; //this.juxingcollist.SelectedItem.; } //句型集合下拉 private void cmbJuxingJiheList_SelectedIndexChanged(object sender, EventArgs e) { if (this.cmbJuxingJiheList.SelectedValue != null&& !string.IsNullOrEmpty(this.cmbJuxingJiheList.SelectedValue.ToString())) { LoadJuxingCol(this.cmbJuxingJiheList.SelectedValue.ToString()); } } //加载句型明细 private void LoadJuxingCol(string colid) { this.juxingcollist.DataSource = null; this.juxingcollist.Items.Clear(); DataTable juxingcolList = JuxingHelper.LoadJuxingColList(colid); this.juxingcollist.DisplayMember = "det_memo"; this.juxingcollist.ValueMember = "det_id"; this.juxingcollist.DataSource = juxingcolList; } //加载句型集合 private void LoadJuxing() { this.cmbJuxingJiheList.DataSource = null; this.cmbJuxingJiheList.Items.Clear(); DataTable juxingList = JuxingHelper.LoadJuxingList(); this.cmbJuxingJiheList.DisplayMember = "col_name"; this.cmbJuxingJiheList.ValueMember = "col_id"; this.cmbJuxingJiheList.DataSource = juxingList; } //加载句型集合 private void BindJuxingEditList() { this.lstJuxingEdit.DataSource = null; this.lstJuxingEdit.Items.Clear(); DataTable juxingList = JuxingHelper.LoadJuxingColList("1"); this.lstJuxingEdit.DisplayMember = "det_memo"; this.lstJuxingEdit.ValueMember = "det_id"; this.lstJuxingEdit.DataSource = juxingList; } #endregion private void tabPage2_Click(object sender, EventArgs e) { } private void btnAddJuXingName_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(this.txtInputJuXingDetail.Text.Trim())) { JuxingHelper.AddJuXing(this.txtInputJuXingDetail.Text.Trim()); BindJuxingEditList(); LoadJuxing(); this.txtInputJuXingDetail.Text = ""; } } private void btnDelJuXingName_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(this.lstJuxingEdit.SelectedValue.ToString())) { //delete mingxi JuxingHelper.DelJuXing(this.lstJuxingEdit.SelectedValue.ToString()); BindJuxingEditList(); LoadJuxing(); } } private void tabPage3_Click(object sender, EventArgs e) { } private void lstJuxingEdit_SelectedIndexChanged(object sender, EventArgs e) { this.label5.Text = this.lstJuxingEdit.Text; } private void juxingcollist_SelectedIndexChanged(object sender, EventArgs e) { this.label6.Text = this.juxingcollist.Text; } } }
25.540453
102
0.526736
[ "Apache-2.0" ]
fat32jin/fanyi
fanyi/Form1.cs
8,018
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading.Tasks; using starsky.feature.metaupdate.Helpers; using starsky.feature.metaupdate.Interfaces; using starsky.foundation.database.Helpers; using starsky.foundation.database.Interfaces; using starsky.foundation.database.Models; using starsky.foundation.injection; using starsky.foundation.platform.Helpers; using starsky.foundation.platform.Interfaces; using starsky.foundation.platform.Models; using starsky.foundation.storage.Interfaces; using starsky.foundation.storage.Models; using starsky.foundation.storage.Storage; namespace starsky.feature.metaupdate.Services { [Service(typeof(IMetaReplaceService), InjectionLifetime = InjectionLifetime.Scoped)] public class MetaReplaceService : IMetaReplaceService { private readonly IQuery _query; private readonly AppSettings _appSettings; private readonly IStorage _iStorage; private readonly StatusCodesHelper _statusCodeHelper; private readonly IWebLogger _logger; /// <summary>Replace meta content</summary> /// <param name="query">Starsky IQuery interface to do calls on the database</param> /// <param name="appSettings">Settings of the application</param> /// <param name="selectorStorage">storage abstraction</param> /// <param name="logger">web logger</param> public MetaReplaceService(IQuery query, AppSettings appSettings, ISelectorStorage selectorStorage, IWebLogger logger) { _query = query; _appSettings = appSettings; if ( selectorStorage != null ) _iStorage = selectorStorage.Get(SelectorStorage.StorageServices.SubPath); _statusCodeHelper = new StatusCodesHelper(_appSettings); _logger = logger; } /// <summary> /// Search and replace in string based fields (only Getting and replacing) /// </summary> /// <param name="f">subPath (split by dot comma ;)</param> /// <param name="search"></param> /// <param name="replace"></param> /// <param name="fieldName"></param> /// <param name="collections"></param> public async Task<List<FileIndexItem>> Replace(string f, string fieldName, string search, string replace, bool collections) { // when you search for nothing, your fast done if ( string.IsNullOrEmpty(search) ) return new List<FileIndexItem> { new FileIndexItem{Status = FileIndexItem.ExifStatus.OperationNotSupported} }; // escaping null values if ( string.IsNullOrEmpty(replace) ) replace = string.Empty; if ( ! FileIndexCompareHelper.CheckIfPropertyExist(fieldName) ) return new List<FileIndexItem> { new FileIndexItem{Status = FileIndexItem.ExifStatus.OperationNotSupported} }; var inputFilePaths = PathHelper.SplitInputFilePaths(f); // the result list var fileIndexUpdatedList = new List<FileIndexItem>(); // Prefill cache to avoid fast updating issues await new AddParentCacheIfNotExist(_query,_logger).AddParentCacheIfNotExistAsync(inputFilePaths); // Assumes that this give status Ok back by default var queryFileIndexItemsList = await _query.GetObjectsByFilePathAsync( inputFilePaths.ToList(), collections); // to collect foreach ( var fileIndexItem in queryFileIndexItemsList ) { if ( _iStorage.IsFolderOrFile(fileIndexItem.FilePath) == FolderOrFileModel.FolderOrFileTypeList.Deleted ) // folder deleted { _statusCodeHelper.ReturnExifStatusError(fileIndexItem, FileIndexItem.ExifStatus.NotFoundSourceMissing, fileIndexUpdatedList); continue; } // Dir is readonly / don't edit if ( new StatusCodesHelper(_appSettings).IsReadOnlyStatus(fileIndexItem) == FileIndexItem.ExifStatus.ReadOnly) { _statusCodeHelper.ReturnExifStatusError(fileIndexItem, FileIndexItem.ExifStatus.ReadOnly, fileIndexUpdatedList); continue; } fileIndexUpdatedList.Add(fileIndexItem); } fileIndexUpdatedList = SearchAndReplace(fileIndexUpdatedList, fieldName, search, replace); AddNotFoundInIndexStatus.Update(inputFilePaths, fileIndexUpdatedList); var fileIndexResultList = new List<FileIndexItem>(); foreach ( var fileIndexItem in fileIndexUpdatedList ) { // Status Ok is already set // Deleted is allowed but the status need be updated if ((fileIndexItem.Status == FileIndexItem.ExifStatus.Ok) && new StatusCodesHelper(_appSettings).IsDeletedStatus(fileIndexItem) == FileIndexItem.ExifStatus.Deleted) { fileIndexItem.Status = FileIndexItem.ExifStatus.Deleted; } fileIndexResultList.Add(fileIndexItem); } return fileIndexResultList; } public List<FileIndexItem> SearchAndReplace(List<FileIndexItem> fileIndexResultsList, string fieldName, string search, string replace) { foreach ( var fileIndexItem in fileIndexResultsList.Where( p => p.Status == FileIndexItem.ExifStatus.Ok || p.Status == FileIndexItem.ExifStatus.Deleted) ) { var searchInObject = FileIndexCompareHelper.Get(fileIndexItem, fieldName); var replacedToObject = new object(); PropertyInfo[] propertiesA = new FileIndexItem().GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance); PropertyInfo property = propertiesA.FirstOrDefault(p => string.Equals( p.Name, fieldName, StringComparison.InvariantCultureIgnoreCase)); if ( property.PropertyType == typeof(string) ) { var searchIn = ( string ) searchInObject; // Replace Ignore Case replacedToObject = Regex.Replace( searchIn, Regex.Escape(search), replace.Replace("$","$$"), RegexOptions.IgnoreCase ); } // only string types are added here, other types are ignored for now FileIndexCompareHelper.Set(fileIndexItem, fieldName, replacedToObject); } return fileIndexResultsList; } } }
35.939024
127
0.742111
[ "MIT" ]
qdraw/starsky
starsky/starsky.feature.metaupdate/Services/MetaReplaceService.cs
5,894
C#
// See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.ML.Runtime; namespace Scikit.ML.DataFrame { /// <summary> /// Implements grouping functions for dataframe. /// </summary> public static class DataFrameRandom { /// <summary> /// Draws n random integers in [0, N-1]. /// They can be distinct or not. /// The function is not efficient if n is close to N and distinct is true. /// </summary> public static int[] RandomIntegers(int n, int N, bool distinct = false, IRandom rand = null) { var res = new int[n]; if (rand == null) rand = new SysRandom(); if (distinct) { if (n > N) throw new DataValueError($"Cannot draw more than {N} distinct values."); var hash = new HashSet<int>(); int nb = 0; int i; while (nb < n) { i = rand.Next(N); if (hash.Contains(i)) continue; hash.Add(i); res[nb] = i; ++nb; } } else { for (int i = 0; i < n; ++i) res[i] = rand.Next(N); } return res; } } }
29.04
100
0.434573
[ "MIT" ]
xadupre/machinelearning_dataframe
DataManipulation/Helpers/DataFrameRandom.cs
1,454
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.7.0.0")] [assembly: AssemblyFileVersion("3.7.0.0")] public class Version{ static string GetVersion(){ return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Major.ToString()+"."+System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Minor.ToString(); } }
27.5625
189
0.75737
[ "Apache-2.0" ]
fredericaltorres/TextHighlighterExtension
__VersionInfo.cs
443
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.Generic; using System.Diagnostics; using System.Diagnostics.ContractsLight; using System.IO; using System.Linq; using System.Threading.Tasks; using BuildXL.ToolSupport; using BuildXL.Utilities; using BuildXL.Utilities.Instrumentation.Common; using BuildXL.Utilities.Tracing; using BuildXL.Utilities.Configuration; using HelpLevel = BuildXL.ToolSupport.HelpLevel; using BuildXL.Storage; namespace BuildXL.Execution.Analyzer { internal sealed partial class Args : CommandLineUtilities { private static readonly string[] s_helpStrings = new[] { "?", "help" }; private readonly AnalysisMode? m_mode; private readonly AnalysisInput m_analysisInput; private AnalysisInput m_analysisInputOther; private readonly Analyzer m_analyzer; private readonly Analyzer m_analyzerOther; private readonly bool m_canHandleWorkerEvents = true; public readonly IEnumerable<Option> AnalyzerOptions; public readonly bool Help; public readonly LoggingContext LoggingContext = new LoggingContext("BuildXL.Execution.Analyzer"); public readonly TrackingEventListener TrackingEventListener = new TrackingEventListener(Events.Log); // Variables that are unused without full telemetry private readonly bool m_telemetryDisabled = false; private Stopwatch m_telemetryStopwatch = new Stopwatch(); public Args(string[] args) : base(args) { List<Option> analyzerOptions = new List<Option>(); string cachedGraphDirectory = null; // TODO: Embed HashType in XLG file and update analyzer to use that instead of setting HashType globally. ContentHashingUtilities.SetDefaultHashType(); foreach (Option opt in Options) { if (opt.Name.Equals("executionLog", StringComparison.OrdinalIgnoreCase) || opt.Name.Equals("xl", StringComparison.OrdinalIgnoreCase)) { if (string.IsNullOrEmpty(m_analysisInput.ExecutionLogPath)) { m_analysisInput.ExecutionLogPath = ParsePathOption(opt); } else { m_analysisInputOther.ExecutionLogPath = ParseSingletonPathOption(opt, m_analysisInputOther.ExecutionLogPath); } } else if (opt.Name.Equals("graphDirectory", StringComparison.OrdinalIgnoreCase) || opt.Name.Equals("gd", StringComparison.OrdinalIgnoreCase)) { cachedGraphDirectory = ParseSingletonPathOption(opt, cachedGraphDirectory); } else if (opt.Name.Equals("mode", StringComparison.OrdinalIgnoreCase) || opt.Name.Equals("m", StringComparison.OrdinalIgnoreCase)) { m_mode = ParseEnumOption<AnalysisMode>(opt); } else if (opt.Name.Equals("disableTelemetry")) { m_telemetryDisabled = true; } else if (opt.Name.Equals("disableWorkerEvents", StringComparison.OrdinalIgnoreCase)) { m_canHandleWorkerEvents = false; } else if (s_helpStrings.Any(s => opt.Name.Equals(s, StringComparison.OrdinalIgnoreCase))) { // If the analyzer was called with '/help' argument - print help and exit Help = true; WriteHelp(); return; } else { analyzerOptions.Add(opt); } } AnalyzerOptions = analyzerOptions; if (!m_mode.HasValue) { throw Error("Mode parameter is required"); } // Add required parameter errors here switch (m_mode.Value) { case AnalysisMode.ObservedAccess: { if (!analyzerOptions.Any(opt => opt.Name.Equals("o"))) { throw Error("When executing `ObservedAccess` mode, an `/o:PATH_TO_OUTPUT_FILE` parameter is required to store the generated output"); } break; } } // Only send telemetry if all arguments were valid TelemetryStartup(); switch (m_mode.Value) { case AnalysisMode.SpecClosure: var analyzer = InitializeSpecClosureAnalyzer(); analyzer.Analyze(); break; } if (string.IsNullOrEmpty(m_analysisInput.ExecutionLogPath) && string.IsNullOrEmpty(cachedGraphDirectory)) { // Try to find the last build log from the user if none was specied. var invocation = new global::BuildXL.Engine.Invocations().GetLastInvocation(LoggingContext); if (invocation == null || !Directory.Exists(invocation.Value.LogsFolder)) { throw Error("executionLog or graphDirectory parameter is required"); } Console.WriteLine("Using last build from: '{0}', you can use /executionLog or /graphDirectory arguments to explicitly choose a build", invocation.Value.LogsFolder); m_analysisInput.ExecutionLogPath = invocation.Value.LogsFolder; } if (m_mode.Value == AnalysisMode.LogCompare && string.IsNullOrEmpty(m_analysisInput.ExecutionLogPath)) { throw Error("Additional executionLog to compare parameter is required"); } // The fingerprint store based cache miss analyzer only uses graph information from the newer build, // so skip loading the graph for the earlier build if (m_mode.Value != AnalysisMode.CacheMiss) { if (!m_analysisInput.LoadCacheGraph(cachedGraphDirectory)) { throw Error($"Could not load cached graph from directory {cachedGraphDirectory}"); } } switch (m_mode.Value) { case AnalysisMode.FingerprintText: m_analyzer = InitializeFingerprintTextAnalyzer(); break; case AnalysisMode.ExportGraph: m_analyzer = InitializePipGraphExporter(); break; case AnalysisMode.DirMembership: m_analyzer = InitializeDirMembershipAnalyzer(); break; case AnalysisMode.Dev: m_analyzer = InitializeDevAnalyzer(); break; case AnalysisMode.DumpProcess: m_analyzer = InitializeDumpProcessAnalyzer(); break; case AnalysisMode.EventStats: m_analyzer = InitializeEventStatsAnalyzer(); break; case AnalysisMode.Simulate: m_analyzer = InitializeBuildSimulatorAnalyzer(m_analysisInput); break; case AnalysisMode.ExportDgml: m_analyzer = InitializeExportDgmlAnalyzer(); break; case AnalysisMode.CriticalPath: m_analyzer = InitializeCriticalPathAnalyzer(); break; case AnalysisMode.FileImpact: m_analyzer = InitializeFileImpactAnalyzer(); break; case AnalysisMode.FileConsumption: m_analyzer = InitializeFileConsumptionAnalyzer(); break; case AnalysisMode.Codex: m_analyzer = InitializeCodexAnalyzer(); break; case AnalysisMode.DumpPip: m_analyzer = InitializeDumpPipAnalyzer(); break; case AnalysisMode.CosineDumpPip: m_analyzer = InitializeCosineDumpPip(); break; case AnalysisMode.CosineJson: m_analyzer = InitializeCosineJsonExport(); break; case AnalysisMode.ProcessRunScript: m_analyzer = InitializeProcessRunScriptAnalyzer(); break; case AnalysisMode.ObservedInput: m_analyzer = InitializeObservedInputResult(); break; case AnalysisMode.ObservedInputSummary: m_analyzer = InitializeObservedInputSummaryResult(); break; case AnalysisMode.ToolEnumeration: m_analyzer = InitializeToolEnumerationAnalyzer(); break; case AnalysisMode.FailedPipInput: m_analyzer = InitializeFailedPipInputAnalyzer(); break; case AnalysisMode.FailedPipsDump: m_analyzer = InitializeFailedPipsDumpAnalyzer(); if (!string.IsNullOrEmpty(m_analysisInputOther.ExecutionLogPath)) { if (!m_analysisInputOther.LoadCacheGraph(null)) { throw Error("Could not load second cached graph"); } m_analyzerOther = ((FailedPipsDumpAnalyzer)m_analyzer).GetDiffAnalyzer(m_analysisInputOther); } break; case AnalysisMode.Whitelist: m_analyzer = InitializeWhitelistAnalyzer(); break; case AnalysisMode.IdeGenerator: m_analyzer = InitializeIdeGenerator(); break; case AnalysisMode.PipExecutionPerformance: m_analyzer = InitializePipExecutionPerformanceAnalyzer(); break; case AnalysisMode.ProcessDetouringStatus: m_analyzer = InitializeProcessDetouringStatusAnalyzer(); break; case AnalysisMode.ObservedAccess: m_analyzer = InitializeObservedAccessAnalyzer(); break; case AnalysisMode.CacheDump: m_analyzer = InitializeCacheDumpAnalyzer(m_analysisInput); break; case AnalysisMode.BuildStatus: m_analyzer = InitializeBuildStatus(m_analysisInput); break; case AnalysisMode.WinIdeDependency: m_analyzer = InitializeWinIdeDependencyAnalyzer(); break; case AnalysisMode.PerfSummary: m_analyzer = InitializePerfSummaryAnalyzer(); break; case AnalysisMode.LogCompare: m_analyzer = InitializeSummaryAnalyzer(m_analysisInput); if (!m_analysisInputOther.LoadCacheGraph(null)) { throw Error("Could not load second cached graph"); } m_analyzerOther = InitializeSummaryAnalyzer(m_analysisInputOther, true); break; case AnalysisMode.CacheMissLegacy: m_analyzer = InitializeCacheMissAnalyzer(m_analysisInput); if (!m_analysisInputOther.LoadCacheGraph(null)) { throw Error("Could not load second cached graph"); } m_analyzerOther = ((CacheMissAnalyzer)m_analyzer).GetDiffAnalyzer(m_analysisInputOther); break; case AnalysisMode.IncrementalSchedulingState: m_analyzer = InitializeIncrementalSchedulingStateAnalyzer(); break; case AnalysisMode.FileChangeTracker: m_analyzer = InitializeFileChangeTrackerAnalyzer(); break; case AnalysisMode.InputTracker: m_analyzer = InitializeInputTrackerAnalyzer(); break; case AnalysisMode.FilterLog: m_analyzer = InitializeFilterLogAnalyzer(); break; case AnalysisMode.PipFilter: m_analyzer = InitializePipFilterAnalyzer(); break; case AnalysisMode.CacheMiss: // This analyzer does not rely on the execution log if (!m_analysisInputOther.LoadCacheGraph(null)) { throw Error("Could not load second cached graph"); } m_analyzer = InitializeFingerprintStoreAnalyzer(m_analysisInput, m_analysisInputOther); break; case AnalysisMode.PipFingerprint: m_analyzer = InitializePipFingerprintAnalyzer(m_analysisInput); break; case AnalysisMode.ScheduledInputsOutputs: m_analyzer = InitializeScheduledInputsOutputsAnalyzer(); break; #if FEATURE_VSTS_ARTIFACTSERVICES case AnalysisMode.CacheHitPredictor: m_analyzer = InitializeCacheHitPredictor(); break; #endif case AnalysisMode.DependencyAnalyzer: m_analyzer = InitializeDependencyAnalyzer(); break; case AnalysisMode.GraphDiffAnalyzer: if (!m_analysisInputOther.LoadCacheGraph(null)) { throw Error("Could not load second cached graph"); } m_analyzer = InitializeGraphDiffAnalyzer(); break; case AnalysisMode.DumpMounts: m_analyzer = InitializeDumpMountsAnalyzer(); break; default: Contract.Assert(false, "Unhandled analysis mode"); break; } Contract.Assert(m_analyzer != null, "Analyzer must be set."); m_analyzer.LoggingContext = LoggingContext; m_analyzer.CanHandleWorkerEvents = m_canHandleWorkerEvents; if (m_analyzerOther != null) { m_analyzerOther.CanHandleWorkerEvents = m_canHandleWorkerEvents; } } public int Analyze() { if (m_analyzer == null) { return 0; } m_analyzer.Prepare(); if (m_analysisInput.ExecutionLogPath != null) { // NOTE: We call Prepare above so we don't need to prepare as a part of reading the execution log var reader = Task.Run(() => m_analyzer.ReadExecutionLog(prepare: false)); if (m_mode == AnalysisMode.LogCompare) { m_analyzerOther.Prepare(); var otherReader = Task.Run(() => m_analyzerOther.ReadExecutionLog()); otherReader.Wait(); } if (m_mode == AnalysisMode.FailedPipsDump && m_analyzerOther != null) { var start = DateTime.Now; Console.WriteLine($"[{start}] Reading compare to Log"); var otherReader = Task.Run(() => m_analyzerOther.ReadExecutionLog()); otherReader.Wait(); var duration = DateTime.Now - start; Console.WriteLine($"Done reading compare to log : duration = [{duration}]"); } reader.Wait(); if (m_mode == AnalysisMode.CacheMissLegacy) { // First pass just to read in PipCacheMissType data var otherReader = Task.Run(() => m_analyzerOther.ReadExecutionLog()); otherReader.Wait(); // Second pass to do fingerprint differences analysis otherReader = Task.Run(() => m_analyzerOther.ReadExecutionLog()); otherReader.Wait(); } } var exitCode = m_analyzer.Analyze(); if (m_mode == AnalysisMode.FailedPipsDump && m_analyzerOther != null) { var failedPipsDump = (FailedPipsDumpAnalyzer)m_analyzer; exitCode = failedPipsDump.Compare(m_analyzerOther); } if (m_mode == AnalysisMode.LogCompare) { m_analyzerOther.Analyze(); SummaryAnalyzer summary = (SummaryAnalyzer)m_analyzer; exitCode = summary.Compare((SummaryAnalyzer)m_analyzerOther); } if (m_mode == AnalysisMode.CacheMissLegacy) { exitCode = m_analyzerOther.Analyze(); } m_analyzer?.Dispose(); m_analyzerOther?.Dispose(); TelemetryShutdown(); return exitCode; } #region Telemetry private void HandleUnhandledFailure(Exception exception) { // Show the exception to the user ConsoleColor original = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine(exception.ToString()); Console.ForegroundColor = original; // Log the exception to telemetry if (AriaV2StaticState.IsEnabled) { Tracing.Logger.Log.ExecutionAnalyzerCatastrophicFailure(LoggingContext, m_mode.ToString(), exception.ToString()); TelemetryShutdown(); } Environment.Exit(ExitCode.FromExitKind(ExitKind.InternalError)); } private void TelemetryStartup() { AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => { HandleUnhandledFailure( eventArgs.ExceptionObject as Exception ); }; if (!Debugger.IsAttached && !m_telemetryDisabled) { AriaV2StaticState.Enable(global::BuildXL.Tracing.AriaTenantToken.Key); TrackingEventListener.RegisterEventSource(ETWLogger.Log); m_telemetryStopwatch.Start(); } } private void TelemetryShutdown() { if (AriaV2StaticState.IsEnabled && !m_telemetryDisabled) { m_telemetryStopwatch.Stop(); Tracing.Logger.Log.ExecutionAnalyzerInvoked(LoggingContext, m_mode.ToString(), m_telemetryStopwatch.ElapsedMilliseconds, Environment.CommandLine); LogEventSummary(); // Analyzer telemetry is not critical to BuildXL, so no special handling for telemetry shutdown issues AriaV2StaticState.TryShutDown(TimeSpan.FromSeconds(10), out Exception telemetryShutdownException); } } #endregion Telemetry private AnalysisInput GetAnalysisInput() { return m_analysisInput; } private static void WriteHelp() { HelpWriter writer = new HelpWriter(); writer.WriteBanner($"{Branding.AnalyzerExecutableName} - Tool for performing analysis/transformation of cached pip graphs and execution logs."); writer.WriteLine(""); writer.WriteLine("Analysis Modes:"); writer.WriteLine(""); WriteFingerprintTextAnalyzerHelp(writer); writer.WriteLine(""); WritePipGraphExporterHelp(writer); writer.WriteLine(""); WriteDirMembershipHelp(writer); writer.WriteLine(""); WriteDumpProcessAnalyzerHelp(writer); writer.WriteLine(""); WriteExportDgmlAnalyzerHelp(writer); writer.WriteLine(""); WriteObservedInputHelp(writer); writer.WriteLine(""); WriteProcessDetouringHelp(writer); writer.WriteLine(""); WritePipExecutionPerformanceAnalyzerHelp(writer); writer.WriteLine(""); WriteObservedInputSummaryHelp(writer); writer.WriteLine(""); WriteObservedAccessHelp(writer); writer.WriteLine(""); WriteToolEnumerationHelp(writer); writer.WriteLine(""); WriteCriticalPathAnalyzerHelp(writer); writer.WriteLine(""); WriteDumpPipAnalyzerHelp(writer); writer.WriteLine(""); WriteProcessRunScriptAnalyzerHelp(writer); writer.WriteLine(""); WriteWhitelistAnalyzerHelp(writer); writer.WriteLine(""); WriteSummaryAnalyzerHelp(writer); writer.WriteLine(""); WriteBuildStatusHelp(writer); writer.WriteLine(""); WriteWinIdeDependencyAnalyzeHelp(writer); writer.WriteLine(""); WritePerfSummaryAnalyzerHelp(writer); writer.WriteLine(""); WriteEventStatsHelp(writer); writer.WriteLine(""); WriteIncrementalSchedulingStateAnalyzerHelp(writer); writer.WriteLine(""); WriteFileChangeTrackerAnalyzerHelp(writer); writer.WriteLine(""); WriteInputTrackerAnalyzerHelp(writer); writer.WriteLine(""); WriteFingerprintStoreAnalyzerHelp(writer); writer.WriteLine(""); WritePipFingerprintAnalyzerHelp(writer); writer.WriteLine(""); WriteCacheMissHelp(writer); writer.WriteLine(""); WriteCacheDumpHelp(writer); writer.WriteLine(""); WriteBuildSimulatorHelp(writer); #if FEATURE_VSTS_ARTIFACTSERVICES writer.WriteLine(""); WriteCacheHitPredictorHelp(writer); #endif writer.WriteLine(""); WriteDependencyAnalyzerHelp(writer); writer.WriteLine(""); WriteGraphDiffAnalyzerHelp(writer); writer.WriteLine(""); WriteDumpMountsAnalyzerHelp(writer); writer.WriteLine(""); WritePipFilterHelp(writer); writer.WriteLine(""); WriteFailedPipsDumpAnalyzerHelp(writer); writer.WriteLine(""); WriteCosineDumpPipHelp(writer); } public void LogEventSummary() { Tracing.Logger.Log.ExecutionAnalyzerEventCount(LoggingContext, TrackingEventListener.ToEventCountDictionary()); } } /// <summary> /// <see cref="HelpWriter"/> for analyzers. /// </summary> public static class HelpWriterExtensions { /// <summary> /// Writes the mode flag help for each analyzer. /// </summary> public static void WriteModeOption(this HelpWriter writer, string modeName, string description, HelpLevel level = HelpLevel.Standard) { writer.WriteOption("mode", string.Format("\"{0}\". {1}", modeName, description), level: level, shortName: "m"); } } }
40.988255
181
0.540137
[ "MIT" ]
MatisseHack/BuildXL
Public/Src/Tools/Execution.Analyzer/Args.cs
24,429
C#
namespace WebMConverter { partial class OverlayForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.menuStrip = new System.Windows.Forms.MenuStrip(); this.previewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.trimTimingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.startToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.endToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.frameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.timeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.buttonConfirm = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.previewFrame = new WebMConverter.PreviewFrame(); this.filePicker = new System.Windows.Forms.OpenFileDialog(); this.menuStrip.SuspendLayout(); this.SuspendLayout(); // // menuStrip // this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.previewToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; this.menuStrip.Size = new System.Drawing.Size(744, 24); this.menuStrip.TabIndex = 0; // // previewToolStripMenuItem // this.previewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.trimTimingToolStripMenuItem, this.frameToolStripMenuItem, this.timeToolStripMenuItem}); this.previewToolStripMenuItem.Name = "previewToolStripMenuItem"; this.previewToolStripMenuItem.Size = new System.Drawing.Size(69, 20); this.previewToolStripMenuItem.Text = "Preview..."; // // trimTimingToolStripMenuItem // this.trimTimingToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.startToolStripMenuItem, this.endToolStripMenuItem}); this.trimTimingToolStripMenuItem.Enabled = false; this.trimTimingToolStripMenuItem.Name = "trimTimingToolStripMenuItem"; this.trimTimingToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.trimTimingToolStripMenuItem.Text = "Trim timing..."; // // startToolStripMenuItem // this.startToolStripMenuItem.Name = "startToolStripMenuItem"; this.startToolStripMenuItem.Size = new System.Drawing.Size(98, 22); this.startToolStripMenuItem.Text = "Start"; this.startToolStripMenuItem.Click += new System.EventHandler(this.startToolStripMenuItem_Click); // // endToolStripMenuItem // this.endToolStripMenuItem.Name = "endToolStripMenuItem"; this.endToolStripMenuItem.Size = new System.Drawing.Size(98, 22); this.endToolStripMenuItem.Text = "End"; this.endToolStripMenuItem.Click += new System.EventHandler(this.endToolStripMenuItem_Click); // // frameToolStripMenuItem // this.frameToolStripMenuItem.Name = "frameToolStripMenuItem"; this.frameToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.frameToolStripMenuItem.Text = "Frame"; this.frameToolStripMenuItem.Click += new System.EventHandler(this.frameToolStripMenuItem_Click); // // timeToolStripMenuItem // this.timeToolStripMenuItem.Name = "timeToolStripMenuItem"; this.timeToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.timeToolStripMenuItem.Text = "Time"; this.timeToolStripMenuItem.Click += new System.EventHandler(this.timeToolStripMenuItem_Click); // // buttonConfirm // this.buttonConfirm.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonConfirm.Location = new System.Drawing.Point(666, 518); this.buttonConfirm.Name = "buttonConfirm"; this.buttonConfirm.Size = new System.Drawing.Size(75, 23); this.buttonConfirm.TabIndex = 1; this.buttonConfirm.Text = "Confirm"; this.buttonConfirm.UseVisualStyleBackColor = true; this.buttonConfirm.Click += new System.EventHandler(this.buttonConfirm_Click); // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(589, 518); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(75, 23); this.buttonCancel.TabIndex = 2; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; // // previewFrame // this.previewFrame.BackColor = System.Drawing.SystemColors.ControlDark; this.previewFrame.Cursor = System.Windows.Forms.Cursors.SizeAll; this.previewFrame.Dock = System.Windows.Forms.DockStyle.Fill; this.previewFrame.Frame = 0; this.previewFrame.Location = new System.Drawing.Point(0, 24); this.previewFrame.Name = "previewFrame"; this.previewFrame.Size = new System.Drawing.Size(744, 520); this.previewFrame.TabIndex = 3; // // filePicker // this.filePicker.AddExtension = false; this.filePicker.Filter = "PNG files|*.png|All files|*.*"; // // OverlayForm // this.AcceptButton = this.buttonConfirm; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.ControlDark; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(744, 544); this.ControlBox = false; this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonConfirm); this.Controls.Add(this.previewFrame); this.Controls.Add(this.menuStrip); this.MainMenuStrip = this.menuStrip; this.MinimumSize = new System.Drawing.Size(466, 310); this.Name = "OverlayForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Overlay"; this.Load += new System.EventHandler(this.OverlayForm_Load); this.menuStrip.ResumeLayout(false); this.menuStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip; private System.Windows.Forms.ToolStripMenuItem previewToolStripMenuItem; private System.Windows.Forms.Button buttonConfirm; private System.Windows.Forms.Button buttonCancel; private PreviewFrame previewFrame; private System.Windows.Forms.ToolStripMenuItem trimTimingToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem startToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem endToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem frameToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem timeToolStripMenuItem; private System.Windows.Forms.OpenFileDialog filePicker; } }
50
164
0.631381
[ "MIT" ]
PatrickMadsen/WebMConverter
Filters/Overlay.Designer.cs
9,052
C#
using Feedbacks.CollectorInterface.DatabaseRepository; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Text; using System.Threading.Tasks; namespace Feedbacks.Collector.DataAccess { public abstract class DBContext { private readonly IDatabaseHandler database; public DBContext(IDatabaseConnectionParams databaseConnectionParams) { DatabaseHandlerFactory factory = new DatabaseHandlerFactory(databaseConnectionParams); database = factory.CreateDatabase(); } public DbConnection GetDatabasecOnnection() { return database.CreateConnection(); } public DbCommand GetCommand(string commandText, CommandType commandType) { return database.CreateCommand(commandText, commandType); } public void CreateParameter(DbCommand command, string name, object value, DbType dbType) { var param = command.CreateParameter(); param.DbType = dbType; param.ParameterName = name; param.Value = value; command.Parameters.Add(param); } public async Task<(DbConnection, DbDataReader)> ExecuteReaderAsync(DbCommand command) { try { var connection = database.CreateConnection(); await connection.OpenAsync(); command.Connection = connection; var reader = await command.ExecuteReaderAsync(); return (connection, reader); } catch (Exception ex) { throw ex; } } public async Task<bool> DeleteAsync(DbCommand command) { try { using var connection = database.CreateConnection(); await connection.OpenAsync(); command.Connection = connection; int affected = await command.ExecuteNonQueryAsync(); return affected > 0; } catch (Exception ex) { throw ex; } } public async Task<bool> InsertAsync(DbCommand command) { try { using var connection = database.CreateConnection(); await connection.OpenAsync(); command.Connection = connection; int affected = await command.ExecuteNonQueryAsync(); return affected > 0; } catch (Exception ex) { throw ex; } } public async Task<bool> UpdateAsync(DbCommand command) { try { using var connection = database.CreateConnection(); await connection.OpenAsync(); command.Connection = connection; int affected = await command.ExecuteNonQueryAsync(); return affected > 0; } catch (Exception ex) { throw ex; } } public async Task<T> GetScalarValue<T>(DbCommand command) { try { using var connection = database.CreateConnection(); await connection.OpenAsync(); command.Connection = connection; object objValue = await command.ExecuteScalarAsync(); if (objValue != null && objValue != DBNull.Value) return (T)Convert.ChangeType(objValue, typeof(T)); else return default; } catch (Exception ex) { throw ex; } } } }
32.845455
98
0.559646
[ "Apache-2.0" ]
KingCobrass/feedbacks.collector
Mahi.Uddin/Feedbacks.Collector.DataAccess/DBContext.cs
3,615
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Linq; using System.Runtime.InteropServices; using Java.Interop.Tools.TypeNameMappings; using Android.Runtime; namespace Java.Interop { public static partial class TypeManager { // Make this internal so that JNIEnv.Initialize can trigger the static // constructor so that JNIEnv.RegisterJNINatives() doesn't include // the static constructor execution. // Lock on jniToManaged before accessing EITHER jniToManaged or managedToJni. internal static Dictionary<string, Type> jniToManaged = new Dictionary<string, Type> (); static Dictionary<Type, string> managedToJni = new Dictionary<Type, string> (); internal static IntPtr id_Class_getName; static TypeManager () { var start = new DateTime (); if (Logger.LogTiming) { start = DateTime.UtcNow; Logger.Log (LogLevel.Info, "monodroid-timing", "TypeManager.cctor start: " + (start - new DateTime (1970, 1, 1)).TotalMilliseconds); } __TypeRegistrations.RegisterPackages (); if (Logger.LogTiming) { var end = DateTime.UtcNow; Logger.Log (LogLevel.Info, "monodroid-timing", "TypeManager.cctor time: " + (end - new DateTime (1970, 1, 1)).TotalMilliseconds + " [elapsed: " + (end - start).TotalMilliseconds + " ms]"); } } internal static string GetClassName (IntPtr class_ptr) { return JNIEnv.GetString (JNIEnv.CallObjectMethod (class_ptr, JNIEnv.mid_Class_getName), JniHandleOwnership.TransferLocalRef).Replace (".", "/"); } internal static string GetJniTypeName (Type type) { string jni; lock (jniToManaged) { if (managedToJni.TryGetValue (type, out jni)) return jni; } return null; } class TypeNameComparer : IComparer<string> { public int Compare (string x, string y) { if (object.ReferenceEquals (x, y)) return 0; if (x == null) return -1; if (y == null) return 1; int xe = x.IndexOf (':'); int ye = y.IndexOf (':'); int r = string.CompareOrdinal (x, 0, y, 0, System.Math.Max (xe, ye)); if (r != 0) return r; if (xe >= 0 && ye >= 0) return xe - ye; if (xe < 0) return x.Length - ye; return xe - y.Length; } } static readonly TypeNameComparer JavaNameComparer = new TypeNameComparer (); public static string LookupTypeMapping (string[] mappings, string javaType) { int i = Array.BinarySearch (mappings, javaType, JavaNameComparer); if (i < 0) return null; int c = mappings [i].IndexOf (':'); return mappings [i].Substring (c+1); } static Action<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr> cb_activate; internal static Delegate GetActivateHandler () { if (cb_activate == null) cb_activate = (Action<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) JNINativeWrapper.CreateDelegate ( (Action<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_Activate); return cb_activate; } #if JAVA_INTEROP internal static bool ActivationEnabled { get { return !JniEnvironment.WithinNewObjectScope; } } #else // !JAVA_INTEROP [ThreadStatic] static bool activation_disabled; internal static bool ActivationEnabled { get { return !activation_disabled; } set { activation_disabled = !value; } } #endif // !JAVA_INTEROP static Type[] GetParameterTypes (string signature) { if (String.IsNullOrEmpty (signature)) return new Type[0]; string[] typenames = signature.Split (':'); Type[] result = new Type [typenames.Length]; for (int i = 0; i < typenames.Length; i++) result [i] = Type.GetType (typenames [i], throwOnError:true); return result; } static void n_Activate (IntPtr jnienv, IntPtr jclass, IntPtr typename_ptr, IntPtr signature_ptr, IntPtr jobject, IntPtr parameters_ptr) { var o = Java.Lang.Object.PeekObject (jobject); var ex = o as IJavaObjectEx; if (ex != null) { if (!ex.NeedsActivation && !ex.IsProxy) return; } if (!ActivationEnabled) { if (Logger.LogGlobalRef) { Logger.Log (LogLevel.Info, "monodroid-gref", string.Format ("warning: Skipping managed constructor invocation for handle 0x{0} (key_handle 0x{1}). " + "Please use JNIEnv.StartCreateInstance() + JNIEnv.FinishCreateInstance() instead of " + "JNIEnv.NewObject() and/or JNIEnv.CreateInstance().", jobject.ToString ("x"), JNIEnv.IdentityHash (jobject).ToString ("x"))); } return; } Type type = Type.GetType (JNIEnv.GetString (typename_ptr, JniHandleOwnership.DoNotTransfer), throwOnError:true); if (type.IsGenericTypeDefinition) { throw new NotSupportedException ( "Constructing instances of generic types from Java is not supported, as the type parameters cannot be determined.", CreateJavaLocationException ()); } Type[] ptypes = GetParameterTypes (JNIEnv.GetString (signature_ptr, JniHandleOwnership.DoNotTransfer)); object[] parms = JNIEnv.GetObjectArray (parameters_ptr, ptypes); ConstructorInfo cinfo = type.GetConstructor (ptypes); if (cinfo == null) { throw CreateMissingConstructorException (type, ptypes); } if (o != null) { cinfo.Invoke (o, parms); return; } try { var activator = ConstructorBuilder.CreateDelegate (type, cinfo, ptypes); activator (jobject, parms); } catch (Exception e) { var m = string.Format ("Could not activate JNI Handle 0x{0} (key_handle 0x{1}) of Java type '{2}' as managed type '{3}'.", jobject.ToString ("x"), JNIEnv.IdentityHash (jobject).ToString ("x"), JNIEnv.GetClassNameFromInstance (jobject), type.FullName); Logger.Log (LogLevel.Warn, "monodroid", m); Logger.Log (LogLevel.Warn, "monodroid", CreateJavaLocationException ().ToString ()); throw new NotSupportedException (m, e); } } static Exception CreateMissingConstructorException (Type type, Type[] ptypes) { var message = new System.Text.StringBuilder (); message.Append ("Unable to find "); if (ptypes.Length == 0) message.Append ("the default constructor"); else { message.Append ("a constructor with signature (") .Append (ptypes [0].FullName); for (int i = 1; i < ptypes.Length; ++i) message.Append (", ").Append (ptypes [i].FullName); message.Append (")"); } message.Append (" on type ").Append (type.FullName) .Append (". Please provide the missing constructor."); return new NotSupportedException (message.ToString (), CreateJavaLocationException ()); } static Exception CreateJavaLocationException () { using (var loc = new Java.Lang.Error ("Java callstack:")) return new JavaLocationException (loc.ToString ()); } [DllImport ("__Internal")] internal static extern IntPtr monodroid_typemap_java_to_managed (string java); internal static Type GetJavaToManagedType (string class_name) { var t = monodroid_typemap_java_to_managed (class_name); if (t != IntPtr.Zero) return Type.GetType (Marshal.PtrToStringAnsi (t)); if (!JNIEnv.IsRunningOnDesktop) { return null; } var type = (Type) null; int ls = class_name.LastIndexOf ('/'); var package = ls >= 0 ? class_name.Substring (0, ls) : ""; List<Converter<string, Type>> mappers; if (packageLookup.TryGetValue (package, out mappers)) { foreach (Converter<string, Type> c in mappers) { type = c (class_name); if (type == null) continue; return type; } } if ((type = Type.GetType (JavaNativeTypeManager.ToCliType (class_name))) != null) { return type; } return null; } internal static IJavaObject CreateInstance (IntPtr handle, JniHandleOwnership transfer) { return CreateInstance (handle, transfer, null); } internal static IJavaObject CreateInstance (IntPtr handle, JniHandleOwnership transfer, Type targetType) { Type type = null; IntPtr class_ptr = JNIEnv.GetObjectClass (handle); string class_name = GetClassName (class_ptr); lock (jniToManaged) { while (class_ptr != IntPtr.Zero && !jniToManaged.TryGetValue (class_name, out type)) { type = GetJavaToManagedType (class_name); if (type != null) { jniToManaged.Add (class_name, type); break; } IntPtr super_class_ptr = JNIEnv.GetSuperclass (class_ptr); JNIEnv.DeleteLocalRef (class_ptr); class_ptr = super_class_ptr; class_name = GetClassName (class_ptr); } } JNIEnv.DeleteLocalRef (class_ptr); if (type == null) { JNIEnv.DeleteRef (handle, transfer); throw new NotSupportedException ( string.Format ("Internal error finding wrapper class for '{0}'. (Where is the Java.Lang.Object wrapper?!)", JNIEnv.GetClassNameFromInstance (handle)), CreateJavaLocationException ()); } if (targetType != null && !targetType.IsAssignableFrom (type)) type = targetType; if (type.IsInterface || type.IsAbstract) { var invokerType = JavaObjectExtensions.GetHelperType (type, "Invoker"); if (invokerType == null) throw new NotSupportedException ("Unable to find Invoker for type '" + type.FullName + "'. Was it linked away?", CreateJavaLocationException ()); type = invokerType; } IJavaObject result = null; try { result = (IJavaObject) CreateProxy (type, handle, transfer); var ex = result as IJavaObjectEx; if (Runtime.IsGCUserPeer (result) && ex != null) ex.IsProxy = true; } catch (MissingMethodException e) { var key_handle = JNIEnv.IdentityHash (handle); JNIEnv.DeleteRef (handle, transfer); throw new NotSupportedException ( string.Format ("Unable to activate instance of type {0} from native handle 0x{1} (key_handle 0x{2}).", type, handle.ToString ("x"), key_handle.ToString ("x")), e); } return result; } internal static object CreateProxy (Type type, IntPtr handle, JniHandleOwnership transfer) { // Skip Activator.CreateInstance() as that requires public constructors, // and we want to hide some constructors for sanity reasons. BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; ConstructorInfo c = type.GetConstructor (flags, null, new[]{typeof (IntPtr), typeof (JniHandleOwnership)}, null); if (c == null) { throw new MissingMethodException ( "No constructor found for " + type.FullName + "::.ctor(System.IntPtr, Android.Runtime.JniHandleOwnership)", CreateJavaLocationException ()); } return c.Invoke (new object[]{handle, transfer}); } public static void RegisterType (string java_class, Type t) { string jniFromType = JNIEnv.GetJniName (t); lock (jniToManaged) { Type lookup; if (!jniToManaged.TryGetValue (java_class, out lookup)) { jniToManaged.Add (java_class, t); if (jniFromType != java_class) { managedToJni.Add (t, java_class); } } else if (!JNIEnv.IsRunningOnDesktop || t != typeof (Java.Interop.TypeManager)) { // skip the registration and output a warning Logger.Log (LogLevel.Warn, "monodroid", string.Format ("Type Registration Skipped for {0} to {1} ", java_class, t.ToString())); } } } static Dictionary<string, List<Converter<string, Type>>> packageLookup = new Dictionary<string, List<Converter<string, Type>>> (); public static void RegisterPackage (string package, Converter<string, Type> lookup) { lock (packageLookup) { List<Converter<string, Type>> lookups; if (!packageLookup.TryGetValue (package, out lookups)) packageLookup.Add (package, lookups = new List<Converter<string, Type>> ()); lookups.Add (lookup); } } public static void RegisterPackages (string[] packages, Converter<string, Type>[] lookups) { if (packages == null) throw new ArgumentNullException ("packages"); if (lookups == null) throw new ArgumentNullException ("lookups"); if (packages.Length != lookups.Length) throw new ArgumentException ("`packages` and `lookups` arrays must have same number of elements."); lock (packageLookup) { for (int i = 0; i < packages.Length; ++i) { string package = packages [i]; Converter<string, Type> lookup = lookups [i]; List<Converter<string, Type>> _lookups; if (!packageLookup.TryGetValue (package, out _lookups)) packageLookup.Add (package, _lookups = new List<Converter<string, Type>> ()); _lookups.Add (lookup); } } } [Register ("mono/android/TypeManager", DoNotGenerateAcw = true)] internal class JavaTypeManager : Java.Lang.Object { [Register ("activate", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;[Ljava/lang/Object;)V", "")] static void n_Activate (IntPtr jnienv, IntPtr jclass, IntPtr typename_ptr, IntPtr signature_ptr, IntPtr jobject, IntPtr parameters_ptr) { TypeManager.n_Activate (jnienv, jclass, typename_ptr, signature_ptr, jobject, parameters_ptr); } internal static Delegate GetActivateHandler () { return TypeManager.GetActivateHandler (); } } } }
34.120419
147
0.681218
[ "MIT" ]
06051979/xamarin-android
src/Mono.Android/Java.Interop/TypeManager.cs
13,034
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.Generic; using System.Linq; using System.Text; using Internal.TypeSystem; using Xunit; namespace TypeSystemTests { public class InstanceFieldLayoutTests { TestTypeSystemContext _context; ModuleDesc _testModule; public InstanceFieldLayoutTests() { _context = new TestTypeSystemContext(TargetArchitecture.X64); var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly"); _context.SetSystemModule(systemModule); _testModule = systemModule; } [Fact] public void TestExplicitLayout() { MetadataType t = _testModule.GetType("Explicit", "Class1"); // With 64bit, there should be 8 bytes for the System.Object EE data pointer + // 10 bytes up until the offset of the char field + the char size of 2 + we // round up the whole instance size to the next pointer size (+4) = 24 Assert.Equal(24, t.InstanceByteCount); foreach (var field in t.GetFields()) { if (field.IsStatic) continue; if (field.Name == "Bar") { // Bar has explicit offset 4 and is in a class (with S.O size overhead of <pointer size>) // Therefore it should have offset 4 + 8 = 12 Assert.Equal(12, field.Offset); } else if (field.Name == "Baz") { // Baz has explicit offset 10. 10 + 8 = 18 Assert.Equal(18, field.Offset); } else { Assert.True(false); } } } [Fact] public void TestExplicitLayoutThatIsEmpty() { var explicitEmptyClassType = _testModule.GetType("Explicit", "ExplicitEmptyClass"); // ExplicitEmpty class has 8 from System.Object overhead = 8 Assert.Equal(8, explicitEmptyClassType.InstanceByteCount); var explicitEmptyStructType = _testModule.GetType("Explicit", "ExplicitEmptyStruct"); // ExplicitEmpty class has 0 bytes in it... so instance field size gets pushed up to 1. Assert.Equal(1, explicitEmptyStructType.InstanceFieldSize); } [Fact] public void TestExplicitTypeLayoutWithSize() { var explicitSizeType = _testModule.GetType("Explicit", "ExplicitSize"); Assert.Equal(48, explicitSizeType.InstanceByteCount); } [Fact] public void TestExplicitTypeLayoutWithInheritance() { MetadataType class2Type = _testModule.GetType("Explicit", "Class2"); // Class1 has size 24 which Class2 inherits from. Class2 adds a byte at offset 20, so + 21 // = 45, rounding up to the next pointer size = 48 Assert.Equal(48, class2Type.InstanceByteCount); foreach (var f in class2Type.GetFields()) { if (f.IsStatic) continue; if (f.Name == "Lol") { // First field after base class, with offset 0 so it should lie on the byte count of // the base class = 24 Assert.Equal(24, f.Offset); } else if (f.Name == "Omg") { // Offset 20 from base class byte count = 44 Assert.Equal(44, f.Offset); } else { Assert.True(false); } } } [Fact] public void TestSequentialTypeLayout() { MetadataType class1Type = _testModule.GetType("Sequential", "Class1"); // Byte count // Base Class 8 // MyInt 4 // MyBool 1 + 1 padding // MyChar 2 // MyString 8 // MyByteArray 8 // MyClass1SelfRef 8 // ------------------- // 40 Assert.Equal(0x28, class1Type.InstanceByteCount); foreach (var f in class1Type.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "MyInt": Assert.Equal(0x8, f.Offset); break; case "MyBool": Assert.Equal(0xC, f.Offset); break; case "MyChar": Assert.Equal(0xE, f.Offset); break; case "MyString": Assert.Equal(0x10, f.Offset); break; case "MyByteArray": Assert.Equal(0x18, f.Offset); break; case "MyClass1SelfRef": Assert.Equal(0x20, f.Offset); break; default: Assert.True(false); break; } } } [Fact] public void TestSequentialTypeLayoutInheritance() { MetadataType class2Type = _testModule.GetType("Sequential", "Class2"); // Byte count // Base Class 40 // MyInt2 4 + 4 byte padding to make class size % pointer size == 0 // ------------------- // 44 Assert.Equal(0x30, class2Type.InstanceByteCount); foreach (var f in class2Type.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "MyInt2": Assert.Equal(0x28, f.Offset); break; default: Assert.True(false); break; } } } [Fact] public void TestSequentialTypeLayoutStruct() { MetadataType struct0Type = _testModule.GetType("Sequential", "Struct0"); // Byte count // bool b1 1 // bool b2 1 // bool b3 1 + 1 padding for int alignment // int i1 4 // string s1 8 // ------------------- // 16 (0x10) Assert.Equal(0x10, struct0Type.InstanceByteCount); foreach (var f in struct0Type.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "b1": Assert.Equal(0x0, f.Offset); break; case "b2": Assert.Equal(0x1, f.Offset); break; case "b3": Assert.Equal(0x2, f.Offset); break; case "i1": Assert.Equal(0x4, f.Offset); break; case "s1": Assert.Equal(0x8, f.Offset); break; default: Assert.True(false); break; } } } [Fact] // Test that when a struct is used as a field, we use its instance byte size as the size (ie, treat it // as a value type) and not a pointer size. public void TestSequentialTypeLayoutStructEmbedded() { MetadataType struct1Type = _testModule.GetType("Sequential", "Struct1"); // Byte count // struct MyStruct0 16 // bool MyBool 1 // ----------------------- // 24 (0x18) Assert.Equal(0x18, struct1Type.InstanceByteCount); foreach (var f in struct1Type.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "MyStruct0": Assert.Equal(0x0, f.Offset); break; case "MyBool": Assert.Equal(0x10, f.Offset); break; default: Assert.True(false); break; } } } [Fact] public void TestTypeContainsPointers() { MetadataType type = _testModule.GetType("ContainsPointers", "NoPointers"); Assert.False(type.ContainsPointers); type = _testModule.GetType("ContainsPointers", "StillNoPointers"); Assert.False(type.ContainsPointers); type = _testModule.GetType("ContainsPointers", "ClassNoPointers"); Assert.False(type.ContainsPointers); type = _testModule.GetType("ContainsPointers", "HasPointers"); Assert.True(type.ContainsPointers); type = _testModule.GetType("ContainsPointers", "FieldHasPointers"); Assert.True(type.ContainsPointers); type = _testModule.GetType("ContainsPointers", "ClassHasPointers"); Assert.True(type.ContainsPointers); type = _testModule.GetType("ContainsPointers", "BaseClassHasPointers"); Assert.True(type.ContainsPointers); type = _testModule.GetType("ContainsPointers", "ClassHasIntArray"); Assert.True(type.ContainsPointers); type = _testModule.GetType("ContainsPointers", "ClassHasArrayOfClassType"); Assert.True(type.ContainsPointers); } } }
33.943894
110
0.460963
[ "MIT" ]
ZZHGit/corert
src/ILCompiler.TypeSystem/tests/InstanceFieldLayoutTests.cs
10,287
C#
using System; using Content.Shared.GameObjects.Components.Power; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Client.GameObjects.Components.Animations; using Robust.Client.Interfaces.GameObjects.Components; using Robust.Shared.Interfaces.GameObjects; using YamlDotNet.RepresentationModel; namespace Content.Client.GameObjects.Components.Power { public class AutolatheVisualizer : AppearanceVisualizer { private const string AnimationKey = "autolathe_animation"; private Animation _buildingAnimation; private Animation _insertingMetalAnimation; private Animation _insertingGlassAnimation; private Animation _insertingGoldAnimation; private Animation _insertingPhoronAnimation; public override void LoadData(YamlMappingNode node) { base.LoadData(node); _buildingAnimation = PopulateAnimation("autolathe_building", "autolathe_building_unlit", 0.5f); _insertingMetalAnimation = PopulateAnimation("autolathe_inserting_metal_plate", "autolathe_inserting_unlit", 0.9f); _insertingGlassAnimation = PopulateAnimation("autolathe_inserting_glass_plate", "autolathe_inserting_unlit", 0.9f); _insertingGoldAnimation = PopulateAnimation("autolathe_inserting_gold_plate", "autolathe_inserting_unlit", 0.9f); _insertingPhoronAnimation = PopulateAnimation("autolathe_inserting_phoron_sheet", "autolathe_inserting_unlit", 0.9f); } private Animation PopulateAnimation(string sprite, string spriteUnlit, float length) { var animation = new Animation {Length = TimeSpan.FromSeconds(length)}; var flick = new AnimationTrackSpriteFlick(); animation.AnimationTracks.Add(flick); flick.LayerKey = AutolatheVisualLayers.Base; flick.KeyFrames.Add(new AnimationTrackSpriteFlick.KeyFrame(sprite, 0f)); var flickUnlit = new AnimationTrackSpriteFlick(); animation.AnimationTracks.Add(flickUnlit); flickUnlit.LayerKey = AutolatheVisualLayers.BaseUnlit; flickUnlit.KeyFrames.Add(new AnimationTrackSpriteFlick.KeyFrame(spriteUnlit, 0f)); return animation; } public override void InitializeEntity(IEntity entity) { if (!entity.HasComponent<AnimationPlayerComponent>()) { entity.AddComponent<AnimationPlayerComponent>(); } } public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); var sprite = component.Owner.GetComponent<ISpriteComponent>(); var animPlayer = component.Owner.GetComponent<AnimationPlayerComponent>(); if (!component.TryGetData(PowerDeviceVisuals.VisualState, out LatheVisualState state)) { state = LatheVisualState.Idle; } switch (state) { case LatheVisualState.Idle: if (animPlayer.HasRunningAnimation(AnimationKey)) { animPlayer.Stop(AnimationKey); } sprite.LayerSetState(AutolatheVisualLayers.Base, "autolathe"); sprite.LayerSetState(AutolatheVisualLayers.BaseUnlit, "autolathe_unlit"); break; case LatheVisualState.Producing: if (!animPlayer.HasRunningAnimation(AnimationKey)) { animPlayer.Play(_buildingAnimation, AnimationKey); } break; case LatheVisualState.InsertingMetal: if (!animPlayer.HasRunningAnimation(AnimationKey)) { animPlayer.Play(_insertingMetalAnimation, AnimationKey); } break; case LatheVisualState.InsertingGlass: if (!animPlayer.HasRunningAnimation(AnimationKey)) { animPlayer.Play(_insertingGlassAnimation, AnimationKey); } break; case LatheVisualState.InsertingGold: if (!animPlayer.HasRunningAnimation(AnimationKey)) { animPlayer.Play(_insertingGoldAnimation, AnimationKey); } break; case LatheVisualState.InsertingPhoron: if (!animPlayer.HasRunningAnimation(AnimationKey)) { animPlayer.Play(_insertingPhoronAnimation, AnimationKey); } break; default: throw new ArgumentOutOfRangeException(); } var glowingPartsVisible = !(component.TryGetData(PowerDeviceVisuals.Powered, out bool powered) && !powered); sprite.LayerSetVisible(AutolatheVisualLayers.BaseUnlit, glowingPartsVisible); } public enum AutolatheVisualLayers : byte { Base, BaseUnlit } } }
42.25
129
0.614239
[ "MIT" ]
dave12311/space-station-14
Content.Client/GameObjects/Components/Power/AutolatheVisualizer.cs
5,241
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Compute.V20191201.Outputs { /// <summary> /// Describes the gallery Image Definition purchase plan. This is used by marketplace images. /// </summary> [OutputType] public sealed class ImagePurchasePlanResponse { /// <summary> /// The plan ID. /// </summary> public readonly string? Name; /// <summary> /// The product ID. /// </summary> public readonly string? Product; /// <summary> /// The publisher ID. /// </summary> public readonly string? Publisher; [OutputConstructor] private ImagePurchasePlanResponse( string? name, string? product, string? publisher) { Name = name; Product = product; Publisher = publisher; } } }
25.73913
97
0.590372
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Compute/V20191201/Outputs/ImagePurchasePlanResponse.cs
1,184
C#
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Website: https://www.blazor.zone or https://argozhang.github.io/ using Microsoft.AspNetCore.Components; using System.Linq.Expressions; using System.Reflection; namespace BootstrapBlazor.Components; /// <summary> /// /// </summary> public partial class TableFooterCell { private string? ClassString => CssBuilder.Default("table-cell") .AddClass("justify-content-start", Align == Alignment.Left) .AddClass("justify-content-center", Align == Alignment.Center) .AddClass("justify-content-end", Align == Alignment.Right) .AddClassFromAttributes(AdditionalAttributes) .Build(); /// <summary> /// 获得/设置 单元格内容 /// </summary> [Parameter] public string? Text { get; set; } /// <summary> /// 获得/设置 文字对齐方式 默认为 Alignment.None /// </summary> [Parameter] public Alignment Align { get; set; } /// <summary> /// 获得/设置 聚合方法枚举 默认 Sum /// </summary> [Parameter] public AggregateType Aggregate { get; set; } /// <summary> /// 获得/设置 自定义统计列回调方法 /// </summary> [Parameter] public Func<object?, string?, string>? CustomerAggregateCallback { get; set; } /// <summary> /// 获得/设置 统计列名称 默认为 null 不参与统计仅作为显示单元格 /// </summary> [Parameter] public string? Field { get; set; } /// <summary> /// 获得/设置 是否为移动端模式 /// </summary> [CascadingParameter(Name = "IsMobileMode")] private bool IsMobileMode { get; set; } /// <summary> /// 获得/设置 是否为移动端模式 /// </summary> [CascadingParameter(Name = "TableFooterContext")] private object? DataSource { get; set; } private string? GetText() => Text ?? (GetCount(DataSource) == 0 ? "0" : (GetCountValue() ?? GetAggegateValue())); /// <summary> /// 解析 Count Aggregate /// </summary> /// <returns></returns> private string? GetCountValue() { string? v = null; if (Aggregate == AggregateType.Count && DataSource != null) { // 绑定数据源类型 var type = DataSource.GetType(); // 数据源泛型 TModel 类型 var modelType = type.GenericTypeArguments[0]; var mi = GetType().GetMethod(nameof(CreateCountMethod), BindingFlags.NonPublic | BindingFlags.Static)!.MakeGenericMethod(modelType); if (mi != null) { var obj = mi.Invoke(null, new object[] { DataSource }); if (obj != null) { v = obj.ToString(); } } } return v; } private string? GetAggegateValue() { return Aggregate == AggregateType.Customer ? AggregateCustomerValue() : AggregateNumberValue(); string? AggregateCustomerValue() { string? v = null; if (CustomerAggregateCallback != null) { v = CustomerAggregateCallback(DataSource, Field); } return v; } string? AggregateNumberValue() { string? v = null; if (!string.IsNullOrEmpty(Field) && DataSource != null) { // 绑定数据源类型 var type = DataSource.GetType(); // 数据源泛型 TModel 类型 var modelType = type.GenericTypeArguments[0]; // 通过 Field 获取到 TModel 属性 var propertyInfo = modelType.GetProperty(Field); if (propertyInfo != null) { // @context.Sum(i => i.Count) // Count 属性类型 var propertyType = propertyInfo.PropertyType; // 构建 Aggegate // @context.Sum(i => i.Count) var aggegateMethod = Aggregate switch { AggregateType.Average => propertyType.Name switch { nameof(Int32) or nameof(Int64) or nameof(Double) => GetType() .GetMethod(nameof(CreateAggregateLambda), BindingFlags.NonPublic | BindingFlags.Static)! .MakeGenericMethod(typeof(Double)), _ => GetType() .GetMethod(nameof(CreateAggregateLambda), BindingFlags.NonPublic | BindingFlags.Static)! .MakeGenericMethod(propertyType), }, _ => GetType().GetMethod(nameof(CreateAggregateLambda), BindingFlags.NonPublic | BindingFlags.Static)! .MakeGenericMethod(propertyType) }; if (aggegateMethod != null) { v = AggregateMethodInvoker(aggegateMethod, type, modelType, propertyType); } } } return v; } string? AggregateMethodInvoker(MethodInfo aggegateMethod, Type type, Type modelType, Type propertyType) { string? v = null; var invoker = aggegateMethod.Invoke(null, new object[] { Aggregate, type, modelType, propertyType }); if (invoker != null) { // 构建 Selector var methodInfo = GetType().GetMethod(nameof(CreateSelector), BindingFlags.NonPublic | BindingFlags.Static)! .MakeGenericMethod(modelType, propertyType); if (methodInfo != null) { var selector = methodInfo.Invoke(null, new object[] { Field }); if (selector != null) { // 执行委托 if (invoker is Delegate d) { var val = d.DynamicInvoke(DataSource, selector); if (val != null) { v = val.ToString(); } } } } } return v; } } /// <summary> /// 通过属性名称构建委托 /// </summary> /// <typeparam name="TModel"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="field"></param> /// <returns></returns> private static Func<TModel, TValue> CreateSelector<TModel, TValue>(string field) { var type = typeof(TModel); var p1 = Expression.Parameter(type); var propertyInfo = type.GetProperty(field); var fieldExpression = Expression.Property(p1, propertyInfo!); return Expression.Lambda<Func<TModel, TValue>>(fieldExpression, p1).Compile(); } private static Func<object, object, TValue?> CreateAggregateLambda<TValue>(AggregateType aggregate, Type type, Type modelType, Type propertyType) { Func<object, object, TValue?> ret = (_, _) => default; // 获得 Enumerable.Sum 方法 var mi = GetMethodInfoByAggregate(aggregate, modelType, propertyType); if (mi != null) { var p1 = Expression.Parameter(typeof(object)); var p2 = Expression.Parameter(typeof(object)); var body = Expression.Call(mi, Expression.Convert(p1, type), Expression.Convert(p2, typeof(Func<,>).MakeGenericType(new Type[] { modelType, propertyType }))); ret = Expression.Lambda<Func<object, object, TValue?>>(body, p1, p2).Compile(); } return ret; } private static MethodInfo? GetMethodInfoByAggregate(AggregateType aggregate, Type modelType, Type propertyType) { var mi = aggregate switch { AggregateType.Average => propertyType.Name switch { nameof(Int32) => typeof(Enumerable).GetMethods() .FirstOrDefault(m => m.Name == aggregate.ToString() && m.IsGenericMethod && m.ReturnType == typeof(Double) && m.GetParameters().Length == 2 && m.GetParameters()[1].ParameterType.GenericTypeArguments[1] == typeof(Int32)), nameof(Int64) => typeof(Enumerable).GetMethods() .FirstOrDefault(m => m.Name == aggregate.ToString() && m.IsGenericMethod && m.ReturnType == typeof(Double) && m.GetParameters().Length == 2 && m.GetParameters()[1].ParameterType.GenericTypeArguments[1] == typeof(Int64)), nameof(Double) => typeof(Enumerable).GetMethods() .FirstOrDefault(m => m.Name == aggregate.ToString() && m.IsGenericMethod && m.ReturnType == typeof(Double) && m.GetParameters().Length == 2 && m.GetParameters()[1].ParameterType.GenericTypeArguments[1] == typeof(Double)), nameof(Decimal) => typeof(Enumerable).GetMethods() .FirstOrDefault(m => m.Name == aggregate.ToString() && m.IsGenericMethod && m.ReturnType == typeof(Decimal) && m.GetParameters().Length == 2 && m.GetParameters()[1].ParameterType.GenericTypeArguments[1] == typeof(Decimal)), nameof(Single) => typeof(Enumerable).GetMethods() .FirstOrDefault(m => m.Name == aggregate.ToString() && m.IsGenericMethod && m.ReturnType == typeof(Single) && m.GetParameters().Length == 2 && m.GetParameters()[1].ParameterType.GenericTypeArguments[1] == typeof(Single)), _ => null }, _ => typeof(Enumerable).GetMethods() .FirstOrDefault(m => m.Name == aggregate.ToString() && m.IsGenericMethod && m.ReturnType == propertyType) }; return mi?.MakeGenericMethod(modelType); } private static int CreateCountMethod<TSource>(IEnumerable<TSource> source) => source.Count(); private static int GetCount(object? source) { var ret = 0; if (source != null) { // 绑定数据源类型 var type = source.GetType(); // 数据源泛型 TModel 类型 var modelType = type.GenericTypeArguments[0]; var mi = typeof(TableFooterCell).GetMethod(nameof(CreateCountMethod), BindingFlags.NonPublic | BindingFlags.Static)!.MakeGenericMethod(modelType); if (mi != null) { var obj = mi.Invoke(null, new object[] { source }); if (obj != null) { var v = obj.ToString(); _ = int.TryParse(v, out ret); } } } return ret; } }
39.079422
158
0.530624
[ "Apache-2.0" ]
First-Coder/BootstrapBlazor
src/BootstrapBlazor/Components/Table/TableFooterCell.razor.cs
11,175
C#
using System.Collections.Generic; using System.Linq; using JetBrains.Space.Generator.Model.HttpApi; using JetBrains.Space.Generator.CodeGeneration.CSharp.Extensions; namespace JetBrains.Space.Generator.CodeGeneration.CSharp { public class MethodParametersBuilder { private class MethodParameter { public string Type { get; } public string Name { get; } public string? DefaultValue { get; } public MethodParameter(string type, string name, string? defaultValue) { Type = type; Name = name; DefaultValue = defaultValue; } } private readonly CodeGenerationContext _context; private readonly List<MethodParameter> _parameters; public MethodParametersBuilder(CodeGenerationContext context) : this(context, new List<MethodParameter>()) { } private MethodParametersBuilder(CodeGenerationContext context, List<MethodParameter> parameters) { _context = context; _parameters = parameters; } public MethodParametersBuilder WithParametersForApiDtoFields(IEnumerable<ApiDtoField> apiDtoFields) => WithParametersForApiFields(apiDtoFields.Select(it => it.Field)); public MethodParametersBuilder WithParametersForApiFields(IEnumerable<ApiField> apiFields) { var methodParametersBuilder = this; var orderedFields = apiFields.OrderBy(it => !it.Type.Nullable ? 0 : 1).ToList(); foreach (var field in orderedFields) { var parameterType = field.Type.ToCSharpType(_context); if (field.Type.Nullable) { parameterType += "?"; } if (!field.Type.Nullable) { if (field.IsPrimitiveAndRequiresAddedNullability()) { parameterType += "?"; } if (field.DefaultValue is ApiDefaultValue.Collection || field.DefaultValue is ApiDefaultValue.Map) { parameterType += "?"; } } var parameterName = field.ToCSharpVariableName(); var parameterDefaultValue = field.ToCSharpDefaultValueForParameterList(_context); methodParametersBuilder = methodParametersBuilder .WithParameter(parameterType, parameterName, parameterDefaultValue); } return methodParametersBuilder; } public MethodParametersBuilder WithParametersForApiParameters(IEnumerable<ApiParameter> apiParameters) { var methodParametersBuilder = this; var orderedParameters = apiParameters.OrderBy(it => !it.Field.Type.Nullable ? 0 : 1).ToList(); foreach (var parameter in orderedParameters) { var parameterType = parameter.Field.Type.ToCSharpType(_context); if (parameter.Field.Type.Nullable) { parameterType += "?"; } if (!parameter.Field.Type.Nullable) { if (parameter.Field.IsPrimitiveAndRequiresAddedNullability()) { parameterType += "?"; } if (parameter.Field.DefaultValue is ApiDefaultValue.Collection || parameter.Field.DefaultValue is ApiDefaultValue.Map) { parameterType += "?"; } } var parameterName = parameter.Field.ToCSharpVariableName(); var parameterDefaultValue = parameter.Field.ToCSharpDefaultValueForParameterList(_context); methodParametersBuilder = methodParametersBuilder .WithParameter(parameterType, parameterName, parameterDefaultValue); } return methodParametersBuilder; } public MethodParametersBuilder WithParameter(string type, string name, string? defaultValue = null) { var futureParameters = new List<MethodParameter>(_parameters); futureParameters.Add(new MethodParameter(type, name, defaultValue)); return new MethodParametersBuilder(_context, futureParameters); } public MethodParametersBuilder WithDefaultValueForAllParameters(string? defaultValue) { var futureParameters = new List<MethodParameter>(); foreach (var futureParameter in _parameters) { futureParameters.Add(new MethodParameter(futureParameter.Type, futureParameter.Name, defaultValue)); } return new MethodParametersBuilder(_context, futureParameters); } public MethodParametersBuilder WithDefaultValueForParameter(string name, string? defaultValue = null) { var futureParameters = new List<MethodParameter>(); foreach (var futureParameter in _parameters) { if (futureParameter.Name == name) { futureParameters.Add(new MethodParameter(futureParameter.Type, futureParameter.Name, defaultValue)); } else { futureParameters.Add(futureParameter); } } return new MethodParametersBuilder(_context, futureParameters); } public string BuildMethodParametersList() => string.Join(", ", _parameters .OrderBy(RequiredParametersFirstOrder) .Select(it => { var parameterDefinition = it.Type + " " + it.Name; if (!string.IsNullOrEmpty(it.DefaultValue)) { parameterDefinition += " = " + it.DefaultValue; } return parameterDefinition; })); public string BuildMethodCallParameters() => string.Join(", ", _parameters .OrderBy(RequiredParametersFirstOrder) .Select(it => { var parameterDefinition = it.Name; if (!string.IsNullOrEmpty(it.DefaultValue)) { parameterDefinition += ": " + it.DefaultValue; } else { parameterDefinition += ": " + parameterDefinition; } return parameterDefinition; })); private int RequiredParametersFirstOrder(MethodParameter it) => string.IsNullOrEmpty(it.DefaultValue) ? 0 : 1; } }
39.385475
120
0.549362
[ "Apache-2.0" ]
PatrickRatzow/space-dotnet-sdk
src/JetBrains.Space.Generator/CodeGeneration/CSharp/MethodParametersBuilder.cs
7,050
C#