content stringlengths 23 1.05M |
|---|
namespace BuildImporter
{
public class RuneCategoryResponse
{
public RuneCategory[] Categories { get; set; }
}
public class RuneCategory
{
public int[] allowedSubStyles { get; set; }
public Assetmap assetMap { get; set; }
public string defaultPageName { get; set; }
public int[] defaultPerks { get; set; }
public int defaultSubStyle { get; set; }
public string iconPath { get; set; }
public int id { get; set; }
public string name { get; set; }
public Slot[] slots { get; set; }
public Substylebonu[] subStyleBonus { get; set; }
public string tooltip { get; set; }
}
public class Assetmap
{
public string p8000_s0_k0 { get; set; }
public string p8000_s0_k8005 { get; set; }
public string p8000_s0_k8008 { get; set; }
public string p8000_s0_k8010 { get; set; }
public string p8000_s0_k8021 { get; set; }
public string p8000_s8100_k0 { get; set; }
public string p8000_s8100_k8005 { get; set; }
public string p8000_s8100_k8008 { get; set; }
public string p8000_s8100_k8010 { get; set; }
public string p8000_s8100_k8021 { get; set; }
public string p8000_s8200_k0 { get; set; }
public string p8000_s8200_k8005 { get; set; }
public string p8000_s8200_k8008 { get; set; }
public string p8000_s8200_k8010 { get; set; }
public string p8000_s8200_k8021 { get; set; }
public string p8000_s8300_k0 { get; set; }
public string p8000_s8300_k8005 { get; set; }
public string p8000_s8300_k8008 { get; set; }
public string p8000_s8300_k8010 { get; set; }
public string p8000_s8300_k8021 { get; set; }
public string p8000_s8400_k0 { get; set; }
public string p8000_s8400_k8005 { get; set; }
public string p8000_s8400_k8008 { get; set; }
public string p8000_s8400_k8010 { get; set; }
public string p8000_s8400_k8021 { get; set; }
public string svg_icon { get; set; }
public string svg_icon_16 { get; set; }
public string p8100_s0_k0 { get; set; }
public string p8100_s0_k8112 { get; set; }
public string p8100_s0_k8124 { get; set; }
public string p8100_s0_k8128 { get; set; }
public string p8100_s0_k9923 { get; set; }
public string p8100_s8000_k0 { get; set; }
public string p8100_s8000_k8112 { get; set; }
public string p8100_s8000_k8124 { get; set; }
public string p8100_s8000_k8128 { get; set; }
public string p8100_s8000_k9923 { get; set; }
public string p8100_s8200_k0 { get; set; }
public string p8100_s8200_k8112 { get; set; }
public string p8100_s8200_k8124 { get; set; }
public string p8100_s8200_k8128 { get; set; }
public string p8100_s8200_k9923 { get; set; }
public string p8100_s8300_k0 { get; set; }
public string p8100_s8300_k8112 { get; set; }
public string p8100_s8300_k8124 { get; set; }
public string p8100_s8300_k8128 { get; set; }
public string p8100_s8300_k9923 { get; set; }
public string p8100_s8400_k0 { get; set; }
public string p8100_s8400_k8112 { get; set; }
public string p8100_s8400_k8124 { get; set; }
public string p8100_s8400_k8128 { get; set; }
public string p8100_s8400_k9923 { get; set; }
public string p8200_s0_k0 { get; set; }
public string p8200_s0_k8214 { get; set; }
public string p8200_s0_k8229 { get; set; }
public string p8200_s0_k8230 { get; set; }
public string p8200_s8000_k0 { get; set; }
public string p8200_s8000_k8214 { get; set; }
public string p8200_s8000_k8229 { get; set; }
public string p8200_s8000_k8230 { get; set; }
public string p8200_s8100_k0 { get; set; }
public string p8200_s8100_k8214 { get; set; }
public string p8200_s8100_k8229 { get; set; }
public string p8200_s8100_k8230 { get; set; }
public string p8200_s8300_k0 { get; set; }
public string p8200_s8300_k8214 { get; set; }
public string p8200_s8300_k8229 { get; set; }
public string p8200_s8300_k8230 { get; set; }
public string p8200_s8400_k0 { get; set; }
public string p8200_s8400_k8214 { get; set; }
public string p8200_s8400_k8229 { get; set; }
public string p8200_s8400_k8230 { get; set; }
public string p8300_s0_k0 { get; set; }
public string p8300_s0_k8351 { get; set; }
public string p8300_s0_k8359 { get; set; }
public string p8300_s0_k8360 { get; set; }
public string p8300_s8000_k0 { get; set; }
public string p8300_s8000_k8351 { get; set; }
public string p8300_s8000_k8359 { get; set; }
public string p8300_s8000_k8360 { get; set; }
public string p8300_s8100_k0 { get; set; }
public string p8300_s8100_k8351 { get; set; }
public string p8300_s8100_k8359 { get; set; }
public string p8300_s8100_k8360 { get; set; }
public string p8300_s8200_k0 { get; set; }
public string p8300_s8200_k8351 { get; set; }
public string p8300_s8200_k8359 { get; set; }
public string p8300_s8200_k8360 { get; set; }
public string p8300_s8400_k0 { get; set; }
public string p8300_s8400_k8351 { get; set; }
public string p8300_s8400_k8359 { get; set; }
public string p8300_s8400_k8360 { get; set; }
public string p8400_s0_k0 { get; set; }
public string p8400_s0_k8437 { get; set; }
public string p8400_s0_k8439 { get; set; }
public string p8400_s0_k8465 { get; set; }
public string p8400_s8000_k0 { get; set; }
public string p8400_s8000_k8437 { get; set; }
public string p8400_s8000_k8439 { get; set; }
public string p8400_s8000_k8465 { get; set; }
public string p8400_s8100_k0 { get; set; }
public string p8400_s8100_k8437 { get; set; }
public string p8400_s8100_k8439 { get; set; }
public string p8400_s8100_k8465 { get; set; }
public string p8400_s8200_k0 { get; set; }
public string p8400_s8200_k8437 { get; set; }
public string p8400_s8200_k8439 { get; set; }
public string p8400_s8200_k8465 { get; set; }
public string p8400_s8300_k0 { get; set; }
public string p8400_s8300_k8437 { get; set; }
public string p8400_s8300_k8439 { get; set; }
public string p8400_s8300_k8465 { get; set; }
}
public class Slot
{
public int[] perks { get; set; }
public string slotLabel { get; set; }
public string type { get; set; }
}
public class Substylebonu
{
public int perkId { get; set; }
public int styleId { get; set; }
}
} |
using System;
using DevExpress.Persistent.Validation;
using FluentAssertions;
using Xpand.Persistent.Base.General;
using Xpand.Persistent.Base.PersistentMetaData;
using Xpand.Test.WorldCreator.TestArtifacts;
using Xpand.Test.WorldCreator.TestArtifacts.Autofixture;
using Xunit;
namespace Xpand.Test.WorldCreator.Validation{
[Trait(Traits.Validation, "Given a persistent assembly info")]
public class PersistentAssemblyInfoSpecs{
[Theory, WorldCreatorAutoData]
public void Name_Is_Required(IWCTestData testData){
var persistentAssemblyInfo = testData.Application.CreateObjectSpace().Create<IPersistentAssemblyInfo>();
var usedProperties = nameof(persistentAssemblyInfo.Name);
Validator.RuleSet.StateOf<RuleRequiredField>(persistentAssemblyInfo, usedProperties)
.Should()
.Be(ValidationState.Invalid);
persistentAssemblyInfo.Name = "name";
Validator.RuleSet.StateOf<RuleRequiredField>(persistentAssemblyInfo, usedProperties)
.Should()
.Be(ValidationState.Valid);
}
[Theory, WorldCreatorAutoData]
public void Name_Is_Unique(IWCTestData testData){
var objectSpace = testData.Application.CreateObjectSpace();
var persistentAssemblyInfo = objectSpace.Create<IPersistentAssemblyInfo>();
persistentAssemblyInfo.Name = "name";
var assemblyInfo = objectSpace.Create<IPersistentAssemblyInfo>();
objectSpace.CommitChanges();
var usedProperties = nameof(persistentAssemblyInfo.Name);
Validator.RuleSet.StateOf<RuleUniqueValue>(persistentAssemblyInfo, usedProperties)
.Should()
.Be(ValidationState.Valid);
assemblyInfo.Name = "name";
Validator.RuleSet.StateOf<RuleUniqueValue>(persistentAssemblyInfo, usedProperties)
.Should()
.Be(ValidationState.Invalid);
}
[Theory, WorldCreatorAutoData]
public void Name_Is_Valid_File_name(WCTestData testData, IPersistentAssemblyInfo persistentAssemblyInfo) {
persistentAssemblyInfo.Name = "file@";
throw new NotImplementedException();
// Validator.RuleSet.StateOf<RuleValidFileName>(persistentAssemblyInfo, nameof(persistentAssemblyInfo.Name))
// .Should().Be(ValidationState.Invalid);
}
}
} |
namespace Dto
{
public abstract class BaseDto
{
public virtual int Id { get; set; }
public string ModifiedBy { get; set; }
}
}
|
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Digitteck.Gateway.Service
{
public interface IGWRuntime
{
Task<OperationResult> Execute(HttpContext gwHttpContext, GatewayConfiguration configuration);
}
} |
namespace TestingLiftInfo.Web.Areas.Administration.Controllers
{
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using TestingLiftInfo.Common;
using TestingLiftInfo.Data;
using TestingLiftInfo.Data.Models;
using TestingLiftInfo.Web.ViewModels.Administration.Admin;
public class AdminController : AdministrationController
{
private readonly ApplicationDbContext dbContext;
public AdminController(ApplicationDbContext dbContext)
{
this.dbContext = dbContext;
}
public IActionResult AddAdmin()
{
return this.View();
}
[HttpPost]
public async Task<IActionResult> AddAdmin([FromForm]GetAllAdminViewModel model)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
var admin = this.dbContext.Roles
.FirstOrDefault(x => x.Name == GlobalConstants.AdministratorRoleName);
var user = this.dbContext.Users
.FirstOrDefault(x => x.Email == model.Add.Email);
if (admin != null && user != null)
{
await this.dbContext.UserRoles
.AddAsync(new IdentityUserRole<string>
{
UserId = user.Id,
RoleId = admin.Id,
});
await this.dbContext.SaveChangesAsync();
return this.View("AdminCreateAdmin");
}
else if (user != null)
{
var isAdmin = this.dbContext.UserRoles
.FirstOrDefault(x => x.RoleId == admin.Id && x.UserId == user.Id);
if (isAdmin == null)
{
await this.dbContext.UserRoles
.AddAsync(new IdentityUserRole<string>
{
UserId = user.Id,
RoleId = admin.Id,
});
await this.dbContext.SaveChangesAsync();
return this.View("AdminCreateAdmin");
}
}
return this.RedirectToAction("AddAdmin");
}
public IActionResult All()
{
var adminRole = this.dbContext.Roles
.Where(x => x.Name == GlobalConstants.AdministratorRoleName)
.FirstOrDefault();
var user = this.dbContext.Users
.OrderBy(x => x.Name)
.Where(x => x.Roles.Any(y => y.RoleId == adminRole.Id) && x.Name != "Admin")
.ToList();
var viewModel = new GetAllAdminViewModel()
{
Users = user,
};
return this.View(viewModel);
}
public async Task<IActionResult> Delete(string id)
{
var userRole = this.dbContext.UserRoles
.FirstOrDefault(x => x.UserId == id);
if (userRole != null)
{
var userTEst = this.dbContext.Users
.Where(x => x.Id == id)
.FirstOrDefault()
.Roles.Remove(userRole);
this.dbContext.UserRoles.Remove(userRole);
await this.dbContext.SaveChangesAsync();
}
return this.RedirectToAction("All");
}
}
}
|
using System.Collections;
namespace Unity.VisualScripting
{
/// <summary>
/// Delays flow by waiting until the next frame.
/// </summary>
[UnitTitle("Wait For Next Frame")]
[UnitShortTitle("Next Frame")]
[UnitOrder(4)]
public class WaitForNextFrameUnit : WaitUnit
{
protected override IEnumerator Await(Flow flow)
{
yield return null;
yield return exit;
}
}
}
|
// ===-----------------------------------------------------------------------==//
//
// Whoop - a Verifier for Device Drivers
//
// Copyright (c) 2013-2014 Pantazis Deligiannis (p.deligiannis@imperial.ac.uk)
//
// This file is distributed under the Microsoft Public License. See
// LICENSE.TXT for details.
//
// ===----------------------------------------------------------------------===//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Microsoft.Boogie;
using Microsoft.Basetypes;
using Whoop.Analysis;
using Whoop.Domain.Drivers;
using Whoop.Regions;
namespace Whoop.Summarisation
{
internal class AccessCheckingSummaryGeneration : SummaryGeneration, IPass
{
public AccessCheckingSummaryGeneration(AnalysisContext ac, EntryPoint ep)
: base(ac, ep)
{
}
public void Run()
{
if (WhoopCommandLineOptions.Get().MeasurePassExecutionTime)
{
base.Timer = new ExecutionTimer();
base.Timer.Start();
}
foreach (var region in base.InstrumentationRegions)
{
if (!base.EP.Name.Equals(region.Implementation().Name))
continue;
this.InstrumentWriteAccessInvariantsInEntryPointRegion(region);
this.InstrumentReadAccessInvariantsInEntryPointRegion(region);
}
foreach (var region in base.InstrumentationRegions)
{
if (base.EP.Name.Equals(region.Implementation().Name))
continue;
this.InstrumentWriteAccessInvariantsInRegion(region);
this.InstrumentReadAccessInvariantsInRegion(region);
}
base.InstrumentExistentialBooleans();
if (WhoopCommandLineOptions.Get().MeasurePassExecutionTime)
{
base.Timer.Stop();
Console.WriteLine(" | |------ [AccessCheckingSummaryGeneration] {0}", base.Timer.Result());
}
}
#region summary instrumentation functions
private void InstrumentWriteAccessInvariantsInEntryPointRegion(InstrumentationRegion region)
{
foreach (var pair in region.GetResourceAccesses())
{
var waVars = base.WriteAccessCheckingVariables.FindAll(val =>
val.Name.Contains(pair.Key + "_$"));
if (this.EP.ForceWriteResource.Contains(pair.Key))
continue;
if (!this.EP.HasWriteAccess.ContainsKey(pair.Key))
{
foreach (var variable in waVars)
{
base.InstrumentEnsures(region, variable, false);
foreach (var block in region.LoopHeaders())
{
base.InstrumentAssert(block, variable, false);
}
}
continue;
}
Expr nonWatchedExpr = null;
foreach (var watchedVar in base.AccessWatchdogConstants)
{
if (!watchedVar.Name.EndsWith(pair.Key))
continue;
foreach (var access in pair.Value)
{
var watchedExpr = Expr.Eq(new IdentifierExpr(watchedVar.tok, watchedVar), access);
foreach (var variable in waVars)
{
base.InstrumentImpliesEnsuresCandidate(region, watchedExpr, variable, false, true);
foreach (var block in region.LoopHeaders())
{
base.InstrumentImpliesAssertCandidate(block, watchedExpr, variable, false, true);
}
}
if (nonWatchedExpr == null)
{
nonWatchedExpr = Expr.Neq(new IdentifierExpr(watchedVar.tok, watchedVar), access);
}
else
{
nonWatchedExpr = Expr.And(nonWatchedExpr,
Expr.Neq(new IdentifierExpr(watchedVar.tok, watchedVar), access));
}
}
}
foreach (var variable in waVars)
{
base.InstrumentImpliesEnsuresCandidate(region, nonWatchedExpr, variable, false, true);
foreach (var block in region.LoopHeaders())
{
base.InstrumentImpliesAssertCandidate(block, nonWatchedExpr, variable, false, true);
}
}
}
}
private void InstrumentReadAccessInvariantsInEntryPointRegion(InstrumentationRegion region)
{
foreach (var pair in region.GetResourceAccesses())
{
var raVars = base.ReadAccessCheckingVariables.FindAll(val =>
val.Name.Contains(pair.Key + "_$"));
if (this.EP.ForceReadResource.Contains(pair.Key))
continue;
if (!this.EP.HasReadAccess.ContainsKey(pair.Key))
{
foreach (var variable in raVars)
{
base.InstrumentEnsures(region, variable, false);
foreach (var block in region.LoopHeaders())
{
base.InstrumentAssert(block, variable, false);
}
}
continue;
}
Expr nonWatchedExpr = null;
foreach (var watchedVar in base.AccessWatchdogConstants)
{
if (!watchedVar.Name.EndsWith(pair.Key))
continue;
foreach (var access in pair.Value)
{
var watchedExpr = Expr.Eq(new IdentifierExpr(watchedVar.tok, watchedVar), access);
foreach (var variable in raVars)
{
base.InstrumentImpliesEnsuresCandidate(region, watchedExpr, variable, false, true);
foreach (var block in region.LoopHeaders())
{
base.InstrumentImpliesAssertCandidate(block, watchedExpr, variable, false, true);
}
}
if (nonWatchedExpr == null)
{
nonWatchedExpr = Expr.Neq(new IdentifierExpr(watchedVar.tok, watchedVar), access);
}
else
{
nonWatchedExpr = Expr.And(nonWatchedExpr,
Expr.Neq(new IdentifierExpr(watchedVar.tok, watchedVar), access));
}
}
}
foreach (var variable in raVars)
{
base.InstrumentImpliesEnsuresCandidate(region, nonWatchedExpr, variable, false, true);
foreach (var block in region.LoopHeaders())
{
base.InstrumentImpliesAssertCandidate(block, nonWatchedExpr, variable, false, true);
}
}
}
}
private void InstrumentWriteAccessInvariantsInRegion(InstrumentationRegion region)
{
if (region.IsNotAccessingResources || region.IsNotWriteAccessingResources)
return;
foreach (var pair in region.GetResourceAccesses())
{
var waVars = base.WriteAccessCheckingVariables.FindAll(val =>
val.Name.Contains(pair.Key + "_$"));
if (this.EP.ForceWriteResource.Contains(pair.Key))
continue;
if (!this.EP.HasWriteAccess.ContainsKey(pair.Key))
continue;
Expr nonWatchedExpr = null;
foreach (var watchedVar in base.AccessWatchdogConstants)
{
if (!watchedVar.Name.EndsWith(pair.Key))
continue;
foreach (var access in pair.Value)
{
var watchedExpr = Expr.Eq(new IdentifierExpr(watchedVar.tok, watchedVar), access);
foreach (var variable in waVars)
{
base.InstrumentImpliesRequiresCandidate(region, watchedExpr, variable, false, true);
base.InstrumentImpliesEnsuresCandidate(region, watchedExpr, variable, false, true);
foreach (var block in region.LoopHeaders())
{
base.InstrumentImpliesAssertCandidate(block, watchedExpr, variable, false, true);
}
}
if (nonWatchedExpr == null)
{
nonWatchedExpr = Expr.Neq(new IdentifierExpr(watchedVar.tok, watchedVar), access);
}
else
{
nonWatchedExpr = Expr.And(nonWatchedExpr,
Expr.Neq(new IdentifierExpr(watchedVar.tok, watchedVar), access));
}
}
}
foreach (var variable in waVars)
{
base.InstrumentImpliesRequiresCandidate(region, nonWatchedExpr, variable, false, true);
base.InstrumentImpliesEnsuresCandidate(region, nonWatchedExpr, variable, false, true);
foreach (var block in region.LoopHeaders())
{
base.InstrumentImpliesAssertCandidate(block, nonWatchedExpr, variable, false, true);
}
}
}
}
private void InstrumentReadAccessInvariantsInRegion(InstrumentationRegion region)
{
if (region.IsNotAccessingResources || region.IsNotReadAccessingResources)
return;
foreach (var pair in region.GetResourceAccesses())
{
var raVars = base.ReadAccessCheckingVariables.FindAll(val =>
val.Name.Contains(pair.Key + "_$"));
if (this.EP.ForceReadResource.Contains(pair.Key))
continue;
if (!this.EP.HasReadAccess.ContainsKey(pair.Key))
continue;
Expr nonWatchedExpr = null;
foreach (var watchedVar in base.AccessWatchdogConstants)
{
if (!watchedVar.Name.EndsWith(pair.Key))
continue;
foreach (var access in pair.Value)
{
var watchedExpr = Expr.Eq(new IdentifierExpr(watchedVar.tok, watchedVar), access);
foreach (var variable in raVars)
{
base.InstrumentImpliesRequiresCandidate(region, watchedExpr, variable, false, true);
base.InstrumentImpliesEnsuresCandidate(region, watchedExpr, variable, false, true);
foreach (var block in region.LoopHeaders())
{
base.InstrumentImpliesAssertCandidate(block, watchedExpr, variable, false, true);
}
}
if (nonWatchedExpr == null)
{
nonWatchedExpr = Expr.Neq(new IdentifierExpr(watchedVar.tok, watchedVar), access);
}
else
{
nonWatchedExpr = Expr.And(nonWatchedExpr,
Expr.Neq(new IdentifierExpr(watchedVar.tok, watchedVar), access));
}
}
}
foreach (var variable in raVars)
{
base.InstrumentImpliesRequiresCandidate(region, nonWatchedExpr, variable, false, true);
base.InstrumentImpliesEnsuresCandidate(region, nonWatchedExpr, variable, false, true);
foreach (var block in region.LoopHeaders())
{
base.InstrumentImpliesAssertCandidate(block, nonWatchedExpr, variable, false, true);
}
}
}
}
#endregion
#region helper functions
protected override Constant CreateConstant()
{
Constant cons = new Constant(Token.NoToken, new TypedIdent(Token.NoToken, "_b$ac$" +
base.EP.Name + "$" + base.Counter, Microsoft.Boogie.Type.Bool), false);
base.ExistentialBooleans.Add(cons);
base.Counter++;
return cons;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using TextReader = System.IO.TextReader;
using ArgumentException = System.ArgumentException;
using Regex = System.Text.RegularExpressions.Regex;
namespace BiteSized
{
public static class Inspection
{
public readonly struct LineTooLong
{
public readonly ulong LineNumber;
public readonly uint Length;
public LineTooLong(ulong lineNumber, uint length)
{
if (lineNumber == 0)
{
throw new ArgumentException("Line numbers are indexed from 1, but got: 0");
}
LineNumber = lineNumber;
Length = length;
}
}
public class Record
{
public readonly List<LineTooLong> LinesTooLong;
public readonly ulong LineCount;
public Record(List<LineTooLong> linesTooLong, ulong lineCount)
{
// Precondition(s)
foreach (var lineTooLong in linesTooLong)
{
if (lineTooLong.LineNumber > lineCount)
{
throw new ArgumentException(
$"Inconsistent line number and line count (== {lineCount}), " +
$"got: {lineTooLong.LineNumber}");
}
}
LinesTooLong = linesTooLong;
LineCount = lineCount;
}
}
/// <summary>
/// Checks that the file observes width and height constraints.
/// </summary>
/// <param name="reader">Reads the source file</param>
/// <param name="maxLineLength">maximum allowed line length</param>
/// <param name="ignoreLinesMatching">ignore all lines matching one of the regular expressions</param>
/// <returns>List of problematic comments</returns>
public static Record InspectLines(TextReader reader, uint maxLineLength, List<Regex> ignoreLinesMatching)
{
var linesTooLong = new List<LineTooLong>(1024);
ulong lineCount = 0;
string? line;
while ((line = reader.ReadLine()) != null)
{
bool ignored = ignoreLinesMatching.Exists((regex) => regex.IsMatch(line));
if (!ignored && line.Length > maxLineLength)
{
linesTooLong.Add(new LineTooLong(lineCount + 1, (uint)line.Length));
}
lineCount++;
}
return new Record(linesTooLong, lineCount);
}
}
} |
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Running;
using SerializationBenchmark.Data;
using SerializationBenchmark.Model;
using SerializationBenchmark.Serialization.Implementation;
using SerializationBenchmark.Serialization.Interface;
using System.Collections.Generic;
namespace SerializationBenchmark
{
[RPlotExporter]
public class SerializationTest
{
[Params(10, 100, 1000, 10000)]
public int NElements; //Params are public (SerializationBenchmark requirement).
private const int NNestedElements = 10;
private readonly Consumer consumer = new Consumer();
private IEnumerable<MainTestObject> _data;
private ISerializationTest<IEnumerable<MainTestObject>> _newtonsoftSerializer;
private ISerializationTest<IEnumerable<MainTestObject>> _serviceStackSerializer;
private ISerializationTest<IEnumerable<MainTestObject>> _systemTextJsonSerializer;
private ISerializationTest<IEnumerable<MainTestObject>> _utf8JsonSerializer;
private ISerializationTest<IEnumerable<MainTestObject>> _jilSerializer;
[GlobalSetup]
public void Setup()
{
_data = MockData.Create(NElements, NNestedElements);
_newtonsoftSerializer = new NewtonsoftSerializer<IEnumerable<MainTestObject>>();
_serviceStackSerializer = new ServiceStackSerializer<IEnumerable<MainTestObject>>();
_systemTextJsonSerializer = new SystemTextJsonSerializer<IEnumerable<MainTestObject>>();
_utf8JsonSerializer = new Utf8JsonSerializer<IEnumerable<MainTestObject>>();
_jilSerializer = new JilSerializer<IEnumerable<MainTestObject>>();
}
[Benchmark]
public void Newtonsoft() => _newtonsoftSerializer.Test(_data).Consume(consumer);
[Benchmark]
public void ServiceStack() => _serviceStackSerializer.Test(_data).Consume(consumer);
[Benchmark]
public void SysTextJson() => _systemTextJsonSerializer.Test(_data).Consume(consumer);
[Benchmark]
public void Utf8Json() => _utf8JsonSerializer.Test(_data).Consume(consumer);
[Benchmark]
public void Jil() => _jilSerializer.Test(_data).Consume(consumer);
}
class Program
{
static void Main(string[] args)
{
BenchmarkRunner.Run<SerializationTest>();
}
}
}
|
namespace BacklogGitLabIntegration.Core.Shared.Models.Abstracts
{
public interface ICreationAudited: ICreationAudited<int> { }
public interface ICreationAudited<TPrimaryKey> : IHasCreationTime
{
TPrimaryKey CreatorId { get; set; }
}
}
|
using CsvHelper.Configuration;
using ESFA.DC.PeriodEnd.ReportService.Model.ReportModels;
namespace ESFA.DC.PeriodEnd.ReportService.Legacy.Mapper
{
public class LearnerLevelViewFinancialsRemovedMapper : ClassMap<LearnerLevelViewModel>
{
public LearnerLevelViewFinancialsRemovedMapper()
{
int i = 0;
Map(m => m.PaymentLearnerReferenceNumber).Index(i++).Name("Learner reference number");
Map(m => m.PaymentUniqueLearnerNumber).Index(i++).Name("Unique learner number");
Map(m => m.FamilyName).Index(i++).Name("Family Name");
Map(m => m.GivenNames).Index(i++).Name("Given Names");
Map(m => m.LearnerEmploymentStatusEmployerId).Index(i++).Name("Employer identifier (ERN)");
Map(m => m.EmployerName).Index(i++).Name("Latest employer name");
Map(m => m.ReasonForIssues).Index(i++).Name("Reasons for issues");
Map(m => m.RuleDescription).Index(i++).Name("Data lock description");
Map(m => m.PaymentFundingLineType).Index(i++).Name("Funding line type");
}
}
}
|
namespace Cinnamon
{
public enum PlayStyle
{
StartToEnd,
Cyclical,
ForwardReverse,
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UIElements;
/// <summary>
/// this is for testing purposes only, remove later
/// </summary>
[Obsolete]
public class UConsole : MonoBehaviour
{
// ui toolkit
private TextField inputField;
private ListView listView;
//private inputfie prefabScale;
//
private UIDocument uiDocument;
private VisualElement rootVisualElement;
public List<string> items;
private static VisualElement MakeItem()
{
var label = new Label();
label.name = "history-item-label";
var stylecolor = new StyleColor();
stylecolor.value = Color.cyan;
label.style.color = stylecolor;
//label.style.height = 12;
return label;
}
private void OnEnable()
{
uiDocument = GetComponent<UIDocument>();
rootVisualElement = uiDocument.rootVisualElement;
inputField = rootVisualElement.Q<TextField>("console-inputfield");
listView = rootVisualElement.Q<ListView>("console-history-listview");
listView.itemHeight = 16;
// Create some list of data, here simply numbers in interval [1, 1000]
const int itemCount = 2;
items = new List<string>(itemCount);
for (int i = 1; i <= itemCount; i++)
items.Add("i.ToString()");
// The "makeItem" function will be called as needed
// when the ListView needs more items to render
//Func<VisualElement> makeItem = () => new Label();
//VisualElement MakeItem() => new Label();
// As the user scrolls through the list, the ListView object
// will recycle elements created by the "makeItem"
// and invoke the "bindItem" callback to associate
// the element with the matching data item (specified as an index in the list)
Action<VisualElement, int> bindItem = (e, i) => (e as Label).text = items[i];
//var listView = container.Q<ListView>();
listView.makeItem = MakeItem;
listView.bindItem = bindItem;
listView.itemsSource = items;
listView.selectionType = SelectionType.Single;
/*// Callback invoked when the user double clicks an item
listView.onItemsChosen += Debug.Log;
// Callback invoked when the user changes the selection inside the ListView
listView.onSelectionChange += Debug.Log;
inputField.RegisterCallback<FocusEvent>(evt => logtext());*/
//myElement.RegisterCallback<KeyDownEvent>((evt) => Debug.Log(evt.keyCode))
//inputField.RegisterCallback<FocusInEvent>(evt => { Input.imeCompositionMode = IMECompositionMode.On; });
//inputField.RegisterCallback<FocusOutEvent>(evt => { Input.imeCompositionMode = IMECompositionMode.Auto; });
// Mirror value of uxml field into the C# field.
/*uxmlVector3Field.RegisterCallback<ChangeEvent<Vector3Field>>((evt) =>
{
spread = evt.newValue;
});*/
}
void logtext()
{
Debug.Log("VAR");
}
private void Update()
{
if (Keyboard.current.enterKey.isPressed)
{
//inputField.panel.focusController.focusedElement == inputField;
if (inputField.panel.focusController.focusedElement == inputField)
{
if (inputField.value != null)
{
items.Add(inputField.value);
//inputField.Clear();
inputField.value = null;
listView.Refresh();
listView.ScrollToItem(items.Count-1);
}
}
}
//inputField.Focus();
/*
if (inputField.text != null)
{
Debug.Log(inputField.text);
}*/
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using DG.Tweening;
public class ColorGradient_UI : MonoBehaviour
{
[SerializeField] TextMeshProUGUI thisTMP;
VertexGradient textGradient;
float a, b, c, d;
private void OnEnable()
{
textGradient = thisTMP.colorGradient;
a = 0;
b = 0;
c = 0;
d = 0;
DOTween.To(() => a, x => a = x, 1, 0.0f);
DOTween.To(() => b, x => b = x, 1, 0.0f);
DOTween.To(() => c, x => c = x, 1, 0.4f);
DOTween.To(() => d, x => d = x, 1, 0.4f);
StartCoroutine(Close());
}
IEnumerator Close()
{
yield return new WaitForSeconds(0.5f);
DOTween.To(() => a, x => a = x, 0, 0.3f);
DOTween.To(() => b, x => b = x, 0, 0.3f);
DOTween.To(() => c, x => c = x, 0, 0.3f);
DOTween.To(() => d, x => d = x, 0, 0.3f);
yield return new WaitForSeconds(0.4f);
gameObject.SetActive(false);
}
private void Update()
{
textGradient.bottomLeft = new Color32(255, 255, 255, (byte)(a * 255));
textGradient.bottomRight = new Color32(255, 255, 255, (byte)(b * 255));
textGradient.topLeft = new Color32(255, 255, 255, (byte)(c * 255));
textGradient.topRight = new Color32(255, 255, 255, (byte)(d * 255));
thisTMP.colorGradient = textGradient;
}
}
|
using System;
using System.Collections.Generic;
public class IntervalTree
{
private Node _root;
public void Insert(decimal lo, decimal hi)
{
this._root = this.Insert(this._root, lo, hi);
}
public void EachInOrder(Action<Interval> action)
{
EachInOrder(this._root, action);
}
public Interval SearchAny(decimal lo, decimal hi)
{
var current = this._root;
while (current != null && !current.Interval.Intersects(lo, hi))
{
if (current.Left != null && current.Left.Max > lo)
{
current = current.Left;
}
else
{
current = current.Right;
}
}
return current?.Interval;
}
public IEnumerable<Interval> SearchAll(decimal lo, decimal hi)
{
var result = new List<Interval>();
this.SearchAll(this._root, lo, hi, result);
return result;
}
private void SearchAll(Node node, decimal lo, decimal hi, List<Interval> result)
{
if (node == null)
{
return;
}
var goLeft = node.Left != null && node.Left.Max > lo;
var goRight = node.Right != null && node.Right.Interval.Lo < hi;
if (goLeft)
{
this.SearchAll(node.Left, lo, hi, result);
}
if (node.Interval.Intersects(lo, hi))
{
result.Add(node.Interval);
}
if (goRight)
{
this.SearchAll(node.Right, lo, hi, result);
}
}
private void EachInOrder(Node node, Action<Interval> action)
{
if (node == null)
{
return;
}
EachInOrder(node.Left, action);
action(node.Interval);
EachInOrder(node.Right, action);
}
private Node Insert(Node node, decimal lo, decimal hi)
{
if (node == null)
{
return new Node(new Interval(lo, hi));
}
int cmp = lo.CompareTo(node.Interval.Lo);
if (cmp < 0)
{
node.Left = Insert(node.Left, lo, hi);
}
else if (cmp > 0)
{
node.Right = Insert(node.Right, lo, hi);
}
UpdateMax(node);
return node;
}
private static void UpdateMax(Node node)
{
var maxChild = GetMax(node.Left, node.Right);
node.Max = GetMax(node, maxChild).Max;
}
private static Node GetMax(Node a, Node b)
{
// :D
return a == null ? b : b == null ? a : a.Max > b.Max ? a : b;
}
private class Node
{
public Interval Interval { get; }
public decimal Max { get; set; }
public Node Right { get; set; }
public Node Left { get; set; }
public Node(Interval interval)
{
this.Interval = interval;
this.Max = interval.Hi;
}
}
} |
using CustomVision;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models;
namespace AzureCognitiveServices
{
public class SalvarProjetoModel : PageModel
{
private readonly Treinamento _treinamento;
public Project Projeto { get; private set; }
public SalvarProjetoModel() =>
_treinamento = new Treinamento();
public void OnGet(string idDoProjeto) =>
Projeto = _treinamento.CarregarProjeto(idDoProjeto);
public IActionResult OnPost(string idDoProjeto)
{
var nome = Request.Form["nome"];
var descricao = Request.Form["descricao"];
if (string.IsNullOrWhiteSpace(idDoProjeto))
_treinamento.CriarProjeto(nome, descricao);
else
_treinamento.EditarProjeto(idDoProjeto,
new Project
{
Name = nome,
Description = descricao
});
return RedirectToPage("/Vision/CustomVision/Projetos");
}
}
} |
namespace BackendForFrontend
{
public class Scopes
{
public const string AccessAsUser = "access_as_user";
}
} |
namespace Qunar.TC.Qmq.Client.Exceptions
{
internal class BlockMessageException : MessageException
{
public BlockMessageException() { }
public BlockMessageException(string messageId)
: base(messageId, "block by whitelist")
{
}
}
}
|
using System;
using Microsoft.Extensions.DependencyInjection;
namespace Reinforce.HttpClientFactory
{
public class ReinforceBuilder : IReinforceBuilder
{
private IHttpClientBuilder ApiClientBuilder { get; }
public IServiceCollection Services => ApiClientBuilder.Services;
public ReinforceBuilder(IHttpClientBuilder builder)
{
ApiClientBuilder = builder ?? throw new ArgumentNullException(nameof(builder));
}
public IReinforceBuilder ConfigureApiClient(Action<IHttpClientBuilder> builder)
{
builder(ApiClientBuilder);
return this;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PolygonAnimate : MonoBehaviour
{
public bool iStrigger ;
//public PhysicsMaterial2D _material ;
private SpriteRenderer spriteRenderer;
private List<Sprite> spritesList;
private Dictionary<int, PolygonCollider2D> spriteColliders;
private bool _processing ;
private int _frame ;
public int Frame {
get { return _frame; }
set {
if (value != _frame) {
if (value > -1) {
spriteColliders [_frame].enabled = false;
_frame = value;
spriteColliders [_frame].enabled = true;
} else {
_processing = true;
StartCoroutine (AddSpriteCollider (spriteRenderer.sprite));
}
}
}
}
private IEnumerator AddSpriteCollider (Sprite sprite)
{
spritesList.Add (sprite);
int index = spritesList.IndexOf (sprite);
PolygonCollider2D spriteCollider = gameObject.AddComponent<PolygonCollider2D> ();
spriteCollider.isTrigger = iStrigger;
// spriteCollider.sharedMaterial = _material;
spriteColliders.Add (index, spriteCollider);
yield return new WaitForEndOfFrame ();
Frame = index;
_processing = false;
}
private void OnEnable ()
{
spriteColliders [Frame].enabled = true;
}
private void OnDisable ()
{
spriteColliders [Frame].enabled = false;
}
private void Awake ()
{
spriteRenderer = this.GetComponent<SpriteRenderer> ();
spritesList = new List<Sprite> ();
spriteColliders = new Dictionary<int, PolygonCollider2D> ();
Frame = spritesList.IndexOf (spriteRenderer.sprite);
}
private void LateUpdate ()
{
if (!_processing)
Frame = spritesList.IndexOf (spriteRenderer.sprite);
}
}
|
using DBUtil;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utils;
namespace DAL
{
/// <summary>
/// 订单明细
/// </summary>
public class BsOrderDetailDal
{
#region 根据订单ID查询订单明细集合
/// <summary>
/// 根据订单ID查询订单明细集合
/// </summary>
public List<BS_ORDER_DETAIL> GetListByOrderId(string orderId)
{
BsOrderDal m_BsOrderDetailDal = ServiceHelper.Get<BsOrderDal>(); //该行代码用于测试DAL相互引用,运行不报错即为通过测试
using (var session = DBHelper.GetSession())
{
SqlString sql = new SqlString("select * from bs_order_detail where order_id=@orderId order by order_num", orderId);
return session.FindListBySql<BS_ORDER_DETAIL>(sql.SQL, sql.Params);
}
}
#endregion
}
}
|
namespace Romanization
{
/// <summary>
/// The type of output numeral parsed numbers should be put into.<br />
/// For instance, Greek numerals are traditionally romanized as Roman numerals except for when in
/// official/government documents.
/// </summary>
public enum OutputNumeralType
{
/// <summary>
/// The numeral system of much of the world.<br />
/// Example: <c>267.5</c>
/// </summary>
Arabic,
/// <summary>
/// The numeral system of Rome, still often used today for names etc.<br />
/// Example: <c>CCLXVIIS</c>
/// </summary>
Roman
}
}
|
namespace RSAEncDecLib.Interfaces
{
public interface IEncryptor
{
byte[] EncryptData(byte[] plainText);
void ImportPublicKey(byte[] encryptionExp, byte[] modulus);
}
} |
using SolcNet.DataDescription.Output;
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Meadow.Core.AbiEncoding;
using Meadow.Core.Utils;
using Meadow.Core.EthTypes;
using Meadow.JsonRpc.Types;
using Meadow.JsonRpc;
using Meadow.JsonRpc.Client;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace Meadow.Contract
{
public interface IContractInstanceSetup
{
void Setup(IJsonRpcClient rpcClient, Address contractAddress, Address defaultFromAccount);
TransactionParams GetTransactionParams(TransactionParams optional);
CallParams GetCallParams(CallParams optional);
IJsonRpcClient JsonRpcClient { get; }
string ContractSolFilePath { get; }
string ContractName { get; }
}
public class ContractInstance : BaseContract
{
protected override string ContractSolFilePath { get; }
protected override string ContractName { get; }
public ContractInstance(
string contractSolFilePath, string contractName,
IJsonRpcClient rpcClient, Address contractAddress, Address defaultFromAccount)
: base(rpcClient, contractAddress, defaultFromAccount)
{
ContractAddress = contractAddress;
DefaultFromAccount = defaultFromAccount;
JsonRpcClient = rpcClient;
ContractSolFilePath = contractSolFilePath;
ContractName = contractName;
}
}
public abstract class BaseContract : IContractInstanceSetup
{
public SolcNet.DataDescription.Output.Abi[] Abi => _abi.Value;
readonly Lazy<SolcNet.DataDescription.Output.Abi[]> _abi;
public Address ContractAddress { get; protected set; }
public Address DefaultFromAccount { get; protected set; }
public IJsonRpcClient JsonRpcClient { get; protected set; }
protected abstract string ContractSolFilePath { get; }
protected abstract string ContractName { get; }
string IContractInstanceSetup.ContractSolFilePath => ContractSolFilePath;
string IContractInstanceSetup.ContractName => ContractName;
public BaseContract(IJsonRpcClient rpcClient, Address contractAddress, Address defaultFromAccount) : this()
{
ContractAddress = contractAddress;
DefaultFromAccount = defaultFromAccount;
JsonRpcClient = rpcClient;
}
public BaseContract()
{
_abi = new Lazy<Abi[]>(() => GeneratedSolcData.Default.GetContractJsonAbi(ContractSolFilePath, ContractName));
}
TransactionParams IContractInstanceSetup.GetTransactionParams(TransactionParams optional)
{
return new TransactionParams
{
From = optional?.From ?? DefaultFromAccount,
To = optional?.To ?? ContractAddress,
Value = optional?.Value,
Gas = optional?.Gas,
GasPrice = optional?.GasPrice,
Nonce = optional?.Nonce,
Data = optional?.Data
};
}
CallParams IContractInstanceSetup.GetCallParams(CallParams optional)
{
return new CallParams
{
From = optional?.From ?? DefaultFromAccount,
To = optional?.To ?? ContractAddress,
Value = optional?.Value,
Gas = optional?.Gas,
GasPrice = optional?.GasPrice,
Data = optional?.Data
};
}
void IContractInstanceSetup.Setup(IJsonRpcClient rpcClient, Address contractAddress, Address defaultFromAccount)
{
ContractAddress = contractAddress;
DefaultFromAccount = defaultFromAccount;
JsonRpcClient = rpcClient;
}
}
}
|
namespace ScriptyTests
{
internal struct LetStatementTestCases
{
public string Input { get; set; }
public string ExpectedIdentifier { get; set; }
private object _expectedVal;
public LetStatementTestCases ExpectedValueSet<T>(T val)
{
_expectedVal = val;
return this;
}
public object ExpectedValueGet() => _expectedVal;
}
} |
using System.Collections.Generic;
/// <summary>
/// Scribble.rs ♯ namespace
/// </summary>
namespace ScribblersSharp
{
/// <summary>
/// Used to signal when a "update-players" game message has been received
/// </summary>
/// <param name="players">Players</param>
public delegate void UpdatePlayersGameMessageReceivedDelegate(IReadOnlyDictionary<string, IPlayer> players);
}
|
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.Xna.Framework;
// Some small functions that are used by multiple subparsers.
namespace Haumea.Parsing
{
internal static partial class Parser
{
// Parses this vector notation: (x, y)
private static Regex VectorRgx { get; } = new Regex(@" *\( *(-?\d+) *, *(-?\d+) *\) *");
private static IEnumerable<string> Lines(string text)
{
if (text.Length == 0) yield break;
foreach (string line in text.Split(Environment.NewLine))
{
if (line.Length > 0) yield return line;
}
}
private static bool TryParseHexColor(string hexString, out Color color)
{
if (hexString.StartsWith("#")) hexString = hexString.Substring(1);
uint hex = Convert.ToUInt32(hexString, 16);
if (hexString.Length != 6)
{
color = default(Color);
return false;
}
byte r = (byte)(hex >> 16);
byte g = (byte)(hex >> 8);
byte b = (byte)(hex);
color = new Color(r, g, b);
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Project.FileSystems
{
public interface IFileSystem
{
FileSystemType FileSystemType { get; }
string ReadFileText(string filePath);
Task SaveFile(string filePath, string source);
Task SaveFile(string fileName, string directoryName, string source);
Task DeleteFile(string fileName);
Task DeleteDirectory(string path);
Task CreateDirectory(string path);
Task GetAllFiles(string path, string extension, Action<string> handler);
bool HasFile(string path);
}
public enum FileSystemType {
InMemory,
PhysicalFile,
Database
}
}
|
namespace system.threading
{
public struct SpinWait
{
public void SpinOnce() => java.lang.Thread.yield();
}
}
|
using UnityEngine;
using static NiTools.Shortcuts.Constructors.FloatVectors;
namespace NiTools.Shortcuts{
using Vec3 = Vector3;
public static partial class VectorFuncs{
public static Vec3 cross(Vec3 a, Vec3 b){
return Vec3.Cross(a, b);
}
public static Vec3 add(Vec3 a, Vec3 b){
return a + b;
}
public static Vec3 lerp(Vec3 a, Vec3 b, float t){
return Vector3.LerpUnclamped(a, b, t);
}
public static float dot(Vec3 a, Vec3 b){
return Vector3.Dot(a, b);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace ACMESharp.Testing.Xunit
{
// With guidance from:
// https://damsteen.nl/blog/2016/06/08/ordered-tests-with-nunit-mstest-xunit-pt4-xunit
public class TestOrderer : ITestCaseOrderer, ITestCollectionOrderer
{
// These have to be constants to be usable in the Xunit.TestCaseOrderer and
// Xunit.TestCollectionOrderer assembly-level attributes however we define
// a static class constructor whose purpose is to verify their correctness
public const string TypeName = "ACMESharp.Testing.Xunit.TestOrderer";
public const string AssemblyName = "ACMESharp.Testing.Xunit";
private Random _rng = new Random();
static TestOrderer()
{
var t = typeof(TestOrderer);
var tName = t.FullName;
if (TypeName != tName)
throw new Exception($"TestOrderer.TypeName constant [{TypeName}] is WRONG ({tName})");
var aName = t.Assembly.GetName().Name;
if (AssemblyName != aName)
throw new Exception($"TestOrderer.AssemblyName constant [{AssemblyName}] is WRONG ({aName})");
}
IEnumerable<ITestCollection> ITestCollectionOrderer.OrderTestCollections(IEnumerable<ITestCollection> testCollections)
{
// First we randomize, then we sort -- this gives us variations for any tests
// that are not explicitly ordered or that are assigned the same order weight.
return testCollections.OrderBy(x => _rng.Next()).OrderBy(x => GetTestOrder(x));
}
IEnumerable<TTestCase> ITestCaseOrderer.OrderTestCases<TTestCase>(IEnumerable<TTestCase> testCases) // where TTestCase : ITestCase
{
// First we randomize, then we sort -- this gives us variations for any tests
// that are not explicitly ordered or that are assigned the same order weight.
return testCases.OrderBy(x => _rng.Next()).OrderBy(x => GetTestOrder(x));
}
public static int GetTestOrder(MemberInfo member)
{
return member.GetCustomAttribute<TestOrderAttribute>()?.Order ?? int.MaxValue;
}
public static string GetTestGroup(MemberInfo member)
{
return member.GetCustomAttribute<TestOrderAttribute>()?.Group;
}
public static int GetTestOrder(object instance)
{
var t = instance.GetType();
return t.GetCustomAttribute<TestOrderAttribute>()?.Order ?? int.MaxValue;
}
public static int GetTestOrder(ITestCollection tc)
{
var cd = tc.CollectionDefinition;
var toa = cd?.GetCustomAttributes(typeof(TestOrderAttribute)).FirstOrDefault();
if (toa != null)
return toa.GetNamedArgument<int>(nameof(TestOrderAttribute.Order));
var tt = Type.GetType(tc.DisplayName);
return tt?.GetCustomAttribute<TestOrderAttribute>().Order ?? int.MaxValue;
}
public static long GetTestOrder(ITestCase tc)
{
var tm = tc.TestMethod.Method;
var toa = tm.GetCustomAttributes(typeof(TestOrderAttribute)).FirstOrDefault();
return toa?.GetNamedArgument<int>(nameof(TestOrderAttribute.Order))
?? int.MaxValue;
}
}
} |
using System;
//using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace ZylLib.Text {
/// <summary>
/// C风格字符串转义模式.
/// </summary>
public enum StringEscapeCMode {
/// <summary>
/// 默认.
/// </summary>
Default = 0,
/// <summary>
/// 自动括号. 转义时,仅在遇到必须转义时才加上引号,否则不会有引号.
/// </summary>
QuoteAuto = 0,
/// <summary>
/// 有括号. 转义时,总是加上引号. 解转义时,仅解转义引号内的内容.
/// </summary>
QuoteYes = 1,
/// <summary>
/// 无括号. 转义时,不会加上引号. 解转义时,假定已经在引号内.
/// </summary>
QuoteNo = 2,
/// <summary>
/// 不转码. 返回原始文本.
/// </summary>
NoEscape = 3,
/// <summary>
/// 引号掩码. 一般多用于转义时.
/// </summary>
QuoteMask = 3,
/// <summary>
/// 自动切换. 解转义时,若遇到单独的引号便自动在 原始文本、解转义 这两种模式下切换.
/// </summary>
SwitchAuto = 0,
/// <summary>
/// 切换为原始文本. 解转义时,若遇到单独的引号,便转为原始文本直接输出剩余内容.
/// </summary>
SwitchRaw = 4,
/// <summary>
/// 忽略切换. 解转义时,若遇到单独的引号,便输出这个引号,然后依旧对剩余数据进行解转义.
/// </summary>
SwitchIgnore = 8,
/// <summary>
/// 切换时中断. 解转义时,若遇到单独的引号,便直接返回,不处理剩余数据.
/// </summary>
SwitchBreak = 0xC,
/// <summary>
/// 切换掩码. 仅用于解转义时.
/// </summary>
SwitchMask = 0xC,
}
/// <summary>
/// C-style escape (C风格字符串转义).
/// </summary>
/// <remarks>
/// 规则有:
/// <para>\\: '\'.</para>
/// <para>\": '"'.</para>
/// <para>\': '''.</para>
/// <para>\0.</para>
/// <para>\a.</para>
/// <para>\b.</para>
/// <para>\f.</para>
/// <para>\n.</para>
/// <para>\r.</para>
/// <para>\t.</para>
/// <para>\v.</para>
/// <para>\uxxxx: 16位unicode字符.</para>
/// <para>\Uyyyyyyyy: 32位unicode字符.</para>
/// <para>未来考虑支持:</para>
/// <para>\000: 8进制字符.</para>
/// <para>\0x00: 16进制字符.</para>
/// </remarks>
public class StringEscapeC {
/// <summary>
/// 保持原值的转义字符.
/// </summary>
public static readonly string EscapeKeepChars = "\\\"\'";
/// <summary>
/// 命名的转义字符.
/// </summary>
public static readonly string EscapeNameChars = "0abfnrtv";
/// <summary>
/// 16位unicode字符转义.
/// </summary>
public static readonly string EscapeUnicode16Chars = "u";
/// <summary>
/// 32位unicode字符转义.
/// </summary>
public static readonly string EscapeUnicode32Chars = "U";
/// <summary>
/// 解转义字符串.
/// </summary>
/// <param name="src">源字符串.</param>
/// <param name="mode">模式.</param>
/// <returns>返回该字符串的解转义.</returns>
public static string UnescapeString(string src, StringEscapeCMode mode) {
if (string.IsNullOrEmpty(src)) return src;
Debug.Assert(mode == StringEscapeCMode.Default, "Now only support StringEscapeCMode.Default!"); //TODO: 支持更多的C转义的解码.
StringBuilder sb = new StringBuilder(src.Length);
char[] arr = src.ToCharArray();
bool bQuoteIn = false; // 已经进入括号内.
bool bBackslash = false; // 前一个是反斜杠.
long posBackslash = 0; // 反斜杠的位置.
for(int i=0; i<arr.Length; ++i) {
bool bOutChar = true; // 输出当前字符.
char ch = arr[i];
if (bQuoteIn) {
if (bBackslash) {
switch (ch) {
case '\\':
case '\"':
case '\'':
// 输出ch.
break;
case '0': ch = '\0'; break;
case 'a': case 'A': ch = '\a'; break;
case 'b': case 'B': ch = '\b'; break;
case 'f': case 'F': ch = '\f'; break;
case 'n': case 'N': ch = '\n'; break;
case 'r': case 'R': ch = '\r'; break;
case 't': case 'T': ch = '\t'; break;
case 'v': case 'V': ch = '\v'; break;
case 'u':
case 'U':
Debug.Assert(false, "Now not support."); //TODO: 实现unicode转码.
sb.Append('\\');
break;
default:
// 无效转义,补上前面的反斜杠.
sb.Append('\\');
break;
}
if (bOutChar) bBackslash = false;
}
else {
switch (ch) {
case '\"':
bQuoteIn = false;
bBackslash = false;
bOutChar = false;
break;
case '\\':
bBackslash = true;
posBackslash = i;
bOutChar = false;
break;
default:
//bOutChar = true;
break;
}
}
}
else {
if ('"' == ch) {
bQuoteIn = true;
bBackslash = false;
bOutChar = false;
}
else {
//bOutChar = true;
}
}
if (bOutChar) sb.Append(ch);
}
if (bBackslash) {
sb.Append(src.Substring((int)posBackslash));
}
return sb.ToString();
}
/// <summary>
/// 解转义字符串.
/// </summary>
/// <param name="src">源字符串.</param>
/// <returns>返回该字符串的解转义.</returns>
public static string UnescapeString(string src) {
return UnescapeString(src, StringEscapeCMode.Default);
}
// checkNeedEscape: 检测是否需要转义.
/// <summary>
/// C转码字符,仅返回会转码的字符串.
/// </summary>
/// <param name="ch">字符.</param>
/// <returns>返回该字符的转义. 不需转码的会返回 null .</returns>
private static string EscapeChar_Only(char ch) {
string rt = null;
switch (ch) {
case '\0': rt = "\\0"; break;
case '\a': rt = "\\a"; break;
case '\b': rt = "\\b"; break;
case '\f': rt = "\\f"; break;
case '\n': rt = "\\n"; break;
case '\r': rt = "\\r"; break;
case '\t': rt = "\\t"; break;
case '\v': rt = "\\v"; break;
default:
if (char.IsControl(ch)) {
rt = string.Format("\\u{0:X4}", (int)ch);
}
break;
}
return rt;
}
/// <summary>
/// C转码字符(字符串版),仅返回会转码的字符串.
/// </summary>
/// <param name="ch">字符.</param>
/// <returns>返回该字符的转义. 不需转码的会返回 null .</returns>
private static string EscapeChar_OnlyS(char ch) {
string rt = null;
switch (ch) {
case '\0': rt = "\\0"; break;
case '\a': rt = "\\a"; break;
case '\b': rt = "\\b"; break;
case '\f': rt = "\\f"; break;
case '\n': rt = "\\n"; break;
case '\r': rt = "\\r"; break;
case '\t': rt = "\\t"; break;
case '\v': rt = "\\v"; break;
case '\'': rt = "\\\'"; break;
case '\"': rt = "\\\""; break;
default:
if (char.IsControl(ch)) {
rt = string.Format("\\u{0:X4}", (int)ch);
}
break;
}
return rt;
}
/// <summary>
/// C转码字符,根据 模式 参数.
/// </summary>
/// <param name="ch">字符.</param>
/// <param name="mode">模式.</param>
/// <returns>返回该字符的转义.</returns>
public static string EscapeChar(char ch, StringEscapeCMode mode) {
if ((mode & StringEscapeCMode.QuoteMask) == StringEscapeCMode.NoEscape) return ch.ToString();
string rt = EscapeChar_Only(ch);
bool hasquote = ((mode & StringEscapeCMode.QuoteMask) == StringEscapeCMode.QuoteYes);
if ((mode & StringEscapeCMode.QuoteMask) == StringEscapeCMode.QuoteAuto && null != rt) hasquote = true;
if (null == rt) rt = ch.ToString();
if (hasquote) rt = string.Format("'{0}'", rt);
return rt;
}
/// <summary>
/// C转码字符,使用默认参数(自动增加引号).
/// </summary>
/// <param name="ch">字符.</param>
/// <returns>返回该字符的转义.</returns>
public static string EscapeChar(char ch) {
return EscapeChar(ch, StringEscapeCMode.Default);
}
/// <summary>
/// C转码字符串,根据 模式 参数.
/// </summary>
/// <param name="src">源字符串.</param>
/// <param name="mode">模式.</param>
/// <returns>返回该字符串的转义.</returns>
public static string EscapeString(string src, StringEscapeCMode mode) {
if (string.IsNullOrEmpty(src)) return src;
if ((mode & StringEscapeCMode.QuoteMask) == StringEscapeCMode.NoEscape) return src;
StringBuilder sb = new StringBuilder();
bool hasescape = false;
foreach (char ch in src) {
string s = EscapeChar_OnlyS(ch);
if (null != s) {
sb.Append(s);
hasescape = true;
}
else {
sb.Append(ch);
}
}
bool hasquote = ((mode & StringEscapeCMode.QuoteMask) == StringEscapeCMode.QuoteYes);
if ((mode & StringEscapeCMode.QuoteMask) == StringEscapeCMode.QuoteAuto && hasescape) hasquote = true;
if (!hasescape && !hasquote) return src;
if (hasquote) {
sb.Insert(0, "\"");
sb.Append('"');
}
return sb.ToString();
}
/// <summary>
/// C转码字符串,使用默认参数(自动增加引号).
/// </summary>
/// <param name="src">源字符串.</param>
/// <returns>返回该字符串的转义.</returns>
public static string EscapeString(string src) {
return EscapeString(src, StringEscapeCMode.Default);
}
}
}
|
// <Snippet1>
using System;
class MyGetTypeFromCLSID
{
public class MyClass1
{
public void MyMethod1()
{
}
}
public static void Main()
{
// Get the type corresponding to the class MyClass.
Type myType = typeof(MyClass1);
// Get the object of the Guid.
Guid myGuid =(Guid) myType.GUID;
Console.WriteLine("The name of the class is "+myType.ToString());
Console.WriteLine("The ClassId of MyClass is "+myType.GUID);
}
}
// </Snippet1>
|
using System;
namespace Netcool.Core.Entities
{
public interface IDeleteAudit
{
DateTime? DeleteTime { get; set; }
int? DeleteUserId { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Design
{
public class DesignButton : Design.DesignPanel
{
private bool isSelected = false;
public DesignButton()
{
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
isSelected = true;
this.Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (isSelected)
e.Graphics.FillRectangle(new SolidBrush(Color.Orange), this.DisplayRectangle);
e.Graphics.DrawImage(this.BackgroundImage, this.DisplayRectangle);
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
isSelected = false;
this.Invalidate();
}
}
}
|
using Solnet.Wallet;
using System.Collections.Generic;
namespace Solnet.Programs
{
/// <summary>
/// Represents a decoded instruction.
/// </summary>
public class DecodedInstruction
{
/// <summary>
/// The public key of the program.
/// </summary>
public PublicKey PublicKey { get; set; }
/// <summary>
/// The program name.
/// </summary>
public string ProgramName { get; set; }
/// <summary>
/// The instruction name.
/// </summary>
public string InstructionName { get; set; }
/// <summary>
/// Values decoded from the instruction.
/// </summary>
public Dictionary<string, object> Values { get; set; }
/// <summary>
/// The inner instructions related to this decoded instruction.
/// </summary>
public List<DecodedInstruction> InnerInstructions { get; set; }
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using Tanzu.Toolkit.CloudFoundryApiClient.Models.AppsResponse;
using Tanzu.Toolkit.CloudFoundryApiClient.Models.OrgsResponse;
using Tanzu.Toolkit.CloudFoundryApiClient.Models.SpacesResponse;
namespace Tanzu.Toolkit.CloudFoundryApiClient
{
public interface ICfApiClient
{
string AccessToken { get; }
Task<string> LoginAsync(string cfTarget, string cfUsername, string cfPassword);
Task<List<Org>> ListOrgs(string cfTarget, string accessToken);
Task<List<Space>> ListSpaces(string cfTarget, string accessToken);
Task<List<Space>> ListSpacesForOrg(string cfTarget, string accessToken, string orgGuid);
Task<List<App>> ListAppsForSpace(string cfTarget, string accessToken, string spaceGuid);
Task<bool> StopAppWithGuid(string cfTarget, string accessToken, string appGuid);
Task<bool> StartAppWithGuid(string cfTarget, string accessToken, string appGuid);
Task<bool> DeleteAppWithGuid(string cfTarget, string accessToken, string appGuid);
}
}
|
using System.Collections;
using JetBrains.Annotations;
using Reborn.Common;
using UnityEngine;
namespace Reborn.Core
{
[UsedImplicitly]
[RequireComponent(typeof(ParticleSystem))]
internal sealed class ArcaneMissile : Projectile
{
[SerializeField] float _selfRotationSpeed;
protected override IEnumerator AutoDestruct()
{
var particle = GetComponent<ParticleSystem>();
particle.Stop();
while (true)
{
if (!particle.IsAlive())
{
ObjectPoolManager.Despawn(this);
yield break;
}
yield return new WaitForSeconds(Settings.LargeTimeStep);
}
}
[UsedImplicitly]
void Update()
{
if (!IsExploded) transform.Rotate(Vector3.forward * _selfRotationSpeed * Time.deltaTime);
}
}
} |
// Instance generated by TankLibHelper.InstanceBuilder
// ReSharper disable All
namespace TankLib.STU.Types {
[STUAttribute(0xD0806FE4)]
public class STU_D0806FE4 : STU_CDA01686 {
[STUFieldAttribute(0xECA9BAAA, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUConfigVar m_ECA9BAAA;
[STUFieldAttribute(0xDB7E052F, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUConfigVar m_DB7E052F;
[STUFieldAttribute(0x3E3E203A, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUConfigVar m_3E3E203A;
[STUFieldAttribute(0xBD631144, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUConfigVar m_BD631144;
[STUFieldAttribute(0x7D4F2FF6, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUConfigVar m_7D4F2FF6;
[STUFieldAttribute(0x170234FA, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUConfigVar m_170234FA;
[STUFieldAttribute(0x828BBB5F, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUConfigVar m_828BBB5F;
[STUFieldAttribute(0xA124969D, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_A124969D;
[STUFieldAttribute(0x8E80A08E, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_8E80A08E;
[STUFieldAttribute(0x1D4855CE, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_1D4855CE;
[STUFieldAttribute(0x5374BCDF, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_5374BCDF;
[STUFieldAttribute(0x425F054A, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_425F054A;
[STUFieldAttribute(0x4C7AEA39, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_4C7AEA39;
[STUFieldAttribute(0x6EC3F345, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_6EC3F345;
[STUFieldAttribute(0x944B2182, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_944B2182;
[STUFieldAttribute(0x2985CB94, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_2985CB94;
[STUFieldAttribute(0x81C159F0, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_81C159F0;
[STUFieldAttribute(0x60A60C24, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_60A60C24;
[STUFieldAttribute(0xF09A6FBE, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_F09A6FBE;
[STUFieldAttribute(0xF5089FE7, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_F5089FE7;
[STUFieldAttribute(0x20D95F23, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_20D95F23;
[STUFieldAttribute(0xC5743428, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_076E0DBA m_C5743428;
[STUFieldAttribute(0xD0EBC4C3, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUStatescriptOutputPlug m_D0EBC4C3;
[STUFieldAttribute(0x5C59D732, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUStatescriptOutputPlug m_5C59D732;
[STUFieldAttribute(0x3950A28B, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUStatescriptOutputPlug m_3950A28B;
[STUFieldAttribute(0x18202F65, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUStatescriptOutputPlug m_18202F65;
[STUFieldAttribute(0x8E08CB9F, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUStatescriptOutputPlug m_8E08CB9F;
[STUFieldAttribute(0xAFED9891, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUStatescriptOutputPlug m_AFED9891;
[STUFieldAttribute(0x6D312579, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STUStatescriptOutputPlug m_6D312579;
[STUFieldAttribute(0x10E16D9D, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_E39E7C11 m_10E16D9D;
}
}
|
// <Snippet1>
using System;
using System.Reflection;
class Mymemberinfo
{
public static int Main()
{
Console.WriteLine ("\nReflection.MemberInfo");
// Get the Type and MemberInfo.
Type MyType = Type.GetType("System.Reflection.PropertyInfo");
MemberInfo[] Mymemberinfoarray = MyType.GetMembers();
// Get the MemberType method and display the elements.
Console.Write("\nThere are {0} members in ", Mymemberinfoarray.GetLength(0));
Console.Write("{0}.", MyType.FullName);
for (int counter = 0; counter < Mymemberinfoarray.Length; counter++)
{
Console.Write("\n" + counter + ". "
+ Mymemberinfoarray[counter].Name
+ " Member type - " +
Mymemberinfoarray[counter].MemberType.ToString());
}
return 0;
}
}
// </Snippet1>
|
namespace SFA.DAS.Payments.Verification.Constants
{
enum Script
{
Inclusions,
Earnings,
Payments,
RequiredPayments,
Datalocks,
}
}
|
namespace Achilles.Entities.Sqlite.SqlStatements.Table
{
public enum OperationAction
{
/// <summary>
/// No action.
/// </summary>
None,
Cascade
}
}
|
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace UnderMineControl.Loader.Core
{
public interface ISteamUtility
{
string FindGameDirectory(string gameName);
bool Verify(int appId);
}
public class SteamUtility : ISteamUtility
{
private const string STEAM_REGKEY_32 = @"SOFTWARE\Valve\Steam";
private const string STEAM_REGKEY_64 = @"SOFTWARE\Wow6432Node\Valve\Steam";
private const string STEAM_REGKEY_INSTALL = "InstallPath";
private const string STEAM_DEFAULT_INSTALL = @"C:\Program Files\Steam";
private const string STEAM_GAME_FOLDER = @"steamapps\common\";
private const string STEAM_LIBRARYFOLDERS_FILE = @"steamapps\libraryfolders.vdf";
private const string STEAM_VERIFY = "steam://validate/";
private readonly ILogger _logger;
public SteamUtility(ILogger<SteamUtility> logger)
{
_logger = logger ?? throw new NullReferenceException("logger");
}
public RegistryKey GetSteamRegistryKey(out bool isX64)
{
isX64 = false;
try
{
_logger.LogDebug("Checking for steam registry keys");
var x64 = Registry.LocalMachine.OpenSubKey(STEAM_REGKEY_64);
if (x64 != null &&
!string.IsNullOrEmpty(x64.ToString()))
{
_logger.LogDebug("Found 64 bit steam reg key");
isX64 = true;
return x64;
}
var x32 = Registry.LocalMachine.OpenSubKey(STEAM_REGKEY_32);
if (x32 != null &&
!string.IsNullOrEmpty(x32.ToString()))
{
_logger.LogDebug("Found 32 bit steam reg key");
return x32;
}
_logger.LogWarning("Couldn't find a steam registry key!");
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error trying to find steam registry keys");
return null;
}
}
public string GetBaseInstallPath()
{
try
{
_logger.LogDebug("Starting to find Steam Base Install Path");
var key = GetSteamRegistryKey(out _);
if (key != null)
{
var regpath = key.GetValue(STEAM_REGKEY_INSTALL)?.ToString();
_logger.LogInformation($"Found steam install path: {regpath}");
if (!string.IsNullOrEmpty(regpath) && Directory.Exists(regpath))
return regpath;
_logger.LogWarning($"Steam install path couldn't be verified: {regpath}");
}
_logger.LogDebug("Attempting to resolve default steam install path as registry key failed!");
if (Directory.Exists(STEAM_DEFAULT_INSTALL))
return STEAM_DEFAULT_INSTALL;
_logger.LogWarning("Couldn't find any steam installs, is steam even installed?");
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error occurred while getting Steam Install Path");
return null;
}
}
public IEnumerable<KeyValuePair<string, string>> ParseVdf(string data)
{
var lines = data.Split('\n');
foreach(var line in lines)
{
if (!line.StartsWith("\t"))
continue;
var parts = line.Trim('\t').Split(new[] { "\t\t" }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2)
yield return new KeyValuePair<string, string>(parts[0].Trim('\"'), parts[1].Trim('\"'));
}
}
public IEnumerable<string> GetGameDirectories(string baseInstallPath)
{
yield return baseInstallPath;
var path = Path.Combine(baseInstallPath, STEAM_LIBRARYFOLDERS_FILE);
if (!File.Exists(path))
{
_logger.LogWarning($"library folders VDF file doesn't exist: {path}");
yield break;
}
var data = File.ReadAllText(path);
var vdf = ParseVdf(data).ToArray();
foreach (var entry in vdf)
{
if (!int.TryParse(entry.Key, out _))
continue;
if (Directory.Exists(entry.Value))
yield return entry.Value;
}
}
public bool Verify(int appId)
{
try
{
_logger.LogInformation("Starting steam file verification...");
Process.Start(new ProcessStartInfo
{
FileName = STEAM_VERIFY + appId,
UseShellExecute = true,
CreateNoWindow = false
});
_logger.LogInformation("Steam file verification finished!");
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error occurred while verifying game files");
return false;
}
}
public string FindGameDirectory(string gameName)
{
try
{
var basePath = GetBaseInstallPath();
if (basePath == null)
return null;
var gameDirectories = GetGameDirectories(basePath);
foreach(var dir in gameDirectories)
{
var path = Path.Combine(dir, STEAM_GAME_FOLDER, gameName);
if (Directory.Exists(path))
{
_logger.LogDebug($"{gameName} directory found: {path}");
return path;
}
}
_logger.LogWarning("Unable to find directory for game: " + gameName);
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error occurred while trying to find the game directory.");
return null;
}
}
}
}
|
using ObjectiveStrategy.GameModels.Definitions;
using System;
using System.Collections.Generic;
namespace ObjectiveStrategy.GameGeneration.TreeGeneration
{
public class UnitBuilder : EntityBuilder, IUnitType
{
public UnitBuilder(Random random, uint id, string symbol)
: base(random, id, symbol)
{
Name = "Unnamed unit";
}
public UnitFlags Flags { get; set; }
public UnitMobility Mobility { get; set; } = UnitMobility.Standard;
public uint BuiltBy { get; set; }
public int MoveRange { get; set; } = 3;
public override void AllocateName(ICollection<string> usedNames)
{
Name = DetermineUniqueName(usedNames, "Unit");
}
public UnitType Build()
{
/*
// 10-15, plus 13-20 per tier
int health = Random.Next(10, 16) + Random.Next(13, 21) * Tier
.RoundNearest(5);
// ~1/3 chance of 1, plus 0.5 to 0.8 per tier
int armor = ((Random.NextDouble(0.3, 0.6) + Random.NextDouble(0.5, 0.9) * Tier))
.RoundNearest(1);
unit.VisionRange = UnitVisionRange;
MoveType = Standard, Cumbersome or Versatile
unit.BuildTime = Random.Next(Math.Max(1, tier - 2), Tier + 2);
unit.Mana = Random.Next(5, 11) + Random.Next(10, 21) * Tier;
unit.MineralCost = Random.Next(35, 61) + Random.Next(20, 31) * Tier;
unit.VespineCost = Math.Max(0, 25 * (Tier - 1));
unit.SupplyCost = Tier;
*/
return new UnitType(this);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BlogEngine.Articles.Events;
using BlogEngine.Subscriptions.API.Configuration;
using BlogEngine.Subscriptions.Application.Abstractions;
using BlogEngine.Subscriptions.Application.Requests.Subscriptions.Queries;
using MassTransit;
using MediatR;
namespace BlogEngine.Subscriptions.API.Consumers
{
public sealed class ArticleCreatedConsumer : IConsumer<ArticleCreatedEvent>
{
private readonly EmailsConfiguration _emails;
private readonly IEmailService _emailService;
private readonly IMediator _mediator;
public ArticleCreatedConsumer(IEmailService emailService, IMediator mediator, EmailsConfiguration emails)
{
_emailService = emailService;
_mediator = mediator;
_emails = emails;
}
public async Task Consume(ConsumeContext<ArticleCreatedEvent> context)
{
var articleCreated = context.Message;
var emails = await GetEmails(articleCreated.HashTags);
await Task.WhenAll(emails.Select(toEmail => _emailService.Send(
toEmail,
_emails.NotificationsFrom,
articleCreated.Title,
GetMessage(articleCreated.Title))));
}
private async Task<IEnumerable<string>> GetEmails(IEnumerable<string> hashTags)
{
var emails = await Task.WhenAll(hashTags.Select(GetEmails));
return new HashSet<string>(emails.SelectMany(e => e));
}
private async Task<IEnumerable<string>> GetEmails(string hashTag)
{
var subscriptions = await _mediator.Send(new GetSubscriptionsByHashTagQuery(hashTag));
return subscriptions.Select(s => s.Email);
}
// TODO: Use Templates?
private static string GetMessage(string title)
{
return $"<h2>{title}</h2>" +
"Visit the Blog to read the new article.";
}
}
} |
using System.Data;
using System.IO;
namespace Kore.Data
{
public static class DataSetExtensions
{
public static void ToCsv(this DataSet dataSet, string directoryPath)
{
dataSet.ToCsv(directoryPath, true);
}
public static void ToCsv(this DataSet dataSet, string directoryPath, bool outputColumnNames)
{
string tableName = string.Empty;
int tableCount = 0;
foreach (DataTable table in dataSet.Tables)
{
if (!string.IsNullOrEmpty(table.TableName))
{
tableName = table.TableName;
}
else
{ tableName = string.Concat("Table", tableCount++); }
table.ToCsv(Path.Combine(directoryPath, string.Concat(tableName, ".csv")), outputColumnNames);
}
}
}
} |
using System;
using Hik.Communication.Mbt.Client;
using Hik.Communication.Mbt.Client.Tcp;
using Hik.Communication.Mbt.Server;
using Hik.Communication.Mbt.Server.Tcp;
namespace Hik.Communication.Mbt.Communication.EndPoints.Tcp
{
/// <summary>
/// Represens a TCP end point in MBT.
/// </summary>
public sealed class MbtTcpEndPoint : MbtEndPoint
{
///<summary>
/// IP address of the server.
///</summary>
public string IpAddress { get; set; }
///<summary>
/// Listening TCP Port for incoming connection requests on server.
///</summary>
public int TcpPort { get; private set; }
/// <summary>
/// Creates a new MbtTcpEndPoint object with specified port number.
/// </summary>
/// <param name="tcpPort">Listening TCP Port for incoming connection requests on server</param>
public MbtTcpEndPoint(int tcpPort)
{
TcpPort = tcpPort;
}
/// <summary>
/// Creates a new MbtTcpEndPoint object with specified IP address and port number.
/// </summary>
/// <param name="ipAddress">IP address of the server</param>
/// <param name="port">Listening TCP Port for incoming connection requests on server</param>
public MbtTcpEndPoint(string ipAddress, int port)
{
IpAddress = ipAddress;
TcpPort = port;
}
/// <summary>
/// Creates a new MbtTcpEndPoint from a string address.
/// Address format must be like IPAddress:Port (For example: 127.0.0.1:10085).
/// </summary>
/// <param name="address">TCP end point Address</param>
/// <returns>Created MbtTcpEndpoint object</returns>
public MbtTcpEndPoint(string address)
{
var splittedAddress = address.Trim().Split(':');
IpAddress = splittedAddress[0].Trim();
TcpPort = Convert.ToInt32(splittedAddress[1].Trim());
}
/// <summary>
/// Creates a Mbt Server that uses this end point to listen incoming connections.
/// </summary>
/// <returns>Mbt Server</returns>
internal override IMbtServer CreateServer()
{
return new MbtTcpServer(this);
}
/// <summary>
/// Creates a Mbt Client that uses this end point to connect to server.
/// </summary>
/// <returns>Mbt Client</returns>
internal override IMbtClient CreateClient()
{
return new MbtTcpClient(this);
}
/// <summary>
/// Generates a string representation of this end point object.
/// </summary>
/// <returns>String representation of this end point object</returns>
public override string ToString()
{
return string.IsNullOrEmpty(IpAddress) ? ("tcp://" + TcpPort) : ("tcp://" + IpAddress + ":" + TcpPort);
}
}
} |
using System;
using System.Collections.Generic;
using Game.Engine.Monsters.MonsterFactories;
using Game.Engine.Monsters;
using System.Windows;
using Game.Engine.Interactions;
using System.Windows.Controls;
using System.Text.RegularExpressions;
using System.IO;
using Game.Engine.Interactions.InteractionFactories;
namespace Game.Engine
{
// container class for an integer matrix that represents game map grid
// map codes:
// 0 - unpassable terrain (the character cannot go there)
// 1 - normal terrain (walkable, but nothing happens)
// 1000 - battle with a monster
// 2000 to 2999 - portal to another map
// 3000 and above - a custom interaction
// -1 to -999 - unpassable terrain (just like 0 but with nicer display)
[Serializable]
class MapMatrix
{
// map parameters
private int monsters;
private int walls;
// other fields and properties
private Random rng;
private GameSession parentSession;
public Dictionary<int, MonsterFactory> MonDict; // key - position number on board, value - monster factory located there
public Dictionary<int, Monster> MemorizedMonsters { get; set; } // for keeping exactly the same monster between battles
public Dictionary<int, Interaction> Interactions { get; private set; } // same as MonDict, but for interactions
public int[,] Matrix { get; set; } // matrix with all board positions
public int Width { get; protected set; } = 25;
public int Height { get; protected set; } = 20;
public MapMatrix(GameSession parent, string Path)
{
parentSession = parent;
Matrix = new int[Height, Width];
List<string> positionList = new List<string>();
List<int> finalList = new List<int>();
Regex reg = new Regex("\t");
foreach (string pos in File.ReadAllLines(Path))
{
positionList.Add(pos);
}
foreach (string pos in positionList)
{
string[] elements = reg.Split(pos);
List<string> elementList = new List<string>();
foreach (string element in elements)
{
elementList.Add(element);
}
foreach (string el in elementList)
{
finalList.Add(Int32.Parse(el));
}
}
MemorizedMonsters = new Dictionary<int, Monster>();
Interactions = new Dictionary<int, Interaction>();
MonDict = new Dictionary<int, MonsterFactory>();
int index = 0;
for (int y = 1; y < Height - 1; y++)
{
for (int x = 1; x < Width; x++)
{
Matrix[y, x] = finalList[index];
if (finalList[index] > 1000 && finalList[index] < 2000)
{
MonDict.Add(y * Width + x, Index.MonsterFactories[Matrix[y, x] - 1001]);
}
else if (finalList[index] > 3000)
{
Interactions.Add(y * Width + x, Index.GetInteractionByNumber(parentSession, finalList[index] - 3000));
}
index++;
}
}
}
public MapMatrix(GameSession parent, List<int> portals, List<Interaction> inters, int randomCode, (int, int) mapParams)
{
parentSession = parent;
monsters = mapParams.Item1;
walls = mapParams.Item2;
Matrix = new int[Height, Width];
rng = new Random(randomCode);
// make map walkable
for (int y = 1; y < Height - 1; y++)
{
for (int x = 1; x < Width - 1; x++)
{
Matrix[y, x] = 1;
}
}
// decorate map with stuff
DecorateWithObstacles();
DecorateWithPortals(portals);
DecorateWithInteractions(inters);
DecorateWithMonsters();
// trim walls
for (int y = 0; y < Height; y++) Matrix[y, 0] = 0;
for (int x = 0; x < Width; x++) Matrix[0, x] = 0;
for (int y = 0; y < Height; y++) Matrix[y, Width - 1] = 0;
for (int x = 0; x < Width; x++) Matrix[Height - 1, x] = 0;
// initialize
InitializeRandomFactoryList();
MemorizedMonsters = new Dictionary<int, Monster>();
}
// fill map with monster factories
private void InitializeRandomFactoryList()
{
MonDict = new Dictionary<int, MonsterFactory>();
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
if (Matrix[y, x] == 1000)
{
MonDict.Add(y * Width + x, Index.RandomMonsterFactory());
}
}
}
}
// produce or hint monsters
public Monster CreateMonster(int x, int y, int playerLevel)
{
if (MemorizedMonsters.ContainsKey(y * Width + x) && MemorizedMonsters[y * Width + x] != null) return MemorizedMonsters[y * Width + x];
if (MonDict.ContainsKey(y * Width + x) && MonDict[y * Width + x] != null)
{
return MonDict[y * Width + x].Create();
}
return null;
}
public Image HintMonsterImage(int x, int y)
{
if (MemorizedMonsters.ContainsKey(y * Width + x) && MemorizedMonsters[y * Width + x] != null) return MemorizedMonsters[y * Width + x].GetImage();
if (MonDict.ContainsKey(y * Width + x) && MonDict[y * Width + x] != null)
{
return MonDict[y * Width + x].Hint();
}
return null;
}
// decorate map with stuff
private void DecorateWithObstacles()
{
List<(int, int)> BlockCoordinates = new List<(int, int)>();
List<BlockStructure> BlockList = new List<BlockStructure>();
//adding randomly-sized blocks and specific coordinates, placing structures in the given places
//for more info, go to BlockStructure.cs
for (int i = 0; i < 15; i++)
{
BlockList.Add(new BlockStructure(rng.Next(3, 6), rng.Next(3, 6)));
}
//1st row
BlockCoordinates.Add((2, 2));
BlockCoordinates.Add((2, 7));
BlockCoordinates.Add((2, 11));
BlockCoordinates.Add((2, 15));
BlockCoordinates.Add((2, 19));
//2nd row
BlockCoordinates.Add((7, 2));
BlockCoordinates.Add((7, 7));
BlockCoordinates.Add((7, 11));
BlockCoordinates.Add((7, 15));
BlockCoordinates.Add((7, 19));
//3rd row
BlockCoordinates.Add((14, 2));
BlockCoordinates.Add((14, 7));
BlockCoordinates.Add((14, 11));
BlockCoordinates.Add((14, 15));
BlockCoordinates.Add((14, 19));
for (int i = 0; i < BlockList.Count; i++)
{
BlockList[i].LoadStructure(Matrix, BlockCoordinates[i].Item1, BlockCoordinates[i].Item2);
}
// making wertical and/or horizontal edges
int W = 0;
//int W = rng.Next(0, 3); // can be used to produce semi-open maps
int y0 = 1;
int ym = Height - 2;
int x0 = 1;
int xm = Width - 2;
for (int y = y0; y <= ym; y++)
{
if (W != 2)
{
Matrix[y, x0] = -1;
Matrix[y, xm] = -1;
}
}
for (int x = x0; x <= xm; x++)
{
if (W != 1)
{
Matrix[y0, x] = -1;
Matrix[ym, x] = -1;
}
}
//making passages through map
for (int y = y0 + 1; y < ym; y++)
{
Matrix[y, 2] = 1;
Matrix[y, 8] = 1;
Matrix[y, 12] = 1;
Matrix[y, 16] = 1;
Matrix[y, 20] = 1;
Matrix[y, 24] = 1;
}
for (int x = x0 + 1; x < xm; x++)
{
Matrix[2, x] = 1;
Matrix[6, x] = 1;
Matrix[13, x] = 1;
Matrix[17, x] = 1;
}
}
private void DecorateWithPortals(List<int> portals)
{
Random rng = new Random();
foreach (int portal in portals)
{
while (true)
{
int x = rng.Next(2, Width - 2);
int y = rng.Next(2, Height - 2);
if (ValidPlace(x, y))
{
Matrix[y, x] = 2000 + portal;
break;
}
}
}
}
private void DecorateWithInteractions(List<Interaction> inters)
{
Interactions = new Dictionary<int, Interaction>();
Random rng = new Random();
foreach (Interaction inter in inters)
{
while (true)
{
int x = rng.Next(2, Width - 2);
int y = rng.Next(2, Height - 2);
if (ValidPlace(x, y) && Matrix[y, x] == 1)
{
if (Interactions.ContainsKey(Width * y + x)) continue;
Interactions.Add(Width * y + x, inter);
Matrix[y, x] = 3000 + Int32.Parse(inter.Name.Replace("interaction", ""));
break;
}
}
}
}
private void DecorateWithMonsters()
{
Random rng = new Random();
for (int i = 0; i < monsters; i++)
{
int x = rng.Next(2, Width - 2);
int y = rng.Next(2, Height - 2);
if (Matrix[y, x] != 1)
{
i--;
continue;
}
Matrix[y, x] = 1000;
}
}
public bool ValidPlace(int x, int y)
{
// utility
if (x < 1 || y < 1 || x > Width - 2 || y > Height - 2) return false;
if (Matrix[y, x] > 2000) return false;
if ((Matrix[y, x - 1] != 1 && Matrix[y, x + 1] != 1) && (Matrix[y - 1, x] == 1 && Matrix[y + 1, x] == 1)) return false;
if ((Matrix[y - 1, x] != 1 && Matrix[y + 1, x] != 1) && (Matrix[y, x - 1] == 1 && Matrix[y, x + 1] == 1)) return false;
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DMR.WebApp.Areas.Game.Services;
using DMR.WebApp.Models;
namespace DMR.WebApp.Areas.Game.Models.CharacterBodyParts
{
public class Head : Asset, ICharacterAsset
{
public Tag Species { get; set; }
public int Skin { get; set; }
// Extra section styles
public int Horn { get; set; }
public HairStyle Hair { get; set; }
public FaceStyle Face { get; set; }
public EyeStyle Eye { get; set; }
public EyebrowStyle Eyebrow { get; set; }
public EarStyle Ear { get; set; }
public int Cheeks { get; set; }
public IEnumerable<Mouth> Mouths { get; set; }
public int Jaw { get; set; }
public int Beard { get; set; }
public int Neck { get; set; }
}
public enum HairStyle
{
HAIR_NORMAL,
HAIR_FEATHER,
HAIR_GHOST,
HAIR_GOO,
HAIR_ANEMONE
}
public enum FaceStyle
{
FACE_HUMAN,
FACE_HORSE,
FACE_DOG,
FACE_COW_MINOTAUR,
FACE_SHARK_TEETH,
FACE_SNAKE_FANGS,
FACE_CAT,
FACE_LIZARD,
FACE_BUNNY,
FACE_KANGAROO,
FACE_SPIDER_FANGS,
FACE_FOX,
FACE_DRAGON,
FACE_RACCOON_MASK,
FACE_RACCOON,
FACE_BUCKTEETH,
FACE_MOUSE
}
public enum EyeStyle
{
EYES_HUMAN,
EYES_FOUR_SPIDER_EYES,
EYES_BLACK_EYES_SAND_TRAP
}
public enum EyebrowStyle
{
}
public enum EarStyle
{
}
public enum PiercingStyle
{
}
}
|
using System;
namespace NeuralNetwork
{
[Serializable]
public class Dendrite
{
public double Weight { get; set; }
public Dendrite()
{
CryptoRandom n = new CryptoRandom();
this.Weight = n.RandomValue;
}
}
}
|
//==============================================================================
// TorqueLab -> ShapeLab -> Shape Selection
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
// ShapeLab -> Collision editing
//==============================================================================
function ShapeLabCollisions::onShapeSelectionChanged( %this ) {
%this.lastColSettings = "" TAB "Bounds";
// Initialise collision mesh target list
ShapeLab_CreateColRollout-->colTarget.clear();
ShapeLab_CreateColRollout-->colTarget.add( "Bounds" );
%objCount = ShapeLab.shape.getObjectCount();
for ( %i = 0; %i < %objCount; %i++ ) {
ShapeLab_CreateColRollout-->colTarget.add( ShapeLab.shape.getObjectName( %i ) );
}
ShapeLab_CreateColRollout-->colTarget.setSelected( %this-->colTarget.findText( "Bounds" ), false );
}
function ShapeLabCollisions::onCollisionChanged( %this ) {
// Sync collision settings
%colData = %this.lastColSettings;
%typeId = %this-->colType.findText( getField( %colData, 0 ) );
%this-->colType.setSelected( %typeId, false );
%targetId = %this-->colTarget.findText( getField( %colData, 1 ) );
%this-->colTarget.setSelected( %targetId, false );
if ( %this-->colType.getText() $= "Convex Hulls" ) {
show(ShapeLabColCreate_Hull);
hide(ShapeLabColCreate_NoHull);
%this-->hullDepth.setValue( getField( %colData, 2 ) );
%this-->hullDepthText.setText( mFloor( %this-->hullDepth.getValue() ) );
%this-->hullMergeThreshold.setValue( getField( %colData, 3 ) );
%this-->hullMergeText.setText( mFloor( %this-->hullMergeThreshold.getValue() ) );
%this-->hullConcaveThreshold.setValue( getField( %colData, 4 ) );
%this-->hullConcaveText.setText( mFloor( %this-->hullConcaveThreshold.getValue() ) );
%this-->hullMaxVerts.setValue( getField( %colData, 5 ) );
%this-->hullMaxVertsText.setText( mFloor( %this-->hullMaxVerts.getValue() ) );
%this-->hullMaxBoxError.setValue( getField( %colData, 6 ) );
%this-->hullMaxBoxErrorText.setText( mFloor( %this-->hullMaxBoxError.getValue() ) );
%this-->hullMaxSphereError.setValue( getField( %colData, 7 ) );
%this-->hullMaxSphereErrorText.setText( mFloor( %this-->hullMaxSphereError.getValue() ) );
%this-->hullMaxCapsuleError.setValue( getField( %colData, 8 ) );
%this-->hullMaxCapsuleErrorText.setText( mFloor( %this-->hullMaxCapsuleError.getValue() ) );
} else {
hide(ShapeLabColCreate_Hull);
show(ShapeLabColCreate_NoHull);
}
}
//==============================================================================
// TorqueLab Collision Functions
//==============================================================================
|
using Advobot.Attributes;
using Advobot.Attributes.ParameterPreconditions.DiscordObjectValidation.Channels;
using Advobot.Attributes.ParameterPreconditions.Numbers;
using Advobot.Attributes.ParameterPreconditions.Strings;
using Advobot.Attributes.Preconditions;
using Advobot.Attributes.Preconditions.Permissions;
using Advobot.Localization;
using Advobot.Modules;
using Advobot.Resources;
using Advobot.Services.ImageResizing;
using Advobot.Utilities;
using AdvorangesUtils;
using Discord;
using Discord.Commands;
using static Discord.ChannelPermission;
namespace Advobot.Standard.Commands;
[Category(nameof(Guilds))]
public sealed class Guilds : ModuleBase
{
[LocalizedGroup(nameof(Groups.CreateGuild))]
[LocalizedAlias(nameof(Aliases.CreateGuild))]
[LocalizedSummary(nameof(Summaries.CreateGuild))]
[Meta("f3e7e812-067a-4be3-9904-42eb9eac8791", IsEnabled = true)]
[RequireBotOwner]
public sealed class CreateGuild : AdvobotModuleBase
{
[Command]
public async Task Command([Remainder, GuildName] string name)
{
var optimalVoiceRegion = await Context.Client.GetOptimalVoiceRegionAsync().CAF();
var newGuild = await Context.Client.CreateGuildAsync(name, optimalVoiceRegion).CAF();
var defaultChannel = await newGuild.GetDefaultChannelAsync().CAF();
var invite = await defaultChannel.CreateInviteAsync().CAF();
await Context.User.SendMessageAsync(invite.Url).CAF();
}
}
[LocalizedGroup(nameof(Groups.DeleteGuild))]
[LocalizedAlias(nameof(Aliases.DeleteGuild))]
[LocalizedSummary(nameof(Summaries.DeleteGuild))]
[Meta("65ec403c-7287-4689-a2f0-c73cf5407540", IsEnabled = true)]
[RequireBotIsOwner]
[RequireBotOwner]
public sealed class DeleteGuild : AdvobotModuleBase
{
[Command]
public Task Command()
=> Context.Guild.DeleteAsync();
}
[LocalizedGroup(nameof(Groups.LeaveGuild))]
[LocalizedAlias(nameof(Aliases.LeaveGuild))]
[LocalizedSummary(nameof(Summaries.LeaveGuild))]
[Meta("3090730c-1377-4a56-b379-485baed393e7", IsEnabled = true)]
public sealed class LeaveGuild : AdvobotModuleBase
{
[Command]
[RequireGuildOwner]
public Task Command()
=> Context.Guild.LeaveAsync();
[Command]
[RequireBotOwner]
public async Task<RuntimeResult> Command([Remainder] IGuild guild)
{
await guild.LeaveAsync().CAF();
return Responses.Guilds.LeftGuild(guild);
}
}
[LocalizedGroup(nameof(Groups.ModifyGuildAfkChannel))]
[LocalizedAlias(nameof(Aliases.ModifyGuildAfkChannel))]
[LocalizedSummary(nameof(Summaries.ModifyGuildAfkChannel))]
[Meta("ec19c9b8-cc0c-46d6-a207-9eb6abf69c9e", IsEnabled = true)]
[RequireGuildPermissions(GuildPermission.ManageGuild)]
public sealed class ModifyGuildAfkChannel : AdvobotModuleBase
{
[Command]
public async Task<RuntimeResult> Command(
[CanModifyChannel(ManageChannels)] IVoiceChannel? channel)
{
await Context.Guild.ModifyAsync(x => x.AfkChannel = Optional.Create(channel), GenerateRequestOptions()).CAF();
return Responses.Guilds.ModifiedAfkChannel(channel);
}
[LocalizedCommand(nameof(Groups.Remove))]
[LocalizedAlias(nameof(Aliases.Remove))]
public Task<RuntimeResult> Remove()
=> Command(null);
}
[LocalizedGroup(nameof(Groups.ModifyGuildAfkTimer))]
[LocalizedAlias(nameof(Aliases.ModifyGuildAfkTimer))]
[LocalizedSummary(nameof(Summaries.ModifyGuildAfkTimer))]
[Meta("bb4ceabc-2660-431d-aa0c-d0f6176b88a1", IsEnabled = true)]
[RequireGuildPermissions(GuildPermission.ManageGuild)]
public sealed class ModifyGuildAfkTimer : AdvobotModuleBase
{
[Command]
public async Task<RuntimeResult> Command([GuildAfkTime] int time)
{
await Context.Guild.ModifyAsync(x => x.AfkTimeout = time, GenerateRequestOptions()).CAF();
return Responses.Guilds.ModifiedAfkTime(time);
}
}
[LocalizedGroup(nameof(Groups.ModifyGuildExplicitContentFilter))]
[LocalizedAlias(nameof(Aliases.ModifyGuildExplicitContentFilter))]
[LocalizedSummary(nameof(Summaries.ModifyGuildExplicitContentFilter))]
[Meta("a60b0a3c-a890-40c7-83f7-9856da3808fe", IsEnabled = true)]
[RequireGuildPermissions(GuildPermission.ManageGuild)]
public sealed class ModifyGuildExplicitContentFilter : AdvobotModuleBase
{
[Command]
public async Task<RuntimeResult> Command(ExplicitContentFilterLevel filter)
{
await Context.Guild.ModifyAsync(x => x.ExplicitContentFilter = filter, GenerateRequestOptions()).CAF();
return Responses.Guilds.ModifiedGuildContentFilter(filter);
}
}
[LocalizedGroup(nameof(Groups.ModifyGuildIcon))]
[LocalizedAlias(nameof(Aliases.ModifyGuildIcon))]
[LocalizedSummary(nameof(Summaries.ModifyGuildIcon))]
[Meta("c6f5c58e-4784-4f30-91a9-3727e580ddf2", IsEnabled = true)]
[RequireGuildPermissions(GuildPermission.ManageGuild)]
public sealed class ModifyGuildIcon : ImageResizerModule
{
[Command]
public Task<RuntimeResult> Command(Uri url)
{
var position = Enqueue(new IconCreationContext(Context, url, null, "Guild Icon",
(ctx, ms) => ctx.Guild.ModifyAsync(x => x.Icon = new Image(ms), ctx.GenerateRequestOptions())));
return Responses.Snowflakes.EnqueuedIcon(Context.Guild, position);
}
[LocalizedCommand(nameof(Groups.Remove))]
[LocalizedAlias(nameof(Aliases.Remove))]
public async Task<RuntimeResult> Remove()
{
await Context.Guild.ModifyAsync(x => x.Icon = new Image(), GenerateRequestOptions()).CAF();
return Responses.Snowflakes.RemovedIcon(Context.Guild);
}
}
[LocalizedGroup(nameof(Groups.ModifyGuildMsgNotif))]
[LocalizedAlias(nameof(Aliases.ModifyGuildMsgNotif))]
[LocalizedSummary(nameof(Summaries.ModifyGuildMsgNotif))]
[Meta("f32a347c-e2d8-4b64-9a3c-53cd46d0f3ed", IsEnabled = true)]
[RequireGuildPermissions(GuildPermission.ManageGuild)]
public sealed class ModifyGuildMsgNotif : AdvobotModuleBase
{
[Command]
public async Task<RuntimeResult> Command(DefaultMessageNotifications msgNotifs)
{
await Context.Guild.ModifyAsync(x => x.DefaultMessageNotifications = msgNotifs, GenerateRequestOptions()).CAF();
return Responses.Guilds.ModifiedMsgNotif(msgNotifs);
}
}
[LocalizedGroup(nameof(Groups.ModifyGuildName))]
[LocalizedAlias(nameof(Aliases.ModifyGuildName))]
[LocalizedSummary(nameof(Summaries.ModifyGuildName))]
[Meta("54a75c3c-be5a-46d4-93d3-b1cbc1af9def", IsEnabled = true)]
[RequireGuildPermissions(GuildPermission.ManageGuild)]
public sealed class ModifyGuildName : AdvobotModuleBase
{
[Command]
public async Task<RuntimeResult> Command([Remainder, GuildName] string name)
{
await Context.Guild.ModifyAsync(x => x.Name = name, GenerateRequestOptions()).CAF();
return Responses.Snowflakes.ModifiedName(Context.Guild, name);
}
}
[LocalizedGroup(nameof(Groups.ModifyGuildRegion))]
[LocalizedAlias(nameof(Aliases.ModifyGuildRegion))]
[LocalizedSummary(nameof(Summaries.ModifyGuildRegion))]
[Meta("e2ab50b0-ce20-48ee-bac9-1fac2e53387d", IsEnabled = true)]
[RequireGuildPermissions(GuildPermission.ManageGuild)]
public sealed class ModifyGuildRegion : AdvobotModuleBase
{
[Command]
public async Task<RuntimeResult> Command(IVoiceRegion region)
{
await Context.Guild.ModifyAsync(x => x.Region = Optional.Create(region), GenerateRequestOptions()).CAF();
return Responses.Guilds.ModifiedRegion(region);
}
[LocalizedCommand(nameof(Groups.Show))]
[LocalizedAlias(nameof(Aliases.Show))]
[Priority(1)]
public async Task<RuntimeResult> Show()
{
var regions = await Context.Guild.GetVoiceRegionsAsync().CAF();
return Responses.Guilds.DisplayRegions(regions);
}
}
[LocalizedGroup(nameof(Groups.ModifyGuildSplash))]
[LocalizedAlias(nameof(Aliases.ModifyGuildSplash))]
[LocalizedSummary(nameof(Summaries.ModifyGuildSplash))]
[Meta("0a02898e-0e5c-417d-9309-7f93714b61f7", IsEnabled = true)]
[RequireGuildPermissions(GuildPermission.ManageGuild)]
[RequirePartneredGuild]
public sealed class ModifyGuildSplash : ImageResizerModule
{
[Command]
public Task<RuntimeResult> Command(Uri url)
{
var position = Enqueue(new IconCreationContext(Context, url, default, "Guild Splash",
(ctx, ms) => ctx.Guild.ModifyAsync(x => x.Splash = new Image(ms), ctx.GenerateRequestOptions())));
return Responses.Guilds.EnqueuedSplash(position);
}
[LocalizedCommand(nameof(Groups.Remove))]
[LocalizedAlias(nameof(Aliases.Remove))]
public async Task<RuntimeResult> Remove()
{
await Context.Guild.ModifyAsync(x => x.Splash = new Image(), GenerateRequestOptions()).CAF();
return Responses.Guilds.RemovedSplash();
}
}
[LocalizedGroup(nameof(Groups.ModifyGuildSystemChannel))]
[LocalizedAlias(nameof(Aliases.ModifyGuildSystemChannel))]
[LocalizedSummary(nameof(Summaries.ModifyGuildSystemChannel))]
[Meta("f6cc90d9-ae1d-4eab-ae15-226d88e42092", IsEnabled = true)]
[RequireGuildPermissions(GuildPermission.ManageGuild)]
public sealed class ModifyGuildSystemChannel : AdvobotModuleBase
{
[Command]
public async Task<RuntimeResult> Command(
[CanModifyChannel(ManageChannels)] ITextChannel? channel)
{
await Context.Guild.ModifyAsync(x => x.SystemChannel = Optional.Create(channel), GenerateRequestOptions()).CAF();
return Responses.Guilds.ModifiedSystemChannel(channel);
}
[LocalizedCommand(nameof(Groups.MessageBoost))]
[LocalizedAlias(nameof(Aliases.MessageBoost))]
public async Task<RuntimeResult> MessageBoost(bool enable)
{
const SystemChannelMessageDeny FLAG = SystemChannelMessageDeny.GuildBoost;
await Context.Guild.ModifySystemChannelFlags(FLAG, enable, GenerateRequestOptions()).CAF();
return Responses.Guilds.ModifySystemMessageBoost(enable);
}
[LocalizedCommand(nameof(Groups.MessageWelcome))]
[LocalizedAlias(nameof(Aliases.MessageWelcome))]
public async Task<RuntimeResult> MessageWelcome(bool enable)
{
const SystemChannelMessageDeny FLAG = SystemChannelMessageDeny.WelcomeMessage;
await Context.Guild.ModifySystemChannelFlags(FLAG, enable, GenerateRequestOptions()).CAF();
return Responses.Guilds.ModifySystemMessageWelcome(enable);
}
[LocalizedCommand(nameof(Groups.Remove))]
[LocalizedAlias(nameof(Aliases.Remove))]
public Task<RuntimeResult> Remove()
=> Command(null);
}
[LocalizedGroup(nameof(Groups.ModifyGuildVerif))]
[LocalizedAlias(nameof(Aliases.ModifyGuildVerif))]
[LocalizedSummary(nameof(Summaries.ModifyGuildVerif))]
[Meta("5640e2e6-7ee8-416c-982c-9efb22634f54", IsEnabled = true)]
[RequireGuildPermissions(GuildPermission.ManageGuild)]
public sealed class ModifyGuildVerif : AdvobotModuleBase
{
[Command]
public async Task<RuntimeResult> Command(VerificationLevel verif)
{
await Context.Guild.ModifyAsync(x => x.VerificationLevel = verif, GenerateRequestOptions()).CAF();
return Responses.Guilds.ModifiedVerif(verif);
}
}
[LocalizedGroup(nameof(Groups.SwapGuildOwner))]
[LocalizedAlias(nameof(Aliases.SwapGuildOwner))]
[LocalizedSummary(nameof(Summaries.SwapGuildOwner))]
[Meta("3cb8a267-5d62-4644-b5af-60281dd8e182", IsEnabled = true)]
[RequireBotIsOwner]
[RequireBotOwner]
public sealed class SwapGuildOwner : AdvobotModuleBase
{
[Command]
public async Task<RuntimeResult> Command()
{
await Context.Guild.ModifyAsync(x => x.Owner = new Optional<IUser>(Context.User)).CAF();
return Responses.Guilds.ModifiedOwner(Context.User);
}
}
} |
@model MyStik.TimeTable.Web.Models.AgendaViewModel
@{
ViewBag.Title = "Tagesplan";
}
@Html.Partial("Agenda", Model)
|
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace Podcasts
{
public class RootPage : Page
{
StackData stackData;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
UseLayoutRounding = true;
base.OnNavigatedTo(e);
stackData = GlobalStateManager.CurrentShell.GetTopStack();
if (e.NavigationMode == NavigationMode.Back)
{
GlobalStateManager.SelectedMenuIndex = stackData.MenuIndex;
}
App.TrackPage(GetType().Name);
Loaded += RootPage_Loaded;
}
private void RootPage_Loaded(object sender, RoutedEventArgs e)
{
stackData.MenuIndex = GlobalStateManager.SelectedMenuIndex;
}
internal virtual void ClearReferences()
{
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
if (e.NavigationMode == NavigationMode.Back || GlobalStateManager.CurrentShell.IsRootNavigation)
{
NavigationCacheMode = NavigationCacheMode.Disabled;
}
Loaded -= RootPage_Loaded;
ClearReferences();
base.OnNavigatingFrom(e);
}
public void UpdateTopStackFiltersData(string value)
{
if (stackData == null)
{
return;
}
stackData.FiltersData = value;
}
public void UpdateTopStackScrollPosition(string value)
{
if (stackData == null)
{
return;
}
stackData.ScrollPosition = value;
}
public string GetTopStackScrollPosition()
{
return stackData.ScrollPosition;
}
public string GetTopStackValueAsString()
{
return stackData.Data;
}
public string GetTopStackFiltersData()
{
return stackData.FiltersData;
}
public int[] GetTopStackValueAsIntArray()
{
return stackData.IDs;
}
public int GetTopStackValueAsInt()
{
return stackData.ID;
}
public bool IsTopStackValueIntArray()
{
return stackData.IDs != null;
}
public void SetTopStackValueAsInt(int id)
{
stackData.ID = id;
}
public bool IsTopStackValueString()
{
return !string.IsNullOrEmpty(stackData.Data);
}
public bool IsTopStackScrollPosition()
{
return !string.IsNullOrEmpty(stackData.ScrollPosition);
}
public int GetTopStackMenuIndex()
{
return stackData.MenuIndex;
}
}
}
|
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Snippy.Infrastructure
{
internal static class Extensions
{
public static bool IsNullOrWhiteSpace(this string value) => string.IsNullOrWhiteSpace(value);
public static Process Run(this string filePath)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return Process.Start(new ProcessStartInfo
{
FileName = "explorer",
Arguments = "\"" + filePath + "\"",
UseShellExecute = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
});
}
return Process.Start(new ProcessStartInfo(filePath)
{
UseShellExecute = true
});
}
public static Process RunWithCode(this string filePath)
{
return Process.Start(new ProcessStartInfo
{
FileName = "code",
Arguments = "\"" + filePath + "\"",
UseShellExecute = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
});
}
public static DateTime? FromUtcToLocal(this DateTime? utc) =>
utc.HasValue ? TimeZoneInfo.ConvertTimeFromUtc(utc.Value, TimeZoneInfo.Local) : (DateTime?)null;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Player3D3P : MonoBehaviour
{
public InputMaster controls;
[Range(0,20)]
public float playerSpeed = 8f;
private Vector2 _moveOutput;
private void Awake()
{
controls = new InputMaster();
controls.PlayerThreeDThirdPerson.Movement.performed += context => Move(context.ReadValue<Vector2>());
controls.Enable();
}
private void FixedUpdate()
{
// basic movement translation
transform.position += (new Vector3(_moveOutput.x, 0, _moveOutput.y) * playerSpeed * Time.deltaTime);
}
public void Move(Vector2 direction)
{
_moveOutput = direction;
}
private void OnEnable()
{
controls = new InputMaster();
controls.Enable();
}
private void OnDisable()
{
controls = new InputMaster();
controls.Disable();
}
}
|
using GzyConcept.Core.ServiceAbstractions;
using SimpleInjector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GzyConcept.Core.Common
{
public class DependencyInversionService : IDependencyResolution
{
public readonly Container Container;
private static volatile DependencyInversionService _service;
private static object _lock = new object();
private DependencyInversionService()
{
if (Container == null)
{
Container = new Container();
}
}
public static DependencyInversionService GetServiceInstance()
{
if (_service == null)
{
lock (_lock)
{
_service = new DependencyInversionService();
}
}
return _service;
}
public T GetInstance<T>() where T : class
{
return Container.GetInstance<T>();
}
}
}
|
using DesafioFULL.Domain.Interfaces.Repositorys;
using DesafioFULL.Domain.Interfaces.Services;
using System;
using System.Collections.Generic;
namespace DesafioFULL.Domain.Service
{
public abstract class ServiceBase<TEntity> : IDisposable, IServiceBase<TEntity> where TEntity : class
{
private readonly IRepositoryBase<TEntity> _repository;
public ServiceBase(IRepositoryBase<TEntity> Repository)
{
_repository = Repository;
}
public virtual TEntity Add(TEntity obj)
{
return _repository.Add(obj);
}
public virtual TEntity GetById(int id)
{
return _repository.GetById(id);
}
public virtual IEnumerable<TEntity> GetAll()
{
return _repository.GetAll();
}
public virtual void Update(TEntity obj)
{
_repository.Update(obj);
}
public virtual void Remove(TEntity obj)
{
_repository.Remove(obj);
}
public virtual void Dispose()
{
_repository.Dispose();
}
public IEnumerable<TEntity> GetByProperty(string property, object id)
{
return _repository.GetByProperty(property, id);
}
}
}
|
using System;
using UnityEngine;
using UnityEngine.UI;
namespace FineGameDesign.Utils
{
public sealed class PauseSystemView : ASingletonView<PauseSystem>
{
[Serializable]
public struct StateNameLink
{
public PauseSystem.State state;
public string name;
}
[SerializeField]
private Button[] m_PauseButtons;
[SerializeField]
private Button[] m_ResumeButtons;
[Header("Optional. Quits application.")]
[SerializeField]
private Button m_QuitButton;
[Header("Optional: Plays linked animation name.")]
[SerializeField]
private Animator m_PauseAnimator;
[SerializeField]
private StateNameLink[] m_AnimationLinks;
/// <summary>
/// On enable, resets.
/// Otherwise, if set paused in editor,
/// in play mode pause overlay did not appear.
/// </summary>
private void OnEnable()
{
controller.Reset();
AddListeners();
}
private void OnDisable()
{
RemoveListeners();
}
private void AddListeners()
{
UpdateAnimation(controller.state);
PauseSystem.onStateChanged += UpdateAnimation;
foreach (var button in m_PauseButtons)
button.onClick.AddListener(controller.Pause);
foreach (var button in m_ResumeButtons)
button.onClick.AddListener(controller.Resume);
if (m_QuitButton != null)
m_QuitButton.onClick.AddListener(Quit);
}
private void RemoveListeners()
{
PauseSystem.onStateChanged -= UpdateAnimation;
foreach (var button in m_PauseButtons)
button.onClick.RemoveListener(controller.Pause);
foreach (var button in m_ResumeButtons)
button.onClick.RemoveListener(controller.Resume);
if (m_QuitButton != null)
m_QuitButton.onClick.RemoveListener(Quit);
}
private void Update()
{
controller.Update(Time.deltaTime);
}
private void UpdateAnimation(PauseSystem.State state)
{
if (m_PauseAnimator == null)
{
return;
}
foreach (StateNameLink link in m_AnimationLinks)
{
if (link.state != state)
continue;
AnimationView.SetState(m_PauseAnimator, link.name);
break;
}
}
private void Quit()
{
Application.Quit();
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#endif
}
}
}
|
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.
using Sce.Atf.VectorMath;
namespace LevelEditorCore
{
/// <summary>
/// Interface for objects that maintain 3D transformation information</summary>
public interface ITransformable
{
/// <summary>
/// Updates transformation matrix using the following transformable properties
/// Translation, Rotation, Scale, and Pivot
/// In most cases the Transform will be auto-updated
/// </summary>
/// <remarks>You should manually call this method when creating new
/// GameObject and setting its Transformable properties</remarks>
void UpdateTransform();
/// <summary>
/// Gets local transformation matrix.
/// This is derived from the various
/// components below.</summary>
Matrix4F Transform
{
get;
}
/// <summary>
/// Gets and sets the node translation. Check TransformationType before using 'set'.</summary>
/// <remarks>If unimplemented, 'get' should return Vec3F.ZeroVector</remarks>
Vec3F Translation
{
get;
set;
}
/// <summary>
/// Gets and sets the node rotation. Check TransformationType before using 'set'</summary>
/// <remarks>If unimplemented, 'get' should return Vec3F.ZeroVector</remarks>
Vec3F Rotation
{
get;
set;
}
/// <summary>
/// Gets and sets the node scale. Check TransformationType before using 'set'</summary>
/// <remarks>If unimplemented, 'get' should return new Vec3F{1,1,1}</remarks>
Vec3F Scale
{
get;
set;
}
/// <summary>
/// Gets and sets the translation to origin of scaling. Check TransformationType before using 'set'.</summary>
/// <remarks>If unimplemented, 'get' should return Vec3F.ZeroVector</remarks>
Vec3F Pivot
{
get;
set;
}
/// <summary>
/// Gets or sets what type of transformation this object can support. All of the transformation properties
/// have a valid 'get', but check the appropriate flag before setting the property.</summary>
TransformationTypes TransformationType
{
get;
set;
}
}
}
|
// MemberAccess
#define UNITY_ASSERTIONS
using ClubPenguin.Adventure;
using Disney.LaunchPadFramework;
using Disney.MobileNetwork;
using System;
using UnityEngine;
using UnityEngine.Assertions;
public class MemberAccess : MonoBehaviour
{
public bool isMemberOnly = true;
public string[] QuestNameExclusions;
public string[] QuestObjectiveExclusions;
public bool IsMemberLocked => isMemberOnly && !isMembershipIgnoredForActiveQuestObjective();
public void OnValidate()
{
}
private bool isMembershipIgnoredForActiveQuestObjective()
{
try
{
if (QuestNameExclusions != null && QuestNameExclusions.Length > 0)
{
Quest activeQuest = Service.Get<QuestService>().ActiveQuest;
if (activeQuest != null)
{
for (int i = 0; i < QuestNameExclusions.Length; i++)
{
Assert.IsTrue(!string.IsNullOrEmpty(QuestNameExclusions[i]), "Quest name cannot be empty");
Assert.IsTrue(!string.IsNullOrEmpty(QuestObjectiveExclusions[i]), "Quest objective cannot be empty");
Assert.IsTrue(!string.IsNullOrEmpty(activeQuest.Id), "Quest id cannot be empty");
Assert.IsTrue(!string.IsNullOrEmpty(activeQuest.CurrentObjectiveName), "Quest objective cannot be empty");
if (activeQuest.Id == QuestNameExclusions[i] && activeQuest.CurrentObjectiveName == QuestObjectiveExclusions[i])
{
return true;
}
}
}
}
}
catch (Exception)
{
Log.LogError(this, "Failed to query quest service. Membership line enforced by default.");
}
return false;
}
}
|
@model SimplCommerce.Module.Payments.ViewModels.CheckoutPaymentForm
@{
ViewBag.Title = "Payment Information";
}
<h2>@Localizer["Select payment method"]</h2>
<div class="row">
<div class="col-md-12 text-center">
@foreach (var paymentProvider in Model.PaymentProviders)
{
<div class="payment-method paymentProvider-@paymentProvider.Id">
@if(!string.IsNullOrWhiteSpace(paymentProvider.LandingViewComponentName))
{
@await Component.InvokeAsync(paymentProvider.LandingViewComponentName)
}
</div>
}
</div>
<div class="col-md-12">
@await Component.InvokeAsync("OrderSummary")
</div>
</div>
|
namespace H8QMedia.Services.Data.Contracts
{
public interface IPurchasesService
{
}
}
|
using UnityEngine;
// Adapted from the 3D math function collection at
// https://wiki.unity3d.com/index.php/3d_Math_functions by Bit Barrel Media
public static class Geometry
{
/// <summary>
/// This function returns a point which is a projection from a point to a line.
/// The line is regarded infinite. If the line is finite, use ProjectPointOnLineSegment() instead.
/// </summary>
public static Vector2 ProjectPointOnLine(Vector2 linePoint, Vector2 lineVec, Vector2 point)
{
//get vector from point on line to point in space
Vector2 linePointToPoint = point - linePoint;
float t = Vector2.Dot(linePointToPoint, lineVec);
return linePoint + lineVec * t;
}
/// <summary>
/// This function returns a point which is a projection from a point to a line segment.
/// If the projected point lies outside of the line segment, the projected point will
/// be clamped to the appropriate line edge.
/// If the line is infinite instead of a segment, use ProjectPointOnLine() instead.
/// </summary>
public static Vector2 ProjectPointOnLineSegment(Vector2 linePoint1, Vector2 linePoint2, Vector2 point)
{
Vector2 vector = linePoint2 - linePoint1;
Vector2 projectedPoint = ProjectPointOnLine(linePoint1, vector.normalized, point);
int side = PointOnWhichSideOfLineSegment(linePoint1, linePoint2, projectedPoint);
switch (side)
{
case 0: return projectedPoint; //The projected point is on the line segment
case 1: return linePoint1;
case 2: return linePoint2;
default: return Vector2.zero; //output is invalid
}
}
/// <summary>
/// This function finds out on which side of a line segment the point is located.
/// The point is assumed to be on a line created by linePoint1 and linePoint2. If the point is not on
/// the line segment, project it on the line using ProjectPointOnLine() first.
/// Returns 0 if point is on the line segment.
/// Returns 1 if point is outside of the line segment and located on the side of linePoint1.
/// Returns 2 if point is outside of the line segment and located on the side of linePoint2.
/// </summary>
public static int PointOnWhichSideOfLineSegment(Vector2 linePoint1, Vector2 linePoint2, Vector2 point)
{
Vector2 lineVec = linePoint2 - linePoint1;
Vector2 pointVec = point - linePoint1;
float dot = Vector2.Dot(pointVec, lineVec);
//point is on side of linePoint2, compared to linePoint1
if (dot > 0)
{
//point is on the line segment
if (pointVec.magnitude <= lineVec.magnitude)
return 0;
//point is not on the line segment and it is on the side of linePoint2
else
return 2;
}
//Point is not on side of linePoint2, compared to linePoint1.
//Point is not on the line segment and it is on the side of linePoint1.
else
return 1;
}
}
|
using System;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using R5T.Aalborg;
using R5T.D0053;
namespace R5T.D0051.Gmail.LessSecure
{
public class EmailSender : ILessSecureGmailNetMailSender
{
public const string GmailSmtpServerHostName = "smtp.gmail.com";
public const int TlsPortNumber = 587;
private IGmailAuthenticationProvider GmailAuthenticationProvider { get; }
private ILogger Logger { get; }
public EmailSender(
IGmailAuthenticationProvider gmailAuthenticationProvider,
ILogger<EmailSender> logger)
{
this.GmailAuthenticationProvider = gmailAuthenticationProvider;
this.Logger = logger;
}
public async Task Send(MailMessage emailMessage)
{
var authentication = await this.GmailAuthenticationProvider.GetGmailAuthentication();
var credential = authentication.GetNetworkCredential();
try
{
using (var smtpClient = new SmtpClient()
{
Host = EmailSender.GmailSmtpServerHostName,
Port = EmailSender.TlsPortNumber,
Credentials = credential,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
})
{
await smtpClient.SendMailAsync(emailMessage);
this.Logger.LogInformation("Send email.");
}
}
catch (Exception exception)
{
this.Logger.LogError(exception, "Failed to send email.");
throw exception; // Re-throw.
}
}
}
}
|
using System.Diagnostics.CodeAnalysis;
using Ardalis.SmartEnum;
namespace LanceC.SpreadsheetIO.Shared;
/// <summary>
/// Represents the kind of cell date.
/// </summary>
[ExcludeFromCodeCoverage]
public class CellDateKind : SmartEnum<CellDateKind>
{
/// <summary>
/// Specifies a date written as a number with a format required for readability.
/// </summary>
public static readonly CellDateKind Number = new(1, "Number");
/// <summary>
/// Specifies a date written as text where formatting cannot be modified.
/// </summary>
public static readonly CellDateKind Text = new(2, "Text");
private CellDateKind(int id, string name)
: base(name, id)
{
}
}
|
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelChange : MonoBehaviour
{
public Animator animator;
public int levelToLoad;
public int LevelConditionsMet;
private void Update()
{
if (LevelConditionsMet == 1)
{
FadeToLevel(1);
}
}
public void FadeToLevel (int levelIndex)
{
animator.SetTrigger("FadeOut");
}
public void OnFadeComplete ()
{
SceneManager.LoadScene(levelToLoad);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace NPOI.OpenXmlFormats.Dml.Chart
{
[Serializable]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/chart")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/chart", IsNullable = true)]
public class CT_View3D
{
private CT_RotX rotXField;
private CT_HPercent hPercentField;
private CT_RotY rotYField;
private CT_DepthPercent depthPercentField;
private CT_Boolean rAngAxField;
private CT_Perspective perspectiveField;
private List<CT_Extension> extLstField;
[XmlElement(Order = 0)]
public CT_RotX rotX
{
get
{
return rotXField;
}
set
{
rotXField = value;
}
}
[XmlElement(Order = 1)]
public CT_HPercent hPercent
{
get
{
return hPercentField;
}
set
{
hPercentField = value;
}
}
[XmlElement(Order = 2)]
public CT_RotY rotY
{
get
{
return rotYField;
}
set
{
rotYField = value;
}
}
[XmlElement(Order = 3)]
public CT_DepthPercent depthPercent
{
get
{
return depthPercentField;
}
set
{
depthPercentField = value;
}
}
[XmlElement(Order = 4)]
public CT_Boolean rAngAx
{
get
{
return rAngAxField;
}
set
{
rAngAxField = value;
}
}
[XmlElement(Order = 5)]
public CT_Perspective perspective
{
get
{
return perspectiveField;
}
set
{
perspectiveField = value;
}
}
[XmlElement(Order = 6)]
public List<CT_Extension> extLst
{
get
{
return extLstField;
}
set
{
extLstField = value;
}
}
public static CT_View3D Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
{
return null;
}
CT_View3D cT_View3D = new CT_View3D();
cT_View3D.extLst = new List<CT_Extension>();
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.LocalName == "rotX")
{
cT_View3D.rotX = CT_RotX.Parse(childNode, namespaceManager);
}
else if (childNode.LocalName == "hPercent")
{
cT_View3D.hPercent = CT_HPercent.Parse(childNode, namespaceManager);
}
else if (childNode.LocalName == "rotY")
{
cT_View3D.rotY = CT_RotY.Parse(childNode, namespaceManager);
}
else if (childNode.LocalName == "depthPercent")
{
cT_View3D.depthPercent = CT_DepthPercent.Parse(childNode, namespaceManager);
}
else if (childNode.LocalName == "rAngAx")
{
cT_View3D.rAngAx = CT_Boolean.Parse(childNode, namespaceManager);
}
else if (childNode.LocalName == "perspective")
{
cT_View3D.perspective = CT_Perspective.Parse(childNode, namespaceManager);
}
else if (childNode.LocalName == "extLst")
{
cT_View3D.extLst.Add(CT_Extension.Parse(childNode, namespaceManager));
}
}
return cT_View3D;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<c:{0}", nodeName));
sw.Write(">");
if (rotX != null)
{
rotX.Write(sw, "rotX");
}
if (hPercent != null)
{
hPercent.Write(sw, "hPercent");
}
if (rotY != null)
{
rotY.Write(sw, "rotY");
}
if (depthPercent != null)
{
depthPercent.Write(sw, "depthPercent");
}
if (rAngAx != null)
{
rAngAx.Write(sw, "rAngAx");
}
if (perspective != null)
{
perspective.Write(sw, "perspective");
}
if (extLst != null)
{
foreach (CT_Extension item in extLst)
{
item.Write(sw, "extLst");
}
}
sw.Write(string.Format("</c:{0}>", nodeName));
}
}
}
|
using System.Threading.Tasks;
using VerifyWhiteListCompany.Lib.WebServiceModel;
using System;
namespace VerifyWhiteListCompany.Lib
{
interface IWhiteListClient
{
void Init(string url);
Task<EntryListResponse> VerifyCompanies(string nips, DateTime date);
}
}
|
namespace TreehouseDefense
{
static class Random
{
private static System.Random _random = new System.Random();
public static double NextDouble()
{
return _random.NextDouble();
}
}
} |
using System.Collections.Generic;
using System.Xml.Serialization;
using UnityEngine;
[CreateAssetMenu(fileName = "DialogXMLObject", menuName = "Dialog XML object")]
[XmlRoot("dialogs")]
public class DialogXMLObject : ScriptableObject {
// Could add name, box color, position...
[SerializeField] private TextAsset dialogXmlAsset;
[XmlRoot("Dialog")]
public class Dialog {
[XmlElement("Line")] public List<Line> LinesList = new List<Line>();
}
public class Line {
[XmlAttribute("Id")] public string id;
[XmlElement("Text")] public List<string> text = new List<string>();
}
public Dialog Load() {
return LoadXML(dialogXmlAsset);
}
private Dialog LoadXML(TextAsset textAsset) {
var serializer = new XmlSerializer(typeof(Dialog));
using (var reader = new System.IO.StringReader(textAsset.text)) {
return serializer.Deserialize(reader) as Dialog;
}
}
} |
// Lexxys Infrastructural library.
// file: Ref.cs
//
// Copyright (c) 2001-2014, Kraft Pro Utilities.
// You may use this code under the terms of the MIT license
//
using System;
using System.Threading;
namespace Lexxys
{
public class Out<T>: IValue<T>
{
private readonly Func<T> _getter;
public Out(Func<T> getter)
{
_getter = getter;
}
public virtual T Value
{
get => _getter();
set => throw new NotImplementedException("Out<T>.Value.get");
}
object IValue.Value => Value;
public static implicit operator T(Out<T> value) => value.Value;
}
public sealed class Ref<T>: Out<T>
{
private readonly Action<T> _setter;
public Ref(Func<T> getter, Action<T> setter): base(getter)
{
_setter = setter;
}
public override T Value
{
get => base.Value;
set => _setter(value);
}
public static implicit operator T(Ref<T> value) => value.Value;
public static implicit operator Ref<T>(T value)
{
var boxed = new Boxed { Value = value };
return new Ref<T>(() => boxed.Value, v => Interlocked.Exchange(ref boxed, new Boxed { Value = v }));
}
private class Boxed { public T Value; }
}
public class OptOut<T>: IValue<T>, IOptions<T> where T : class, new()
{
protected readonly Func<T> _getter;
public OptOut(Func<T> getter)
{
_getter = getter;
}
public virtual T Value
{
get => _getter();
set => throw new NotImplementedException("Out<T>.Value.get");
}
object IValue.Value => Value;
public static implicit operator T(OptOut<T> value) => value.Value;
public static implicit operator Out<T>(OptOut<T> value) => new Out<T>(value._getter);
}
public sealed class OptRef<T>: OptOut<T> where T : class, new()
{
private readonly Action<T> _setter;
public OptRef(Func<T> getter, Action<T> setter) : base(getter)
{
_setter = setter;
}
public override T Value
{
get => base.Value;
set => _setter(value);
}
public static implicit operator T(OptRef<T> value) => value.Value;
public static implicit operator OptRef<T>(T value)
{
var copy = value;
return new OptRef<T>(() => copy, v => Interlocked.Exchange(ref copy, v));
}
public static implicit operator Ref<T>(OptRef<T> value) => new Ref<T>(value._getter, value._setter);
}
}
|
using System.Diagnostics;
using Ebby;
namespace nucs.Chaining {
public delegate E E(Chain c);
[DebuggerStepThrough]
public class Chain : BaseChain<E, E> {
public static Chain Build(E func) { return new Chain(func); }
public Chain(E script) : base(script) { }
protected Chain() { }
#region Overrides of BaseChain<E>
protected override E InvokeDelegate(E @delegate) { return @delegate?.Invoke(this); }
/// <summary>
/// How should be <typeparamref name="TDelegate"/> be invoked?
/// </summary>
protected override E InvokeReturnedDelegate(E @delegate) {return @delegate?.Invoke(this);}
protected override E NullReturningDelegate { get; } = c => null;
#endregion
}
} |
using log4net.Repository;
using System;
namespace log4net.Core
{
/// <summary>
/// Provides data for the <see cref="E:log4net.Core.IRepositorySelector.LoggerRepositoryCreatedEvent" /> event.
/// </summary>
/// <remarks>
/// <para>
/// A <see cref="E:log4net.Core.IRepositorySelector.LoggerRepositoryCreatedEvent" />
/// event is raised every time a <see cref="T:log4net.Repository.ILoggerRepository" /> is created.
/// </para>
/// </remarks>
public class LoggerRepositoryCreationEventArgs : EventArgs
{
/// <summary>
/// The <see cref="T:log4net.Repository.ILoggerRepository" /> created
/// </summary>
private ILoggerRepository m_repository;
/// <summary>
/// The <see cref="T:log4net.Repository.ILoggerRepository" /> that has been created
/// </summary>
/// <value>
/// The <see cref="T:log4net.Repository.ILoggerRepository" /> that has been created
/// </value>
/// <remarks>
/// <para>
/// The <see cref="T:log4net.Repository.ILoggerRepository" /> that has been created
/// </para>
/// </remarks>
public ILoggerRepository LoggerRepository => m_repository;
/// <summary>
/// Construct instance using <see cref="T:log4net.Repository.ILoggerRepository" /> specified
/// </summary>
/// <param name="repository">the <see cref="T:log4net.Repository.ILoggerRepository" /> that has been created</param>
/// <remarks>
/// <para>
/// Construct instance using <see cref="T:log4net.Repository.ILoggerRepository" /> specified
/// </para>
/// </remarks>
public LoggerRepositoryCreationEventArgs(ILoggerRepository repository)
{
m_repository = repository;
}
}
}
|
//===============================================================================================================
// System : Visual Studio Spell Checker Package
// File : SpellingDictionary.cs
// Authors : Noah Richards, Roman Golovin, Michael Lehenbauer, Eric Woodruff
// Updated : 02/04/2020
// Note : Copyright 2010-2020, Microsoft Corporation, All rights reserved
// Portions Copyright 2013-2020, Eric Woodruff, All rights reserved
//
// This file contains a class that implements the spelling dictionary service
//
// This code is published under the Microsoft Public License (Ms-PL). A copy of the license should be
// distributed with the code and can be found at the project website: https://github.com/EWSoftware/VSSpellChecker
// This notice, the author's name, and all copyright notices must remain intact in all applications,
// documentation, and source files.
//
// Date Who Comments
// ==============================================================================================================
// 04/14/2013 EFW Imported the code into the project
// 04/15/2013 EFW Added support for NHunspell and language specific dictionaries
// 05/31/2013 EFW Added support for Ignore Once
// 07/28/2015 EFW Added support for culture information in the spelling suggestions
// 08/01/2015 EFW Added support for multiple dictionary languages
//===============================================================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.VisualStudio.Text;
using VisualStudio.SpellChecker.Definitions;
namespace VisualStudio.SpellChecker
{
/// <summary>
/// This class implements the spelling dictionary service. The spelling dictionary utilizes NHunspell to
/// perform the spell checking.
/// </summary>
internal sealed class SpellingDictionary
{
#region Private data members
//=====================================================================
private readonly IEnumerable<string> ignoredWords;
#endregion
#region Properties
//=====================================================================
/// <summary>
/// This read-only property returns the dictionary count
/// </summary>
public int DictionaryCount { get; }
/// <summary>
/// This read-only property returns the list of dictionaries being used for spell checking
/// </summary>
public IEnumerable<GlobalDictionary> Dictionaries { get; }
/// <summary>
/// This read-only property is used to see if the dictionary is fully initialized and ready for use
/// </summary>
public bool IsReadyForUse => this.Dictionaries.All(d => d.IsInitialized);
#endregion
#region Constructor
//=====================================================================
/// <summary>
/// Constructor
/// </summary>
/// <param name="dictionaries">The dictionaries to use</param>
/// <param name="ignoredWords">An optional enumerable list of ignored words</param>
public SpellingDictionary(IEnumerable<GlobalDictionary> dictionaries, IEnumerable<string> ignoredWords)
{
this.DictionaryCount = dictionaries.Count();
this.Dictionaries = dictionaries;
this.ignoredWords = (ignoredWords ?? Enumerable.Empty<string>());
// Register to receive events when any of the global dictionaries are updated
foreach(var d in dictionaries)
d.RegisterSpellingDictionaryService(this);
}
#endregion
#region Spelling dictionary members
//=====================================================================
/// <summary>
/// This is used to spell check a word
/// </summary>
/// <param name="word">The word to spell check</param>
/// <returns>True if spelled correctly, false if not</returns>
public bool IsSpelledCorrectly(string word)
{
return this.Dictionaries.Any(d => d.IsSpelledCorrectly(word));
}
/// <summary>
/// This is used to suggest corrections for a misspelled word
/// </summary>
/// <param name="word">The misspelled word for which to get suggestions</param>
/// <returns>An enumerable list of zero or more suggested correct spellings. Each suggestion contains
/// the dictionary culture with which it is associated. If the word contains a mnemonic, it is removed
/// in order to find the suggestions. Each word in the returned list of suggestions will contain the
/// mnemonic if it contains a matching letter.</remarks>
public IEnumerable<SpellingSuggestion> SuggestCorrections(string word)
{
char mnemonicCharacter = '\x0', mnemonicLetter = '\x0';
int pos = word.IndexOfAny(new[] { '&', '_' });
// Remove the mnemonic if present. It will be added to each suggestion below.
if(pos != -1)
{
mnemonicCharacter = word[pos];
mnemonicLetter = word[pos + 1];
word = word.Substring(0, pos) + word.Substring(pos + 1);
}
// IMPORTANT: ALWAYS return an actual list here not an enumeration. This list can get used a lot
// and deferred execution has a significant impact on performance.
List<SpellingSuggestion> allSuggestions = new List<SpellingSuggestion>();
if(this.DictionaryCount == 1)
allSuggestions.AddRange(this.Dictionaries.First().SuggestCorrections(word));
else
foreach(var d in this.Dictionaries)
allSuggestions.AddRange(d.SuggestCorrections(word));
if(mnemonicCharacter != '\x0')
foreach(var suggestion in allSuggestions)
suggestion.AddMnemonic(mnemonicCharacter, mnemonicLetter);
return allSuggestions;
}
/// <summary>
/// Add the given word to the dictionary so that it will no longer show up as an incorrect spelling
/// </summary>
/// <param name="word">The word to add to the dictionary.</param>
/// <param name="culture">The culture of the dictionary to which the word is added or null to add it to
/// the first dictionary.</param>
/// <returns><c>true</c> if the word was successfully added to the dictionary, even if it was already in
/// the dictionary.</returns>
public bool AddWordToDictionary(string word, CultureInfo culture)
{
GlobalDictionary dictionary = null;
if(String.IsNullOrWhiteSpace(word))
return false;
if(culture != null)
dictionary = this.Dictionaries.FirstOrDefault(d => d.Culture == culture);
if(dictionary == null)
dictionary = this.Dictionaries.First();
#pragma warning disable VSTHRD010
return (this.ShouldIgnoreWord(word) || dictionary.AddWordToDictionary(word));
#pragma warning restore VSTHRD010
}
/// <summary>
/// Raised when a request is made to ignore a word once
/// </summary>
/// <remarks>The event arguments contains the word that should be ignored once</remarks>
public event EventHandler<SpellingEventArgs> IgnoreOnce;
/// <summary>
/// Ignore the given word once, but don't add it to the dictionary
/// </summary>
/// <param name="span">The tracking span used to locate the word to ignore once</param>
public void IgnoreWordOnce(ITrackingSpan span)
{
IgnoreOnce?.Invoke(this, new SpellingEventArgs(span));
}
/// <summary>
/// Ignore all occurrences of the given word, but don't add it to the dictionary
/// </summary>
/// <param name="word">The word to be ignored</param>
/// <returns><c>true</c> if the word was successfully marked as ignored</returns>
public bool IgnoreWord(string word)
{
if(String.IsNullOrWhiteSpace(word))
return false;
return (this.ShouldIgnoreWord(word) || this.Dictionaries.All(d => d.IgnoreWord(word)));
}
/// <summary>
/// Check the ignored words dictionary for the given word
/// </summary>
/// <param name="word">The word for which to check</param>
/// <returns>True if the word should be ignored, false if not</returns>
public bool ShouldIgnoreWord(string word)
{
word = word.Replace("&", String.Empty).Replace("_", String.Empty);
if(String.IsNullOrWhiteSpace(word) || ignoredWords.Contains(word))
return true;
return this.Dictionaries.Any(d => d.ShouldIgnoreWord(word));
}
/// <summary>
/// Raised when the dictionary has been changed
/// </summary>
/// <remarks>When a new word is added to the dictionary, the event arguments contains the word that was
/// added.</remarks>
public event EventHandler<SpellingEventArgs> DictionaryUpdated;
/// <summary>
/// This is used to raise the <see cref="DictionaryUpdated"/> event
/// </summary>
/// <param name="word">The word that triggered the update</param>
private void OnDictionaryUpdated(string word)
{
DictionaryUpdated?.Invoke(this, new SpellingEventArgs(word));
}
/// <summary>
/// Raised when all occurrences of a word should be replaced
/// </summary>
/// <remarks>The event arguments contains the word that should be replaced along with its replacement</remarks>
public event EventHandler<SpellingEventArgs> ReplaceAll;
/// <summary>
/// This is used to replace all occurrences of the specified word
/// </summary>
/// <param name="word">The word to be replaced</param>
/// <param name="replacement">The suggestion to use as the replacement</param>
public void ReplaceAllOccurrences(string word, ISpellingSuggestion replacement)
{
ReplaceAll?.Invoke(this, new SpellingEventArgs(word, replacement));
}
#endregion
#region Methods and event handlers
//=====================================================================
/// <summary>
/// This is called by the global dictionary to raise the <see cref="DictionaryUpdated"/> event when the
/// global dictionary changes
/// </summary>
/// <param name="word">The word that triggered the update</param>
internal void GlobalDictionaryUpdated(string word)
{
this.OnDictionaryUpdated(word);
}
#endregion
}
}
|
global using BooksAPI.Models;
global using Microsoft.AspNetCore.Mvc;
global using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder();
builder.Services.AddSqlServer<BooksContext>(builder.Configuration.GetConnectionString("BooksConnection"));
builder.Services.AddControllers();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Books API v1"));
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.MapControllers();
app.Run();
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrainTracks_WeakPoint
: MonoBehaviour
{
public static int weakpointCount = 0;
[SerializeField]
private bool flipped;
// Use this for initialization
void Start() {
weakpointCount = 2; //TODO: Figure out nice way to increment this without breaking R debugging
float startx = Random.Range(-2f, 2f);
float yfactor = 0.47f;
if (flipped) {
yfactor *= -1;
}
Vector3 position = new Vector3(startx, startx * yfactor, 0);
transform.localPosition = position;
}
// Update is called once per frame
void Update() {
}
void OnMouseDown() {
weakpointCount--;
if (weakpointCount == 0) {
MicrogameController.instance.setVictory(victory: true, final: true);
}
Destroy(transform.parent.gameObject);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Bullet : MonoBehaviour
{
public float BulletDamage { get; set; }
void OnCollisionEnter (Collision col)
{
Destroy (gameObject);
}
}
|
using DirectorEditor.UILogic;
using DirectorEditor.Views;
using MVPFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DirectorEditor.Presenters
{
[ViewLogicBinding(typeof(AttributeAddressingViewLogic))]
public class AttributeAddressingPresenter:Presenter<IAttributeAddressingView>
{
public AttributeAddressingPresenter()
{
}
public void Show()
{
View.Show();
}
public void Activate()
{
View.Activate();
}
}
}
|
using System;
using System.Linq;
using System.Text;
public class ImageVector
{
private const int byteShift = byte.MaxValue / 2 + 1;
private double[] dimensions;
public int Dimensions
{
get { return dimensions.Length; }
}
public ImageVector(IntPtr start, int dataLength, int channels)
{
dimensions = Enumerable.Repeat<double>(0, channels).ToArray();
unsafe
{
byte* startPtr = (byte*)start.ToPointer();
byte* endPtr = startPtr + dataLength;
for (byte* ptr = startPtr; ptr != endPtr; ptr += channels)
{
for (int i = 0; i < channels; ++i)
{
dimensions[i] += ptr[i] - byteShift;
}
}
}
unit(dimensions);
}
// returns a percentage (0..1) of how different the images are (0 == same, 1 == opposite)
public double diff(ImageVector other)
{
if (dimensions.Length != other.dimensions.Length)
throw new InvalidOperationException("ImageVectors must have the same number of dimensions");
// vector subtraction
double[] sub = new double[dimensions.Length];
for (int i = 0; i < dimensions.Length; ++i)
{
sub[i] = dimensions[i] - other.dimensions[i];
}
// max length of subtracting two unit vectors is 2
return magnitude(sub) / 2f;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach(double d in dimensions)
{
sb.Append(d).Append(' ');
}
return sb.ToString();
}
private static double magnitude(double[] dims)
{
double total = 0;
for (int i = 0; i < dims.Length; ++i)
{
total += dims[i] * dims[i];
}
return Math.Sqrt(total);
}
private static void unit(double[] dims)
{
double length = magnitude(dims);
for (int i = 0; i < dims.Length; ++i)
{
dims[i] /= length;
}
}
}
|
using System.Linq;
using NFluent;
using Xunit;
namespace LASI.Core.Tests.PatternMatching
{
public class MatchTTResultTest
{
[Fact]
public void MatchChangingMidwayToLessDerivedResultType1()
{
ILexical target = new VerbPhrase(new BaseVerb("walk"), new Adverb("briskly"));
var result = target.Match()
.Case((VerbPhrase v) => v.Words)
.Case((IVerbal v) => new[] { v }.OfType<ILexical>())
.Result();
Check.That(result).IsNotNull().And.Contains(((Phrase)target).Words).Only().InThatOrder();
}
[Fact]
public void MatchChangingMidwayToLessDerivedResultType2()
{
ILexical target = new VerbPhrase(new BaseVerb("walk"), new Adverb("briskly"));
var result = target.Match()
.Case((IVerbal v) => new[] { v })
.Case((VerbPhrase v) => v.Words.OfType<ILexical>())
.Result();
Check.That(result).IsNotNull().And.Contains(target).Only().InThatOrder();
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using Xunit;
using static VariantNative;
// Class used to validate the IClassX generation path doesn't fail.
// Support for this scenario is extremely limited so we simply validate
// it continues be generated and can be marshalled to native.
//
// This class must be marked public in order for the IDispatch path for
// field access to be validated.
public class GenerateIClassX
{
public int FieldPrimitive;
public System.Collections.Generic.List<int> FieldWithGeneric;
public object FieldRefType;
public DateTime FieldValueType;
}
partial class Test_VariantTest
{
private const byte NumericValue = 15;
private const char CharValue = 'z';
private const string StringValue = "Abcdefg";
private const decimal DecimalValue = 74.25M;
private static readonly DateTime DateValue = new DateTime(2018, 11, 6);
private unsafe static void TestByValue(bool hasComSupport)
{
Assert.True(Marshal_ByValue_Byte((byte)NumericValue, NumericValue));
Assert.True(Marshal_ByValue_SByte((sbyte)NumericValue, (sbyte)NumericValue));
Assert.True(Marshal_ByValue_Int16((short)NumericValue, NumericValue));
Assert.True(Marshal_ByValue_UInt16((ushort)NumericValue, NumericValue));
Assert.True(Marshal_ByValue_Int32((int)NumericValue, NumericValue));
Assert.True(Marshal_ByValue_UInt32((uint)NumericValue, NumericValue));
Assert.True(Marshal_ByValue_Int64((long)NumericValue, NumericValue));
Assert.True(Marshal_ByValue_UInt64((ulong)NumericValue, NumericValue));
Assert.True(Marshal_ByValue_Single((float)NumericValue, NumericValue));
Assert.True(Marshal_ByValue_Double((double)NumericValue, NumericValue));
Assert.True(Marshal_ByValue_String(StringValue, StringValue));
Assert.True(Marshal_ByValue_String(new BStrWrapper(null), null));
Assert.True(Marshal_ByValue_Char(CharValue, CharValue));
Assert.True(Marshal_ByValue_Boolean(true, true));
Assert.True(Marshal_ByValue_DateTime(DateValue, DateValue));
Assert.True(Marshal_ByValue_Decimal(DecimalValue, DecimalValue));
Assert.True(Marshal_ByValue_Currency(new CurrencyWrapper(DecimalValue), DecimalValue));
Assert.True(Marshal_ByValue_Null(DBNull.Value));
Assert.True(Marshal_ByValue_Missing(System.Reflection.Missing.Value));
Assert.True(Marshal_ByValue_Empty(null));
if (hasComSupport)
{
Assert.True(Marshal_ByValue_Object(new object()));
Assert.True(Marshal_ByValue_Object_IUnknown(new UnknownWrapper(new object())));
Assert.True(Marshal_ByValue_Object(new GenerateIClassX()));
Assert.True(Marshal_ByValue_Object_IUnknown(new UnknownWrapper(new GenerateIClassX())));
}
else
{
Assert.Throws<NotSupportedException>(
() =>
{
Marshal_ByValue_Object(new object());
});
Assert.Throws<NotSupportedException>(
() =>
{
Marshal_ByValue_Object_IUnknown(new UnknownWrapper(new object()));
});
}
Assert.Throws<ArgumentException>(() => Marshal_ByValue_Invalid(TimeSpan.Zero));
Assert.Throws<NotSupportedException>(() => Marshal_ByValue_Invalid(new CustomStruct()));
Assert.Throws<ArgumentException>(() => Marshal_ByValue_Invalid(new VariantWrapper(CharValue)));
}
private unsafe static void TestByRef(bool hasComSupport)
{
object obj;
obj = (byte)NumericValue;
Assert.True(Marshal_ByRef_Byte(ref obj, NumericValue));
obj = (sbyte)NumericValue;
Assert.True(Marshal_ByRef_SByte(ref obj, (sbyte)NumericValue));
obj = (short)NumericValue;
Assert.True(Marshal_ByRef_Int16(ref obj, NumericValue));
obj = (ushort)NumericValue;
Assert.True(Marshal_ByRef_UInt16(ref obj, NumericValue));
obj = (int)NumericValue;
Assert.True(Marshal_ByRef_Int32(ref obj, NumericValue));
obj = (uint)NumericValue;
Assert.True(Marshal_ByRef_UInt32(ref obj, NumericValue));
obj = (long)NumericValue;
Assert.True(Marshal_ByRef_Int64(ref obj, NumericValue));
obj = (ulong)NumericValue;
Assert.True(Marshal_ByRef_UInt64(ref obj, NumericValue));
obj = (float)NumericValue;
Assert.True(Marshal_ByRef_Single(ref obj, NumericValue));
obj = (double)NumericValue;
Assert.True(Marshal_ByRef_Double(ref obj, NumericValue));
obj = StringValue;
Assert.True(Marshal_ByRef_String(ref obj, StringValue));
obj = new BStrWrapper(null);
Assert.True(Marshal_ByRef_String(ref obj, null));
obj = CharValue;
Assert.True(Marshal_ByRef_Char(ref obj, CharValue));
obj = true;
Assert.True(Marshal_ByRef_Boolean(ref obj, true));
obj = DateValue;
Assert.True(Marshal_ByRef_DateTime(ref obj, DateValue));
obj = DecimalValue;
Assert.True(Marshal_ByRef_Decimal(ref obj, DecimalValue));
obj = new CurrencyWrapper(DecimalValue);
Assert.True(Marshal_ByRef_Currency(ref obj, DecimalValue));
obj = DBNull.Value;
Assert.True(Marshal_ByRef_Null(ref obj));
obj = System.Reflection.Missing.Value;
Assert.True(Marshal_ByRef_Missing(ref obj));
obj = null;
Assert.True(Marshal_ByRef_Empty(ref obj));
if (hasComSupport)
{
obj = new object();
Assert.True(Marshal_ByRef_Object(ref obj));
obj = new UnknownWrapper(new object());
Assert.True(Marshal_ByRef_Object_IUnknown(ref obj));
obj = new GenerateIClassX();
Assert.True(Marshal_ByRef_Object(ref obj));
obj = new UnknownWrapper(new GenerateIClassX());
Assert.True(Marshal_ByRef_Object_IUnknown(ref obj));
}
else
{
Assert.Throws<NotSupportedException>(
() =>
{
obj = new object();
Marshal_ByRef_Object(ref obj);
});
Assert.Throws<NotSupportedException>(
() =>
{
obj = new UnknownWrapper(new object());
Marshal_ByRef_Object_IUnknown(ref obj);
});
}
obj = DecimalValue;
Assert.True(Marshal_ChangeVariantType(ref obj, NumericValue));
Assert.True(obj is int);
Assert.Equal(NumericValue, (int)obj);
}
private unsafe static void TestOut()
{
Assert.True(Marshal_Out(out object obj, NumericValue));
Assert.True(obj is int);
Assert.Equal(NumericValue, (int)obj);
}
private unsafe static void TestFieldByValue(bool hasComSupport)
{
ObjectWrapper wrapper = new ObjectWrapper();
wrapper.value = (byte)NumericValue;
Assert.True(Marshal_Struct_ByValue_Byte(wrapper, NumericValue));
wrapper.value = (sbyte)NumericValue;
Assert.True(Marshal_Struct_ByValue_SByte(wrapper, (sbyte)NumericValue));
wrapper.value = (short)NumericValue;
Assert.True(Marshal_Struct_ByValue_Int16(wrapper, NumericValue));
wrapper.value = (ushort)NumericValue;
Assert.True(Marshal_Struct_ByValue_UInt16(wrapper, NumericValue));
wrapper.value = (int)NumericValue;
Assert.True(Marshal_Struct_ByValue_Int32(wrapper, NumericValue));
wrapper.value = (uint)NumericValue;
Assert.True(Marshal_Struct_ByValue_UInt32(wrapper, NumericValue));
wrapper.value = (long)NumericValue;
Assert.True(Marshal_Struct_ByValue_Int64(wrapper, NumericValue));
wrapper.value = (ulong)NumericValue;
Assert.True(Marshal_Struct_ByValue_UInt64(wrapper, NumericValue));
wrapper.value = (float)NumericValue;
Assert.True(Marshal_Struct_ByValue_Single(wrapper, NumericValue));
wrapper.value = (double)NumericValue;
Assert.True(Marshal_Struct_ByValue_Double(wrapper, NumericValue));
wrapper.value = StringValue;
Assert.True(Marshal_Struct_ByValue_String(wrapper, StringValue));
wrapper.value = new BStrWrapper(null);
Assert.True(Marshal_Struct_ByValue_String(wrapper, null));
wrapper.value = CharValue;
Assert.True(Marshal_Struct_ByValue_Char(wrapper, CharValue));
wrapper.value = true;
Assert.True(Marshal_Struct_ByValue_Boolean(wrapper, true));
wrapper.value = DateValue;
Assert.True(Marshal_Struct_ByValue_DateTime(wrapper, DateValue));
wrapper.value = DecimalValue;
Assert.True(Marshal_Struct_ByValue_Decimal(wrapper, DecimalValue));
wrapper.value = new CurrencyWrapper(DecimalValue);
Assert.True(Marshal_Struct_ByValue_Currency(wrapper, DecimalValue));
wrapper.value = DBNull.Value;
Assert.True(Marshal_Struct_ByValue_Null(wrapper));
wrapper.value = System.Reflection.Missing.Value;
Assert.True(Marshal_Struct_ByValue_Missing(wrapper));
wrapper.value = null;
Assert.True(Marshal_Struct_ByValue_Empty(wrapper));
if (hasComSupport)
{
wrapper.value = new object();
Assert.True(Marshal_Struct_ByValue_Object(wrapper));
wrapper.value = new UnknownWrapper(new object());
Assert.True(Marshal_Struct_ByValue_Object_IUnknown(wrapper));
wrapper.value = new GenerateIClassX();
Assert.True(Marshal_Struct_ByValue_Object(wrapper));
wrapper.value = new UnknownWrapper(new GenerateIClassX());
Assert.True(Marshal_Struct_ByValue_Object_IUnknown(wrapper));
}
else
{
Assert.Throws<NotSupportedException>(
() =>
{
wrapper.value = new object();
Marshal_Struct_ByValue_Object(wrapper);
});
Assert.Throws<NotSupportedException>(
() =>
{
wrapper.value = new UnknownWrapper(new object());
Marshal_Struct_ByValue_Object_IUnknown(wrapper);
});
}
}
private unsafe static void TestFieldByRef(bool hasComSupport)
{
ObjectWrapper wrapper = new ObjectWrapper();
wrapper.value = (byte)NumericValue;
Assert.True(Marshal_Struct_ByRef_Byte(ref wrapper, NumericValue));
wrapper.value = (sbyte)NumericValue;
Assert.True(Marshal_Struct_ByRef_SByte(ref wrapper, (sbyte)NumericValue));
wrapper.value = (short)NumericValue;
Assert.True(Marshal_Struct_ByRef_Int16(ref wrapper, NumericValue));
wrapper.value = (ushort)NumericValue;
Assert.True(Marshal_Struct_ByRef_UInt16(ref wrapper, NumericValue));
wrapper.value = (int)NumericValue;
Assert.True(Marshal_Struct_ByRef_Int32(ref wrapper, NumericValue));
wrapper.value = (uint)NumericValue;
Assert.True(Marshal_Struct_ByRef_UInt32(ref wrapper, NumericValue));
wrapper.value = (long)NumericValue;
Assert.True(Marshal_Struct_ByRef_Int64(ref wrapper, NumericValue));
wrapper.value = (ulong)NumericValue;
Assert.True(Marshal_Struct_ByRef_UInt64(ref wrapper, NumericValue));
wrapper.value = (float)NumericValue;
Assert.True(Marshal_Struct_ByRef_Single(ref wrapper, NumericValue));
wrapper.value = (double)NumericValue;
Assert.True(Marshal_Struct_ByRef_Double(ref wrapper, NumericValue));
wrapper.value = StringValue;
Assert.True(Marshal_Struct_ByRef_String(ref wrapper, StringValue));
wrapper.value = new BStrWrapper(null);
Assert.True(Marshal_Struct_ByRef_String(ref wrapper, null));
wrapper.value = CharValue;
Assert.True(Marshal_Struct_ByRef_Char(ref wrapper, CharValue));
wrapper.value = true;
Assert.True(Marshal_Struct_ByRef_Boolean(ref wrapper, true));
wrapper.value = DateValue;
Assert.True(Marshal_Struct_ByRef_DateTime(ref wrapper, DateValue));
wrapper.value = DecimalValue;
Assert.True(Marshal_Struct_ByRef_Decimal(ref wrapper, DecimalValue));
wrapper.value = new CurrencyWrapper(DecimalValue);
Assert.True(Marshal_Struct_ByRef_Currency(ref wrapper, DecimalValue));
wrapper.value = DBNull.Value;
Assert.True(Marshal_Struct_ByRef_Null(ref wrapper));
wrapper.value = System.Reflection.Missing.Value;
Assert.True(Marshal_Struct_ByRef_Missing(ref wrapper));
wrapper.value = null;
Assert.True(Marshal_Struct_ByRef_Empty(ref wrapper));
if (hasComSupport)
{
wrapper.value = new object();
Assert.True(Marshal_Struct_ByRef_Object(ref wrapper));
wrapper.value = new UnknownWrapper(new object());
Assert.True(Marshal_Struct_ByRef_Object_IUnknown(ref wrapper));
wrapper.value = new GenerateIClassX();
Assert.True(Marshal_Struct_ByRef_Object(ref wrapper));
wrapper.value = new UnknownWrapper(new GenerateIClassX());
Assert.True(Marshal_Struct_ByRef_Object_IUnknown(ref wrapper));
}
else
{
Assert.Throws<NotSupportedException>(
() =>
{
wrapper.value = new object();
Marshal_Struct_ByRef_Object(ref wrapper);
});
Assert.Throws<NotSupportedException>(
() =>
{
wrapper.value = new UnknownWrapper(new object());
Marshal_Struct_ByRef_Object_IUnknown(ref wrapper);
});
}
}
}
|
using System;
using System.Net;
namespace De.Osthus.Ambeth.Event
{
public interface IEventBatcherExtendable
{
void RegisterEventBatcher(IEventBatcher eventBatcher, Type eventType);
void UnregisterEventBatcher(IEventBatcher eventBatcher, Type eventType);
}
}
|
namespace Poker.Tests.PokerHandsChecker
{
using NUnit.Framework;
using Poker;
using Poker.Tests.Fakes;
[TestFixture]
public class IsThreeOfAKindTests
{
[Test]
public void IsThreeOfAKind_HandHasThreeCardsOfEqualFaceValueAndTwoCardsOfDifferentFaceValue_ShouldReturnTrue()
{
var hand = new HandTypePresetsFakeHand(HandType.IsThreeOfAKind);
var handChecker = new PokerHandsChecker();
var actualResult = handChecker.IsThreeOfAKind(hand);
Assert.IsTrue(actualResult);
}
[Test]
public void IsThreeOfAKind_HandHasThreeCardsOfEqualFaceValueAndTheOtherTwoFormAPair_ShouldReturnFalse()
{
var hand = new HandTypePresetsFakeHand(HandType.IsFullHouse);
var handChecker = new PokerHandsChecker();
var actualResult = handChecker.IsThreeOfAKind(hand);
Assert.IsFalse(actualResult);
}
[Test]
public void IsThreeOfAKind_HandHasFourCardsOfTheSameFaceValue_ShouldReturnFalse()
{
var hand = new HandTypePresetsFakeHand(HandType.IsFourOfAKind);
var handChecker = new PokerHandsChecker();
var actualResult = handChecker.IsThreeOfAKind(hand);
Assert.IsFalse(actualResult);
}
}
}
|
// https://www.nuget.org/packages/UkooLabs.FbxSharpie/
// https://github.com/UkooLabs/FBXSharpie
// License: MIT
namespace AcTools.ExtraKn5Utils.FbxUtils.Tokens {
public class CommentToken : Token {
public readonly string Value;
public CommentToken(string value) : base(TokenType.Comment, ValueType.None) {
Value = value;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using LinqGarden.Functions;
namespace FluentDiagrams.Primitives
{
public class Coordinate
{
public Coordinate( decimal x, decimal y )
{
X = x;
Y = y;
}
/// <summary>
/// Get the cartesian coordinate X position
/// </summary>
public decimal X { get; }
/// <summary>
/// Get the cartesian coordinate Y position
/// </summary>
public decimal Y { get; }
/// <summary>
/// Get the cartesian coordinate angle
/// </summary>
public Angle Angle =>
Math.Atan2( (double)Y, (double)X )
.Pipe( x => (decimal)x )
.Pipe( Angle.FromRadians );
/// <summary>
/// Get the cartesian coordinate radius
/// </summary>
public decimal Radius =>
( Math.Pow( (double)X, 2 ) + Math.Pow( (double)Y, 2 ) )
.Pipe( Math.Sqrt )
.Pipe( x => (decimal)x );
public Coordinate Translate( Vector vector ) =>
new Coordinate( X + vector.Dx, Y + vector.Dy );
public Coordinate Translate( decimal dx, decimal dy ) =>
new Coordinate( X + dx, Y + dy );
public Coordinate RotateAbout( Coordinate rotationOrigin, Angle angle )
{
//convert to polar coordinates
var preRotateTranslate = Vector.FromCoordinates( rotationOrigin, Coordinate.Origin() );
var postRotateTranslate = preRotateTranslate.Reverse();
return
this
.Translate( preRotateTranslate )
.Pipe( x => x.Rotate( angle ) )
.Translate( postRotateTranslate );
}
public static Coordinate Cartesian( decimal x, decimal y ) =>
new Coordinate( x, y );
public Coordinate Rotate( Angle angle ) =>
Coordinate.Polar( Angle.Plus( angle ), Radius );
public static Coordinate Origin() =>
new Coordinate( 0M, 0M );
public static Coordinate Polar( Angle angle, decimal radius )
{
decimal x = radius * (decimal)Math.Cos( (double)angle.Radians );
decimal y = radius * (decimal)Math.Sin( (double)angle.Radians );
return new Coordinate( x, y );
}
public static Coordinate Average( params Coordinate[] coordinates ) =>
Coordinate.Cartesian( coordinates.Select( x => x.X ).Average(), coordinates.Select( x => x.Y ).Average() );
public static IEnumerable<Coordinate> InterpolateBetween( Coordinate start, Coordinate end, int totalValues )
{
var xCoords = Maths.Interpolate( start.X, end.X, totalValues );
var yCoords = Maths.Interpolate( start.Y, end.Y, totalValues );
return xCoords.Zip( yCoords, ( x, y ) => Coordinate.Cartesian( x, y ) );
}
public static Coordinate Bisect( Coordinate start, Coordinate end ) =>
Average( start, end );
/// <summary>
/// Scale the coordinate about the origin
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public Coordinate Scale( decimal x = 1, decimal y = 1 ) =>
Coordinate.Cartesian( this.X * x, this.Y * y );
}
}
|
using AutoMapper;
using Challenge.RealEstates.Application.DTOs;
using Challenge.RealEstates.Domain.Entities;
namespace Challenge.RealEstates.Application.Mappers
{
public class LocationProfile : Profile
{
public LocationProfile()
{
LocationMap();
LocationDtoMap();
}
private void LocationMap()
{
CreateMap<LocationDTO, Location>();
}
private void LocationDtoMap()
{
CreateMap<Location, LocationDTO>();
}
}
} |
using System;
using System.ComponentModel;
namespace Company.Desktop.Framework.Mvvm.Interactivity
{
public interface IBusyState : INotifyPropertyChanged
{
bool IsBusy { get; set; }
IObservable<PropertyChangedEventArgs> WhenPropertyChanged { get; }
void Increment();
void Decrement();
IDisposable Session();
}
} |
using BibleNote.Middleware.NavigationProviders.SharedViewModels;
using MediatR;
namespace BibleNote.Middleware.NavigationProviders.Queries.OneNote.GetHierarchyInfo
{
public class Request: IRequest<HierarchyItemVm>
{
public string HierarchyId { get; set; }
public Request(string hierarchyId)
{
HierarchyId = hierarchyId;
}
}
}
|
using System;
namespace MRRC.SearchParser.Parts
{
public interface IMatchable
{
string[] Matches(string[] options);
Tuple<Tuple<string, T>[], T[]> Matches<T>(Tuple<string, T>[] options);
}
} |
using System;
using Tweetinvi.Core.Injectinvi;
namespace Tweetinvi.Core
{
/// <summary>
/// @Injectable : use in order to retrieve tweetinvi settings anywhere in the application.
/// </summary>
public interface ITweetinviSettingsAccessor
{
/// <summary>
/// Current thread settings.
/// </summary>
ITweetinviSettings CurrentThreadSettings { get; set; }
/// <summary>
/// Application thread settings.
/// </summary>
ITweetinviSettings ApplicationSettings { get; set; }
/// <summary>
/// Proxy URL used by the current thread.
/// </summary>
IProxyConfig ProxyConfig { get; set; }
/// <summary>
/// Http requests timeout in the current thread.
/// </summary>
int HttpRequestTimeout { get; set; }
/// <summary>
/// Upload timeout in the current thread.
/// </summary>
int UploadTimeout { get; set; }
/// <summary>
/// Solution used to track the rate limits in the current thread.
/// </summary>
RateLimitTrackerMode RateLimitTrackerMode { get; set; }
}
public class TweetinviSettingsAccessor : ITweetinviSettingsAccessor
{
private static ITweetinviSettings StaticTweetinviSettings { get; set; }
public TweetinviSettingsAccessor()
{
var threadSettings = TweetinviCoreModule.TweetinviContainer.Resolve<ITweetinviSettings>();
threadSettings.HttpRequestTimeout = 10000;
threadSettings.UploadTimeout = 60000;
CurrentThreadSettings = threadSettings;
}
[ThreadStatic]
private static ITweetinviSettings _currentThreadSettings;
public ITweetinviSettings CurrentThreadSettings
{
get
{
if (_currentThreadSettings == null)
{
InitialiseSettings();
}
return _currentThreadSettings;
}
set
{
_currentThreadSettings = value;
if (!HasTheApplicationSettingsBeenInitialized() && _currentThreadSettings != null)
{
StaticTweetinviSettings = value.Clone();
}
}
}
private void InitialiseSettings()
{
_currentThreadSettings = TweetinviCoreModule.TweetinviContainer.Resolve<ITweetinviSettings>();
_currentThreadSettings.InitialiseFrom(StaticTweetinviSettings);
}
public ITweetinviSettings ApplicationSettings
{
get { return StaticTweetinviSettings; }
set
{
StaticTweetinviSettings = value;
if (_currentThreadSettings != null)
{
_currentThreadSettings = value;
}
}
}
private bool HasTheApplicationSettingsBeenInitialized()
{
return StaticTweetinviSettings != null;
}
public IProxyConfig ProxyConfig
{
get { return CurrentThreadSettings.ProxyConfig; }
set { CurrentThreadSettings.ProxyConfig = value; }
}
public int HttpRequestTimeout
{
get { return CurrentThreadSettings.HttpRequestTimeout; }
set { CurrentThreadSettings.HttpRequestTimeout = value; }
}
public int UploadTimeout
{
get { return CurrentThreadSettings.UploadTimeout; }
set { CurrentThreadSettings.UploadTimeout = value; }
}
public RateLimitTrackerMode RateLimitTrackerMode
{
get { return CurrentThreadSettings.RateLimitTrackerMode; }
set { CurrentThreadSettings.RateLimitTrackerMode = value; }
}
}
} |
using System.Collections.Generic;
namespace ShardingCore.Sharding.Enumerators.StreamMergeSync
{
/*
* @Author: xjm
* @Description:
* @Date: Saturday, 14 August 2021 22:06:38
* @Email: 326308290@qq.com
*/
public interface IStreamMergeEnumerator<T>:IEnumerator<T>
{
bool SkipFirst();
bool HasElement();
T ReallyCurrent { get; }
}
} |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Threading;
using VsChromium.Core.Utility;
using VsChromium.Package;
using VsChromium.ToolsOptions;
namespace VsChromium.Settings {
[Export(typeof(IGlobalSettingsProvider))]
public class GlobalSettingsProvider : IGlobalSettingsProvider {
private readonly IToolsOptionsPageProvider _visualStudioPackageProvider;
private readonly IDispatchThreadEventBus _eventBus;
private readonly Lazy<GlobalSettings> _globalSettings;
private readonly int _writeThreadId = Thread.CurrentThread.ManagedThreadId;
private bool _swallowGlobalSettingsPropertyChangeNotifications;
[ImportingConstructor]
public GlobalSettingsProvider(
IToolsOptionsPageProvider visualStudioPackageProvider,
IDispatchThreadEventBus eventBus) {
_visualStudioPackageProvider = visualStudioPackageProvider;
_eventBus = eventBus;
_globalSettings = new Lazy<GlobalSettings>(CreateGlobalSettings);
}
public GlobalSettings GlobalSettings {
get {
return _globalSettings.Value;
}
}
/// <summary>
/// Invoked when any property of the "Tools|Options" page is modified.
/// </summary>
private void ToolsOptionsPageApplyHandler(object sender, EventArgs eventArgs) {
CheckOnWriteThread();
_swallowGlobalSettingsPropertyChangeNotifications = true;
try {
CopyOptionsPagesToGlobalSettings(_globalSettings.Value);
}
finally {
_swallowGlobalSettingsPropertyChangeNotifications = false;
}
}
/// <summary>
/// Invoked when any property of the "GlobalSettings" instance is modified.
/// </summary>
private void GlobalSettingsPropertyChangedHandler(object sender, PropertyChangedEventArgs args) {
CheckOnWriteThread();
if (_swallowGlobalSettingsPropertyChangeNotifications)
return;
var globalSettings = (GlobalSettings)sender;
CopyGlobalSettingsToOptionPages(globalSettings);
}
private GlobalSettings CreateGlobalSettings() {
var result = new GlobalSettings();
CopyOptionsPagesToGlobalSettings(result);
// Ensure changes to the GlobalSettings object are save to the VS Settings.
result.PropertyChanged += GlobalSettingsPropertyChangedHandler;
// Ensure changes to the VS Settings are reflected to the GlobalSettings object.
_eventBus.RegisterHandler(EventNames.ToolsOptions.PageApply, ToolsOptionsPageApplyHandler);
return result;
}
/// <summary>
/// Copy properties from "Tools|Options" page objects to <paramref
/// name="globalSettings"/>.
/// </summary>
private void CopyOptionsPagesToGlobalSettings(GlobalSettings globalSettings) {
CheckOnWriteThread();
var page = _visualStudioPackageProvider.GetToolsOptionsPage<GeneralOptions>();
ReflectionUtils.CopyDeclaredPublicProperties(page, "", globalSettings, "", throwOnExtraProperty: true);
var page2 = _visualStudioPackageProvider.GetToolsOptionsPage<CodingStyleOptions>();
ReflectionUtils.CopyDeclaredPublicProperties(page2, "", globalSettings, "CodingStyle", throwOnExtraProperty: true);
}
/// <summary>
/// Copy properties from <paramref name="globalSettings"/> to
/// "Tools|Options" pages objects.
/// </summary>
private void CopyGlobalSettingsToOptionPages(GlobalSettings globalSettings) {
CheckOnWriteThread();
var page = _visualStudioPackageProvider.GetToolsOptionsPage<GeneralOptions>();
ReflectionUtils.CopyDeclaredPublicProperties(globalSettings, "", page, "", throwOnExtraProperty: false);
page.SaveSettingsToStorage();
var page2 = _visualStudioPackageProvider.GetToolsOptionsPage<CodingStyleOptions>();
ReflectionUtils.CopyDeclaredPublicProperties(globalSettings, "CodingStyle", page2, "", throwOnExtraProperty: false);
page2.SaveSettingsToStorage();
}
private void CheckOnWriteThread() {
if (Thread.CurrentThread.ManagedThreadId != _writeThreadId) {
throw new InvalidOperationException("Global Settings can only be mofidied on the UI thread.");
}
}
}
} |
using System;
// ReSharper disable once CheckNamespace
namespace Hattem.Api.Fluent
{
partial class ApiResponseExtensions
{
/// <summary>
/// Union results of two responses
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <returns></returns>
public static ApiResponse<(T1, T2)> Union<T1, T2>(
this ApiResponse<T1> source,
Func<T1, ApiResponse<T2>> selector
)
{
if (source.Error is not null)
{
return ApiResponse
.Error<(T1, T2)>(source.Error)
.WithStatusCode(source.StatusCode);
}
var output = selector(source.Data!);
if (output.Error is not null)
{
return ApiResponse
.Error<(T1, T2)>(output.Error)
.WithStatusCode(output.StatusCode);
}
return ApiResponse
.Ok((source.Data!, output.Data!))
.WithStatusCode(source.StatusCode ?? output.StatusCode);
}
/// <summary>
/// Add response to current assembly of responses
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <returns></returns>
public static ApiResponse<(T1, T2, T3)> Union<T1, T2, T3>(
this ApiResponse<(T1, T2)> source,
Func<ApiResponse<T3>> selector
)
{
return source.Union((_, _) => selector());
}
/// <summary>
/// Add response to current assembly of responses
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <returns></returns>
public static ApiResponse<(T1, T2, T3)> Union<T1, T2, T3>(
this ApiResponse<(T1, T2)> source,
Func<T1, T2, ApiResponse<T3>> selector
)
{
if (source.Error is not null)
{
return ApiResponse
.Error<(T1, T2, T3)>(source.Error)
.WithStatusCode(source.StatusCode);
}
var output = selector(source.Data.Item1, source.Data.Item2);
if (output.Error is not null)
{
return ApiResponse
.Error<(T1, T2, T3)>(output.Error)
.WithStatusCode(output.StatusCode);
}
return ApiResponse
.Ok((source.Data.Item1!, source.Data.Item2!, output.Data!))
.WithStatusCode(source.StatusCode ?? output.StatusCode);
}
/// <summary>
/// Add response to current assembly of responses
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <typeparam name="T4"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <returns></returns>
public static ApiResponse<(T1, T2, T3, T4)> Union<T1, T2, T3, T4>(
this ApiResponse<(T1, T2, T3)> source,
Func<ApiResponse<T4>> selector
)
{
return source.Union((_, _, _) => selector());
}
/// <summary>
/// Add response to current assembly of responses
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <typeparam name="T4"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <returns></returns>
public static ApiResponse<(T1, T2, T3, T4)> Union<T1, T2, T3, T4>(
this ApiResponse<(T1, T2, T3)> source,
Func<T1, T2, T3, ApiResponse<T4>> selector
)
{
if (source.Error is not null)
{
return ApiResponse
.Error<(T1, T2, T3, T4)>(source.Error)
.WithStatusCode(source.StatusCode);
}
var output = selector(
source.Data.Item1,
source.Data.Item2,
source.Data.Item3);
if (output.Error is not null)
{
return ApiResponse
.Error<(T1, T2, T3, T4)>(output.Error)
.WithStatusCode(output.StatusCode);
}
return ApiResponse
.Ok((source.Data.Item1!, source.Data.Item2!, source.Data.Item3!, output.Data!))
.WithStatusCode(source.StatusCode ?? output.StatusCode);
}
/// <summary>
/// Add response to current assembly of responses
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <typeparam name="T4"></typeparam>
/// <typeparam name="T5"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <returns></returns>
public static ApiResponse<(T1, T2, T3, T4, T5)> Union<T1, T2, T3, T4, T5>(
this ApiResponse<(T1, T2, T3, T4)> source,
Func<ApiResponse<T5>> selector
)
{
return source.Union(
(
_,
_,
_,
_
) => selector());
}
/// <summary>
/// Add response to current assembly of responses
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <typeparam name="T4"></typeparam>
/// <typeparam name="T5"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <returns></returns>
public static ApiResponse<(T1, T2, T3, T4, T5)> Union<T1, T2, T3, T4, T5>(
this ApiResponse<(T1, T2, T3, T4)> source,
Func<T1, T2, T3, T4, ApiResponse<T5>> selector
)
{
if (source.Error is not null)
{
return ApiResponse
.Error<(T1, T2, T3, T4, T5)>(source.Error)
.WithStatusCode(source.StatusCode);
}
var output = selector(
source.Data.Item1,
source.Data.Item2,
source.Data.Item3,
source.Data.Item4);
if (output.Error is not null)
{
return ApiResponse
.Error<(T1, T2, T3, T4, T5)>(output.Error)
.WithStatusCode(output.StatusCode);
}
return ApiResponse
.Ok((source.Data.Item1!, source.Data.Item2!, source.Data.Item3!, source.Data.Item4!, output.Data!))
.WithStatusCode(source.StatusCode ?? output.StatusCode);
}
}
}
|
using Orckestra.Composer.Enums;
using Orckestra.Composer.ViewModels;
namespace Orckestra.Composer.Product.ViewModels.Inventory
{
public sealed class InventoryScheduleViewModel : BaseViewModel
{
/// <summary>
/// The inventory location identifier
/// </summary>
public string InventoryLocationId { get; set; }
/// <summary>
/// The associated product sku
/// </summary>
public string Sku { get; set; }
/// <summary>
/// The date range of the schedule
/// </summary>
public DateRangeViewModel DateRange { get; set; }
/// <summary>
/// The status of product inventory
/// </summary>
public InventoryStatusEnum InventoryStatus { get; set; }
}
}
|
using Newtonsoft.Json;
using static Sniper.CustomAttributes.CustomAttributes;
namespace Sniper.Common
{
/// <summary>
/// Represents reference to downloaded message
/// </summary>
/// <remarks>
/// See the <a href="https://md5.tpondemand.com/api/v1/MessageUids/meta">API documentation - MessageUid</a>
/// </remarks>
[CanCreateReadUpdateDelete]
public class MessageUniqueId : Entity
{
[JsonProperty(Required = Required.Default)]
public string MailLogin { get; set; }
[JsonProperty(Required = Required.Default)]
public string MailServer { get; set; }
[JsonProperty(Required = Required.Default)]
public string Uid { get; set; }
}
} |
// DigitalRune Engine - Copyright (C) DigitalRune GmbH
// This file is subject to the terms and conditions defined in
// file 'LICENSE.TXT', which is part of this source code package.
namespace DigitalRune.Editor.Documents
{
/// <summary>
/// Defines the user choices provided by a Save Changes dialog.
/// </summary>
internal enum SaveChangesDialogResult
{
/// <summary>
/// The user has chosen to save and close the modified files.
/// </summary>
SaveAndClose,
/// <summary>
/// The user has chosen to close the modified files without saving.
/// </summary>
CloseWithoutSaving,
/// <summary>
/// The user has chosen to do nothing and leave the files opened.
/// </summary>
Cancel,
}
}
|
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using ServiceStack;
namespace MyApp.Client
{
public abstract class StackBaseComponent : ComponentBase
{
[CascadingParameter]
protected Task<AuthenticationState> AuthenticationStateTask { get; set; }
[Inject]
private JsonHttpClient Client {get;set;}
protected async Task<JsonHttpClient> GetClientAsync() {
var state = await AuthenticationStateTask;
if(state.User is ClaimsPrincipal principal && principal.Identity.IsAuthenticated){
Client.BearerToken = principal.Claims.Where(c => c.Type == "token").FirstOrDefault()?.Value;
}
return Client;
}
}
} |
/****************************************************************
* File : Assets\CORE\GameController.cs
* Author : www.loywong.com
* COPYRIGHT : (C)
* Date : 2019/07/29
* Description : 场景控制器,负责场景调度,资源加载卸载等
* Version : 1.0
* Maintain : //[date] desc
****************************************************************/
// ************************************************
// 加载Prefab_界面
// ************************************************
using UnityEngine;
// 必须和.unity场景文件名称严格匹配
public enum Enum_Scene {
None = 0,
Splash = 1, //自定义的片头展示
NewPlayer = 2, //新手引导专有展示场景(只触发一次(但必须完整的通过,否则会再次触发))
Login = 3,
Lobby = 4,
Battle = 5,
}
public class GameController {
private static GameController _Instance = null;
public static GameController Instance {
get {
if (_Instance == null)
_Instance = new GameController ();
return _Instance;
}
}
private int curSceneId = (int) Enum_Scene.None;
// private string preSceneName = "";
private string curSceneName { get { return ((Enum_Scene) curSceneId).ToString (); } }
// 一定是通过Lua层来调用
public void GoScene (int sid /**, System.Action cbComplete = null */ ) {
var sceneName = ((Enum_Scene) sid).ToString ();
//0,如果当前处于有效场景(不是第一个场景)
if (curSceneId > (int) Enum_Scene.None)
EndScene ();
//1, 预加载资源(和CocosCreator不同,Unity会自动收集所有相关的依赖资源,并提供加载进度,不需要自己手动指定加载的资源(文件夹))
//2,加载场景
SceneLoading.Instance.OnStart (sid, () => {
//3,Lua的部分
LuaManager.Instance.StartScene (sceneName);
//??? 这步不需要!!! 加载场景 Model (如果场景上什么都不放) 但那是Cocos,Unity不存在这种情况
//4,加载默认界面 Panel
UIManager.Instance.LoadSceneBase (sceneName, (GameObject go) => {
if (go == null) {
Debug.LogError ("场景默认UI加载失败" + sceneName);
// // 清理已经加载的部分
// // 比如
// LuaManager.Instance.EndScene (sceneName);
// return;
}
Debug.Log ("场景加载完成" + sceneName);
StartScene (sid);
//??? 完成回调通知
// if (cbComplete != null)
// cbComplete ();
});
});
}
private void StartScene (int sceneId) {
Debug.Log ("GameController StartScene(): " + ((Enum_Scene) sceneId).ToString ());
curSceneId = sceneId;
LuaManager.Instance.CallFunction (curSceneName + "Controller.OnStart");
//初始下下一个场景的对象
// 1 音乐播放
string bgm = "S_BGM_Lobby";
// SoundManager.Instance.PlayBGM (bgm);
AudioPoolManager.Instance.PlayMusic (bgm);
// 2 Fn管理器
// FnController.Instance.OnStart();
}
private void EndScene () {
Debug.Log ("GameController EndScene: " + curSceneName);
LuaManager.Instance.CallFunction (curSceneName + "Controller.OnEnd");
//1,清理 Lua的部分
LuaManager.Instance.EndScene (curSceneName);
//2,清理 资源
Resources.UnloadUnusedAssets ();
//3,清理 C#内存
System.GC.Collect ();
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Hotfix
{
[Window(EWindowType.UIMain, EWindowLayer.Panel)]
public class UIMain : UIWindow
{
public override void OnCreate()
{
AddButtonListener("UIMain/Meum/Button (Settings)", OnClickSetting);
AddButtonListener("UIMain/Spell/Button (Attack)", OnClickSkill1);
AddButtonListener("UIMain/Spell/Button (Shield)", OnClickSkill2);
AddButtonListener("UIMain/Spell/Button (Swords)", OnClickSkill3);
}
public override void OnDestroy()
{
}
public override void OnRefresh()
{
}
public override void OnUpdate()
{
#if UNITY_EDITOR
if (Input.GetKeyDown(KeyCode.Alpha1))
OnClickSkill1();
if (Input.GetKeyDown(KeyCode.Alpha2))
OnClickSkill2();
if (Input.GetKeyDown(KeyCode.Alpha3))
OnClickSkill3();
#endif
}
private void OnClickSetting()
{
UIManager.Instance.OpenWindow(EWindowType.UISetting);
}
private void OnClickSkill1()
{
BattleEvent.PlayerSpell msg = new BattleEvent.PlayerSpell();
msg.SkillID = 1001;
HotfixEventManager.Instance.Send(HotfixEventMessageTag.BattleEvent, msg);
}
private void OnClickSkill2()
{
BattleEvent.PlayerSpell msg = new BattleEvent.PlayerSpell();
msg.SkillID = 1003;
HotfixEventManager.Instance.Send(HotfixEventMessageTag.BattleEvent, msg);
}
private void OnClickSkill3()
{
BattleEvent.PlayerSpell msg = new BattleEvent.PlayerSpell();
msg.SkillID = 1002;
HotfixEventManager.Instance.Send(HotfixEventMessageTag.BattleEvent, msg);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.