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 UnityEngine; namespace ToolBox.Behaviours.Conditions { public class CompareWithValue<T, C> : SharedDataComparer<T, C> where C : ContextKey { [SerializeField] private T value = default; public override void OnEnter() => Invoke(equalityComparer.Equals(sharedDataToCompare.Value, value)); public override void OnExit() { } } }
23.066667
84
0.742775
[ "MIT" ]
IntoTheDev/Behaviour-System-for-Unity
Conditions/Shared Data/Comparers/CompareWithValue.cs
348
C#
namespace remu { partial class MainForm { /// <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.flpRamPanel = new System.Windows.Forms.FlowLayoutPanel(); this.flpROM = new System.Windows.Forms.FlowLayoutPanel(); this.flpConst = new System.Windows.Forms.FlowLayoutPanel(); this.SuspendLayout(); // // flpRamPanel // this.flpRamPanel.FlowDirection = System.Windows.Forms.FlowDirection.TopDown; this.flpRamPanel.Location = new System.Drawing.Point(0, 0); this.flpRamPanel.Name = "flpRamPanel"; this.flpRamPanel.Size = new System.Drawing.Size(361, 250); this.flpRamPanel.TabIndex = 0; // // flpROM // this.flpROM.Location = new System.Drawing.Point(361, 0); this.flpROM.Name = "flpROM"; this.flpROM.Size = new System.Drawing.Size(491, 473); this.flpROM.TabIndex = 1; // // flpConst // this.flpConst.FlowDirection = System.Windows.Forms.FlowDirection.TopDown; this.flpConst.Location = new System.Drawing.Point(0, 250); this.flpConst.Name = "flpConst"; this.flpConst.Size = new System.Drawing.Size(361, 299); this.flpConst.TabIndex = 2; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(864, 552); this.Controls.Add(this.flpConst); this.Controls.Add(this.flpROM); this.Controls.Add(this.flpRamPanel); this.DoubleBuffered = true; this.Name = "MainForm"; this.Text = "R200"; this.Load += new System.EventHandler(this.MainForm_Load); this.ResumeLayout(false); } #endregion private System.Windows.Forms.FlowLayoutPanel flpRamPanel; private System.Windows.Forms.FlowLayoutPanel flpROM; private System.Windows.Forms.FlowLayoutPanel flpConst; } }
37.506173
107
0.567479
[ "MIT" ]
atsidaev/R200
R200 emulator/src/UI/MainForm.Designer.cs
3,040
C#
using BizHawk.Emulation.Common; namespace BizHawk.Client.Common { public class AndAdapter : IController { public ControllerDefinition Definition => Source.Definition; public bool IsPressed(string button) { if (Source != null && SourceAnd != null) { return Source.IsPressed(button) & SourceAnd.IsPressed(button); } return false; } // pass floats solely from the original source // this works in the code because SourceOr is the autofire controller public float GetFloat(string name) { return Source.GetFloat(name); } internal IController Source { get; set; } internal IController SourceAnd { get; set; } } public class ORAdapter : IController { public ControllerDefinition Definition => Source.Definition; public bool IsPressed(string button) { return (Source?.IsPressed(button) ?? false) | (SourceOr?.IsPressed(button) ?? false); } // pass floats solely from the original source // this works in the code because SourceOr is the autofire controller public float GetFloat(string name) { return Source.GetFloat(name); } internal IController Source { get; set; } internal IController SourceOr { get; set; } } }
24.470588
72
0.682692
[ "MIT" ]
GyroscopeHQ/BizHawk
BizHawk.Client.Common/inputAdapters/BitwiseAdapters.cs
1,250
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(4983)] [Attributes(9)] public class Wcdma1800TxCompVsFreq3Secondary { [ElementsCount(16)] [ElementType("int8")] [Description("")] public sbyte[] Value { get; set; } } }
20.238095
49
0.611765
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/Wcdma1800TxCompVsFreq3SecondaryI.cs
425
C#
namespace BFF.DataVirtualizingCollection.Sample.Model.Models { public interface ILowWorkloadObject : ISomeWorkloadObject { } internal class LowWorkloadObject : SomeWorkloadObject, ILowWorkloadObject { public LowWorkloadObject(int number) : base(number) { } } }
23.769231
77
0.695793
[ "Unlicense" ]
Yeah69/BFF.DataVirtualizingCollection
Sample.Model/Models/LowWorkloadObject.cs
309
C#
//////////////////////////////////////////////////////////////////////////////// // // CopyRight (c) 2018 Kyungkun Ko // // Author : KyungKun Ko // // Description : Tong script Missing script node // //////////////////////////////////////////////////////////////////////////////// using Sce.Atf; using Sce.Atf.Controls.Adaptable.Graphs; namespace SF.Tong { public class MissingScriptNode : ScriptNode { protected override void OnNodeSet() { base.OnNodeSet(); m_missingElementType = new MissingElementType(MissingTypeName); m_missingElementType.Image = ResourceUtil.GetImage(Sce.Atf.Resources.PackageErrorImage); } /// <summary> /// Gets ICircuitElementType type</summary> public override ICircuitElementType ElementType { get { return m_missingElementType; } } public static string MissingTypeName = "?Missing?"; private MissingElementType m_missingElementType; } }
28.378378
101
0.524762
[ "Apache-2.0" ]
blue3k/StormForge
Tools/Src/LibSharp/Tong.bak/MissingScriptNode.cs
1,052
C#
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace SysHv.Server.DAL.Migrations { public partial class AddClientSensor : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "ClientSensors", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), ClientId = table.Column<int>(nullable: false), SensorId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ClientSensors", x => x.Id); table.ForeignKey( name: "FK_ClientSensors_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_ClientSensors_Sensors_SensorId", column: x => x.SensorId, principalTable: "Sensors", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_ClientSensors_ClientId", table: "ClientSensors", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_ClientSensors_SensorId", table: "ClientSensors", column: "SensorId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "ClientSensors"); } } }
39.107143
122
0.518265
[ "MIT" ]
andrew-kulikov/sys-hv
SysHv/SysHv.Server.DAL/Migrations/20190428071130_AddClientSensor.cs
2,192
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.OperationalInsights.V20200301Preview.Outputs { /// <summary> /// The cluster sku definition. /// </summary> [OutputType] public sealed class ClusterSkuResponse { /// <summary> /// The capacity value /// </summary> public readonly double? Capacity; /// <summary> /// The name of the SKU. /// </summary> public readonly string? Name; [OutputConstructor] private ClusterSkuResponse( double? capacity, string? name) { Capacity = capacity; Name = name; } } }
24.538462
81
0.601881
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/OperationalInsights/V20200301Preview/Outputs/ClusterSkuResponse.cs
957
C#
/* Copyright 2010-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MongoDB.Driver { /// <summary> /// The result of a delete operation. /// </summary> public abstract class DeleteResult { // static internal static DeleteResult FromCore(BulkWriteResult result) { if (result.IsAcknowledged) { return new Acknowledged(result.DeletedCount); } return Unacknowledged.Instance; } // properties /// <summary> /// Gets the deleted count. If IsAcknowledged is false, this will throw an exception. /// </summary> public abstract long DeletedCount { get; } /// <summary> /// Gets a value indicating whether the result is acknowledged. /// </summary> public abstract bool IsAcknowledged { get; } // constructors /// <summary> /// Initializes a new instance of the <see cref="DeleteResult"/> class. /// </summary> protected DeleteResult() { } // nested classes /// <summary> /// The result of an acknowledged delete operation. /// </summary> public class Acknowledged : DeleteResult { private readonly long _deletedCount; /// <summary> /// Initializes a new instance of the class. /// </summary> /// <param name="deletedCount">The deleted count.</param> public Acknowledged(long deletedCount) { _deletedCount = deletedCount; } /// <inheritdoc/> public override long DeletedCount { get { return _deletedCount; } } /// <inheritdoc/> public override bool IsAcknowledged { get { return true; } } } /// <summary> /// The result of an unacknowledged delete operation. /// </summary> public class Unacknowledged : DeleteResult { private static Unacknowledged __instance = new Unacknowledged(); /// <summary> /// Gets the instance. /// </summary> public static Unacknowledged Instance { get { return __instance; } } private Unacknowledged() { } /// <inheritdoc/> public override long DeletedCount { get { throw new NotSupportedException("Only acknowledged writes support the DeletedCount property."); } } /// <inheritdoc/> public override bool IsAcknowledged { get { return false; } } } } }
28.775
119
0.552853
[ "MIT" ]
DBestBean/ETandGF
Server/ThirdParty/MongodbDriver/MongoDB.Driver/DeleteResult.cs
3,453
C#
using BlazorFluentUI.Style; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using Microsoft.JSInterop; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlazorFluentUI.Lists { public partial class DetailsHeader<TItem> : FluentUIComponentBase, IAsyncDisposable { //[CascadingParameter] //private SelectionZone<TItem> SelectionZone { get; set; } [Parameter] public string? AriaLabelForSelectAllCheckbox { get; set; } [Parameter] public string? AriaLabelForSelectionColumn { get; set; } [Parameter] public string? AriaLabelForToggleAllGroup { get; set; } [Parameter] public CheckboxVisibility CheckboxVisibility { get; set; } [Parameter] public CollapseAllVisibility CollapseAllVisibility { get; set; } [Parameter] public RenderFragment<object>? ColumnHeaderTooltipTemplate { get; set; } [Parameter] public object? ColumnReorderOptions { get; set; } [Parameter] public object? ColumnReorderProps { get; set; } [Parameter] public IEnumerable<DetailsRowColumn<TItem>>? Columns { get; set; } [Parameter] public RenderFragment? DetailsCheckboxTemplate { get; set; } [Parameter] public int GroupNestingDepth { get; set; } [Parameter] public bool IsAllCollapsed { get; set; } [Parameter] public double IndentWidth { get; set; } [Parameter] public bool IsAllSelected { get; set; } [Parameter] public DetailsListLayoutMode LayoutMode { get; set; } [Parameter] public int MinimumPixelsForDrag { get; set; } [Parameter] public EventCallback<ItemContainer<DetailsRowColumn<TItem>>> OnColumnAutoResized { get; set; } [Parameter] public EventCallback<DetailsRowColumn<TItem>> OnColumnClick { get; set; } [Parameter] public EventCallback<DetailsRowColumn<TItem>> OnColumnContextMenu { get; set; } [Parameter] public EventCallback<object> OnColumnIsSizingChanged { get; set; } [Parameter] public EventCallback<ColumnResizedArgs<TItem>> OnColumnResized { get; set; } [Parameter] public EventCallback<bool> OnToggleCollapsedAll { get; set; } [Parameter] public SelectAllVisibility SelectAllVisibility { get; set; } = SelectAllVisibility.Visible; [Parameter] public Selection<TItem>? Selection { get; set; } [Parameter] public SelectionMode SelectionMode { get; set; } [Parameter] public string? TooltipHostClassName { get; set; } [Parameter] public bool UseFastIcons { get; set; } = true; [Inject] private IJSRuntime? JSRuntime { get; set; } private const string ScriptPath = "./_content/BlazorFluentUI.CoreComponents/detailsList.js"; private IJSObjectReference? scriptModule; private bool showCheckbox; private bool isCheckboxHidden; private bool isCheckboxAlwaysVisible; private int frozenColumnCountFromStart; //private int frozenColumnCountFromEnd; private string? id; //private object? dragDropHelper; private (int SourceIndex, int TargetIndex) onDropIndexInfo; //private int currentDropHintIndex; //private int draggedColumnIndex = -1; private bool isResizingColumn; const double MIN_COLUMN_WIDTH = 100; //state //private bool isAllSelected; //private bool isAllCollapsed; private bool isSizing; private int resizeColumnIndex; private double resizeColumnMinWidth; private double resizeColumnOriginX; private DotNetObjectReference<DetailsHeader<TItem>>? selfReference; //private ElementReference cellSizer; protected override Task OnInitializedAsync() { id = "G" + Guid.NewGuid().ToString(); onDropIndexInfo = (-1, -1); //currentDropHintIndex = -1; return base.OnInitializedAsync(); } protected override Task OnParametersSetAsync() { showCheckbox = SelectAllVisibility != SelectAllVisibility.None; isCheckboxHidden = SelectAllVisibility == SelectAllVisibility.Hidden; isCheckboxAlwaysVisible = CheckboxVisibility == CheckboxVisibility.Always; isResizingColumn = isSizing; // TBD if (ColumnReorderProps!= null && ColumnReorderProps.ToString() == "something") { frozenColumnCountFromStart = 1234; } else { frozenColumnCountFromStart = 0; } return base.OnParametersSetAsync(); } protected override async Task OnAfterRenderAsync(bool firstRender) { scriptModule = await JSRuntime!.InvokeAsync<IJSObjectReference>("import", ScriptPath); if (firstRender) { selfReference = DotNetObjectReference.Create(this); await scriptModule!.InvokeVoidAsync("registerDetailsHeader", selfReference, RootElementReference); } await base.OnAfterRenderAsync(firstRender); } [JSInvokable] public void OnSizerMouseDown(int columnIndex, double originX) { isSizing = true; resizeColumnIndex = columnIndex; //columnIndex - (showCheckbox ? 2 : 1); resizeColumnOriginX = originX; resizeColumnMinWidth = Columns!.ElementAt(resizeColumnIndex).CalculatedWidth; InvokeAsync(StateHasChanged); } [JSInvokable] public void OnDoubleClick(int columnIndex) { //System.Diagnostics.Debug.WriteLine("DoubleClick happened."); OnColumnAutoResized.InvokeAsync(new ItemContainer<DetailsRowColumn<TItem>> { Item = Columns!.ElementAt(columnIndex), Index = columnIndex }); } private void OnSelectAllClicked(MouseEventArgs mouseEventArgs) { if (!isCheckboxHidden) { Selection?.ToggleAllSelected(); } } private static void OnToggleCollapseAll(MouseEventArgs mouseEventArgs) { } //private void OnSizerMouseDown(MouseEventArgs args, int colIndex) //{ // isSizing = true; // resizeColumnIndex = colIndex - (showCheckbox ? 2 : 1); // resizeColumnOriginX = args.ClientX; // resizeColumnMinWidth = Columns.ElementAt(resizeColumnIndex).CalculatedWidth; //} private void OnSizerMouseMove(MouseEventArgs mouseEventArgs) { if (mouseEventArgs.ClientX != resizeColumnOriginX) { //OnColumnIsSizingChanged.InvokeAsync(); } if (OnColumnResized.HasDelegate) { double movement = mouseEventArgs.ClientX - resizeColumnOriginX; //skipping RTL check double calculatedWidth = resizeColumnMinWidth + movement; double currentColumnMinWidth = Columns!.ElementAt(resizeColumnIndex).MinWidth; double constrictedCalculatedWidth = Math.Max((currentColumnMinWidth < 0 || double.IsNaN(currentColumnMinWidth) ? MIN_COLUMN_WIDTH : currentColumnMinWidth), calculatedWidth); OnColumnResized.InvokeAsync(new ColumnResizedArgs<TItem>(Columns!.ElementAt(resizeColumnIndex), resizeColumnIndex, constrictedCalculatedWidth)); } } private void OnSizerMouseUp(MouseEventArgs mouseEventArgs) { isSizing = false; } private static void UpdateDragInfo(int itemIndex) { } public override async ValueTask DisposeAsync() { if (selfReference != null) { await scriptModule!.InvokeVoidAsync("unregisterDetailsHeader", selfReference); selfReference?.Dispose(); } if (scriptModule != null) await scriptModule.DisposeAsync(); } } }
33.143426
189
0.628802
[ "MIT" ]
ColonelBundy/BlazorFluentUI
src/BlazorFluentUI.ListComponents/DetailsList/DetailsHeader.razor.cs
8,321
C#
using System; using System.Collections.Generic; using System.Security.Claims; using System.Security.Principal; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication2 { public partial class SiteMaster : MasterPage { private const string AntiXsrfTokenKey = "__AntiXsrfToken"; private const string AntiXsrfUserNameKey = "__AntiXsrfUserName"; private string _antiXsrfTokenValue; protected void Page_Init(object sender, EventArgs e) { // Код ниже защищает от XSRF-атак var requestCookie = Request.Cookies[AntiXsrfTokenKey]; Guid requestCookieGuidValue; if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue)) { // Использование маркера Anti-XSRF из файла cookie _antiXsrfTokenValue = requestCookie.Value; Page.ViewStateUserKey = _antiXsrfTokenValue; } else { // Создание нового маркера Anti-XSRF и его сохранение в файле cookie _antiXsrfTokenValue = Guid.NewGuid().ToString("N"); Page.ViewStateUserKey = _antiXsrfTokenValue; var responseCookie = new HttpCookie(AntiXsrfTokenKey) { HttpOnly = true, Value = _antiXsrfTokenValue }; if (FormsAuthentication.RequireSSL && Request.IsSecureConnection) { responseCookie.Secure = true; } Response.Cookies.Set(responseCookie); } Page.PreLoad += master_Page_PreLoad; } protected void master_Page_PreLoad(object sender, EventArgs e) { if (!IsPostBack) { // Задание маркера Anti-XSRF ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey; ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty; } else { // Проверка маркера Anti-XSRF if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty)) { throw new InvalidOperationException("Ошибка проверки маркера Anti-XSRF."); } } } protected void Page_Load(object sender, EventArgs e) { } protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e) { Context.GetOwinContext().Authentication.SignOut(); } } }
34.7875
110
0.581028
[ "Apache-2.0" ]
MiracleSirius1/Projects
WebApplication2/WebApplication2/Site.Master.cs
2,924
C#
using System; using System.Globalization; using System.Windows.Data; namespace WpfMvvm.Converters { /// <summary>Базовый абстрактный класс для реализации ковертеров без обратного (от цели к источнику) преобразования.<para/> /// При обращении к методу <see cref="ConvertBack(object, Type, object, CultureInfo)"/> всегда выкидывается /// исключение <see cref="NotImplementedConvertBackException"/>.</summary> public abstract class WithoutConvertBackConverter : IValueConverter { /// <inheritdoc cref="IValueConverter.Convert(object, Type, object, CultureInfo)"/> public abstract object Convert(object value, Type targetType, object parameter, CultureInfo culture); /// <summary>Не реализован.</summary> /// <returns>Всегда исключение <see cref="NotImplementedConvertBackException"/>.</returns> /// <exception cref="NotImplementedException">Всегда <see cref="NotImplementedConvertBackException"/>.</exception> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw NotImplementedConvertBackException; /// <summary>Ошибка при обращении к методу <see cref="ConvertBack(object, Type, object, CultureInfo)"/>.</summary> public static NotImplementedException NotImplementedConvertBackException { get; } = new NotImplementedException($"Метод {nameof(ConvertBack)} не реализован."); } }
55.5
127
0.731809
[ "MIT" ]
WpfMvvm/WpfMvvm.Converters
WpfMvvm.Converters/WithoutConvertBackConverter.cs
1,656
C#
using BenchmarkDotNet.Attributes; using Microsoft.VisualBasic.Activities; using System.Activities; using System.Activities.Statements; using System.Activities.Validation; using System.Text; namespace CoreWf.Benchmarks; public class Expressions { private readonly Activity[] _vb100Stmts; private readonly Activity[] _vb400Stmts; private readonly Activity[] _vbSingleExpr100; private int _activityIndex; public Expressions() { _vb100Stmts = new Activity[] { GenerateManyExpressionsWorkflow(0, 100), GenerateManyExpressionsWorkflow(100, 100), GenerateManyExpressionsWorkflow(200, 100), GenerateManyExpressionsWorkflow(300, 100), GenerateManyExpressionsWorkflow(400, 100), GenerateManyExpressionsWorkflow(500, 100), GenerateManyExpressionsWorkflow(600, 100), GenerateManyExpressionsWorkflow(700, 100), GenerateManyExpressionsWorkflow(800, 100), GenerateManyExpressionsWorkflow(900, 100), }; _vb400Stmts = new Activity[] { GenerateManyExpressionsWorkflow(0, 400), GenerateManyExpressionsWorkflow(400, 400), GenerateManyExpressionsWorkflow(800, 400), }; _vbSingleExpr100 = GenerateManySingleExpressionWorkflows(500, 100); _activityIndex = 0; } [Benchmark] public void VB100Stmts() { var activity = _vb100Stmts[_activityIndex]; _activityIndex = (_activityIndex + 1) % _vb100Stmts.Length; _ = ActivityValidationServices.Validate(activity); } [Benchmark] public void VB400Stmts() { var activity = _vb400Stmts[_activityIndex]; _activityIndex = (_activityIndex + 1) % _vb400Stmts.Length; _ = ActivityValidationServices.Validate(activity); } [Benchmark] public void VBSingleExpr100() { var activity = _vbSingleExpr100[_activityIndex]; _activityIndex = (_activityIndex + 1) % _vbSingleExpr100.Length; _ = ActivityValidationServices.Validate(activity); } private static Activity GenerateManyExpressionsWorkflow(int startExprNum, int numExpressions) { Sequence workflow = new(); int endExprNum = startExprNum + numExpressions; for (int i = startExprNum; i < endExprNum; i++) { VisualBasicValue<string> vbv = new(@$"String.Concat(""alpha "", ""beta "", {i})"); WriteLine writeLine = new(); writeLine.Text = new InArgument<string>(vbv); workflow.Activities.Add(writeLine); } return workflow; } private static Activity GenerateSingleExpressionWorkflow(int startExprNum, int numExpressions) { StringBuilder sb = new(); sb.Append(@"String.Concat(""alpha "", ""beta """); int endExprNum = startExprNum + numExpressions; for (int i = startExprNum; i < endExprNum; i++) { sb.Append(", "); sb.Append(i); } sb.Append(')'); VisualBasicValue<string> vbv = new(sb.ToString()); WriteLine writeLine = new(); writeLine.Text = new InArgument<string>(vbv); Sequence workflow = new(); workflow.Activities.Add(writeLine); return workflow; } private static Activity[] GenerateManySingleExpressionWorkflows(int numWorkflows, int numExpressions) { Activity[] workflows = new Activity[numWorkflows]; for (int i = 0; i < numWorkflows; i++) { workflows[i] = GenerateSingleExpressionWorkflow(i, numExpressions); } return workflows; } }
33.207207
105
0.640532
[ "MIT" ]
GaryPlattenburg/CoreWF
src/Perf/CoreWf.Benchmarks/Expressions.cs
3,688
C#
// --------------------------------------------------------------------------- // <copyright file="Span.cs" owner="svm-git"> // // Copyright (c) 2018 svm-git // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // </copyright> // --------------------------------------------------------------------------- namespace Media.Captions.WebVTT { using System.Collections.Generic; /// <summary> /// Represents a caption or subtitle cue component. /// </summary> /// <remarks>See http://www.w3.org/TR/webvtt1/#webvtt-caption-or-subtitle-cue-components for details.</remarks> public class Span { /// <summary> /// Gets or sets type of the span. /// </summary> public SpanType Type { get; set; } /// <summary> /// Gets or sets classes of the span. /// </summary> public string[] Classes { get; set; } /// <summary> /// Gets or sets children spans. /// </summary> public Span[] Children { get; set; } /// <summary> /// Gets or sets span annotation. /// </summary> public string Annotation { get; set; } /// <summary> /// Gets or sets span text. /// </summary> public string Text { get; set; } } }
36.920635
115
0.602752
[ "MIT" ]
svm-git/WebVTT
src/Media.Captions.WebVTT/Span.cs
2,328
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Aspose.Cells.GridWeb.Examples.CSharp.GridWebBasics { public partial class HandleDoubleClickEvents { /// <summary> /// CheckBox1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox CheckBox1; /// <summary> /// GridWeb1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::Aspose.Cells.GridWeb.GridWeb GridWeb1; } }
33.088235
84
0.506667
[ "MIT" ]
Aspose/Aspose.Cells-for-.NET
Examples.GridWeb/CSharp/GridWebBasics/HandleDoubleClickEvents.aspx.designer.cs
1,125
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum ObjectType { BOX, WALL, TARGET, SAW, TURRET, PROJECTILE } public class SokobanObjectManager : MonoBehaviour { [Header("Object")] public ObjectType objectType; public GameObject objectParent; public SokobanObjectList objectsInScene; public GameObject animationModel; [Header("Moveable Objects")] public float gridSize = 1; public float speed = 10f; public Vector3 objectNextPos; public Vector3 direction = Vector3.zero; public List<Vector3> prevPos = new List<Vector3>(); public Vector3 initialPosition = Vector3.zero; [Header("Box")] public Material boxMaterialInitial; public Material boxMaterialInserted; public MeshRenderer meshRendererAnim; public SokobanObjectManager targetOfThisBox; [Header("Turret")] public GameObject turretProjectile; public int fireRate = 5; public Vector3 fireDirection = Vector3.zero; public int turnCounter = 0; [Header("Projectile")] public GameObject animObject; public GameObject currentAnimModel; private Vector3 projectileSpawnPos; private Transform initialTransformParent; private void Awake() { if (objectType == ObjectType.SAW) { direction = transform.right.normalized; } objectParent = GameObject.Find("Object Parent"); objectsInScene = objectParent.GetComponent<SokobanObjectList>(); } private void Start() { initialTransformParent = transform.parent; if (objectType != ObjectType.PROJECTILE) { projectileSpawnPos = transform.position + fireDirection * gridSize; if(objectType == ObjectType.BOX) prevPos.Add(transform.position); objectNextPos = transform.position + direction * gridSize; if (objectType == ObjectType.WALL) { objectNextPos = transform.position; } } else { //Initializa the projectile with the information direction = transform.parent.GetComponent<SokobanObjectManager>().fireDirection; transform.SetParent(transform.parent.transform.parent); objectNextPos = transform.position; currentAnimModel = Instantiate(animObject,transform.position,Quaternion.identity); currentAnimModel.GetComponent<AnimationHandler>().objectEntityManager = this; } initialPosition = transform.position; } private void Update() { if (currentAnimModel == null && gameObject.activeSelf && objectType == ObjectType.PROJECTILE) { //For the model that will follow the projectile currentAnimModel = Instantiate(animObject, transform.position, Quaternion.identity); currentAnimModel.GetComponent<AnimationHandler>().objectEntityManager = this; } //Check for box target position if (objectType == ObjectType.BOX) { BoxTarget(); if (targetOfThisBox != null) { if (transform.position != targetOfThisBox.transform.position) { meshRendererAnim.material = boxMaterialInitial; targetOfThisBox = new SokobanObjectManager(); } } } } public void MoveObjects() { //Commands for movement and fire are given if (objectParent == null) { objectParent = GameObject.Find("Object Parent").gameObject; } objectsInScene = objectParent.GetComponent<SokobanObjectList>(); prevPos.Add(transform.position); switch (objectType) { case ObjectType.BOX: ICommand commandPrevBox = new SokobanMoveObjectCommand(objectNextPos,transform, prevPos[prevPos.Count - 1]); CommandInvoker.SaveBoxCommand(commandPrevBox); ICommand commandBox = new SokobanMoveObjectCommand(objectNextPos, speed, direction, transform); commandBox.Execute(); break; case ObjectType.SAW: objectNextPos = objectNextPos = transform.position + direction * gridSize; if (HazardObjectTargetFinder()) { ICommand commandPrevSaw= new SokobanMoveObjectCommand(objectNextPos, transform, prevPos[prevPos.Count - 1]); CommandInvoker.SaveHazardCommand(commandPrevSaw); ICommand commandSaw = new SokobanMoveObjectCommand(objectNextPos, speed, direction, transform); commandSaw.Execute(); if (transform.position == objectNextPos) { HazardObjectTargetFinder(); objectNextPos = transform.position + direction * gridSize; } } break; case ObjectType.PROJECTILE: objectNextPos = transform.position + direction * gridSize; ICommand commandHazard = new SokobanMoveObjectCommand(objectNextPos, speed, direction, transform); commandHazard.Execute(); ICommand commandPrevProjectile = new SokobanMoveObjectCommand(objectNextPos, transform, prevPos[prevPos.Count - 1]); CommandInvoker.SaveHazardCommand(commandPrevProjectile); if (transform.position == objectNextPos) { HazardObjectTargetFinder(); objectNextPos = transform.position + direction * gridSize; } break; case ObjectType.TURRET: if (objectType == ObjectType.TURRET) { turnCounter++; if (turnCounter % fireRate == 0) { GameObject newObject = Instantiate(turretProjectile, projectileSpawnPos, Quaternion.identity); newObject.transform.SetParent(transform); objectsInScene.sokobanObjectManagers.Add(newObject.GetComponent<SokobanObjectManager>()); Destroy(currentAnimModel); ICommand commandSavedProjectileSpawn = new SokobanMoveObjectCommand(newObject,objectsInScene.sokobanObjectManagers); CommandInvoker.SaveDestroyCommand(commandSavedProjectileSpawn); } } break; } if (Input.GetKeyDown(KeyCode.R) && prevPos.Count > 0) { prevPos.RemoveAt(prevPos.Count - 1); } } //For object collision made by the saw or projectile. Saw changes direction, projectile disables its activity bool HazardObjectTargetFinder() { Vector3 hazardNextPos = transform.position + direction * gridSize; Vector3 playerTransform = objectsInScene.playerTransform.position; foreach(SokobanObjectManager objectManager in objectsInScene.sokobanObjectManagers) { if (hazardNextPos == objectManager.transform.position && objectType == ObjectType.SAW) { direction = -direction; objectNextPos = transform.position + direction * gridSize; return false; } else if (objectType == ObjectType.PROJECTILE) { if (transform.position == objectManager.transform.position && this != objectManager) { Vector3 spawnPos = transform.position - direction * gridSize; //Save the command for reactivation when Undo is done ICommand commandSaveDestroy = new SokobanMoveObjectCommand(gameObject); CommandInvoker.SaveSpawnCommand(commandSaveDestroy); gameObject.SetActive(false); return false; } } } return true; } void BoxTarget() { //Travel through the list of objects in the scene and check if the box is at the same posisiton with the target. foreach(SokobanObjectManager objects in objectsInScene.sokobanObjectManagers) { if (objects.objectType == ObjectType.TARGET && objects.transform.position == transform.position) { if (meshRendererAnim.transform.position == transform.position) { meshRendererAnim.material = boxMaterialInserted; targetOfThisBox = objects; } break; } } } }
40.665138
139
0.594134
[ "MIT" ]
dogasarpsezer/Basic-Game-Collection
Pong Internship/Assets/Scripts/Sokoban/Managers & Essentials/SokobanObjectManager.cs
8,865
C#
using System; namespace Demo.WASM { public static class DateTimeExtension { private const int Second = 1; private const int Minute = 60 * Second; private const int Hour = 60 * Minute; private const int Day = 24 * Hour; private const int Month = 30 * Day; // todo: Need to be localized public static string ToFriendlyDisplay(this DateTime dateTime) { var ts = DateTime.Now - dateTime; var delta = ts.TotalSeconds; if (delta < 0) { return "not yet"; } if (delta < 1 * Minute) { return ts.Seconds == 1 ? "1秒前" : ts.Seconds + "秒前"; } if (delta < 2 * Minute) { return "1分钟之前"; } if (delta < 45 * Minute) { return ts.Minutes + "分钟"; } if (delta < 90 * Minute) { return "1小时前"; } if (delta < 24 * Hour) { return ts.Hours + "小时前"; } if (delta < 48 * Hour) { return "昨天"; } if (delta < 30 * Day) { return ts.Days + " 天之前"; } if (delta < 12 * Month) { var months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return months <= 1 ? "一个月之前" : months + "月之前"; } else { var years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return years <= 1 ? "一年前" : years + "年前"; } } } }
28.032258
79
0.398734
[ "MIT" ]
caopengfei/BlazCharts
Demo.WASM/Extensions/DateTimeExtension.cs
1,808
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 BenchmarkDotNet.Attributes; namespace System.MathBenchmarks { public partial class Single { // Tests MathF.Tan(float) over 5000 iterations for the domain -PI/2, +PI/2 private const float tanDelta = 0.0004f; private const float tanExpectedResult = 1.66717815f; [Benchmark] public void Tan() => TanTest(); public static void TanTest() { float result = 0.0f, value = -1.0f; for (int iteration = 0; iteration < MathTests.Iterations; iteration++) { value += tanDelta; result += MathF.Tan(value); } float diff = MathF.Abs(tanExpectedResult - result); if (diff > MathTests.SingleEpsilon) { throw new Exception($"Expected Result {tanExpectedResult,10:g9}; Actual Result {result,10:g9}"); } } } }
29.230769
112
0.596491
[ "MIT" ]
333fred/performance
src/benchmarks/micro/runtime/Math/Functions/Single/TanSingle.cs
1,142
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementOrStatementStatementIpSetReferenceStatementIpSetForwardedIpConfigArgs : Pulumi.ResourceArgs { /// <summary> /// - Match status to assign to the web request if the request doesn't have a valid IP address in the specified position. Valid values include: `MATCH` or `NO_MATCH`. /// </summary> [Input("fallbackBehavior", required: true)] public Input<string> FallbackBehavior { get; set; } = null!; /// <summary> /// - Name of the HTTP header to use for the IP address. /// </summary> [Input("headerName", required: true)] public Input<string> HeaderName { get; set; } = null!; /// <summary> /// - Position in the header to search for the IP address. Valid values include: `FIRST`, `LAST`, or `ANY`. If `ANY` is specified and the header contains more than 10 IP addresses, AWS WAFv2 inspects the last 10. /// </summary> [Input("position", required: true)] public Input<string> Position { get; set; } = null!; public WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementOrStatementStatementIpSetReferenceStatementIpSetForwardedIpConfigArgs() { } } }
44.447368
220
0.695086
[ "ECL-2.0", "Apache-2.0" ]
chivandikwa/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementOrStatementStatementIpSetReferenceStatementIpSetForwardedIpConfigArgs.cs
1,689
C#
namespace InControl { // @cond nodoc [AutoDiscover, Preserve] public class SaitekAviatorWinProfile : UnityInputDeviceProfile { public SaitekAviatorWinProfile() { Name = "Saitek AV8R"; Meta = "Saitek AV8R on Windows"; DeviceClass = InputDeviceClass.FlightStick; IncludePlatforms = new[] { "Windows", }; JoystickNames = new[] { "Aviator for Playstation 3/PC", }; ButtonMappings = new[] { new InputControlMapping { Handle = "X", Target = InputControlType.Action1, Source = Button2 }, new InputControlMapping { Handle = "Circle", Target = InputControlType.Action2, Source = Button0 }, new InputControlMapping { Handle = "Square", Target = InputControlType.Action3, Source = Button3 }, new InputControlMapping { Handle = "Triangle", Target = InputControlType.Action4, Source = Button1 }, new InputControlMapping { Handle = "DPad Up", Target = InputControlType.DPadUp, Source = Button4, }, new InputControlMapping { Handle = "DPad Right", Target = InputControlType.DPadRight, Source = Button5, }, new InputControlMapping { Handle = "DPad Down", Target = InputControlType.DPadDown, Source = Button6, Invert = true }, new InputControlMapping { Handle = "DPad Left", Target = InputControlType.DPadLeft, Source = Button7, }, new InputControlMapping { Handle = "Left Stick Button", Target = InputControlType.LeftStickButton, Source = Button8 }, new InputControlMapping { Handle = "Right Stick Button", Target = InputControlType.RightStickButton, Source = Button9 }, new InputControlMapping { Handle = "Select", Target = InputControlType.Select, Source = Button10 }, new InputControlMapping { Handle = "Start", Target = InputControlType.Start, Source = Button11 }, }; AnalogMappings = new[] { LeftStickLeftMapping( Analog0 ), LeftStickRightMapping( Analog0 ), LeftStickUpMapping( Analog1 ), LeftStickDownMapping( Analog1 ), RightStickLeftMapping( Analog4 ), RightStickRightMapping( Analog4 ), new InputControlMapping { Handle = "Right Stick Up", Target = InputControlType.RightStickUp, Source = Analog5, SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne }, new InputControlMapping { Handle = "Right Stick Down", Target = InputControlType.RightStickDown, Source = Analog5, SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne }, new InputControlMapping { Handle = "Throttle Up", Target = InputControlType.RightTrigger, Source = Analog2, SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToMinusOne, Invert = true }, new InputControlMapping { Handle = "Throttle Down", Target = InputControlType.LeftTrigger, Source = Analog2, SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "Left Bumper", Target = InputControlType.LeftBumper, Source = Analog3, SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToMinusOne, Invert = true }, new InputControlMapping { Handle = "Right Bumper", Target = InputControlType.RightBumper, Source = Analog3, SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne }, }; } } // @endcond }
24.89726
63
0.650344
[ "Apache-2.0" ]
denevcoding/Ponshot-Videogame
Ponshot/Assets/AuxiliarAssets/InControl/Source/Unity/DeviceProfiles/SaitekAviatorWinProfile.cs
3,637
C#
/* Copyright (C) 2019 Alex Watt (alexwatt@hotmail.com) This file is part of Highlander Project https://github.com/alexanderwatt/Highlander.Net Highlander is free software: you can redistribute it and/or modify it under the terms of the Highlander license. You should have received a copy of the license along with this program; if not, license is available at <https://github.com/alexanderwatt/Highlander.Net/blob/develop/LICENSE>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #region Usings using System; using System.Windows.Forms; #endregion namespace Orion.PortfolioValuer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new PortfolioValuerForm()); } } }
29.307692
88
0.706912
[ "BSD-3-Clause" ]
mmrath/Highlander.Net
FpML.V5r3.Applications/PortfolioValuer/Program.cs
1,145
C#
namespace NServiceBus.Hosting.Windows.Profiles.Handlers { using Faults; using Hosting.Profiles; internal class ProductionProfileHandler : IHandleProfile<Production> { void IHandleProfile.ProfileActivated() { if (!Configure.Instance.Configurer.HasComponent<IManageMessageFailures>()) { Configure.Instance.MessageForwardingInCaseOfFault(); } } } }
28.625
87
0.624454
[ "Apache-2.0", "MIT" ]
ianbattersby/NServiceBus
src/NServiceBus.Hosting.Windows/Profiles/Handlers/ProductionProfileHandler.cs
445
C#
using Microsoft.Azure.Functions.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Text; using TrickleToTide.Api.DAL; [assembly: FunctionsStartup(typeof(TrickleToTide.Api.Startup))] namespace TrickleToTide.Api { class Startup : FunctionsStartup { public override void Configure(IFunctionsHostBuilder builder) { var config = new ConfigurationBuilder() .AddJsonFile("settings.json", true, true) .AddJsonFile("local.settings.json", true, true) .AddEnvironmentVariables() .Build(); builder.Services.AddDbContext<PositionContext>(options => { options.UseSqlServer(config.GetConnectionString("ttt")); }); } } }
31.366667
72
0.672689
[ "MIT" ]
RandomBlueThing/TrickleToTide
Api/TrickleToTide.Api/Startup.cs
943
C#
using Enmeshed.DevelopmentKit.Identity.ValueObjects; using Enmeshed.Tooling; using Microsoft.AspNetCore.Identity; namespace Devices.Domain.Entities; public class ApplicationUser : IdentityUser { private readonly Device _device; #pragma warning disable CS8618 public ApplicationUser() : base(Username.New()) { } #pragma warning restore CS8618 public ApplicationUser(Identity identity, DeviceId? createdByDevice = null) : base(Username.New()) { _device = new Device(identity, createdByDevice); DeviceId = Device.Id; CreatedAt = SystemTime.UtcNow; } public DeviceId DeviceId { get; set; } public Device Device { get => _device; init { _device = value; DeviceId = value.Id; } } public DateTime CreatedAt { get; set; } public DateTime? LastLoginAt { get; set; } public void LoginOccurred() { LastLoginAt = SystemTime.UtcNow; } }
22.744186
102
0.653374
[ "MIT" ]
nmshd/bkb-devices
Devices.Domain/Entities/ApplicationUser.cs
980
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Cme.V20191029.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeMaterialsRequest : AbstractModel { /// <summary> /// 平台 Id,指定访问的平台。关于平台概念,请参见文档 [平台](https://cloud.tencent.com/document/product/1156/43767)。 /// </summary> [JsonProperty("Platform")] public string Platform{ get; set; } /// <summary> /// 媒体 ID 列表,一次最多可拉取20个媒体的信息。 /// </summary> [JsonProperty("MaterialIds")] public string[] MaterialIds{ get; set; } /// <summary> /// 列表排序,支持下列排序字段: /// <li>CreateTime:创建时间;</li> /// <li>UpdateTime:更新时间。</li> /// </summary> [JsonProperty("Sort")] public SortBy Sort{ get; set; } /// <summary> /// 操作者。如不填,默认为 `cmeid_system`,表示平台管理员操作,可以获取任意媒体的信息。如果指定操作者,则操作者必须对媒体有读权限。 /// </summary> [JsonProperty("Operator")] public string Operator{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Platform", this.Platform); this.SetParamArraySimple(map, prefix + "MaterialIds.", this.MaterialIds); this.SetParamObj(map, prefix + "Sort.", this.Sort); this.SetParamSimple(map, prefix + "Operator", this.Operator); } } }
32.791045
99
0.619481
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Cme/V20191029/Models/DescribeMaterialsRequest.cs
2,451
C#
/* * Copyright (c) 2012 Stephen A. Pratt * * 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 org.critterai.nav.u3d.editor; using org.critterai.nav.u3d; using UnityEngine; namespace org.critterai.nmbuild.u3d.editor { internal sealed class DebugViewContext { private static GUIContent mShowInputLabel = new GUIContent( "Input Geometry" , "Framerate Killer!"); private readonly InputDebugView mInputView = new InputDebugView(); private readonly TileGridDebugView mGridView = new TileGridDebugView(); private readonly SelectionDebugView mSelectionView; private readonly MeshDebugView mMeshView = new MeshDebugView(); private readonly NavmeshBuild mBuild; private readonly TileSelection mSelection; private bool mNeedsRepaint; public DebugViewContext(NavmeshBuild build, TileSelection selection) { if (!build || selection == null) throw new System.ArgumentNullException(); mSelectionView = new SelectionDebugView(); mSelectionView.Enabled = true; mSelectionView.Show = true; mSelectionView.IncludeRootTile = true; mBuild = build; mSelection = selection; } public bool NeedsRepaint { get { return mNeedsRepaint || mSelectionView.NeedsRepaint || mMeshView.NeedsRepaint || mInputView.NeedsRepaint || mGridView.NeedsRepaint; } set { mNeedsRepaint = value; if (!mNeedsRepaint) { mSelectionView.NeedsRepaint = false; mMeshView.NeedsRepaint = false; mInputView.NeedsRepaint = false; mGridView.NeedsRepaint = false; } } } public void DisableAllViews() { mInputView.Enabled = false; mGridView.Enabled = false; mSelectionView.Enabled = false; mMeshView.Enabled = false; } public void SetViews(ViewOption options) { // Debug.Log("Set Debug Views: " + options); mInputView.Enabled = (options & ViewOption.Input) != 0; mGridView.Enabled = (options & ViewOption.Grid) != 0; mSelectionView.Enabled = (options & ViewOption.Selection) != 0; mMeshView.Enabled = (options & ViewOption.Mesh) != 0; } public void OnSceneGUI() { if (!mBuild) return; mInputView.OnRenderObject(mBuild); mGridView.OnRenderObject(mBuild); mSelectionView.OnRenderObject(mBuild, mSelection); mMeshView.OnRenderObject(mBuild, mSelection); } public void OnGUIDebugExtras() { // Design note: Not allowing the selection display to be disabled. // It is too important. bool guiEnabled = GUI.enabled; if (mInputView.Enabled) mInputView.Show = GUILayout.Toggle(mInputView.Show, "Input Bounds"); if (mGridView.Enabled) { mGridView.Show = GUILayout.Toggle(mGridView.Show, "Tile Grid"); GUILayout.Space(ControlUtil.MarginSize); GUI.enabled = guiEnabled && mGridView.Show; mGridView.YOffset = GUILayout.HorizontalSlider(mGridView.YOffset, 0, 1); GUI.enabled = guiEnabled; } if (mSelectionView.Enabled) { mSelectionView.Show = GUILayout.Toggle(mSelectionView.Show, "Selection Bounds"); } } public void OnGUIMeshDisplayOptions() { if (!mBuild || !mMeshView.Enabled) return; bool guiEnabled = GUI.enabled; MeshDebugView meshView = mMeshView; INavmeshData bnm = mBuild.BuildTarget; NavmeshSceneDraw sceneDraw = NavmeshSceneDraw.Instance; bool showBaked = false; if (bnm != null) { showBaked = sceneDraw.OnGUI(bnm, "Baked Navmesh", false, false); if (showBaked) meshView.Show = MeshDebugOption.None; } if (GUILayout.Toggle(meshView.Show == MeshDebugOption.WorkingMesh , "Working Navmesh")) { meshView.Show = MeshDebugOption.WorkingMesh; showBaked = false; } else if (meshView.Show == MeshDebugOption.WorkingMesh) meshView.Show = MeshDebugOption.None; GUI.enabled = guiEnabled && meshView.Show == MeshDebugOption.WorkingMesh || showBaked; bool orig = sceneDraw.ColorByArea; sceneDraw.ColorByArea = GUILayout.Toggle(sceneDraw.ColorByArea, "Color by Area"); if (sceneDraw.ColorByArea != orig) mNeedsRepaint = true; GUILayout.Space(ControlUtil.MarginSize); GUI.enabled = guiEnabled && (mSelection.HasSelection || !mBuild.BuildData.IsTiled); if (GUILayout.Toggle(meshView.Show == MeshDebugOption.PolyMesh , "PolyMesh")) { meshView.Show = MeshDebugOption.PolyMesh; showBaked = false; } else if (meshView.Show == MeshDebugOption.PolyMesh) meshView.Show = MeshDebugOption.None; if (GUILayout.Toggle(meshView.Show == MeshDebugOption.Detailmesh , "Detail Mesh")) { meshView.Show = MeshDebugOption.Detailmesh; showBaked = false; } else if (meshView.Show == MeshDebugOption.Detailmesh) meshView.Show = MeshDebugOption.None; if (mBuild.TileSetDefinition != null) { if (GUILayout.Toggle(meshView.Show == MeshDebugOption.InputGeometry , mShowInputLabel)) { meshView.Show = MeshDebugOption.InputGeometry; showBaked = false; } else if (meshView.Show == MeshDebugOption.InputGeometry) meshView.Show = MeshDebugOption.None; } GUI.enabled = guiEnabled; if (showBaked) meshView.Show = MeshDebugOption.None; else sceneDraw.Hide(); } } }
35.941176
97
0.557976
[ "MIT" ]
hjjss/critterai
src/main/Assets/CAI/nmbuild-u3d/Editor/views/DebugViewContext.cs
7,945
C#
namespace GameThing.UI { public delegate void ContentLoadedEventHandler(); }
15.8
50
0.797468
[ "Apache-2.0" ]
rythos42/GameThing
GameThing.UI/ContentLoadedEventHandler.cs
81
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.480) // Version 5.480.0.0 www.ComponentFactory.com // ***************************************************************************** using System.ComponentModel; using System.Diagnostics; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Ribbon { /// <summary> /// Implement storage for a ribbon state. /// </summary> public class PaletteRibbonJustGroup : Storage { #region Instance Fields private readonly PaletteRibbonBack _ribbonGroupNormalBorder; private readonly PaletteRibbonDouble _ribbonGroupNormalTitle; private readonly PaletteRibbonBack _ribbonGroupCollapsedBorder; private readonly PaletteRibbonBack _ribbonGroupCollapsedBack; private readonly PaletteRibbonBack _ribbonGroupCollapsedFrameBorder; private readonly PaletteRibbonBack _ribbonGroupCollapsedFrameBack; private readonly PaletteRibbonText _ribbonGroupCollapsedText; #endregion #region Identity /// <summary> /// Initialize a new instance of the PaletteRibbonJustGroup class. /// </summary> /// <param name="inherit">Source for inheriting values.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public PaletteRibbonJustGroup(PaletteRibbonRedirect inherit, NeedPaintHandler needPaint) { Debug.Assert(inherit != null); // Store the provided paint notification delegate NeedPaint = needPaint; // Create storage that maps onto the inherit instances _ribbonGroupNormalBorder = new PaletteRibbonBack(inherit.RibbonGroupNormalBorder, needPaint); _ribbonGroupNormalTitle = new PaletteRibbonDouble(inherit.RibbonGroupNormalTitle, inherit.RibbonGroupNormalTitle, needPaint); _ribbonGroupCollapsedBorder = new PaletteRibbonBack(inherit.RibbonGroupCollapsedBorder, needPaint); _ribbonGroupCollapsedBack = new PaletteRibbonBack(inherit.RibbonGroupCollapsedBack, needPaint); _ribbonGroupCollapsedFrameBorder = new PaletteRibbonBack(inherit.RibbonGroupCollapsedFrameBorder, needPaint); _ribbonGroupCollapsedFrameBack = new PaletteRibbonBack(inherit.RibbonGroupCollapsedFrameBack, needPaint); _ribbonGroupCollapsedText = new PaletteRibbonText(inherit.RibbonGroupCollapsedText, needPaint); } #endregion #region IsDefault /// <summary> /// Gets a value indicating if all values are default. /// </summary> [Browsable(false)] public override bool IsDefault => (RibbonGroupNormalBorder.IsDefault && RibbonGroupNormalTitle.IsDefault && RibbonGroupCollapsedBorder.IsDefault && RibbonGroupCollapsedBack.IsDefault && RibbonGroupCollapsedFrameBorder.IsDefault && RibbonGroupCollapsedFrameBack.IsDefault && RibbonGroupCollapsedText.IsDefault); #endregion #region PopulateFromBase /// <summary> /// Populate values from the base palette. /// </summary> /// <param name="state">The palette state to populate with.</param> public virtual void PopulateFromBase(PaletteState state) { _ribbonGroupNormalBorder.PopulateFromBase(state); _ribbonGroupNormalTitle.PopulateFromBase(state); _ribbonGroupCollapsedBorder.PopulateFromBase(state); _ribbonGroupCollapsedBack.PopulateFromBase(state); _ribbonGroupCollapsedFrameBorder.PopulateFromBase(state); _ribbonGroupCollapsedFrameBack.PopulateFromBase(state); _ribbonGroupCollapsedText.PopulateFromBase(state); } #endregion #region SetInherit /// <summary> /// Sets the inheritence parent. /// </summary> public virtual void SetInherit(PaletteRibbonRedirect inherit) { _ribbonGroupNormalBorder.SetInherit(inherit.RibbonGroupNormalBorder); _ribbonGroupNormalTitle.SetInherit(inherit.RibbonGroupNormalTitle, inherit.RibbonGroupNormalTitle); _ribbonGroupCollapsedBorder.SetInherit(inherit.RibbonGroupCollapsedBorder); _ribbonGroupCollapsedBack.SetInherit(inherit.RibbonGroupCollapsedBack); _ribbonGroupCollapsedFrameBorder.SetInherit(inherit.RibbonGroupCollapsedFrameBorder); _ribbonGroupCollapsedFrameBack.SetInherit(inherit.RibbonGroupCollapsedFrameBack); _ribbonGroupCollapsedText.SetInherit(inherit.RibbonGroupCollapsedText); } #endregion #region RibbonGroupNormalBorder /// <summary> /// Gets access to the ribbon group normal border palette details. /// </summary> [Category("Visuals")] [Description("Overrides for defining ribbon group normal border appearance.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public virtual PaletteRibbonBack RibbonGroupNormalBorder => _ribbonGroupNormalBorder; private bool ShouldSerializeRibbonGroupNormalBorder() { return !_ribbonGroupNormalBorder.IsDefault; } #endregion #region RibbonGroupNormalTitle /// <summary> /// Gets access to the ribbon group normal title palette details. /// </summary> [Category("Visuals")] [Description("Overrides for defining ribbon group normal title appearance.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public virtual PaletteRibbonDouble RibbonGroupNormalTitle => _ribbonGroupNormalTitle; private bool ShouldSerializeRibbonGroupNormalTitle() { return !_ribbonGroupNormalTitle.IsDefault; } #endregion #region RibbonGroupCollapsedBorder /// <summary> /// Gets access to the ribbon group collapsed border palette details. /// </summary> [Category("Visuals")] [Description("Overrides for defining ribbon group collapsed border appearance.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public virtual PaletteRibbonBack RibbonGroupCollapsedBorder => _ribbonGroupCollapsedBorder; private bool ShouldSerializeRibbonGroupCollapsedBorder() { return !_ribbonGroupCollapsedBorder.IsDefault; } #endregion #region RibbonGroupCollapsedBack /// <summary> /// Gets access to the ribbon group collapsed background palette details. /// </summary> [Category("Visuals")] [Description("Overrides for defining ribbon group collapsed background appearance.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public virtual PaletteRibbonBack RibbonGroupCollapsedBack => _ribbonGroupCollapsedBack; private bool ShouldSerializeRibbonGroupCollapsedBack() { return !_ribbonGroupCollapsedBack.IsDefault; } #endregion #region RibbonGroupCollapsedFrameBorder /// <summary> /// Gets access to the ribbon group collapsed frame border palette details. /// </summary> [Category("Visuals")] [Description("Overrides for defining ribbon group collapsed frame border appearance.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public virtual PaletteRibbonBack RibbonGroupCollapsedFrameBorder => _ribbonGroupCollapsedFrameBorder; private bool ShouldSerializeRibbonGroupCollapsedFrameBorder() { return !_ribbonGroupCollapsedFrameBorder.IsDefault; } #endregion #region RibbonGroupCollapsedFrameBack /// <summary> /// Gets access to the ribbon group collapsed frame background palette details. /// </summary> [Category("Visuals")] [Description("Overrides for defining ribbon group collapsed frame background appearance.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public virtual PaletteRibbonBack RibbonGroupCollapsedFrameBack => _ribbonGroupCollapsedFrameBack; private bool ShouldSerializeRibbonGroupCollapsedFrameBack() { return !_ribbonGroupCollapsedFrameBack.IsDefault; } #endregion #region RibbonGroupCollapsedText /// <summary> /// Gets access to the ribbon group collapsed text palette details. /// </summary> [Category("Visuals")] [Description("Overrides for defining ribbon group collapsed text appearance.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public virtual PaletteRibbonText RibbonGroupCollapsedText => _ribbonGroupCollapsedText; private bool ShouldSerializeRibbonGroupCollapsedText() { return !_ribbonGroupCollapsedText.IsDefault; } #endregion #region Implementation /// <summary> /// Handle a change event from palette source. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="needLayout">True if a layout is also needed.</param> protected void OnNeedPaint(object sender, bool needLayout) { // Pass request from child to our own handler PerformNeedPaint(needLayout); } #endregion } }
46.262222
157
0.671726
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.480
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/Palette/PaletteRibbonJustGroup.cs
10,412
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //Testing common sub-expression elimination in random code using System; internal unsafe class testout1 { public static int sa = 2; public static int sb = 1; public struct VT_0_1_2_5_2 { public double a4_0_1_2_5_2; } public struct VT_0_1_2_5_1 { public double a1_0_1_2_5_1; } public struct VT_0_1_2_4_3 { public long a0_0_1_2_4_3; } public struct VT_0_1_2_4_2 { public double a2_0_1_2_4_2; } public struct VT_0_1_2_3_2 { public long a2_0_1_2_3_2; } public struct VT_0_1_2_3_1 { public int a1_0_1_2_3_1; public long a4_0_1_2_3_1; } public struct VT_0_1_2_2_2 { public double a3_0_1_2_2_2; } public struct VT_0_1_2_2_1 { public long a0_0_1_2_2_1; public double a1_0_1_2_2_1; public double a4_0_1_2_2_1; public long a5_0_1_2_2_1; } public struct VT_0_1_2_1_2 { public int a1_0_1_2_1_2; public double a4_0_1_2_1_2; } public struct VT_0_1_2_1_1 { public double a0_0_1_2_1_1; public double a3_0_1_2_1_1; public double a4_0_1_2_1_1; } public struct VT_0_1_2_5 { public double a1_0_1_2_5; public double a2_0_1_2_5; } public struct VT_0_1_2_3 { public int a1_0_1_2_3; public long a2_0_1_2_3; } public struct VT_0_1_2_2 { public double a3_0_1_2_2; } public struct VT_0_1_2_1 { public double a1_0_1_2_1; public double a3_0_1_2_1; } public struct VT_0_1_2 { public double a0_0_1_2; } public struct VT_0_1 { public float a2_0_1; public int a3_0_1; } public struct VT_0 { public float a2_0; public double a3_0; public double a4_0; } public class CL_0_1_2_5_2 { public long a0_0_1_2_5_2 = -sa * sb; } public class CL_0_1_2_5_1 { public double[,,] arr3d_0_1_2_5_1 = new double[5, 11, 4]; } public class CL_0_1_2_4_1 { public long[,,] arr3d_0_1_2_4_1 = new long[5, 11, 4]; public long a1_0_1_2_4_1 = sa + sb; } public class CL_0_1_2_3_2 { public long[,,] arr3d_0_1_2_3_2 = new long[5, 11, 4]; public int[,] arr2d_0_1_2_3_2 = new int[3, 11]; } public class CL_0_1_2_3_1 { public long[] arr1d_0_1_2_3_1 = new long[11]; public int[,,] arr3d_0_1_2_3_1 = new int[5, 11, 4]; public int a5_0_1_2_3_1 = -sa / sb; } public class CL_0_1_2_2_2 { public double a4_0_1_2_2_2 = sa - sb; } public class CL_0_1_2_2_1 { public int[,] arr2d_0_1_2_2_1 = new int[3, 11]; } public class CL_0_1_2_1_2 { public double a0_0_1_2_1_2 = sa - sb; } public class CL_0_1_2_5 { public int[,] arr2d_0_1_2_5 = new int[3, 11]; } public class CL_0_1_2_1 { public long[,] arr2d_0_1_2_1 = new long[3, 11]; } public class CL_0_1 { public double a1_0_1 = sa + sb; } public static VT_0_1_2_5_2 vtstatic_0_1_2_5_2 = new VT_0_1_2_5_2(); public static VT_0_1_2_4_3 vtstatic_0_1_2_4_3 = new VT_0_1_2_4_3(); public static CL_0_1_2_4_1 clstatic_0_1_2_4_1 = new CL_0_1_2_4_1(); public static VT_0_1_2_3_2 vtstatic_0_1_2_3_2 = new VT_0_1_2_3_2(); private static int s_a2_0_1_2_3_1 = sa / sb; public static VT_0_1_2_3_1 vtstatic_0_1_2_3_1 = new VT_0_1_2_3_1(); private static double s_a1_0_1_2_2_2 = -sa * sb; public static VT_0_1_2_2_1 vtstatic_0_1_2_2_1 = new VT_0_1_2_2_1(); public static CL_0_1_2_2_1 clstatic_0_1_2_2_1 = new CL_0_1_2_2_1(); public static VT_0_1_2_5 vtstatic_0_1_2_5 = new VT_0_1_2_5(); public static VT_0_1_2_2 vtstatic_0_1_2_2 = new VT_0_1_2_2(); public static VT_0_1 vtstatic_0_1 = new VT_0_1(); public static VT_0 vtstatic_0 = new VT_0(); public static double Func_0_1_2_5_2(CL_0_1_2_5_2 cl_0_1_2_5_2, double* a5_0_1_2_5_2) { double a2_0_1_2_5_2 = sa + sb; double a3_0_1_2_5_2 = sa - sb; vtstatic_0_1_2_5_2.a4_0_1_2_5_2 = sa + sb; double retval_0_1_2_5_2 = Convert.ToDouble((a2_0_1_2_5_2 + ((sa + sb - ((sa - sb + cl_0_1_2_5_2.a0_0_1_2_5_2) / (*a5_0_1_2_5_2))) * (((*a5_0_1_2_5_2) / a3_0_1_2_5_2) + vtstatic_0_1_2_5_2.a4_0_1_2_5_2)))); Console.WriteLine("retval_0_1_2_5_2 is {0}", retval_0_1_2_5_2); return retval_0_1_2_5_2; } public static double Func_0_1_2_5_1(CL_0_1_2_5_1 cl_0_1_2_5_1) { VT_0_1_2_5_1 vt_0_1_2_5_1 = new VT_0_1_2_5_1(); vt_0_1_2_5_1.a1_0_1_2_5_1 = sa * sb; double retval_0_1_2_5_1 = Convert.ToDouble((((vt_0_1_2_5_1.a1_0_1_2_5_1 + -sa * sb) - vt_0_1_2_5_1.a1_0_1_2_5_1) * ((vt_0_1_2_5_1.a1_0_1_2_5_1 * 1.0) + ((vt_0_1_2_5_1.a1_0_1_2_5_1 + cl_0_1_2_5_1.arr3d_0_1_2_5_1[4, 0, 3]) - (-sa * sb))))); Console.WriteLine("retval_0_1_2_5_1 is {0}", retval_0_1_2_5_1); return retval_0_1_2_5_1; } public static double Func_0_1_2_4_3() { int[,] arr2d_0_1_2_4_3 = new int[3, 11]; vtstatic_0_1_2_4_3.a0_0_1_2_4_3 = -sa / sb; arr2d_0_1_2_4_3[2, 1] = sa / sb; double retval_0_1_2_4_3 = Convert.ToDouble(((((double)((long)(Convert.ToInt32(arr2d_0_1_2_4_3[2, 1]) + (long)(vtstatic_0_1_2_4_3.a0_0_1_2_4_3)) * 0.25)) + (arr2d_0_1_2_4_3[2, 1] * (0.25 - (-sa / sb)))) - (((-sa / sb + sa + sb) + (-sa + sb * sa * sb))))); Console.WriteLine("retval_0_1_2_4_3 is {0}", retval_0_1_2_4_3); return retval_0_1_2_4_3; } public static double Func_0_1_2_4_2(VT_0_1_2_4_2 vt_0_1_2_4_2, double a3_0_1_2_4_2) { double a0_0_1_2_4_2 = -sa / sb; double retval_0_1_2_4_2 = Convert.ToDouble(((a0_0_1_2_4_2 + ((a0_0_1_2_4_2 - sa / sb) * a3_0_1_2_4_2)) + ((-sa / sb * ((a3_0_1_2_4_2 - sa / sb) - (vt_0_1_2_4_2.a2_0_1_2_4_2))) + (a0_0_1_2_4_2 + sa / sb)))); Console.WriteLine("retval_0_1_2_4_2 is {0}", retval_0_1_2_4_2); return retval_0_1_2_4_2; } public static long Func_0_1_2_4_1(int[,,] arr3d_0_1_2_4_1) { CL_0_1_2_4_1 cl_0_1_2_4_1 = new CL_0_1_2_4_1(); clstatic_0_1_2_4_1.arr3d_0_1_2_4_1[4, 0, 3] = -sa % sb; long retval_0_1_2_4_1 = Convert.ToInt64(((long)(Convert.ToInt32(arr3d_0_1_2_4_1[4, 2, 3]) - (long)((clstatic_0_1_2_4_1.arr3d_0_1_2_4_1[4, 0, 3] - cl_0_1_2_4_1.a1_0_1_2_4_1))) + clstatic_0_1_2_4_1.arr3d_0_1_2_4_1[4, 0, 3])); Console.WriteLine("retval_0_1_2_4_1 is {0}", retval_0_1_2_4_1); return retval_0_1_2_4_1; } public static long Func_0_1_2_3_2(int[,] arr2d_0_1_2_3_2, CL_0_1_2_3_2 cl_0_1_2_3_2) { vtstatic_0_1_2_3_2.a2_0_1_2_3_2 = -sa * sb; cl_0_1_2_3_2.arr3d_0_1_2_3_2[4, 0, 3] = sa * sb; long retval_0_1_2_3_2 = Convert.ToInt64((((long)(((long)(vtstatic_0_1_2_3_2.a2_0_1_2_3_2) * (long)(sa + sb)) / -sa * sb)) - (long)(Convert.ToInt32((Convert.ToInt32((Convert.ToInt32(cl_0_1_2_3_2.arr2d_0_1_2_3_2[2, 4])) % (Convert.ToInt32(arr2d_0_1_2_3_2[2, 1]))))) - (long)(((long)(vtstatic_0_1_2_3_2.a2_0_1_2_3_2 / (vtstatic_0_1_2_3_2.a2_0_1_2_3_2 - cl_0_1_2_3_2.arr3d_0_1_2_3_2[4, 0, 3]))))))); Console.WriteLine("retval_0_1_2_3_2 is {0}", retval_0_1_2_3_2); return retval_0_1_2_3_2; } public static long Func_0_1_2_3_1(CL_0_1_2_3_1 cl_0_1_2_3_1) { VT_0_1_2_3_1 vt_0_1_2_3_1 = new VT_0_1_2_3_1(); vt_0_1_2_3_1.a1_0_1_2_3_1 = -sa / sb; vt_0_1_2_3_1.a4_0_1_2_3_1 = sa + sb + sa / sb; vtstatic_0_1_2_3_1.a1_0_1_2_3_1 = -sa / sb; vtstatic_0_1_2_3_1.a4_0_1_2_3_1 = sa + sb; cl_0_1_2_3_1.arr1d_0_1_2_3_1[0] = sa / sb; long retval_0_1_2_3_1 = Convert.ToInt64((long)(Convert.ToInt32(((Convert.ToInt32((Convert.ToInt32(cl_0_1_2_3_1.arr3d_0_1_2_3_1[4, 3, 3])) % (Convert.ToInt32(s_a2_0_1_2_3_1)))) + cl_0_1_2_3_1.a5_0_1_2_3_1)) + (long)((long)(Convert.ToInt32(((cl_0_1_2_3_1.a5_0_1_2_3_1 + 0) - ((Convert.ToInt32((Convert.ToInt32(vt_0_1_2_3_1.a1_0_1_2_3_1)) % (Convert.ToInt32(sa + sb))))))) + (long)((vtstatic_0_1_2_3_1.a4_0_1_2_3_1 - cl_0_1_2_3_1.arr1d_0_1_2_3_1[0])))))); Console.WriteLine("retval_0_1_2_3_1 is {0}", retval_0_1_2_3_1); return retval_0_1_2_3_1; } public static double Func_0_1_2_2_2(int[,] arr2d_0_1_2_2_2, VT_0_1_2_2_2 vt_0_1_2_2_2, CL_0_1_2_2_2 cl_0_1_2_2_2) { double retval_0_1_2_2_2 = Convert.ToDouble(((-sa * sb * (cl_0_1_2_2_2.a4_0_1_2_2_2 + (cl_0_1_2_2_2.a4_0_1_2_2_2 - (vt_0_1_2_2_2.a3_0_1_2_2_2)))) - ((arr2d_0_1_2_2_2[2, 0] - (Convert.ToInt32(arr2d_0_1_2_2_2[2, 0] * sa * sb))) / (-sa * sb / s_a1_0_1_2_2_2)))); Console.WriteLine("retval_0_1_2_2_2 is {0}", retval_0_1_2_2_2); return retval_0_1_2_2_2; } public static double Func_0_1_2_2_1(VT_0_1_2_2_1 vt_0_1_2_2_1) { vtstatic_0_1_2_2_1.a0_0_1_2_2_1 = -sa + sb; vtstatic_0_1_2_2_1.a1_0_1_2_2_1 = sa + sb * sb; vtstatic_0_1_2_2_1.a4_0_1_2_2_1 = sb * sa + sb * sa; vtstatic_0_1_2_2_1.a5_0_1_2_2_1 = sa - sb * sb; clstatic_0_1_2_2_1.arr2d_0_1_2_2_1[2, 3] = sa * sb - sb; double retval_0_1_2_2_1 = Convert.ToDouble((((sa + sb * sb - vtstatic_0_1_2_2_1.a1_0_1_2_2_1) + ((vtstatic_0_1_2_2_1.a1_0_1_2_2_1 + 0.0) / (20.0 - (sb * sa + sb * sa)))) - (((double)(((long)(vtstatic_0_1_2_2_1.a0_0_1_2_2_1 / (vtstatic_0_1_2_2_1.a0_0_1_2_2_1 + vt_0_1_2_2_1.a5_0_1_2_2_1 + sa - sb))) * (clstatic_0_1_2_2_1.arr2d_0_1_2_2_1[2, 3] * vtstatic_0_1_2_2_1.a4_0_1_2_2_1)))))); Console.WriteLine("retval_0_1_2_2_1 is {0}", retval_0_1_2_2_1); return retval_0_1_2_2_1; } public static double Func_0_1_2_1_2(VT_0_1_2_1_2 vt_0_1_2_1_2) { CL_0_1_2_1_2 cl_0_1_2_1_2 = new CL_0_1_2_1_2(); double retval_0_1_2_1_2 = Convert.ToDouble(((vt_0_1_2_1_2.a1_0_1_2_1_2 / (cl_0_1_2_1_2.a0_0_1_2_1_2 - (vt_0_1_2_1_2.a4_0_1_2_1_2))) - cl_0_1_2_1_2.a0_0_1_2_1_2)); Console.WriteLine("retval_0_1_2_1_2 is {0}", retval_0_1_2_1_2); return retval_0_1_2_1_2; } public static double Func_0_1_2_1_1() { VT_0_1_2_1_1 vt_0_1_2_1_1 = new VT_0_1_2_1_1(); vt_0_1_2_1_1.a0_0_1_2_1_1 = (sa + sb) * (sa + sb); vt_0_1_2_1_1.a3_0_1_2_1_1 = -(sa + sb) / (sa - sb); vt_0_1_2_1_1.a4_0_1_2_1_1 = -(sa + sb) / (sa * sb); double retval_0_1_2_1_1 = Convert.ToDouble((((vt_0_1_2_1_1.a3_0_1_2_1_1 - vt_0_1_2_1_1.a0_0_1_2_1_1) + vt_0_1_2_1_1.a3_0_1_2_1_1) - ((vt_0_1_2_1_1.a3_0_1_2_1_1 - vt_0_1_2_1_1.a0_0_1_2_1_1) - ((vt_0_1_2_1_1.a0_0_1_2_1_1 + vt_0_1_2_1_1.a4_0_1_2_1_1))))); Console.WriteLine("retval_0_1_2_1_1 is {0}", retval_0_1_2_1_1); return retval_0_1_2_1_1; } public static double Func_0_1_2_5(CL_0_1_2_5 cl_0_1_2_5) { VT_0_1_2_5 vt_0_1_2_5 = new VT_0_1_2_5(); vt_0_1_2_5.a1_0_1_2_5 = sa - sb; vt_0_1_2_5.a2_0_1_2_5 = sa * sb; vtstatic_0_1_2_5.a1_0_1_2_5 = sa - sb; vtstatic_0_1_2_5.a2_0_1_2_5 = sa - sb; CL_0_1_2_5_2 cl_0_1_2_5_2 = new CL_0_1_2_5_2(); double* a5_0_1_2_5_2 = stackalloc double[1]; *a5_0_1_2_5_2 = sa * sb; double val_0_1_2_5_2 = Func_0_1_2_5_2(cl_0_1_2_5_2, a5_0_1_2_5_2); CL_0_1_2_5_1 cl_0_1_2_5_1 = new CL_0_1_2_5_1(); cl_0_1_2_5_1.arr3d_0_1_2_5_1[4, 0, 3] = sa * sb; double val_0_1_2_5_1 = Func_0_1_2_5_1(cl_0_1_2_5_1); double retval_0_1_2_5 = Convert.ToDouble(((Convert.ToInt32((cl_0_1_2_5.arr2d_0_1_2_5[2, 0] * vt_0_1_2_5.a1_0_1_2_5) - (vtstatic_0_1_2_5.a2_0_1_2_5 + (vtstatic_0_1_2_5.a2_0_1_2_5 + (vtstatic_0_1_2_5.a2_0_1_2_5 + val_0_1_2_5_2))))) * val_0_1_2_5_1)); Console.WriteLine("retval_0_1_2_5 is {0}", retval_0_1_2_5); return retval_0_1_2_5; } public static long Func_0_1_2_4(long* a0_0_1_2_4) { double val_0_1_2_4_3 = Func_0_1_2_4_3(); VT_0_1_2_4_2 vt_0_1_2_4_2 = new VT_0_1_2_4_2(); vt_0_1_2_4_2.a2_0_1_2_4_2 = -sa * sb; double a3_0_1_2_4_2 = -sa * sb; double val_0_1_2_4_2 = Func_0_1_2_4_2(vt_0_1_2_4_2, a3_0_1_2_4_2); int[,,] arr3d_0_1_2_4_1 = new int[5, 11, 4]; arr3d_0_1_2_4_1[4, 2, 3] = sa * sb; long val_0_1_2_4_1 = Func_0_1_2_4_1(arr3d_0_1_2_4_1); long retval_0_1_2_4 = Convert.ToInt64((long)(Convert.ToInt32((Convert.ToInt32(((*a0_0_1_2_4) / val_0_1_2_4_3) + val_0_1_2_4_2))) - (long)(val_0_1_2_4_1))); Console.WriteLine("retval_0_1_2_4 is {0}", retval_0_1_2_4); return retval_0_1_2_4; } public static int Func_0_1_2_3() { VT_0_1_2_3 vt_0_1_2_3 = new VT_0_1_2_3(); vt_0_1_2_3.a1_0_1_2_3 = -sa - sb; vt_0_1_2_3.a2_0_1_2_3 = sa + sb; long[,] arr2d_0_1_2_3 = new long[3, 11]; int a3_0_1_2_3 = sa / sb; arr2d_0_1_2_3[2, 0] = sa / sb; CL_0_1_2_3_2 cl_0_1_2_3_2 = new CL_0_1_2_3_2(); int[,] arr2d_0_1_2_3_2 = new int[3, 11]; arr2d_0_1_2_3_2[2, 1] = sa + sb; cl_0_1_2_3_2.arr2d_0_1_2_3_2[2, 4] = sa - sb; long val_0_1_2_3_2 = Func_0_1_2_3_2(arr2d_0_1_2_3_2, cl_0_1_2_3_2); CL_0_1_2_3_1 cl_0_1_2_3_1 = new CL_0_1_2_3_1(); cl_0_1_2_3_1.arr3d_0_1_2_3_1[4, 3, 3] = sa - sb; long val_0_1_2_3_1 = Func_0_1_2_3_1(cl_0_1_2_3_1); int retval_0_1_2_3 = Convert.ToInt32((Convert.ToInt32((long)((long)(Convert.ToInt32((a3_0_1_2_3 - (vt_0_1_2_3.a1_0_1_2_3))) + (long)((long)(Convert.ToInt32((Convert.ToInt32((long)(arr2d_0_1_2_3[2, 0]) - (long)(val_0_1_2_3_2)))) + (long)(arr2d_0_1_2_3[2, 0]))))) - (long)((long)(Convert.ToInt32(((sa + sb) / vt_0_1_2_3.a2_0_1_2_3)) - (long)(val_0_1_2_3_1)))))); Console.WriteLine("retval_0_1_2_3 is {0}", retval_0_1_2_3); return retval_0_1_2_3; } public static long Func_0_1_2_2(long[,] arr2d_0_1_2_2) { vtstatic_0_1_2_2.a3_0_1_2_2 = -(sa - sb); VT_0_1_2_2_2 vt_0_1_2_2_2 = new VT_0_1_2_2_2(); vt_0_1_2_2_2.a3_0_1_2_2_2 = -sa / sb; CL_0_1_2_2_2 cl_0_1_2_2_2 = new CL_0_1_2_2_2(); int[,] arr2d_0_1_2_2_2 = new int[3, 11]; arr2d_0_1_2_2_2[2, 0] = sa - sb; double val_0_1_2_2_2 = Func_0_1_2_2_2(arr2d_0_1_2_2_2, vt_0_1_2_2_2, cl_0_1_2_2_2); VT_0_1_2_2_1 vt_0_1_2_2_1 = new VT_0_1_2_2_1(); vt_0_1_2_2_1.a0_0_1_2_2_1 = -sa / sb; vt_0_1_2_2_1.a1_0_1_2_2_1 = sa / sb; vt_0_1_2_2_1.a4_0_1_2_2_1 = sa - sb; vt_0_1_2_2_1.a5_0_1_2_2_1 = sa - sb; double val_0_1_2_2_1 = Func_0_1_2_2_1(vt_0_1_2_2_1); long retval_0_1_2_2 = Convert.ToInt64(((long)(Convert.ToInt32((Convert.ToInt32((val_0_1_2_2_1 - (val_0_1_2_2_2)) + vtstatic_0_1_2_2.a3_0_1_2_2))) - (long)(arr2d_0_1_2_2[2, 0])) - arr2d_0_1_2_2[2, 1])); Console.WriteLine("retval_0_1_2_2 is {0}", retval_0_1_2_2); return retval_0_1_2_2; } public static double Func_0_1_2_1(CL_0_1_2_1 cl_0_1_2_1, VT_0_1_2_1 vt_0_1_2_1) { VT_0_1_2_1_2 vt_0_1_2_1_2 = new VT_0_1_2_1_2(); vt_0_1_2_1_2.a1_0_1_2_1_2 = 1; vt_0_1_2_1_2.a4_0_1_2_1_2 = -(sa / sb); double val_0_1_2_1_2 = Func_0_1_2_1_2(vt_0_1_2_1_2); double val_0_1_2_1_1 = Func_0_1_2_1_1(); double retval_0_1_2_1 = Convert.ToDouble(((((vt_0_1_2_1.a1_0_1_2_1 + ((double)(cl_0_1_2_1.arr2d_0_1_2_1[2, 0] * (sa / sb)))) * vt_0_1_2_1.a1_0_1_2_1) + val_0_1_2_1_1) / (((double)(cl_0_1_2_1.arr2d_0_1_2_1[2, 0] * val_0_1_2_1_2)) - (vt_0_1_2_1.a3_0_1_2_1)))); Console.WriteLine("retval_0_1_2_1 is {0}", retval_0_1_2_1); return retval_0_1_2_1; } public static long Func_0_1_2(VT_0_1_2 vt_0_1_2) { CL_0_1_2_5 cl_0_1_2_5 = new CL_0_1_2_5(); cl_0_1_2_5.arr2d_0_1_2_5[2, 0] = sa * sb; double val_0_1_2_5 = Func_0_1_2_5(cl_0_1_2_5); long* a0_0_1_2_4 = stackalloc long[1]; *a0_0_1_2_4 = sa + sb; long val_0_1_2_4 = Func_0_1_2_4(a0_0_1_2_4); int val_0_1_2_3 = Func_0_1_2_3(); long[,] arr2d_0_1_2_2 = new long[3, 11]; arr2d_0_1_2_2[2, 0] = -sa * sb; arr2d_0_1_2_2[2, 1] = sa * (sa + sb); long val_0_1_2_2 = Func_0_1_2_2(arr2d_0_1_2_2); VT_0_1_2_1 vt_0_1_2_1 = new VT_0_1_2_1(); vt_0_1_2_1.a1_0_1_2_1 = -(sa * sb); vt_0_1_2_1.a3_0_1_2_1 = -sa + sb; CL_0_1_2_1 cl_0_1_2_1 = new CL_0_1_2_1(); cl_0_1_2_1.arr2d_0_1_2_1[2, 0] = 2L; double val_0_1_2_1 = Func_0_1_2_1(cl_0_1_2_1, vt_0_1_2_1); long retval_0_1_2 = Convert.ToInt64((long)(Convert.ToInt32((Convert.ToInt32(val_0_1_2_5 - ((val_0_1_2_3 * vt_0_1_2.a0_0_1_2))))) + (long)((((long)((long)(Convert.ToInt32(sa + sb) - (long)(val_0_1_2_2)) / val_0_1_2_1)) + val_0_1_2_4)))); Console.WriteLine("retval_0_1_2 is {0}", retval_0_1_2); return retval_0_1_2; } public static double Func_0_1_1() { double[,] arr2d_0_1_1 = new double[3, 11]; arr2d_0_1_1[2, 0] = 0.0; double retval_0_1_1 = Convert.ToDouble(arr2d_0_1_1[2, 0]); Console.WriteLine("retval_0_1_1 is {0}", retval_0_1_1); return retval_0_1_1; } public static double Func_0_1(long[] arr1d_0_1, VT_0_1 vt_0_1) { CL_0_1 cl_0_1 = new CL_0_1(); vtstatic_0_1.a2_0_1 = sa + sb; vtstatic_0_1.a3_0_1 = sa + sb; VT_0_1_2 vt_0_1_2 = new VT_0_1_2(); vt_0_1_2.a0_0_1_2 = -(sa + sb); long val_0_1_2 = Func_0_1_2(vt_0_1_2); double val_0_1_1 = Func_0_1_1(); double retval_0_1 = Convert.ToDouble((((((long)(val_0_1_2 / arr1d_0_1[0])) / (vtstatic_0_1.a3_0_1 * (sa + sb))) + val_0_1_1) * ((vt_0_1.a2_0_1 * (sa + sb)) * (cl_0_1.a1_0_1 - ((arr1d_0_1[0] / -(sa + sb))))))); Console.WriteLine("retval_0_1 is {0}", retval_0_1); return retval_0_1; } public static int Func_0(double[,] arr2d_0, VT_0 vt_0) { vtstatic_0.a2_0 = sa / sb; vtstatic_0.a3_0 = sa - sb; vtstatic_0.a4_0 = sa - sb; VT_0_1 vt_0_1 = new VT_0_1(); vt_0_1.a2_0_1 = sa + sb; vt_0_1.a3_0_1 = sa / sb; long[] arr1d_0_1 = new long[11]; arr1d_0_1[0] = 2L; double val_0_1 = Func_0_1(arr1d_0_1, vt_0_1); int retval_0 = Convert.ToInt32((Convert.ToInt32((Convert.ToInt32((val_0_1 - vtstatic_0.a3_0) + (vtstatic_0.a3_0 + (sa * sb)))) * (vtstatic_0.a4_0 / (((vt_0.a2_0 - (sb - sa)) * (vtstatic_0.a4_0 * sa * sb)) - (arr2d_0[2, 0])))))); Console.WriteLine("retval_0 is {0}", retval_0); return retval_0; } public static int Main() { sa = 10; sb = 5; vtstatic_0.a2_0 = sa + sb; vtstatic_0.a3_0 = sa * sb; vtstatic_0.a4_0 = sa - sb; VT_0 vt_0 = new VT_0(); vt_0.a2_0 = sa * sb; vt_0.a3_0 = sa + sb; vt_0.a4_0 = sa - sb; double[,] arr2d_0 = new double[3, 11]; arr2d_0[2, 0] = sa * sb; int retval; retval = Func_0(arr2d_0, vt_0); if (retval != 4858) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
35.544118
460
0.645997
[ "MIT" ]
CyberSys/coreclr-mono
tests/src/JIT/Directed/coverage/oldtests/cse2.cs
19,336
C#
/*********************************************************** Copyright (c) 2017-2018 Clicked, Inc. Licensed under the MIT license found in the LICENSE file in the Docs folder of the distributed package. ***********************************************************/ using UnityEngine; using UnityEngine.Assertions; using System; using System.Collections; using System.Runtime.InteropServices; [ExecuteInEditMode] public abstract class AirVRCameraRig : MonoBehaviour { private const int InvalidPlayerID = -1; [DllImport(AirVRServerPlugin.Name)] private static extern void onairvr_GetViewNumber(int playerID, double timeStamp, float orientationX, float orientationY, float orientationZ, float orientationW, out int viewNumber); [DllImport(AirVRServerPlugin.Name)] private static extern IntPtr onairvr_InitStreams_RenderThread_Func(); [DllImport(AirVRServerPlugin.Name)] private static extern IntPtr onairvr_EncodeVideoFrame_RenderThread_Func(); [DllImport(AirVRServerPlugin.Name)] private static extern IntPtr onairvr_ResetStreams_RenderThread_Func(); [DllImport(AirVRServerPlugin.Name)] private static extern IntPtr onairvr_CleanupStreams_RenderThread_Func(); [DllImport(AirVRServerPlugin.Name)] private static extern bool onairvr_IsStreaming(int playerID); [DllImport(AirVRServerPlugin.Name)] private static extern IntPtr onairvr_AdjustBitRate_RenderThread_Func(); [DllImport(AirVRServerPlugin.Name)] private static extern void onairvr_RecenterPose(int playerID); [DllImport(AirVRServerPlugin.Name)] private static extern void onairvr_EnableNetworkTimeWarp(int playerID, bool enable); [DllImport(AirVRServerPlugin.Name)] private static extern void onairvr_SendCameraClipPlanes(int playerID, float nearClip, float farClip); [DllImport(AirVRServerPlugin.Name)] private static extern void onairvr_Disconnect(int playerID); private Vector3 _cameraPosition = Vector3.zero; private Quaternion _cameraOrientation = Quaternion.identity; private AirVRClientConfig _config; private bool _mediaStreamJustStopped; private int _viewNumber; private bool _encodeVideoFrameRequested; private void enableCameras() { foreach (Camera cam in cameras) { cam.enabled = true; } } private void disableCameras() { foreach (Camera cam in cameras) { cam.enabled = false; } } private void initializeCamerasForMediaStream() { Assert.IsNotNull(_config); setupCamerasOnBound(_config); } private void startToRenderCamerasForMediaStream() { enableCameras(); onStartRender(); _mediaStreamJustStopped = false; StartCoroutine(CallPluginEndOfFrame()); } private Transform findDirectChildByName(Transform parent, string name) { Transform[] xforms = gameObject.GetComponentsInChildren<Transform>(); foreach (Transform xform in xforms) { if (xform.parent == parent && xform.gameObject.name.Equals(name)) { return xform; } } return null; } private void Awake() { ensureGameObjectIntegrity(); if (Application.isPlaying == false) { return; } AirVRServer.LoadOnce(FindObjectOfType<AirVRServerInitParams>()); disableCameras(); AirVRCameraRigManager.managerOnCurrentScene.RegisterCameraRig(this); AirVRCameraRigManager.managerOnCurrentScene.eventDispatcher.MessageReceived += onAirVRMessageReceived; playerID = InvalidPlayerID; inputStream = new AirVRServerInputStream(); inputStream.owner = this; } private void Start() { ensureGameObjectIntegrity(); if (Application.isPlaying == false) { return; } init(); } private void Update() { ensureGameObjectIntegrity(); if (Application.isPlaying == false) { return; } } // Events called by AirVRCameraRigManager to guarantee the update execution order internal void OnUpdate() { inputStream.UpdateReceivers(); } internal void OnLateUpdate() { if (mediaStream != null && _mediaStreamJustStopped == false && _encodeVideoFrameRequested) { Assert.IsTrue(isBoundToClient); double timeStamp = 0.0; inputStream.GetTransform(AirVRInputDeviceName.HeadTracker, (byte)AirVRHeadTrackerKey.Transform, ref timeStamp, ref _cameraPosition, ref _cameraOrientation); onairvr_GetViewNumber(playerID, timeStamp, _cameraOrientation.x, _cameraOrientation.y, _cameraOrientation.z, _cameraOrientation.w, out _viewNumber); updateCameraTransforms(_config, _cameraPosition, _cameraOrientation); mediaStream.GetNextFramebufferTexturesAsRenderTargets(cameras); } inputStream.UpdateSenders(); } private void OnDestroy() { if (Application.isPlaying == false) { return; } if (AirVRCameraRigManager.CheckIfExistManagerOnCurrentScene()) { AirVRCameraRigManager.managerOnCurrentScene.eventDispatcher.MessageReceived -= onAirVRMessageReceived; AirVRCameraRigManager.managerOnCurrentScene.UnregisterCameraRig(this); } } private void onAirVRMessageReceived(AirVRMessage message) { AirVRServerMessage serverMessage = message as AirVRServerMessage; int srcPlayerID = serverMessage.source.ToInt32(); if (srcPlayerID != playerID) { return; } if (serverMessage.IsMediaStreamEvent()) { if (serverMessage.Name.Equals(AirVRServerMessage.NameInitialized)) { onAirVRMediaStreamInitialized(serverMessage); } else if (serverMessage.Name.Equals(AirVRServerMessage.NameStarted)) { onAirVRMediaStreamStarted(serverMessage); } else if (serverMessage.Name.Equals(AirVRServerMessage.NameEncodeVideoFrame)) { onAirVRMediaStreamEncodeVideoFrame(serverMessage); } else if (serverMessage.Name.Equals(AirVRServerMessage.NameStopped)) { onAirVRMediaStreamStopped(serverMessage); } else if (serverMessage.Name.Equals(AirVRServerMessage.NameCleanupUp)) { onAirVRMediaStreamCleanedUp(serverMessage); } } else if (serverMessage.IsInputStreamEvent()) { if (serverMessage.Name.Equals(AirVRServerMessage.NameRemoteInputDeviceRegistered)) { onAirVRInputStreamRemoteInputDeviceRegistered(serverMessage); } else if (serverMessage.Name.Equals(AirVRServerMessage.NameRemoteInputDeviceUnregistered)) { onAirVRInputStreamRemoteInputDeviceUnregistered(serverMessage); } } } private void onAirVRMediaStreamInitialized(AirVRServerMessage message) { Assert.IsNull(mediaStream); initializeCamerasForMediaStream(); onairvr_SendCameraClipPlanes(playerID, cameras[0].nearClipPlane, cameras[0].farClipPlane); mediaStream = new AirVRServerMediaStream(playerID, _config, cameras.Length); GL.IssuePluginEvent(onairvr_InitStreams_RenderThread_Func(), AirVRServerPlugin.RenderEventArg((uint)playerID)); inputStream.Init(); } private void onAirVRMediaStreamStarted(AirVRServerMessage message) { startToRenderCamerasForMediaStream(); inputStream.Start(); } private void onAirVRMediaStreamEncodeVideoFrame(AirVRServerMessage message) { _encodeVideoFrameRequested = true; } private void onAirVRMediaStreamStopped(AirVRServerMessage message) { onStopRender(); disableCameras(); _mediaStreamJustStopped = true; // StopCoroutine(_CallPluginEndOfFrame) executes the routine one more in the next frame after the call. // so use a flag to completely stop the routine. GL.IssuePluginEvent(onairvr_ResetStreams_RenderThread_Func(), AirVRServerPlugin.RenderEventArg((uint)playerID)); inputStream.Stop(); } private void onAirVRMediaStreamCleanedUp(AirVRServerMessage message) { Assert.IsTrue(_mediaStreamJustStopped); Assert.IsNotNull(mediaStream); inputStream.Cleanup(); GL.IssuePluginEvent(onairvr_CleanupStreams_RenderThread_Func(), AirVRServerPlugin.RenderEventArg((uint)playerID)); mediaStream.Destroy(); mediaStream = null; foreach (Camera cam in cameras) { cam.targetTexture = null; } } private void onAirVRInputStreamRemoteInputDeviceRegistered(AirVRServerMessage message) { Assert.IsTrue(string.IsNullOrEmpty(message.DeviceName) == false); inputStream.HandleRemoteInputDeviceRegistered(message.DeviceName, (byte)message.DeviceID); } private void onAirVRInputStreamRemoteInputDeviceUnregistered(AirVRServerMessage message) { inputStream.HandleRemoteInputDeviceUnregistered((byte)message.DeviceID); } private IEnumerator CallPluginEndOfFrame() { yield return new WaitForEndOfFrame(); Assert.IsNotNull(mediaStream); GL.IssuePluginEvent(onairvr_EncodeVideoFrame_RenderThread_Func(), AirVRServerPlugin.RenderEventArg((uint)playerID, (uint)_viewNumber, (uint)mediaStream.currentFramebufferIndex)); // the first render event while (_mediaStreamJustStopped == false) { yield return new WaitForEndOfFrame(); if (_mediaStreamJustStopped) { yield break; } else if (_encodeVideoFrameRequested) { Assert.IsNotNull(mediaStream); GL.IssuePluginEvent(onairvr_EncodeVideoFrame_RenderThread_Func(), AirVRServerPlugin.RenderEventArg((uint)playerID, (uint)_viewNumber, (uint)mediaStream.currentFramebufferIndex)); _encodeVideoFrameRequested = false; } } } protected Transform getOrCreateGameObject(string name, Transform parent) { Transform result = findDirectChildByName(parent, name); if (result == null) { result = new GameObject(name).transform; result.parent = parent; result.localPosition = Vector3.zero; result.localRotation = Quaternion.identity; result.localScale = Vector3.one; } return result; } protected abstract void ensureGameObjectIntegrity(); protected virtual void init() { } protected abstract void setupCamerasOnBound(AirVRClientConfig config); protected virtual void onStartRender() { } protected virtual void onStopRender() { } protected abstract void updateCameraTransforms(AirVRClientConfig config, Vector3 centerEyePosition, Quaternion centerEyeOrientation); internal int playerID { get; private set; } internal AirVRServerInputStream inputStream { get; private set; } public AirVRServerMediaStream mediaStream { get; private set; } internal bool isStreaming { get { return onairvr_IsStreaming(playerID); } } internal abstract Matrix4x4 clientSpaceToWorldMatrix { get; } internal abstract Transform headPose { get; } internal abstract Camera[] cameras { get; } internal void BindPlayer(int playerID) { Assert.IsFalse(isBoundToClient); Assert.IsNull(_config); this.playerID = playerID; _config = AirVRServerPlugin.GetConfig(playerID); Assert.IsNotNull(_config); } internal void BindPlayer(int playerID, AirVRServerMediaStream mediaStream, AirVRServerInputStream inputStream) { BindPlayer(playerID); this.mediaStream = mediaStream; this.inputStream = inputStream; this.inputStream.owner = this; initializeCamerasForMediaStream(); if (isStreaming) { startToRenderCamerasForMediaStream(); } } internal void UnbindPlayer() { Assert.IsTrue(isBoundToClient); playerID = InvalidPlayerID; _config = null; } internal void PreHandOverStreams() { Assert.IsTrue(isBoundToClient); inputStream.DisableAllDeviceFeedbacks(); } internal void PostHandOverStreams() { foreach (Camera cam in cameras) { cam.targetTexture = null; } } internal void EnableNetworkTimeWarp(bool enable) { if (isBoundToClient) { onairvr_EnableNetworkTimeWarp(playerID, enable); } } public AirVRClientType type { get { return GetType() == typeof(AirVRStereoCameraRig) ? AirVRClientType.Stereoscopic : AirVRClientType.Monoscopic; } } public bool isBoundToClient { get { return playerID >= 0; } } public AirVRClientConfig GetConfig() { if (isBoundToClient) { return _config; } return null; } public void AdjustBitrate(uint bitrateInKbps) { if (isBoundToClient) { GL.IssuePluginEvent(onairvr_AdjustBitRate_RenderThread_Func(), AirVRServerPlugin.RenderEventArg((uint)playerID, bitrateInKbps)); } } public void RecenterPose() { if (isBoundToClient) { onairvr_RecenterPose(playerID); } } public void Disconnect() { if (isBoundToClient) { onairvr_Disconnect(playerID); } } }
34.252525
215
0.676792
[ "MIT" ]
kteem/onairvr-server-for-unity
Assets/onAirVR/Server/Scripts/AirVRCameraRig.cs
13,566
C#
using Amazon.DynamoDBv2.DataModel; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Comp306Lab3MovieApp.Models { [DynamoDBTable("Reviews")] public class Review { public string ReviewID { get; set; } [Required(ErrorMessage = "Please enter Title!")] public string Title { get; set; } [Required(ErrorMessage = "Please enter Review!")] public string ReviewDescription { get; set; } public int MovieId { get; set; } public int MovieRating { get; set; } public Movie Movie { get; set; } public string UserEmail { get; set; } } }
27.615385
57
0.66156
[ "MIT" ]
Srashi25/MovieWeb
Comp306Lab3MovieApp/Models/Review.cs
720
C#
// Copyright 2020 New Relic, Inc. All rights reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using NewRelic.Agent.IntegrationTestHelpers.JsonConverters; using Newtonsoft.Json; namespace NewRelic.Agent.IntegrationTestHelpers.Models { [JsonConverter(typeof(JsonArrayConverter))] public class ErrorEventPayload { [JsonArrayIndex(Index = 0)] public readonly object AgentRunId; [JsonArrayIndex(Index = 1)] public readonly ErrorEventAdditions Additions; [JsonArrayIndex(Index = 2)] public IList<ErrorEventEvents> Events; public ErrorEventPayload() { } public ErrorEventPayload(long agentRunId, ErrorEventAdditions additions, IList<ErrorEventEvents> events) { AgentRunId = agentRunId; Additions = additions; Events = events; } } public class ErrorEventAdditions { [JsonProperty("reservoir_size")] public readonly uint ReservoirSize; [JsonProperty("events_seen")] public readonly uint EventsSeen; public ErrorEventAdditions() { } public ErrorEventAdditions(uint reservoirSize, uint eventsSeen) { ReservoirSize = reservoirSize; EventsSeen = eventsSeen; } } [JsonConverter(typeof(JsonArrayConverter))] public class ErrorEventEvents { [JsonArrayIndex(Index = 0)] public readonly IDictionary<string, object> IntrinsicAttributes; [JsonArrayIndex(Index = 1)] public readonly IDictionary<string, object> UserAttributes; [JsonArrayIndex(Index = 2)] public readonly IDictionary<string, object> AgentAttributes; public ErrorEventEvents() { } public ErrorEventEvents(IDictionary<string, object> intrinsicAttributes, IDictionary<string, object> userAttributes, IDictionary<string, object> agentAttributes) { IntrinsicAttributes = intrinsicAttributes; UserAttributes = userAttributes; AgentAttributes = agentAttributes; } public IDictionary<string, object> GetByType(EventAttributeType attributeType) { IDictionary<string, object> attributes; switch (attributeType) { case EventAttributeType.Intrinsic: attributes = IntrinsicAttributes; break; case EventAttributeType.Agent: attributes = AgentAttributes; break; case EventAttributeType.User: attributes = UserAttributes; break; default: throw new NotImplementedException(); } return attributes ?? new Dictionary<string, object>(); } } }
30.231579
169
0.630223
[ "Apache-2.0" ]
JoshuaColeman/newrelic-dotnet-agent
tests/Agent/IntegrationTests/IntegrationTestHelpers/Models/ErrorEvent.cs
2,872
C#
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("ecsc")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("jonathan")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
34.892857
81
0.743091
[ "MIT" ]
jonathanvdc/ecsc
src/ecsc/Properties/AssemblyInfo.cs
979
C#
// *********************************************************************** // Assembly : MPT.CSI.OOAPI // Author : Mark Thomas // Created : 11-18-2018 // // Last Modified By : Mark Thomas // Last Modified On : 11-20-2018 // *********************************************************************** // <copyright file="MassSource.cs" company=""> // Copyright © 2018 // </copyright> // <summary></summary> // *********************************************************************** using MPT.CSI.API.Core.Program.ModelBehavior.Definition.Property; using MPT.CSI.API.Core.Support; using MPT.CSI.OOAPI.Core.Program.Model.ProjectSettings; namespace MPT.CSI.OOAPI.Core.Program.Model.Definitions.Masses { /// <summary> /// Represents the mass source in the application. /// </summary> public class MassSource { #if BUILD_ETABS2015 || BUILD_ETABS2016 || BUILD_ETABS2017 /// <summary> /// The material properties API object. /// </summary> protected static MaterialProperties _materialProperties = Registry.ProgramDefinitions?.Properties?.MaterialProperties; #else /// <summary> /// The material properties API object. /// </summary> protected static MassSource _materialProperties = Registry.ProgramDefinitions?.MassSource; #endif /// <summary> /// The mass source name. /// </summary> /// <value>The name.</value> public string Name {get; protected set; } /// <summary> /// True: Element self mass is included in the mass. /// </summary> /// <value><c>true</c> if this instance is from elements; otherwise, <c>false</c>.</value> public bool IsFromElements { get; protected set; } /// <summary> /// True: Assigned masses are included in the mass. /// </summary> /// <value><c>true</c> if this instance is from masses; otherwise, <c>false</c>.</value> public bool IsFromMasses { get; protected set; } /// <summary> /// True: Specified load patterns are included in the mass. /// </summary> /// <value><c>true</c> if this instance is from loads; otherwise, <c>false</c>.</value> public bool IsFromLoads { get; protected set; } #if !BUILD_ETABS2015 && !BUILD_ETABS2016 && !BUILD_ETABS2017 /// <summary> /// True: Mass source is the default mass source. /// Only one mass source can be the default mass source so when this assignment is True all other mass sources are automatically set to have the IsDefault flag False. /// </summary> /// <value><c>true</c> if this instance is default; otherwise, <c>false</c>.</value> public bool IsDefault { get; protected set; } #endif /// <summary> /// Load pattern names specified for the mass source. /// </summary> /// <value>The names load patterns.</value> public string[] NamesLoadPatterns { get; protected set; } /// <summary> /// Load pattern multipliers specified for the mass source. /// </summary> /// <value>The scale factors.</value> public double[] ScaleFactors { get; protected set; } /// <summary> /// Initializes a new instance of the <see cref="MassSource"/> class. /// </summary> /// <param name="name">The name.</param> public MassSource(string name) { Name = name; } /// <summary> /// Retrieves the mass source data for an existing mass source. /// </summary> /// <param name="app">The application.</param> /// <exception cref="CSiException"><see cref="CSiApiBase.API_DEFAULT_ERROR_CODE" /></exception> public void FillMassSource() { #if BUILD_ETABS2015 || BUILD_ETABS2016 || BUILD_ETABS2017 _materialProperties.GetMassSource( out var isMassFromElements, out var isMassFromMasses, out var isMassFromLoads, out var namesLoadPatterns, out var scaleFactors); #else _materialProperties.GetMassSource( out var nameMassSource, out var isMassFromElements, out var isMassFromMasses, out var isMassFromLoads, out var isDefault, out var namesLoadPatterns, out var scaleFactors); Name = nameMassSource; IsDefault = isDefault; #endif IsFromElements = isMassFromElements; IsFromMasses = isMassFromMasses; IsFromLoads = isMassFromLoads; NamesLoadPatterns = namesLoadPatterns; ScaleFactors = scaleFactors; } /// <summary> /// Adds a new mass source to the model or reinitializes an existing mass source. /// </summary> /// <exception cref="CSiException"><see cref="CSiApiBase.API_DEFAULT_ERROR_CODE" /></exception> public void SetMassSource() { #if BUILD_ETABS2015 || BUILD_ETABS2016 || BUILD_ETABS2017 _materialProperties.SetMassSource( IsFromElements, IsFromMasses, IsFromLoads, NamesLoadPatterns, ScaleFactors); #else _materialProperties.SetMassSource( Name, IsFromElements, IsFromMasses, IsFromLoads, IsDefault, NamesLoadPatterns, ScaleFactors); #endif } } }
36.895425
174
0.55961
[ "MIT" ]
MarkPThomas/MPT.Net
MPT/CSI/API/MPT.CSI.OOAPI.EndToEndTests/Core/Program/Model/Definitions/Masses/MassSource.cs
5,648
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Networking.Connectivity; using Windows.Security.ExchangeActiveSyncProvisioning; namespace IoTHelpers.Boards { public enum DeviceType { RaspberryPi2, RaspberryPi3, MinnowBoardMax, DragonBoard410c, Colibri, Joule, GenericBoard, Unknown }; public static class DeviceInformation { public static DeviceType Type { get; } = DeviceType.Unknown; public static string DeviceName { get; } public static Guid Id { get; } public static string ProductName { get; } static DeviceInformation() { var deviceInfo = new EasClientDeviceInformation(); Id = deviceInfo.Id; DeviceName = deviceInfo.FriendlyName; ProductName = deviceInfo.SystemProductName; if (ProductName.IndexOf("MinnowBoard", StringComparison.OrdinalIgnoreCase) >= 0) { Type = DeviceType.MinnowBoardMax; } else if (ProductName.IndexOf("Raspberry", StringComparison.OrdinalIgnoreCase) >= 0) { if (ProductName.IndexOf("Pi 3", StringComparison.OrdinalIgnoreCase) >= 0) Type = DeviceType.RaspberryPi3; else Type = DeviceType.RaspberryPi2; } else if (ProductName == "SBC") { Type = DeviceType.DragonBoard410c; } else if (ProductName.IndexOf("Cardhu", StringComparison.OrdinalIgnoreCase) >= 0) { Type = DeviceType.Colibri; } else if (ProductName.IndexOf("Broxton M", StringComparison.OrdinalIgnoreCase) >= 0) { Type = DeviceType.Joule; } else { Type = DeviceType.GenericBoard; } } public static string GetIpAddress() { var icp = NetworkInformation.GetInternetConnectionProfile(); if (icp?.NetworkAdapter != null) { var hostname = NetworkInformation.GetHostNames() .SingleOrDefault(hn => hn.IPInformation?.NetworkAdapter?.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId); return hostname?.CanonicalName; } return null; } } }
28.931034
138
0.564561
[ "MIT" ]
Dot-and-Net/IoTHelpers
Src/IoTHelpers/Boards/DeviceInformation.cs
2,519
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using IAGrim.Database; namespace IAGrim.UI.Filters { public partial class Classes : UserControl { private readonly Dictionary<string, FirefoxCheckBox> _classes; private readonly IList<ItemTag> _classTags; public Classes(IList<ItemTag> classTags) { InitializeComponent(); _classes = new Dictionary<string, FirefoxCheckBox>(); _classTags = classTags; Load += Classes_Load; } public List<string> DesiredClasses { get { return _classes.Keys.Where(key => _classes[key].Checked).ToList(); } } public void Classes_Load(object sender, EventArgs e) { // 3,4+n*33 // 3,37 // 3,70 var cbNum = 1; // Handle hardcoded classes foreach (var c in classesPanelBox.Controls) { if (c is FirefoxCheckBox cb) { cbNum++; } } // TODO: Localize hardcoded classes and skip adding them if they exist _classes["class01"] = cbSoldier; _classes["class02"] = cbDemolitionist; _classes["class03"] = cbOccultist; _classes["class04"] = cbNightblade; _classes["class05"] = cbArcanist; _classes["class06"] = cbShaman; _classes["class07"] = cbInquisitor; _classes["class08"] = cbNecromancer; _classes["class09"] = cbOathkeeper; // Hardcoded classes from the base game -- Helps a bit with 4k scaling to not create these dynamically. var prefilled = new[] { "class01", "class02", "class03", "class04", "class05", "class06", "class07", "class08", "class09" }; int yOffsetHeight = cbDemolitionist.Location.Y - cbSoldier.Location.Y; int cbHeight = cbDemolitionist.Height; foreach (var tag in _classTags) { var translationTag = $"{tag.Tag.ToLowerInvariant()}"; if (!prefilled.Contains(translationTag)) { var cb = new FirefoxCheckBox { Size = new Size {Height = cbHeight, Width = classesPanelBox.Size.Width - 15}, Tag = translationTag, Text = tag.Name, Location = new Point {X = 3, Y = 3 + cbNum * yOffsetHeight} }; _classes[tag.Tag] = cb; classesPanelBox.Controls.Add(cb); cbNum++; } else if (_classes.ContainsKey(tag.Tag)) { _classes[tag.Tag].Text = tag.Name; } } classesPanelBox.Size = new Size { Height = 10 + cbNum * yOffsetHeight, Width = classesPanelBox.Size.Width }; } } }
36.309524
115
0.523607
[ "MIT" ]
211847750/iagd
IAGrim/UI/Filters/Classes.cs
3,052
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.GoogleNative.ToolResults.V1Beta3.Outputs { /// <summary> /// Testing timing break down to know phases. /// </summary> [OutputType] public sealed class TestTimingResponse { /// <summary> /// How long it took to run the test process. - In response: present if previously set. - In create/update request: optional /// </summary> public readonly Outputs.DurationResponse TestProcessDuration; [OutputConstructor] private TestTimingResponse(Outputs.DurationResponse testProcessDuration) { TestProcessDuration = testProcessDuration; } } }
30.774194
132
0.686583
[ "Apache-2.0" ]
AaronFriel/pulumi-google-native
sdk/dotnet/ToolResults/V1Beta3/Outputs/TestTimingResponse.cs
954
C#
// Copyright (c) DITUS INC. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for // details. namespace Ditus.Api.Documentation { using System; /// <summary> /// Specifies the summary description for a RESTful web service method. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class RestMethodSummaryAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="RestMethodSummaryAttribute"/> class. /// </summary> /// <param name="summary">The summary.</param> public RestMethodSummaryAttribute(string summary) { this.Summary = summary; } /// <summary> /// Gets a summary of the method. /// </summary> /// <returns>The summary.</returns> public string Summary { get; } } }
26.757576
90
0.631937
[ "MIT" ]
ditus-software/ditus-api-documentation
src/RestMethodSummaryAttribute.cs
883
C#
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: SatelliteContractVersionAttribute ** ** <OWNER>[....]</OWNER> ** ** ** Purpose: Specifies which version of a satellite assembly ** the ResourceManager should ask for. ** ** ===========================================================*/ namespace System.Resources { using System; using System.Diagnostics.Contracts; [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class SatelliteContractVersionAttribute : Attribute { private String _version; public SatelliteContractVersionAttribute(String version) { if (version == null) throw new ArgumentNullException("version"); Contract.EndContractBlock(); _version = version; } public String Version { get { return _version; } } } }
25.690476
70
0.549583
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/clr/src/BCL/system/resources/satellitecontractversionattribute.cs
1,079
C#
using System; namespace LiteDB.Shell.Commands { [Help( Name = "version", Syntax = "ver", Description = "Show LiteDB version" )] internal class Version : IShellCommand { public bool IsCommand(StringScanner s) { return s.Scan(@"ver(sion)?$").Length > 0; } public void Execute(StringScanner s, Env env) { var assembly = typeof(ILiteDatabase).Assembly.GetName(); env.Display.WriteLine(assembly.FullName); } } }
22.416667
68
0.555762
[ "MIT" ]
7eXx/LiteDB
LiteDB.Shell/Commands/Version.cs
540
C#
using System; namespace RefaceCore.HttpProxy.Interceptors { public class OriginalMethod : IOriginalMethod { private Func<object[], object> invoker; public OriginalMethod(Func<object[], object> invoker) { this.invoker = invoker; } public object Execute(object[] args) { return invoker(args); } } }
19.6
61
0.581633
[ "MIT" ]
ShimizuShiori/RefaceCore.HttpProxy
src/Interceptors/OriginalMethod.cs
392
C#
using Discord; using Discord.Commands; using NadekoBot.Classes; using System.Text; using System.Timers; using static NadekoBot.Modules.Games.Commands.Bomberman; namespace NadekoBot.Modules.Games.Commands { class Bomberman : DiscordCommand { public Field[,] board = new Field[15, 15]; public BombermanPlayer[] players = new BombermanPlayer[4]; public Channel gameChannel = null; public Message godMsg = null; public int curI = 5; public int curJ = 5; public Bomberman(DiscordModule module) : base(module) { for (int i = 0; i < 15; i++) { for (int j = 0; j < 15; j++) { board[i, j] = new Field(); } } NadekoBot.Client.MessageReceived += (s, e) => { if (e.Channel != gameChannel || e.User.Id == NadekoBot.Client.CurrentUser.Id) return; if (e.Message.Text == "w") { board[curI - 1, curJ] = board[curI--, curJ]; board[curI + 1, curJ].player = null; } else if (e.Message.Text == "s") { board[curI + 1, curJ] = board[curI++, curJ]; board[curI - 1, curJ].player = null; } else if (e.Message.Text == "a") { board[curI, curJ - 1] = board[curI, curJ--]; board[curI, curJ + 1].player = null; } else if (e.Message.Text == "d") { board[curI, curJ + 1] = board[curI, curJ++]; board[curI, curJ - 1].player = null; } e.Message.Delete(); }; var t = new Timer(); t.Elapsed += async (s, e) => { if (gameChannel == null) return; var boardStr = new StringBuilder(); for (int i = 0; i < 15; i++) { for (int j = 0; j < 15; j++) { boardStr.Append(board[i, j].ToString()); } boardStr.AppendLine(); } if (godMsg.Id != 0) await godMsg.Edit(boardStr.ToString()).ConfigureAwait(false); }; t.Interval = 1000; t.Start(); } internal override void Init(CommandGroupBuilder cgb) { //cgb.CreateCommand(Module.Prefix + "bomb") // .Description("Bomberman start") // .Do(async e => // { // if (gameChannel != null) // return; // godMsg = await e.Channel.SendMessage("GAME START IN 1 SECOND....").ConfigureAwait(false); // gameChannel = e.Channel; // players[0] = new BombermanPlayer // { // User = e.User, // }; // board[5, 5].player = players[0]; // }); } public class BombermanPlayer { public User User = null; public string Icon = "👳"; internal void MoveLeft() { } } } internal struct Field { public BombermanPlayer player; public override string ToString() => player?.Icon ?? "⬜"; } }
28.722222
111
0.41144
[ "MIT" ]
013164515/V
Modules/Games/Commands/Bomberman.cs
3,626
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.Payroll { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Get_Tax_Document_Deliveries_ResponseType : INotifyPropertyChanged { private Unique_IdentifierObjectType[] request_ReferencesField; private Tax_Document_Delivery_Request_CriteriaType request_CriteriaField; private Response_FilterType response_FilterField; private Tax_Document_Delivery_Response_GroupType response_GroupField; private Response_ResultsType response_ResultsField; private Tax_Document_DeliveryType[] response_DataField; private string versionField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlArray(Order = 0), XmlArrayItem("Tax_Document_Delivery_Reference", IsNullable = false)] public Unique_IdentifierObjectType[] Request_References { get { return this.request_ReferencesField; } set { this.request_ReferencesField = value; this.RaisePropertyChanged("Request_References"); } } [XmlElement(Order = 1)] public Tax_Document_Delivery_Request_CriteriaType Request_Criteria { get { return this.request_CriteriaField; } set { this.request_CriteriaField = value; this.RaisePropertyChanged("Request_Criteria"); } } [XmlElement(Order = 2)] public Response_FilterType Response_Filter { get { return this.response_FilterField; } set { this.response_FilterField = value; this.RaisePropertyChanged("Response_Filter"); } } [XmlElement(Order = 3)] public Tax_Document_Delivery_Response_GroupType Response_Group { get { return this.response_GroupField; } set { this.response_GroupField = value; this.RaisePropertyChanged("Response_Group"); } } [XmlElement(Order = 4)] public Response_ResultsType Response_Results { get { return this.response_ResultsField; } set { this.response_ResultsField = value; this.RaisePropertyChanged("Response_Results"); } } [XmlArray(Order = 5), XmlArrayItem("Tax_Document_Delivery", IsNullable = false)] public Tax_Document_DeliveryType[] Response_Data { get { return this.response_DataField; } set { this.response_DataField = value; this.RaisePropertyChanged("Response_Data"); } } [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string version { get { return this.versionField; } set { this.versionField = value; this.RaisePropertyChanged("version"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
22.021277
136
0.736232
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.Payroll/Get_Tax_Document_Deliveries_ResponseType.cs
3,105
C#
/* * _____ ______ * /_ / ____ ____ ____ _________ / __/ /_ * / / / __ \/ __ \/ __ \/ ___/ __ \/ /_/ __/ * / /__/ /_/ / / / / /_/ /\_ \/ /_/ / __/ /_ * /____/\____/_/ /_/\__ /____/\____/_/ \__/ * /____/ * * Authors: * 钟峰(Popeye Zhong) <zongsoft@qq.com> * * Copyright (C) 2015-2017 Zongsoft Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.Collections.Generic; using Zongsoft.Data; using Zongsoft.Services; using Zongsoft.Security.Membership; using Zongsoft.Community.Models; namespace Zongsoft.Community.Services { public class UserService : DataService<UserProfile> { #region 成员字段 private string _basePath; #endregion #region 构造函数 public UserService(Zongsoft.Services.IServiceProvider serviceProvider) : base(serviceProvider) { } #endregion #region 公共属性 public string BasePath { get { return _basePath; } set { if(string.IsNullOrWhiteSpace(value)) throw new ArgumentNullException(); _basePath = value.Trim(); } } [ServiceDependency(IsRequired = true)] public IUserProvider UserProvider { get; set; } #endregion #region 公共方法 public IEnumerable<IHistory> GetHistories(uint userId, Paging paging = null) { if(userId == 0) userId = this.Credential.User.UserId; return this.DataAccess.Select<IHistory>(Condition.Equal("UserId", userId), "Thread", paging); } public int GetMessageTotalCount(uint userId = 0) { if(userId == 0) userId = this.Credential.User.UserId; return this.DataAccess.Count<Message.MessageUser>(Condition.Equal("UserId", userId)); } public int GetMessageUnreadCount(uint userId = 0) { if(userId == 0) userId = this.Credential.User.UserId; return this.DataAccess.Count<Message.MessageUser>(Condition.Equal("UserId", userId) & Condition.Equal("IsRead", false)); } public IEnumerable<Message> GetMessages(uint userId = 0, bool? isRead = null, Paging paging = null) { if(userId == 0) userId = this.Credential.User.UserId; var conditions = ConditionCollection.And(Condition.Equal("UserId", userId)); if(isRead.HasValue) conditions.Add(Condition.Equal("IsRead", isRead.Value)); return this.DataAccess.Select<Message.MessageUser>(conditions, "Message", paging).Select(p => p.Message); } public bool SetStatus(uint userId, UserStatus status) { return this.UserProvider.SetStatus(userId, status); } public bool SetAvatar(uint userId, string avatar) { return this.DataAccess.Update(this.Name, new { Avatar = avatar }, Condition.Equal(nameof(UserProfile.UserId), userId)) > 0; } public bool SetPhotoPath(uint userId, string path) { return this.DataAccess.Update(this.Name, new { PhotoPath = path }, Condition.Equal(nameof(UserProfile.UserId), userId)) > 0; } #endregion #region 重写方法 protected override UserProfile OnGet(ICondition condition, ISchema schema, IDictionary<string, object> states, out IPageable pageable) { //调用基类同名方法 var profile = base.OnGet(condition, schema, states, out pageable); if(profile == null) return null; return profile; } protected override int OnInsert(IDataDictionary<UserProfile> data, ISchema schema, IDictionary<string, object> states) { //调用基类同名方法(新增用户配置信息) if(base.OnInsert(data, schema, states) > 0) { var user = Model.Build<IUser>(u => { u.UserId = data.GetValue(p => p.UserId); u.Name = data.GetValue(p => p.Name); }); //默认设置用户状态为可用 user.Status = UserStatus.Active; //如果未显式指定用户的命名空间,则使用当前用户的命名空间 if(string.IsNullOrWhiteSpace(user.Namespace)) { user.Namespace = this.Credential.User.Namespace; } //创建基础用户账户 if(!this.UserProvider.Create(user, user.Name.Trim().ToLowerInvariant())) throw new InvalidOperationException($"The '{user.Name}' user create failed."); //更新用户编号 data.SetValue(p => p.UserId, user.UserId); } return 1; } protected override int OnUpdate(IDataDictionary<UserProfile> data, ICondition condition, ISchema schema, IDictionary<string, object> states) { //如果没有指定用户编号或指定的用户编号为零,则显式指定为当前用户编号 if(!data.TryGetValue(p => p.UserId, out var userId) || userId == 0) data.SetValue(p => p.UserId, userId = this.Credential.User.UserId); //调用基类同名方法 return base.OnUpdate(data, condition, schema, states); } #endregion #region 文件路径 public string GetFilePath(uint userId, string name) { if(string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name)); if(string.Equals(name, "avatar", StringComparison.OrdinalIgnoreCase) || string.Equals(name, "photo", StringComparison.OrdinalIgnoreCase)) return Zongsoft.IO.Path.Combine(_basePath, name.Trim() + "-" + userId.ToString()); throw new ArgumentNullException($"Invalid '{name}' value of the name argument."); } #endregion } }
27.39801
142
0.68531
[ "Apache-2.0" ]
Zongsoft/Zongsoft.Community
src/Services/UserService.cs
5,799
C#
namespace MongoSignalR.Backplane.Sample; public class AppUrl { public AppUrl(string url) { Url = new Uri(url); } public Uri Url { get; } public override string ToString() { return Url.ToString(); } }
15.4375
41
0.591093
[ "MIT" ]
gottscj/Mongo.SignalR.Backplane
src/MongoSignalR.Backplane.Sample/AppUrl.cs
249
C#
 using System; using System.Linq; using Foundation; namespace Microsoft.PlatformChannels { public partial class ChannelService { internal void Initialize() { // TODO: selector invoke } } }
15.866667
39
0.617647
[ "MIT" ]
Redth/Microsoft.Maui.Platform.Channels
Microsoft.PlatformChannels/Platforms/MacCatalyst/ChannelService.maccatalyst.cs
240
C#
using System; using System.Data; using System.IO; using System.Reflection; using System.Windows.Forms; namespace MetroFramework.Localization { // Token: 0x02000062 RID: 98 internal class MetroLocalize { // Token: 0x0600041B RID: 1051 RVA: 0x0000E558 File Offset: 0x0000C758 public string DefaultLanguage() { return "en"; } // Token: 0x0600041C RID: 1052 RVA: 0x0000E560 File Offset: 0x0000C760 public string CurrentLanguage() { string text = Application.CurrentCulture.TwoLetterISOLanguageName; if (text.Length == 0) { text = this.DefaultLanguage(); } return text.ToLower(); } // Token: 0x0600041D RID: 1053 RVA: 0x0000E58D File Offset: 0x0000C78D public MetroLocalize(string ctrlName) { this.importManifestResource(ctrlName); } // Token: 0x0600041E RID: 1054 RVA: 0x0000E59C File Offset: 0x0000C79C public MetroLocalize(Control ctrl) { this.importManifestResource(ctrl.Name); } // Token: 0x0600041F RID: 1055 RVA: 0x0000E5B0 File Offset: 0x0000C7B0 private void importManifestResource(string ctrlName) { Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = string.Concat(new string[] { callingAssembly.GetName().Name, ".Localization.", this.CurrentLanguage(), ".", ctrlName, ".xml" }); Stream manifestResourceStream = callingAssembly.GetManifestResourceStream(name); if (manifestResourceStream == null) { name = string.Concat(new string[] { callingAssembly.GetName().Name, ".Localization.", this.DefaultLanguage(), ".", ctrlName, ".xml" }); manifestResourceStream = callingAssembly.GetManifestResourceStream(name); } if (this.languageDataset == null) { this.languageDataset = new DataSet(); } if (manifestResourceStream != null) { DataSet dataSet = new DataSet(); dataSet.ReadXml(manifestResourceStream); this.languageDataset.Merge(dataSet); manifestResourceStream.Close(); } } // Token: 0x06000420 RID: 1056 RVA: 0x0000E69E File Offset: 0x0000C89E private string convertVar(object var) { if (var == null) { return ""; } return var.ToString(); } // Token: 0x06000421 RID: 1057 RVA: 0x0000E6B0 File Offset: 0x0000C8B0 public string translate(string key) { if (string.IsNullOrEmpty(key)) { return ""; } if (this.languageDataset == null) { return "~" + key; } if (this.languageDataset.Tables["Localization"] == null) { return "~" + key; } DataRow[] array = this.languageDataset.Tables["Localization"].Select("Key='" + key + "'"); if (array.Length <= 0) { return "~" + key; } return array[0]["Value"].ToString(); } // Token: 0x06000422 RID: 1058 RVA: 0x0000E754 File Offset: 0x0000C954 public string translate(string key, object var1) { string text = this.translate(key); return text.Replace("#1", this.convertVar(var1)); } // Token: 0x06000423 RID: 1059 RVA: 0x0000E77C File Offset: 0x0000C97C public string translate(string key, object var1, object var2) { string text = this.translate(key); text = text.Replace("#1", this.convertVar(var1)); return text.Replace("#2", this.convertVar(var2)); } // Token: 0x06000424 RID: 1060 RVA: 0x0000E7B8 File Offset: 0x0000C9B8 public string getValue(string key, object var1, object var2, object var3) { string text = this.translate(key); text = text.Replace("#1", this.convertVar(var1)); text = text.Replace("#2", this.convertVar(var2)); return text.Replace("#3", this.convertVar(var3)); } // Token: 0x06000425 RID: 1061 RVA: 0x0000E808 File Offset: 0x0000CA08 public string getValue(string key, object var1, object var2, object var3, object var4) { string text = this.translate(key); text = text.Replace("#1", this.convertVar(var1)); text = text.Replace("#2", this.convertVar(var2)); text = text.Replace("#3", this.convertVar(var3)); return text.Replace("#4", this.convertVar(var4)); } // Token: 0x06000426 RID: 1062 RVA: 0x0000E86C File Offset: 0x0000CA6C public string getValue(string key, object var1, object var2, object var3, object var4, object var5) { string text = this.translate(key); text = text.Replace("#1", this.convertVar(var1)); text = text.Replace("#2", this.convertVar(var2)); text = text.Replace("#3", this.convertVar(var3)); text = text.Replace("#4", this.convertVar(var4)); return text.Replace("#5", this.convertVar(var5)); } // Token: 0x04000116 RID: 278 private DataSet languageDataset; } }
28.110429
101
0.676342
[ "Unlicense" ]
tavvi1337/PrivateData
PrivateData/MetroFramework.Fonts/MetroFramework/Localization/MetroLocalize.cs
4,584
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Toscana { /// <summary> /// A capability definition defines a named, typed set of data that can be associated with /// Node Type or Node Template to describe a transparent capability or feature of the software /// component the node describes. /// </summary> public class ToscaCapability { /// <summary> /// Initializes an instance of ToscaCapability class /// </summary> public ToscaCapability() { Properties = new Dictionary<string, ToscaProperty>(); Attributes = new Dictionary<string, ToscaAttribute>(); ValidSourceTypes = new string[0]; } /// <summary> /// The required name of the Capability Type the capability definition is based upon. /// </summary> [Required(ErrorMessage = "type is required on capability", AllowEmptyStrings = false)] public string Type { get; set; } /// <summary> /// The optional description of the Capability definition. /// </summary> public string Description { get; set; } /// <summary> /// An optional list of property definitions for the Capability definition. /// </summary> public Dictionary<string, ToscaProperty> Properties { get; set; } /// <summary> /// An optional list of attribute definitions for the Capability definition. /// </summary> public Dictionary<string, ToscaAttribute> Attributes { get; set; } /// <summary> /// An optional list of one or more valid names of Node Types that are supported as valid sources of any relationship established to the declared Capability Type. /// </summary> public string[] ValidSourceTypes { get; set; } /// <summary> /// Initializes an instance of of <see cref="ToscaCapability"/> and set its Type property /// </summary> /// <param name="type">Value to set to Type property</param> /// <returns>An instance of ToscaCapability</returns> public static implicit operator ToscaCapability(string type) { return new ToscaCapability { Type = type }; } } }
38.898305
170
0.623529
[ "Apache-2.0" ]
QualiSystems/Toscana
Toscana/ToscaCapability.cs
2,297
C#
/* * Copyright 2013 ThirdMotion, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// This pretends to call Facebook and get you info relevant to the game /// ====================== /// This is one of two example ISocialService classes, demonstrating how easily /// you can swap between them thanks to IoC. /// /// As I did in the myfirstproject example, note that I'm cheating a bit to show how /// a webservice would work. You'd never really want to inject the contextView into your /// service...I just want to demonstrate the async nature, so I'm borrowing a coroutine. /// /// Never mind that the service is faked. What's important is that it's DIFFERENT from the /// Google one. And you can swap the two of them in and own with a single-line /// change in the Context that doesn't touch any other part of your app. using System; using System.Collections; using UnityEngine; using strange.extensions.context.api; using strange.extensions.dispatcher.eventdispatcher.api; using strange.extensions.signal.impl; namespace strange.examples.multiplecontexts.signals.social { public class FacebookService : ISocialService { [Inject(ContextKeys.CONTEXT_VIEW)] public GameObject contextView { get; set; } public Signal<UserVO> FULFILL_CURRENT_USER_REQUEST { get; private set; } public Signal<ArrayList> FULFILL_FRIENDS_REQUEST { get; private set; } public FacebookService() { FULFILL_CURRENT_USER_REQUEST = new Signal<UserVO>(); FULFILL_FRIENDS_REQUEST = new Signal<ArrayList>(); } public void FetchCurrentUser() { MonoBehaviour root = contextView.GetComponent<SocialSignalRoot>(); root.StartCoroutine(waitASecondThenReturnCurrentUser()); } public void FetchScoresForFriends() { MonoBehaviour root = contextView.GetComponent<SocialSignalRoot>(); root.StartCoroutine(waitASecondThenReturnFriendList()); } private IEnumerator waitASecondThenReturnCurrentUser() { yield return new WaitForSeconds(1f); //...then pass back some fake data UserVO user = getUserData("Zaphod", "12345", "http://upload.wikimedia.org/wikipedia/en/7/72/Mark_Wing-Davey_as_Zaphod_Beeblebrox.jpg", 100); FULFILL_CURRENT_USER_REQUEST.Dispatch(user); } private IEnumerator waitASecondThenReturnFriendList() { yield return new WaitForSeconds(1f); ArrayList friends = new ArrayList(); friends.Add(getUserData("Arthur", "12346", "http://upload.wikimedia.org/wikipedia/en/e/eb/Arthur_Dent_Livid.jpg", 20)); friends.Add(getUserData("Ford", "12347", "http://fc01.deviantart.net/fs7/i/2005/227/8/3/Ford_Prefect_by_KatoChan.jpg", 50)); friends.Add(getUserData("Trillian", "12348", "http://upload.wikimedia.org/wikipedia/en/6/6d/Sandra_Dickinson_as_Trillian.jpg", 110)); friends.Add(getUserData("Slartibartfast", "12349", "http://upload.wikimedia.org/wikipedia/en/3/31/SlartBartFast.JPG", 200)); friends.Add(getUserData("Marvin", "12350", "http://upload.wikimedia.org/wikipedia/en/2/25/Marvin-TV-3.jpg", 800)); FULFILL_FRIENDS_REQUEST.Dispatch(friends); } private UserVO getUserData(string name, string id, string imgUrl, int score) { UserVO retv = new UserVO(); retv.userFirstName = name; retv.serviceId = id; retv.imgUrl = imgUrl; retv.highScore = score; return retv; } } }
44.757895
146
0.659454
[ "Apache-2.0" ]
lorenchorley/StrangeIoC-Updated
Assets/Examples/Scripts/IoC/Multiple Contexts/signals/social/service/FacebookService.cs
4,252
C#
// ***************************************************************************** // // © Component Factory Pty Ltd, 2006 - 2016. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, PO Box 1504, // Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms. // // Version 5.462.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Windows.Forms; using ComponentFactory.Krypton.Toolkit; namespace KryptonInputBoxExamples { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void buttonShow_Click(object sender, EventArgs e) { KryptonInputBox.Show(this, textBoxPrompt.Text, textBoxCaption.Text, textBoxDefaultResponse.Text); } } }
32
109
0.573958
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.462
Source/Demos/Non-NuGet/Krypton Toolkit Examples/KryptonInputBox Examples/Form1.cs
963
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.Collections; using System.Globalization; namespace System.Diagnostics { /// <summary> /// A collection containing all the instance data for a counter. This collection is contained in the /// <see cref='System.Diagnostics.InstanceDataCollectionCollection'/> when using the /// <see cref='System.Diagnostics.PerformanceCounterCategory.ReadCategory'/> method. /// </summary> public class InstanceDataCollection : DictionaryBase { [Obsolete("This constructor has been deprecated. Please use System.Diagnostics.InstanceDataCollectionCollection.get_Item to get an instance of this collection instead. https://go.microsoft.com/fwlink/?linkid=14202")] public InstanceDataCollection(string counterName) { if (counterName == null) throw new ArgumentNullException(nameof(counterName)); CounterName = counterName; } public string CounterName { get; } public ICollection Keys { get { return Dictionary.Keys; } } public ICollection Values { get { return Dictionary.Values; } } public InstanceData this[string instanceName] { get { if (instanceName == null) throw new ArgumentNullException(nameof(instanceName)); if (instanceName.Length == 0) instanceName = PerformanceCounterLib.SingleInstanceName; string objectName = instanceName.ToLower(CultureInfo.InvariantCulture); return (InstanceData)Dictionary[objectName]; } } internal void Add(string instanceName, InstanceData value) { string objectName = instanceName.ToLower(CultureInfo.InvariantCulture); Dictionary.Add(objectName, value); } public bool Contains(string instanceName) { if (instanceName == null) throw new ArgumentNullException(nameof(instanceName)); string objectName = instanceName.ToLower(CultureInfo.InvariantCulture); return Dictionary.Contains(objectName); } public void CopyTo(InstanceData[] instances, int index) { Dictionary.Values.CopyTo(instances, index); } } }
33.392405
226
0.622441
[ "MIT" ]
2E0PGS/corefx
src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollection.cs
2,638
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 Microsoft.Diagnostics.Runtime { /// <summary> /// Types of GC segments. /// </summary> public enum GCSegmentType { /// <summary> /// Ephemeral segments are the only segments to contain Gen0 and Gen1 objects. /// It may also contain Gen2 objects, but not always. Objects are only allocated /// on the ephemeral segment. There is one ephemeral segment per logical GC heap. /// It is important to not have too many pinned objects in the ephemeral segment, /// or you will run into a performance problem where the runtime runs too many GCs. /// </summary> Ephemeral, /// <summary> /// Regular GC segments only contain Gen2 objects. /// </summary> Regular, /// <summary> /// The large object heap contains objects greater than a certain threshold. Large /// object segments are never compacted. Large objects are directly allocated /// onto LargeObject segments, and all large objects are considered gen2. /// </summary> LargeObject } }
40
91
0.647727
[ "MIT" ]
DamirAinullin/clrmd
src/Microsoft.Diagnostics.Runtime/src/Common/GCSegmentType.cs
1,322
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Settings { class Settings { static readonly string path = "settings.conf"; public static void SetValue(string key, string value) { string[] settings = ReadFile(); string scannedKey = String.Copy(key); scannedKey.Replace('\n', '_').Replace('=', '_'); int index = GetKeyIndex(scannedKey, settings); string encoded = Encode(value); string data = ""; if (index == -1) { for (int i = 0; i < settings.Length; i++) { data += settings[i] + "\n"; } data += scannedKey + "=" + encoded; } else { for (int i = 0; i < settings.Length; i++) { if (i == index) { data += scannedKey + "=" + encoded + "\n"; } else { data += settings[i] + "\n"; } } } WriteFile(data); } public static string GetValue(string key) { string[] settings = ReadFile(); string scannedKey = String.Copy(key); scannedKey.Replace('\n', '_').Replace('=', '_'); int index = GetKeyIndex(scannedKey, settings); if (index >= 0) { string line = settings[index]; int start = line.IndexOf('=') + 1; string decoded = Decode(line.Substring(start, line.Length - start)); return decoded; } return ""; } static string[] ReadFile() { try { if (File.Exists(path)) { using (StreamReader sr = File.OpenText(path)) { LinkedList<string> data = new LinkedList<string>(); string line = ""; while ((line = sr.ReadLine()) != null) { if (line.Contains("=")) { data.AddLast(line); } } sr.Close(); return data.ToArray(); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return new string[0]; } static void WriteFile(string data) { try { using (FileStream fs = File.Create(path)) { Byte[] info = new UTF8Encoding(true).GetBytes(data); fs.Write(info, 0, info.Length); fs.Close(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } static int GetKeyIndex(string key, string[] settings) { for (int i = 0; i < settings.Length; i++) { string elementKey = settings[i].Substring(0, settings[i].IndexOf('=')); if (key == elementKey) { return i; } } return -1; } static string Encode(string input) { string output = ""; for (int i = 0; i < input.Length; i++) { if (input[i] == '\n') { output += "\\n"; } else if (input[i] == '\\') { output += "\\\\"; } else { output += input[i]; } } return output; } static string Decode(string input) { string output = ""; for (int i = 0; i < input.Length; i++) { if (input[i] == '\\' && input[i + 1] == 'n') { output += "\n"; i++; } else if (input[i] == '\\' && input[i + 1] == '\\') { output += "\\"; i++; } else { output += input[i]; } } return output; } } }
27.709302
87
0.338019
[ "MIT" ]
slole/settings-for-csharp
Settings/Settings.cs
4,768
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("AWSSDK.WorkDocs")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon WorkDocs. Amazon WorkDocs is a fully managed, secure enterprise storage and sharing service with strong administrative controls and feedback capabilities that improve user productivity.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.0.65")]
47.9375
272
0.756845
[ "Apache-2.0" ]
wdolek/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/WorkDocs/Properties/AssemblyInfo.cs
1,534
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Dynamic; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using Microsoft.Scripting; using System.Reflection; using System.Diagnostics; #if FEATURE_NUMERICS using System.Numerics; #endif namespace IronPython.Runtime.Binding { using Ast = Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; class PythonConversionBinder : DynamicMetaObjectBinder, IPythonSite, IExpressionSerializable { private readonly PythonContext/*!*/ _context; private readonly ConversionResultKind/*!*/ _kind; private readonly Type _type; private readonly bool _retObject; private CompatConversionBinder _compatConvert; public PythonConversionBinder(PythonContext/*!*/ context, Type/*!*/ type, ConversionResultKind resultKind) { Assert.NotNull(context, type); _context = context; _kind = resultKind; _type = type; } public PythonConversionBinder(PythonContext/*!*/ context, Type/*!*/ type, ConversionResultKind resultKind, bool retObject) { Assert.NotNull(context, type); _context = context; _kind = resultKind; _type = type; _retObject = retObject; } public Type Type { get { return _type; } } public ConversionResultKind ResultKind { get { return _kind; } } public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) { DynamicMetaObject self = target; DynamicMetaObject res = null; if (self.NeedsDeferral()) { return MyDefer(self); } IPythonConvertible convertible = target as IPythonConvertible; if (convertible != null) { res = convertible.BindConvert(this); } else if (res == null) { res = BindConvert(self); } if (_retObject) { res = new DynamicMetaObject( AstUtils.Convert(res.Expression, typeof(object)), res.Restrictions ); } return res; } public override Type ReturnType { get { if (_retObject) { return typeof(object); } return (_kind == ConversionResultKind.ExplicitCast || _kind == ConversionResultKind.ImplicitCast) ? Type : _type.IsValueType() ? typeof(object) : _type; } } private DynamicMetaObject MyDefer(DynamicMetaObject self) { return new DynamicMetaObject( DynamicExpression.Dynamic( this, ReturnType, self.Expression ), self.Restrictions ); } private DynamicMetaObject BindConvert(DynamicMetaObject self) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Convert " + Type.FullName + " " + self.LimitType); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "Conversion"); DynamicMetaObject res; #if FEATURE_COM DynamicMetaObject comConvert; if (Microsoft.Scripting.ComInterop.ComBinder.TryConvert(CompatBinder, self, out comConvert)) { res = comConvert; } else #endif { res = self.BindConvert(CompatBinder); } // if we return object and the interop binder had to put on an extra conversion // to the strong type go ahead and remove it now. if (ReturnType == typeof(object) && res.Expression.Type != typeof(object) && res.Expression.NodeType == ExpressionType.Convert) { res = new DynamicMetaObject( ((UnaryExpression)res.Expression).Operand, res.Restrictions ); } return res; } internal CompatConversionBinder CompatBinder { get { if (_compatConvert == null) { _compatConvert = new CompatConversionBinder(this, Type, _kind == ConversionResultKind.ExplicitCast || _kind == ConversionResultKind.ExplicitTry); } return _compatConvert; } } internal DynamicMetaObject FallbackConvert(Type returnType, DynamicMetaObject self, DynamicMetaObject errorSuggestion) { Type type = Type; DynamicMetaObject res = null; switch (type.GetTypeCode()) { case TypeCode.Boolean: res = MakeToBoolConversion(self); break; case TypeCode.Char: res = TryToCharConversion(self); break; case TypeCode.String: if (self.GetLimitType() == typeof(Bytes) && !_context.PythonOptions.Python30) { res = new DynamicMetaObject( Ast.Call( typeof(PythonOps).GetMethod("MakeString"), AstUtils.Convert(self.Expression, typeof(IList<byte>)) ), BindingRestrictionsHelpers.GetRuntimeTypeRestriction(self.Expression, typeof(Bytes)) ); } break; case TypeCode.Object: // !!! Deferral? if (type.IsArray && self.Value is PythonTuple && type.GetArrayRank() == 1) { res = MakeToArrayConversion(self, type); } else if (type.IsGenericType && !type.IsAssignableFrom(CompilerHelpers.GetType(self.Value))) { Type genTo = type.GetGenericTypeDefinition(); // Interface conversion helpers... if (genTo == typeof(IList<>)) { if (self.LimitType == typeof(string)) { res = new DynamicMetaObject( Ast.Call( typeof(PythonOps).GetMethod("MakeByteArray"), AstUtils.Convert(self.Expression, typeof(string)) ), BindingRestrictions.GetTypeRestriction( self.Expression, typeof(string) ) ); } else { res = TryToGenericInterfaceConversion(self, type, typeof(IList<object>), typeof(ListGenericWrapper<>)); } } else if (genTo == typeof(IDictionary<,>)) { res = TryToGenericInterfaceConversion(self, type, typeof(IDictionary<object, object>), typeof(DictionaryGenericWrapper<,>)); } else if (genTo == typeof(IEnumerable<>)) { res = TryToGenericInterfaceConversion(self, type, typeof(IEnumerable), typeof(IEnumerableOfTWrapper<>)); } } else if (type == typeof(IEnumerable)) { if (!typeof(IEnumerable).IsAssignableFrom(self.GetLimitType()) && IsIndexless(self)) { res = ConvertToIEnumerable(this, self.Restrict(self.GetLimitType())); } } else if (type == typeof(IEnumerator)) { if (!typeof(IEnumerator).IsAssignableFrom(self.GetLimitType()) && !typeof(IEnumerable).IsAssignableFrom(self.GetLimitType()) && IsIndexless(self)) { res = ConvertToIEnumerator(this, self.Restrict(self.GetLimitType())); } } break; } if (type.IsEnum() && Enum.GetUnderlyingType(type) == self.GetLimitType()) { // numeric type to enum, this is ok if the value is zero object value = Activator.CreateInstance(type); return new DynamicMetaObject( Ast.Condition( Ast.Equal( AstUtils.Convert(self.Expression, Enum.GetUnderlyingType(type)), AstUtils.Constant(Activator.CreateInstance(self.GetLimitType())) ), AstUtils.Constant(value), Ast.Call( typeof(PythonOps).GetMethod("TypeErrorForBadEnumConversion").MakeGenericMethod(type), AstUtils.Convert(self.Expression, typeof(object)) ) ), self.Restrictions.Merge(BindingRestrictionsHelpers.GetRuntimeTypeRestriction(self.Expression, self.GetLimitType())), value ); } return res ?? EnsureReturnType(returnType, Context.Binder.ConvertTo(Type, ResultKind, self, _context.SharedOverloadResolverFactory, errorSuggestion)); } private static DynamicMetaObject EnsureReturnType(Type returnType, DynamicMetaObject dynamicMetaObject) { if (dynamicMetaObject.Expression.Type != returnType) { dynamicMetaObject = new DynamicMetaObject( AstUtils.Convert( dynamicMetaObject.Expression, returnType ), dynamicMetaObject.Restrictions ); } return dynamicMetaObject; } public override T BindDelegate<T>(CallSite<T> site, object[] args) { //Debug.Assert(typeof(T).GetMethod("Invoke").ReturnType == Type); object target = args[0]; T res = null; if (typeof(T) == typeof(Func<CallSite, object, string>) && target is string) { res = (T)(object)new Func<CallSite, object, string>(StringConversion); } else if (typeof(T) == typeof(Func<CallSite, object, int>)) { if (target is int) { res = (T)(object)new Func<CallSite, object, int>(IntConversion); } else if (target is bool) { res = (T)(object)new Func<CallSite, object, int>(BoolToIntConversion); } } else if (typeof(T) == typeof(Func<CallSite, bool, int>)) { res = (T)(object)new Func<CallSite, bool, int>(BoolToIntConversion); } else if (typeof(T) == typeof(Func<CallSite, object, bool>)) { if (target is bool) { res = (T)(object)new Func<CallSite, object, bool>(BoolConversion); } else if (target is string) { res = (T)(object)new Func<CallSite, object, bool>(StringToBoolConversion); } else if (target is int) { res = (T)(object)new Func<CallSite, object, bool>(IntToBoolConversion); } else if (target == null) { res = (T)(object)new Func<CallSite, object, bool>(NullToBoolConversion); } else if (target.GetType() == typeof(object)) { res = (T)(object)new Func<CallSite, object, bool>(ObjectToBoolConversion); } else if (target.GetType() == typeof(List)) { res = (T)(object)new Func<CallSite, object, bool>(ListToBoolConversion); } else if (target.GetType() == typeof(PythonTuple)) { res = (T)(object)new Func<CallSite, object, bool>(TupleToBoolConversion); } } else if (target != null) { // Special cases: // - string or bytes to IEnumerable or IEnumerator // - CLR 4 only: BigInteger -> Complex #if FEATURE_NUMERICS if (target is BigInteger) { if (typeof(T) == typeof(Func<CallSite, BigInteger, Complex>)) { res = (T)(object)new Func<CallSite, BigInteger, Complex>(BigIntegerToComplexConversion); } else if (typeof(T) == typeof(Func<CallSite, object, Complex>)) { res = (T)(object)new Func<CallSite, object, Complex>(BigIntegerObjectToComplexConversion); } else if (typeof(T) == typeof(Func<CallSite, BigInteger, object>)) { res = (T)(object)new Func<CallSite, BigInteger, object>(BigIntegerToComplexObjectConversion); } } else #endif if (target is string) { if (typeof(T) == typeof(Func<CallSite, string, IEnumerable>)) { res = (T)(object)new Func<CallSite, string, IEnumerable>(StringToIEnumerableConversion); } else if (typeof(T) == typeof(Func<CallSite, string, IEnumerator>)) { res = (T)(object)new Func<CallSite, string, IEnumerator>(StringToIEnumeratorConversion); } else if (typeof(T) == typeof(Func<CallSite, object, IEnumerable>)) { res = (T)(object)new Func<CallSite, object, IEnumerable>(ObjectToIEnumerableConversion); } else if (typeof(T) == typeof(Func<CallSite, object, IEnumerator>)) { res = (T)(object)new Func<CallSite, object, IEnumerator>(ObjectToIEnumeratorConversion); } } else if (target.GetType() == typeof(Bytes)) { if (typeof(T) == typeof(Func<CallSite, Bytes, IEnumerable>)) { res = (T)(object)new Func<CallSite, Bytes, IEnumerable>(BytesToIEnumerableConversion); } else if (typeof(T) == typeof(Func<CallSite, Bytes, IEnumerator>)) { res = (T)(object)new Func<CallSite, Bytes, IEnumerator>(BytesToIEnumeratorConversion); } else if (typeof(T) == typeof(Func<CallSite, object, IEnumerable>)) { res = (T)(object)new Func<CallSite, object, IEnumerable>(ObjectToIEnumerableConversion); } else if (typeof(T) == typeof(Func<CallSite, object, IEnumerator>)) { res = (T)(object)new Func<CallSite, object, IEnumerator>(ObjectToIEnumeratorConversion); } } if (res == null && (target.GetType() == Type || Type.IsAssignableFrom(target.GetType()))) { if (typeof(T) == typeof(Func<CallSite, object, object>)) { // called via a helper call site in the runtime (e.g. Converter.Convert) res = (T)(object)new Func<CallSite, object, object>(new IdentityConversion(target.GetType()).Convert); } else { // called via an embedded call site Debug.Assert(typeof(T).GetMethod("Invoke").ReturnType == Type); if (typeof(T).GetMethod("Invoke").GetParameters()[1].ParameterType == typeof(object)) { object identityConversion = Activator.CreateInstance(typeof(IdentityConversion<>).MakeGenericType(Type), target.GetType()); res = (T)(object)identityConversion.GetType().GetMethod("Convert").CreateDelegate(typeof(T), identityConversion); } } } } if (res != null) { CacheTarget(res); return res; } PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Convert " + Type.FullName + " " + CompilerHelpers.GetType(args[0]) + " " + typeof(T)); return base.BindDelegate(site, args); } public string StringConversion(CallSite site, object value) { string str = value as string; if (str != null) { return str; } return ((CallSite<Func<CallSite, object, string>>)site).Update(site, value); } public int IntConversion(CallSite site, object value) { if (value is int) { return (int)value; } return ((CallSite<Func<CallSite, object, int>>)site).Update(site, value); } public int BoolToIntConversion(CallSite site, object value) { if (value is bool) { return (bool)value ? 1 : 0; } return ((CallSite<Func<CallSite, object, int>>)site).Update(site, value); } public int BoolToIntConversion(CallSite site, bool value) { return (bool)value ? 1 : 0; } public bool BoolConversion(CallSite site, object value) { if (value is bool) { return (bool)value; } else if (value == null) { // improve perf of sites just polymorphic on bool & None return false; } return ((CallSite<Func<CallSite, object, bool>>)site).Update(site, value); } public bool IntToBoolConversion(CallSite site, object value) { if (value is int) { return (int)value != 0; } else if (value == null) { // improve perf of sites just polymorphic on int & None return false; } return ((CallSite<Func<CallSite, object, bool>>)site).Update(site, value); } public bool StringToBoolConversion(CallSite site, object value) { if (value is string) { return ((string)value).Length > 0; } else if (value == null) { // improve perf of sites just polymorphic on str & None return false; } return ((CallSite<Func<CallSite, object, bool>>)site).Update(site, value); } public bool NullToBoolConversion(CallSite site, object value) { if (value == null) { return false; } return ((CallSite<Func<CallSite, object, bool>>)site).Update(site, value); } public bool ObjectToBoolConversion(CallSite site, object value) { if (value != null && value.GetType() == typeof(Object)) { return true; } else if (value == null) { // improve perf of sites just polymorphic on object & None return false; } return ((CallSite<Func<CallSite, object, bool>>)site).Update(site, value); } public bool ListToBoolConversion(CallSite site, object value) { if (value == null) { return false; } else if (value.GetType() == typeof(List)) { return ((List)value).Count != 0; } return ((CallSite<Func<CallSite, object, bool>>)site).Update(site, value); } public bool TupleToBoolConversion(CallSite site, object value) { if (value == null) { return false; } else if (value.GetType() == typeof(PythonTuple)) { return ((PythonTuple)value).Count != 0; } return ((CallSite<Func<CallSite, object, bool>>)site).Update(site, value); } public IEnumerable StringToIEnumerableConversion(CallSite site, string value) { if (value == null) { return ((CallSite<Func<CallSite, string, IEnumerable>>)site).Update(site, value); } return PythonOps.StringEnumerable(value); } public IEnumerator StringToIEnumeratorConversion(CallSite site, string value) { if (value == null) { return ((CallSite<Func<CallSite, string, IEnumerator>>)site).Update(site, value); } return PythonOps.StringEnumerator(value).Key; } public IEnumerable BytesToIEnumerableConversion(CallSite site, Bytes value) { if (value == null) { return ((CallSite<Func<CallSite, Bytes, IEnumerable>>)site).Update(site, value); } return _context.PythonOptions.Python30 ? PythonOps.BytesIntEnumerable(value) : PythonOps.BytesEnumerable(value); } public IEnumerator BytesToIEnumeratorConversion(CallSite site, Bytes value) { if (value == null) { return ((CallSite<Func<CallSite, Bytes, IEnumerator>>)site).Update(site, value); } return _context.PythonOptions.Python30 ? (IEnumerator)PythonOps.BytesIntEnumerator(value).Key : (IEnumerator)PythonOps.BytesEnumerator(value).Key; } public IEnumerable ObjectToIEnumerableConversion(CallSite site, object value) { if (value != null) { if (value is string) { return PythonOps.StringEnumerable((string)value); } else if (value.GetType() == typeof(Bytes)) { return _context.PythonOptions.Python30 ? PythonOps.BytesIntEnumerable((Bytes)value) : PythonOps.BytesEnumerable((Bytes)value); } } return ((CallSite<Func<CallSite, object, IEnumerable>>)site).Update(site, value); } public IEnumerator ObjectToIEnumeratorConversion(CallSite site, object value) { if (value != null) { if (value is string) { return PythonOps.StringEnumerator((string)value).Key; } else if (value.GetType() == typeof(Bytes)) { return _context.PythonOptions.Python30 ? (IEnumerator)PythonOps.BytesIntEnumerator((Bytes)value).Key : (IEnumerator)PythonOps.BytesEnumerator((Bytes)value).Key; } } return ((CallSite<Func<CallSite, object, IEnumerator>>)site).Update(site, value); } #if FEATURE_NUMERICS public Complex BigIntegerToComplexConversion(CallSite site, BigInteger value) { return BigIntegerOps.ConvertToComplex(value); } public Complex BigIntegerObjectToComplexConversion(CallSite site, object value) { if (value is BigInteger) { return BigIntegerOps.ConvertToComplex((BigInteger)value); } return ((CallSite<Func<CallSite, object, Complex>>)site).Update(site, value); } public object BigIntegerToComplexObjectConversion(CallSite site, BigInteger value) { return (object)BigIntegerOps.ConvertToComplex((BigInteger)value); } #endif class IdentityConversion { private readonly Type _type; public IdentityConversion(Type type) { _type = type; } public object Convert(CallSite site, object value) { if (value != null && value.GetType() == _type) { return value; } return ((CallSite<Func<CallSite, object, object>>)site).Update(site, value); } } class IdentityConversion<T> { private readonly Type _type; public IdentityConversion(Type type) { _type = type; } public T Convert(CallSite site, object value) { if (value != null && value.GetType() == _type) { return (T)value; } return ((CallSite<Func<CallSite, object, T>>)site).Update(site, value); } } internal static bool IsIndexless(DynamicMetaObject/*!*/ arg) { return arg.GetLimitType() != typeof(OldInstance); } public override int GetHashCode() { return base.GetHashCode() ^ _context.Binder.GetHashCode() ^ _kind.GetHashCode(); } public override bool Equals(object obj) { PythonConversionBinder ob = obj as PythonConversionBinder; if (ob == null) { return false; } return ob._context.Binder == _context.Binder && _kind == ob._kind && base.Equals(obj) && _retObject == ob._retObject; } public PythonContext/*!*/ Context { get { return _context; } } #region Conversion Logic private static DynamicMetaObject TryToGenericInterfaceConversion(DynamicMetaObject/*!*/ self, Type/*!*/ toType, Type/*!*/ fromType, Type/*!*/ wrapperType) { if (fromType.IsAssignableFrom(CompilerHelpers.GetType(self.Value))) { Type making = wrapperType.MakeGenericType(toType.GetGenericArguments()); self = self.Restrict(CompilerHelpers.GetType(self.Value)); return new DynamicMetaObject( Ast.New( making.GetConstructor(new Type[] { fromType }), AstUtils.Convert( self.Expression, fromType ) ), self.Restrictions ); } return null; } private static DynamicMetaObject/*!*/ MakeToArrayConversion(DynamicMetaObject/*!*/ self, Type/*!*/ toType) { self = self.Restrict(typeof(PythonTuple)); return new DynamicMetaObject( Ast.Call( typeof(PythonOps).GetMethod("ConvertTupleToArray").MakeGenericMethod(toType.GetElementType()), self.Expression ), self.Restrictions ); } private DynamicMetaObject TryToCharConversion(DynamicMetaObject/*!*/ self) { DynamicMetaObject res; // we have an implicit conversion to char if the // string length == 1, but we can only represent // this is implicit via a rule. string strVal = self.Value as string; Expression strExpr = self.Expression; if (strVal == null) { Extensible<string> extstr = self.Value as Extensible<string>; if (extstr != null) { strVal = extstr.Value; strExpr = Ast.Property( AstUtils.Convert( strExpr, typeof(Extensible<string>) ), typeof(Extensible<string>).GetProperty("Value") ); } } // we can only produce a conversion if we have a string value... if (strVal != null) { self = self.Restrict(self.GetRuntimeType()); Expression getLen = Ast.Property( AstUtils.Convert( strExpr, typeof(string) ), typeof(string).GetProperty("Length") ); if (strVal.Length == 1) { res = new DynamicMetaObject( Ast.Call( AstUtils.Convert(strExpr, typeof(string)), typeof(string).GetMethod("get_Chars"), AstUtils.Constant(0) ), self.Restrictions.Merge(BindingRestrictions.GetExpressionRestriction(Ast.Equal(getLen, AstUtils.Constant(1)))) ); } else { res = new DynamicMetaObject( this.Throw( Ast.Call( typeof(PythonOps).GetMethod("TypeError"), AstUtils.Constant("expected string of length 1 when converting to char, got '{0}'"), Ast.NewArrayInit(typeof(object), self.Expression) ), ReturnType ), self.Restrictions.Merge(BindingRestrictions.GetExpressionRestriction(Ast.NotEqual(getLen, AstUtils.Constant(1)))) ); } } else { // let the base class produce the rule res = null; } return res; } private DynamicMetaObject/*!*/ MakeToBoolConversion(DynamicMetaObject/*!*/ self) { DynamicMetaObject res; if (self.HasValue) { self = self.Restrict(self.GetRuntimeType()); } // Optimization: if we already boxed it to a bool, and now // we're unboxing it, remove the unnecessary box. if (self.Expression.NodeType == ExpressionType.Convert && self.Expression.Type == typeof(object)) { var convert = (UnaryExpression)self.Expression; if (convert.Operand.Type == typeof(bool)) { return new DynamicMetaObject(convert.Operand, self.Restrictions); } } if (self.GetLimitType() == typeof(DynamicNull)) { // None has no __nonzero__ and no __len__ but it's always false res = MakeNoneToBoolConversion(self); } else if (self.GetLimitType() == typeof(bool)) { // nothing special to convert from bool to bool res = self; } else if (typeof(IStrongBox).IsAssignableFrom(self.GetLimitType())) { // Explictly block conversion of References to bool res = MakeStrongBoxToBoolConversionError(self); } else if (self.GetLimitType().IsPrimitive() || self.GetLimitType().IsEnum()) { // optimization - rather than doing a method call for primitives and enums generate // the comparison to zero directly. res = MakePrimitiveToBoolComparison(self); } else { // anything non-null that doesn't fall under one of the above rules is true. So we // fallback to the base Python conversion which will check for __nonzero__ and // __len__. The fallback is handled by our ConvertTo site binder. return PythonProtocol.ConvertToBool(this, self) ?? new DynamicMetaObject( AstUtils.Constant(true), self.Restrictions ); } return res; } private static DynamicMetaObject/*!*/ MakeNoneToBoolConversion(DynamicMetaObject/*!*/ self) { // null is never true return new DynamicMetaObject( AstUtils.Constant(false), self.Restrictions ); } private static DynamicMetaObject/*!*/ MakePrimitiveToBoolComparison(DynamicMetaObject/*!*/ self) { object zeroVal = Activator.CreateInstance(self.GetLimitType()); return new DynamicMetaObject( Ast.NotEqual( AstUtils.Constant(zeroVal), self.Expression ), self.Restrictions ); } private DynamicMetaObject/*!*/ MakeStrongBoxToBoolConversionError(DynamicMetaObject/*!*/ self) { return new DynamicMetaObject( this.Throw( Ast.Call( typeof(ScriptingRuntimeHelpers).GetMethod("SimpleTypeError"), AstUtils.Constant("Can't convert a Reference<> instance to a bool") ), ReturnType ), self.Restrictions ); } internal static DynamicMetaObject ConvertToIEnumerable(DynamicMetaObjectBinder/*!*/ conversion, DynamicMetaObject/*!*/ metaUserObject) { PythonType pt = MetaPythonObject.GetPythonType(metaUserObject); PythonContext pyContext = PythonContext.GetPythonContext(conversion); CodeContext context = pyContext.SharedContext; PythonTypeSlot pts; if (pt.TryResolveSlot(context, "__iter__", out pts)) { return MakeIterRule(metaUserObject, "CreatePythonEnumerable"); } else if (pt.TryResolveSlot(context, "__getitem__", out pts)) { return MakeGetItemIterable(metaUserObject, pyContext, pts, "CreateItemEnumerable"); } return null; } internal static DynamicMetaObject ConvertToIEnumerator(DynamicMetaObjectBinder/*!*/ conversion, DynamicMetaObject/*!*/ metaUserObject) { PythonType pt = MetaPythonObject.GetPythonType(metaUserObject); PythonContext state = PythonContext.GetPythonContext(conversion); CodeContext context = state.SharedContext; PythonTypeSlot pts; if (pt.TryResolveSlot(context, "__iter__", out pts)) { ParameterExpression tmp = Ast.Parameter(typeof(object), "iterVal"); return new DynamicMetaObject( Expression.Block( new[] { tmp }, Expression.Call( typeof(PythonOps).GetMethod("CreatePythonEnumerator"), Ast.Block( MetaPythonObject.MakeTryGetTypeMember( state, pts, metaUserObject.Expression, tmp ), DynamicExpression.Dynamic( new PythonInvokeBinder( state, new CallSignature(0) ), typeof(object), AstUtils.Constant(context), tmp ) ) ) ), metaUserObject.Restrictions ); } else if (pt.TryResolveSlot(context, "__getitem__", out pts)) { return MakeGetItemIterable(metaUserObject, state, pts, "CreateItemEnumerator"); } return null; } private static DynamicMetaObject MakeGetItemIterable(DynamicMetaObject metaUserObject, PythonContext state, PythonTypeSlot pts, string method) { ParameterExpression tmp = Ast.Parameter(typeof(object), "getitemVal"); return new DynamicMetaObject( Expression.Block( new[] { tmp }, Expression.Call( typeof(PythonOps).GetMethod(method), Ast.Block( MetaPythonObject.MakeTryGetTypeMember( state, pts, tmp, metaUserObject.Expression, Ast.Call( typeof(DynamicHelpers).GetMethod("GetPythonType"), AstUtils.Convert( metaUserObject.Expression, typeof(object) ) ) ), tmp ), AstUtils.Constant( CallSite<Func<CallSite, CodeContext, object, int, object>>.Create( new PythonInvokeBinder(state, new CallSignature(1)) ) ) ) ), metaUserObject.Restrictions ); } private static DynamicMetaObject/*!*/ MakeIterRule(DynamicMetaObject/*!*/ self, string methodName) { return new DynamicMetaObject( Ast.Call( typeof(PythonOps).GetMethod(methodName), AstUtils.Convert(self.Expression, typeof(object)) ), self.Restrictions ); } #endregion public override string ToString() { return String.Format("Python Convert {0} {1}", Type, ResultKind); } #region IExpressionSerializable Members public Expression CreateExpression() { return Ast.Call( typeof(PythonOps).GetMethod("MakeConversionAction"), BindingHelpers.CreateBinderStateExpression(), AstUtils.Constant(Type), AstUtils.Constant(ResultKind) ); } #endregion } class CompatConversionBinder : ConvertBinder { private readonly PythonConversionBinder _binder; public CompatConversionBinder(PythonConversionBinder binder, Type toType, bool isExplicit) : base(toType, isExplicit) { _binder = binder; } public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { return _binder.FallbackConvert(ReturnType, target, errorSuggestion); } } }
42.868421
165
0.518416
[ "MIT" ]
TrevorDArcyEvans/EllieWare
code/IronLanguages/Languages/IronPython/IronPython/Runtime/Binding/ConversionBinder.cs
39,098
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Linq_003_QueryDesdeMetodos { class CClaseExplicita { // Creamos un arreglo sobre el cual trabajar private static string[] postres = { "pay de manzana", "pastel de chocolate", "manzana caramelizada", "fresas con crema" }; // Creamos el query // No puede usarse de forma implicita // Debe de ser estatico private static IEnumerable<string> encontrados = from p in postres where p.Contains("manzana") orderby p select p; // El metodo regresa y todo se trabaja internamente public static IEnumerable<int> ObtenerNumerosPares() { int[] numeros = { 1, 5, 4, 7, 6, 3, 5, 9, 8, 11 }; IEnumerable<int> pares = from n in numeros where n % 2 == 0 select n; return pares; } // Este metodo regresa el resultado del query public static IEnumerable<string> ObtenerPostres() { return encontrados; } // Este metodo regresa el resultado de un query inmediato public static int[] ObtenerNumerosImpares() { int[] numeros = { 1, 5, 4, 7, 6, 3, 5, 9, 8, 11 }; var resultados = from n in numeros where n % 2 != 0 select n; return resultados.ToArray(); } } }
33.038462
130
0.482538
[ "MIT" ]
maxponmar/LinqBasico_Nicosiored
Linq_003-QueryDesdeMetodos/CClaseExplicita.cs
1,720
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfApplicationTest.Enums { public enum Classifications { BugReport, UserRequirements, Miscellaneous } }
17.6875
35
0.671378
[ "Unlicense" ]
seelprojects/MARC-2.0
MARC 2.0/Enums/Classifications.cs
285
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SFB_ShotFollowTarget : MonoBehaviour { public GameObject target; public float turnSpeed = 4.0f; public float speed = 10.0f; // Use this for initialization void Start () { if (!target) { target = GameObject.Find ("Enemy"); } } // Update is called once per frame void Update () { // Creates a Vector with the X/Z of the target, but the Y of the source // Otherwise, when the playerObject gets close to the characer doing the looking, // it will lean back or forward in order to Look At the player. // Get rotation between forward of two objects Quaternion targetRotation = Quaternion.LookRotation(target.transform.position - transform.position); // Turn towards playerObject over time. transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * turnSpeed); transform.Translate(Vector3.forward * Time.deltaTime * speed); } }
32.8
104
0.742886
[ "MIT" ]
HoBeenH/Second-Popol
Assets/InfinityPBR/Demo Scripts/SFB_ShotFollowTarget.cs
986
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 waf-2015-08-24.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.WAF.Model { /// <summary> /// Container for the parameters to the UpdateRuleGroup operation. /// Inserts or deletes <a>ActivatedRule</a> objects in a <code>RuleGroup</code>. /// /// /// <para> /// You can only insert <code>REGULAR</code> rules into a rule group. /// </para> /// /// <para> /// You can have a maximum of ten rules per rule group. /// </para> /// /// <para> /// To create and configure a <code>RuleGroup</code>, perform the following steps: /// </para> /// <ol> <li> /// <para> /// Create and update the <code>Rules</code> that you want to include in the <code>RuleGroup</code>. /// See <a>CreateRule</a>. /// </para> /// </li> <li> /// <para> /// Use <code>GetChangeToken</code> to get the change token that you provide in the <code>ChangeToken</code> /// parameter of an <a>UpdateRuleGroup</a> request. /// </para> /// </li> <li> /// <para> /// Submit an <code>UpdateRuleGroup</code> request to add <code>Rules</code> to the <code>RuleGroup</code>. /// </para> /// </li> <li> /// <para> /// Create and update a <code>WebACL</code> that contains the <code>RuleGroup</code>. /// See <a>CreateWebACL</a>. /// </para> /// </li> </ol> /// <para> /// If you want to replace one <code>Rule</code> with another, you delete the existing /// one and add the new one. /// </para> /// /// <para> /// For more information about how to use the AWS WAF API to allow or block HTTP requests, /// see the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/">AWS WAF Developer /// Guide</a>. /// </para> /// </summary> public partial class UpdateRuleGroupRequest : AmazonWAFRequest { private string _changeToken; private string _ruleGroupId; private List<RuleGroupUpdate> _updates = new List<RuleGroupUpdate>(); /// <summary> /// Gets and sets the property ChangeToken. /// <para> /// The value returned by the most recent call to <a>GetChangeToken</a>. /// </para> /// </summary> [AWSProperty(Required=true, Min=1)] public string ChangeToken { get { return this._changeToken; } set { this._changeToken = value; } } // Check to see if ChangeToken property is set internal bool IsSetChangeToken() { return this._changeToken != null; } /// <summary> /// Gets and sets the property RuleGroupId. /// <para> /// The <code>RuleGroupId</code> of the <a>RuleGroup</a> that you want to update. <code>RuleGroupId</code> /// is returned by <a>CreateRuleGroup</a> and by <a>ListRuleGroups</a>. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string RuleGroupId { get { return this._ruleGroupId; } set { this._ruleGroupId = value; } } // Check to see if RuleGroupId property is set internal bool IsSetRuleGroupId() { return this._ruleGroupId != null; } /// <summary> /// Gets and sets the property Updates. /// <para> /// An array of <code>RuleGroupUpdate</code> objects that you want to insert into or delete /// from a <a>RuleGroup</a>. /// </para> /// /// <para> /// You can only insert <code>REGULAR</code> rules into a rule group. /// </para> /// /// <para> /// <code>ActivatedRule|OverrideAction</code> applies only when updating or adding a /// <code>RuleGroup</code> to a <code>WebACL</code>. In this case you do not use <code>ActivatedRule|Action</code>. /// For all other update requests, <code>ActivatedRule|Action</code> is used instead of /// <code>ActivatedRule|OverrideAction</code>. /// </para> /// </summary> [AWSProperty(Required=true, Min=1)] public List<RuleGroupUpdate> Updates { get { return this._updates; } set { this._updates = value; } } // Check to see if Updates property is set internal bool IsSetUpdates() { return this._updates != null && this._updates.Count > 0; } } }
34.551948
123
0.585416
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/WAF/Generated/Model/UpdateRuleGroupRequest.cs
5,321
C#
using System; using System.Globalization; using System.Text; using DocumentFormat.OpenXml.Spreadsheet; namespace SpreadsheetLight { /// <summary> /// Specifies reading order. /// </summary> public enum SLAlignmentReadingOrderValues { /// <summary> /// Reading order is context dependent. /// </summary> ContextDependent = 0, /// <summary> /// Reading order is from left to right. /// </summary> LeftToRight = 1, /// <summary> /// Reading order is from right to left. /// </summary> RightToLeft = 2 } /// <summary> /// Encapsulates properties and methods for text alignment in cells. This simulates the DocumentFormat.OpenXml.Spreadsheet.Alignment class. /// </summary> public class SLAlignment { internal bool HasHorizontal; private HorizontalAlignmentValues vHorizontal; /// <summary> /// Specifies the horizontal alignment. Default value is General. /// </summary> public HorizontalAlignmentValues Horizontal { get { return vHorizontal; } set { vHorizontal = value; HasHorizontal = true; } } internal bool HasVertical; private VerticalAlignmentValues vVertical; /// <summary> /// Specifies the vertical alignment. Default value is Bottom. /// </summary> public VerticalAlignmentValues Vertical { get { return vVertical; } set { vVertical = value; HasVertical = true; } } private int? iTextRotation; /// <summary> /// Specifies the rotation angle of the text, ranging from -90 degrees to 90 degrees. Default value is 0 degrees. /// </summary> public int? TextRotation { get { return iTextRotation; } set { if (value >= -90 && value <= 90) { iTextRotation = value; } else { iTextRotation = null; } } } /// <summary> /// Specifies if the text in the cell should be wrapped. /// </summary> public bool? WrapText { get; set; } /// <summary> /// Specifies the indent. Each unit value equals 3 spaces. /// </summary> public uint? Indent { get; set; } /// <summary> /// This property is used when the class is part of a SLDifferentialFormat class. It specifies the indent value in addition to the given Indent property. /// </summary> public int? RelativeIndent { get; set; } /// <summary> /// Specifies if the last line should be justified (usually for East Asian fonts). /// </summary> public bool? JustifyLastLine { get; set; } /// <summary> /// Specifies if the text in the cell should be shrunk to fit the cell. /// </summary> public bool? ShrinkToFit { get; set; } internal bool HasReadingOrder; private SLAlignmentReadingOrderValues vReadingOrder; /// <summary> /// Specifies the reading order of the text in the cell. /// </summary> public SLAlignmentReadingOrderValues ReadingOrder { get { return vReadingOrder; } set { vReadingOrder = value; HasReadingOrder = true; } } /// <summary> /// Initializes an instance of SLAlignment. /// </summary> public SLAlignment() { this.SetAllNull(); } private void SetAllNull() { this.vHorizontal = HorizontalAlignmentValues.General; this.HasHorizontal = false; this.vVertical = VerticalAlignmentValues.Bottom; this.HasVertical = false; this.TextRotation = null; this.WrapText = null; this.Indent = null; this.RelativeIndent = null; this.JustifyLastLine = null; this.ShrinkToFit = null; this.vReadingOrder = SLAlignmentReadingOrderValues.LeftToRight; this.HasReadingOrder = false; } internal void FromAlignment(Alignment align) { this.SetAllNull(); if (align.Horizontal != null) this.Horizontal = align.Horizontal.Value; if (align.Vertical != null) this.Vertical = align.Vertical.Value; if (align.TextRotation != null && align.TextRotation.Value <= 180) { this.TextRotation = this.TextRotationToIntuitiveValue(align.TextRotation.Value); } if (align.WrapText != null) this.WrapText = align.WrapText.Value; if (align.Indent != null) this.Indent = align.Indent.Value; if (align.RelativeIndent != null) this.RelativeIndent = align.RelativeIndent.Value; if (align.JustifyLastLine != null) this.JustifyLastLine = align.JustifyLastLine.Value; if (align.ShrinkToFit != null) this.ShrinkToFit = align.ShrinkToFit.Value; if (align.ReadingOrder != null) { switch (align.ReadingOrder.Value) { case (uint)SLAlignmentReadingOrderValues.ContextDependent: this.ReadingOrder = SLAlignmentReadingOrderValues.ContextDependent; break; case (uint)SLAlignmentReadingOrderValues.LeftToRight: this.ReadingOrder = SLAlignmentReadingOrderValues.LeftToRight; break; case (uint)SLAlignmentReadingOrderValues.RightToLeft: this.ReadingOrder = SLAlignmentReadingOrderValues.RightToLeft; break; } } } internal Alignment ToAlignment() { Alignment align = new Alignment(); if (this.HasHorizontal) align.Horizontal = this.Horizontal; if (this.HasVertical) align.Vertical = this.Vertical; if (this.TextRotation != null) align.TextRotation = this.TextRotationToOpenXmlValue(this.TextRotation.Value); if (this.WrapText != null) align.WrapText = this.WrapText.Value; if (this.Indent != null) align.Indent = this.Indent.Value; if (this.RelativeIndent != null) align.RelativeIndent = this.RelativeIndent.Value; if (this.JustifyLastLine != null) align.JustifyLastLine = this.JustifyLastLine.Value; if (this.ShrinkToFit != null) align.ShrinkToFit = this.ShrinkToFit.Value; if (this.HasReadingOrder) align.ReadingOrder = (uint)this.ReadingOrder; return align; } internal void FromHash(string Hash) { this.SetAllNull(); string[] sa = Hash.Split(new string[] { SLConstants.XmlAlignmentAttributeSeparator }, StringSplitOptions.None); if (sa.Length >= 9) { if (!sa[0].Equals("null")) this.Horizontal = (HorizontalAlignmentValues)Enum.Parse(typeof(HorizontalAlignmentValues), sa[0]); if (!sa[1].Equals("null")) this.Vertical = (VerticalAlignmentValues)Enum.Parse(typeof(VerticalAlignmentValues), sa[1]); if (!sa[2].Equals("null")) this.TextRotation = int.Parse(sa[2]); if (!sa[3].Equals("null")) this.WrapText = bool.Parse(sa[3]); if (!sa[4].Equals("null")) this.Indent = uint.Parse(sa[4]); if (!sa[5].Equals("null")) this.RelativeIndent = int.Parse(sa[5]); if (!sa[6].Equals("null")) this.JustifyLastLine = bool.Parse(sa[6]); if (!sa[7].Equals("null")) this.ShrinkToFit = bool.Parse(sa[7]); if (!sa[8].Equals("null")) this.ReadingOrder = (SLAlignmentReadingOrderValues)Enum.Parse(typeof(SLAlignmentReadingOrderValues), sa[8]); } } internal string ToHash() { StringBuilder sb = new StringBuilder(); if (this.HasHorizontal) sb.AppendFormat("{0}{1}", this.Horizontal, SLConstants.XmlAlignmentAttributeSeparator); else sb.AppendFormat("null{0}", SLConstants.XmlAlignmentAttributeSeparator); if (this.HasVertical) sb.AppendFormat("{0}{1}", this.Vertical, SLConstants.XmlAlignmentAttributeSeparator); else sb.AppendFormat("null{0}", SLConstants.XmlAlignmentAttributeSeparator); if (this.TextRotation != null) sb.AppendFormat("{0}{1}", this.TextRotation.Value.ToString(CultureInfo.InvariantCulture), SLConstants.XmlAlignmentAttributeSeparator); else sb.AppendFormat("null{0}", SLConstants.XmlAlignmentAttributeSeparator); if (this.WrapText != null) sb.AppendFormat("{0}{1}", this.WrapText.Value, SLConstants.XmlAlignmentAttributeSeparator); else sb.AppendFormat("null{0}", SLConstants.XmlAlignmentAttributeSeparator); if (this.Indent != null) sb.AppendFormat("{0}{1}", this.Indent.Value.ToString(CultureInfo.InvariantCulture), SLConstants.XmlAlignmentAttributeSeparator); else sb.AppendFormat("null{0}", SLConstants.XmlAlignmentAttributeSeparator); if (this.RelativeIndent != null) sb.AppendFormat("{0}{1}", this.RelativeIndent.Value.ToString(CultureInfo.InvariantCulture), SLConstants.XmlAlignmentAttributeSeparator); else sb.AppendFormat("null{0}", SLConstants.XmlAlignmentAttributeSeparator); if (this.JustifyLastLine != null) sb.AppendFormat("{0}{1}", this.JustifyLastLine.Value, SLConstants.XmlAlignmentAttributeSeparator); else sb.AppendFormat("null{0}", SLConstants.XmlAlignmentAttributeSeparator); if (this.ShrinkToFit != null) sb.AppendFormat("{0}{1}", this.ShrinkToFit.Value, SLConstants.XmlAlignmentAttributeSeparator); else sb.AppendFormat("null{0}", SLConstants.XmlAlignmentAttributeSeparator); if (this.HasReadingOrder) sb.AppendFormat("{0}{1}", this.ReadingOrder, SLConstants.XmlAlignmentAttributeSeparator); else sb.AppendFormat("null{0}", SLConstants.XmlAlignmentAttributeSeparator); return sb.ToString(); } internal int TextRotationToIntuitiveValue(uint Degree) { int iDegree = 0; if (Degree >= 0 && Degree <= 90) { iDegree = (int)Degree; } else if (Degree >= 91 && Degree <= 180) { iDegree = 90 - (int)Degree; } return iDegree; } internal uint TextRotationToOpenXmlValue(int Degree) { uint iDegree = 0; if (Degree >= 0 && Degree <= 90) { iDegree = (uint)Degree; } else if (Degree >= -90 && Degree < 0) { iDegree = (uint)(90 - Degree); } return iDegree; } internal string WriteToXmlTag() { StringBuilder sb = new StringBuilder(); sb.Append("<x:alignment"); if (this.HasHorizontal) { switch (this.Horizontal) { case HorizontalAlignmentValues.Center: sb.Append(" horizontal=\"center\""); break; case HorizontalAlignmentValues.CenterContinuous: sb.Append(" horizontal=\"centerContinuous\""); break; case HorizontalAlignmentValues.Distributed: sb.Append(" horizontal=\"distributed\""); break; case HorizontalAlignmentValues.Fill: sb.Append(" horizontal=\"fill\""); break; case HorizontalAlignmentValues.General: sb.Append(" horizontal=\"general\""); break; case HorizontalAlignmentValues.Justify: sb.Append(" horizontal=\"justify\""); break; case HorizontalAlignmentValues.Left: sb.Append(" horizontal=\"left\""); break; case HorizontalAlignmentValues.Right: sb.Append(" horizontal=\"right\""); break; } } if (this.HasVertical) { switch (this.Vertical) { case VerticalAlignmentValues.Bottom: sb.Append(" vertical=\"bottom\""); break; case VerticalAlignmentValues.Center: sb.Append(" vertical=\"center\""); break; case VerticalAlignmentValues.Distributed: sb.Append(" vertical=\"distributed\""); break; case VerticalAlignmentValues.Justify: sb.Append(" vertical=\"justify\""); break; case VerticalAlignmentValues.Top: sb.Append(" vertical=\"top\""); break; } } if (this.TextRotation != null) sb.AppendFormat(" textRotation=\"{0}\"", this.TextRotation.Value.ToString(CultureInfo.InvariantCulture)); if (this.WrapText != null) sb.AppendFormat(" wrapText=\"{0}\"", this.WrapText.Value ? "1" : "0"); if (this.Indent != null) sb.AppendFormat(" indent=\"{0}\"", this.Indent.Value.ToString(CultureInfo.InvariantCulture)); if (this.RelativeIndent != null) sb.AppendFormat(" relativeIndent=\"{0}\"", this.RelativeIndent.Value.ToString(CultureInfo.InvariantCulture)); if (this.JustifyLastLine != null) sb.AppendFormat(" justifyLastLine=\"{0}\"", this.JustifyLastLine.Value ? "1" : "0"); if (this.ShrinkToFit != null) sb.AppendFormat(" shrinkToFit=\"{0}\"", this.ShrinkToFit.Value ? "1" : "0"); if (this.HasReadingOrder) sb.AppendFormat(" readingOrder=\"{0}\"", (uint)this.ReadingOrder); sb.Append(" />"); return sb.ToString(); } internal SLAlignment Clone() { SLAlignment align = new SLAlignment(); align.HasHorizontal = this.HasHorizontal; align.vHorizontal = this.vHorizontal; align.HasVertical = this.HasVertical; align.vVertical = this.vVertical; align.iTextRotation = this.iTextRotation; align.WrapText = this.WrapText; align.Indent = this.Indent; align.RelativeIndent = this.RelativeIndent; align.JustifyLastLine = this.JustifyLastLine; align.ShrinkToFit = this.ShrinkToFit; align.HasReadingOrder = this.HasReadingOrder; align.vReadingOrder = this.vReadingOrder; return align; } } }
40.17801
181
0.556685
[ "MIT" ]
ARLM-Keller/SpreadsheetLight
style/SLAlignment.cs
15,350
C#
#nullable disable namespace CryptoWatch.Entities.Domains { public partial class Balance { public int Id { get; set; } public string Symbol { get; set; } public string AltSymbol { get; set; } public string Name { get; set; } public bool Exclude { get; set; } public decimal? Amount { get; set; } public decimal BalanceTarget { get; set; } public decimal BuyTarget { get; set; } public decimal SellTarget { get; set; } } }
34.4
51
0.585271
[ "MIT" ]
briankavanaugh/CryptoWatch
CryptoWatch.Entities/Domains/Balance.cs
518
C#
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; namespace OpenSim.Region.Framework.Interfaces { public interface ISharedRegionModule : IRegionModuleBase { /// <summary> /// This is called exactly once after all the shared region-modules have been instanciated and /// <see cref="IRegionModuleBase.Initialize"/>d. /// </summary> void PostInitialize(); } }
48.04878
102
0.736548
[ "BSD-3-Clause" ]
Ana-Green/halcyon-1
OpenSim/Region/Framework/Interfaces/ISharedRegionModule.cs
1,970
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GuiExt.cs" company="Slash Games"> // Copyright (c) Slash Games. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Slash.Unity.Common.GUI { using UnityEngine; /// <summary> /// Extends the Unity.GUI class. /// </summary> public static class GUIExt { #region Static Fields private static readonly int popupListHash = "PopupList".GetHashCode(); #endregion #region Delegates public delegate void PopupCallback(); #endregion #region Public Methods and Operators public static bool Popup( Rect position, ref bool showList, ref int listEntry, GUIContent buttonContent, object[] list, GUIStyle listStyle, PopupCallback callback) { return Popup( position, ref showList, ref listEntry, buttonContent, list, "button", "box", listStyle, callback); } public static bool Popup( Rect position, ref bool showList, ref int listEntry, GUIContent buttonContent, object[] list, GUIStyle buttonStyle, GUIStyle boxStyle, GUIStyle listStyle, PopupCallback callback) { int controlID = GUIUtility.GetControlID(popupListHash, FocusType.Passive); bool done = false; switch (Event.current.GetTypeForControl(controlID)) { case EventType.MouseDown: if (position.Contains(Event.current.mousePosition)) { GUIUtility.hotControl = controlID; showList = true; } break; case EventType.MouseUp: if (showList) { done = true; // Call our delegate method callback(); } break; } GUI.Label(position, buttonContent, buttonStyle); if (showList) { // Get our list of strings string[] text = new string[list.Length]; // convert to string for (int i = 0; i < list.Length; i++) { text[i] = list[i].ToString(); } Rect listRect = new Rect(position.x, position.y, position.width, list.Length * 20); GUI.Box(listRect, "", boxStyle); listEntry = GUI.SelectionGrid(listRect, listEntry, text, 1, listStyle); } if (done) { showList = false; } return done; } #endregion } }
31.30303
120
0.44466
[ "MIT" ]
SlashGames/slash-framework
Source/Slash.Unity.Common/Source/GUI/GuiExt.cs
3,101
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.System.Power { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented] #endif public static partial class BackgroundEnergyManager { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static uint ExcessiveUsageLevel { get { throw new global::System.NotImplementedException("The member uint BackgroundEnergyManager.ExcessiveUsageLevel is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static uint LowUsageLevel { get { throw new global::System.NotImplementedException("The member uint BackgroundEnergyManager.LowUsageLevel is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static uint MaxAcceptableUsageLevel { get { throw new global::System.NotImplementedException("The member uint BackgroundEnergyManager.MaxAcceptableUsageLevel is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static uint NearMaxAcceptableUsageLevel { get { throw new global::System.NotImplementedException("The member uint BackgroundEnergyManager.NearMaxAcceptableUsageLevel is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static uint NearTerminationUsageLevel { get { throw new global::System.NotImplementedException("The member uint BackgroundEnergyManager.NearTerminationUsageLevel is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static uint RecentEnergyUsage { get { throw new global::System.NotImplementedException("The member uint BackgroundEnergyManager.RecentEnergyUsage is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static uint RecentEnergyUsageLevel { get { throw new global::System.NotImplementedException("The member uint BackgroundEnergyManager.RecentEnergyUsageLevel is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static uint TerminationUsageLevel { get { throw new global::System.NotImplementedException("The member uint BackgroundEnergyManager.TerminationUsageLevel is not implemented in Uno."); } } #endif // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.LowUsageLevel.get // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.NearMaxAcceptableUsageLevel.get // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.MaxAcceptableUsageLevel.get // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.ExcessiveUsageLevel.get // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.NearTerminationUsageLevel.get // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.TerminationUsageLevel.get // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.RecentEnergyUsage.get // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.RecentEnergyUsageLevel.get // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.RecentEnergyUsageIncreased.add // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.RecentEnergyUsageIncreased.remove // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.RecentEnergyUsageReturnedToLow.add // Forced skipping of method Windows.System.Power.BackgroundEnergyManager.RecentEnergyUsageReturnedToLow.remove #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static event global::System.EventHandler<object> RecentEnergyUsageIncreased { [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.System.Power.BackgroundEnergyManager", "event EventHandler<object> BackgroundEnergyManager.RecentEnergyUsageIncreased"); } [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.System.Power.BackgroundEnergyManager", "event EventHandler<object> BackgroundEnergyManager.RecentEnergyUsageIncreased"); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static event global::System.EventHandler<object> RecentEnergyUsageReturnedToLow { [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.System.Power.BackgroundEnergyManager", "event EventHandler<object> BackgroundEnergyManager.RecentEnergyUsageReturnedToLow"); } [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.System.Power.BackgroundEnergyManager", "event EventHandler<object> BackgroundEnergyManager.RecentEnergyUsageReturnedToLow"); } } #endif } }
53.595588
211
0.762519
[ "Apache-2.0" ]
AbdalaMask/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.System.Power/BackgroundEnergyManager.cs
7,289
C#
using System; using System.Collections.Generic; using System.Text; using AvaExt.Common; using AvaExt.PagedSource; using AvaGE.FormDataReference.UserForm; using AvaExt.Manual.Table; namespace AvaGE.FormDataReference { public class MobDataReferenceSlipsPurchaseReturns: MobImplDataReferenceForGridForm { public MobDataReferenceSlipsPurchaseReturns(string pCmd) : base(pCmd, TableINVOICE.TABLE) { // source = new PagedSourceSlip(null); } protected override Type getActivityType() { return typeof(MobDataReferencePurchaseReturnsForm); } } }
22.965517
87
0.672673
[ "MIT" ]
rualb/ava-agent-xamarin
AvaGE/FormDataReference/MobDataReferenceSlipsPurchaseReturns.cs
666
C#
namespace TeamCity.MSBuild.Logger.Tests.Helpers { using System; using System.Collections.Generic; using System.Linq; using JetBrains.TeamCity.ServiceMessages; using JetBrains.TeamCity.ServiceMessages.Read; using Shouldly; using JetBrains.Annotations; internal static class ServiceMessages { private static readonly IServiceMessageParser Parser = new ServiceMessageParser(); [NotNull] public static IEnumerable<string> FilterTeamCityServiceMessages([NotNull] IEnumerable<string> lines) { if (lines == null) throw new ArgumentNullException(nameof(lines)); foreach (var line in lines) { if (line != null && line.StartsWith("##teamcity[")) { continue; } yield return line; } } public static int GetNumberServiceMessage([NotNull] IEnumerable<string> lines) { if (lines == null) throw new ArgumentNullException(nameof(lines)); return GetNumberServiceMessage(string.Join("\n", lines)); } public static void ResultShouldContainCorrectStructureAndSequence([NotNull] IEnumerable<string> lines) { ResultShouldContainCorrectStructureAndSequence(string.Join("\n", lines)); } private static int GetNumberServiceMessage([NotNull] string text) { if (text == null) throw new ArgumentNullException(nameof(text)); var actualMessages = Parser.ParseServiceMessages(text).ToList(); return actualMessages.Count; } private static void ResultShouldContainCorrectStructureAndSequence([NotNull] string text) { if (text == null) throw new ArgumentNullException(nameof(text)); var messages = Parser.ParseServiceMessages(text).ToList(); var rootFlows = new List<Flow>(); foreach (var serviceMessage in messages) { var message = new Message(serviceMessage); var flow = rootFlows.SingleOrDefault(i => i.FlowId == message.FlowIdAttr); if (flow == null) { flow = new Flow(message.CurrentFlowId); rootFlows.Add(flow); } flow.ProcessMessage(message); if (flow.IsFinished) { rootFlows.Remove(flow); } } } private class Message { public Message(IServiceMessage message) { if (message == null) throw new ArgumentNullException(nameof(message)); Name = message.Name; FlowIdAttr = message.GetValue("flowId") ?? string.Empty; NameAttr = message.GetValue("name"); ParentAttr = message.GetValue("parent"); CaptureStandardOutputAttr = message.GetValue("captureStandardOutput"); DurationAttr = message.GetValue("duration"); OutAttr = message.GetValue("duration"); MessageAttr = message.GetValue("message"); DetailsAttr = message.GetValue("details"); TcTagsAttr = message.GetValue("tc:tags"); IdentityAttr = message.GetValue("identity"); DescriptionAttr = message.GetValue("description"); KeyAttr = message.GetValue("key"); ValueAttr = message.GetValue("value"); } public string Name { get; } public string FlowIdAttr { get; } public string NameAttr { get; } public string ParentAttr { get; } public string CurrentFlowId => ParentAttr ?? FlowIdAttr; public string CaptureStandardOutputAttr { get; } public string DurationAttr { get; } public string OutAttr { get; } // ReSharper disable once MemberCanBePrivate.Local // ReSharper disable once UnusedAutoPropertyAccessor.Local public string MessageAttr { get; } public string DetailsAttr { get; } public string TcTagsAttr { get; } public string IdentityAttr { get; } public string DescriptionAttr { get; } public string KeyAttr { get; } public string ValueAttr { get; } } private class Flow { private readonly Stack<Message> _messages = new Stack<Message>(); private readonly HashSet<string> _statistics = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase); public Flow(string flowId) { FlowId = flowId; } public string FlowId { get; private set; } public bool IsFinished => _messages.Count == 0; public void ProcessMessage(Message message) { switch (message.Name) { case "message": break; case "blockOpened": IsNotEmpty(message.NameAttr, "Name attribute is empty"); FlowId = message.FlowIdAttr; _messages.Push(message); break; case "blockClosed": var blockClosed = _messages.Pop(); AreEqual(blockClosed.Name, "blockOpened", "blockOpened should close blockClosed"); AreEqual(blockClosed.NameAttr, message.NameAttr, "Invalid Name attribute"); break; case "testSuiteStarted": IsNotEmpty(message.FlowIdAttr, "FlowId attribute is empty"); IsNotEmpty(message.NameAttr, "Name attribute is empty"); FlowId = message.FlowIdAttr; _messages.Push(message); break; case "testSuiteFinished": var testSuiteStarted = _messages.Pop(); AreEqual(testSuiteStarted.Name, "testSuiteStarted", "testSuiteFinished should close testSuiteStarted"); AreEqual(testSuiteStarted.FlowIdAttr, message.FlowIdAttr, "Invalid FlowId attribute"); AreEqual(testSuiteStarted.NameAttr, message.NameAttr, "Invalid Name attribute"); break; case "flowStarted": IsNotEmpty(message.FlowIdAttr, "Invalid FlowId attribute"); AreEqual(message.ParentAttr, FlowId, "Invalid Parent attribute"); FlowId = message.FlowIdAttr; _messages.Push(message); break; case "flowFinished": AreEqual(message.FlowIdAttr, FlowId, "Invalid FlowId attribute"); Greater(_messages.Count, 0, "flowFinished should close flowStarted"); var flowStarted = _messages.Pop(); AreEqual(flowStarted.Name, "flowStarted", "flowFinished should close flowStarted"); FlowId = flowStarted.ParentAttr; break; case "testStarted": AreEqual(message.FlowIdAttr, FlowId, "Invalid FlowId attribute"); IsNotEmpty(message.NameAttr, "Name attribute is empty"); if (message.CaptureStandardOutputAttr != null) AreEqual(message.CaptureStandardOutputAttr, "false", "Invalid CaptureStandardOutput attribute"); _messages.Push(message); break; case "testFinished": AreEqual(message.FlowIdAttr, FlowId, "Invalid FlowId attribute"); IsNotEmpty(message.NameAttr, "Name attribute is empty"); Greater(_messages.Count, 0, "testFinished should close testStarted"); var testStarted = _messages.Pop(); AreEqual(testStarted.Name, "testStarted", "testFinished should close testStarted"); AreEqual(testStarted.NameAttr, message.NameAttr, "Invalid Name attribute"); IsNotEmpty(message.DurationAttr, "Duration attribute is empty"); break; case "testStdOut": AreEqual(message.FlowIdAttr, FlowId, "Invalid FlowId attribute"); IsNotEmpty(message.NameAttr, "Name attribute is empty"); Greater(_messages.Count, 1, "testStdOut should be within testStarted and testFinished"); var testStartedForStdOut = _messages.Peek(); AreEqual(testStartedForStdOut.Name, "testStarted", "testStdOut should be within testStarted and testFinished"); AreEqual(testStartedForStdOut.NameAttr, message.NameAttr, "Invalid Name attribute"); IsNotEmpty(message.OutAttr, "Out attribute is empty"); IsNotEmpty(message.TcTagsAttr, "tc:tags should be tc:parseServiceMessagesInside"); break; case "testFailed": AreEqual(message.FlowIdAttr, FlowId, "Invalid FlowId attribute"); IsNotEmpty(message.NameAttr, "Name attribute is empty"); Greater(_messages.Count, 1, "testFailed should be within testStarted and testFinished"); var testStartedForTestFailed = _messages.Peek(); AreEqual(testStartedForTestFailed.Name, "testStarted", "testFailed should be within testStarted and testFinished"); AreEqual(testStartedForTestFailed.NameAttr, message.NameAttr, "Invalid Name attribute"); // IsNotEmpty(message.MessageAttr, "Message attribute is empty"); IsNotNull(message.DetailsAttr, "Details attribute is empty"); break; case "testIgnored": AreEqual(message.FlowIdAttr, FlowId, "Invalid FlowId attribute"); IsNotEmpty(message.NameAttr, "Name attribute is empty"); Greater(_messages.Count, 1, "testIgnored should be within testStarted and testFinished"); var testStartedForTestIgnored = _messages.Peek(); AreEqual(testStartedForTestIgnored.Name, "testStarted", "testIgnored should be within testStarted and testFinished"); AreEqual(testStartedForTestIgnored.NameAttr, message.NameAttr, "Invalid Name attribute"); // IsNotEmpty(message.MessageAttr, "Message attribute is empty"); break; case "buildProblem": IsNotEmpty(message.IdentityAttr, "Identity attribute is empty"); IsNotEmpty(message.DescriptionAttr, "Description attribute is empty"); break; case "buildStatisticValue": IsNotEmpty(message.KeyAttr, "Key attribute is empty"); IsNotEmpty(message.ValueAttr, "Value attribute is empty"); if (!_statistics.Add(message.KeyAttr)) { Fail($"Statistics {message.KeyAttr} already exists"); } break; default: Fail($"Unexpected message {message.Name}"); break; } } } private static void Fail(string message) { throw new Exception(message); } private static void IsNotNull(string str, string message) { str.ShouldNotBeNull(message); } private static void Greater(int val1, int val2, string message) { val1.ShouldBeGreaterThan(val2, message); } private static void IsNotEmpty(string str, string message = "") { str.ShouldNotBeNullOrEmpty(message); } private static void AreEqual<T>(T val1, T val2, string message) { val1.ShouldBe(val2, message); } } }
43.944056
141
0.546626
[ "Apache-2.0" ]
JetBrains/TeamCity.MSBuild.Logger
TeamCity.MSBuild.Logger.Tests/Helpers/ServiceMessages.cs
12,570
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; namespace _5.Extract_Email { class ExtractEmail { static void Main(string[] args) { string input = Console.ReadLine(); Regex regex = new Regex(@"((?<=\s)[a-zA-Z0-9]+([-.]\w*)*@[a-zA-Z]+?([.-][a-zA-Z]*)*(\.[a-z]{2,}))"); MatchCollection matches = regex.Matches(input); foreach (Match item in matches) { Console.WriteLine(item.Value); } } } }
23.111111
112
0.552885
[ "MIT" ]
DimitarIvanov8/software-university
Homeworks/Regular Expressions - Exercise/5. Extract Email/ExtractEmail.cs
626
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void MultiplyUInt64() { var test = new VectorBinaryOpTest__MultiplyUInt64(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__MultiplyUInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt64> _fld1; public Vector256<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__MultiplyUInt64 testClass) { var result = Vector256.Multiply(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector256<UInt64> _clsVar1; private static Vector256<UInt64> _clsVar2; private Vector256<UInt64> _fld1; private Vector256<UInt64> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__MultiplyUInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); } public VectorBinaryOpTest__MultiplyUInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Multiply( Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.Multiply), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Multiply), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt64)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Multiply( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr); var result = Vector256.Multiply(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__MultiplyUInt64(); var result = Vector256.Multiply(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Multiply(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Multiply(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<UInt64> op1, Vector256<UInt64> op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (ulong)(left[0] * right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (ulong)(left[i] * right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Multiply)}<UInt64>(Vector256<UInt64>, Vector256<UInt64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
44.011594
190
0.604847
[ "MIT" ]
333fred/runtime
src/tests/JIT/HardwareIntrinsics/General/Vector256/Multiply.UInt64.cs
15,184
C#
namespace SharpBucket.V2.Pocos { public class CommentsInfo : ListBasedPage<Comment> { } }
17
54
0.686275
[ "MIT" ]
shannonphillipl/SharpBucket
SharpBucket/V2/Pocos/CommentsInfo.cs
104
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org) // Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net) // Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp) // See the LICENSE.md file in the project root for full license information. using System; namespace Stride.UI.Events { /// <summary> /// Represents and identifies a routed event and declares its characteristics. /// </summary> public abstract class RoutedEvent { /// <summary> /// Gets the identifying name of the routed event. /// </summary> public string Name { get; internal set; } /// <summary> /// Gets the registered owner type of the routed event. /// </summary> public Type OwnerType { get; internal set; } /// <summary> /// Gets the routing strategy of the routed event. /// </summary> public RoutingStrategy RoutingStrategy { get; internal set; } internal abstract Type HandlerSecondArgumentType { get; } internal RoutedEvent() { } } /// <summary> /// A routed event typed with the <see cref="RoutedEventArgs"/> it triggers. /// </summary> /// <typeparam name="T">The type of <see cref="RoutedEventArgs"/> the routed event triggers</typeparam> public sealed class RoutedEvent<T> : RoutedEvent where T : RoutedEventArgs { internal override Type HandlerSecondArgumentType => typeof(T); } }
33.369565
107
0.639088
[ "MIT" ]
Ethereal77/stride
sources/engine/Stride.UI/Events/RoutedEvent.cs
1,535
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.PowerShell.Cmdlets.Migrate.Models.Api20210210 { using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions; /// <summary>Update replication protected item provider specific input.</summary> public partial class UpdateReplicationProtectedItemProviderInput { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IUpdateReplicationProtectedItemProviderInput. /// Note: the Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IUpdateReplicationProtectedItemProviderInput interface /// is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the payload. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IUpdateReplicationProtectedItemProviderInput. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IUpdateReplicationProtectedItemProviderInput FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode node) { if (!(node is Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json)) { return null; } // Polymorphic type -- select the appropriate constructor using the discriminator switch ( json.StringProperty("instanceType") ) { case "A2A": { return new A2AUpdateReplicationProtectedItemInput(json); } case "HyperVReplicaAzure": { return new HyperVReplicaAzureUpdateReplicationProtectedItemInput(json); } case "InMageAzureV2": { return new InMageAzureV2UpdateReplicationProtectedItemInput(json); } case "InMageRcm": { return new InMageRcmUpdateReplicationProtectedItemInput(json); } } return new UpdateReplicationProtectedItemProviderInput(json); } /// <summary> /// Serializes this instance of <see cref="UpdateReplicationProtectedItemProviderInput" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /// />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="UpdateReplicationProtectedItemProviderInput" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /// />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); AfterToJson(ref container); return container; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject into a new instance of <see cref="UpdateReplicationProtectedItemProviderInput" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject instance to deserialize from.</param> internal UpdateReplicationProtectedItemProviderInput(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } {_instanceType = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)InstanceType;} AfterFromJson(json); } } }
62.585185
282
0.67002
[ "MIT" ]
Agazoth/azure-powershell
src/Migrate/generated/api/Models/Api20210210/UpdateReplicationProtectedItemProviderInput.json.cs
8,315
C#
/* Copyright <2021> <Thorben Linneweber> * * 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; namespace GJKEPADemo { public class PhongShader : BasicShader, IModelViewProjection, IViewPosition { public UniformMatrix4 Model { private set; get; } public UniformMatrix4 View { private set; get; } public UniformMatrix4 Projection { private set; get; } public UniformVector3 ViewPosition { private set; get; } public UniformVector3 Ambient { private set; get; } public UniformVector3 Diffuse { private set; get; } public UniformVector3 Specular { private set; get; } public UniformFloat Shininess { private set; get; } public UniformFloat Alpha { private set; get; } public PhongShader() : base(vshader, fshader) { Model = this.Uniforms["model"] as UniformMatrix4; View = this.Uniforms["view"] as UniformMatrix4; Projection = this.Uniforms["projection"] as UniformMatrix4; ViewPosition = this.Uniforms["viewPos"] as UniformVector3; Ambient = this.Uniforms["material.ambient"] as UniformVector3; Diffuse = this.Uniforms["material.diffuse"] as UniformVector3; Specular = this.Uniforms["material.specular"] as UniformVector3; Shininess = this.Uniforms["material.shininess"] as UniformFloat; Alpha = this.Uniforms["material.alpha"] as UniformFloat; } public void SetDefaultMaterial() { Ambient.Set(0.5f,0.5f,0.5f); Diffuse.Set(0.6f,0.6f,0.6f); Specular.Set(0.3f,0.3f,0.3f); Shininess.Set(128.0f); Alpha.Set(1.0f); } private static string vshader = @" #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec3 aNorm; uniform mat4 model; uniform mat4 view; uniform mat4 projection; out vec3 normal; out vec3 pos; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0); normal = mat3(transpose(inverse(model))) * aNorm; pos = vec3(model * vec4(aPos, 1.0)); } "; private static string fshader = @" #version 330 core struct Material { vec3 ambient; vec3 diffuse; vec3 specular; float shininess; float alpha; }; uniform Material material; uniform vec3 viewPos; in vec3 normal; in vec3 pos; out vec4 FragColor; void main() { vec3 lightColor = vec3(1,1,1); vec3 lights[4]; // three spot-lights from above, // one diffusive reflection from the ground lights[0] = vec3(-10, 20, 0); lights[1] = vec3(10, 20, 0); lights[2] = vec3(0, 10, -10); lights[3] = vec3(0, -10, 0); vec3 nn = normalize(normal); // ambient vec3 ambient = lightColor * material.ambient; vec3 diffusive = vec3(0, 0, 0); vec3 specular = vec3(0, 0, 0); for(int i=0; i<4; i++) { // diffuse vec3 lightDir = normalize(lights[i] - pos); float diff = max(-dot(nn, lightDir), 0.0); diffusive += lightColor * diff * material.diffuse; } for(int i=0; i<3; i++) { // specular vec3 lightDir = normalize(lights[i] - pos); vec3 viewDir = normalize(viewPos - pos); vec3 reflectDir = reflect(-lightDir, nn); float spec = pow(max(dot(viewDir, reflectDir),0.0), material.shininess); specular += lightColor * spec * material.specular; } vec3 result = ambient + 0.25*diffusive + 0.333*specular; FragColor = vec4(result, material.alpha); } "; } }
35.971831
88
0.586335
[ "MIT" ]
notgiven688/unified_epa
src/Shaders/PhongShader.cs
5,108
C#
using Business.Abstract; using Entities; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NetCoreWebMvc.Controllers { public class OrderTypeController : Controller { IOrder_TypeService _order_TypeService; public OrderTypeController(IOrder_TypeService order_TypeService) { _order_TypeService = order_TypeService; } public ActionResult Index() { var get = _order_TypeService.getAll().Data; return View(get); } [HttpPost] public IActionResult Add(Order_Type order_Type) { if (ModelState.IsValid) { var dataa = new Order_Type { orderTypeName = order_Type.orderTypeName, }; var order_Typeresult = _order_TypeService.Add(dataa); if (order_Typeresult.Success) { return RedirectToAction("Index", "OrderType"); } else { return RedirectToAction("Add", "OrderType"); } } return View(order_Type); } [HttpPost] public IActionResult Updated(Order_Type order_Type, int id) { var update = _order_TypeService.Update(order_Type); var id2 = _order_TypeService.getById(id).Data; if (update.Success) { id2.id = order_Type.id; id2.orderTypeName = order_Type.orderTypeName.Trim(); return RedirectToAction("Index"); } return View(); } public IActionResult Deleted(int id) { var id2 = _order_TypeService.getById(id).Data; _order_TypeService.Delete(id2); return RedirectToAction("Index"); } public IActionResult Add() { return View(); } public IActionResult Updated(int id) { return View(); } } }
20.790476
72
0.527256
[ "MIT" ]
ugurkurekci/CoffeiSoft
NetCoreWebMvc/Areas/Admin/Controllers/OrderTypeController.cs
2,185
C#
using Microsoft.QualityTools.Testing.Fakes; using Microsoft.Research.DataOnboarding.DomainModel; using Microsoft.Research.DataOnboarding.FileService.Interface; using Microsoft.Research.DataOnboarding.FileService.Interface.Fakes; using Microsoft.Research.DataOnboarding.FileService.Models; using Microsoft.Research.DataOnboarding.Services.UserService; using Microsoft.Research.DataOnboarding.Services.UserService.Fakes; using Microsoft.Research.DataOnboarding.TestUtilities; using Microsoft.Research.DataOnboarding.Utilities.Extensions.Fakes; using Microsoft.Research.DataOnboarding.WebApi.Api; using Microsoft.Research.DataOnboarding.WebApi.Fakes; using Microsoft.Research.DataOnboarding.WebApi.FileHandlers; using Microsoft.Research.DataOnboarding.WebApi.Helpers.Fakes; using Microsoft.Research.DataOnboarding.WebApi.FileHandlers.Fakes; using Microsoft.Research.DataOnboarding.WebApi.Resources; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Fakes; using System.Runtime.Serialization; using System.Threading.Tasks; using System.Web; using System.Web.Fakes; using System.Web.Http; using System.Web.Http.Hosting; using Memory = System.IO; namespace Microsoft.Research.DataOnboarding.WebApi.Tests.UnitTests { [TestClass] public class BlobControllerUnitTests { public HttpContext context; private IFileService fileService = null; private IFileServiceFactory fileServiceFactory = null; [TestMethod] [TestCategory(TestCategories.UnitTest)] public void Allow_File_Download_For_Valid_UserID_and_FileId() { File fakeFile = null; byte[] byteArray = null; this.fileService = new StubIFileService() { DownloadFileInt32Int32 = (userId, fileId) => { return new DataDetail() { FileDetail = fakeFile, FileNameToDownLoad = fakeFile.Name, MimeTypeToDownLoad = "text/plain", DataStream = byteArray }; } }; BlobController controller = SetupBaseAndRequest(out fakeFile, HttpMethod.Get); // Serialize the object to send as stream byteArray = SerializeObject(fakeFile); HttpResponseMessage response; // Perform response = controller.DownLoadFile(fakeFile.FileId); // Assert Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, "Stataus is not as expected(OK)"); var result = response.Content.ReadAsByteArrayAsync().Result; //Deserialize the object to identify results File resultFile = (File)DeserializeObject<File>(result); Assert.AreEqual(resultFile.Name, fakeFile.Name, "Expected and Actual result is not same."); Assert.AreEqual(resultFile.FileId, fakeFile.FileId, "Expected and Actual result is not same."); Assert.AreEqual(resultFile.RepositoryId, fakeFile.RepositoryId, "Expected and Actual result is not same."); Assert.AreEqual(resultFile.CreatedBy, fakeFile.CreatedBy, "Expected and Actual result is not same."); } [TestMethod] [TestCategory(TestCategories.UnitTest)] public void Return_Error_On_Download_When_FileService_Is_Null() { File fakeFile = null; this.fileService = null; BlobController controller = SetupBaseAndRequest(out fakeFile, HttpMethod.Get); // Perform var response = controller.DownLoadFile(fakeFile.FileId); // Assert Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest, "Stataus is not as expected"); var result = response.Content.ReadAsAsync<HttpError>().Result; Assert.IsNotNull(result, "Result is not as Expected"); Assert.AreEqual(result.Message, MessageStrings.Invalid_File_Id, "Result is not as expected"); } [TestMethod] [TestCategory(TestCategories.UnitTest)] [ExpectedException(typeof(AggregateException), "An empty file name was inappropriately allowed.")] public void Post_ShouldThrowArgumentException_WhenfileNameIsNullOrEmpty() { IFileServiceFactory fileServiceFactory = new StubIFileServiceFactory() { //GetFileServiceStringSkyDriveConfiguration = (instanceName, skyDriveConfiguration) => { return null; } }; IUserService userService = new StubIUserService(); IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory(); try { using (ShimsContext.Create()) { ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => null; BlobController blobController = new BlobController(fileServiceFactory, userService, fileHandlerFactory); Task task = blobController.Post(string.Empty, string.Empty, string.Empty); task.Wait(); } Assert.Fail("Should have exceptioned above!"); } catch (AggregateException ex) { if (ex.InnerException != null && ex.InnerException is ArgumentException) throw; } } [TestMethod] [TestCategory(TestCategories.UnitTest)] [ExpectedException(typeof(AggregateException), "An empty file extension was inappropriately allowed.")] public void Post_ShouldThrowArgumentException_WhenFileExtensionIsNullOrEmpty() { IFileServiceFactory fileServiceFactory = new StubIFileServiceFactory() { GetFileServiceString = (instanceName) => { return null; } }; IUserService userService = new StubIUserService(); IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory(); try { using (ShimsContext.Create()) { ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => null; BlobController blobController = new BlobController(fileServiceFactory, userService, fileHandlerFactory); Task task = blobController.Post("SomeFileName", string.Empty, string.Empty); task.Wait(); } Assert.Fail("Should have exceptioned above!"); } catch (AggregateException ex) { if (ex.InnerException != null && ex.InnerException is ArgumentException) throw; } } [TestMethod] [TestCategory(TestCategories.UnitTest)] [ExpectedException(typeof(AggregateException), "An empty content type was inappropriately allowed.")] public void Post_ShouldThrowArgumentException_WhenContentTypeIsNullOrEmpty() { IFileServiceFactory fileServiceFactory = new StubIFileServiceFactory() { GetFileServiceString = (instanceName) => { return null; } }; IUserService userService = new StubIUserService(); IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory(); try { using (ShimsContext.Create()) { ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => null; BlobController blobController = new BlobController(fileServiceFactory, userService, fileHandlerFactory); Task task = blobController.Post("SomeFileName", "SomeFileExtension", string.Empty); task.Wait(); } Assert.Fail("Should have exceptioned above!"); } catch (AggregateException ex) { if (ex.InnerException != null && ex.InnerException is ArgumentException) throw; } } [TestMethod] [TestCategory(TestCategories.UnitTest)] [ExpectedException(typeof(AggregateException), "A null bufferless input stream was inappropriately allowed.")] public void Post_ShouldThrowArgumentNullException_WhenBufferlessInputStreamIsNull() { IFileServiceFactory fileServiceFactory = new StubIFileServiceFactory() { GetFileServiceString = (instanceName) => { return null; } }; IUserService userService = new StubIUserService(); IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory(); try { using (ShimsContext.Create()) { ShimHttpContext.CurrentGet = () => new ShimHttpContext(); ShimHttpContext.AllInstances.RequestGet = httpContext => new ShimHttpRequest(); ShimHttpRequest.AllInstances.GetBufferlessInputStream = httpRequest => null; ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => null; BlobController blobController = new BlobController(fileServiceFactory, userService, fileHandlerFactory); Task task = blobController.Post("SomeFileName", "SomeFileExtension", "SomeContentType"); task.Wait(); } Assert.Fail("Should have exceptioned above!"); } catch (AggregateException ex) { if (ex.InnerException != null && ex.InnerException is ArgumentException) throw; } } [TestMethod] [TestCategory(TestCategories.UnitTest)] public void Post_ShouldReturnHttpStatusCodeOk_WhenBufferlessInputStreamIsNotNull() { HttpResponseMessage httpResponseMessage = null; IFileService fileService = new StubIFileService() { UploadFileDataDetail = dd => { dd.FileDetail = new File() { FileId = 1 }; return dd; } }; IFileServiceFactory fileServiceFactory = new StubIFileServiceFactory() { GetFileServiceString = (instanceName) => fileService }; IUserService userService = new StubIUserService(); IFileHandler fileHandler = new StubIFileHandler() { UploadDataFile = df => new List<DataDetail>() { new DataDetail() { FileDetail = new File() { FileId = 1 } } } }; IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory() { GetFileHandlerStringInt32 = (type, userId) => fileHandler }; HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, string.Empty); httpRequestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration()); using (ShimsContext.Create()) { ShimHttpContext.CurrentGet = () => new ShimHttpContext(); ShimHttpContext.AllInstances.RequestGet = httpContext => new ShimHttpRequest(); ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => new User(); ShimStreamExtensions.GetBytesAsyncStream = stream => Task.FromResult(new byte[0]); ShimHttpRequest.AllInstances.GetBufferlessInputStream = httpRequest => new Memory.MemoryStream(); BlobController blobController = new BlobController(fileServiceFactory, userService, fileHandlerFactory); blobController.Request = httpRequestMessage; var task = blobController.Post("SomeFileName", "SomeFileExtension", "SomeContentType"); task.Wait(); httpResponseMessage = task.Result; } Assert.AreEqual(HttpStatusCode.OK, httpResponseMessage.StatusCode, "Stataus is not as expected(Bad Request)"); } [TestMethod] [TestCategory(TestCategories.UnitTest)] [ExpectedException(typeof(Exception), "File Service threw exception.")] public void DownLoadFile_ShouldThrowException_WhenFileServiceThrowsException() { File fakeFile = null; this.fileService = new StubIFileService() { DownloadFileInt32Int32 = (userId, fileId) => { throw new Exception("Cannot Download File"); } }; BlobController controller = SetupBaseAndRequest(out fakeFile, HttpMethod.Get); controller.DownLoadFile(fakeFile.FileId); } /// <summary> /// Setup Base for controller and Create Request /// </summary> /// <param name="fakeFile">file object</param> /// <param name="Method">MEthod type to pass (GET, PUT, POST or Delete)</param> /// <returns>Contrller object</returns> private BlobController SetupBaseAndRequest(out File fakeFile, HttpMethod Method) { fakeFile = new File() { Name = "test1", FileId = 100, RepositoryId = 1, CreatedBy = 1, FileAttributes = new[] { new FileAttribute() }, FileColumns = new[] { new FileColumn() }, FileMetadataFields = new[] { new FileMetadataField() }, FileQualityChecks = new[] { new FileQualityCheck() } }; this.fileServiceFactory = new StubIFileServiceFactory() { GetFileServiceString = (instanceName) => { return this.fileService; } }; IUserService userService = new Microsoft.Research.DataOnboarding.Services.UserService.Fakes.StubIUserService() { }; IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory(); BlobController blobController; using (ShimsContext.Create()) { ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => new User(); blobController = new BlobController(this.fileServiceFactory, userService, fileHandlerFactory); } blobController.Request = new HttpRequestMessage(Method, string.Empty); blobController.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = new HttpConfiguration(); // Perform return blobController; } [TestMethod] [TestCategory(TestCategories.UnitTest)] public void Return_Error_On_Download_When_Model_State_Is_Invalid() { File fakeFile = null; byte[] byteArray = null; this.fileService = new StubIFileService() { DownloadFileInt32Int32 = (userId, fileId) => { return new DataDetail() { FileDetail = fakeFile, FileNameToDownLoad = fakeFile.Name, MimeTypeToDownLoad = "text/plain", DataStream = byteArray }; } }; BlobController controller = SetupBaseAndRequest(out fakeFile, HttpMethod.Get); controller.ModelState.AddModelError("Invalid", "Invalid Model State"); // Serialize the object to send as stream byteArray = SerializeObject(fakeFile); // Perform var response = controller.DownLoadFile(fakeFile.FileId); // Assert Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest, "Stataus is not as expected"); var result = response.Content.ReadAsAsync<HttpError>().Result; Assert.IsNotNull(result, "Result is not as Expected"); } /// <summary> /// Serialize Object /// </summary> /// <typeparam name="T">Object type</typeparam> /// <param name="obj">Object that needs to be converted</param> /// <returns>byte stream</returns> private byte[] SerializeObject<T>(T obj) { DataContractSerializer se = new DataContractSerializer(typeof(T)); byte[] tempArr; using (Memory.MemoryStream ms = new Memory.MemoryStream()) { se.WriteObject(ms, obj); ms.Position = 0; tempArr = new byte[ms.Length]; ms.Read(tempArr, 0, Convert.ToInt32(ms.Length)); } return tempArr; } /// <summary> /// Deserialize Object /// </summary> /// <typeparam name="T">type of Object</typeparam> /// <param name="buffer">stream</param> /// <returns>object</returns> public object DeserializeObject<T>(byte[] buffer) { DataContractSerializer se = new DataContractSerializer(typeof(T)); Memory.MemoryStream memStream = new Memory.MemoryStream(buffer); object obj = se.ReadObject(memStream); return obj; } [TestMethod] [TestCategory(TestCategories.UnitTest)] public void DownLoadFile_ShouldThrowArgumentException_WhenNameIdentifierIsNullOrEmpty() { IFileServiceFactory fileServiceFactory = new StubIFileServiceFactory() { GetFileServiceString = (instanceName) => { return null; } }; IUserService userService = new StubIUserService(); IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory(); using (ShimsContext.Create()) { ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => null; BlobController blobController = new BlobController(fileServiceFactory, userService, fileHandlerFactory); blobController.Request = new HttpRequestMessage(HttpMethod.Post, string.Empty); blobController.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = new HttpConfiguration(); HttpResponseMessage httpResponseMessage = blobController.DownLoadFile(string.Empty, 0); Assert.AreEqual(HttpStatusCode.BadRequest, httpResponseMessage.StatusCode); } } [TestMethod] [TestCategory(TestCategories.UnitTest)] public void DownLoadFile_ShouldReturnBadRequestHttpStatusCode_WhenModelStateIsInvalid() { IFileServiceFactory fileServiceFactory = new StubIFileServiceFactory() { GetFileServiceString = (instanceName) => { return null; } }; IUserService userService = new StubIUserService(); IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory(); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, string.Empty); httpRequestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration()); HttpResponseMessage httpResponseMessage = null; using (ShimsContext.Create()) { ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => null; BlobController blobController = new BlobController(fileServiceFactory, userService, fileHandlerFactory); blobController.ModelState.AddModelError("Invalid", "Invalid Model State"); blobController.Request = httpRequestMessage; httpResponseMessage = blobController.DownLoadFile("SomeNameIdentifier", 0); } Assert.AreEqual(HttpStatusCode.BadRequest, httpResponseMessage.StatusCode, "Status Code is not as expected(Bad Request)"); } [TestMethod] [TestCategory(TestCategories.UnitTest)] public void DownLoadFile_ShouldReturnOktHttpStatusCode_WhenUserIdAndFileIdAreValid() { DataDetail dataDetail = new DataDetail() { FileNameToDownLoad = "abc.csv", DataStream = new byte[0] }; StubIFileService fileService = new StubIFileService() { DownloadFileInt32Int32 = (userId, fileId) => dataDetail }; IFileServiceFactory fileServiceFactory = new StubIFileServiceFactory() { GetFileServiceString = (instanceName) => fileService }; IUserService userService = new StubIUserService(); IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory(); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, string.Empty); httpRequestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration()); HttpResponseMessage httpResponseMessage = null; using (ShimsContext.Create()) { ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => null; ShimIdentityHelper.GetUserIUserServiceString = (us, ni) => new User(); BlobController blobController = new BlobController(fileServiceFactory, userService, fileHandlerFactory); blobController.Request = httpRequestMessage; httpResponseMessage = blobController.DownLoadFile("SomeNameIdentifier", 0); } Assert.AreEqual(HttpStatusCode.OK, httpResponseMessage.StatusCode, "Status Code is not as expected(Bad Request)"); } [TestMethod] [TestCategory(TestCategories.UnitTest)] [ExpectedException(typeof(AggregateException), "An empty name identifier was inappropriately allowed.")] public void Post_ShouldThrowArgumentException_WhenNameIdentifierIsNullOrEmpty() { IFileServiceFactory fileServiceFactory = new StubIFileServiceFactory() { GetFileServiceString = (instanceName) => { return null; } }; IUserService userService = new StubIUserService(); IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory(); try { using (ShimsContext.Create()) { ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => null; BlobController blobController = new BlobController(fileServiceFactory, userService, fileHandlerFactory); Task task = blobController.Post(string.Empty); task.Wait(); } Assert.Fail("Should have exceptioned above!"); } catch (AggregateException ex) { if (ex.InnerException != null && ex.InnerException is ArgumentException) throw; } } [TestMethod] [TestCategory(TestCategories.UnitTest)] [ExpectedException(typeof(AggregateException), "An empty name identifier was inappropriately allowed.")] public void Post_ShouldThrowHttpResponseException_WhenRequestContentIsNotMimeMultipart() { IFileServiceFactory fileServiceFactory = new StubIFileServiceFactory() { GetFileServiceString = (instanceName) => { return null; } }; IUserService userService = new StubIUserService(); IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory(); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, string.Empty); httpRequestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration()); httpRequestMessage.Content = new StubHttpContent(); try { using (ShimsContext.Create()) { ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => null; BlobController blobController = new BlobController(fileServiceFactory, userService, fileHandlerFactory); blobController.Request = httpRequestMessage; Task task = blobController.Post("SomeNameIdentifier"); task.Wait(); Assert.Fail("Should have exceptioned above!"); } } catch (AggregateException ex) { if (ex.InnerException != null && ex.InnerException is HttpResponseException) throw; } } [TestMethod] [TestCategory(TestCategories.UnitTest)] public void Post_ShouldReturnOktHttpStatusCode_WhenRequestContentIsMimeMultipart() { IFileServiceFactory fileServiceFactory = new StubIFileServiceFactory() { GetFileServiceString = (instanceName) => { return null; } }; IUserService userService = new StubIUserService(); IFileHandlerFactory fileHandlerFactory = new StubIFileHandlerFactory(); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, string.Empty); httpRequestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration()); HttpContent httpContent = new StubMultipartFormDataContent(); httpRequestMessage.Content = httpContent; using (ShimsContext.Create()) { ShimIdentityHelper.GetCurrentUserIUserServiceClaimsPrincipal = (us, cp) => null; ShimHttpContext.CurrentGet = () => new ShimHttpContext(); ShimHttpContext.AllInstances.ServerGet = httpContext => new ShimHttpServerUtility(); ShimHttpServerUtility.AllInstances.MapPathString = (hsu, s) => @"C:\"; BlobController blobController = new BlobController(fileServiceFactory, userService, fileHandlerFactory); blobController.Request = httpRequestMessage; Task task = blobController.Post("SomeNameIdentifier"); task.Wait(); } } } }
46.81338
211
0.616623
[ "MIT" ]
CDLUC3/dataup2
Tests/API/WebApi.Tests/UnitTests/BlobControllerUnitTests.cs
26,592
C#
using System; using System.Collections.Generic; using System.Text; using CarRental.Entities.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace CarRental.DataAccess.DbContexts.DbContextConfigurations { public class RentalConfigurations: IEntityTypeConfiguration<Rental> { public void Configure(EntityTypeBuilder<Rental> builder) { // customer car many to many relation builder .HasOne<Car>(c => c.Car) .WithMany(r => r.Rentals) .HasForeignKey(f => f.CarId); builder .HasOne<Customer>(c => c.Customer) .WithMany(r => r.Rentals) .HasForeignKey(f => f.CustomerId); } } }
29.592593
71
0.623279
[ "Apache-2.0" ]
kdrkrgz/Kiralamax
src/api/CarRental.DataAccess/DbContexts/DbContextConfigurations/RentalConfigurations.cs
801
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.ResourceManager; namespace Azure.ResourceManager.Network { internal class ExpressRouteCircuitConnectionOperationSource : IOperationSource<ExpressRouteCircuitConnectionResource> { private readonly ArmClient _client; internal ExpressRouteCircuitConnectionOperationSource(ArmClient client) { _client = client; } ExpressRouteCircuitConnectionResource IOperationSource<ExpressRouteCircuitConnectionResource>.CreateResult(Response response, CancellationToken cancellationToken) { using var document = JsonDocument.Parse(response.ContentStream); var data = ExpressRouteCircuitConnectionData.DeserializeExpressRouteCircuitConnectionData(document.RootElement); return new ExpressRouteCircuitConnectionResource(_client, data); } async ValueTask<ExpressRouteCircuitConnectionResource> IOperationSource<ExpressRouteCircuitConnectionResource>.CreateResultAsync(Response response, CancellationToken cancellationToken) { using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); var data = ExpressRouteCircuitConnectionData.DeserializeExpressRouteCircuitConnectionData(document.RootElement); return new ExpressRouteCircuitConnectionResource(_client, data); } } }
40.365854
192
0.770393
[ "MIT" ]
AikoBB/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/LongRunningOperation/ExpressRouteCircuitConnectionOperationSource.cs
1,655
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace PSO2emergencyGetter { class ChpDatabase_Writer : AbstractDBWriter { IChpDataBase chpDB; public ChpDatabase_Writer(IChpDataBase chpDB) : base(chpDB, "PSO2ChpTable") { this.chpDB = chpDB; } protected override void setDBtable() { chpDB.setTable(tablename); } public int writeDB(List<string> strData) { chpDB.cleartable(); string que = chpDB.ChpDataConvertQue(strData); object result = chpDB.command(que); if(result is int) { logOutput.writeLog("覇者の紋章のデータベースへの書き込みが失敗しました。"); return 1; } else { logOutput.writeLog("データベースに覇者の紋章の情報を書き込みました。"); return 0; } } //非同期で実行 public async Task AsyncWriteDB(List<string> stData) { await Task.Run(() => { writeDB(stData); }); } } }
23.285714
84
0.51972
[ "MIT" ]
Riunia/PSO2emergencyGetter
PSO2emergencyGetter/ChpDatabase_Writer.cs
1,255
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace sistema_rrhh.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [IgnoreAntiforgeryToken] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
25.515152
88
0.685273
[ "MIT" ]
Matthew-Gonzalez/sistema-mantencion-dis
sistema_rrhh/Pages/Error.cshtml.cs
842
C#
using GoToWindow.Plugins.ExpandBrowsersTabs.Common; using GoToWindow.Plugins.ExpandBrowsersTabs.Contracts; namespace GoToWindow.Plugins.ExpandBrowsersTabs.Chrome { public class ChromeTab : ShortcutBasedTab, ITab { public ChromeTab(string title, int tabIndex) : base(title, tabIndex) { } } }
21.785714
54
0.783607
[ "MIT" ]
christianrondeau/GoToWindow
GoToWindow.Plugins.ExpandBrowsersTabs/Chrome/ChromeTab.cs
307
C#
namespace Unifaun.Rest.Client.Models { public interface IBaseResponse { // string JsonData { get; set; } } }
16.25
40
0.615385
[ "MIT" ]
PolrSE/Unifaun.Rest.Client
src/Unifaun.Rest.Client/Models/BaseResponse.cs
132
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; namespace Chubrik.Kit { public static class ExceptionHandler { private static int _counter = 0; public static readonly List<IDataClient> Clients = new List<IDataClient>(); public static void Register(Exception exception, LogLevel level = LogLevel.Error) { var startTime = DateTimeOffset.Now; var message = Regex.Replace(exception.Message, @"\r?\n", " ") + GetPlaceSuffix(exception); var count = ++_counter; var logLabel = $"Exception #{count}"; LogService.Log($"{logLabel}: {message}", level); var fullText = $"{logLabel}\r\n{message}\r\n{ExtendedDump(exception)}"; var fileName = PathHelper.SafeFileName($"{count.ToString().PadLeft(3, '0')} {message}.txt"); foreach (var client in Clients) try { client.PushToWrite(PathHelper.Combine(Kit.DiagnisticsCurrentDirectory, fileName), fullText); } catch (Exception registerException) { Debug.Fail(registerException.ToString()); // no throw for register exception } LogService.Log($"{logLabel} registered at {TimeHelper.FormattedLatency(startTime)}"); } #region Utils private static string GetPlaceSuffix(Exception exception) { var match = Regex.Match(exception.ToString(), @"(\w+\.cs):line (\d+)"); return match.Success ? $" ({match.Groups[1].Value}:{match.Groups[2].Value})" : string.Empty; } private static string ExtendedDump(Exception exception) { var result = string.Empty; var innerest = exception.FirstInnerestException(); if (innerest != exception) result += $"\r\n\r\n\r\nFIRST INNEREST EXCEPTION:\r\n\r\n{innerest}\r\n"; var dump = exception.ToString().Replace(" --->", "\r\n--->"); result += $"\r\n\r\n\r\nFULL DUMP:\r\n\r\n{dump}\r\n"; return result; } #endregion } }
34.969231
112
0.563132
[ "MIT" ]
chubrik/Kit
Kit/Services/ExceptionHandler.cs
2,275
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace LetsGame.Web.Data.Migrations { public partial class event_notificationdate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<DateTime>( name: "StartingSoonNotificationSentAtUtc", table: "GroupEvents", type: "timestamp without time zone", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "StartingSoonNotificationSentAtUtc", table: "GroupEvents"); } } }
29.36
71
0.618529
[ "MIT" ]
leddt/lets-game
LetsGame.Web/Data/Migrations/20210119024634_event_notificationdate.cs
736
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 codepipeline-2015-07-09.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.CodePipeline.Model { /// <summary> /// Execution result information, such as the external execution ID. /// </summary> public partial class ActionExecutionResult { private string _externalExecutionId; private string _externalExecutionSummary; private string _externalExecutionUrl; /// <summary> /// Gets and sets the property ExternalExecutionId. /// <para> /// The action provider's external ID for the action execution. /// </para> /// </summary> public string ExternalExecutionId { get { return this._externalExecutionId; } set { this._externalExecutionId = value; } } // Check to see if ExternalExecutionId property is set internal bool IsSetExternalExecutionId() { return this._externalExecutionId != null; } /// <summary> /// Gets and sets the property ExternalExecutionSummary. /// <para> /// The action provider's summary for the action execution. /// </para> /// </summary> public string ExternalExecutionSummary { get { return this._externalExecutionSummary; } set { this._externalExecutionSummary = value; } } // Check to see if ExternalExecutionSummary property is set internal bool IsSetExternalExecutionSummary() { return this._externalExecutionSummary != null; } /// <summary> /// Gets and sets the property ExternalExecutionUrl. /// <para> /// The deepest external link to the external resource (for example, a repository URL /// or deployment endpoint) that is used when running the action. /// </para> /// </summary> [AWSProperty(Min=1, Max=2048)] public string ExternalExecutionUrl { get { return this._externalExecutionUrl; } set { this._externalExecutionUrl = value; } } // Check to see if ExternalExecutionUrl property is set internal bool IsSetExternalExecutionUrl() { return this._externalExecutionUrl != null; } } }
32.340206
110
0.637552
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CodePipeline/Generated/Model/ActionExecutionResult.cs
3,137
C#
/** * Copyright 2015 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: jmis $ * Last modified: $LastChangedDate: 2015-09-15 11:09:53 -0400 (Tue, 15 Sep 2015) $ * Revision: $LastChangedRevision: 9796 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Pharmacy.Pome_mt010040ca { using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Datatype; using Ca.Infoway.Messagebuilder.Datatype.Impl; using Ca.Infoway.Messagebuilder.Model; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Domainvalue; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Pharmacy.Merged; using System; /** * <summary>Business Name: Monitoring Programs</summary> * * <p>Allows association of additional business requirements * with a particular drug</p> <p>A system of additional * business rules, documentation or reporting associated with a * particular drug or group of drugs. These are typically * instituted to detect potential abuse, or to monitor * prescribing and/or dispensing patterns of a sensitive class * of medications. Examples include triplicate programs, * antibiotic monitoring programs, etc.</p> */ [Hl7PartTypeMappingAttribute(new string[] {"POME_MT010040CA.MonitoringProgram"})] public class MonitoringPrograms : MessagePartBean { private CV code; private ST title; private Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Pharmacy.Merged.AssignedEntity3 custodianAssignedEntity; public MonitoringPrograms() { this.code = new CVImpl(); this.title = new STImpl(); } /** * <summary>Business Name: Program Type</summary> * * <remarks>Relationship: * POME_MT010040CA.MonitoringProgram.code * Conformance/Cardinality: MANDATORY (1) <p>Used for * classifying and sorting monitoring programs.</p><p>This is * mandatory because, different program types have different * business rules.</p> <p>A coded value denoting a specific * kind of monitoring program. For example, &quot;Drugs of * potential abuse&quot;, &quot;Antibiotics&quot;, etc.</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"code"})] public ActMonitoringProtocolType Code { get { return (ActMonitoringProtocolType) this.code.Value; } set { this.code.Value = value; } } /** * <summary>Business Name: Program Name</summary> * * <remarks>Relationship: * POME_MT010040CA.MonitoringProgram.title * Conformance/Cardinality: REQUIRED (0-1) <p>Provides a * provider-recognizable label for the program.</p> <p>A * user-friendly label assigned to the monitoring program.</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"title"})] public String Title { get { return this.title.Value; } set { this.title.Value = value; } } /** * <summary>Relationship: * POME_MT010040CA.Custodian.assignedEntity</summary> * * <remarks>Conformance/Cardinality: REQUIRED (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"custodian/assignedEntity"})] public Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Pharmacy.Merged.AssignedEntity3 CustodianAssignedEntity { get { return this.custodianAssignedEntity; } set { this.custodianAssignedEntity = value; } } } }
43.544554
126
0.652115
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-r02_04_02/Main/Ca/Infoway/Messagebuilder/Model/Pcs_mr2009_r02_04_02/Pharmacy/Pome_mt010040ca/MonitoringPrograms.cs
4,398
C#
namespace cristales_pva { partial class g_variaciones { /// <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(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(g_variaciones)); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.label6 = new System.Windows.Forms.Label(); this.button4 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.datagridviewNE1 = new cristales_pva.datagridviewNE(); this.CP = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.clave = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.articulo = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.cantidad = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.operacion = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.removerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.label5 = new System.Windows.Forms.Label(); this.datagridviewNE2 = new cristales_pva.datagridviewNE(); this.contextMenuStrip2 = new System.Windows.Forms.ContextMenuStrip(this.components); this.eliminarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.modificarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.label3 = new System.Windows.Forms.Label(); this.comboBox2 = new System.Windows.Forms.ComboBox(); this.button1 = new System.Windows.Forms.Button(); this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.datagridviewNE1)).BeginInit(); this.contextMenuStrip1.SuspendLayout(); this.tabPage2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.datagridviewNE2)).BeginInit(); this.contextMenuStrip2.SuspendLayout(); this.SuspendLayout(); // // tabControl1 // this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Location = new System.Drawing.Point(12, 12); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(607, 436); this.tabControl1.TabIndex = 1; // // tabPage1 // this.tabPage1.Controls.Add(this.label6); this.tabPage1.Controls.Add(this.button4); this.tabPage1.Controls.Add(this.button3); this.tabPage1.Controls.Add(this.button2); this.tabPage1.Controls.Add(this.textBox1); this.tabPage1.Controls.Add(this.label4); this.tabPage1.Controls.Add(this.datagridviewNE1); this.tabPage1.Controls.Add(this.richTextBox1); this.tabPage1.Controls.Add(this.label1); this.tabPage1.Controls.Add(this.label2); this.tabPage1.Controls.Add(this.comboBox1); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(599, 410); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Generar"; this.tabPage1.UseVisualStyleBackColor = true; // // label6 // this.label6.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label6.AutoSize = true; this.label6.ForeColor = System.Drawing.Color.Red; this.label6.Location = new System.Drawing.Point(17, 242); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(393, 13); this.label6.TabIndex = 15; this.label6.Text = "*Coloca -1 en cantidad si deseas que el módulo conserve la cantidad por defecto."; // // button4 // this.button4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button4.Image = global::cristales_pva.Properties.Resources.Actions_edit_delete_icon; this.button4.Location = new System.Drawing.Point(555, 8); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(29, 23); this.button4.TabIndex = 14; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // button3 // this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button3.Image = global::cristales_pva.Properties.Resources.add_icon_16bits; this.button3.Location = new System.Drawing.Point(441, 242); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(143, 34); this.button3.TabIndex = 13; this.button3.Text = "Añadir Artículo"; this.button3.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button3.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // button2 // this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button2.Image = global::cristales_pva.Properties.Resources.save_16; this.button2.Location = new System.Drawing.Point(489, 370); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(95, 34); this.button2.TabIndex = 12; this.button2.Text = "Guardar"; this.button2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button2.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // textBox1 // this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox1.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper; this.textBox1.Location = new System.Drawing.Point(69, 10); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(480, 20); this.textBox1.TabIndex = 11; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(16, 13); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(47, 13); this.label4.TabIndex = 10; this.label4.Text = "Nombre:"; // // datagridviewNE1 // this.datagridviewNE1.AllowUserToAddRows = false; this.datagridviewNE1.AllowUserToDeleteRows = false; this.datagridviewNE1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.datagridviewNE1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.datagridviewNE1.BackgroundColor = System.Drawing.SystemColors.Highlight; this.datagridviewNE1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.datagridviewNE1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.CP, this.clave, this.articulo, this.cantidad, this.operacion}); this.datagridviewNE1.ContextMenuStrip = this.contextMenuStrip1; this.datagridviewNE1.Location = new System.Drawing.Point(16, 69); this.datagridviewNE1.Name = "datagridviewNE1"; this.datagridviewNE1.Size = new System.Drawing.Size(568, 167); this.datagridviewNE1.TabIndex = 9; // // CP // this.CP.HeaderText = "CP"; this.CP.Name = "CP"; this.CP.ReadOnly = true; // // clave // this.clave.HeaderText = "clave"; this.clave.Name = "clave"; this.clave.ReadOnly = true; // // articulo // this.articulo.HeaderText = "articulo"; this.articulo.Name = "articulo"; this.articulo.ReadOnly = true; // // cantidad // dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255))))); this.cantidad.DefaultCellStyle = dataGridViewCellStyle1; this.cantidad.HeaderText = "cantidad"; this.cantidad.Name = "cantidad"; // // operacion // this.operacion.HeaderText = "operacion"; this.operacion.Name = "operacion"; this.operacion.ReadOnly = true; // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.removerToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(164, 26); // // removerToolStripMenuItem // this.removerToolStripMenuItem.Name = "removerToolStripMenuItem"; this.removerToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D))); this.removerToolStripMenuItem.Size = new System.Drawing.Size(163, 22); this.removerToolStripMenuItem.Text = "Remover"; this.removerToolStripMenuItem.Click += new System.EventHandler(this.removerToolStripMenuItem_Click); // // richTextBox1 // this.richTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.richTextBox1.Location = new System.Drawing.Point(16, 295); this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.Size = new System.Drawing.Size(568, 69); this.richTextBox1.TabIndex = 8; this.richTextBox1.Text = ""; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(16, 41); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(36, 13); this.label1.TabIndex = 5; this.label1.Text = "Linea:"; // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(16, 279); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(66, 13); this.label2.TabIndex = 7; this.label2.Text = "Descripción:"; // // comboBox1 // this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(69, 38); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(515, 21); this.comboBox1.TabIndex = 6; // // tabPage2 // this.tabPage2.Controls.Add(this.label5); this.tabPage2.Controls.Add(this.datagridviewNE2); this.tabPage2.Controls.Add(this.label3); this.tabPage2.Controls.Add(this.comboBox2); this.tabPage2.Controls.Add(this.button1); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(599, 410); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Variaciones"; this.tabPage2.UseVisualStyleBackColor = true; // // label5 // this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label5.AutoSize = true; this.label5.ForeColor = System.Drawing.Color.Red; this.label5.Location = new System.Drawing.Point(14, 386); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(62, 13); this.label5.TabIndex = 11; this.label5.Text = "Cargando..."; this.label5.Visible = false; // // datagridviewNE2 // this.datagridviewNE2.AllowUserToAddRows = false; this.datagridviewNE2.AllowUserToDeleteRows = false; this.datagridviewNE2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.datagridviewNE2.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.datagridviewNE2.BackgroundColor = System.Drawing.SystemColors.Highlight; this.datagridviewNE2.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.datagridviewNE2.ContextMenuStrip = this.contextMenuStrip2; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.datagridviewNE2.DefaultCellStyle = dataGridViewCellStyle2; this.datagridviewNE2.Location = new System.Drawing.Point(16, 48); this.datagridviewNE2.Name = "datagridviewNE2"; this.datagridviewNE2.ReadOnly = true; dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.datagridviewNE2.RowsDefaultCellStyle = dataGridViewCellStyle3; this.datagridviewNE2.Size = new System.Drawing.Size(568, 333); this.datagridviewNE2.TabIndex = 9; // // contextMenuStrip2 // this.contextMenuStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.eliminarToolStripMenuItem, this.modificarToolStripMenuItem}); this.contextMenuStrip2.Name = "contextMenuStrip2"; this.contextMenuStrip2.Size = new System.Drawing.Size(171, 48); // // eliminarToolStripMenuItem // this.eliminarToolStripMenuItem.Name = "eliminarToolStripMenuItem"; this.eliminarToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D))); this.eliminarToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.eliminarToolStripMenuItem.Text = "Eliminar"; this.eliminarToolStripMenuItem.Click += new System.EventHandler(this.eliminarToolStripMenuItem_Click); // // modificarToolStripMenuItem // this.modificarToolStripMenuItem.Name = "modificarToolStripMenuItem"; this.modificarToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.M))); this.modificarToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.modificarToolStripMenuItem.Text = "Modificar"; this.modificarToolStripMenuItem.Click += new System.EventHandler(this.modificarToolStripMenuItem_Click); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(14, 19); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(36, 13); this.label3.TabIndex = 7; this.label3.Text = "Linea:"; // // comboBox2 // this.comboBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.comboBox2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox2.FormattingEnabled = true; this.comboBox2.Location = new System.Drawing.Point(59, 16); this.comboBox2.Name = "comboBox2"; this.comboBox2.Size = new System.Drawing.Size(485, 21); this.comboBox2.TabIndex = 8; this.comboBox2.SelectedIndexChanged += new System.EventHandler(this.comboBox2_SelectedIndexChanged); // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button1.Image = global::cristales_pva.Properties.Resources.Counterclockwise_arrow_icon; this.button1.Location = new System.Drawing.Point(550, 15); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(34, 23); this.button1.TabIndex = 10; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // backgroundWorker1 // this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork); // // g_variaciones // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(631, 460); this.Controls.Add(this.tabControl1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "g_variaciones"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Variaciones"; this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.datagridviewNE1)).EndInit(); this.contextMenuStrip1.ResumeLayout(false); this.tabPage2.ResumeLayout(false); this.tabPage2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.datagridviewNE2)).EndInit(); this.contextMenuStrip2.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private datagridviewNE datagridviewNE1; private System.Windows.Forms.RichTextBox richTextBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox comboBox1; private datagridviewNE datagridviewNE2; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox comboBox2; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem removerToolStripMenuItem; private System.Windows.Forms.ContextMenuStrip contextMenuStrip2; private System.Windows.Forms.ToolStripMenuItem eliminarToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem modificarToolStripMenuItem; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label4; private System.ComponentModel.BackgroundWorker backgroundWorker1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label5; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.DataGridViewTextBoxColumn CP; private System.Windows.Forms.DataGridViewTextBoxColumn clave; private System.Windows.Forms.DataGridViewTextBoxColumn articulo; private System.Windows.Forms.DataGridViewTextBoxColumn cantidad; private System.Windows.Forms.DataGridViewTextBoxColumn operacion; private System.Windows.Forms.Label label6; } }
55.956044
179
0.635153
[ "MIT" ]
ingIsaac/AlussPr
cristales_pva/g_variaciones.Designer.cs
25,466
C#
using System; using Firebase.Firestore; using Firebase; using System.Collections.Concurrent; namespace Plugin.CloudFirestore { public class CloudFirestoreImplementation : ICloudFirestore { public IFirestore Instance => FirestoreProvider.Firestore; public IFirestore GetInstance(string appName) { return FirestoreProvider.GetFirestore(appName); } } }
22.722222
66
0.716381
[ "MIT" ]
CatalinPrata/Plugin.CloudFirestore
Plugin.CloudFirestore.Android/CloudFirestoreImplementation.cs
411
C#
namespace XLabs { using System; using System.Windows.Input; /// <summary> /// Generic RelayCommand class. /// </summary> /// <typeparam name="T"></typeparam> public class RelayCommand<T> : ICommand { /// <summary> /// The execute /// </summary> private readonly Action<T> execute; /// <summary> /// The can execute /// </summary> private readonly Predicate<T> canExecute; /// <summary> /// Initializes a new instance of the <see cref="RelayCommand{T}" /> class. /// </summary> /// <param name="execute">The execute action.</param> /// <exception cref="System.ArgumentNullException">execute</exception> public RelayCommand(Action<T> execute) : this(execute, null) { } /// <summary> /// Initializes a new instance of the <see cref="RelayCommand{T}" /> class. /// </summary> /// <param name="execute">The execute.</param> /// <param name="canExecute">The can execute predicate.</param> /// <exception cref="System.ArgumentNullException">execute</exception> public RelayCommand(Action<T> execute, Predicate<T> canExecute) { if (execute == null) { throw new ArgumentNullException("execute"); } this.execute = execute; if (canExecute != null) { this.canExecute = canExecute; } } /// <summary> /// Occurs when changes occur that affect whether the command should execute. /// </summary> public event EventHandler CanExecuteChanged; /// <summary> /// Raise <see cref="RelayCommand{T}.CanExecuteChanged" /> event. /// </summary> public void RaiseCanExecuteChanged() { var handler = this.CanExecuteChanged; if (handler != null) { handler(this, EventArgs.Empty); } } /// <summary> /// Determines whether this instance can execute the specified parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <returns><c>true</c> if this instance can execute the specified parameter; otherwise, <c>false</c>.</returns> public bool CanExecute(object parameter) { return this.canExecute == null || this.canExecute.Invoke((T)parameter); } /// <summary> /// Executes the specified parameter. /// </summary> /// <param name="parameter">The parameter.</param> public virtual void Execute(object parameter) { if (CanExecute(parameter)) { this.execute((T)parameter); } } } }
31.891304
122
0.524199
[ "Apache-2.0" ]
DavidStrickland0/XLabs
src/XLabs.Core/RelayCommand{T}.cs
2,934
C#
using System.Linq; using FeatureFlags.FeatureFlagProviders; using FeatureFlags.FeatureFlagProviders.Inmemory; using Xunit; namespace FeatureFlagTests.FeatureFlagProviders { public class InMemoryFeatureFlagProviderTests { [Fact] public void EmptyInmemory_GetFlags_ReturnsEmptyCollection() { var featureFlagProvider = new InMemoryFeatureFlagProvider(); var result = featureFlagProvider.GetFlags(); Assert.Empty(result); } [Fact] public void CanAddFlag() { const string testFlag = nameof(testFlag); var featureFlagProvider = new InMemoryFeatureFlagProvider(); featureFlagProvider.AddFlag(testFlag); var result = featureFlagProvider.GetFlags(); var flag = Assert.Single(result); Assert.Equal(testFlag, flag.Name); } [Fact] public void CanAddFlagMultipleTimes_But_RemainOnlyOne() { const string testFlag = nameof(testFlag); var featureFlagProvider = new InMemoryFeatureFlagProvider(); featureFlagProvider.AddFlag(testFlag); featureFlagProvider.AddFlag(testFlag); var result = featureFlagProvider.GetFlags(); var flag = Assert.Single(result); Assert.Equal(testFlag, flag.Name); } [Fact] public void CanAddMultipleFlag() { const string testFlag1 = nameof(testFlag1); const string testFlag2 = nameof(testFlag2); const string testFlag3 = nameof(testFlag3); var featureFlagProvider = new InMemoryFeatureFlagProvider(); featureFlagProvider.AddFlag(testFlag1); featureFlagProvider.AddFlag(testFlag2); featureFlagProvider.AddFlag(testFlag3); var result = featureFlagProvider.GetFlags(); Assert.NotNull(result); Assert.Equal(3,result.Count()); var items = result.ToArray(); Assert.Equal(testFlag1, items[0].Name); Assert.Equal(testFlag2, items[1].Name); Assert.Equal(testFlag3, items[2].Name); } [Fact] public void CanRemoveFlag() { const string testFlag = nameof(testFlag); const string flagToRemove = nameof(flagToRemove); var featureFlagProvider = new InMemoryFeatureFlagProvider(); featureFlagProvider.AddFlag(flagToRemove); featureFlagProvider.AddFlag(testFlag); featureFlagProvider.RemoveFlag(flagToRemove); var result = featureFlagProvider.GetFlags(); var flag = Assert.Single(result); Assert.Equal(testFlag, flag.Name); } [Fact] public void CanClearFlags() { const string testFlag = nameof(testFlag); var featureFlagProvider = new InMemoryFeatureFlagProvider(); featureFlagProvider.AddFlag(testFlag); featureFlagProvider.ClearFlags(); var result = featureFlagProvider.GetFlags(); Assert.Empty(result); } } }
28.392857
72
0.613522
[ "MIT" ]
Kosrabt/FeatureFlags
test/FeatureFlagTests/FeatureFlagProviders/InMemoryFeatureFlagProviderTests.cs
3,182
C#
using System; using System.Diagnostics; using System.Reflection; using System.Collections.Generic; using System.Xml.Serialization; using System.Linq; using System.Windows.Forms; using System.IO; using MeshLib; using UtilityLib; using SharedForms; using SharpDX; using SharpDX.Direct3D11; //ambiguous stuff using Device = SharpDX.Direct3D11.Device; namespace ColladaConvert { public partial class AnimForm : Form { //file dialog OpenFileDialog mOFD =new OpenFileDialog(); SaveFileDialog mSFD =new SaveFileDialog(); //graphics device Device mGD; //matlib MaterialLib.MaterialLib mMatLib; //anim lib AnimLib mAnimLib; //selected anim info string mSelectedAnim; float mAnimStartTime, mAnimEndTime; float mCurAnimTime; bool mbPaused; StaticMesh mStatMesh; Character mChar; IArch mArch; public event EventHandler eMeshChanged; public event EventHandler eSkeletonChanged; public event EventHandler eBoundsChanged; public event EventHandler ePrint; public AnimForm(Device gd, MaterialLib.MaterialLib mats, AnimLib alib) { InitializeComponent(); mGD =gd; mMatLib =mats; mAnimLib =alib; mArch =new CharacterArch(); mChar =new Character(mArch, alib); AnimList.Columns.Add("Name"); AnimList.Columns.Add("Total Time"); AnimList.Columns.Add("Start Time"); AnimList.Columns.Add("Looping"); AnimList.Columns.Add("Ping Pong"); AnimList.Columns.Add("Num Keys"); } internal bool GetDrawAxis() { return DrawAxis.Checked; } internal bool GetDrawBox() { return ShowBox.Checked; } internal bool GetDrawSphere() { return ShowSphere.Checked; } internal void GetBoneNamesInUseByDraw(List<string> names) { mChar.GetBoneNamesInUseByDraw(names); } internal void BonesChanged() { mChar.ReBuildBones(mGD); } internal COLLADA DeSerializeCOLLADA(string path) { FileStream fs =new FileStream(path, FileMode.Open, FileAccess.Read); XmlSerializer xs =new XmlSerializer(typeof(COLLADA)); COLLADA ret =xs.Deserialize(fs) as COLLADA; fs.Close(); return ret; } internal void SerializeCOLLADA(COLLADA saveyThing, string path) { FileStream fs =new FileStream(path, FileMode.Create, FileAccess.Write); XmlSerializer xs =new XmlSerializer(typeof(COLLADA)); xs.Serialize(fs, saveyThing); fs.Close(); } //crude dae export internal void ConvertMesh(IArch ia, out COLLADA col) { col =new COLLADA(); col.asset =new asset(); col.asset.created =DateTime.Now; col.asset.unit =new assetUnit(); col.asset.unit.meter =0.1f; col.asset.unit.name ="meter"; col.asset.up_axis =UpAxisType.Z_UP; col.Items =new object[2]; library_geometries geom =new library_geometries(); int partCount =ia.GetPartCount(); geom.geometry =new geometry[partCount]; for(int i=0;i < partCount;i++) { geometry g =new geometry(); g.name =ia.GetPartName(i); g.id =g.name + "-mesh"; polylist plist =new polylist(); Type vType =ia.GetPartVertexType(i); plist.input =MakeInputs(g.id, vType); plist.material =g.id + "_mat"; //hax string polys, vcounts; plist.count =(ulong)ia.GetPartColladaPolys(i, out polys, out vcounts); plist.p =polys; plist.vcount =vcounts; object []itemses =new object[1]; itemses[0] =plist; mesh m =new mesh(); m.Items =itemses; m.source =MakeSources(g.id, ia, i); m.vertices =new vertices(); m.vertices.id =g.id + "-vertices"; m.vertices.input =new InputLocal[1]; m.vertices.input[0] =new InputLocal(); m.vertices.input[0].semantic ="POSITION"; m.vertices.input[0].source ="#" + g.id + "-positions"; g.Item =m; geom.geometry[i] =g; } col.Items[0] =geom; library_visual_scenes lvs =new library_visual_scenes(); lvs.visual_scene =new visual_scene[1]; lvs.visual_scene[0] =new visual_scene(); lvs.visual_scene[0].id ="RootNode"; lvs.visual_scene[0].name ="RootNode"; node []nodes =new node[partCount]; for(int i=0;i < partCount;i++) { nodes[i] =new node(); nodes[i].id =ia.GetPartName(i); nodes[i].name =ia.GetPartName(i); Matrix mat =ia.GetPartTransform(i); TargetableFloat3 trans =new TargetableFloat3(); trans.sid ="translate"; trans.Values =new float[3]; trans.Values[0] =mat.TranslationVector.X; trans.Values[1] =mat.TranslationVector.Y; trans.Values[2] =mat.TranslationVector.Z; rotate rot =new rotate(); rot.sid ="rotateX"; rot.Values =new float[4]; rot.Values[0] =1f; rot.Values[1] =0f; rot.Values[2] =0f; rot.Values[3] =-90f; nodes[i].Items =new object[2]; nodes[i].ItemsElementName =new ItemsChoiceType2[2]; nodes[i].ItemsElementName[0] =ItemsChoiceType2.translate; nodes[i].ItemsElementName[1] =ItemsChoiceType2.rotate; nodes[i].Items[0] =trans; nodes[i].Items[1] =rot; nodes[i].instance_geometry =new instance_geometry[1]; nodes[i].instance_geometry[0] =new instance_geometry(); nodes[i].instance_geometry[0].url ="#" + ia.GetPartName(i) + "-mesh"; } lvs.visual_scene[0].node =nodes; col.Items[1] =lvs; COLLADAScene scene =new COLLADAScene(); scene.instance_visual_scene =new InstanceWithExtra(); scene.instance_visual_scene.url ="#RootNode"; col.scene =scene; } //loads an animation into an existing anim lib internal bool LoadAnimDAE(string path, AnimLib alib, bool bCheckSkeleton) { COLLADA colladaFile =DeSerializeCOLLADA(path); //don't have a way to test this if(colladaFile.asset.up_axis == UpAxisType.X_UP) { PrintToOutput("Warning! X up axis not supported. Strange things may happen!\n"); } //do have a way to test this, but it causes //the bind shape matrii to have a rotation else if(colladaFile.asset.up_axis == UpAxisType.Y_UP) { PrintToOutput("Warning! Y up axis sort of works but might cause problems sharing anims between mesh parts!\n"); } //unit conversion float scaleFactor =colladaFile.asset.unit.meter; scaleFactor *=MeshConverter.GetScaleFactor(GetScaleFactor()); Skeleton skel =BuildSkeleton(colladaFile, ePrint); skel.ConvertToLeftHanded(); //grab visual scenes IEnumerable<library_visual_scenes> lvss = colladaFile.Items.OfType<library_visual_scenes>(); library_visual_scenes lvs =lvss.First(); //see if animlib has a skeleton yet if(alib.GetSkeleton() == null) { alib.SetSkeleton(skel); Misc.SafeInvoke(eSkeletonChanged, skel); } else if(bCheckSkeleton) { //make sure they match if(!alib.CheckSkeleton(skel)) { PrintToOutput("Warning! Skeleton check failed, anim load aborted!\n"); return false; } } Anim anm =BuildAnim(colladaFile, alib.GetSkeleton(), lvs, path, ePrint); alib.AddAnim(anm); TransformRoots(alib.GetSkeleton(), anm, scaleFactor); //need to do this again in case keyframes were added //for the root bone. anm.SetBoneRefs(alib.GetSkeleton()); return true; } internal MeshConverter.ScaleFactor GetScaleFactor() { if(UnitsCentimeters.Checked) { return MeshConverter.ScaleFactor.Centimeters; } else if(UnitsGrog.Checked) { return MeshConverter.ScaleFactor.Grog; } else if(UnitsMeters.Checked) { return MeshConverter.ScaleFactor.Meters; } else if(UnitsQuake.Checked) { return MeshConverter.ScaleFactor.Quake; } else if(UnitsValve.Checked) { return MeshConverter.ScaleFactor.Valve; } PrintToOutput("Warning! Desired Units could not be determined, using meters...\n"); return MeshConverter.ScaleFactor.Meters; } internal void LoadCharacterDAE(string path, AnimLib alib, IArch arch, Character chr) { COLLADA colladaFile =DeSerializeCOLLADA(path); //don't have a way to test this if(colladaFile.asset.up_axis == UpAxisType.X_UP) { PrintToOutput("Warning! X up axis not supported. Strange things may happen!\n"); } //do have a way to test this, but it causes //the bind shape matrii to have a rotation else if(colladaFile.asset.up_axis == UpAxisType.Y_UP) { PrintToOutput("Warning! Y up axis sort of works but might cause problems sharing anims between mesh parts!\n"); } //unit conversion float scaleFactor =1f; if(colladaFile.asset.unit != null) { scaleFactor =colladaFile.asset.unit.meter; } scaleFactor *=MeshConverter.GetScaleFactor(GetScaleFactor()); Matrix scaleMat =Matrix.Scaling(Vector3.One * (1f / scaleFactor)); //grab visual scenes IEnumerable<library_visual_scenes> lvss = colladaFile.Items.OfType<library_visual_scenes>(); library_visual_scenes lvs =lvss.First(); List<MeshConverter> allChunks =GetMeshChunks(colladaFile, true, GetScaleFactor()); List<MeshConverter> chunks =new List<MeshConverter>(); //skip dummies foreach(MeshConverter mc in allChunks) { if(!mc.GetName().Contains("DummyGeometry")) { chunks.Add(mc); mc.ePrint +=OnPrintString; } } allChunks.Clear(); AddVertexWeightsToChunks(colladaFile, chunks); //build or get skeleton Skeleton skel =BuildSkeleton(colladaFile, ePrint); skel.ConvertToLeftHanded(); //see if animlib has a skeleton yet if(alib.GetSkeleton() == null) { alib.SetSkeleton(skel); Misc.SafeInvoke(eSkeletonChanged, skel); } else { //make sure they match if(!alib.CheckSkeleton(skel)) { PrintToOutput("Warning! Skeleton check failed! Might need to restart to clear the animation library skeleton.\n"); return; } //use old one skel =alib.GetSkeleton(); } //adjust coordinate system //currently blender won't do anything but Z_UP Matrix shiftMat =Matrix.Identity; if(colladaFile.asset.up_axis == UpAxisType.Z_UP) { shiftMat *=Matrix.RotationX(MathUtil.PiOverTwo); } //bake shiftmat into part verts and normals foreach(MeshConverter mc in chunks) { mc.BakeTransformIntoVerts(shiftMat); } Anim anm =BuildAnim(colladaFile, alib.GetSkeleton(), lvs, path, ePrint); alib.AddAnim(anm); TransformRoots(alib.GetSkeleton(), anm, scaleFactor); //need to do this again in case keyframes were added //for the root bone. anm.SetBoneRefs(skel); CreateSkin(colladaFile, arch, chunks, skel, scaleFactor, ePrint); BuildFinalVerts(mGD, colladaFile, chunks); foreach(MeshConverter mc in chunks) { Mesh conv =mc.GetConvertedMesh(); Matrix mat =GetSceneNodeTransform(colladaFile, mc); //this might not be totally necessary //but it is nice to have if(!mat.IsIdentity) { PrintToOutput("Warning! Mesh chunk " + conv.Name + "'s scene node is not identity! This can make it tricksy to orient and move them in a game.\n"); } conv.Name =mc.GetGeomName(); conv.SetTransform(Matrix.Identity); arch.AddPart(conv); chr.AddPart(mMatLib); if(!conv.Name.EndsWith("Mesh")) { conv.Name +="Mesh"; } mc.ePrint -=OnPrintString; } } internal IArch LoadStatic(string path, out StaticMesh sm) { COLLADA colladaFile =DeSerializeCOLLADA(path); //don't have a way to test this if(colladaFile.asset.up_axis == UpAxisType.X_UP) { PrintToOutput("Warning! X up axis not supported. Strange things may happen!\n"); } IArch arch =new StaticArch(); sm =new StaticMesh(arch); List<MeshConverter> chunks =GetMeshChunks(colladaFile, false, GetScaleFactor()); //adjust coordinate system Matrix shiftMat =Matrix.Identity; if(colladaFile.asset.up_axis == UpAxisType.Z_UP) { shiftMat *=Matrix.RotationX(MathUtil.PiOverTwo); } //this needs to be identity so the game //can mess with it without needing the axis info sm.SetTransform(Matrix.Identity); BuildFinalVerts(mGD, colladaFile, chunks); foreach(MeshConverter mc in chunks) { Mesh m =mc.GetConvertedMesh(); Matrix mat =GetSceneNodeTransform(colladaFile, mc); m.Name =mc.GetGeomName(); //set transform of each mesh m.SetTransform(mat * shiftMat); arch.AddPart(m); sm.AddPart(mMatLib); } return arch; } void BuildFinalVerts(Device gd, COLLADA colladaFile, List<MeshConverter> chunks) { IEnumerable<library_geometries> geoms =colladaFile.Items.OfType<library_geometries>(); IEnumerable<library_controllers> conts =colladaFile.Items.OfType<library_controllers>(); PrintToOutput("geoms.Count() is: " + geoms.Count() + " in BuildFinalVerts()\n"); foreach(object geomItem in geoms.First().geometry) { geometry geom =geomItem as geometry; if(geom == null) { PrintToOutput("Null geometry in BuildFinalVerts()!\n"); continue; } //blast any chunks with no verts (happens with max collada) List<MeshConverter> toNuke =new List<MeshConverter>(); foreach(MeshConverter cnk in chunks) { string name =cnk.GetName(); if(cnk.mGeometryID == geom.id) { int normStride, tex0Stride, tex1Stride, tex2Stride, tex3Stride; int col0Stride, col1Stride, col2Stride, col3Stride; List<int> posIdxs =GetGeometryIndexesBySemantic(geom, "VERTEX", 0, name); float_array norms =GetGeometryFloatArrayBySemantic(geom, "NORMAL", 0, name, out normStride); List<int> normIdxs =GetGeometryIndexesBySemantic(geom, "NORMAL", 0, name); float_array texCoords0 =GetGeometryFloatArrayBySemantic(geom, "TEXCOORD", 0, name, out tex0Stride); float_array texCoords1 =GetGeometryFloatArrayBySemantic(geom, "TEXCOORD", 1, name, out tex1Stride); float_array texCoords2 =GetGeometryFloatArrayBySemantic(geom, "TEXCOORD", 2, name, out tex2Stride); float_array texCoords3 =GetGeometryFloatArrayBySemantic(geom, "TEXCOORD", 3, name, out tex3Stride); List<int> texIdxs0 =GetGeometryIndexesBySemantic(geom, "TEXCOORD", 0, name); List<int> texIdxs1 =GetGeometryIndexesBySemantic(geom, "TEXCOORD", 1, name); List<int> texIdxs2 =GetGeometryIndexesBySemantic(geom, "TEXCOORD", 2, name); List<int> texIdxs3 =GetGeometryIndexesBySemantic(geom, "TEXCOORD", 3, name); float_array colors0 =GetGeometryFloatArrayBySemantic(geom, "COLOR", 0, name, out col0Stride); float_array colors1 =GetGeometryFloatArrayBySemantic(geom, "COLOR", 1, name, out col1Stride); float_array colors2 =GetGeometryFloatArrayBySemantic(geom, "COLOR", 2, name, out col2Stride); float_array colors3 =GetGeometryFloatArrayBySemantic(geom, "COLOR", 3, name, out col3Stride); List<int> colIdxs0 =GetGeometryIndexesBySemantic(geom, "COLOR", 0, name); List<int> colIdxs1 =GetGeometryIndexesBySemantic(geom, "COLOR", 1, name); List<int> colIdxs2 =GetGeometryIndexesBySemantic(geom, "COLOR", 2, name); List<int> colIdxs3 =GetGeometryIndexesBySemantic(geom, "COLOR", 3, name); List<int> vertCounts =GetGeometryVertCount(geom, name, ePrint); if(vertCounts.Count == 0) { PrintToOutput("Empty geometry chunk in BuildFinalVerts()!\n"); toNuke.Add(cnk); continue; } cnk.AddNormTexByPoly(posIdxs, norms, normIdxs, texCoords0, texIdxs0, texCoords1, texIdxs1, texCoords2, texIdxs2, texCoords3, texIdxs3, colors0, colIdxs0, colors1, colIdxs1, colors2, colIdxs2, colors3, colIdxs3, vertCounts, col0Stride, col1Stride, col2Stride, col3Stride); bool bPos =(posIdxs != null && posIdxs.Count > 0); bool bNorm =(norms != null && norms.count > 0); bool bTex0 =(texCoords0 != null && texCoords0.count > 0); bool bTex1 =(texCoords1 != null && texCoords1.count > 0); bool bTex2 =(texCoords2 != null && texCoords2.count > 0); bool bTex3 =(texCoords3 != null && texCoords3.count > 0); bool bCol0 =(colors0 != null && colors0.count > 0); bool bCol1 =(colors1 != null && colors1.count > 0); bool bCol2 =(colors2 != null && colors2.count > 0); bool bCol3 =(colors3 != null && colors3.count > 0); bool bBone =false; //see if any skins reference this geometry if(conts.Count() > 0) { foreach(controller cont in conts.First().controller) { skin sk =cont.Item as skin; if(sk == null) { continue; } string skinSource =sk.source1.Substring(1); if(skinSource == null || skinSource == "") { continue; } if(skinSource == geom.id) { bBone =true; break; } } } //todo obey stride on everything cnk.BuildBuffers(gd, bPos, bNorm, bBone, bBone, bTex0, bTex1, bTex2, bTex3, bCol0, bCol1, bCol2, bCol3); } } //blast empty chunks foreach(MeshConverter nuke in toNuke) { chunks.Remove(nuke); } toNuke.Clear(); } } static void BakeSceneNodesIntoVerts(COLLADA colladaFile, Skeleton skel, List<MeshConverter> chunks, EventHandler ePrint) { if(colladaFile.Items.OfType<library_controllers>().Count() <= 0) { return; } var ctrlNodes =from vss in colladaFile.Items.OfType<library_visual_scenes>().First().visual_scene from n in vss.node select n; var skinControllers =from conts in colladaFile.Items.OfType<library_controllers>().First().controller where conts.Item is skin select conts; foreach(controller cont in skinControllers) { string contID =cont.id; skin sk =cont.Item as skin; string skinSource =sk.source1.Substring(1); foreach(node n in ctrlNodes) { string nname =GetNodeNameForInstanceController(n, cont.id); if(nname == "") { Misc.SafeInvoke(ePrint, "Empty node name for instance controller: " + cont.id + "!\n"); continue; } Matrix mat =Matrix.Identity; if(!skel.GetMatrixForBone(nname, out mat)) { Misc.SafeInvoke(ePrint, "Node: " + nname + " not found in skeleton!\n"); continue; } foreach(MeshConverter mc in chunks) { if(mc.mGeometryID == skinSource) { mc.BakeTransformIntoVerts(mat); } } } } } static Anim BuildAnim(COLLADA colladaFile, Skeleton skel, library_visual_scenes lvs, string path, EventHandler ePrint) { //create useful anims List<SubAnim> subs =CreateSubAnims(colladaFile, skel, ePrint); foreach(SubAnim sub in subs) { sub.ConvertToLeftHanded(); } Anim anm =new Anim(subs); FixMultipleSkeletons(lvs, anm, skel); anm.SetBoneRefs(skel); anm.Name =NameFromPath(path); return anm; } static void CreateSkin(COLLADA colladaFile, IArch arch, List<MeshConverter> chunks, Skeleton skel, float scaleFactor, EventHandler ePrint) { IEnumerable<library_controllers> lcs =colladaFile.Items.OfType<library_controllers>(); if(lcs.Count() <= 0) { Misc.SafeInvoke(ePrint, "No library_controllers in CreateSkin()!\n"); return; } //create or reuse a single master skin for the character's parts Skin skin =arch.GetSkin(); if(skin == null) { skin =new Skin(); } Dictionary<int, Matrix> invBindPoses =new Dictionary<int, Matrix>(); foreach(controller cont in lcs.First().controller) { skin sk =cont.Item as skin; if(sk == null) { continue; } string skinSource =sk.source1.Substring(1); if(skinSource == null || skinSource == "") { continue; } Matrix bindMat =Matrix.Identity; GetMatrixFromString(sk.bind_shape_matrix, out bindMat); //Blender now seems to always have a rotation stuck in here, //and there seems no way to get rid of it, so I compensate //for it elsewhere if(!Mathery.IsIdentity(bindMat, Mathery.VCompareEpsilon)) { Misc.SafeInvoke(ePrint, "Non identity bind pose in skin: " + sk.source1 + "\n"); } string jointSrc =""; string invSrc =""; foreach(InputLocal inp in sk.joints.input) { if(inp.semantic == "JOINT") { jointSrc =inp.source.Substring(1); } else if(inp.semantic == "INV_BIND_MATRIX") { invSrc =inp.source.Substring(1); } } Name_array na =null; float_array ma =null; foreach(source src in sk.source) { if(src.id == jointSrc) { na =src.Item as Name_array; } else if(src.id == invSrc) { ma =src.Item as float_array; } } List<Matrix> mats =GetMatrixListFromFA(ma); List<string> bnames =GetBoneNamesViaSID(na.Values, colladaFile); Debug.Assert(mats.Count == bnames.Count); //add to master list for(int i=0;i < mats.Count;i++) { string bname =bnames[i]; Matrix ibp =mats[i]; int idx =skel.GetBoneIndex(bname); if(idx == -1) { Misc.SafeInvoke(ePrint, "Warning! No index in skeleton for bone: " + bname + "!\n"); continue; } if(invBindPoses.ContainsKey(idx)) { Misc.SafeInvoke(ePrint, "Warning! Duplicate bind pose for bone: " + bname + "!\n"); continue; } if(invBindPoses.ContainsKey(idx)) { if(!Mathery.IsIdentity(invBindPoses[idx], Mathery.VCompareEpsilon)) { //if bone name already added, make sure the //inverse bind pose is the same for this skin if(!Mathery.CompareMatrix(ibp, invBindPoses[idx], Mathery.VCompareEpsilon)) { Misc.SafeInvoke(ePrint, "Warning! Non matching bind pose for bone: " + bname + "!\n"); } } } else { //coord system change the inverse bind poses ibp.Invert(); KeyFrame.RightHandToLeft(ref ibp); //adjust coordinate system //There always seems to be a rotation in blenders stuff these days Matrix shiftMat =Matrix.RotationX(MathUtil.PiOverTwo); //this will put the model verts back into the space //where the animation happens, which is usually meter space shiftMat *=Matrix.Scaling(scaleFactor); ibp *=shiftMat; ibp.Invert(); invBindPoses.Add(idx, ibp); } } } skin.SetBonePoses(invBindPoses); arch.SetSkin(skin); FixBoneIndexes(colladaFile, chunks, skel); } static List<SubAnim> CreateSubAnims(COLLADA colladaFile, Skeleton skel, EventHandler ePrint) { //create useful anims List<SubAnim> subs =new List<SubAnim>(); IEnumerable<library_visual_scenes> lvs =colladaFile.Items.OfType<library_visual_scenes>(); if(lvs.Count() <= 0) { Misc.SafeInvoke(ePrint, "No library_visual_scenes in CreateSubAnims()!\n"); return subs; } IEnumerable<library_animations> anims =colladaFile.Items.OfType<library_animations>(); if(anims.Count() <= 0) { Misc.SafeInvoke(ePrint, "No library_animations in CreateSubAnims()!\n"); return subs; } Animation.KeyPartsUsed partsUsed =Animation.KeyPartsUsed.None; foreach(animation anim in anims.First().animation) { if(anim.Items == null) { continue; } Animation an =new Animation(anim); subs.AddRange(an.GetAnims(skel, lvs.First(), out partsUsed)); } //TODO: All of this merging stuff needs testing again //merge animations affecting a single bone List<SubAnim> merged =new List<SubAnim>(); List<Animation.KeyPartsUsed> mergedParts =new List<Animation.KeyPartsUsed>(); //grab full list of bones List<string> boneNames =new List<string>(); skel.GetBoneNames(boneNames); foreach(string bone in boneNames) { List<SubAnim> combine =new List<SubAnim>(); List<Animation.KeyPartsUsed> combineParts =new List<Animation.KeyPartsUsed>(); for(int i=0;i < subs.Count;i++) { SubAnim sa =subs[i]; if(sa.GetBoneName() == bone) { combine.Add(sa); combineParts.Add(partsUsed); } } if(combine.Count == 1) { merged.Add(combine[0]); mergedParts.Add(combineParts[0]); continue; } else if(combine.Count <= 0) { continue; } //merge together SubAnim first =combine.First(); KeyFrame []firstKeys =first.GetKeys(); for(int i=1;i < combine.Count;i++) { KeyFrame []next =combine[i].GetKeys(); Debug.Assert(firstKeys.Length == next.Length); Animation.KeyPartsUsed nextParts =combineParts[i]; //ensure no overlap (shouldn't be) Debug.Assert(((UInt32)nextParts & (UInt32)combineParts[0]) == 0); MergeKeys(firstKeys, next, nextParts); combineParts[0] |=nextParts; } merged.Add(first); mergedParts.Add(combineParts[0]); } //post merge, fill in any gaps in the keyframes with //data from the nodes themselves for(int i=0;i < merged.Count;i++) { SubAnim sub =merged[i]; string boneName =sub.GetBoneName(); KeyFrame boneKey =skel.GetBoneKey(boneName); KeyFrame []keys =sub.GetKeys(); foreach(KeyFrame key in keys) { FillKeyGaps(key, mergedParts[i], boneKey); } } return merged; } static void FillKeyGaps(KeyFrame key, Animation.KeyPartsUsed keyPartsUsed, KeyFrame boneKey) { if(!Misc.bFlagSet((UInt32)keyPartsUsed, (UInt32)Animation.KeyPartsUsed.TranslateX)) { key.mPosition.X =boneKey.mPosition.X; } if(!Misc.bFlagSet((UInt32)keyPartsUsed, (UInt32)Animation.KeyPartsUsed.TranslateY)) { key.mPosition.Y =boneKey.mPosition.Y; } if(!Misc.bFlagSet((UInt32)keyPartsUsed, (UInt32)Animation.KeyPartsUsed.TranslateZ)) { key.mPosition.Z =boneKey.mPosition.Z; } if(!Misc.bFlagSet((UInt32)keyPartsUsed, (UInt32)Animation.KeyPartsUsed.ScaleX)) { key.mScale.X =boneKey.mScale.X; } if(!Misc.bFlagSet((UInt32)keyPartsUsed, (UInt32)Animation.KeyPartsUsed.ScaleY)) { key.mScale.Y =boneKey.mScale.Y; } if(!Misc.bFlagSet((UInt32)keyPartsUsed, (UInt32)Animation.KeyPartsUsed.ScaleZ)) { key.mScale.Z =boneKey.mScale.Z; } if(!Misc.bFlagSet((UInt32)keyPartsUsed, (UInt32)Animation.KeyPartsUsed.RotateX)) { key.mRotation =Quaternion.Multiply(key.mRotation, boneKey.mRotation); key.mRotation =Quaternion.Multiply(boneKey.mRotation, key.mRotation); } if(!Misc.bFlagSet((UInt32)keyPartsUsed, (UInt32)Animation.KeyPartsUsed.RotateY)) { key.mRotation =Quaternion.Multiply(key.mRotation, boneKey.mRotation); key.mRotation =Quaternion.Multiply(boneKey.mRotation, key.mRotation); } if(!Misc.bFlagSet((UInt32)keyPartsUsed, (UInt32)Animation.KeyPartsUsed.RotateZ)) { key.mRotation =Quaternion.Multiply(key.mRotation, boneKey.mRotation); key.mRotation =Quaternion.Multiply(boneKey.mRotation, key.mRotation); } } static void MergeKeys(KeyFrame []first, KeyFrame []next, Animation.KeyPartsUsed nextParts) { Debug.Assert(first.Length == next.Length); for(int i=0;i < first.Length;i++) { if(Misc.bFlagSet((UInt32)nextParts, (UInt32)Animation.KeyPartsUsed.TranslateX)) { first[i].mPosition.X =next[i].mPosition.X; } if(Misc.bFlagSet((UInt32)nextParts, (UInt32)Animation.KeyPartsUsed.TranslateY)) { first[i].mPosition.Y =next[i].mPosition.Y; } if(Misc.bFlagSet((UInt32)nextParts, (UInt32)Animation.KeyPartsUsed.TranslateZ)) { first[i].mPosition.Z =next[i].mPosition.Z; } if(Misc.bFlagSet((UInt32)nextParts, (UInt32)Animation.KeyPartsUsed.ScaleX)) { first[i].mScale.X =next[i].mScale.X; } if(Misc.bFlagSet((UInt32)nextParts, (UInt32)Animation.KeyPartsUsed.ScaleY)) { first[i].mScale.Y =next[i].mScale.Y; } if(Misc.bFlagSet((UInt32)nextParts, (UInt32)Animation.KeyPartsUsed.ScaleZ)) { first[i].mScale.Z =next[i].mScale.Z; } if(Misc.bFlagSet((UInt32)nextParts, (UInt32)Animation.KeyPartsUsed.RotateX)) { first[i].mRotation =Quaternion.Multiply(next[i].mRotation, first[i].mRotation); first[i].mRotation =Quaternion.Multiply(first[i].mRotation, next[i].mRotation); } if(Misc.bFlagSet((UInt32)nextParts, (UInt32)Animation.KeyPartsUsed.RotateY)) { first[i].mRotation =Quaternion.Multiply(next[i].mRotation, first[i].mRotation); first[i].mRotation =Quaternion.Multiply(first[i].mRotation, next[i].mRotation); } if(Misc.bFlagSet((UInt32)nextParts, (UInt32)Animation.KeyPartsUsed.RotateZ)) { first[i].mRotation =Quaternion.Multiply(next[i].mRotation, first[i].mRotation); first[i].mRotation =Quaternion.Multiply(first[i].mRotation, next[i].mRotation); } } } internal static List<Matrix> GetMatrixListFromFloatList(List<float> fa) { List<Matrix> ret =new List<Matrix>(); Debug.Assert(fa.Count % 16 == 0); for(int i=0;i < (int)fa.Count;i+=16) { Matrix mat =new Matrix(); mat.M11 =fa[i + 0]; mat.M21 =fa[i + 1]; mat.M31 =fa[i + 2]; mat.M41 =fa[i + 3]; mat.M12 =fa[i + 4]; mat.M22 =fa[i + 5]; mat.M32 =fa[i + 6]; mat.M42 =fa[i + 7]; mat.M13 =fa[i + 8]; mat.M23 =fa[i + 9]; mat.M33 =fa[i + 10]; mat.M43 =fa[i + 11]; mat.M14 =fa[i + 12]; mat.M24 =fa[i + 13]; mat.M34 =fa[i + 14]; mat.M44 =fa[i + 15]; ret.Add(mat); } return ret; } internal static int GetNodeItemIndex(node n, string sid) { if(n.Items == null) { return -1; } for(int i=0;i < n.Items.Length;i++) { object item =n.Items[i]; Type t =item.GetType(); PropertyInfo []pinfo =t.GetProperties(); foreach(PropertyInfo pi in pinfo) { if(pi.Name == "sid") { string itemSid =pi.GetValue(item, null) as string; if(itemSid == sid) { return i; } } } } return -1; } static string NameFromPath(string path) { int lastSlash =path.LastIndexOf('\\'); if(lastSlash == -1) { lastSlash =0; } else { lastSlash++; } int extension =path.LastIndexOf('.'); string name =path.Substring(lastSlash, extension - lastSlash); return name; } static void FixBoneIndexes(COLLADA colladaFile, List<MeshConverter> chunks, Skeleton skel) { if(colladaFile.Items.OfType<library_controllers>().Count() <= 0) { return; } var skins =from conts in colladaFile.Items.OfType<library_controllers>().First().controller where conts.Item is skin select conts.Item as skin; foreach(skin sk in skins) { string jointSrc =""; foreach(InputLocal inp in sk.joints.input) { if(inp.semantic == "JOINT") { jointSrc =inp.source.Substring(1); } } Name_array na =null; foreach(source src in sk.source) { if(src.id == jointSrc) { na =src.Item as Name_array; } } List<string> bnames =GetBoneNamesViaSID(na.Values, colladaFile); string skinSource =sk.source1.Substring(1); foreach(MeshConverter cnk in chunks) { if(cnk.mGeometryID == skinSource) { cnk.FixBoneIndexes(skel, bnames); } } } } static List<string> GetBoneNamesViaSID(string []sids, COLLADA cfile) { List<string> boneNames =new List<string>(); IEnumerable<library_visual_scenes> lvs =cfile.Items.OfType<library_visual_scenes>(); foreach(string sid in sids) { //supposed to use sids (I think, the spec is ambiguous) //but if that fails use ids. Maybe should use names I dunno node n =LookUpNodeViaSID(lvs.First(), sid); if(n == null) { n =LookUpNode(lvs.First(), sid); } Debug.Assert(n != null); boneNames.Add(n.name); } return boneNames; } internal static node LookUpNodeViaSID(library_visual_scenes lvs, string SID) { //find the node addressed node addressed =null; foreach(visual_scene vs in lvs.visual_scene) { foreach(node n in vs.node) { addressed =LookUpNodeViaSID(n, SID); if(addressed != null) { break; } } } return addressed; } internal static node LookUpNodeViaSID(node n, string sid) { if(n.sid == sid) { return n; } if(n.node1 == null) { return null; } foreach(node child in n.node1) { node ret =LookUpNodeViaSID(child, sid); if(ret != null) { return ret; } } return null; } internal static void GetMatrixFromString(string str, out Matrix mat) { string[] tokens =str.Split(' ', '\n', '\t'); int tokIdx =0; //transpose as we load //this looks very unsafe / dangerous while(!Single.TryParse(tokens[tokIdx++],out mat.M11)); while(!Single.TryParse(tokens[tokIdx++],out mat.M21)); while(!Single.TryParse(tokens[tokIdx++],out mat.M31)); while(!Single.TryParse(tokens[tokIdx++],out mat.M41)); while(!Single.TryParse(tokens[tokIdx++],out mat.M12)); while(!Single.TryParse(tokens[tokIdx++],out mat.M22)); while(!Single.TryParse(tokens[tokIdx++],out mat.M32)); while(!Single.TryParse(tokens[tokIdx++],out mat.M42)); while(!Single.TryParse(tokens[tokIdx++],out mat.M13)); while(!Single.TryParse(tokens[tokIdx++],out mat.M23)); while(!Single.TryParse(tokens[tokIdx++],out mat.M33)); while(!Single.TryParse(tokens[tokIdx++],out mat.M43)); while(!Single.TryParse(tokens[tokIdx++],out mat.M14)); while(!Single.TryParse(tokens[tokIdx++],out mat.M24)); while(!Single.TryParse(tokens[tokIdx++],out mat.M34)); while(!Single.TryParse(tokens[tokIdx++],out mat.M44)); } internal static List<Matrix> GetMatrixListFromFA(float_array fa) { List<Matrix> ret =new List<Matrix>(); Debug.Assert(fa.count % 16 == 0); for(int i=0;i < (int)fa.count;i+=16) { Matrix mat =new Matrix(); mat.M11 =fa.Values[i + 0]; mat.M21 =fa.Values[i + 1]; mat.M31 =fa.Values[i + 2]; mat.M41 =fa.Values[i + 3]; mat.M12 =fa.Values[i + 4]; mat.M22 =fa.Values[i + 5]; mat.M32 =fa.Values[i + 6]; mat.M42 =fa.Values[i + 7]; mat.M13 =fa.Values[i + 8]; mat.M23 =fa.Values[i + 9]; mat.M33 =fa.Values[i + 10]; mat.M43 =fa.Values[i + 11]; mat.M14 =fa.Values[i + 12]; mat.M24 =fa.Values[i + 13]; mat.M34 =fa.Values[i + 14]; mat.M44 =fa.Values[i + 15]; ret.Add(mat); } return ret; } static void FixMultipleSkeletons(library_visual_scenes lvs, Anim anm, Skeleton skel) { Debug.Assert(lvs.visual_scene.Length == 1); foreach(node n in lvs.visual_scene[0].node) { if(n.instance_controller != null) { Debug.Assert(n.instance_controller.Length == 1); string []skels =n.instance_controller.First().skeleton; if(skels != null) { if(skels.Length > 1) { for(int i=1;i < skels.Length;i++) { string skelName =skels[i].Substring(1); node skelNode =LookUpNodeViaSID(lvs, skelName); if(skelNode == null) { skelNode =LookUpNode(lvs, skelName); } anm.FixDetatchedSkeleton(skel, skelNode.name); } } } } } } static string GetNodeNameForInstanceController(node n, string ic) { if(n.instance_controller != null) { foreach(instance_controller inst in n.instance_controller) { if(inst.url.Substring(1) == ic) { return n.name; } } } if(n.node1 == null) { return ""; } //check kids foreach(node kid in n.node1) { string ret =GetNodeNameForInstanceController(kid, ic); if(ret != "") { return ret; } } return ""; } static string AdjustName(List<string> namesInUse, string name) { string origName =name; int postNum =0; while(namesInUse.Contains(name)) { name =origName + String.Format("{0,10:D6}", postNum); } return name; } static void BuildSkeleton(node n, List<string> namesInUse, out GSNode gsn, EventHandler ePrint) { gsn =new GSNode(); if(namesInUse.Contains(n.name)) { Misc.SafeInvoke(ePrint, "Warning! Non unique bone name: " + n.name + "!\n"); string newName =AdjustName(namesInUse, n.name); gsn.SetName(newName); namesInUse.Add(newName); //also need to adjust the collada data so searches //will spot the adjusted name n.name =newName; } else { gsn.SetName(n.name); namesInUse.Add(n.name); } KeyFrame kf =GetKeyFromCNode(n); gsn.SetKey(kf); if(n.node1 == null) { return; } foreach(node child in n.node1) { GSNode kid =new GSNode(); BuildSkeleton(child, namesInUse, out kid, ePrint); gsn.AddChild(kid); } } static Skeleton BuildSkeleton(COLLADA colMesh, EventHandler ePrint) { Skeleton ret =new Skeleton(); var nodes =from lvs in colMesh.Items.OfType<library_visual_scenes>().First().visual_scene from n in lvs.node select n; List<string> namesInUse =new List<string>(); foreach(node n in nodes) { GSNode gsnRoot =new GSNode(); BuildSkeleton(n, namesInUse, out gsnRoot, ePrint); ret.AddRoot(gsnRoot); } ret.ComputeNameIndex(); return ret; } static void AddVertexWeightsToChunks(COLLADA colladaFile, List<MeshConverter> chunks) { if(colladaFile.Items.OfType<library_controllers>().Count() <= 0) { return; } var skins =from conts in colladaFile.Items.OfType<library_controllers>().First().controller where conts.Item is skin select conts.Item as skin; foreach(skin sk in skins) { string skinSource =sk.source1.Substring(1); foreach(MeshConverter cnk in chunks) { if(cnk.mGeometryID == skinSource) { cnk.AddWeightsToBaseVerts(sk); } } } } static List<int> GetGeometryVertCount(geometry geom, string material, EventHandler ePrint) { List<int> ret =new List<int>(); mesh msh =geom.Item as mesh; if(msh == null || msh.Items == null) { return null; } foreach(object polObj in msh.Items) { polygons polys =polObj as polygons; polylist plist =polObj as polylist; triangles tris =polObj as triangles; if(polys == null && plist == null && tris == null) { Misc.SafeInvoke(ePrint, "Unknown polygon type: " + polObj + " in mesh: " + geom.name + "!\n"); continue; } if(polys != null) { if(polys.material != material) { continue; } if(polys.Items == null) { Misc.SafeInvoke(ePrint, geom.name + ", null Items!\n"); continue; } //find the stride int stride =0; for(int i=0;i < polys.input.Length;i++) { InputLocalOffset inp =polys.input[i]; if((int)inp.offset > stride) { stride =(int)inp.offset; } } foreach(object polyObj in polys.Items) { string pols =polyObj as string; Debug.Assert(pols != null); pols =pols.Trim(); string []tokens =pols.Split(' ', '\n'); //sometimes inputs share an index, sometimes they are all separated ret.Add(tokens.Length / (stride + 1)); } } else if(plist != null) { //this path is very untested now if(plist.material != material) { continue; } Misc.SafeInvoke(ePrint, "Warning! PolyLists are very untested at the moment!\n"); string []tokens =plist.vcount.Split(' ', '\n'); int numSem =plist.input.Length; foreach(string tok in tokens) { if(tok == "") { continue; //blender exporter wierdness } int vertCount; bool bGood =Int32.TryParse(tok, out vertCount); Debug.Assert(bGood); ret.Add(vertCount); } } else if(tris != null) { //this path is very untested now if(tris.material != material) { continue; } Misc.SafeInvoke(ePrint, "Warning! Tris are very untested at the moment!\n"); for(int i=0;i < (int)tris.count;i++) { ret.Add(3); } } } return ret; } List<MeshConverter> GetMeshChunks(COLLADA colladaFile, bool bSkinned, MeshConverter.ScaleFactor sf) { List<MeshConverter> chunks =new List<MeshConverter>(); //if you crash and land here, there are no geoms in the file var geoms =from g in colladaFile.Items.OfType<library_geometries>().First().geometry where g.Item is mesh select g; var polyObjs =from g in geoms let m = g.Item as mesh from pols in m.Items select pols; foreach(geometry geom in geoms) { mesh m =geom.Item as mesh; //check for empty geoms if(m.Items == null) { PrintToOutput("Empty mesh in GetMeshChunks()\n"); continue; } foreach(object polyObj in m.Items) { polygons polys =polyObj as polygons; polylist plist =polyObj as polylist; triangles tris =polyObj as triangles; if(polys == null && plist == null && tris == null) { PrintToOutput("Unknown polygon type: " + polyObj + " in mesh: " + geom.name + "!\n"); continue; } string mat =null; UInt64 count =0; if(polys != null) { mat =polys.material; count =polys.count; } else if(plist != null) { mat =plist.material; count =plist.count; } else if(tris != null) { mat =tris.material; count =tris.count; } if(count <= 0) { if(mat != null) { PrintToOutput("Empty polygon in GetMeshChunks for material: " + mat + "\n"); } else { PrintToOutput("Empty polygon in GetMeshChunks!\n"); } continue; } float_array verts =null; MeshConverter cnk =null; int stride =0; verts =GetGeometryFloatArrayBySemantic(geom, "VERTEX", 0, mat, out stride); if(verts == null) { PrintToOutput("Empty verts for geom: " + geom.name + ", material: " + mat + "\n"); continue; } if(mat == null) { PrintToOutput("No material for geom: " + geom.name + "\n"); //return an empty list return new List<MeshConverter>(); } cnk =new MeshConverter(mat, geom.name); float fileUnitSize =1f; if(colladaFile.asset.unit != null) { fileUnitSize =colladaFile.asset.unit.meter; } cnk.CreateBaseVerts(verts, fileUnitSize, sf); cnk.mPartIndex =-1; cnk.SetGeometryID(geom.id); chunks.Add(cnk); } } return chunks; } void ParseIndexes(string []tokens, int offset, int inputStride, List<int> indexes) { int curIdx =0; foreach(string tok in tokens) { if(curIdx == offset) { int val =0; if(int.TryParse(tok, out val)) { indexes.Add(val); } } curIdx++; if(curIdx > inputStride) { curIdx =0; } } } List<int> GetGeometryIndexesBySemantic(geometry geom, string sem, int set, string material) { List<int> ret =new List<int>(); mesh msh =geom.Item as mesh; if(msh == null || msh.Items == null) { return null; } string key =""; int idx =-1; int ofs =-1; foreach(object polObj in msh.Items) { polygons polys =polObj as polygons; polylist plist =polObj as polylist; triangles tris =polObj as triangles; if(polys == null && plist == null && tris == null) { PrintToOutput("Unknown polygon type: " + polObj + " in mesh: " + geom.name + "!\n"); continue; } InputLocalOffset []inputs =null; if(polys != null) { inputs =polys.input; if(polys.material != material) { continue; } } else if(plist != null) { inputs =plist.input; if(plist.material != material) { continue; } } else if(tris != null) { inputs =tris.input; if(tris.material != material) { continue; } } //find the key, idx, and offset for passed in sem for(int i=0;i < inputs.Length;i++) { InputLocalOffset inp =inputs[i]; if(inp.semantic == sem && set == (int)inp.set) { //strip # key =inp.source.Substring(1); idx =i; ofs =(int)inp.offset; break; } } if(key == "") { //this is not a big deal, just means this particular //semantic doesn't exist, like if there's no vertex //colors or texcoords etc continue; } //find the stride to the matched sem, by checking max offset int stride =0; for(int i=0;i < inputs.Length;i++) { InputLocalOffset inp =inputs[i]; if((int)inp.offset > stride) { stride =(int)inp.offset; } } if(polys != null && polys.Items != null) { foreach(object polyObj in polys.Items) { string pols =polyObj as string; Debug.Assert(pols != null); //better collada adds some annoying whitespace pols =pols.Trim(); string []tokens =pols.Split(' ', '\n'); ParseIndexes(tokens, ofs, stride, ret); } } else if(plist != null) { //this path is very untested now PrintToOutput("Warning! PolyLists are very untested at the moment!\n"); string []tokens =plist.p.Split(' ', '\n'); ParseIndexes(tokens, ofs, stride, ret); } else if(tris != null) { //this path is very untested now PrintToOutput("Warning! Tris are very untested at the moment!\n"); string []tokens =tris.p.Split(' ', '\n'); ParseIndexes(tokens, ofs, stride, ret); } } return ret; } float_array GetGeometryFloatArrayBySemantic(geometry geom, string sem, int set, string material, out int stride) { stride =-1; mesh msh =geom.Item as mesh; if(msh == null) { return null; } string key =""; int idx =-1; int ofs =-1; foreach(object polObj in msh.Items) { polygons polys =polObj as polygons; polylist plist =polObj as polylist; triangles tris =polObj as triangles; if(polys == null && plist == null && tris == null) { PrintToOutput("Unknown polygon type: " + polObj + " in mesh: " + geom.name + "!\n"); continue; } InputLocalOffset []inputs =null; string polyMat =""; if(polys != null) { polyMat =polys.material; inputs =polys.input; } else if(plist != null) { polyMat =plist.material; inputs =plist.input; } else if(tris != null) { polyMat =tris.material; inputs =tris.input; } if(polyMat != material) { continue; } for(int i=0;i < inputs.Length;i++) { InputLocalOffset inp =inputs[i]; if(inp.semantic == sem && set == (int)inp.set) { //strip # key =inp.source.Substring(1); idx =i; ofs =(int)inp.offset; break; } } } if(key == "") { //this is not a big deal, just means this particular //semantic doesn't exist, like if there's no vertex //colors or texcoords etc return null; } //check vertices if(msh.vertices != null && msh.vertices.id == key) { key =msh.vertices.input[0].source.Substring(1); } for(int j=0;j < msh.source.Length;j++) { float_array verts =msh.source[j].Item as float_array; if(verts == null || msh.source[j].id != key) { continue; } stride =(int)msh.source[j].technique_common.accessor.stride; return verts; } stride =-1; return null; } geometry GetGeometryByID(COLLADA colladaFile, string id) { return (from geoms in colladaFile.Items.OfType<library_geometries>().First().geometry where geoms is geometry where geoms.id == id select geoms).FirstOrDefault(); } static void matrixToMatrix(ref matrix cMat, ref Matrix sdxMat) { sdxMat.M11 =cMat.Values[0]; sdxMat.M21 =cMat.Values[1]; sdxMat.M31 =cMat.Values[2]; sdxMat.M41 =cMat.Values[3]; sdxMat.M12 =cMat.Values[4]; sdxMat.M22 =cMat.Values[5]; sdxMat.M32 =cMat.Values[6]; sdxMat.M42 =cMat.Values[7]; sdxMat.M13 =cMat.Values[8]; sdxMat.M23 =cMat.Values[9]; sdxMat.M33 =cMat.Values[10]; sdxMat.M43 =cMat.Values[11]; sdxMat.M14 =cMat.Values[12]; sdxMat.M24 =cMat.Values[13]; sdxMat.M34 =cMat.Values[14]; sdxMat.M44 =cMat.Values[15]; } static KeyFrame GetKeyFromCNode(node n) { KeyFrame key =new KeyFrame(); if(n.Items == null) { return key; } Matrix mat =Matrix.Identity; for(int i=0;i < n.Items.Length;i++) { if(n.ItemsElementName[i] == ItemsChoiceType2.matrix) { matrix cmat =n.Items[i] as matrix; Debug.Assert(cmat != null); matrixToMatrix(ref cmat, ref mat); } else if(n.ItemsElementName[i] == ItemsChoiceType2.rotate) { rotate rot =n.Items[i] as rotate; Debug.Assert(rot != null); Vector3 axis =Vector3.Zero; axis.X =rot.Values[0]; axis.Y =rot.Values[1]; axis.Z =rot.Values[2]; float angle =MathUtil.DegreesToRadians(rot.Values[3]); mat =Matrix.RotationAxis(axis, angle) * mat; } else if(n.ItemsElementName[i] == ItemsChoiceType2.translate) { TargetableFloat3 trans =n.Items[i] as TargetableFloat3; Vector3 t =Vector3.Zero; t.X =trans.Values[0]; t.Y =trans.Values[1]; t.Z =trans.Values[2]; mat =Matrix.Translation(t) * mat; } else if(n.ItemsElementName[i] == ItemsChoiceType2.scale) { TargetableFloat3 scl =n.Items[i] as TargetableFloat3; Vector3 t =Vector3.Zero; t.X =scl.Values[0]; t.Y =scl.Values[1]; t.Z =scl.Values[2]; mat =Matrix.Scaling(t) * mat; } } mat.Decompose(out key.mScale, out key.mRotation, out key.mPosition); return key; } internal static node LookUpNode(library_visual_scenes lvs, string nodeID) { //find the node addressed node addressed =null; foreach(visual_scene vs in lvs.visual_scene) { foreach(node n in vs.node) { addressed =LookUpNode(n, nodeID); if(addressed != null) { break; } } } return addressed; } internal static node LookUpNode(node n, string id) { if(n.id == id) { return n; } if(n.node1 == null) { return null; } foreach(node child in n.node1) { node ret =LookUpNode(child, id); if(ret != null) { return ret; } } return null; } bool CNodeHasKeyData(node n) { if(n.Items == null) { return false; } Matrix mat =Matrix.Identity; for(int i=0;i < n.Items.Length;i++) { if(n.ItemsElementName[i] == ItemsChoiceType2.matrix) { return true; } if(n.ItemsElementName[i] == ItemsChoiceType2.rotate) { return true; } else if(n.ItemsElementName[i] == ItemsChoiceType2.translate) { return true; } else if(n.ItemsElementName[i] == ItemsChoiceType2.scale) { return true; } } return false; } Matrix GetSceneNodeTransform(COLLADA colFile, MeshConverter chunk) { geometry g =GetGeometryByID(colFile, chunk.mGeometryID); if(g == null) { return Matrix.Identity; } var geomNodes =from lvs in colFile.Items.OfType<library_visual_scenes>().First().visual_scene from n in lvs.node where n.instance_geometry != null select n; foreach(node n in geomNodes) { foreach(instance_geometry ig in n.instance_geometry) { if(ig.url.Substring(1) == g.id) { if(!CNodeHasKeyData(n)) { //no transform needed return Matrix.Identity; } KeyFrame kf =GetKeyFromCNode(n); Matrix mat =Matrix.Scaling(kf.mScale) * Matrix.RotationQuaternion(kf.mRotation) * Matrix.Translation(kf.mPosition); KeyFrame.RightHandToLeft(ref mat); return mat; } } } //might have a max pivot geomNodes =from lvs in colFile.Items.OfType<library_visual_scenes>().First().visual_scene from n in lvs.node where n.instance_geometry == null && n.node1 != null select n; foreach(node n in geomNodes) { var subNodes =from nd in n.node1 where nd.instance_geometry != null select nd; foreach(node sn in subNodes) { foreach(instance_geometry ig in sn.instance_geometry) { if(ig.url.Substring(1) == g.id) { if(!CNodeHasKeyData(sn) && !CNodeHasKeyData(n)) { //no transform needed return Matrix.Identity; } Matrix parentMat =Matrix.Identity; Matrix mat =Matrix.Identity; if(CNodeHasKeyData(n)) { KeyFrame kfParent =GetKeyFromCNode(n); parentMat =Matrix.Scaling(kfParent.mScale) * Matrix.RotationQuaternion(kfParent.mRotation) * Matrix.Translation(kfParent.mPosition); KeyFrame.RightHandToLeft(ref parentMat); } if(CNodeHasKeyData(sn)) { KeyFrame kf =GetKeyFromCNode(sn); mat =Matrix.Scaling(kf.mScale) * Matrix.RotationQuaternion(kf.mRotation) * Matrix.Translation(kf.mPosition); KeyFrame.RightHandToLeft(ref mat); } return parentMat * mat;// * parentMat; } } } } //none found, not necessarily bad //skinned stuff doesn't have this return Matrix.Identity; } internal void RenderUpdate(float msDelta) { if(mChar == null) { return; } if(mSelectedAnim != null && mSelectedAnim != "") { if(!mbPaused) { mCurAnimTime +=msDelta * (float)AnimTimeScale.Value; } if(mAnimStartTime == 0f && mAnimEndTime == 0) { mCurAnimTime =0; } else { if(mCurAnimTime > mAnimEndTime) { mCurAnimTime %=mAnimEndTime; } if(mCurAnimTime < mAnimStartTime) { mCurAnimTime =mAnimStartTime; } } Debug.Assert(!float.IsNaN(mCurAnimTime)); mChar.Animate(mSelectedAnim, mCurAnimTime); } } internal void Render(DeviceContext dc) { if(mStatMesh == null && mChar == null) { return; } if(mStatMesh != null) { mStatMesh.Draw(dc, mMatLib); } if(mChar != null) { mChar.Draw(dc, mMatLib); } } internal void RenderDMN(DeviceContext dc) { if(mStatMesh == null && mChar == null) { return; } if(mStatMesh != null) { mStatMesh.DrawDMN(dc, mMatLib); } if(mChar != null) { mChar.DrawDMN(dc, mMatLib); } } internal void NukeVertexElement(List<int> partIndexes, List<int> vertElementIndexes) { mArch.NukeVertexElements(mGD, partIndexes, vertElementIndexes); } internal void NukeMeshPart(List<int> indexes) { if(mArch != null) { mArch.NukeParts(indexes); } if(mStatMesh != null) { mStatMesh.NukeParts(indexes); } else { mChar.NukeParts(indexes); } } source []MakeSources(string sourcePrefix, IArch arch, int partIndex) { List<source> ret =new List<source>(); Type vType =arch.GetPartVertexType(partIndex); FieldInfo []fi =vType.GetFields(); for(int i=0;i < fi.Length;i++) { source src =new source(); if(fi[i].Name == "Position") { src.id =sourcePrefix + "-positions"; float_array fa =new float_array(); float []positions; arch.GetPartColladaPositions(partIndex, out positions); fa.count =(ulong)positions.Length; fa.id =src.id + "-array"; fa.magnitude =38; //default? fa.Values =positions; src.Item =fa; src.technique_common =new sourceTechnique_common(); src.technique_common.accessor =MakeAccessor(fa.id, positions.Length); } else if(fi[i].Name == "Normal") { src.id =sourcePrefix + "-normals"; float_array fa =new float_array(); float []normals; arch.GetPartColladaNormals(partIndex, out normals); fa.count =(ulong)normals.Length; fa.id =src.id + "-array"; fa.magnitude =38; //default? fa.Values =normals; src.Item =fa; src.technique_common =new sourceTechnique_common(); src.technique_common.accessor =MakeAccessor(fa.id, normals.Length); } else { continue; } ret.Add(src); } return ret.ToArray(); } accessor MakeAccessor(string src, int count) { accessor acc =new accessor(); acc.count =(ulong)(count / 3); acc.stride =3; acc.source ="#" + src; acc.param =new param[3]; for(int i=0;i < 3;i++) { acc.param[i] =new param(); acc.param[i].type ="float"; } acc.param[0].name ="X"; acc.param[1].name ="Y"; acc.param[2].name ="Z"; return acc; } InputLocalOffset []MakeInputs(string sourcePrefix, Type vType) { FieldInfo []fi =vType.GetFields(); List<InputLocalOffset> ret =new List<InputLocalOffset>(); int usedIndex =0; for(int i=0;i < fi.Length;i++) { InputLocalOffset inp =new InputLocalOffset(); inp.offset =(ulong)usedIndex; if(fi[i].Name == "Position") { inp.semantic ="VERTEX"; inp.source ="#" + sourcePrefix + "-vertices"; usedIndex++; } else if(fi[i].Name == "Normal") { inp.semantic ="NORMAL"; inp.source ="#" + sourcePrefix + "-normals"; usedIndex++; } else { continue; } // else if(fi[i].Name == "TexCoord0") // { // inp.semantic ="TEXCOORD"; // inp.source =sourcePrefix + "-normals"; // } ret.Add(inp); } return ret.ToArray(); } void SizeColumns(ListView lv) { //set to header size first Action<ListView> autoResize =lvar => lvar.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); FormExtensions.Invoke(lv, autoResize); List<int> sizes =new List<int>(); for(int i=0;i < lv.Columns.Count;i++) { Action<ListView> addWidth =lvar => sizes.Add(lvar.Columns[i].Width); FormExtensions.Invoke(lv, addWidth); } for(int i=0;i < lv.Columns.Count;i++) { Action<ListView> arHeader =lvar => { lvar.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); if(lvar.Columns[i].Width < sizes[i]) { lvar.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize); } }; FormExtensions.Invoke(lv, arHeader); } } void RefreshAnimList() { Action<ListView> clear =lv => lv.Items.Clear(); FormExtensions.Invoke(AnimList, clear); List<Anim> anims =mAnimLib.GetAnims(); foreach(Anim anm in anims) { Action<ListView> addItem =lv => lv.Items.Add(anm.Name); FormExtensions.Invoke(AnimList, addItem); } for(int i=0;i < AnimList.Items.Count;i++) { Action<ListView> tagAndSub =lv => { lv.Items[i].SubItems.Add(anims[i].TotalTime.ToString()); lv.Items[i].SubItems.Add(anims[i].StartTime.ToString()); lv.Items[i].SubItems.Add(anims[i].Looping.ToString()); lv.Items[i].SubItems.Add(anims[i].PingPong.ToString()); lv.Items[i].SubItems.Add(anims[i].NumKeyFrames.ToString()); }; FormExtensions.Invoke(AnimList, tagAndSub); } SizeColumns(AnimList); } //for adjusting coordinate systems void TransformRoots(Skeleton skel, Anim anm, float scaleFactor) { //adjust coordinate system Matrix shiftMat =Matrix.RotationX(MathUtil.PiOverTwo); //this will undo the scaling from the bind shape shiftMat *=Matrix.Scaling(Vector3.One * scaleFactor); List<string> roots =new List<string>(); skel.GetRootNames(roots); //rotate the animation to match our coord system foreach(string root in roots) { anm.TransformBoneAnim(root, shiftMat); } } void PrintToOutput(string stuff) { OnPrintString(stuff, null); } #region FormEvents void OnPrintString(object sender, EventArgs ea) { //pass it along Misc.SafeInvoke(ePrint, sender, ea); } void OnSaveAnimLib(object sender, EventArgs e) { mSFD.DefaultExt ="*.AnimLib"; mSFD.Filter ="Animation library files (*.AnimLib)|*.AnimLib|All files (*.*)|*.*"; DialogResult dr =mSFD.ShowDialog(); if(dr == DialogResult.Cancel) { return; } mAnimLib.SaveToFile(mSFD.FileName); } void OnLoadAnimLib(object sender, EventArgs e) { mOFD.DefaultExt ="*.AnimLib"; mOFD.Filter ="Animation library files (*.AnimLib)|*.AnimLib|All files (*.*)|*.*"; mOFD.Multiselect =false; DialogResult dr =mOFD.ShowDialog(); if(dr == DialogResult.Cancel) { return; } mAnimLib.ReadFromFile(mOFD.FileName); Misc.SafeInvoke(eSkeletonChanged, mAnimLib.GetSkeleton()); RefreshAnimList(); } void OnLoadCharacter(object sender, EventArgs e) { mOFD.DefaultExt ="*.Character"; mOFD.Filter ="Character files (*.Character)|*.Character|All files (*.*)|*.*"; DialogResult dr =mOFD.ShowDialog(); if(dr == DialogResult.Cancel) { return; } mArch =new CharacterArch(); mChar =new Character(mArch, mAnimLib); Mesh.MeshAndArch mea =new Mesh.MeshAndArch(); mea.mMesh =mChar; mea.mArch =mArch; mArch.ReadFromFile(mOFD.FileName, mGD, true); if(!mChar.ReadFromFile(mOFD.FileName + "Instance")) { //make some materialmesh things int count =mArch.GetPartCount(); for(int i=0;i < count;i++) { mChar.AddPart(mMatLib); } } else { mChar.SetMatLib(mMatLib); } Misc.SafeInvoke(eMeshChanged, mea); } void OnSaveCharacter(object sender, EventArgs e) { mSFD.DefaultExt ="*.Character"; mSFD.Filter ="Character files (*.Character)|*.Character|All files (*.*)|*.*"; DialogResult dr =mSFD.ShowDialog(); if(dr == DialogResult.Cancel) { return; } mArch.SaveToFile(mSFD.FileName); mChar.SaveToFile(mSFD.FileName + "Instance"); } void OnLoadStatic(object sender, EventArgs e) { mOFD.DefaultExt ="*.Static"; mOFD.Filter ="Static mesh files (*.Static)|*.Static|All files (*.*)|*.*"; DialogResult dr =mOFD.ShowDialog(); if(dr == DialogResult.Cancel) { return; } mArch =new StaticArch(); mStatMesh =new StaticMesh(mArch); Mesh.MeshAndArch mea =new Mesh.MeshAndArch(); mea.mMesh =mStatMesh; mea.mArch =mArch; mArch.ReadFromFile(mOFD.FileName, mGD, true); if(!mStatMesh.ReadFromFile(mOFD.FileName + "Instance")) { //make some materialmesh things int count =mArch.GetPartCount(); for(int i=0;i < count;i++) { mStatMesh.AddPart(mMatLib); } } else { mStatMesh.SetMatLib(mMatLib); } Misc.SafeInvoke(eMeshChanged, mea); } void OnSaveStatic(object sender, EventArgs e) { mSFD.DefaultExt ="*.Static"; mSFD.Filter ="Static mesh files (*.Static)|*.Static|All files (*.*)|*.*"; DialogResult dr =mSFD.ShowDialog(); if(dr == DialogResult.Cancel) { return; } mArch.SaveToFile(mSFD.FileName); mStatMesh.SaveToFile(mSFD.FileName + "Instance"); } void OnOpenStaticDAE(object sender, EventArgs e) { mOFD.DefaultExt ="*.dae"; mOFD.Filter ="DAE Collada files (*.dae)|*.dae|All files (*.*)|*.*"; mOFD.Multiselect =false; DialogResult dr =mOFD.ShowDialog(); if(dr == DialogResult.Cancel) { return; } mArch =LoadStatic(mOFD.FileName, out mStatMesh); Mesh.MeshAndArch mea =new Mesh.MeshAndArch(); mea.mMesh =mStatMesh; mea.mArch =mArch; Misc.SafeInvoke(eMeshChanged, mea); } void OnLoadCharacterDAE(object sender, EventArgs e) { mOFD.DefaultExt ="*.dae"; mOFD.Filter ="DAE Collada files (*.dae)|*.dae|All files (*.*)|*.*"; mOFD.Multiselect =true; //individual parts now DialogResult dr =mOFD.ShowDialog(); if(dr == DialogResult.Cancel) { return; } foreach(string fileName in mOFD.FileNames) { LoadCharacterDAE(fileName, mAnimLib, mArch, mChar); } RefreshAnimList(); Mesh.MeshAndArch mea =new Mesh.MeshAndArch(); mea.mMesh =mChar; mea.mArch =mArch; Misc.SafeInvoke(eMeshChanged, mea); } void OnLoadAnimDAE(object sender, EventArgs e) { mOFD.DefaultExt ="*.dae"; mOFD.Filter ="DAE Collada files (*.dae)|*.dae|All files (*.*)|*.*"; mOFD.Multiselect =false; DialogResult dr =mOFD.ShowDialog(); if(dr == DialogResult.Cancel) { return; } LoadAnimDAE(mOFD.FileName, mAnimLib, CheckSkeleton.Checked); RefreshAnimList(); } void OnAnimListSelectionChanged(object sender, EventArgs e) { if(AnimList.SelectedIndices.Count != 1) { return; } string selAnim =AnimList.SelectedItems[0].Text; Anim anm =mAnimLib.GetAnim(selAnim); if(anm == null) { return; } mSelectedAnim =anm.Name; mAnimStartTime =anm.StartTime; mAnimEndTime =anm.TotalTime + anm.StartTime; } void OnReCollada(object sender, EventArgs e) { mSFD.DefaultExt ="*.dae"; mSFD.Filter ="DAE Collada files (*.dae)|*.dae|All files (*.*)|*.*"; DialogResult dr =mSFD.ShowDialog(); if(dr == DialogResult.Cancel) { return; } COLLADA col; ConvertMesh(mArch, out col); SerializeCOLLADA(col, mSFD.FileName); } void OnPauseAnim(object sender, EventArgs e) { mbPaused =!mbPaused; if(mbPaused) { PauseButton.Text ="Paused"; } else { PauseButton.Text ="Pause"; } } void OnAnimCellValueChanged(object sender, DataGridViewCellEventArgs e) { if(e.ColumnIndex == 0) { mAnimLib.FixRename(); } } void OnCalcBounds(object sender, EventArgs e) { mArch.UpdateBounds(); if(mStatMesh != null) { if(!mStatMesh.IsEmpty()) { mStatMesh.UpdateBounds(); Misc.SafeInvoke(eBoundsChanged, mStatMesh); } } if(mChar != null) { if(!mChar.IsEmpty()) { mChar.UpdateBounds(); Misc.SafeInvoke(eBoundsChanged, mChar); } } } void OnShowSphereChanged(object sender, EventArgs e) { if(ShowSphere.Checked) { ShowBox.Checked =false; } } void OnShowBoxChanged(object sender, EventArgs e) { if(ShowBox.Checked) { ShowSphere.Checked =false; } } void OnAnimRename(object sender, LabelEditEventArgs e) { if(!mAnimLib.RenameAnim(AnimList.Items[e.Item].Text, e.Label)) { e.CancelEdit =true; } else { SizeColumns(AnimList); } } void OnAnimListKeyUp(object sender, KeyEventArgs e) { if(e.KeyValue == 46) //delete { if(AnimList.SelectedItems.Count < 1) { return; //nothing to do } foreach(ListViewItem lvi in AnimList.SelectedItems) { mAnimLib.NukeAnim(lvi.Text); } RefreshAnimList(); } } #endregion } }
24.02223
155
0.604164
[ "MIT" ]
Kharzette/GrogTools
ColladaConvert/Forms/AnimForm.cs
69,162
C#
namespace TravellerUtils.Libraries.Common.Constants { public static class StellarLuminosities { public const string Ia = "Ia"; public const string Ib = "Ib"; public const string I = "I"; public const string II = "II"; public const string III = "III"; public const string IV= "IV"; public const string V = "V"; public const string D = "D"; } }
28
52
0.588095
[ "MIT" ]
brian-nelson/traveller-tools
src/Apps/Common/Constants/StellarLuminosities.cs
422
C#
using System; using System.Diagnostics; using System.Reflection; using QAHelper.WPF; namespace QAHelper.ViewModels { public class AboutViewModel : BindableBase { public AboutViewModel() { SupportCommand = new DelegateCommand(SupportAction); } public string SupportEmail => "andriy.buzhak.1@gmail.com"; public string ToolVersion { get { Version v = Assembly.GetExecutingAssembly().GetName().Version; return "v" + string.Join(".", v.Major, v.Minor, v.Build); } } public DelegateCommand SupportCommand { get; } private void SupportAction() { Process.Start(new Uri("mailto:" + SupportEmail + "?subject=QA Helper " + ToolVersion + " Support: <Please, specify subject of the issue>&body=<Please, specify description of the issue>").AbsoluteUri); } } }
27.764706
212
0.598517
[ "Apache-2.0" ]
heo732/QAHelper
src/ViewModels/AboutViewModel.cs
946
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("ViennaNET.Messaging.MQSeriesQueue.Tests")] [assembly: InternalsVisibleTo("ViennaNET.Messaging.Tests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
46.6
73
0.83691
[ "MIT" ]
Raiffeisen-DGTL/Company.Framework
src/ViennaNET.Messaging.MQSeriesQueue/AssemblyInfo.cs
235
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* PftDebugEventArgs.cs -- * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using JetBrains.Annotations; using MoonSharp.Interpreter; #endregion namespace ManagedIrbis.Pft.Infrastructure { /// <summary> /// /// </summary> [PublicAPI] [MoonSharpUserData] public sealed class PftDebugEventArgs : EventArgs { #region Properties /// <summary> /// Cancel execution? /// </summary> public bool CancelExecution { get; set; } /// <summary> /// Context. /// </summary> [CanBeNull] public PftContext Context { get; set; } /// <summary> /// AST node. /// </summary> [CanBeNull] public PftNode Node { get; set; } /// <summary> /// Variable. /// </summary> [CanBeNull] public PftVariable Variable { get; set; } #endregion #region Construction /// <summary> /// Constructor. /// </summary> public PftDebugEventArgs() { } /// <summary> /// Constructor. /// </summary> public PftDebugEventArgs ( [CanBeNull] PftContext context, [CanBeNull] PftNode node ) { Context = context; Node = node; } #endregion } }
20.463415
84
0.498212
[ "MIT" ]
amironov73/ManagedClient.45
Source/Classic/Libs/ManagedIrbis/Source/Pft/Infrastructure/PftDebugEventArgs.cs
1,680
C#
using System; using System.Collections.Generic; using System.Text; namespace P01_Vehicle.Models { public class Truck : Vehicle { public Truck(double quantity, double consumption) : base(quantity, consumption) { } protected override double FuelConsumtionModifier => 1.6; public override void Refuel(double liters) { base.Refuel(liters * 0.95); } } }
22.684211
87
0.62877
[ "MIT" ]
aalishov/SoftUni
04-CSharp-OOP-February-2020/Topic12-Polymorphism-Exercise/P01-Vehicle/Models/Truck.cs
433
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.R_kvstore.Model.V20150101 { public class DescribeParameterTemplatesResponse : AcsResponse { private string requestId; private string engine; private string engineVersion; private string parameterCount; private List<DescribeParameterTemplates_TemplateRecord> parameters; public string RequestId { get { return requestId; } set { requestId = value; } } public string Engine { get { return engine; } set { engine = value; } } public string EngineVersion { get { return engineVersion; } set { engineVersion = value; } } public string ParameterCount { get { return parameterCount; } set { parameterCount = value; } } public List<DescribeParameterTemplates_TemplateRecord> Parameters { get { return parameters; } set { parameters = value; } } public class DescribeParameterTemplates_TemplateRecord { private string parameterName; private string parameterValue; private bool? forceModify; private bool? forceRestart; private string checkingCode; private string parameterDescription; public string ParameterName { get { return parameterName; } set { parameterName = value; } } public string ParameterValue { get { return parameterValue; } set { parameterValue = value; } } public bool? ForceModify { get { return forceModify; } set { forceModify = value; } } public bool? ForceRestart { get { return forceRestart; } set { forceRestart = value; } } public string CheckingCode { get { return checkingCode; } set { checkingCode = value; } } public string ParameterDescription { get { return parameterDescription; } set { parameterDescription = value; } } } } }
16.518717
70
0.605698
[ "Apache-2.0" ]
bitType/aliyun-openapi-net-sdk
aliyun-net-sdk-r-kvstore/R_kvstore/Model/V20150101/DescribeParameterTemplatesResponse.cs
3,089
C#
using UnityEngine; namespace PropHunt.Utils { /// <summary> /// Interface to hold the data for a controller collider hit event. /// Wrapping this in an interface makes the testing of a controller collider hit /// easier to manage. /// </summary> public interface IControllerColliderHit { /// <summary> /// The collider that was hit by the controller. /// </summary> Collider collider { get; } /// <summary> /// The rigidbody that was hit by the controller. /// </summary> Rigidbody rigidbody { get; } /// <summary> /// The game object that was hit by the controller. /// </summary> GameObject gameObject { get; } /// <summary> /// The transform that was hit by the controller. /// </summary> Transform transform { get; } /// <summary> /// The impact point in world space. /// </summary> Vector3 point { get; } /// <summary> /// The normal of the surface we collided with in world space. /// </summary> Vector3 normal { get; } /// <summary> /// The direction the CharacterController was moving in when the collision occurred. /// </summary> Vector3 moveDirection { get; } /// <summary> /// How far the character has travelled until it hit the collider. /// </summary> float moveLength { get; } } public class KinematicCharacterControllerHit : IControllerColliderHit { /// <summary> /// Create a hit event for a kinematic character controller /// </summary> /// <param name="hit">the collider hit by this character controller</param> /// <param name="rigidbody">the rigidbody hit by this character controller</param> /// <param name="gameObject">the game object that was hit by this character controller</param> /// <param name="transform">the transform of the game object hit by this character controller</param> /// <param name="point">the point that this character controller collided with the object</param> /// <param name="normal">the normal vector of the hit between the character controller and the hit object</param> /// <param name="moveDirection">the direction the player was moving</param> /// <param name="moveLength">the distance the player was moving</param> public KinematicCharacterControllerHit( Collider hit, Rigidbody rigidbody, GameObject gameObject, Transform transform, Vector3 point, Vector3 normal, Vector3 moveDirection, float moveLength) { this.collider = collider; this.rigidbody = rigidbody; this.gameObject = gameObject; this.transform = transform; this.point = point; this.normal = normal; this.moveDirection = moveDirection; this.moveLength = moveLength; } public Collider collider { get; private set; } public Rigidbody rigidbody { get; private set; } public GameObject gameObject { get; private set; } public Transform transform { get; private set; } public Vector3 point { get; private set; } public Vector3 normal { get; private set; } public Vector3 moveDirection { get; private set; } public float moveLength { get; private set; } } /// <summary> /// Wrapper for the data in a ControllerColliderHit /// </summary> public class ControllerColliderHitWrapper : IControllerColliderHit { ControllerColliderHit colliderHit; Vector3 moveVector; public ControllerColliderHitWrapper(ControllerColliderHit colliderHit, Vector3 moveVector) { this.colliderHit = colliderHit; this.moveVector = moveVector; } public Collider collider => colliderHit.collider; public Rigidbody rigidbody => colliderHit.rigidbody; public GameObject gameObject => colliderHit.gameObject; public Transform transform => colliderHit.transform; public Vector3 point => colliderHit.point; public Vector3 normal => colliderHit.normal; public Vector3 moveDirection => moveVector.normalized; public float moveLength => moveVector.magnitude; } }
37.415254
121
0.621518
[ "MIT" ]
nicholas-maltbie/FallingParkour
Assets/Scripts/Utils/ControllerColliderHitWrapper.cs
4,415
C#
// <copyright file="AutoAddDefineSymbols.cs" company="Jan Ivar Z. Carlsen, Sindri Jóelsson"> // Copyright (c) 2016 Jan Ivar Z. Carlsen, Sindri Jóelsson. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> #if UNITY_EDITOR namespace CloudOnce.Internal.Editor.Utils { using UnityEditor; #if UNITY_2017_1_OR_NEWER using UnityEditor.Build; #endif /// <summary> /// Automatically adds the NO_GPGS script define symbol to iOS player settings. /// </summary> [InitializeOnLoad] public class AutoAddDefineSymbols #if UNITY_2017_1_OR_NEWER : IActiveBuildTargetChanged #endif { private const string defineSymbol = "NO_GPGS"; static AutoAddDefineSymbols() { SetNoGPGS(); } #if UNITY_2017_1_OR_NEWER public int callbackOrder { get { return 0; } } public void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget newTarget) { if (newTarget == BuildTarget.iOS) { SetNoGPGS(); } } #endif private static void SetNoGPGS() { var defineSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS).Trim(); if (!defineSymbols.Contains(defineSymbol)) { if (string.IsNullOrEmpty(defineSymbols)) { PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS, defineSymbol); } else { PlayerSettings.SetScriptingDefineSymbolsForGroup( BuildTargetGroup.iOS, defineSymbols + ";" + defineSymbol); } } // Disable Jar background resolution EditorPrefs.SetBool("GooglePlayServices.AutoResolverEnabled", false); } } } #endif
30.424242
110
0.603088
[ "MIT" ]
babak-ss/CloudOnce
source/PluginDev/Assets/Extensions/CloudOnce/Internal/Editor/Utils/AutoAddDefineSymbols.cs
2,010
C#
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir & xuri 2021 // // 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. // This file was automatically generated and should not be edited directly. using System; namespace SharpVk.Multivendor { /// <summary> /// </summary> public static class PhysicalDeviceExtensions { /// <summary> /// Acquire access to a Display using Xlib. /// </summary> /// <param name="extendedHandle"> /// The PhysicalDevice handle to extend. /// </param> /// <param name="dpy"> /// A connection to the X11 server that currently owns the display. /// </param> /// <param name="display"> /// The display the caller wishes to control in Vulkan. /// </param> public static unsafe void AcquireXlibDisplay(this PhysicalDevice extendedHandle, IntPtr dpy, Khronos.Display display) { try { CommandCache commandCache = default; IntPtr* marshalledDpy = default; commandCache = extendedHandle.commandCache; marshalledDpy = (IntPtr*)(Interop.HeapUtil.Allocate<IntPtr>()); *marshalledDpy = dpy; SharpVk.Interop.Multivendor.VkPhysicalDeviceAcquireXlibDisplayDelegate commandDelegate = commandCache.Cache.vkAcquireXlibDisplayEXT; Result methodResult = commandDelegate(extendedHandle.Handle, marshalledDpy, display?.Handle ?? default); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// Query the DisplayKHR corresponding to an X11 RandR Output. /// </summary> /// <param name="extendedHandle"> /// The PhysicalDevice handle to extend. /// </param> /// <param name="dpy"> /// </param> /// <param name="rrOutput"> /// </param> public static unsafe Khronos.Display GetRandROutputDisplay(this PhysicalDevice extendedHandle, IntPtr dpy, IntPtr rrOutput) { try { Khronos.Display result = default; CommandCache commandCache = default; IntPtr* marshalledDpy = default; SharpVk.Interop.Khronos.Display marshalledDisplay = default; commandCache = extendedHandle.commandCache; marshalledDpy = (IntPtr*)(Interop.HeapUtil.Allocate<IntPtr>()); *marshalledDpy = dpy; SharpVk.Interop.Multivendor.VkPhysicalDeviceGetRandROutputDisplayDelegate commandDelegate = commandCache.Cache.vkGetRandROutputDisplayEXT; Result methodResult = commandDelegate(extendedHandle.Handle, marshalledDpy, rrOutput, &marshalledDisplay); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } result = new Khronos.Display(extendedHandle, marshalledDisplay); return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// Query surface capabilities. /// </summary> /// <param name="extendedHandle"> /// The PhysicalDevice handle to extend. /// </param> /// <param name="surface"> /// </param> public static unsafe SurfaceCapabilities2 GetSurfaceCapabilities2(this PhysicalDevice extendedHandle, Khronos.Surface surface) { try { SurfaceCapabilities2 result = default; CommandCache commandCache = default; SharpVk.Interop.Multivendor.SurfaceCapabilities2 marshalledSurfaceCapabilities = default; commandCache = extendedHandle.commandCache; SharpVk.Interop.Multivendor.VkPhysicalDeviceGetSurfaceCapabilities2Delegate commandDelegate = commandCache.Cache.vkGetPhysicalDeviceSurfaceCapabilities2EXT; Result methodResult = commandDelegate(extendedHandle.Handle, surface?.Handle ?? default, &marshalledSurfaceCapabilities); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } result = SurfaceCapabilities2.MarshalFrom(&marshalledSurfaceCapabilities); return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// </summary> /// <param name="extendedHandle"> /// The PhysicalDevice handle to extend. /// </param> /// <param name="samples"> /// </param> public static unsafe MultisampleProperties GetMultisampleProperties(this PhysicalDevice extendedHandle, SampleCountFlags samples) { try { MultisampleProperties result = default; CommandCache commandCache = default; SharpVk.Interop.Multivendor.MultisampleProperties marshalledMultisampleProperties = default; commandCache = extendedHandle.commandCache; SharpVk.Interop.Multivendor.VkPhysicalDeviceGetMultisamplePropertiesDelegate commandDelegate = commandCache.Cache.vkGetPhysicalDeviceMultisamplePropertiesEXT; commandDelegate(extendedHandle.Handle, samples, &marshalledMultisampleProperties); result = MultisampleProperties.MarshalFrom(&marshalledMultisampleProperties); return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// </summary> /// <param name="extendedHandle"> /// The PhysicalDevice handle to extend. /// </param> public static unsafe TimeDomain[] GetCalibrateableTimeDomains(this PhysicalDevice extendedHandle) { try { TimeDomain[] result = default; uint marshalledTimeDomainCount = default; CommandCache commandCache = default; TimeDomain* marshalledTimeDomains = default; commandCache = extendedHandle.commandCache; SharpVk.Interop.Multivendor.VkPhysicalDeviceGetCalibrateableTimeDomainsDelegate commandDelegate = commandCache.Cache.vkGetPhysicalDeviceCalibrateableTimeDomainsEXT; Result methodResult = commandDelegate(extendedHandle.Handle, &marshalledTimeDomainCount, marshalledTimeDomains); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } marshalledTimeDomains = (TimeDomain*)(Interop.HeapUtil.Allocate<TimeDomain>((uint)(marshalledTimeDomainCount))); commandDelegate(extendedHandle.Handle, &marshalledTimeDomainCount, marshalledTimeDomains); if (marshalledTimeDomains != null) { var fieldPointer = new TimeDomain[(uint)(marshalledTimeDomainCount)]; for(int index = 0; index < (uint)(marshalledTimeDomainCount); index++) { fieldPointer[index] = marshalledTimeDomains[index]; } result = fieldPointer; } else { result = null; } return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// </summary> /// <param name="extendedHandle"> /// The PhysicalDevice handle to extend. /// </param> public static unsafe PhysicalDeviceToolProperties[] GetToolProperties(this PhysicalDevice extendedHandle) { try { PhysicalDeviceToolProperties[] result = default; uint marshalledToolCount = default; CommandCache commandCache = default; SharpVk.Interop.Multivendor.PhysicalDeviceToolProperties* marshalledToolProperties = default; commandCache = extendedHandle.commandCache; SharpVk.Interop.Multivendor.VkPhysicalDeviceGetToolPropertiesDelegate commandDelegate = commandCache.Cache.vkGetPhysicalDeviceToolPropertiesEXT; Result methodResult = commandDelegate(extendedHandle.Handle, &marshalledToolCount, marshalledToolProperties); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } marshalledToolProperties = (SharpVk.Interop.Multivendor.PhysicalDeviceToolProperties*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Multivendor.PhysicalDeviceToolProperties>((uint)(marshalledToolCount))); commandDelegate(extendedHandle.Handle, &marshalledToolCount, marshalledToolProperties); if (marshalledToolProperties != null) { var fieldPointer = new PhysicalDeviceToolProperties[(uint)(marshalledToolCount)]; for(int index = 0; index < (uint)(marshalledToolCount); index++) { fieldPointer[index] = PhysicalDeviceToolProperties.MarshalFrom(&marshalledToolProperties[index]); } result = fieldPointer; } else { result = null; } return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// Query supported presentation modes /// </summary> /// <param name="extendedHandle"> /// The PhysicalDevice handle to extend. /// </param> /// <param name="surfaceInfo"> /// An instance of the VkPhysicalDeviceSurfaceInfo2KHR structure, /// describing the surface and other fixed parameters that would be /// consumed by vkCreateSwapchainKHR. /// </param> public static unsafe Khronos.PresentMode[] GetSurfacePresentModes2(this PhysicalDevice extendedHandle, Khronos.PhysicalDeviceSurfaceInfo2 surfaceInfo) { try { Khronos.PresentMode[] result = default; uint marshalledPresentModeCount = default; CommandCache commandCache = default; SharpVk.Interop.Khronos.PhysicalDeviceSurfaceInfo2* marshalledSurfaceInfo = default; Khronos.PresentMode* marshalledPresentModes = default; commandCache = extendedHandle.commandCache; marshalledSurfaceInfo = (SharpVk.Interop.Khronos.PhysicalDeviceSurfaceInfo2*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Khronos.PhysicalDeviceSurfaceInfo2>()); surfaceInfo.MarshalTo(marshalledSurfaceInfo); SharpVk.Interop.Multivendor.VkPhysicalDeviceGetSurfacePresentModes2Delegate commandDelegate = commandCache.Cache.vkGetPhysicalDeviceSurfacePresentModes2EXT; Result methodResult = commandDelegate(extendedHandle.Handle, marshalledSurfaceInfo, &marshalledPresentModeCount, marshalledPresentModes); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } marshalledPresentModes = (Khronos.PresentMode*)(Interop.HeapUtil.Allocate<Khronos.PresentMode>((uint)(marshalledPresentModeCount))); commandDelegate(extendedHandle.Handle, marshalledSurfaceInfo, &marshalledPresentModeCount, marshalledPresentModes); if (marshalledPresentModes != null) { var fieldPointer = new Khronos.PresentMode[(uint)(marshalledPresentModeCount)]; for(int index = 0; index < (uint)(marshalledPresentModeCount); index++) { fieldPointer[index] = marshalledPresentModes[index]; } result = fieldPointer; } else { result = null; } return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// </summary> /// <param name="extendedHandle"> /// The PhysicalDevice handle to extend. /// </param> /// <param name="queueFamilyIndex"> /// </param> /// <param name="dfb"> /// </param> public static unsafe void GetDirectFBPresentationSupport(this PhysicalDevice extendedHandle, uint queueFamilyIndex, IDirectFB dfb) { try { CommandCache commandCache = default; IDirectFB* marshalledDfb = default; commandCache = extendedHandle.commandCache; marshalledDfb = (IDirectFB*)(Interop.HeapUtil.Allocate<IDirectFB>()); *marshalledDfb = dfb; SharpVk.Interop.Multivendor.VkPhysicalDeviceGetDirectFBPresentationSupportDelegate commandDelegate = commandCache.Cache.vkGetPhysicalDeviceDirectFBPresentationSupportEXT; commandDelegate(extendedHandle.Handle, queueFamilyIndex, marshalledDfb); } finally { Interop.HeapUtil.FreeAll(); } } } }
46.230061
217
0.597372
[ "MIT" ]
xuri02/SharpVk
src/SharpVk/Multivendor/PhysicalDeviceExtensions.gen.cs
15,071
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. #nullable disable using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Windows.Forms.Layout; namespace System.Windows.Forms { [ToolboxItem(false)] public class ToolStripPanelRow : Component, IArrangedElement { private Rectangle _bounds = Rectangle.Empty; private BitVector32 _state; private int _suspendCount; private ToolStripPanelRowManager _rowManager; private const int MinAllowedWidth = 50; private readonly int _minAllowedWidth = MinAllowedWidth; private static readonly int s_stateVisible = BitVector32.CreateMask(); private static readonly int s_stateDisposing = BitVector32.CreateMask(s_stateVisible); private static readonly int s_stateLocked = BitVector32.CreateMask(s_stateDisposing); private static readonly int s_stateInitialized = BitVector32.CreateMask(s_stateLocked); private static readonly int s_stateCachedBoundsMode = BitVector32.CreateMask(s_stateInitialized); private static readonly int s_stateInLayout = BitVector32.CreateMask(s_stateCachedBoundsMode); private static readonly int s_propControlsCollection = PropertyStore.CreateKey(); #if DEBUG internal static TraceSwitch s_toolStripPanelRowCreationDebug = new TraceSwitch("ToolStripPanelRowCreationDebug", "Debug code for rafting row creation"); #else internal static TraceSwitch s_toolStripPanelRowCreationDebug; #endif #if DEBUG private static int s_rowCreationCount; private readonly int _thisRowID; #endif public ToolStripPanelRow(ToolStripPanel parent) : this(parent, true) { } internal ToolStripPanelRow(ToolStripPanel parent, bool visible) { #if DEBUG _thisRowID = ++s_rowCreationCount; #endif if (DpiHelper.IsScalingRequirementMet) { _minAllowedWidth = DpiHelper.LogicalToDeviceUnitsX(MinAllowedWidth); } this.ToolStripPanel = parent; _state[s_stateVisible] = visible; _state[s_stateDisposing | s_stateLocked | s_stateInitialized] = false; Debug.WriteLineIf(s_toolStripPanelRowCreationDebug.TraceVerbose, "Created new ToolStripPanelRow"); using (LayoutTransaction lt = new LayoutTransaction(parent, this, null)) { Margin = DefaultMargin; CommonProperties.SetAutoSize(this, true); } } public Rectangle Bounds { get { return _bounds; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [SRDescription(nameof(SR.ControlControlsDescr))] public Control[] Controls { get { Control[] controls = new Control[ControlsInternal.Count]; ControlsInternal.CopyTo(controls, 0); return controls; } } /// <summary> /// Collection of child controls. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [SRDescription(nameof(SR.ControlControlsDescr))] internal ToolStripPanelRowControlCollection ControlsInternal { get { ToolStripPanelRowControlCollection controlsCollection = (ToolStripPanelRowControlCollection)Properties.GetObject(s_propControlsCollection); if (controlsCollection is null) { controlsCollection = CreateControlsInstance(); Properties.SetObject(s_propControlsCollection, controlsCollection); } return controlsCollection; } } internal ArrangedElementCollection Cells { get { return ControlsInternal.Cells; } } internal bool CachedBoundsMode { get { return _state[s_stateCachedBoundsMode]; } set { _state[s_stateCachedBoundsMode] = value; } } private ToolStripPanelRowManager RowManager { get { if (_rowManager is null) { _rowManager = (Orientation == Orientation.Horizontal) ? new HorizontalRowManager(this) as ToolStripPanelRowManager : new VerticalRowManager(this) as ToolStripPanelRowManager; Initialized = true; } return _rowManager; } } protected virtual Padding DefaultMargin { get { ToolStripPanelCell cell = RowManager.GetNextVisibleCell(0, /*forward*/true); if (cell != null && cell.DraggedControl != null) { if (cell.DraggedControl.Stretch) { Padding padding = ToolStripPanel.RowMargin; // clear out the padding. if (Orientation == Orientation.Horizontal) { padding.Left = 0; padding.Right = 0; } else { padding.Top = 0; padding.Bottom = 0; } return padding; } } return ToolStripPanel.RowMargin; } } protected virtual Padding DefaultPadding { get { return Padding.Empty; } } public Rectangle DisplayRectangle { get { return RowManager.DisplayRectangle; } } public LayoutEngine LayoutEngine { get { return FlowLayout.Instance; } } internal bool Locked { get { return _state[s_stateLocked]; } } private bool Initialized { get { return _state[s_stateInitialized]; } set { _state[s_stateInitialized] = value; } } public Padding Margin { get { return CommonProperties.GetMargin(this); } set { if (Margin != value) { CommonProperties.SetMargin(this, value); } } } public virtual Padding Padding { get { return CommonProperties.GetPadding(this, DefaultPadding); } set { if (Padding != value) { CommonProperties.SetPadding(this, value); } } } internal Control ParentInternal { get { return ToolStripPanel; } } /// <summary> /// Retrieves our internal property storage object. If you have a property /// whose value is not always set, you should store it in here to save /// space. /// </summary> internal PropertyStore Properties { get; } = new PropertyStore(); public ToolStripPanel ToolStripPanel { get; } internal bool Visible { get { return _state[s_stateVisible]; } } public Orientation Orientation { get { return ToolStripPanel.Orientation; } } #if DEBUG internal void Debug_PrintRowID() { Debug.Write(_thisRowID.ToString(CultureInfo.CurrentCulture)); } #endif /// <summary> /// returns true if there is enough space to "raft" the control /// ow returns false /// </summary> public bool CanMove(ToolStrip toolStripToDrag) { return !ToolStripPanel.Locked && !Locked && RowManager.CanMove(toolStripToDrag); } private ToolStripPanelRowControlCollection CreateControlsInstance() { return new ToolStripPanelRowControlCollection(this); } protected override void Dispose(bool disposing) { try { if (disposing) { Debug.WriteLineIf(s_toolStripPanelRowCreationDebug.TraceVerbose, "Disposed ToolStripPanelRow"); _state[s_stateDisposing] = true; ControlsInternal.Clear(); } } finally { _state[s_stateDisposing] = false; base.Dispose(disposing); } } protected internal virtual void OnControlAdded(Control control, int index) { // if previously added - remove. if (control is ISupportToolStripPanel controlToBeDragged) { controlToBeDragged.ToolStripPanelRow = this; } RowManager.OnControlAdded(control, index); } protected internal virtual void OnOrientationChanged() { _rowManager = null; } protected void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) { ((IArrangedElement)this).PerformLayout((IArrangedElement)this, PropertyNames.Size); RowManager.OnBoundsChanged(oldBounds, newBounds); } protected internal virtual void OnControlRemoved(Control control, int index) { if (!_state[s_stateDisposing]) { SuspendLayout(); RowManager.OnControlRemoved(control, index); // if previously added - remove. if (control is ISupportToolStripPanel controlToBeDragged && controlToBeDragged.ToolStripPanelRow == this) { controlToBeDragged.ToolStripPanelRow = null; } ResumeLayout(true); if (ControlsInternal.Count <= 0) { ToolStripPanel.RowsInternal.Remove(this); Dispose(); } } } internal Size GetMinimumSize(ToolStrip toolStrip) { if (toolStrip.MinimumSize == Size.Empty) { return new Size(_minAllowedWidth, _minAllowedWidth); } else { return toolStrip.MinimumSize; } } private void ApplyCachedBounds() { for (int i = 0; i < Cells.Count; i++) { IArrangedElement element = Cells[i] as IArrangedElement; if (element.ParticipatesInLayout) { ToolStripPanelCell cell = element as ToolStripPanelCell; element.SetBounds(cell.CachedBounds, BoundsSpecified.None); // Debug.Assert( cell.Control is null || cell.CachedBounds.Location == cell.Control.Bounds.Location, "CachedBounds out of sync with bounds!"); } } } protected virtual void OnLayout(LayoutEventArgs e) { if (Initialized && !_state[s_stateInLayout]) { _state[s_stateInLayout] = true; try { Margin = DefaultMargin; CachedBoundsMode = true; try { // dont layout in the constructor that's just tacky. bool parentNeedsLayout = LayoutEngine.Layout(this, e); } finally { CachedBoundsMode = false; } ToolStripPanelCell cell = RowManager.GetNextVisibleCell(Cells.Count - 1, /*forward*/false); if (cell is null) { ApplyCachedBounds(); } else if (Orientation == Orientation.Horizontal) { OnLayoutHorizontalPostFix(); } else { OnLayoutVerticalPostFix(); } } finally { _state[s_stateInLayout] = false; } } } private void OnLayoutHorizontalPostFix() { ToolStripPanelCell cell = RowManager.GetNextVisibleCell(Cells.Count - 1, /*forward*/false); if (cell is null) { ApplyCachedBounds(); return; } // figure out how much space we actually need to free. int spaceToFree = cell.CachedBounds.Right - RowManager.DisplayRectangle.Right; if (spaceToFree <= 0) { // we're all good. Just apply the cached bounds. ApplyCachedBounds(); return; } // STEP 1 remove empty space in the row. // since layout sisuspended, we'll need to watch changes to the margin // as a result of calling FreeSpaceFromRow. int[] margins = new int[Cells.Count]; for (int i = 0; i < Cells.Count; i++) { ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; margins[i] = c.Margin.Left; } spaceToFree -= RowManager.FreeSpaceFromRow(spaceToFree); // now apply those changes to the cached bounds. for (int i = 0; i < Cells.Count; i++) { ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; Rectangle cachedBounds = c.CachedBounds; cachedBounds.X -= Math.Max(0, margins[i] - c.Margin.Left); c.CachedBounds = cachedBounds; } if (spaceToFree <= 0) { ApplyCachedBounds(); return; } // STEP 2 change the size of the remaing ToolStrips from Right to Left. int[] cellOffsets = null; for (int i = Cells.Count - 1; i >= 0; i--) { ToolStripPanelCell currentCell = Cells[i] as ToolStripPanelCell; if (currentCell.Visible) { Size minSize = GetMinimumSize(currentCell.Control as ToolStrip); Rectangle cachedBounds = currentCell.CachedBounds; // found some space to free. if (cachedBounds.Width > minSize.Width) { spaceToFree -= (cachedBounds.Width - minSize.Width); // make sure we dont take more space than we need - if spaceToFree is less than 0, add back in. cachedBounds.Width = (spaceToFree < 0) ? minSize.Width + -spaceToFree : minSize.Width; // we're not reperforming a layout, so we need to adjust the next cell for (int j = i + 1; j < Cells.Count; j++) { if (cellOffsets is null) { cellOffsets = new int[Cells.Count]; } cellOffsets[j] += Math.Max(0, currentCell.CachedBounds.Width - cachedBounds.Width); } currentCell.CachedBounds = cachedBounds; } } if (spaceToFree <= 0) { break; } } // fixup for items before it shrinking. if (cellOffsets != null) { for (int i = 0; i < Cells.Count; i++) { ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; Rectangle cachedBounds = c.CachedBounds; cachedBounds.X -= cellOffsets[i]; c.CachedBounds = cachedBounds; } } ApplyCachedBounds(); } private void OnLayoutVerticalPostFix() { ToolStripPanelCell cell = RowManager.GetNextVisibleCell(Cells.Count - 1, /*forward*/false); // figure out how much space we actually need to free. int spaceToFree = cell.CachedBounds.Bottom - RowManager.DisplayRectangle.Bottom; if (spaceToFree <= 0) { // we're all good. Just apply the cached bounds. ApplyCachedBounds(); return; } // STEP 1 remove empty space in the row. // since layout sisuspended, we'll need to watch changes to the margin // as a result of calling FreeSpaceFromRow. int[] margins = new int[Cells.Count]; for (int i = 0; i < Cells.Count; i++) { ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; margins[i] = c.Margin.Top; } spaceToFree -= RowManager.FreeSpaceFromRow(spaceToFree); // now apply those changes to the cached bounds. for (int i = 0; i < Cells.Count; i++) { ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; Rectangle cachedBounds = c.CachedBounds; cachedBounds.X = Math.Max(0, cachedBounds.X - margins[i] - c.Margin.Top); c.CachedBounds = cachedBounds; } if (spaceToFree <= 0) { ApplyCachedBounds(); return; } // STEP 2 change the size of the remaing ToolStrips from Bottom to Top. int[] cellOffsets = null; for (int i = Cells.Count - 1; i >= 0; i--) { ToolStripPanelCell currentCell = Cells[i] as ToolStripPanelCell; if (currentCell.Visible) { Size minSize = GetMinimumSize(currentCell.Control as ToolStrip); Rectangle cachedBounds = currentCell.CachedBounds; // found some space to free. if (cachedBounds.Height > minSize.Height) { spaceToFree -= (cachedBounds.Height - minSize.Height); // make sure we dont take more space than we need - if spaceToFree is less than 0, add back in. cachedBounds.Height = (spaceToFree < 0) ? minSize.Height + -spaceToFree : minSize.Height; // we're not reperforming a layout, so we need to adjust the next cell for (int j = i + 1; j < Cells.Count; j++) { if (cellOffsets is null) { cellOffsets = new int[Cells.Count]; } cellOffsets[j] += Math.Max(0, currentCell.CachedBounds.Height - cachedBounds.Height); } currentCell.CachedBounds = cachedBounds; } } if (spaceToFree <= 0) { break; } } // fixup for items before it shrinking. if (cellOffsets != null) { for (int i = 0; i < Cells.Count; i++) { ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; Rectangle cachedBounds = c.CachedBounds; cachedBounds.Y -= cellOffsets[i]; c.CachedBounds = cachedBounds; } } ApplyCachedBounds(); } private void SetBounds(Rectangle bounds) { if (bounds != this._bounds) { Rectangle oldBounds = this._bounds; this._bounds = bounds; OnBoundsChanged(oldBounds, bounds); } } private void SuspendLayout() { _suspendCount++; } private void ResumeLayout(bool performLayout) { _suspendCount--; if (performLayout) { ((IArrangedElement)this).PerformLayout(this, null); } } ArrangedElementCollection IArrangedElement.Children { get { return Cells; } } /// <summary> /// Should not be exposed as this returns an unexposed type. /// </summary> IArrangedElement IArrangedElement.Container { get { return ToolStripPanel; } } Rectangle IArrangedElement.DisplayRectangle { get { Rectangle displayRectangle = Bounds; return displayRectangle; } } bool IArrangedElement.ParticipatesInLayout { get { return Visible; } } PropertyStore IArrangedElement.Properties { get { return Properties; } } Size IArrangedElement.GetPreferredSize(Size constrainingSize) { Size preferredSize = LayoutEngine.GetPreferredSize(this, constrainingSize - Padding.Size) + Padding.Size; if (Orientation == Orientation.Horizontal && ParentInternal != null) { preferredSize.Width = DisplayRectangle.Width; } else { preferredSize.Height = DisplayRectangle.Height; } return preferredSize; } // Sets the bounds for an element. void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { // in this case the parent is telling us to refresh our bounds - dont // call PerformLayout SetBounds(bounds); } void IArrangedElement.PerformLayout(IArrangedElement container, string propertyName) { if (_suspendCount <= 0) { OnLayout(new LayoutEventArgs(container, propertyName)); } } #region MouseStuff #if DEBUG internal static readonly TraceSwitch ToolStripPanelMouseDebug = new TraceSwitch("ToolStripPanelMouse", "Debug ToolStrip WM_MOUSEACTIVATE code"); #else internal static readonly TraceSwitch ToolStripPanelMouseDebug; #endif internal Rectangle DragBounds { get { return RowManager.DragBounds; } } internal void MoveControl(ToolStrip movingControl, Point startClientLocation, Point endClientLocation) { RowManager.MoveControl(movingControl, startClientLocation, endClientLocation); } // internal void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) { RowManager.JoinRow(toolStripToDrag, locationToDrag); } internal void LeaveRow(ToolStrip toolStripToDrag) { RowManager.LeaveRow(toolStripToDrag); if (ControlsInternal.Count == 0) { ToolStripPanel.RowsInternal.Remove(this); Dispose(); } } #endregion private abstract class ToolStripPanelRowManager { private FlowLayoutSettings _flowLayoutSettings; public ToolStripPanelRowManager(ToolStripPanelRow owner) { Row = owner; } public virtual bool CanMove(ToolStrip toolStripToDrag) { if (toolStripToDrag is ISupportToolStripPanel raftingControl) { if (raftingControl.Stretch) { Debug.WriteLineIf(ToolStripPanelRow.s_toolStripPanelRowCreationDebug.TraceVerbose, "TSP RM CanMove returns false - the item moving is stretched."); return false; } } foreach (Control c in Row.ControlsInternal) { raftingControl = c as ISupportToolStripPanel; if (raftingControl != null) { if (raftingControl.Stretch) { Debug.WriteLineIf(ToolStripPanelRow.s_toolStripPanelRowCreationDebug.TraceVerbose, "TSP RM CanMove returns false - the row already contains a stretched item."); return false; } } } return true; } public virtual Rectangle DragBounds { get { return Rectangle.Empty; } } public virtual Rectangle DisplayRectangle { get { return Rectangle.Empty; } } public ToolStripPanel ToolStripPanel { get { return Row.ToolStripPanel; } } public ToolStripPanelRow Row { get; } public FlowLayoutSettings FlowLayoutSettings { get { if (_flowLayoutSettings is null) { _flowLayoutSettings = new FlowLayoutSettings(Row); } return _flowLayoutSettings; } } protected internal virtual int FreeSpaceFromRow(int spaceToFree) { return 0; } protected virtual int Grow(int index, int growBy) { int freedSpace = 0; if (index >= 0 && index < Row.ControlsInternal.Count - 1) { ToolStripPanelCell cell = (ToolStripPanelCell)Row.Cells[index]; if (cell.Visible) { freedSpace = cell.Grow(growBy); } } return freedSpace; } public ToolStripPanelCell GetNextVisibleCell(int index, bool forward) { if (forward) { for (int i = index; i < Row.Cells.Count; i++) { ToolStripPanelCell cell = Row.Cells[i] as ToolStripPanelCell; if ((cell.Visible || (Row.ToolStripPanel.Visible && cell.ControlInDesignMode)) && cell.ToolStripPanelRow == Row) { return cell; } } } else { for (int i = index; i >= 0; i--) { ToolStripPanelCell cell = Row.Cells[i] as ToolStripPanelCell; if ((cell.Visible || (Row.ToolStripPanel.Visible && cell.ControlInDesignMode)) && cell.ToolStripPanelRow == Row) { return cell; } } } return null; } /// <summary> /// grows all controls after the index to be their preferred size. /// reports back how much space was used. /// </summary> protected virtual int GrowControlsAfter(int index, int growBy) { if (growBy < 0) { Debug.Fail("why was a negative number given to growControlsAfter?"); return 0; } int spaceToFree = growBy; for (int i = index + 1; i < Row.ControlsInternal.Count; i++) { // grow the n+1 item first if it was previously shrunk. int freedSpace = Grow(i, spaceToFree); if (freedSpace >= 0) { spaceToFree -= freedSpace; if (spaceToFree <= 0) { return growBy; } } } return growBy - spaceToFree; } /// <summary> /// grows all controls before the index to be their preferred size. /// reports back how much space was used. /// </summary> protected virtual int GrowControlsBefore(int index, int growBy) { if (growBy < 0) { Debug.Fail("why was a negative number given to growControlsAfter?"); return 0; } int spaceToFree = growBy; // grow the n-1 item first if it was previously shrunk. for (int i = index - 1; i >= 0; i--) { spaceToFree -= Grow(i, spaceToFree); if (spaceToFree <= 0) { return growBy; // we've already gotten all the free space. } } return growBy - spaceToFree; } public virtual void MoveControl(ToolStrip movingControl, Point startClientLocation, Point endClientLocation) { // ToolStripPanel.Join(movingControl, endScreenLocation); } public virtual void LeaveRow(ToolStrip toolStripToDrag) { } public virtual void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) { } protected internal virtual void OnControlAdded(Control c, int index) { } protected internal virtual void OnControlRemoved(Control c, int index) { } protected internal virtual void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) { } } private class HorizontalRowManager : ToolStripPanelRowManager { public HorizontalRowManager(ToolStripPanelRow owner) : base(owner) { owner.SuspendLayout(); FlowLayoutSettings.WrapContents = false; FlowLayoutSettings.FlowDirection = FlowDirection.LeftToRight; owner.ResumeLayout(false); } public override Rectangle DisplayRectangle { get { Rectangle displayRect = ((IArrangedElement)Row).DisplayRectangle; if (ToolStripPanel != null) { Rectangle raftingDisplayRectangle = ToolStripPanel.DisplayRectangle; if ((!ToolStripPanel.Visible || LayoutUtils.IsZeroWidthOrHeight(raftingDisplayRectangle)) && (ToolStripPanel.ParentInternal != null)) { // if were layed out before we're visible we have the wrong display rectangle, so we need to calculate it. displayRect.Width = ToolStripPanel.ParentInternal.DisplayRectangle.Width - (ToolStripPanel.Margin.Horizontal + ToolStripPanel.Padding.Horizontal) - Row.Margin.Horizontal; } else { displayRect.Width = raftingDisplayRectangle.Width - Row.Margin.Horizontal; } } return displayRect; } } public override Rectangle DragBounds { get { Rectangle dragBounds = Row.Bounds; int index = ToolStripPanel.RowsInternal.IndexOf(Row); if (index > 0) { Rectangle previousRowBounds = ToolStripPanel.RowsInternal[index - 1].Bounds; int y = previousRowBounds.Y + previousRowBounds.Height - (previousRowBounds.Height >> 2); dragBounds.Height += dragBounds.Y - y; dragBounds.Y = y; } if (index < ToolStripPanel.RowsInternal.Count - 1) { Rectangle nextRowBounds = ToolStripPanel.RowsInternal[index + 1].Bounds; dragBounds.Height += (nextRowBounds.Height >> 2) + Row.Margin.Bottom + ToolStripPanel.RowsInternal[index + 1].Margin.Top; } dragBounds.Width += Row.Margin.Horizontal + ToolStripPanel.Padding.Horizontal + 5; dragBounds.X -= Row.Margin.Left + ToolStripPanel.Padding.Left + 4; return dragBounds; } } /// <summary> /// returns true if there is enough space to "raft" the control /// ow returns false /// </summary> public override bool CanMove(ToolStrip toolStripToDrag) { if (base.CanMove(toolStripToDrag)) { Size totalSize = Size.Empty; for (int i = 0; i < Row.ControlsInternal.Count; i++) { totalSize += Row.GetMinimumSize(Row.ControlsInternal[i] as ToolStrip); } totalSize += Row.GetMinimumSize(toolStripToDrag as ToolStrip); return totalSize.Width < DisplayRectangle.Width; } Debug.WriteLineIf(ToolStripPanelRow.s_toolStripPanelRowCreationDebug.TraceVerbose, "HorizontalRM.CanMove returns false - not enough room"); return false; } protected internal override int FreeSpaceFromRow(int spaceToFree) { int requiredSpace = spaceToFree; // take a look at the last guy. if his right edge exceeds // the new bounds, then we should go ahead and push him into view. if (spaceToFree > 0) { // we should shrink the last guy and then move him. ToolStripPanelCell lastCellOnRow = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); if (lastCellOnRow is null) { return 0; } Padding cellMargin = lastCellOnRow.Margin; // only check margin.left as we are only concerned with getting right edge of // the toolstrip into view. (space after the fact doesnt count). if (cellMargin.Left >= spaceToFree) { cellMargin.Left -= spaceToFree; cellMargin.Right = 0; spaceToFree = 0; } else { spaceToFree -= lastCellOnRow.Margin.Left; cellMargin.Left = 0; cellMargin.Right = 0; } lastCellOnRow.Margin = cellMargin; // start moving the toolstrips before this guy. spaceToFree -= MoveLeft(Row.Cells.Count - 1, spaceToFree); if (spaceToFree > 0) { spaceToFree -= lastCellOnRow.Shrink(spaceToFree); } } return requiredSpace - Math.Max(0, spaceToFree); } public override void MoveControl(ToolStrip movingControl, Point clientStartLocation, Point clientEndLocation) { if (Row.Locked) { return; } if (DragBounds.Contains(clientEndLocation)) { int index = Row.ControlsInternal.IndexOf(movingControl); int deltaX = clientEndLocation.X - clientStartLocation.X; if (deltaX < 0) { // moving to the left MoveLeft(index, deltaX * -1); } else { MoveRight(index, deltaX); } } else { base.MoveControl(movingControl, clientStartLocation, clientEndLocation); } } private int MoveLeft(int index, int spaceToFree) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveLeft: " + spaceToFree.ToString(CultureInfo.InvariantCulture)); int freedSpace = 0; Row.SuspendLayout(); try { if (spaceToFree == 0 || index < 0) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveLeft Early EXIT - 0 "); return 0; } // remove all margins starting from the index. for (int i = index; i >= 0; i--) { ToolStripPanelCell cell = (ToolStripPanelCell)Row.Cells[i]; if (!cell.Visible && !cell.ControlInDesignMode) { continue; } int requiredSpace = spaceToFree - freedSpace; Padding cellMargin = cell.Margin; if (cellMargin.Horizontal >= requiredSpace) { freedSpace += requiredSpace; cellMargin.Left -= requiredSpace; cellMargin.Right = 0; cell.Margin = cellMargin; } else { freedSpace += cell.Margin.Horizontal; cellMargin.Left = 0; cellMargin.Right = 0; cell.Margin = cellMargin; } if (freedSpace >= spaceToFree) { // add the space we freed to the next guy. if (index + 1 < Row.Cells.Count) { cell = GetNextVisibleCell(index + 1, /*forward*/true); if (cell != null) { cellMargin = cell.Margin; cellMargin.Left += spaceToFree; cell.Margin = cellMargin; } } Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveLeft Recovered (Margin only): " + spaceToFree.ToString(CultureInfo.InvariantCulture)); return spaceToFree; } } } finally { Row.ResumeLayout(true); } Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveLeft Recovered Partial (Shrink): " + freedSpace.ToString(CultureInfo.InvariantCulture)); return freedSpace; } private int MoveRight(int index, int spaceToFree) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight: " + spaceToFree.ToString(CultureInfo.InvariantCulture)); int freedSpace = 0; Row.SuspendLayout(); try { if (spaceToFree == 0 || index < 0 || index >= Row.ControlsInternal.Count) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight Early EXIT - 0 "); return 0; } ToolStripPanelCell cell; Padding cellMargin; // remove all margins after this point in the index. for (int i = index + 1; i < Row.Cells.Count; i++) { cell = (ToolStripPanelCell)Row.Cells[i]; if (!cell.Visible && !cell.ControlInDesignMode) { continue; } int requiredSpace = spaceToFree - freedSpace; cellMargin = cell.Margin; if (cellMargin.Horizontal >= requiredSpace) { freedSpace += requiredSpace; cellMargin.Left -= requiredSpace; cellMargin.Right = 0; cell.Margin = cellMargin; } else { freedSpace += cell.Margin.Horizontal; cellMargin.Left = 0; cellMargin.Right = 0; cell.Margin = cellMargin; } break; } // add in the space at the end of the row. if (Row.Cells.Count > 0 && (spaceToFree > freedSpace)) { ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); if (lastCell != null) { freedSpace += DisplayRectangle.Right - lastCell.Bounds.Right; } else { freedSpace += DisplayRectangle.Width; } } // set the margin of the control that's moving. if (spaceToFree <= freedSpace) { // add the space we freed to the first guy. cell = GetNextVisibleCell(index, /*forward*/true); if (cell is null) { cell = Row.Cells[index] as ToolStripPanelCell; } Debug.Assert(cell != null, "Dont expect cell to be null here, what's going on?"); if (cell != null) { cellMargin = cell.Margin; cellMargin.Left += spaceToFree; cell.Margin = cellMargin; } Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight Recovered (Margin only): " + spaceToFree.ToString(CultureInfo.InvariantCulture)); return spaceToFree; } // Now start shrinking. for (int i = index + 1; i < Row.Cells.Count; i++) { cell = (ToolStripPanelCell)Row.Cells[i]; if (!cell.Visible && !cell.ControlInDesignMode) { continue; } int requiredSpace = spaceToFree - freedSpace; freedSpace += cell.Shrink(requiredSpace); if (spaceToFree >= freedSpace) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight Recovered (Shrink): " + spaceToFree.ToString(CultureInfo.InvariantCulture)); Row.ResumeLayout(true); return spaceToFree; } } if (Row.Cells.Count == 1) { cell = GetNextVisibleCell(index,/*forward*/true); if (cell != null) { cellMargin = cell.Margin; cellMargin.Left += freedSpace; cell.Margin = cellMargin; } } } finally { Row.ResumeLayout(true); } Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight Recovered Partial (Shrink): " + freedSpace.ToString(CultureInfo.InvariantCulture)); return freedSpace; } public override void LeaveRow(ToolStrip toolStripToDrag) { // this code is here to properly add space to the next control when the // toolStripToDrag has been removed from the row. Row.SuspendLayout(); int index = Row.ControlsInternal.IndexOf(toolStripToDrag); if (index >= 0) { if (index < Row.ControlsInternal.Count - 1 /*not the last one in the row*/) { ToolStripPanelCell cell = (ToolStripPanelCell)Row.Cells[index]; if (cell.Visible) { int spaceOccupiedByCell = cell.Margin.Horizontal + cell.Bounds.Width; // add the space occupied by the cell to the next one. ToolStripPanelCell nextCell = GetNextVisibleCell(index + 1, /*forward*/true); if (nextCell != null) { Padding nextCellMargin = nextCell.Margin; nextCellMargin.Left += spaceOccupiedByCell; nextCell.Margin = nextCellMargin; } } } // remove the control from the row. ((IList)Row.Cells).RemoveAt(index); } Row.ResumeLayout(true); } protected internal override void OnControlAdded(Control control, int index) { } protected internal override void OnControlRemoved(Control control, int index) { } public override void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "Horizontal JoinRow called "); int index; if (!Row.ControlsInternal.Contains(toolStripToDrag)) { Row.SuspendLayout(); try { if (Row.ControlsInternal.Count > 0) { // walk through the columns and determine which column you want to insert into. for (index = 0; index < Row.Cells.Count; index++) { ToolStripPanelCell cell = Row.Cells[index] as ToolStripPanelCell; if (!cell.Visible && !cell.ControlInDesignMode) { continue; } // [: ] [: x ] if (Row.Cells[index].Bounds.Contains(locationToDrag)) { break; } // take into account the following scenarios // [: ] x [: ] // x [: ] [: ] if (Row.Cells[index].Bounds.X >= locationToDrag.X) { break; } } Control controlToPushAside = Row.ControlsInternal[index]; // Plop the new control in the midst of the row in question. if (index < Row.ControlsInternal.Count) { Row.ControlsInternal.Insert(index, toolStripToDrag); } else { Row.ControlsInternal.Add(toolStripToDrag); } // since layout is suspended the control may not be set to its preferred size yet int controlToDragWidth = (toolStripToDrag.AutoSize) ? toolStripToDrag.PreferredSize.Width : toolStripToDrag.Width; // // now make it look like it belongs in the row. // // PUSH the controls after it to the right int requiredSpace = controlToDragWidth; if (index == 0) { // make sure we account for the left side requiredSpace += locationToDrag.X; } int freedSpace = 0; if (index < Row.ControlsInternal.Count - 1) { ToolStripPanelCell nextCell = (ToolStripPanelCell)Row.Cells[index + 1]; Padding nextCellMargin = nextCell.Margin; // if we've already got the empty space // (available to us via the margin) use that. if (nextCellMargin.Left > requiredSpace) { nextCellMargin.Left -= requiredSpace; nextCell.Margin = nextCellMargin; freedSpace = requiredSpace; } else { // otherwise we've got to // push all controls after this point to the right // this dumps the extra stuff into the margin of index+1 freedSpace = MoveRight(index + 1, requiredSpace - freedSpace); // refetch the margin for "index+1" and remove the freed space // from it - we want to actually put this to use on the control // before this one - we're making room for the control at // position "index" if (freedSpace > 0) { nextCellMargin = nextCell.Margin; nextCellMargin.Left = Math.Max(0, nextCellMargin.Left - freedSpace); nextCell.Margin = nextCellMargin; } } } else { // we're adding to the end. ToolStripPanelCell nextCell = GetNextVisibleCell(Row.Cells.Count - 2, /*forward*/false); ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); // count the stuff at the end of the row as freed space if (nextCell != null && lastCell != null) { Padding lastCellMargin = lastCell.Margin; lastCellMargin.Left = Math.Max(0, locationToDrag.X - nextCell.Bounds.Right); lastCell.Margin = lastCellMargin; freedSpace = requiredSpace; } } // If we still need more space, then... // PUSH the controls before it to the left if (freedSpace < requiredSpace && index > 0) { freedSpace = MoveLeft(index - 1, requiredSpace - freedSpace); } if (index == 0) { // if the index is zero and there were controls in the row // we need to take care of pushing over the new cell. if (freedSpace - controlToDragWidth > 0) { ToolStripPanelCell newCell = Row.Cells[index] as ToolStripPanelCell; Padding newCellMargin = newCell.Margin; newCellMargin.Left = freedSpace - controlToDragWidth; newCell.Margin = newCellMargin; } } } else { // we're adding to the beginning. Row.ControlsInternal.Add(toolStripToDrag); #if DEBUG ISupportToolStripPanel ctg = toolStripToDrag as ISupportToolStripPanel; ToolStripPanelRow newPanelRow = ctg.ToolStripPanelRow; Debug.Assert(newPanelRow == Row, "we should now be in the new panel row."); #endif if (Row.Cells.Count > 0 || toolStripToDrag.IsInDesignMode) { // we're adding to the beginning. ToolStripPanelCell cell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); if (cell is null && toolStripToDrag.IsInDesignMode) { cell = (ToolStripPanelCell)Row.Cells[Row.Cells.Count - 1]; } if (cell != null) { Padding cellMargin = cell.Margin; cellMargin.Left = Math.Max(0, locationToDrag.X - Row.Margin.Left); cell.Margin = cellMargin; } } } } finally { Row.ResumeLayout(true); } } } protected internal override void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) { base.OnBoundsChanged(oldBounds, newBounds); } } private class VerticalRowManager : ToolStripPanelRowManager { public VerticalRowManager(ToolStripPanelRow owner) : base(owner) { owner.SuspendLayout(); FlowLayoutSettings.WrapContents = false; FlowLayoutSettings.FlowDirection = FlowDirection.TopDown; owner.ResumeLayout(false); } public override Rectangle DisplayRectangle { get { Rectangle displayRect = ((IArrangedElement)Row).DisplayRectangle; if (ToolStripPanel != null) { Rectangle raftingDisplayRectangle = ToolStripPanel.DisplayRectangle; if ((!ToolStripPanel.Visible || LayoutUtils.IsZeroWidthOrHeight(raftingDisplayRectangle)) && (ToolStripPanel.ParentInternal != null)) { // if were layed out before we're visible we have the wrong display rectangle, so we need to calculate it. displayRect.Height = ToolStripPanel.ParentInternal.DisplayRectangle.Height - (ToolStripPanel.Margin.Vertical + ToolStripPanel.Padding.Vertical) - Row.Margin.Vertical; } else { displayRect.Height = raftingDisplayRectangle.Height - Row.Margin.Vertical; } } return displayRect; } } public override Rectangle DragBounds { get { Rectangle dragBounds = Row.Bounds; int index = ToolStripPanel.RowsInternal.IndexOf(Row); if (index > 0) { Rectangle previousRowBounds = ToolStripPanel.RowsInternal[index - 1].Bounds; int x = previousRowBounds.X + previousRowBounds.Width - (previousRowBounds.Width >> 2); dragBounds.Width += dragBounds.X - x; dragBounds.X = x; } if (index < ToolStripPanel.RowsInternal.Count - 1) { Rectangle nextRowBounds = ToolStripPanel.RowsInternal[index + 1].Bounds; dragBounds.Width += (nextRowBounds.Width >> 2) + Row.Margin.Right + ToolStripPanel.RowsInternal[index + 1].Margin.Left; } dragBounds.Height += Row.Margin.Vertical + ToolStripPanel.Padding.Vertical + 5; dragBounds.Y -= Row.Margin.Top + ToolStripPanel.Padding.Top + 4; return dragBounds; } } /// <summary> /// returns true if there is enough space to "raft" the control /// ow returns false /// </summary> public override bool CanMove(ToolStrip toolStripToDrag) { if (base.CanMove(toolStripToDrag)) { Size totalSize = Size.Empty; for (int i = 0; i < Row.ControlsInternal.Count; i++) { totalSize += Row.GetMinimumSize(Row.ControlsInternal[i] as ToolStrip); } totalSize += Row.GetMinimumSize(toolStripToDrag); return totalSize.Height < DisplayRectangle.Height; } Debug.WriteLineIf(ToolStripPanelRow.s_toolStripPanelRowCreationDebug.TraceVerbose, "VerticalRM.CanMove returns false - not enough room"); return false; } protected internal override int FreeSpaceFromRow(int spaceToFree) { int requiredSpace = spaceToFree; // take a look at the last guy. if his right edge exceeds // the new bounds, then we should go ahead and push him into view. if (spaceToFree > 0) { // we should shrink the last guy and then move him. ToolStripPanelCell lastCellOnRow = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); if (lastCellOnRow is null) { return 0; } Padding cellMargin = lastCellOnRow.Margin; // only check margin.left as we are only concerned with getting right edge of // the toolstrip into view. (space after the fact doesnt count). if (cellMargin.Top >= spaceToFree) { cellMargin.Top -= spaceToFree; cellMargin.Bottom = 0; spaceToFree = 0; } else { spaceToFree -= lastCellOnRow.Margin.Top; cellMargin.Top = 0; cellMargin.Bottom = 0; } lastCellOnRow.Margin = cellMargin; // start moving the toolstrips before this guy. spaceToFree -= MoveUp(Row.Cells.Count - 1, spaceToFree); if (spaceToFree > 0) { spaceToFree -= lastCellOnRow.Shrink(spaceToFree); } } return requiredSpace - Math.Max(0, spaceToFree); } public override void MoveControl(ToolStrip movingControl, Point clientStartLocation, Point clientEndLocation) { if (Row.Locked) { return; } if (DragBounds.Contains(clientEndLocation)) { int index = Row.ControlsInternal.IndexOf(movingControl); int deltaY = clientEndLocation.Y - clientStartLocation.Y; if (deltaY < 0) { // moving to the left MoveUp(index, deltaY * -1); } else { MoveDown(index, deltaY); } } else { base.MoveControl(movingControl, clientStartLocation, clientEndLocation); } } private int MoveUp(int index, int spaceToFree) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveUp: " + spaceToFree.ToString(CultureInfo.InvariantCulture)); int freedSpace = 0; Row.SuspendLayout(); try { if (spaceToFree == 0 || index < 0) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveUp Early EXIT - 0 "); return 0; } // remove all margins starting from the index. for (int i = index; i >= 0; i--) { ToolStripPanelCell cell = (ToolStripPanelCell)Row.Cells[i]; if (!cell.Visible && !cell.ControlInDesignMode) { continue; } int requiredSpace = spaceToFree - freedSpace; Padding cellMargin = cell.Margin; if (cellMargin.Vertical >= requiredSpace) { freedSpace += requiredSpace; cellMargin.Top -= requiredSpace; cellMargin.Bottom = 0; cell.Margin = cellMargin; } else { freedSpace += cell.Margin.Vertical; cellMargin.Top = 0; cellMargin.Bottom = 0; cell.Margin = cellMargin; } if (freedSpace >= spaceToFree) { // add the space we freed to the next guy. if (index + 1 < Row.Cells.Count) { cell = GetNextVisibleCell(index + 1, /*forward*/true); if (cell != null) { cellMargin = cell.Margin; cellMargin.Top += spaceToFree; cell.Margin = cellMargin; } } Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveUp Recovered (Margin only): " + spaceToFree.ToString(CultureInfo.InvariantCulture)); return spaceToFree; } } } finally { Row.ResumeLayout(true); } Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveLeft Recovered Partial (Shrink): " + freedSpace.ToString(CultureInfo.InvariantCulture)); return freedSpace; } private int MoveDown(int index, int spaceToFree) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveDown: " + spaceToFree.ToString(CultureInfo.InvariantCulture)); int freedSpace = 0; Row.SuspendLayout(); try { if (spaceToFree == 0 || index < 0 || index >= Row.ControlsInternal.Count) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveDown Early EXIT - 0 "); return 0; } ToolStripPanelCell cell; Padding cellMargin; // remove all margins after this point in the index. for (int i = index + 1; i < Row.Cells.Count; i++) { cell = (ToolStripPanelCell)Row.Cells[i]; if (!cell.Visible && !cell.ControlInDesignMode) { continue; } int requiredSpace = spaceToFree - freedSpace; cellMargin = cell.Margin; if (cellMargin.Vertical >= requiredSpace) { freedSpace += requiredSpace; cellMargin.Top -= requiredSpace; cellMargin.Bottom = 0; cell.Margin = cellMargin; } else { freedSpace += cell.Margin.Vertical; cellMargin.Top = 0; cellMargin.Bottom = 0; cell.Margin = cellMargin; } break; } // add in the space at the end of the row. if (Row.Cells.Count > 0 && (spaceToFree > freedSpace)) { ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); if (lastCell != null) { freedSpace += DisplayRectangle.Bottom - lastCell.Bounds.Bottom; } else { freedSpace += DisplayRectangle.Height; } } // set the margin of the control that's moving. if (spaceToFree <= freedSpace) { // add the space we freed to the first guy. cell = (ToolStripPanelCell)Row.Cells[index]; cellMargin = cell.Margin; cellMargin.Top += spaceToFree; cell.Margin = cellMargin; Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveDown Recovered (Margin only): " + spaceToFree.ToString(CultureInfo.InvariantCulture)); return spaceToFree; } // Now start shrinking. for (int i = index + 1; i < Row.Cells.Count; i++) { cell = (ToolStripPanelCell)Row.Cells[i]; if (!cell.Visible && !cell.ControlInDesignMode) { continue; } int requiredSpace = spaceToFree - freedSpace; freedSpace += cell.Shrink(requiredSpace); if (spaceToFree >= freedSpace) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveDown Recovered (Shrink): " + spaceToFree.ToString(CultureInfo.InvariantCulture)); Row.ResumeLayout(true); return spaceToFree; } } if (Row.Cells.Count == 1) { cell = GetNextVisibleCell(index,/*forward*/true); if (cell != null) { cellMargin = cell.Margin; cellMargin.Top += freedSpace; cell.Margin = cellMargin; } } } finally { Row.ResumeLayout(true); } int recoveredSpace = spaceToFree - freedSpace; Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveDown Recovered Partial (Shrink): " + recoveredSpace.ToString(CultureInfo.InvariantCulture)); return recoveredSpace; } protected internal override void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) { base.OnBoundsChanged(oldBounds, newBounds); // if our bounds have changed - we should shove the toolbars up so they're in view. if (Row.Cells.Count > 0) { // take a look at the last guy. if his right edge exceeds // the new bounds, then we should go ahead and push him into view. ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward=*/false); int spaceToFree = (lastCell != null) ? lastCell.Bounds.Bottom - newBounds.Height : 0; if (spaceToFree > 0) { // we should shrink the last guy and then move him. ToolStripPanelCell lastCellOnRow = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); Padding cellMargin = lastCellOnRow.Margin; // only check margin.left as we are only concerned with getting bottom edge of // the toolstrip into view. (space after the fact doesnt count). if (cellMargin.Top >= spaceToFree) { cellMargin.Top -= spaceToFree; cellMargin.Bottom = 0; lastCellOnRow.Margin = cellMargin; spaceToFree = 0; } else { spaceToFree -= lastCellOnRow.Margin.Top; cellMargin.Top = 0; cellMargin.Bottom = 0; lastCellOnRow.Margin = cellMargin; } spaceToFree -= lastCellOnRow.Shrink(spaceToFree); // start moving the toolstrips before this guy. MoveUp(Row.Cells.Count - 1, spaceToFree); } } } protected internal override void OnControlRemoved(Control c, int index) { } protected internal override void OnControlAdded(Control control, int index) { } public override void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "Vertical JoinRow called "); int index; if (!Row.ControlsInternal.Contains(toolStripToDrag)) { Row.SuspendLayout(); try { if (Row.ControlsInternal.Count > 0) { // walk through the columns and determine which column you want to insert into. for (index = 0; index < Row.Cells.Count; index++) { ToolStripPanelCell cell = Row.Cells[index] as ToolStripPanelCell; if (!cell.Visible && !cell.ControlInDesignMode) { continue; } // [: ] [: x ] if (cell.Bounds.Contains(locationToDrag)) { break; } // take into account the following scenarios // [: ] x [: ] // x [: ] [: ] if (cell.Bounds.Y >= locationToDrag.Y) { break; } } Control controlToPushAside = Row.ControlsInternal[index]; // Plop the new control in the midst of the row in question. if (index < Row.ControlsInternal.Count) { Row.ControlsInternal.Insert(index, toolStripToDrag); } else { Row.ControlsInternal.Add(toolStripToDrag); } // since layout is suspended the control may not be set to its preferred size yet int controlToDragWidth = (toolStripToDrag.AutoSize) ? toolStripToDrag.PreferredSize.Height : toolStripToDrag.Height; // // now make it look like it belongs in the row. // // PUSH the controls after it to the right int requiredSpace = controlToDragWidth; if (index == 0) { // make sure we account for the left side requiredSpace += locationToDrag.Y; } int freedSpace = 0; if (index < Row.ControlsInternal.Count - 1) { ToolStripPanelCell nextCell = GetNextVisibleCell(index + 1, /*forward*/true); if (nextCell != null) { Padding nextCellMargin = nextCell.Margin; // if we've already got the empty space // (available to us via the margin) use that. if (nextCellMargin.Top > requiredSpace) { nextCellMargin.Top -= requiredSpace; nextCell.Margin = nextCellMargin; freedSpace = requiredSpace; } else { // otherwise we've got to // push all controls after this point to the right // this dumps the extra stuff into the margin of index+1 freedSpace = MoveDown(index + 1, requiredSpace - freedSpace); // refetch the margin for "index+1" and remove the freed space // from it - we want to actually put this to use on the control // before this one - we're making room for the control at // position "index" if (freedSpace > 0) { nextCellMargin = nextCell.Margin; nextCellMargin.Top -= freedSpace; nextCell.Margin = nextCellMargin; } } } } else { // we're adding to the end. ToolStripPanelCell nextCell = GetNextVisibleCell(Row.Cells.Count - 2, /*forward*/false); ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); // count the stuff at the end of the row as freed space if (nextCell != null && lastCell != null) { Padding lastCellMargin = lastCell.Margin; lastCellMargin.Top = Math.Max(0, locationToDrag.Y - nextCell.Bounds.Bottom); lastCell.Margin = lastCellMargin; freedSpace = requiredSpace; } } // If we still need more space, then... // PUSH the controls before it to the left if (freedSpace < requiredSpace && index > 0) { freedSpace = MoveUp(index - 1, requiredSpace - freedSpace); } if (index == 0) { // if the index is zero and there were controls in the row // we need to take care of pushing over the new cell. if (freedSpace - controlToDragWidth > 0) { ToolStripPanelCell newCell = Row.Cells[index] as ToolStripPanelCell; Padding newCellMargin = newCell.Margin; newCellMargin.Top = freedSpace - controlToDragWidth; newCell.Margin = newCellMargin; } } } else { // we're adding to the beginning. Row.ControlsInternal.Add(toolStripToDrag); #if DEBUG ISupportToolStripPanel ctg = toolStripToDrag as ISupportToolStripPanel; ToolStripPanelRow newPanelRow = ctg.ToolStripPanelRow; Debug.Assert(newPanelRow == Row, "we should now be in the new panel row."); #endif if (Row.Cells.Count > 0) { ToolStripPanelCell cell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); if (cell != null) { Padding cellMargin = cell.Margin; cellMargin.Top = Math.Max(0, locationToDrag.Y - Row.Margin.Top); cell.Margin = cellMargin; } } } } finally { Row.ResumeLayout(true); } } } public override void LeaveRow(ToolStrip toolStripToDrag) { // this code is here to properly add space to the next control when the // toolStripToDrag has been removed from the row. Row.SuspendLayout(); int index = Row.ControlsInternal.IndexOf(toolStripToDrag); if (index >= 0) { if (index < Row.ControlsInternal.Count - 1 /*not the last one in the row*/) { ToolStripPanelCell cell = (ToolStripPanelCell)Row.Cells[index]; if (cell.Visible) { int spaceOccupiedByCell = cell.Margin.Vertical + cell.Bounds.Height; // add the space occupied by the cell to the next one. ToolStripPanelCell nextCell = GetNextVisibleCell(index + 1, /*forward*/true); if (nextCell != null) { Padding nextCellMargin = nextCell.Margin; nextCellMargin.Top += spaceOccupiedByCell; nextCell.Margin = nextCellMargin; } } } // remove the control from the row. ((IList)Row.Cells).RemoveAt(index); } Row.ResumeLayout(true); } } /// <summary> /// ToolStripPanelRowControlCollection /// /// this class represents the collection of controls on a particular row. /// when you add and remove controls from this collection - you also add and remove /// controls to and from the ToolStripPanel.Control's collection (which happens /// to be externally readonly.) /// /// This class is used to represent the IArrangedElement.Children for the ToolStripPanelRow - /// which means that this collection represents the IArrangedElements to layout for /// a particular ToolStripPanelRow. /// /// We need to keep copies of the controls in both the ToolStripPanelRowControlCollection and /// the ToolStripPanel.Control collection as the ToolStripPanel.Control collection /// is responsible for parenting and unparenting the controls (ToolStripPanelRows do NOT derive from /// Control and thus are NOT hwnd backed). /// </summary> internal class ToolStripPanelRowControlCollection : ArrangedElementCollection, IList, IEnumerable { private readonly ToolStripPanelRow _owner; private ArrangedElementCollection _cellCollection; public ToolStripPanelRowControlCollection(ToolStripPanelRow owner) { _owner = owner; } public ToolStripPanelRowControlCollection(ToolStripPanelRow owner, Control[] value) { _owner = owner; AddRange(value); } public new virtual Control this[int index] { get { return GetControl(index); } } public ArrangedElementCollection Cells { get { if (_cellCollection is null) { _cellCollection = new ArrangedElementCollection(InnerList); } return _cellCollection; } } public ToolStripPanel ToolStripPanel { get { return _owner.ToolStripPanel; } } [EditorBrowsable(EditorBrowsableState.Never)] public int Add(Control value) { if (value is null) { throw new ArgumentNullException(nameof(value)); } if (!(value is ISupportToolStripPanel control)) { throw new NotSupportedException(string.Format(SR.TypedControlCollectionShouldBeOfType, typeof(ToolStrip).Name)); } int index = InnerList.Add(control.ToolStripPanelCell); OnAdd(control, index); return index; } [EditorBrowsable(EditorBrowsableState.Never)] public void AddRange(Control[] value) { if (value is null) { throw new ArgumentNullException(nameof(value)); } ToolStripPanel currentOwner = ToolStripPanel; if (currentOwner != null) { currentOwner.SuspendLayout(); } try { for (int i = 0; i < value.Length; i++) { Add(value[i]); } } finally { if (currentOwner != null) { currentOwner.ResumeLayout(); } } } public bool Contains(Control value) { for (int i = 0; i < Count; i++) { if (GetControl(i) == value) { return true; } } return false; } public virtual void Clear() { if (_owner != null) { ToolStripPanel.SuspendLayout(); } try { while (Count != 0) { RemoveAt(Count - 1); } } finally { if (_owner != null) { ToolStripPanel.ResumeLayout(); } } } public override IEnumerator GetEnumerator() { return new ToolStripPanelCellToControlEnumerator(InnerList); } private Control GetControl(int index) { Control control = null; ToolStripPanelCell cell = null; if (index < Count && index >= 0) { cell = (ToolStripPanelCell)(InnerList[index]); control = cell?.Control; } return control; } private int IndexOfControl(Control c) { for (int i = 0; i < Count; i++) { ToolStripPanelCell cell = (ToolStripPanelCell)(InnerList[i]); if (cell.Control == c) { return i; } } return -1; } void IList.Clear() { Clear(); } bool IList.IsFixedSize { get { return InnerList.IsFixedSize; } } bool IList.Contains(object value) { return InnerList.Contains(value); } bool IList.IsReadOnly { get { return InnerList.IsReadOnly; } } void IList.RemoveAt(int index) { RemoveAt(index); } void IList.Remove(object value) { Remove(value as Control); } int IList.Add(object value) { return Add(value as Control); } int IList.IndexOf(object value) { return IndexOf(value as Control); } void IList.Insert(int index, object value) { Insert(index, value as Control); } public int IndexOf(Control value) { for (int i = 0; i < Count; i++) { if (GetControl(i) == value) { return i; } } return -1; } [EditorBrowsable(EditorBrowsableState.Never)] public void Insert(int index, Control value) { if (value is null) { throw new ArgumentNullException(nameof(value)); } if (!(value is ISupportToolStripPanel control)) { throw new NotSupportedException(string.Format(SR.TypedControlCollectionShouldBeOfType, typeof(ToolStrip).Name)); } InnerList.Insert(index, control.ToolStripPanelCell); OnAdd(control, index); } /// <summary> /// Do proper cleanup of ownership, etc. /// </summary> private void OnAfterRemove(Control control, int index) { if (_owner != null) { // unfortunately we dont know the index of the control in the ToolStripPanel's // control collection, as all rows share this collection. // To unparent this control we need to use Remove instead of RemoveAt. using (LayoutTransaction t = new LayoutTransaction(ToolStripPanel, control, PropertyNames.Parent)) { _owner.ToolStripPanel.Controls.Remove(control); _owner.OnControlRemoved(control, index); } } } private void OnAdd(ISupportToolStripPanel controlToBeDragged, int index) { if (_owner != null) { LayoutTransaction layoutTransaction = null; if (ToolStripPanel != null && ToolStripPanel.ParentInternal != null) { layoutTransaction = new LayoutTransaction(ToolStripPanel, ToolStripPanel.ParentInternal, PropertyNames.Parent); } try { if (controlToBeDragged != null) { controlToBeDragged.ToolStripPanelRow = _owner; if (controlToBeDragged is Control control) { control.ParentInternal = _owner.ToolStripPanel; _owner.OnControlAdded(control, index); } } } finally { if (layoutTransaction != null) { layoutTransaction.Dispose(); } } } } [EditorBrowsable(EditorBrowsableState.Never)] public void Remove(Control value) { int index = IndexOfControl(value); RemoveAt(index); } [EditorBrowsable(EditorBrowsableState.Never)] public void RemoveAt(int index) { if (index >= 0 && index < Count) { Control control = GetControl(index); ToolStripPanelCell cell = InnerList[index] as ToolStripPanelCell; InnerList.RemoveAt(index); OnAfterRemove(control, index); } } [EditorBrowsable(EditorBrowsableState.Never)] public void CopyTo(Control[] array, int index) { if (array is null) { throw new ArgumentNullException(nameof(array)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (index >= array.Length || InnerList.Count > array.Length - index) { throw new ArgumentException(SR.ToolStripPanelRowControlCollectionIncorrectIndexLength); } for (int i = 0; i < InnerList.Count; i++) { array[index++] = GetControl(i); } } /// We want to pretend like we're only holding controls... so everywhere we've returned controls. /// but the problem is if you do a foreach, you'll get the cells not the controls. So we've got /// to sort of write a wrapper class around the ArrayList enumerator. private class ToolStripPanelCellToControlEnumerator : IEnumerator, ICloneable { private readonly IEnumerator _arrayListEnumerator; internal ToolStripPanelCellToControlEnumerator(ArrayList list) { _arrayListEnumerator = ((IEnumerable)list).GetEnumerator(); } public virtual object Current { get { ToolStripPanelCell cell = _arrayListEnumerator.Current as ToolStripPanelCell; Debug.Assert(cell != null, "Expected ToolStripPanel cells only!!!" + _arrayListEnumerator.Current.GetType().ToString()); return cell?.Control; } } public object Clone() { return MemberwiseClone(); } public virtual bool MoveNext() { return _arrayListEnumerator.MoveNext(); } public virtual void Reset() { _arrayListEnumerator.Reset(); } } } } }
39.330747
198
0.445386
[ "MIT" ]
Amy-Li03/winforms
src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs
96,323
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SSRS_Portal { public partial class ReportViewer { /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// ScriptManager1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.ScriptManager ScriptManager1; /// <summary> /// ReportViewer1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::Microsoft.Reporting.WebForms.ReportViewer ReportViewer1; } }
32.930233
84
0.509181
[ "Apache-2.0" ]
IYoni/cats
Web/ReportViewer.aspx.designer.cs
1,418
C#