content stringlengths 23 1.05M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChanceNET;
using ChanceNET.Attributes;
namespace ChanceNET.Tests
{
public class Book
{
[Year]
public int Year;
[Sentence]
public string Title;
[Date]
public DateTime Release;
[Person(emailDomain: "gmail.com")]
public Person Author;
[Location]
public Location Location;
[Guid]
public string Guid;
[Double(0, 100)]
public double Price;
[Color]
public string CoverColor;
[Url]
public string Website;
[Enum(typeof(Genre))]
public Genre Genre;
[Object(typeof(Publisher))]
public Publisher Publisher;
}
public enum Genre
{
Murder = 1,
Mystery = 2,
Comedy = 3,
Erotica = 4,
Biography = 5
}
}
|
using System;
namespace BLToolkit.Aspects
{
/// <summary>
/// http://www.bltoolkit.net/Doc/Aspects/index.htm
/// </summary>
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Interface |
AttributeTargets.Property |
AttributeTargets.Method,
AllowMultiple=true)]
public class NoCacheAttribute : NoInterceptionAttribute
{
public NoCacheAttribute()
: base(typeof(CacheAspect), InterceptType.BeforeCall | InterceptType.AfterCall)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orient.Client.API.Types;
namespace Orient.Client.Protocol.Serializers
{
public static class RecordSerializerFactory
{
public static IRecordSerializer GetSerializer(ODatabase database)
{
//if (database.ProtocolVersion < 22)
// return (IRecordSerializer)new RecordCSVSerializer(database.GetConnection());
//else
// return (IRecordSerializer)new RecordBinarySerializer(database.GetConnection());
// Temporary return old serializer
// TODO: Fix after implement binary serializer compleatly
return (IRecordSerializer)new RecordCSVSerializer((database != null) ? database.GetConnection() : null);
}
public static IRecordSerializer GetSerializer(ORecordFormat format)
{
switch (format)
{
case ORecordFormat.ORecordDocument2csv:
return new RecordCSVSerializer(null);
case ORecordFormat.ORecordSerializerBinary:
return new RecordBinarySerializer(null);
}
throw new NotImplementedException("The " + format + " serializer not implemented it");
}
}
}
|
using Auth.Domain.Entities;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
namespace Auth.Infrastructure.Jwt
{
public class JwtTokenService
{
private SigningConfigurations _signingConfigurations;
private TokenConfigurations _tokenConfigurations;
public JwtTokenService(
SigningConfigurations signingConfigurations,
TokenConfigurations tokenConfigurations)
{
_signingConfigurations = signingConfigurations;
_tokenConfigurations = tokenConfigurations;
}
public string GererateToken(UserDomain user)
{
var identity = UserToClaimsIdentity(user);
DateTime expires = DateTime.Now + TimeSpan.FromSeconds(_tokenConfigurations.Seconds);
var securityToken = new JwtSecurityToken
(
issuer: null,
audience: null,
signingCredentials: _signingConfigurations.SigningCredentials,
expires: expires,
claims: identity.Claims
);
return new JwtSecurityTokenHandler().WriteToken(securityToken);
}
private ClaimsIdentity UserToClaimsIdentity(UserDomain user)
{
var claims = new List<Claim>();
claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")));
claims.Add(new Claim(JwtRegisteredClaimNames.UniqueName, user.Id.ToString()));
claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));
claims.Add(new Claim(ClaimTypes.Role, user.Role));
if (user.Permissions.Any())
claims.AddRange(user.Permissions.Select(permission => new Claim(ClaimTypes.Role, permission)));
return new ClaimsIdentity(new ClaimsIdentity(claims), claims);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CalcDatabaseSize
{
public partial class TableControle : UserControl
{
public TableControle()
{
InitializeComponent();
}
private void tbRows_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
}
}
public string TableName
{
get
{
return lblName.Text;
}
set
{
lblName.Text = value;
}
}
public int Rows
{
get
{
return int.Parse(tbRows.Text);
}
}
}
}
|
using Ardalis.Result;
using Thing.Designer.SolidModeling.Models;
using Thing.Domain.SolidModeling;
using Thing.ModelDesign;
namespace Thing.Designer.SolidModeling;
public class SolidModelDesigner
{
public event EventHandler<SolidModelMeshDto>? ModelMeshUpdated;
public IResult RecalculateSolidModel(SolidModelDesignDto solidModelDesign)
{
var designer = new SolidModelDomainDesigner();
designer.RequestBodyDimensions(
solidModelDesign.Width,
solidModelDesign.Height,
solidModelDesign.Depth);
foreach (var featureDto in solidModelDesign.Features)
{
var holeDesigner = designer.AddFeature<HoleDesigner>();
// TODO: Make gooder holes
}
var asciiStl = new MeshGenerator().ExportStl(designer);
ModelMeshUpdated?.Invoke(this, new SolidModelMeshDto { AsciiStlMeshData = asciiStl });
return Result<bool>.Success(true);
}
}
|
namespace StudentManagement.Data
{
public partial class Course
{
public Course()
{
Enrollments = new HashSet<Enrollment>();
}
public int Id { get; set; }
public string Name { get; set; } = null!;
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Discord;
namespace Zhongli.Data.Models.Discord.Message.Components;
public class ActionRow
{
public ActionRow() { }
public ActionRow(ActionRowComponent row) : this(row.Components) { }
public ActionRow(ActionRowBuilder row) : this(row.Components) { }
[SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")]
private ActionRow(IEnumerable<IMessageComponent> components)
{
Components = components
.Select<IMessageComponent, Component>(c => c switch
{
ButtonComponent button => new Button(button),
SelectMenuComponent menu => new SelectMenu(menu),
_ => throw new ArgumentOutOfRangeException(nameof(c))
})
.ToList();
}
public Guid Id { get; set; }
public virtual ICollection<Component> Components { get; set; } = new List<Component>();
public static implicit operator ActionRow(ActionRowComponent row) => new(row);
public static implicit operator ActionRow(ActionRowBuilder builder) => new(builder);
} |
namespace Specify.Configuration
{
/// <summary>
/// Represents an action to be performed once per Appliction (before and after all scenarios are run).
/// </summary>
public interface IPerApplicationAction
{
/// <summary>
/// Action to be performed before any scenarios have run.
/// </summary>
void Before();
/// <summary>
/// Action to be performed after all scenarios have run.
/// </summary>
void After();
/// <summary>
/// The order the action will run in.
/// </summary>
int Order { get; set; }
}
} |
using System;
using System.Linq;
namespace QueryPro
{
class Program
{
static void Main(string[] args)
{
var provider = new QueryProvider();
var customer = new Query<Customer>(provider);
IQueryable<Customer> query = customer.Where(c => c.Id == 1);
Console.WriteLine($"query: {query}");
Console.ReadKey();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using Microsoft.Azure.Cosmos;
using Newtonsoft.Json;
namespace coffeebook
{
/// <summary>
/// ユーザー情報のインターフェース
/// </summary>
public partial class UserInfo
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
}
/// <summary>
/// ユーザークラス
/// </summary>
public partial class User
{
[JsonProperty("userId")]
public string UserId { get; set; }
[JsonProperty("hashedPassword")]
public byte[] HashedPassword { get; set; }
[JsonProperty("salt")]
public byte[] Salt { get; set; }
}
/// <summary>
/// セッションクラス
/// </summary>
public partial class Session
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("userId")]
public string UserId { get; set; }
[JsonProperty("sessionId")]
public string SessionId { get; set; }
}
/// <summary>
/// ユーザーに関連する定数
/// </summary>
public class UserConst
{
public const string sessionId = "sessionId";
}
/// <summary>
/// ユーザーに関連する共通メソッドを提供する
/// </summary>
public class UserService
{
/// <summary>
/// ソルトを生成
/// </summary>
/// <returns>ソルト</returns>
public static byte[] GenerateSalt()
{
using var rng = RandomNumberGenerator.Create();
{
var buff = new byte[128 / 8];
rng.GetBytes(buff);
return buff;
}
}
/// <summary>
/// パスワードとソルトからハッシュを作成
/// </summary>
/// <returns>ハッシュ</returns>
public static byte[] GenerateHashedValue(string password, byte[] salt)
{
var b = new Rfc2898DeriveBytes(
password,
salt,
100,
HashAlgorithmName.SHA256);
return b.GetBytes(256);
}
/// <summary>
/// セッションIDを生成
/// </summary>
/// <returns>セッションID</returns>
public static string GenerateSessionId()
{
return Encoding.UTF8.GetString(GenerateSalt());
}
/// <summary>
/// セッションIDからユーザーIDを取得
/// </summary>
/// <returns>ユーザーID</returns>
public static async Task<string> GetUserIdFromSessionContainer(string connectionString, string sessionId)
{
// コンテナを取得する
var client = new CosmosClient(connectionString);
var sessionContainer = client.GetContainer(Consts.COFFEEBOOK_DB, Consts.SESSION_CONTAINER);
var sessionQuery = sessionContainer.GetItemQueryIterator<Session>(new QueryDefinition(
"select * from r where r.sessionId = @sessionId")
.WithParameter("@sessionId", sessionId));
var sessions = new List<Session>();
while (sessionQuery.HasMoreResults)
{
var response = await sessionQuery.ReadNextAsync();
sessions.AddRange(response.ToList());
}
return sessions[0].UserId;
}
}
}
|
using Common;
using Backend.Game;
using System;
namespace Backend.Network
{
public partial class Incoming
{
private void OnRecvChangeStatus(IChannel channel, Message message)
{
CChangeStatus request = message as CChangeStatus;
var conn = db.Instance.Connect();
if (request.on == true)
{
if (request.treasure.effect != '1')
db.Instance.ChangeStatusOn(request.userDbid, request.treasure.id, conn);
else
db.Instance.DeleteTreasure(request.treasure.id, conn);
}
else
db.Instance.ChangeStatusOff(request.userDbid, request.treasure.id, conn);
}
}
}
|
// Parkitect.Mods.AssetPacks.MaterialDecorator
using Parkitect.Mods.AssetPacks;
using UnityEngine;
internal class MaterialDecorator : IDecorator
{
private Material standard;
private Material diffuse;
private Material colorDiffuse;
private Material specular;
private Material colorSpecular;
private Material colorDiffuseIllum;
private Material colorSpecularIllum;
public MaterialDecorator()
{
Material[] objectMaterials = ScriptableSingleton<AssetManager>.Instance.objectMaterials;
foreach (Material material in objectMaterials)
{
switch (material.name)
{
case "Diffuse":
this.diffuse = material;
break;
case "CustomColorsDiffuse":
this.colorDiffuse = material;
break;
case "Specular":
this.specular = material;
break;
case "CustomColorsSpecular":
this.colorSpecular = material;
break;
case "CustomColorsIllum":
this.colorDiffuseIllum = material;
break;
case "CustomColorsIllumSpecular":
this.colorSpecularIllum = material;
break;
}
}
}
public void Decorate(GameObject assetGO, Asset asset, AssetBundle assetBundle)
{
if (asset.Type == AssetType.Fence)
{
Fence component = assetGO.GetComponent<Fence>();
this.replaceMaterials(component.flatGO, asset);
if ((Object)component.postGO != (Object)null)
{
this.replaceMaterials(component.postGO, asset);
}
}
else
{
this.replaceMaterials(assetGO, asset);
}
}
private void replaceMaterials(GameObject go, Asset asset)
{
Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>();
foreach (Renderer renderer in componentsInChildren)
{
Material[] sharedMaterials = renderer.sharedMaterials;
for (int j = 0; j < sharedMaterials.Length; j++)
{
Material material = sharedMaterials[j];
if (!((Object)material == (Object)null))
{
if (material.name.StartsWith("Diffuse"))
{
sharedMaterials[j] = this.diffuse;
}
else if (material.name.StartsWith("CustomColorsDiffuseIllum"))
{
sharedMaterials[j] = this.colorDiffuseIllum;
}
else if (material.name.StartsWith("CustomColorsDiffuse"))
{
sharedMaterials[j] = this.colorDiffuse;
}
else if (material.name.StartsWith("Specular"))
{
sharedMaterials[j] = this.specular;
}
else if (material.name.StartsWith("CustomColorsSpecularIllum"))
{
sharedMaterials[j] = this.colorSpecularIllum;
}
else if (material.name.StartsWith("CustomColorsSpecular"))
{
sharedMaterials[j] = this.colorSpecular;
}
else if (!material.name.StartsWith("SignTextMaterial") && !material.name.StartsWith("tv_image"))
{
sharedMaterials[j] = material;
sharedMaterials[j].shader = ScriptableSingleton<AssetManager>.Instance.standardShader;
}
}
}
renderer.sharedMaterials = sharedMaterials;
}
}
} |
using Bitmex.NET.Models;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
namespace Bitmex.NET.IntegrationTests.Tests
{
[TestClass]
[TestCategory("REST")]
public class BitmexApiServicePositionApiTests : IntegrationTestsClass<IBitmexApiService>
{
[TestMethod]
public void should_get_all_the_positions()
{
// arrange
var @params = new PositionGETRequestParams();
// act
var result = Sut.Execute(BitmexApiUrls.Position.GetPosition, @params).Result;
// assert
result.Should().NotBeNull();
result.Count.Should().BeGreaterThan(0);
}
[TestMethod]
public void should_get_the_positions_with_params()
{
// arrange
var @params = new PositionGETRequestParams
{
Filter = new Dictionary<string, string> { { "symbol", "XBTUSD" } }
};
// act
var result = Sut.Execute(BitmexApiUrls.Position.GetPosition, @params).Result;
// assert
result.Should().NotBeNull();
result.Count.Should().BeGreaterThan(0);
result.All(a => a.Symbol == "XBTUSD").Should().BeTrue();
}
[TestMethod]
public void should_execute_position_isolate()
{
// arrange
var @params = new PositionIsolatePOSTRequestParams
{
Symbol = "XBTUSD",
Enabled = true
};
// act
var result = Sut.Execute(BitmexApiUrls.Position.PostPositionIsolate, @params).Result;
// assert
result.Should().NotBeNull();
result.Symbol.Should().Be("XBTUSD");
}
[TestMethod]
public void should_execute_position_leverage()
{
// arrange
var @params = new PositionLeveragePOSTRequestParams
{
Symbol = "XBTUSD",
Leverage = 1
};
// act
var result = Sut.Execute(BitmexApiUrls.Position.PostPositionLeverage, @params).Result;
// assert
result.Should().NotBeNull();
result.Symbol.Should().Be("XBTUSD");
}
[TestMethod]
public void should_execute_position_risk_limit()
{
// arrange
var @params = new PositionRiskLimitPOSTRequestParams
{
Symbol = "XBTUSD",
RiskLimit = 1
};
// act
var result = Sut.Execute(BitmexApiUrls.Position.PostPositionRiskLimit, @params).Result;
// assert
result.Should().NotBeNull();
result.Symbol.Should().Be("XBTUSD");
}
// works only for certain account conditions
[TestMethod, Ignore]
public void should_execute_position_transfer_margin()
{
// arrange
var @params = new PositionTransferMarginPOSTRequestParams
{
Symbol = "XBTUSD",
Amount = 1
};
// act
var result = Sut.Execute(BitmexApiUrls.Position.PostPositionTransferMargin, @params).Result;
// assert
result.Should().NotBeNull();
result.Symbol.Should().Be("XBTUSD");
}
}
}
|
using System;
using System.IO;
using System.Reflection;
namespace WebAssembly{
/// <summary>A WebAssembly global section.</summary>
public class GlobalSection : Section{
/// <summary>All globals in this section.</summary>
public GlobalVariable[] Globals;
public GlobalSection():base(6){}
public override void Load(Reader reader,int length){
// Create set:
Globals=new GlobalVariable[(int)reader.VarUInt32()];
for(int i=0;i<Globals.Length;i++){
// Load it:
Globals[i]=new GlobalVariable(reader,i);
}
}
/// <summary>Compiles all the globals in this code section (sets up their field and initialiser).</summary>
public void Compile(ILGenerator gen){
if(Globals==null){
return;
}
for(int i=0;i<Globals.Length;i++){
// Get the gv:
GlobalVariable global = Globals[i];
// Field:
Type type;
FieldInfo field = global.GetField(Module,out type);
object init=global.Init;
if(init!=null){
// Apply the initialiser now:
if(init is FieldInfo){
// Global (must be imported)
gen.LoadField(init as FieldInfo);
}else{
// Must be one of the four constant expr's:
if(init is int){
gen.LoadInt32((int)init);
}else if(init is long){
gen.LoadInt64((long)init);
}else if(init is float){
gen.LoadSingle((float)init);
}else if(init is double){
gen.LoadDouble((double)init);
}
}
gen.StoreField(field);
}
}
}
}
} |
namespace DoExtension
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class EnumerableExtension
{
public static ICollection<T> FluentAdd<T>(this ICollection<T> list, T obj)
{
list.Add(obj);
return list;
}
public static ICollection<T> FluentAddRange<T>(this ICollection<T> list, IEnumerable<T> objs)
{
foreach (var obj in objs)
{
list.Add(obj);
}
return list;
}
public static void ForEach<T>(this IEnumerable<T> list, Action<T> mapFunction)
{
foreach (var item in list)
{
mapFunction(item);
}
}
public static U GetValue<T, U>(this IDictionary<T, U> dict, T key)
{
if (!dict.TryGetValue(key, out var value))
{
throw new KeyNotFoundException($"Cannot find key {key}");
}
return value;
}
public static U GetValueOrDefault<T, U>(this IDictionary<T, U> dict, T key, U defaultValue = default)
{
if (!dict.TryGetValue(key, out var value))
{
return defaultValue;
}
return value;
}
public static bool IsIn<T>(this T source, params T[] list)
{
if (null == source)
{
throw new ArgumentNullException(nameof(source));
}
if (DoCheck.IsEmpty(list))
{
throw new ArgumentNullException(nameof(list));
}
return list.Contains(source);
}
public static bool IsIn<T>(this T source, IEnumerable<T> list)
{
if (null == source)
{
throw new ArgumentNullException(nameof(source));
}
if (DoCheck.IsEmpty(list))
{
throw new ArgumentNullException(nameof(list));
}
return list.Contains(source);
}
public static string Join<T>(this IEnumerable<T> list, string separator = ", ")
{
return string.Join(separator, list);
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list)
{
return list.OrderBy(x => Guid.NewGuid());
}
}
}
|
#nullable enable
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using JetBlack.MessageBus.Distributor.Roles;
namespace JetBlack.MessageBus.Distributor.Test.Roles
{
[TestClass]
public class InteractorRoleTest
{
[TestMethod]
public void ShouldUnderstandRoles()
{
var role = new InteractorRole("host", "user", Role.Subscribe, Role.Publish | Role.Notify | Role.Authorize);
Assert.IsTrue(role.HasRole(Role.Subscribe, true));
Assert.IsFalse(role.HasRole(Role.Publish, true));
Assert.IsFalse(role.HasRole(Role.Notify, true));
Assert.IsFalse(role.HasRole(Role.Authorize, true));
}
}
}
|
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.DocumentationRules
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.DocumentationRules;
using StyleCop.Analyzers.Test.Helpers;
using StyleCop.Analyzers.Test.Verifiers;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.CustomDiagnosticVerifier<StyleCop.Analyzers.DocumentationRules.SA1607PartialElementDocumentationMustHaveSummaryText>;
/// <summary>
/// This class contains unit tests for <see cref="SA1607PartialElementDocumentationMustHaveSummaryText"/>.
/// </summary>
public class SA1607UnitTests
{
[Theory]
[MemberData(nameof(CommonMemberData.TypeDeclarationKeywords), MemberType = typeof(CommonMemberData))]
public async Task TestTypeNoDocumentationAsync(string typeName)
{
var testCode = @"
partial {0} TypeName
{{
}}";
await VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(CommonMemberData.TypeDeclarationKeywords), MemberType = typeof(CommonMemberData))]
public async Task TestTypeWithSummaryDocumentationAsync(string typeName)
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
partial {0} TypeName
{{
}}";
await VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(CommonMemberData.TypeDeclarationKeywords), MemberType = typeof(CommonMemberData))]
public async Task TestTypeWithContentDocumentationAsync(string typeName)
{
var testCode = @"
/// <content>
/// Foo
/// </content>
partial {0} TypeName
{{
}}";
await VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(CommonMemberData.TypeDeclarationKeywords), MemberType = typeof(CommonMemberData))]
public async Task TestTypeWithInheritedDocumentationAsync(string typeName)
{
var testCode = @"
/// <inheritdoc/>
partial {0} TypeName
{{
}}";
await VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(CommonMemberData.TypeDeclarationKeywords), MemberType = typeof(CommonMemberData))]
public async Task TestTypeWithoutSummaryDocumentationAsync(string typeName)
{
var testCode = @"
/// <summary>
///
/// </summary>
partial {0}
TypeName
{{
}}";
DiagnosticResult expected = Diagnostic().WithLocation(6, 1);
await VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), expected, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(CommonMemberData.BaseTypeDeclarationKeywords), MemberType = typeof(CommonMemberData))]
public async Task TestNonPartialTypeWithoutSummaryDocumentationAsync(string typeName)
{
var testCode = @"
/// <summary>
///
/// </summary>
{0} TypeName
{{
}}";
await VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(CommonMemberData.TypeDeclarationKeywords), MemberType = typeof(CommonMemberData))]
public async Task TestTypeWithoutContentDocumentationAsync(string typeName)
{
var testCode = @"
/// <content>
///
/// </content>
partial {0}
TypeName
{{
}}";
DiagnosticResult expected = Diagnostic().WithLocation(6, 1);
await VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), expected, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(CommonMemberData.BaseTypeDeclarationKeywords), MemberType = typeof(CommonMemberData))]
public async Task TestNonPartialTypeWithoutContentDocumentationAsync(string typeName)
{
var testCode = @"
/// <content>
///
/// </content>
{0} TypeName
{{
}}";
await VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestMethodNoDocumentationAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
partial void Test();
}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestMethodWithSummaryDocumentationAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <summary>
/// Foo
/// </summary>
partial void Test();
}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestMethodWithContentDocumentationAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <content>
/// Foo
/// </content>
partial void Test();
}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestMethodWithInheritedDocumentationAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <inheritdoc/>
partial void Test();
}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestMethodWithoutSummaryDocumentationAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <summary>
///
/// </summary>
partial void Test();
}";
DiagnosticResult expected = Diagnostic().WithLocation(10, 18);
await VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestNonPartialMethodWithoutSummaryDocumentationAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <summary>
///
/// </summary>
public void Test() { }
}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestMethodWithoutContentDocumentationAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <content>
///
/// </content>
partial void Test();
}";
DiagnosticResult expected = Diagnostic().WithLocation(10, 18);
await VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestNonPartialMethodWithoutContentDocumentationAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <content>
///
/// </content>
public void Test() { }
}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestIncludedDocumentationWithoutSummaryOrContentAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <include file='MethodWithoutSummaryOrContent.xml' path='/ClassName/Test/*'/>
partial void Test();
}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestIncludedDocumentationWithEmptySummaryAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <include file='MethodWithEmptySummary.xml' path='/ClassName/Test/*'/>
partial void Test();
}";
var expected = Diagnostic().WithLocation(8, 18);
await VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestIncludedDocumentationWithEmptyContentAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <include file='MethodWithEmptyContent.xml' path='/ClassName/Test/*'/>
partial void Test();
}";
var expected = Diagnostic().WithLocation(8, 18);
await VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestIncludedDocumentationWithInheritdocAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <include file='MethodWithInheritdoc.xml' path='/ClassName/Test/*'/>
partial void Test();
}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestIncludedDocumentationWithSummaryAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <include file='MethodWithSummary.xml' path='/ClassName/Test/*'/>
partial void Test();
}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestIncludedDocumentationWithContentAsync()
{
var testCode = @"
/// <summary>
/// Foo
/// </summary>
public partial class ClassName
{
/// <include file='MethodWithContent.xml' path='/ClassName/Test/*'/>
partial void Test();
}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
protected static Task VerifyCSharpDiagnosticAsync(string source, DiagnosticResult expected, CancellationToken cancellationToken)
=> VerifyCSharpDiagnosticAsync(source, new[] { expected }, cancellationToken);
protected static Task VerifyCSharpDiagnosticAsync(string source, DiagnosticResult[] expected, CancellationToken cancellationToken)
{
string contentWithoutSummaryOrContent = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<ClassName>
<Test>
</Test>
</ClassName>
";
string contentWithEmptySummary = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<ClassName>
<Test>
<summary>
</summary>
</Test>
</ClassName>
";
string contentWithEmptyContent = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<ClassName>
<Test>
<content>
</content>
</Test>
</ClassName>
";
string contentWithInheritdoc = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<ClassName>
<Test>
<inheritdoc/>
</Test>
</ClassName>
";
string contentWithSummary = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<ClassName>
<Test>
<summary>
Foo
</summary>
</Test>
</ClassName>
";
string contentWithContent = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<ClassName>
<Test>
<content>
Foo
</content>
</Test>
</ClassName>
";
var test = new StyleCopDiagnosticVerifier<SA1607PartialElementDocumentationMustHaveSummaryText>.CSharpTest
{
TestCode = source,
XmlReferences =
{
{ "MethodWithoutSummaryOrContent.xml", contentWithoutSummaryOrContent },
{ "MethodWithEmptySummary.xml", contentWithEmptySummary },
{ "MethodWithEmptyContent.xml", contentWithEmptyContent },
{ "MethodWithInheritdoc.xml", contentWithInheritdoc },
{ "MethodWithSummary.xml", contentWithSummary },
{ "MethodWithContent.xml", contentWithContent },
},
};
test.ExpectedDiagnostics.AddRange(expected);
return test.RunAsync(cancellationToken);
}
}
}
|
using UnityEngine;
public class CameraPlacer : MonoBehaviour {
/// <summary>
/// Насколько больше будет Bounds при вычислении размера камеры
/// </summary>
[SerializeField]
private float margin = 1;
private new Camera camera;
private void Awake()
{
camera = GetComponent<Camera>();
}
/// <summary>
/// Установить размер камеры таким чтобы Bounds поместился целиком
/// </summary>
/// <param name="targetBounds"></param>
public void ScaleCamera(Bounds targetBounds)
{
float screenRatio = (float)Screen.width / (float)Screen.height;
float targetRatio = targetBounds.size.x / targetBounds.size.z;
if (screenRatio >= targetRatio)
{
camera.orthographicSize = targetBounds.size.z / 2 * margin;
}
else
{
float differenceInSize = targetRatio / screenRatio;
camera.orthographicSize = targetBounds.size.z / 2 * differenceInSize * margin;
}
transform.position = new Vector3(targetBounds.center.x, 1f, targetBounds.center.z);
}
}
|
namespace MonetDb.Mapi.Enums
{
/// <summary>
/// Enum definitions for the close Commands
/// </summary>
public enum CommandCloseStrategy
{
/// <summary>
/// None
/// </summary>
None = 0,
/// <summary>
/// Terminated Session
/// </summary>
TerminateSession
}
} |
using Newtonsoft.Json;
namespace Crimediggers.Geo.Console
{
public class WaypointContainer
{
[JsonProperty("wpt")]
public Waypoint[] Waypoints { get; set; }
}
}
|
using System;
namespace Agent.Plugins.TestResultParser.Plugin
{
public interface IBus<out TMessage>
{
/// <summary>
/// Subscribe to Message Bus to receive messages via Pub-Sub model
/// </summary>
Guid Subscribe(Action<TMessage> handlerAction);
/// <summary>
/// Unsubscribe to Message Bus so that subscriber no longer receives messages
/// </summary>
void Unsubscribe(Guid subscriptionId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StardewModdingAPI;
using StardewValley;
using xTile.Layers;
using xTile.Dimensions;
namespace Entoarox.Utilities.Internals
{
using Api;
using Helpers;
using Tools;
using xTile.Tiles;
internal class EntoUtilsMod : Mod
{
internal static EntoUtilsMod Instance;
public override void Entry(IModHelper helper)
{
helper.Events.GameLoop.GameLaunched += this.OnGameLoopGameLaunched;
helper.Events.World.LocationListChanged += this.OnLocationListChanged;
helper.Events.GameLoop.DayStarted += this.OnLocationListChanged;
//helper.ConsoleCommands.Add("emu_forcelayers", "Force-reloads all the custom layers.", (c, a) => this.OnLocationListChanged(null, null));
helper.Content.AssetLoaders.Add(new AssetHandlers.HelperSheetLoader());
Instance = this;
}
public override object GetApi()
{
return EntoUtilsApi.Instance;
}
private void OnLocationListChanged(object s, EventArgs e)
{
this.Monitor.StartTimer("ExtendedLayers", "Reloading extended layers...");
foreach(var location in Game1.locations)
{
var l = location.map.GetLayer("Back");
l.BeforeDraw -= this.ExtendedDrawBack;
l.BeforeDraw += this.ExtendedDrawBack;
var i = location.map.TileSheets.FirstOrDefault(_ => _.ImageSource.Contains("__EMU_HELPER_TILESHEET"));
if (i == null)
{
i = new TileSheet("__EMU_HELPER_TILESHEET", location.map, "__EMU_HELPER_TILESHEET", new Size(1, 1), new Size(16, 16));
location.map.AddTileSheet(i);
}
Parallel.For(0, l.LayerWidth, x =>
{
Parallel.For(0, l.LayerHeight, y =>
{
if (l.Tiles[x, y] == null)
l.Tiles[x, y] = new StaticTile(l, i, BlendMode.Additive, 0);
});
});
l = location.map.GetLayer("Buildings");
l.AfterDraw -= this.ExtendedDrawBuildings;
l.AfterDraw += this.ExtendedDrawBuildings;
l = location.map.GetLayer("Front");
l.BeforeDraw -= this.ExtendedDrawFront;
l.BeforeDraw += this.ExtendedDrawFront;
l = location.map.GetLayer("AlwaysFront");
if (l == null)
continue;
l.AfterDraw -= this.ExtendedDrawAlwaysFront;
l.AfterDraw += this.ExtendedDrawAlwaysFront;
}
this.Monitor.StopTimer("ExtendedLayers", "Reloaded extended layers in {{TIME}} milliseconds.");
}
private void ExtendedDrawBack(object s, LayerEventArgs e)
{
Game1.currentLocation?.Map.GetLayer("FarBack")?.Draw(Game1.mapDisplayDevice, Game1.viewport, Location.Origin, false, 4);
Game1.currentLocation?.Map.GetLayer("MidBack")?.Draw(Game1.mapDisplayDevice, Game1.viewport, Location.Origin, false, 4);
}
private void ExtendedDrawBuildings(object s, LayerEventArgs e)
{
Game1.currentLocation?.Map.GetLayer("Shadows")?.Draw(Game1.mapDisplayDevice, Game1.viewport, Location.Origin, false, 4);
}
private void ExtendedDrawFront(object s, LayerEventArgs e)
{
Game1.currentLocation?.Map.GetLayer("LowFront")?.Draw(Game1.mapDisplayDevice, Game1.viewport, Location.Origin, false, 4);
}
private void ExtendedDrawAlwaysFront(object s, LayerEventArgs e)
{
Game1.currentLocation?.Map.GetLayer("AlwaysFront2")?.Draw(Game1.mapDisplayDevice, Game1.viewport, Location.Origin, false, 4);
}
private void OnGameLoopGameLaunched(object s, EventArgs e)
{
this.Helper.Events.GameLoop.GameLaunched -= this.OnGameLoopGameLaunched;
try
{
this.Monitor.StartTimer("TypeId", "Initializing TypeId...");
// Register typeId's, both for vanilla and any mods that we explicitly support (if loaded)
var euApi = EntoUtilsApi.Instance;
Data.Init();
this.Monitor.Log("Initializing SDV TypeId support...");
euApi.RegisterItemTypeHandler("sdv.object", TypeHandlers.StardewObject);
euApi.RegisterItemTypeHandler("sdv.craftable", TypeHandlers.StardewCraftable);
euApi.RegisterItemTypeHandler("sdv.boots", TypeHandlers.StardewBoots);
euApi.RegisterItemTypeHandler("sdv.furniture", TypeHandlers.StardewFurniture);
euApi.RegisterItemTypeHandler("sdv.hat", TypeHandlers.StardewHat);
euApi.RegisterItemTypeHandler("sdv.ring", TypeHandlers.StardewRing);
euApi.RegisterItemTypeHandler("sdv.floor", TypeHandlers.StardewFloor);
euApi.RegisterItemTypeHandler("sdv.wallpaper", TypeHandlers.StardewWallpaper);
euApi.RegisterItemTypeHandler("sdv.weapon", TypeHandlers.StardewWeapon);
euApi.RegisterItemTypeHandler("sdv.clothing", TypeHandlers.StardewClothing);
euApi.RegisterItemTypeHandler("sdv.tool", TypeHandlers.StardewTool);
euApi.RegisterItemTypeHandler("sdv.artisan", TypeHandlers.StardewArtisan);
euApi.RegisterItemTypeResolver(TypeResolvers.StardewResolver);
/**
* Build-in compatibility for mods with public API's that the TypeId registry can hook into
* Mods which do not provide a public API will need to provide TypeId support from their end
*/
if (ModApi.IsLoadedAndApiAvailable<IJsonAssetsApi>("spacechase0.JsonAssets", out var jaApi))
{
this.Monitor.Log("JsonAssets detected, initializing TypeId support...");
Data.JaApi = jaApi;
euApi.RegisterItemTypeHandler("ja.object", TypeHandlers.JsonAssetsObject);
euApi.RegisterItemTypeHandler("ja.craftable", TypeHandlers.JsonAssetsCraftable);
euApi.RegisterItemTypeHandler("ja.hat", TypeHandlers.JsonAssetsHat);
euApi.RegisterItemTypeHandler("ja.weapon", TypeHandlers.JsonAssetsWeapon);
euApi.RegisterItemTypeHandler("ja.clothing", TypeHandlers.JsonAssetsClothing);
euApi.RegisterItemTypeResolver(TypeResolvers.JsonAssetsResolver);
}
if (ModApi.IsLoadedAndApiAvailable<ICustomFarmingApi>("Platonymous.CustomFarming", out var cfApi))
{
this.Monitor.Log("CustomFarmingRedux detected, initializing TypeId support...");
Data.CfApi = cfApi;
euApi.RegisterItemTypeHandler("cf.machine", TypeHandlers.CustomFarmingMachine);
}
if (ModApi.IsLoadedAndApiAvailable<IPrismaticToolsApi>("stokastic.PrismaticTools", out var ptApi))
{
this.Monitor.Log("PrismaticTools detected, initializing TypeId support...");
Data.PtApi = ptApi;
euApi.RegisterItemTypeHandler("pt.item", TypeHandlers.PrismaticToolsItem);
euApi.RegisterItemTypeResolver(TypeResolvers.PrismaticToolsResolver);
}
this.Monitor.StopTimer("TypeId", "TypeId initialization took {{TIME}} milliseconds.");
}
catch(Exception err)
{
this.Monitor.Log("TypeId failed to load due to a exception being thrown: \n" + err, LogLevel.Error);
}
this.OnLocationListChanged(null, null);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Gallery.Common.Security
{
public class ProtectedDataHelper
{
public static string ProtectString(string text, byte[] entropy = null)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
byte[] cipherBytes = ProtectedData.Protect(bytes, entropy, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(cipherBytes);
}
public static string UnProtectString(string text, byte[] entropy = null)
{
byte[] cipherBytes = Convert.FromBase64String(text);
byte[] bytes = ProtectedData.Unprotect(cipherBytes, entropy, DataProtectionScope.CurrentUser);
return Encoding.UTF8.GetString(bytes);
}
}
}
|
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("CQRSMagic")]
[assembly: AssemblyDescription("todo - assembly description")]
[assembly: InternalsVisibleTo("CQRSMagic.Specifications")] |
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.Extensions.NETCore.Setup;
using EasyDynamo.Abstractions;
using EasyDynamo.Config;
using EasyDynamo.Exceptions;
using EasyDynamo.Extensions.DependencyInjection;
using EasyDynamo.Tests.Fakes;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using System;
using System.Threading.Tasks;
using Xunit;
namespace EasyDynamo.Tests.Extensions.DependencyInjection
{
public class ServiceCollectionExtensionsTests
{
private readonly Mock<IDynamoContextOptions> contextOptionsMock;
private readonly Mock<IConfiguration> configurationMock;
private readonly IServiceCollection services;
public ServiceCollectionExtensionsTests()
{
this.contextOptionsMock = new Mock<IDynamoContextOptions>();
this.configurationMock = new Mock<IConfiguration>();
this.services = new ServiceCollection();
}
#region AddDynamoContext with only IConfiguration
[Fact]
public async Task AddDynamoContext_AddsAwsOptionsToServiceProvider()
{
this.contextOptionsMock
.SetupGet(o => o.Profile)
.Returns("ApplicationDevelopment");
this.contextOptionsMock
.SetupGet(o => o.LocalMode)
.Returns(false);
this.contextOptionsMock
.SetupGet(o => o.RegionEndpoint)
.Returns(RegionEndpoint.APNortheast1);
await TestRetrier.RetryAsync(() =>
{
services.AddDynamoContext<FakeDynamoContext>(this.configurationMock.Object);
var serviceProvider = this.services.BuildServiceProvider();
var awsOptions = serviceProvider.GetService<AWSOptions>();
Assert.NotNull(awsOptions);
});
}
[Fact]
public async Task AddDynamoContext_InvokesOnConfiguring()
{
this.contextOptionsMock
.SetupGet(o => o.Profile)
.Returns("ApplicationDevelopment");
this.contextOptionsMock
.SetupGet(o => o.LocalMode)
.Returns(false);
this.contextOptionsMock
.SetupGet(o => o.RegionEndpoint)
.Returns(RegionEndpoint.APNortheast1);
await TestRetrier.RetryAsync(() =>
{
FakeDynamoContext.OnConfiguringInvoked = false;
services.AddDynamoContext<FakeDynamoContext>(this.configurationMock.Object);
Assert.True(FakeDynamoContext.OnConfiguringInvoked);
});
}
[Fact]
public async Task AddDynamoContext_InvokesOnModelCreating()
{
this.contextOptionsMock
.SetupGet(o => o.Profile)
.Returns("ApplicationDevelopment");
this.contextOptionsMock
.SetupGet(o => o.LocalMode)
.Returns(false);
this.contextOptionsMock
.SetupGet(o => o.RegionEndpoint)
.Returns(RegionEndpoint.APNortheast1);
await TestRetrier.RetryAsync(() =>
{
FakeDynamoContext.OnModelCreatingInvoked = false;
services.AddDynamoContext<FakeDynamoContext>(this.configurationMock.Object);
Assert.True(FakeDynamoContext.OnModelCreatingInvoked);
});
}
[Fact]
public async Task AddDynamoContext_AddsContextToServicesAsSingleton()
{
this.contextOptionsMock
.SetupGet(o => o.Profile)
.Returns("ApplicationDevelopment");
this.contextOptionsMock
.SetupGet(o => o.LocalMode)
.Returns(false);
this.contextOptionsMock
.SetupGet(o => o.RegionEndpoint)
.Returns(RegionEndpoint.APNortheast1);
await TestRetrier.RetryAsync(() =>
{
services.AddDynamoContext<FakeDynamoContext>(this.configurationMock.Object);
Assert.Contains(this.services, s =>
s.ImplementationType == typeof(FakeDynamoContext) &&
s.Lifetime == ServiceLifetime.Singleton);
});
}
[Fact]
public async Task AddDynamoContext_AddsDynamoContextToServicesAsSingleton()
{
this.contextOptionsMock
.SetupGet(o => o.Profile)
.Returns("ApplicationDevelopment");
this.contextOptionsMock
.SetupGet(o => o.LocalMode)
.Returns(false);
this.contextOptionsMock
.SetupGet(o => o.RegionEndpoint)
.Returns(RegionEndpoint.APNortheast1);
await TestRetrier.RetryAsync(() =>
{
services.AddDynamoContext<FakeDynamoContext>(this.configurationMock.Object);
Assert.Contains(this.services, s =>
s.ServiceType == typeof(IDynamoDBContext) &&
s.ImplementationType == typeof(DynamoDBContext) &&
s.Lifetime == ServiceLifetime.Singleton);
});
}
[Fact]
public async Task AddDynamoContext_CloudMode_AddsDynamoClientToServices()
{
this.contextOptionsMock
.SetupGet(o => o.Profile)
.Returns("ApplicationDevelopment");
this.contextOptionsMock
.SetupGet(o => o.LocalMode)
.Returns(false);
this.contextOptionsMock
.SetupGet(o => o.RegionEndpoint)
.Returns(RegionEndpoint.APNortheast1);
await TestRetrier.RetryAsync(() =>
{
services.AddDynamoContext<FakeDynamoContext>(this.configurationMock.Object);
Assert.Contains(this.services, s =>
s.ServiceType == typeof(IAmazonDynamoDB) &&
s.ImplementationType == typeof(AmazonDynamoDBClient));
});
}
[Fact]
public async Task AddDynamoContext_LocalMode_AddsDynamoClientToServices()
{
this.contextOptionsMock
.SetupGet(o => o.Profile)
.Returns("ApplicationDevelopment");
this.contextOptionsMock
.SetupGet(o => o.LocalMode)
.Returns(false);
this.contextOptionsMock
.SetupGet(o => o.RegionEndpoint)
.Returns(RegionEndpoint.APNortheast1);
await TestRetrier.RetryAsync(() =>
{
services.AddDynamoContext<FakeDynamoContext>(this.configurationMock.Object);
Assert.Contains(this.services, s =>
s.ServiceType == typeof(IAmazonDynamoDB) &&
s.ImplementationType == typeof(AmazonDynamoDBClient));
});
}
#endregion
#region AddDynamoContext with ContextOptions and IConfiguration
[Fact]
public async Task AddDynamoContext_ValidOptions_AddsAwsOptionsToServiceProvider()
{
await TestRetrier.RetryAsync(() =>
{
services.AddDynamoContext<FakeDynamoContext>(
this.configurationMock.Object,
options =>
{
options.Profile = "ApplicationDevelopment";
options.LocalMode = false;
options.RegionEndpoint = RegionEndpoint.APNortheast1;
});
var serviceProvider = this.services.BuildServiceProvider();
var awsOptions = serviceProvider.GetService<AWSOptions>();
Assert.NotNull(awsOptions);
});
}
[Fact]
public async Task AddDynamoContext_ValidOptions_ContextAddedTwice_ThrowsException()
{
await TestRetrier.RetryAsync(() =>
{
services.AddDynamoContext<FakeDynamoContext>(
this.configurationMock.Object,
options =>
{
options.Profile = "ApplicationDevelopment";
options.LocalMode = false;
options.RegionEndpoint = RegionEndpoint.APNortheast1;
});
Assert.Throws<DynamoContextConfigurationException>(
() => services.AddDynamoContext<FakeDynamoContext>(
this.configurationMock.Object,
options =>
{
options.Profile = "ApplicationDevelopment";
options.LocalMode = false;
options.RegionEndpoint = RegionEndpoint.APNortheast1;
}));
});
}
[Fact]
public async Task AddDynamoContext_ValidOptions_InvokesOnConfiguring()
{
await TestRetrier.RetryAsync(() =>
{
FakeDynamoContext.OnConfiguringInvoked = false;
services.AddDynamoContext<FakeDynamoContext>(
this.configurationMock.Object,
options =>
{
options.Profile = "ApplicationDevelopment";
options.LocalMode = false;
options.RegionEndpoint = RegionEndpoint.APNortheast1;
});
services.AddDynamoContext<FakeDynamoContext>(this.configurationMock.Object);
Assert.True(FakeDynamoContext.OnConfiguringInvoked);
});
}
[Fact]
public async Task AddDynamoContext_ValidOptions_InvokesOnModelCreating()
{
await TestRetrier.RetryAsync(() =>
{
FakeDynamoContext.OnModelCreatingInvoked = false;
services.AddDynamoContext<FakeDynamoContext>(
this.configurationMock.Object,
options =>
{
options.Profile = "ApplicationDevelopment";
options.LocalMode = false;
options.RegionEndpoint = RegionEndpoint.APNortheast1;
});
Assert.True(FakeDynamoContext.OnModelCreatingInvoked);
});
}
[Fact]
public async Task AddDynamoContext_ValidOptions_AddsContextToServicesAsSingleton()
{
await TestRetrier.RetryAsync(() =>
{
services.AddDynamoContext<FakeDynamoContext>(
this.configurationMock.Object,
options =>
{
options.Profile = "ApplicationDevelopment";
options.LocalMode = false;
options.RegionEndpoint = RegionEndpoint.APNortheast1;
});
Assert.Contains(this.services, s =>
s.ImplementationType == typeof(FakeDynamoContext) &&
s.Lifetime == ServiceLifetime.Singleton);
});
}
[Fact]
public async Task AddDynamoContext_ValidOptions_AddsDynamoContextToServicesAsSingleton()
{
await TestRetrier.RetryAsync(() =>
{
services.AddDynamoContext<FakeDynamoContext>(
this.configurationMock.Object,
options =>
{
options.Profile = "ApplicationDevelopment";
options.LocalMode = false;
options.RegionEndpoint = RegionEndpoint.APNortheast1;
});
Assert.Contains(this.services, s =>
s.ServiceType == typeof(IDynamoDBContext) &&
s.ImplementationType == typeof(DynamoDBContext) &&
s.Lifetime == ServiceLifetime.Singleton);
});
}
[Fact]
public async Task AddDynamoContext_ValidOptionsAndCloudMode_AddsDynamoClientToServices()
{
await TestRetrier.RetryAsync(() =>
{
services.AddDynamoContext<FakeDynamoContext>(
this.configurationMock.Object,
options =>
{
options.Profile = "ApplicationDevelopment";
options.LocalMode = false;
options.RegionEndpoint = RegionEndpoint.APNortheast1;
});
Assert.Contains(this.services, s =>
s.ServiceType == typeof(IAmazonDynamoDB) &&
s.ImplementationType == typeof(AmazonDynamoDBClient));
});
}
[Fact]
public async Task AddDynamoContext_ValidOptionsAndLocalMode_AddsDynamoClientToServices()
{
await TestRetrier.RetryAsync(() =>
{
services.AddDynamoContext<FakeDynamoContext>(
this.configurationMock.Object,
options =>
{
options.Profile = "ApplicationDevelopment";
options.LocalMode = true;
options.RegionEndpoint = RegionEndpoint.APNortheast1;
});
Assert.Contains(this.services, s =>
s.ServiceType == typeof(IAmazonDynamoDB) &&
s.ImplementationType == typeof(AmazonDynamoDBClient));
});
}
[Fact]
public async Task AddDynamoContext_OptionsIsNull_ThrowsException()
{
await TestRetrier.RetryAsync(() =>
{
Assert.Throws<ArgumentNullException>(
() => services.AddDynamoContext<FakeDynamoContext>(
this.configurationMock.Object,
default(Action<DynamoContextOptions>)));
});
}
#endregion
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using java = biz.ritter.javapi;
namespace org.apache.harmony.awt.gl.color
{
internal class ColorScaler
{
private const float MAX_SHORT = 0xFFFF;
private const float MAX_XYZ = 1f + (32767f / 32768f);
// Cached values for scaling color data
private float[] channelMinValues = null;
private float[] channelMulipliers = null; // for scale
private float[] invChannelMulipliers = null; // for unscale
int nColorChannels = 0;
// For scaling rasters, false if transfer type is double or float
bool isTTypeIntegral = false;
/**
* Use this method only for double of float transfer types.
* Extracts scaling data from the color space signature
* and other tags, stored in the profile
* @param pf - ICC profile
*/
public void loadScalingData(java.awt.color.ICC_Profile pf)
{
// Supposing double or float transfer type
isTTypeIntegral = false;
nColorChannels = pf.getNumComponents();
// Get min/max values directly from the profile
// Very much like fillMinMaxValues in ICC_ColorSpace
float[] maxValues = new float[nColorChannels];
float[] minValues = new float[nColorChannels];
switch (pf.getColorSpaceType())
{
case java.awt.color.ColorSpace.TYPE_XYZ:
minValues[0] = 0;
minValues[1] = 0;
minValues[2] = 0;
maxValues[0] = MAX_XYZ;
maxValues[1] = MAX_XYZ;
maxValues[2] = MAX_XYZ;
break;
case java.awt.color.ColorSpace.TYPE_Lab:
minValues[0] = 0;
minValues[1] = -128;
minValues[2] = -128;
maxValues[0] = 100;
maxValues[1] = 127;
maxValues[2] = 127;
break;
default:
for (int i = 0; i < nColorChannels; i++)
{
minValues[i] = 0;
maxValues[i] = 1;
}
break;
}
channelMinValues = minValues;
channelMulipliers = new float[nColorChannels];
invChannelMulipliers = new float[nColorChannels];
for (int i = 0; i < nColorChannels; i++)
{
channelMulipliers[i] =
MAX_SHORT / (maxValues[i] - channelMinValues[i]);
invChannelMulipliers[i] =
(maxValues[i] - channelMinValues[i]) / MAX_SHORT;
}
}
/**
* Extracts scaling data from the color space
* @param cs - color space
*/
public void loadScalingData(java.awt.color.ColorSpace cs)
{
nColorChannels = cs.getNumComponents();
channelMinValues = new float[nColorChannels];
channelMulipliers = new float[nColorChannels];
invChannelMulipliers = new float[nColorChannels];
for (int i = 0; i < nColorChannels; i++)
{
channelMinValues[i] = cs.getMinValue(i);
channelMulipliers[i] =
MAX_SHORT / (cs.getMaxValue(i) - channelMinValues[i]);
invChannelMulipliers[i] =
(cs.getMaxValue(i) - channelMinValues[i]) / MAX_SHORT;
}
}
/**
* Scales one pixel and puts obtained values to the chanData
* @param pixelData - input pixel
* @param chanData - output buffer
* @param chanDataOffset - output buffer offset
*/
public void scale(float[] pixelData, short[] chanData, int chanDataOffset)
{
for (int chan = 0; chan < nColorChannels; chan++)
{
chanData[chanDataOffset + chan] =
(short)((pixelData[chan] - channelMinValues[chan]) *
channelMulipliers[chan] + 0.5f);
}
}
/**
* Unscales one pixel and puts obtained values to the pixelData
* @param pixelData - output pixel
* @param chanData - input buffer
* @param chanDataOffset - input buffer offset
*/
public void unscale(float[] pixelData, short[] chanData, int chanDataOffset)
{
for (int chan = 0; chan < nColorChannels; chan++)
{
pixelData[chan] = (chanData[chanDataOffset + chan] & 0xFFFF)
* invChannelMulipliers[chan] + channelMinValues[chan];
}
}
}
} |
namespace AMKsGear.Core.Automation.Mapper
{
public enum MappingType
{
ObjectMap,
QueryableProjection,
CollectionSynchronization,
Default = ObjectMap
}
} |
namespace AVRDisassembler.InstructionSet.OpCodes.Branch
{
public class ICALL : OpCode
{
public override string Comment => "Indirect Call to Subroutine";
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DecisionMaking.StateMachine;
public class Defending : TeamStateBehaviour
{
protected override void Enter()
{
base.Enter();
}
protected override void Execute()
{
base.Execute();
}
protected override void Exit()
{
base.Exit();
}
// Start is called before the first frame update
private void Start()
{
}
// Update is called once per frame
private void Update()
{
}
} |
using Aquality.Selenium.Elements.Interfaces;
using Aquality.Selenium.Forms;
using OpenQA.Selenium;
namespace Aquality.Selenium.Tests.Integration.TestApp.AutomationPractice.Forms
{
internal class AuthenticationForm : Form
{
public AuthenticationForm() : base(By.Id("email_create"), "Authentication")
{
}
private IButton CreateAccountButton => ElementFactory.GetButton(By.Id("SubmitCreate"), "Submit Create");
private ITextBox EmailTextBox => ElementFactory.GetTextBox(By.Id("email_create"), "Email Create");
public void ClickCreateAccountButton()
{
CreateAccountButton.ClickAndWait();
}
public void SetEmail(string email)
{
EmailTextBox.ClearAndType(email);
}
}
}
|
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace XamarinStudy11
{
public partial class StartPage : ContentPage
{
NavigationPage navi;
public StartPage()
{
InitializeComponent();
}
protected override void OnParentSet()
{
navi = Parent as NavigationPage;
}
void OnBindingClicked(object sender, EventArgs args)
{
navi.PushAsync(new BindingPattern());
}
void OnStyleClicked(object sender, EventArgs args)
{
navi.PushAsync(new ImplicitStylePattern());
}
}
}
|
@model TeamBins.Common.ViewModels.DashBoardVm
@{
ViewBag.Title = "Dashboard";
}
@if (!Model.IsCurrentUserTeamMember)
{
<div>
<div data-duration="10000" class="alert alert-info" role="alert">You are seeing a view only version of the dashboard because the admin of this dashbaord made it public-readonly visible. </div>
</div>
}
<div ng-app="teamBins" ng-controller="dashboardCtrl as vm" ng-cloak>
<div class="dbItemContainer">
<div class="dashboardItem">
<h4>At a glance {{summary1}}</h4>
<div class="dashboard-ataglance" ng-repeat="item in vm.summaryItems">
<span>{{item.itemName}}</span> <span>{{item.count}} </span>
</div>
</div>
<div class="dashboardItem">
<h4>Issues by status </h4>
<div id="pieChart">
<canvas id="myChart" width="200" height="200"></canvas>
<div class="db-pieChartLegends">
<ul class="legends">
<li ng-repeat="legend in vm.summaryItems">
<div class="db-chart-legend spn-new" style="background-color: {{legend.color}}"></div><span class="legendtext">{{legend.itemName}}</span>
</li>
</ul>
</div>
</div>
</div>
<div class="dashboardItem">
<h4>Issues by priority </h4>
<div id="issuesPriority">
<canvas id="issuesPriorityPieChart" width="200" height="200"></canvas>
<div class="db-pieChartLegends">
<ul class="legends">
<li ng-repeat="legend in vm.issuesGroupedByPriority">
<div class="db-chart-legend spn-new" style="background-color: {{legend.color}}"></div><span class="legendtext">{{legend.itemName}}</span>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="dbItemContainer">
@Html.Partial("Partials/_Widget-RecentIssues")
@Html.Partial("Partials/_Widget-OverdueIssuesAssignedToMe")
@Html.Partial("Partials/_Widget-IssuesAssignedToMe")
@Html.Partial("Partials/_Widget-Projects")
<div class="dashboardItem">
<h4>Issues by Project</h4>
<table class="table table-condensed">
<tr ng-repeat="item in vm.issuesGroupedByProject">
<td>{{item.itemName}}</td>
<td><b>{{item.count}}</b></td>
<td>{{item.percentage}}%</td>
</tr>
</table>
</div>
</div>
<div class="dbItemContainer">
<div class="dashboardItem">
<h4>Team Activity</h4>
<ul class="db-recent-activity">
<li ng-repeat="activity in vm.activities | orderBy:'createdTime':true">
<a href="#" class="activity-author">{{activity.actor.name}}</a> {{activity.description}}
<a href="@Url.Content("~")/{{activity.objectUrl}}" class="activity-name">{{activity.objectTitle}}</a>
<i>{{activity.newState}}</i>
<p class="activity-date">{{activity.createdTime | date:'medium'}}</p>
</li>
</ul>
</div>
<div class="dashboardItem">
<h4>TeamBins news</h4>
<p>No news now !</p>
</div>
</div>
</div>
@Html.HiddenFor(s => s.TeamId)
@section Scripts
{
@*<script src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
<script src="~/signalr/hubs"></script>*@
@*<script src="~/Scripts/Chart.min.js"></script>*@
<script src="~/js/dashboardcontroller.js"></script>
<script src="~/js/dashboardservice.js"></script>
@*<script src="~/signalr/hubs"></script>*@
<script src="~/js/chart.min.js"></script>
<script type="text/javascript">
appInsights.trackEvent("Dashboard view");
var a = angular.module("teamBins")
.service('summaryService', TeamBins.DashboardService)
.controller("dashboardCtrl", TeamBins.DashboardController);
// TeamBins.DashboardController.inject = ['$http', 'issueDetailService'];
angular.module("teamBins").value("pageContext", @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
//$.connection.hub.start()
// .done(function() {
// chat.server.subscribeToTeam($("#TeamID").val());
// });
</script>
}
|
using System;
namespace ArduinoMajoro
{
public class Arduino : IEquatable<Arduino>
{
public Arduino(string name, string serialPort)
{
Name = name;
SerialPort = serialPort;
}
public string Name { get; private set; }
public string SerialPort { get; private set; }
public bool Equals(Arduino other)
{
return Name == other.Name && SerialPort == other.SerialPort;
}
public override int GetHashCode()
{
return Name.GetHashCode() + SerialPort.GetHashCode();
}
}
}
|
namespace Popcron.Sheets
{
public enum AuthorizationType
{
Key,
AccessToken
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis;
internal readonly record struct ParsedDocument(DocumentId Id, SourceText Text, SyntaxNode Root)
{
public SyntaxTree SyntaxTree => Root.SyntaxTree;
public static async ValueTask<ParsedDocument> CreateAsync(Document document, CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return new ParsedDocument(document.Id, text, root);
}
#if !CODE_STYLE
public static ParsedDocument CreateSynchronously(Document document, CancellationToken cancellationToken)
{
var text = document.GetTextSynchronously(cancellationToken);
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
return new ParsedDocument(document.Id, text, root);
}
#endif
}
|
namespace _04.Random_List
{
using System;
using System.Collections;
public class RandomList : ArrayList
{
private Random rdn;
public RandomList()
{
this.rdn = new Random();
}
public int randomInteger()
{
return this.rdn.Next();
}
public int randomString() => randomInteger();
}
}
|
/*
Copyright 2018 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Extensions;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
namespace PlaceText
{
internal class PlaceTextTool : MapTool
{
public PlaceTextTool()
{
IsSketchTool = true;
SketchType = SketchGeometryType.Point;
SketchOutputMode = SketchOutputMode.Map;
}
protected override Task OnToolActivateAsync(bool active)
{
return base.OnToolActivateAsync(active);
}
protected override Task OnToolDeactivateAsync(bool hasMapViewChanged)
{
foreach(var graphic in Module1.Current.Graphics)
{
graphic.Dispose();
}
Module1.Current.Graphics.Clear();
return Task.CompletedTask;
}
protected override Task<bool> OnSketchCompleteAsync(Geometry geometry)
{
return QueuedTask.Run(() =>
{
//MapView.Active.AddOverlay()
var textGraphic = new CIMTextGraphic();
textGraphic.Symbol = SymbolFactory.Instance.ConstructTextSymbol(
ColorFactory.Instance.BlackRGB, 12, "Times New Roman", "Regular").MakeSymbolReference();
//make the callout for the circle
var callOut = new CIMPointSymbolCallout();
callOut.PointSymbol = new CIMPointSymbol();
//Circle outline - 40
var circle_outline = SymbolFactory.Instance.ConstructMarker(40, "ESRI Default Marker") as CIMCharacterMarker;
//Square - 41
//Triangle - 42
//Pentagon - 43
//Hexagon - 44
//Octagon - 45
circle_outline.Size = 40;
//eliminate the outline
foreach (var layer in circle_outline.Symbol.SymbolLayers)
{
if (layer is CIMSolidStroke)
{
((CIMSolidStroke)layer).Width = 0;
}
}
//Circle fill - 33
var circle_fill = SymbolFactory.Instance.ConstructMarker(33, "ESRI Default Marker") as CIMCharacterMarker;
//Square - 34
//Triangle - 35
//Pentagon - 36
//Hexagon - 37
//Octagon - 38
circle_fill.Size = 40;
//eliminate the outline, make sure the fill is white
foreach (var layer in circle_fill.Symbol.SymbolLayers)
{
if (layer is CIMSolidFill)
{
((CIMSolidFill)layer).Color = ColorFactory.Instance.WhiteRGB;
}
else if (layer is CIMSolidStroke)
{
((CIMSolidStroke)layer).Width = 0;
}
}
var calloutLayers = new List<CIMSymbolLayer>();
calloutLayers.Add(circle_outline);
calloutLayers.Add(circle_fill);
//set the layers on the callout
callOut.PointSymbol.SymbolLayers = calloutLayers.ToArray();
//set the callout on the text symbol
var textSym = textGraphic.Symbol.Symbol as CIMTextSymbol;
textSym.Callout = callOut;
textSym.Height = 12;//adjust as needed
//now set the text
textGraphic.Text = "12 <SUP><UND>00</UND></SUP>";
textGraphic.Shape = geometry;
var graphic = MapView.Active.AddOverlay(textGraphic);
Module1.Current.Graphics.Add(graphic);
return true;
});
}
}
}
|
using System;
namespace LaubPlusCo.Foundation.HelixTemplating.Manifest
{
public class ManifestTypeInstantiator
{
internal T CreateInstance<T>(string typeAttribute)
{
var type = Type.GetType(typeAttribute);
if (type == null) throw new ArgumentException("Cannot find type " + typeAttribute);
var instance = (T)Activator.CreateInstance(type);
if (instance != null) return instance;
throw new ArgumentException($"Cannot cast {typeAttribute} as {typeof(T).FullName}");
}
}
} |
using System;
namespace LogoFX.Client.Mvvm.ViewModel
{
/// <summary>
/// Child Operation Event Arguments
/// </summary>
/// <typeparam name="T"> type of child</typeparam>
public class ChildEventArgs<T> : EventArgs
{
private readonly ChildOperation _operation;
private readonly T _item;
private readonly int _index;
/// <summary>
/// Constructor
/// </summary>
/// <param name="operation"></param>
/// <param name="item"></param>
/// <param name="index"></param>
public ChildEventArgs(ChildOperation operation, T item, int index)
{
_operation = operation;
_item = item;
_index = index;
}
/// <summary>
/// Added item
/// </summary>
public T Item { get { return _item; } }
/// <summary>
/// Changed index
/// </summary>
public int Index { get { return _index; } }
/// <summary>
/// Gets the action.
/// </summary>
/// <value>The action.</value>
public ChildOperation Action
{
get { return _operation; }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 10.0f;
public float drag = 0.5f;
public float terminalRotationSpeed = 25.0f;
public Vector3 MoveVector { set; get; }
public VirtualJoystick joystick;
private Rigidbody thisRigidbody;
void Start()
{
thisRigidbody = gameObject.GetComponent<Rigidbody>();
thisRigidbody.maxAngularVelocity = terminalRotationSpeed;
thisRigidbody.drag = drag;
}
void Update()
{
MoveVector = PoolInput();
Move();
}
private void Move()
{
thisRigidbody.AddForce(MoveVector * moveSpeed);
}
private Vector3 PoolInput()
{
Vector3 dir = Vector3.zero;
dir.x = joystick.Horizontal();
dir.z = joystick.Vertical();
if (dir.magnitude > 1)
dir.Normalize();
return dir;
}
}
|
using System;
using UnityEngine;
// Token: 0x02000027 RID: 39
public class SE_Harpooned : StatusEffect
{
// Token: 0x060003AC RID: 940 RVA: 0x0001EF30 File Offset: 0x0001D130
public override void Setup(Character character)
{
base.Setup(character);
}
// Token: 0x060003AD RID: 941 RVA: 0x0001F45C File Offset: 0x0001D65C
public override void SetAttacker(Character attacker)
{
ZLog.Log("Setting attacker " + attacker.m_name);
this.m_attacker = attacker;
this.m_time = 0f;
if (this.m_character.IsBoss())
{
this.m_broken = true;
return;
}
if (Vector3.Distance(this.m_attacker.transform.position, this.m_character.transform.position) > this.m_maxDistance)
{
this.m_attacker.Message(MessageHud.MessageType.Center, "Target too far", 0, null);
this.m_broken = true;
return;
}
this.m_attacker.Message(MessageHud.MessageType.Center, this.m_character.m_name + " harpooned", 0, null);
foreach (GameObject gameObject in this.m_startEffectInstances)
{
if (gameObject)
{
LineConnect component = gameObject.GetComponent<LineConnect>();
if (component)
{
component.SetPeer(this.m_attacker.GetComponent<ZNetView>());
}
}
}
}
// Token: 0x060003AE RID: 942 RVA: 0x0001F554 File Offset: 0x0001D754
public override void UpdateStatusEffect(float dt)
{
base.UpdateStatusEffect(dt);
if (!this.m_attacker)
{
return;
}
Rigidbody component = this.m_character.GetComponent<Rigidbody>();
if (component)
{
Vector3 vector = this.m_attacker.transform.position - this.m_character.transform.position;
Vector3 normalized = vector.normalized;
float radius = this.m_character.GetRadius();
float magnitude = vector.magnitude;
float num = Mathf.Clamp01(Vector3.Dot(normalized, component.velocity));
float t = Utils.LerpStep(this.m_minDistance, this.m_maxDistance, magnitude);
float num2 = Mathf.Lerp(this.m_minForce, this.m_maxForce, t);
float num3 = Mathf.Clamp01(this.m_maxMass / component.mass);
float num4 = num2 * num3;
if (magnitude - radius > this.m_minDistance && num < num4)
{
normalized.y = 0f;
normalized.Normalize();
if (this.m_character.GetStandingOnShip() == null && !this.m_character.IsAttached())
{
component.AddForce(normalized * num4, ForceMode.VelocityChange);
}
this.m_drainStaminaTimer += dt;
if (this.m_drainStaminaTimer > this.m_staminaDrainInterval)
{
this.m_drainStaminaTimer = 0f;
float num5 = 1f - Mathf.Clamp01(num / num2);
this.m_attacker.UseStamina(this.m_staminaDrain * num5);
}
}
if (magnitude > this.m_maxDistance)
{
this.m_broken = true;
this.m_attacker.Message(MessageHud.MessageType.Center, "Line broke", 0, null);
}
if (!this.m_attacker.HaveStamina(0f))
{
this.m_broken = true;
this.m_attacker.Message(MessageHud.MessageType.Center, this.m_character.m_name + " escaped", 0, null);
}
}
}
// Token: 0x060003AF RID: 943 RVA: 0x0001F730 File Offset: 0x0001D930
public override bool IsDone()
{
if (base.IsDone())
{
return true;
}
if (this.m_broken)
{
return true;
}
if (!this.m_attacker)
{
return true;
}
if (this.m_time > 2f && (this.m_attacker.IsBlocking() || this.m_attacker.InAttack()))
{
this.m_attacker.Message(MessageHud.MessageType.Center, this.m_character.m_name + " released", 0, null);
return true;
}
return false;
}
// Token: 0x04000399 RID: 921
[Header("SE_Harpooned")]
public float m_minForce = 2f;
// Token: 0x0400039A RID: 922
public float m_maxForce = 10f;
// Token: 0x0400039B RID: 923
public float m_minDistance = 6f;
// Token: 0x0400039C RID: 924
public float m_maxDistance = 30f;
// Token: 0x0400039D RID: 925
public float m_staminaDrain = 10f;
// Token: 0x0400039E RID: 926
public float m_staminaDrainInterval = 0.1f;
// Token: 0x0400039F RID: 927
public float m_maxMass = 50f;
// Token: 0x040003A0 RID: 928
private bool m_broken;
// Token: 0x040003A1 RID: 929
private Character m_attacker;
// Token: 0x040003A2 RID: 930
private float m_drainStaminaTimer;
}
|
namespace PetStore.Services
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PetStore.Data;
using PetStore.Data.Models;
public class PetsService : IPetsService
{
private readonly ApplicationDbContext dbContext;
public PetsService(ApplicationDbContext dbContext)
{
this.dbContext = dbContext;
}
public IEnumerable<KeyValuePair<string, string>> GetByKeyValuePairs()
{
return this.dbContext
.Pets
.Select(p => new
{
Id = p.Id,
Name = p.Name,
})
.OrderBy(p => p.Name)
.ToList().Select(p => new KeyValuePair<string, string>(p.Id, p.Name));
}
}
}
|
namespace Edi.Core.Converters.MessageType
{
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
[ValueConversion(typeof(Msg.MsgCategory), typeof(ImageSource))]
public class MsgTypeToResourceConverter : IValueConverter
{
#region IValueConverter Members
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Check input parameter types
if (value == null)
return Binding.DoNothing;
if (!(value is Msg.MsgCategory))
throw new ArgumentException("Invalid argument. Expected argument: ViewModel.Base.Msg.MsgType");
if (targetType != typeof(ImageSource))
throw new ArgumentException("Invalid return type. Expected return type: System.Windows.Media.ImageSource");
string resourceUri = "Images/MessageIcons/Unknown.png";
switch ((Msg.MsgCategory) value)
{
case Msg.MsgCategory.Information:
break;
case Msg.MsgCategory.Error:
resourceUri = "Images/MessageIcons/Error.png";
break;
case Msg.MsgCategory.Warning:
resourceUri = "Images/MessageIcons/Warning.png";
break;
case Msg.MsgCategory.InternalError:
resourceUri = "Images/MessageIcons/InternalError.png";
break;
default:
resourceUri = "Images/MessageIcons/Unknown.png";
break;
}
BitmapImage icon = new BitmapImage();
try
{
icon.BeginInit();
icon.UriSource = new Uri(string.Format(CultureInfo.InvariantCulture, "pack://application:,,,/{0};component/{1}",
"Themes", resourceUri));
icon.EndInit();
}
catch
{
return Binding.DoNothing;
}
return icon;
}
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is Visibility val && targetType == typeof(bool))
{
return val == Visibility.Visible;
}
throw new ArgumentException("Invalid argument/return type. Expected argument: Visibility and return type: bool");
}
#endregion
}
} |
@model MySqlASPNetMVC.Models.Pessoa
@{
ViewBag.Title = "Detalhe Pessoa";
}
<div class="page-header">
<h1>Pessoa <small>organize o cadastro de pessoas</small></h1>
<a href="@Url.Action("Cadastrar","Pessoa")" class="btn btn-sm btn-primary">Nova Pessoa</a>
</div>
<fieldset>
<legend>Detalhes da Pessoa</legend>
<div class="form-group">
<strong>Nome: </strong> @Model.Nome
</div>
</fieldset>
<hr />
<p>
<a href="@Url.Action("Editar","Home", new{Id=Model.Id})" class="btn btn-sm btn-info">Editar</a>
<a href="@Url.Action("Index","Home")">Voltar</a>
</p> |
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SSMLVerifier;
using SSMLVerifier.Extensions;
using SSMLVerifier.TagStrategies.Amazon;
namespace SSMLVerifierTests.TagStrategies.Amazon
{
[TestClass]
public class PhonemeStrategyTests
{
[TestMethod]
public void ReturnValidForValidTag()
{
var element = "<phoneme alphabet=\"ipa\" ph=\"ˈpi.kæn\">pecan</phoneme>".ToXElement();
var strategy = new PhonemeStrategy();
var errors = strategy.Verify(element);
Assert.AreEqual(0, errors.Count());
}
[TestMethod]
public void ReturnInvalidForMissingAttributeAlphabet()
{
var element = "<phoneme ph=\"ˈpi.kæn\">pecan</phoneme>".ToXElement();
var strategy = new PhonemeStrategy();
var errors = strategy.Verify(element);
Assert.AreEqual(VerificationState.MissingAttribute, errors.First().State);
}
[TestMethod]
public void ReturnInvalidForMissingAttributePh()
{
var element = "<phoneme alphabet=\"ipa\">pecan</phoneme>".ToXElement();
var strategy = new PhonemeStrategy();
var errors = strategy.Verify(element);
Assert.AreEqual(VerificationState.MissingAttribute, errors.First().State);
}
[TestMethod]
public void ReturnInvalidForInvalidAttributeValue()
{
var element = "<phoneme alphabet=\"ipa2\" ph=\"ˈpi.kæn\">pecan</phoneme>".ToXElement();
var strategy = new PhonemeStrategy();
var errors = strategy.Verify(element);
Assert.AreEqual(VerificationState.InvalidAttributeValue, errors.First().State);
}
}
} |
using AzR.Utilities.Attributes;
namespace AzR.Core.Config
{
[IgnoreEntity]
public interface IBaseEntity
{
}
} |
using Cosmos.HAL.Drivers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cosmos.System
{
public class VBEScreen
{
/// <summary>
/// Driver for Setting vbe modes and ploting/getting pixels
/// </summary>
private VBEDriver _vbe = new VBEDriver();
/// <summary>
/// The current Width of the screen in pixels
/// </summary>
public int ScreenWidth { get; set; }
/// <summary>
/// The current Height of the screen in pixels
/// </summary>
public int ScreenHeight { get; set; }
/// <summary>
/// The current Bytes per pixel
/// </summary>
public int ScreenBpp { get; set; }
#region Display
/// <summary>
/// All the avalible screen resolutions
/// </summary>
public enum ScreenSize
{
Size320x200,
Size640x400,
Size640x480,
Size800x600,
Size1024x768,
Size1280x1024
}
/// <summary>
/// All the suported Bytes per pixel
/// </summary>
public enum Bpp
{
Bpp15,
Bpp16,
Bpp24,
Bpp32
}
/// <summary>
/// Use this to setup the screen, this will disable the console.
/// </summary>
/// <param name="aSize">The dezired screen resolution</param>
/// <param name="aBpp">The dezired Bytes per pixel</param>
public void SetMode(ScreenSize aSize, Bpp aBpp)
{
//Get screen size
switch (aSize)
{
case ScreenSize.Size320x200:
ScreenWidth = 320;
ScreenHeight = 200;
break;
case ScreenSize.Size640x400:
ScreenWidth = 640;
ScreenHeight = 400;
break;
case ScreenSize.Size640x480:
ScreenWidth = 640;
ScreenHeight = 480;
break;
case ScreenSize.Size800x600:
ScreenWidth = 800;
ScreenHeight = 600;
break;
case ScreenSize.Size1024x768:
ScreenWidth = 1024;
ScreenHeight = 768;
break;
case ScreenSize.Size1280x1024:
ScreenWidth = 1280;
ScreenHeight = 1024;
break;
}
//Get bpp
switch (aBpp)
{
case Bpp.Bpp15:
ScreenBpp = 15;
break;
case Bpp.Bpp16:
ScreenBpp = 16;
break;
case Bpp.Bpp24:
ScreenBpp = 24;
break;
case Bpp.Bpp32:
ScreenBpp = 32;
break;
}
//set the screen
_vbe.vbe_set((ushort)ScreenWidth, (ushort)ScreenHeight, (ushort)ScreenBpp);
}
#endregion
#region Drawing
//used to convert from rgb to hex color
private uint GetIntFromRBG(byte red, byte green, byte blue)
{
uint x;
x = (blue);
x += (uint)(green << 8);
x += (uint)(red << 16);
return x;
}
/// <summary>
/// Clear the screen with a given color
/// </summary>
/// <param name="color">The color in hex</param>
public void Clear(uint color)
{
for (uint x = 0; x < ScreenWidth; x++)
{
for (uint y = 0; y < ScreenHeight; y++)
{
SetPixel(x, y, color);
}
}
}
/// <summary>
/// Clear the screen with a given color
/// </summary>
/// <param name="red">Red value max is 255</param>
/// <param name="green">Green value max is 255</param>
/// <param name="blue">Blue value max is 255</param>
public void Clear(byte red, byte green, byte blue)
{
Clear(GetIntFromRBG(red, green, blue));
}
/// <summary>
/// Set a pixel at a given point to the give color
/// </summary>
/// <param name="x">X coordinate</param>
/// <param name="y">Y coordinate</param>
/// <param name="color">Color in hex</param>
public void SetPixel(uint x, uint y, uint color)
{
uint where = x * ((uint)ScreenBpp / 8) + y * (uint)(ScreenWidth * ((uint)ScreenBpp / 8));
_vbe.set_vram(where, (byte)(color & 255)); // BLUE
_vbe.set_vram(where + 1, (byte)((color >> 8) & 255)); // GREEN
_vbe.set_vram(where + 2, (byte)((color >> 16) & 255)); // RED
}
/// <summary>
/// Set a pixel at a given point to the give color
/// </summary>
/// <param name="x">X coordinate</param>
/// <param name="y">Y coordinate</param>
/// <param name="red">Red value max is 255</param>
/// <param name="green">Green value max is 255</param>
/// <param name="blue">Blue value max is 255</param>
public void SetPixel(uint x, uint y, byte red, byte green, byte blue)
{
SetPixel(x, y, GetIntFromRBG(red, green, blue));
}
#endregion
#region Reading
/// <summary>
/// Get a pixel's color at the given point
/// </summary>
/// <param name="x">X coordinate</param>
/// <param name="y"></param>
/// <returns>Returns the color in hex</returns>
public uint GetPixel(uint x, uint y)
{
uint where = x * ((uint)ScreenBpp / 8) + y * (uint)(ScreenWidth * ((uint)ScreenBpp / 8));
return GetIntFromRBG(_vbe.get_vram(where + 2), _vbe.get_vram(where + 1), _vbe.get_vram(where));
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// the class that contains the waypoint info to serialize
/// </summary>
[System.Serializable]
public class Point {
// Enums
public enum PointType
{
TakeOff = 0,
WayPoint,
Stop,
Land,
};
public enum RecMode
{
Photo = 0,
Video
};
// Variables
public int id;
[SerializeField]
float speed = 0;
[SerializeField]
Vector3 coordinates;
[SerializeField]
PointType point_type;
[SerializeField]
uint stopTime = 0; //ms
Transform pointTransf;
Transform poi;
int segmentsTop;
int segmentsRight;
/// <summary>
/// Number of points between waypoints in the curve drawn on the top camera
/// </summary>
public int SegmentsTop
{
get { return segmentsTop; }
set { segmentsTop = value; }
}
/// <summary>
/// Number of points between waypoints in the curve drawn on the front camera
/// </summary>
public int SegmentsRight
{
get { return segmentsRight; }
set { segmentsRight = value; }
}
public Transform Poi
{
get { return Poi1; }
set {
Poi1 = value;
}
}
// Getters & Setters
public int Id
{
get { return id; }
set { id = value; }
}
public Transform PointTransf
{
get { return PointTransf1; }
set { PointTransf1 = value; }
}
public float Speed
{
get
{
return speed;
}
set
{
speed = value;
}
}
public Transform PointTransf1
{
get
{
return pointTransf;
}
set
{
pointTransf = value;
}
}
public Transform Poi1
{
get
{
return poi;
}
set
{
poi = value;
}
}
public Vector3 PointPosition
{
get
{
return coordinates;
}
set
{
coordinates = value;
}
}
public uint StopTime
{
get
{
return stopTime;
}
set
{
stopTime = value;
}
}
public PointType getPointType()
{
return point_type;
}
public void setPointType(PointType type)
{
point_type = type;
}
public Point(Transform transf)
{
PointTransf1 = transf;
PointPosition = transf.position;
Speed = 0;
}
// Custom functions
}
|
using PlayFab;
using PlayFab.ClientModels;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Core : Entity
{
void Start()
{
base.Start();
}
protected override void OnDead(GameObject killer)
{
GameObject.FindObjectOfType<GameState>().Gameover();
}
}
|
using System;
using System.Runtime.InteropServices;
namespace TidyDesktopMonster.WinApi.Shell32
{
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb759795.aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 2)]
internal struct ShellFileOptions
{
public IntPtr handle;
public FileOperation func;
[MarshalAs(UnmanagedType.LPWStr)]
public string from;
[MarshalAs(UnmanagedType.LPWStr)]
public string to;
public FileOperationFlags flags;
[MarshalAs(UnmanagedType.Bool)]
public bool anyOperationsAborted;
public IntPtr nameMappings;
[MarshalAs(UnmanagedType.LPWStr)]
public string progressTitle;
}
}
|
using System.Collections.Generic;
namespace AdapterPattern.DBOperations
{
interface IAdapter<T> where T : class
{
List<T> GetData(string tableName);
}
}
|
using UnityEngine;
public class ApplicationSettings : MonoBehaviour
{
[SerializeField]
private int _targetFrameRate = 60;
[SerializeField]
private int _sleepTimeout = SleepTimeout.SystemSetting;
private void Awake()
{
Screen.sleepTimeout = _sleepTimeout;
Application.targetFrameRate = _targetFrameRate;
}
}
|
using OpenTracker.Models.Sections;
namespace OpenTracker.ViewModels.Maps.Locations
{
public interface IMarkingMapLocationVM
{
delegate IMarkingMapLocationVM Factory(IMarkableSection section);
}
} |
using BLL.Infrastructure;
using Microsoft.AspNetCore.Mvc;
namespace RL.Utilities
{
public static class ControllerUtilities
{
public static ActionResult CheckResult(Result result)
{
if (result.Failure)
return new BadRequestObjectResult(result.Error);
return new OkResult();
}
public static ActionResult<T> CheckResult<T>(Result<T> result)
{
if (result.Failure)
return new BadRequestObjectResult(result.Error);
return new OkObjectResult(result.Value);
}
}
} |
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace AirCannon.Framework.Tests.Utilities
{
/// <summary>
/// Verifies the methods on <see cref = "Assert2" /> work correctly.
/// </summary>
[TestFixture]
public class Assert2Tests
{
/// <summary>
/// Verifies that <see cref = "Assert2.ContainsKeyAndValue{TKey,TValue}" /> throws the
/// correct exception when the expected key is missing.
/// </summary>
[Test, ExpectedException(typeof (AssertionException))]
public void ContainsKeyAndValueKeyMissingTest()
{
var dictionary = new Dictionary<string, string> {{"A", "B"}};
Assert2.ContainsKeyAndValue(dictionary, "B", "B");
}
/// <summary>
/// Verifies that <see cref = "Assert2.ContainsKeyAndValue{TKey,TValue}" /> does not
/// throw an exception when the key and value are in the dictionary.
/// </summary>
[Test]
public void ContainsKeyAndValueSuccessfulTest()
{
var dictionary = new Dictionary<string, string> {{"A", "B"}};
Assert2.ContainsKeyAndValue(dictionary, "A", "B");
}
/// <summary>
/// Verifies that <see cref = "Assert2.ContainsKeyAndValue{TKey,TValue}" /> throws the
/// correct exception when the expected value is wrong.
/// </summary>
[Test, ExpectedException(typeof (AssertionException))]
public void ContainsKeyAndValueValueWrongTest()
{
var dictionary = new Dictionary<string, string> {{"A", "A"}};
Assert2.ContainsKeyAndValue(dictionary, "A", "B");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BreakableGroundWalk : MonoBehaviour
{
public AudioClip settle;
public AudioSource source;
public ParticleSystem dust;
public void OnTriggerEnter2D(Collider2D other){
if(other.tag == "Player"){
source.PlayOneShot(settle,0.1f);
dust.Play();
}
}
}
|
using CY.Core.Regularization;
using CY.Core.Service;
using System;
using System.Collections.Generic;
using System.Text;
namespace CY.Application.Service
{
public class AccessWEB:IAccesscs
{
private List<string> result;
private LotteryDataRegularization _regularization;
public AccessWEB()
{
result = new List<string>();
_regularization = new LotteryDataRegularization();
}
public List<string> getPrizeNumber(string year, string month)
{
month = _regularization.regularizeMonth(month);
string urlAddress = "https://www.etax.nat.gov.tw/etw-main/web/ETW183W2_" +
year + month + "/";
WebService webService = new WebService();
string html = webService.getHTML(urlAddress, Encoding.UTF8);
if (html != "")
{
HtmlService htmlService = new HtmlService(html);
result = htmlService.getPrizeNumber();
}
return result;
}
}
}
|
using UnityEngine;
namespace Character
{
public class PlayerInventory : MonoBehaviour
{
[SerializeField] private Inventory playerInventory;
private void Awake()
{
if (GlobalInventory.playerInventoryInstance == null)
{
GlobalInventory.playerInventoryInstance = playerInventory;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
} |
// Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace DotNetFramework.CAP.Diagnostics
{
public class TracingHeaders : IEnumerable<KeyValuePair<string, string>>
{
private List<KeyValuePair<string, string>> _dataStore = new List<KeyValuePair<string, string>>();
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return _dataStore.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(string name, string value)
{
_dataStore.Add(new KeyValuePair<string, string>(name, value));
}
public bool Contains(string name)
{
return _dataStore != null && _dataStore.Any(x => x.Key == name);
}
public void Remove(string name)
{
_dataStore?.RemoveAll(x => x.Key == name);
}
public void Cleaar()
{
_dataStore?.Clear();
}
}
}
|
namespace PlayMe.Plumbing.Diagnostics
{
public class Logger : NLog.Logger, ILogger
{
}
}
|
using OpenTK.Windowing.GraphicsLibraryFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VengineX.Core;
namespace VengineX.Input
{
public class MouseActionBinding : Binding<bool>
{
public MouseButton Button { get; set; }
public MouseActionBinding(MouseButton button)
{
Button = button;
}
public override void UpdateValue(InputManager input)
{
MouseState ms = input.MouseState;
Value = ms.IsButtonDown(Button);
}
}
}
|
namespace Battleship.Model
{
public class GuessRequest
{
public Cell Cell { get; set; }
public string GameState { get; set; }
}
} |
using System.Collections.Generic;
namespace API_Football.SDK.V3
{
public static class Venues
{
public static ApiResponse<List<Models.Venue>> GetVenues(this Instance instance)
{
return instance.DoCall<List<Models.Venue>>("venues");
}
}
} |
using Microsoft.Data.SqlClient;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RepoDb.Extensions;
using RepoDb.IntegrationTests.Models;
using RepoDb.IntegrationTests.Setup;
using System;
using System.Collections.Generic;
using System.Linq;
namespace RepoDb.IntegrationTests.Operations
{
[TestClass]
public class InsertAllTest
{
[TestInitialize]
public void Initialize()
{
Database.Initialize();
Cleanup();
}
[TestCleanup]
public void Cleanup()
{
Database.Cleanup();
}
#region InsertAll<TEntity>
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableViaEntityTableName()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<IdentityTable>(ClassMappedNameCache.Get<IdentityTable>(),
tables);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableViaEntityTableNameWithFields()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<IdentityTable>(ClassMappedNameCache.Get<IdentityTable>(),
tables,
fields: Field.From(nameof(IdentityTable.Id), nameof(IdentityTable.RowGuid), nameof(IdentityTable.ColumnNVarChar)));
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Assert.AreEqual(table.RowGuid, entity.RowGuid);
Assert.AreEqual(table.ColumnNVarChar, entity.ColumnNVarChar);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTable()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<IdentityTable>(tables);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableWithFields()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<IdentityTable>(tables,
fields: Field.From(nameof(IdentityTable.Id), nameof(IdentityTable.RowGuid), nameof(IdentityTable.ColumnNVarChar)));
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Assert.AreEqual(table.RowGuid, entity.RowGuid);
Assert.AreEqual(table.ColumnNVarChar, entity.ColumnNVarChar);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllWithSizePerBatchEqualsToOneForIdentityTable()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<IdentityTable>(tables,
1);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForNonIdentityTable()
{
// Setup
var tables = Helper.CreateNonIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<NonIdentityTable>(tables);
// Act
var result = connection.QueryAll<NonIdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllWithSizePerBatchEqualsToOneForNonIdentityTable()
{
// Setup
var tables = Helper.CreateNonIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<NonIdentityTable>(tables,
1);
// Act
var result = connection.QueryAll<NonIdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableWithHints()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<IdentityTable>(tables,
hints: SqlServerTableHints.TabLock);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
#endregion
#region InsertAll<TEntity>(Extra Fields)
[TestMethod]
public void TestSqlConnectionInsertAllWithExtraFields()
{
// Setup
var tables = Helper.CreateWithExtraFieldsIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<WithExtraFieldsIdentityTable>(tables);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllWithSizePerBatchEqualsToOneAndWithExtraFields()
{
// Setup
var tables = Helper.CreateWithExtraFieldsIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<WithExtraFieldsIdentityTable>(tables,
1);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
#endregion
#region InsertAllAsync<TEntity>
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableViaEntityTableName()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<IdentityTable>(ClassMappedNameCache.Get<IdentityTable>(),
tables).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableViaEntityTableNameWithFields()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<IdentityTable>(ClassMappedNameCache.Get<IdentityTable>(),
tables,
fields: Field.From(nameof(IdentityTable.Id), nameof(IdentityTable.RowGuid), nameof(IdentityTable.ColumnNVarChar))).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Assert.AreEqual(table.RowGuid, entity.RowGuid);
Assert.AreEqual(table.ColumnNVarChar, entity.ColumnNVarChar);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTable()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<IdentityTable>(tables).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableWithFields()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<IdentityTable>(tables,
fields: Field.From(nameof(IdentityTable.Id), nameof(IdentityTable.RowGuid), nameof(IdentityTable.ColumnNVarChar))).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Assert.AreEqual(table.RowGuid, entity.RowGuid);
Assert.AreEqual(table.ColumnNVarChar, entity.ColumnNVarChar);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncWithSizePerBatchEqualsToOneForIdentityTable()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<IdentityTable>(tables,
1).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForNonIdentityTable()
{
// Setup
var tables = Helper.CreateNonIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<NonIdentityTable>(tables).Wait();
// Act
var result = connection.QueryAll<NonIdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncWithSizePerBatchEqualsToOneForNonIdentityTable()
{
// Setup
var tables = Helper.CreateNonIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<NonIdentityTable>(tables,
1).Wait();
// Act
var result = connection.QueryAll<NonIdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableWithHints()
{
// Setup
var tables = Helper.CreateIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<IdentityTable>(tables,
hints: SqlServerTableHints.TabLock).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
#endregion
#region InsertAll<TEntity>(Extra Fields)
[TestMethod]
public void TestSqlConnectionInsertAllAsyncWithExtraFields()
{
// Setup
var tables = Helper.CreateWithExtraFieldsIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<WithExtraFieldsIdentityTable>(tables).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllWithSizePerBatchEqualsToOneAsyncWithExtraFields()
{
// Setup
var tables = Helper.CreateWithExtraFieldsIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<WithExtraFieldsIdentityTable>(tables,
1).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count());
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(r => r.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
#endregion
#region InsertAll(TableName)
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableViaDynamicTableName()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<object>(ClassMappedNameCache.Get<IdentityTable>(),
tables);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableViaDynamicTableNameWithFields()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<object>(ClassMappedNameCache.Get<IdentityTable>(),
tables,
fields: Field.From(nameof(IdentityTable.Id), nameof(IdentityTable.RowGuid), nameof(IdentityTable.ColumnNVarChar)));
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Assert.AreEqual(table.RowGuid, entity.RowGuid);
Assert.AreEqual(table.ColumnNVarChar, entity.ColumnNVarChar);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableViaExpandoOjectTableName()
{
// Setup
var tables = Helper.CreateExpandoObjectIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<object>(ClassMappedNameCache.Get<IdentityTable>(),
tables);
// Assert
tables.ForEach(table => Assert.IsTrue(((dynamic)table).Id > 0));
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var currentItem = (dynamic)table;
var entity = result.FirstOrDefault(item => item.Id == currentItem.Id);
Helper.AssertPropertiesEquality(entity, table);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableViaExpandoOjectTableNameWithFields()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll<object>(ClassMappedNameCache.Get<IdentityTable>(),
tables,
fields: Field.From(nameof(IdentityTable.Id), nameof(IdentityTable.RowGuid), nameof(IdentityTable.ColumnNVarChar)));
// Assert
tables.ForEach(table => Assert.IsTrue(((dynamic)table).Id > 0));
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var currentItem = (dynamic)table;
var entity = result.FirstOrDefault(item => item.Id == currentItem.Id);
Assert.AreEqual(currentItem.RowGuid, entity.RowGuid);
Assert.AreEqual(currentItem.ColumnNVarChar, entity.ColumnNVarChar);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableViaTableName()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(ClassMappedNameCache.Get<IdentityTable>(),
tables);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableViaTableNameWithFields()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(ClassMappedNameCache.Get<IdentityTable>(),
tables,
fields: Field.From(nameof(IdentityTable.Id), nameof(IdentityTable.RowGuid), nameof(IdentityTable.ColumnNVarChar)));
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Assert.AreEqual(table.RowGuid, entity.RowGuid);
Assert.AreEqual(table.ColumnNVarChar, entity.ColumnNVarChar);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllWithSizePerBatchEqualsToOneForIdentityTableViaTableName()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(ClassMappedNameCache.Get<IdentityTable>(),
tables,
1);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableViaTableNameWithLimitedColumns()
{
// Setup
var tables = Helper.CreateDynamicIdentityTablesWithLimitedColumns(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(ClassMappedNameCache.Get<IdentityTable>(),
tables.Item1,
fields: tables.Item2);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Item1.Count, result.Count);
tables.Item1.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllWithSizePerBatchEqualsToOneForIdentityTableViaTableNameWithLimitedColumns()
{
// Setup
var tables = Helper.CreateDynamicIdentityTablesWithLimitedColumns(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(ClassMappedNameCache.Get<IdentityTable>(),
tables.Item1,
1,
fields: tables.Item2);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Item1.Count, result.Count);
tables.Item1.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForNonIdentityTableViaTableName()
{
// Setup
var tables = Helper.CreateDynamicNonIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(ClassMappedNameCache.Get<NonIdentityTable>(),
tables);
// Act
var result = connection.QueryAll(ClassMappedNameCache.Get<NonIdentityTable>()).AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllWithSizePerBatchEqualsToOneForNonIdentityTableViaTableName()
{
// Setup
var tables = Helper.CreateDynamicNonIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(ClassMappedNameCache.Get<NonIdentityTable>(),
tables,
1);
// Act
var result = connection.QueryAll(ClassMappedNameCache.Get<NonIdentityTable>()).AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForNonIdentityTableViaTableNameWithLimitedColumns()
{
// Setup
var tables = Helper.CreateDynamicNonIdentityTablesWithLimitedColumns(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(ClassMappedNameCache.Get<NonIdentityTable>(),
tables.Item1,
fields: tables.Item2);
// Act
var result = connection.QueryAll(ClassMappedNameCache.Get<NonIdentityTable>()).AsList();
// Assert
Assert.AreEqual(tables.Item1.Count, result.Count);
tables.Item1.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllWithSizePerBatchEqualsToOneForNonIdentityTableViaTableNameWithLimitedColumns()
{
// Setup
var tables = Helper.CreateDynamicNonIdentityTablesWithLimitedColumns(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(ClassMappedNameCache.Get<NonIdentityTable>(),
tables.Item1,
1,
fields: tables.Item2);
// Act
var result = connection.QueryAll<NonIdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Item1.Count, result.Count);
tables.Item1.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableViaTableNameWithIncompleteProperties()
{
// Setup
var tables = new List<dynamic>
{
new {RowGuid = Guid.NewGuid(),ColumnBit = true,ColumnInt = 1},
new {RowGuid = Guid.NewGuid(),ColumnBit = true,ColumnInt = 2},
new {RowGuid = Guid.NewGuid(),ColumnBit = true,ColumnInt = 3}
};
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var insertAllResult = connection.InsertAll(ClassMappedNameCache.Get<IdentityTable>(),
tables);
// Act
var result = connection.QueryAll(ClassMappedNameCache.Get<IdentityTable>()).AsList();
// Assert
Assert.AreEqual(tables.Count(), result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.RowGuid == table.RowGuid);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllForIdentityTableViaTableNameWithHints()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(ClassMappedNameCache.Get<IdentityTable>(),
tables,
hints: SqlServerTableHints.TabLock);
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
#endregion
#region InsertAllAsync(TableName)
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableViaDynamicTableName()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<object>(ClassMappedNameCache.Get<IdentityTable>(),
tables).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableViaDynamicTableNameWithFields()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<object>(ClassMappedNameCache.Get<IdentityTable>(),
tables,
fields: Field.From(nameof(IdentityTable.Id), nameof(IdentityTable.RowGuid), nameof(IdentityTable.ColumnNVarChar))).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Assert.AreEqual(table.RowGuid, entity.RowGuid);
Assert.AreEqual(table.ColumnNVarChar, entity.ColumnNVarChar);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableViaExpandoOjectTableName()
{
// Setup
var tables = Helper.CreateExpandoObjectIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<object>(ClassMappedNameCache.Get<IdentityTable>(),
tables).Wait();
// Assert
tables.ForEach(table => Assert.IsTrue(((dynamic)table).Id > 0));
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var currentItem = (dynamic)table;
var entity = result.FirstOrDefault(item => item.Id == currentItem.Id);
Helper.AssertPropertiesEquality(entity, table);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableViaExpandoOjectTableNameWithFields()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync<object>(ClassMappedNameCache.Get<IdentityTable>(),
tables,
fields: Field.From(nameof(IdentityTable.Id), nameof(IdentityTable.RowGuid), nameof(IdentityTable.ColumnNVarChar))).Wait();
// Assert
tables.ForEach(table => Assert.IsTrue(((dynamic)table).Id > 0));
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var currentItem = (dynamic)table;
var entity = result.FirstOrDefault(item => item.Id == currentItem.Id);
Assert.AreEqual(currentItem.RowGuid, entity.RowGuid);
Assert.AreEqual(currentItem.ColumnNVarChar, entity.ColumnNVarChar);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableViaTableName()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync(ClassMappedNameCache.Get<IdentityTable>(),
tables).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableViaTableNameWithFields()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync(ClassMappedNameCache.Get<IdentityTable>(),
tables,
fields: Field.From(nameof(IdentityTable.Id), nameof(IdentityTable.RowGuid), nameof(IdentityTable.ColumnNVarChar))).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Assert.AreEqual(table.RowGuid, entity.RowGuid);
Assert.AreEqual(table.ColumnNVarChar, entity.ColumnNVarChar);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncWithSizePerBatchEqualsToOneForIdentityTableViaTableName()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync(ClassMappedNameCache.Get<IdentityTable>(),
tables,
1).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableViaTableNameWithLimitedColumns()
{
// Setup
var tables = Helper.CreateDynamicIdentityTablesWithLimitedColumns(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync(ClassMappedNameCache.Get<IdentityTable>(),
tables.Item1,
fields: tables.Item2).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Item1.Count, result.Count);
tables.Item1.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncWithSizePerBatchEqualsToOneForIdentityTableViaTableNameWithLimitedColumns()
{
// Setup
var tables = Helper.CreateDynamicIdentityTablesWithLimitedColumns(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync(ClassMappedNameCache.Get<IdentityTable>(),
tables.Item1,
1,
fields: tables.Item2).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Item1.Count, result.Count);
tables.Item1.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForNonIdentityTableViaTableName()
{
// Setup
var tables = Helper.CreateDynamicNonIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync(ClassMappedNameCache.Get<NonIdentityTable>(),
tables).Wait();
// Act
var result = connection.QueryAll(ClassMappedNameCache.Get<NonIdentityTable>()).AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncWithSizePerBatchEqualsToOneForNonIdentityTableViaTableName()
{
// Setup
var tables = Helper.CreateDynamicNonIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync(ClassMappedNameCache.Get<NonIdentityTable>(),
tables,
1).Wait();
// Act
var result = connection.QueryAll(ClassMappedNameCache.Get<NonIdentityTable>()).AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForNonIdentityTableViaTableNameWithLimitedColumns()
{
// Setup
var tables = Helper.CreateDynamicNonIdentityTablesWithLimitedColumns(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync(ClassMappedNameCache.Get<NonIdentityTable>(),
tables.Item1,
fields: tables.Item2).Wait();
// Act
var result = connection.QueryAll(ClassMappedNameCache.Get<NonIdentityTable>()).AsList();
// Assert
Assert.AreEqual(tables.Item1.Count, result.Count);
tables.Item1.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncWithSizePerBatchEqualsToOneForNonIdentityTableViaTableNameWithLimitedColumns()
{
// Setup
var tables = Helper.CreateDynamicNonIdentityTablesWithLimitedColumns(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync(ClassMappedNameCache.Get<NonIdentityTable>(),
tables.Item1,
1,
fields: tables.Item2).Wait();
// Act
var result = connection.QueryAll<NonIdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Item1.Count, result.Count);
tables.Item1.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableViaTableNameWithIncompleteProperties()
{
// Setup
var tables = new List<dynamic>
{
new {RowGuid = Guid.NewGuid(),ColumnBit = true,ColumnInt = 1},
new {RowGuid = Guid.NewGuid(),ColumnBit = true,ColumnInt = 2},
new {RowGuid = Guid.NewGuid(),ColumnBit = true,ColumnInt = 3}
};
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var insertAllResult = connection.InsertAllAsync(ClassMappedNameCache.Get<IdentityTable>(),
tables).Result;
// Act
var result = connection.QueryAll(ClassMappedNameCache.Get<IdentityTable>()).AsList();
// Assert
Assert.AreEqual(tables.Count(), result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.RowGuid == table.RowGuid);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
[TestMethod]
public void TestSqlConnectionInsertAllAsyncForIdentityTableViaTableNameWithHints()
{
// Setup
var tables = Helper.CreateDynamicIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAllAsync(ClassMappedNameCache.Get<IdentityTable>(),
tables,
hints: SqlServerTableHints.TabLock).Wait();
// Act
var result = connection.QueryAll<IdentityTable>().AsList();
// Assert
Assert.AreEqual(tables.Count, result.Count);
tables.ForEach(table =>
{
var entity = result.FirstOrDefault(item => item.Id == table.Id);
Helper.AssertPropertiesEquality(table, entity);
});
}
}
#endregion
}
}
|
using CarDealership.Models.DataModels;
using CarDealership.Models.DataModels.Adds.Vehicles;
using CarDealership.Models.DataModels.Comments;
using CarDealership.Models.DataModels.Extras;
using CarDealership.Models.DataModels.News;
using CarDealership.Models.DataModels.Pictures;
using CarDealership.Models.DataModels.Vehicles;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace CarDealership.Data
{
public class DealershipDbContext : IdentityDbContext<DealershipUser>
{
public DealershipDbContext(DbContextOptions<DealershipDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(Configuration.ConnectionString);
optionsBuilder.UseLazyLoadingProxies();
}
}
public DbSet<CarAdd> CarAdds { get; set; }
public DbSet<Car> Cars { get; set; }
public DbSet<NewsClass> News { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<CarExtra> CarExtras { get; set; }
public DbSet<CarPicture> CarPictures { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
} |
using System.Collections.Generic;
using CommandDotNet.Tokens;
namespace CommandDotNet
{
public class OriginalInput
{
/// <summary>The original string array passed to the program</summary>
public IReadOnlyCollection<string> Args { get; }
/// <summary>The original tokens before any input transformations were applied</summary>
public TokenCollection Tokens { get; }
public OriginalInput(string[] args, TokenCollection tokens)
{
Args = args;
Tokens = tokens;
}
}
} |
namespace WindowsFormsApplication1
{
partial class Form1
{
/// <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.maskTC = new System.Windows.Forms.Label();
this.maskTelefon = new System.Windows.Forms.Label();
this.maskDTarih = new System.Windows.Forms.Label();
this.maskKart = new System.Windows.Forms.Label();
this.maskIp = new System.Windows.Forms.Label();
this.maskedTextBox1 = new System.Windows.Forms.MaskedTextBox();
this.maskedTextBox2 = new System.Windows.Forms.MaskedTextBox();
this.maskedTextBox3 = new System.Windows.Forms.MaskedTextBox();
this.maskedTextBox4 = new System.Windows.Forms.MaskedTextBox();
this.maskedTextBox5 = new System.Windows.Forms.MaskedTextBox();
this.SuspendLayout();
//
// maskTC
//
this.maskTC.AutoSize = true;
this.maskTC.Location = new System.Drawing.Point(117, 48);
this.maskTC.Name = "maskTC";
this.maskTC.Size = new System.Drawing.Size(31, 13);
this.maskTC.TabIndex = 0;
this.maskTC.Text = "tc.no";
//
// maskTelefon
//
this.maskTelefon.AutoSize = true;
this.maskTelefon.Location = new System.Drawing.Point(117, 71);
this.maskTelefon.Name = "maskTelefon";
this.maskTelefon.Size = new System.Drawing.Size(39, 13);
this.maskTelefon.TabIndex = 1;
this.maskTelefon.Text = "telefon";
//
// maskDTarih
//
this.maskDTarih.AutoSize = true;
this.maskDTarih.Location = new System.Drawing.Point(104, 97);
this.maskDTarih.Name = "maskDTarih";
this.maskDTarih.Size = new System.Drawing.Size(64, 13);
this.maskDTarih.TabIndex = 2;
this.maskDTarih.Text = "doğum tarihi";
//
// maskKart
//
this.maskKart.AutoSize = true;
this.maskKart.Location = new System.Drawing.Point(117, 123);
this.maskKart.Name = "maskKart";
this.maskKart.Size = new System.Drawing.Size(40, 13);
this.maskKart.TabIndex = 3;
this.maskKart.Text = "kart no";
//
// maskIp
//
this.maskIp.AutoSize = true;
this.maskIp.Location = new System.Drawing.Point(117, 147);
this.maskIp.Name = "maskIp";
this.maskIp.Size = new System.Drawing.Size(44, 13);
this.maskIp.TabIndex = 4;
this.maskIp.Text = "ıp adres";
this.maskIp.Click += new System.EventHandler(this.label5_Click);
//
// maskedTextBox1
//
this.maskedTextBox1.Location = new System.Drawing.Point(184, 45);
this.maskedTextBox1.Name = "maskedTextBox1";
this.maskedTextBox1.Size = new System.Drawing.Size(100, 20);
this.maskedTextBox1.TabIndex = 10;
//
// maskedTextBox2
//
this.maskedTextBox2.Location = new System.Drawing.Point(184, 71);
this.maskedTextBox2.Name = "maskedTextBox2";
this.maskedTextBox2.Size = new System.Drawing.Size(100, 20);
this.maskedTextBox2.TabIndex = 11;
//
// maskedTextBox3
//
this.maskedTextBox3.Location = new System.Drawing.Point(184, 97);
this.maskedTextBox3.Name = "maskedTextBox3";
this.maskedTextBox3.Size = new System.Drawing.Size(100, 20);
this.maskedTextBox3.TabIndex = 12;
//
// maskedTextBox4
//
this.maskedTextBox4.Location = new System.Drawing.Point(184, 123);
this.maskedTextBox4.Name = "maskedTextBox4";
this.maskedTextBox4.Size = new System.Drawing.Size(100, 20);
this.maskedTextBox4.TabIndex = 13;
//
// maskedTextBox5
//
this.maskedTextBox5.Location = new System.Drawing.Point(167, 149);
this.maskedTextBox5.Name = "maskedTextBox5";
this.maskedTextBox5.Size = new System.Drawing.Size(100, 20);
this.maskedTextBox5.TabIndex = 14;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(712, 261);
this.Controls.Add(this.maskedTextBox5);
this.Controls.Add(this.maskedTextBox4);
this.Controls.Add(this.maskedTextBox3);
this.Controls.Add(this.maskedTextBox2);
this.Controls.Add(this.maskedTextBox1);
this.Controls.Add(this.maskIp);
this.Controls.Add(this.maskKart);
this.Controls.Add(this.maskDTarih);
this.Controls.Add(this.maskTelefon);
this.Controls.Add(this.maskTC);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label maskTC;
private System.Windows.Forms.Label maskTelefon;
private System.Windows.Forms.Label maskDTarih;
private System.Windows.Forms.Label maskKart;
private System.Windows.Forms.Label maskIp;
private System.Windows.Forms.MaskedTextBox maskedTextBox1;
private System.Windows.Forms.MaskedTextBox maskedTextBox2;
private System.Windows.Forms.MaskedTextBox maskedTextBox3;
private System.Windows.Forms.MaskedTextBox maskedTextBox4;
private System.Windows.Forms.MaskedTextBox maskedTextBox5;
}
}
|
namespace Opendentity.Emails;
public static class EmailConstants
{
public static class ReplacementMarks
{
public static class PasswordReset
{
public const string _PasswordTokenMark = "{{PASSWORD_TOKEN}}";
public const string _EmailMark = "{{EMAIL}}";
public const string _PortalUrlMark = "{{PORTAL_URL}}";
}
public static class Confirmation
{
public const string _VerifyTokenMark = "{{VERIFY_TOKEN}}";
public const string _EmailMark = "{{EMAIL}}";
public const string _PortalUrlMark = "{{PORTAL_URL}}";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CEWSP_v2.Backend
{
/// <summary>
/// Provide information about the given CE version
/// </summary>
public class CEVersionInfo
{
/// <summary>
/// Path to the 64bit executable of CE
/// </summary>
public string ExecPath { get; private set; }
/// <summary>
/// The major version number of this CE (3.8.1 yields 3)
/// </summary>
public int MajorVersion { get; private set; }
/// <summary>
/// The minor version number of this CE (3.8.1 yields 8)
/// </summary>
public int MinorVersion { get; private set; }
/// <summary>
/// The subversion number of this CE (3.8.1 yields 1)
/// </summary>
public int SubVersion { get; private set; }
/// <summary>
/// Constructs a new version info object for the given path
/// </summary>
/// <param name="sExecPath">Path to the 64bit editor executable</param>
public CEVersionInfo(string sExecPath)
{
var info = new FileInfo(sExecPath);
if (!info.Exists)
{
throw new ArgumentException("Path is valid but file doesn't exist", "sExecPath");
}
this.ExecPath = sExecPath;
var versionInfo = FileVersionInfo.GetVersionInfo(info.FullName);
this.MajorVersion = versionInfo.FileMajorPart;
this.MinorVersion = versionInfo.FileMinorPart;
this.SubVersion = versionInfo.FileBuildPart;
}
}
}
|
using System;
using GraphProcessor;
using HLVS.Runtime;
using UnityEngine;
namespace HLVS.Nodes.ActionNodes
{
[Serializable, NodeMenuItem("Transform/Move Towards")]
public class MoveTowardNode : HlvsActionNode
{
public override string name => "Move Towards";
[Input("Object")]
public GameObject target;
[Input("Destination")]
public GameObject destination;
[Input("Duration")]
[LargerThan(0.0f)]
public float duration = 1;
private float _endTime = 0;
public override void Reset()
{
_endTime = 0;
}
public override ProcessingStatus Evaluate()
{
if (_endTime == 0)
{
Init();
}
if (IsFinished())
{
target.transform.position = destination.transform.position;
return ProcessingStatus.Finished;
}
else
{
Vector3 destinationPos = destination.transform.position;
Vector3 currPos = target.transform.position;
float distance = Vector3.Distance(destinationPos, currPos);
float remainingTime = _endTime - Time.time;
float neededSpeed = distance / remainingTime;
Vector3 direction = (destinationPos - currPos).normalized;
target.transform.position += direction * neededSpeed * Time.deltaTime;
return ProcessingStatus.Unfinished;
}
}
private bool IsFinished()
{
return Time.time >= _endTime;
}
private void Init()
{
_endTime = Time.time + duration;
}
}
[Serializable, NodeMenuItem("Transform/Rotate")]
public class RotateNode : HlvsActionNode
{
public override string name => "Rotate";
[Input("Object")]
public GameObject target;
[Input("Angles")]
public Vector3 angles;
[Input("Duration")]
[LargerThan(0.0f)]
public float duration = 1;
private float _endTime = 0;
private Vector3 _startEuler;
public enum Axis
{
X,
Y,
Z,
}
public override void Reset()
{
_endTime = 0;
}
public override ProcessingStatus Evaluate()
{
if (_endTime == 0)
{
Init();
}
if (IsFinished())
{
target.transform.rotation = Quaternion.Euler(angles);
;
return ProcessingStatus.Finished;
}
else
{
float remainingTimeNormalized = 1 - (_endTime - Time.time) / duration;
Vector3 lerpResult = Vector3.Lerp(_startEuler, angles, remainingTimeNormalized);
target.transform.rotation = Quaternion.Euler(lerpResult);
return ProcessingStatus.Unfinished;
}
}
private bool IsFinished()
{
return Time.time >= _endTime;
}
private void Init()
{
_endTime = Time.time + duration;
_startEuler = target.transform.rotation.eulerAngles;
}
}
[Serializable, NodeMenuItem("Transform/Scale")]
public class ScaleNode : HlvsActionNode
{
public override string name => "Scale";
[Input("Object")]
public GameObject target;
[Input("Scaling")]
public float scaling = 1;
[Input("Duration")]
[LargerThan(0.0f)]
public float duration = 1;
private float _endTime = 0;
private Vector3 _startScale, _targetScale;
public override void Reset()
{
_endTime = 0;
}
public override ProcessingStatus Evaluate()
{
if (_endTime == 0)
{
Init();
}
if (IsFinished())
{
target.transform.localScale = _targetScale;
return ProcessingStatus.Finished;
}
else
{
float remainingTimeNormalized = 1 - (_endTime - Time.time) / duration;
Vector3 lerpResult = Vector3.Lerp(_startScale, _targetScale, remainingTimeNormalized);
target.transform.localScale = lerpResult;
return ProcessingStatus.Unfinished;
}
}
private bool IsFinished()
{
return Time.time >= _endTime;
}
private void Init()
{
_endTime = Time.time + duration;
_startScale = target.transform.localScale;
_targetScale = _startScale * scaling;
}
}
[Serializable, NodeMenuItem("Transform/Move To Direction")]
public class MoveDirectionNode : HlvsActionNode
{
public override string name => "Move To Direction";
[Input("Object")]
public GameObject target;
[Input("Direction")]
public Vector3 direction;
[Input("Orientation")]
public CoordSystem orientation;
public enum CoordSystem
{
Global, Local,
}
public override ProcessingStatus Evaluate()
{
if (!target)
{
Debug.LogError("No gameobject to move was given");
return ProcessingStatus.Finished;
}
var rb = target.GetComponent<Rigidbody>();
if (rb)
{
switch (orientation)
{
case CoordSystem.Global:
rb.MovePosition(target.transform.position + Time.deltaTime * direction);
break;
case CoordSystem.Local:
var movement = target.transform.rotation * direction;
rb.MovePosition(target.transform.position + Time.deltaTime * movement);
break;
}
} else
{
switch (orientation)
{
case CoordSystem.Global:
target.transform.position += Time.deltaTime * direction;
break;
case CoordSystem.Local:
var movement = target.transform.rotation * direction;
target.transform.position += Time.deltaTime * movement;
break;
}
}
return ProcessingStatus.Finished;
}
}
[Serializable, NodeMenuItem("Transform/Rotate To Direction")]
public class RotateToDirectionNode : HlvsActionNode
{
public override string name => "Rotate To Direction";
[Input("Object")]
public GameObject target;
[Input("Direction")]
public Vector3 direction;
[Input("Speed")] [LargerOrEqual(0)]
public float smoothAmount = 120.0f;
public override ProcessingStatus Evaluate()
{
if (!target)
{
Debug.LogError("No gameobject to move was given");
return ProcessingStatus.Finished;
}
if(direction.sqrMagnitude != 0)
{
var rot = Quaternion.LookRotation(direction);
rot = Quaternion.RotateTowards(target.transform.rotation, rot, smoothAmount * Time.deltaTime);
target.transform.rotation = rot;
}
return ProcessingStatus.Finished;
}
}
[Serializable, NodeMenuItem("Transform/Parent To")]
public class ParentNode : HlvsActionNode
{
public override string name => "Parent To";
[Input("Parent")]
public GameObject parent;
[Input("Child")]
public GameObject child;
public override ProcessingStatus Evaluate()
{
child.transform.SetParent(parent.transform, true);
return ProcessingStatus.Finished;
}
}
} |
// Copyright (c) Allan Nielsen.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace OurPresence.Modeller.Interfaces
{
/// <summary>
/// Defines the files to be used as a project
/// </summary>
public interface IProject : IOutput
{
/// <summary>
/// The files within the project that should be generated
/// </summary>
IEnumerable<IFileGroup> FileGroups { get; }
/// <summary>
/// The files within the project that should be copied
/// </summary>
IEnumerable<IFolderCopy> Folders { get; }
/// <summary>
/// Relative path if used within a <see cref="ISolution"/> otherwise a full path
/// </summary>
string Path { get; set; }
/// <summary>
/// Project Id as used by Visual Studio
/// </summary>
Guid Id { get; }
IOutput AddFileGroup(IOutput output);
void AddFolder(IOutput output);
}
}
|
using SiteManager.V4.Application.Common.Exceptions;
using SiteManager.V4.Application.RoleAdmin.Queries;
using SiteManager.V4.Domain.Entities;
using FluentAssertions;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using SiteManager.V4.Infrastructure.Identity;
namespace SiteManager.V4.Application.IntegrationTests.RoleAdmin.Queries
{
using static Testing;
public class GetRolesTests : TestBase
{
[Test, Order(2)]
public async Task ShouldReturnTestRoles()
{
var userId = await RunAsDefaultUserAsync();
var command = new GetAllRolesQuery();
var userList = await SendAsync(command);
userList.Should().HaveCount(3);
}
}
} |
namespace CryptoCurrency.Core.OrderType
{
public enum OrderTypeEnum
{
Limit,
Market
}
} |
using System;
using System.Net.Http.Headers;
using System.Text;
namespace SourceLink
{
public interface IAuthenticationHeaderValueProvider
{
AuthenticationHeaderValue GetValue();
}
internal class BasicAuthenticationHeaderValueProvider : IAuthenticationHeaderValueProvider
{
private readonly string _username;
private readonly string _password;
private readonly Encoding _encoding;
public BasicAuthenticationHeaderValueProvider(string username, string password, Encoding encoding = null)
{
if (string.IsNullOrWhiteSpace(username)) throw new ArgumentNullException(nameof(username),"Invalid username value");
if (string.IsNullOrWhiteSpace(password)) throw new ArgumentNullException(nameof(password),"Invalid password value");
_username = username;
_password = password;
_encoding = encoding ?? Encoding.ASCII;
}
public AuthenticationHeaderValue GetValue()
{
return new AuthenticationHeaderValue("Basic", Convert.ToBase64String(_encoding.GetBytes($"{_username}:{_password}")));
}
}
}
|
using Xunit;
namespace Tests.CefGlue.WebBrowserEngineTests.Infra
{
[CollectionDefinition("CefGlue Context")]
public class CefGlueContextFixture : ICollectionFixture<CefGlueContext>
{
}
} |
#region copyright
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************
#endregion
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Inventory.Data;
using Inventory.Models;
namespace Inventory.Services
{
public class LogService : ILogService
{
public LogService(IMessageService messageService)
{
MessageService = messageService;
}
public IMessageService MessageService { get; }
public async Task WriteAsync(LogType type, string source, string action, Exception ex)
{
await WriteAsync(LogType.Error, source, action, ex.Message, ex.ToString());
Exception deepException = ex.InnerException;
while(deepException!=null)
{
await WriteAsync(LogType.Error, source, action, deepException.Message, deepException.ToString());
deepException = deepException.InnerException;
}
}
public async Task WriteAsync(LogType type, string source, string action, string message, string description)
{
var appLog = new AppLog()
{
User = AppSettings.Current.UserName ?? "App",
Type = type,
Source = source,
Action = action,
Message = message,
Description = description,
};
appLog.IsRead = type != LogType.Error;
await CreateLogAsync(appLog);
MessageService.Send(this, "LogAdded", appLog);
}
private AppLogDb CreateDataSource()
{
return new AppLogDb(AppSettings.Current.AppLogConnectionString);
}
public async Task<AppLogModel> GetLogAsync(long id)
{
using (var ds = CreateDataSource())
{
var item = await ds.GetLogAsync(id);
if (item != null)
{
return CreateAppLogModel(item);
}
return null;
}
}
public async Task<IList<AppLogModel>> GetLogsAsync(DataRequest<AppLog> request)
{
var collection = new LogCollection(this);
await collection.LoadAsync(request);
return collection;
}
public async Task<IList<AppLogModel>> GetLogsAsync(int skip, int take, DataRequest<AppLog> request)
{
var models = new List<AppLogModel>();
using (var ds = CreateDataSource())
{
var items = await ds.GetLogsAsync(skip, take, request);
foreach (var item in items)
{
models.Add(CreateAppLogModel(item));
}
return models;
}
}
public async Task<int> GetLogsCountAsync(DataRequest<AppLog> request)
{
using (var ds = CreateDataSource())
{
return await ds.GetLogsCountAsync(request);
}
}
public async Task<int> CreateLogAsync(AppLog appLog)
{
using (var ds = CreateDataSource())
{
return await ds.CreateLogAsync(appLog);
}
}
public async Task<int> DeleteLogAsync(AppLogModel model)
{
var appLog = new AppLog { Id = model.Id };
using (var ds = CreateDataSource())
{
return await ds.DeleteLogsAsync(appLog);
}
}
public async Task<int> DeleteLogRangeAsync(int index, int length, DataRequest<AppLog> request)
{
using (var ds = CreateDataSource())
{
var items = await ds.GetLogKeysAsync(index, length, request);
return await ds.DeleteLogsAsync(items.ToArray());
}
}
public async Task MarkAllAsReadAsync()
{
using (var ds = CreateDataSource())
{
await ds.MarkAllAsReadAsync();
}
}
private AppLogModel CreateAppLogModel(AppLog source)
{
return new AppLogModel()
{
Id = source.Id,
IsRead = source.IsRead,
DateTime = source.DateTime,
User = source.User,
Type = source.Type,
Source = source.Source,
Action = source.Action,
Message = source.Message,
Description = source.Description,
};
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace Microsoft.EntityFrameworkCore.Migrations.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class SqlServerMigrationsAnnotationProvider : MigrationsAnnotationProvider
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override IEnumerable<IAnnotation> For(IKey key)
{
var isClustered = key.SqlServer().IsClustered;
if (isClustered.HasValue)
{
yield return new Annotation(
SqlServerFullAnnotationNames.Instance.Clustered,
isClustered.Value);
}
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override IEnumerable<IAnnotation> For(IIndex index)
{
var isClustered = index.SqlServer().IsClustered;
if (isClustered.HasValue)
{
yield return new Annotation(
SqlServerFullAnnotationNames.Instance.Clustered,
isClustered.Value);
}
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override IEnumerable<IAnnotation> For(IProperty property)
{
if (property.SqlServer().ValueGenerationStrategy == SqlServerValueGenerationStrategy.IdentityColumn)
{
yield return new Annotation(
SqlServerFullAnnotationNames.Instance.ValueGenerationStrategy,
SqlServerValueGenerationStrategy.IdentityColumn);
}
}
}
}
|
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <author name="Daniel Grunwald"/>
// <version>$Revision: 5747 $</version>
// </file>
using System;
namespace ICSharpCode.AvalonEdit.Document
{
using LineNode = DocumentLine;
// A tree node in the document line tree.
// For the purpose of the invariants, "children", "descendents", "siblings" etc. include the DocumentLine object,
// it is treated as a third child node between left and right.
// Originally, this was a separate class, with a reference to the documentLine. The documentLine had a reference
// back to the node. To save memory, the same object is used for both the documentLine and the line node.
// This saves 16 bytes per line (8 byte object overhead + two pointers).
// sealed class LineNode
// {
// internal readonly DocumentLine documentLine;
partial class DocumentLine
{
internal DocumentLine left, right, parent;
internal bool color;
// optimization note: I tried packing color and isDeleted into a single byte field, but that
// actually increased the memory requirements. The JIT packs two bools and a byte (delimiterSize)
// into a single DWORD, but two bytes get each their own DWORD. Three bytes end up in the same DWORD, so
// apparently the JIT only optimizes for memory when there are at least three small fields.
// Currently, DocumentLine takes 36 bytes on x86 (8 byte object overhead, 3 pointers, 3 ints, and another DWORD
// for the small fields).
// TODO: a possible optimization would be to combine 'totalLength' and the small fields into a single uint.
// delimiterSize takes only two bits, the two bools take another two bits; so there's still
// 28 bits left for totalLength. 268435455 characters per line should be enough for everyone :)
/// <summary>
/// Resets the line to enable its reuse after a document rebuild.
/// </summary>
internal void ResetLine()
{
totalLength = delimiterLength = 0;
isDeleted = color = false;
left = right = parent = null;
}
internal LineNode InitLineNode()
{
this.nodeTotalCount = 1;
this.nodeTotalLength = this.TotalLength;
return this;
}
internal LineNode LeftMost {
get {
LineNode node = this;
while (node.left != null)
node = node.left;
return node;
}
}
internal LineNode RightMost {
get {
LineNode node = this;
while (node.right != null)
node = node.right;
return node;
}
}
/// <summary>
/// The number of lines in this node and its child nodes.
/// Invariant:
/// nodeTotalCount = 1 + left.nodeTotalCount + right.nodeTotalCount
/// </summary>
internal int nodeTotalCount;
/// <summary>
/// The total text length of this node and its child nodes.
/// Invariant:
/// nodeTotalLength = left.nodeTotalLength + documentLine.TotalLength + right.nodeTotalLength
/// </summary>
internal int nodeTotalLength;
}
}
|
using Marosoft.Mist.Parsing;
using System.Linq;
using Marosoft.Mist.Lexing;
namespace Marosoft.Mist.Evaluation.Special
{
[SpecialForm("cond")]
public class Cond : SpecialForm
{
public override Expression Call(Expression expr)
{
var forms = expr.Elements.Skip(1).ToList();
if (forms.Count() % 2 != 0)
throw new MistException("COND requires an even number of forms");
for (int i = 0; i < forms.Count() - 1; i = i + 2)
{
var condition = forms[i].Evaluate(Environment.CurrentScope);
if (condition.IsTrue)
return forms[i + 1].Evaluate(Environment.CurrentScope);
}
return NIL.Instance;
}
}
}
|
using System;
namespace Arebis.Pdf.Writing
{
[Serializable]
public enum PdfImagePlacement
{
Stretch = 0,
Center = 1,
LeftOrTop = 2,
RightOrBottom = 3,
LeftOrBottom = 4,
RightOrTop = 5,
}
public static class PdfImagePlacementExtensions
{
public static PdfImagePlacement Rotated(this PdfImagePlacement me, PdfImageRotation rotation)
{
for (var rotations = 0; rotations < (int)rotation; rotations++)
{
switch (me)
{
case PdfImagePlacement.LeftOrTop:
me = PdfImagePlacement.RightOrTop;
break;
case PdfImagePlacement.RightOrTop:
me = PdfImagePlacement.RightOrBottom;
break;
case PdfImagePlacement.RightOrBottom:
me = PdfImagePlacement.LeftOrBottom;
break;
case PdfImagePlacement.LeftOrBottom:
me = PdfImagePlacement.LeftOrTop;
break;
}
}
return me;
}
}
}
|
using Edgar.Geometry;
using Edgar.Legacy.GeneralAlgorithms.DataStructures.Common;
namespace Edgar.Legacy.Utils.Serialization.Models
{
public class DoorModel<TNode>
{
public TNode Node { get; set; }
public Vector2Int From { get; set; }
public Vector2Int To { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace HalfShot.MagnetHS.DatastoreService
{
[AttributeUsage(AttributeTargets.Method)]
class DataStoreAttribute : Attribute
{
public DataStoreOperation Operation { get; set; }
public DataStoreAttribute(DataStoreOperation operation) {
Operation = operation;
}
}
}
|
using CustomFiltersAndFormatters.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using System.Threading.Tasks;
namespace CustomFiltersAndFormatters.Formatter
{
public class ImageFormatter : OutputFormatter
{
public ImageFormatter()
{
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("image/png"));
}
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
{
HttpResponse response = context.HttpContext.Response;
Value value = context.Object as Value;
if(value != null)
await response.SendFileAsync((value).Thumbnail);
}
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using CodeExecutionSystem.Contracts.Abstractions;
using CodeExecutionSystem.Contracts.Data;
namespace EducationSystem.Implementations.Code
{
public sealed class CodeExecutionApi : ICodeExecutionApi
{
private static readonly Random Random = new Random();
public Task<CodeExecutionResult> ExecuteCodeAsync(TestingCode code)
{
var results = new[]
{
GetErrorResult(),
GetSuccessResult()
};
return Task.FromResult(results[Random.Next(results.Length)]);
}
private static CodeExecutionResult GetSuccessResult()
{
return new CodeExecutionResult
{
Results = new[]
{
CreateSuccessResult(),
CreateSuccessResult(),
CreateSuccessResult(),
CreateSuccessResult(),
CreateSuccessResult()
}
};
}
private static CodeExecutionResult GetErrorResult()
{
return new CodeExecutionResult
{
CompilationErrors = new[]
{
GetRandomString(25),
GetRandomString(50),
GetRandomString(75),
GetRandomString(100)
},
Results = new[]
{
CreateSuccessResult(),
CreateSuccessResult(),
CreateResult(ExecutionResult.KilledByMemoryLimit),
CreateResult(ExecutionResult.KilledByTimeout)
}
};
}
private static TestRunResult CreateSuccessResult()
{
return new TestRunResult
{
ExecutionResult = ExecutionResult.Success,
ExpectedOutput = nameof(TestRunResult.ExpectedOutput),
UserOutput = nameof(TestRunResult.ExpectedOutput)
};
}
private static TestRunResult CreateResult(ExecutionResult result)
{
return new TestRunResult
{
ExecutionResult = result,
ExpectedOutput = GetRandomString(25),
UserOutput = GetRandomString(25)
};
}
private static string GetRandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable
.Repeat(chars, length)
.Select(s => s[Random.Next(s.Length)])
.ToArray());
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class ToolTip : MonoBehaviour
{
#region Singleton
public static ToolTip instance;
void Awake()
{
if (instance != null)
{
Debug.LogWarning("More than one Instance of Tooltip found");
return;
}
instance = this;
if (instance == null){
Debug.Log("check");
}
gameObject.SetActive(false);
}
#endregion
public void ShowTooltip(Vector3 position, IDescribable description)
{
gameObject.SetActive(true);
gameObject.transform.position = position;
gameObject.GetComponentInChildren<Text>().text = description.GetDescription();
}
public void HideTooltip()
{
gameObject.SetActive(false);
}
}
|
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Antlr4.Runtime;
using Excess.Compiler.Roslyn;
namespace Excess.Compiler.Antlr4
{
//interop between antlr and excess, derive
public abstract class AntlrGrammar : IGrammar<SyntaxToken, SyntaxNode, ParserRuleContext>
{
public ParserRuleContext Parse(LexicalExtension<SyntaxToken> extension, Scope scope)
{
var text = RoslynCompiler.TokensToString(extension.Body); //td: token matching
AntlrInputStream stream = new AntlrInputStream(text);
ITokenSource lexer = GetLexer(stream);
ITokenStream tokenStream = new CommonTokenStream(lexer);
Parser parser = GetParser(tokenStream);
parser.AddErrorListener(new AntlrErrors<IToken>(scope, extension.BodyStart));
var result = GetRoot(parser);
if (parser.NumberOfSyntaxErrors > 0)
return null;
return result;
}
protected abstract ParserRuleContext GetRoot(Parser parser);
protected abstract Parser GetParser(ITokenStream tokenStream);
protected abstract ITokenSource GetLexer(AntlrInputStream stream);
}
}
|
namespace FluentACS.ManagementService
{
public enum RuleTypes
{
Simple,
Passthrough
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DigitalPlatform.LibraryClient.localhost;
// 2017/10/1
namespace DigitalPlatform.LibraryClient
{
/// <summary>
/// 文件事项枚举类
/// 包装利用 ListFile() API
/// </summary>
public class FileItemLoader : IEnumerable
{
public LibraryChannel Channel { get; set; }
public DigitalPlatform.Stop Stop { get; set; }
public string Category { get; set; }
public string FileName { get; set; }
//public string Style { get; set; }
//public string Lang { get; set; }
// 每批获取最多多少个记录
public long BatchSize { get; set; }
public FileItemLoader(LibraryChannel channel,
DigitalPlatform.Stop stop,
string category,
string filename)
{
this.Channel = channel;
this.Stop = stop;
this.Category = category;
this.FileName = filename;
//this.Style = style;
//this.Lang = lang;
}
public IEnumerator GetEnumerator()
{
string strError = "";
long nStart = 0;
long nPerCount = -1;
long nCount = 0;
if (this.BatchSize != 0)
nPerCount = this.BatchSize;
while (true)
{
FileItemInfo[] items = null;
long lRet = this.Channel.ListFile(
this.Stop,
"list",
this.Category,
this.FileName,
nStart,
nPerCount,
out items,
out strError);
if (lRet == -1)
{
if (this.Channel.ErrorCode != ErrorCode.NoError)
throw new ChannelException(Channel.ErrorCode, strError);
goto ERROR1;
}
if (items == null || items.Length == 0)
yield break;
if (items != null)
{
foreach (FileItemInfo item in items)
{
yield return item;
}
nStart += items.Length;
nCount += items.Length;
}
if (nCount >= lRet)
yield break;
}
ERROR1:
throw new Exception(strError);
}
}
}
|
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Shop.Domain.Models;
namespace Shop.Domain.Infrastructure
{
public interface IProductManager
{
TResult GetProductById<TResult>(int id, Func<Product, TResult> selector);
TResult GetProductByName<TResult>(string name, Func<Product, TResult> selector);
IEnumerable<TResult> GetProducts<TResult>(Func<Product, TResult> selector);
IEnumerable<TResult> GetProductWithStock<TResult>(Func<Product, TResult> selector);
Task<int> CreateProduct(Product product);
Task<int> RemoveProductById(int id);
Task<int> UpdateProduct(Product product);
}
} |
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Prism.Ioc;
using Lyrico.Navigation;
using Lyrico.Repository;
using Lyrico.ViewModels;
using Lyrico.Views;
using Lyrico.Services;
using Lyrico.Services.Interfaces;
using Prism;
namespace Lyrico
{
public partial class App
{
static LyricsDatabase database;
public App(IPlatformInitializer platformInitializer)
:base(platformInitializer)
{
InitializeComponent();
}
public static LyricsDatabase Database
{
get
{
if(database == null)
{
database = new LyricsDatabase();
}
return database;
}
}
protected override async void OnInitialized()
{
InitializeComponent();
var result = await NavigationService.NavigateAsync(Navigate.Start);
if (!result.Success)
{
Console.WriteLine(result.Exception.ToString());
System.Diagnostics.Debugger.Break();
}
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
containerRegistry.RegisterForNavigation<SpotifyLoginPage>();
containerRegistry.Register<IRestService, RestService>();
containerRegistry.Register<ISpotifyService, SpotifyService>();
containerRegistry.Register<IPollingService, PollingService>();
}
}
}
|
using ShaderUtils;
using ShaderUtils.Attributes;
using ShaderUtils.Mathematics;
namespace ShaderExample.Shaders
{
class PassFragment : FragmentShader
{
[In]
public Vector4 Col { private get; set; }
public override void Main()
{
Color = Col;
}
}
}
|
using System;
namespace LogoFX.Client.Mvvm.ViewModel.Contracts
{
/// <summary>
/// Object that notifies about selection change
/// </summary>
public interface INotifySelectionChanged
{
/// <summary>
/// Occurs when [selection changed].
/// </summary>
event EventHandler SelectionChanged;
/// <summary>
/// Occurs when [selection changing].
/// </summary>
event EventHandler<SelectionChangingEventArgs> SelectionChanging;
}
} |
using Ryujinx.HLE.HOS.Ipc;
using System.Collections.Generic;
using System.IO;
namespace Ryujinx.HLE.HOS.Services.FspSrv
{
class IStorage : IpcService
{
private Dictionary<int, ServiceProcessRequest> _commands;
public override IReadOnlyDictionary<int, ServiceProcessRequest> Commands => _commands;
private Stream _baseStream;
public IStorage(Stream baseStream)
{
_commands = new Dictionary<int, ServiceProcessRequest>
{
{ 0, Read }
};
_baseStream = baseStream;
}
// Read(u64 offset, u64 length) -> buffer<u8, 0x46, 0> buffer
public long Read(ServiceCtx context)
{
long offset = context.RequestData.ReadInt64();
long size = context.RequestData.ReadInt64();
if (context.Request.ReceiveBuff.Count > 0)
{
IpcBuffDesc buffDesc = context.Request.ReceiveBuff[0];
//Use smaller length to avoid overflows.
if (size > buffDesc.Size)
{
size = buffDesc.Size;
}
byte[] data = new byte[size];
lock (_baseStream)
{
_baseStream.Seek(offset, SeekOrigin.Begin);
_baseStream.Read(data, 0, data.Length);
}
context.Memory.WriteBytes(buffDesc.Position, data);
}
return 0;
}
}
}
|
using System;
namespace WebApiThrottle
{
[Flags]
public enum ThrottlingBy
{
IpThrottling = 1,
ClientThrottling = 2,
EndpointThrottling = 4
}
} |
using Newtonsoft.Json;
namespace B1SLayer
{
public class SLResponseError
{
[JsonProperty("error")]
public SLErrorDetails Error { get; set; }
}
public class SLErrorDetails
{
[JsonProperty("code")]
public int Code { get; set; }
[JsonProperty("message")]
public SLErrorMessage Message { get; set; }
}
public class SLErrorMessage
{
[JsonProperty("lang")]
public string Lang { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
} |
@using Frontend.Controllers
@using Helpers.Assembly
@{
// SMELL: Bad code, move to controller
ApplicationInformation.ExecutingAssembly = typeof(AccountController).Assembly;
}
<div class="note note-warning">
<h4 class="block">Blaze Beta @(ApplicationInformation.ExecutingAssemblyVersion.ToString())</h4>
<p>You are currently using the Beta version of Blaze.</p>
</div> |
/*
* Copyright (c) Roman Polunin 2016.
* MIT license, see https://opensource.org/licenses/MIT.
*/
using System;
using System.Diagnostics;
namespace OrgChart.Layout
{
/// <summary>
/// A rectangle in the diagram logical coordinate space.
/// </summary>
[DebuggerDisplay("{TopLeft.X}:{TopLeft.Y}, {Size.Width}x{Size.Height}")]
public struct Rect
{
/// <summary>
/// Top-left corner.
/// </summary>
public readonly Point TopLeft;
/// <summary>
/// Computed bottom-right corner.
/// </summary>
public Point BottomRight => new Point(TopLeft.X + Size.Width, TopLeft.Y + Size.Height);
/// <summary>
/// Left edge.
/// </summary>
public double Left => TopLeft.X;
/// <summary>
/// Right edge.
/// </summary>
public double Right => TopLeft.X + Size.Width;
/// <summary>
/// Horizontal center.
/// </summary>
public double CenterH => TopLeft.X + Size.Width/2;
/// <summary>
/// Vertical center.
/// </summary>
public double CenterV => TopLeft.Y + Size.Height/2;
/// <summary>
/// Top edge.
/// </summary>
public double Top => TopLeft.Y;
/// <summary>
/// Bottom edge.
/// </summary>
public double Bottom => TopLeft.Y + Size.Height;
/// <summary>
/// Size of the rectangle.
/// </summary>
public readonly Size Size;
/// <summary>
/// Ctr. to help client code prevent naming conflicts with Rect, Point and Size type names.
/// </summary>
public Rect(double x, double y, double w, double h)
{
if (w < 0)
{
throw new ArgumentOutOfRangeException(nameof(w));
}
if (h < 0)
{
throw new ArgumentOutOfRangeException(nameof(h));
}
TopLeft = new Point(x, y);
Size = new Size(w, h);
}
/// <summary>
/// Ctr. for case with known location.
/// </summary>
public Rect(Point topLeft, Size size)
{
TopLeft = topLeft;
Size = size;
}
/// <summary>
/// Ctr. for case with only the size known.
/// </summary>
public Rect(Size size)
{
TopLeft = new Point(0, 0);
Size = size;
}
/// <summary>
/// Computes a rect that encloses both of given rectangles.
/// </summary>
public static Rect operator +(Rect x, Rect y)
{
var left = Math.Min(x.Left, y.Left);
var top = Math.Min(x.Top, y.Top);
var right = Math.Max(x.Right, y.Right);
var bottom = Math.Max(x.Bottom, y.Bottom);
return new Rect(left, top, right - left, bottom - top);
}
/// <summary>
/// Returns a rectangle moved by <paramref name="offsetX"/> horizontally.
/// </summary>
public Rect MoveH(double offsetX)
{
return new Rect(new Point(Left + offsetX, Top), Size);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Eco;
using Eco.Serialization.Xml;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
string schema = XmlSchemaExporter.GetSchemaFor<spaceBattle>(defaultUsage: Usage.Optional);
using (var sw = new StreamWriter(@"d:\spaceBattle.xsd"))
sw.Write(schema);
schema = XmlSchemaExporter.GetSchemaFor<externalFleets>(defaultUsage: Usage.Optional);
using (var sw = new StreamWriter(@"d:\externalFleets.xsd"))
sw.Write(schema);
string settingsFileName = @"d:\exampleUsage.config";
spaceBattle settings = Settings.Load<spaceBattle>(settingsFileName);
Settings.Save(settings, settingsFileName);
}
}
}
|
namespace ApiClient.Models
{
public class PassiveSkill
{
public virtual int Id { get; set; }
public string Name { get; set; }
public float IncreasePerPoint { get; set; }
public bool UpIsGood { get; set; }
public int MinimumRound { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.