content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SC.BL;
using SC.BL.Domain;
using Xamarin.Forms;
namespace SupportCenter
{
public partial class TicketCreate : ContentPage
{
private readonly TicketManager manager;
public TicketCreate()
{
InitializeComponent();
manager = new TicketManager();
}
private async void BtnCreate_OnClicked(object sender, EventArgs e)
{
try
{
var ticket = new Ticket()
{
AccountId = Convert.ToInt32(txtAccountId.Text),
Text = txtText.Text
};
ticket = await Task.Run(() => manager.CreateTicket(ticket));
if (ticket != null)
{
await DisplayAlert("Ticket created!", ticket.Text, "OK");
await Navigation.PopAsync(true);
}
else
await DisplayAlert("Oy Vey!", "Something went wrong...\nTry again in a minute please...", "OK");
}
catch (AggregateException)
{
await DisplayAlert("Error", "No internet connection", "Ok");
}
}
}
}
| 26.673077 | 116 | 0.52199 | [
"MIT"
] | anerach/SupportCenter-Xamarin | SupportCenter/SupportCenter/TicketCreate.xaml.cs | 1,389 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Nest
{
[ContractJsonConverter(typeof(PercentileRanksAggregationJsonConverter))]
public interface IPercentileRanksAggregation : IMetricAggregation
{
IEnumerable<double> Values { get; set; }
IPercentilesMethod Method { get; set; }
}
public class PercentileRanksAggregation : MetricAggregationBase, IPercentileRanksAggregation
{
public IEnumerable<double> Values { get; set; }
public IPercentilesMethod Method { get; set; }
internal PercentileRanksAggregation() { }
public PercentileRanksAggregation(string name, Field field) : base(name, field) { }
internal override void WrapInContainer(AggregationContainer c) => c.PercentileRanks = this;
}
public class PercentileRanksAggregationDescriptor<T>
: MetricAggregationDescriptorBase<PercentileRanksAggregationDescriptor<T>, IPercentileRanksAggregation, T>, IPercentileRanksAggregation
where T : class
{
IEnumerable<double> IPercentileRanksAggregation.Values { get; set; }
IPercentilesMethod IPercentileRanksAggregation.Method { get; set; }
public PercentileRanksAggregationDescriptor<T> Values(IEnumerable<double> values) =>
Assign(a => a.Values = values?.ToList());
public PercentileRanksAggregationDescriptor<T> Values(params double[] values) =>
Assign(a => a.Values = values?.ToList());
public PercentileRanksAggregationDescriptor<T> Method(Func<PercentilesMethodDescriptor, IPercentilesMethod> methodSelctor) =>
Assign(a => a.Method = methodSelctor?.Invoke(new PercentilesMethodDescriptor()));
}
}
| 35.977273 | 137 | 0.78585 | [
"Apache-2.0"
] | BedeGaming/elasticsearch-net | src/Nest/Aggregations/Metric/PercentileRanks/PercentileRanksAggregation.cs | 1,585 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// La plantilla de elemento Página en blanco está documentada en https://go.microsoft.com/fwlink/?LinkId=234238
namespace Claro.Views
{
/// <summary>
/// Una página vacía que se puede usar de forma independiente o a la que se puede navegar dentro de un objeto Frame.
/// </summary>
public sealed partial class Detalle : Page
{
public Detalle()
{
this.InitializeComponent();
}
}
}
| 27.806452 | 120 | 0.729698 | [
"MIT"
] | jealuna/DemoUWP | Claro/Views/Detalle.xaml.cs | 868 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics;
using StarkPlatform.CodeAnalysis.Stark.Symbols;
using StarkPlatform.CodeAnalysis.Stark.Syntax;
using Roslyn.Utilities;
namespace StarkPlatform.CodeAnalysis.Stark
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node)
{
return RewriteLocalDeclaration(node, node.Syntax, node.LocalSymbol, VisitExpression(node.InitializerOpt), node.HasErrors);
}
private BoundStatement RewriteLocalDeclaration(BoundLocalDeclaration originalOpt, SyntaxNode syntax, LocalSymbol localSymbol, BoundExpression rewrittenInitializer, bool hasErrors = false)
{
// A declaration of a local variable without an initializer has no associated IL.
// Simply remove the declaration from the bound tree. The local symbol will
// remain in the bound block, so codegen will make a stack frame location for it.
if (rewrittenInitializer == null)
{
return null;
}
// A declaration of a local constant also does nothing, even though there is
// an assignment. The value will be emitted directly where it is used. The
// local symbol remains in the bound block, but codegen will skip making a
// stack frame location for it. (We still need a symbol for it to stay
// around because we'll be generating debug info for it.)
if (localSymbol.IsConst)
{
if (!localSymbol.Type.IsReferenceType && localSymbol.ConstantValue == null)
{
// This can occur in error scenarios (e.g. bad imported metadata)
hasErrors = true;
}
else
{
return null;
}
}
// lowered local declaration node is associated with declaration (not whole statement)
// this is done to make sure that debugger stepping is same as before
var localDeclaration = syntax as LocalDeclarationStatementSyntax;
if (localDeclaration != null)
{
syntax = localDeclaration.Declaration;
}
BoundStatement rewrittenLocalDeclaration = new BoundExpressionStatement(
syntax,
new BoundAssignmentOperator(
syntax,
new BoundLocal(
syntax,
localSymbol,
null,
localSymbol.Type.TypeSymbol
),
rewrittenInitializer,
localSymbol.Type.TypeSymbol,
localSymbol.IsRef),
hasErrors);
return InstrumentLocalDeclarationIfNecessary(originalOpt, localSymbol, rewrittenLocalDeclaration);
}
private BoundStatement InstrumentLocalDeclarationIfNecessary(BoundLocalDeclaration originalOpt, LocalSymbol localSymbol, BoundStatement rewrittenLocalDeclaration)
{
// Add sequence points, if necessary.
if (this.Instrument && originalOpt?.WasCompilerGenerated == false && !localSymbol.IsConst &&
(originalOpt.Syntax.Kind() == SyntaxKind.VariableDeclaration ||
originalOpt.Syntax.Kind() == SyntaxKind.LocalDeclarationStatement))
{
rewrittenLocalDeclaration = _instrumenter.InstrumentLocalInitialization(originalOpt, rewrittenLocalDeclaration);
}
return rewrittenLocalDeclaration;
}
public override sealed BoundNode VisitOutVariablePendingInference(OutVariablePendingInference node)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| 44.722222 | 195 | 0.61913 | [
"Apache-2.0"
] | stark-lang/stark-roslyn | src/Compilers/Stark/Portable/Lowering/LocalRewriter/LocalRewriter_LocalDeclaration.cs | 4,027 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.Design;
using Curvature.Widgets;
namespace Curvature
{
class AgentPropertyAdapter : ICustomTypeDescriptor
{
private Dictionary<KnowledgeBase.Record, object> PropertyDict;
public AgentPropertyAdapter(Dictionary<KnowledgeBase.Record, object> propdict)
{
PropertyDict = propdict;
}
public string GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
public string GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return PropertyDict;
}
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
public object GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
public PropertyDescriptor GetDefaultProperty()
{
return null;
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor)this).GetProperties(new Attribute[0]);
}
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
var properties = new List<PropertyDescriptor>();
foreach (var kvp in PropertyDict)
{
if (kvp.Key.Params == KnowledgeBase.Record.Parameterization.Enumeration)
properties.Add(new DictionaryPropertyDescriptor<string>(PropertyDict, kvp.Key));
else
properties.Add(new DictionaryPropertyDescriptor<double>(PropertyDict, kvp.Key));
}
return new PropertyDescriptorCollection(properties.ToArray());
}
}
[TypeConverter(typeof(KBPropertyConverter))]
[Editor(typeof(KBPropertyEditor), typeof(UITypeEditor))]
class KBPropertyConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type t)
{
if (t == typeof(string))
return true;
return base.CanConvertFrom(context, t);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
if (double.TryParse(value as string, out double result))
return result;
return value;
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
return value.ToString();
return base.ConvertTo(context, culture, value, destinationType);
}
}
class KBPropertyWrapper<T>
{
Dictionary<KnowledgeBase.Record, object> PropertyDict;
internal KnowledgeBase.Record Record;
internal KBPropertyWrapper(Dictionary<KnowledgeBase.Record, object> dict, KnowledgeBase.Record key)
{
PropertyDict = dict;
Record = key;
}
internal void SetProperty(object value)
{
PropertyDict[Record] = value;
}
internal T GetProperty()
{
return (T)PropertyDict[Record];
}
public override string ToString()
{
return $"{PropertyDict[Record]}";
}
}
class KBPropertyEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.DropDown;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
if (provider == null)
return value;
var editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
if (editorService == null)
return value;
var wrapper = value as KBPropertyWrapper<double>;
if (wrapper == null)
{
var stringwrap = value as KBPropertyWrapper<string>;
if (stringwrap == null)
return value;
var listcontrol = new System.Windows.Forms.ListBox();
foreach (var str in stringwrap.Record.EnumerationValues)
listcontrol.Items.Add(str);
listcontrol.SelectedItem = stringwrap.GetProperty();
listcontrol.Click += (obj, args) =>
{
editorService.CloseDropDown();
};
editorService.DropDownControl(listcontrol);
if (listcontrol.SelectedIndex >= 0)
value = listcontrol.SelectedItem;
return value;
}
var control = new EditWidgetKnowledgeBaseParameter(wrapper.GetProperty(), wrapper.Record.MinimumValue, wrapper.Record.MaximumValue);
editorService.DropDownControl(control);
value = control.GetValue();
return value;
}
}
class DictionaryPropertyDescriptor<T> : PropertyDescriptor
{
KBPropertyWrapper<T> Wrap;
internal DictionaryPropertyDescriptor(Dictionary<KnowledgeBase.Record, object> dict, KnowledgeBase.Record key)
: base(key.ReadableName, null)
{
Wrap = new KBPropertyWrapper<T>(dict, key);
}
public override Type PropertyType
{
get { return typeof(KBPropertyConverter); }
}
public override void SetValue(object component, object value)
{
Wrap.SetProperty(value);
}
public override object GetValue(object component)
{
return Wrap;
}
public override bool IsReadOnly
{
get { return false; }
}
public override Type ComponentType
{
get { return null; }
}
public override bool CanResetValue(object component)
{
return false;
}
public override void ResetValue(object component)
{
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
public override string Category => "Knowledge Base";
}
}
| 28.468635 | 144 | 0.595593 | [
"BSD-3-Clause"
] | apoch/curvature | Scenarios/AgentPropertyAdapter.cs | 7,717 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DataProcessing")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DataProcessing")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("48e024a7-6d44-4886-968d-01309e97828b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.351351 | 84 | 0.749119 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | bsamuels453/Pikatwo | DataProcessing/Properties/AssemblyInfo.cs | 1,422 | C# |
using SX.WebCore.MvcControllers;
namespace simlex.Controllers
{
public sealed class StaticContentController : SxStaticContentController
{
}
} | 19.375 | 75 | 0.767742 | [
"MIT"
] | simlex-titul2005/simlex | simlex/Controllers/StaticContentController.cs | 157 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WFA_EntityFramework_Sorgular.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 37.033333 | 152 | 0.573357 | [
"MIT"
] | BercKoskun/CSharpBilge | Data Access/27.02/WFA_EntityFramework_Sorgular/WFA_EntityFramework_Sorgular/Properties/Settings.Designer.cs | 1,113 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ListaDoblementeEnlazada
{
class Program
{
//Creación de la clase jugador
class Player
{
int number;
public int Number
{
get
{
return number;
}
}
public Player(int i) //Constructor
{
number = i;
}
}
//Creación de la clase Nodo
class Node
{
public Player data;
public Node next; //Apuntador al nodo siguiente
public Node prev; //Apuntador al nodo anterior
public Node(Player p) //Constructor
{
data = p;
}
}
//Creación de la clase Lista
class List
{
Node header; //Nodo cabeza
Node footer; //Nodo cola
//Agrega un nodo al principio
public void AddFirst(Player p)
{
if(header==null)
{
header = footer = new Node(p);
}
else
{
Node temp = header;
header = new Node(p);
temp.prev = header;
header.next = temp;
}
}
//Agrega un nodo al final de la lista
public void AddLast(Player p)
{
if(header==null)
{
AddFirst(p);
}
else
{
Node temp = footer;
footer = new Node(p);
temp.next = footer;
footer.prev = temp;
}
}
//Agrega nodo al inicio o en medio
public void AddBeforePlayer(Player p)
{
if(header==null)
{
AddFirst(p);
}
else
{
Node temp = header;
while(temp.next!=null&&p.Number>temp.data.Number)
{
temp = temp.next;
}
if (temp.prev == null && p.Number <= temp.data.Number)
{
AddFirst(p);
}
else if (temp.next == null && p.Number >= temp.data.Number)
{
AddLast(p);
}
else
{
Node insert = new Node(p);
insert.prev = temp.prev;
insert.next = temp;
temp.prev = insert;
temp.prev.next = insert;
}
}
}
//Impresión normal (Principio al final)
public void Print()
{
if(header!=null)
{
Node temp = header;
while(temp!=null)
{
Console.WriteLine("Número de Jugador: {0}", temp.data.Number);
temp = temp.next;
}
}
}
//Impresión de reversa (Final al principio)
public void PrintRev()
{
if(footer!=null)
{
Node temp = footer;
while(temp!=null)
{
Console.WriteLine("Número de Jugador: {0}", temp.data.Number);
temp = temp.prev;
}
}
}
}
static void Main(string[] args)
{
//Creación de objetos
Player p1 = new Player(2);
Player p2 = new Player(3);
Player p3 = new Player(5);
Player p4 = new Player(10);
Player p5 = new Player(15);
Player p6 = new Player(4);
Player p7 = new Player(6);
//Creación de la lista
List team1 = new List();
//Agregar nodos al principio
team1.AddFirst(p3);
team1.AddFirst(p2);
team1.AddFirst(p1);
//Agregar nodos al final
team1.AddLast(p4);
team1.AddLast(p5);
team1.AddBeforePlayer(p6);
team1.AddBeforePlayer(new Player(0));
team1.AddBeforePlayer(new Player(1));
team1.AddBeforePlayer(new Player(2));
team1.AddBeforePlayer(new Player(3));
team1.AddBeforePlayer(new Player(4));
team1.AddBeforePlayer(new Player(5));
team1.AddBeforePlayer(new Player(6));
team1.AddBeforePlayer(new Player(14));
team1.AddBeforePlayer(new Player(15));
team1.AddBeforePlayer(new Player(16));
//Impresión normal
Console.WriteLine("Lista:");
team1.Print();
//Impresión de reversa
Console.WriteLine("Lista de Reversa:");
team1.PrintRev();
Console.ReadLine();
}
}
} | 30.11236 | 86 | 0.396082 | [
"MIT"
] | Nyoseka/EstructuraDeDatos2.0 | Unidad 3/ListaDoblementeEnlazada.cs | 5,371 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class worldDebugColoring_DistanceAbstractBase : worldEditorDebugColoringSettings
{
[Ordinal(0)] [RED("maxColor")] public CColor MaxColor { get; set; }
[Ordinal(1)] [RED("maxDistance")] public CFloat MaxDistance { get; set; }
[Ordinal(2)] [RED("minColor")] public CColor MinColor { get; set; }
[Ordinal(3)] [RED("minDistance")] public CFloat MinDistance { get; set; }
public worldDebugColoring_DistanceAbstractBase(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 35.631579 | 126 | 0.713442 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/worldDebugColoring_DistanceAbstractBase.cs | 659 | C# |
// Copyright 2020 Energinet DataHub A/S
//
// Licensed under the Apache License, Version 2.0 (the "License2");
// 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 Energinet.DataHub.MeteringPoints.Application.EDI;
using Energinet.DataHub.MeteringPoints.Domain.MasterDataHandling.Errors;
namespace Energinet.DataHub.MeteringPoints.Infrastructure.EDI.Errors.Converters.Create
{
public class InvalidSettlementMethodValueErrorConverter : ErrorConverter<InvalidSettlementMethodValue>
{
protected override ErrorMessage Convert(InvalidSettlementMethodValue validationError)
{
if (validationError == null) throw new ArgumentNullException(nameof(validationError));
return new("D15", $"Settlement method {validationError.ProvidedValue} has wrong value (outside domain)");
}
}
}
| 41.516129 | 117 | 0.759907 | [
"Apache-2.0"
] | Energinet-DataHub/geh-metering-point | source/Energinet.DataHub.MeteringPoints.Infrastructure/EDI/Errors/Converters/Create/InvalidSettlementMethodErrorConverter.cs | 1,289 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace StockMonitorDemo.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.5.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.666667 | 151 | 0.583567 | [
"BSD-3-Clause-Clear"
] | git-thinh/clinq | sourceCode/StockMonitorDemo/StockMonitorDemo/Properties/Settings.Designer.cs | 1,073 | C# |
using System;
using System.Linq;
using Xunit;
namespace Validatum.Tests
{
public class ValidatorBuilderBooleanExtensionsTests
{
[Fact]
public void True_ThrowsException_WhenBuilderIsNull()
{
Assert.Throws<ArgumentNullException>("builder", () =>
{
ValidatorBuilderExtensions.True(null);
});
}
[Fact]
public void True_ShouldAddBrokenRule_WhenValueIsFalse()
{
// arrange
var validator = new ValidatorBuilder<bool>()
.True()
.Build();
// act
var result = validator.Validate(false);
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.NotNull(brokenRule);
Assert.Equal("True", brokenRule.Rule);
Assert.Equal("Boolean", brokenRule.Key);
Assert.Equal("Value must be true.", brokenRule.Message);
}
[Fact]
public void True_ShouldNotAddBrokenRule_WhenValueIsTrue()
{
// arrange
var validator = new ValidatorBuilder<bool>()
.True()
.Build();
// act
var result = validator.Validate(true);
// assert
Assert.Empty(result.BrokenRules);
}
[Fact]
public void True_ShouldPassKeyToBrokenRule_WhenKeyProvided()
{
// arrange
var validator = new ValidatorBuilder<bool>()
.True("test")
.Build();
// act
var result = validator.Validate(false);
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.Equal("test", brokenRule.Key);
}
[Fact]
public void True_ShouldPassMessageToBrokenRule_WhenMessageProvided()
{
// arrange
var validator = new ValidatorBuilder<bool>()
.True(message: "test")
.Build();
// act
var result = validator.Validate(false);
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.Equal("test", brokenRule.Message);
}
[Fact]
public void TrueFor_ThrowsException_WhenBuilderIsNull()
{
Assert.Throws<ArgumentNullException>("builder", () =>
{
ValidatorBuilderExtensions.True<string>(null, null);
});
}
[Fact]
public void TrueFor_ThrowsException_WhenSelectorIsNull()
{
Assert.Throws<ArgumentNullException>("selector", () =>
{
ValidatorBuilderExtensions.True<string>(new ValidatorBuilder<string>(), null);
});
}
[Fact]
public void TrueFor_ShouldAddBrokenRule_WhenValueIsFalse()
{
// arrange
var validator = new ValidatorBuilder<Employee>()
.True(e => e.Active)
.Build();
// act
var result = validator.Validate(new Employee { Active = false });
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.NotNull(brokenRule);
Assert.Equal("True", brokenRule.Rule);
Assert.Equal("Active", brokenRule.Key);
Assert.Equal("Value must be true.", brokenRule.Message);
}
[Fact]
public void TrueFor_ShouldNotAddBrokenRule_WhenValueIsTrue()
{
// arrange
var validator = new ValidatorBuilder<Employee>()
.True(e => e.Active)
.Build();
// act
var result = validator.Validate(new Employee { Active = true });
// assert
Assert.Empty(result.BrokenRules);
}
[Fact]
public void TrueFor_ShouldPassKeyToBrokenRule_WhenKeyProvided()
{
// arrange
var validator = new ValidatorBuilder<Employee>()
.True(e => e.Active, "test")
.Build();
// act
var result = validator.Validate(new Employee());
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.Equal("test", brokenRule.Key);
}
[Fact]
public void TrueFor_ShouldPassMessageToBrokenRule_WhenMessageProvided()
{
// arrange
var validator = new ValidatorBuilder<Employee>()
.True(e => e.Active, message: "test")
.Build();
// act
var result = validator.Validate(new Employee());
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.Equal("test", brokenRule.Message);
}
[Fact]
public void False_ThrowsException_WhenBuilderIsNull()
{
Assert.Throws<ArgumentNullException>("builder", () =>
{
ValidatorBuilderExtensions.False(null);
});
}
[Fact]
public void False_ShouldAddBrokenRule_WhenValueIsTrue()
{
// arrange
var validator = new ValidatorBuilder<bool>()
.False()
.Build();
// act
var result = validator.Validate(true);
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.NotNull(brokenRule);
Assert.Equal("False", brokenRule.Rule);
Assert.Equal("Boolean", brokenRule.Key);
Assert.Equal("Value must be false.", brokenRule.Message);
}
[Fact]
public void False_ShouldNotAddBrokenRule_WhenValueIsFalse()
{
// arrange
var validator = new ValidatorBuilder<bool>()
.False()
.Build();
// act
var result = validator.Validate(false);
// assert
Assert.Empty(result.BrokenRules);
}
[Fact]
public void False_ShouldPassKeyToBrokenRule_WhenKeyProvided()
{
// arrange
var validator = new ValidatorBuilder<bool>()
.False("test")
.Build();
// act
var result = validator.Validate(true);
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.Equal("test", brokenRule.Key);
}
[Fact]
public void False_ShouldPassMessageToBrokenRule_WhenMessageProvided()
{
// arrange
var validator = new ValidatorBuilder<bool>()
.False(message: "test")
.Build();
// act
var result = validator.Validate(true);
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.Equal("test", brokenRule.Message);
}
[Fact]
public void FalseFor_ThrowsException_WhenBuilderIsNull()
{
Assert.Throws<ArgumentNullException>("builder", () =>
{
ValidatorBuilderExtensions.False<string>(null, null);
});
}
[Fact]
public void FalseFor_ThrowsException_WhenSelectorIsNull()
{
Assert.Throws<ArgumentNullException>("selector", () =>
{
ValidatorBuilderExtensions.False<string>(new ValidatorBuilder<string>(), null);
});
}
[Fact]
public void FalseFor_ShouldAddBrokenRule_WhenValueIsTrue()
{
// arrange
var validator = new ValidatorBuilder<Employee>()
.False(e => e.Active)
.Build();
// act
var result = validator.Validate(new Employee { Active = true });
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.NotNull(brokenRule);
Assert.Equal("False", brokenRule.Rule);
Assert.Equal("Active", brokenRule.Key);
Assert.Equal("Value must be false.", brokenRule.Message);
}
[Fact]
public void FalseFor_ShouldNotAddBrokenRule_WhenValueIsFalse()
{
// arrange
var validator = new ValidatorBuilder<Employee>()
.False(e => e.Active)
.Build();
// act
var result = validator.Validate(new Employee { Active = false });
// assert
Assert.Empty(result.BrokenRules);
}
[Fact]
public void FalseFor_ShouldPassKeyToBrokenRule_WhenKeyProvided()
{
// arrange
var validator = new ValidatorBuilder<Employee>()
.False(e => e.Active, "test")
.Build();
// act
var result = validator.Validate(new Employee { Active = true });
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.Equal("test", brokenRule.Key);
}
[Fact]
public void FalseFor_ShouldPassMessageToBrokenRule_WhenMessageProvided()
{
// arrange
var validator = new ValidatorBuilder<Employee>()
.False(e => e.Active, message: "test")
.Build();
// act
var result = validator.Validate(new Employee { Active = true });
var brokenRule = result.BrokenRules.FirstOrDefault();
// assert
Assert.Equal("test", brokenRule.Message);
}
}
}
| 29.640244 | 95 | 0.521703 | [
"MIT"
] | bsheldrick/validatum | src/Validatum/test/ValidatorBuilderExtensions.Boolean.Tests.cs | 9,722 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 OpenSimulator 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;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using OpenSim.ScriptEngine.Components.DotNetEngine.Compilers.LSL;
using OpenSim.ScriptEngine.Shared;
namespace OpenSim.ScriptEngine.Components.DotNetEngine.Compilers
{
public class Compiler_LSL : IScriptCompiler
{
private readonly Compiler_CS m_Compiler_CS = new Compiler_CS();
private readonly LSL2CS m_LSL2CS = new LSL2CS();
public string Compile(ScriptMetaData scriptMetaData, ref string script)
{
// Convert script to CS
string scriptCS = m_LSL2CS.Convert(ref script);
// Use CS compiler to compile it
return m_Compiler_CS.Compile(scriptMetaData, ref scriptCS);
}
public string PreProcessScript(ref string script)
{
// This is handled by our converter
return script;
}
}
}
| 43.810345 | 80 | 0.72806 | [
"BSD-3-Clause"
] | Ideia-Boa/diva-distribution | OpenSim/ScriptEngine/Components/DotNetEngine/Compilers/Compiler_LSL.cs | 2,543 | C# |
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Insma.Mxa.Framework.Avatar")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Insma.Mxa.Framework.Avatar")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 35.709677 | 84 | 0.745257 | [
"MIT"
] | baszalmstra/MXA | MXA-Framework/src/Framework.Avatar/Properties/AssemblyInfo.cs | 1,110 | C# |
namespace Shop.Module.EmailSenderSmtp
{
public class EmailSmtpOptions
{
public string SmtpUserName { get; set; }
public string SmtpPassword { get; set; }
public string SmtpHost { get; set; } = "smtp.mxhichina.com";
public int SmtpPort { get; set; } = 587;
}
}
| 22 | 68 | 0.613636 | [
"MIT"
] | LGinC/module-shop | src/server/src/Modules/Shop.Module.EmailSenderSmtp/EmailSmtpOptions.cs | 310 | 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 outposts-2019-12-03.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.Outposts.Model
{
/// <summary>
/// A summary of line items in your order.
/// </summary>
public partial class OrderSummary
{
private Dictionary<string, int> _lineItemCountsByStatus = new Dictionary<string, int>();
private DateTime? _orderFulfilledDate;
private string _orderId;
private DateTime? _orderSubmissionDate;
private OrderType _orderType;
private string _outpostId;
private OrderStatus _status;
/// <summary>
/// Gets and sets the property LineItemCountsByStatus.
/// <para>
/// The status of all line items in the order.
/// </para>
/// </summary>
public Dictionary<string, int> LineItemCountsByStatus
{
get { return this._lineItemCountsByStatus; }
set { this._lineItemCountsByStatus = value; }
}
// Check to see if LineItemCountsByStatus property is set
internal bool IsSetLineItemCountsByStatus()
{
return this._lineItemCountsByStatus != null && this._lineItemCountsByStatus.Count > 0;
}
/// <summary>
/// Gets and sets the property OrderFulfilledDate.
/// <para>
/// Fulfilment date for the order.
/// </para>
/// </summary>
public DateTime OrderFulfilledDate
{
get { return this._orderFulfilledDate.GetValueOrDefault(); }
set { this._orderFulfilledDate = value; }
}
// Check to see if OrderFulfilledDate property is set
internal bool IsSetOrderFulfilledDate()
{
return this._orderFulfilledDate.HasValue;
}
/// <summary>
/// Gets and sets the property OrderId.
/// <para>
/// The ID of the order.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=20)]
public string OrderId
{
get { return this._orderId; }
set { this._orderId = value; }
}
// Check to see if OrderId property is set
internal bool IsSetOrderId()
{
return this._orderId != null;
}
/// <summary>
/// Gets and sets the property OrderSubmissionDate.
/// <para>
/// Submission date for the order.
/// </para>
/// </summary>
public DateTime OrderSubmissionDate
{
get { return this._orderSubmissionDate.GetValueOrDefault(); }
set { this._orderSubmissionDate = value; }
}
// Check to see if OrderSubmissionDate property is set
internal bool IsSetOrderSubmissionDate()
{
return this._orderSubmissionDate.HasValue;
}
/// <summary>
/// Gets and sets the property OrderType.
/// <para>
/// The type of order.
/// </para>
/// </summary>
public OrderType OrderType
{
get { return this._orderType; }
set { this._orderType = value; }
}
// Check to see if OrderType property is set
internal bool IsSetOrderType()
{
return this._orderType != null;
}
/// <summary>
/// Gets and sets the property OutpostId.
/// <para>
/// The ID of the Outpost.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=20)]
public string OutpostId
{
get { return this._outpostId; }
set { this._outpostId = value; }
}
// Check to see if OutpostId property is set
internal bool IsSetOutpostId()
{
return this._outpostId != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The status of the order.
/// </para>
/// <ul> <li>
/// <para>
/// <code>PREPARING</code> - Order is received and is being prepared.
/// </para>
/// </li> <li>
/// <para>
/// <code>IN_PROGRESS</code> - Order is either being built, shipped, or installed. For
/// more information, see the <code>LineItem</code> status.
/// </para>
/// </li> <li>
/// <para>
/// <code>COMPLETED</code> - Order is complete.
/// </para>
/// </li> <li>
/// <para>
/// <code>CANCELLED</code> - Order is cancelled.
/// </para>
/// </li> <li>
/// <para>
/// <code>ERROR</code> - Customer should contact support.
/// </para>
/// </li> </ul> <note>
/// <para>
/// The following statuses are deprecated: <code>RECEIVED</code>, <code>PENDING</code>,
/// <code>PROCESSING</code>, <code>INSTALLING</code>, and <code>FULFILLED</code>.
/// </para>
/// </note>
/// </summary>
public OrderStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
}
} | 30.585 | 106 | 0.548308 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/Outposts/Generated/Model/OrderSummary.cs | 6,117 | C# |
using System;
using Advertise.ServiceLayer.Contracts.Users;
namespace Advertise.ServiceLayer.EFServices.Users
{
public class UserClaimService : IUserClaimService
{
public void Create()
{
throw new NotImplementedException();
}
public void Edit()
{
throw new NotImplementedException();
}
public void Delete()
{
throw new NotImplementedException();
}
public void Get()
{
throw new NotImplementedException();
}
}
} | 20.392857 | 53 | 0.565674 | [
"Apache-2.0"
] | imangit/Advertise | Advertise/Advertise.ServiceLayer/EFServices/Users/UserClaimService.cs | 573 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OpenCC_GUI.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.4.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("cht")]
public string Language {
get {
return ((string)(this["Language"]));
}
set {
this["Language"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("800, 600")]
public global::System.Drawing.Size Size {
get {
return ((global::System.Drawing.Size)(this["Size"]));
}
set {
this["Size"] = value;
}
}
}
}
| 38.117647 | 151 | 0.562757 | [
"MIT"
] | casperhkce/opencc-gui-csharp | OpenCC GUI/Properties/Settings.Designer.cs | 1,946 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.EntityFrameworkCore.Migrations
{
/// <summary>
/// <para>
/// An interface for the repository used to access the '__EFMigrationsHistory' table that tracks metadata
/// about EF Core Migrations such as which migrations have been applied.
/// </para>
/// <para>
/// Database providers typically implement this service by inheriting from <see cref="HistoryRepository" />.
/// </para>
/// <para>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" />. This means that each
/// <see cref="DbContext" /> instance will use its own instance of this service.
/// The implementation may depend on other services registered with any lifetime.
/// The implementation does not need to be thread-safe.
/// </para>
/// </summary>
public interface IHistoryRepository
{
/// <summary>
/// Checks whether or not the history table exists.
/// </summary>
/// <returns> <see langword="true" /> if the table already exists, <see langword="false" /> otherwise. </returns>
bool Exists();
/// <summary>
/// Checks whether or not the history table exists.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken" /> to observe while waiting for the task to complete.</param>
/// <returns>
/// A task that represents the asynchronous operation. The task result contains
/// <see langword="true" /> if the table already exists, <see langword="false" /> otherwise.
/// </returns>
/// <exception cref="OperationCanceledException"> If the <see cref="CancellationToken"/> is canceled. </exception>
Task<bool> ExistsAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Queries the history table for all migrations that have been applied.
/// </summary>
/// <returns> The list of applied migrations, as <see cref="HistoryRow" /> entities. </returns>
IReadOnlyList<HistoryRow> GetAppliedMigrations();
/// <summary>
/// Queries the history table for all migrations that have been applied.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken" /> to observe while waiting for the task to complete.</param>
/// <returns>
/// A task that represents the asynchronous operation. The task result contains
/// the list of applied migrations, as <see cref="HistoryRow" /> entities.
/// </returns>
/// <exception cref="OperationCanceledException"> If the <see cref="CancellationToken"/> is canceled. </exception>
Task<IReadOnlyList<HistoryRow>> GetAppliedMigrationsAsync(
CancellationToken cancellationToken = default);
/// <summary>
/// Generates a SQL script that will create the history table.
/// </summary>
/// <returns> The SQL script. </returns>
string GetCreateScript();
/// <summary>
/// Generates a SQL script that will create the history table if and only if it does not already exist.
/// </summary>
/// <returns> The SQL script. </returns>
string GetCreateIfNotExistsScript();
/// <summary>
/// Generates a SQL script to insert a row into the history table.
/// </summary>
/// <param name="row"> The row to insert, represented as a <see cref="HistoryRow" /> entity. </param>
/// <returns> The generated SQL. </returns>
string GetInsertScript(HistoryRow row);
/// <summary>
/// Generates a SQL script to delete a row from the history table.
/// </summary>
/// <param name="migrationId"> The migration identifier of the row to delete. </param>
/// <returns> The generated SQL. </returns>
string GetDeleteScript(string migrationId);
/// <summary>
/// Generates a SQL Script that will <c>BEGIN</c> a block
/// of SQL if and only if the migration with the given identifier does not already exist in the history table.
/// </summary>
/// <param name="migrationId"> The migration identifier. </param>
/// <returns> The generated SQL. </returns>
string GetBeginIfNotExistsScript(string migrationId);
/// <summary>
/// Generates a SQL Script that will <c>BEGIN</c> a block
/// of SQL if and only if the migration with the given identifier already exists in the history table.
/// </summary>
/// <param name="migrationId"> The migration identifier. </param>
/// <returns> The generated SQL. </returns>
string GetBeginIfExistsScript(string migrationId);
/// <summary>
/// Generates a SQL script to <c>END</c> the SQL block.
/// </summary>
/// <returns> The generated SQL. </returns>
string GetEndIfScript();
}
}
| 47.80531 | 137 | 0.618475 | [
"Apache-2.0"
] | 0x0309/efcore | src/EFCore.Relational/Migrations/IHistoryRepository.cs | 5,402 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using Silk.NET.Core;
using Silk.NET.Core.Native;
using Silk.NET.Core.Attributes;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Loader;
#pragma warning disable 1591
namespace Silk.NET.DXVA
{
public unsafe readonly struct PfnPdxva2SWVideoprocessendframe : IDisposable
{
private readonly void* _handle;
public delegate* unmanaged[Cdecl]<void*, void**, int> Handle => (delegate* unmanaged[Cdecl]<void*, void**, int>) _handle;
public PfnPdxva2SWVideoprocessendframe
(
delegate* unmanaged[Cdecl]<void*, void**, int> ptr
) => _handle = ptr;
public PfnPdxva2SWVideoprocessendframe
(
Pdxva2SWVideoprocessendframe proc
) => _handle = (void*) SilkMarshal.DelegateToPtr(proc);
public static PfnPdxva2SWVideoprocessendframe From(Pdxva2SWVideoprocessendframe proc) => new PfnPdxva2SWVideoprocessendframe(proc);
public void Dispose() => SilkMarshal.Free((nint) _handle);
public static implicit operator nint(PfnPdxva2SWVideoprocessendframe pfn) => (nint) pfn.Handle;
public static explicit operator PfnPdxva2SWVideoprocessendframe(nint pfn)
=> new PfnPdxva2SWVideoprocessendframe((delegate* unmanaged[Cdecl]<void*, void**, int>) pfn);
public static implicit operator PfnPdxva2SWVideoprocessendframe(Pdxva2SWVideoprocessendframe proc)
=> new PfnPdxva2SWVideoprocessendframe(proc);
public static explicit operator Pdxva2SWVideoprocessendframe(PfnPdxva2SWVideoprocessendframe pfn)
=> SilkMarshal.PtrToDelegate<Pdxva2SWVideoprocessendframe>(pfn);
public static implicit operator delegate* unmanaged[Cdecl]<void*, void**, int>(PfnPdxva2SWVideoprocessendframe pfn) => pfn.Handle;
public static implicit operator PfnPdxva2SWVideoprocessendframe(delegate* unmanaged[Cdecl]<void*, void**, int> ptr) => new PfnPdxva2SWVideoprocessendframe(ptr);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int Pdxva2SWVideoprocessendframe(void* arg0, void** arg1);
}
| 43.148148 | 168 | 0.738197 | [
"MIT"
] | Ar37-rs/Silk.NET | src/Microsoft/Silk.NET.DXVA/Structs/PfnPdxva2SWVideoprocessendframe.gen.cs | 2,330 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
namespace Nemesis.Wpf.Converters
{
[ValueConversion(typeof(object), typeof(bool))]
public abstract class ToBoolConverter : BaseConverter
{
[ConstructorArgument("invert")]
public bool Invert { get; set; }
protected ToBoolConverter() { }
protected ToBoolConverter(bool invert) => Invert = invert;
public sealed override object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
CanConvert(value) ? (Invert ? !ToBool(value) : ToBool(value)) : Binding.DoNothing;
protected virtual bool CanConvert(object @object) => true;
protected abstract bool ToBool(object @object);
}
[ValueConversion(typeof(Nullable<>), typeof(bool))]
public class NullableToBooleanConverter : ToBoolConverter
{
//protected override bool CanConvert(object @object) => @object == null || @object.GetType() is var type && (!type.IsValueType || Nullable.GetUnderlyingType(type) != null);
protected override bool ToBool(object @object) => @object != null;
}
[ValueConversion(typeof(bool), typeof(object))]
public abstract class FromBoolConverter<TTo> : BaseConverter
{
[ConstructorArgument("trueValue")]
public TTo True { get; set; }
[ConstructorArgument("falseValue")]
public TTo False { get; set; }
[ConstructorArgument("invert")]
public bool Invert { get; set; }
protected FromBoolConverter(TTo trueValue, TTo falseValue) : this(trueValue, falseValue, false) { }
protected FromBoolConverter(TTo trueValue, TTo falseValue, bool invert)
{
True = trueValue;
False = falseValue;
Invert = invert;
}
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
value is bool b ?
(Invert ? (b ? False : True) : (b ? True : False)) :
False;
public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
value is TTo variable && EqualityComparer<TTo>.Default.Equals(variable, Invert ? False : True);
}
/// <example><![CDATA[
/// <Application.Resources>
/// <app:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" True="Collapsed" False="Visible" />
/// </Application.Resources>
/// ]]></example>
[ValueConversion(typeof(bool), typeof(Visibility))]
[ValueConversion(typeof(bool?), typeof(Visibility))]
public sealed class BooleanToVisibilityConverter : FromBoolConverter<Visibility>
{
public BooleanToVisibilityConverter() : base(Visibility.Visible, Visibility.Collapsed) { }
public BooleanToVisibilityConverter(bool invert) : base(Visibility.Visible, Visibility.Collapsed, invert) { }
}
[ValueConversion(typeof(bool), typeof(string))]
[ValueConversion(typeof(bool?), typeof(string))]
public sealed class BooleanToStringConverter : FromBoolConverter<string>
{
public BooleanToStringConverter() : base("true", "false") { }
public BooleanToStringConverter(bool invert) : base("true", "false", invert) { }
}
}
| 38.488636 | 180 | 0.668143 | [
"MIT"
] | nemesissoft/Nemesis.Wpf | Nemesis.Wpf/Converters/BoolConverters.cs | 3,389 | C# |
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace NetCrypto
{
//私钥 AES固定格式为128/192/256 bits.即:16/24/32bytes
//初始化向量参数,AES 为16bytes.
public class AesEncryptProvider : IDataEncrypt
{
private const int BufferSize = 1024;
/// <summary>
/// AES加密
/// </summary>
/// <param name="msg"></param>
/// <param name="key"></param>
/// <returns></returns>
public string Encrypt(string msg, string key = null)
{
if (string.IsNullOrEmpty(msg)) return null;
byte[] toEncryptArray = Encoding.UTF8.GetBytes(msg);
RijndaelManaged rm = new RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = rm.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray);
}
/// <summary>
/// AES加密
/// </summary>
/// <param name="msg"></param>
/// <param name="key"></param>
/// <returns></returns>
public byte[] Encrypt(byte[] msg, string key = null)
{
if(msg==null)
{
return null;
}
byte[] cryptograph = null; // 加密后的密文
RijndaelManaged rm = new RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = rm.CreateEncryptor();
// 开辟一块内存流 ,存储密文数据
using (MemoryStream memData = new MemoryStream(msg))
{
using (MemoryStream Memory = new MemoryStream())
{
// 把内存流对象包装成加密流对象
using (CryptoStream Encryptor = new CryptoStream(Memory, cTransform, CryptoStreamMode.Write))
{
int bytesRead = 0;
byte[] buffer = new byte[BufferSize];
do
{
bytesRead = memData.Read(buffer, 0, BufferSize);
Encryptor.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
Encryptor.FlushFinalBlock();
//// 明文数据写入加密流
//Encryptor.Write(msg, 0, msg.Length);
//Encryptor.FlushFinalBlock();
cryptograph = Memory.ToArray();
}
}
}
return cryptograph;
}
/// <summary>
/// AES加密
/// </summary>
/// <param name="msg"></param>
/// <param name="key"></param>
/// <returns></returns>
public byte[] Encrypt(Stream msg, string key = null)
{
byte[] buf = new byte[msg.Length];
msg.Read(null, 0, buf.Length);
return Encrypt(buf, key);
}
}
}
| 32.929293 | 113 | 0.47546 | [
"MIT"
] | jinyuttt/DBAcessSrv | NetCrypto/Encrypt/AesEncryptProvider.cs | 3,407 | C# |
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Android.Runtime.ResourceDesignerAttribute("ControllRinger.Resource", IsApplication=true)]
namespace ControllRinger
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public static void UpdateIdValues()
{
}
public partial class Attribute
{
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class Drawable
{
// aapt resource value: 0x7f020000
public const int Icon = 2130837504;
static Drawable()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Drawable()
{
}
}
public partial class Id
{
// aapt resource value: 0x7f050000
public const int myButton = 2131034112;
static Id()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Id()
{
}
}
public partial class Layout
{
// aapt resource value: 0x7f030000
public const int Main = 2130903040;
static Layout()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Layout()
{
}
}
public partial class String
{
// aapt resource value: 0x7f040001
public const int app_name = 2130968577;
// aapt resource value: 0x7f040000
public const int hello = 2130968576;
static String()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String()
{
}
}
}
}
#pragma warning restore 1591
| 18.964602 | 108 | 0.603826 | [
"MIT"
] | IshamMohamed/xamarin-android-samples | ControllRinger/ControllRinger/Resources/Resource.designer.cs | 2,143 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
partial class DockPanel
{
/// <summary>
/// DragHandlerBase is the base class for drag handlers. The derived class should:
/// 1. Define its public method BeginDrag. From within this public BeginDrag method,
/// DragHandlerBase.BeginDrag should be called to initialize the mouse capture
/// and message filtering.
/// 2. Override the OnDragging and OnEndDrag methods.
/// </summary>
private abstract class DragHandlerBase : NativeWindow, IMessageFilter
{
protected DragHandlerBase()
{
}
protected abstract Control DragControl
{
get;
}
private Point m_startMousePosition = Point.Empty;
protected Point StartMousePosition
{
get { return m_startMousePosition; }
private set { m_startMousePosition = value; }
}
protected bool BeginDrag()
{
if (DragControl == null)
return false;
StartMousePosition = Control.MousePosition;
if (!Win32Helper.IsRunningOnMono)
if (!NativeMethods.DragDetect(DragControl.Handle, StartMousePosition))
return false;
DragControl.FindForm().Capture = true;
AssignHandle(DragControl.FindForm().Handle);
Application.AddMessageFilter(this);
return true;
}
protected abstract void OnDragging();
protected abstract void OnEndDrag(bool abort);
private void EndDrag(bool abort)
{
ReleaseHandle();
Application.RemoveMessageFilter(this);
DragControl.FindForm().Capture = false;
OnEndDrag(abort);
}
bool IMessageFilter.PreFilterMessage(ref Message m)
{
if (m.Msg == (int)Win32.Msgs.WM_MOUSEMOVE)
OnDragging();
else if (m.Msg == (int)Win32.Msgs.WM_LBUTTONUP)
EndDrag(false);
else if (m.Msg == (int)Win32.Msgs.WM_CAPTURECHANGED)
EndDrag(true);
else if (m.Msg == (int)Win32.Msgs.WM_KEYDOWN && (int)m.WParam == (int)Keys.Escape)
EndDrag(true);
return OnPreFilterMessage(ref m);
}
protected virtual bool OnPreFilterMessage(ref Message m)
{
return false;
}
protected sealed override void WndProc(ref Message m)
{
if (m.Msg == (int)Win32.Msgs.WM_CANCELMODE || m.Msg == (int)Win32.Msgs.WM_CAPTURECHANGED)
EndDrag(true);
base.WndProc(ref m);
}
}
private abstract class DragHandler : DragHandlerBase
{
private DockPanel m_dockPanel;
protected DragHandler(DockPanel dockPanel)
{
m_dockPanel = dockPanel;
}
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
private IDragSource m_dragSource;
protected IDragSource DragSource
{
get { return m_dragSource; }
set { m_dragSource = value; }
}
protected sealed override Control DragControl
{
get { return DragSource == null ? null : DragSource.DragControl; }
}
protected sealed override bool OnPreFilterMessage(ref Message m)
{
if ((m.Msg == (int)Win32.Msgs.WM_KEYDOWN || m.Msg == (int)Win32.Msgs.WM_KEYUP) &&
((int)m.WParam == (int)Keys.ControlKey || (int)m.WParam == (int)Keys.ShiftKey))
OnDragging();
return base.OnPreFilterMessage(ref m);
}
}
}
}
| 32.037594 | 105 | 0.529453 | [
"MIT"
] | gudebai120/dockpanelsuite | WinFormsUI/Docking/DockPanel.DragHandler.cs | 4,261 | C# |
//<summary>
// Title : Assembly info for: CAS.CommServer.UA.Server.Service.UnitTest
// System : Microsoft Visual C# .NET
// $LastChangedDate: $
// $Rev: $
// $LastChangedBy: $
// $URL: $
// $Id: $
//
// Copyright (c) 2000-2016 CAS LODZ POLAND
// +48 (42) 686 25 47
// techsupp@cas.eu
// www.cas.eu
//</summary>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CAS.CommServer.UA.Server.Service.UnitTest")]
[assembly: AssemblyDescription("CommServer Multi-source OPC UA Server Unit Test")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("CAS")]
[assembly: AssemblyProduct("CAS CommServerUA Family")]
[assembly: AssemblyCopyright("Copyright (c) 2000-2016 CAS LODZ POLAND")]
[assembly: AssemblyTrademark("CommServer")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("4cb5126d-9273-47cb-b6c8-be057eeb45b8")]
[assembly: AssemblyVersion("1.00.33.*")]
[assembly: AssemblyFileVersion("1.00.33")]
| 31.5 | 83 | 0.696545 | [
"MIT"
] | mpostol/OPCUA.Server | Server.ServiceUnitTest/Properties/AssemblyInfo.cs | 1,073 | C# |
using System;
using System.Windows.Media;
using Cadena.Data;
using StarryEyes.Views;
namespace StarryEyes.Models.Backstages.TwitterEvents
{
public sealed class QuotedEvent : TwitterEventBase
{
public QuotedEvent(TwitterUser source, TwitterStatus status)
: base(source, status.QuotedStatus?.User, status)
{
if (status.QuotedStatus == null)
{
throw new ArgumentException("specified status has not quote information.");
}
}
public override string Title => "QT";
public override string Detail => Source.ScreenName + ": " + TargetStatus;
public override Color Background => MetroColors.Olive;
}
} | 28.8 | 91 | 0.644444 | [
"MIT"
] | karno/StarryEyes | StarryEyes/Models/Backstages/TwitterEvents/QuotedEvent.cs | 722 | C# |
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using WebApplicationPostTest.Models;
namespace WebApplicationPostTest.Areas.Identity.Pages.Account.Manage
{
public class ChangePasswordModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<ChangePasswordModel> _logger;
public ChangePasswordModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILogger<ChangePasswordModel> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
[TempData]
public string StatusMessage { get; set; }
public class InputModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var hasPassword = await _userManager.HasPasswordAsync(user);
if (!hasPassword)
{
return RedirectToPage("./SetPassword");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);
if (!changePasswordResult.Succeeded)
{
foreach (var error in changePasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
await _signInManager.RefreshSignInAsync(user);
_logger.LogInformation("User changed their password successfully.");
StatusMessage = "Your password has been changed.";
return RedirectToPage();
}
}
}
| 34.05 | 129 | 0.591777 | [
"MIT"
] | ahmed-abdelrazek/SuperPostDroidPunk | src/WebApplicationPostTest/Areas/Identity/Pages/Account/Manage/ChangePassword.cshtml.cs | 3,407 | C# |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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 Microsoft.VisualStudio.TestTools.Common;
using Microsoft.VisualStudio.TestTools.TestAdapter;
using Microsoft.VisualStudio.TestTools.Vsip;
namespace Gallio.VisualStudio.Tip
{
/// <summary>
/// Constructs instances of target interfaces from the proxy.
/// </summary>
public interface IProxyTargetFactory
{
ITestAdapter CreateTestAdapter();
ITip CreateTip(ITmi tmi);
}
}
| 33.545455 | 75 | 0.738031 | [
"ECL-2.0",
"Apache-2.0"
] | citizenmatt/gallio | src/Extensions/VisualStudio/Gallio.VisualStudio.Tip.Proxy/IProxyTargetFactory.cs | 1,107 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reactive.Disposables;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.Controls.Primitives.PopupPositioning;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Input.Raw;
using Avalonia.Platform;
using Avalonia.Rendering;
namespace Avalonia.DesignerSupport.Remote
{
class WindowStub : IWindowImpl, IPopupImpl
{
public Action Deactivated { get; set; }
public Action Activated { get; set; }
public IPlatformHandle Handle { get; }
public Size MaxAutoSizeHint { get; }
public Size ClientSize { get; }
public double RenderScaling { get; } = 1.0;
public double DesktopScaling => 1.0;
public IEnumerable<object> Surfaces { get; }
public Action<RawInputEventArgs> Input { get; set; }
public Action<Rect> Paint { get; set; }
public Action<Size> Resized { get; set; }
public Action<double> ScalingChanged { get; set; }
public Func<bool> Closing { get; set; }
public Action Closed { get; set; }
public Action LostFocus { get; set; }
public IMouseDevice MouseDevice { get; } = new MouseDevice();
public IPopupImpl CreatePopup() => new WindowStub(this);
public PixelPoint Position { get; set; }
public Action<PixelPoint> PositionChanged { get; set; }
public WindowState WindowState { get; set; }
public Action<WindowState> WindowStateChanged { get; set; }
public Action<WindowTransparencyLevel> TransparencyLevelChanged { get; set; }
public Action<bool> ExtendClientAreaToDecorationsChanged { get; set; }
public Thickness ExtendedMargins { get; } = new Thickness();
public Thickness OffScreenMargin { get; } = new Thickness();
public WindowStub(IWindowImpl parent = null)
{
if (parent != null)
PopupPositioner = new ManagedPopupPositioner(new ManagedPopupPositionerPopupImplHelper(parent,
(_, size, __) =>
{
Resize(size);
}));
}
public IRenderer CreateRenderer(IRenderRoot root) => new ImmediateRenderer(root);
public void Dispose()
{
}
public void Invalidate(Rect rect)
{
}
public void SetInputRoot(IInputRoot inputRoot)
{
}
public Point PointToClient(PixelPoint p) => p.ToPoint(1);
public PixelPoint PointToScreen(Point p) => PixelPoint.FromPoint(p, 1);
public void SetCursor(ICursorImpl cursor)
{
}
public void Show(bool activate)
{
}
public void Hide()
{
}
public void BeginMoveDrag(PointerPressedEventArgs e)
{
}
public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e)
{
}
public void Activate()
{
}
public void Resize(Size clientSize)
{
}
public void Move(PixelPoint point)
{
}
public IScreenImpl Screen { get; } = new ScreenStub();
public void SetMinMaxSize(Size minSize, Size maxSize)
{
}
public void SetTitle(string title)
{
}
public void ShowDialog(IWindowImpl parent)
{
}
public void SetSystemDecorations(SystemDecorations enabled)
{
}
public void SetIcon(IWindowIconImpl icon)
{
}
public void ShowTaskbarIcon(bool value)
{
}
public void CanResize(bool value)
{
}
public void SetTopmost(bool value)
{
}
public void SetParent(IWindowImpl parent)
{
}
public void SetEnabled(bool enable)
{
}
public void SetExtendClientAreaToDecorationsHint(bool extendIntoClientAreaHint)
{
}
public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints)
{
}
public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight)
{
}
public IPopupPositioner PopupPositioner { get; }
public Action GotInputWhenDisabled { get; set; }
public void SetTransparencyLevelHint(WindowTransparencyLevel transparencyLevel) { }
public void SetWindowManagerAddShadowHint(bool enabled)
{
}
public WindowTransparencyLevel TransparencyLevel { get; private set; }
public bool IsClientAreaExtendedToDecorations { get; }
public bool NeedsManagedDecorations => false;
public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 1, 1);
}
class ClipboardStub : IClipboard
{
public Task<string> GetTextAsync() => Task.FromResult("");
public Task SetTextAsync(string text) => Task.CompletedTask;
public Task ClearAsync() => Task.CompletedTask;
public Task SetDataObjectAsync(IDataObject data) => Task.CompletedTask;
public Task<string[]> GetFormatsAsync() => Task.FromResult(new string[0]);
public Task<object> GetDataAsync(string format) => Task.FromResult((object)null);
}
class CursorFactoryStub : ICursorFactory
{
public ICursorImpl GetCursor(StandardCursorType cursorType) => new CursorStub();
public ICursorImpl CreateCursor(IBitmapImpl cursor, PixelPoint hotSpot) => new CursorStub();
private class CursorStub : ICursorImpl
{
public void Dispose() { }
}
}
class IconLoaderStub : IPlatformIconLoader
{
class IconStub : IWindowIconImpl
{
public void Save(Stream outputStream)
{
}
}
public IWindowIconImpl LoadIcon(string fileName) => new IconStub();
public IWindowIconImpl LoadIcon(Stream stream) => new IconStub();
public IWindowIconImpl LoadIcon(IBitmapImpl bitmap) => new IconStub();
}
class SystemDialogsStub : ISystemDialogImpl
{
public Task<string[]> ShowFileDialogAsync(FileDialog dialog, Window parent) =>
Task.FromResult((string[])null);
public Task<string> ShowFolderDialogAsync(OpenFolderDialog dialog, Window parent) =>
Task.FromResult((string)null);
}
class ScreenStub : IScreenImpl
{
public int ScreenCount => 1;
public IReadOnlyList<Screen> AllScreens { get; } =
new Screen[] { new Screen(1, new PixelRect(0, 0, 4000, 4000), new PixelRect(0, 0, 4000, 4000), true) };
}
}
| 28.304167 | 133 | 0.620197 | [
"MIT"
] | SteamTools-Team/Avalonia | src/Avalonia.DesignerSupport/Remote/Stubs.cs | 6,793 | 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.DataProtection.Models.Api20220401
{
using static Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Extensions;
/// <summary>Base for all lists of V2 resources.</summary>
public partial class DppBaseResourceList :
Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20220401.IDppBaseResourceList,
Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20220401.IDppBaseResourceListInternal
{
/// <summary>Backing field for <see cref="NextLink" /> property.</summary>
private string _nextLink;
/// <summary>
/// The uri to fetch the next page of resources. Call ListNext() fetches next page of resources.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataProtection.PropertyOrigin.Owned)]
public string NextLink { get => this._nextLink; set => this._nextLink = value; }
/// <summary>Backing field for <see cref="Value" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20220401.IDppBaseResource[] _value;
/// <summary>List of Dpp resources.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataProtection.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20220401.IDppBaseResource[] Value { get => this._value; set => this._value = value; }
/// <summary>Creates an new <see cref="DppBaseResourceList" /> instance.</summary>
public DppBaseResourceList()
{
}
}
/// Base for all lists of V2 resources.
public partial interface IDppBaseResourceList :
Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.IJsonSerializable
{
/// <summary>
/// The uri to fetch the next page of resources. Call ListNext() fetches next page of resources.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The uri to fetch the next page of resources. Call ListNext() fetches next page of resources.",
SerializedName = @"nextLink",
PossibleTypes = new [] { typeof(string) })]
string NextLink { get; set; }
/// <summary>List of Dpp resources.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"List of Dpp resources.",
SerializedName = @"value",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20220401.IDppBaseResource) })]
Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20220401.IDppBaseResource[] Value { get; set; }
}
/// Base for all lists of V2 resources.
internal partial interface IDppBaseResourceListInternal
{
/// <summary>
/// The uri to fetch the next page of resources. Call ListNext() fetches next page of resources.
/// </summary>
string NextLink { get; set; }
/// <summary>List of Dpp resources.</summary>
Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20220401.IDppBaseResource[] Value { get; set; }
}
} | 50.932432 | 161 | 0.683736 | [
"MIT"
] | jago2136/azure-powershell | src/DataProtection/generated/api/Models/Api20220401/DppBaseResourceList.cs | 3,696 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Unity.Appodeal.Xcode.PBX {
class PropertyCommentChecker {
private int m_Level;
private bool m_All;
private List<List<string>> m_Props;
/* The argument is an array of matcher strings each of which determine
whether a property with a certain path needs to be decorated with a
comment.
A path is a number of path elements concatenated by '/'. The last path
element is either:
the key if we're referring to a dict key
the value if we're referring to a value in an array
the value if we're referring to a value in a dict
All other path elements are either:
the key if the container is dict
'*' if the container is array
Path matcher has the same structure as a path, except that any of the
elements may be '*'. Matcher matches a path if both have the same number
of elements and for each pair matcher element is the same as path element
or is '*'.
a/b/c matches a/b/c but not a/b nor a/b/c/d
a/* /c matches a/d/c but not a/b nor a/b/c/d
* /* /* matches any path from three elements
*/
protected PropertyCommentChecker (int level, List<List<string>> props) {
m_Level = level;
m_All = false;
m_Props = props;
}
public PropertyCommentChecker () {
m_Level = 0;
m_All = false;
m_Props = new List<List<string>> ();
}
public PropertyCommentChecker (IEnumerable<string> props) {
m_Level = 0;
m_All = false;
m_Props = new List<List<string>> ();
foreach (var prop in props) {
m_Props.Add (new List<string> (prop.Split ('/')));
}
}
bool CheckContained (string prop) {
if (m_All)
return true;
foreach (var list in m_Props) {
if (list.Count == m_Level + 1) {
if (list[m_Level] == prop)
return true;
if (list[m_Level] == "*") {
m_All = true; // short-circuit all at this level
return true;
}
}
}
return false;
}
public bool CheckStringValueInArray (string value) { return CheckContained (value); }
public bool CheckKeyInDict (string key) { return CheckContained (key); }
public bool CheckStringValueInDict (string key, string value) {
foreach (var list in m_Props) {
if (list.Count == m_Level + 2) {
if ((list[m_Level] == "*" || list[m_Level] == key) &&
list[m_Level + 1] == "*" || list[m_Level + 1] == value)
return true;
}
}
return false;
}
public PropertyCommentChecker NextLevel (string prop) {
var newList = new List<List<string>> ();
foreach (var list in m_Props) {
if (list.Count <= m_Level + 1)
continue;
if (list[m_Level] == "*" || list[m_Level] == prop)
newList.Add (list);
}
return new PropertyCommentChecker (m_Level + 1, newList);
}
}
class Serializer {
public static PBXElementDict ParseTreeAST (TreeAST ast, TokenList tokens, string text) {
var el = new PBXElementDict ();
foreach (var kv in ast.values) {
PBXElementString key = ParseIdentifierAST (kv.key, tokens, text);
PBXElement value = ParseValueAST (kv.value, tokens, text);
el[key.value] = value;
}
return el;
}
public static PBXElementArray ParseArrayAST (ArrayAST ast, TokenList tokens, string text) {
var el = new PBXElementArray ();
foreach (var v in ast.values) {
el.values.Add (ParseValueAST (v, tokens, text));
}
return el;
}
public static PBXElement ParseValueAST (ValueAST ast, TokenList tokens, string text) {
if (ast is TreeAST)
return ParseTreeAST ((TreeAST) ast, tokens, text);
if (ast is ArrayAST)
return ParseArrayAST ((ArrayAST) ast, tokens, text);
if (ast is IdentifierAST)
return ParseIdentifierAST ((IdentifierAST) ast, tokens, text);
return null;
}
public static PBXElementString ParseIdentifierAST (IdentifierAST ast, TokenList tokens, string text) {
Token tok = tokens[ast.value];
string value;
switch (tok.type) {
case TokenType.String:
value = text.Substring (tok.begin, tok.end - tok.begin);
return new PBXElementString (value);
case TokenType.QuotedString:
value = text.Substring (tok.begin, tok.end - tok.begin);
value = PBXStream.UnquoteString (value);
return new PBXElementString (value);
default:
throw new Exception ("Internal parser error");
}
}
static string k_Indent = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
static string GetIndent (int indent) {
return k_Indent.Substring (0, indent);
}
static void WriteStringImpl (StringBuilder sb, string s, bool comment, GUIDToCommentMap comments) {
if (comment)
comments.WriteStringBuilder (sb, s);
else
sb.Append (PBXStream.QuoteStringIfNeeded (s));
}
public static void WriteDictKeyValue (StringBuilder sb, string key, PBXElement value, int indent, bool compact,
PropertyCommentChecker checker, GUIDToCommentMap comments) {
if (!compact) {
sb.Append ("\n");
sb.Append (GetIndent (indent));
}
WriteStringImpl (sb, key, checker.CheckKeyInDict (key), comments);
sb.Append (" = ");
if (value is PBXElementString)
WriteStringImpl (sb, value.AsString (), checker.CheckStringValueInDict (key, value.AsString ()), comments);
else if (value is PBXElementDict)
WriteDict (sb, value.AsDict (), indent, compact, checker.NextLevel (key), comments);
else if (value is PBXElementArray)
WriteArray (sb, value.AsArray (), indent, compact, checker.NextLevel (key), comments);
sb.Append (";");
if (compact)
sb.Append (" ");
}
public static void WriteDict (StringBuilder sb, PBXElementDict el, int indent, bool compact,
PropertyCommentChecker checker, GUIDToCommentMap comments) {
sb.Append ("{");
if (el.Contains ("isa"))
WriteDictKeyValue (sb, "isa", el["isa"], indent + 1, compact, checker, comments);
var keys = new List<string> (el.values.Keys);
keys.Sort (StringComparer.Ordinal);
foreach (var key in keys) {
if (key != "isa")
WriteDictKeyValue (sb, key, el[key], indent + 1, compact, checker, comments);
}
if (!compact) {
sb.Append ("\n");
sb.Append (GetIndent (indent));
}
sb.Append ("}");
}
public static void WriteArray (StringBuilder sb, PBXElementArray el, int indent, bool compact,
PropertyCommentChecker checker, GUIDToCommentMap comments) {
sb.Append ("(");
foreach (var value in el.values) {
if (!compact) {
sb.Append ("\n");
sb.Append (GetIndent (indent + 1));
}
if (value is PBXElementString)
WriteStringImpl (sb, value.AsString (), checker.CheckStringValueInArray (value.AsString ()), comments);
else if (value is PBXElementDict)
WriteDict (sb, value.AsDict (), indent + 1, compact, checker.NextLevel ("*"), comments);
else if (value is PBXElementArray)
WriteArray (sb, value.AsArray (), indent + 1, compact, checker.NextLevel ("*"), comments);
sb.Append (",");
if (compact)
sb.Append (" ");
}
if (!compact) {
sb.Append ("\n");
sb.Append (GetIndent (indent));
}
sb.Append (")");
}
}
} | 40.838565 | 123 | 0.518173 | [
"MIT"
] | lukeh17/Weiner-Run | Weiner Run/Assets/Appodeal/Editor/xcode/PBX/Serializer.cs | 9,107 | C# |
namespace QlikApiParser
{
#region Usings
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using NLog;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
#endregion
public enum AsyncMode
{
NONE,
SHOW
}
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore,
NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class QlikApiConfig
{
#region Properties
[JsonProperty(Required = Required.Always)]
public string SourceFile { get; set; }
[JsonProperty(Required = Required.Always)]
public string OutputFolder { get; set; }
[JsonProperty(Required = Required.Always)]
public string NamespaceName { get; set; }
[JsonProperty]
public bool UseQlikResponseLogic { get; set; } = true;
[JsonProperty]
public bool UseDescription { get; set; } = true;
[JsonProperty]
public AsyncMode AsyncMode { get; set; } = AsyncMode.SHOW;
[JsonProperty]
public bool GenerateCancelationToken { get; set; } = true;
[JsonIgnore]
public string BaseObjectInterfaceClassName { get; } = "ObjectInterface";
[JsonIgnore]
public string BaseObjectInterfaceName
{
get { return $"I{BaseObjectInterfaceClassName }"; }
}
#endregion
public string GetChangeFile()
{
var name = Path.GetFileNameWithoutExtension(SourceFile);
return $"{name}_change.json";
}
}
} | 29.654545 | 80 | 0.618026 | [
"MIT"
] | konne/qlik-engineapi | src/qlik-engineapi-generator/QlikApiConfig.cs | 1,631 | C# |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Lunchorder.Test.Integration.Helpers.Base;
using NUnit.Framework;
namespace Lunchorder.Test.Integration.Services
{
[TestFixture]
public class ApplicationUserServiceTest : ServiceBase
{
[Test]
public async Task CreateWithoutPassword()
{
var username = "username 123456";
var email = "user@name.123456";
var firstName = "first";
var lastName = "name";
var dbUserId = await ApplicationUserService.Create(username, email, firstName, lastName);
Assert.AreNotEqual(new Guid().ToString(), dbUserId);
Assert.IsNullOrEmpty(dbUserId.PasswordHash);
}
[Test]
public async Task CreateWithPassword()
{
for (var i = 0; i < 20; i++)
{
await CreateUserWithPassword(i, "demo_admin");
}
for (var i = 0; i < 20; i++)
{
await CreateUserWithPassword(i, "demo_user");
}
}
private async Task CreateUserWithPassword(int i, string username)
{
if (i > 0)
{
username += i;
}
var email = $"{username}@lunchorder.be";
var name = username.Split('_');
var firstName = name[0];
var lastName = name[1];
var dbUserId = await ApplicationUserService.Create(username, email, firstName, lastName, password: username);
Assert.AreNotEqual(new Guid().ToString(), dbUserId);
Assert.IsNotNullOrEmpty(dbUserId.PasswordHash);
}
}
}
| 30.285714 | 121 | 0.560142 | [
"MIT"
] | CoditEU/lunchorder | backend/WebApi/Lunchorder.Test/Integration/Services/ApplicationUserServiceTest.cs | 1,698 | C# |
namespace Kentico.Kontent.Delivery.Tests.Models.ContentTypes
{
public interface IArticle
{
public string Title { get; }
}
}
| 18.125 | 61 | 0.668966 | [
"MIT"
] | Kentico/delivery-sdk-net | Kentico.Kontent.Delivery.Tests/Models/ContentTypes/IArticle.cs | 147 | 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 quicksight-2018-04-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.QuickSight.Model
{
/// <summary>
/// Container for the parameters to the ListThemeAliases operation.
/// Lists all the aliases of a theme.
/// </summary>
public partial class ListThemeAliasesRequest : AmazonQuickSightRequest
{
private string _awsAccountId;
private int? _maxResults;
private string _nextToken;
private string _themeId;
/// <summary>
/// Gets and sets the property AwsAccountId.
/// <para>
/// The ID of the AWS account that contains the theme aliases that you're listing.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=12, Max=12)]
public string AwsAccountId
{
get { return this._awsAccountId; }
set { this._awsAccountId = value; }
}
// Check to see if AwsAccountId property is set
internal bool IsSetAwsAccountId()
{
return this._awsAccountId != null;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of results to be returned per request.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=100)]
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token for the next set of results, or null if there are no more results.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property ThemeId.
/// <para>
/// The ID for the theme.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=2048)]
public string ThemeId
{
get { return this._themeId; }
set { this._themeId = value; }
}
// Check to see if ThemeId property is set
internal bool IsSetThemeId()
{
return this._themeId != null;
}
}
} | 29.644068 | 108 | 0.587764 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/src/Services/QuickSight/Generated/Model/ListThemeAliasesRequest.cs | 3,498 | C# |
using Microsoft.Web.WebView2.Core;
namespace WebView2.DOM
{
// https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/svg/svg_foreign_object_element.idl
public class SVGForeignObjectElement : SVGGraphicsElement
{
protected internal SVGForeignObjectElement(CoreWebView2 coreWebView, string referenceId)
: base(coreWebView, referenceId) { }
public SVGAnimatedLength x => Get<SVGAnimatedLength>();
public SVGAnimatedLength y => Get<SVGAnimatedLength>();
public SVGAnimatedLength width => Get<SVGAnimatedLength>();
public SVGAnimatedLength height => Get<SVGAnimatedLength>();
}
} | 36.588235 | 119 | 0.790997 | [
"MIT"
] | R2D221/WebView2.DOM | WebView2.DOM/SVG/Elements/SVGForeignObjectElement.cs | 624 | C# |
// <copyright file="Complex32.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2010 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Globalization;
using System.Runtime.Serialization;
namespace BGC.Mathematics
{
/// <summary>
/// Represents a complex number with single-precision floating point components
/// </summary>
public readonly struct Complex32 : IEquatable<Complex32>, IFormattable
{
/// <summary>
/// The real component of the complex number.
/// </summary>
[DataMember(Order = 1)]
private readonly float _real;
/// <summary>
/// The imaginary component of the complex number.
/// </summary>
[DataMember(Order = 2)]
private readonly float _imag;
/// <summary>
/// Returns a new Complex32 instance with a real number equal to zero and an imaginary number equal to zero.
/// </summary>
public static readonly Complex32 Zero = new Complex32(0f, 0f);
/// <summary>
/// Returns a new Complex32 instance with a real number equal to one and an imaginary number equal to zero.
/// </summary>
public static readonly Complex32 One = new Complex32(1f, 0f);
/// <summary>
/// Returns a new Complex32 instance with a real number equal to zero and an imaginary number equal to one.
/// </summary>
public static readonly Complex32 ImaginaryOne = new Complex32(0f, 1f);
/// <summary>
/// Returns a new Complex32 instance with real and imaginary numbers positive infinite.
/// </summary>
public static readonly Complex32 PositiveInfinity = new Complex32(float.PositiveInfinity, float.PositiveInfinity);
/// <summary>
/// Returns a new Complex32 instance with real and imaginary numbers not a number.
/// </summary>
public static readonly Complex32 NaN = new Complex32(float.NaN, float.NaN);
/// <summary>
/// Initializes a new Complex32 structure using the specified real and imaginary values.
/// </summary>
public Complex32(float real, float imaginary)
{
_real = real;
_imag = imaginary;
}
/// <summary>
/// Gets the imaginary component of the current System.Numerics.Complex32 object.
/// </summary>
public float Imaginary => _imag;
/// <summary>
/// Gets the real component of the current System.Numerics.Complex32 object.
/// </summary>
public float Real => _real;
/// <summary>
/// Gets the magnitude (or absolute value) of a complex number.
/// </summary>
public float Magnitude
{
get
{
if (float.IsNaN(_real) || float.IsNaN(_imag))
{
return float.NaN;
}
if (float.IsInfinity(_real) || float.IsInfinity(_imag))
{
return float.PositiveInfinity;
}
float a = Math.Abs(_real);
float b = Math.Abs(_imag);
if (a > b)
{
double tmp = b / (double)a;
return a * (float)Math.Sqrt(1.0 + tmp * tmp);
}
if (a == 0f) // one can write a >= float.Epsilon here
{
return b;
}
else
{
double tmp = a / (double)b;
return b * (float)Math.Sqrt(1.0 + tmp * tmp);
}
}
}
/// <summary>
/// Gets the phase of a complex number in radians.
/// </summary>
public float Phase => _imag == 0f && _real < 0f ? GeneralMath.fPI : (float)Math.Atan2(_imag, _real);
/// <summary>
/// Gets the absolute value (or magnitude) of a complex number.
/// </summary>
public static float Abs(in Complex32 value) => value.Magnitude;
/// <summary>
/// Trigonometric principal Arc Cosine of this Complex32 number.
/// </summary>
/// <param name="value">The complex value.</param>
/// <returns>The arc cosine of a complex number.</returns>
// From Mathnet.Numerics
public static Complex32 Acos(in Complex32 value)
{
if (value.Imaginary < 0f || value.Imaginary == 0f && value.Real > 0f)
{
return GeneralMath.fPI - Acos(-value);
}
return -ImaginaryOne * (value + (ImaginaryOne * (1f - value.Square()).SquareRoot())).NaturalLogarithm();
}
/// <summary>
/// Returns the sum of the two Complex32 inputs
/// </summary>
public static Complex32 Add(in Complex32 left, in Complex32 right) => left + right;
/// <summary>
/// Trigonometric principal Arc Sine of this Complex32 number.
/// </summary>
/// <param name="value">The complex value.</param>
/// <returns>The arc sine of a complex number.</returns>
// From Mathnet.Numerics
public static Complex32 Asin(in Complex32 value)
{
if (value.Imaginary > 0f || value.Imaginary == 0f && value.Real < 0f)
{
return -Asin(-value);
}
return -ImaginaryOne * ((1f - value.Square()).SquareRoot() + (ImaginaryOne * value)).NaturalLogarithm();
}
/// <summary>
/// Trigonometric principal Arc Tangent of this Complex32 number.
/// </summary>
/// <param name="value">The complex value.</param>
/// <returns>The arc tangent of a complex number.</returns>
// From Mathnet.Numerics
public static Complex32 Atan(in Complex32 value)
{
Complex32 iz = new Complex32(-value.Imaginary, value.Real); // I*this
return new Complex32(0f, 0.5f) * ((1f - iz).NaturalLogarithm() - (1f + iz).NaturalLogarithm());
}
/// <summary>
/// Computes the conjugate of a complex number and returns the result.
/// </summary>
public static Complex32 Conjugate(in Complex32 value) => value.Conjugate();
/// <summary>
/// Trigonometric Cosine of a Complex32 number.
/// </summary>
/// <param name="value">The complex value.</param>
/// <returns>The cosine of a complex number.</returns>
// From Mathnet.Numerics
public static Complex32 Cos(in Complex32 value)
{
if (value.IsReal())
{
return new Complex32((float)Math.Cos(value.Real), 0f);
}
return new Complex32(
(float)(Math.Cos(value.Real) * GeneralMath.Cosh(value.Imaginary)),
(float)(-Math.Sin(value.Real) * GeneralMath.Sinh(value.Imaginary)));
}
/// <summary>
/// Hyperbolic Cosine of a Complex32 number.
/// </summary>
/// <param name="value">The complex value.</param>
/// <returns>The hyperbolic cosine of a complex number.</returns>
// From Mathnet.Numerics
public static Complex32 Cosh(in Complex32 value)
{
if (value.IsReal())
{
return new Complex32(GeneralMath.Cosh(value.Real), 0f);
}
// cosh(x + j*y) = cosh(x)*cos(y) + j*sinh(x)*sin(y)
// if x > huge, cosh(x + j*y) = exp(|x|)/2*cos(y) + j*sign(x)*exp(|x|)/2*sin(y)
if (Math.Abs(value.Real) >= 22f) // Taken from the msun library in FreeBSD
{
double h = Math.Exp(Math.Abs(value.Real)) * 0.5;
return new Complex32(
(float)(h * Math.Cos(value.Imaginary)),
(float)(Math.Sign(value.Real) * h * Math.Sin(value.Imaginary)));
}
return new Complex32(
(float)(GeneralMath.Cosh(value.Real) * Math.Cos(value.Imaginary)),
(float)(GeneralMath.Sinh(value.Real) * Math.Sin(value.Imaginary)));
}
/// <summary>
/// Divides one complex number by another and returns the result.
/// </summary>
public static Complex32 Divide(in Complex32 dividend, in Complex32 divisor) => dividend / divisor;
/// <summary>
/// Returns e raised to the power specified by a complex number.
/// </summary>
public static Complex32 Exp(in Complex32 value) => value.Exponential();
/// <summary>
/// Creates a complex number from a point's polar coordinates.
/// </summary>
public static Complex32 FromPolarCoordinates(float magnitude, float phase) =>
new Complex32(
(float)(magnitude * Math.Cos(phase)),
(float)(magnitude * Math.Sin(phase)));
/// <summary>
/// Creates a complex number from a point's polar coordinates.
/// </summary>
public static Complex32 FromPolarCoordinates(double magnitude, double phase) =>
new Complex32(
(float)(magnitude * Math.Cos(phase)),
(float)(magnitude * Math.Sin(phase)));
/// <summary>
/// Returns the natural (base e) logarithm of a specified complex number.
/// </summary>
public static Complex32 Log(in Complex32 value) => value.NaturalLogarithm();
/// <summary>
/// Returns the logarithm of a specified complex number in a specified base.
/// </summary>
public static Complex32 Log(in Complex32 value, float baseValue) => value.Logarithm(baseValue);
/// <summary>
/// Returns the base-10 logarithm of a specified complex number.
/// </summary>
public static Complex32 Log10(in Complex32 value) => value.CommonLogarithm();
/// <summary>
/// Returns the product of two complex numbers.
/// </summary>
public static Complex32 Multiply(in Complex32 left, in Complex32 right) => left * right;
/// <summary>
/// Returns the additive inverse of a specified complex number.
/// </summary>
public static Complex32 Negate(in Complex32 value) => -value;
/// <summary>
/// Returns a specified complex number raised to a power specified by a float-precision floating-point number.
/// </summary>
public static Complex32 Pow(in Complex32 value, float power) => value.Power(power);
/// <summary>
/// Returns a specified complex number raised to a power specified by a complex number.
/// </summary>
public static Complex32 Pow(in Complex32 value, in Complex32 power) => value.Power(power);
/// <summary>
/// Returns the multiplicative inverse of a complex number.
/// </summary>
public static Complex32 Reciprocal(in Complex32 value) => value.Reciprocal();
/// <summary>
/// Trigonometric Sine of a Complex32 number.
/// </summary>
/// <param name="value">The complex value.</param>
/// <returns>The sine of the complex number.</returns>
// From Mathnet.Numerics
public static Complex32 Sin(in Complex32 value)
{
if (value.IsReal())
{
return new Complex32((float)Math.Sin(value.Real), 0f);
}
return new Complex32(
(float)(Math.Sin(value.Real) * GeneralMath.Cosh(value.Imaginary)),
(float)(Math.Cos(value.Real) * GeneralMath.Sinh(value.Imaginary)));
}
/// <summary>
/// Hyperbolic Sine of a Complex32 number.
/// </summary>
/// <param name="value">The complex value.</param>
/// <returns>The hyperbolic sine of a complex number.</returns>
// From Mathnet.Numerics
public static Complex32 Sinh(in Complex32 value)
{
if (value.IsReal())
{
return new Complex32(GeneralMath.Sinh(value.Real), 0f);
}
// sinh(x + j y) = sinh(x)*cos(y) + j*cosh(x)*sin(y)
// if x > huge, sinh(x + jy) = sign(x)*exp(|x|)/2*cos(y) + j*exp(|x|)/2*sin(y)
if (Math.Abs(value.Real) >= 22f) // Taken from the msun library in FreeBSD
{
double h = Math.Exp(Math.Abs(value.Real)) * 0.5;
return new Complex32(
(float)(Math.Sign(value.Real) * h * Math.Cos(value.Imaginary)),
(float)(h * Math.Sin(value.Imaginary)));
}
return new Complex32(
(float)(GeneralMath.Sinh(value.Real) * Math.Cos(value.Imaginary)),
(float)(GeneralMath.Cosh(value.Real) * Math.Sin(value.Imaginary)));
}
/// <summary>
/// The Square (power 2) of this Complex32
/// </summary>
/// <returns>
/// The square of this complex number.
/// </returns>
public Complex32 Square()
{
if (IsReal())
{
return new Complex32(_real * _real, 0.0f);
}
return new Complex32((_real * _real) - (_imag * _imag), 2 * _real * _imag);
}
/// <summary>
/// The Square Root of a complex number
/// </summary>
// From Mathnet.Numerics
public static Complex32 Sqrt(in Complex32 value) => value.SquareRoot();
/// <summary>
/// The difference between two Complex32 numbers;
/// </summary>
/// <returns>The complex difference.</returns>
// From Mathnet.Numerics
public static Complex32 Subtract(in Complex32 left, Complex32 right) => left - right;
/// <summary>
/// Trigonometric Tangent of a Complex32 number.
/// </summary>
/// <param name="value">The complex value.</param>
/// <returns>The tangent of the complex number.</returns>
// From Mathnet.Numerics
public static Complex32 Tan(in Complex32 value)
{
if (value.IsReal())
{
return new Complex32((float)Math.Tan(value.Real), 0f);
}
// tan(z) = - j*tanh(j*z)
Complex32 z = Tanh(new Complex32(-value.Imaginary, value.Real));
return new Complex32(z.Imaginary, -z.Real);
}
/// <summary>
/// Hyperbolic Tangent of a Complex32 number.
/// </summary>
/// <param name="value">The complex value.</param>
/// <returns>The hyperbolic tangent of a complex number.</returns>
// From Mathnet.Numerics
public static Complex32 Tanh(in Complex32 value)
{
if (value.IsReal())
{
return new Complex32(GeneralMath.Tanh(value.Real), 0f);
}
// tanh(x + j*y) = (cosh(x)*sinh(x)/cos^2(y) + j*tan(y))/(1 + sinh^2(x)/cos^2(y))
// if |x| > huge, tanh(z) = sign(x) + j*4*cos(y)*sin(y)*exp(-2*|x|)
// if exp(-|x|) = 0, tanh(z) = sign(x)
// if tan(y) = +/- oo or 1/cos^2(y) = 1 + tan^2(y) = oo, tanh(z) = cosh(x)/sinh(x)
//
// The algorithm is based on Kahan.
if (Math.Abs(value.Real) >= 22f) // Taken from the msun library in FreeBSD
{
double e = Math.Exp(-Math.Abs(value.Real));
if (e == 0.0)
{
return new Complex32(Math.Sign(value.Real), 0f);
}
else
{
return new Complex32(
Math.Sign(value.Real),
(float)(4.0 * Math.Cos(value.Imaginary) * Math.Sin(value.Imaginary) * e * e));
}
}
float tani = (float)Math.Tan(value.Imaginary);
float beta = 1 + tani * tani; // beta = 1/cos^2(y) = 1 + t^2
float sinhr = GeneralMath.Sinh(value.Real);
float coshr = GeneralMath.Cosh(value.Real);
if (float.IsInfinity(tani))
{
return new Complex32(coshr / sinhr, 0f);
}
float denom = 1f + beta * sinhr * sinhr;
return new Complex32(beta * coshr * sinhr / denom, tani / denom);
}
/// <summary>
/// Retuns the Complex32 number, rotated by <paramref name="phase"/> radians, or exp(i*phase)
/// </summary>
public Complex32 Rotation(float phase)
{
float cosPhase = (float)Math.Cos(phase);
float sinePhase = (float)Math.Sin(phase);
return new Complex32(
_real * cosPhase - _imag * sinePhase,
_real * sinePhase + _imag * cosPhase);
}
/// <summary>
/// Retuns the real value of the Complex32 number after rotation by <paramref name="phase"/> radians, or exp(i*phase)
/// </summary>
public float RealRotation(float phase) => _real * (float)Math.Cos(phase) - _imag * (float)Math.Sin(phase);
/// <summary>
/// Returns a value that indicates whether the current instance and a specified complex number have the same value.
/// </summary>
public bool Equals(in Complex32 value)
{
if (IsNaN() || value.IsNaN())
{
return false;
}
if (IsInfinity() && value.IsInfinity())
{
return true;
}
return GeneralMath.Approximately(_real, value._real) &&
GeneralMath.Approximately(_imag, value._imag);
}
/// <summary>
/// Returns a value that indicates whether the current instance and a specified complex number have the same value.
/// </summary>
bool IEquatable<Complex32>.Equals(Complex32 other) => Equals(other);
/// <summary>
/// Returns a value that indicates whether the current instance and a specified object have the same value.
/// </summary>
public override bool Equals(object obj) => (obj is Complex32) && Equals((Complex32)obj);
/// <summary>
/// Returns the hash code for the current Complex32 object.
/// </summary>
public override int GetHashCode()
{
int hash = 27;
hash = (13 * hash) + _real.GetHashCode();
hash = (13 * hash) + _imag.GetHashCode();
return hash;
}
/// <summary>
/// Converts the value of the current complex number to its equivalent string representation in Cartesian form by using the specified format for its real and imaginary parts.
/// </summary>
public string ToString(string format) =>
$"({_real.ToString(format, CultureInfo.CurrentCulture)}, {_imag.ToString(format, CultureInfo.CurrentCulture)})";
/// <summary>
/// Converts the value of the current complex number to its equivalent string representation in Cartesian form by using the specified culture-specific formatting information.
/// </summary>
public string ToString(IFormatProvider provider) =>
string.Format(provider, "({0}, {1})", _real, _imag);
/// <summary>
/// Converts the value of the current complex number to its equivalent string representation in Cartesian form by using the specified format and culture-specific format information for its real and imaginary parts.
/// </summary>
public string ToString(string format, IFormatProvider provider) =>
string.Format(provider,
"({0}, {1})",
_real.ToString(format, provider),
_imag.ToString(format, provider));
/// <summary>
/// Converts the value of the current complex number to its equivalent string representation in Cartesian form.
/// </summary>
/// <returns></returns>
public override string ToString() => $"({_real}, {_imag})";
/// <summary>
/// Adds two complex numbers.
/// </summary>
public static Complex32 operator +(in Complex32 left, in Complex32 right) => new Complex32(left._real + right._real, left._imag + right._imag);
/// <summary>
/// Returns the additive inverse of a specified complex number.
/// </summary>
public static Complex32 operator -(in Complex32 value) => new Complex32(-value._real, -value._imag);
/// <summary>
/// Subtracts a complex number from another complex number.
/// </summary>
public static Complex32 operator -(in Complex32 left, in Complex32 right) => new Complex32(left._real - right._real, left._imag - right._imag);
/// <summary>
/// Multiplies two specified complex numbers.
/// </summary>
public static Complex32 operator *(in Complex32 left, in Complex32 right) => new Complex32(
(left._real * right._real) - (left._imag * right._imag),
(left._real * right._imag) + (left._imag * right._real));
/// <summary>
/// Divides a specified complex number by another specified complex number.
/// </summary>
public static Complex32 operator /(in Complex32 dividend, in Complex32 divisor)
{
if (dividend.IsZero() && divisor.IsZero())
{
return NaN;
}
if (divisor.IsZero())
{
return PositiveInfinity;
}
float a = dividend.Real;
float b = dividend.Imaginary;
float c = divisor.Real;
float d = divisor.Imaginary;
if (Math.Abs(d) <= Math.Abs(c))
{
return InternalDiv(a, b, c, d, false);
}
return InternalDiv(b, a, d, c, true);
}
/// <summary>
/// Returns a value that indicates whether two complex numbers are equal.
/// </summary>
public static bool operator ==(in Complex32 left, in Complex32 right) => left.Equals(right);
/// <summary>
/// Returns a value that indicates whether two complex numbers are not equal.
/// </summary>
public static bool operator !=(in Complex32 left, in Complex32 right) => !left.Equals(right);
/// <summary>
/// Defines an implicit conversion of an unsigned byte to a complex number.
/// </summary>
public static implicit operator Complex32(byte value) => new Complex32(value, 0f);
/// <summary>
/// Defines an implicit conversion of a single-precision floating-point number to a complex number.
/// </summary>
public static implicit operator Complex32(float value) => new Complex32(value, 0f);
/// <summary>
/// Defines an implicit conversion of a double-precision floating-point number to a complex number.
/// </summary>
/// <param name="value"></param>
public static implicit operator Complex32(double value) => new Complex32((float)value, 0f);
/// <summary>
/// Defines an implicit conversion of a signed byte to a complex number.
/// </summary>
public static implicit operator Complex32(sbyte value) => new Complex32(value, 0f);
/// <summary>
/// Defines an implicit conversion of a 64-bit unsigned integer to a complex number.
/// </summary>
public static implicit operator Complex32(ulong value) => new Complex32(value, 0f);
/// <summary>
/// Defines an implicit conversion of a 32-bit unsigned integer to a complex number.
/// </summary>
public static implicit operator Complex32(uint value) => new Complex32(value, 0f);
/// <summary>
/// Defines an implicit conversion of a 16-bit unsigned integer to a complex number.
/// </summary>
public static implicit operator Complex32(ushort value) => new Complex32(value, 0f);
/// <summary>
/// Defines an implicit conversion of a 64-bit signed integer to a complex number.
/// </summary>
public static implicit operator Complex32(long value) => new Complex32(value, 0f);
/// <summary>
/// Defines an implicit conversion of a 32-bit signed integer to a complex number.
/// </summary>
public static implicit operator Complex32(int value) => new Complex32(value, 0f);
/// <summary>
/// Defines an implicit conversion of a 16-bit signed integer to a complex number.
/// </summary>
public static implicit operator Complex32(short value) => new Complex32(value, 0f);
/// <summary>
/// Defines an explicit conversion of a System.Decimal value to a complex number.
/// </summary>
public static explicit operator Complex32(decimal value) => new Complex32((float)value, 0f);
public void Deconstruct(out float real, out float imag) => (real, imag) = (_real, _imag);
/// <summary>
/// Gets a value indicating whether the provided Complex32 is real.
/// </summary>
/// <returns>true if this instance is a real number; otherwise, false.</returns>
public bool IsReal() => _imag == 0f;
/// <summary>
/// Gets a value indicating whether the provided Complex32 is real and not negative, that is >= 0.
/// </summary>
/// <returns>
/// true if this instance is real nonnegative number; otherwise, false.
/// </returns>
public bool IsRealNonNegative() => _imag == 0f && _real >= 0f;
/// <summary>
/// Gets a value indicating whether the Complex32 is zero.
/// </summary>
/// <returns>true if this instance is zero; otherwise, false.</returns>
public bool IsZero() => _real == 0f && _imag == 0f;
/// <summary>
/// Gets a value indicating whether the Complex32 is one.
/// </summary>
/// <returns>true if this instance is one; otherwise, false.</returns>
public bool IsOne() => _real == 1f && _imag == 0f;
/// <summary>
/// Gets a value indicating whether the Complex32 is the imaginary unit.
/// </summary>
/// <returns>true if this instance is ImaginaryOne; otherwise, false.</returns>
public bool IsImaginaryOne() => _real == 0f && _imag == 1f;
/// <summary>
/// Gets a value indicating whether the provided Complex32 evaluates to an
/// infinite value.
/// </summary>
/// <returns>
/// true if this instance is infinite; otherwise, false.
/// </returns>
/// <remarks>
/// True if it either evaluates to a complex infinity
/// or to a directed infinity.
/// </remarks>
public bool IsInfinity() => float.IsInfinity(_real) || float.IsInfinity(_imag);
/// <summary>
/// Gets a value indicating whether the provided Complex32evaluates
/// to a value that is not a number.
/// </summary>
/// <returns>
/// true if this instance is <see cref="NaN"/>; otherwise,
/// false.
/// </returns>
public bool IsNaN() => float.IsNaN(_real) || float.IsNaN(_imag);
/// <summary>
/// Gets the squared magnitude (or squared absolute value) of a complex number.
/// </summary>
/// <returns>The squared magnitude of the current instance.</returns>
public float MagnitudeSquared => (_real * _real) + (_imag * _imag);
/// <summary>
/// Raise this Complex32 to the given value.
/// </summary>
/// <param name="exponent">
/// The exponent.
/// </param>
/// <returns>
/// The complex number raised to the given exponent.
/// </returns>
public Complex32 Power(in Complex32 exponent)
{
if (IsZero())
{
if (exponent.IsZero())
{
return One;
}
if (exponent.Real > 0f)
{
return Zero;
}
if (exponent.Real < 0f)
{
return exponent.Imaginary == 0f
? new Complex32(float.PositiveInfinity, 0f)
: new Complex32(float.PositiveInfinity, float.PositiveInfinity);
}
return NaN;
}
return (exponent * NaturalLogarithm()).Exponential();
}
/// <summary>
/// Natural Logarithm of this Complex32 (Base E).
/// </summary>
/// <returns>The natural logarithm of this complex number.</returns>
public Complex32 NaturalLogarithm()
{
if (IsRealNonNegative())
{
return new Complex32((float)Math.Log(_real), 0f);
}
return new Complex32(0.5f * (float)Math.Log(MagnitudeSquared), Phase);
}
/// <summary>
/// Common Logarithm of this Complex32 (Base 10).
/// </summary>
/// <returns>The common logarithm of this complex number.</returns>
public Complex32 CommonLogarithm()
{
if (IsRealNonNegative())
{
return new Complex32((float)Math.Log10(_real), 0f);
}
return new Complex32(0.5f * (float)Math.Log10(MagnitudeSquared), Phase);
}
/// <summary>
/// Logarithm of this Complex32 with custom base.
/// </summary>
/// <returns>The logarithm of this complex number.</returns>
public Complex32 Logarithm(float baseValue) => NaturalLogarithm() / (float)Math.Log(baseValue);
/// <summary>
/// Exponential of this Complex32 (exp(x), E^x).
/// </summary>
/// <returns>
/// The exponential of this complex number.
/// </returns>
public Complex32 Exponential()
{
double exp = Math.Exp(_real);
if (IsReal())
{
return new Complex32((float)exp, 0f);
}
return new Complex32(
(float)(exp * Math.Cos(_imag)),
(float)(exp * Math.Sin(_imag)));
}
/// <summary>
/// Returns the real component of the product of this Complex32 with other.
/// </summary>
/// <returns>
/// The real component of the product.
/// </returns>
public float RealProduct(in Complex32 other) => _real * other._real - _imag * other._imag;
/// <summary>
/// Computes the conjugate of a complex number and returns the result.
/// </summary>
public Complex32 Conjugate() => new Complex32(_real, -_imag);
/// <summary>
/// Returns the multiplicative inverse of a complex number.
/// </summary>
public Complex32 Reciprocal() => IsZero() ? Zero : 1f / this;
/// <summary>
/// The Square Root (power 1/2) of this Complex32
/// </summary>
/// <returns>
/// The square root of this complex number.
/// </returns>
public Complex32 SquareRoot()
{
if (IsRealNonNegative())
{
return new Complex32((float)Math.Sqrt(_real), 0f);
}
Complex32 result;
double absReal = Math.Abs(Real);
double absImag = Math.Abs(Imaginary);
double w;
if (absReal >= absImag)
{
double ratio = Imaginary / (double)Real;
w = Math.Sqrt(absReal) * Math.Sqrt(0.5 * (1.0 + Math.Sqrt(1.0 + (ratio * ratio))));
}
else
{
double ratio = Real / (double)Imaginary;
w = Math.Sqrt(absImag) * Math.Sqrt(0.5 * (Math.Abs(ratio) + Math.Sqrt(1.0 + (ratio * ratio))));
}
if (Real >= 0f)
{
result = new Complex32(
(float)w,
(float)(Imaginary / (2.0 * w)));
}
else if (Imaginary >= 0f)
{
result = new Complex32(
(float)(absImag / (2.0 * w)),
(float)w);
}
else
{
result = new Complex32(
(float)(absImag / (2.0 * w)),
-(float)w);
}
return result;
}
/// <summary>
/// Helper method for dividing.
/// </summary>
/// <param name="a">Re first</param>
/// <param name="b">Im first</param>
/// <param name="c">Re second</param>
/// <param name="d">Im second</param>
private static Complex32 InternalDiv(float a, float b, float c, float d, bool swapped)
{
float r = d / c;
float t = 1 / (c + d * r);
float e, f;
if (r != 0f) // one can use r >= float.Epsilon || r <= float.Epsilon instead
{
e = (a + b * r) * t;
f = (b - a * r) * t;
}
else
{
e = (a + d * (b / c)) * t;
f = (b - d * (a / c)) * t;
}
if (swapped)
{
f = -f;
}
return new Complex32(e, f);
}
}
}
| 38.115132 | 222 | 0.546187 | [
"MIT"
] | MicroWorldwide/BGC_Tools | Mathematics/Complex32.cs | 34,763 | C# |
using System;
using System.Windows.Forms;
namespace SuperPutty.Utils
{
/// <summary>
/// Make a text box focus and select all on mouse click, tab in, etc.
/// http://stackoverflow.com/questions/97459/automatically-select-all-text-on-focus-in-winforms-textbox
/// </summary>
public class TextBoxFocusHelper : IDisposable
{
public TextBoxFocusHelper(TextBox txt)
{
this.TextBox = txt;
this.TextBox.GotFocus += TextBox_GotFocus;
this.TextBox.MouseUp += TextBox_MouseUp;
this.TextBox.Leave += TextBox_Leave;
}
void TextBox_MouseUp(object sender, MouseEventArgs e)
{
// Web browsers like Google Chrome select the text on mouse up.
// They only do it if the textbox isn't already focused,
// and if the user hasn't selected all text.
if (!alreadyFocused && this.TextBox.SelectionLength == 0)
{
alreadyFocused = true;
this.TextBox.SelectAll();
}
}
void TextBox_GotFocus(object sender, EventArgs e)
{
// Select all text only if the mouse isn't down.
// This makes tabbing to the textbox give focus.
if (Control.MouseButtons == MouseButtons.None)
{
this.TextBox.SelectAll();
alreadyFocused = true;
}
}
void TextBox_Leave(object sender, EventArgs e)
{
alreadyFocused = false;
}
public void Dispose()
{
this.TextBox.GotFocus -= TextBox_GotFocus;
this.TextBox.MouseUp -= TextBox_MouseUp;
this.TextBox.Leave -= TextBox_Leave;
this.TextBox = null;
}
bool alreadyFocused;
public TextBox TextBox { get; private set; }
}
}
| 31.836066 | 108 | 0.549434 | [
"MIT"
] | Mattlk13/superputty | SuperPutty/Utils/TextBoxFocusHelper.cs | 1,944 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("07. Query Mess")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("07. Query Mess")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d55caa95-8fda-416a-b4c4-c5cc42592feb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.864865 | 84 | 0.741613 | [
"MIT"
] | AneliaDoychinova/Programming-Fundamentals | 12. Regular Expressions (RegEx)/Exercises Regular Expressions/07. Query Mess/Properties/AssemblyInfo.cs | 1,404 | 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.Network.V20160330
{
/// <summary>
/// ApplicationGateways resource
/// </summary>
[AzureNativeResourceType("azure-native:network/v20160330:ApplicationGateway")]
public partial class ApplicationGateway : Pulumi.CustomResource
{
/// <summary>
/// Gets or sets backend address pool of application gateway resource
/// </summary>
[Output("backendAddressPools")]
public Output<ImmutableArray<Outputs.ApplicationGatewayBackendAddressPoolResponse>> BackendAddressPools { get; private set; } = null!;
/// <summary>
/// Gets or sets backend http settings of application gateway resource
/// </summary>
[Output("backendHttpSettingsCollection")]
public Output<ImmutableArray<Outputs.ApplicationGatewayBackendHttpSettingsResponse>> BackendHttpSettingsCollection { get; private set; } = null!;
/// <summary>
/// Gets a unique read-only string that changes whenever the resource is updated
/// </summary>
[Output("etag")]
public Output<string?> Etag { get; private set; } = null!;
/// <summary>
/// Gets or sets frontend IP addresses of application gateway resource
/// </summary>
[Output("frontendIPConfigurations")]
public Output<ImmutableArray<Outputs.ApplicationGatewayFrontendIPConfigurationResponse>> FrontendIPConfigurations { get; private set; } = null!;
/// <summary>
/// Gets or sets frontend ports of application gateway resource
/// </summary>
[Output("frontendPorts")]
public Output<ImmutableArray<Outputs.ApplicationGatewayFrontendPortResponse>> FrontendPorts { get; private set; } = null!;
/// <summary>
/// Gets or sets subnets of application gateway resource
/// </summary>
[Output("gatewayIPConfigurations")]
public Output<ImmutableArray<Outputs.ApplicationGatewayIPConfigurationResponse>> GatewayIPConfigurations { get; private set; } = null!;
/// <summary>
/// Gets or sets HTTP listeners of application gateway resource
/// </summary>
[Output("httpListeners")]
public Output<ImmutableArray<Outputs.ApplicationGatewayHttpListenerResponse>> HttpListeners { get; private set; } = null!;
/// <summary>
/// Resource location
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Gets operational state of application gateway resource
/// </summary>
[Output("operationalState")]
public Output<string> OperationalState { get; private set; } = null!;
/// <summary>
/// Gets or sets probes of application gateway resource
/// </summary>
[Output("probes")]
public Output<ImmutableArray<Outputs.ApplicationGatewayProbeResponse>> Probes { get; private set; } = null!;
/// <summary>
/// Gets or sets Provisioning state of the ApplicationGateway resource Updating/Deleting/Failed
/// </summary>
[Output("provisioningState")]
public Output<string?> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Gets or sets request routing rules of application gateway resource
/// </summary>
[Output("requestRoutingRules")]
public Output<ImmutableArray<Outputs.ApplicationGatewayRequestRoutingRuleResponse>> RequestRoutingRules { get; private set; } = null!;
/// <summary>
/// Gets or sets resource GUID property of the ApplicationGateway resource
/// </summary>
[Output("resourceGuid")]
public Output<string?> ResourceGuid { get; private set; } = null!;
/// <summary>
/// Gets or sets sku of application gateway resource
/// </summary>
[Output("sku")]
public Output<Outputs.ApplicationGatewaySkuResponse?> Sku { get; private set; } = null!;
/// <summary>
/// Gets or sets ssl certificates of application gateway resource
/// </summary>
[Output("sslCertificates")]
public Output<ImmutableArray<Outputs.ApplicationGatewaySslCertificateResponse>> SslCertificates { get; private set; } = null!;
/// <summary>
/// Resource tags
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Gets or sets URL path map of application gateway resource
/// </summary>
[Output("urlPathMaps")]
public Output<ImmutableArray<Outputs.ApplicationGatewayUrlPathMapResponse>> UrlPathMaps { get; private set; } = null!;
/// <summary>
/// Create a ApplicationGateway resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ApplicationGateway(string name, ApplicationGatewayArgs args, CustomResourceOptions? options = null)
: base("azure-native:network/v20160330:ApplicationGateway", name, args ?? new ApplicationGatewayArgs(), MakeResourceOptions(options, ""))
{
}
private ApplicationGateway(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:network/v20160330:ApplicationGateway", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network/v20160330:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/latest:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/latest:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20150501preview:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20150501preview:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20150615:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20150615:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20160601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20160901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20161201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20161201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20170301:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170301:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20170601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20170801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20170901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20171001:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171001:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20171101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20181001:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20181101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20181201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20191101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20191201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200301:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200501:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:ApplicationGateway"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ApplicationGateway resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ApplicationGateway Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new ApplicationGateway(name, id, options);
}
}
public sealed class ApplicationGatewayArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the ApplicationGateway.
/// </summary>
[Input("applicationGatewayName")]
public Input<string>? ApplicationGatewayName { get; set; }
[Input("backendAddressPools")]
private InputList<Inputs.ApplicationGatewayBackendAddressPoolArgs>? _backendAddressPools;
/// <summary>
/// Gets or sets backend address pool of application gateway resource
/// </summary>
public InputList<Inputs.ApplicationGatewayBackendAddressPoolArgs> BackendAddressPools
{
get => _backendAddressPools ?? (_backendAddressPools = new InputList<Inputs.ApplicationGatewayBackendAddressPoolArgs>());
set => _backendAddressPools = value;
}
[Input("backendHttpSettingsCollection")]
private InputList<Inputs.ApplicationGatewayBackendHttpSettingsArgs>? _backendHttpSettingsCollection;
/// <summary>
/// Gets or sets backend http settings of application gateway resource
/// </summary>
public InputList<Inputs.ApplicationGatewayBackendHttpSettingsArgs> BackendHttpSettingsCollection
{
get => _backendHttpSettingsCollection ?? (_backendHttpSettingsCollection = new InputList<Inputs.ApplicationGatewayBackendHttpSettingsArgs>());
set => _backendHttpSettingsCollection = value;
}
/// <summary>
/// Gets a unique read-only string that changes whenever the resource is updated
/// </summary>
[Input("etag")]
public Input<string>? Etag { get; set; }
[Input("frontendIPConfigurations")]
private InputList<Inputs.ApplicationGatewayFrontendIPConfigurationArgs>? _frontendIPConfigurations;
/// <summary>
/// Gets or sets frontend IP addresses of application gateway resource
/// </summary>
public InputList<Inputs.ApplicationGatewayFrontendIPConfigurationArgs> FrontendIPConfigurations
{
get => _frontendIPConfigurations ?? (_frontendIPConfigurations = new InputList<Inputs.ApplicationGatewayFrontendIPConfigurationArgs>());
set => _frontendIPConfigurations = value;
}
[Input("frontendPorts")]
private InputList<Inputs.ApplicationGatewayFrontendPortArgs>? _frontendPorts;
/// <summary>
/// Gets or sets frontend ports of application gateway resource
/// </summary>
public InputList<Inputs.ApplicationGatewayFrontendPortArgs> FrontendPorts
{
get => _frontendPorts ?? (_frontendPorts = new InputList<Inputs.ApplicationGatewayFrontendPortArgs>());
set => _frontendPorts = value;
}
[Input("gatewayIPConfigurations")]
private InputList<Inputs.ApplicationGatewayIPConfigurationArgs>? _gatewayIPConfigurations;
/// <summary>
/// Gets or sets subnets of application gateway resource
/// </summary>
public InputList<Inputs.ApplicationGatewayIPConfigurationArgs> GatewayIPConfigurations
{
get => _gatewayIPConfigurations ?? (_gatewayIPConfigurations = new InputList<Inputs.ApplicationGatewayIPConfigurationArgs>());
set => _gatewayIPConfigurations = value;
}
[Input("httpListeners")]
private InputList<Inputs.ApplicationGatewayHttpListenerArgs>? _httpListeners;
/// <summary>
/// Gets or sets HTTP listeners of application gateway resource
/// </summary>
public InputList<Inputs.ApplicationGatewayHttpListenerArgs> HttpListeners
{
get => _httpListeners ?? (_httpListeners = new InputList<Inputs.ApplicationGatewayHttpListenerArgs>());
set => _httpListeners = value;
}
/// <summary>
/// Resource Id
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Resource location
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
[Input("probes")]
private InputList<Inputs.ApplicationGatewayProbeArgs>? _probes;
/// <summary>
/// Gets or sets probes of application gateway resource
/// </summary>
public InputList<Inputs.ApplicationGatewayProbeArgs> Probes
{
get => _probes ?? (_probes = new InputList<Inputs.ApplicationGatewayProbeArgs>());
set => _probes = value;
}
/// <summary>
/// Gets or sets Provisioning state of the ApplicationGateway resource Updating/Deleting/Failed
/// </summary>
[Input("provisioningState")]
public Input<string>? ProvisioningState { get; set; }
[Input("requestRoutingRules")]
private InputList<Inputs.ApplicationGatewayRequestRoutingRuleArgs>? _requestRoutingRules;
/// <summary>
/// Gets or sets request routing rules of application gateway resource
/// </summary>
public InputList<Inputs.ApplicationGatewayRequestRoutingRuleArgs> RequestRoutingRules
{
get => _requestRoutingRules ?? (_requestRoutingRules = new InputList<Inputs.ApplicationGatewayRequestRoutingRuleArgs>());
set => _requestRoutingRules = value;
}
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// Gets or sets resource GUID property of the ApplicationGateway resource
/// </summary>
[Input("resourceGuid")]
public Input<string>? ResourceGuid { get; set; }
/// <summary>
/// Gets or sets sku of application gateway resource
/// </summary>
[Input("sku")]
public Input<Inputs.ApplicationGatewaySkuArgs>? Sku { get; set; }
[Input("sslCertificates")]
private InputList<Inputs.ApplicationGatewaySslCertificateArgs>? _sslCertificates;
/// <summary>
/// Gets or sets ssl certificates of application gateway resource
/// </summary>
public InputList<Inputs.ApplicationGatewaySslCertificateArgs> SslCertificates
{
get => _sslCertificates ?? (_sslCertificates = new InputList<Inputs.ApplicationGatewaySslCertificateArgs>());
set => _sslCertificates = value;
}
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
[Input("urlPathMaps")]
private InputList<Inputs.ApplicationGatewayUrlPathMapArgs>? _urlPathMaps;
/// <summary>
/// Gets or sets URL path map of application gateway resource
/// </summary>
public InputList<Inputs.ApplicationGatewayUrlPathMapArgs> UrlPathMaps
{
get => _urlPathMaps ?? (_urlPathMaps = new InputList<Inputs.ApplicationGatewayUrlPathMapArgs>());
set => _urlPathMaps = value;
}
public ApplicationGatewayArgs()
{
}
}
}
| 50.93379 | 154 | 0.633242 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Network/V20160330/ApplicationGateway.cs | 22,309 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osuTK;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class TestSceneSpinner : OsuSkinnableTestScene
{
private int depthIndex;
private TestDrawableSpinner drawableSpinner;
[TestCase(true)]
[TestCase(false)]
public void TestVariousSpinners(bool autoplay)
{
string term = autoplay ? "Hit" : "Miss";
AddStep($"{term} Big", () => SetContents(() => testSingle(2, autoplay)));
AddStep($"{term} Medium", () => SetContents(() => testSingle(5, autoplay)));
AddStep($"{term} Small", () => SetContents(() => testSingle(7, autoplay)));
}
[TestCase(false)]
[TestCase(true)]
public void TestLongSpinner(bool autoplay)
{
AddStep("Very short spinner", () => SetContents(() => testSingle(5, autoplay, 2000)));
AddUntilStep("Wait for completion", () => drawableSpinner.Result.HasResult);
AddUntilStep("Check correct progress", () => drawableSpinner.Progress == (autoplay ? 1 : 0));
}
[TestCase(false)]
[TestCase(true)]
public void TestSuperShortSpinner(bool autoplay)
{
AddStep("Very short spinner", () => SetContents(() => testSingle(5, autoplay, 200)));
AddUntilStep("Wait for completion", () => drawableSpinner.Result.HasResult);
AddUntilStep("Short spinner implicitly completes", () => drawableSpinner.Progress == 1);
}
private Drawable testSingle(float circleSize, bool auto = false, double length = 3000)
{
const double delay = 2000;
var spinner = new Spinner
{
StartTime = Time.Current + delay,
EndTime = Time.Current + delay + length
};
spinner.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty { CircleSize = circleSize });
drawableSpinner = new TestDrawableSpinner(spinner, auto)
{
Anchor = Anchor.Centre,
Depth = depthIndex++,
Scale = new Vector2(0.75f)
};
foreach (var mod in SelectedMods.Value.OfType<IApplicableToDrawableHitObjects>())
mod.ApplyToDrawableHitObjects(new[] { drawableSpinner });
return drawableSpinner;
}
private class TestDrawableSpinner : DrawableSpinner
{
private readonly bool auto;
public TestDrawableSpinner(Spinner s, bool auto)
: base(s)
{
this.auto = auto;
}
protected override void Update()
{
base.Update();
if (auto)
RotationTracker.AddRotation((float)(Clock.ElapsedFrameTime * 3));
}
}
}
}
| 35.326316 | 110 | 0.56615 | [
"MIT"
] | Airkek/osu | osu.Game.Rulesets.Osu.Tests/TestSceneSpinner.cs | 3,264 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{
public class MaxRequestBufferSizeTests : LoggedTest
{
// The client is typically paused after uploading this many bytes:
//
// OS MaxRequestBufferSize (MB) connectionAdapter Transport min pause (MB) max pause (MB)
// --------------- ------------------------- ----------------- --------- -------------- --------------
// Windows 10 1803 1 false Libuv 1.7 3.3
// Windows 10 1803 1 false Sockets 1.7 4.4
// Windows 10 1803 1 true Libuv 3.0 8.4
// Windows 10 1803 1 true Sockets 3.2 9.0
//
// Windows 10 1803 5 false Libuv 6 13
// Windows 10 1803 5 false Sockets 7 24
// Windows 10 1803 5 true Libuv 12 12
// Windows 10 1803 5 true Sockets 12 36
// Ubuntu 18.04 5 false Libuv 13 15
// Ubuntu 18.04 5 false Sockets 13 15
// Ubuntu 18.04 5 true Libuv 19 20
// Ubuntu 18.04 5 true Sockets 18 20
// macOS 10.13.4 5 false Libuv 6 6
// macOS 10.13.4 5 false Sockets 6 6
// macOS 10.13.4 5 true Libuv 11 11
// macOS 10.13.4 5 true Sockets 11 11
//
// When connectionAdapter=true, the MaxRequestBufferSize is set on two pipes, so it's effectively doubled.
//
// To ensure reliability, _dataLength must be greater than the largest "max pause" in any configuration
private const int _dataLength = 100 * 1024 * 1024;
private static readonly string[] _requestLines = new[]
{
"POST / HTTP/1.1\r\n",
"Host: \r\n",
$"Content-Length: {_dataLength}\r\n",
"\r\n"
};
public static IEnumerable<object[]> LargeUploadData
{
get
{
var totalHeaderSize = 0;
for (var i = 1; i < _requestLines.Length - 1; i++)
{
totalHeaderSize += _requestLines[i].Length;
}
var maxRequestBufferSizeValues = new Tuple<long?, bool>[] {
// Smallest buffer that can hold the test request headers without causing
// the server to hang waiting for the end of the request line or
// a header line.
Tuple.Create((long?)totalHeaderSize, true),
// Small buffer, but large enough to hold all request headers.
Tuple.Create((long?)16 * 1024, true),
// Default buffer.
Tuple.Create((long?)1024 * 1024, true),
// Larger than default, but still significantly lower than data, so client should be paused.
Tuple.Create((long?)5 * 1024 * 1024, true),
// Even though maxRequestBufferSize < _dataLength, client should not be paused since the
// OS-level buffers in client and/or server will handle the overflow.
Tuple.Create((long?)_dataLength - 1, false),
// Buffer is exactly the same size as data. Exposed race condition where
// the connection was resumed after socket was disconnected.
Tuple.Create((long?)_dataLength, false),
// Largest possible buffer, should never trigger backpressure.
Tuple.Create((long?)long.MaxValue, false),
// Disables all code related to computing and limiting the size of the input buffer.
Tuple.Create((long?)null, false)
};
var sslValues = new[] { true, false };
return from maxRequestBufferSize in maxRequestBufferSizeValues
from ssl in sslValues
select new object[] {
maxRequestBufferSize.Item1,
ssl,
maxRequestBufferSize.Item2
};
}
}
[Theory]
[MemberData(nameof(LargeUploadData))]
[QuarantinedTest] // This is inherently flaky and should never be unquarantined.
public async Task LargeUpload(long? maxRequestBufferSize, bool connectionAdapter, bool expectPause)
{
// Parameters
var data = new byte[_dataLength];
var bytesWrittenTimeout = TimeSpan.FromMilliseconds(100);
var bytesWrittenPollingInterval = TimeSpan.FromMilliseconds(bytesWrittenTimeout.TotalMilliseconds / 10);
var maxSendSize = 4096;
var startReadingRequestBody = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var clientFinishedSendingRequestBody = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var lastBytesWritten = DateTime.MaxValue;
var memoryPoolFactory = new DiagnosticMemoryPoolFactory(allowLateReturn: true);
using (var host = await StartWebHost(maxRequestBufferSize, data, connectionAdapter, startReadingRequestBody, clientFinishedSendingRequestBody, memoryPoolFactory.Create))
{
var port = host.GetPort();
using (var socket = CreateSocket(port))
using (var stream = new NetworkStream(socket))
{
await WritePostRequestHeaders(stream, data.Length);
var bytesWritten = 0;
Func<Task> sendFunc = async () =>
{
while (bytesWritten < data.Length)
{
var size = Math.Min(data.Length - bytesWritten, maxSendSize);
await stream.WriteAsync(data, bytesWritten, size).ConfigureAwait(false);
bytesWritten += size;
lastBytesWritten = DateTime.Now;
}
Assert.Equal(data.Length, bytesWritten);
clientFinishedSendingRequestBody.TrySetResult();
};
var sendTask = sendFunc();
if (expectPause)
{
// The minimum is (maxRequestBufferSize - maxSendSize + 1), since if bytesWritten is
// (maxRequestBufferSize - maxSendSize) or smaller, the client should be able to
// complete another send.
var minimumExpectedBytesWritten = maxRequestBufferSize.Value - maxSendSize + 1;
// The maximum is harder to determine, since there can be OS-level buffers in both the client
// and server, which allow the client to send more than maxRequestBufferSize before getting
// paused. We assume the combined buffers are smaller than the difference between
// data.Length and maxRequestBufferSize.
var maximumExpectedBytesWritten = data.Length - 1;
// Block until the send task has gone a while without writing bytes AND
// the bytes written exceeds the minimum expected. This indicates the server buffer
// is full.
//
// If the send task is paused before the expected number of bytes have been
// written, keep waiting since the pause may have been caused by something else
// like a slow machine.
while ((DateTime.Now - lastBytesWritten) < bytesWrittenTimeout ||
bytesWritten < minimumExpectedBytesWritten)
{
await Task.Delay(bytesWrittenPollingInterval);
}
// Verify the number of bytes written before the client was paused.
Assert.InRange(bytesWritten, minimumExpectedBytesWritten, maximumExpectedBytesWritten);
// Tell server to start reading request body
startReadingRequestBody.TrySetResult();
// Wait for sendTask to finish sending the remaining bytes
await sendTask;
}
else
{
// Ensure all bytes can be sent before the server starts reading
await sendTask;
// Tell server to start reading request body
startReadingRequestBody.TrySetResult();
}
await AssertStreamContains(stream, $"bytesRead: {data.Length}");
}
await host.StopAsync();
}
await memoryPoolFactory.WhenAllBlocksReturned(TestConstants.DefaultTimeout);
}
[Fact]
public async Task ServerShutsDownGracefullyWhenMaxRequestBufferSizeExceeded()
{
// Parameters
var data = new byte[_dataLength];
var bytesWrittenTimeout = TimeSpan.FromMilliseconds(100);
var bytesWrittenPollingInterval = TimeSpan.FromMilliseconds(bytesWrittenTimeout.TotalMilliseconds / 10);
var maxSendSize = 4096;
var startReadingRequestBody = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var clientFinishedSendingRequestBody = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var lastBytesWritten = DateTime.MaxValue;
var memoryPoolFactory = new DiagnosticMemoryPoolFactory(allowLateReturn: true);
using (var host = await StartWebHost(16 * 1024, data, false, startReadingRequestBody, clientFinishedSendingRequestBody, memoryPoolFactory.Create))
{
var port = host.GetPort();
using (var socket = CreateSocket(port))
using (var stream = new NetworkStream(socket))
{
await WritePostRequestHeaders(stream, data.Length);
var bytesWritten = 0;
Func<Task> sendFunc = async () =>
{
while (bytesWritten < data.Length)
{
var size = Math.Min(data.Length - bytesWritten, maxSendSize);
await stream.WriteAsync(data, bytesWritten, size).ConfigureAwait(false);
bytesWritten += size;
lastBytesWritten = DateTime.Now;
}
clientFinishedSendingRequestBody.TrySetResult();
};
var ignore = sendFunc();
// The minimum is (maxRequestBufferSize - maxSendSize + 1), since if bytesWritten is
// (maxRequestBufferSize - maxSendSize) or smaller, the client should be able to
// complete another send.
var minimumExpectedBytesWritten = (16 * 1024) - maxSendSize + 1;
// The maximum is harder to determine, since there can be OS-level buffers in both the client
// and server, which allow the client to send more than maxRequestBufferSize before getting
// paused. We assume the combined buffers are smaller than the difference between
// data.Length and maxRequestBufferSize.
var maximumExpectedBytesWritten = data.Length - 1;
// Block until the send task has gone a while without writing bytes AND
// the bytes written exceeds the minimum expected. This indicates the server buffer
// is full.
//
// If the send task is paused before the expected number of bytes have been
// written, keep waiting since the pause may have been caused by something else
// like a slow machine.
while ((DateTime.Now - lastBytesWritten) < bytesWrittenTimeout ||
bytesWritten < minimumExpectedBytesWritten)
{
await Task.Delay(bytesWrittenPollingInterval);
}
// Verify the number of bytes written before the client was paused.
Assert.InRange(bytesWritten, minimumExpectedBytesWritten, maximumExpectedBytesWritten);
// Dispose host prior to closing connection to verify the server doesn't throw during shutdown
// if a connection no longer has alloc and read callbacks configured.
await host.StopAsync();
host.Dispose();
}
}
// Allow appfunc to unblock
startReadingRequestBody.SetResult();
clientFinishedSendingRequestBody.SetResult();
await memoryPoolFactory.WhenAllBlocksReturned(TestConstants.DefaultTimeout);
}
private async Task<IWebHost> StartWebHost(long? maxRequestBufferSize,
byte[] expectedBody,
bool useConnectionAdapter,
TaskCompletionSource startReadingRequestBody,
TaskCompletionSource clientFinishedSendingRequestBody,
Func<MemoryPool<byte>> memoryPoolFactory = null)
{
var host = TransportSelector.GetWebHostBuilder(memoryPoolFactory, maxRequestBufferSize)
.ConfigureServices(AddTestLogging)
.UseKestrel(options =>
{
options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions =>
{
if (useConnectionAdapter)
{
listenOptions.UsePassThrough();
}
});
options.Limits.MaxRequestBufferSize = maxRequestBufferSize;
if (maxRequestBufferSize.HasValue &&
maxRequestBufferSize.Value < options.Limits.MaxRequestLineSize)
{
options.Limits.MaxRequestLineSize = (int)maxRequestBufferSize;
}
if (maxRequestBufferSize.HasValue &&
maxRequestBufferSize.Value < options.Limits.MaxRequestHeadersTotalSize)
{
options.Limits.MaxRequestHeadersTotalSize = (int)maxRequestBufferSize;
}
options.Limits.MinRequestBodyDataRate = null;
options.Limits.MaxRequestBodySize = _dataLength;
})
.UseContentRoot(Directory.GetCurrentDirectory())
.Configure(app => app.Run(async context =>
{
await startReadingRequestBody.Task.TimeoutAfter(TimeSpan.FromSeconds(120));
var buffer = new byte[expectedBody.Length];
var bytesRead = 0;
while (bytesRead < buffer.Length)
{
bytesRead += await context.Request.Body.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead);
}
await clientFinishedSendingRequestBody.Task.TimeoutAfter(TimeSpan.FromSeconds(120));
// Verify client didn't send extra bytes
if (await context.Request.Body.ReadAsync(new byte[1], 0, 1) != 0)
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsync("Client sent more bytes than expectedBody.Length");
return;
}
await context.Response.WriteAsync($"bytesRead: {bytesRead.ToString()}");
}))
.Build();
await host.StartAsync();
return host;
}
private static Socket CreateSocket(int port)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Timeouts large enough to prevent false positives, but small enough to fail quickly.
socket.SendTimeout = 10 * 1000;
socket.ReceiveTimeout = 120 * 1000;
socket.Connect(IPAddress.Loopback, port);
return socket;
}
private static async Task WritePostRequestHeaders(Stream stream, int contentLength)
{
using (var writer = new StreamWriter(stream, Encoding.ASCII, bufferSize: 1024, leaveOpen: true))
{
foreach (var line in _requestLines)
{
await writer.WriteAsync(line).ConfigureAwait(false);
}
}
}
// THIS IS NOT GENERAL PURPOSE. If the initial characters could repeat, this is broken. However, since we're
// looking for /bytesWritten: \d+/ and the initial "b" cannot occur elsewhere in the pattern, this works.
private static async Task AssertStreamContains(Stream stream, string expectedSubstring)
{
var expectedBytes = Encoding.ASCII.GetBytes(expectedSubstring);
var exptectedLength = expectedBytes.Length;
var responseBuffer = new byte[exptectedLength];
var matchedChars = 0;
while (matchedChars < exptectedLength)
{
var count = await stream.ReadAsync(responseBuffer, 0, exptectedLength - matchedChars).DefaultTimeout();
if (count == 0)
{
Assert.True(false, "Stream completed without expected substring.");
}
for (var i = 0; i < count && matchedChars < exptectedLength; i++)
{
if (responseBuffer[i] == expectedBytes[matchedChars])
{
matchedChars++;
}
else
{
matchedChars = 0;
}
}
}
}
}
}
| 48.987805 | 181 | 0.522629 | [
"Apache-2.0"
] | DeeplyRecursive/aspnetcore | src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs | 20,085 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DocumentDB.V20160319.Inputs
{
/// <summary>
/// Cosmos DB SQL database id object
/// </summary>
public sealed class SqlDatabaseResourceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Name of the Cosmos DB SQL database
/// </summary>
[Input("id", required: true)]
public Input<string> Id { get; set; } = null!;
public SqlDatabaseResourceArgs()
{
}
}
}
| 26.517241 | 81 | 0.643693 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DocumentDB/V20160319/Inputs/SqlDatabaseResourceArgs.cs | 769 | C# |
namespace Suzianna.Rest.Tests.Integration.Model
{
public class CreateUserResponse
{
public int Id { get; set; }
public string Name { get; set; }
public string Job { get; set; }
}
} | 24.111111 | 48 | 0.603687 | [
"Apache-2.0"
] | H-Ahmadi/Suzianna | Code/test/Suzianna.Rest.Tests.Integration/Model/CreateUserResponse.cs | 219 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Engine.Models
{
public class MonsterEncounter
{
public int MonsterID { get; set; }
public int ChanceOfEncountering { get; set; }
public MonsterEncounter(int monsterID, int chanceOfEntercountering)
{
MonsterID = monsterID;
ChanceOfEncountering = ChanceOfEncountering;
}
}
}
| 22.761905 | 75 | 0.669456 | [
"MIT"
] | jun383914/GameLearning | Engine/Models/MonsterEncounter.cs | 480 | C# |
using Moq;
using Noise.RavenDatabase.Logging;
using NUnit.Framework;
using Noise.BaseDatabase.Tests.DataProviders;
using Noise.Infrastructure.Interfaces;
using Noise.RavenDatabase.DataProviders;
namespace Noise.RavenDatabase.Tests.DataProviders {
[TestFixture]
public class InternetStreamProviderTests : BaseInternetStreamProviderTests {
private CommonTestSetup mCommon;
private Mock<ILogRaven> mLog;
[TestFixtureSetUp]
public void FixtureSetup() {
mCommon = new CommonTestSetup();
mCommon.FixtureSetup();
mLog = new Mock<ILogRaven>();
}
[SetUp]
public void Setup() {
mCommon.Setup();
}
[TearDown]
public void Teardown() {
mCommon.Teardown();
}
protected override IInternetStreamProvider CreateSut() {
return ( new InternetStreamProvider( mCommon.DatabaseFactory.Object, mLog.Object ));
}
}
}
| 22.891892 | 87 | 0.753247 | [
"MIT"
] | bswanson58/NoiseMusicSystem | Noise.RavenDatabase.Tests/DataProviders/InternetStreamProviderTests.cs | 849 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace Aliyun.SDK.CCP.CCPClient.Models
{
/**
* 获取文件元数据
*/
public class GetFileRequest : TeaModel {
[NameInMap("drive_id")]
[Validation(Required=true, Pattern="[0-9]+")]
public string DriveId { get; set; }
[NameInMap("file_id")]
[Validation(Required=true, MaxLength=50, Pattern="[a-z0-9.-_]{1,50}")]
public string FileId { get; set; }
[NameInMap("file_path")]
[Validation(Required=false)]
public string FilePath { get; set; }
[NameInMap("image_thumbnail_process")]
[Validation(Required=false)]
public string ImageThumbnailProcess { get; set; }
[NameInMap("image_url_process")]
[Validation(Required=false)]
public string ImageUrlProcess { get; set; }
[NameInMap("share_id")]
[Validation(Required=false)]
public string ShareId { get; set; }
}
}
| 25.047619 | 78 | 0.613118 | [
"Apache-2.0"
] | aliyun/aliyun-ccp | ccppath-sdk/cs/core/Models/GetFileRequest.cs | 1,066 | C# |
using System;
using Hackney.Core.Testing.Shared;
using Moq;
using NUnit.Framework;
using ServiceStack;
using ServiceStack.Redis;
using SingleViewApi.V1.Boundary;
using SingleViewApi.V1.Gateways;
using SingleViewApi.V1.Helpers;
using SingleViewApi.V1.Helpers.Interfaces;
using SingleViewApi.V1.UseCase;
namespace SingleViewApi.Tests.V1.UseCase;
[TestFixture]
public class GetJigsawAuthTokenUseCaseTests : LogCallAspectFixture
{
private Mock<IRedisGateway> _mockRedisGateway;
private Mock<IJigsawGateway> _jigsawGatewayMock;
private Mock<IDecoderHelper> _decoderHelperMock;
private GetJigsawAuthTokenUseCase _classUnderTest;
[SetUp]
public void Setup()
{
_mockRedisGateway = new Mock<IRedisGateway>();
_jigsawGatewayMock = new Mock<IJigsawGateway>();
_decoderHelperMock = new Mock<IDecoderHelper>();
_classUnderTest = new GetJigsawAuthTokenUseCase(_jigsawGatewayMock.Object, _mockRedisGateway.Object, _decoderHelperMock.Object);
}
[Test]
public void ReturnsAuthTokenCachedWhenMatchingHackneyTokenIsProvided()
{
const string hackneyToken = "hackneyToken";
const string redisId = "redisId";
const string jigsawToken = "jigsawToken";
_mockRedisGateway.Setup(x => x.GetValue(hackneyToken)).Returns(jigsawToken);
var result = _classUnderTest.Execute(redisId, hackneyToken).Result;
Assert.That(result.Token, Is.EqualTo(jigsawToken));
}
[Test]
public void UsesRedisIdToFetchCredentialsWhenNoMatchingHackneyTokenProvided()
{
const string hackneyToken = "hackneyToken";
const string mockJigsawUsername = "mockJigsawUsername";
const string mockJigsawPassword = "mockJigsawPassword";
const string redisId = "redisId";
const string jigsawToken = "jigsawToken";
const string encryptedCredentials = "encryptedCredentials";
JigsawCredentials mockJigsawCredentials = new JigsawCredentials
{
Username = mockJigsawUsername,
Password = mockJigsawPassword
};
AuthGatewayResponse mockAuthGatewayResponse = new AuthGatewayResponse
{
Token = jigsawToken
};
_mockRedisGateway.Setup(x => x.GetValue(hackneyToken)).Returns("");
_mockRedisGateway.Setup(x => x.GetValue(redisId)).Returns(encryptedCredentials);
_decoderHelperMock.Setup(x => x.DecodeJigsawCredentials(encryptedCredentials)).Returns(mockJigsawCredentials);
_jigsawGatewayMock.Setup(x => x.GetAuthToken(mockJigsawCredentials)).Returns(mockAuthGatewayResponse.AsTaskResult());
_mockRedisGateway.Setup(x => x.AddValueWithKey(hackneyToken, mockAuthGatewayResponse.Token, 1));
var result = _classUnderTest.Execute(redisId, hackneyToken).Result;
Assert.That(result.Token, Is.EqualTo(jigsawToken));
_jigsawGatewayMock.Verify(x => x.GetAuthToken(mockJigsawCredentials), Times.Once);
_mockRedisGateway.Verify(x => x.AddValueWithKey(hackneyToken, jigsawToken, 1), Times.Once);
}
}
| 38.3375 | 136 | 0.731007 | [
"MIT"
] | LBHackney-IT/single-view-api | SingleViewApi.Tests/V1/UseCase/GetJigsawAuthTokenUseCaseTests.cs | 3,067 | 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 kms-2014-11-01.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.KeyManagementService.Model
{
/// <summary>
/// Container for the parameters to the EnableKeyRotation operation.
/// Enables rotation of the specified customer master key.
/// </summary>
public partial class EnableKeyRotationRequest : AmazonKeyManagementServiceRequest
{
private string _keyId;
/// <summary>
/// Gets and sets the property KeyId.
/// <para>
/// A unique identifier for the customer master key. This value can be a globally unique
/// identifier or the fully specified ARN to a key. <ul> <li>Key ARN Example - arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</li>
/// <li>Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012</li> </ul>
///
/// </para>
/// </summary>
public string KeyId
{
get { return this._keyId; }
set { this._keyId = value; }
}
// Check to see if KeyId property is set
internal bool IsSetKeyId()
{
return this._keyId != null;
}
}
} | 33.333333 | 167 | 0.662 | [
"Apache-2.0"
] | jasoncwik/aws-sdk-net | sdk/src/Services/KeyManagementService/Generated/Model/EnableKeyRotationRequest.cs | 2,000 | C# |
using System;
using System.Collections.Generic;
namespace SDKTemplate
{
static class RecognizerHelper
{
private static Dictionary<string, string> Bcp47ToRecognizerNameDictionary =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "en-US", "Microsoft English (US) Handwriting Recognizer" },
{ "en-GB", "Microsoft English (UK) Handwriting Recognizer" },
{ "en-CA", "Microsoft English (Canada) Handwriting Recognizer" },
{ "en-AU", "Microsoft English (Australia) Handwriting Recognizer" },
{ "de-DE", "Microsoft-Handschrifterkennung - Deutsch" },
{ "de-CH", "Microsoft-Handschrifterkennung - Deutsch (Schweiz)" },
{ "es-ES", "Reconocimiento de escritura a mano en español de Microsoft" },
{ "es-MX", "Reconocedor de escritura en Español (México) de Microsoft" },
{ "es-AR", "Reconocedor de escritura en Español (Argentina) de Microsoft" },
{ "fr", "Reconnaissance d'écriture Microsoft - Français" },
{ "fr-FR", "Reconnaissance d'écriture Microsoft - Français" },
{ "ja", "Microsoft 日本語手書き認識エンジン" },
{ "ja-JP", "Microsoft 日本語手書き認識エンジン" },
{ "it", "Riconoscimento grafia italiana Microsoft" },
{ "nl-NL", "Microsoft Nederlandstalige handschriftherkenning" },
{ "nl-BE", "Microsoft Nederlandstalige (België) handschriftherkenning" },
{ "zh", "Microsoft 中文(简体)手写识别器" },
{ "zh-CN", "Microsoft 中文(简体)手写识别器" },
{ "zh-Hans-CN", "Microsoft 中文(简体)手写识别器" },
{ "zh-Hant", "Microsoft 中文(繁體)手寫辨識器" },
{ "zh-TW", "Microsoft 中文(繁體)手寫辨識器" },
{ "ru", "Microsoft система распознавания русского рукописного ввода" },
{ "pt-BR", "Reconhecedor de Manuscrito da Microsoft para Português (Brasil)" },
{ "pt-PT", "Reconhecedor de escrita manual da Microsoft para português" },
{ "ko", "Microsoft 한글 필기 인식기" },
{ "pl", "System rozpoznawania polskiego pisma odręcznego firmy Microsoft" },
{ "sv", "Microsoft Handskriftstolk för svenska" },
{ "cs", "Microsoft rozpoznávač rukopisu pro český jazyk" },
{ "da", "Microsoft Genkendelse af dansk håndskrift" },
{ "nb", "Microsoft Håndskriftsgjenkjenner for norsk" },
{ "nn", "Microsoft Håndskriftsgjenkjenner for nynorsk" },
{ "fi", "Microsoftin suomenkielinen käsinkirjoituksen tunnistus" },
{ "ro", "Microsoft recunoaştere grafie - Română" },
{ "hr", "Microsoftov hrvatski rukopisni prepoznavač" },
{ "sr-Latn", "Microsoft prepoznavač rukopisa za srpski (latinica)" },
{ "sr", "Microsoft препознавач рукописа за српски (ћирилица)" },
{ "ca", "Reconeixedor d'escriptura manual en català de Microsoft" },
};
public static string LanguageTagToRecognizerName(string bcp47tag)
{
string recognizerName;
if (!Bcp47ToRecognizerNameDictionary.TryGetValue(bcp47tag, out recognizerName))
{
recognizerName = string.Empty;
}
return recognizerName;
}
}
}
| 56.274194 | 96 | 0.558326 | [
"MIT"
] | 544146/Windows-universal-samples | Samples/SimpleInk/cs/RecognizerHelper.cs | 3,688 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Network.Models;
namespace Azure.ResourceManager.Network
{
/// <summary> A Class representing a Subnet along with the instance operations that can be performed on it. </summary>
public partial class Subnet : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="Subnet"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string virtualNetworkName, string subnetName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _subnetClientDiagnostics;
private readonly SubnetsRestOperations _subnetRestClient;
private readonly ClientDiagnostics _resourceNavigationLinksClientDiagnostics;
private readonly ResourceNavigationLinksRestOperations _resourceNavigationLinksRestClient;
private readonly ClientDiagnostics _serviceAssociationLinksClientDiagnostics;
private readonly ServiceAssociationLinksRestOperations _serviceAssociationLinksRestClient;
private readonly SubnetData _data;
/// <summary> Initializes a new instance of the <see cref="Subnet"/> class for mocking. </summary>
protected Subnet()
{
}
/// <summary> Initializes a new instance of the <see cref = "Subnet"/> class. </summary>
/// <param name="armClient"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal Subnet(ArmClient armClient, SubnetData data) : this(armClient, new ResourceIdentifier(data.Id))
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="Subnet"/> class. </summary>
/// <param name="armClient"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal Subnet(ArmClient armClient, ResourceIdentifier id) : base(armClient, id)
{
_subnetClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Network", ResourceType.Namespace, DiagnosticOptions);
ArmClient.TryGetApiVersion(ResourceType, out string subnetApiVersion);
_subnetRestClient = new SubnetsRestOperations(_subnetClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, subnetApiVersion);
_resourceNavigationLinksClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Network", ProviderConstants.DefaultProviderNamespace, DiagnosticOptions);
_resourceNavigationLinksRestClient = new ResourceNavigationLinksRestOperations(_resourceNavigationLinksClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri);
_serviceAssociationLinksClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Network", ProviderConstants.DefaultProviderNamespace, DiagnosticOptions);
_serviceAssociationLinksRestClient = new ServiceAssociationLinksRestOperations(_serviceAssociationLinksClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Network/virtualNetworks/subnets";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual SubnetData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary> Gets the specified subnet by virtual network and resource group. </summary>
/// <param name="expand"> Expands referenced resources. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<Subnet>> GetAsync(string expand = null, CancellationToken cancellationToken = default)
{
using var scope = _subnetClientDiagnostics.CreateScope("Subnet.Get");
scope.Start();
try
{
var response = await _subnetRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, expand, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _subnetClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new Subnet(ArmClient, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets the specified subnet by virtual network and resource group. </summary>
/// <param name="expand"> Expands referenced resources. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<Subnet> Get(string expand = null, CancellationToken cancellationToken = default)
{
using var scope = _subnetClientDiagnostics.CreateScope("Subnet.Get");
scope.Start();
try
{
var response = _subnetRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, expand, cancellationToken);
if (response.Value == null)
throw _subnetClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new Subnet(ArmClient, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists all available geo-locations. </summary>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of locations that may take multiple service requests to iterate over. </returns>
public async virtual Task<IEnumerable<AzureLocation>> GetAvailableLocationsAsync(CancellationToken cancellationToken = default)
{
using var scope = _subnetClientDiagnostics.CreateScope("Subnet.GetAvailableLocations");
scope.Start();
try
{
return await ListAvailableLocationsAsync(ResourceType, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists all available geo-locations. </summary>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of locations that may take multiple service requests to iterate over. </returns>
public virtual IEnumerable<AzureLocation> GetAvailableLocations(CancellationToken cancellationToken = default)
{
using var scope = _subnetClientDiagnostics.CreateScope("Subnet.GetAvailableLocations");
scope.Start();
try
{
return ListAvailableLocations(ResourceType, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes the specified subnet. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<SubnetDeleteOperation> DeleteAsync(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _subnetClientDiagnostics.CreateScope("Subnet.Delete");
scope.Start();
try
{
var response = await _subnetRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new SubnetDeleteOperation(_subnetClientDiagnostics, Pipeline, _subnetRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes the specified subnet. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual SubnetDeleteOperation Delete(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _subnetClientDiagnostics.CreateScope("Subnet.Delete");
scope.Start();
try
{
var response = _subnetRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
var operation = new SubnetDeleteOperation(_subnetClientDiagnostics, Pipeline, _subnetRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response);
if (waitForCompletion)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Prepares a subnet by applying network intent policies. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="prepareNetworkPoliciesRequestParameters"> Parameters supplied to prepare subnet by applying network intent policies. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="prepareNetworkPoliciesRequestParameters"/> is null. </exception>
public async virtual Task<SubnetPrepareNetworkPoliciesOperation> PrepareNetworkPoliciesAsync(bool waitForCompletion, PrepareNetworkPoliciesRequest prepareNetworkPoliciesRequestParameters, CancellationToken cancellationToken = default)
{
if (prepareNetworkPoliciesRequestParameters == null)
{
throw new ArgumentNullException(nameof(prepareNetworkPoliciesRequestParameters));
}
using var scope = _subnetClientDiagnostics.CreateScope("Subnet.PrepareNetworkPolicies");
scope.Start();
try
{
var response = await _subnetRestClient.PrepareNetworkPoliciesAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, prepareNetworkPoliciesRequestParameters, cancellationToken).ConfigureAwait(false);
var operation = new SubnetPrepareNetworkPoliciesOperation(_subnetClientDiagnostics, Pipeline, _subnetRestClient.CreatePrepareNetworkPoliciesRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, prepareNetworkPoliciesRequestParameters).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Prepares a subnet by applying network intent policies. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="prepareNetworkPoliciesRequestParameters"> Parameters supplied to prepare subnet by applying network intent policies. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="prepareNetworkPoliciesRequestParameters"/> is null. </exception>
public virtual SubnetPrepareNetworkPoliciesOperation PrepareNetworkPolicies(bool waitForCompletion, PrepareNetworkPoliciesRequest prepareNetworkPoliciesRequestParameters, CancellationToken cancellationToken = default)
{
if (prepareNetworkPoliciesRequestParameters == null)
{
throw new ArgumentNullException(nameof(prepareNetworkPoliciesRequestParameters));
}
using var scope = _subnetClientDiagnostics.CreateScope("Subnet.PrepareNetworkPolicies");
scope.Start();
try
{
var response = _subnetRestClient.PrepareNetworkPolicies(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, prepareNetworkPoliciesRequestParameters, cancellationToken);
var operation = new SubnetPrepareNetworkPoliciesOperation(_subnetClientDiagnostics, Pipeline, _subnetRestClient.CreatePrepareNetworkPoliciesRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, prepareNetworkPoliciesRequestParameters).Request, response);
if (waitForCompletion)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Unprepares a subnet by removing network intent policies. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="unprepareNetworkPoliciesRequestParameters"> Parameters supplied to unprepare subnet to remove network intent policies. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="unprepareNetworkPoliciesRequestParameters"/> is null. </exception>
public async virtual Task<SubnetUnprepareNetworkPoliciesOperation> UnprepareNetworkPoliciesAsync(bool waitForCompletion, UnprepareNetworkPoliciesRequest unprepareNetworkPoliciesRequestParameters, CancellationToken cancellationToken = default)
{
if (unprepareNetworkPoliciesRequestParameters == null)
{
throw new ArgumentNullException(nameof(unprepareNetworkPoliciesRequestParameters));
}
using var scope = _subnetClientDiagnostics.CreateScope("Subnet.UnprepareNetworkPolicies");
scope.Start();
try
{
var response = await _subnetRestClient.UnprepareNetworkPoliciesAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, unprepareNetworkPoliciesRequestParameters, cancellationToken).ConfigureAwait(false);
var operation = new SubnetUnprepareNetworkPoliciesOperation(_subnetClientDiagnostics, Pipeline, _subnetRestClient.CreateUnprepareNetworkPoliciesRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, unprepareNetworkPoliciesRequestParameters).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Unprepares a subnet by removing network intent policies. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="unprepareNetworkPoliciesRequestParameters"> Parameters supplied to unprepare subnet to remove network intent policies. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="unprepareNetworkPoliciesRequestParameters"/> is null. </exception>
public virtual SubnetUnprepareNetworkPoliciesOperation UnprepareNetworkPolicies(bool waitForCompletion, UnprepareNetworkPoliciesRequest unprepareNetworkPoliciesRequestParameters, CancellationToken cancellationToken = default)
{
if (unprepareNetworkPoliciesRequestParameters == null)
{
throw new ArgumentNullException(nameof(unprepareNetworkPoliciesRequestParameters));
}
using var scope = _subnetClientDiagnostics.CreateScope("Subnet.UnprepareNetworkPolicies");
scope.Start();
try
{
var response = _subnetRestClient.UnprepareNetworkPolicies(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, unprepareNetworkPoliciesRequestParameters, cancellationToken);
var operation = new SubnetUnprepareNetworkPoliciesOperation(_subnetClientDiagnostics, Pipeline, _subnetRestClient.CreateUnprepareNetworkPoliciesRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, unprepareNetworkPoliciesRequestParameters).Request, response);
if (waitForCompletion)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets a list of resource navigation links for a subnet. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="ResourceNavigationLink" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<ResourceNavigationLink> GetResourceNavigationLinksAsync(CancellationToken cancellationToken = default)
{
async Task<Page<ResourceNavigationLink>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _resourceNavigationLinksClientDiagnostics.CreateScope("Subnet.GetResourceNavigationLinks");
scope.Start();
try
{
var response = await _resourceNavigationLinksRestClient.ListAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null);
}
/// <summary> Gets a list of resource navigation links for a subnet. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="ResourceNavigationLink" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<ResourceNavigationLink> GetResourceNavigationLinks(CancellationToken cancellationToken = default)
{
Page<ResourceNavigationLink> FirstPageFunc(int? pageSizeHint)
{
using var scope = _resourceNavigationLinksClientDiagnostics.CreateScope("Subnet.GetResourceNavigationLinks");
scope.Start();
try
{
var response = _resourceNavigationLinksRestClient.List(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, null);
}
/// <summary> Gets a list of service association links for a subnet. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="ServiceAssociationLink" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<ServiceAssociationLink> GetServiceAssociationLinksAsync(CancellationToken cancellationToken = default)
{
async Task<Page<ServiceAssociationLink>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _serviceAssociationLinksClientDiagnostics.CreateScope("Subnet.GetServiceAssociationLinks");
scope.Start();
try
{
var response = await _serviceAssociationLinksRestClient.ListAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null);
}
/// <summary> Gets a list of service association links for a subnet. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="ServiceAssociationLink" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<ServiceAssociationLink> GetServiceAssociationLinks(CancellationToken cancellationToken = default)
{
Page<ServiceAssociationLink> FirstPageFunc(int? pageSizeHint)
{
using var scope = _serviceAssociationLinksClientDiagnostics.CreateScope("Subnet.GetServiceAssociationLinks");
scope.Start();
try
{
var response = _serviceAssociationLinksRestClient.List(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, null);
}
}
}
| 57.901408 | 296 | 0.665613 | [
"MIT"
] | git-thomasdolan/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/Subnet.cs | 24,666 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 02.05.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.GreaterThanOrEqual.Complete.NullableInt32.NullableInt16{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.Int32>;
using T_DATA2 =System.Nullable<System.Int16>;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__03__NV
public static class TestSet_504__param__03__NV
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => vv1 /*OP{*/ >= /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001
//-----------------------------------------------------------------------
[Test]
public static void Test_002()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ >= /*}OP*/ vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002
};//class TestSet_504__param__03__NV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.GreaterThanOrEqual.Complete.NullableInt32.NullableInt16
| 28.166667 | 153 | 0.538757 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/GreaterThanOrEqual/Complete/NullableInt32/NullableInt16/TestSet_504__param__03__NV.cs | 3,382 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.WsFederation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using wsfed_issue.Providers;
namespace wsfed_issue {
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
// Add framework services.
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDataProtection();
services.Configure<ForwardedHeadersOptions>(
ConfigureForwardedHeaders);
AddAuthenticationTo(services);
// Simple example with dependency injection for a data provider.
services.AddSingleton<IWeatherProvider, WeatherProviderFake>();
}
private void ConfigureForwardedHeaders(ForwardedHeadersOptions options) {
options.KnownNetworks.Add(Network);
}
private IPNetwork _network;
private IPNetwork Network => _network ?? (_network = new IPNetwork(LocalAddress, 8));
private IPAddress LocalAddress => NetworkInterface
.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up)
.Where(n => n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.SelectMany(n => n.GetIPProperties()?.GatewayAddresses)
.Select(ToGatewayAddress)
.FirstOrDefault(a => a != null);
private IPAddress ToGatewayAddress(GatewayIPAddressInformation info) {
var firstThreeOctets = info?.Address.GetAddressBytes().Take(3);
var octets = firstThreeOctets.Append((byte)0).ToArray();
return new IPAddress(octets).MapToIPv6();
}
private void AddAuthenticationTo(IServiceCollection services) {
var builder = services.AddAuthentication(ConfigureAuthentication);
builder.AddCookie();
builder.AddWsFederation(
WsFederationDefaults.AuthenticationScheme,
"Org Auth",
ConfigureWsFederation);
}
private void ConfigureAuthentication(AuthenticationOptions auth) {
auth.DefaultScheme =
CookieAuthenticationDefaults.AuthenticationScheme;
auth.DefaultChallengeScheme =
WsFederationDefaults.AuthenticationScheme;
}
private void ConfigureWsFederation(WsFederationOptions options) {
// MetadataAddress represents the Active Directory instance used to authenticate users.
options.MetadataAddress = Configuration["WsAuthMetadataAddress"];
// Wtrealm is the app's identifier in the Active Directory instance.
// For ADFS, use the relying party's identifier, its WS-Federation Passive protocol URL:
options.Wtrealm = Configuration["WsAuthrealm"];
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env) {
if (env.IsDevelopment())
ConfigureDevelopmentFor(app);
else
app.UseExceptionHandler("/Home/Error");
app.UseStaticFiles();
var forwardedOptions = new ForwardedHeadersOptions {
ForwardedHeaders = ForwardedHeaders.XForwardedFor
| ForwardedHeaders.XForwardedProto
};
app.UseForwardedHeaders(forwardedOptions);
//app.Use(Middleware);
app.UseAuthentication();
app.UseMvc(ConfigureRoutes);
}
private void ConfigureDevelopmentFor(IApplicationBuilder app) {
var webpackOptions = new WebpackDevMiddlewareOptions {
HotModuleReplacement = true,
};
// Webpack initialization with hot-reload.
app.UseWebpackDevMiddleware(webpackOptions);
app.UseDeveloperExceptionPage();
}
private void ConfigureRoutes(IRouteBuilder routes) {
routes.MapRoute(
"default",
"{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
"spa-fallback",
new {controller = "Home", action = "Index"});
}
private async Task Middleware(HttpContext context, Func<Task> next) {
var newline = Environment.NewLine;
var request = context.Request;
var response = context.Response;
response.ContentType = "text/plain";
// Request method, scheme, and path
await response.WriteAsync(
$"Request Method: {request.Method}{newline}");
await response.WriteAsync(
$"Request Scheme: {request.Scheme}{newline}");
await response.WriteAsync($"Request Path: {request.Path}{newline}");
// Headers
await response.WriteAsync($"Request Headers:{newline}");
foreach (var header in request.Headers)
await response.WriteAsync(
$"{header.Key}: {header.Value}{newline}");
await response.WriteAsync(newline);
// Connection: RemoteIp
await response.WriteAsync(
$"Request RemoteIp: {context.Connection.RemoteIpAddress}{newline}");
await response.WriteAsync($"Network: {Network.Prefix}");
await next();
}
}
}
| 38.515152 | 106 | 0.641227 | [
"MIT"
] | ryakstis/docker-swarm-nginx-dotnet-wsfederation-issue | Startup.cs | 6,355 | C# |
namespace Polytet.Communication.Messages
{
[Header(0b_1000_0100, MessageReceiver.Client)]
public readonly struct TickServer : IMessage
{
internal static IMessage DeSerialize(byte[] message, byte playerIntegerSize)
{
return new TickServer();
}
byte[] IMessage.Serialize(byte playerIntegerSize)
{
return new byte[0];
}
}
} | 21.5 | 78 | 0.738372 | [
"MIT"
] | 89netraM/Polytet | Communication/Messages/Tick.cs | 346 | C# |
// Copyright (C) 2018 Fievus
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using Windows.Devices.Input;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Input;
namespace Charites.Windows.Mvc.Wrappers
{
/// <summary>
/// Provides data of the <see cref="TappedRoutedEventArgs"/>
/// resolved by <see cref="ITappedRoutedEventArgsResolver"/>.
/// </summary>
public static class TappedRoutedEventArgsWrapper
{
/// <summary>
/// Gets or sets the <see cref="ITappedRoutedEventArgsResolver"/>
/// that resolves data of the <see cref="TappedRoutedEventArgs"/>.
/// </summary>
public static ITappedRoutedEventArgsResolver Resolver { get; set; } = new DefaultTappedRoutedEventArgsResolver();
/// <summary>
/// Gets a value that marks the routed event as handled.
/// A <c>true</c> value prevents most handlers along the event
/// route from handling the same event again.
/// </summary>
/// <param name="e">The requested <see cref="TappedRoutedEventArgs"/>.</param>
/// <returns>
/// <c>true</c> to mark the routed event handled.
/// <c>false</c> to leave the routed event unhandled, which permits the event to potentially
/// route further and be acted on by other handlers.
/// </returns>
public static bool Handled(this TappedRoutedEventArgs e) => Resolver.Handled(e);
/// <summary>
/// Sets a value that marks the routed event as handled.
/// A <c>true</c> value prevents most handlers along the event
/// route from handling the same event again.
/// </summary>
/// <param name="e">The requested <see cref="TappedRoutedEventArgs"/>.</param>
/// <param name="handled">
/// <c>true</c> to mark the routed event handled.
/// <c>false</c> to leave the routed event unhandled, which permits the event to potentially
/// route further and be acted on by other handlers.
/// </param>
public static void Handled(this TappedRoutedEventArgs e, bool handled) => Resolver.Handled(e, handled);
/// <summary>
/// Gets a reference to the object that raised the event.
/// This is often a template part of a control rather than an element that was declared in your app UI.
/// </summary>
/// <param name="e">The requested <see cref="TappedRoutedEventArgs"/>.</param>
/// <returns>The object that raised the event.</returns>
public static object OriginalSource(this TappedRoutedEventArgs e) => Resolver.OriginalSource(e);
/// <summary>
/// Gets the <see cref="global::Windows.Devices.Input.PointerDeviceType"/> for the pointer device
/// that initiated the associated input event.
/// </summary>
/// <param name="e">The requested <see cref="TappedRoutedEventArgs"/>.</param>
/// <returns>The <see cref="global::Windows.Devices.Input.PointerDeviceType"/> for this event occurrence.</returns>
public static PointerDeviceType PointerDeviceType(this TappedRoutedEventArgs e) => Resolver.PointerDeviceType(e);
/// <summary>
/// Gets the x- and y-coordinates of the pointer position, optionally evaluated against a coordinate origin
/// of a supplied <see cref="UIElement"/>.
/// </summary>
/// <param name="e">The requested <see cref="TappedRoutedEventArgs"/>.</param>
/// <param name="relativeTo">
/// Any <see cref="UIElement"/>-derived object that is connected to the same object tree.
/// To specify the object relative to the overall coordinate system,
/// use a <paramref name="relativeTo"/> value of <c>null</c>.
/// </param>
/// <returns>
/// A Point that represents the current x- and y-coordinates of the mouse pointer position.
/// If <c>null</c> was passed as <paramref name="relativeTo"/>, this coordinate is for the overall window.
/// If a value other than <c>null</c> for <paramref name="relativeTo"/> was passed, this coordinate is relative
/// to the object referenced by <paramref name="relativeTo"/>.
/// </returns>
public static Point GetPositionWrapped(this TappedRoutedEventArgs e, UIElement relativeTo) => Resolver.GetPosition(e, relativeTo);
private sealed class DefaultTappedRoutedEventArgsResolver : ITappedRoutedEventArgsResolver
{
bool ITappedRoutedEventArgsResolver.Handled(TappedRoutedEventArgs e) => e.Handled;
void ITappedRoutedEventArgsResolver.Handled(TappedRoutedEventArgs e, bool handled) => e.Handled = handled;
object ITappedRoutedEventArgsResolver.OriginalSource(TappedRoutedEventArgs e) => e.OriginalSource;
PointerDeviceType ITappedRoutedEventArgsResolver.PointerDeviceType(TappedRoutedEventArgs e) => e.PointerDeviceType;
Point ITappedRoutedEventArgsResolver.GetPosition(TappedRoutedEventArgs e, UIElement relativeTo) => e.GetPosition(relativeTo);
}
}
/// <summary>
/// Resolves data of the <see cref="TappedRoutedEventArgs"/>.
/// </summary>
public interface ITappedRoutedEventArgsResolver
{
/// <summary>
/// Gets a value that marks the routed event as handled.
/// A <c>true</c> value prevents most handlers along the event
/// route from handling the same event again.
/// </summary>
/// <param name="e">The requested <see cref="TappedRoutedEventArgs"/>.</param>
/// <returns>
/// <c>true</c> to mark the routed event handled.
/// <c>false</c> to leave the routed event unhandled, which permits the event to potentially
/// route further and be acted on by other handlers.
/// </returns>
bool Handled(TappedRoutedEventArgs e);
/// <summary>
/// Sets a value that marks the routed event as handled.
/// A <c>true</c> value prevents most handlers along the event
/// route from handling the same event again.
/// </summary>
/// <param name="e">The requested <see cref="TappedRoutedEventArgs"/>.</param>
/// <param name="handled">
/// <c>true</c> to mark the routed event handled.
/// <c>false</c> to leave the routed event unhandled, which permits the event to potentially
/// route further and be acted on by other handlers.
/// </param>
void Handled(TappedRoutedEventArgs e, bool handled);
/// <summary>
/// Gets a reference to the object that raised the event.
/// This is often a template part of a control rather than an element that was declared in your app UI.
/// </summary>
/// <param name="e">The requested <see cref="TappedRoutedEventArgs"/>.</param>
/// <returns>The object that raised the event.</returns>
object OriginalSource(TappedRoutedEventArgs e);
/// <summary>
/// Gets the <see cref="global::Windows.Devices.Input.PointerDeviceType"/> for the pointer device
/// that initiated the associated input event.
/// </summary>
/// <param name="e">The requested <see cref="TappedRoutedEventArgs"/>.</param>
/// <returns>The <see cref="global::Windows.Devices.Input.PointerDeviceType"/> for this event occurrence.</returns>
PointerDeviceType PointerDeviceType(TappedRoutedEventArgs e);
/// <summary>
/// Gets the x- and y-coordinates of the pointer position, optionally evaluated against a coordinate origin
/// of a supplied <see cref="UIElement"/>.
/// </summary>
/// <param name="e">The requested <see cref="TappedRoutedEventArgs"/>.</param>
/// <param name="relativeTo">
/// Any <see cref="UIElement"/>-derived object that is connected to the same object tree.
/// To specify the object relative to the overall coordinate system,
/// use a <paramref name="relativeTo"/> value of <c>null</c>.
/// </param>
/// <returns>
/// A Point that represents the current x- and y-coordinates of the mouse pointer position.
/// If <c>null</c> was passed as <paramref name="relativeTo"/>, this coordinate is for the overall window.
/// If a value other than <c>null</c> for <paramref name="relativeTo"/> was passed, this coordinate is relative
/// to the object referenced by <paramref name="relativeTo"/>.
/// </returns>
Point GetPosition(TappedRoutedEventArgs e, UIElement relativeTo);
}
}
| 54.2625 | 138 | 0.646625 | [
"MIT"
] | averrunci/UwpMvc | Source/UwpMvc/Mvc/Wrappers/TappedRoutedEventArgsWrapper.cs | 8,684 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraAspectRatio : MonoBehaviour
{
// Use this for initialization
void Start()
{
// set the desired aspect ratio (the values in this example are
// hard-coded for 16:9, but you could make them into public
// variables instead so you can set them at design time)
float targetaspect = 9.0f / 16.0f;
// determine the game window's current aspect ratio
float windowaspect = (float)Screen.width / (float)Screen.height;
// current viewport height should be scaled by this amount
float scaleheight = windowaspect / targetaspect;
// obtain camera component so we can modify its viewport
Camera camera = GetComponent<Camera>();
// if scaled height is less than current height, add letterbox
if (scaleheight < 1.0f)
{
Rect rect = camera.rect;
rect.width = 1.0f;
rect.height = scaleheight;
rect.x = 0;
rect.y = (1.0f - scaleheight) / 2.0f;
camera.rect = rect;
}
else // add pillarbox
{
float scalewidth = 1.0f / scaleheight;
Rect rect = camera.rect;
rect.width = scalewidth;
rect.height = 1.0f;
rect.x = (1.0f - scalewidth) / 2.0f;
rect.y = 0;
camera.rect = rect;
}
}
}
| 28.823529 | 72 | 0.576871 | [
"MIT"
] | BYJRK/AircraftWar3D | Assets/Scripts/CameraAspectRatio.cs | 1,470 | C# |
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(Camera))]
public class TiltedSplitscreen : PostEffectsBase {
public Camera camera2;
public Transform followTarget1, followTarget2;
public Shader titledSplitscreenShader;
RenderTexture otherTexture;
Material m;
Vector3 direction;
float yDist, xDist;
public override void Start() {
//if(camera2.targetTexture == null || camera2.targetTexture.width != Screen.width)
camera2.targetTexture = new RenderTexture(Screen.width, Screen.height, 32);
otherTexture = camera2.targetTexture;
m = new Material(titledSplitscreenShader);
}
void Update () {
direction = (followTarget1.position - followTarget2.position).normalized;
yDist = followTarget1.position.y - followTarget2.position.y;
xDist = followTarget1.position.x - followTarget2.position.x;
}
void OnRenderImage(RenderTexture source, RenderTexture destination){
if(camera2.enabled){
m.SetTexture("_OtherTex", otherTexture);
m.SetVector("_Vector", new Vector4(-direction.x, direction.y, 0, 0));
m.SetFloat("_YDistance", yDist);
m.SetFloat("_XDistance", xDist);
Graphics.Blit(source, destination, m);
}else{
Graphics.Blit(source, destination);
}
}
}
| 29.261905 | 84 | 0.747762 | [
"MIT"
] | staffantan/splitscreen | TiltedSplitscreen.cs | 1,231 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: mybank.credit.supplychain.wf.tokeninvalidstatus.query
/// </summary>
public class MybankCreditSupplychainWfTokeninvalidstatusQueryRequest : IAopRequest<MybankCreditSupplychainWfTokeninvalidstatusQueryResponse>
{
/// <summary>
/// 通知token失效状态
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "mybank.credit.supplychain.wf.tokeninvalidstatus.query";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if(this.udfParams == null)
{
this.udfParams = new Dictionary<string, string>();
}
this.udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
if(udfParams != null)
{
parameters.AddAll(this.udfParams);
}
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 25.467742 | 144 | 0.596897 | [
"Apache-2.0"
] | alipay/alipay-sdk-net | AlipaySDKNet.Standard/Request/MybankCreditSupplychainWfTokeninvalidstatusQueryRequest.cs | 3,170 | C# |
using System;
using System.Xml.Serialization;
namespace GravatarMobile
{
/// <summary>
/// Gravatar name data
/// </summary>
public class GravatarName
{
[XmlElement(ElementName="givenName")]
public string GivenName {get; set;}
[XmlElement(ElementName="familyName")]
public string FamilyName {get; set;}
[XmlElement(ElementName="formatted")]
public string Formatted {get; set;}
}
}
| 17.608696 | 40 | 0.708642 | [
"MIT"
] | newky2k/GravatarMobile | src/GravatarMobile/Data/GravatarName.shared.cs | 407 | C# |
namespace LoWaiLo.WebAPI.Areas.Identity.Pages.Account
{
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using LoWaiLo.Data.Models;
using LoWaiLo.WebAPI.Areas.Identity.Pages.Account.InputModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
[AllowAnonymous]
#pragma warning disable SA1649 // File name should match first type name
public class ForgotPasswordModel : PageModel
#pragma warning restore SA1649 // File name should match first type name
{
private readonly UserManager<ApplicationUser> userManager;
private readonly IEmailSender emailSender;
public ForgotPasswordModel(UserManager<ApplicationUser> userManager, IEmailSender emailSender)
{
this.userManager = userManager;
this.emailSender = emailSender;
}
[BindProperty]
public ForgotPasswordInputModel Input { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (this.ModelState.IsValid)
{
var user = await this.userManager.FindByEmailAsync(this.Input.Email);
if (user == null || !(await this.userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return this.RedirectToPage("./ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please
// visit https://go.microsoft.com/fwlink/?LinkID=532713
var code = await this.userManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = this.Url.Page(
"/Account/ResetPassword",
pageHandler: null,
values: new { code },
protocol: this.Request.Scheme);
await this.emailSender.SendEmailAsync(
this.Input.Email,
"Reset Password",
$"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
return this.RedirectToPage("./ForgotPasswordConfirmation");
}
return this.Page();
}
}
}
| 38.765625 | 125 | 0.624345 | [
"MIT"
] | TeMePyT/LoWaiLo-Project | LoWaiLoWebApi/Web/LoWaiLo.WebAPI/Areas/Identity/Pages/Account/ForgotPassword.cshtml.cs | 2,483 | C# |
using UnityEngine;
namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityParticleSystem
{
[TaskCategory("Basic/ParticleSystem")]
[TaskDescription("Pause the Particle System.")]
public class Pause : Action
{
[Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")]
public SharedGameObject targetGameObject;
private ParticleSystem particleSystem;
private GameObject prevGameObject;
public override void OnStart()
{
var currentGameObject = GetDefaultGameObject(targetGameObject.Value);
if (currentGameObject != prevGameObject) {
particleSystem = currentGameObject.GetComponent<ParticleSystem>();
prevGameObject = currentGameObject;
}
}
public override TaskStatus OnUpdate()
{
if (particleSystem == null) {
Debug.LogWarning("ParticleSystem is null");
return TaskStatus.Failure;
}
particleSystem.Pause();
return TaskStatus.Success;
}
public override void OnReset()
{
targetGameObject = null;
}
}
} | 30.634146 | 100 | 0.593153 | [
"Apache-2.0"
] | brustlinker/unity_behaviortree_sk | Assets/Behavior Designer/Runtime/Basic Tasks/ParticleSystem/Pause.cs | 1,256 | C# |
// <copyright file="CacheSpecificationBuilder.cs" company="improvGroup, LLC">
// Copyright © 2021 improvGroup, LLC. All Rights Reserved.
// </copyright>
namespace SharedCode.Specifications.Builders;
/// <summary>
/// The cache specification builder class. Implements the <see cref="ICacheSpecificationBuilder{T}" />.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <seealso cref="ICacheSpecificationBuilder{T}" />
public class CacheSpecificationBuilder<T> : ICacheSpecificationBuilder<T> where T : class
{
/// <summary>
/// Initializes a new instance of the <see cref="CacheSpecificationBuilder{T}" /> class.
/// </summary>
/// <param name="specification">The specification.</param>
public CacheSpecificationBuilder(Specification<T> specification) => this.Specification = specification;
/// <summary>
/// Gets the specification.
/// </summary>
/// <value>The specification.</value>
public Specification<T> Specification { get; }
}
| 36.769231 | 104 | 0.723849 | [
"MIT"
] | improvgroup/sharedcode | SharedCode.Core/Specifications/Builders/CacheSpecificationBuilder.cs | 957 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MLKitSample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MLKitSample")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.702703 | 84 | 0.744803 | [
"MIT"
] | DigitallyImported/GoogleApisForiOSComponents | samples/Firebase/MLKit/MLKitSample/Properties/AssemblyInfo.cs | 1,398 | C# |
using System;
using System.Linq;
using System.Windows.Input;
using Xamarin.Forms;
namespace Simple.Xamarin.Framework
{
public class ExtendedLabel : StackLayout
{
[Obsolete("Use of Width is forbidden.", true)]
public new static readonly BindableProperty WidthRequestProperty;
[Obsolete("Use of Height is forbidden.", true)]
public new static readonly BindableProperty HeightRequestProperty;
[Obsolete("Use of MinimumWidth is forbidden.", true)]
public new static readonly BindableProperty MinimumWidthRequestProperty;
[Obsolete("Use of MinimumHeight is forbidden.", true)]
public new static readonly BindableProperty MinimumHeightRequestProperty;
[Obsolete("Use of MinimumHeight is forbidden.", true)]
public new static readonly BindableProperty SpacingProperty;
public ExtendedLabel()
{
Spacing = 0;
Padding = Margin = new NamedThickness(ExetendedNamedSize.Zero);
HorizontalOptions = LayoutOptions.StartAndExpand;
VerticalOptions = LayoutOptions.FillAndExpand;
Children.Add(new Label
{
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
});
}
#region Common Properties
public new static readonly BindableProperty MarginProperty =
BindableProperty.Create(nameof(Margin), typeof(NamedThickness), typeof(ExtendedLabel), default(NamedThickness), propertyChanged: (b, o, n) =>
{
if (b is StackLayout stackLayout)
{
if (n is NamedThickness thickness)
{
stackLayout.Margin = new Thickness(thickness.Left, thickness.Top, thickness.Right, thickness.Bottom);
}
}
});
public new NamedThickness Margin
{
get => (NamedThickness)GetValue(MarginProperty);
set => SetValue(MarginProperty, value);
}
public new static readonly BindableProperty PaddingProperty =
BindableProperty.Create(nameof(Padding), typeof(NamedThickness), typeof(ExtendedLabel), default(NamedThickness), propertyChanged: (b, o, n) =>
{
if (b is StackLayout stackLayout)
{
if (n is NamedThickness thickness)
{
stackLayout.Padding = new Thickness(thickness.Left, thickness.Top, thickness.Right, thickness.Bottom);
}
}
});
public new NamedThickness Padding
{
get => (NamedThickness)GetValue(MarginProperty);
set => SetValue(MarginProperty, value);
}
public static readonly BindableProperty TapCommandProperty =
BindableProperty.Create(nameof(TapCommand), typeof(ICommand), typeof(ExtendedLabel), default(ICommand), propertyChanged: (b, o, n) =>
{
if (b is StackLayout stackLayout)
{
stackLayout.GestureRecognizers.Clear();
stackLayout.GestureRecognizers.Add(new TapGestureRecognizer
{
Command = n as ICommand,
});
}
});
/// <summary>
/// Command that will be will execute when user Tap on this label
/// </summary>
public ICommand TapCommand
{
get => (ICommand)GetValue(TapCommandProperty);
set => SetValue(TapCommandProperty, value);
}
public static readonly BindableProperty TapCommandParameterProperty =
BindableProperty.Create(nameof(TapCommandParameter), typeof(object), typeof(ExtendedLabel), default(object), propertyChanged: (b, o, n) =>
{
if (b is StackLayout stackLayout)
{
if (stackLayout.GestureRecognizers.FirstOrDefault() is TapGestureRecognizer gesture)
gesture.CommandParameter = n;
}
});
/// <summary>
/// Command parameter that will be passed to Command executing
/// </summary>
public object TapCommandParameter
{
get => GetValue(TapCommandParameterProperty);
set => SetValue(TapCommandParameterProperty, value);
}
#endregion
#region Label Properties
public static readonly BindableProperty HorizontalTextAlignmentProperty =
BindableProperty.Create(nameof(HorizontalTextAlignment), typeof(TextAlignment), typeof(ExtendedLabel), default(TextAlignment), propertyChanged: (b, o, n) =>
{
var label = GetLabel(b);
if (n is TextAlignment textAlignment)
{
label.HorizontalTextAlignment = textAlignment;
}
});
public TextAlignment HorizontalTextAlignment
{
get => (TextAlignment)GetValue(HorizontalTextAlignmentProperty);
set => SetValue(HorizontalTextAlignmentProperty, value);
}
public static readonly BindableProperty VerticalTextAlignmentProperty =
BindableProperty.Create(nameof(VerticalTextAlignment), typeof(TextAlignment), typeof(ExtendedLabel), default(TextAlignment), propertyChanged: (b, o, n) =>
{
var label = GetLabel(b);
if (n is TextAlignment textAlignment)
{
label.VerticalTextAlignment = textAlignment;
}
});
public TextAlignment VerticalTextAlignment
{
get => (TextAlignment)GetValue(VerticalTextAlignmentProperty);
set => SetValue(VerticalTextAlignmentProperty, value);
}
public static readonly BindableProperty FontSizeProperty =
BindableProperty.Create(nameof(FontSize), typeof(ExetendedNamedSize), typeof(ExtendedLabel), ExetendedNamedSize.Default, propertyChanged: (b, o, n) =>
{
var label = GetLabel(b);
if (n is ExetendedNamedSize size)
{
label.FontSize = SXF.GetFontSize(size);
}
});
public ExetendedNamedSize FontSize
{
get => (ExetendedNamedSize)GetValue(FontSizeProperty);
set => SetValue(FontSizeProperty, value);
}
public static readonly BindableProperty TextProperty =
BindableProperty.Create(nameof(Text), typeof(string), typeof(ExtendedLabel), default(string), propertyChanged: (b, o, n) =>
{
var label = GetLabel(b);
if (n is string text)
{
label.Text = text;
}
});
/// <summary>
/// Text of <see cref="ExtendedLabel"/>
/// </summary>
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public static readonly BindableProperty TextColorProperty =
BindableProperty.Create(nameof(TextColor), typeof(Color), typeof(ExtendedLabel), default(Color), propertyChanged: (b, o, n) =>
{
var label = GetLabel(b);
if (n is Color color)
{
label.TextColor = color;
}
});
/// <summary>
/// Color of <see cref="ExtendedLabel"/>
/// </summary>
public Color TextColor
{
get => (Color)GetValue(TextColorProperty);
set => SetValue(TextColorProperty, value);
}
public static readonly BindableProperty FontAttributesProperty =
BindableProperty.Create(nameof(FontAttributes), typeof(FontAttributes), typeof(ExtendedLabel), default(FontAttributes), propertyChanged: (b, o, n) =>
{
var label = GetLabel(b);
if (n is FontAttributes attributes)
label.FontAttributes = attributes;
});
/// <summary>
/// A string specifying style information like Italic and Bold.
/// </summary>
public FontAttributes FontAttributes
{
get => (FontAttributes)GetValue(FontAttributesProperty);
set => SetValue(FontAttributesProperty, value);
}
public static readonly BindableProperty FontFamilyProperty =
BindableProperty.Create(nameof(FontFamily), typeof(string), typeof(ExtendedLabel), default(string), propertyChanged: (b, o, n) =>
{
var label = GetLabel(b);
if (n is string family)
label.FontFamily = family;
});
/// <summary>
/// The <see cref="string"/> font name.
/// </summary>
public string FontFamily
{
get => (string)GetValue(FontFamilyProperty);
set => SetValue(FontFamilyProperty, value);
}
#endregion
#region Helpers
private static Label GetLabel(BindableObject bindable)
{
var control = bindable as StackLayout;
if (control.Children.FirstOrDefault() is Label label)
return label;
return null;
}
#endregion
}
}
| 37.023438 | 168 | 0.575438 | [
"MIT"
] | kkolodziejczak/Simple.Xamarin.Framework | Simple.Xamarin.Framework/Components/Extended/ExtendedLabel.cs | 9,480 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
namespace UnusedSymbolsAnalyzer.UseCases.Interactors.AnalyzeSolution
{
public class AnalyzeSolutionInteractor
{
private static readonly HashSet<string> SkippedNamespaces = new HashSet<string>()
{
"System.Runtime.CompilerServices"
};
private static readonly HashSet<string> SkippedAttributes = new HashSet<string>()
{
"System.Runtime.CompilerServices.CompilerGeneratedAttribute",
"Microsoft.VisualStudio.TestPlatform.TestSDKAutoGeneratedCode",
"NUnit.Framework.TestFixtureAttribute",
"NUnit.Framework.TestAttribute",
"System.ComponentModel.DataAnnotations.KeyAttribute"
};
public Task<AnalyzeSolutionResult> AnalyzeSolution(
AnalyzeSolutionArguments arguments,
CancellationToken cancellationToken)
{
this.AssertArguments(arguments);
return this.AnalyzeSolutionImpl(arguments, cancellationToken);
}
private static AnalyzeSolutionSymbolVisitorResult GetAnalyzeSolutionSymbolVisitorResult(IAssemblySymbol assembly)
{
var visitor = new AnalyzeSolutionSymbolVisitor(
SkippedNamespaces,
SkippedAttributes);
visitor.Visit(assembly.GlobalNamespace);
return visitor.GetResult();
}
private void AssertArguments(AnalyzeSolutionArguments arguments)
{
if (arguments == null)
{
throw new ArgumentNullException(nameof(arguments));
}
if (arguments.Solution == null)
{
throw new ArgumentException($"{nameof(arguments.Solution)} of {nameof(arguments)} was null.", nameof(arguments));
}
}
private async Task<AnalyzeSolutionResult> AnalyzeSolutionImpl(
AnalyzeSolutionArguments arguments,
CancellationToken cancellationToken)
{
var solution = arguments.Solution;
var compilationTasks = solution.Projects.Select(project => project.GetCompilationAsync(cancellationToken));
var compilations = await Task.WhenAll(compilationTasks);
var visitorResults = compilations.Select(compilation => GetAnalyzeSolutionSymbolVisitorResult(compilation.Assembly));
var potentialTypes = visitorResults.SelectMany(visitorResult => visitorResult.PotentialTypes).ToList();
var potentialMethods = visitorResults.SelectMany(visitorResult => visitorResult.PotentialMethods).ToList();
var methodReferenceDatas = await this.GetMethodReferenceDatas(solution, potentialMethods, cancellationToken);
var methodReferenceDatasLookup = methodReferenceDatas
.ToLookup<MethodData, INamedTypeSymbol>(
keySelector: methodData => methodData.MethodSymbol.ContainingType,
comparer: SymbolEqualityComparer.Default);
var unusedTypes = new List<INamedTypeSymbol>();
foreach (var type in potentialTypes)
{
var references = await SymbolFinder.FindReferencesAsync(type, solution, cancellationToken);
var locations = references.SelectMany(reference => reference.Locations).ToList();
if (!locations.Any())
{
var methods = methodReferenceDatasLookup[type];
if (methods.Any(method => method.IsExternallyReferenced()))
{
continue;
}
unusedTypes.Add(type);
}
}
var unusedMethods = methodReferenceDatas
.Where(methodReferenceData => !methodReferenceData.IsExternallyReferenced())
.Select(methodReferenceData => methodReferenceData.MethodSymbol)
.ToList();
if (arguments.IgnoreOverriddenMethods)
{
unusedMethods = unusedMethods.Where(methodReferenceData => !methodReferenceData.IsOverride).ToList();
}
return new AnalyzeSolutionResult
{
UnusedTypes = unusedTypes,
UnusedMethods = unusedMethods
};
}
private async Task<List<MethodData>> GetMethodReferenceDatas(
Solution solution,
IList<IMethodSymbol> methodSymbols,
CancellationToken cancellationToken)
{
var methodReferenceData = new List<MethodData>();
foreach (var methodSymbol in methodSymbols)
{
var documentsOfTheType = methodSymbol.ContainingType.Locations.Select(document => document.SourceTree?.FilePath);
Console.WriteLine($"Grabbing references from: {methodSymbol}.");
var stopWatch = new Stopwatch();
stopWatch.Start();
var references = await SymbolFinder.FindReferencesAsync(methodSymbol, solution, cancellationToken);
stopWatch.Stop();
Console.WriteLine($"Grabbing references from: {methodSymbol} took: {stopWatch.ElapsedMilliseconds}.");
var locations = references.SelectMany(reference => reference.Locations).ToList();
var externalLocations = locations
.Where(referenceLocation => !documentsOfTheType.Contains(referenceLocation.Document.FilePath))
.ToList();
methodReferenceData.Add(
new MethodData
{
MethodSymbol = methodSymbol,
ExternalReferenceLocations = externalLocations
});
}
return methodReferenceData;
}
}
}
| 41.586207 | 129 | 0.622222 | [
"MIT"
] | schrufygroovy/unused-symbols-analyzer | src/UnusedSymbolsAnalyzer.UseCases/Interactors/AnalyzeSolution/AnalyzeSolutionInteractor.cs | 6,032 | C# |
// Copyright 2021 Google LLC
//
// 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
//
// https://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 Google.Cloud.Spanner.V1.Internal.Logging;
namespace Google.Cloud.Spanner.NHibernate.IntegrationTests
{
public class SingleTableFixture : SpannerFixtureBase
{
public SingleTableFixture()
{
if (Database.Fresh)
{
Logger.DefaultLogger.Debug($"Creating database {Database.DatabaseName}");
CreateTable();
}
else
{
Logger.DefaultLogger.Debug($"Deleting data in {Database.DatabaseName}");
ClearTables();
}
Logger.DefaultLogger.Debug($"Ready to run tests");
}
private void ClearTables()
{
using var con = GetConnection();
using var tx = con.BeginTransaction();
var cmd = con.CreateDmlCommand("DELETE FROM TestTable WHERE TRUE");
cmd.Transaction = tx;
cmd.ExecuteNonQuery();
tx.Commit();
}
private void CreateTable()
{
using var con = GetConnection();
var cmd = con.CreateDdlCommand("CREATE TABLE TestTable (Key STRING(MAX), Value STRING(MAX)) PRIMARY KEY (Key)");
cmd.ExecuteNonQuery();
}
}
}
| 33.814815 | 124 | 0.612815 | [
"Apache-2.0"
] | AlexandrTrf/dotnet-spanner-nhibernate | Google.Cloud.Spanner.NHibernate.IntegrationTests/SingleTableFixture.cs | 1,828 | C# |
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;
namespace Mongo.CRUD
{
public static class MongoExtension
{
public static void AddMongoDb(this IServiceCollection services, string connection)
{
var mongoUrl = new MongoUrl(connection);
IMongoClient client = new MongoClient(mongoUrl);
var database = client.GetDatabase(mongoUrl.DatabaseName);
services.AddSingleton<IMongoDatabase>(database);
services.AddSingleton<IMongoClient>(client);
MongoCRUD.RegisterDefaultConventionPack((x) => true);
}
}
} | 31.4 | 90 | 0.676752 | [
"MIT"
] | ThiagoBarradas/mongo-crud-dotnet | Mongo.CRUD/MongoExtension.cs | 630 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Charlotte.Commons;
using Charlotte.GameCommons;
namespace Charlotte.Games.Enemies.Tests
{
/// <summary>
/// テスト用_敵
/// </summary>
public class Enemy_B0002 : Enemy
{
public Enemy_B0002(double x, double y)
: base(x, y, 10)
{ }
protected override IEnumerable<bool> E_Draw()
{
for (int frame = 1; ; frame++)
{
if (frame % 20 == 0)
Game.I.Enemies.Add(new Enemy_BTama0001(this.X, this.Y));
D2Point speed = DDUtils.AngleToPoint(
DDUtils.GetAngle(Game.I.Player.X - this.X, Game.I.Player.Y - this.Y),
2.5
);
this.X += speed.X;
this.Y += speed.Y;
DDDraw.DrawCenter(Ground.I.Picture.Enemy0002, this.X, this.Y);
this.Crash = DDCrashUtils.Circle(new D2Point(this.X, this.Y), 64.0);
yield return true; // 自機をホーミングするので、画面外に出て行かない。
}
}
}
}
| 20.930233 | 74 | 0.65 | [
"MIT"
] | soleil-taruto/Elsa2 | e20201303_YokoShoot_Demo/Elsa20200001/Elsa20200001/Games/Enemies/Tests/Enemy_B0002.cs | 960 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
///
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""c0d21ef9ba207c335d8347e5172fce1d:2722""}]")]
public class MusicOnHoldSourceModify22AnnouncementCustomSourceMediaFiles
{
private BroadWorksConnector.Ocip.Models.AnnouncementFileKey _audioFile;
[XmlElement(ElementName = "audioFile", IsNullable = true, Namespace = "")]
[Optional]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:2722")]
public BroadWorksConnector.Ocip.Models.AnnouncementFileKey AudioFile
{
get => _audioFile;
set
{
AudioFileSpecified = true;
_audioFile = value;
}
}
[XmlIgnore]
protected bool AudioFileSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.AnnouncementFileKey _videoFile;
[XmlElement(ElementName = "videoFile", IsNullable = true, Namespace = "")]
[Optional]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:2722")]
public BroadWorksConnector.Ocip.Models.AnnouncementFileKey VideoFile
{
get => _videoFile;
set
{
VideoFileSpecified = true;
_videoFile = value;
}
}
[XmlIgnore]
protected bool VideoFileSpecified { get; set; }
}
}
| 29.333333 | 130 | 0.624402 | [
"MIT"
] | JTOne123/broadworks-connector-net | BroadworksConnector/Ocip/Models/MusicOnHoldSourceModify22AnnouncementCustomSourceMediaFiles.cs | 1,672 | C# |
using UnityEngine;
using System.Collections;
public class Steps : MonoBehaviour {
CharacterController controller;
// Use this for initialization
void Start () {
controller = transform.parent.GetComponent<CharacterController>();
GetComponent<AudioSource>().Play();
}
// Update is called once per frame
void FixedUpdate () {
if (controller.isGrounded && controller.velocity.magnitude > 0.0f) {
GetComponent<AudioSource>().volume = 0.05f;
} else {
GetComponent<AudioSource>().volume = 0.0f;
}
}
}
| 22.782609 | 70 | 0.71374 | [
"Unlicense"
] | redien/Ludum-Dare-26 | Assets/Audio/Steps.cs | 524 | C# |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace infinite_scrolling_background.Desktop
{
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D backgroundImage;
Background[] background;
SpriteFont font;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
//set window size
graphics.PreferredBackBufferWidth = 1024;
graphics.PreferredBackBufferHeight = 800;
//set mouse visible
IsMouseVisible = true;
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
//load the font
font = Content.Load<SpriteFont>("Font");
//load background image
backgroundImage = Content.Load<Texture2D>("castle-bg");
//create two instances of the background they are going to swap position to make the infinite scrolling effect
background = new Background[2];
background[0] = new Background(new Vector2(0,0), backgroundImage);
background[1] = new Background(new Vector2(backgroundImage.Width,0), backgroundImage);
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
//call the move method for each background
foreach(Background bg in background)
{
bg.Move(gameTime);
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
//draw each instance of the background on the screen
foreach(Background bg in background)
{
bg.Draw(spriteBatch);
}
//draw message on the screen
string text = "infinite scrolling background";
spriteBatch.DrawString(font, text, new Vector2(10,10), Color.Black);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| 25.76 | 132 | 0.634705 | [
"MIT"
] | GameTemplates/MonoGame-Examples | infinite-scrolling-background/Linux/infinite-scrolling-background/Game1.cs | 2,578 | C# |
using UnityEngine;
// Glow uses the alpha channel as a source of "extra brightness".
// All builtin Unity shaders output baseTexture.alpha * color.alpha, plus
// specularHighlight * specColor.alpha into that.
// Usually you'd want either to make base textures to have zero alpha; or
// set the color to have zero alpha (by default alpha is 0.5).
namespace UnitySampleAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent(typeof (Camera))]
[AddComponentMenu("Image Effects/Glow")]
public class GlowEffect : MonoBehaviour
{
/// The brightness of the glow. Values larger than one give extra "boost".
public float glowIntensity = 1.5f;
/// Blur iterations - larger number means more blur.
public int blurIterations = 3;
/// Blur spread for each iteration. Lower values
/// give better looking blur, but require more iterations to
/// get large blurs. Value is usually between 0.5 and 1.0.
public float blurSpread = 0.7f;
/// Tint glow with this color. Alpha adds additional glow everywhere.
public Color glowTint = new Color(1, 1, 1, 0);
// --------------------------------------------------------
// The final composition shader:
// adds (glow color * glow alpha * amount) to the original image.
// In the combiner glow amount can be only in 0..1 range; we apply extra
// amount during the blurring phase.
public Shader compositeShader;
private Material m_CompositeMaterial = null;
protected Material compositeMaterial
{
get
{
if (m_CompositeMaterial == null)
{
m_CompositeMaterial = new Material(compositeShader);
m_CompositeMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_CompositeMaterial;
}
}
// --------------------------------------------------------
// The blur iteration shader.
// Basically it just takes 4 texture samples and averages them.
// By applying it repeatedly and spreading out sample locations
// we get a Gaussian blur approximation.
// The alpha value in _Color would normally be 0.25 (to average 4 samples),
// however if we have glow amount larger than 1 then we increase this.
public Shader blurShader;
private Material m_BlurMaterial = null;
protected Material blurMaterial
{
get
{
if (m_BlurMaterial == null)
{
m_BlurMaterial = new Material(blurShader);
m_BlurMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_BlurMaterial;
}
}
// --------------------------------------------------------
// The image downsample shaders for each brightness mode.
// It is in external assets as it's quite complex and uses Cg.
public Shader downsampleShader;
private Material m_DownsampleMaterial = null;
protected Material downsampleMaterial
{
get
{
if (m_DownsampleMaterial == null)
{
m_DownsampleMaterial = new Material(downsampleShader);
m_DownsampleMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_DownsampleMaterial;
}
}
// --------------------------------------------------------
// finally, the actual code
protected void OnDisable()
{
if (m_CompositeMaterial)
{
DestroyImmediate(m_CompositeMaterial);
}
if (m_BlurMaterial)
{
DestroyImmediate(m_BlurMaterial);
}
if (m_DownsampleMaterial)
DestroyImmediate(m_DownsampleMaterial);
}
protected void Start()
{
// Disable if we don't support image effects
if (!SystemInfo.supportsImageEffects)
{
enabled = false;
return;
}
// Disable the effect if no downsample shader is setup
if (downsampleShader == null)
{
Debug.Log("No downsample shader assigned! Disabling glow.");
enabled = false;
}
// Disable if any of the shaders can't run on the users graphics card
else
{
if (!blurMaterial.shader.isSupported)
enabled = false;
if (!compositeMaterial.shader.isSupported)
enabled = false;
if (!downsampleMaterial.shader.isSupported)
enabled = false;
}
}
// Performs one blur iteration.
public void FourTapCone(RenderTexture source, RenderTexture dest, int iteration)
{
float off = 0.5f + iteration*blurSpread;
Graphics.BlitMultiTap(source, dest, blurMaterial,
new Vector2(off, off),
new Vector2(-off, off),
new Vector2(off, -off),
new Vector2(-off, -off)
);
}
// Downsamples the texture to a quarter resolution.
private void DownSample4x(RenderTexture source, RenderTexture dest)
{
downsampleMaterial.color = new Color(glowTint.r, glowTint.g, glowTint.b, glowTint.a/4.0f);
Graphics.Blit(source, dest, downsampleMaterial);
}
// Called by the camera to apply the image effect
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
// Clamp parameters to sane values
glowIntensity = Mathf.Clamp(glowIntensity, 0.0f, 10.0f);
blurIterations = Mathf.Clamp(blurIterations, 0, 30);
blurSpread = Mathf.Clamp(blurSpread, 0.5f, 1.0f);
RenderTexture buffer = RenderTexture.GetTemporary(source.width/4, source.height/4, 0);
RenderTexture buffer2 = RenderTexture.GetTemporary(source.width/4, source.height/4, 0);
// Copy source to the 4x4 smaller texture.
DownSample4x(source, buffer);
// Blur the small texture
float extraBlurBoost = Mathf.Clamp01((glowIntensity - 1.0f)/4.0f);
blurMaterial.color = new Color(1F, 1F, 1F, 0.25f + extraBlurBoost);
bool oddEven = true;
for (int i = 0; i < blurIterations; i++)
{
if (oddEven)
FourTapCone(buffer, buffer2, i);
else
FourTapCone(buffer2, buffer, i);
oddEven = !oddEven;
}
Graphics.Blit(source, destination);
if (oddEven)
BlitGlow(buffer, destination);
else
BlitGlow(buffer2, destination);
RenderTexture.ReleaseTemporary(buffer);
RenderTexture.ReleaseTemporary(buffer2);
}
public void BlitGlow(RenderTexture source, RenderTexture dest)
{
compositeMaterial.color = new Color(1F, 1F, 1F, Mathf.Clamp01(glowIntensity));
Graphics.Blit(source, dest, compositeMaterial);
}
}
} | 37.514563 | 103 | 0.527821 | [
"MIT"
] | DavidLibeau/Delphinarium-Unity | Assets/Store/Standard Assets/Effects/ImageEffects (Pro Only)/Scripts/GlowEffect.cs | 7,728 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using AldursLab.WurmApi;
using AldursLab.WurmAssistant3.Areas.Config;
using AldursLab.WurmAssistant3.Areas.Granger.DataLayer;
using AldursLab.WurmAssistant3.Areas.Insights;
using AldursLab.WurmAssistant3.Areas.Logging;
using AldursLab.WurmAssistant3.Areas.TrayPopups;
using JetBrains.Annotations;
namespace AldursLab.WurmAssistant3.Areas.Granger.LogFeedManager
{
public class LogsFeedManager : IDisposable
{
readonly GrangerContext context;
readonly IWurmApi wurmApi;
readonly ILogger logger;
readonly ITrayPopups trayPopups;
readonly IWurmAssistantConfig wurmAssistantConfig;
[NotNull] readonly CreatureColorDefinitions creatureColorDefinitions;
readonly GrangerFeature parentModule;
readonly Dictionary<string, PlayerManager> playerManagers = new Dictionary<string, PlayerManager>();
readonly GrangerSettings grangerSettings;
readonly ITelemetry telemetry;
public LogsFeedManager(
[NotNull] GrangerFeature parentModule,
[NotNull] GrangerContext context,
[NotNull] IWurmApi wurmApi,
[NotNull] ILogger logger,
[NotNull] ITrayPopups trayPopups,
[NotNull] IWurmAssistantConfig wurmAssistantConfig,
[NotNull] CreatureColorDefinitions creatureColorDefinitions,
[NotNull] GrangerSettings grangerSettings,
[NotNull] ITelemetry telemetry)
{
if (parentModule == null) throw new ArgumentNullException(nameof(parentModule));
if (context == null) throw new ArgumentNullException(nameof(context));
if (wurmApi == null) throw new ArgumentNullException(nameof(wurmApi));
if (logger == null) throw new ArgumentNullException(nameof(logger));
if (trayPopups == null) throw new ArgumentNullException(nameof(trayPopups));
if (wurmAssistantConfig == null) throw new ArgumentNullException(nameof(wurmAssistantConfig));
if (creatureColorDefinitions == null) throw new ArgumentNullException(nameof(creatureColorDefinitions));
if (grangerSettings == null) throw new ArgumentNullException(nameof(grangerSettings));
this.parentModule = parentModule;
this.context = context;
this.wurmApi = wurmApi;
this.logger = logger;
this.trayPopups = trayPopups;
this.wurmAssistantConfig = wurmAssistantConfig;
this.creatureColorDefinitions = creatureColorDefinitions;
this.grangerSettings = grangerSettings;
this.telemetry = telemetry ?? throw new ArgumentNullException(nameof(telemetry));
}
public void TryRegisterPlayer(string playerName)
{
if (!playerManagers.ContainsKey(playerName))
{
try
{
playerManagers[playerName] = new PlayerManager(parentModule,
context,
playerName,
wurmApi,
logger,
trayPopups,
wurmAssistantConfig,
creatureColorDefinitions,
grangerSettings,
telemetry);
}
catch (Exception exception)
{
logger.Error(exception, "Count not register PlayerManager for player name: " + playerName);
}
}
}
public void UnregisterPlayer(string playerName)
{
PlayerManager ph;
if (playerManagers.TryGetValue(playerName, out ph))
{
ph.Dispose();
playerManagers.Remove(playerName);
}
}
public void Dispose()
{
foreach (var keyval in playerManagers)
{
keyval.Value.Dispose();
}
}
internal void UpdatePlayers(IEnumerable<string> players)
{
var list = players.ToList();
foreach (var player in list)
{
if (!playerManagers.ContainsKey(player))
{
TryRegisterPlayer(player);
}
}
var managedPlayers = playerManagers.Keys.ToArray();
foreach (var player in managedPlayers)
{
if (!list.Contains(player))
UnregisterPlayer(player);
}
}
internal void Update()
{
foreach (var keyval in playerManagers)
{
keyval.Value.Update();
}
}
}
}
| 37.093023 | 116 | 0.588506 | [
"MIT"
] | artizzan/WurmAssistant3 | src/Apps/WurmAssistant/WurmAssistant3/Areas/Granger/LogFeedManager/LogsFeedManager.cs | 4,787 | C# |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using FarseerPhysics.Common;
using FarseerPhysics.Common;
namespace FarseerPhysics.Dynamics.Joints
{
// p = attached point, m = mouse point
// C = p - m
// Cdot = v
// = v + cross(w, r)
// J = [I r_skew]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
/// <summary>
/// A mouse joint is used to make a point on a body track a
/// specified world point. This a soft constraint with a maximum
/// force. This allows the constraint to stretch and without
/// applying huge forces.
/// NOTE: this joint is not documented in the manual because it was
/// developed to be used in the testbed. If you want to learn how to
/// use the mouse joint, look at the testbed.
/// </summary>
public class FixedMouseJoint : Joint
{
private Vector2 _worldAnchor;
private float _frequency;
private float _dampingRatio;
private float _beta;
// Solver shared
private Vector2 _impulse;
private float _maxForce;
private float _gamma;
// Solver temp
private int _indexA;
private Vector2 _rA;
private Vector2 _localCenterA;
private float _invMassA;
private float _invIA;
private Mat22 _mass;
private Vector2 _C;
/// <summary>
/// This requires a world target point,
/// tuning parameters, and the time step.
/// </summary>
/// <param name="body">The body.</param>
/// <param name="worldAnchor">The target.</param>
public FixedMouseJoint(Body body, Vector2 worldAnchor)
: base(body)
{
JointType = JointType.FixedMouse;
Frequency = 5.0f;
DampingRatio = 0.7f;
MaxForce = 1000 * body.Mass;
Debug.Assert(worldAnchor.IsValid());
_worldAnchor = worldAnchor;
LocalAnchorA = MathUtils.MulT(BodyA._xf, worldAnchor);
}
/// <summary>
/// The local anchor point on BodyA
/// </summary>
public Vector2 LocalAnchorA { get; set; }
public override Vector2 WorldAnchorA
{
get { return BodyA.GetWorldPoint(LocalAnchorA); }
set { LocalAnchorA = BodyA.GetLocalPoint(value); }
}
public override Vector2 WorldAnchorB
{
get { return _worldAnchor; }
set
{
WakeBodies();
_worldAnchor = value;
}
}
/// <summary>
/// The maximum constraint force that can be exerted
/// to move the candidate body. Usually you will express
/// as some multiple of the weight (multiplier * mass * gravity).
/// </summary>
public float MaxForce
{
get { return _maxForce; }
set
{
Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f);
_maxForce = value;
}
}
/// <summary>
/// The response speed.
/// </summary>
public float Frequency
{
get { return _frequency; }
set
{
Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f);
_frequency = value;
}
}
/// <summary>
/// The damping ratio. 0 = no damping, 1 = critical damping.
/// </summary>
public float DampingRatio
{
get { return _dampingRatio; }
set
{
Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f);
_dampingRatio = value;
}
}
public override Vector2 GetReactionForce(float invDt)
{
return invDt * _impulse;
}
public override float GetReactionTorque(float invDt)
{
return invDt * 0.0f;
}
internal override void InitVelocityConstraints(ref SolverData data)
{
_indexA = BodyA.IslandIndex;
_localCenterA = BodyA._sweep.LocalCenter;
_invMassA = BodyA._invMass;
_invIA = BodyA._invI;
Vector2 cA = data.positions[_indexA].c;
float aA = data.positions[_indexA].a;
Vector2 vA = data.velocities[_indexA].v;
float wA = data.velocities[_indexA].w;
Rot qA = new Rot(aA);
float mass = BodyA.Mass;
// Frequency
float omega = 2.0f * Settings.Pi * Frequency;
// Damping coefficient
float d = 2.0f * mass * DampingRatio * omega;
// Spring stiffness
float k = mass * (omega * omega);
// magic formulas
// gamma has units of inverse mass.
// beta has units of inverse time.
float h = data.step.dt;
Debug.Assert(d + h * k > Settings.Epsilon);
_gamma = h * (d + h * k);
if (_gamma != 0.0f)
{
_gamma = 1.0f / _gamma;
}
_beta = h * k * _gamma;
// Compute the effective mass matrix.
_rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
// K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)]
// = [1/m1+1/m2 0 ] + invI1 * [r1.Y*r1.Y -r1.X*r1.Y] + invI2 * [r1.Y*r1.Y -r1.X*r1.Y]
// [ 0 1/m1+1/m2] [-r1.X*r1.Y r1.X*r1.X] [-r1.X*r1.Y r1.X*r1.X]
Mat22 K = new Mat22();
K.ex.X = _invMassA + _invIA * _rA.Y * _rA.Y + _gamma;
K.ex.Y = -_invIA * _rA.X * _rA.Y;
K.ey.X = K.ex.Y;
K.ey.Y = _invMassA + _invIA * _rA.X * _rA.X + _gamma;
_mass = K.Inverse;
_C = cA + _rA - _worldAnchor;
_C *= _beta;
// Cheat with some damping
wA *= 0.98f;
if (Settings.EnableWarmstarting)
{
_impulse *= data.step.dtRatio;
vA += _invMassA * _impulse;
wA += _invIA * MathUtils.Cross(_rA, _impulse);
}
else
{
_impulse = Vector2.Zero;
}
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
}
internal override void SolveVelocityConstraints(ref SolverData data)
{
Vector2 vA = data.velocities[_indexA].v;
float wA = data.velocities[_indexA].w;
// Cdot = v + cross(w, r)
Vector2 Cdot = vA + MathUtils.Cross(wA, _rA);
Vector2 impulse = MathUtils.Mul(ref _mass, -(Cdot + _C + _gamma * _impulse));
Vector2 oldImpulse = _impulse;
_impulse += impulse;
float maxImpulse = data.step.dt * MaxForce;
if (_impulse.LengthSquared() > maxImpulse * maxImpulse)
{
_impulse *= maxImpulse / _impulse.Length();
}
impulse = _impulse - oldImpulse;
vA += _invMassA * impulse;
wA += _invIA * MathUtils.Cross(_rA, impulse);
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
}
internal override bool SolvePositionConstraints(ref SolverData data)
{
return true;
}
}
} | 32.394636 | 109 | 0.536606 | [
"MIT"
] | PsichiX/mindvolving | FarseerPhysics.Portable/Dynamics/Joints/FixedMouseJoint.cs | 8,455 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
public class ShopSystem : MonoBehaviour
{
[SerializeField] private Gun Weapon;
[SerializeField] private CoinSystem CoinSystem;
[SerializeField] private GameObject ShopPanel;
[SerializeField] private Transform ShopTransform;
[SerializeField] private Transform Player;
[SerializeField] private float Distance;
[SerializeField] private Button AttackRateButton;
[SerializeField] private Button DamageButton;
[SerializeField] private Button AmmoButton;
[SerializeField] private TMPro.TMP_Text DamageStatTxt;
[SerializeField] private TMPro.TMP_Text AttackRateStatTxt;
[SerializeField] private TMPro.TMP_Text MaxAmmoStatTxt;
private bool CanBuyAttackRate = true;
private MenuController _menuController;
private void Awake()
{
_menuController = ShopPanel.GetComponent<MenuController>();
}
// Start is called before the first frame update
// Update is called once per frame
void Update()
{
if (!ShopPanel.activeSelf &&Input.GetKeyDown(KeyCode.E) && Vector3.Distance(ShopTransform.position, Player.transform.position) < Distance)
{
_menuController.SetActive(true, 0.25f);
ThirdPersonAim.FollowMouse = false;
UpdateButtons();
}
else if(ShopPanel.activeSelf && Input.GetKeyDown(KeyCode.E))
{
_menuController.SetActive(false, 0.25f);
ThirdPersonAim.FollowMouse = true;
}
}
private void UpdateButtons()
{
DamageStatTxt.text = Weapon.DamageNumber.ToString();
AttackRateStatTxt.text = (1 / Weapon.AttackRate).ToString("F2");
MaxAmmoStatTxt.text = Weapon.AmmoCapacity.ToString();
DisableButton(AmmoButton);
DisableButton(DamageButton);
DisableButton(AttackRateButton);
if (CoinSystem.HasCoins(10))
{
EnableButton(AmmoButton);
EnableButton(DamageButton);
if (CanBuyAttackRate)
{
EnableButton(AttackRateButton);
}
}
}
public void CloseShop()
{
ShopPanel.SetActive(false);
}
public void BuyDamage()
{
if (CoinSystem.HasCoins(10))
{
Weapon.DamageNumber += 5;
CoinSystem.RemoveCoins(10);
}
UpdateButtons();
}
public void BuyAmmoMax()
{
if (CoinSystem.HasCoins(10))
{
Weapon.AmmoCapacity += 5;
CoinSystem.RemoveCoins(10);
}
UpdateButtons();
}
public void BuyAttackRate()
{
if (!CanBuyAttackRate) return;
if(CoinSystem.HasCoins(10))
{
Weapon.AttackRate -= 0.02f;
CoinSystem.RemoveCoins(10);
if (Weapon.AttackRate < 0.1f)
{
Weapon.AttackRate = 0.1f;
CanBuyAttackRate = false;
}
}
UpdateButtons();
}
private void DisableButton(Button button)
{
Color defaultColor = button.image.color;
button.image.color = new Color(defaultColor.r, defaultColor.g, defaultColor.b, 0.5f);
button.interactable = false;
}
private void EnableButton(Button button)
{
Color defaultColor = button.image.color;
button.image.color = new Color(defaultColor.r, defaultColor.g, defaultColor.b, 1f);
button.interactable = true;
}
}
| 30.245763 | 146 | 0.624264 | [
"MIT"
] | xfac11/Bug-Game | Assets/Scripts/ShopSystem.cs | 3,571 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.KeyVault.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources.Models;
namespace Azure.ResourceManager.KeyVault
{
public partial class MhsmPrivateEndpointConnectionData : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsDefined(Etag))
{
writer.WritePropertyName("etag");
writer.WriteStringValue(Etag);
}
if (Optional.IsDefined(Sku))
{
writer.WritePropertyName("sku");
writer.WriteObjectValue(Sku);
}
writer.WritePropertyName("tags");
writer.WriteStartObject();
foreach (var item in Tags)
{
writer.WritePropertyName(item.Key);
writer.WriteStringValue(item.Value);
}
writer.WriteEndObject();
writer.WritePropertyName("location");
writer.WriteStringValue(Location);
writer.WritePropertyName("properties");
writer.WriteStartObject();
if (Optional.IsDefined(PrivateEndpoint))
{
writer.WritePropertyName("privateEndpoint");
JsonSerializer.Serialize(writer, PrivateEndpoint);
}
if (Optional.IsDefined(PrivateLinkServiceConnectionState))
{
writer.WritePropertyName("privateLinkServiceConnectionState");
writer.WriteObjectValue(PrivateLinkServiceConnectionState);
}
if (Optional.IsDefined(ProvisioningState))
{
writer.WritePropertyName("provisioningState");
writer.WriteStringValue(ProvisioningState.Value.ToString());
}
writer.WriteEndObject();
writer.WriteEndObject();
}
internal static MhsmPrivateEndpointConnectionData DeserializeMhsmPrivateEndpointConnectionData(JsonElement element)
{
Optional<string> etag = default;
Optional<ManagedHsmSku> sku = default;
IDictionary<string, string> tags = default;
AzureLocation location = default;
ResourceIdentifier id = default;
string name = default;
ResourceType type = default;
SystemData systemData = default;
Optional<SubResource> privateEndpoint = default;
Optional<MhsmPrivateLinkServiceConnectionState> privateLinkServiceConnectionState = default;
Optional<PrivateEndpointConnectionProvisioningState> provisioningState = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("etag"))
{
etag = property.Value.GetString();
continue;
}
if (property.NameEquals("sku"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
sku = ManagedHsmSku.DeserializeManagedHsmSku(property.Value);
continue;
}
if (property.NameEquals("tags"))
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (var property0 in property.Value.EnumerateObject())
{
dictionary.Add(property0.Name, property0.Value.GetString());
}
tags = dictionary;
continue;
}
if (property.NameEquals("location"))
{
location = property.Value.GetString();
continue;
}
if (property.NameEquals("id"))
{
id = new ResourceIdentifier(property.Value.GetString());
continue;
}
if (property.NameEquals("name"))
{
name = property.Value.GetString();
continue;
}
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("systemData"))
{
systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString());
continue;
}
if (property.NameEquals("properties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("privateEndpoint"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
privateEndpoint = JsonSerializer.Deserialize<SubResource>(property0.Value.ToString());
continue;
}
if (property0.NameEquals("privateLinkServiceConnectionState"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
privateLinkServiceConnectionState = MhsmPrivateLinkServiceConnectionState.DeserializeMhsmPrivateLinkServiceConnectionState(property0.Value);
continue;
}
if (property0.NameEquals("provisioningState"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
provisioningState = new PrivateEndpointConnectionProvisioningState(property0.Value.GetString());
continue;
}
}
continue;
}
}
return new MhsmPrivateEndpointConnectionData(id, name, type, systemData, tags, location, sku.Value, etag.Value, privateEndpoint, privateLinkServiceConnectionState.Value, Optional.ToNullable(provisioningState));
}
}
}
| 42.148571 | 222 | 0.505965 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/keyvault/Azure.ResourceManager.KeyVault/src/Generated/Models/MhsmPrivateEndpointConnectionData.Serialization.cs | 7,376 | C# |
using GameLibrary.Domain.Core;
using GameLibrary.Domain.Entities.Token;
using GameLibrary.Domain.Interfaces.Repositories;
using GameLibrary.Domain.Interfaces.Services;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace GameLibrary.Domain.Services
{
public class TokenService : ITokenService
{
private readonly IUsuarioRepository _usuarioRepository;
private readonly IOptions<AppSettings> _configuration;
private readonly IDistributedCache _cache;
public TokenService(IUsuarioRepository usuarioRepository, IOptions<AppSettings> configuration, IDistributedCache cache)
{
_usuarioRepository = usuarioRepository;
_configuration = configuration;
_cache = cache;
}
public async Task<bool> ValidateCredentials(AccessTokenCredentials credenciais)
{
bool credenciaisValidas = false;
if (credenciais != null && !String.IsNullOrWhiteSpace(credenciais.CPF))
{
if (credenciais.GrantType == "password")
{
var usuario = await _usuarioRepository.FindAsync(x => x.CPF == credenciais.CPF);
if (usuario != null)
{
// Validar senha
///TODO implementar hash de validação
return usuario.SenhaHash == credenciais.Password;
}
}
else if (credenciais.GrantType == "refresh_token")
{
if (!string.IsNullOrWhiteSpace(credenciais.RefreshToken))
{
RefreshTokenData refreshTokenBase = null;
string strTokenArmazenado = _cache.GetString(credenciais.RefreshToken);
if (!string.IsNullOrWhiteSpace(strTokenArmazenado))
{
refreshTokenBase = JsonConvert
.DeserializeObject<RefreshTokenData>(strTokenArmazenado);
}
credenciaisValidas = (refreshTokenBase != null &&
credenciais.UserID == refreshTokenBase.UserID &&
credenciais.RefreshToken == refreshTokenBase.RefreshToken);
// Elimina o token de refresh já que um novo será gerado
if (credenciaisValidas)
_cache.Remove(credenciais.RefreshToken);
}
}
}
return credenciaisValidas;
}
public Token GenerateToken(AccessTokenCredentials credenciais)
{
try
{
DateTime dataCriacao = DateTime.Now;
DateTime dataExpiracao = dataCriacao +
TimeSpan.FromMinutes(_configuration.Value.SecurityTokenExpirationMinutesParameter);
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration.Value.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim("CPF", credenciais.CPF.ToString())
}),
NotBefore = dataCriacao,
Expires = dataExpiracao,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(securityToken);
var resultado = new Token()
{
Authenticated = true,
Created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"),
Expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"),
AccessToken = token,
RefreshToken = Guid.NewGuid().ToString().Replace("-", String.Empty),
Message = "OK"
};
// Armazena o refresh token em cache através do Redis
var refreshTokenData = new RefreshTokenData();
refreshTokenData.RefreshToken = resultado.RefreshToken;
refreshTokenData.UserID = credenciais.UserID;
// Calcula o tempo máximo de validade do refresh token
// (o mesmo será invalidado automaticamente pelo Redis)
TimeSpan finalExpiration =
TimeSpan.FromMinutes(_configuration.Value.FinalExpiration);
DistributedCacheEntryOptions opcoesCache =
new DistributedCacheEntryOptions();
opcoesCache.SetAbsoluteExpiration(finalExpiration);
_cache.SetString(resultado.RefreshToken,
JsonConvert.SerializeObject(refreshTokenData),
opcoesCache);
return resultado;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
| 39.373239 | 134 | 0.56734 | [
"MIT"
] | evertonrps/Game-Library | src/GameLibrary.Domain/Services/TokenService.cs | 5,600 | C# |
using System;
using System.Reflection;
using Jasily.FunctionInvoker;
using JetBrains.Annotations;
using Jasily.FunctionInvoker.ArgumentsResolvers;
namespace Jasily.Awaitablify.Internal
{
internal abstract class AwaitableAdapter : IAwaitableAdapter
{
private readonly bool _isValueType;
protected AwaitableAdapter(AwaitableInfo info)
{
this.AwaitableInfo = info ?? throw new ArgumentNullException(nameof(info));
this._isValueType = info.AwaitableType.GetTypeInfo().IsValueType;
}
protected AwaitableInfo AwaitableInfo { get; }
public bool IsAwaitable => true;
public abstract bool IsCompleted(object instance);
public abstract object GetResult(object instance);
public abstract void OnCompleted(object instance, Action continuation);
protected void VerifyArgument<T>([NotNull] T instance)
{
if (!this._isValueType && instance == null) throw new ArgumentNullException(nameof(instance));
if (!this.IsAwaitable) throw new InvalidOperationException("is NOT awaitable.");
}
public abstract IBaseAwaitable CreateAwaitable(object instance);
}
internal abstract class AwaitableAdapter<TInstance, TAwaiter> : AwaitableAdapter, ITypedAwaitableAdapter<TInstance>
{
private readonly IObjectMethodInvoker<TInstance, TAwaiter> _getAwaiterInvoker;
protected AwaitableAdapter(AwaitableInfo info, FunctionInvokerResolver funcResolver)
: base(info)
{
this._getAwaiterInvoker = funcResolver.Resolve(this.AwaitableInfo.GetAwaiterMethod).AsObjectMethodInvoker<TInstance, TAwaiter>();
}
protected abstract AwaiterAdapter<TAwaiter> AwaiterAdapter { get; }
protected TAwaiter GetAwaiter(TInstance instance)
{
this.VerifyArgument(instance);
return this._getAwaiterInvoker.Invoke(instance);
}
public bool IsCompleted(TInstance instance) => this.AwaiterAdapter.IsCompleted(this.GetAwaiter(instance));
public void OnCompleted(TInstance instance, Action continuation)
{
this.AwaiterAdapter.OnCompleted(this.GetAwaiter(instance), continuation);
}
public override bool IsCompleted(object instance) => this.IsCompleted((TInstance)instance);
public override void OnCompleted(object instance, Action continuation) => this.OnCompleted((TInstance)instance, continuation);
public abstract IBaseAwaitable CreateAwaitable(TInstance instance);
}
} | 37.405797 | 141 | 0.710965 | [
"MIT"
] | Jasily/jasily.awaitablify-csharp | Jasily.Awaitablify/Internal/AwaitableAdapter.cs | 2,583 | C# |
using System;
using Steeltoe.Messaging.RabbitMQ.Config;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Steeltoe.Messaging.RabbitMQ.Extensions;
using Microsoft.Extensions.Hosting;
using Steeltoe.Messaging.RabbitMQ.Host;
namespace ConsoleSendReceive
{
class Program
{
static void Main(string[] args)
{
var hostBuilder = RabbitMQHost.CreateDefaultBuilder(args);
hostBuilder.ConfigureServices((hostbuilderContext, services) => {
services.AddLogging(b =>
{
b.SetMinimumLevel(LogLevel.Information);
b.AddDebug();
b.AddConsole();
});
// Add queue to be declared
services.AddRabbitQueue(new Queue("myqueue"));
});
using (var host = hostBuilder.Start())
{
var admin = host.Services.GetRabbitAdmin();
var template = host.Services.GetRabbitTemplate();
try
{
template.ConvertAndSend("myqueue", "foo");
var foo = template.ReceiveAndConvert<string>("myqueue");
Console.WriteLine(foo);
}
finally
{
// Delete queue and shutdown container
admin.DeleteQueue("myqueue");
}
}
}
}
}
| 30.346939 | 77 | 0.527909 | [
"Apache-2.0"
] | SteeltoeOSS/Samples | Messaging/src/Console/DependencyInjection/Program.cs | 1,489 | C# |
//
// JobKey.cs
//
// Copyright (c) Christofel authors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Christofel.Scheduling
{
/// <summary>
/// Represents key of a job.
/// </summary>
/// <param name="Group">Gets the name of the group the job is in.</param>
/// <param name="Name">Gets the name of the command.</param>
public record JobKey(string Group, string Name);
} | 32.466667 | 103 | 0.667351 | [
"MIT"
] | ctu-fee-group/Christofel.Scheduler | src/Christofel.Scheduling.Abstractions/JobKey.cs | 487 | C# |
namespace MusicX.Data.Models.Interfaces
{
public interface IHaveOwner
{
string OwnerId { get; set; }
ApplicationUser Owner { get; set; }
}
}
| 17.1 | 43 | 0.614035 | [
"MIT"
] | MrPIvanov/SoftUni | 17-ASP.NET Core MVC/29_BLAZOR/DemoCode/Data/MusicX.Data.Models/Interfaces/IHaveOwner.cs | 173 | C# |
using CleanArchitecture.Application.Common.Interfaces;
using CleanArchitecture.Domain.Entities;
using CleanArchitecture.Domain.Events;
using MediatR;
namespace CleanArchitecture.Application.Owners.Commands.CreateOwner;
public class CreateOwnerCommand : IRequest<int>
{
public int IdOwner { get; set; }
public string? Name { get; set; }
}
public class CreateOwnerCommandHandler : IRequestHandler<CreateOwnerCommand, int>
{
private readonly IApplicationDbContext _context;
public CreateOwnerCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<int> Handle(CreateOwnerCommand request, CancellationToken cancellationToken)
{
var entity = new Owner
{
IdOwner = request.IdOwner,
Name = request.Name,
Done = false
};
entity.DomainEvents.Add(new OwnerCreatedEvent(entity));
_context.Owners.Add(entity);
await _context.SaveChangesAsync(cancellationToken);
return entity.IdOwner;
}
}
| 25.142857 | 98 | 0.707386 | [
"MIT"
] | cleycruz/weelo | src/Application/Owners/Commands/CreateOwner/CreateOwnerCommand.cs | 1,058 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Storage.V20210101.Outputs
{
[OutputType]
public sealed class IdentityResponse
{
/// <summary>
/// The principal ID of resource identity.
/// </summary>
public readonly string PrincipalId;
/// <summary>
/// The tenant ID of resource.
/// </summary>
public readonly string TenantId;
/// <summary>
/// The identity type.
/// </summary>
public readonly string Type;
/// <summary>
/// Gets or sets a list of key value pairs that describe the set of User Assigned identities that will be used with this storage account. The key is the ARM resource identifier of the identity. Only 1 User Assigned identity is permitted here.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.UserAssignedIdentityResponse>? UserAssignedIdentities;
[OutputConstructor]
private IdentityResponse(
string principalId,
string tenantId,
string type,
ImmutableDictionary<string, Outputs.UserAssignedIdentityResponse>? userAssignedIdentities)
{
PrincipalId = principalId;
TenantId = tenantId;
Type = type;
UserAssignedIdentities = userAssignedIdentities;
}
}
}
| 33.04 | 250 | 0.645884 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Storage/V20210101/Outputs/IdentityResponse.cs | 1,652 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DAL.Models
{
public class Answer : AuditableEntity
{
public int Id { get; set; }
public string ImgPath { get; set; }
public string Text { get; set; }
public bool IsCorrect { get; set; }
public int QUestionId { get; set; }
public virtual Question Question { get; set; }
}
}
| 22.944444 | 54 | 0.615012 | [
"MIT"
] | michalfalat/skillPortal | src/DAL/Models/Answer.cs | 415 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SIL.Machine.Tokenization
{
public enum DetokenizeOperation
{
NoOperation,
MergeLeft,
MergeRight,
MergeBoth
}
public abstract class StringDetokenizer : IDetokenizer<string, string>
{
public string Detokenize(IEnumerable<string> tokens)
{
string[] tokenArray = tokens.ToArray();
object ctxt = CreateContext();
DetokenizeOperation[] ops = tokenArray.Select(t => GetOperation(ctxt, t)).ToArray();
var sb = new StringBuilder();
for (int i = 0; i < tokenArray.Length; i++)
{
sb.Append(tokenArray[i]);
bool appendSeparator = true;
if (i + 1 == ops.Length)
appendSeparator = false;
else if (ops[i + 1] == DetokenizeOperation.MergeLeft || ops[i + 1] == DetokenizeOperation.MergeBoth)
appendSeparator = false;
else if (ops[i] == DetokenizeOperation.MergeRight || ops[i] == DetokenizeOperation.MergeBoth)
appendSeparator = false;
if (appendSeparator)
sb.Append(GetSeparator(tokenArray, ops, i));
}
return sb.ToString();
}
protected virtual object CreateContext()
{
return null;
}
protected abstract DetokenizeOperation GetOperation(object ctxt, string token);
protected virtual string GetSeparator(IReadOnlyList<string> tokens, IReadOnlyList<DetokenizeOperation> ops,
int index)
{
return " ";
}
}
}
| 25.236364 | 109 | 0.700288 | [
"MIT"
] | russellmorley/machine | src/SIL.Machine/Tokenization/StringDetokenizer.cs | 1,388 | C# |
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kooboo.CMS.Sites.Models;
namespace Kooboo.CMS.Web.Areas.Sites.ModelBinders
{
public class PagePositionBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var positionType = controllerContext.HttpContext.Request["PositionType"];
object model = null;
switch (positionType)
{
case "View":
model = new ViewPosition();
break;
case "Module":
model = new ModulePosition();
break;
case "Content":
model = new HtmlPosition();
break;
default:
break;
}
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
return model;
}
}
} | 30.190476 | 134 | 0.577287 | [
"BSD-3-Clause"
] | Bringsy/Kooboo.CMS | Kooboo.CMS/Kooboo.CMS.Web/Areas/Sites/ModelBinders/PagePositionBinder.cs | 1,270 | C# |
//创建者:Icarus
//手动滑稽,滑稽脸
//ヾ(•ω•`)o
//2019年05月02日-05:04
//AnimationExpansion.Editor
using System;
using Icarus.IcAttribute.Core;
namespace Icarus.IcAttribute.Attributes
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DisableAttribute : BaseAttribute
{
public bool IsShowArraySize { get; } = false;
public DisableAttribute()
{
}
public DisableAttribute(bool isShowArraySize)
{
IsShowArraySize = isShowArraySize;
}
}
} | 22.346154 | 113 | 0.666093 | [
"MIT"
] | yika-aixi/IcAttribute | Attribute/Scripts/DisableAttribute.cs | 616 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OsuRTDataProvider.Mods;
using RealTimePPDisplayer.Displayer;
using RealTimePPDisplayer.Utility;
namespace RealTimePPDisplayer.Calculator
{
public sealed class CatchTheBeatPerformanceCalculator : PerformanceCalculatorBase
{
private const int KEEP_ALIVE = 0;
private const int KEEP_ALIVE_OK = 1;
private const int CALCULATE_CTB_PP = 2;
private const int FULL_COMBO = int.MaxValue;
private static Process s_ctbServer;
public static bool CtbServerRunning => !(s_ctbServer?.HasExited??true);
private TcpClient _tcpClient;
private Timer _timer;
public int FullCombo { get; private set; }
public int RealTimeMaxCombo { get; private set; }
private double _stars = 0.0;
private double _rt_stars = 0.0;
public override double Stars => _stars;
public override double RealTimeStars => _rt_stars;
public class CtbServerResult
{
public double Stars { get; set; }
public int FullCombo { get; set; }
public double ApproachRate { get; set; }
}
#region static
static CatchTheBeatPerformanceCalculator()
{
StartCtbServer();
}
private static void StartCtbServer()
{
if (!File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"ctb-server\pypy3\pypy3-rtpp.exe")))
{
Sync.Tools.IO.CurrentIO.WriteColor($"[RTPPD::CTB]Please download ctb-server to the Sync root directory.", ConsoleColor.Red);
return;
}
s_ctbServer = new Process();
s_ctbServer.StartInfo.Arguments = @"/c .\run_ctb_server.bat";
s_ctbServer.StartInfo.FileName = "cmd.exe";
s_ctbServer.StartInfo.CreateNoWindow = true;
s_ctbServer.StartInfo.UseShellExecute = false;
s_ctbServer.StartInfo.WorkingDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @".\ctb-server");
s_ctbServer.Start();
}
private static void StopCtbServer()
{
foreach (var process in Process.GetProcessesByName("pypy3-rtpp"))
{
process.Kill();
}
}
private static void RestartCtbServer()
{
StopCtbServer();
StartCtbServer();
}
#endregion
public CatchTheBeatPerformanceCalculator()
{
ConnectCtbServer();
}
private void ConnectCtbServer()
{
if (!CtbServerRunning)
{
RestartCtbServer();
return;
}
_tcpClient = new TcpClient("127.0.0.1", 11800);
_timer?.Dispose();
_timer = new Timer((_) =>SendKeepAlive(),null,TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
//_tcpClient.ReceiveTimeout = 3 * 1000;
}
private void SendKeepAlive()
{
if (!CtbServerRunning)
{
RestartCtbServer();
return;
}
try
{
lock (_tcpClient)
{
using (var sw = new BinaryWriter(_tcpClient.GetStream(), Encoding.UTF8, true))
{
sw.Write(KEEP_ALIVE);
}
using (var sr = new BinaryReader(_tcpClient.GetStream(), Encoding.UTF8, true))
{
int cmd = sr.ReadInt32();
if (cmd != KEEP_ALIVE_OK)
throw new SocketException();
}
}
}
catch (Exception)
{
Sync.Tools.IO.CurrentIO.WriteColor("[RTPPD::CTB]Reconnect ctb-server", ConsoleColor.Green);
_tcpClient.Close();
ConnectCtbServer();
}
}
public CtbServerResult SendCalculateCtb(ArraySegment<byte> content, uint mods)
{
if (!CtbServerRunning)
{
RestartCtbServer();
return new CtbServerResult();
}
if (content.Count == 0) return new CtbServerResult();
try
{
lock (_tcpClient)
{
var stream = _tcpClient.GetStream();
using (var sw = new BinaryWriter(stream, Encoding.UTF8, true))
{
sw.Write(CALCULATE_CTB_PP);
sw.Write(content.Count);
stream.Write(content.Array, content.Offset, content.Count);
sw.Write(mods); //mods
}
using (var br = new BinaryReader(stream, Encoding.UTF8, true))
{
var ret = new CtbServerResult();
ret.Stars = br.ReadDouble();
ret.FullCombo = br.ReadInt32();
ret.ApproachRate = br.ReadDouble();
return ret;
}
}
}
catch (Exception e)
{
#if DEBUG
Sync.Tools.IO.CurrentIO.WriteColor($"[RTPPD::CTB]:{e.Message}", ConsoleColor.Yellow);
#endif
_tcpClient.Close();
ConnectCtbServer();
return null;
}
}
/// <summary>
/// Calculates the pp.
/// </summary>
/// <param name="serverResult">The server result.</param>
/// <param name="ar">The ar.</param>
/// <param name="mods">The mods.</param>
/// <param name="acc">The acc (0-100).</param>
/// <param name="maxCombo">The maximum combo.</param>
/// <param name="nmiss">The nmiss.</param>
/// <returns></returns>
public static double CalculatePp(CtbServerResult serverResult, uint mods, double acc, int maxCombo, int nmiss)
{
acc /= 100.0;
double pp = Math.Pow(((5 * serverResult.Stars / 0.0049) - 4), 2) / 100000;
double length_bonus = 0.95 + 0.4 * Math.Min(1, maxCombo / 3000.0);
if (maxCombo > 3000)
length_bonus += Math.Log10(maxCombo / 3000.0) * 0.5;
pp *= length_bonus;
pp *= Math.Pow(0.97, nmiss);
pp *= Math.Min(Math.Pow(maxCombo, 0.8) / Math.Pow(serverResult.FullCombo, 0.8), 1);
if (serverResult.ApproachRate > 9)
pp *= 1 + 0.1 * (serverResult.ApproachRate - 9);
if (serverResult.ApproachRate < 8)
pp *= 1 + 0.025 * (8 - serverResult.ApproachRate);
if (mods.HasMod(ModsInfo.Mods.Hidden))
pp *= 1.05 + 0.075 * (10 - Math.Min(10, serverResult.ApproachRate));
if (mods.HasMod(ModsInfo.Mods.Flashlight))
pp *= 1.35 * length_bonus;
pp *= Math.Pow(acc, 5.5);
if (mods.HasMod(ModsInfo.Mods.NoFail))
pp *= 0.9;
if (mods.HasMod(ModsInfo.Mods.SpunOut))
pp *= 0.95;
return pp;
}
private bool _cleared = true;
private double _lastAcc = 0;
private int _last_max_combo = 0;
private int _last_nmiss = 0;
private PPTuple _ppTuple = new PPTuple();
private CtbServerResult _maxPpResult;
public override PPTuple GetPerformance()
{
int pos = Beatmap.GetPosition(Time, out int nobject);
if (_cleared == true)
{
_maxPpResult = SendCalculateCtb(new ArraySegment<byte>(Beatmap.RawData), Mods);
if (_maxPpResult != null)
{
_ppTuple.MaxPP = CalculatePp(_maxPpResult, Mods, 100, _maxPpResult.FullCombo, 0);
_ppTuple.MaxAccuracyPP = 0;
_ppTuple.MaxSpeedPP = 0;
_ppTuple.MaxAimPP = 0;
_stars = _maxPpResult.Stars;
}
FullCombo = _maxPpResult.FullCombo;
_cleared = false;
}
if (_lastAcc != Accuracy)
{
if (_maxPpResult != null)
{
double fcpp = CalculatePp(_maxPpResult, Mods, Accuracy, _maxPpResult.FullCombo, 0);
_ppTuple.FullComboPP = fcpp;
_ppTuple.FullComboAccuracyPP = 0;
_ppTuple.FullComboSpeedPP = 0;
_ppTuple.FullComboAimPP = 0;
}
}
_lastAcc = Accuracy;
bool needUpdate = _last_max_combo != MaxCombo;
needUpdate |= _last_nmiss != CountMiss;
if (needUpdate)
{
if (nobject > 0)
{
CtbServerResult ctbServerResult;
ctbServerResult = SendCalculateCtb(new ArraySegment<byte>(Beatmap.RawData, 0, pos), Mods);
if (ctbServerResult != null)
{
_ppTuple.RealTimePP = CalculatePp(ctbServerResult, Mods, Accuracy, MaxCombo, CountMiss);
_ppTuple.RealTimeAccuracyPP = 0;
_ppTuple.RealTimeSpeedPP = 0;
_ppTuple.RealTimeAimPP = 0;
RealTimeMaxCombo = ctbServerResult.FullCombo;
_rt_stars = ctbServerResult.Stars;
}
}
}
return _ppTuple;
}
public override void ClearCache()
{
base.ClearCache();
_ppTuple = new PPTuple();
_cleared = true;
_lastAcc = 0;
_last_max_combo = 0;
_last_nmiss = 0;
}
public override double Accuracy
{
get
{
int total = Count50 + Count100 + Count300 + CountMiss + CountKatu;
double acc = 1.0;
if (total > 0)
acc = (double)(Count50 + Count100 + Count300) / total;
return acc * 100;
}
}
}
}
| 33.240506 | 140 | 0.50476 | [
"MIT"
] | BadAimWeeb/RealTimePPDisplayer | Calculator/CatchTheBeatPerformanceCalculator.cs | 10,506 | C# |
using PnP.Framework.Extensions;
using System;
using System.Collections;
using System.Collections.Generic;
namespace PnP.Framework.Provisioning.Providers.Xml.Resolvers
{
/// <summary>
/// Type resolver for Teams from Schema to Model
/// </summary>
internal class TeamsFromSchemaToModelTypeResolver : ITypeResolver
{
public string Name => this.GetType().Name;
public bool CustomCollectionResolver => false;
public object Resolve(object source, Dictionary<string, IResolver> resolvers = null, bool recursive = false)
{
var result = new List<Model.Teams.Team>();
var teams = source.GetPublicInstancePropertyValue("Items");
var teamWithSettingsTypeName = $"{PnPSerializationScope.Current?.BaseSchemaNamespace}.TeamWithSettings, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}";
var teamWithSettingsType = Type.GetType(teamWithSettingsTypeName, true);
if (null != teams)
{
foreach (var t in ((IEnumerable)teams))
{
if (teamWithSettingsType.IsInstanceOfType(t))
{
var targetItem = new Model.Teams.Team();
PnPObjectsMapper.MapProperties(t, targetItem, resolvers, recursive);
result.Add(targetItem);
}
}
}
return (result);
}
}
}
| 35.119048 | 173 | 0.60339 | [
"MIT"
] | Arturiby/pnpframework | src/lib/PnP.Framework/Provisioning/Providers/Xml/Resolvers/V201903/TeamsFromSchemaToModelTypeResolver.cs | 1,477 | C# |
namespace MagisIT.ReactiveActions.Sample.Models
{
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public int AvailableAmount { get; set; }
}
}
| 18.785714 | 48 | 0.593156 | [
"MIT"
] | MagisIT/MagisIT.ReactiveActions | MagisIT.ReactiveActions.Sample/Models/Product.cs | 263 | C# |
using System;
using System.Collections.Generic;
namespace BeatDetection
{
public interface IBeatDetection
{
void Detect(Span<short> memory);
List<DetectedBeat> GetBeats();
}
}
| 15.923077 | 40 | 0.676329 | [
"MIT"
] | manio143/BeatDetection | BeatDetection/IBeatDetection.cs | 209 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace SoftJail.Data.Models
{
public class Officer
{
public Officer()
{
this.OfficerPrisoners = new HashSet<OfficerPrisoner>();
}
public int Id { get; set; }
[Required]
public string FullName { get; set; }
public decimal Salary { get; set; }
public Position Position { get; set; }
public Weapon Weapon { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
public ICollection<OfficerPrisoner> OfficerPrisoners { get; set; }
}
// • Id – integer, Primary Key
//• FullName – text with min length 3 and max length 30 (required)
//• Salary – decimal (non-negative, minimum value: 0) (required)
//• Position - Position enumeration with possible values: “Overseer, Guard, Watcher, Labour” (required)
//• Weapon - Weapon enumeration with possible values: “Knife, FlashPulse, ChainRifle, Pistol, Sniper” (required)
//• DepartmentId - integer, foreign key(required)
//• Department – the officer's department (required)
//• OfficerPrisoners - collection of type OfficerPrisoner
}
| 29.952381 | 112 | 0.666932 | [
"MIT"
] | BorisLechev/C-DB | Entity Framework Core/Exams/14.08.2020/SoftJail/SoftJail/Data/Models/Officer.cs | 1,292 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// This source code is made available under the terms of the Microsoft Public License (MS-PL)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace IQToolkit.Data.Common
{
public interface IQueryLanguage
{
string Quote(string name);
bool AllowsMultipleCommands { get; }
bool AllowSubqueryInSelectWithoutFrom { get; }
Expression GetRowsAffectedExpression(Expression command);
bool IsScalar(Type type);
bool IsAggregate(MemberInfo member);
bool CanBeColumn(Expression expression);
bool MustBeColumn(Expression expression);
QueryLinguist CreateLinguist(QueryTranslator translator);
}
/// <summary>
/// Defines the language rules for the query provider
/// </summary>
public abstract class QueryLanguage : IQueryLanguage
{
#region Type, Expresions 1
public abstract QueryTypeSystem TypeSystem { get; }
public abstract Expression GetGeneratedIdExpression(MemberInfo member);
public virtual string Quote(string name)
{
return name;
}
public virtual bool AllowsMultipleCommands
{
get { return false; }
}
public virtual bool AllowSubqueryInSelectWithoutFrom
{
get { return false; }
}
public virtual bool AllowDistinctInAggregates
{
get { return false; }
}
public virtual Expression GetRowsAffectedExpression(Expression command)
{
return new FunctionExpression(typeof(int), "@@ROWCOUNT", null);
}
public virtual bool IsRowsAffectedExpressions(Expression expression)
{
FunctionExpression fex = expression as FunctionExpression;
return fex != null && fex.Name == "@@ROWCOUNT";
}
public virtual Expression GetOuterJoinTest(SelectExpression select)
{
// if the column is used in the join condition (equality test)
// if it is null in the database then the join test won't match (null != null) so the row won't appear
// we can safely use this existing column as our test to determine if the outer join produced a row
// find a column that is used in equality test
var aliases = DeclaredAliasGatherer.Gather(select.From);
var joinColumns = JoinColumnGatherer.Gather(aliases, select).ToList();
if (joinColumns.Count > 0)
{
// prefer one that is already in the projection list.
foreach (var jc in joinColumns)
{
foreach (var col in select.Columns)
{
if (jc.Equals(col.Expression))
{
return jc;
}
}
}
return joinColumns[0];
}
// fall back to introducing a constant
return Expression.Constant(1, typeof(int?));
}
public virtual ProjectionExpression AddOuterJoinTest(ProjectionExpression proj)
{
var test = this.GetOuterJoinTest(proj.Select);
var select = proj.Select;
ColumnExpression testCol = null;
// look to see if test expression exists in columns already
foreach (var col in select.Columns)
{
if (test.Equals(col.Expression))
{
var colType = this.TypeSystem.GetColumnType(test.Type);
testCol = new ColumnExpression(test.Type, colType, select.Alias, col.Name);
break;
}
}
if (testCol == null)
{
// add expression to projection
testCol = test as ColumnExpression;
string colName = (testCol != null) ? testCol.Name : "Test";
colName = proj.Select.Columns.GetAvailableColumnName(colName);
var colType = this.TypeSystem.GetColumnType(test.Type);
select = select.AddColumn(new ColumnDeclaration(colName, test, colType));
testCol = new ColumnExpression(test.Type, colType, select.Alias, colName);
}
var newProjector = new OuterJoinedExpression(testCol, proj.Projector);
return new ProjectionExpression(select, newProjector, proj.Aggregator);
}
#endregion
class JoinColumnGatherer
{
HashSet<TableAlias> aliases;
HashSet<ColumnExpression> columns = new HashSet<ColumnExpression>();
private JoinColumnGatherer(HashSet<TableAlias> aliases)
{
this.aliases = aliases;
}
public static HashSet<ColumnExpression> Gather(HashSet<TableAlias> aliases, SelectExpression select)
{
var gatherer = new JoinColumnGatherer(aliases);
gatherer.Gather(select.Where);
return gatherer.columns;
}
private void Gather(Expression expression)
{
BinaryExpression b = expression as BinaryExpression;
if (b != null)
{
switch (b.NodeType)
{
case ExpressionType.Equal:
case ExpressionType.NotEqual:
if (IsExternalColumn(b.Left) && GetColumn(b.Right) != null)
{
this.columns.Add(GetColumn(b.Right));
}
else if (IsExternalColumn(b.Right) && GetColumn(b.Left) != null)
{
this.columns.Add(GetColumn(b.Left));
}
break;
case ExpressionType.And:
case ExpressionType.AndAlso:
if (b.Type == typeof(bool) || b.Type == typeof(bool?))
{
this.Gather(b.Left);
this.Gather(b.Right);
}
break;
}
}
}
private ColumnExpression GetColumn(Expression exp)
{
while (exp.NodeType == ExpressionType.Convert)
exp = ((UnaryExpression)exp).Operand;
return exp as ColumnExpression;
}
private bool IsExternalColumn(Expression exp)
{
var col = GetColumn(exp);
if (col != null && !this.aliases.Contains(col.Alias))
return true;
return false;
}
}
/// <summary>
/// Determines whether the CLR type corresponds to a scalar data type in the query language
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public virtual bool IsScalar(Type type)
{
type = TypeHelper.GetNonNullableType(type);
switch (Type.GetTypeCode(type))
{
case TypeCode.Empty:
case TypeCode.DBNull:
return false;
case TypeCode.Object:
return
type == typeof(DateTimeOffset) ||
type == typeof(TimeSpan) ||
type == typeof(Guid) ||
type == typeof(byte[]);
default:
return true;
}
}
public virtual bool IsAggregate(MemberInfo member)
{
var method = member as MethodInfo;
if (method != null)
{
if (method.DeclaringType == typeof(Queryable)
|| method.DeclaringType == typeof(Enumerable))
{
switch (method.Name)
{
case "Count":
case "LongCount":
case "Sum":
case "Min":
case "Max":
case "Average":
return true;
}
}
}
var property = member as PropertyInfo;
if (property != null
&& property.Name == "Count"
&& typeof(IEnumerable).IsAssignableFrom(property.DeclaringType))
{
return true;
}
return false;
}
public virtual bool AggregateArgumentIsPredicate(string aggregateName)
{
return aggregateName == "Count" || aggregateName == "LongCount";
}
/// <summary>
/// Determines whether the given expression can be represented as a column in a select expressionss
/// </summary>
public virtual bool CanBeColumn(Expression expression)
{
return this.MustBeColumn(expression) || this.IsScalar(expression.Type);
}
/// <summary>
/// Determines whether the given expression must be represented as a column in a SELECT column list
/// </summary>
public virtual bool MustBeColumn(Expression expression)
{
switch (expression.NodeType)
{
case (ExpressionType)DbExpressionType.Column:
case (ExpressionType)DbExpressionType.Scalar:
case (ExpressionType)DbExpressionType.Exists:
case (ExpressionType)DbExpressionType.AggregateSubquery:
case (ExpressionType)DbExpressionType.Aggregate:
return true;
default:
return false;
}
}
public virtual QueryLinguist CreateLinguist(QueryTranslator translator)
{
return new QueryLinguist(this, translator);
}
}
public interface IQueryLinguist
{
QueryLanguage Language { get; }
IQueryTranslator Translator { get; }
}
public class QueryLinguist
{
QueryLanguage language;
QueryTranslator translator;
public QueryLinguist(QueryLanguage language, QueryTranslator translator)
{
this.language = language;
this.translator = translator;
}
public QueryLanguage Language
{
get { return this.language; }
}
public IQueryTranslator Translator
{
get { return this.translator; }
}
/// <summary>
/// Provides language specific query translation. Use this to apply language specific rewrites or
/// to make assertions/validations about the query.
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public virtual Expression Translate(Expression expression)
{
// remove redundant layers again before cross apply rewrite
expression = UnusedColumnRemover.Remove(expression);
expression = RedundantColumnRemover.Remove(expression);
expression = RedundantSubqueryRemover.Remove(expression);
// convert cross-apply and outer-apply joins into inner & left-outer-joins if possible
var rewritten = CrossApplyRewriter.Rewrite(this.language, expression);
// convert cross joins into inner joins
rewritten = CrossJoinRewriter.Rewrite(rewritten);
if (rewritten != expression)
{
expression = rewritten;
// do final reduction
expression = UnusedColumnRemover.Remove(expression);
expression = RedundantSubqueryRemover.Remove(expression);
expression = RedundantJoinRemover.Remove(expression);
expression = RedundantColumnRemover.Remove(expression);
}
return expression;
}
/// <summary>
/// Converts the query expression into text of this query language
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public virtual string Format(Expression expression)
{
// use common SQL formatter by default
return SqlFormatter.Format(expression);
}
/// <summary>
/// Determine which sub-expressions must be parameters
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public virtual Expression Parameterize(Expression expression)
{
return Parameterizer.Parameterize(this.language, expression);
}
}
} | 36.066116 | 114 | 0.533685 | [
"Apache-2.0"
] | akrisiun/System.Linq.Dynamic.Core | src/IQToolkit.Sql/Core/Data/Common/Language/QueryLanguage.cs | 13,094 | C# |
using System.Net.Sockets;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ReshaperCore.Messages;
using ReshaperCore.Messages.Entities.Http;
using ReshaperCore.Proxies;
using ReshaperCore.Rules;
using ReshaperCore.Rules.Thens;
namespace ReshaperTests
{
[TestClass]
public class ThenHttpConnectTests
{
[TestMethod]
public void ThenHttpConnect_PerformTest()
{
string hostname = "www.google.com";
int port = 90;
Mock<EventInfo> mockEventInfo = new Mock<EventInfo>();
Mock<ProxyConnection> mockProxyConnection = new Mock<ProxyConnection>(It.IsAny<ProxyHost>(), It.IsAny<ProxyInfo>(), It.IsAny<TcpClient>());
Mock<HttpMessage> mockHttpMessage = new Mock<HttpMessage>();
Mock<HttpHeaders> mockHttpHeaders = new Mock<HttpHeaders>();
EventInfo eventInfo = mockEventInfo.Object;
ProxyConnection proxyConnection = mockProxyConnection.Object;
HttpMessage httpMessage = mockHttpMessage.Object;
HttpHeaders httpHeaders = mockHttpHeaders.Object;
mockHttpMessage.SetupGet(mock => mock.Headers).Returns(httpHeaders);
var testCases = new[]
{
new
{
HasTargetConnection = false,
DataDirection = DataDirection.Target,
OverrideCurrentConnection = false,
HeaderValue = (string)null,
InitTargetChannelSuccess = false,
InitTargetChannelCalled = false,
ExpectedThenResponse = ThenResponse.BreakRules,
ExpectedHostname = (string)null,
ExpectedPort = (int?)null
},
new
{
HasTargetConnection = true,
DataDirection = DataDirection.Target,
OverrideCurrentConnection = true,
HeaderValue = $"{hostname}:{port}",
InitTargetChannelSuccess = true,
InitTargetChannelCalled = true,
ExpectedThenResponse = ThenResponse.Continue,
ExpectedHostname = hostname,
ExpectedPort = (int?)port
},
new
{
HasTargetConnection = false,
DataDirection = DataDirection.Target,
OverrideCurrentConnection = false,
HeaderValue = $"{hostname}:{port}",
InitTargetChannelSuccess = true,
InitTargetChannelCalled = true,
ExpectedThenResponse = ThenResponse.Continue,
ExpectedHostname = hostname,
ExpectedPort = (int?)port
},
new
{
HasTargetConnection = false,
DataDirection = DataDirection.Target,
OverrideCurrentConnection = false,
HeaderValue = $"{hostname}",
InitTargetChannelSuccess = true,
InitTargetChannelCalled = true,
ExpectedThenResponse = ThenResponse.Continue,
ExpectedHostname = hostname,
ExpectedPort = (int?)80
},
new
{
HasTargetConnection = false,
DataDirection = DataDirection.Target,
OverrideCurrentConnection = false,
HeaderValue = $"{hostname}:{port}",
InitTargetChannelSuccess = false,
InitTargetChannelCalled = true,
ExpectedThenResponse = ThenResponse.BreakRules,
ExpectedHostname = hostname,
ExpectedPort = (int?)port
}
};
foreach (var testCase in testCases)
{
ThenHttpConnect then = new ThenHttpConnect();
mockEventInfo.Reset();
mockProxyConnection.Reset();
mockHttpHeaders.Reset();
mockEventInfo.Setup(mock => mock.ProxyConnection).Returns(proxyConnection);
mockEventInfo.Setup(mock => mock.Direction).Returns(testCase.DataDirection);
mockEventInfo.Setup(mock => mock.Message).Returns(httpMessage);
mockHttpHeaders.Setup(mock => mock.GetOrDefault("Host")).Returns(testCase.HeaderValue);
mockProxyConnection.Setup(mock => mock.HasTargetConnection).Returns(testCase.HasTargetConnection);
if (testCase.InitTargetChannelCalled)
{
then.OverrideCurrentConnection = testCase.OverrideCurrentConnection;
mockProxyConnection.Setup(mock => mock.InitConnection(It.IsAny<DataDirection>(), It.IsAny<string>(), It.IsAny<int>())).Returns(testCase.InitTargetChannelSuccess);
Assert.AreEqual(testCase.ExpectedThenResponse, then.Perform(eventInfo));
mockProxyConnection.Verify(mock => mock.InitConnection(testCase.DataDirection, testCase.ExpectedHostname, testCase.ExpectedPort.GetValueOrDefault()), Times.Once);
}
else
{
then.OverrideCurrentConnection = testCase.OverrideCurrentConnection;
Assert.AreEqual(testCase.ExpectedThenResponse, then.Perform(eventInfo));
mockProxyConnection.Verify(mock => mock.InitConnection(It.IsAny<DataDirection>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never);
}
}
}
}
}
| 33.308271 | 167 | 0.724379 | [
"MIT"
] | synfron/Reshaper | ReshaperTests/ThenHttpConnectTests.cs | 4,432 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace AscheLib.UniMonad {
public static partial class Option {
private class MergeCore<T> : IOptionMonad<T[]> {
IOptionMonad<T>[] _sources;
public MergeCore(IOptionMonad<T>[] sources) {
_sources = sources;
}
public IOptionResult<T[]> RunOption() {
List<IOptionResult<T>> resultList = _sources.Select(source => source.RunOption()).ToList();
if(resultList.All(result => !result.IsNone)) return new JustResult<T[]>(resultList.Select(result => result.Value).ToArray());
return NoneResult<T[]>.Default;
}
}
public static IOptionMonad<T[]> Merge<T>(this IOptionMonad<T> self, params IOptionMonad<T>[] sources) {
List<IOptionMonad<T>> mergeList = new List<IOptionMonad<T>>() { self };
return Merge(mergeList.Concat(sources));
}
public static IOptionMonad<T[]> Merge<T>(IEnumerable<IOptionMonad<T>> sources) {
return Merge(sources.ToArray());
}
public static IOptionMonad<T[]> Merge<T>(params IOptionMonad<T>[] sources) {
return new MergeCore<T>(sources);
}
}
} | 37.482759 | 129 | 0.701012 | [
"MIT"
] | AscheLab/AscheLib.UniMonad | Assets/AscheLib/UniMonad/Monad/Option/Option.Merge.cs | 1,089 | C# |
using System;
namespace Xamarin.Forms.Controls.GalleryPages.GradientGalleries
{
public partial class BindableBrushGallery : ContentPage
{
public BindableBrushGallery()
{
InitializeComponent();
InitializeBrush();
BindingContext = this;
}
public LinearGradientBrush LinearGradient { get; set; }
void InitializeBrush()
{
LinearGradient = new LinearGradientBrush
{
GradientStops = new GradientStopCollection
{
new GradientStop { Color = Color.Red, Offset = 0.0f },
new GradientStop { Color = Color.Orange, Offset = 0.5f }
},
StartPoint = new Point(0, 0),
EndPoint = new Point(1, 0)
};
}
void OnUpdateBrushClicked(object sender, EventArgs e)
{
var random = new Random();
LinearGradient.GradientStops = new GradientStopCollection
{
new GradientStop { Color = Color.FromRgb(random.Next(255), random.Next(255), random.Next(255)), Offset = 0.0f },
new GradientStop { Color = Color.FromRgb(random.Next(255), random.Next(255), random.Next(255)), Offset = 0.5f }
};
}
}
} | 25.756098 | 116 | 0.686553 | [
"MIT"
] | AlleSchonWeg/Xamarin.Forms | Xamarin.Forms.Controls/GalleryPages/GradientGalleries/BindableBrushGallery.xaml.cs | 1,058 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using RegistrationServices.BusinessLayer.UseCase;
using Moq;
using RegistrationServices.BusinessLayer;
using OnlineServices.Shared.RegistrationServices.Interface;
using OnlineServices.Common.RegistrationServices.Interfaces;
using OnlineServices.Common.RegistrationServices.TransferObject;
namespace RegistrationServices.BusinessLayerTests.UseCase
{
[TestClass]
public class Assistant_UpdateSessionTest
{
Mock<IRSUnitOfWork> MockUofW = new Mock<IRSUnitOfWork>();
Mock<IRSSessionRepository> MockSessionRepository = new Mock<IRSSessionRepository>();
CourseTO course = new CourseTO {Id = 1, Name = "Course" };
UserTO teacher = new UserTO { Id = 1, Name = "teacher" };
[TestMethod]
public void UpdateSession_ThrowException_WhenSessionIsNull()
{
//ARRANGE
var assistant = new AssistantRole(MockUofW.Object);
//ASSERT
Assert.ThrowsException<ArgumentNullException>(() => assistant.UpdateSession(null));
}
[TestMethod]
public void UpdateSession_ThrowException_WhenSessionIdIsZero()
{
//ARRANGE
var sessionIdZero = new SessionTO { Id = 0, Course = null };
var assistant = new AssistantRole(MockUofW.Object);
//ASSERT
Assert.ThrowsException<Exception>(() => assistant.UpdateSession(sessionIdZero));
}
[TestMethod]
public void UpdateSession_ReturnsTrue_WhenAValidSessionIsProvidedAndUpdatedInDB()
{
//ARRANGE
MockSessionRepository.Setup(x => x.Update(It.IsAny<SessionTO>()));
MockUofW.Setup(x => x.SessionRepository).Returns(MockSessionRepository.Object);
var assistant = new AssistantRole(MockUofW.Object);
var user = new SessionTO { Id = 1, Course = course, Teacher = teacher };
//ASSERT
Assert.IsTrue(assistant.UpdateSession(user));
}
[TestMethod]
public void UpdateSession_UserRepositoryIsCalledOnce_WhenAValidSessionIsProvidedAndUpdatedInDB()
{
//ARRANGE
MockSessionRepository.Setup(x => x.Update(It.IsAny<SessionTO>()));
MockUofW.Setup( x => x.SessionRepository).Returns(MockSessionRepository.Object);
var ass = new AssistantRole(MockUofW.Object);
var userToUpdate = new SessionTO { Id = 1, Course = course, Teacher = teacher };
//ACT
ass.UpdateSession(userToUpdate);
MockSessionRepository.Verify( x => x.Update(It.IsAny<SessionTO>()), Times.Once);
}
}
}
| 37.418919 | 104 | 0.657999 | [
"Apache-2.0"
] | ambroise04/OnlineServices | UserServices/UserServices.BusinessLayerTests/UseCase/AssistantSessionTests/Assistant_UpdateSessionTest.cs | 2,771 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure;
using Microsoft.EntityFrameworkCore.SqlServer.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Storage;
// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore.Metadata.Conventions
{
/// <summary>
/// A convention that configures the filter for unique non-clustered indexes with nullable columns
/// to filter out null values.
/// </summary>
public class SqlServerIndexConvention :
IEntityTypeBaseTypeChangedConvention,
IIndexAddedConvention,
IIndexUniquenessChangedConvention,
IIndexAnnotationChangedConvention,
IPropertyNullabilityChangedConvention,
IPropertyAnnotationChangedConvention
{
private readonly ISqlGenerationHelper _sqlGenerationHelper;
/// <summary>
/// Creates a new instance of <see cref="SqlServerIndexConvention" />.
/// </summary>
/// <param name="dependencies"> Parameter object containing dependencies for this convention. </param>
/// <param name="relationalDependencies"> Parameter object containing relational dependencies for this convention. </param>
/// <param name="sqlGenerationHelper"> SQL command generation helper service. </param>
public SqlServerIndexConvention(
[NotNull] ProviderConventionSetBuilderDependencies dependencies,
[NotNull] RelationalConventionSetBuilderDependencies relationalDependencies,
[NotNull] ISqlGenerationHelper sqlGenerationHelper)
{
_sqlGenerationHelper = sqlGenerationHelper;
Dependencies = dependencies;
}
/// <summary>
/// Parameter object containing service dependencies.
/// </summary>
protected virtual ProviderConventionSetBuilderDependencies Dependencies { get; }
/// <summary>
/// Called after the base type of an entity type changes.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity type. </param>
/// <param name="newBaseType"> The new base entity type. </param>
/// <param name="oldBaseType"> The old base entity type. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
public virtual void ProcessEntityTypeBaseTypeChanged(
IConventionEntityTypeBuilder entityTypeBuilder,
IConventionEntityType newBaseType,
IConventionEntityType oldBaseType,
IConventionContext<IConventionEntityType> context)
{
if (oldBaseType == null
|| newBaseType == null)
{
foreach (var index in entityTypeBuilder.Metadata.GetDeclaredIndexes())
{
SetIndexFilter(index.Builder);
}
}
}
/// <summary>
/// Called after an index is added to the entity type.
/// </summary>
/// <param name="indexBuilder"> The builder for the index. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
public virtual void ProcessIndexAdded(
IConventionIndexBuilder indexBuilder,
IConventionContext<IConventionIndexBuilder> context)
=> SetIndexFilter(indexBuilder);
/// <summary>
/// Called after the uniqueness for an index is changed.
/// </summary>
/// <param name="indexBuilder"> The builder for the index. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
public virtual void ProcessIndexUniquenessChanged(
IConventionIndexBuilder indexBuilder,
IConventionContext<bool?> context)
=> SetIndexFilter(indexBuilder);
/// <summary>
/// Called after the nullability for a property is changed.
/// </summary>
/// <param name="propertyBuilder"> The builder for the property. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
public virtual void ProcessPropertyNullabilityChanged(
IConventionPropertyBuilder propertyBuilder,
IConventionContext<bool?> context)
{
foreach (var index in propertyBuilder.Metadata.GetContainingIndexes())
{
SetIndexFilter(index.Builder);
}
}
/// <summary>
/// Called after an annotation is changed on an index.
/// </summary>
/// <param name="indexBuilder"> The builder for the index. </param>
/// <param name="name"> The annotation name. </param>
/// <param name="annotation"> The new annotation. </param>
/// <param name="oldAnnotation"> The old annotation. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
public virtual void ProcessIndexAnnotationChanged(
IConventionIndexBuilder indexBuilder,
string name,
IConventionAnnotation annotation,
IConventionAnnotation oldAnnotation,
IConventionContext<IConventionAnnotation> context)
{
if (name == SqlServerAnnotationNames.Clustered)
{
SetIndexFilter(indexBuilder);
}
}
/// <summary>
/// Called after an annotation is changed on a property.
/// </summary>
/// <param name="propertyBuilder"> The builder for the property. </param>
/// <param name="name"> The annotation name. </param>
/// <param name="annotation"> The new annotation. </param>
/// <param name="oldAnnotation"> The old annotation. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
public virtual void ProcessPropertyAnnotationChanged(
IConventionPropertyBuilder propertyBuilder,
string name,
IConventionAnnotation annotation,
IConventionAnnotation oldAnnotation,
IConventionContext<IConventionAnnotation> context)
{
if (name == RelationalAnnotationNames.ColumnName)
{
foreach (var index in propertyBuilder.Metadata.GetContainingIndexes())
{
SetIndexFilter(index.Builder, columnNameChanged: true);
}
}
}
private IConventionIndexBuilder SetIndexFilter(IConventionIndexBuilder indexBuilder, bool columnNameChanged = false)
{
var index = indexBuilder.Metadata;
if (index.IsUnique
&& index.IsClustered() != true
&& GetNullableColumns(index) is List<string> nullableColumns
&& nullableColumns.Count > 0)
{
if (columnNameChanged
|| index.GetFilter() == null)
{
indexBuilder.HasFilter(CreateIndexFilter(nullableColumns));
}
}
else
{
if (index.GetFilter() != null)
{
indexBuilder.HasFilter(null);
}
}
return indexBuilder;
}
private string CreateIndexFilter(List<string> nullableColumns)
{
var builder = new StringBuilder();
for (var i = 0; i < nullableColumns.Count; i++)
{
if (i != 0)
{
builder.Append(" AND ");
}
builder
.Append(_sqlGenerationHelper.DelimitIdentifier(nullableColumns[i]))
.Append(" IS NOT NULL");
}
return builder.ToString();
}
private List<string> GetNullableColumns(IIndex index)
{
var tableName = index.DeclaringEntityType.GetTableName();
if (tableName == null)
{
return null;
}
var nullableColumns = new List<string>();
var table = StoreObjectIdentifier.Table(tableName, index.DeclaringEntityType.GetSchema());
foreach (var property in index.Properties)
{
var columnName = property.GetColumnName(table);
if (columnName == null)
{
return null;
}
if (!property.IsColumnNullable(table))
{
continue;
}
nullableColumns.Add(columnName);
}
return nullableColumns;
}
}
}
| 40.612335 | 132 | 0.600282 | [
"Apache-2.0"
] | FriendsTmCo/efcore | src/EFCore.SqlServer/Metadata/Conventions/SqlServerIndexConvention.cs | 9,219 | C# |
using System;
using System.Collections;
using UnityEngine;
using Utility.StateMachine;
namespace Mechanics.Boss.States
{
public class ChargeAttack : IState
{
private BossStateMachine _stateMachine;
private BossMovement _bossMovement;
private float _timeToRotate;
private float _acceleration;
private float _velocity;
private float _retreatSpeed;
private float _impactHold;
private bool _debug;
private Coroutine _chargeRoutine = null;
private bool _isRotated;
private bool _isRetreating;
public ChargeAttack(BossStateMachine stateMachine, BossMovement bossMovement, BossAiData data)
{
_stateMachine = stateMachine;
_bossMovement = bossMovement;
_timeToRotate = data.TimeToRotate;
_acceleration = data.ChargeAcceleration;
_retreatSpeed = data.RetreatSpeed;
_impactHold = data.ImpactHoldTime;
_debug = data.Debug;
}
public void Escalate()
{
_timeToRotate /= 1.5f;
}
public void Enter()
{
_velocity = 0;
if (_chargeRoutine != null) {
_stateMachine.StopCoroutine(_chargeRoutine);
}
if (_isRotated) {
if (_isRetreating) _bossMovement.StartSecondCharge();
NextEvent(Charge());
} else {
_bossMovement.StartCharge();
NextEvent(Rotate());
}
}
private void NextEvent(IEnumerator nextEvent)
{
_chargeRoutine = _stateMachine.StartCoroutine(nextEvent);
}
private IEnumerator Rotate()
{
//if (_debug) Debug.Log("ChargeAttack: Rotate");
for (float t = 0; t < _timeToRotate; t += Time.deltaTime) {
float delta = t / _timeToRotate;
_bossMovement.Rotate(90f * delta);
yield return null;
}
_isRotated = true;
NextEvent(Charge());
}
private IEnumerator Charge()
{
if (_debug) Debug.Log(" - Charge");
while (true) {
_velocity += _acceleration * Time.deltaTime;
bool finished = _bossMovement.Charge(_velocity * Time.deltaTime);
if (finished) {
break;
}
yield return null;
}
NextEvent(Impact());
}
private IEnumerator Impact()
{
//if (_debug) Debug.Log("ChargeAttack: Impact");
_bossMovement.Impact();
yield return new WaitForSecondsRealtime(_impactHold);
NextEvent(Retreat());
}
private IEnumerator Retreat()
{
_isRetreating = true;
if (_debug) Debug.Log(" - Retreat");
while (true) {
bool finished = _bossMovement.Retreat(_retreatSpeed * Time.deltaTime);
if (finished) {
break;
}
yield return null;
}
_isRetreating = false;
NextEvent(EndRotate());
}
private IEnumerator EndRotate()
{
//if (_debug) Debug.Log("ChargeAttack: EndRotate");
for (float t = 0; t < _timeToRotate; t += Time.deltaTime) {
float delta = t / _timeToRotate;
_bossMovement.Rotate(90f - 90f * delta);
yield return null;
}
_isRotated = false;
_stateMachine.BossFinishedAttack();
}
public void Tick()
{
}
public void FixedTick()
{
}
public void Exit()
{
if (_chargeRoutine != null) {
_stateMachine.StopCoroutine(_chargeRoutine);
}
}
}
} | 29.5 | 102 | 0.518341 | [
"MIT"
] | BrandonMCoffey/4368-Homework-01 | Assets/Scripts/Mechanics/Boss/States/ChargeAttack.cs | 3,953 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.