content
stringlengths
23
1.05M
using Moq; using RestEase.Implementation; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace RestEase.UnitTests.ImplementationFactoryTests { public class HeaderTests : ImplementationFactoryTestsBase { [Header("Class Header 1", "Yes")] [Header("Class Header 2", "Yes")] public interface IHasClassHeaders { [Get("foo")] Task FooAsync(); } public interface IHasMethodHeaders { [Get("foo")] [Header("Method Header 1", "Yes")] [Header("Method Header 2", "Yes")] Task FooAsync(); } public interface IHasParamHeaders { [Get("foo")] Task FooAsync([Header("Param Header 1")] string foo, [Header("Param Header 2")] object bar); } public interface IHasParamHeaderOfNonStringType { [Get("foo")] Task FooAsync([Header("Param Header")] int foo); } public interface IHasParamHeaderWithValue { [Get("foo")] Task FooAsync([Header("Param Header", "ShouldNotBeSet")] string foo); } [Header("Foo")] public interface IHasClassHeaderWithoutValue { [Get("foo")] Task FooAsync(); } [Header("Foo: Bar", "Bar")] public interface IHasClassHeaderWithColon { [Get("foo")] Task FooAsync(); } public interface IHasMethodHeaderWithColon { [Get("foo")] [Header("Foo: Bar", "Baz")] Task FooAsync(); } public interface IHasHeaderParamWithColon { [Get("foo")] Task FooAsync([Header("Foo: Bar")] string foo); } public interface IHasHeaderParamWithValue { [Get("foo")] Task FooAsync([Header("Foo", "Bar")] string foo); } public interface IHasPropertyHeaderWithValue { [Header("Name", "Value")] int Header { get; set; } } public interface IHasNullablePropertyHeaderWithValue { [Header("Name", "Value")] int? Header { get; set; } [Get("foo")] Task FooAsync(); } public interface IHasObjectPropertyHeaderWithValue { [Header("Name", "Value")] string Header { get; set; } [Get("foo")] Task FooAsync(); } public interface IHasPropertyHeaderWithColon { [Header("Name: Value")] string Header { get; set; } } public interface IHasPropertyHeaderWithGetterOnly { [Header("Name")] string Header { get; } } public interface IHasPropertyHeaderWithSetterOnly { [Header("Name")] string Header { set; } } public interface IHasPropertyHeader { [Header("X-API-Key", "IgnoredDefault")] string ApiKey { get; set; } [Get("foo")] Task FooAsync(); } public interface IHasAuthorizationHeader { [Header("Authorization")] AuthenticationHeaderValue Authorization { get; set; } [Get("foo")] Task FooAsync(); } public interface IHasNullHeaderValues { [Header("foo", null)] string Foo { get; set; } [Header("bar", null)] [Get("Foo")] Task FooAsync([Header("baz")] string header); } public interface IHasFormattedPathHeader { [Header("foo", Format = "C")] int Foo { get; set; } [Get("foo")] Task FooAsync(); } public interface IHasFormattedHeaderParam { [Get("foo")] Task FooAsync([Header("Foo", Format = "X2")] int foo); } public HeaderTests(ITestOutputHelper output) : base(output) { } [Fact] public void HandlesClassHeaders() { var requestInfo = this.Request<IHasClassHeaders>(x => x.FooAsync()); var expected = new[] { new KeyValuePair<string, string>("Class Header 1", "Yes"), new KeyValuePair<string, string>("Class Header 2", "Yes"), }; Assert.NotNull(requestInfo.ClassHeaders); Assert.Equal(expected, requestInfo.ClassHeaders.OrderBy(x => x.Key)); } [Fact] public void HandlesMethodHeaders() { var requestInfo = this.Request<IHasMethodHeaders>(x => x.FooAsync()); var expected = new[] { new KeyValuePair<string, string>("Method Header 1", "Yes"), new KeyValuePair<string, string>("Method Header 2", "Yes"), }; Assert.Equal(expected, requestInfo.MethodHeaders.OrderBy(x => x.Key)); } [Fact] public void HandlesParamHeaders() { var requestInfo = this.Request<IHasParamHeaders>(x => x.FooAsync("value 1", "value 2")); var headerParams = requestInfo.HeaderParams.ToList(); Assert.Equal(2, headerParams.Count); var serialized1 = headerParams[0].SerializeToString(null); Assert.Equal("Param Header 1", serialized1.Key); Assert.Equal("value 1", serialized1.Value); var serialized2 = headerParams[1].SerializeToString(null); Assert.Equal("Param Header 2", serialized2.Key); Assert.Equal("value 2", serialized2.Value); } [Fact] public void HandlesNullParamHeaders() { var requestInfo = this.Request<IHasParamHeaders>(x => x.FooAsync("value 1", null)); var headerParams = requestInfo.HeaderParams.ToList(); Assert.Equal(2, headerParams.Count); var serialized = headerParams[1].SerializeToString(null); Assert.Equal("Param Header 2", serialized.Key); Assert.Null(serialized.Value); } [Fact] public void HandlesNonStringParamHeaders() { var requestInfo = this.Request<IHasParamHeaderOfNonStringType>(x => x.FooAsync(3)); var headerParams = requestInfo.HeaderParams.ToList(); Assert.Single(headerParams); var serialized = headerParams[0].SerializeToString(null); Assert.Equal("Param Header", serialized.Key); Assert.Equal("3", serialized.Value); } [Fact] public void ThrowsIfParamHeaderHasValue() { this.VerifyDiagnostics<IHasParamHeaderWithValue>( // (4,28): Error REST009: Header attribute must have the form [Header("Param Header")], not [Header("Param Header", "ShouldNotBeSet")] // Header("Param Header", "ShouldNotBeSet") Diagnostic(DiagnosticCode.HeaderParameterMustNotHaveValue, @"Header(""Param Header"", ""ShouldNotBeSet"")").WithLocation(4, 28) ); } [Fact] public void ThrowsIfClassHeaderDoesNotHaveValue() { this.VerifyDiagnostics<IHasClassHeaderWithoutValue>( // (1,10): Error REST008: Header on interface must have a value (i.e. be of the form [Header("Foo", "Value Here")]) // Header("Foo") Diagnostic(DiagnosticCode.HeaderOnInterfaceMustHaveValue, @"Header(""Foo"")").WithLocation(1, 10) ); } [Fact] public void ThrowsIfClassHeaderHasColon() { this.VerifyDiagnostics<IHasClassHeaderWithColon>( // (1,10): Error REST010: Header attribute name 'Foo: Bar' must not contain a colon // Header("Foo: Bar", "Bar") Diagnostic(DiagnosticCode.HeaderMustNotHaveColonInName, @"Header(""Foo: Bar"", ""Bar"")").WithLocation(1, 10) ); } [Fact] public void ThrowsIfMethodHeaderHasColon() { this.VerifyDiagnostics<IHasMethodHeaderWithColon>( // (4,14): Error REST010: Header attribute name 'Foo: Bar' must not contain a colon // Header("Foo: Bar", "Baz") Diagnostic(DiagnosticCode.HeaderMustNotHaveColonInName, @"Header(""Foo: Bar"", ""Baz"")").WithLocation(4, 14) ); } [Fact] public void ThrowsIfHeaderParamHasColon() { this.VerifyDiagnostics<IHasHeaderParamWithColon>( // (4,28): Error REST010: Header attribute name 'Foo: Bar' must not contain a colon // Header("Foo: Bar") Diagnostic(DiagnosticCode.HeaderMustNotHaveColonInName, @"Header(""Foo: Bar"")").WithLocation(4, 28) ); } [Fact] public void ThrowsIfHeaderParamHasValue() { this.VerifyDiagnostics<IHasHeaderParamWithValue>( // (4,28): Error REST009: Header attribute must have the form [Header("Foo")], not [Header("Foo", "Bar")] // Header("Foo", "Bar") Diagnostic(DiagnosticCode.HeaderParameterMustNotHaveValue, @"Header(""Foo"", ""Bar"")").WithLocation(4, 28) ); } [Fact] public void ThrowsIfPropertyHeaderIsValueTypeAndHasValue() { this.VerifyDiagnostics<IHasPropertyHeaderWithValue>( // (3,14): Error REST012: [Header("Name", "Value")] on property (i.e. containing a default value) can only be used if the property type is nullable // Header("Name", "Value") Diagnostic(DiagnosticCode.HeaderPropertyWithValueMustBeNullable, @"Header(""Name"", ""Value"")").WithLocation(3, 14) ); } [Fact] public void UsesSpecifiedDefaultForNullableProperty() { var requestInfo = this.Request<IHasNullablePropertyHeaderWithValue>(x => x.FooAsync()); var propertyHeaders = requestInfo.PropertyHeaders.ToList(); Assert.Single(propertyHeaders); var serialized = propertyHeaders[0].SerializeToString(null); Assert.Equal("Name", serialized.Key); Assert.Equal("Value", serialized.Value); } [Fact] public void UsesSpecifiedDefaultForObjectProperty() { var requestInfo = this.Request<IHasObjectPropertyHeaderWithValue>(x => x.FooAsync()); var propertyHeaders = requestInfo.PropertyHeaders.ToList(); Assert.Single(propertyHeaders); var serialized = propertyHeaders[0].SerializeToString(null); Assert.Equal("Name", serialized.Key); Assert.Equal("Value", serialized.Value); } [Fact] public void ThrowsIfPropertyHeaderHasColon() { this.VerifyDiagnostics<IHasPropertyHeaderWithColon>( // (3,14): Error REST010: Header attribute name 'Name: Value' must not contain a colon // Header("Name: Value") Diagnostic(DiagnosticCode.HeaderMustNotHaveColonInName, @"Header(""Name: Value"")").WithLocation(3, 14) ); } [Fact] public void ThrowsIfPropertyHeaderOnlyHasGetter() { this.VerifyDiagnostics<IHasPropertyHeaderWithGetterOnly>( // (4,20): Error REST011: Property must have a getter and a setter // Header Diagnostic(DiagnosticCode.PropertyMustBeReadWrite, "Header").WithLocation(4, 20) ); } [Fact] public void ThrowsIfPropertyHeaderOnlyHasSetter() { this.VerifyDiagnostics<IHasPropertyHeaderWithSetterOnly>( // (4,20): Error REST011: Property must have a getter and a setter // Header Diagnostic(DiagnosticCode.PropertyMustBeReadWrite, "Header").WithLocation(4, 20) ); } [Fact] public void HandlesPropertyHeaders() { var requestInfo = this.Request<IHasPropertyHeader>(x => { x.ApiKey = "Foo Bar"; return x.FooAsync(); }); var propertyHeaders = requestInfo.PropertyHeaders.ToList(); Assert.Single(propertyHeaders); var serialized = propertyHeaders[0].SerializeToString(null); Assert.Equal("X-API-Key", serialized.Key); Assert.Equal("Foo Bar", serialized.Value); } [Fact] public void PropertyHeadersBehaveAsReadHeaders() { var implementation = this.CreateImplementation<IHasPropertyHeader>(); Assert.Null(implementation.ApiKey); implementation.ApiKey = "test"; Assert.Equal("test", implementation.ApiKey); implementation.ApiKey = null; Assert.Null(implementation.ApiKey); } [Fact] public void SpecifyingAuthorizationHeaderWorksAsExpected() { // Values from http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side string value = Convert.ToBase64String(Encoding.ASCII.GetBytes("Aladdin:open sesame")); var requestInfo = this.Request<IHasAuthorizationHeader>(x => { x.Authorization = new AuthenticationHeaderValue("Basic", value); return x.FooAsync(); }); var propertyHeaders = requestInfo.PropertyHeaders.ToList(); Assert.Single(propertyHeaders); var serialized = propertyHeaders[0].SerializeToString(null); Assert.Equal("Authorization", serialized.Key); Assert.Equal("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", serialized.Value); } [Fact] public void HandlesNullHeaderValues() { this.VerifyDiagnostics<IHasNullHeaderValues>(); } [Fact] public void HandlesFormattedPathHeader() { var requestInfo = this.Request<IHasFormattedPathHeader>(x => { x.Foo = 10; return x.FooAsync(); }); Assert.Single(requestInfo.PropertyHeaders); var serialized = requestInfo.PropertyHeaders.First().SerializeToString(CultureInfo.InvariantCulture); Assert.Equal("foo", serialized.Key); Assert.Equal("¤10.00", serialized.Value); } [Fact] public void HandlesFormattedHeaderParam() { var requestInfo = this.Request<IHasFormattedHeaderParam>(x => x.FooAsync(12)); Assert.Single(requestInfo.HeaderParams); var serialized = requestInfo.HeaderParams.First().SerializeToString(null); Assert.Equal("Foo", serialized.Key); Assert.Equal("0C", serialized.Value); } [Fact] public void FormattedPathHeaderUsesGivenFormatProvider() { var formatProvider = new Mock<IFormatProvider>(); var requestInfo = this.Request<IHasFormattedPathHeader>(x => x.FooAsync()); Assert.Single(requestInfo.PropertyHeaders); var serialized = requestInfo.PropertyHeaders.First().SerializeToString(formatProvider.Object); formatProvider.Verify(x => x.GetFormat(typeof(NumberFormatInfo))); } } }
/** * Autogenerated by Thrift Compiler (0.9.2) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using Thrift; using Thrift.Collections; using System.Runtime.Serialization; using Thrift.Protocol; using Thrift.Transport; namespace Net.Thrift { #if !SILVERLIGHT [Serializable] #endif public partial class ProtocolHeader : TBase { private PeerType _targetType; private PeerType _sourceType; private int _targetId; private int _sourceId; private long _channelId; private SerializeType _serializeType; private int _protocolHash; private sbyte _flag; private bool _closeSocket; /// <summary> /// /// <seealso cref="PeerType"/> /// </summary> public PeerType TargetType { get { return _targetType; } set { __isset.targetType = true; this._targetType = value; } } /// <summary> /// /// <seealso cref="PeerType"/> /// </summary> public PeerType SourceType { get { return _sourceType; } set { __isset.sourceType = true; this._sourceType = value; } } public int TargetId { get { return _targetId; } set { __isset.targetId = true; this._targetId = value; } } public int SourceId { get { return _sourceId; } set { __isset.sourceId = true; this._sourceId = value; } } public long ChannelId { get { return _channelId; } set { __isset.channelId = true; this._channelId = value; } } /// <summary> /// /// <seealso cref="SerializeType"/> /// </summary> public SerializeType SerializeType { get { return _serializeType; } set { __isset.serializeType = true; this._serializeType = value; } } public int ProtocolHash { get { return _protocolHash; } set { __isset.protocolHash = true; this._protocolHash = value; } } public sbyte Flag { get { return _flag; } set { __isset.flag = true; this._flag = value; } } public bool CloseSocket { get { return _closeSocket; } set { __isset.closeSocket = true; this._closeSocket = value; } } public Isset __isset; #if !SILVERLIGHT [Serializable] #endif public struct Isset { public bool targetType; public bool sourceType; public bool targetId; public bool sourceId; public bool channelId; public bool serializeType; public bool protocolHash; public bool flag; public bool closeSocket; } public ProtocolHeader() { this._targetType = PeerType.PEER_TYPE_DEFAULT; this.__isset.targetType = true; this._sourceType = PeerType.PEER_TYPE_CLIENT; this.__isset.sourceType = true; this._serializeType = SerializeType.SERIALIZE_TYPE_THRIFT; this.__isset.serializeType = true; this._closeSocket = false; this.__isset.closeSocket = true; } public void Read (TProtocol iprot) { TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.I32) { TargetType = (PeerType)iprot.ReadI32(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 2: if (field.Type == TType.I32) { SourceType = (PeerType)iprot.ReadI32(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 3: if (field.Type == TType.I32) { TargetId = iprot.ReadI32(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 4: if (field.Type == TType.I32) { SourceId = iprot.ReadI32(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 5: if (field.Type == TType.I64) { ChannelId = iprot.ReadI64(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 6: if (field.Type == TType.I32) { SerializeType = (SerializeType)iprot.ReadI32(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 7: if (field.Type == TType.I32) { ProtocolHash = iprot.ReadI32(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 8: if (field.Type == TType.Byte) { Flag = iprot.ReadByte(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 9: if (field.Type == TType.Bool) { CloseSocket = iprot.ReadBool(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); } public void Write(TProtocol oprot) { TStruct struc = new TStruct("ProtocolHeader"); oprot.WriteStructBegin(struc); TField field = new TField(); if (__isset.targetType) { field.Name = "targetType"; field.Type = TType.I32; field.ID = 1; oprot.WriteFieldBegin(field); oprot.WriteI32((int)TargetType); oprot.WriteFieldEnd(); } if (__isset.sourceType) { field.Name = "sourceType"; field.Type = TType.I32; field.ID = 2; oprot.WriteFieldBegin(field); oprot.WriteI32((int)SourceType); oprot.WriteFieldEnd(); } if (__isset.targetId) { field.Name = "targetId"; field.Type = TType.I32; field.ID = 3; oprot.WriteFieldBegin(field); oprot.WriteI32(TargetId); oprot.WriteFieldEnd(); } if (__isset.sourceId) { field.Name = "sourceId"; field.Type = TType.I32; field.ID = 4; oprot.WriteFieldBegin(field); oprot.WriteI32(SourceId); oprot.WriteFieldEnd(); } if (__isset.channelId) { field.Name = "channelId"; field.Type = TType.I64; field.ID = 5; oprot.WriteFieldBegin(field); oprot.WriteI64(ChannelId); oprot.WriteFieldEnd(); } if (__isset.serializeType) { field.Name = "serializeType"; field.Type = TType.I32; field.ID = 6; oprot.WriteFieldBegin(field); oprot.WriteI32((int)SerializeType); oprot.WriteFieldEnd(); } if (__isset.protocolHash) { field.Name = "protocolHash"; field.Type = TType.I32; field.ID = 7; oprot.WriteFieldBegin(field); oprot.WriteI32(ProtocolHash); oprot.WriteFieldEnd(); } if (__isset.flag) { field.Name = "flag"; field.Type = TType.Byte; field.ID = 8; oprot.WriteFieldBegin(field); oprot.WriteByte(Flag); oprot.WriteFieldEnd(); } if (__isset.closeSocket) { field.Name = "closeSocket"; field.Type = TType.Bool; field.ID = 9; oprot.WriteFieldBegin(field); oprot.WriteBool(CloseSocket); oprot.WriteFieldEnd(); } oprot.WriteFieldStop(); oprot.WriteStructEnd(); } public override string ToString() { StringBuilder __sb = new StringBuilder("ProtocolHeader("); bool __first = true; if (__isset.targetType) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("TargetType: "); __sb.Append(TargetType); } if (__isset.sourceType) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("SourceType: "); __sb.Append(SourceType); } if (__isset.targetId) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("TargetId: "); __sb.Append(TargetId); } if (__isset.sourceId) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("SourceId: "); __sb.Append(SourceId); } if (__isset.channelId) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("ChannelId: "); __sb.Append(ChannelId); } if (__isset.serializeType) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("SerializeType: "); __sb.Append(SerializeType); } if (__isset.protocolHash) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("ProtocolHash: "); __sb.Append(ProtocolHash); } if (__isset.flag) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Flag: "); __sb.Append(Flag); } if (__isset.closeSocket) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("CloseSocket: "); __sb.Append(CloseSocket); } __sb.Append(")"); return __sb.ToString(); } } }
using System.Text.Json.Serialization; namespace SimplyCast.Models.SMS { public class Campaign { [JsonPropertyName("id")] public int Id { get; set; } [JsonPropertyName("status")] public string Status { get; set; } [JsonPropertyName("totalPrice")] public float TotalPrice { get; set; } [JsonPropertyName("totalQueued")] public int TotalQueued { get; set; } [JsonPropertyName("totalSent")] public int TotalSent { get; set; } [JsonPropertyName("totalFailed")] public int TotalFailed { get; set; } [JsonPropertyName("sentTime")] public DateTime SentTime { get; set; } [JsonPropertyName("transactional")] public int Transactional { get; set; } [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("message")] public string Message { get; set; } [JsonPropertyName("totalResponses")] public int TotalResponses { get; set; } [JsonPropertyName("lists")] public CampaignList[]? Lists { get; set; } [JsonPropertyName("links")] public Link[] Links { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace EgnValidator.Services { public interface IValidateEgn { string IsValid(string egn); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; using Abp.Domain.Entities; using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Xn.Models.Employees { public class Employees:Entity { public string Name { get; set; } public string Phone { get; set; } public DateTime? Birthday { get; set; } public string Position { get; set; } [ForeignKey("Company")] public string Code { get; set; } public string KeyUser { get; set; } public int IdCty { get; set; } public long CreateIdUser { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Dx.Wopi.Models { internal interface IFileUrlProperties { Uri CloseUrl { get; set; } Uri DownloadUrl { get; set; } Uri FileSharingUrl { get; set; } Uri HostEditUrl { get; set; } Uri HostViewUrl { get; set; } Uri SignoutUrl { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; namespace Cofoundry.Web.Admin { public class StandardAngularModuleController : BaseAdminMvcController { public ActionResult Index() { var vm = new StandardAngularModuleViewModel(); vm.RouteLibrary = RouteData.DataTokens["RouteLibrary"] as AngularModuleRouteLibrary; if (vm.RouteLibrary == null) throw new Exception("The 'RouteLibrary' route data token should not be null."); vm.Title = RouteData.DataTokens["ModuleTitle"] as string; if (vm.RouteLibrary == null) throw new Exception("The 'ModuleTitle' route data token should not be null."); return View("~/Framework/Angular/StandardAngularModules/Routes/Index.cshtml", vm); } } }
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using System; using System.IO; namespace VketTools { /// <summary> /// A.提出形式 /// 01:Unity 2017.4.15f1で作成すること /// </summary> public class UnityVersionRule : BaseRule { public new string ruleName = "A01:Unity version Rule"; public override string RuleName { get { return ruleName; } } public UnityVersionRule(Options _options) : base(_options) { } public override Result Validate() { base.Validate(); Result result; string actualVer = Application.unityVersion; string expectedVer = "2017.4.15f1"; AddResultLog("Unity version:" + actualVer); if (Application.unityVersion == expectedVer) { result = Result.SUCCESS; } else { result = Result.FAIL; } return SetResult(result); } } }
using System.Threading.Tasks; namespace AJProds.EFDataSeeder { /// <summary> /// Seed procedure implementation. /// Register your seed implementations with the <see cref="Extensions.RegisterDataSeeder{TSeeder}"/> /// </summary> /// <remarks> /// <see cref="Extensions.RegisterDataSeeder{TSeeder}"/> can register multiple implementation types /// behind the <see cref="ISeed"/> interface /// </remarks> public interface ISeed { /// <summary> /// The lower priority (number) will run earlier /// </summary> public int Priority { get; } /// <summary> /// Unique identifier for this seed. /// </summary> public string SeedName { get; } /// <inheritdoc cref="SeedMode"/> public SeedMode Mode { get; } /// <summary> /// Should this seed run everytime when the seed procedures got triggered? /// </summary> public bool AlwaysRun { get; } /// <summary> /// Runs the data injection /// </summary> public Task SeedAsync(); } }
/* Licensed under the MIT/X11 license. * Copyright (c) 2016-2018 jointly owned by eBestow Technocracy India Pvt. Ltd. & M&M Info-Tech UK Ltd. * This notice may not be removed from any source distribution. * See license.txt for detailed licensing details. */ // Author: Mukesh Adhvaryu. using System; using System.Collections.Generic; namespace MnM.GWS { public sealed class GenreCollection : _Lexicon<string, Type, IGenre>, IGenreCollection { #region CONSTRUCTORS /// <summary> /// Initializes a new instance of the <see cref="GenreCollection"/> class. /// </summary> public GenreCollection() { } /// <summary> /// Initializes a new instance of the <see cref="GenreCollection"/> class. /// </summary> /// <param name="capacity">The capacity.</param> public GenreCollection(int capacity) : base(capacity) {; } /// <summary> /// Initializes a new instance of the <see cref="GenreCollection"/> class. /// </summary> /// <param name="source">The source.</param> public GenreCollection(IEnumerable<IGenre> source) : base(source) { } /// <summary> /// Initializes a new instance of the <see cref="GenreCollection"/> class. /// </summary> /// <param name="types">The types.</param> public GenreCollection(params Type[] types) { foreach (var item in types) { if (item != null) { Add(Factory.newGenre(item, false)); } else base.Add(null); } } #endregion #region ADD /// <summary> /// Adds the specified tp. /// </summary> /// <param name="tp">The tp.</param> public void Add(Type tp) { if (tp == null) { IGenre g = null; base.Add(g); } else { Add(Factory.newGenre(tp, false)); } } #endregion #region ADD RANGE public void AddRange(IEnumerable<Type> collection) { foreach (var t in collection) { Add(t); } } #endregion #region FIND GENRE FROM EXPRSSION public IGenre GetGenre(string Expression) { Entry<IGenre> seek = this.Find(Criteria.StringEqualNoCase, Expression); if (seek) return seek.Value; return null; } #endregion } }
using Newtonsoft.Json; namespace CFAN_netfan.CfanAggregator.FactorioCom.Schema { public class ModsPageJson { [JsonProperty(Required = Required.Always)] public PaginationJson pagination; [JsonProperty(Required = Required.Always)] public ModJson[] results; public class PaginationJson { public uint count; public uint page_size; public LinksJson links; public uint page_count; public uint page; public class LinksJson { public string next; public string first; public string last; public string prev; } } } }
using System; using System.Threading.Tasks; using Plivo.Client; namespace Plivo.Resource.Account { /// <summary> /// Account. /// </summary> public class Account : Resource { /// <summary> /// Gets the identifier. /// </summary> /// <value>The identifier.</value> public new string Id => AuthId; /// <summary> /// Gets or sets the type of the account. /// </summary> /// <value>The type of the account.</value> public string AccountType { get; set; } /// <summary> /// Gets or sets the address. /// </summary> /// <value>The address.</value> public string Address { get; set; } /// <summary> /// Gets or sets the auth identifier. /// </summary> /// <value>The auth identifier.</value> public string AuthId { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:plivo.Resource.Account.Account"/> auto recharge. /// </summary> /// <value><c>true</c> if auto recharge; otherwise, <c>false</c>.</value> public bool AutoRecharge { get; set; } /// <summary> /// Gets or sets the billing mode. /// </summary> /// <value>The billing mode.</value> public string BillingMode { get; set; } /// <summary> /// Gets or sets the cash credits. /// </summary> /// <value>The cash credits.</value> public string CashCredits { get; set; } /// <summary> /// Gets or sets the city. /// </summary> /// <value>The city.</value> public string City { get; set; } /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public string Name { get; set; } /// <summary> /// Gets or sets the resource URI. /// </summary> /// <value>The resource URI.</value> public string ResourceUri { get; set; } /// <summary> /// Gets or sets the state. /// </summary> /// <value>The state.</value> public string State { get; set; } /// <summary> /// Gets or sets the timezone. /// </summary> /// <value>The timezone.</value> public string Timezone { get; set; } // public Account(string accountType, string address, string authId, bool autoRecharge, string billingMode, // string cashCredits, string city, string name, string resourceUri, string state, string timezone) // { // AccountType = accountType ?? throw new ArgumentNullException(nameof(accountType)); // Address = address ?? throw new ArgumentNullException(nameof(address)); // AuthId = authId ?? throw new ArgumentNullException(nameof(authId)); // AutoRecharge = autoRecharge; // BillingMode = billingMode ?? throw new ArgumentNullException(nameof(billingMode)); // CashCredits = cashCredits ?? throw new ArgumentNullException(nameof(cashCredits)); // City = city ?? throw new ArgumentNullException(nameof(city)); // Name = name ?? throw new ArgumentNullException(nameof(name)); // ResourceUri = resourceUri ?? throw new ArgumentNullException(nameof(resourceUri)); // State = state ?? throw new ArgumentNullException(nameof(state)); // Timezone = timezone ?? throw new ArgumentNullException(nameof(timezone)); // } #region Update /// <summary> /// Update the specified name, city and address. /// </summary> /// <returns>The update.</returns> /// <param name="name">Name.</param> /// <param name="city">City.</param> /// <param name="address">Address.</param> /// <param state="state">State.</param> public UpdateResponse<Account> Update(string name = null, string city = null, string address = null, string state=null) { var updateResponse = ((AccountInterface) Interface).Update(name, city, address, state); if (name != null) Name = name; if (city != null) City = city; if (address != null) Address = address; if (state != null) State = state; return updateResponse; } /// <summary> /// Asynchronously update the specified name, city and address. /// </summary> /// <returns>The update.</returns> /// <param name="name">Name.</param> /// <param name="city">City.</param> /// <param name="address">Address.</param> /// <param name="state">State.</param> public async Task<UpdateResponse<Account>> UpdateAsync(string name = null, string city = null, string address = null, string state = null) { var updateResponse = await ((AccountInterface)Interface).UpdateAsync(name, city, address); if (name != null) Name = name; if (city != null) City = city; if (address != null) Address = address; if (state != null) State = state; return updateResponse; } #endregion /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:plivo.Resource.Account.Account"/>. /// </summary> /// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:plivo.Resource.Account.Account"/>.</returns> public override string ToString() { return "Account Type: " + AccountType + "\n" + "Address: " + Address + "\n" + "AuthId: " + AuthId + "\n" + "AutoRecharge: " + AutoRecharge + "\n" + "BillingMode: " + BillingMode + "\n" + "CashCredits: " + CashCredits + "\n" + "City: " + City + "\n" + "Name: " + Name + "\n" + "ResourceUri: " + ResourceUri + "\n" + "State: " + State + "\n" + "Timezone: " + Timezone + "\n"; } } }
 namespace DFW_Draw_Generator { partial class GroupStageForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.textBox_tier1 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.textBox_tier2 = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.textBox_tier3 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.textBox_tier4 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // textBox_tier1 // this.textBox_tier1.Location = new System.Drawing.Point(82, 40); this.textBox_tier1.Name = "textBox_tier1"; this.textBox_tier1.Size = new System.Drawing.Size(242, 21); this.textBox_tier1.TabIndex = 0; this.textBox_tier1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox_tier1_KeyPress); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(30, 43); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(35, 12); this.label1.TabIndex = 1; this.label1.Text = "一档:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(30, 82); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(35, 12); this.label2.TabIndex = 3; this.label2.Text = "二档:"; // // textBox_tier2 // this.textBox_tier2.Location = new System.Drawing.Point(82, 79); this.textBox_tier2.Name = "textBox_tier2"; this.textBox_tier2.Size = new System.Drawing.Size(242, 21); this.textBox_tier2.TabIndex = 2; this.textBox_tier2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox_tier2_KeyPress); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(30, 122); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(35, 12); this.label3.TabIndex = 5; this.label3.Text = "三档:"; // // textBox_tier3 // this.textBox_tier3.Location = new System.Drawing.Point(82, 119); this.textBox_tier3.Name = "textBox_tier3"; this.textBox_tier3.Size = new System.Drawing.Size(242, 21); this.textBox_tier3.TabIndex = 4; this.textBox_tier3.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox_tier3_KeyPress); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(30, 162); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(35, 12); this.label4.TabIndex = 7; this.label4.Text = "四档:"; // // textBox_tier4 // this.textBox_tier4.Location = new System.Drawing.Point(82, 159); this.textBox_tier4.Name = "textBox_tier4"; this.textBox_tier4.Size = new System.Drawing.Size(242, 21); this.textBox_tier4.TabIndex = 6; this.textBox_tier4.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox_tier4_KeyPress); // // GroupStageForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(432, 482); this.Controls.Add(this.label4); this.Controls.Add(this.textBox_tier4); this.Controls.Add(this.label3); this.Controls.Add(this.textBox_tier3); this.Controls.Add(this.label2); this.Controls.Add(this.textBox_tier2); this.Controls.Add(this.label1); this.Controls.Add(this.textBox_tier1); this.Name = "GroupStageForm"; this.Text = "Group Stage"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.GroupStageForm_FormClosed); this.Load += new System.EventHandler(this.GroupStageForm_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBox_tier1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBox_tier2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox_tier3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBox_tier4; } }
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace PartialClassTest1 { public partial class Point /* Level 0 */ { private BigInteger _x; private BigInteger _y; } }
using System; using System.IO; using System.Threading.Tasks; namespace NusRipper { public static class FileIdentification { private const int MagicSampleSize = 32; // Magic Bytes private static readonly byte[] GifMagic1 = { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }; // GIF87a private static readonly byte[] GifMagic2 = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }; // GIF89a private static readonly byte[] BmpMagic = { 0x42, 0x4D }; // BM private static readonly byte[] JpegMagic = { 0xFF, 0xD8, 0xFF }; // ÿØÿ private static readonly byte[] PngMagic = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; // .PNG.... private static readonly byte[] ZipMagic = { 0x50, 0x4B }; // PK public static async Task<string> DetermineImageFileExtension(string path) { byte[] startingBytes; await using (FileStream fs = File.OpenRead(path)) { startingBytes = new byte[MagicSampleSize]; await fs.ReadAsync(startingBytes, 0, MagicSampleSize); } if (startingBytes.StartsWith(GifMagic1) || startingBytes.StartsWith(GifMagic2)) return "gif"; if (startingBytes.StartsWith(BmpMagic)) return "bmp"; if (startingBytes.StartsWith(JpegMagic)) return "jpg"; if (startingBytes.StartsWith(PngMagic)) return "png"; if (startingBytes.StartsWith(ZipMagic)) return "zip"; Log.Instance.Error($"Unknown file type for file '{path}'."); return "bin"; } } }
namespace AstroAdapters.Services { public interface IChannel { void Subscribe<T>(string topic, Action<string, T?> action) where T: class; void Publish<T>(string topic, T? payload) where T: class; } }
using System.Diagnostics; using Microsoft.Extensions.CommandLineUtils; namespace CliHelpers { public sealed class CliFlag { CommandOption m_Option; internal CliFlag(CommandOption option) { Debug.Assert(option != null); Debug.Assert(option.OptionType == CommandOptionType.NoValue); m_Option = option; } public bool IsSet() { return m_Option.HasValue(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Asteroid : MonoBehaviour { public GameObject deathExplosion; public int pointValue; public AudioClip deathKnell; // Use this for initialization void Start () { pointValue = 10; } // Update is called once per frame void Update () { } public void Die() { AudioSource.PlayClipAtPoint(deathKnell, gameObject.transform.position); Instantiate(deathExplosion, gameObject.transform.position, Quaternion.AngleAxis(-90, Vector3.right)); GameObject obj = GameObject.Find("GlobalObject"); Global g = obj.GetComponent<Global>(); g.score += pointValue; Destroy(gameObject); } }
using System; using System.Linq; using System.Reflection; public class AmmunitionFactory : IAmmunitionFactory { public IAmmunition CreateAmmunition(string ammunitionType) { Type typeOfAmmunition = Assembly.GetCallingAssembly().GetTypes() .SingleOrDefault(type => type.Name == ammunitionType); if (typeOfAmmunition == null) throw new ArgumentException( String.Format(OutputMessages.MissingAmmunitionType, ammunitionType)); if (!typeof(IAmmunition).IsAssignableFrom(typeOfAmmunition)) throw new InvalidOperationException( String.Format(OutputMessages.InvalidAmmunitionType, ammunitionType)); IAmmunition ammunition = (IAmmunition)Activator.CreateInstance(typeOfAmmunition); return ammunition; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WeepingSnake.Game.Geometry; using WeepingSnake.Game.Player; using Xunit; namespace WeepingSnake.Game.Tests.Player { public class PlayerActionTests { [Fact] public void TestApply() { // Arrange var mockPlayer = new MockPlayer(); mockPlayer.ApplyOrientationAndMoveFunc = (_) => new GameDistance(4, 0, new PlayerDirection(), mockPlayer); var position = new GameCoordinate(0, 0, 1); var direction = new PlayerDirection(4, 0); var orientation = new PlayerOrientation(position, direction); var playerAction = new PlayerAction(mockPlayer, orientation, PlayerAction.Action.CHANGE_NOTHING); // Act var result = playerAction.Apply(); // Assert Assert.Equal(4, playerAction.NewOrientation.Position.X); Assert.Equal(0, playerAction.NewOrientation.Position.Y); Assert.True(result.HasValue); Assert.Equal(4, result.Value.StartX); Assert.Equal(0, result.Value.StartY); Assert.Equal(4, result.Value.EndX); Assert.Equal(0, result.Value.EndY); } } }
// // Copyright 2013, Leanplum, Inc. // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. namespace LeanplumSDK { internal class UnityWebResponse : WebResponse { private readonly string error; private long statusCode; private readonly string responseBody; private readonly object responseBodyAsAsset; public UnityWebResponse(long statusCode, string error, string text, object data) { this.statusCode = statusCode; this.error = error; this.responseBody = text; this.responseBodyAsAsset = data; } public override long GetStatusCode() { #if LP_UNITYWEBREQUEST return statusCode; #else if (error != null) { if (error[0] == '4' || error[0] == '5') { string code = error.Substring(0, 3); if (!string.IsNullOrEmpty(code) && long.TryParse(code, out statusCode)) { return statusCode; } else { return 400; } } else { return statusCode; } } return statusCode; #endif } public override string GetError() { return error; } public override string GetResponseBody() { return responseBody; } public override object GetResponseAsAsset() { return responseBodyAsAsset; } } }
using Simple1C.Impl.Helpers; using Simple1C.Impl.Sql.SqlAccess.Syntax; using Simple1C.Impl.Sql.Translation.QueryEntities; namespace Simple1C.Impl.Sql.Translation.Visitors { internal class DeduceEntityTypeFromIsReferenceExpressionVisitor : SqlVisitor { private readonly QueryEntityTree queryEntityTree; public DeduceEntityTypeFromIsReferenceExpressionVisitor(QueryEntityTree queryEntityTree) { this.queryEntityTree = queryEntityTree; } public override SelectClause VisitSelect(SelectClause clause) { var result = base.VisitSelect(clause); VisitCondition(result.WhereExpression); return result; } private void VisitCondition(ISqlElement sqlElement) { if (sqlElement == null) return; var isReference = sqlElement as IsReferenceExpression; if (isReference != null) { SetPropertyType(isReference.Argument, isReference.ObjectName); return; } var andExpression = sqlElement as AndExpression; if (andExpression != null) { VisitCondition(andExpression.Left); VisitCondition(andExpression.Right); } } private void SetPropertyType(ColumnReferenceExpression columnReference, string name) { var queryRoot = queryEntityTree.Get(columnReference.Table); var propertyNames = columnReference.Name.Split('.'); var referencedProperties = queryEntityTree.GetProperties(queryRoot, propertyNames); foreach (var property in referencedProperties) property.nestedEntities.RemoveAll(entity => !entity.mapping.QueryTableName.EqualsIgnoringCase(name)); } } }
using System; class CenterPoint { static void Main() { double pointX1 = double.Parse(Console.ReadLine()); double pointY1 = double.Parse(Console.ReadLine()); double pointX2 = double.Parse(Console.ReadLine()); double pointY2 = double.Parse(Console.ReadLine()); Console.WriteLine("(" + String.Join(", ", GetNearestPoint(pointX1, pointY1, pointX2, pointY2)) + ")"); } static double[] GetNearestPoint(double x1, double y1, double x2, double y2) { double[] points = new double[2]; if (Math.Sqrt(Math.Pow(x1, 2) + Math.Pow(y1, 2)) < Math.Sqrt(Math.Pow(x2, 2) + Math.Pow(y2, 2))) { points[0] = x1; points[1] = y1; return points; } else { points[0] = x2; points[1] = y2; return points; } } }
using Sitecore.XConnect.Collection.Model; namespace Feature.FormsExtensions.Business.FieldBindings.xDbBindingHandlers.ContactPersonalInfo { public abstract class PersonalInformationBindingHandler : BaseXDbBindingHandler<PersonalInformation> { protected override string GetFacetKey() { return PersonalInformation.DefaultFacetKey; } protected override PersonalInformation CreateFacet() { return new PersonalInformation(); } } }
@using Mictlanix.BE @{ ViewBag.Title = Resources.SinchronizeTimeClocks; }
using System; using System.Xml; namespace SignalVisualizer.Contracts { /// <summary> /// Represents a configurable object. /// </summary> public interface IConfigurable { /// <summary> /// Configures the object. /// </summary> void Configure(); /// <summary> /// Loads the object configuration from a XML storage. /// </summary> /// <param name="element">The XML element that contains the configuration data to load.</param> void Load(XmlElement element); /// <summary> /// Stores the object configuration to a XML storage. /// </summary> /// <param name="writer">The XML writer to write the configuration data to.</param> void Save(XmlWriter writer); /// <summary> /// Raised when the configuration is internally changed. /// </summary> event EventHandler ConfigurationChanged; } }
// Copyright(c) 2019 Ken Okabe // This software is released under the MIT License, see LICENSE. using System; namespace BowlingGame { public class Game { bool firstThrowInFrame = true; Scorer itsScorer = new Scorer(); public int Score { get { return ScoreForFrame(CurrentFrame - 1); } } public int CurrentFrame { get; private set; } = 1; public void Add(int pins) { itsScorer.AddThrow(pins); AdjustCurrentFrame(pins); } void AdjustCurrentFrame(int pins) { if (firstThrowInFrame) { if (!AdjustFrameForStrike(pins)) firstThrowInFrame = false; } else { firstThrowInFrame = true; AdvanceFrame(); } } bool AdjustFrameForStrike(int pins) { if (pins == 10) { AdvanceFrame(); return true; } return false; } void AdvanceFrame() { CurrentFrame = Math.Min(11, CurrentFrame + 1); } public int ScoreForFrame(int theFrame) { return itsScorer.ScoreForFrame(theFrame); } } }
using System.Numerics; using NeoSharp.VM; namespace NeoSharp.Core.SmartContract.ContractParameters { public class IntegerContractParameter : ContractParameter { public IntegerContractParameter(int value) : base(ContractParameterType.Integer, value) { } public IntegerContractParameter(short value) : base(ContractParameterType.Integer, value) { } public IntegerContractParameter(long value) : base(ContractParameterType.Integer, value) { } public IntegerContractParameter(byte value) : base(ContractParameterType.Integer, value) { } public IntegerContractParameter(uint value) : base(ContractParameterType.Integer, value) { } public IntegerContractParameter(ushort value) : base(ContractParameterType.Integer, value) { } public IntegerContractParameter(ulong value) : base(ContractParameterType.Integer, value) { } public IntegerContractParameter(sbyte value) : base(ContractParameterType.Integer, value) { } public IntegerContractParameter(BigInteger value) : base(ContractParameterType.Integer, value) { } public override void PushIntoScriptBuilder(ScriptBuilder scriptBuilder) { if (this.Value is BigInteger bi) { scriptBuilder.EmitPush(bi); } else { if (BigInteger.TryParse(this.Value.ToString(), out var bip)) { scriptBuilder.EmitPush(bip); } } } } }
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\codecapi.h(1901,1) using System; namespace DirectN { [Flags] public enum eAVAudioChannelConfig { eAVAudioChannelConfig_FRONT_LEFT = 0x00000001, eAVAudioChannelConfig_FRONT_RIGHT = 0x00000002, eAVAudioChannelConfig_FRONT_CENTER = 0x00000004, eAVAudioChannelConfig_LOW_FREQUENCY = 0x00000008, eAVAudioChannelConfig_BACK_LEFT = 0x00000010, eAVAudioChannelConfig_BACK_RIGHT = 0x00000020, eAVAudioChannelConfig_FRONT_LEFT_OF_CENTER = 0x00000040, eAVAudioChannelConfig_FRONT_RIGHT_OF_CENTER = 0x00000080, eAVAudioChannelConfig_BACK_CENTER = 0x00000100, eAVAudioChannelConfig_SIDE_LEFT = 0x00000200, eAVAudioChannelConfig_SIDE_RIGHT = 0x00000400, eAVAudioChannelConfig_TOP_CENTER = 0x00000800, eAVAudioChannelConfig_TOP_FRONT_LEFT = 0x00001000, eAVAudioChannelConfig_TOP_FRONT_CENTER = 0x00002000, eAVAudioChannelConfig_TOP_FRONT_RIGHT = 0x00004000, eAVAudioChannelConfig_TOP_BACK_LEFT = 0x00008000, eAVAudioChannelConfig_TOP_BACK_CENTER = 0x00010000, eAVAudioChannelConfig_TOP_BACK_RIGHT = 0x00020000, } }
using System; using Newtonsoft.Json; namespace InstaSharp.Models.Responses { /// <summary> /// oEmbed is a format for allowing an embedded representation of a URL on third party sites. /// </summary> public class OEmbedResponse { /// <summary> /// Gets the provider URL. /// </summary> /// <value> /// The provider URL. /// </value> [JsonProperty("provider_url")] public String ProviderUrl { get; set; } /// <summary> /// Gets the media identifier. /// </summary> /// <value> /// The media identifier. /// </value> [JsonProperty("media_id")] public String MediaId { get; set; } /// <summary> /// Getsthe title. /// </summary> /// <value> /// The title. /// </value> [JsonProperty("title")] public String Title { get; set; } /// <summary> /// Gets the full URL. /// </summary> /// <value> /// The URL. /// </value> [JsonProperty("url")] public String Url { get; set; } /// <summary> /// Gets the name of the author. /// </summary> /// <value> /// The name of the author. /// </value> [JsonProperty("author_name")] public String AuthorName { get; set; } /// <summary> /// Gets the height in pixels /// </summary> /// <value> /// The height. /// </value> [JsonProperty("height")] public int Height { get; set; } /// <summary> /// Gets the width in pixels </summary> /// <value> /// The width. /// </value> [JsonProperty("width")] public int Width { get; set; } /// <summary> /// Gets the version. /// </summary> /// <value> /// The version. /// </value> [JsonProperty("version")] public String Version { get; set; } /// <summary> /// Gets the author Url. /// </summary> /// <value> /// The version. /// </value> [JsonProperty("author_url")] public String AuthorUrl { get; set; } /// <summary> /// Gets the author identifier. /// </summary> /// <value> /// The author identifier. /// </value> [JsonProperty("author_id")] public int AuthorId { get; set; } /// <summary> /// Gets the type. /// </summary> /// <value> /// The type. /// </value> /// <example>"photo"</example> [JsonProperty("type")] public String Type { get; set; } /// <summary> /// Gets the name of the provider. /// </summary> /// <value> /// The name of the provider. /// </value> /// <example>Instagram</example> [JsonProperty("provider_name")] public String ProviderName { get; set; } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.Drawing.Drawing2D; using System.Windows.Forms; using Blumind.Canvas; using Blumind.Canvas.GdiPlus; using Blumind.Controls; using Blumind.Core; using Blumind.Globalization; namespace Blumind.Design { class LineAnchorEditor : ListEditor<LineAnchor> { private bool IsEndCap = false; protected override LineAnchor[] GetStandardValues() { return new LineAnchor[]{ LineAnchor.None, LineAnchor.Arrow, LineAnchor.Round, LineAnchor.Square, LineAnchor.Diamond}; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if (value is LineAnchor) { IsEndCap = context.PropertyDescriptor.Name == "EndCap"; } return base.EditValue(context, provider, value); } public override bool GetPaintValueSupported(ITypeDescriptorContext context) { return true; } /*public override void PaintValue(PaintValueEventArgs e) { e.Graphics.FillRectangle(Brushes.White, e.Bounds); if (e.Value is LineAnchor && ((LineCap)e.Value) != LineCap.Flat) { Pen pen = new Pen(Color.Black, 5); Point pt = PaintHelper.CenterPoint(e.Bounds); if (IsEndCap) { pen.EndCap = (LineCap)e.Value; e.Graphics.DrawLine(pen, e.Bounds.Left + 2, pt.Y, e.Bounds.Right - pen.Width - 2, pt.Y); } else { pen.StartCap = (LineCap)e.Value; e.Graphics.DrawLine(pen, e.Bounds.Left + pen.Width + 2, pt.Y, e.Bounds.Right - 2, pt.Y); } } }*/ protected override void DrawListItem(DrawItemEventArgs e, Rectangle rect, ListItem<LineAnchor> listItem) { var value = listItem.Value; //base.DrawItem(e, rect, value); if (value != LineAnchor.None) { Color foreColor = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ? SystemColors.HighlightText : SystemColors.WindowText; Point pt = PaintHelper.CenterPoint(rect); rect.Inflate(-10, 0); rect.X += 5; rect.Width -= 5; IGraphics grf = new GdiGraphics(e.Graphics); var gs = grf.Save(); grf.SetHighQualityRender(); var pen = grf.Pen(foreColor, 5); if (IsEndCap) grf.DrawLine(pen, rect.Left, pt.Y, rect.Right, pt.Y, LineAnchor.None, (LineAnchor)value); else grf.DrawLine(pen, rect.Left, pt.Y, rect.Right, pt.Y, (LineAnchor)value, LineAnchor.None); grf.Restore(gs); } } } class LineCapConverter : BaseTypeConverter { protected override object ConvertValueToString(object value) { if (value is LineCap) { switch ((LineCap)value) { case LineCap.Flat: return Lang._("None"); case LineCap.Square: return string.Empty;// LanguageManage.GetText("Square"); case LineCap.Round: return string.Empty;// LanguageManage.GetText("Round"); case LineCap.Triangle: return string.Empty;// LanguageManage.GetText("Triangle"); //case LineCap.NoAnchor: // break; case LineCap.SquareAnchor: return string.Empty;// LanguageManage.GetText("Square Anchor"); case LineCap.RoundAnchor: return string.Empty;// LanguageManage.GetText("Round Anchor"); case LineCap.DiamondAnchor: return string.Empty;// LanguageManage.GetText("Diamond Anchor"); case LineCap.ArrowAnchor: return string.Empty;// LanguageManage.GetText("Arrow Anchor"); //case LineCap.AnchorMask: // break; //case LineCap.Custom: } } return base.ConvertValueToString(value); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { public static partial class SyntaxNodeExtensions { /// <summary> /// Creates a new tree of nodes with the specified nodes, tokens and trivia replaced. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root node of the tree of nodes.</param> /// <param name="nodes">The nodes to be replaced.</param> /// <param name="computeReplacementNode">A function that computes a replacement node for the /// argument nodes. The first argument is the original node. The second argument is the same /// node potentially rewritten with replaced descendants.</param> /// <param name="tokens">The tokens to be replaced.</param> /// <param name="computeReplacementToken">A function that computes a replacement token for /// the argument tokens. The first argument is the original token. The second argument is /// the same token potentially rewritten with replaced trivia.</param> /// <param name="trivia">The trivia to be replaced.</param> /// <param name="computeReplacementTrivia">A function that computes replacement trivia for /// the specified arguments. The first argument is the original trivia. The second argument is /// the same trivia with potentially rewritten sub structure.</param> public static TRoot ReplaceSyntax<TRoot>( this TRoot root, IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode, IEnumerable<SyntaxToken> tokens, Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken, IEnumerable<SyntaxTrivia> trivia, Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia> computeReplacementTrivia) where TRoot : SyntaxNode { return (TRoot)root.ReplaceCore( nodes: nodes, computeReplacementNode: computeReplacementNode, tokens: tokens, computeReplacementToken: computeReplacementToken, trivia: trivia, computeReplacementTrivia: computeReplacementTrivia); } /// <summary> /// Creates a new tree of nodes with the specified old node replaced with a new node. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <typeparam name="TNode">The type of the nodes being replaced.</typeparam> /// <param name="root">The root node of the tree of nodes.</param> /// <param name="nodes">The nodes to be replaced; descendants of the root node.</param> /// <param name="computeReplacementNode">A function that computes a replacement node for the /// argument nodes. The first argument is the original node. The second argument is the same /// node potentially rewritten with replaced descendants.</param> public static TRoot ReplaceNodes<TRoot, TNode>(this TRoot root, IEnumerable<TNode> nodes, Func<TNode, TNode, SyntaxNode> computeReplacementNode) where TRoot : SyntaxNode where TNode : SyntaxNode { return (TRoot)root.ReplaceCore(nodes: nodes, computeReplacementNode: computeReplacementNode); } /// <summary> /// Creates a new tree of nodes with the specified old node replaced with a new node. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root node of the tree of nodes.</param> /// <param name="oldNode">The node to be replaced; a descendant of the root node.</param> /// <param name="newNode">The new node to use in the new tree in place of the old node.</param> public static TRoot ReplaceNode<TRoot>(this TRoot root, SyntaxNode oldNode, SyntaxNode newNode) where TRoot : SyntaxNode { return (TRoot)root.ReplaceCore(nodes: new[] { oldNode }, computeReplacementNode: (o, r) => newNode); } /// <summary> /// Creates a new tree of nodes with specified old node replaced with a new nodes. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root of the tree of nodes.</param> /// <param name="oldNode">The node to be replaced; a descendant of the root node and an element of a list member.</param> /// <param name="newNodes">A sequence of nodes to use in the tree in place of the old node.</param> public static TRoot ReplaceNode<TRoot>(this TRoot root, SyntaxNode oldNode, IEnumerable<SyntaxNode> newNodes) where TRoot : SyntaxNode { return (TRoot)root.ReplaceNodeInListCore(oldNode, newNodes); } /// <summary> /// Creates a new tree of nodes with new nodes inserted before the specified node. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root of the tree of nodes.</param> /// <param name="nodeInList">The node to insert before; a descendant of the root node an element of a list member.</param> /// <param name="newNodes">A sequence of nodes to insert into the tree immediately before the specified node.</param> public static TRoot InsertNodesBefore<TRoot>(this TRoot root, SyntaxNode nodeInList, IEnumerable<SyntaxNode> newNodes) where TRoot : SyntaxNode { return (TRoot)root.InsertNodesInListCore(nodeInList, newNodes, insertBefore: true); } /// <summary> /// Creates a new tree of nodes with new nodes inserted after the specified node. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root of the tree of nodes.</param> /// <param name="nodeInList">The node to insert after; a descendant of the root node an element of a list member.</param> /// <param name="newNodes">A sequence of nodes to insert into the tree immediately after the specified node.</param> public static TRoot InsertNodesAfter<TRoot>(this TRoot root, SyntaxNode nodeInList, IEnumerable<SyntaxNode> newNodes) where TRoot : SyntaxNode { return (TRoot)root.InsertNodesInListCore(nodeInList, newNodes, insertBefore: false); } /// <summary> /// Creates a new tree of nodes with the specified old token replaced with new tokens. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root of the tree of nodes.</param> /// <param name="tokenInList">The token to be replaced; a descendant of the root node and an element of a list member.</param> /// <param name="newTokens">A sequence of tokens to use in the tree in place of the specified token.</param> public static TRoot ReplaceToken<TRoot>(this TRoot root, SyntaxToken tokenInList, IEnumerable<SyntaxToken> newTokens) where TRoot : SyntaxNode { return (TRoot)root.ReplaceTokenInListCore(tokenInList, newTokens); } /// <summary> /// Creates a new tree of nodes with new tokens inserted before the specified token. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root of the tree of nodes.</param> /// <param name="tokenInList">The token to insert before; a descendant of the root node and an element of a list member.</param> /// <param name="newTokens">A sequence of tokens to insert into the tree immediately before the specified token.</param> public static TRoot InsertTokensBefore<TRoot>(this TRoot root, SyntaxToken tokenInList, IEnumerable<SyntaxToken> newTokens) where TRoot : SyntaxNode { return (TRoot)root.InsertTokensInListCore(tokenInList, newTokens, insertBefore: true); } /// <summary> /// Creates a new tree of nodes with new tokens inserted after the specified token. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root of the tree of nodes.</param> /// <param name="tokenInList">The token to insert after; a descendant of the root node and an element of a list member.</param> /// <param name="newTokens">A sequence of tokens to insert into the tree immediately after the specified token.</param> public static TRoot InsertTokensAfter<TRoot>(this TRoot root, SyntaxToken tokenInList, IEnumerable<SyntaxToken> newTokens) where TRoot : SyntaxNode { return (TRoot)root.InsertTokensInListCore(tokenInList, newTokens, insertBefore: false); } /// <summary> /// Creates a new tree of nodes with the specified old trivia replaced with new trivia. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root of the tree of nodes.</param> /// <param name="oldTrivia">The trivia to be replaced; a descendant of the root node.</param> /// <param name="newTrivia">A sequence of trivia to use in the tree in place of the specified trivia.</param> public static TRoot ReplaceTrivia<TRoot>(this TRoot root, SyntaxTrivia oldTrivia, IEnumerable<SyntaxTrivia> newTrivia) where TRoot : SyntaxNode { return (TRoot)root.ReplaceTriviaInListCore(oldTrivia, newTrivia); } /// <summary> /// Creates a new tree of nodes with new trivia inserted before the specified trivia. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root of the tree of nodes.</param> /// <param name="trivia">The trivia to insert before; a descendant of the root node.</param> /// <param name="newTrivia">A sequence of trivia to insert into the tree immediately before the specified trivia.</param> public static TRoot InsertTriviaBefore<TRoot>(this TRoot root, SyntaxTrivia trivia, IEnumerable<SyntaxTrivia> newTrivia) where TRoot : SyntaxNode { return (TRoot)root.InsertTriviaInListCore(trivia, newTrivia, insertBefore: true); } /// <summary> /// Creates a new tree of nodes with new trivia inserted after the specified trivia. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root of the tree of nodes.</param> /// <param name="trivia">The trivia to insert after; a descendant of the root node.</param> /// <param name="newTrivia">A sequence of trivia to insert into the tree immediately after the specified trivia.</param> public static TRoot InsertTriviaAfter<TRoot>(this TRoot root, SyntaxTrivia trivia, IEnumerable<SyntaxTrivia> newTrivia) where TRoot : SyntaxNode { return (TRoot)root.InsertTriviaInListCore(trivia, newTrivia, insertBefore: false); } /// <summary> /// Creates a new tree of nodes with the specified old node replaced with a new node. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root node of the tree of nodes.</param> /// <param name="tokens">The token to be replaced; descendants of the root node.</param> /// <param name="computeReplacementToken">A function that computes a replacement token for /// the argument tokens. The first argument is the original token. The second argument is /// the same token potentially rewritten with replaced trivia.</param> public static TRoot ReplaceTokens<TRoot>(this TRoot root, IEnumerable<SyntaxToken> tokens, Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken) where TRoot : SyntaxNode { return (TRoot)root.ReplaceCore<SyntaxNode>(tokens: tokens, computeReplacementToken: computeReplacementToken); } /// <summary> /// Creates a new tree of nodes with the specified old token replaced with a new token. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root node of the tree of nodes.</param> /// <param name="oldToken">The token to be replaced.</param> /// <param name="newToken">The new token to use in the new tree in place of the old /// token.</param> public static TRoot ReplaceToken<TRoot>(this TRoot root, SyntaxToken oldToken, SyntaxToken newToken) where TRoot : SyntaxNode { return (TRoot)root.ReplaceCore<SyntaxNode>(tokens: new[] { oldToken }, computeReplacementToken: (o, r) => newToken); } /// <summary> /// Creates a new tree of nodes with the specified trivia replaced with new trivia. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root node of the tree of nodes.</param> /// <param name="trivia">The trivia to be replaced; descendants of the root node.</param> /// <param name="computeReplacementTrivia">A function that computes replacement trivia for /// the specified arguments. The first argument is the original trivia. The second argument is /// the same trivia with potentially rewritten sub structure.</param> public static TRoot ReplaceTrivia<TRoot>(this TRoot root, IEnumerable<SyntaxTrivia> trivia, Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia> computeReplacementTrivia) where TRoot : SyntaxNode { return (TRoot)root.ReplaceCore<SyntaxNode>(trivia: trivia, computeReplacementTrivia: computeReplacementTrivia); } /// <summary> /// Creates a new tree of nodes with the specified trivia replaced with new trivia. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root node of the tree of nodes.</param> /// <param name="trivia">The trivia to be replaced.</param> /// <param name="newTrivia">The new trivia to use in the new tree in place of the old trivia.</param> public static TRoot ReplaceTrivia<TRoot>(this TRoot root, SyntaxTrivia trivia, SyntaxTrivia newTrivia) where TRoot : SyntaxNode { return (TRoot)root.ReplaceCore<SyntaxNode>(trivia: new[] { trivia }, computeReplacementTrivia: (o, r) => newTrivia); } /// <summary> /// Creates a new tree of nodes with the specified node removed. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root node from which to remove a descendant node from.</param> /// <param name="node">The node to remove.</param> /// <param name="options">Options that determine how the node's trivia is treated.</param> public static TRoot RemoveNode<TRoot>(this TRoot root, SyntaxNode node, SyntaxRemoveOptions options) where TRoot : SyntaxNode { return (TRoot)root.RemoveNodesCore(new[] { node }, options); } /// <summary> /// Creates a new tree of nodes with the specified nodes removed. /// </summary> /// <typeparam name="TRoot">The type of the root node.</typeparam> /// <param name="root">The root node from which to remove a descendant node from.</param> /// <param name="nodes">The nodes to remove.</param> /// <param name="options">Options that determine how the nodes' trivia is treated.</param> public static TRoot RemoveNodes<TRoot>( this TRoot root, IEnumerable<SyntaxNode> nodes, SyntaxRemoveOptions options) where TRoot : SyntaxNode { return (TRoot)root.RemoveNodesCore(nodes, options); } internal const string DefaultIndentation = " "; /// <summary> /// Creates a new syntax node with all whitespace and end of line trivia replaced with /// regularly formatted trivia. /// </summary> /// <typeparam name="TNode">The type of the node.</typeparam> /// <param name="node">The node to format.</param> /// <param name="indentation">An optional sequence of whitespace characters that defines a /// single level of indentation.</param> /// <param name="elasticTrivia">If true the replaced trivia is elastic trivia.</param> public static TNode NormalizeWhitespace<TNode>(this TNode node, string indentation = DefaultIndentation, bool elasticTrivia = false) where TNode : SyntaxNode { return (TNode)node.NormalizeWhitespaceCore(indentation, elasticTrivia); } /// <summary> /// Creates a new node from this node with both the leading and trailing trivia of the specified node. /// </summary> public static TSyntax WithTriviaFrom<TSyntax>(this TSyntax syntax, SyntaxNode node) where TSyntax : SyntaxNode { return syntax.WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()); } /// <summary> /// Creates a new node from this node without leading or trailing trivia. /// </summary> public static TSyntax WithoutTrivia<TSyntax>(this TSyntax syntax) where TSyntax : SyntaxNode { return syntax.WithoutLeadingTrivia().WithoutTrailingTrivia(); } /// <summary> /// Creates a new node from this node with the leading trivia replaced. /// </summary> public static TSyntax WithLeadingTrivia<TSyntax>( this TSyntax node, SyntaxTriviaList trivia) where TSyntax : SyntaxNode { var first = node.GetFirstToken(includeZeroWidth: true); var newFirst = first.WithLeadingTrivia(trivia); return node.ReplaceToken(first, newFirst); } /// <summary> /// Creates a new node from this node with the leading trivia replaced. /// </summary> public static TSyntax WithLeadingTrivia<TSyntax>( this TSyntax node, IEnumerable<SyntaxTrivia> trivia) where TSyntax : SyntaxNode { var first = node.GetFirstToken(includeZeroWidth: true); var newFirst = first.WithLeadingTrivia(trivia); return node.ReplaceToken(first, newFirst); } /// <summary> /// Creates a new node from this node with the leading trivia removed. /// </summary> public static TSyntax WithoutLeadingTrivia<TSyntax>( this TSyntax node ) where TSyntax : SyntaxNode { return node.WithLeadingTrivia((IEnumerable<SyntaxTrivia>)null); } /// <summary> /// Creates a new node from this node with the leading trivia replaced. /// </summary> public static TSyntax WithLeadingTrivia<TSyntax>( this TSyntax node, params SyntaxTrivia[] trivia) where TSyntax : SyntaxNode { return node.WithLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia); } /// <summary> /// Creates a new node from this node with the trailing trivia replaced. /// </summary> public static TSyntax WithTrailingTrivia<TSyntax>( this TSyntax node, SyntaxTriviaList trivia) where TSyntax : SyntaxNode { var last = node.GetLastToken(includeZeroWidth: true); var newLast = last.WithTrailingTrivia(trivia); return node.ReplaceToken(last, newLast); } /// <summary> /// Creates a new node from this node with the trailing trivia replaced. /// </summary> public static TSyntax WithTrailingTrivia<TSyntax>( this TSyntax node, IEnumerable<SyntaxTrivia> trivia) where TSyntax : SyntaxNode { var last = node.GetLastToken(includeZeroWidth: true); var newLast = last.WithTrailingTrivia(trivia); return node.ReplaceToken(last, newLast); } /// <summary> /// Creates a new node from this node with the trailing trivia removed. /// </summary> public static TSyntax WithoutTrailingTrivia<TSyntax>( this TSyntax node ) where TSyntax : SyntaxNode { return node.WithTrailingTrivia((IEnumerable<SyntaxTrivia>)null); } /// <summary> /// Creates a new node from this node with the trailing trivia replaced. /// </summary> public static TSyntax WithTrailingTrivia<TSyntax>( this TSyntax node, params SyntaxTrivia[] trivia) where TSyntax : SyntaxNode { return node.WithTrailingTrivia((IEnumerable<SyntaxTrivia>)trivia); } } }
// Copyright © 2020 Dmitry Sikorsky. 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.IO; using System.Threading.Tasks; using Magicalizer.Data.Repositories.Abstractions; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Platformus.Website.Data.Entities; using Platformus.Website.FieldValidators; using Platformus.Website.Filters; using Platformus.Website.FormHandlers; namespace Platformus.Website.Frontend.Controllers { public class FormsController : Core.Frontend.Controllers.ControllerBase { public FormsController(IStorage storage) : base(storage) { } [HttpPost] public async Task<IActionResult> SendAsync(int formId, string origin) { Form form = await this.Storage.GetRepository<int, Form, FormFilter>().GetByIdAsync( formId, new Inclusion<Form>(f => f.Name.Localizations), new Inclusion<Form>("Fields.FieldType"), new Inclusion<Form>("Fields.Name.Localizations") ); IDictionary<Field, string> valuesByFields = this.GetValuesByFields(form); foreach (Field field in valuesByFields.Keys) if (!string.IsNullOrEmpty(field.FieldType.ValidatorCSharpClassName)) if (!await this.CreateFieldValidator(field.FieldType).ValidateAsync(this.HttpContext, form, field, valuesByFields[field])) return this.BadRequest(); IDictionary<string, byte[]> attachmentsByFilenames = this.GetAttachmentsByFilenames(form); if (form.ProduceCompletedForms) await this.ProduceCompletedForms(form, valuesByFields, attachmentsByFilenames); IFormHandler formHandler = StringActivator.CreateInstance<IFormHandler>(form.FormHandlerCSharpClassName); if (formHandler != null) return await formHandler.HandleAsync(this.HttpContext, origin, form, valuesByFields, attachmentsByFilenames); return this.NotFound(); } private IDictionary<Field, string> GetValuesByFields(Form form) { IDictionary<Field, string> valuesByFields = new Dictionary<Field, string>(); foreach (Field field in form.Fields) if (field.FieldType.Code != "FileUpload") valuesByFields.Add(field, this.Request.Form[string.Format("field{0}", field.Code)]); return valuesByFields; } private IFieldValidator CreateFieldValidator(FieldType fieldType) { return StringActivator.CreateInstance<IFieldValidator>(fieldType.ValidatorCSharpClassName); } private IDictionary<string, byte[]> GetAttachmentsByFilenames(Form form) { IDictionary<string, byte[]> attachmentsByFilenames = new Dictionary<string, byte[]>(); foreach (Field field in form.Fields) { if (field.FieldType.Code == "FileUpload") { IFormFile file = this.Request.Form.Files[string.Format("field{0}", field.Code)]; if (file != null && !string.IsNullOrEmpty(file.FileName)) { string filename = file.FileName; if (!string.IsNullOrEmpty(filename) && filename.Contains(Path.DirectorySeparatorChar.ToString())) filename = Path.GetFileName(filename); attachmentsByFilenames.Add(filename, this.GetBytesFromStream(file.OpenReadStream())); } } } return attachmentsByFilenames; } private async Task ProduceCompletedForms(Form form, IDictionary<Field, string> valuesByFields, IDictionary<string, byte[]> attachmentsByFilenames) { CompletedForm completedForm = new CompletedForm(); completedForm.FormId = form.Id; completedForm.Created = DateTime.Now; this.Storage.GetRepository<int, CompletedForm, CompletedFormFilter>().Create(completedForm); await this.Storage.SaveAsync(); foreach (KeyValuePair<Field, string> valueByField in valuesByFields) { CompletedField completedField = new CompletedField(); completedField.CompletedFormId = completedForm.Id; completedField.FieldId = valueByField.Key.Id; completedField.Value = valueByField.Value; this.Storage.GetRepository<int, CompletedField, CompletedFieldFilter>().Create(completedField); } await this.Storage.SaveAsync(); } private byte[] GetBytesFromStream(Stream input) { using (MemoryStream output = new MemoryStream()) { input.CopyTo(output); return output.ToArray(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Skender.Stock.Indicators; namespace Internal.Tests { [TestClass] public class Slope : TestBase { [TestMethod] public void Standard() { List<SlopeResult> results = quotes.GetSlope(20).ToList(); // assertions // proper quantities // should always be the same number of results as there is quotes Assert.AreEqual(502, results.Count); Assert.AreEqual(483, results.Where(x => x.Slope != null).Count()); Assert.AreEqual(483, results.Where(x => x.StdDev != null).Count()); Assert.AreEqual(20, results.Where(x => x.Line != null).Count()); // sample values SlopeResult r1 = results[249]; Assert.AreEqual(0.312406m, Math.Round((decimal)r1.Slope, 6)); Assert.AreEqual(180.4164m, Math.Round((decimal)r1.Intercept, 4)); Assert.AreEqual(0.8056m, Math.Round((decimal)r1.RSquared, 4)); Assert.AreEqual(2.0071m, Math.Round((decimal)r1.StdDev, 4)); Assert.AreEqual(null, r1.Line); SlopeResult r2 = results[482]; Assert.AreEqual(-0.337015m, Math.Round((decimal)r2.Slope, 6)); Assert.AreEqual(425.1111m, Math.Round((decimal)r2.Intercept, 4)); Assert.AreEqual(0.1730m, Math.Round((decimal)r2.RSquared, 4)); Assert.AreEqual(4.6719m, Math.Round((decimal)r2.StdDev, 4)); Assert.AreEqual(267.9069m, Math.Round((decimal)r2.Line, 4)); SlopeResult r3 = results[501]; Assert.AreEqual(-1.689143m, Math.Round((decimal)r3.Slope, 6)); Assert.AreEqual(1083.7629m, Math.Round((decimal)r3.Intercept, 4)); Assert.AreEqual(0.7955m, Math.Round((decimal)r3.RSquared, 4)); Assert.AreEqual(10.9202m, Math.Round((decimal)r3.StdDev, 4)); Assert.AreEqual(235.8131m, Math.Round((decimal)r3.Line, 4)); } [TestMethod] public void BadData() { IEnumerable<SlopeResult> r = Indicator.GetSlope(historyBad, 15); Assert.AreEqual(502, r.Count()); } [TestMethod] public void Removed() { List<SlopeResult> results = quotes.GetSlope(20) .RemoveWarmupPeriods() .ToList(); // assertions Assert.AreEqual(502 - 19, results.Count); SlopeResult last = results.LastOrDefault(); Assert.AreEqual(-1.689143m, Math.Round((decimal)last.Slope, 6)); Assert.AreEqual(1083.7629m, Math.Round((decimal)last.Intercept, 4)); Assert.AreEqual(0.7955m, Math.Round((decimal)last.RSquared, 4)); Assert.AreEqual(10.9202m, Math.Round((decimal)last.StdDev, 4)); Assert.AreEqual(235.8131m, Math.Round((decimal)last.Line, 4)); } [TestMethod] public void Exceptions() { // bad lookback period Assert.ThrowsException<ArgumentOutOfRangeException>(() => Indicator.GetSlope(quotes, 0)); // insufficient quotes Assert.ThrowsException<BadQuotesException>(() => Indicator.GetSlope(HistoryTestData.Get(29), 30)); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Hasse.Core.GameAggregate { public abstract class FunctionalBuilder<TSubject, TSelf> where TSelf : FunctionalBuilder<TSubject, TSelf> where TSubject : new() { private readonly List<Func<TSubject, TSubject>> actions = new(); public TSelf Do(Action<TSubject> action) => AddAction(action); private TSelf AddAction(Action<TSubject> action) { actions.Add(b => { action(b); return b; }); return (TSelf) this; } public virtual TSubject Build() => actions.Aggregate(new TSubject(), (p, f) => f(p)); } }
namespace MassTransit.Abstractions.Tests { using System; using System.Diagnostics; using NUnit.Framework; [TestFixture] public class When_generating_id { [Test] public void Should_match_when_all_providers_equal() { // Arrange var generator1 = new NewIdGenerator(_tickProvider, _workerIdProvider, _processIdProvider); var generator2 = new NewIdGenerator(_tickProvider, _workerIdProvider, _processIdProvider); // Act var id1 = generator1.Next(); var id2 = generator2.Next(); // Assert Assert.AreEqual(id1, id2); } [Test] public void Should_match_when_all_providers_equal_with_guid_method() { // Arrange var generator1 = new NewIdGenerator(_tickProvider, _workerIdProvider, _processIdProvider); var generator2 = new NewIdGenerator(_tickProvider, _workerIdProvider, _processIdProvider); generator1.Next().ToGuid(); generator2.NextGuid(); // Act var id1 = generator1.Next().ToGuid(); var id2 = generator2.NextGuid(); // Assert Assert.AreEqual(id1, id2); } [Test] public void Should_not_match_when_generated_from_two_processes() { // Arrange var generator1 = new NewIdGenerator(_tickProvider, _workerIdProvider, _processIdProvider); _processIdProvider = new MockProcessIdProvider(BitConverter.GetBytes(11)); var generator2 = new NewIdGenerator(_tickProvider, _workerIdProvider, _processIdProvider); // Act var id1 = generator1.Next(); var id2 = generator2.Next(); // Assert Assert.AreNotEqual(id1, id2); } [Test] public void Should_not_match_when_processor_id_provided() { // Arrange var generator1 = new NewIdGenerator(_tickProvider, _workerIdProvider); var generator2 = new NewIdGenerator(_tickProvider, _workerIdProvider, _processIdProvider); // Act var id1 = generator1.Next(); var id2 = generator2.Next(); // Assert Assert.AreNotEqual(id1, id2); } [Test] public void Should_match_sequentially() { var generator = new NewIdGenerator(_tickProvider, _workerIdProvider); var id1 = generator.Next().ToGuid(); var id2 = generator.NextGuid(); var id3 = generator.NextGuid(); Assert.AreNotEqual(id1, id2); Assert.AreNotEqual(id2, id3); Assert.Greater(id2, id1); Console.WriteLine(id1); Console.WriteLine(id2); Console.WriteLine(id3); NewId nid1 = id1.ToNewId(); NewId nid2 = id2.ToNewId(); } [Test] public void Should_match_sequentially_with_sequential_guid() { var generator = new NewIdGenerator(_tickProvider, _workerIdProvider); var nid = generator.Next(); var id1 = nid.ToSequentialGuid(); var id2 = generator.NextSequentialGuid(); var id3 = generator.NextSequentialGuid(); Assert.AreNotEqual(id1, id2); Assert.AreNotEqual(id2, id3); Assert.Greater(id2, id1); Console.WriteLine(id1); Console.WriteLine(id2); Console.WriteLine(id3); NewId nid1 = id1.ToNewIdFromSequential(); NewId nid2 = id2.ToNewIdFromSequential(); Assert.AreEqual(nid, nid1); } [SetUp] public void Init() { _start = DateTime.UtcNow; _stopwatch = Stopwatch.StartNew(); _tickProvider = new MockTickProvider(GetTicks()); _workerIdProvider = new MockNetworkProvider(BitConverter.GetBytes(1234567890L)); _processIdProvider = new MockProcessIdProvider(BitConverter.GetBytes(10)); } ITickProvider _tickProvider; IWorkerIdProvider _workerIdProvider; IProcessIdProvider _processIdProvider; DateTime _start; Stopwatch _stopwatch; long GetTicks() { return _start.AddTicks(_stopwatch.Elapsed.Ticks).Ticks; } class MockTickProvider : ITickProvider { public MockTickProvider(long ticks) { Ticks = ticks; } public long Ticks { get; } } class MockNetworkProvider : IWorkerIdProvider { readonly byte[] _workerId; public MockNetworkProvider(byte[] workerId) { _workerId = workerId; } public byte[] GetWorkerId(int index) { return _workerId; } } class MockProcessIdProvider : IProcessIdProvider { readonly byte[] _processId; public MockProcessIdProvider(byte[] processId) { _processId = processId; } public byte[] GetProcessId() { return _processId; } } } }
using System; using IocPerformance.Classes.Complex; using IocPerformance.Classes.Dummy; using IocPerformance.Classes.Generics; using IocPerformance.Classes.Multiple; using IocPerformance.Classes.Properties; using IocPerformance.Classes.Standard; using Lamar; using Microsoft.Extensions.DependencyInjection; namespace IocPerformance.Adapters { public sealed class LamarContainerAdapter : ContainerAdapterBase { private Container container; public override string PackageName => "Lamar"; public override string Url => "https://jasperfx.github.io/lamar/"; public override bool SupportsInterception => false; public override bool SupportGeneric => true; public override bool SupportsMultiple => true; public override bool SupportsPropertyInjection => true; public override bool SupportsChildContainer => false; public override bool SupportAspNetCore => true; public override object Resolve(Type type) => this.container.GetService(type); public override void Dispose() { // Allow the container and everything it references to be garbage collected. if (this.container == null) { return; } this.container.Dispose(); this.container = null; } public override void Prepare() { var registry = new ServiceRegistry(); RegisterBasic(registry); RegisterPropertyInjection(registry); RegisterGeneric(registry); RegisterMultiple(registry); this.RegisterAspNetCoreClasses(registry); this.container = new Container(registry); } public override void PrepareBasic() { var registry = new ServiceRegistry(); RegisterBasic(registry); this.container = new Container(registry); } private static void RegisterBasic(ServiceRegistry r) { RegisterDummies(r); RegisterStandard(r); RegisterComplex(r); } private static void RegisterDummies(ServiceRegistry r) { r.AddTransient<IDummyOne, DummyOne>(); r.AddTransient<IDummyTwo, DummyTwo>(); r.AddTransient<IDummyThree, DummyThree>(); r.AddTransient<IDummyFour, DummyFour>(); r.AddTransient<IDummyFive, DummyFive>(); r.AddTransient<IDummySix, DummySix>(); r.AddTransient<IDummySeven, DummySeven>(); r.AddTransient<IDummyEight, DummyEight>(); r.AddTransient<IDummyNine, DummyNine>(); r.AddTransient<IDummyTen, DummyTen>(); } private static void RegisterStandard(ServiceRegistry r) { r.AddSingleton<ISingleton1, Singleton1>(); r.AddSingleton<ISingleton2, Singleton2>(); r.AddSingleton<ISingleton3, Singleton3>(); r.AddTransient<ITransient1, Transient1>(); r.AddTransient<ITransient2, Transient2>(); r.AddTransient<ITransient3, Transient3>(); r.AddTransient<ICombined1, Combined1>(); r.AddTransient<ICombined2, Combined2>(); r.AddTransient<ICombined3, Combined3>(); } private static void RegisterComplex(ServiceRegistry r) { r.AddSingleton<IFirstService, FirstService>(); r.AddSingleton<ISecondService, SecondService>(); r.AddSingleton<IThirdService, ThirdService>(); r.AddTransient<ISubObjectOne, SubObjectOne>(); r.AddTransient<ISubObjectTwo, SubObjectTwo>(); r.AddTransient<ISubObjectThree, SubObjectThree>(); r.AddTransient<IComplex1, Complex1>(); r.AddTransient<IComplex2, Complex2>(); r.AddTransient<IComplex3, Complex3>(); } private static void RegisterPropertyInjection(ServiceRegistry r) { r.AddSingleton<IServiceA, ServiceA>(); r.AddSingleton<IServiceB, ServiceB>(); r.AddSingleton<IServiceC, ServiceC>(); r.AddTransient<ISubObjectA, SubObjectA>(); r.AddTransient<ISubObjectB, SubObjectB>(); r.AddTransient<ISubObjectC, SubObjectC>(); r.AddTransient<IComplexPropertyObject1, ComplexPropertyObject1>(); r.AddTransient<IComplexPropertyObject2, ComplexPropertyObject2>(); r.AddTransient<IComplexPropertyObject3, ComplexPropertyObject3>(); } private static void RegisterGeneric(ServiceRegistry r) { r.For(typeof(IGenericInterface<>)).Use(typeof(GenericExport<>)); r.For(typeof(ImportGeneric<>)).Use(typeof(ImportGeneric<>)); } private static void RegisterMultiple(ServiceRegistry r) { r.AddTransient<ISimpleAdapter, SimpleAdapterOne>(); r.AddTransient<ISimpleAdapter, SimpleAdapterTwo>(); r.AddTransient<ISimpleAdapter, SimpleAdapterThree>(); r.AddTransient<ISimpleAdapter, SimpleAdapterFour>(); r.AddTransient<ISimpleAdapter, SimpleAdapterFive>(); r.AddTransient<ImportMultiple1, ImportMultiple1>(); r.AddTransient<ImportMultiple2, ImportMultiple2>(); r.AddTransient<ImportMultiple3, ImportMultiple3>(); } } }
using System; using System.Drawing; using System.Windows.Forms; using Spire.Pdf; using Spire.Pdf.Graphics; using Spire.Pdf.Security; namespace Decryption { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //Load a pdf document String encryptedPdf = @"..\..\..\..\..\..\Data\Decryption.pdf"; PdfDocument doc = new PdfDocument(); //Open the document doc.LoadFromFile(encryptedPdf, "test"); //Decrypt the document doc.Security.Encrypt("", "", PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key256Bit, "test"); //Save Pdf file doc.SaveToFile("Decryption.pdf", FileFormat.PDF); DocumentViewer("Decryption.pdf"); } private void DocumentViewer(string fileName) { try { System.Diagnostics.Process.Start(fileName); } catch { } } } }
using Dapper; using DoorsExport.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DoorsExport.Data.DAO { /// <summary> /// Centralizar o acesso a dados de e<see cref="LocalDeTrabalho"/> /// </summary> internal class LocalDeTrabalhoDAO { /// <summary> /// Obter um local de uma empresa /// </summary> /// <param name="codigo">codigo do local a ser pesquisado</param> /// <param name="empresa">codigo da empresa vinculada</param> /// <returns></returns> internal LocalDeTrabalho Get(int codigo, int empresa) { var query = @"SELECT TABFPLOCA.CODIG_LOCA as Codigo, TABFPLOCA.DESCR_LOCA as Descricao, TABFPLOCA.EMPRE_LOCA AS Empresa FROM TABFPLOCA WHERE TABFPLOCA.CODIG_LOCA = @Codigo and TABFPLOCA.EMPRE_LOCA = @Empresa"; using (var db = ConnectionDAO.GetInstancia().GetFirebirdConnection()) { return db.Query<LocalDeTrabalho>(query, new { @Codigo = codigo, @Empresa = empresa }).FirstOrDefault(); } } /// <summary> /// Obter todos os locais de uma empresa /// </summary> /// <param name="empresa">codigo da empresa</param> /// <returns></returns> internal IList<LocalDeTrabalho> GetAll(int empresa) { var query = @"SELECT TABFPLOCA.CODIG_LOCA as Codigo, TABFPLOCA.DESCR_LOCA as Descricao, TABFPLOCA.EMPRE_LOCA AS Empresa FROM TABFPLOCA WHERE TABFPLOCA.EMPRE_LOCA = @Empresa"; using (var db = ConnectionDAO.GetInstancia().GetFirebirdConnection()) { return db.Query<LocalDeTrabalho>(query, new { @Empresa = empresa }).ToList(); } } } }
using Android.Runtime; using Android.Views; using Android.Widget; using System; using Toggl.Core.UI.ViewModels; using Toggl.Shared; namespace Toggl.Droid.ViewHolders { public sealed class ClientCreationSelectionViewHolder : BaseRecyclerViewHolder<SelectableClientBaseViewModel> { private TextView creationTextView; public ClientCreationSelectionViewHolder(View itemView) : base(itemView) { } public ClientCreationSelectionViewHolder(IntPtr handle, JniHandleOwnership ownership) : base(handle, ownership) { } protected override void InitializeViews() { creationTextView = ItemView.FindViewById<TextView>(Resource.Id.CreationLabel); } protected override void UpdateView() { creationTextView.Text = $"{Resources.CreateClient} \"{Item.Name.Trim()}\""; } } }
using Equilaterus.Vortex; using System; using System.Collections.Generic; using System.Text; using TodoApp.Domain.Models; namespace TodoApp.Domain.Behaviors { public static class TodoBehavior { public static Maybe<Todo> TryUpdate(Todo persitedTodo, Todo newTodo) { return persitedTodo != null ? new Maybe<Todo>(new Todo(newTodo)) : new Maybe<Todo>(); } public static Maybe<Todo> TryDelete(Todo persitedTodo) { return persitedTodo != null ? new Maybe<Todo>(new Todo(persitedTodo)) : new Maybe<Todo>(); } } }
/** * Copyright 2021 The Nakama Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Nakama.Examples { public class PurchaseExamples { private IClient client; private ISession session; private async void ValidatePurchaseApple() { string appleReceipt = "<receipt>"; IApiValidatePurchaseResponse response = await client.ValidatePurchaseAppleAsync(session, appleReceipt); foreach (IApiValidatedPurchase validatedPurchase in response.ValidatedPurchases) { System.Console.WriteLine("Validated purchase: " + validatedPurchase); } } private async void ValidatePurcahseGoogle() { string googleReceipt = "<receipt>"; IApiValidatePurchaseResponse response = await client.ValidatePurchaseGoogleAsync(session, googleReceipt); foreach (IApiValidatedPurchase validatedPurchase in response.ValidatedPurchases) { System.Console.WriteLine("Validated purchase: " + validatedPurchase); } } private async void ValidatePurchaseHuawei() { string huaweiReceipt = "<receipt>"; string huaweiSignature = "<signature>"; IApiValidatePurchaseResponse response = await client.ValidatePurchaseHuaweiAsync(session, huaweiReceipt, huaweiSignature); foreach (IApiValidatedPurchase validatedPurchase in response.ValidatedPurchases) { System.Console.WriteLine("Validated purchase: " + validatedPurchase); } } } }
using System; using TrueCraft.Core.World; using NUnit.Framework; namespace TrueCraft.Core.Test.World { [TestFixture] public class TestGlobalChunkCoordinates { [TestCase(1, 2)] [TestCase(-2, -3)] public void ctor(int x, int z) { GlobalChunkCoordinates actual = new GlobalChunkCoordinates(x, z); Assert.AreEqual(x, actual.X); Assert.AreEqual(z, actual.Z); } [Test] public void Test_Equals_Object() { GlobalChunkCoordinates a = new GlobalChunkCoordinates(-1, 2); GlobalChunkCoordinates b = new GlobalChunkCoordinates(a.X, a.Z); GlobalColumnCoordinates c = new GlobalColumnCoordinates(a.X, a.Z); Assert.False(a.Equals(null)); Assert.False(a.Equals(a.ToString())); Assert.True(a.Equals((object)b)); Assert.False(a.Equals(c)); } [Test] public void Test_Equals_GlobalChunkCoordinates() { GlobalChunkCoordinates a = new GlobalChunkCoordinates(-1, 2); GlobalChunkCoordinates b = new GlobalChunkCoordinates(a.X, a.Z); Assert.True(a == b); Assert.False(a != b); Assert.False(a == null); Assert.True(a != null); } [TestCase("<-1,2>", -1, 2)] public void Test_ToString(string expected, int x, int z) { GlobalChunkCoordinates a = new GlobalChunkCoordinates(x, z); string actual = a.ToString(); Assert.AreEqual(expected, actual); } [TestCase(0, 0, 0, 0, 0)] [TestCase(0, 0, WorldConstants.ChunkWidth - 1, 1, WorldConstants.ChunkWidth - 1)] [TestCase(1, 0, WorldConstants.ChunkWidth, 60, WorldConstants.ChunkWidth - 1)] [TestCase(1, 1, WorldConstants.ChunkWidth, 127, WorldConstants.ChunkDepth)] [TestCase(1, 1, 2 * WorldConstants.ChunkWidth - 1, 1, 2 * WorldConstants.ChunkDepth - 1)] [TestCase(-1, -1, -1, 0, -1)] [TestCase(-1, -1, -WorldConstants.ChunkWidth, 5, -WorldConstants.ChunkDepth)] [TestCase(-2, -2, -WorldConstants.ChunkWidth - 1, 7, -WorldConstants.ChunkDepth - 1)] public void Test_Convert_From_GlobalVoxelCoordinates(int expectedX, int expectedZ, int voxelX, int voxelY, int voxelZ) { GlobalVoxelCoordinates other = new GlobalVoxelCoordinates(voxelX, voxelY, voxelZ); GlobalChunkCoordinates actual = (GlobalChunkCoordinates)other; Assert.AreEqual(expectedX, actual.X); Assert.AreEqual(expectedZ, actual.Z); } [TestCase(0, 0, 0, 0, 0)] [TestCase(0, 0, WorldConstants.ChunkWidth - 0.001, 0, WorldConstants.ChunkWidth - 0.001)] [TestCase(1, 0, WorldConstants.ChunkWidth, 50, WorldConstants.ChunkWidth - 0.001)] [TestCase(1, 1, WorldConstants.ChunkWidth, 127, WorldConstants.ChunkDepth)] [TestCase(1, 1, 2 * WorldConstants.ChunkWidth - 0.001, 5, 2 * WorldConstants.ChunkDepth - 0.001)] [TestCase(2, 2, 2 * WorldConstants.ChunkWidth + 0.001, 10, 2 * WorldConstants.ChunkDepth + 0.001)] [TestCase(-1, -1, -0.001, 27, -0.001)] [TestCase(-1, -1, -WorldConstants.ChunkWidth + 0.001, 124, -WorldConstants.ChunkDepth + 0.001)] [TestCase(-2, -2, -WorldConstants.ChunkWidth - 0.001, 42, -WorldConstants.ChunkDepth - 0.001)] public void Test_Convert_From_Vector3(int expectedX, int expectedZ, double x, double y, double z) { Vector3 other = new Vector3(x, y, z); GlobalChunkCoordinates actual = (GlobalChunkCoordinates)other; Assert.AreEqual(expectedX, actual.X); Assert.AreEqual(expectedZ, actual.Z); } } }
// ----------------------------------------------------------------------- // <copyright file="IErrorToExceptionTranslator.cs" company="YamNet"> // Copyright (c) 2013 YamNet contributors // </copyright> // ----------------------------------------------------------------------- namespace YamNet.Client.Errors { using System; using System.Net; /// <summary> /// The ErrorToException interface. /// </summary> public interface IErrorToExceptionTranslator { /// <summary> /// Translate error bodies into more granular exceptions. /// </summary> /// <param name="statusCode">The status code.</param> /// <param name="error">The error.</param> /// <returns>The <see cref="Exception"/>.</returns> Exception Translate(HttpStatusCode statusCode, Error error); } }
using System; using System.IO; using Wire.Extensions; namespace Wire.ValueSerializers { public class StringSerializer : ValueSerializer { public const byte Manifest = 7; public static readonly StringSerializer Instance = new StringSerializer(); public static void WriteValueImpl(Stream stream, string s, SerializerSession session) { int byteCount; var bytes = NoAllocBitConverter.GetBytes(s, session, out byteCount); stream.Write(bytes, 0, byteCount); } public static string ReadValueImpl(Stream stream, DeserializerSession session) { return stream.ReadString(session); } public override void WriteManifest(Stream stream, SerializerSession session) { stream.WriteByte(Manifest); } public override void WriteValue(Stream stream, object value, SerializerSession session) { WriteValueImpl(stream, (string) value, session); } public override object ReadValue(Stream stream, DeserializerSession session) { return ReadValueImpl(stream, session); } public override Type GetElementType() { return typeof(string); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using FashionShop.Models.Objects; namespace FashionShop.Models { public class OrderModel { private Provider provider = new Provider(); public int total() { string sql = "Select Count(PurchaseOrder) As Total From PurchaseOrder Where State != 0"; DataTable result = this.provider.executeQuery(sql); int total = (int)result.Rows[0]["Total"]; total = (int)Math.Ceiling(total * 1f / 20); return total; } public Order[] get(int page) { SqlCommand command = new SqlCommand("usp_GetAllOrders"); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@page", SqlDbType.Int); command.Parameters["@page"].Value = page; DataTable result = this.provider.executeQueryFromStoredProcedure(command); Order[] orders = new Order[result.Rows.Count]; int index = 0; foreach (DataRow row in result.Rows) { Order order = new Order(); order.Customer = row["Customer"].ToString(); order.CustomerName = row["Name"].ToString(); order.Time = (DateTime)row["Time"]; order.PurchaseOrder = row["PurchaseOrder"].ToString(); orders[index] = order; index++; } return orders; } } }
using System; namespace Piranha.Jawbone { public readonly struct WavHeader { private static readonly byte[] _keys; static WavHeader() { var keys = "RIFFWAVEfmt data"; _keys = new byte[keys.Length]; for (int i = 0; i < keys.Length; ++i) _keys[i] = (byte)keys[i]; } public int ChunkSize { get; } public int SampleRate { get; } public int ByteRate { get; } public short Format { get; } public short Channels { get; } public short BitsPerSample { get; } public short Excess { get; } public int DataOffset { get; } public WavHeader(ReadOnlySpan<byte> data) : this() { var keySpan = _keys.AsSpan(); if (data.Length > 44 && data.StartsWith(keySpan.Slice(0, 4)) && data.Slice(8).StartsWith(keySpan.Slice(4, 4))) { if (data.Slice(12).StartsWith(keySpan.Slice(8, 4))) { Format = BitConverter.ToInt16(data.Slice(20)); Channels = BitConverter.ToInt16(data.Slice(22)); SampleRate = BitConverter.ToInt32(data.Slice(24)); ByteRate = BitConverter.ToInt32(data.Slice(28)); BitsPerSample = BitConverter.ToInt16(data.Slice(34)); if (data.Slice(36).StartsWith(keySpan.Slice(12, 4))) { ChunkSize = BitConverter.ToInt32(data.Slice(40)); DataOffset = 44; } } } } } }
using System; namespace SetMeta.Abstract { public interface IOptionValueConverter<T> { T GetValue(string value); string GetStringValue(T value); string GetStringValue(T value, IFormatProvider formatProvider); } }
using System; using ClientBoundary; using ClientConsoleScriptContainer; using Lamar; namespace ClientConsoleScript { internal class Program { private static void Main(string[] args) { // Set up the IoC framework var reg = new ConsoleScriptContainer(); reg.DoRegister(); var appContainer = new Container(reg); var interactor = appContainer.GetInstance<IInteractor>(); interactor.SetAppContainer(appContainer); // Make some calls Console.WriteLine($"Pinging interactor: {interactor.GetHelloFromInteractor("Console Application")}"); Console.WriteLine($"Pinging interactor: {interactor.GetHelloFromInteractorPlugin("Console Application")}"); Console.WriteLine($"Pinging interactor: {interactor.GetHelloFromDataStore("Console Application")}"); } } }
using Microsoft.Diagnostics.Runtime; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace msos { static class ClrRootExtensions { public static string BetterToString(this ClrRoot root) { if (root.Kind == GCRootKind.LocalVar && root.Thread != null) { return String.Format("{0} thread {1}", root.Name, root.Thread.ManagedThreadId); } return root.Name; } } }
using Banshee.Customers.Domain.Entities; using Banshee.Customers.Domain.Exceptions; using Banshee.Customers.Domain.Interfaces; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Linq; namespace Banshee.Customers.Domain.Services { public class CustomerService : ICustomerService { private readonly ICustomerRepository _customerRepository; public CustomerService(ICustomerRepository customerRepository) { _customerRepository = customerRepository; } public async Task<bool> Delete(int id) { return await _customerRepository.Delete(id); } public async Task<IEnumerable<Customer>> GetAll() { return await _customerRepository.GetAll(); } public async Task<IEnumerable<Customer>> GetById(int id) { return await _customerRepository.GetById(id); } public async Task<bool> Save(Customer customer) { return await _customerRepository.Save(customer); } public async Task<bool> Update(Customer customer) { return await _customerRepository.Update(customer); } public async Task<IEnumerable<Customer>> ValidateCustomer(int id) { var customer = await _customerRepository.GetById(id); if (customer == null || customer.Count() == 0) { throw new CustomerNotFoundException($"Customer id: { id } not found"); } return customer; } } }
using Mimp.SeeSharper.DependencyInjection.Abstraction; using Mimp.SeeSharper.DependencyInjection.Scope.Abstraction; using Mimp.SeeSharper.DependencyInjection.Tag; using System; namespace Mimp.SeeSharper.DependencyInjection.Scope { public class TagScopeDependencyFactory : ScopeDependencyFactory, ITagDependencyFactory { public Func<ITagDependencyContext, Type, bool> IsTagged { get; } public TagScopeDependencyFactory( Func<IDependencyContext, Type, bool> constructible, Func<IDependencyContext, Type, Action<object>, object> factory, IScope scope, Func<ITagDependencyContext, Type, bool> isTagged, bool disposeAutomatically ) : base(constructible, factory, scope, disposeAutomatically) { IsTagged = isTagged ?? throw new ArgumentNullException(nameof(isTagged)); } public bool Tagged(ITagDependencyContext context, Type type) { if (context is null) throw new ArgumentNullException(nameof(context)); if (type is null) throw new ArgumentNullException(nameof(type)); return IsTagged(context, type); } } }
using Cake.Core; using Cake.Core.Annotations; using Cake.Core.IO; namespace Cake.Orchard { /// <summary> /// Contains functionality related to running Orchard build tasks. /// </summary> [CakeAliasCategory("Orchard")] public static class OrchardAliases { /// <summary> /// Validates Orchard module project files. /// </summary> /// <example> /// <code> /// #addin Cake.Orchard /// /// Task("ValidateProjectFiles") /// .Does(() => { /// ValidateProjectFiles(GetFiles("pattern to match")); /// }); /// </code> /// </example> /// <param name="context">The context.</param> /// <param name="files">Orchard module project files to be validated.</param> [CakeMethodAlias] public static void ValidateOrchardFiles(this ICakeContext context, FilePathCollection files) { ValidateExtensionProjectFiles.ValidateFiles(context, files); } /// <summary> /// Filters module binaries that are in common with orchard web project binaries. /// </summary> /// <example> /// <code> /// #addin Cake.Orchard /// /// Task("FilterModuleBinaries") /// .Does(() => { /// var filteredBinaries = FilterModuleBinaries(GetFiles("**/Modules/**/*.dll"),GetFiles("**/**/*.dll"); /// }); /// </code> /// </example> /// <param name="context">The context.</param> /// <param name="moduleBinaries">Collection of module binaries.</param> /// <param name="orchardWebBinaries">Collection of Orchard.Web project binaries.</param> /// <returns>Collection of module binaries that are shared.</returns> [CakeMethodAlias] public static FilePathCollection FilterModuleBinaries(this ICakeContext context, FilePathCollection moduleBinaries, FilePathCollection orchardWebBinaries) { return FilterBinaries.Filter(context, moduleBinaries, orchardWebBinaries); } /// <summary> /// Filters theme binaries that are in common with the orchard web project binaries. /// </summary> /// <example> /// <code> /// #addin Cake.Orchard /// /// Task("FilterThemeBinaries") /// .Does(() => { /// var filteredBinaries = FilterThemeBinaries(GetFiles("**/Themes/**/*.dll"),GetFiles("**/**/*.dll")); /// }); /// </code> /// </example> /// <param name="context">The context.</param> /// <param name="themeBinaries">Collection of theme binaries.</param> /// <param name="orchardWebBinaries">Collection of Orchard.Web project binaries.</param> /// <returns>Collection theme of binaries that are shared.</returns> [CakeMethodAlias] public static FilePathCollection FilterThemeBinaries(this ICakeContext context, FilePathCollection themeBinaries, FilePathCollection orchardWebBinaries) { return FilterBinaries.Filter(context, themeBinaries, orchardWebBinaries); } } }
// 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.IO; namespace NuGet.Test.Utility { public class TestPackageInfo : IDisposable { public TestPackageInfo(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentException($"{nameof(filePath)} cannot be null or empty"); } File = new FileInfo(filePath); } public string Id { get; set; } public string Version { get; set; } public FileInfo File { get; } public void Dispose() { try { if (File.Exists) { File.Delete(); } } catch { } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerControls : MonoBehaviour { private const string HORIZONTAL = "Horizontal"; private const string VERTICAL = "Vertical"; [SerializeField] private float _moveSpeed; public float MoveSpeed { get { return _moveSpeed; } } [SerializeField] private Rigidbody2D _rigidbody; public Rigidbody2D Rigidbody { get { return _rigidbody; } } // Use this for initialization void Start () { _moveSpeed = 5.0f; _rigidbody = GetComponent<Rigidbody2D>(); } private void Move(float dx, float dy) { Rigidbody.velocity = new Vector2(dx * MoveSpeed, dy * MoveSpeed); } // Update is called once per frame void Update () { float x = Input.GetAxis(HORIZONTAL); float y = Input.GetAxis(VERTICAL); Move(x, y); } }
using System.ComponentModel; namespace XFFirebaseAuthExample.ViewModels { // PropertyChanged.Fody will take care of boiler plate code ralted to INotifyPropertyChanged public class BaseViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public bool IsBusy { get; protected set; } } }
 namespace UnityExtensions { /// <summary> /// 状态栈的行为 /// </summary> public enum StackAction { Push, Pop, } /// <summary> /// 栈状态接口 /// </summary> public interface IStackState { /// <summary> /// 进入状态时触发 /// </summary> void OnEnter(StackAction stackAction); /// <summary> /// 离开状态时触发 /// </summary> void OnExit(StackAction stackAction); /// <summary> /// 更新状态时触发 /// </summary> void OnUpdate(float deltaTime); } // interface IStackState } // namespace UnityExtensions
using RimWorld; using Verse; namespace Locker; public class CompAssignableToPawn_Locker : CompAssignableToPawn { public new Building_RegistableContainer parent => (Building_RegistableContainer)base.parent; public new CompProperties_AssignableToPawn_OnlyOne Props => (CompProperties_AssignableToPawn_OnlyOne)props; public override bool AssignedAnything(Pawn pawn) { foreach (var item in Util.AllMapBuildings<Building_RegistableContainer>(pawn.Map)) { if (item.GetType() != Props.buildingClass) { continue; } var list = item.TryGetComp<CompAssignableToPawn_Locker>().assignedPawns; if (!list.NullOrEmpty() && list.Contains(pawn)) { return true; } } return false; } public bool AnyAssigned() { return AssignedPawn() != null; } public Pawn AssignedPawn() { if (assignedPawns.Any()) { return assignedPawns[0]; } return null; } public bool Assigned(Pawn pawn) { return assignedPawns.Contains(pawn); } public override void ForceAddPawn(Pawn pawn) { TryAssignPawn(pawn); } public override void ForceRemovePawn(Pawn pawn) { TryUnassignPawn(pawn); } public override void TryAssignPawn(Pawn newOwner) { if (Assigned(newOwner)) { return; } var oldOwner = AssignedPawn(); assignedPawns.Clear(); foreach (var item in Util.AllMapBuildings<Building_RegistableContainer>(newOwner.Map)) { if (item.GetType() != Props.buildingClass) { continue; } var compAssignableToPawn_Locker = item.TryGetComp<CompAssignableToPawn_Locker>(); compAssignableToPawn_Locker.TryUnassignPawn(newOwner); } assignedPawns.Add(newOwner); parent.ChangeOwner(oldOwner, newOwner); } public override void TryUnassignPawn(Pawn oldOwner, bool sort = true) { if (!Assigned(oldOwner)) { return; } assignedPawns.Remove(oldOwner); parent.ChangeOwner(oldOwner, null); } protected override string GetAssignmentGizmoDesc() { return "EKAI_Desc_AssignPawn".Translate(parent.def.label); } }
namespace UI.ViewModels { public enum SortBy { SizeAsc, SizeDesc, Duration } }
namespace vcdb.SqlServer.SchemaBuilding.Models { internal class UserAndLogin { public string name { get; set; } public string type_desc { get; set; } public string authentication_type_desc { get; set; } public string login { get; set; } public bool is_disabled { get; set; } public string default_schema_name { get; set; } } }
using Microsoft.Data.Entity; namespace GeekQuiz.Models { public class TriviaDbContext : DbContext { private static bool _created = false; public TriviaDbContext() { if (!_created) { _created = true; Database.EnsureCreated(); } } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<TriviaOption>() .HasKey(o => new { o.QuestionId, o.Id }); builder.Entity<TriviaAnswer>() .HasOne(a => a.TriviaOption) .WithMany() .HasForeignKey(a => new { a.QuestionId, a.OptionId }); builder.Entity<TriviaQuestion>() .HasMany(q => q.Options) .WithOne(o => o.TriviaQuestion); } public DbSet<TriviaQuestion> TriviaQuestions { get; set; } public DbSet<TriviaOption> TriviaOptions { get; set; } public DbSet<TriviaAnswer> TriviaAnswers { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ServiceModel.Channels { using System.ComponentModel; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using System.ServiceModel.Security; using Microsoft.Xml; public sealed class ReliableSessionBindingElement : BindingElement, IPolicyExportExtension { private TimeSpan _acknowledgementInterval = ReliableSessionDefaults.AcknowledgementInterval; private bool _flowControlEnabled = ReliableSessionDefaults.FlowControlEnabled; private TimeSpan _inactivityTimeout = ReliableSessionDefaults.InactivityTimeout; private int _maxPendingChannels = ReliableSessionDefaults.MaxPendingChannels; private int _maxRetryCount = ReliableSessionDefaults.MaxRetryCount; private int _maxTransferWindowSize = ReliableSessionDefaults.MaxTransferWindowSize; private bool _ordered = ReliableSessionDefaults.Ordered; private ReliableMessagingVersion _reliableMessagingVersion = ReliableMessagingVersion.Default; private static MessagePartSpecification s_bodyOnly; public ReliableSessionBindingElement() { } internal ReliableSessionBindingElement(ReliableSessionBindingElement elementToBeCloned) : base(elementToBeCloned) { this.AcknowledgementInterval = elementToBeCloned.AcknowledgementInterval; this.FlowControlEnabled = elementToBeCloned.FlowControlEnabled; this.InactivityTimeout = elementToBeCloned.InactivityTimeout; this.MaxPendingChannels = elementToBeCloned.MaxPendingChannels; this.MaxRetryCount = elementToBeCloned.MaxRetryCount; this.MaxTransferWindowSize = elementToBeCloned.MaxTransferWindowSize; this.Ordered = elementToBeCloned.Ordered; this.ReliableMessagingVersion = elementToBeCloned.ReliableMessagingVersion; } public ReliableSessionBindingElement(bool ordered) { _ordered = ordered; } [DefaultValue(typeof(TimeSpan), ReliableSessionDefaults.AcknowledgementIntervalString)] public TimeSpan AcknowledgementInterval { get { return _acknowledgementInterval; } set { if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.TimeSpanMustbeGreaterThanTimeSpanZero)); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.SFxTimeoutOutOfRangeTooBig)); } _acknowledgementInterval = value; } } [DefaultValue(ReliableSessionDefaults.FlowControlEnabled)] public bool FlowControlEnabled { get { return _flowControlEnabled; } set { _flowControlEnabled = value; } } [DefaultValue(typeof(TimeSpan), ReliableSessionDefaults.InactivityTimeoutString)] public TimeSpan InactivityTimeout { get { return _inactivityTimeout; } set { if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.TimeSpanMustbeGreaterThanTimeSpanZero)); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.SFxTimeoutOutOfRangeTooBig)); } _inactivityTimeout = value; } } [DefaultValue(ReliableSessionDefaults.MaxPendingChannels)] public int MaxPendingChannels { get { return _maxPendingChannels; } set { if (value <= 0 || value > 16384) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, string.Format(SRServiceModel.ValueMustBeInRange, 0, 16384))); _maxPendingChannels = value; } } [DefaultValue(ReliableSessionDefaults.MaxRetryCount)] public int MaxRetryCount { get { return _maxRetryCount; } set { if (value <= 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.ValueMustBePositive)); _maxRetryCount = value; } } [DefaultValue(ReliableSessionDefaults.MaxTransferWindowSize)] public int MaxTransferWindowSize { get { return _maxTransferWindowSize; } set { if (value <= 0 || value > 4096) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, string.Format(SRServiceModel.ValueMustBeInRange, 0, 4096))); _maxTransferWindowSize = value; } } [DefaultValue(ReliableSessionDefaults.Ordered)] public bool Ordered { get { return _ordered; } set { _ordered = value; } } [DefaultValue(typeof(ReliableMessagingVersion), ReliableSessionDefaults.ReliableMessagingVersionString)] public ReliableMessagingVersion ReliableMessagingVersion { get { return _reliableMessagingVersion; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (!ReliableMessagingVersion.IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } _reliableMessagingVersion = value; } } private static MessagePartSpecification BodyOnly { get { if (s_bodyOnly == null) { MessagePartSpecification temp = new MessagePartSpecification(true); temp.MakeReadOnly(); s_bodyOnly = temp; } return s_bodyOnly; } } public override BindingElement Clone() { return new ReliableSessionBindingElement(this); } public override T GetProperty<T>(BindingContext context) { throw new NotImplementedException(); } public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context) { throw new NotImplementedException(); } public override bool CanBuildChannelFactory<TChannel>(BindingContext context) { throw new NotImplementedException(); } internal override bool IsMatch(BindingElement b) { if (b == null) return false; ReliableSessionBindingElement session = b as ReliableSessionBindingElement; if (session == null) return false; if (_acknowledgementInterval != session._acknowledgementInterval) return false; if (_flowControlEnabled != session._flowControlEnabled) return false; if (_inactivityTimeout != session._inactivityTimeout) return false; if (_maxPendingChannels != session._maxPendingChannels) return false; if (_maxRetryCount != session._maxRetryCount) return false; if (_maxTransferWindowSize != session._maxTransferWindowSize) return false; if (_ordered != session._ordered) return false; if (_reliableMessagingVersion != session._reliableMessagingVersion) return false; return true; } private static void ProtectProtocolMessage( ScopedMessagePartSpecification signaturePart, ScopedMessagePartSpecification encryptionPart, string action) { signaturePart.AddParts(BodyOnly, action); encryptionPart.AddParts(MessagePartSpecification.NoParts, action); //encryptionPart.AddParts(BodyOnly, action); } private void SetSecuritySettings(BindingContext context) { SecurityBindingElement element = context.RemainingBindingElements.Find<SecurityBindingElement>(); if (element != null) { element.LocalServiceSettings.ReconnectTransportOnFailure = true; } } private void VerifyTransportMode(BindingContext context) { TransportBindingElement transportElement = context.RemainingBindingElements.Find<TransportBindingElement>(); // Verify ManualAdderssing is turned off. if ((transportElement != null) && (transportElement.ManualAddressing)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SRServiceModel.ManualAddressingNotSupported)); } ConnectionOrientedTransportBindingElement connectionElement = transportElement as ConnectionOrientedTransportBindingElement; HttpTransportBindingElement httpElement = transportElement as HttpTransportBindingElement; // Verify TransportMode is Buffered. TransferMode transportTransferMode; if (connectionElement != null) { transportTransferMode = connectionElement.TransferMode; } else if (httpElement != null) { transportTransferMode = httpElement.TransferMode; } else { // Not one of the elements we can check, we have to assume TransferMode.Buffered. transportTransferMode = TransferMode.Buffered; } if (transportTransferMode != TransferMode.Buffered) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(string.Format(SRServiceModel.TransferModeNotSupported, transportTransferMode, this.GetType().Name))); } } void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context) { if (exporter == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); if (context == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); if (context.BindingElements != null) { BindingElementCollection bindingElements = context.BindingElements; ReliableSessionBindingElement settings = bindingElements.Find<ReliableSessionBindingElement>(); if (settings != null) { // ReliableSession assertion XmlElement assertion = settings.CreateReliabilityAssertion(exporter.PolicyVersion, bindingElements); context.GetBindingAssertions().Add(assertion); } } } private static XmlElement CreatePolicyElement(PolicyVersion policyVersion, XmlDocument doc) { string policy = MetadataStrings.WSPolicy.Elements.Policy; string policyNs = policyVersion.Namespace; string policyPrefix = MetadataStrings.WSPolicy.Prefix; return doc.CreateElement(policyPrefix, policy, policyNs); } private XmlElement CreateReliabilityAssertion(PolicyVersion policyVersion, BindingElementCollection bindingElements) { XmlDocument doc = new XmlDocument(); XmlElement child = null; string reliableSessionPrefix; string reliableSessionNs; string assertionPrefix; string assertionNs; if (this.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { reliableSessionPrefix = ReliableSessionPolicyStrings.ReliableSessionFebruary2005Prefix; reliableSessionNs = ReliableSessionPolicyStrings.ReliableSessionFebruary2005Namespace; assertionPrefix = reliableSessionPrefix; assertionNs = reliableSessionNs; } else { reliableSessionPrefix = ReliableSessionPolicyStrings.ReliableSession11Prefix; reliableSessionNs = ReliableSessionPolicyStrings.ReliableSession11Namespace; assertionPrefix = ReliableSessionPolicyStrings.NET11Prefix; assertionNs = ReliableSessionPolicyStrings.NET11Namespace; } // ReliableSession assertion XmlElement assertion = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.ReliableSessionName, reliableSessionNs); if (this.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11) { // Policy XmlElement policy = CreatePolicyElement(policyVersion, doc); // SequenceSTR if (IsSecureConversationEnabled(bindingElements)) { XmlElement sequenceSTR = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.SequenceSTR, reliableSessionNs); policy.AppendChild(sequenceSTR); } // DeliveryAssurance XmlElement deliveryAssurance = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.DeliveryAssurance, reliableSessionNs); // Policy XmlElement nestedPolicy = CreatePolicyElement(policyVersion, doc); // ExactlyOnce XmlElement exactlyOnce = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.ExactlyOnce, reliableSessionNs); nestedPolicy.AppendChild(exactlyOnce); if (_ordered) { // InOrder XmlElement inOrder = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.InOrder, reliableSessionNs); nestedPolicy.AppendChild(inOrder); } deliveryAssurance.AppendChild(nestedPolicy); policy.AppendChild(deliveryAssurance); assertion.AppendChild(policy); } // Nested InactivityTimeout assertion child = doc.CreateElement(assertionPrefix, ReliableSessionPolicyStrings.InactivityTimeout, assertionNs); WriteMillisecondsAttribute(child, this.InactivityTimeout); assertion.AppendChild(child); // Nested AcknowledgementInterval assertion child = doc.CreateElement(assertionPrefix, ReliableSessionPolicyStrings.AcknowledgementInterval, assertionNs); WriteMillisecondsAttribute(child, this.AcknowledgementInterval); assertion.AppendChild(child); return assertion; } private static bool IsSecureConversationEnabled(BindingElementCollection bindingElements) { bool foundRM = false; for (int i = 0; i < bindingElements.Count; i++) { if (!foundRM) { ReliableSessionBindingElement bindingElement = bindingElements[i] as ReliableSessionBindingElement; foundRM = (bindingElement != null); } else { SecurityBindingElement securityBindingElement = bindingElements[i] as SecurityBindingElement; if (securityBindingElement != null) { SecurityBindingElement bootstrapSecurity; // The difference in bool (requireCancellation) does not affect whether the binding is valid, // but the method does match on the value so we need to pass both true and false. return SecurityBindingElement.IsSecureConversationBinding(securityBindingElement, true, out bootstrapSecurity) || SecurityBindingElement.IsSecureConversationBinding(securityBindingElement, false, out bootstrapSecurity); } break; } } return false; } private static void WriteMillisecondsAttribute(XmlElement childElement, TimeSpan timeSpan) { UInt64 milliseconds = Convert.ToUInt64(timeSpan.TotalMilliseconds); childElement.SetAttribute(ReliableSessionPolicyStrings.Milliseconds, XmlConvert.ToString(milliseconds)); } private class BindingDeliveryCapabilitiesHelper : IBindingDeliveryCapabilities { private ReliableSessionBindingElement _element; private IBindingDeliveryCapabilities _inner; internal BindingDeliveryCapabilitiesHelper(ReliableSessionBindingElement element, IBindingDeliveryCapabilities inner) { _element = element; _inner = inner; } bool IBindingDeliveryCapabilities.AssuresOrderedDelivery { get { return _element.Ordered; } } bool IBindingDeliveryCapabilities.QueuedDelivery { get { return _inner != null ? _inner.QueuedDelivery : false; } } } } }
using System.Linq; using System.Threading.Tasks; using NUnit.Framework; namespace YnabBudgetBuilder.Models.NUnit { [TestFixture] internal sealed class AppViewModelFixture { private AppViewModel m_Model; [SetUp] public async Task SetUp() { m_Model = new AppViewModel(); await m_Model.Initialize(); } [Test] public void TestInitialize() { Assert.That(m_Model.Budgets, Is.Not.Null); Assert.That(m_Model.SelectedBudget, Is.EqualTo(m_Model.Budgets.First())); Assert.That(m_Model.InitializeCommand.CanExecute(null), Is.False); } } }
 public class ScaleEffect : BaseEffect { private float a; private float b; private float c; public ScaleEffect( float a, float b, float c ) { this.a = a; this.b = b; this.c = c; } public override void OnTick() { Target.SetScale( Lerp3( a, b, c, T ) ); } }
using NUnit.Framework; using System; using akarnokd.reactive_extensions; namespace akarnokd.reactive_extensions_test.observablesource { [TestFixture] public class ObservableSourceIsEmptyTest { [Test] public void Basic() { ObservableSource.Range(1, 5) .IsEmpty() .Test() .AssertResult(false); } [Test] public void Empty() { ObservableSource.Empty<int>() .IsEmpty() .Test() .AssertResult(true); } [Test] public void Fused() { ObservableSource.Range(1, 5) .IsEmpty() .Test(fusionMode: FusionSupport.Any) .AssertFuseable() .AssertFusionMode(FusionSupport.Async) .AssertResult(false); } [Test] public void Fused_Empty() { ObservableSource.Empty<int>() .IsEmpty() .Test(fusionMode: FusionSupport.Any) .AssertFuseable() .AssertFusionMode(FusionSupport.Async) .AssertResult(true); } [Test] public void Error() { ObservableSource.Error<int>(new InvalidOperationException()) .IsEmpty() .Test() .AssertFailure(typeof(InvalidOperationException)); } [Test] public void Dispose() { TestHelper.VerifyDisposeObservableSource<int, bool>(o => o.IsEmpty()); } [Test] public void Dispose_Eager() { var ps = new PublishSubject<int>(); var to = ps.IsEmpty().Test(); Assert.True(ps.HasObservers); ps.OnNext(1); Assert.False(ps.HasObservers); to.AssertResult(false); } } }
using Microsoft.EntityFrameworkCore; using Abp.Zero.EntityFrameworkCore; using DemoCompany.DemoProject.Authorization.Roles; using DemoCompany.DemoProject.Authorization.Users; using DemoCompany.DemoProject.MultiTenancy; namespace DemoCompany.DemoProject.EntityFrameworkCore { public class DemoProjectDbContext : AbpZeroDbContext<Tenant, Role, User, DemoProjectDbContext> { /* Define a DbSet for each entity of the application */ public DbSet<ConfigureRule.ConfigureRule> ConfigureRule { get; set; } public DemoProjectDbContext(DbContextOptions<DemoProjectDbContext> options) : base(options) { } } }
 namespace Entity { public interface IControllerInputNames { IInputName HomeButton { get; } IInputName PrimaryButton { get; } IInputName SecondaryButton { get; } IInputName FaceButtonTop { get; } IInputName FaceButtonBottom { get; } IInputName FaceButtonLeft { get; } IInputName FaceButtonRight { get; } bool DPadUsesAxisInput { get; } bool DPadVerticalAxisInverted { get; } IInputName DPadTop { get; } IInputName DPadBottom { get; } IInputName DPadLeft { get; } IInputName DPadRight { get; } IInputName LeftStickButon { get; } IInputName LeftStickXAxis { get; } IInputName LeftStickYAxis { get; } IInputName RightStickButon { get; } IInputName RightStickXAxis { get; } IInputName RightStickYAxis { get; } IInputName LeftBumper { get; } IInputName RightBumper { get; } IInputName LeftTrigger { get; } IInputName RightTrigger { get; } } public class InputNames : IControllerInputNames { public InputNames( string homeButtonName, string homeButtonLabel, string primaryButtonName, string primaryButtonLabel, string secondaryButtonName, string secondaryButtonLabel, string faceButtonTopName, string faceButtonTopLabel, string faceButtonBottomName, string faceButtonBottomLabel, string faceButtonLeftName, string faceButtonLeftLabel, string faceButtonRightName, string faceButtonRightLabel, string dpadTopName, string dpadTopLabel, string dpadBottomName, string dpadBottomLabel, string dpadLeftName, string dpadLeftLabel, string dpadRightName, string dpadRightLabel, string leftStickButtonName, string leftStickButtonLabel, string leftStickXAxisName, string leftStickXAxisLabel, string leftStickYAxisName, string leftStickYAxisLabel, string rightStickButtonName, string rightStickButtonLabel, string rightStickXAxisName, string rightStickXAxisLabel, string rightStickYAxisName, string rightStickYAxisLabel, string leftBumperName, string leftBumperLabel, string rightBumperName, string rightBumperLabel, string leftTriggerName, string leftTriggerLabel, string rightTriggerName, string rightTriggerLabel) { this.HomeButton = new InputName(homeButtonName, homeButtonLabel); this.PrimaryButton = new InputName(primaryButtonName, primaryButtonLabel); this.SecondaryButton = new InputName(secondaryButtonName, secondaryButtonLabel); this.FaceButtonTop = new InputName(faceButtonTopName, faceButtonTopLabel); this.FaceButtonBottom = new InputName(faceButtonBottomName, faceButtonBottomLabel); this.FaceButtonLeft = new InputName(faceButtonLeftName, faceButtonLeftLabel); this.FaceButtonRight = new InputName(faceButtonRightName, faceButtonRightLabel); this.DPadTop = new InputName(dpadTopName, dpadTopLabel); this.DPadBottom = new InputName(dpadBottomName, dpadBottomLabel); this.DPadLeft = new InputName(dpadLeftName, dpadLeftLabel); this.DPadRight = new InputName(dpadRightName, dpadRightLabel); this.LeftStickButon = new InputName(leftStickButtonName, leftStickButtonLabel); this.LeftStickXAxis = new InputName(leftStickXAxisName, leftStickXAxisLabel); this.LeftStickYAxis = new InputName(leftStickYAxisName, leftStickYAxisLabel); this.RightStickButon = new InputName(rightStickButtonName, rightStickButtonLabel); this.RightStickXAxis = new InputName(rightStickXAxisName, rightStickXAxisLabel); this.RightStickYAxis = new InputName(rightStickYAxisName, rightStickYAxisLabel); this.LeftBumper = new InputName(leftBumperName, leftBumperLabel); this.RightBumper = new InputName(rightBumperName, rightBumperLabel); this.LeftTrigger = new InputName(leftTriggerName, leftTriggerLabel); this.RightTrigger = new InputName(rightTriggerName, rightTriggerLabel); } public IInputName HomeButton { get; private set; } public IInputName PrimaryButton { get; private set; } public IInputName SecondaryButton { get; private set; } public IInputName FaceButtonTop { get; private set; } public IInputName FaceButtonBottom { get; private set; } public IInputName FaceButtonLeft { get; private set; } public IInputName FaceButtonRight { get; private set; } public virtual bool DPadUsesAxisInput { get { return false; } } public virtual bool DPadVerticalAxisInverted { get { return false; } } public IInputName DPadTop { get; private set; } public IInputName DPadBottom { get; private set; } public IInputName DPadLeft { get; private set; } public IInputName DPadRight { get; private set; } public IInputName LeftStickButon { get; private set; } public IInputName LeftStickXAxis { get; private set; } public IInputName LeftStickYAxis { get; private set; } public IInputName RightStickButon { get; private set; } public IInputName RightStickXAxis { get; private set; } public IInputName RightStickYAxis { get; private set; } public IInputName LeftBumper { get; private set; } public IInputName RightBumper { get; private set; } public IInputName LeftTrigger { get; private set; } public IInputName RightTrigger { get; private set; } } public class ControllerInputNames : InputNames { public ControllerInputNames( string homeButtonName, string homeButtonLabel, string primaryButtonName, string primaryButtonLabel, string secondaryButtonName, string secondaryButtonLabel, string faceButtonTopName, string faceButtonTopLabel, string faceButtonBottomName, string faceButtonBottomLabel, string faceButtonLeftName, string faceButtonLeftLabel, string faceButtonRightName, string faceButtonRightLabel, string dpadTopName, string dpadBottomName, string dpadLeftName, string dpadRightName, string leftStickButtonName, string leftStickXAxisName, string leftStickYAxisName, string rightStickButtonName, string rightStickXAxisName, string rightStickYAxisName, string leftBumperName, string rightBumperName, string leftTriggerName, string rightTriggerName) : base( homeButtonName, homeButtonLabel, primaryButtonName, primaryButtonLabel, secondaryButtonName, secondaryButtonLabel, faceButtonTopName, faceButtonTopLabel, faceButtonBottomName, faceButtonBottomLabel, faceButtonLeftName, faceButtonLeftLabel, faceButtonRightName, faceButtonRightLabel, dpadTopName, "DPad-Up", dpadBottomName, "DPad-Bottom", dpadLeftName, "DPad-Left", dpadRightName, "DPad-Right", leftStickButtonName, "LeftStick", leftStickXAxisName, "LeftStick-Horizontal", leftStickYAxisName, "LeftStick-Vertical", rightStickButtonName, "RightStick", rightStickXAxisName, "RightStick-Horizontal", rightStickYAxisName, "RightStick-Vertical", leftBumperName, "LeftBumper", rightBumperName, "RightBumper", leftTriggerName, "LeftTrigger", rightTriggerName, "RightTrigger") { } } public class XboxInputNames : ControllerInputNames { public XboxInputNames( string homeButton, string primaryButton, string secondaryButton, string faceButtonTop, string faceButtonBottom, string faceButtonLeft, string faceButtonRight, string dpadTop, string dpadBottom, string dpadLeft, string dpadRight, string leftStickButton, string leftStickXAxis, string leftStickYAxis, string rightStickButton, string rightStickXAxis, string rightStickYAxis, string leftBumper, string rightBumper, string leftTrigger, string rightTrigger) : base( homeButton, "Xbox", primaryButton, "Start", secondaryButton, "Select", faceButtonTop, "Y", faceButtonBottom, "A", faceButtonLeft, "X", faceButtonRight, "B", dpadTop, dpadBottom, dpadLeft, dpadRight, leftStickButton, leftStickXAxis, leftStickYAxis, rightStickButton, rightStickXAxis, rightStickYAxis, leftBumper, rightBumper, leftTrigger, rightTrigger) { } } public class PlaystationInputNames : ControllerInputNames { public PlaystationInputNames( string homeButton, string primaryButton, string secondaryButton, string faceButtonTop, string faceButtonBottom, string faceButtonLeft, string faceButtonRight, string dpadTop, string dpadBottom, string dpadLeft, string dpadRight, string leftStickButton, string leftStickXAxis, string leftStickYAxis, string rightStickButton, string rightStickXAxis, string rightStickYAxis, string leftBumper, string rightBumper, string leftTrigger, string rightTrigger) : base( homeButton, "Playstation", primaryButton, "Options", secondaryButton, "Share", faceButtonTop, "Triangle", faceButtonBottom, "X", faceButtonLeft, "Square", faceButtonRight, "Circle", dpadTop, dpadBottom, dpadLeft, dpadRight, leftStickButton, leftStickXAxis, leftStickYAxis, rightStickButton, rightStickXAxis, rightStickYAxis, leftBumper, rightBumper, leftTrigger, rightTrigger) { } } }
using System; namespace HomeworkOne { [Serializable] public class Student : Member { private double GPA; protected string Major { get; set; } = String.Empty; protected string Sport { get; set; } = String.Empty; public Student() { } public Student(int id) : base(id) { } public new void Generate() { base.Generate(); Major = Names.department[random.Next(Names.department.Length)]; GPA = (random.Next(400 - 200 + 1) + 200)/100.0; } public new void Generate(int id) { base.Generate(id); Major = Names.department[random.Next(Names.department.Length)]; GPA = (random.Next(400 - 200 + 1) + 200)/100.0; } public new string ToString() { return base.ToString() + string.Format($" { GPA, 2 } {Major} "); } public string toString(bool value) { return (value ? "STU " : "") + ToString(); } public new string HtmlRow() { return "<tr>" + HtmlColumns() + "</tr>"; } public new string HtmlColumns() { return base.HtmlColumns() + "<td>" + GPA + "</td>" + "<td colspan=2>" + Major + "</td>"; } } }
using Microsoft.Extensions.DependencyInjection; using R3M_UserManagement_ExternalServices; using R3M_UserManagement_Services.Interfaces; namespace R3M_UserManagement_Services { public static class ServicesExtension { public static void ConfigureServices(this IServiceCollection services) { services.AddSingleton<ISystemService, SystemService>(); services.ConfigureExternalServices(); } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Generated from: Employees/Employee.proto // Note: requires additional types generated from: User.proto // Note: requires additional types generated from: OrganizationUserPermissions.proto // Note: requires additional types generated from: Timestamp.proto namespace Diadoc.Api.Proto.Employees { [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"Employee")] public partial class Employee : global::ProtoBuf.IExtensible { public Employee() {} private Diadoc.Api.Proto.UserV2 _User; [global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"User", DataFormat = global::ProtoBuf.DataFormat.Default)] public Diadoc.Api.Proto.UserV2 User { get { return _User; } set { _User = value; } } private Diadoc.Api.Proto.Employees.EmployeePermissions _Permissions; [global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"Permissions", DataFormat = global::ProtoBuf.DataFormat.Default)] public Diadoc.Api.Proto.Employees.EmployeePermissions Permissions { get { return _Permissions; } set { _Permissions = value; } } private string _Position; [global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"Position", DataFormat = global::ProtoBuf.DataFormat.Default)] public string Position { get { return _Position; } set { _Position = value; } } private bool _CanBeInvitedForChat; [global::ProtoBuf.ProtoMember(4, IsRequired = true, Name=@"CanBeInvitedForChat", DataFormat = global::ProtoBuf.DataFormat.Default)] public bool CanBeInvitedForChat { get { return _CanBeInvitedForChat; } set { _CanBeInvitedForChat = value; } } private Diadoc.Api.Proto.Timestamp _CreationTimestamp = null; [global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"CreationTimestamp", DataFormat = global::ProtoBuf.DataFormat.Default)] [global::System.ComponentModel.DefaultValue(null)] public Diadoc.Api.Proto.Timestamp CreationTimestamp { get { return _CreationTimestamp; } set { _CreationTimestamp = value; } } private global::ProtoBuf.IExtension extensionObject; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); } } [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"EmployeePermissions")] public partial class EmployeePermissions : global::ProtoBuf.IExtensible { public EmployeePermissions() {} private string _UserDepartmentId; [global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"UserDepartmentId", DataFormat = global::ProtoBuf.DataFormat.Default)] public string UserDepartmentId { get { return _UserDepartmentId; } set { _UserDepartmentId = value; } } private bool _IsAdministrator; [global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"IsAdministrator", DataFormat = global::ProtoBuf.DataFormat.Default)] public bool IsAdministrator { get { return _IsAdministrator; } set { _IsAdministrator = value; } } private Diadoc.Api.Proto.DocumentAccessLevel _DocumentAccessLevel; [global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"DocumentAccessLevel", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)] public Diadoc.Api.Proto.DocumentAccessLevel DocumentAccessLevel { get { return _DocumentAccessLevel; } set { _DocumentAccessLevel = value; } } private readonly global::System.Collections.Generic.List<string> _SelectedDepartmentIds = new global::System.Collections.Generic.List<string>(); [global::ProtoBuf.ProtoMember(4, Name=@"SelectedDepartmentIds", DataFormat = global::ProtoBuf.DataFormat.Default)] public global::System.Collections.Generic.List<string> SelectedDepartmentIds { get { return _SelectedDepartmentIds; } } private readonly global::System.Collections.Generic.List<Diadoc.Api.Proto.Employees.EmployeeAction> _Actions = new global::System.Collections.Generic.List<Diadoc.Api.Proto.Employees.EmployeeAction>(); [global::ProtoBuf.ProtoMember(5, Name=@"Actions", DataFormat = global::ProtoBuf.DataFormat.Default)] public global::System.Collections.Generic.List<Diadoc.Api.Proto.Employees.EmployeeAction> Actions { get { return _Actions; } } private Diadoc.Api.Proto.AuthorizationPermission _AuthorizationPermission = null; [global::ProtoBuf.ProtoMember(6, IsRequired = false, Name=@"AuthorizationPermission", DataFormat = global::ProtoBuf.DataFormat.Default)] [global::System.ComponentModel.DefaultValue(null)] public Diadoc.Api.Proto.AuthorizationPermission AuthorizationPermission { get { return _AuthorizationPermission; } set { _AuthorizationPermission = value; } } private global::ProtoBuf.IExtension extensionObject; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); } } [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"EmployeeAction")] public partial class EmployeeAction : global::ProtoBuf.IExtensible { public EmployeeAction() {} private string _Name; [global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"Name", DataFormat = global::ProtoBuf.DataFormat.Default)] public string Name { get { return _Name; } set { _Name = value; } } private bool _IsAllowed; [global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"IsAllowed", DataFormat = global::ProtoBuf.DataFormat.Default)] public bool IsAllowed { get { return _IsAllowed; } set { _IsAllowed = value; } } private global::ProtoBuf.IExtension extensionObject; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); } } [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"EmployeeList")] public partial class EmployeeList : global::ProtoBuf.IExtensible { public EmployeeList() {} private readonly global::System.Collections.Generic.List<Diadoc.Api.Proto.Employees.Employee> _Employees = new global::System.Collections.Generic.List<Diadoc.Api.Proto.Employees.Employee>(); [global::ProtoBuf.ProtoMember(1, Name=@"Employees", DataFormat = global::ProtoBuf.DataFormat.Default)] public global::System.Collections.Generic.List<Diadoc.Api.Proto.Employees.Employee> Employees { get { return _Employees; } } private int _TotalCount; [global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"TotalCount", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)] public int TotalCount { get { return _TotalCount; } set { _TotalCount = value; } } private global::ProtoBuf.IExtension extensionObject; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); } } }
using System; using ColossalGame.Models; using ColossalGame.Services; using MongoDB.Bson; using MongoDB.Driver; using NUnit.Framework; namespace ColossalServiceTests { public class Tests { [SetUp] public void Setup() { } [Test] public void TestMongoIsUp() { try { var client = new MongoClient("mongodb://127.0.0.1:27017"); var database = client.GetDatabase("Colossal"); database.RunCommandAsync((Command<BsonDocument>)"{ping:1}") .Wait(); } catch (Exception) { Assert.Fail("The MongoDB server is not running."); } } [Test] public void TestMongoServiceAdd() { try { UserService us = new UserService("mongodb://127.0.0.1:27017"); var x = us.Create(new User{PasswordHash = "test",Username = "test"}); var y = us.Get(x.Id); //Console.WriteLine(y.Id); Assert.AreEqual("test",y.Username); us.Remove(x.Id); } catch (Exception e) { Assert.Fail(e.StackTrace); } } } }
using System; using System.Diagnostics; using System.Xml.Serialization; namespace dk.nita.saml20.Schema.Core { /// <summary> /// The Saml ConditionAbstract class. /// Serves as an extension point for new conditions. /// </summary> [XmlInclude(typeof (ProxyRestriction))] [XmlInclude(typeof (OneTimeUse))] [XmlInclude(typeof (AudienceRestriction))] [Serializable] [DebuggerStepThrough] [XmlType(Namespace=Saml20Constants.ASSERTION)] [XmlRoot(ELEMENT_NAME, Namespace = Saml20Constants.ASSERTION, IsNullable = false)] public abstract class ConditionAbstract { /// <summary> /// The XML Element name of this class /// </summary> public const string ELEMENT_NAME = "Condition"; } }
#region << 版 本 注 释 >> /*----------------------------------------------------------------- * 项目名称 :Kane.GlobalHook * 项目描述 :全局钩子 * 类 名 称 :HookProc * 类 描 述 :钩子定义的回调函数 * 所在的域 :KK-HOME * 命名空间 :Kane.GlobalHook * 机器名称 :KK-HOME * CLR 版本 :4.0.30319.42000 * 作  者 :Kane Leung * 创建时间 :2020/3/31 22:17:20 * 更新时间 :2020/3/31 22:17:20 * 版 本 号 :v1.0.0.0 ******************************************************************* * Copyright @ Kane Leung 2020. All rights reserved. ******************************************************************* -----------------------------------------------------------------*/ #endregion using System; namespace Kane.GlobalHook { /// <summary> /// 钩子定义的回调函数(CALLBACK Function) /// </summary> /// <param name="nCode">【nCode】参数是Hook代码,Hook子程使用这个参数来确定任务。这个参数的值依赖于Hook类型,每一种Hook都有自己的Hook代码特征字符集。</param> /// <param name="wParam">【wParam】和【lParam】参数的值依赖于Hook代码,但是它们的典型值是包含了关于发送或者接收消息的信息。</param> /// <param name="lParam">【wParam】和【lParam】参数的值依赖于Hook代码,但是它们的典型值是包含了关于发送或者接收消息的信息。</param> /// <returns></returns> public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam); }
using System; using Auto.Inspections.App.Adapters; using Auto.Inspections.App.Plugin; using Auto.Inspections.Domain.Plugin; using Auto.Inspections.Infra.Adapters; using Auto.Inspections.Infra.Plugin; using Auto.Inspections.WebApi.Plugin; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetFusion.Azure.ServiceBus.Plugin; using NetFusion.Builder; using NetFusion.Messaging.Plugin; using NetFusion.Rest.Server.Plugin; using NetFusion.Serilog; using NetFusion.Settings.Plugin; using NetFusion.Web.Mvc.Plugin; using Serilog; namespace Auto.Inspections.WebApi { // Configures the HTTP request pipeline and bootstraps the NetFusion application container. public class Startup { // Microsoft Abstractions: private readonly IConfiguration _configuration; private readonly IWebHostEnvironment _hostingEnv; public Startup(IConfiguration configuration, IWebHostEnvironment hostingEnv) { _configuration = configuration; _hostingEnv = hostingEnv; } public void ConfigureServices(IServiceCollection services) { services.CompositeContainer(_configuration, new SerilogExtendedLogger()) .AddSettings() .AddMessaging() .AddWebMvc() .AddRest() // Messaging Integration: .AddAzureServiceBus() .AddPlugin<InfraPlugin>() .AddPlugin<AppPlugin>() .AddPlugin<DomainPlugin>() .AddPlugin<WebApiPlugin>() .Compose(); services.AddCors(); services.AddHttpContextAccessor(); services.AddControllers(); services.AddHttpClient<IRecallAdapter, RecallAdapter>(c => { c.BaseAddress = new Uri("https://api.nhtsa.gov"); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { string viewerUrl = _configuration.GetValue<string>("Netfusion:ViewerUrl"); if (! string.IsNullOrWhiteSpace(viewerUrl)) { app.UseCors(builder => builder.WithOrigins(viewerUrl) .AllowAnyMethod() .AllowCredentials() .WithExposedHeaders("WWW-Authenticate","resource-404") .AllowAnyHeader()); } app.UseSerilogRequestLogging(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
using CodeCampServer.Infrastructure.CommandProcessor; using MvcContrib.CommandProcessor.Interfaces; using StructureMap.Configuration.DSL; namespace CodeCampServer.DependencyResolution { public class CommandProcessorRegistry : Registry { protected override void configure() { For<IUnitOfWork>().Use<CommandProcessorUnitOfWorkProxy>(); } } }
using System; using System.Linq; using dngrep.core.VirtualNodes; using dngrep.core.VirtualNodes.VirtualQueries; using dngrep.core.VirtualNodes.VirtualQueries.Extensions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using RoslyJump.Core.Infrastructure; namespace RoslyJump.Core.Contexts.ActiveFile.Local.SiblingStates.States { public class ClassMemberSiblingState : SiblingStateBase { public ClassMemberSiblingState(CombinedSyntaxNode baseNode) : base(baseNode) { Type baseNodeType = baseNode.BaseNode.GetType(); if (baseNodeType != typeof(ClassDeclarationSyntax) && baseNodeType != typeof(StructDeclarationSyntax) && baseNodeType != typeof(InterfaceDeclarationSyntax)) { throw new ArgumentException( "Only base nodes of type class, struct or interface " + "are supported by this state.", nameof(baseNode)); } } protected override CombinedSyntaxNode[] QueryTargetsProtected(CombinedSyntaxNode baseNode) { CombinedSyntaxNode[] members = baseNode.BaseNode.ChildNodes() .Where(ClassMemberSyntaxNodeMatcher.Instance.Match) .GroupBy(x => { SyntaxKind kind = x.Kind(); // "patch" event-field to treat it as a general event // it allows to treat them as the same sibling kind return kind == SyntaxKind.EventFieldDeclaration ? SyntaxKind.EventDeclaration : kind; }) .Select(x => x.First()) .QueryVirtualAndCombine( AutoPropertyVirtualQuery.Instance, ReadOnlyPropertyVirtualQuery.Instance) .ToArray(); return members; } } }
using System.Collections.Concurrent; using System.Collections.Generic; namespace Kachuwa.Web { public interface IMetaTag { ConcurrentDictionary<string, string> MetaKeyValues { get; set; } string Generate(); } }
using PNet; using System; namespace Ghost.Server.Core.Classes { public class MoreInstantiates : INetSerializable { public string JsonData { get; private set; } public string[] Components { get; private set; } public MoreInstantiates(string[] components, string jsonData) { components = components ?? Array.Empty<string>(); if (components.Length > byte.MaxValue) throw new ArgumentOutOfRangeException(nameof(components), "maximum length is 255"); Components = components; JsonData = jsonData ?? string.Empty; foreach (var c in Components) AllocSize += c.Length * 2; AllocSize += JsonData.Length * 2; } public int AllocSize { get; private set; } public void OnDeserialize(NetMessage msg) { var cc = msg.ReadByte(); Components = new string[cc]; for (var i = 0; i < cc; i++) Components[i] = msg.ReadString(); JsonData = msg.ReadString(); } public void OnSerialize(NetMessage msg) { msg.Write((byte)Components.Length); foreach (var c in Components) msg.Write(c); msg.Write(JsonData); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace BiotimeControlPanel { public partial class User { [NotMapped] private string MiddleNameForFullName { get { if (!string.IsNullOrEmpty(MiddleName)) { return $"{Environment.NewLine}{MiddleName}"; } else { return string.Empty; } } } [NotMapped] private string MiddleNameForFullNameNbsp { get { if (!string.IsNullOrEmpty(MiddleName)) { return $" {MiddleName}"; } else { return string.Empty; } } } [NotMapped] public string FullName => $"{LastName} {FirstName}{MiddleNameForFullName}"; [NotMapped] public string FullNameWithCode1c => $"{FullName} {Code1C}"; [NotMapped] public string FullNameWithCode1cAndId => $"{FullNameWithCode1c} {Id}"; [NotMapped] public string FullNameNbsp => $"{LastName} {FirstName}{MiddleNameForFullNameNbsp}"; [NotMapped] public string FullNameWithCode1cNbsp => $"{FullNameNbsp} {Code1C}"; [NotMapped] public string FullNameWithCode1cAndIdNbsp => $"{FullNameWithCode1cNbsp} {Id}"; } }
using Xunit; namespace Falu.Tests; public class ConstantsTests { [Fact] public void MaxMpesaStatementFileSizeString_IsCorrect() { Assert.Equal("128 KiB", Constants.MaxMpesaStatementFileSizeString); } [Theory] [InlineData("wksp_602cd2747409e867a240d000")] [InlineData("wksp_60ffe3f79c1deb8060f91312")] [InlineData("wksp_27e868O6xW4NYrQb3WvxDb8iW6D")] public void WorkspaceIdFormat_IsCorrect(string input) { Assert.Matches(Constants.WorkspaceIdFormat, input); } [Theory] [InlineData("5C5F6FC9-DD6A-4C5D-A63A-DC96740CFE12")] [InlineData("dad11640-8f1c-4b91-8e61-051241204c8f")] [InlineData("pay:reload:202205091300")] [InlineData("pay_reload:202205091300")] public void IdempotencyKeyFormat_IsCorrect(string input) { Assert.Matches(Constants.IdempotencyKeyFormat, input); } [Theory] [InlineData("evt_602cd2747409e867a240d000")] [InlineData("evt_60ffe3f79c1deb8060f91312")] [InlineData("evt_27e868O6xW4NYrQb3WvxDb8iW6D")] public void EventIdFormat_IsCorrect(string input) { Assert.Matches(Constants.EventIdFormat, input); } [Theory] [InlineData("we_602cd2747409e867a240d000")] [InlineData("we_60ffe3f79c1deb8060f91312")] [InlineData("we_27e868O6xW4NYrQb3WvxDb8iW6D")] public void WebhookEndpointIdFormat_IsCorrect(string input) { Assert.Matches(Constants.WebhookEndpointIdFormat, input); } [Theory] [InlineData("mtpl_602cd2747409e867a240d000")] [InlineData("tmpl_60ffe3f79c1deb8060f91312")] [InlineData("mtpl_27e868O6xW4NYrQb3WvxDb8iW6D")] public void MessageTemplateIdFormat_IsCorrect(string input) { Assert.Matches(Constants.MessageTemplateIdFormat, input); } [Theory] [InlineData("promo-message")] [InlineData("promo_message")] [InlineData("Birthday_Wishes_2022-05-10")] public void MessageTemplateAliasFormat_IsCorrect(string input) { Assert.Matches(Constants.MessageTemplateAliasFormat, input); } [Theory] [InlineData("+254722000000")] [InlineData("+254700000000")] [InlineData("+14155552671")] public void E164PhoneNumberFormat_IsCorrect(string input) { Assert.Matches(Constants.E164PhoneNumberFormat, input); } }
using System.Collections.Generic; using System.Text.Json.Serialization; using Essensoft.Paylink.Alipay.Domain; namespace Essensoft.Paylink.Alipay.Response { /// <summary> /// AlipayCommerceAbntaskModifyResponse. /// </summary> public class AlipayCommerceAbntaskModifyResponse : AlipayResponse { /// <summary> /// 操作失败任务数量 /// </summary> [JsonPropertyName("fail_count")] public long FailCount { get; set; } /// <summary> /// 失败任务明细列表 /// </summary> [JsonPropertyName("fail_task_details")] public List<FailTaskDetail> FailTaskDetails { get; set; } /// <summary> /// 操作成功任务数量 /// </summary> [JsonPropertyName("success_count")] public long SuccessCount { get; set; } } }
using CommandLine; using VcEngineAutomation; namespace VcEngineRunner.Simulation { public class GenericOptions { public GenericOptions() { InstallationPath = VcEngine.DefaultInstallationPath; } [Option("installation-path", HelpText = "Path to the installation folder")] public string InstallationPath { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ML.NET_NLP { public class TextBagOfWords { public float[] BagOfWords { get; set; } } //public static class TextNGramsExtensions //{ // public static void ConsolePrint(this TextNGrams nGrams) // { // Console.Write(Environment.NewLine); // var sb = new StringBuilder(); // foreach (var nGram in nGrams.NGrams) // { // sb.AppendLine(nGram.ToString()); // } // Console.WriteLine(sb.ToString()); // } //} }
using System; using System.Xml.Linq; namespace R5T.Magyar.Xml { public static class XElementHelper { public const XElement NotFound = default; // null public static bool IsLeaf(XElement xElement) { var isLeaf = !xElement.HasElements; return isLeaf; } public static bool IsNotFound(XElement xElement) { var isNotFound = xElement == XElementHelper.NotFound; return isNotFound; } public static bool ValueAsBoolean(string xElementValue) { var valueAsBoolean = Boolean.Parse(xElementValue); return valueAsBoolean; } public static bool WasFound(XElement xElement) { var wasFound = xElement != XElementHelper.NotFound; return wasFound; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.TestPlatform.TestUtilities { using System.Reflection; #if !NET451 using System.Runtime.Loader; #endif /// <summary> /// Assembly utility to perform assembly related functions. /// </summary> public class AssemblyUtility { /// <summary> /// Gets the assembly name at a given location. /// </summary> /// <param name="assemblyPath"></param> /// <returns></returns> public static AssemblyName GetAssemblyName(string assemblyPath) { #if !NET451 return AssemblyLoadContext.GetAssemblyName(assemblyPath); #else return AssemblyName.GetAssemblyName(assemblyPath); #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Decia.Business.Common.Modeling; using Decia.Business.Common.Time; using Decia.Business.Common.ValueObjects; namespace Decia.Business.Common.Computation { public interface ICurrentState_Base { ProcessingType ProcessingType { get; } OperationValidityType ValidityArea { get; } bool UseExtendedStructure { get; } ProcessingAcivityType AcivityType { get; } bool IsModelLevel { get; } bool ComputeByPeriod { get; } Guid ProjectGuid { get; } long RevisionNumber { get; } ModelObjectReference ModelTemplateRef { get; } ModelObjectReference VariableTemplateRef { get; } ModelObjectReference ModelInstanceRef { get; } ModelObjectReference VariableInstanceRef { get; } Nullable<ModelObjectReference> NullableModelInstanceRef { get; } Nullable<ModelObjectReference> NullableVariableInstanceRef { get; } Nullable<TimePeriodType> PrimaryPeriodType { get; } Nullable<TimePeriodType> SecondaryPeriodType { get; } Nullable<TimePeriod> PrimaryPeriod { get; } Nullable<TimePeriod> SecondaryPeriod { get; } MultiTimePeriodKey TimeKey { get; } Nullable<TimePeriod> NavigationPeriod { get; set; } DateTime ModelStartDate { get; set; } DateTime ModelEndDate { get; set; } bool HasParentComputationGroup { get; } IComputationGroup ParentComputationGroup { get; set; } } }
using System.Windows.Controls.Primitives; namespace boilersGraphics.Controls { public class SnapPoint : Thumb { } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CompNet.Tests { [TestClass] public class ComputerTests { [TestMethod] public void SetInfectedTest() { var comp = new Computer("Linux", 0, false); Assert.IsFalse(comp.IsInfected); comp.SetInfected(); Assert.IsTrue(comp.IsInfected); } [TestMethod] public void ComputerTest() { var comp = new Computer("Linux", 0.2, false); Assert.AreEqual("Linux", comp.TypeOfOS); Assert.AreEqual(0.2, comp.ProbabilityOfInfection); Assert.AreEqual(false, comp.IsInfected); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace AsyncFileIOWinForm { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private async Task<long> CopyAsync(string FromPath, string ToPath) { btnSyncCopy.Enabled = false; long totalCopied = 0; using (FileStream fromStream = new FileStream(FromPath, FileMode.Open)) { using (FileStream toStream = new FileStream(ToPath, FileMode.Create)) { byte[] buffer = new byte[1024 * 1024]; int nRead = 0; while ((nRead = await fromStream.ReadAsync(buffer, 0, buffer.Length)) != 0) { await toStream.WriteAsync(buffer, 0, nRead); totalCopied += nRead; // 프로그레스바에 현재 파일 복사 상태 표시 pbCopy.Value = (int)(((double)totalCopied / (double)fromStream.Length) * pbCopy.Maximum); } } } btnSyncCopy.Enabled = true; return totalCopied; } private long CopySync(string FromPath, string ToPath) { btnAsyncCopy.Enabled = false; long totalCopied = 0; using (FileStream fromStream = new FileStream(FromPath, FileMode.Open)) { using (FileStream toStream = new FileStream(ToPath, FileMode.Create)) { byte[] buffer = new byte[1024 * 1024]; int nRead = 0; while ((nRead = fromStream.Read(buffer, 0, buffer.Length)) != 0) { toStream.Write(buffer, 0, nRead); totalCopied += nRead; // 프로그레스바에 현재 파일 복사 상태 표시 pbCopy.Value = (int)(((double)totalCopied / (double)fromStream.Length) * pbCopy.Maximum); } } } btnAsyncCopy.Enabled = true; return totalCopied; } private void btnFindSource_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtSource.Text = dlg.FileName; } } private void btnFindTarget_Click(object sender, EventArgs e) { SaveFileDialog dlg = new SaveFileDialog(); if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtTarget.Text = dlg.FileName; } } private async void btnAsyncCopy_Click(object sender, EventArgs e) { long totalCopied = await CopyAsync(txtSource.Text, txtTarget.Text); } private void btnSyncCopy_Click(object sender, EventArgs e) { long totalCopied = CopySync(txtSource.Text, txtTarget.Text); } private void btnCancel_Click(object sender, EventArgs e) { MessageBox.Show("UI 반응 테스트 성공."); } } }
using System; using System.Collections.Generic; using UIC.Framework.Interfaces.Edm.Definition; namespace UIC.Framework.Interfaces.Project { public interface UicProject { string ProjectKey { get; } string Name { get; } string Description { get; } string Owner { get; } Guid CustomerForeignKey { get; } List<AttributeDefinition> Attributes { get; } List<ProjectDatapointTask> DatapointTasks { get; } } }
using NUnit.Framework; using System; using akarnokd.reactive_extensions; using System.Reactive.Concurrency; using System.Reactive.Linq; namespace akarnokd.reactive_extensions_test.single { [TestFixture] public class SingleRepeatTest { #region + Times + [Test] public void Times_Basic() { var count = 0; var src = SingleSource.FromFunc(() => ++count); var obs = src.Repeat(); obs .SubscribeOn(NewThreadScheduler.Default) .Take(5) .Test() .AwaitDone(TimeSpan.FromSeconds(5)) .AssertResult(1, 2, 3, 4, 5); Assert.True(5 <= count, $"{count}"); } [Test] public void Times_Limit() { var count = 0; var src = SingleSource.FromFunc(() => ++count); var obs = src.Repeat(4); obs .Test() .AssertResult(1, 2, 3, 4, 5); Assert.AreEqual(5, count); } [Test] public void Times_Error() { SingleSource.Error<int>(new InvalidOperationException()) .Repeat() .Test() .AssertFailure(typeof(InvalidOperationException)); } [Test] public void Times_Dispose() { TestHelper.VerifyDisposeSingle<int, int>(m => m.Repeat()); } #endregion + Times + #region + Handler + [Test] public void Handler_Basic() { var count = 0; var src = SingleSource.FromFunc(() => ++count); var obs = src.Repeat(v => true); obs .SubscribeOn(NewThreadScheduler.Default) .Take(5) .Test() .AwaitDone(TimeSpan.FromSeconds(5)) .AssertResult(1, 2, 3, 4, 5); Assert.True(5 <= count, $"{count}"); } [Test] public void Handler_Limit() { var count = 0; var src = SingleSource.FromFunc(() => ++count); var obs = src.Repeat(v => v < 5); obs .Test() .AssertResult(1, 2, 3, 4, 5); Assert.AreEqual(5, count); } [Test] public void Handler_Error() { SingleSource.Error<int>(new InvalidOperationException()) .Repeat(v => true) .Test() .AssertFailure(typeof(InvalidOperationException)); } [Test] public void Handler_Dispose() { TestHelper.VerifyDisposeSingle<int, int>(m => m.Repeat(v => true)); } [Test] public void Handler_False() { var count = 0; var src = SingleSource.FromFunc(() => ++count); var obs = src.Repeat(v => false); obs .Test() .AssertResult(1); Assert.AreEqual(1, count); } #endregion + Handler + } }
using System; using System.Linq; namespace ReferencesCheck { /// <summary> /// Supported project configurations. /// </summary> static class SupportedConfigs { /// <summary> /// Supported names. /// </summary> private static readonly string[] Names = new string[] { "Debug", "Release" }; /// <summary> /// Gets the help string for supported names. /// </summary> public static string Help => $"({String.Join("|", Names.Select(i => $"\"{i.ToLowerInvariant()}\""))})"; /// <summary> /// Matches a command line parameter for configuration name. /// </summary> /// <param name="config">Configuration name given.</param> /// <param name="configDirectory">Configuration directory name.</param> /// <returns>True if given name matches.</returns> public static bool Match(string config, out string configDirectory) { configDirectory = null; foreach (var name in Names) { if (name.Equals(config, StringComparison.OrdinalIgnoreCase)) { configDirectory = name; return true; } } return false; } } }
using System; using UnityEngine; namespace Zenject.SpaceFighter { public class EnemyStateRunAway : IEnemyState { readonly EnemyStateManager _stateManager; readonly Settings _settings; readonly EnemyModel _model; readonly PlayerFacade _player; public EnemyStateRunAway( PlayerFacade player, EnemyModel model, Settings settings, EnemyStateManager stateManager) { _stateManager = stateManager; _settings = settings; _model = model; _player = player; } public void Initialize() { } public void Dispose() { } public void Update() { if (_player.IsDead) { _stateManager.ChangeState(EnemyStates.Idle); return; } // look away from player _model.DesiredLookDir = -(_player.Position - _model.Position).normalized; if ((_player.Position - _model.Position).magnitude > _settings.SafeDistance) { _stateManager.ChangeState(EnemyStates.Idle); } } public void FixedUpdate() { MoveAwayFromPlayer(); } void MoveAwayFromPlayer() { _model.AddForce(_model.LookDir * _model.MoveSpeed); } [Serializable] public class Settings { public float SafeDistance; } } }
using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using StackExchange.Redis; namespace Gofer.NET { public interface IBackend { Task Enqueue(string queueKey, string jsonString); Task<string> Dequeue(string queueKey); Task<IEnumerable<string>> DequeueBatch(string queueKey, int batchSize=100); Task<IBackendLock> LockBlocking(string lockKey); Task<IBackendLock> LockNonBlocking(string lockKey); Task SetString(string key, string value); Task<string> GetString(string key); Task<IEnumerable<string>> GetStrings(IEnumerable<string> key); Task<ISet<string>> GetSet(string key); Task AddToSet(string key, string value); Task RemoveFromSet(string key, string value); Task<IEnumerable<string>> GetList(string key); Task<long> AddToList(string key, string value); Task<long> RemoveFromList(string key, string value); Task DeleteKey(string key); Task<LoadedLuaScript> LoadLuaScript(string scriptContents); Task<RedisResult> RunLuaScript(LoadedLuaScript script, RedisKey[] keys, RedisValue[] values); Task AddToOrderedSet(string setKey, long score, string value); Task<bool> RemoveFromOrderedSet(string setKey, string value); Task SetMapField(string mapKey, string mapField, RedisValue value); Task SetMapFields(string mapKey, params (RedisValue, RedisValue)[] mapFieldValuePairs); Task<bool> DeleteMapFields(string mapKey, params RedisValue[] mapFields); Task<RedisValue> GetMapField(string mapKey, string mapField); } }
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// TradePeriodDTO Data Structure. /// </summary> [Serializable] public class TradePeriodDTO : AopObject { /// <summary> /// 归属日期 /// </summary> [XmlElement("belong_day")] public string BelongDay { get; set; } /// <summary> /// 非交易的描述,如:春节、周末休日,交易日时此描述为交易中 /// </summary> [XmlElement("state_desc")] public string StateDesc { get; set; } /// <summary> /// 日期是否是交易日,true:表示是交易日 /// </summary> [XmlElement("trading_day")] public bool TradingDay { get; set; } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; namespace MicroFx.Mapper { public interface IMapper { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MenuController : MonoBehaviour { Transform lastHit; Transform pointer; public TextMesh countdownText; IEnumerator countdownCoroutine; // New York, San Francisco, Paris, Atlanta float[] latitudes = { 40.749642f, 37.808045f, 48.857622f, 33.770855f }; float[] longitudes = { -73.987144f, -122.475540f, 2.295737f, -84.395587f }; int city = -1; void Start () { pointer = GameObject.Find("Cylinder").transform; pointer.localScale = new Vector3(0.05f, 0.05f, 0.05f); countdownText.text = ""; } void Update() { if (Input.GetMouseButton(0)) { float deltaX = Input.GetAxis("Mouse X"); float deltaY = Input.GetAxis("Mouse Y"); transform.Rotate(new Vector3(-deltaY, deltaX, 0)); } Ray ray = new Ray(transform.position, transform.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { if (lastHit != null && lastHit != hit.transform) { if (countdownCoroutine != null) { StopCoroutine(countdownCoroutine); countdownCoroutine = null; } countdownText.text = ""; } lastHit = hit.transform; pointer.localScale = new Vector3(0.2f, 0.2f, 0.2f); if (countdownCoroutine == null) { countdownCoroutine = countdown(); StartCoroutine(countdownCoroutine); switch (hit.rigidbody.gameObject.name) { case "New York": city = 0; break; case "San Francisco": city = 1; break; case "Paris": city = 2; break; case "Atlanta": city = 3; break; } } } else if (lastHit != null) { countdownText.text = ""; if (countdownCoroutine != null) { StopCoroutine(countdownCoroutine); countdownCoroutine = null; } pointer.localScale = new Vector3(0.05f, 0.05f, 0.05f); } } IEnumerator countdown() { yield return new WaitForSeconds(1); countdownText.text = "3"; yield return new WaitForSeconds(1); countdownText.text = "2"; yield return new WaitForSeconds(1); countdownText.text = "1"; yield return new WaitForSeconds(1); PlayerPrefs.SetFloat("latitude", latitudes[city]); PlayerPrefs.SetFloat("longitude", longitudes[city]); Application.LoadLevel("GameScene"); } }
using BlazorComponent; using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Masa.Blazor { public class MDataTableRow<TItem> : BDataTableRow<TItem> { [Parameter] public Func<TItem, bool> IsSelected { get; set; } [Parameter] public Func<TItem, bool> IsExpanded { get; set; } [Parameter] public string ItemClass { get; set; } [Parameter] public bool Stripe { get; set; } public bool IsStripe => Stripe && Index % 2 == 1; protected override void SetComponentClass() { CssProvider .Apply(cssBuilder => { cssBuilder .AddIf("m-data-table__selected", () => IsSelected(Item)) .AddIf("m-data-table__expanded m-data-table__expanded__row", () => IsExpanded(Item)) .AddIf("stripe", () => IsStripe) .Add(ItemClass); }) .Apply("cell", cssBuilder => { if (cssBuilder.Data is DataTableHeader header) { cssBuilder .Add($"text-{header.Align ?? "start"}") .Add(header.CellClass) .AddIf("m-data-table__divider", () => header.Divider); } }); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace AntDesign { /// <summary> /// /// </summary> public class ConfirmRef : FeedbackRefWithOkCancelBase { #region internal internal bool IsCreateByModalService => Service != null; internal TaskCompletionSource<ConfirmResult> TaskCompletionSource { get; set; } internal ConfirmRef(ConfirmOptions config) { Config = config; } internal ConfirmRef(ConfirmOptions config, ModalService service) { Config = config; Service = service; } #endregion /// <summary> /// ModalService /// </summary> protected ModalService Service { get; set; } /// <summary> /// Confirm dialog options /// </summary> public ConfirmOptions Config { get; private set; } #region base inheritdoc /// <summary> /// close Confirm dialog /// </summary> /// <returns></returns> public override async Task CloseAsync() { await (Service?.DestroyConfirmAsync(this) ?? Task.CompletedTask); } /// <summary> /// Open Confirm dialog /// </summary> /// <returns></returns> public override async Task OpenAsync() { await (Service?.OpenConfirmAsync(this) ?? Task.CompletedTask); } /// <summary> /// update Confirm dialog config which Visible=true /// </summary> /// <returns></returns> public override async Task UpdateConfigAsync() { await (Service?.UpdateConfirmAsync(this) ?? Task.CompletedTask); } /// <summary> /// update Confirm dialog config with a new ConfirmOptions /// </summary> /// <param name="config"></param> /// <returns></returns> public async Task UpdateConfigAsync(ConfirmOptions config) { Config = config; await UpdateConfigAsync(); } #endregion } /// <summary> /// ConfirmRef with return value /// </summary> /// <typeparam name="TResult"></typeparam> public class ConfirmRef<TResult> : ConfirmRef, IOkCancelRef<TResult> { internal ConfirmRef(ConfirmOptions config, ModalService service) : base(config, service) { } /// <inheritdoc /> public new Func<TResult, Task> OnCancel { get; set; } /// <inheritdoc /> public new Func<TResult, Task> OnOk { get; set; } /// <inheritdoc /> public async Task OkAsync(TResult result) { await (OnOk?.Invoke(result) ?? Task.CompletedTask); } /// <inheritdoc /> public async Task CancelAsync(TResult result) { await (OnCancel?.Invoke(result) ?? Task.CompletedTask); } } }
using Microsoft.EntityFrameworkCore; using RS1_PrakticniDioIspita_2017_01_24.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RS1_PrakticniDioIspita_2017_01_24.EF { public class MojContext : DbContext { public MojContext(DbContextOptions<MojContext> options) : base(options) { } public DbSet<AkademskaGodina> AkademskaGodina { get; set; } public DbSet<Angazovan> Angazovan { get; set; } public DbSet<Nastavnik> Nastavnik { get; set; } public DbSet<Predmet> Predmet { get; set; } public DbSet<SlusaPredmet> SlusaPredmet { get; set; } public DbSet<Student> Student { get; set; } public DbSet<UpisGodine> UpisGodine { get; set; } public DbSet<OdrzaniCas> OdrzaniCas { get; set; } public DbSet<OdrzaniCasDetalji> OdrzaniCasDetalji { get; set; } } }