content stringlengths 23 1.05M |
|---|
using CharlieBackend.Core.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace CharlieBackend.Data.Configurations
{
class StudentGroupEntityConfiguration : IEntityTypeConfiguration<StudentGroup>
{
public void Configure(EntityTypeBuilder<StudentGroup> entity)
{
entity.ToTable("StudentGroups");
entity.Property(e => e.Id)
.IsRequired()
.HasColumnName("ID");
entity.Property(e => e.CourseId)
.IsRequired()
.HasColumnName("CourseID");
entity.Property(e => e.Name)
.IsRequired()
.HasColumnName("Name")
.HasColumnType("VARCHAR(100)");
entity.Property(e => e.StartDate)
.IsRequired()
.HasColumnName("StartDate")
.HasColumnType("DATE");
entity.Property(e => e.FinishDate)
.IsRequired()
.HasColumnName("FinishDate")
.HasColumnType("DATE");
entity.Property(e => e.IsActive)
.IsRequired()
.HasColumnName("IsActive")
.HasColumnType("BIT")
.HasDefaultValueSql("1");
entity.HasKey(e => e.Id)
.HasName("PRIMARY");
entity.HasOne(d => d.Course)
.WithMany(p => p.StudentGroup)
.HasForeignKey(d => d.CourseId)
.HasConstraintName("FK_CourseStudentGroups");
entity.HasIndex(e => e.Name)
.HasName("UQ_NameStudentGroups")
.IsUnique();
}
}
}
|
// Copyright (c) 2012, Joshua Burke
// All rights reserved.
//
// See LICENSE for more information.
using System.Runtime.InteropServices;
using SharpDX;
namespace Frost.DirectX.Composition
{
[StructLayout(LayoutKind.Sequential)] internal struct RenderConstants
{
public static readonly int ByteSize;
static RenderConstants()
{
ByteSize = GPUData.SizeOf<RenderConstants>();
}
public Vector4 TextureRegion;
public Vector4 DrawnRegion;
public Matrix Transform;
}
} |
using System;
using Net.Sf.Pkcs11.Wrapper;
namespace Net.Sf.Pkcs11.Objects
{
/// <summary>
/// Description of GostPrivateKey.
/// </summary>
public class GostPrivateKey : PrivateKey
{
/// <summary>
/// Params.
/// </summary>
protected ByteArrayAttribute params_ = new ByteArrayAttribute((uint)CKA.GOSTR3410PARAMS);
public ByteArrayAttribute Params
{
get { return params_; }
}
public GostPrivateKey()
{
this.KeyType.KeyType = CKK.GOST;
params_.Value = PKCS11Constants.SC_PARAMSET_GOSTR3410_A;
}
public GostPrivateKey(Session session, uint hObj)
: base(session, hObj)
{
params_.Value = PKCS11Constants.SC_PARAMSET_GOSTR3410_A;
}
public static new P11Object GetInstance(Session session, uint hObj)
{
return new GostPrivateKey(session, hObj);
}
public override void ReadAttributes(Session session)
{
base.ReadAttributes(session);
params_ = ReadAttribute(session, HObj, params_);
}
}
}
|
using System;
using System.Data.Linq.Mapping;
using Bloom.Domain.Enums;
namespace Bloom.Domain.Models
{
/// <summary>
/// Represents a segment of a song.
/// </summary>
[Table(Name = "song_segment")]
public class SongSegment
{
/// <summary>
/// Creates a new song segment instance.
/// </summary>
/// <param name="song">A song.</param>
/// <param name="startTime">The segment start time.</param>
/// <param name="stopTime">The segment stop time.</param>
public static SongSegment Create(Song song, int startTime, int stopTime)
{
return new SongSegment
{
Id = Guid.NewGuid(),
SongId = song.Id,
StartTime = startTime,
StopTime = stopTime
};
}
/// <summary>
/// Creates a new song segment instance.
/// </summary>
/// <param name="song">A song.</param>
/// <param name="startTime">The segment start time.</param>
/// <param name="stopTime">The segment stop time.</param>
/// <param name="name">The segment name.</param>
public static SongSegment Create(Song song, int startTime, int stopTime, string name)
{
return new SongSegment
{
Id = Guid.NewGuid(),
SongId = song.Id,
StartTime = startTime,
StopTime = stopTime,
Name = name
};
}
/// <summary>
/// Gets or sets the song segment identifier.
/// </summary>
[Column(Name = "id", IsPrimaryKey = true)]
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the song identifier.
/// </summary>
[Column(Name = "song_id")]
public Guid SongId { get; set; }
/// <summary>
/// Gets or sets the song segment name.
/// </summary>
[Column(Name = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the song segment start time in milliseconds.
/// </summary>
[Column(Name = "start_time")]
public int StartTime { get; set; }
/// <summary>
/// Gets or sets the song segment stop time in milliseconds.
/// </summary>
[Column(Name = "stop_time")]
public int StopTime { get; set; }
/// <summary>
/// Gets or sets the BPM.
/// </summary>
[Column(Name = "bpm")]
public int? Bpm { get; set; }
/// <summary>
/// Gets or sets the song segment musical key.
/// </summary>
[Column(Name = "key")]
public MusicalKeys? Key { get; set; }
/// <summary>
/// Gets or sets the time signature identifier.
/// </summary>
[Column(Name = "time_signature_id")]
public Guid? TimeSignatureId { get; set; }
/// <summary>
/// Gets or sets the song segment time signature.
/// </summary>
public TimeSignature TimeSignature
{
get { return _timeSignature; }
set
{
_timeSignature = value;
TimeSignatureId = _timeSignature?.Id;
}
}
private TimeSignature _timeSignature;
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
public override string ToString()
{
return !string.IsNullOrEmpty(Name) ? Name : Id.ToString();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DelaunayTriangulation
{
public class Edge
{
private float m_Length;
public float length
{
get
{
return m_Length;
}
}
private Vertex m_Point0;
public Vertex point0
{
get
{
return m_Point0;
}
}
private Vertex m_Point1;
public Vertex point1
{
get
{
return m_Point1;
}
}
public Edge(Vertex point0, Vertex point1)
{
m_Point0 = point0;
m_Point1 = point1;
Vector2 edgeVector = m_Point1.position - m_Point0.position;
m_Length = edgeVector.magnitude;
}
public float Length()
{
return m_Length;
}
public override bool Equals(object obj)
{
Edge other = obj as Edge;
if (other != null)
{
// Check if the two first points overlap
bool isSame = other.point0.Equals(point0) && other.point1.Equals(point1);
// Check if the points overlap in cross
isSame |= other.point1.Equals(point0) && other.point0.Equals(point1);
return isSame;
}
return false;
}
public override int GetHashCode()
{
return m_Point0.GetHashCode() + 31 * m_Point1.GetHashCode();
}
}
}
|
using System;
namespace Fizz
{
public class FizzError
{
public static readonly int ERROR_BAD_ARGUMENT = 0xF122400;
public static readonly int ERROR_REQUEST_FAILED = 0xF122401;
public static readonly int ERROR_INVALID_REQUEST = 0xF122402;
public static readonly int ERROR_AUTH_FAILED = 0xF122403;
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace SujaySarma.Sdk.Azure.Storage
{
/// <summary>
/// Routing preference for the storage endpoints
/// </summary>
public class RoutingPreference
{
/// <summary>
/// Specify if internet routing storage endpoints are to be published
/// </summary>
[JsonProperty("publishInternetEndpoints")]
public bool AreInternetEndpointsPublished { get; set; }
/// <summary>
/// Specify if Microsoft routing storage endpoints to be published
/// </summary>
[JsonProperty("publishMicrosoftEndpoints")]
public bool AreMicrosoftEndpointsPublished { get; set; }
/// <summary>
/// Choice of routing opted
/// </summary>
[JsonProperty("routingChoice"), JsonConverter(typeof(StringEnumConverter))]
public RoutingChoice RoutingChoice { get; set; }
/// <summary>
/// Default constructor
/// </summary>
public RoutingPreference() { }
}
}
|
// Copyright (c) Anton Abramenko <anton@abramenko.dev>
// Licensed under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
namespace ExactJson.Tests.Unit
{
public sealed class JsonNumberTests
{
#region Create
[TestCase(byte.MinValue)]
[TestCase(byte.MaxValue)]
public void Create_UInt8(byte value)
{
var num = JsonNumber.Create(value);
Assert.That(num.Value, Is.EqualTo((JsonDecimal) value));
Assert.That(num.Format, Is.EqualTo(JsonNumberFormat.For(value)));
}
[TestCase(sbyte.MinValue)]
[TestCase(sbyte.MaxValue)]
public void Create_Int8(sbyte value)
{
var num = JsonNumber.Create(value);
Assert.That(num.Value, Is.EqualTo((JsonDecimal) value));
Assert.That(num.Format, Is.EqualTo(JsonNumberFormat.For(value)));
}
[TestCase(short.MinValue)]
[TestCase(short.MaxValue)]
public void Create_Int16(short value)
{
var num = JsonNumber.Create(value);
Assert.That(num.Value, Is.EqualTo((JsonDecimal) value));
Assert.That(num.Format, Is.EqualTo(JsonNumberFormat.For(value)));
}
[TestCase(ushort.MinValue)]
[TestCase(ushort.MaxValue)]
public void Create_UInt16(ushort value)
{
var num = JsonNumber.Create(value);
Assert.That(num.Value, Is.EqualTo((JsonDecimal) value));
Assert.That(num.Format, Is.EqualTo(JsonNumberFormat.For(value)));
}
[TestCase(int.MaxValue)]
[TestCase(int.MinValue)]
public void Create_Int32(int value)
{
var num = JsonNumber.Create(value);
Assert.That(num.Value, Is.EqualTo((JsonDecimal) value));
Assert.That(num.Format, Is.EqualTo(JsonNumberFormat.For(value)));
}
[TestCase(uint.MaxValue)]
[TestCase(uint.MinValue)]
public void Create_UInt32(uint value)
{
var num = JsonNumber.Create(value);
Assert.That(num.Value, Is.EqualTo((JsonDecimal) value));
Assert.That(num.Format, Is.EqualTo(JsonNumberFormat.For(value)));
}
[TestCase(long.MinValue)]
[TestCase(long.MaxValue)]
public void Create_Int64Max(long value)
{
var num = JsonNumber.Create(value);
Assert.That(num.Value, Is.EqualTo((JsonDecimal) value));
Assert.That(num.Format, Is.EqualTo(JsonNumberFormat.For(value)));
}
[TestCase(ulong.MaxValue)]
[TestCase(ulong.MinValue)]
public void Create_UInt64Max(ulong value)
{
var num = JsonNumber.Create(value);
Assert.That(num.Value, Is.EqualTo((JsonDecimal) value));
Assert.That(num.Format, Is.EqualTo(JsonNumberFormat.For(value)));
}
[TestCase(0.0)]
[TestCase(double.MaxValue)]
[TestCase(double.MinValue)]
[TestCase(double.Epsilon)]
public void Create_Double(double value)
{
var num = JsonNumber.Create(value);
Assert.That(num.Value, Is.EqualTo((JsonDecimal) value));
Assert.That(num.Format, Is.EqualTo(JsonNumberFormat.For(value)));
}
[TestCase(0.0f)]
[TestCase(float.MaxValue)]
[TestCase(float.MinValue)]
[TestCase(float.Epsilon)]
public void Create_Single(float value)
{
var num = JsonNumber.Create(value);
Assert.That(num.Value, Is.EqualTo((JsonDecimal) value));
Assert.That(num.Format, Is.EqualTo(JsonNumberFormat.For(value)));
}
[TestCase("0")]
[TestCase("-79228162514264337593543950335")]
[TestCase("79228162514264337593543950335")]
public void Create_Decimal(string s)
{
decimal value = decimal.Parse(s);
var num = JsonNumber.Create(value);
Assert.That(num.Value, Is.EqualTo((JsonDecimal) value));
Assert.That(num.Format, Is.EqualTo(JsonNumberFormat.For(value)));
}
#endregion
#region NodeType
[Test]
public void NodeType_ByDefault_Number()
{
var num = JsonNumber.Create(int.MaxValue);
Assert.That(num.NodeType, Is.EqualTo(JsonNodeType.Number));
}
#endregion
#region ValueAsDecimal
[Test]
public void ValueAsDecimal_BeingInt32Number_ReturnsInt32Value()
{
var num = JsonNumber.Create(int.MaxValue);
var result = num.Value;
Assert.That(result, Is.EqualTo((JsonDecimal) int.MaxValue));
}
[Test]
public void ValueAsDecimal_BeingInt64Number_ReturnsInt64Value()
{
var num = JsonNumber.Create(long.MaxValue);
var result = num.Value;
Assert.That(result, Is.EqualTo((JsonDecimal) long.MaxValue));
}
[Test]
public void ValueAsDecimal_BeingDecimalNumber_ReturnsDecimalValue()
{
var num = JsonNumber.Create(decimal.MaxValue);
var result = num.Value;
Assert.That(result, Is.EqualTo((JsonDecimal) decimal.MaxValue));
}
#endregion
#region Equals
[Test]
public void Equals_BeingInt32NumberAndGivenNull_ReturnsFalse()
{
object num = JsonNumber.Create(int.MaxValue);
Assert.That(num.Equals(null), Is.False);
}
[Test]
public void Equals_BeingInt64NumberAndGivenNull_ReturnsFalse()
{
object num = JsonNumber.Create(long.MaxValue);
Assert.That(num.Equals(null), Is.False);
}
[Test]
public void Equals_BeingDecimalNumberAndGivenNull_ReturnsFalse()
{
object num = JsonNumber.Create(decimal.MaxValue);
Assert.That(num.Equals(null), Is.False);
}
[Test]
public void Equals_BeingInt32NumberAndGivenEqualInt32Number_ReturnsTrue()
{
object num1 = JsonNumber.Create(int.MaxValue);
object num2 = JsonNumber.Create(int.MaxValue);
Assert.That(num1.Equals(num2), Is.True);
}
[Test]
public void Equals_BeingInt64NumberAndGivenEqualInt64Number_ReturnsTrue()
{
object num1 = JsonNumber.Create(long.MaxValue);
object num2 = JsonNumber.Create(long.MaxValue);
Assert.That(num1.Equals(num2), Is.True);
}
[Test]
public void Equals_BeingDecimalNumberAndGivenEqualDecimalNumber_ReturnsTrue()
{
object num1 = JsonNumber.Create(decimal.MaxValue);
object num2 = JsonNumber.Create(decimal.MaxValue);
Assert.That(num1.Equals(num2), Is.True);
}
[Test]
public void Equals_BeingInt32NumberAndGivenNotEqualInt32Number_ReturnsFalse()
{
object num1 = JsonNumber.Create(int.MaxValue);
object num2 = JsonNumber.Create(int.MinValue);
Assert.That(num1.Equals(num2), Is.False);
}
[Test]
public void Equals_BeingInt64NumberAndGivenNotEqualInt64Number_ReturnsFalse()
{
object num1 = JsonNumber.Create(long.MaxValue);
object num2 = JsonNumber.Create(long.MinValue);
Assert.That(num1.Equals(num2), Is.False);
}
[Test]
public void Equals_BeingDecimalNumberAndGivenNotEqualDecimalNumber_ReturnsFalse()
{
object num1 = JsonNumber.Create(decimal.MaxValue);
object num2 = JsonNumber.Create(decimal.MinValue);
Assert.That(num1.Equals(num2), Is.False);
}
#endregion
#region GetHashCode
[Test]
public void GetHashCode_TwoInt32NumbersEqual_HashCodesMatch()
{
int hash1 = JsonNumber.Create(int.MaxValue).GetHashCode();
int hash2 = JsonNumber.Create(int.MaxValue).GetHashCode();
Assert.That(hash1, Is.EqualTo(hash2));
}
[Test]
public void GetHashCode_TwoInt64NumbersEqual_HashCodesMatch()
{
int hash1 = JsonNumber.Create(long.MaxValue).GetHashCode();
int hash2 = JsonNumber.Create(long.MaxValue).GetHashCode();
Assert.That(hash1, Is.EqualTo(hash2));
}
[Test]
public void GetHashCode_TwoDecimalNumbersEqual_HashCodesMatch()
{
int hash1 = JsonNumber.Create(decimal.MaxValue).GetHashCode();
int hash2 = JsonNumber.Create(decimal.MaxValue).GetHashCode();
Assert.That(hash1, Is.EqualTo(hash2));
}
#endregion
#region Write
[Test]
public void Write_BeingInt32NumberAndGivenNull_ThrowsArgumentNullException()
{
var num = JsonNumber.Create(int.MaxValue);
Assert.Throws<ArgumentNullException>(() => num.WriteTo((JsonWriter) null));
}
[Test]
public void Write_BeingInt64NumberAndGivenNull_ThrowsArgumentNullException()
{
var num = JsonNumber.Create(long.MaxValue);
Assert.Throws<ArgumentNullException>(() => num.WriteTo((JsonWriter) null));
}
[Test]
public void Write_BeingDecimalNumberAndGivenNull_ThrowsArgumentNullException()
{
var num = JsonNumber.Create(decimal.MaxValue);
Assert.Throws<ArgumentNullException>(() => num.WriteTo((JsonWriter) null));
}
[Test]
public void Write_BeingInt32Number_WritesDecimalNumber()
{
var mock = new Mock<JsonWriter>();
var num = JsonNumber.Create(int.MaxValue);
num.WriteTo(mock.Object);
mock.Verify(w => w.WriteNumber(int.MaxValue, JsonNumberFormat.For(int.MaxValue)), Times.Once);
mock.VerifyNoOtherCalls();
}
[Test]
public void Write_BeingInt64Number_WritesDecimalNumber()
{
var mock = new Mock<JsonWriter>();
var num = JsonNumber.Create(long.MaxValue);
num.WriteTo(mock.Object);
mock.Verify(w => w.WriteNumber(long.MaxValue, JsonNumberFormat.For(long.MaxValue)), Times.Once);
mock.VerifyNoOtherCalls();
}
[Test]
public void Write_BeingDecimalNumber_WritesDecimalNumber()
{
var mock = new Mock<JsonWriter>();
var num = JsonNumber.Create(decimal.MaxValue);
num.WriteTo(mock.Object);
mock.Verify(w => w.WriteNumber(decimal.MaxValue, JsonNumberFormat.For(decimal.MaxValue)), Times.Once);
mock.VerifyNoOtherCalls();
}
#endregion
#region ToString
[Test]
public void ToString_Number_OutputFormattedNumber()
{
var result = JsonNumber.Create(1, ".1").ToString();
Assert.That(result, Is.EqualTo("1.0"));
}
#endregion
}
} |
using Microservices.Core.Infrastructure.Options;
using System.Collections.Generic;
namespace Web.Infrastructure.Options
{
public class AppConfig
{
public StoreSettings StoreSettings { get; set; }
public ServiceConfig Services { get; set; }
public RedisOptions Redis { get; set; }
}
}
|
namespace ImageSharp.Processing.AutoCrop.Models
{
public interface IAutoCropSettings
{
int PadX { get; }
int PadY { get; }
int? ColorThreshold { get; }
float? BucketThreshold { get; }
PadMode PadMode { get; }
bool AnalyzeWeights { get; }
}
}
|
using DavidLievrouw.Utils.ForTesting.FakeItEasy;
using DavidLievrouw.Utils.ForTesting.FluentAssertions;
using DavidLievrouw.Voter.Data.Dapper;
using FluentAssertions;
using NUnit.Framework;
namespace DavidLievrouw.Voter.Data {
[TestFixture]
public class KnownUserDataServiceTests {
IQueryExecutor _queryExecutor;
KnownUserDataService _sut;
[SetUp]
public virtual void SetUp() {
_queryExecutor = _queryExecutor.Fake();
_sut = new KnownUserDataService(_queryExecutor);
}
[TestFixture]
public class Construction : KnownUserDataServiceTests {
[Test]
public void HasExactlyOneConstructor_WithNoOptionalParameters() {
_sut.Should().HaveExactlyOneConstructorWithoutOptionalParameters();
}
}
}
} |
using System.Collections.Generic;
namespace ReadingIsGood.Entities.DTOs
{
public class UpdateBookDto
{
public string ISBN { get; set; }
public string AuthorId { get; set; }
public IEnumerable<string> CategoryIds { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Pages { get; set; }
public int UnitsInStock { get; set; }
public decimal UnitPrice { get; set; }
public int YearOfPublication { get; set; }
}
}
|
using CleanArchitectureCosmosDB.Core.Interfaces;
using CleanArchitectureCosmosDB.Core.Interfaces.Persistence;
using CleanArchitectureCosmosDB.Infrastructure.AppSettings;
using CleanArchitectureCosmosDB.Infrastructure.CosmosDbData.Repository;
using CleanArchitectureCosmosDB.Infrastructure.Extensions;
using CleanArchitectureCosmosDB.Infrastructure.Identity.Models;
using CleanArchitectureCosmosDB.Infrastructure.Identity.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CleanArchitectureCosmosDB.WebAPI.Config
{
/// <summary>
/// Database related configurations
/// </summary>
public static class DatabaseConfig
{
/// <summary>
/// Setup Cosmos DB
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
public static void SetupCosmosDb(this IServiceCollection services, IConfiguration configuration)
{
// Bind database-related bindings
CosmosDbSettings cosmosDbConfig = configuration.GetSection("ConnectionStrings:CleanArchitectureCosmosDB").Get<CosmosDbSettings>();
// register CosmosDB client and data repositories
services.AddCosmosDb(cosmosDbConfig.EndpointUrl,
cosmosDbConfig.PrimaryKey,
cosmosDbConfig.DatabaseName,
cosmosDbConfig.Containers);
services.AddScoped<IToDoItemRepository, ToDoItemRepository>();
services.AddScoped<IAuditRepository, AuditRepository>();
}
/// <summary>
/// Setup ASP.NET Core Identity DB, including connection string, Identity options, token providers, and token services, etc..
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
public static void SetupIdentityDatabase(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<ApplicationDbContext>(options =>
//options.UseSqlServer(configuration.GetConnectionString("CleanArchitectureIdentity"))
options.UseInMemoryDatabase("CleanArchitectureIdentity")
);
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddDefaultTokenProviders()
.AddUserManager<UserManager<ApplicationUser>>()
.AddSignInManager<SignInManager<ApplicationUser>>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.Configure<IdentityOptions>(
options =>
{
options.SignIn.RequireConfirmedEmail = true;
options.User.RequireUniqueEmail = true;
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
// Identity : Default password settings
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
});
// services required using Identity
services.AddScoped<ITokenService, TokenService>();
}
}
}
|
using System;
using System.Linq;
using System.Reflection;
namespace Alsein.Extensions.DependencyInjection.Internal
{
internal sealed class ReflectionConstructorRegistryBuilder : RegistryBuilderBase, IConstructorRegistryBuilder
{
private ConstructorInfo _constructor;
private object[] _providedArgs;
protected override Type ImplementationType => _constructor.DeclaringType;
protected override IRegistry BuildRegistry()
=> new ReflectionConstructorRegistry(_lifetime, _injectProperties, _constructor, _providedArgs);
IConstructorRegistryBuilder IConstructorRegistryBuilder.UseConstructor(ConstructorInfo constructor)
{
_constructor = constructor;
return this;
}
IConstructorRegistryBuilder IConstructorRegistryBuilder.UseProvidedArgs(params object[] providedArgs)
{
_providedArgs = providedArgs;
return this;
}
}
} |
using Hikipuro.Text.Interpreter;
using Hikipuro.Text.Parser.Generator;
using Hikipuro.Text.Parser.Generator.Expressions;
using Hikipuro.Text.Tokenizer;
using System.Diagnostics;
using TokenType = Hikipuro.Text.Parser.EBNF.EBNFParser.TokenType;
namespace Hikipuro.Text.Parser.EBNF.Expressions {
/// <summary>
/// EBNF のパース時に使用する Expression のベースクラス.
/// </summary>
class BaseExpression : Expression<EBNFContext> {
/// <summary>
/// デバッグ用.
/// true で処理中にデバッグメッセージを表示する.
/// </summary>
public bool DebugFlag = true;
/// <summary>
/// 評価用メソッド.
/// </summary>
/// <param name="context">コンテキストオブジェクト.</param>
public virtual void Interpret(EBNFContext context) {
}
/// <summary>
/// デバッグ用.
/// DebugFlag が true の時のみメッセージを表示する.
/// </summary>
/// <param name="text">表示するメッセージ.</param>
public void DebugLog(string text) {
if (DebugFlag == false) {
return;
}
Debug.WriteLine(text);
}
/// <summary>
/// トークンの null チェック.
/// null の場合は例外を発生させる.
/// </summary>
/// <param name="token">トークン.</param>
public void CheckTokenExists(Token<TokenType> token) {
if (token != null) {
return;
}
ThrowParseException(
ErrorMessages.TokenNotFound, token
);
}
/// <summary>
/// トークンの種類のチェック.
/// 引数に指定されたトークンでない場合は例外を発生させる.
/// </summary>
/// <param name="token">トークン.</param>
/// <param name="type">トークンの種類.</param>
public void CheckTokenType(Token<TokenType> token, TokenType type) {
if (token.Type == type) {
return;
}
ThrowParseException(
ErrorMessages.UnexpectedToken, token
);
}
/// <summary>
/// トークンの種類のチェック.
/// 引数に指定されたトークンでない場合は例外を発生させる.
/// </summary>
/// <param name="token">トークン.</param>
/// <param name="typeList">トークンの種類.</param>
public void CheckTokenType(Token<TokenType> token, TokenType[] typeList) {
if (typeList == null || typeList.Length <= 0) {
return;
}
bool isMatch = false;
foreach (TokenType type in typeList) {
if (token.Type == type) {
isMatch = true;
break;
}
}
if (isMatch == false) {
ThrowParseException(
ErrorMessages.UnexpectedToken, token
);
}
}
/// <summary>
/// コンマが正常な位置にあるかチェックする.
/// </summary>
/// <param name="token"></param>
public void CheckComma(Token<TokenType> token) {
if (token.Next.Type == TokenType.Comma) {
ThrowParseException(ErrorMessages.UnexpectedToken, token);
}
if (token.Prev.Type == TokenType.Comma) {
ThrowParseException(ErrorMessages.UnexpectedToken, token);
}
}
/// <summary>
/// StringExpression の処理を実行する.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public GeneratedExpression ParseTerminal(EBNFContext context) {
StringExpression exp = new StringExpression();
exp.Interpret(context);
return context.PopExpression();
}
/// <summary>
/// 非終端文字の処理を実行する.
/// </summary>
/// <param name="context"></param>
/// <param name="name"></param>
public GeneratedExpression ParseNonterminal(EBNFContext context, string name) {
return ExpressionFactory.CreateNonterminal(name);
}
public GeneratedExpression ParseField(EBNFContext context) {
FieldExpression exp = new FieldExpression();
exp.Interpret(context);
return context.PopExpression();
}
public GeneratedExpression ParseRight(EBNFContext context) {
RightExpression exp = new RightExpression();
exp.Interpret(context);
return context.PopExpression();
}
/// <summary>
/// OrExpression の処理を実行する.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public GeneratedExpression ParseOr(EBNFContext context) {
OrExpression exp = new OrExpression();
exp.Interpret(context);
return context.PopExpression();
}
/// <summary>
/// GroupExpression の処理を実行する.
/// </summary>
/// <param name="context"></param>
public GeneratedExpression ParseGroup(EBNFContext context) {
GroupExpression exp = new GroupExpression();
exp.Interpret(context);
return context.PopExpression();
}
/// <summary>
/// LoopExpression の処理を実行する.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public GeneratedExpression ParseLoop(EBNFContext context) {
LoopExpression exp = new LoopExpression();
exp.Interpret(context);
return context.PopExpression();
}
/// <summary>
/// OptionExpression の処理を実行する.
/// </summary>
/// <param name="context"></param>
public GeneratedExpression ParseOption(EBNFContext context) {
OptionExpression exp = new OptionExpression();
exp.Interpret(context);
return context.PopExpression();
}
/// <summary>
/// ExceptionExpression の処理を実行する.
/// </summary>
/// <param name="context"></param>
public GeneratedExpression ParseException(EBNFContext context) {
ExceptionExpression exp = new ExceptionExpression();
exp.Interpret(context);
return context.PopExpression();
}
/// <summary>
/// パースエラーを発生させる.
/// </summary>
/// <param name="message">メッセージ.</param>
/// <param name="token">エラー発生箇所のトークン.</param>
public void ThrowParseException(string message, Token<TokenType> token) {
if (token == null) {
throw new InterpreterException(string.Format(
"{0}",
message
));
}
throw new InterpreterException(string.Format(
"{0} (Line: {1}, Index: {2}) {3}",
message,
token.LineNumber,
token.LineIndex,
token.Text
));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Plugin.Geolocator;
using Plugin.Connectivity;
using Xamarin.Forms;
using Android;
using Android.Locations;
using Android.Content;
using Android.Net;
namespace GPSAppClient
{
public partial class StartPage : ContentPage
{
bool gpscheck, netcheck, switchstate;
Xamarin.Forms.IButtonController t;
public StartPage()
{
InitializeComponent();
t = btnSwitch as IButtonController;
switchstate = false;
lblGPSCheck.IsVisible = false;
btnSwitch.Text = "Kiểm tra lại";
btnSwitch.IsVisible = true;
btnSwitch.Clicked += BtnSwitch_Clicked;
OverallCheck();
}
private void BtnSwitch_Clicked(object sender, EventArgs e)
{
switch (switchstate)
{
case true:
App.MyNavigationPage.PushAsync(new LoginPage(), true);
break;
case false:
OverallCheck();
break;
}
}
public static bool CheckNetwork()
{
return CrossConnectivity.Current.IsConnected;
}
private async void Check()
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 20;
await RetrieveLocation();
}
private async Task RetrieveLocation()
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 20;
try
{
var position = await locator.GetPositionAsync(TimeSpan.FromMilliseconds(10000));
gpscheck = true;
}
catch
{
gpscheck = false;
t.SendClicked();
}
}
private void OverallCheck()
{
netcheck = CheckNetwork();
//Check();
/*switch (gpscheck)
{
case true:
lblGPSCheck.Text = "Đã kết nối GPS";
break;
case false:
lblGPSCheck.Text = "Vui lòng kết nối GPS để sử dụng ứng dụng";
break;
}*/
switch (netcheck)
{
case true:
lblNetworkCheck.Text = "Đã kết nối mạng";
break;
case false:
lblNetworkCheck.Text = "Vui lòng kết nối mạng để sử dụng ứng dụng";
break;
}
if ((netcheck == true))
{
switchstate = true;
btnSwitch.IsVisible = true;
btnSwitch.Text = "Bấm vào đây để tiếp tục";
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AssetsSobre : MonoBehaviour
{
[SerializeField]
private GameObject autoresText = null;
[SerializeField]
private GameObject assetsLegendaText = null;
[SerializeField]
private GameObject assets1Text = null;
[SerializeField]
private GameObject assets2Text = null;
[SerializeField]
private GameObject assets3Text = null;
[SerializeField]
private GameObject assets4Text = null;
[SerializeField]
private GameObject assets5Text = null;
[SerializeField]
private GameObject assets6Text = null;
[SerializeField]
private GameObject assets7Text = null;
[SerializeField]
private GameObject assets8Text = null;
[SerializeField]
private GameObject assets9Text = null;
[SerializeField]
private GameObject assets10Text = null;
[SerializeField]
private GameObject assets11Text = null;
[SerializeField]
private GameObject assets12Text = null;
[SerializeField]
private GameObject assets13Text = null;
[SerializeField]
private GameObject assets14Text = null;
[SerializeField]
private GameObject assets15Text = null;
[SerializeField]
private GameObject assets16Text = null;
[SerializeField]
private GameObject assets17Text = null;
[SerializeField]
private GameObject assets18Text = null;
[SerializeField]
private GameObject assets19Text = null;
[SerializeField]
private GameObject assets20Text = null;
[SerializeField]
private GameObject assets21Text = null;
[SerializeField]
private GameObject assets22Text = null;
[SerializeField]
private GameObject btnAnterior = null;
[SerializeField]
private GameObject btnProximo = null;
public void Proximo()
{
if(autoresText.activeSelf==true)
{
autoresText.SetActive(false);
assetsLegendaText.SetActive(true);
assets1Text.SetActive(true);
btnAnterior.SetActive(true);
return;
}
if(assets1Text.activeSelf==true)
{
assets1Text.SetActive(false);
assets2Text.SetActive(true);
return;
}
if(assets2Text.activeSelf==true)
{
assets2Text.SetActive(false);
assets3Text.SetActive(true);
return;
}
if(assets3Text.activeSelf==true)
{
assets3Text.SetActive(false);
assets4Text.SetActive(true);
return;
}
if(assets4Text.activeSelf==true)
{
assets4Text.SetActive(false);
assets5Text.SetActive(true);
return;
}
if(assets5Text.activeSelf==true)
{
assets5Text.SetActive(false);
assets6Text.SetActive(true);
return;
}
if(assets6Text.activeSelf==true)
{
assets6Text.SetActive(false);
assets7Text.SetActive(true);
return;
}
if(assets7Text.activeSelf==true)
{
assets7Text.SetActive(false);
assets8Text.SetActive(true);
return;
}
if(assets8Text.activeSelf==true)
{
assets8Text.SetActive(false);
assets9Text.SetActive(true);
return;
}
if(assets9Text.activeSelf==true)
{
assets9Text.SetActive(false);
assets10Text.SetActive(true);
return;
}
if(assets10Text.activeSelf==true)
{
assets10Text.SetActive(false);
assets11Text.SetActive(true);
return;
}
if(assets11Text.activeSelf==true)
{
assets11Text.SetActive(false);
assets12Text.SetActive(true);
return;
}
if(assets12Text.activeSelf==true)
{
assets12Text.SetActive(false);
assets13Text.SetActive(true);
return;
}
if(assets13Text.activeSelf==true)
{
assets13Text.SetActive(false);
assets14Text.SetActive(true);
return;
}
if(assets14Text.activeSelf==true)
{
assets14Text.SetActive(false);
assets15Text.SetActive(true);
return;
}
if(assets15Text.activeSelf==true)
{
assets15Text.SetActive(false);
assets16Text.SetActive(true);
return;
}
if(assets16Text.activeSelf==true)
{
assets16Text.SetActive(false);
assets17Text.SetActive(true);
return;
}
if(assets17Text.activeSelf==true)
{
assets17Text.SetActive(false);
assets18Text.SetActive(true);
return;
}
if(assets18Text.activeSelf==true)
{
assets18Text.SetActive(false);
assets19Text.SetActive(true);
return;
}
if(assets19Text.activeSelf==true)
{
assets19Text.SetActive(false);
assets20Text.SetActive(true);
return;
}
if(assets20Text.activeSelf==true)
{
assets20Text.SetActive(false);
assets21Text.SetActive(true);
return;
}
if(assets21Text.activeSelf==true)
{
assets21Text.SetActive(false);
assets22Text.SetActive(true);
btnProximo.SetActive(false);
return;
}
}
public void Anterior()
{
if(assets1Text.activeSelf==true)
{
assetsLegendaText.SetActive(false);
assets1Text.SetActive(false);
btnAnterior.SetActive(false);
autoresText.SetActive(true);
btnProximo.SetActive(true);
return;
}
if(assets2Text.activeSelf==true)
{
assets2Text.SetActive(false);
assets1Text.SetActive(true);
return;
}
if(assets3Text.activeSelf==true)
{
assets3Text.SetActive(false);
assets2Text.SetActive(true);
return;
}
if(assets4Text.activeSelf==true)
{
assets4Text.SetActive(false);
assets3Text.SetActive(true);
return;
}
if(assets5Text.activeSelf==true)
{
assets5Text.SetActive(false);
assets4Text.SetActive(true);
return;
}
if(assets6Text.activeSelf==true)
{
assets6Text.SetActive(false);
assets5Text.SetActive(true);
return;
}
if(assets7Text.activeSelf==true)
{
assets7Text.SetActive(false);
assets6Text.SetActive(true);
return;
}
if(assets8Text.activeSelf==true)
{
assets8Text.SetActive(false);
assets7Text.SetActive(true);
return;
}
if(assets9Text.activeSelf==true)
{
assets9Text.SetActive(false);
assets8Text.SetActive(true);
return;
}
if(assets10Text.activeSelf==true)
{
assets10Text.SetActive(false);
assets9Text.SetActive(true);
return;
}
if(assets11Text.activeSelf==true)
{
assets11Text.SetActive(false);
assets10Text.SetActive(true);
return;
}
if(assets12Text.activeSelf==true)
{
assets12Text.SetActive(false);
assets11Text.SetActive(true);
return;
}
if(assets13Text.activeSelf==true)
{
assets13Text.SetActive(false);
assets12Text.SetActive(true);
return;
}
if(assets14Text.activeSelf==true)
{
assets14Text.SetActive(false);
assets13Text.SetActive(true);
return;
}
if(assets15Text.activeSelf==true)
{
assets15Text.SetActive(false);
assets14Text.SetActive(true);
return;
}
if(assets16Text.activeSelf==true)
{
assets16Text.SetActive(false);
assets15Text.SetActive(true);
return;
}
if(assets17Text.activeSelf==true)
{
assets17Text.SetActive(false);
assets16Text.SetActive(true);
return;
}
if(assets18Text.activeSelf==true)
{
assets18Text.SetActive(false);
assets17Text.SetActive(true);
return;
}
if(assets19Text.activeSelf==true)
{
assets19Text.SetActive(false);
assets18Text.SetActive(true);
return;
}
if(assets20Text.activeSelf==true)
{
assets20Text.SetActive(false);
assets19Text.SetActive(true);
return;
}
if(assets21Text.activeSelf==true)
{
assets21Text.SetActive(false);
assets20Text.SetActive(true);
return;
}
if(assets22Text.activeSelf==true)
{
assets22Text.SetActive(false);
assets21Text.SetActive(true);
return;
}
}
}
|
#region Header
// Vorspire _,-'/-'/ TypeSelect.cs
// . __,-; ,'( '/
// \. `-.__`-._`:_,-._ _ , . ``
// `:-._,------' ` _,`--` -: `_ , ` ,' :
// `---..__,,--' (C) 2018 ` -'. -'
// # Vita-Nex [http://core.vita-nex.com] #
// {o)xxx|===============- # -===============|xxx(o}
// # The MIT License (MIT) #
#endregion
#region References
using System;
using Server;
using Server.Mobiles;
#endregion
namespace VitaNex
{
public interface ITypeSelectProperty
{
Type ExpectedType { get; }
Type InternalType { get; }
bool IsNotNull { get; }
[CommandProperty(AccessLevel.GameMaster)]
string TypeName { get; set; }
bool CheckType(Type t);
object CreateInstanceObject(params object[] args);
}
public interface ITypeSelectProperty<TObj> : ITypeSelectProperty
where TObj : class
{
TObj CreateInstance(params object[] args);
T CreateInstance<T>(params object[] args)
where T : TObj;
}
public class TypeSelectProperty<TObj> : PropertyObject, ITypeSelectProperty<TObj>
where TObj : class
{
private readonly Type _ExpectedType = typeof(TObj);
public Type ExpectedType { get { return _ExpectedType; } }
public Type InternalType { get; protected set; }
public bool IsNotNull { get { return InternalType != null; } }
[CommandProperty(AccessLevel.GameMaster)]
public virtual string TypeName
{
get { return IsNotNull ? InternalType.Name : String.Empty; }
set
{
if (String.IsNullOrWhiteSpace(value))
{
InternalType = null;
return;
}
VitaNexCore.TryCatch(
() =>
{
var t = Type.GetType(value, false, true) ??
ScriptCompiler.FindTypeByName(value, true) ?? ScriptCompiler.FindTypeByFullName(value, true);
if (CheckType(t))
{
InternalType = t;
}
},
VitaNexCore.ToConsole);
}
}
public TypeSelectProperty(string type = "")
{
TypeName = type;
}
public TypeSelectProperty(GenericReader reader)
: base(reader)
{ }
public override void Clear()
{
TypeName = null;
}
public override void Reset()
{
TypeName = null;
}
public virtual bool CheckType(Type t)
{
return CheckType(t, true);
}
public virtual bool CheckType(Type t, bool children)
{
return t != null &&
(!children || ExpectedType.IsSealed ? t.IsEqual(ExpectedType) : t.IsEqualOrChildOf(ExpectedType));
}
public virtual object CreateInstanceObject(params object[] args)
{
return CreateInstance(args);
}
public virtual TObj CreateInstance(params object[] args)
{
return CreateInstance<TObj>(args);
}
public virtual T CreateInstance<T>(params object[] args)
where T : TObj
{
return IsNotNull ? InternalType.CreateInstanceSafe<T>(args) : default(T);
}
public override string ToString()
{
return String.IsNullOrEmpty(TypeName) ? "null" : TypeName;
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
var version = writer.SetVersion(0);
switch (version)
{
case 0:
writer.WriteType(InternalType);
break;
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
var version = reader.GetVersion();
switch (version)
{
case 0:
InternalType = reader.ReadType();
break;
}
}
public static implicit operator TypeSelectProperty<TObj>(string typeName)
{
return new TypeSelectProperty<TObj>(typeName);
}
public static implicit operator string(TypeSelectProperty<TObj> t)
{
return ((t == null || t.InternalType == null) ? String.Empty : t.InternalType.FullName);
}
public static implicit operator TypeSelectProperty<TObj>(Type t)
{
return new TypeSelectProperty<TObj>((t == null) ? null : t.FullName);
}
public static implicit operator Type(TypeSelectProperty<TObj> t)
{
return ((t == null) ? null : t.InternalType);
}
}
public class EntityTypeSelectProperty : TypeSelectProperty<IEntity>
{
public EntityTypeSelectProperty(string type = "")
: base(type)
{ }
public EntityTypeSelectProperty(GenericReader reader)
: base(reader)
{ }
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
var version = writer.SetVersion(0);
switch (version)
{
case 0:
break;
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
var version = reader.GetVersion();
switch (version)
{
case 0:
break;
}
}
public static implicit operator EntityTypeSelectProperty(string typeName)
{
return new EntityTypeSelectProperty(typeName);
}
public static implicit operator string(EntityTypeSelectProperty t)
{
return ((t == null || t.InternalType == null) ? String.Empty : t.InternalType.FullName);
}
public static implicit operator EntityTypeSelectProperty(Type t)
{
return new EntityTypeSelectProperty((t == null) ? null : t.FullName);
}
public static implicit operator Type(EntityTypeSelectProperty t)
{
return ((t == null) ? null : t.InternalType);
}
}
public class ItemTypeSelectProperty : TypeSelectProperty<Item>
{
public ItemTypeSelectProperty(string type = "")
: base(type)
{ }
public ItemTypeSelectProperty(GenericReader reader)
: base(reader)
{ }
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
var version = writer.SetVersion(0);
switch (version)
{
case 0:
break;
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
var version = reader.GetVersion();
switch (version)
{
case 0:
break;
}
}
public static implicit operator ItemTypeSelectProperty(string typeName)
{
return new ItemTypeSelectProperty(typeName);
}
public static implicit operator string(ItemTypeSelectProperty t)
{
return ((t == null || t.InternalType == null) ? String.Empty : t.InternalType.FullName);
}
public static implicit operator ItemTypeSelectProperty(Type t)
{
return new ItemTypeSelectProperty((t == null) ? null : t.FullName);
}
public static implicit operator Type(ItemTypeSelectProperty t)
{
return ((t == null) ? null : t.InternalType);
}
}
public class MobileTypeSelectProperty : TypeSelectProperty<Mobile>
{
public MobileTypeSelectProperty(string type = "")
: base(type)
{ }
public MobileTypeSelectProperty(GenericReader reader)
: base(reader)
{ }
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
var version = writer.SetVersion(0);
switch (version)
{
case 0:
break;
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
var version = reader.GetVersion();
switch (version)
{
case 0:
break;
}
}
public static implicit operator MobileTypeSelectProperty(string typeName)
{
return new MobileTypeSelectProperty(typeName);
}
public static implicit operator string(MobileTypeSelectProperty t)
{
return ((t == null || t.InternalType == null) ? String.Empty : t.InternalType.FullName);
}
public static implicit operator MobileTypeSelectProperty(Type t)
{
return new MobileTypeSelectProperty((t == null) ? null : t.FullName);
}
public static implicit operator Type(MobileTypeSelectProperty t)
{
return ((t == null) ? null : t.InternalType);
}
}
public class CreatureTypeSelectProperty : TypeSelectProperty<BaseCreature>
{
public CreatureTypeSelectProperty(string type = "")
: base(type)
{ }
public CreatureTypeSelectProperty(GenericReader reader)
: base(reader)
{ }
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
var version = writer.SetVersion(0);
switch (version)
{
case 0:
break;
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
var version = reader.GetVersion();
switch (version)
{
case 0:
break;
}
}
public static implicit operator CreatureTypeSelectProperty(string typeName)
{
return new CreatureTypeSelectProperty(typeName);
}
public static implicit operator string(CreatureTypeSelectProperty t)
{
return ((t == null || t.InternalType == null) ? String.Empty : t.InternalType.FullName);
}
public static implicit operator CreatureTypeSelectProperty(Type t)
{
return new CreatureTypeSelectProperty((t == null) ? null : t.FullName);
}
public static implicit operator Type(CreatureTypeSelectProperty t)
{
return ((t == null) ? null : t.InternalType);
}
}
public class VendorTypeSelectProperty : TypeSelectProperty<BaseVendor>
{
public VendorTypeSelectProperty(string type = "")
: base(type)
{ }
public VendorTypeSelectProperty(GenericReader reader)
: base(reader)
{ }
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
var version = writer.SetVersion(0);
switch (version)
{
case 0:
break;
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
var version = reader.GetVersion();
switch (version)
{
case 0:
break;
}
}
public static implicit operator VendorTypeSelectProperty(string typeName)
{
return new VendorTypeSelectProperty(typeName);
}
public static implicit operator string(VendorTypeSelectProperty t)
{
return ((t == null || t.InternalType == null) ? String.Empty : t.InternalType.FullName);
}
public static implicit operator VendorTypeSelectProperty(Type t)
{
return new VendorTypeSelectProperty((t == null) ? null : t.FullName);
}
public static implicit operator Type(VendorTypeSelectProperty t)
{
return ((t == null) ? null : t.InternalType);
}
}
public class SpellTypeSelectProperty : TypeSelectProperty<ISpell>
{
public SpellTypeSelectProperty(string type = "")
: base(type)
{ }
public SpellTypeSelectProperty(GenericReader reader)
: base(reader)
{ }
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
var version = writer.SetVersion(0);
switch (version)
{
case 0:
break;
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
var version = reader.GetVersion();
switch (version)
{
case 0:
break;
}
}
public static implicit operator SpellTypeSelectProperty(string typeName)
{
return new SpellTypeSelectProperty(typeName);
}
public static implicit operator string(SpellTypeSelectProperty t)
{
return ((t == null || t.InternalType == null) ? String.Empty : t.InternalType.FullName);
}
public static implicit operator SpellTypeSelectProperty(Type t)
{
return new SpellTypeSelectProperty((t == null) ? null : t.FullName);
}
public static implicit operator Type(SpellTypeSelectProperty t)
{
return ((t == null) ? null : t.InternalType);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Gruppenarbeit_HSP_neu
{
/// <summary>
/// Interaktionslogik für GUI.xaml
/// </summary>
public partial class GUI : UserControl
{
public GUI()
{
InitializeComponent();
tbc_außen.Visibility = Visibility.Hidden;
tbc_innen.Visibility = Visibility.Hidden;
}
//wenn TreeviewItem "außenverzahnte Stirnräder..Zahnrad einzeln" ausgewählt ist
private void tvi_außen1_Selected(object sender, RoutedEventArgs e)
{
tbc_innen.Visibility = Visibility.Hidden;
tbc_außen.Visibility = Visibility.Visible;
grd_EingabeAußenEinzel.Visibility = Visibility.Visible;
grd_EingabeAußenGegenrad1.Visibility = Visibility.Hidden;
grd_EingabeAußenGegenrad2.Visibility = Visibility.Hidden;
grd_AusgabeAußenEinzel.Visibility = Visibility.Visible;
grd_AusgabeAußenGegenrad1.Visibility = Visibility.Hidden;
grd_AusgabeAußenGegenrad2.Visibility = Visibility.Hidden;
}
// wenn TreeviewItem "innenverzahnte Stirnräder.. Zahnrad einzeln" ausgewählt ist
private void tvi_innen1_Selected(object sender, RoutedEventArgs e)
{
tbc_außen.Visibility = Visibility.Hidden;
tbc_innen.Visibility = Visibility.Visible;
grd_EingabeInnenEinzel.Visibility = Visibility.Visible;
grd_EingabeInnenGegenrad1.Visibility = Visibility.Hidden;
grd_EingabeInnenGegenrad2.Visibility = Visibility.Hidden;
grd_AusgabeInnenEinzel.Visibility = Visibility.Visible;
grd_AusgabeInnenGegenrad1.Visibility = Visibility.Hidden;
grd_AusgabeInnenGegenrad2.Visibility = Visibility.Hidden;
}
//wenn TvI "außenverzahnte Stirnräder... mit Gegenrad" ausgewählt ist
private void tvi_außen2_Selected(object sender, RoutedEventArgs e)
{
tbc_innen.Visibility = Visibility.Hidden;
tbc_außen.Visibility = Visibility.Visible;
grd_EingabeAußenGegenrad1.Visibility = Visibility.Visible;
grd_EingabeAußenGegenrad2.Visibility = Visibility.Visible;
grd_EingabeAußenEinzel.Visibility = Visibility.Hidden;
grd_AusgabeAußenEinzel.Visibility = Visibility.Hidden;
grd_AusgabeAußenGegenrad1.Visibility = Visibility.Visible;
grd_AusgabeAußenGegenrad2.Visibility = Visibility.Visible;
}
//wenn TvI "innenverzahnte Stirnräder... mit Gegenrad" ausgewählt ist
private void tvi_innen2_Selected(object sender, RoutedEventArgs e)
{
tbc_außen.Visibility = Visibility.Hidden;
tbc_innen.Visibility = Visibility.Visible;
grd_EingabeInnenEinzel.Visibility = Visibility.Hidden;
grd_EingabeInnenGegenrad1.Visibility = Visibility.Visible;
grd_EingabeInnenGegenrad2.Visibility = Visibility.Visible;
grd_AusgabeInnenEinzel.Visibility = Visibility.Hidden;
grd_AusgabeInnenGegenrad1.Visibility = Visibility.Visible;
grd_AusgabeInnenGegenrad2.Visibility = Visibility.Visible;
}
//Button Exit
private void btn_Exit_Click(object sender, RoutedEventArgs e) => Application.Current.Shutdown();
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace Async_Inn.Migrations
{
public partial class firsthotl : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "Rooms",
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "RoomName",
table: "HotelRooms",
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "State",
table: "Hotel",
maxLength: 2,
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "HotelName",
table: "Hotel",
maxLength: 25,
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "City",
table: "Hotel",
maxLength: 25,
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "Address",
table: "Hotel",
maxLength: 30,
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "Amenities",
maxLength: 25,
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.InsertData(
table: "Hotel",
columns: new[] { "ID", "Address", "City", "HotelName", "State", "Zip" },
values: new object[] { 1, "2901 3rd Ave #300", "Seattle", "Async Inn", "WA", 98121 });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Hotel",
keyColumn: "ID",
keyValue: 1);
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "Rooms",
nullable: true,
oldClrType: typeof(string));
migrationBuilder.AlterColumn<string>(
name: "RoomName",
table: "HotelRooms",
nullable: true,
oldClrType: typeof(string));
migrationBuilder.AlterColumn<string>(
name: "State",
table: "Hotel",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 2);
migrationBuilder.AlterColumn<string>(
name: "HotelName",
table: "Hotel",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 25);
migrationBuilder.AlterColumn<string>(
name: "City",
table: "Hotel",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 25);
migrationBuilder.AlterColumn<string>(
name: "Address",
table: "Hotel",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 30);
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "Amenities",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 25);
}
}
}
|
using System;
using Server.Core.Common.Messages;
namespace Server.Core.Lists.Workflow.RemoveListItem
{
/// <summary>
/// Ответ на удаляемый список.
/// </summary>
public class RemoveListItemResponse: MessageOutputBase
{
/// <summary>
/// Код удаленного списка.
/// </summary>
public Guid ListItemId { get; set; }
}
}
|
namespace Transit.Core.Events
{
public class EventRoutePreRegistrationEventArgs : EventRouteRegistrationEventArgs
{
private EventRoutePreRegistrationEventArgs() : base(null)
{
}
public EventRoutePreRegistrationEventArgs(EventRoute eventRoute) : base(eventRoute)
{
}
#region public
public bool Cancel { get; set; }
#endregion
}
}
|
namespace Bbt.Campaign.Public.Dtos.CampaignRule
{
public class CampaignRuleUpdateFormDto : CampaignRuleInsertFormDto
{
public bool IsInvisibleCampaign { get; set; }
public CampaignRuleDto CampaignRule { get; set; }
}
}
|
using System;
using System.Linq;
namespace _06.Batteries
{
public class Batteries
{
public static void Main()
{
double[] capacity = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
double[] usagePerHour = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
int hours = int.Parse(Console.ReadLine());
double[] allUsageEnergy = new double[capacity.Length];
double[] batteryLasted = new double[capacity.Length];
double[] batteryDead = new double[capacity.Length];
double[] percent = new double[capacity.Length];
for (int i = 0; i < capacity.Length; i++)
{
allUsageEnergy[i] = usagePerHour[i] * hours;
batteryLasted[i] = Math.Abs(allUsageEnergy[i] - capacity[i]);
batteryDead[i] = capacity[i] / usagePerHour[i];
percent[i] = (batteryLasted[i] / capacity[i]) * 100;
}
for (int i = 0; i < capacity.Length; i++)
{
if (allUsageEnergy[i] < capacity[i])
{
Console.WriteLine($"Battery {i + 1}: {batteryLasted[i]:F2} mAh ({percent[i]:F2})%");
}
else
{
Console.WriteLine($"Battery {i + 1}: dead (lasted {Math.Ceiling(batteryDead[i])} hours)");
}
}
}
}
} |
namespace Xamarin.Cognitive.Face.Model
{
/// <summary>
/// Noise level. The level include `Low`, `Medium` and `High`.
/// </summary>
public enum NoiseLevel
{
/// <summary>
/// Low.
/// </summary>
Low,
/// <summary>
/// Medium.
/// </summary>
Medium,
/// <summary>
/// High.
/// </summary>
High
}
} |
using System;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using LibGit2Sharp;
namespace ReactiveGit
{
public partial class ObservableRepository
{
/// <inheritdoc />
public IObservable<Unit> Push(IObserver<Tuple<string, int>> observer)
{
var branch = _repository.Head;
var isCancelled = false;
var options = new PushOptions
{
CredentialsProvider = _credentialsHandler,
OnPushTransferProgress = (current, total, bytes) =>
{
var progress = 0;
if (total != 0)
{
progress = 50 + (50 * current) / total;
}
observer.OnNext(Tuple.Create("", progress));
return !isCancelled;
}
};
return Observable.Create<Unit>(subj =>
{
var sub = Observable.Start(() =>
{
_repository.Network.Push(branch, options);
observer.OnNext(Tuple.Create("push completed", 100));
observer.OnCompleted();
}, Scheduler.Default).Subscribe(subj);
return new CompositeDisposable(
sub,
Disposable.Create(() =>
{
isCancelled = true;
observer.OnCompleted();
}));
});
}
}
}
|
using Frank.Libraries.Logging.Shared;
namespace Frank.Libraries.Logging.EntityFramework
{
public class EntityFrameworkLoggerConfiguration : LoggerConfigurationBase
{
}
} |
namespace SemanticReleaseNotesParser.BuildServers
{
internal interface IBuildServer
{
bool CanApplyToCurrentContext();
void SetEnvironmentVariable(string variable, string value);
}
}
|
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using LanguageExt;
using MediatR;
using static LanguageExt.Prelude;
namespace ErsatzTV.Application.Streaming.Queries
{
public abstract class FFmpegProcessHandler<T> : IRequestHandler<T, Either<BaseError, Process>>
where T : FFmpegProcessRequest
{
private readonly IChannelRepository _channelRepository;
private readonly IConfigElementRepository _configElementRepository;
protected FFmpegProcessHandler(
IChannelRepository channelRepository,
IConfigElementRepository configElementRepository)
{
_channelRepository = channelRepository;
_configElementRepository = configElementRepository;
}
public Task<Either<BaseError, Process>> Handle(T request, CancellationToken cancellationToken) =>
Validate(request)
.Map(v => v.ToEither<Tuple<Channel, string>>())
.BindT(tuple => GetProcess(request, tuple.Item1, tuple.Item2));
protected abstract Task<Either<BaseError, Process>> GetProcess(T request, Channel channel, string ffmpegPath);
private async Task<Validation<BaseError, Tuple<Channel, string>>> Validate(T request) =>
(await ChannelMustExist(request), await FFmpegPathMustExist())
.Apply((channel, ffmpegPath) => Tuple(channel, ffmpegPath));
private async Task<Validation<BaseError, Channel>> ChannelMustExist(T request) =>
(await _channelRepository.GetByNumber(request.ChannelNumber))
.ToValidation<BaseError>($"Channel number {request.ChannelNumber} does not exist.");
private Task<Validation<BaseError, string>> FFmpegPathMustExist() =>
_configElementRepository.GetValue<string>(ConfigElementKey.FFmpegPath)
.FilterT(File.Exists)
.Map(maybePath => maybePath.ToValidation<BaseError>("FFmpeg path does not exist on filesystem"));
}
}
|
using System;
namespace DapperDemo
{
class Program
{
static void Main(string[] args)
{
using var db = new DemoDb();
db.Open();
db.AllData().ForEach(Console.WriteLine);
Console.WriteLine("\r\nFiltered:");
db.DataLike("an").ForEach(Console.WriteLine);
}
}
} |
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using HelperExpressions;
using HelperExpressionsTest;
using System;
namespace BenchmarkHelpers
{
class Program
{
public static void Main(string[] args)
{
BenchmarkRunner.Run<SimpleTest>();
}
}
public class SimpleTest
{
private ClassInfos _infos;
private ClassForTest _x, _y, _xA, _xB, _xC, _xD;
private Func<ClassForTest, object> _deleA, _deleB, _deleC, _deleD;
private Func<ClassForTest, int> _deleAG;
private Func<ClassForTest, string> _deleBG;
private Func<ClassForTest, float> _deleCG;
private Func<ClassForTest, DateTime> _deleDG;
//[Params( new ClassForTest[] { _x, _y, _xA, _xB, _xC, _xD })]
ClassForTest X {get; set;}
[Setup]
public void SetupData()
{
_infos = new ClassInfos();
_x = new ClassForTest { A = 101, B = "qwertyuiop", C = 3.1415926f, D = DateTime.Today };
_xA = new ClassForTest { A = 10, B = "qwertyuiop", C = 3.1415926f, D = DateTime.Today };
_xB = new ClassForTest { A = 101, B = "qwerty", C = 3.1415926f, D = DateTime.Today };
_xC = new ClassForTest { A = 101, B = "qwertyuiop", C = 2.1415926f, D = DateTime.Today };
_xD = new ClassForTest { A = 101, B = "qwertyuiop", C = 3.1415926f, D = DateTime.Now };
_y = new ClassForTest { A = 101, B = "qwertyuiop", C = 3.1415926f, D = DateTime.Today };
_deleA = _infos.GetPropertyFunc<ClassForTest>("A");
_deleB = _infos.GetPropertyFunc<ClassForTest>("B");
_deleC = _infos.GetPropertyFunc<ClassForTest>("C");
_deleD = _infos.GetPropertyFunc<ClassForTest>("D");
_deleAG = (Func<ClassForTest, int>)_infos.GetPropertyDelegate<ClassForTest>("A");
_deleBG = (Func<ClassForTest, string>)_infos.GetPropertyDelegate<ClassForTest>("B");
_deleCG = (Func<ClassForTest, float>)_infos.GetPropertyDelegate<ClassForTest>("C");
_deleDG = (Func<ClassForTest, DateTime>)_infos.GetPropertyDelegate<ClassForTest>("D");
}
[Benchmark]
public void TestDelegateGet()
{
_infos = new ClassInfos();
_deleAG = (Func<ClassForTest, int>)_infos.GetPropertyDelegate<ClassForTest>("A");
_deleBG = (Func<ClassForTest, string>)_infos.GetPropertyDelegate<ClassForTest>("B");
_deleCG = (Func<ClassForTest, float>)_infos.GetPropertyDelegate<ClassForTest>("C");
_deleDG = (Func<ClassForTest, DateTime>)_infos.GetPropertyDelegate<ClassForTest>("D");
var reA = _deleAG(_x);
var reB = _deleBG(_x);
var reC = _deleCG(_x);
var reD = _deleDG(_x);
reA = _deleAG(_xA);
reB = _deleBG(_xA);
reC = _deleCG(_xA);
reD = _deleDG(_xA);
reA = _deleAG(_xB);
reB = _deleBG(_xB);
reC = _deleCG(_xB);
reD = _deleDG(_xB);
reA = _deleAG(_xC);
reB = _deleBG(_xC);
reC = _deleCG(_xC);
reD = _deleDG(_xC);
reA = _deleAG(_xD);
reB = _deleBG(_xD);
reC = _deleCG(_xD);
reD = _deleDG(_xD);
reA = _deleAG(_y);
reB = _deleBG(_y);
reC = _deleCG(_y);
reD = _deleDG(_y);
}
[Benchmark]
public void Test1()
{
_infos = new ClassInfos();
var reA = _deleA(_x);
var reB = _deleB(_x);
var reC = _deleC(_x);
var reD = _deleD(_x);
reA =_deleA(_xA);
reB =_deleB(_xA);
reC =_deleC(_xA);
reD =_deleD(_xA);
reA =_deleA(_xB);
reB =_deleB(_xB);
reC =_deleC(_xB);
reD =_deleD(_xB);
reA =_deleA(_xC);
reB =_deleB(_xC);
reC =_deleC(_xC);
reD =_deleD(_xC);
reA =_deleA(_xD);
reB =_deleB(_xD);
reC =_deleC(_xD);
reD =_deleD(_xD);
reA =_deleA(_y);
reB =_deleB(_y);
reC =_deleC(_y);
reD =_deleD(_y);
}
[Benchmark(Baseline = true)]
public void TestDirect()
{
var reA = _x.A;
var reB = _x.B;
var reC = _x.C;
var reD = _x.D;
reA = _xA.A;
reB = _xA.B;
reC = _xA.C;
reD = _xA.D;
reA = _xB.A;
reB = _xB.B;
reC = _xB.C;
reD = _xB.D;
reA = _xC.A;
reB = _xC.B;
reC = _xC.C;
reD = _xC.D;
reB = _xD.B;
reA = _xD.A;
reC = _xD.C;
reD = _xD.D;
reA = _y.A;
reB = _y.B;
reC = _y.C;
reD = _y.D;
}
// [Benchmark]
public void TestBoxUnbox()
{
int re = 101;
object re1 = re;
int re2 = (int)re1;
string reB = "qwertyuiop";
object reB1 = reB;
string reB2 =(string)reB1;
}
}
} |
//
// Copyright Seth Hendrick 2020.
// Distributed under the MIT License.
// (See accompanying file LICENSE in the root of the repository).
//
using Cake.LicenseHeaderUpdater.Tests.TestCore;
using NUnit.Framework;
namespace Cake.LicenseHeaderUpdater.Tests.IntegrationTests
{
[TestFixture]
public class HeaderRemovalTests
{
// ---------------- Fields ----------------
private BaseTestFramework testFrame;
// ---------------- Setup / Teardown ----------------
[SetUp]
public void TestSetup()
{
this.testFrame = new BaseTestFramework();
this.testFrame.DoTestSetup();
}
[TearDown]
public void TestTeardown()
{
this.testFrame?.DoTestTeardown();
}
// ---------------- Tests ----------------
/// <summary>
/// Not sure why one would *want* to remove a header,
/// but we'll support it.
/// </summary>
[Test]
public void RemoveHeaderTest()
{
const string originalFile =
@"//
// Copyright Seth Hendrick 2020.
// Distributed under the MIT License.
// (See accompanying file LICENSE in the root of the repository).
//
using System;
using System.Collections.Generic;
using System.Text;
namespace Cake.LicenseHeaderUpdater.Tests.IntegrationTests
{
class Class1
{
}
}
";
const string expectedFile =
@"using System;
using System.Collections.Generic;
using System.Text;
namespace Cake.LicenseHeaderUpdater.Tests.IntegrationTests
{
class Class1
{
}
}
";
const string regex =
@"//
// Copyright Seth Hendrick 2020\.
// Distributed under the MIT License\.
// \(See accompanying file LICENSE in the root of the repository\)\.
//
";
CakeLicenseHeaderUpdaterSettings settings = new CakeLicenseHeaderUpdaterSettings
{
LicenseString = null
};
settings.OldHeaderRegexPatterns.Add( regex );
ModifyHeaderResult result = this.testFrame.DoModifyHeaderTest( originalFile, expectedFile, settings );
// No to adding a header, yes to replacing a header with nothing.
result.WasSuccess( false, true );
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
namespace NMF.Expressions
{
public interface INotifyEnumerable : IEnumerable, INotifyCollectionChanged, INotifiable { }
public interface INotifyEnumerable<out T> : IEnumerable<T>, INotifyEnumerable { }
public interface IOrderableNotifyEnumerable<T> : INotifyEnumerable<T>
{
IEnumerable<IEnumerable<T>> Sequences { get; }
IEnumerable<T> GetSequenceForItem(T item);
}
public interface INotifyCollection<T> : INotifyEnumerable<T>, ICollection<T> { }
public interface INotifyGrouping<out TKey, out TItem> : INotifyEnumerable<TItem>, IGrouping<TKey, TItem> { }
public interface INotifySplit<T>
{
INotifyValue<T> Head { get; }
INotifyValue<bool> Empty { get; }
INotifyEnumerable<T> Tail { get; }
}
}
|
using SpearPay.Naming;
using System;
namespace SpearPay.AllinPay.Models
{
public abstract class BaseModel : IModel
{
protected BaseModel()
{
RandomStr = Guid.NewGuid().ToString("N");
}
/// <summary> 随机字符串 </summary>
[Naming("randomstr")]
public string RandomStr { get; set; }
}
}
|
namespace ReduxSimple.Uwp.RouterStore
{
/// <summary>
/// Interface of a state used to store router navigation details.
/// </summary>
public interface IBaseRouterState
{
/// <summary>
/// Router state.
/// </summary>
RouterState Router { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EDO.Core.Model
{
public class ElseIf :ICloneable
{
public ElseIf()
{
IfCondition = new IfCondition();
}
public IfCondition IfCondition { get; set; }
public string ThenConstructId { get; set; }
public string ElseConstructId { get; set; }
public object Clone()
{
return MemberwiseClone();
}
}
}
|
#region File Description
//-----------------------------------------------------------------------------
// CollectCollection.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections;
#endregion
namespace VectorRumble
{
/// <summary>
/// A collection with an additional feature to isolate the "collection"
/// of the objects.
/// </summary>
sealed class CollectCollection<T>
: System.Collections.ObjectModel.Collection<T>
{
#region Fields and Properties
private World world;
public World World
{
get { return world; }
}
private System.Collections.ObjectModel.Collection<T> garbage;
public System.Collections.ObjectModel.Collection<T> Garbage
{
get { return garbage; }
set { garbage = value; }
}
#endregion
#region Initialization
/// <summary>
/// Constructs a new collection.
/// </summary>
/// <param name="world">The world this particle system resides in.</param>
public CollectCollection(World world)
{
this.world = world;
this.garbage =
new System.Collections.ObjectModel.Collection<T>();
}
#endregion
#region Collection
/// <summary>
/// Remove all of the "garbage" ParticleSystem objects from this collection.
/// </summary>
public void Collect()
{
for (int i = 0; i < garbage.Count; i++)
{
Remove(garbage[i]);
}
garbage.Clear();
}
#endregion
}
}
|
@{
ViewBag.Title = "Contact";
}
<ol class="breadcrumb">
<li><a href="#">Mitra</a></li>
<li class="active">Contato</li>
</ol> |
namespace Platform.Network.ExtensibleServer
{
/// <summary>
/// Summary description for AnyRunLevel.
/// </summary>
public class AnyRunLevel
: RunLevel
{
public const string RunLevelName = "ANY";
public static readonly AnyRunLevel Default = new AnyRunLevel();
public AnyRunLevel()
: base(RunLevelName)
{
}
}
}
|
using Mantle.Data.Entity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Mantle.Tasks.Domain
{
public class ScheduledTaskMap : IEntityTypeConfiguration<ScheduledTask>, IMantleEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder<ScheduledTask> builder)
{
builder.ToTable("Mantle_ScheduledTasks");
builder.HasKey(s => s.Id);
builder.Property(s => s.Name).IsRequired().HasMaxLength(255).IsUnicode(true);
builder.Property(s => s.Type).IsRequired().HasMaxLength(255).IsUnicode(false);
builder.Property(s => s.Seconds).IsRequired();
builder.Property(s => s.Enabled).IsRequired();
builder.Property(s => s.StopOnError).IsRequired();
}
public bool IsEnabled => true;
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using Zephyr.Core;
namespace Zephyr.Models
{
[Module("Sys")]
public class sys_menuService : ServiceBase<sys_menu>
{
}
public class sys_menu : ModelBase
{
[PrimaryKey]
public string MenuCode { get; set; }
public string ParentCode { get; set; }
public string MenuName { get; set; }
public string URL { get; set; }
public string IconClass { get; set; }
public string IconURL { get; set; }
public string MenuSeq { get; set; }
public string Description { get; set; }
public bool? IsVisible { get; set; }
public bool? IsEnable { get; set; }
public string CreatePerson { get; set; }
public DateTime? CreateDate { get; set; }
public string UpdatePerson { get; set; }
public DateTime? UpdateDate { get; set; }
}
}
|
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace HorseMoon
{
public class ScreenFade : SingletonMonoBehaviour<ScreenFade>
{
//private Canvas canvas;
private RawImage blackImage;
private Coroutine doFadeCoroutine;
public System.Action fadedOut;
public System.Action fadedIn;
private new void Awake()
{
base.Awake();
//canvas = GetComponentInChildren<Canvas>();
blackImage = GetComponentInChildren<RawImage>();
}
public Coroutine FadeOut() {
return Fade(1f, Color.clear, Color.black, fadedOut);
}
public Coroutine FadeOut(float duration) {
return Fade(duration, Color.clear, Color.black, fadedOut);
}
public Coroutine FadeOut(float duration, Color fromColor, Color toColor) {
return Fade(duration, fromColor, toColor, fadedOut);
}
public Coroutine FadeIn() {
return Fade(1f, Color.black, Color.clear, fadedIn);
}
public Coroutine FadeIn(float duration) {
return Fade(duration, Color.black, Color.clear, fadedIn);
}
public Coroutine FadeIn(float duration, Color fromColor, Color toColor) {
return Fade(duration, fromColor, toColor, fadedIn);
}
private Coroutine Fade(float duration, Color fromColor, Color toColor, System.Action eventDele)
{
if (doFadeCoroutine != null)
StopCoroutine(doFadeCoroutine);
doFadeCoroutine = StartCoroutine(DoFade(duration, fromColor, toColor, eventDele));
return doFadeCoroutine;
}
private IEnumerator DoFade(float duration, Color fromColor, Color toColor, System.Action eventDele)
{
float t = 0f;
while (t < 1f)
{
t += Time.unscaledDeltaTime / duration;
blackImage.color = Color.Lerp(fromColor, toColor, t);
yield return null;
}
eventDele?.Invoke();
doFadeCoroutine = null;
}
}
} |
namespace Core
{
public class TextIdStrategy : IdentityStrategy
{
private string id;
public string GetId()
{
return this.id;
}
public void SetId(string newId)
{
this.id = newId;
}
}
}
|
// 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.
#nullable enable
using System.Text.Json;
namespace Microsoft.AspNetCore.Components.Web
{
internal static class WheelEventArgsReader
{
private static readonly JsonEncodedText DeltaX = JsonEncodedText.Encode("deltaX");
private static readonly JsonEncodedText DeltaY = JsonEncodedText.Encode("deltaY");
private static readonly JsonEncodedText DeltaZ = JsonEncodedText.Encode("deltaZ");
private static readonly JsonEncodedText DeltaMode = JsonEncodedText.Encode("deltaMode");
internal static WheelEventArgs Read(JsonElement jsonElement)
{
var eventArgs = new WheelEventArgs();
foreach (var property in jsonElement.EnumerateObject())
{
if (property.NameEquals(DeltaX.EncodedUtf8Bytes))
{
eventArgs.DeltaX = property.Value.GetDouble();
}
else if (property.NameEquals(DeltaY.EncodedUtf8Bytes))
{
eventArgs.DeltaY = property.Value.GetDouble();
}
else if (property.NameEquals(DeltaZ.EncodedUtf8Bytes))
{
eventArgs.DeltaZ = property.Value.GetDouble();
}
else if (property.NameEquals(DeltaMode.EncodedUtf8Bytes))
{
eventArgs.DeltaMode = property.Value.GetInt64();
}
else
{
MouseEventArgsReader.ReadProperty(eventArgs, property);
}
}
return eventArgs;
}
}
}
|
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
namespace Microsoft.Samples.HyperV.FibreChannel
{
using System;
using System.Collections.Generic;
using System.Management;
using System.Globalization;
using Microsoft.Samples.HyperV.Common;
static class EnumerateFcPorts
{
private static readonly string StatusNotHyperVCapable = "Not Hyper-V Capable";
private static readonly string StatusAvailable = "Available";
/// <summary>
/// Encapsulates the information for an external FC port.
/// </summary>
private class FcPortInfo
{
internal WorldWideName PortWwn;
internal string HostResource;
internal string Status;
};
/// <summary>
/// Encapsulates the information for a Virtual SAN.
/// </summary>
private struct SanInfo
{
internal string SanName;
internal string[] HostResources;
}
/// <summary>
/// Builds a list of SanInfo instances for each Virtual SAN configured in the system.
/// It uses the Resource Allocation Setting Data for the virtual SAN to determine the
/// host resources assigned to the Virtual SAN.
/// </summary>
/// <returns></returns>
private static List<SanInfo>
BuildSanInfo()
{
ManagementObjectCollection fcPools =
WmiUtilities.GetResourcePools(FibreChannelUtilities.FcConnectionResourceType,
FibreChannelUtilities.FcConnectionResourceSubType,
FibreChannelUtilities.GetFcScope());
List<SanInfo> sanInfoList = new List<SanInfo>();
foreach (ManagementObject san in fcPools)
{
//
// Virtual SANs are resource pools that are children of the primordial pool.
//
if (!(bool)san["Primordial"])
{
SanInfo sanInfo = new SanInfo();
sanInfo.SanName = (string) san["PoolId"];
//
// The resources assigned to the Virtual SAN are present in the HostResource
// property of the associated Resource Allocation Setting Data.
//
using (ManagementObjectCollection poolRasds =
san.GetRelated("Msvm_FcPortAllocationSettingData"))
using (ManagementObject allocationSettingData =
WmiUtilities.GetFirstObjectFromCollection(poolRasds))
{
sanInfo.HostResources = (string[])allocationSettingData["HostResource"];
}
sanInfoList.Add(sanInfo);
}
}
if (sanInfoList.Count == 0)
{
Console.WriteLine("No Virtual SANs detected in the system.");
}
return sanInfoList;
}
/// <summary>
/// Check whether the port is Hyper-V Capable and return the appropriate status.
/// The boolean IsHyperVCapable property of the Msvm_ExternalFcPort class is used for this.
/// </summary>
/// <param name="port">Instance of Msvm_ExternalFcPort</param>
/// <returns>"Available" or "Not Hyper-V Capable"</returns>
private static string
GetPortStatus(
ManagementObject port)
{
string status = StatusAvailable;
if (!(bool)port["IsHyperVCapable"])
{
status = StatusNotHyperVCapable;
}
return status;
}
/// <summary>
/// Builds a list of FcPortInfo instances for each external FC port.
/// We do not associate the SAN info yet.
/// </summary>
/// <returns>List of FcPortInfo instances for each instance of Msvm_ExternalFcPort.</returns>
private static List<FcPortInfo>
BuildPortInfo()
{
List<FcPortInfo> portInfoList = new List<FcPortInfo>();
ManagementScope scope = FibreChannelUtilities.GetFcScope();
using (ManagementClass portClass = new ManagementClass("Msvm_ExternalFcPort"))
{
portClass.Scope = scope;
using (ManagementObjectCollection fcPorts = portClass.GetInstances())
{
foreach (ManagementObject port in fcPorts)
{
WorldWideName wwn = new WorldWideName();
wwn.NodeName = (string)port["WWNN"];
wwn.PortName = (string)port["WWPN"];
FcPortInfo portInfo = new FcPortInfo();
portInfo.PortWwn = wwn;
//
// Convert the WWN to the path of the corresponding Virtual FC Switch to be used
// as HostResources for the ResourcePool.
//
portInfo.HostResource = FibreChannelUtilities.GetHostResourceFromWwn(wwn);
portInfo.Status = GetPortStatus(port);
portInfoList.Add(portInfo);
}
}
}
if (portInfoList.Count == 0)
{
Console.WriteLine("No FibreChannel Ports found in the system.");
}
return portInfoList;
}
/// <summary>
/// Generates as output a list of WWNN, WWPN and Status for each external FC port.
/// If the port is not HyperVCapable, then status is Not Hyper-V Capable.
/// If the port is assigned to a Virtual SAN, then the status will be the SAN Name.
/// Else the status will be Available.
/// </summary>
private static void
OutputFcPortInfo()
{
List<SanInfo> sanInfoList = BuildSanInfo();
List<FcPortInfo> portInfoList = BuildPortInfo();
//
// Update the port Status by checking if it is assigned to a Virtual SAN.
// The HostResource of the external FC port must be present in the
// HostResources array for the Virtual SAN.
// A port can only be assigned to 1 Virtual SAN.
//
foreach (FcPortInfo portInfo in portInfoList)
{
foreach (SanInfo sanInfo in sanInfoList)
{
if (sanInfo.HostResources == null)
{
continue;
}
foreach (string sanResource in sanInfo.HostResources)
{
if (string.Equals(sanResource, portInfo.HostResource, StringComparison.OrdinalIgnoreCase))
{
portInfo.Status = sanInfo.SanName;
}
}
}
}
if (portInfoList.Count != 0)
{
Console.WriteLine();
Console.WriteLine("WorldWideNodeName\tWorldWidePortName\tStatus");
Console.WriteLine("-----------------\t-----------------\t------");
}
foreach (FcPortInfo portInfo in portInfoList)
{
Console.WriteLine("{0} \t{1} \t{2}",
portInfo.PortWwn.NodeName,
portInfo.PortWwn.PortName,
portInfo.Status);
}
}
/// <summary>
/// Entry point for the CreateSan sample.
/// </summary>
/// <param name="args">The command line arguments.</param>
internal static void
ExecuteSample(
string[] args)
{
if (args.Length > 0)
{
Console.WriteLine("Usage: EnumerateFcPorts");
return;
}
try
{
OutputFcPortInfo();
}
catch (Exception ex)
{
Console.WriteLine("Failed to enumerate FC ports. Error message details:\n");
Console.WriteLine(ex.Message);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InnovatorAdmin
{
public class QueryParameter
{
public enum DataType
{
String,
Boolean,
DateTime,
Decimal,
Integer,
Null
}
public string Name { get; set; }
public string TextValue { get; set; }
public DataType Type { get; set; }
public object GetValue()
{
switch (this.Type)
{
case DataType.Boolean:
if (this.TextValue == "1" || (this.TextValue ?? "").Equals("true", StringComparison.OrdinalIgnoreCase))
return true;
if (this.TextValue == "0" || (this.TextValue ?? "").Equals("false", StringComparison.OrdinalIgnoreCase))
return false;
throw new FormatException(string.Format("`{0}` is not a valid boolean value", TextValue));
case DataType.DateTime:
return DateTime.Parse(TextValue);
case DataType.Decimal:
return decimal.Parse(TextValue);
case DataType.Integer:
return long.Parse(TextValue);
case DataType.Null:
if (string.IsNullOrEmpty(this.TextValue))
return null;
throw new FormatException("The value must be empty if the type is Null");
default:
return TextValue ?? string.Empty;
}
}
public void Overwrite(QueryParameter value)
{
this.Name = value.Name;
this.TextValue = value.TextValue;
this.Type = value.Type;
}
public QueryParameter Clone()
{
return new QueryParameter()
{
Name = this.Name,
TextValue = this.TextValue,
Type = this.Type
};
}
}
}
|
using System;
using Moq;
using TestEasy.Core.Abstractions;
namespace TestEasy.TestHelpers
{
public class MockGenerator
{
public static string Randomize(string val)
{
var r1 = new Random((int) DateTime.Now.Ticks/2);
var r2 = new Random(r1.Next());
val = val + "_" + r1.Next() + "_" + r2.Next();
return val;
}
public Mock<IFileSystem> FileSystem { get; private set; }
public Mock<IEnvironmentSystem> EnvironmentSystem { get; private set; }
public Mock<IProcessRunner> ProcessRunner { get; private set; }
public MockGenerator()
{
FileSystem = new Mock<IFileSystem>(MockBehavior.Strict);
EnvironmentSystem = new Mock<IEnvironmentSystem>(MockBehavior.Strict);
ProcessRunner = new Mock<IProcessRunner>(MockBehavior.Strict);
}
}
}
|
using Creekdream.SimpleDemo.Books.Dto;
using System.Threading.Tasks;
using Creekdream.Application.Service;
using Creekdream.Application.Service.Dto;
using System;
namespace Creekdream.SimpleDemo.Books
{
/// <summary>
/// 书信息服务
/// </summary>
public interface IBookService : IApplicationService
{
/// <summary>
/// 获取书信息
/// </summary>
Task<GetBookOutput> Get(Guid id);
/// <summary>
/// 获取书信息
/// </summary>
Task<PagedResultOutput<GetBookOutput>> GetPaged(GetPagedBookInput input);
/// <summary>
/// 新增书信息
/// </summary>
Task<GetBookOutput> Create(CreateBookInput input);
/// <summary>
/// 修改书信息
/// </summary>
Task<GetBookOutput> Update(Guid id, UpdateBookInput input);
/// <summary>
/// 删除书信息
/// </summary>
Task Delete(Guid id);
}
}
|
using System.Collections.Generic;
namespace Norml.Common.Data
{
public interface IModelDataConverter
{
IDatatableObjectMapping ConvertToDataTable<TModel>(IEnumerable<TModel> models);
}
}
|
using System;
namespace ArchiveUnpacker.Core.Exceptions
{
// Should prob make this better
public class InvalidMagicException : Exception { }
}
|
using System;
using System.Collections.Generic;
using Ninject;
using Ninject.Syntax;
using TehPers.Core.Api.DI;
namespace TehPers.Core.DI
{
internal class SimpleFactory<TService> : ISimpleFactory<TService>
{
private readonly IResolutionRoot serviceResolver;
public SimpleFactory(IResolutionRoot resolutionRoot)
{
this.serviceResolver = resolutionRoot ?? throw new ArgumentNullException(nameof(resolutionRoot));
}
public TService GetSingle()
{
return this.serviceResolver.Get<TService>();
}
public IEnumerable<TService> GetAll()
{
return this.serviceResolver.GetAll<TService>();
}
}
}
|
using ChiaRPC.Models;
using ChiaRPC.Parsers;
using System;
using System.Text.Json.Serialization;
namespace ChiaRPC.Results
{
internal sealed class GetRecentEosResult : ChiaResult
{
[JsonPropertyName("eos")]
public EndOfSubSlotBundle EndOfSubSlotBundle { get; init; }
[JsonPropertyName("time_received")]
[JsonConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset ReceivedAt { get; init; }
[JsonPropertyName("peak_height")]
public uint CurrentPeakHeight { get; init; }
[JsonPropertyName("reverted")]
public bool Reverted { get; init; }
public GetRecentEosResult()
{
}
}
}
|
using SteamKit2;
using System.Collections.Generic;
namespace SteamChatBot.Triggers.TriggerOptions
{
public class AntiSpamTriggerOptions
{
public string Name { get; set; }
public NoCommand NoCommand { get; set; }
public List<SteamID> admins { get; set; }
public Dictionary<SteamID, Dictionary<SteamID, int>> groups { get; set; }
public Score score { get; set; }
public Timers timers { get; set; }
public PTimer ptimer { get; set; }
public string warnMessage { get; set; }
public int msgPenalty { get; set; }
//public Dictionary<string, int> badWords { get; set; } // TODO: Add badwords
}
public class Score
{
public int warn { get; set; }
public int warnMax { get; set; }
public int kick { get; set; }
public int ban { get; set; }
public int tattle { get; set; }
public int tattleMax { get; set; }
}
public class Timers
{
public int messages { get; set; }
public int unban { get; set; }
}
public class PTimer
{
public int resolution { get; set; }
public int amount { get; set; }
}
}
|
namespace FactoryPattern
{
public class SlicedPepperoni : Pepperoni
{
}
}
|
// Taken from the Windows API Code Pack for Microsoft (r) .NET Framework
// Originally Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
namespace Taskbar
{
#region Enums
internal enum KnownDestinationCategory
{
Frequent = 1,
Recent
}
internal enum ShellAddToRecentDocs
{
Pidl = 0x1,
PathA = 0x2,
PathW = 0x3,
AppIdInfo = 0x4, // indicates the data type is a pointer to a SHARDAPPIDINFO structure
AppIdInfoIdList = 0x5, // indicates the data type is a pointer to a SHARDAPPIDINFOIDLIST structure
Link = 0x6, // indicates the data type is a pointer to an IShellLink instance
AppIdInfoLink = 0x7, // indicates the data type is a pointer to a SHARDAPPIDINFOLINK structure
}
internal enum TaskbarProgressBarStatus
{
NoProgress = 0,
Indeterminate = 0x1,
Normal = 0x2,
Error = 0x4,
Paused = 0x8
}
internal enum TaskbarActiveTabSetting
{
UseMdiThumbnail = 0x1,
UseMdiLivePreview = 0x2
}
internal enum ThumbButtonMask
{
Bitmap = 0x1,
Icon = 0x2,
Tooltip = 0x4,
THB_FLAGS = 0x8
}
[Flags]
internal enum ThumbButtonOptions
{
Enabled = 0x00000000,
Disabled = 0x00000001,
DismissOnClick = 0x00000002,
NoBackground = 0x00000004,
Hidden = 0x00000008,
NonInteractive = 0x00000010
}
internal enum SetTabPropertiesOption
{
None = 0x0,
UseAppThumbnailAlways = 0x1,
UseAppThumbnailWhenActive = 0x2,
UseAppPeekAlways = 0x4,
UseAppPeekWhenActive = 0x8
}
#endregion
#region Structs
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct ThumbButton
{
/// <summary>
/// WPARAM value for a THUMBBUTTON being clicked.
/// </summary>
internal const int Clicked = 0x1800;
[MarshalAs(UnmanagedType.U4)]
internal ThumbButtonMask Mask;
internal uint Id;
internal uint Bitmap;
internal IntPtr Icon;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
internal string Tip;
[MarshalAs(UnmanagedType.U4)]
internal ThumbButtonOptions Flags;
}
#endregion;
internal static class TaskbarNativeMethods
{
internal static class TaskbarGuids
{
internal static Guid IObjectArray = new Guid("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9");
internal static Guid IUnknown = new Guid("00000000-0000-0000-C000-000000000046");
}
internal const int WmCommand = 0x0111;
// Register Window Message used by Shell to notify that the corresponding taskbar button has been added to the taskbar.
internal static readonly uint WmTaskbarButtonCreated = RegisterWindowMessage("TaskbarButtonCreated");
internal const uint WmDwmSendIconThumbnail = 0x0323;
internal const uint WmDwmSendIconicLivePreviewBitmap = 0x0326;
#region Methods
[DllImport("shell32.dll")]
internal static extern void SetCurrentProcessExplicitAppUserModelID(
[MarshalAs(UnmanagedType.LPWStr)] string AppID);
[DllImport("shell32.dll")]
internal static extern void GetCurrentProcessExplicitAppUserModelID(
[Out(), MarshalAs(UnmanagedType.LPWStr)] out string AppID);
[DllImport("shell32.dll")]
internal static extern void SHAddToRecentDocs(
ShellAddToRecentDocs flags,
[MarshalAs(UnmanagedType.LPWStr)] string path);
internal static void SHAddToRecentDocs(string path)
{
SHAddToRecentDocs(ShellAddToRecentDocs.PathW, path);
}
[DllImport("user32.dll", EntryPoint = "RegisterWindowMessage", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint RegisterWindowMessage([MarshalAs(UnmanagedType.LPWStr)] string lpString);
#endregion
}
/// <summary>
/// Thumbnail Alpha Types
/// </summary>
public enum ThumbnailAlphaType
{
/// <summary>
/// Let the system decide.
/// </summary>
Unknown = 0,
/// <summary>
/// No transparency
/// </summary>
NoAlphaChannel = 1,
/// <summary>
/// Has transparency
/// </summary>
HasAlphaChannel = 2,
}
}
|
using System.Collections.Generic;
using System.Text;
namespace tvn.cosine.expressions
{
public class InfixExpression<T> : List<ExpressionObject>, ICalculate<T>
{
public Operand<T> Calculate()
{
var sya = new ShuntingYard<T>();
var pf = sya.ToPostFix(this);
return pf.Calculate();
}
public override string ToString()
{
var sb = new StringBuilder();
foreach (var i in this)
{
sb.AppendFormat(" {0}", i.ToString());
}
return sb.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CozyKxlol.Engine.Tiled.Json;
namespace CozyKxlol.Engine.Tiled
{
public class CozyTileJsonManager
{
private Dictionary<string, CozyTileJsonResult> TilesDictionary = new Dictionary<string, CozyTileJsonResult>();
public CozyTiledJsonParser Parser { get; set; }
public CozyTileJsonManager()
{
Parser = new CozyTiledJsonParser();
}
public CozyTileJsonResult ParseWithFile(string filename)
{
if(!TilesDictionary.ContainsKey(filename))
{
TilesDictionary[filename] = Parser.ParseWithFile(filename) as CozyTileJsonResult;
}
return TilesDictionary[filename];
}
public CozyTileJsonResult Parse(string json)
{
return Parser.Parse(json) as CozyTileJsonResult;
}
}
}
|
using System;
using System.Collections.Generic;
namespace Cartogram
{
public class Map : IEquatable<Map>
{
public int Id { get; set; }
public int SqlId { get; set; }
public string Rarity { get; set; }
public int Level { get; set; }
public string Name { get; set; }
public int Quality { get; set; }
public int Quantity { get; set; }
public int ItemRarity { get; set; }
public int PackSize { get; set; }
public List<string> Affixes { get; set; }
public DateTime StartAt { get; set; }
public DateTime FinishAt { get; set; }
public Experience ExpBefore { get; set; }
public Experience ExpAfter { get; set; }
public string Notes { get; set; }
public string League { get; set; }
public string Character { get; set; }
public bool OwnMap { get; set; }
public bool Unidentified { get; set; }
public string ZanaMod { get; set; }
public bool Equals(Map other)
{
return other.Id == Id;
}
}
public class Maps
{
public static string[] MapArray()
{
return new[]
{
"Academy", "Crypt","Dried Lake","Dunes","Dungeon","Grotto","Overgrown Ruin", "Tropical Island",
"Arcade","Arsenal","Cemetery","Mountain Ledge","Sewer","Thicket", "Wharf","Ghetto", "Museum",
"Mud Geyser","Reef","Spider Lair","Springs","Vaal Pyramid", "Catacomb", "Overgrown Shrine",
"Promenade","Shore","Spider Forest","Tunnel","Bog", "Coves", "Graveyard", "Pier",
"Underground Sea","Arachnid Nest","Colonnade", "Dry Woods", "Strand", "Temple",
"Jungle Valley", "Torture Chamber", "Waste Pool", "Mine", "Dry Peninsula", "Canyon",
"Cells", "Dark Forest", "Gorge", "Conservatory", "Underground River", "Bazaar", "Necropolis",
"Plateau", "Crematorium", "Precinct", "Shipyard", "Shrine", "Villa", "Palace", "Pit",
"Desert", "Aqueduct", "Quarry", "Arena", "Abyss", "Village Ruin", "Wasteland", "Excavation",
"Waterways", "Core", "Volcano", "Colosseum", "Orchard", "Malformation", "Terrace", "Residence"
};
}
}
}
|
using System.Drawing;
using ChartJS.NET.Infrastructure;
namespace ChartJS.NET.Charts.Doughnut
{
public class DoughnutChartOptions
{
/// <summary>
/// Whether or not to show a stroke on each segment
/// </summary>
public bool? SegmentShowStroke { get; set; }
/// <summary>
/// Color of each segment stroke; this should be a hex color code i.e. "#fff"
/// </summary>
public Color SegmentStrokeColor { get; set; }
/// <summary>
/// The width of each segment stroke in pixels
/// </summary>
public int? SegmentStrokeWidth { get; set; }
/// <summary>
/// The percentage of the chart that we cut out of the middle; for pie charts this is zero by default
/// </summary>
public int? PercentageInnerCutout { get; set; }
/// <summary>
/// The number of animation steps
/// </summary>
public int? AnimationSteps { get; set; }
/// <summary>
/// The animation easing effect
/// </summary>
public Enums.AnimationEasing AnimationEasing { get; set; }
/// <summary>
/// Whether we animate the rotation of the Pie chart
/// </summary>
public bool? AnimateRotate { get; set; }
/// <summary>
/// Whether we animate scaling the Pie chart from the center
/// </summary>
public bool? AnimateScale { get; set; }
}
} |
using System.Collections;
using System.Diagnostics;
namespace C3DE.Components
{
public class Coroutine
{
/// <summary>
/// A coroutine that waits for n seconds. It depends of the time scale.
/// </summary>
/// <returns>The for seconds.</returns>
/// <param name="time">Time.</param>
public static IEnumerator WaitForSeconds(float time)
{
var watch = Stopwatch.StartNew();
while (watch.Elapsed.TotalSeconds < time)
yield return 0;
}
/// <summary>
/// A coroutine that waits for n seconds. It doesn't depend of the time scale.
/// </summary>
/// <returns>The for real seconds.</returns>
/// <param name="time">Time.</param>
public static IEnumerator WaitForRealSeconds(float time)
{
var watch = Stopwatch.StartNew();
while (watch.Elapsed.TotalSeconds * Time.TimeScale < time)
yield return 0;
}
}
}
|
using System;
using System.Collections.Generic;
namespace PdfReader
{
public abstract class PdfPageInherit : PdfDictionary
{
public PdfPageInherit(PdfObject parent, ParseDictionary dictionary)
: base(parent, dictionary)
{
}
public PdfPageInherit Inherit { get => TypedParent<PdfPageInherit>(); }
public abstract void FindLeafPages(List<PdfPage> pages);
public T InheritableOptionalValue<T>(string name) where T : PdfObject
{
// Try and get the value from this dictionary
T here = OptionalValue<T>(name);
// If not present then inherit it from the parent
if ((here == null) && (Inherit != null))
here = Inherit.InheritableOptionalValue<T>(name);
return here;
}
public T InheritableOptionalRefValue<T>(string name) where T : PdfObject
{
// Try and get the value from this dictionary
T here = OptionalValueRef<T>(name);
// If not present then inherit it from the parent
if ((here == null) && (Inherit != null))
here = Inherit.InheritableOptionalRefValue<T>(name);
return here;
}
public T InheritableMandatoryValue<T>(string name) where T : PdfObject
{
// Try and get the value from this dictionary
T here = OptionalValue<T>(name);
// If not present then inherit it from the parent
if ((here == null) && (Inherit != null))
here = Inherit.InheritableMandatoryValue<T>(name);
// Enforce mandatory existence
if (here == null)
throw new ApplicationException($"Page is missing a mandatory inheritable value for '{name}'.");
return here;
}
public T InheritableMandatoryRefValue<T>(string name) where T : PdfObject
{
// Try and get the value from this dictionary
T here = OptionalValueRef<T>(name);
// If not present then inherit it from the parent
if ((here == null) && (Inherit != null))
here = Inherit.InheritableMandatoryRefValue<T>(name);
// Enforce mandatory existence
if (here == null)
throw new ApplicationException($"Page is missing a mandatory inheritable value for '{name}'.");
return here;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//
// Used to switch something on/off
//
public class Switch : MonoBehaviour
{
[SerializeField] bool isOn;
[SerializeField] Renderer renderer;
[SerializeField] Material onMaterial;
[SerializeField] Material offMaterial;
[SerializeField] GameObject objectToSwitch;
void Awake()
{
SetMaterial();
objectToSwitch.GetComponent<Item>().usable = isOn;
}
void Update()
{
}
public void Use() // Here for now if needed later
{
SetMaterial();
objectToSwitch.SendMessage("UseObject",SendMessageOptions.DontRequireReceiver);
isOn = !isOn;
}
private void SetMaterial()
{
if(isOn)
renderer.material = onMaterial;
else
renderer.material = offMaterial;
}
}
|
using LexLibrary.Google.reCAPTCHA.Models;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Text;
namespace LexLibrary.Google.reCAPTCHA
{
public static class GoogleCaptchaHelper
{
public static HtmlString GooglereCaptchaV2(this IHtmlHelper helper)
{
var setting = helper.ViewContext.HttpContext.RequestServices.GetRequiredService<GoogleCaptchaSetting>();
StringBuilder sb = new StringBuilder();
sb.AppendLine("<!-- LexLibrary.Google.reCAPTCHA.v2 by lex.xu(https://blog.exfast.me) -->");
sb.AppendLine("<script src='https://www.google.com/recaptcha/api.js'></script>");
sb.AppendLine("<div class='g-recaptcha' data-sitekey='{0}'></div>");
sb.AppendLine("<!-- LexLibrary.Google.reCAPTCHA.v2 by lex.xu(https://blog.exfast.me) -->");
sb.Replace("{0}", setting.Sitekey);
return new HtmlString(sb.ToString());
}
public static HtmlString GooglereCaptchaV3(this IHtmlHelper helper, string action)
{
var setting = helper.ViewContext.HttpContext.RequestServices.GetRequiredService<GoogleCaptchaSetting>();
if (string.IsNullOrWhiteSpace(action))
{
throw new ArgumentNullException(nameof(action));
}
StringBuilder sb = new StringBuilder();
sb.AppendLine("<!-- LexLibrary.Google.reCAPTCHA.v3 by lex.xu(https://blog.exfast.me) -->");
sb.AppendLine("<input type='hidden' name='g-recaptcha-response' id='g-recaptcha-response'>");
sb.AppendLine(@"
<script>
if(!window.grecaptcha) {
var scriptGooglereCaptchaV3 = document.createElement('script');
scriptGooglereCaptchaV3.type = 'text/javascript';
scriptGooglereCaptchaV3.src = 'https://www.google.com/recaptcha/api.js?render={0}';
scriptGooglereCaptchaV3.onload = callbackGooglereCaptchaV3;
document.body.appendChild(scriptGooglereCaptchaV3);
}
function callbackGooglereCaptchaV3() {
grecaptcha.ready(function() {
grecaptcha.execute('{0}', {action: '{1}'}).then(function(token) {
document.getElementById('g-recaptcha-response').value = token;
});
});
}
</script>");
sb.AppendLine("<!-- LexLibrary.Google.reCAPTCHA.v3 by lex.xu(https://blog.exfast.me) -->");
sb.Replace("{0}", setting.Sitekey);
sb.Replace("{1}", action);
return new HtmlString(sb.ToString());
}
}
}
|
using System;
using System.Runtime.InteropServices;
using AudioSwitcher.AudioApi.CoreAudio.Interfaces;
namespace AudioSwitcher.AudioApi.CoreAudio.Topology
{
[Guid(ComInterfaceIds.CONTROL_INTERFACE_IID)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IControlInterface
{
[PreserveSig]
int GetName([Out] [MarshalAs(UnmanagedType.LPWStr)] out string name);
[PreserveSig]
int GetInterfaceId([Out] out Guid interfaceId); //Note this was GetIID, hoping the vtable is enough
}
}
|
using System;
namespace Phema.Validation.Examples.WorkerService
{
public class ReceivedMessage
{
public TimeSpan Elapsed { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace NetPad.Compilation
{
public static class SystemAssemblies
{
private static HashSet<string>? _systemAssembliesLocations;
public static HashSet<string> GetAssemblyLocations()
{
return _systemAssembliesLocations ??= GetAssemblyLocationsFromAppContext();
}
private static HashSet<string> GetAssemblyLocationsFromAppDomain()
{
return AppDomain.CurrentDomain.GetAssemblies()
.Where(assembly =>
!assembly.IsDynamic &&
!string.IsNullOrWhiteSpace(assembly.Location) &&
assembly.GetName().Name?.StartsWith("System.") == true)
.Select(assembly => assembly.Location)
.ToHashSet();
}
private static HashSet<string> GetAssemblyLocationsFromAppContext()
{
string? assemblyPaths = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") as string;
if (string.IsNullOrWhiteSpace(assemblyPaths))
throw new Exception("TRUSTED_PLATFORM_ASSEMBLIES is empty. " +
"Make sure you are not running the app as a Single File application.");
var includeList = new[] { "System.", "mscorlib.", "netstandard." };
return assemblyPaths
.Split(Path.PathSeparator)
.Where(path =>
{
var fileName = Path.GetFileName(path);
return includeList.Any(p => fileName.StartsWith(p));
})
.ToHashSet();
}
}
}
|
using AutoMapper;
using Fancy.Data.Models.Models;
using Fancy.Web.Areas.Admin.Models;
namespace Fancy.Web.App_Start.AutomapperProfiles
{
public class ModelViewToData : Profile
{
public ModelViewToData()
{
this.CreateMap<AddItemViewModel, Item>()
.ForMember(x => x.Orders, opt => opt.Ignore())
.ForMember(x => x.Id, opt => opt.Ignore());
}
}
} |
using System;
using System.Security.Cryptography;
using System.Text;
namespace Mffer {
/// <summary>
/// Static methods for general utilization
/// </summary>
public static class Utilities {
/// <summary>
/// Calculates a hashed version of a string
/// </summary>
/// <remarks>
/// Creates a base 64 representation of the given string, creates
/// an MD5 hash of that base 64 representation, and returns the bytestring
/// of that hash; the result is a 32-character capitalized hexadecimal string.
/// This is used in multiple places in Marvel Future Fight, and is included
/// here for testing but is generally not reversible.
/// </remarks>
/// <param name="toHash">String to hash</param>
/// <returns>hashed version of the string</returns>
public static string HashString( string toHash ) {
StringBuilder stringBuilder = new StringBuilder();
string base64string = Convert.ToBase64String( Encoding.UTF8.GetBytes( toHash ) );
using ( MD5 md5hash = MD5.Create() ) {
byte[] hashBytes = md5hash.ComputeHash( Encoding.UTF8.GetBytes( base64string ) );
for ( int i = 0; i < hashBytes.Length; i++ ) {
stringBuilder.Append( hashBytes[i].ToString( "X2" ) );
}
}
return stringBuilder.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AzPerf.Storage.Helpers;
using Microsoft.WindowsAzure.Storage.Blob;
namespace AzPerf.Storage.Blob
{
public class UploadSinglePageFileMultipleThreadsSmart : StoragePerformanceScenarioBase
{
protected string FilePath;
protected int FileSize;
protected int EmptyPercentage;
protected async Task InitializeFileSizeAsync()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("Chose file size in MB: ");
Console.ForegroundColor = ConsoleColor.Magenta;
var input = Console.ReadLine();
int size;
if (!int.TryParse(input, out size))
{
await InitializeFileSizeAsync();
return;
}
if (size < 1)
{
await InitializeFileSizeAsync();
return;
}
FileSize = size;
}
protected async Task InitializeEmptyPercentageAsync()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("Chose file empty percentage: ");
Console.ForegroundColor = ConsoleColor.Magenta;
var input = Console.ReadLine();
int percentage;
if (!int.TryParse(input, out percentage))
{
await InitializeEmptyPercentageAsync();
return;
}
if (percentage < 0 || percentage > 100)
{
await InitializeEmptyPercentageAsync();
return;
}
EmptyPercentage = percentage;
}
protected async Task InitializeFileAsync()
{
FilePath = Path.GetTempFileName();
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine(FilePath);
await FileHelper.CreateFileWithEmptyPagesAsync(FilePath, FileSize, EmptyPercentage);
}
protected override async Task InitializeAsync()
{
await InitializeFileSizeAsync();
await InitializeEmptyPercentageAsync();
await InitializeFileAsync();
}
protected override async Task DoWorkAsync()
{
var fileInfo = new FileInfo(FilePath);
var blob = BlobContainer.GetPageBlobReference(Guid.NewGuid().ToString("N"));
await blob.CreateAsync(fileInfo.Length);
var tasks = new List<Task>();
using (var fileStream = new FileStream(FilePath, FileMode.Open))
{
var buffer = new byte[512];
while (fileStream.Position < fileStream.Length)
{
await fileStream.ReadAsync(buffer, 0, 512);
if (buffer.Any(b => b != 0))
{
tasks.Add(UploadPageAsync(blob, buffer, fileStream.Position));
}
}
await Task.WhenAll(tasks);
}
}
private async Task UploadPageAsync(CloudPageBlob blob, byte[] pageBuffer, long position)
{
var memStream = new MemoryStream(pageBuffer);
await blob.WritePagesAsync(memStream, position, null);
}
protected override async Task CleanupAsync()
{
if (!string.IsNullOrEmpty(FilePath) && File.Exists(FilePath))
{
File.Delete(FilePath);
}
}
}
} |
using Fast.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Fast.Buffers.Tests
{
[TestClass]
public class FastCopyTest
{
[TestMethod]
public void test_fast_copy()
{
const int count = 23;
var expected = Utility.GetTestArray(count);
var actual = new byte[count];
Assert.IsFalse(Utility.CheckTestArray(actual));
FastCopy.CopyBytes(actual, expected);
Assert.IsTrue(Utility.CheckTestArray(actual));
}
}
}
|
using Microsoft.Extensions.FileProviders;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Smidge.Tests")]
namespace Smidge
{
/// <summary>
/// A marker interface for an <see cref="IFileProvider"/> for Smidge
/// </summary>
public interface ISmidgeFileProvider : IFileProvider
{
}
}
|
using BeboerWeb.Api.Domain.Models.Bookings;
using BeboerWeb.Api.Domain.Models.Chat;
using BeboerWeb.Api.Domain.Models.Documents;
using BeboerWeb.Api.Domain.Models.PropertyManangement;
using Microsoft.EntityFrameworkCore;
namespace BeboerWeb.Api.Persistence.Contexts
{
public interface IApiDbContext : IDbContext
{
DbSet<Address> Addresses { get; set; }
DbSet<BookingItem> BookingItems { get; set; }
DbSet<Booking> Bookings { get; set; }
DbSet<BookingWindow> BookingWindows { get; set; }
DbSet<City> Cities { get; set; }
DbSet<Company> Companies { get; set; }
DbSet<Country> Countries { get; set; }
DbSet<Employee> Employees { get; set; }
DbSet<LeasePeriod> LeasePeriods { get; set; }
DbSet<Lease> Leases { get; set; }
DbSet<Property> Properties { get; set; }
DbSet<Tenant> Tenants { get; set; }
DbSet<Document> Documents { get; set; }
DbSet<TenantToTenantMessage> InternalMessages { get; set; }
DbSet<TenantToEmployeeMessage> TenantToEmployeeMessages { get; set; }
DbSet<EmployeeToTenantMessage> EmployeeToTenantMessages { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace Zaabee.Cryptographic.UnitTest
{
public class Md5Test
{
[Fact]
public void Test()
{
Md5Helper.Encoding = Encoding.UTF8;
Assert.Equal(Md5Helper.Encoding, Encoding.UTF8);
}
[Theory]
[InlineData("apple", "1F-38-70-BE-27-4F-6C-49-B3-E3-1A-0C-67-28-95-7F")]
public void ComputeHashStringTest(string str, string result)
{
Assert.Equal(str.ToMd5String(), result);
}
[Theory]
[InlineData("apple", "1F-38-70-BE-27-4F-6C-49-B3-E3-1A-0C-67-28-95-7F")]
public void ComputeHashBytesTest(string str, string result)
{
Assert.True(str.ToMd5Bytes().SequenceEqual(HexToBytes(result)));
}
[Fact]
public void NullTest()
{
string str = null;
byte[] bytes = null;
Assert.Throws<ArgumentNullException>(() => str.ToMd5String());
Assert.Throws<ArgumentNullException>(() => bytes.ToMd5String());
Assert.Throws<ArgumentNullException>(() => str.ToMd5Bytes());
Assert.Throws<ArgumentNullException>(() => bytes.ToMd5Bytes());
}
private static IEnumerable<byte> HexToBytes(string str)
{
var arr = str.Split('-');
var array = new byte[arr.Length];
for (var i = 0; i < arr.Length; i++) array[i] = Convert.ToByte(arr[i], 16);
return array;
}
}
} |
namespace EPI.Graphs.Algorithms
{
public class AdjacencyListGraphNode
{
public int destNode;
public int weight;
public AdjacencyListGraphNode(int node, int w)
{
destNode = node;
weight = w;
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MQTTnet.Formatter;
using MQTTnet.Packets;
using MQTTnet.Protocol;
namespace MQTTnet.Tests.Server
{
[TestClass]
public sealed class KeepAlive_Tests : BaseTestClass
{
[TestMethod]
public async Task Disconnect_Client_DueTo_KeepAlive()
{
using (var testEnvironment = CreateTestEnvironment())
{
await testEnvironment.StartServer();
var client = await testEnvironment.ConnectLowLevelClient(o => o
.WithCommunicationTimeout(TimeSpan.FromSeconds(1))
.WithCommunicationTimeout(TimeSpan.Zero)
.WithProtocolVersion(MqttProtocolVersion.V500)).ConfigureAwait(false);
await client.SendAsync(new MqttConnectPacket
{
CleanSession = true,
ClientId = "Disconnect_Client_DueTo_KeepAlive",
KeepAlivePeriod = 1
}, CancellationToken.None).ConfigureAwait(false);
var responsePacket = await client.ReceiveAsync(CancellationToken.None).ConfigureAwait(false);
Assert.IsTrue(responsePacket is MqttConnAckPacket);
for (var i = 0; i < 6; i++)
{
await Task.Delay(500);
await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
responsePacket = await client.ReceiveAsync(CancellationToken.None);
Assert.IsTrue(responsePacket is MqttPingRespPacket);
}
// If we reach this point everything works as expected (server did not close the connection
// due to proper ping messages.
// Now we will wait 1.1 seconds because the server MUST wait 1.5 seconds in total (See spec).
await Task.Delay(1100);
await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
responsePacket = await client.ReceiveAsync(CancellationToken.None);
Assert.IsTrue(responsePacket is MqttPingRespPacket);
// Now we will wait longer than 1.5 so that the server will close the connection.
responsePacket = await client.ReceiveAsync(CancellationToken.None);
var disconnectPacket = responsePacket as MqttDisconnectPacket;
Assert.IsTrue(disconnectPacket != null);
Assert.AreEqual(disconnectPacket.ReasonCode, MqttDisconnectReasonCode.KeepAliveTimeout);
}
}
}
} |
using bS.Sked.Model.Interfaces.Entities.Base;
namespace bS.Sked.Model.Interfaces.Elements.Properties
{
public interface IAttachableFileModel : IFileObject, IPersisterEntity, IHistoricalEntity
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IoTSharp.Models.DeviceMapping.Prop;
namespace IoTSharp.Models.DeviceMapping
{
public class Node<T>
{
public string id { get; set; }
public T Biz { get; set; } //原始设备数据
public int zIndex { get; set; }
public Point position { get; set; }
public Size size { get; set; }
public string shape { get; set; } //Shape类型,网关为矩形
public Port ports { get; set; } //对应端口数据
public Attr attrs { get; set; } //名称
}
public class Port
{
public Group groups { get; set; } //描述端口绘制属性
public PortInfo items { get; set; }
}
public class PortInfo
{
public string id { get; set; } //端口Id
public string group { get; set; } //输入输出 ,in或者out
}
public class Group
{
public GroupItem @in { get; set; }
public GroupItem @out { get; set; }
}
public class GroupItem
{
public Position position { get; set; }
public Attr attrs { get; set; }
public Label label
{ get; set; }
}
}
|
using System.Numerics;
using static glTFLoader.Schema.MeshPrimitive;
namespace AssetGenerator.Runtime
{
internal enum MeshPrimitiveMode
{
Points = ModeEnum.POINTS,
Lines = ModeEnum.LINES,
LineLoop = ModeEnum.LINE_LOOP,
LineStrip = ModeEnum.LINE_STRIP,
Triangles = ModeEnum.TRIANGLES,
TriangleStrip = ModeEnum.TRIANGLE_STRIP,
TriangleFan = ModeEnum.TRIANGLE_FAN,
}
internal class JointVector
{
public int Index0 { get; }
public int Index1 { get; }
public int Index2 { get; }
public int Index3 { get; }
public JointVector(int index0, int index1 = 0, int index2 = 0, int index3 = 0)
{
Index0 = index0;
Index1 = index1;
Index2 = index2;
Index3 = index3;
}
}
internal class WeightVector
{
public float Value0 { get; }
public float Value1 { get; }
public float Value2 { get; }
public float Value3 { get; }
public WeightVector(float value0, float value1 = 0.0f, float value2 = 0.0f, float value3 = 0.0f)
{
Value0 = value0;
Value1 = value1;
Value2 = value2;
Value3 = value3;
}
}
internal class MeshPrimitive
{
public Material Material { get; set; }
public MeshPrimitiveMode Mode { get; set; } = MeshPrimitiveMode.Triangles;
public Data<int> Indices { get; set; }
public bool? Interleave { get; set; }
public Data<Vector3> Positions { get; set; }
public Data<Vector3> Normals { get; set; }
public Data<Vector4> Tangents { get; set; }
public Data Colors { get; set; }
public Data<Vector2> TexCoords0 { get; set; }
public Data<Vector2> TexCoords1 { get; set; }
public Data<JointVector> Joints { get; set; }
public Data<WeightVector> Weights { get; set; }
}
}
|
using System;
using System.Threading.Tasks;
using CCS.Application.Domains.Entities;
using CCS.Application.Domains.Interfaces;
using CCS.Application.Domains.Requests;
using MediatR;
namespace CCS.Application.Applications
{
public class SampleService : BaseService
{
public SampleService(IMediator mediator, IDbRepository dbRepository)
: base(mediator, dbRepository)
{
}
public async Task<Sample> GetById(Guid id)
{
return await _mediator.Send(new SampleGetRequest { Id = id });
}
public async Task<Sample> Create()
{
var result = await _mediator.Send(new SampleInsertRequest());
_dbRepository.Commit();
return await _mediator.Send(new SampleGetRequest { Id = result.Id });
}
public async Task<Sample[]> Search()
{
return await _mediator.Send(new SampleQueryRequest { });
}
public async Task<Sample> Update(Guid id)
{
await _mediator.Send(new SampleGetRequest { Id = id });
_dbRepository.Commit();
return await _mediator.Send(new SampleGetRequest { Id = id });
}
}
}
|
//
// CSVReaderBuilderTest.cs
//
// Author:
// tsntsumi <tsntsumi@tsntsumi.com>
//
// Copyright (c) 2016 tsntsumi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Text;
using NUnit.Framework;
using SimpleCSV;
namespace SimpleCSVTest
{
public class CSVReaderBuilderTest
{
private CSVReaderBuilder builder;
private TextReader reader;
[SetUp]
public void SetUp()
{
reader = new StringReader("");
builder = new CSVReaderBuilder(reader);
}
[Test]
public void TestDefaultBuilder()
{
Assert.AreSame(reader, builder.Reader);
Assert.Null(builder.CsvParser);
Assert.AreEqual(CSVReader.DefaultSkipLines, builder.SkipLines);
CSVReader csvReader = builder.Build();
Assert.AreEqual(CSVReader.DefaultSkipLines, csvReader.SkipLines);
}
[Test]
public void TestNullReader()
{
Assert.Throws<ArgumentNullException>(() => builder = new CSVReaderBuilder(null));
}
[Test]
public void TestWithCSVParserNull()
{
builder.WithCSVParser(new CSVParser());
builder.WithCSVParser(null);
Assert.Null(builder.CsvParser);
}
[Test]
public void TestWithCSVParser()
{
CSVParser csvParser = new CSVParser();
builder.WithCSVParser(csvParser);
Assert.AreSame(csvParser, builder.CsvParser);
CSVReader actual = builder.Build();
Assert.AreSame(csvParser, actual.Parser);
}
[Test]
public void TestWithSkipLines()
{
builder.WithSkipLines(99);
Assert.AreEqual(99, builder.SkipLines);
CSVReader actual = builder.Build();
Assert.AreEqual(99, actual.SkipLines);
}
[Test]
public void TestWithSkipLinesZero()
{
builder.WithSkipLines(0);
Assert.AreEqual(0, builder.SkipLines);
CSVReader actual = builder.Build();
Assert.AreEqual(0, actual.SkipLines);
}
[Test]
public void TestWithSkipLinesNegative()
{
builder.WithSkipLines(-1);
Assert.AreEqual(0, builder.SkipLines);
CSVReader actual = builder.Build();
Assert.AreEqual(0, actual.SkipLines);
}
[Test]
public void TestWithNullFieldIndicator()
{
CSVReader reader = builder.WithFieldAsNull(CSVReaderNullFieldIndicator.EmptySeparators).Build();
Assert.AreEqual(CSVReaderNullFieldIndicator.EmptySeparators, reader.Parser.NullFieldIndicator);
}
}
}
|
using System;
using System.Collections;
using Microsoft.Maui.Graphics;
using NUnit.Framework;
namespace Microsoft.Maui.Controls.Core.UnitTests
{
[TestFixture(Category = "RadioButton")]
public class RadioButtonTemplateTests : BaseTestFixture
{
class FrameStyleCases : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return new object[] { Frame.VerticalOptionsProperty, LayoutOptions.End };
yield return new object[] { Frame.HorizontalOptionsProperty, LayoutOptions.End };
yield return new object[] { Frame.BackgroundColorProperty, Colors.Red };
yield return new object[] { Frame.BorderColorProperty, Colors.Magenta };
yield return new object[] { Frame.MarginProperty, new Thickness(1, 2, 3, 4) };
yield return new object[] { Frame.OpacityProperty, 0.67 };
yield return new object[] { Frame.RotationProperty, 0.3 };
yield return new object[] { Frame.ScaleProperty, 0.8 };
yield return new object[] { Frame.ScaleXProperty, 0.9 };
yield return new object[] { Frame.ScaleYProperty, 0.95 };
yield return new object[] { Frame.TranslationXProperty, 123 };
yield return new object[] { Frame.TranslationYProperty, 321 };
}
}
[TestCaseSource(typeof(FrameStyleCases))]
[Description("Frame Style properties should not affect RadioButton")]
public void RadioButtonIgnoresFrameStyleProperties(BindableProperty property, object value)
{
var implicitFrameStyle = new Style(typeof(Frame));
implicitFrameStyle.Setters.Add(new Setter() { Property = property, Value = value });
var page = new ContentPage();
page.Resources.Add(implicitFrameStyle);
var radioButton = new RadioButton() { ControlTemplate = RadioButton.DefaultTemplate };
page.Content = radioButton;
var root = (radioButton as IControlTemplated)?.TemplateRoot as Frame;
Assert.IsNotNull(root);
Assert.That(root.GetValue(property), Is.Not.EqualTo(value), $"{property.PropertyName} should be ignored.");
}
class RadioButtonStyleCases : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return new object[] { RadioButton.VerticalOptionsProperty, LayoutOptions.End };
yield return new object[] { RadioButton.HorizontalOptionsProperty, LayoutOptions.End };
yield return new object[] { RadioButton.BackgroundColorProperty, Colors.Red };
yield return new object[] { RadioButton.MarginProperty, new Thickness(1, 2, 3, 4) };
yield return new object[] { RadioButton.OpacityProperty, 0.67 };
yield return new object[] { RadioButton.RotationProperty, 0.3 };
yield return new object[] { RadioButton.ScaleProperty, 0.8 };
yield return new object[] { RadioButton.ScaleXProperty, 0.9 };
yield return new object[] { RadioButton.ScaleYProperty, 0.95 };
yield return new object[] { RadioButton.TranslationXProperty, 123 };
yield return new object[] { RadioButton.TranslationYProperty, 321 };
}
}
[TestCaseSource(typeof(RadioButtonStyleCases))]
[Description("RadioButton Style properties should affect RadioButton")]
public void RadioButtonStyleSetsPropertyOnTemplateRoot(BindableProperty property, object value)
{
var radioButtonStyle = new Style(typeof(RadioButton));
radioButtonStyle.Setters.Add(new Setter() { Property = property, Value = value });
var radioButton = new RadioButton() { ControlTemplate = RadioButton.DefaultTemplate, Style = radioButtonStyle };
var root = (radioButton as IControlTemplated)?.TemplateRoot as Frame;
Assert.IsNotNull(root);
Assert.That(root.GetValue(property), Is.EqualTo(value), $"{property.PropertyName} should match.");
}
}
}
|
using BoomBang.Forms;
using BoomBang.game.dao;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BoomBang.game.instances
{
public class CatalogObjectInstance
{
public int id;
public string titulo;
public string swf_name;
public string descripcion;
public int tipo;
public int price;
public string colores_hex;
public string colores_rgb;
public string espacio_mapabytes;
public int rotacion;
public int visible;
public int active;
public CatalagoPlantaInstance Planta;
public CatalogObjectInstance(DataRow row)
{
this.id = (int)row["id"];
this.titulo = (string)row["titulo"];
this.swf_name = (string)row["swf_name"];
try
{
this.descripcion = (string)row["descripcion"];
}
catch
{
this.descripcion = "";
}
this.tipo = (int)row["tipo"];
this.price = (int)row["price"];
this.colores_hex = (string)row["colores_hex"];
this.colores_rgb = (string)row["colores_rgb"];
this.espacio_mapabytes = (string)row["espacio_mapabytes"];
this.rotacion = (int)row["rotacion"];
this.visible = (int)row["visible"];
this.active = (int)row["active"];
this.Planta = setPlanta();
}
private CatalagoPlantaInstance setPlanta()
{
return CatalagoPlantaDAO.getPlanta(this.id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using MarioObjects.Objects.BaseObjects;
namespace MarioObjects.Objects.Patterns
{
public class VisitorObject
{
public virtual void Action(GraphicObject g) { }
}
}
|
using UnityEngine;
using System;
using System.Collections.Generic;
using Toki.Tween;
public interface IXTween
{
float Duration
{
get;
}
float Position
{
get;
}
bool IsPlaying
{
get;
}
void StopOnDestroy();
IXTween Play();
IXTween Play( float position );
WaitForTweenPlay WaitForPlay();
WaitForTweenPlay WaitForPlay( float position );
IXTween Seek( float position );
void Stop();
void Reset();
IXTween Clone();
IXTween SetFrameSkip(uint skip);
IXTween SetLock();
IXTween SetReverse();
IXTween SetRepeat(int count);
IXTween SetScale(float scale);
IXTween SetDelay(float preDelay, float postDelay = 0f);
IXTween AddOnComplete(Action listener);
IXTween AddOnComplete(IExecutable executor);
IXTween AddOnStop(Action listener);
IXTween AddOnStop(IExecutable executor);
IXTween AddOnPlay(Action listener);
IXTween AddOnPlay(IExecutable executor);
IXTween AddOnUpdate(Action listener);
IXTween AddOnUpdate(IExecutable executor);
void Release();
}
|
namespace Tabula.Writers
{
public class TSVWriter : CSVWriter
{
public TSVWriter() : base("\t")
{ }
}
}
|
namespace Softeq.XToolkit.DefaultAuthorization.Infrastructure
{
public enum ErrorCodes
{
//NotFound
UserNotFound = 1001,
UserRoleNotFound = 1003,
//InputValidation
UserIsInDeletedState = 2001,
RequestModelValidationFailed = 2003,
InvalidEmailConfirmationCodeException = 2005,
InvalidResendEmailCodeException = 2006,
InvalidResetPasswordCodeException = 2007,
EmailAlreadyTaken = 2009,
IdentityError = 2010,
ActivationCodeExpired = 2012,
PendingAllowedRequirementFailed = 2015,
PasswordHasExpired = 2019,
PasswordHashIsNotUnique = 2020,
InactiveUserState = 4001,
EmailIsNotConfirmed = 4002,
UserIsInPendingState = 4003,
//Conflict
UserHadAlreadyAcceptedTermsAndPolicies = 5000,
UserWithDefinedEmailAlreadyExist = 5001,
EmailAlreadyConfirmed = 5002,
UnsupportedRole = 5008,
UserIsAlreadyInDeletedState = 5016,
UserIsNotInActiveState = 5038,
UnsupportedAuthorizationStatus = 5045,
UserIsNotInPendingOrInactiveState = 5050,
UnsupportedTokenPurpose = 5069,
//Unknown errors
UnknownIdentityError = 6000,
UnknownError = 6001
}
}
|
using System;
namespace ARMeilleure.CodeGen.RegisterAllocators
{
unsafe readonly struct LiveRange : IEquatable<LiveRange>
{
private struct Data
{
public int Start;
public int End;
public LiveRange Next;
}
private readonly Data* _data;
public ref int Start => ref _data->Start;
public ref int End => ref _data->End;
public ref LiveRange Next => ref _data->Next;
public LiveRange(int start, int end, LiveRange next = default)
{
_data = Allocators.LiveRanges.Allocate<Data>();
Start = start;
End = end;
Next = next;
}
public bool Overlaps(int start, int end)
{
return Start < end && start < End;
}
public bool Overlaps(LiveRange range)
{
return Start < range.End && range.Start < End;
}
public bool Overlaps(int position)
{
return position >= Start && position < End;
}
public bool Equals(LiveRange range)
{
return range._data == _data;
}
public override bool Equals(object obj)
{
return obj is LiveRange range && Equals(range);
}
public static bool operator ==(LiveRange a, LiveRange b)
{
return a.Equals(b);
}
public static bool operator !=(LiveRange a, LiveRange b)
{
return !a.Equals(b);
}
public override int GetHashCode()
{
return HashCode.Combine((IntPtr)_data);
}
public override string ToString()
{
return $"[{Start}, {End})";
}
}
} |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.Configuration;
namespace soverance.com.Models
{
public partial class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
}
public virtual DbSet<Category> Category { get; set; }
public virtual DbSet<Post> Post { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>(entity =>
{
entity.Property(e => e.CategoryName).IsRequired();
});
modelBuilder.Entity<Post>(entity =>
{
entity.HasOne(d => d.Category)
.WithMany(p => p.Post)
.HasForeignKey(d => d.CategoryId);
});
}
}
}
|
namespace Tarea25
{
partial class FRMCON
{
/// <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.LBLC = new System.Windows.Forms.Label();
this.TXTC = new System.Windows.Forms.TextBox();
this.LBLD = new System.Windows.Forms.Label();
this.TXTD = new System.Windows.Forms.TextBox();
this.TXTC2 = new System.Windows.Forms.TextBox();
this.CMDCON = new System.Windows.Forms.Button();
this.CMDOTRO = new System.Windows.Forms.Button();
this.LBLCON2 = new System.Windows.Forms.Label();
this.LBLF = new System.Windows.Forms.Label();
this.LBLY = new System.Windows.Forms.Label();
this.LBLCM = new System.Windows.Forms.Label();
this.LBLSALIDA = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// LBLC
//
this.LBLC.AutoSize = true;
this.LBLC.Location = new System.Drawing.Point(12, 25);
this.LBLC.Name = "LBLC";
this.LBLC.Size = new System.Drawing.Size(60, 13);
this.LBLC.TabIndex = 0;
this.LBLC.Text = "Conversion";
//
// TXTC
//
this.TXTC.Location = new System.Drawing.Point(165, 30);
this.TXTC.Name = "TXTC";
this.TXTC.Size = new System.Drawing.Size(100, 20);
this.TXTC.TabIndex = 1;
//
// LBLD
//
this.LBLD.AutoSize = true;
this.LBLD.Location = new System.Drawing.Point(12, 69);
this.LBLD.Name = "LBLD";
this.LBLD.Size = new System.Drawing.Size(147, 13);
this.LBLD.TabIndex = 2;
this.LBLD.Text = "Ingrese el numero a convertir:";
//
// TXTD
//
this.TXTD.Location = new System.Drawing.Point(165, 62);
this.TXTD.Name = "TXTD";
this.TXTD.Size = new System.Drawing.Size(100, 20);
this.TXTD.TabIndex = 3;
//
// TXTC2
//
this.TXTC2.Location = new System.Drawing.Point(32, 126);
this.TXTC2.Name = "TXTC2";
this.TXTC2.ReadOnly = true;
this.TXTC2.Size = new System.Drawing.Size(115, 20);
this.TXTC2.TabIndex = 4;
//
// CMDCON
//
this.CMDCON.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CMDCON.Location = new System.Drawing.Point(303, 25);
this.CMDCON.Name = "CMDCON";
this.CMDCON.Size = new System.Drawing.Size(95, 29);
this.CMDCON.TabIndex = 5;
this.CMDCON.Text = "&Conversion";
this.CMDCON.UseVisualStyleBackColor = true;
this.CMDCON.Click += new System.EventHandler(this.CMDCON_Click);
//
// CMDOTRO
//
this.CMDOTRO.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CMDOTRO.Location = new System.Drawing.Point(303, 69);
this.CMDOTRO.Name = "CMDOTRO";
this.CMDOTRO.Size = new System.Drawing.Size(95, 29);
this.CMDOTRO.TabIndex = 6;
this.CMDOTRO.Text = "&Clear";
this.CMDOTRO.UseVisualStyleBackColor = true;
this.CMDOTRO.Click += new System.EventHandler(this.CMDOTRO_Click);
//
// LBLCON2
//
this.LBLCON2.AutoSize = true;
this.LBLCON2.Location = new System.Drawing.Point(300, 126);
this.LBLCON2.Name = "LBLCON2";
this.LBLCON2.Size = new System.Drawing.Size(0, 13);
this.LBLCON2.TabIndex = 7;
//
// LBLF
//
this.LBLF.AutoSize = true;
this.LBLF.Location = new System.Drawing.Point(300, 158);
this.LBLF.Name = "LBLF";
this.LBLF.Size = new System.Drawing.Size(0, 13);
this.LBLF.TabIndex = 8;
//
// LBLY
//
this.LBLY.AutoSize = true;
this.LBLY.Location = new System.Drawing.Point(300, 193);
this.LBLY.Name = "LBLY";
this.LBLY.Size = new System.Drawing.Size(0, 13);
this.LBLY.TabIndex = 9;
//
// LBLCM
//
this.LBLCM.AutoSize = true;
this.LBLCM.Location = new System.Drawing.Point(300, 222);
this.LBLCM.Name = "LBLCM";
this.LBLCM.Size = new System.Drawing.Size(0, 13);
this.LBLCM.TabIndex = 10;
//
// LBLSALIDA
//
this.LBLSALIDA.AutoSize = true;
this.LBLSALIDA.Location = new System.Drawing.Point(300, 249);
this.LBLSALIDA.Name = "LBLSALIDA";
this.LBLSALIDA.Size = new System.Drawing.Size(0, 13);
this.LBLSALIDA.TabIndex = 11;
//
// FRMCON
//
this.AcceptButton = this.CMDCON;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(444, 276);
this.Controls.Add(this.LBLSALIDA);
this.Controls.Add(this.LBLCM);
this.Controls.Add(this.LBLY);
this.Controls.Add(this.LBLF);
this.Controls.Add(this.LBLCON2);
this.Controls.Add(this.CMDOTRO);
this.Controls.Add(this.CMDCON);
this.Controls.Add(this.TXTC2);
this.Controls.Add(this.TXTD);
this.Controls.Add(this.LBLD);
this.Controls.Add(this.TXTC);
this.Controls.Add(this.LBLC);
this.Name = "FRMCON";
this.Text = "Conversion";
this.Load += new System.EventHandler(this.FRMCON_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label LBLC;
private System.Windows.Forms.TextBox TXTC;
private System.Windows.Forms.Label LBLD;
private System.Windows.Forms.TextBox TXTD;
private System.Windows.Forms.TextBox TXTC2;
private System.Windows.Forms.Button CMDCON;
private System.Windows.Forms.Button CMDOTRO;
private System.Windows.Forms.Label LBLCON2;
private System.Windows.Forms.Label LBLF;
private System.Windows.Forms.Label LBLY;
private System.Windows.Forms.Label LBLCM;
private System.Windows.Forms.Label LBLSALIDA;
}
}
|
@{
Layout = "_Layout";
}
@using VendorOrderTracker.Models;
<h1>Vendors</h1>
@if (@Model.Count == 0)
{
<div class="card bg-light mb-3">
<div class="card-body">
<h3>Please Add Vendors!</h3>
</div>
</div>
}
@foreach (Vendor vendor in Model)
{
<div class="card bg-light mb-3">
<div class="card-body">
<h3><a href='/vendors/@vendor.Id'>@vendor.Name</a></h3>
<h6>@vendor.Description</h6>
<h6>@vendor.PhoneNumber</h6>
</div>
</div>
} |
using reposer.Config;
using reposer.Rendering.CopyHtml;
using reposer.Repository;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace reposer.Rendering
{
public class RenderService
{
public RenderService(
ConfigService configService,
IRepositoryPullService pullService,
IRendererFactory rendererFactory)
{
this.configService = configService;
this.pullService = pullService;
this.rendererFactory = rendererFactory;
this.pullService.RepositoryChanged += RepositoryChanged;
}
private readonly ConfigService configService;
private readonly IRepositoryPullService pullService;
private readonly IRendererFactory rendererFactory;
private void RepositoryChanged(object sender, RepositoryChangedEventArgs e)
{
var renderer = rendererFactory.Create();
renderer.Render();
SwapRenderOutputToWebroot();
}
private void SwapRenderOutputToWebroot()
{
var swapPath = configService.WebrootSwapPath;
var webrootPath = configService.WebrootPath;
var renderPath = configService.RenderPath;
CopyHtmlRenderer.CopyFilesRecursively(
new DirectoryInfo(renderPath),
new DirectoryInfo(webrootPath),
"*"
);
}
}
} |
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Xpf.Core.Native;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Controls;
namespace DevExpress.DevAV {
public class HorizontalScrollingOnMouseWheelBehavior : Behavior<ListView> {
protected override void OnAttached() {
base.OnAttached();
AssociatedObject.PreviewMouseWheel += OnPreviewMouseWheel;
}
protected override void OnDetaching() {
base.OnDetaching();
AssociatedObject.PreviewMouseWheel -= OnPreviewMouseWheel;
}
void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e) {
var scrollBar = (ScrollBar)LayoutHelper.FindElementByName(AssociatedObject, "PART_HorizontalScrollBar");
if(e.Delta > 0)
ScrollBar.LineLeftCommand.Execute(null, scrollBar);
else if(e.Delta < 0) {
ScrollBar.LineRightCommand.Execute(null, scrollBar);
}
}
}
} |
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Lifestyle.Scoped;
namespace Castle.Windsor.MsDependencyInjection
{
/// <summary>
/// Implements <see cref="IScopeAccessor"/> to get <see cref="ILifetimeScope"/>
/// from <see cref="MsLifetimeScope.Current"/>.
/// </summary>
public class MsScopedAccesor : IScopeAccessor
{
public void Dispose()
{
}
public ILifetimeScope GetScope(CreationContext context)
{
return MsLifetimeScope.Current.WindsorLifeTimeScope;
}
}
} |
using Microsoft.EntityFrameworkCore;
using Mix.Cms.Lib.Extensions;
namespace Mix.Cms.Lib.Models.Cms
{
public partial class SqliteMixCmsContext : MixCmsContext
{
public SqliteMixCmsContext()
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyAllConfigurationsFromNamespace(
this.GetType().Assembly,
"Mix.Cms.Lib.Models.EntityConfigurations.SQLITE");
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
} |
using TwilightSparkle.Forum.Foundation.ThreadsService;
namespace TwilightSparkle.Forum.Features.Threads.Models
{
public class ThreadCommentsCountResult
{
public int Count { get; set; }
public ThreadCommentsCountResult(ThreadCommentsCount commentsCount)
{
Count = commentsCount.Count;
}
}
}
|
namespace Npgsql;
#pragma warning disable CS1591
#pragma warning disable RS0016
public static class NpgsqlEventId
{
#region Connection
public const int OpeningConnection = 1000;
public const int OpenedConnection = 1001;
public const int ClosingConnection = 1003;
public const int ClosedConnection = 1004;
public const int OpeningPhysicalConnection = 1110;
public const int OpenedPhysicalConnection = 1111;
public const int ClosingPhysicalConnection = 1112;
public const int ClosedPhysicalConnection = 1113;
public const int StartingWait = 1300;
public const int ReceivedNotice = 1301;
public const int ConnectionExceededMaximumLifetime = 1500;
public const int SendingKeepalive = 1600;
public const int CompletedKeepalive = 1601;
public const int KeepaliveFailed = 1602;
public const int BreakingConnection = 1900;
public const int CaughtUserExceptionInNoticeEventHandler = 1901;
public const int CaughtUserExceptionInNotificationEventHandler = 1902;
public const int ExceptionWhenClosingPhysicalConnection = 1903;
public const int ExceptionWhenOpeningConnectionForMultiplexing = 1904;
#endregion Connection
#region Command
public const int ExecutingCommand = 2000;
public const int CommandExecutionCompleted = 2001;
public const int CancellingCommand = 2002;
public const int ExecutingInternalCommand = 2003;
public const int PreparingCommandExplicitly = 2100;
public const int CommandPreparedExplicitly = 2101;
public const int AutoPreparingStatement = 2102;
public const int UnpreparingCommand = 2103;
public const int DerivingParameters = 2500;
public const int ExceptionWhenWritingMultiplexedCommands = 2600;
#endregion Command
#region Transaction
public const int StartedTransaction = 30000;
public const int CommittedTransaction = 30001;
public const int RolledBackTransaction = 30002;
public const int CreatingSavepoint = 30100;
public const int RolledBackToSavepoint = 30101;
public const int ReleasedSavepoint = 30102;
public const int ExceptionDuringTransactionDispose = 30200;
public const int EnlistedVolatileResourceManager = 31000;
public const int CommittingSinglePhaseTransaction = 31001;
public const int RollingBackSinglePhaseTransaction = 31002;
public const int SinglePhaseTransactionRollbackFailed = 31003;
public const int PreparingTwoPhaseTransaction = 31004;
public const int CommittingTwoPhaseTransaction = 31005;
public const int TwoPhaseTransactionCommitFailed = 31006;
public const int RollingBackTwoPhaseTransaction = 31007;
public const int TwoPhaseTransactionRollbackFailed = 31008;
public const int TwoPhaseTransactionInDoubt = 31009;
public const int ConnectionInUseWhenRollingBack = 31010;
public const int CleaningUpResourceManager = 31011;
#endregion Transaction
#region Copy
public const int StartingBinaryExport = 40000;
public const int StartingBinaryImport = 40001;
public const int StartingTextExport = 40002;
public const int StartingTextImport = 40003;
public const int StartingRawCopy = 40004;
public const int CopyOperationCompleted = 40100;
public const int CopyOperationCancelled = 40101;
public const int ExceptionWhenDisposingCopyOperation = 40102;
#endregion Copy
#region Replication
public const int CreatingReplicationSlot = 50000;
public const int DroppingReplicationSlot = 50001;
public const int StartingLogicalReplication = 50002;
public const int StartingPhysicalReplication = 50003;
public const int ExecutingReplicationCommand = 50004;
public const int ReceivedReplicationPrimaryKeepalive = 50100;
public const int SendingReplicationStandbyStatusUpdate = 50101;
public const int SentReplicationFeedbackMessage = 50102;
public const int ReplicationFeedbackMessageSendingFailed = 50103;
#endregion Replication
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace NPOI.OpenXmlFormats.Dml.Diagram
{
[Serializable]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/diagram", IsNullable = true)]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/diagram")]
[DebuggerStepThrough]
[DesignerCategory("code")]
public class CT_NumericRule
{
private CT_OfficeArtExtensionList extLstField;
private ST_ConstraintType typeField;
private ST_ConstraintRelationship forField;
private string forNameField;
private List<ST_ElementType> ptTypeField;
private double valField;
private double factField;
private double maxField;
[XmlElement(Order = 0)]
public CT_OfficeArtExtensionList extLst
{
get
{
return extLstField;
}
set
{
extLstField = value;
}
}
[XmlAttribute]
public ST_ConstraintType type
{
get
{
return typeField;
}
set
{
typeField = value;
}
}
[DefaultValue(ST_ConstraintRelationship.self)]
[XmlAttribute]
public ST_ConstraintRelationship @for
{
get
{
return forField;
}
set
{
forField = value;
}
}
[DefaultValue("")]
[XmlAttribute]
public string forName
{
get
{
return forNameField;
}
set
{
forNameField = value;
}
}
[XmlAttribute]
public List<ST_ElementType> ptType
{
get
{
return ptTypeField;
}
set
{
ptTypeField = value;
}
}
[DefaultValue(double.NaN)]
[XmlAttribute]
public double val
{
get
{
return valField;
}
set
{
valField = value;
}
}
[XmlAttribute]
[DefaultValue(double.NaN)]
public double fact
{
get
{
return factField;
}
set
{
factField = value;
}
}
[DefaultValue(double.NaN)]
[XmlAttribute]
public double max
{
get
{
return maxField;
}
set
{
maxField = value;
}
}
public CT_NumericRule()
{
ptTypeField = new List<ST_ElementType>();
forField = ST_ConstraintRelationship.self;
forNameField = "";
ST_ElementType[] collection = new ST_ElementType[1];
ptTypeField = new List<ST_ElementType>(collection);
valField = double.NaN;
factField = double.NaN;
maxField = double.NaN;
}
}
}
|
using System;
using System.Collections.Generic;
namespace Claytondus.EasyPost.Models
{
public class ScanForm
{
public string? id { get; set; }
public DateTime? created_at { get; set; }
public DateTime? updated_at { get; set; }
public List<string>? tracking_codes { get; set; }
public Address? address { get; set; }
public string? form_url { get; set; }
public string? form_file_type { get; set; }
public string? mode { get; set; }
public string? status { get; set; }
public string? message { get; set; }
public string? batch_id { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class confettiTrigger : MonoBehaviour
{
public GameObject confetti1, confetti2, confetti3, confetti4, confetti5, confetti6;
private void Start()
{
confetti1.SetActive(false);
confetti2.SetActive(false);
confetti3.SetActive(false);
confetti4.SetActive(false);
confetti5.SetActive(false);
confetti6.SetActive(false);
}
private void OnTriggerEnter(Collider other)
{
confetti1.SetActive(true);
confetti2.SetActive(true);
confetti3.SetActive(true);
confetti4.SetActive(true);
confetti5.SetActive(true);
confetti6.SetActive(true);
}
}
|
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using DSInternals.Common.Data;
using DSInternals.Common.Exceptions;
using Newtonsoft.Json;
namespace DSInternals.Common.AzureAD
{
public class AzureADClient : IDisposable
{
private const string DefaultTenantId = "myorganization";
private const string SelectParameter = "$select=userPrincipalName,searchableDeviceKey,objectId,displayName,accountEnabled";
private const string ApiVersionParameter = "api-version=1.6-internal";
private const string BatchSizeParameterFormat = "$top={0}";
private const string UPNFilterParameterFormat = "$filter=userPrincipalName eq '{0}'";
private const string IdFilterParameterFormat = "$filter=objectId eq '{0}'";
private const string AuthenticationScheme = "Bearer";
private const char UriParameterSeparator = '&';
private const string UsersUrlFormat = "https://graph.windows.net/{0}/users/{1}?";
private const string JsonContentType = "application/json";
private const string KeyCredentialAttributeName = "searchableDeviceKey";
public const int MaxBatchSize = 999;
private static readonly MediaTypeWithQualityHeaderValue s_odataContentType = MediaTypeWithQualityHeaderValue.Parse("application/json;odata=nometadata;streaming=false");
private string _tenantId;
private HttpClient _httpClient;
private readonly string _batchSizeParameter;
private JsonSerializer _jsonSerializer = JsonSerializer.CreateDefault();
public AzureADClient(string accessToken, Guid? tenantId = null, int batchSize = MaxBatchSize)
{
// Validate inputs
Validator.AssertNotNullOrWhiteSpace(accessToken, nameof(accessToken));
_tenantId = tenantId?.ToString() ?? DefaultTenantId;
_batchSizeParameter = string.Format(CultureInfo.InvariantCulture, BatchSizeParameterFormat, batchSize);
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(AuthenticationScheme, accessToken);
_httpClient.DefaultRequestHeaders.Accept.Add(s_odataContentType);
}
public async Task<AzureADUser> GetUserAsync(string userPrincipalName)
{
// Vaidate the input
Validator.AssertNotNullOrEmpty(userPrincipalName, nameof(userPrincipalName));
var filter = string.Format(CultureInfo.InvariantCulture, UPNFilterParameterFormat, userPrincipalName);
return await GetUserAsync(filter, userPrincipalName).ConfigureAwait(false);
}
public async Task<AzureADUser> GetUserAsync(Guid objectId)
{
var filter = string.Format(CultureInfo.InvariantCulture, IdFilterParameterFormat, objectId);
return await GetUserAsync(filter, objectId).ConfigureAwait(false);
}
private async Task<AzureADUser> GetUserAsync(string filterParameter, object userIdentifier)
{
// Build uri with filter
var url = new StringBuilder();
url.AppendFormat(CultureInfo.InvariantCulture, UsersUrlFormat, _tenantId, String.Empty);
url.Append(SelectParameter);
url.Append(UriParameterSeparator);
url.Append(filterParameter);
// Send the request
var result = await GetUsersAsync(url.ToString()).ConfigureAwait(false);
if ((result.Items?.Count ?? 0) == 0)
{
throw new DirectoryObjectNotFoundException(userIdentifier);
}
return result.Items[0];
}
public async Task<OdataPagedResponse<AzureADUser>> GetUsersAsync(string nextLink = null)
{
var url = new StringBuilder(nextLink);
if (string.IsNullOrEmpty(nextLink))
{
// Build the intial URL
url.AppendFormat(CultureInfo.InvariantCulture, UsersUrlFormat, _tenantId, String.Empty);
url.Append(SelectParameter);
}
// Add query string parameters
url.Append(UriParameterSeparator);
url.Append(ApiVersionParameter);
url.Append(UriParameterSeparator);
url.Append(_batchSizeParameter);
using (var request = new HttpRequestMessage(HttpMethod.Get, url.ToString()))
{
// Perform API call
var result = await SendODataRequest<OdataPagedResponse<AzureADUser>>(request).ConfigureAwait(false);
// Update key credential owner references
if (result.Items != null)
{
result.Items.ForEach(user => user.UpdateKeyCredentialReferences());
}
return result;
}
}
public async Task SetUserAsync(string userPrincipalName, KeyCredential[] keyCredentials)
{
// Vaidate the input
Validator.AssertNotNullOrEmpty(userPrincipalName, nameof(userPrincipalName));
var properties = new Hashtable() { { KeyCredentialAttributeName, keyCredentials } };
await SetUserAsync(userPrincipalName, properties).ConfigureAwait(false);
}
public async Task SetUserAsync(Guid objectId, KeyCredential[] keyCredentials)
{
var properties = new Hashtable() { { KeyCredentialAttributeName, keyCredentials } };
await SetUserAsync(objectId.ToString(), properties).ConfigureAwait(false);
}
private async Task SetUserAsync(string userIdentifier, Hashtable properties)
{
// Build the request uri
var url = new StringBuilder();
url.AppendFormat(CultureInfo.InvariantCulture, UsersUrlFormat, _tenantId, userIdentifier);
url.Append(ApiVersionParameter);
// TODO: Switch to HttpMethod.Patch after migrating to .NET Standard 2.1 / .NET 5
using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), url.ToString()))
{
request.Content = new StringContent(JsonConvert.SerializeObject(properties), Encoding.UTF8, JsonContentType);
await SendODataRequest<object>(request).ConfigureAwait(false);
}
}
private async Task<T> SendODataRequest<T>(HttpRequestMessage request)
{
try
{
using (var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
{
if(response.StatusCode == HttpStatusCode.NoContent)
{
// No objects have been returned, but the call was successful.
return default(T);
}
using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
using (var streamReader = new StreamReader(responseStream))
{
if (s_odataContentType.MediaType.Equals(response.Content.Headers.ContentType.MediaType, StringComparison.InvariantCultureIgnoreCase))
{
// The response is a JSON document
using (var jsonTextReader = new JsonTextReader(streamReader))
{
if (response.StatusCode == HttpStatusCode.OK)
{
return _jsonSerializer.Deserialize<T>(jsonTextReader);
}
else
{
// Translate OData response to an exception
var error = _jsonSerializer.Deserialize<OdataErrorResponse>(jsonTextReader);
throw error.GetException();
}
}
}
else
{
// The response is not a JSON document, so we parse its first line as message text
string message = await streamReader.ReadLineAsync().ConfigureAwait(false);
throw new GraphApiException(message, response.StatusCode.ToString());
}
}
}
}
catch (JsonException e)
{
throw new GraphApiException("The data returned by the REST API call has an unexpected format.", e);
}
catch (HttpRequestException e)
{
// Unpack a more meaningful message, e. g. DNS error
throw new GraphApiException(e?.InnerException.Message ?? "An error occured while trying to call the REST API.", e);
}
}
#region IDisposable Support
public virtual void Dispose()
{
_httpClient.Dispose();
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.