content stringlengths 23 1.05M |
|---|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;
public class BoardScript : MonoBehaviour
{
public Text hintText;
public Sprite black;
public Sprite white;
public static bool Offensive;
public static bool MyTurn;
public const int BoardSize = 15;
private const int BoardLength = 504;
private const int PieceLength = 36;
public GameObject pieceTemplate;
private readonly PieceScript[,] _pieces = new PieceScript[BoardSize+1, BoardSize+1];
private void Start()
{
hintText.text = Offensive ? "该你了" : "等待对手";
for (var i = 1; i <= BoardSize; i++)
{
for (var j = 1; j <= BoardSize; j++)
{
var piece = Instantiate(pieceTemplate, transform, true);
piece.transform.localScale = Vector3.one;
var pieceTransform = piece.transform.localPosition;
pieceTransform.x = -BoardLength / 2 + (i - 1) * PieceLength;
pieceTransform.y = -BoardLength / 2 + (j - 1) * PieceLength;
pieceTransform.z = 1;
piece.transform.localPosition = pieceTransform;
var pieceButton = piece.GetComponent<Button>();
var pieceScript = piece.AddComponent<PieceScript>();
pieceScript.x = i;
pieceScript.y = j;
pieceScript.hintText = hintText;
pieceScript.black = black;
pieceScript.white = white;
pieceButton.onClick.AddListener(pieceScript.Step);
_pieces[i,j] = pieceScript;
MyTurn = Offensive;
}
}
}
public void OpponentStep(int x, int y)
{
_pieces[x, y].OpponentStep();
}
}
|
using Curiosity.Configuration;
using Curiosity.Tools;
namespace Curiosity.Hosting
{
/// <summary>
/// Basic configuration for Marvin's app.
/// </summary>
public interface ICuriosityAppConfiguration: IValidatableOptions, ILoggableOptions
{
/// <summary>
/// Application name.
/// </summary>
/// <remarks>
/// Uses in logging, etc.
/// </remarks>
public string AppName { get; }
/// <summary>
/// Culture options.
/// </summary>
public CultureOptions Culture { get; }
/// <summary>
/// Logs configuration options.
/// </summary>
public ILoggingConfigurationOptions Log { get; }
}
} |
using System;
namespace Joe.Business.Resource
{
public interface IResourceProvider
{
void FlushResourceCache();
string GetResource(string Name, string type);
}
}
|
using SwfLib.ClipActions;
using SwfLib.Data;
namespace SwfLib.Tags.DisplayListTags {
public class PlaceObject2Tag : PlaceObjectBaseTag {
public bool HasClipActions { get; set; }
public bool HasClipDepth { get; set; }
public bool HasName { get; set; }
public bool HasRatio { get; set; }
public bool HasColorTransform { get; set; }
public bool HasMatrix { get; set; }
public bool HasCharacter { get; set; }
public bool Move { get; set; }
/// <summary>
/// Gets or sets ColorTransform.
/// </summary>
public ColorTransformRGBA ColorTransform { get; set; }
public ushort Ratio { get; set; }
/// <summary>
/// Gets or sets name.
/// </summary>
public string Name { get; set; }
public ushort ClipDepth { get; set; }
public readonly ClipActionsList ClipActions = new ClipActionsList();
/// <summary>
/// Gets swf tag type.
/// </summary>
public override SwfTagType TagType {
get { return SwfTagType.PlaceObject2; }
}
public override TResult AcceptVistor<TArg, TResult>(ISwfTagVisitor<TArg, TResult> visitor, TArg arg) {
return visitor.Visit(this, arg);
}
}
} |
// Copyright 2014 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using BenchmarkDotNet.Attributes;
using NodaTime.Calendars;
#if !V1_0 && !V1_1 && !V1_2
namespace NodaTime.Benchmarks.NodaTimeTests.Calendars
{
public class HebrewCalendarBenchmarks
{
// Note: avoiding properties for backward compatibility
private static readonly CalendarSystem ScripturalCalendar = CalendarSystem.GetHebrewCalendar(HebrewMonthNumbering.Scriptural);
private static readonly CalendarSystem CivilCalendar = CalendarSystem.GetHebrewCalendar(HebrewMonthNumbering.Civil);
[Benchmark]
public LocalDate ScripturalConversion() => TestLeapCycle(ScripturalCalendar);
[Benchmark]
public LocalDate CivilConversion() => TestLeapCycle(CivilCalendar);
/// <summary>
/// Converts each day in a full leap cycle (for coverage of different scenarios) to the ISO
/// calendar and back. This exercises fetching the number of days since the epoch and getting
/// a year/month/day *from* a number of days.
/// </summary>
private static LocalDate TestLeapCycle(CalendarSystem calendar)
{
LocalDate returnLocalDate = new LocalDate();
for (int year = 5400; year < 5419; year++)
{
#if !V1
int maxMonth = calendar.GetMonthsInYear(year);
#else
int maxMonth = calendar.GetMaxMonth(year);
#endif
for (int month = 1; month <= maxMonth; month++)
{
int maxDay = calendar.GetDaysInMonth(year, month);
for (int day = 1; day <= maxDay; day++)
{
var date = new LocalDate(year, month, day, calendar);
returnLocalDate = date.WithCalendar(CalendarSystem.Iso).WithCalendar(calendar);
}
}
}
return returnLocalDate;
}
}
}
#endif
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ParkingLot.BusinessInterfaces;
using ParkingLot.Business;
namespace ParkingLotTest.Utils
{
[TestClass]
public class SlotTest
{
private ISlot _slot;
[TestInitialize]
public void SetUp()
{
_slot = new Slot();
}
[TestMethod]
public void GivenCommandAs_create_parking_lot_1_Then_Get_1()
{
//Given: command as "create_parking_lot 1"
string command = "create_parking_lot 1";
//When: I call Slot object
int result = _slot.GetSlotSize(command);
//Then: get 1
Assert.AreEqual(1, result);
}
[TestMethod]
public void GivenCommandAs_create_parking_lot_30000_Then_Get_30000()
{
//Given: command as "create_parking_lot 30000"
string command = "create_parking_lot 30000";
//When: I call Slot object
int result = _slot.GetSlotSize(command);
//Then: get 30000
Assert.AreEqual(30000, result);
}
[TestMethod]
public void GivenCommandAs_create_parking_lot_0_Then_Get_0()
{
//Given: command as "create_parking_lot 0"
string command = "create_parking_lot 0";
//When: I call Slot object
int result = _slot.GetSlotSize(command);
//Then: get 0
Assert.AreEqual(0, result);
}
[TestMethod]
public void GivenCommandAs_create_parking_lot_minus1_Then_Get_minus1()
{
//Given: command as "create_parking_lot -1"
string command = "create_parking_lot -1";
//When: I call Slot object
int result = _slot.GetSlotSize(command);
//Then: get -1
Assert.AreEqual(-1, result);
}
[TestMethod]
public void GivenCommandAs_create_parking_lot_A1_Then_Get_0()
{
//Given: command as "create_parking_lot A1"
string command = "create_parking_lot A1";
//When: I call Slot object
int result = _slot.GetSlotSize(command);
//Then: get 0
Assert.AreEqual(0, result);
}
[TestMethod]
public void GivenCommandAs_EmptyString_Then_Get_0()
{
//Given: command as emptyString
string command = string.Empty;
//When: I call Slot object
int result = _slot.GetSlotSize(command);
//Then: get 0
Assert.AreEqual(0, result);
}
[TestMethod]
public void GivenCommandAs_create_parking_lot_Space_Then_Get_0()
{
//Given: command as "create_parking_lot "
string command = "create_parking_lot ";
//When: I call Slot object
int result = _slot.GetSlotSize(command);
//Then: get 0
Assert.AreEqual(0, result);
}
[TestMethod]
public void GivenCommandAs_create_parking_lot_Then_Get_0()
{
//Given: command as "create_parking_lot"
string command = "create_parking_lot";
//When: I call Slot object
int result = _slot.GetSlotSize(command);
//Then: get 0
Assert.AreEqual(0, result);
}
}
} |
namespace River.Orqa.Editor.Common
{
using System;
using System.Drawing;
public interface IRange
{
// Properties
Point EndPoint { get; set; }
Point StartPoint { get; set; }
}
}
|
//Session 2: Conditionals, Loops and Classes
//12Nov 2017
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Session2 : MonoBehaviour {
//Variables
int myNumber = 2;
public bool QuestionTime = true;
int myVariableQuestionTime;
string[] fruits = { "banana", "apple", "mange", "blueberry" };
List<int> evenNumbers = new List<int>();
int[] evenNumbersSmart = new int[10];
// Use this for initialization
void Start () {
//variable name is equal to either 1 or 0 based on the value of questionTime
myVariableQuestionTime = (QuestionTime == true) ? 1 : 0;
Debug.Log("The value of myVariableQuestionTime is :" + myVariableQuestionTime);
if (myNumber==2)
{
Debug.Log("Your number is equal to 2.");
}else
{
Debug.Log("Your number is equal to 2.");
}
}
// Update is called once per frame
void Update () {
}
}
|
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Discovery
{
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
abstract class ResolveRequestResponseAsyncResult<TResolveMessage, TResponseMessage> : AsyncResult
{
readonly ResolveCriteria resolveCriteria;
readonly IDiscoveryServiceImplementation discoveryServiceImpl;
readonly DiscoveryOperationContext context;
static AsyncCompletion onOnResolveCompletedCallback = new AsyncCompletion(OnOnResolveCompleted);
EndpointDiscoveryMetadata matchingEndpoint;
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
protected ResolveRequestResponseAsyncResult(
TResolveMessage resolveMessage,
IDiscoveryServiceImplementation discoveryServiceImpl,
AsyncCallback callback,
object state)
: base(callback, state)
{
Fx.Assert(resolveMessage != null, "The resolveMessage must be non null.");
Fx.Assert(discoveryServiceImpl != null, "The discoveryServiceImpl must be non null.");
this.discoveryServiceImpl = discoveryServiceImpl;
if (!this.Validate(resolveMessage))
{
this.Complete(true);
return;
}
else
{
this.context = new DiscoveryOperationContext(OperationContext.Current);
this.resolveCriteria = this.GetResolveCriteria(resolveMessage);
if (this.ProcessResolveRequest())
{
this.Complete(true);
return;
}
}
}
protected DiscoveryOperationContext Context
{
get
{
return this.context;
}
}
protected virtual bool Validate(TResolveMessage resolveMessage)
{
return (DiscoveryService.EnsureMessageId() &&
this.ValidateContent(resolveMessage) &&
this.EnsureNotDuplicate());
}
protected abstract bool ValidateContent(TResolveMessage resolveMessage);
protected abstract ResolveCriteria GetResolveCriteria(TResolveMessage resolveMessage);
protected abstract TResponseMessage GetResolveResponse(
DiscoveryMessageSequence discoveryMessageSequence,
EndpointDiscoveryMetadata matchingEndpoints);
protected TResponseMessage End()
{
this.context.AddressRequestResponseMessage(OperationContext.Current);
return this.GetResolveResponse(
this.discoveryServiceImpl.GetNextMessageSequence(),
this.matchingEndpoint);
}
static bool OnOnResolveCompleted(IAsyncResult result)
{
ResolveRequestResponseAsyncResult<TResolveMessage, TResponseMessage> thisPtr =
(ResolveRequestResponseAsyncResult<TResolveMessage, TResponseMessage>)result.AsyncState;
thisPtr.matchingEndpoint = thisPtr.discoveryServiceImpl.EndResolve(result);
return true;
}
bool ProcessResolveRequest()
{
IAsyncResult result = this.discoveryServiceImpl.BeginResolve(
this.resolveCriteria,
this.PrepareAsyncCompletion(onOnResolveCompletedCallback),
this);
return (result.CompletedSynchronously && OnOnResolveCompleted(result));
}
bool EnsureNotDuplicate()
{
bool isDuplicate = this.discoveryServiceImpl.IsDuplicate(OperationContext.Current.IncomingMessageHeaders.MessageId);
if (isDuplicate && TD.DuplicateDiscoveryMessageIsEnabled())
{
TD.DuplicateDiscoveryMessage(
this.context.EventTraceActivity,
ProtocolStrings.TracingStrings.Resolve,
OperationContext.Current.IncomingMessageHeaders.MessageId.ToString());
}
return !isDuplicate;
}
}
}
|
namespace Cafe.Api.Hateoas.Resources.Waiter
{
public class WaitersContainerResource : ResourceContainer<WaiterResource>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Threading;
namespace UniMob
{
internal sealed class TimerDispatcher : IDisposable
{
private static int _mainThreadId;
private readonly Action<Exception> _exceptionHandler;
private readonly object _lock = new object();
private readonly List<Action> _threadedQueue = new List<Action>();
private readonly List<Action> _tickers = new List<Action>();
private float _time;
private int _threadedDirty;
private List<Action> _queue = new List<Action>();
private List<Action> _toPass = new List<Action>();
internal bool ThreadedDirty => _threadedDirty == 1;
public TimerDispatcher(int mainThreadId, Action<Exception> exceptionHandler)
{
_mainThreadId = mainThreadId;
_exceptionHandler = exceptionHandler ?? throw new ArgumentNullException(nameof(exceptionHandler));
}
public void Dispose()
{
lock (_lock)
{
_threadedQueue.Clear();
}
_queue.Clear();
_toPass.Clear();
}
internal void Tick(float time)
{
if (Interlocked.CompareExchange(ref _threadedDirty, 0, 1) == 1)
{
lock (_lock)
{
if (_threadedQueue.Count > 0)
{
_queue.AddRange(_threadedQueue);
_threadedQueue.Clear();
}
}
}
_time = time;
_toPass.Clear();
var emptyList = _toPass;
_toPass = _queue;
_queue = emptyList;
for (int i = 0; i < _toPass.Count; i++)
{
try
{
_toPass[i].Invoke();
}
catch (Exception ex)
{
_exceptionHandler(ex);
}
}
for (var i = _tickers.Count - 1; i >= 0; i--)
{
try
{
_tickers[i].Invoke();
}
catch (Exception ex)
{
_exceptionHandler(ex);
}
}
}
internal void AddTicker(Action action)
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (Thread.CurrentThread.ManagedThreadId != _mainThreadId)
{
throw new InvalidOperationException($"{nameof(AddTicker)} must be called from MainThread");
}
_tickers.Add(action);
}
internal void RemoveTicker(Action action)
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (Thread.CurrentThread.ManagedThreadId != _mainThreadId)
{
throw new InvalidOperationException($"{nameof(AddTicker)} must be called from MainThread");
}
_tickers.Remove(action);
}
internal void Invoke(Action action)
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (Thread.CurrentThread.ManagedThreadId == _mainThreadId)
{
_queue.Add(action);
}
else
{
lock (_lock)
{
_threadedQueue.Add(action);
Interlocked.Exchange(ref _threadedDirty, 1);
}
}
}
}
} |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace FabricDCA.Test
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Diagnostics.Tracing;
using System.Fabric.Common;
using System.Fabric.Common.Tracing;
using System.Fabric.Dca;
using System.Fabric.Dca.EtlConsumerHelper;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Tools.EtlReader;
[TestClass]
public class EtlInMemoryProducerTests
{
private const string LogSourceId = "EtlInMemoryProducerTests";
private const string TestNodeId = "abcd";
private static string executingAssemblyPath;
private static string dcaTestArtifactPath;
private static string activeEtlFileName;
private static string expectedOutputDataFolderPath;
// <summary>
/// Set static state shared between all tests.
/// </summary>
/// <param name="context">Test context.</param>
[ClassInitialize]
public static void ClassSetup(TestContext context)
{
Utility.TraceSource = new ErrorAndWarningFreeTraceEventSource();
executingAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var sourceArtifactPath = Path.Combine(
executingAssemblyPath,
"DcaTestArtifacts");
dcaTestArtifactPath = Path.Combine(Environment.CurrentDirectory, "DcaTestArtifacts_EtlInMemoryProducerTests");
TestUtility.CopyAndOverwrite(Path.Combine(sourceArtifactPath, TestUtility.ManifestFolderName), Path.Combine(dcaTestArtifactPath, TestUtility.ManifestFolderName));
// Rename .etl.dat files to .etl. This is a workaround for runtests.cmd which exludes .etl files
// from upload.
var destFolder = Path.Combine(dcaTestArtifactPath, "Data");
TestUtility.CopyAndOverwrite(Path.Combine(sourceArtifactPath, "Data"), destFolder);
foreach (var file in Directory.GetFiles(destFolder, "*.etl.dat"))
{
// Move file to same name without .dat extension
var etlName = file.Substring(0, file.Length - 4);
if (File.Exists(etlName))
{
File.Delete(etlName);
}
File.Move(file, etlName);
}
// Remove everything but etls
foreach (var file in Directory.GetFiles(destFolder))
{
if (Path.GetExtension(file) != ".etl")
{
File.Delete(file);
}
}
// Set active file name to the file with largest filetimestamp in name.
activeEtlFileName =
Path.GetFileName(
Directory.GetFiles(Path.Combine(dcaTestArtifactPath, "Data")).OrderByDescending(n => n).First());
expectedOutputDataFolderPath = Path.Combine(sourceArtifactPath, "OutputData");
var logFolderPrefix = Path.Combine(Environment.CurrentDirectory, LogSourceId);
Directory.CreateDirectory(logFolderPrefix);
TraceTextFileSink.SetPath(Path.Combine(logFolderPrefix, LogSourceId));
}
/// <summary>
/// Test inactive and active etl files are converted given enough time.
/// </summary>
[TestMethod]
public void TestNormalEtlProcessing()
{
var testEtlPath = TestUtility.InitializeTestFolder("EtlInMemoryProducerTests", "TestNormalEtlProcessing", executingAssemblyPath, dcaTestArtifactPath);
var etlInMemoryProducer = CreateEtlInMemoryProducerForTest(testEtlPath, new TraceFileEventReaderFactory());
Thread.Sleep(TimeSpan.FromSeconds(10));
etlInMemoryProducer.Dispose();
TestUtility.AssertFinished(testEtlPath, expectedOutputDataFolderPath);
}
/// <summary>
/// Test inactive and active etl files are converted using FlushOnDispose flag.
/// </summary>
[TestMethod]
public void TestShutdownLoss()
{
var testEtlPath = TestUtility.InitializeTestFolder("EtlInMemoryProducerTests", "TestShutdownLoss", executingAssemblyPath, dcaTestArtifactPath);
var etlProducer = CreateEtlInMemoryProducerForTest(testEtlPath, new TraceFileEventReaderFactory());
etlProducer.FlushData();
// Must flush a second time or last trace will be left off to protect against duplicates.
// If better checkpointing can be used then this call might not be necessary.
etlProducer.FlushData();
etlProducer.Dispose();
TestUtility.AssertFinished(testEtlPath, expectedOutputDataFolderPath);
}
/// <summary>
/// Test active etl file gets converted properly over lifetime of different EtlProducers.
/// </summary>
[TestMethod]
public void TestStopStartLoss()
{
var testEtlPath = TestUtility.InitializeTestFolder("EtlInMemoryProducerTests", "TestStopStartLoss", executingAssemblyPath, dcaTestArtifactPath);
var activeEtlFilePath = Path.Combine(testEtlPath, activeEtlFileName);
var mockTraceFileEventReaderFactory = TestUtility.MockRepository.Create<ITraceFileEventReaderFactory>();
mockTraceFileEventReaderFactory
.Setup(f => f.CreateTraceFileEventReader(It.Is((string file) => file == activeEtlFilePath)))
.Returns(() => TestUtility.CreateForwardingEventReader(activeEtlFilePath).Object);
mockTraceFileEventReaderFactory
.Setup(f => f.CreateTraceFileEventReader(It.Is((string file) => file != activeEtlFilePath)))
.Returns((string f) => new TraceFileEventReader(f));
var etlInMemoryProducer = CreateEtlInMemoryProducerForTest(testEtlPath, mockTraceFileEventReaderFactory.Object);
Thread.Sleep(TimeSpan.FromSeconds(6));
etlInMemoryProducer.Dispose();
etlInMemoryProducer = CreateEtlInMemoryProducerForTest(testEtlPath, mockTraceFileEventReaderFactory.Object);
Thread.Sleep(TimeSpan.FromSeconds(6));
etlInMemoryProducer.Dispose();
TestUtility.AssertFinished(testEtlPath, expectedOutputDataFolderPath);
}
/// <summary>
/// Tests that the in-memory producer blocks until it gets acked by both
/// the fast and the slow consumer.
/// </summary>
[TestMethod]
public void TestEtlProcessingWithFastAndSlowConsumer()
{
var testEtlPath = TestUtility.InitializeTestFolder("EtlInMemoryProducerTests", "TestEtlProcessingWithFastAndSlowConsumer", executingAssemblyPath, dcaTestArtifactPath);
var etlInMemoryProducer = CreateEtlInMemoryProducerWithFastAndSlowConsumerForTest(testEtlPath, new TraceFileEventReaderFactory());
Thread.Sleep(TimeSpan.FromSeconds(15));
etlInMemoryProducer.Dispose();
TestUtility.AssertFinished(testEtlPath, expectedOutputDataFolderPath, "*_fast");
TestUtility.AssertFinished(testEtlPath, expectedOutputDataFolderPath, "*_slow");
}
private static EtlInMemoryProducer CreateEtlInMemoryProducerForTest(
string logDirectory,
ITraceFileEventReaderFactory traceFileEventReaderFactory)
{
var mockDiskSpaceManager = TestUtility.MockRepository.Create<DiskSpaceManager>();
var etlInMemoryProducerSettings = new EtlInMemoryProducerSettings(
true,
TimeSpan.FromSeconds(1),
TimeSpan.FromDays(3000),
WinFabricEtlType.DefaultEtl,
logDirectory,
TestUtility.TestEtlFilePatterns,
true);
var configReader = TestUtility.MockRepository.Create<IEtlInMemoryProducerConfigReader>();
configReader.Setup(c => c.GetSettings()).Returns(etlInMemoryProducerSettings);
var mockTraceEventSourceFactory = TestUtility.MockRepository.Create<ITraceEventSourceFactory>();
mockTraceEventSourceFactory
.Setup(tsf => tsf.CreateTraceEventSource(It.IsAny<EventTask>()))
.Returns(new ErrorAndWarningFreeTraceEventSource());
var configStore = TestUtility.MockRepository.Create<IConfigStore>();
configStore
.Setup(cs => cs.ReadUnencryptedString("Diagnostics", "MaxDiskQuotaInMB"))
.Returns("100");
configStore
.Setup(cs => cs.ReadUnencryptedString("Diagnostics", "DiskFullSafetySpaceInMB"))
.Returns("0");
Utility.InitializeConfigStore(configStore.Object);
var mockConfigReaderFactory = TestUtility.MockRepository.Create<IEtlInMemoryProducerConfigReaderFactory>();
mockConfigReaderFactory.Setup(f => f.CreateEtlInMemoryProducerConfigReader(It.IsAny<FabricEvents.ExtensionsEvents>(), It.IsAny<string>()))
.Returns(configReader.Object);
var dcaInMemoryConsumer = CreateEtlToInMemoryBufferWriter(logDirectory, null);
var etlToInMemoryBufferWriter = new EtlToInMemoryBufferWriter(
mockTraceEventSourceFactory.Object,
LogSourceId,
TestNodeId,
TestUtility.GetActualOutputFolderPath(logDirectory),
true,
dcaInMemoryConsumer);
var initParam = new ProducerInitializationParameters
{
ConsumerSinks = new[] { etlToInMemoryBufferWriter }
};
return new EtlInMemoryProducer(
mockDiskSpaceManager.Object,
mockConfigReaderFactory.Object,
traceFileEventReaderFactory,
mockTraceEventSourceFactory.Object,
initParam);
}
private static EtlInMemoryProducer CreateEtlInMemoryProducerWithFastAndSlowConsumerForTest(
string logDirectory,
ITraceFileEventReaderFactory traceFileEventReaderFactory)
{
var mockDiskSpaceManager = TestUtility.MockRepository.Create<DiskSpaceManager>();
var etlInMemoryProducerSettings = new EtlInMemoryProducerSettings(
true,
TimeSpan.FromSeconds(1),
TimeSpan.FromDays(3000),
WinFabricEtlType.DefaultEtl,
logDirectory,
TestUtility.TestEtlFilePatterns,
true);
var configReader = TestUtility.MockRepository.Create<IEtlInMemoryProducerConfigReader>();
configReader.Setup(c => c.GetSettings()).Returns(etlInMemoryProducerSettings);
var mockTraceEventSourceFactory = TestUtility.MockRepository.Create<ITraceEventSourceFactory>();
mockTraceEventSourceFactory
.Setup(tsf => tsf.CreateTraceEventSource(It.IsAny<EventTask>()))
.Returns(new ErrorAndWarningFreeTraceEventSource());
var configStore = TestUtility.MockRepository.Create<IConfigStore>();
configStore
.Setup(cs => cs.ReadUnencryptedString("Diagnostics", "MaxDiskQuotaInMB"))
.Returns("100");
configStore
.Setup(cs => cs.ReadUnencryptedString("Diagnostics", "DiskFullSafetySpaceInMB"))
.Returns("0");
Utility.InitializeConfigStore(configStore.Object);
var mockConfigReaderFactory = TestUtility.MockRepository.Create<IEtlInMemoryProducerConfigReaderFactory>();
mockConfigReaderFactory.Setup(f => f.CreateEtlInMemoryProducerConfigReader(It.IsAny<FabricEvents.ExtensionsEvents>(), It.IsAny<string>()))
.Returns(configReader.Object);
var fastDcaInMemoryConsumer = CreateEtlToInMemoryBufferWriter(logDirectory, false);
var slowDcaInMemoryConsumer = CreateEtlToInMemoryBufferWriter(logDirectory, true);
var fastEtlToInMemoryBufferWriter = new EtlToInMemoryBufferWriter(
mockTraceEventSourceFactory.Object,
LogSourceId,
TestNodeId,
TestUtility.GetActualOutputFolderPath(logDirectory),
true,
fastDcaInMemoryConsumer);
var slowEtlToInMemoryBufferWriter = new EtlToInMemoryBufferWriter(
mockTraceEventSourceFactory.Object,
LogSourceId,
TestNodeId,
TestUtility.GetActualOutputFolderPath(logDirectory),
true,
slowDcaInMemoryConsumer);
var initParam = new ProducerInitializationParameters
{
ConsumerSinks = new[] { fastEtlToInMemoryBufferWriter, slowEtlToInMemoryBufferWriter }
};
return new EtlInMemoryProducer(
mockDiskSpaceManager.Object,
mockConfigReaderFactory.Object,
traceFileEventReaderFactory,
mockTraceEventSourceFactory.Object,
initParam);
}
private static string CreateDestinationFileName(string etlFileName, string additionalSuffix, bool isActiveEtl, EventIndex lastEventIndexProcessed)
{
string differentiator = string.Format(
CultureInfo.InvariantCulture,
"{0:D10}",
isActiveEtl ? lastEventIndexProcessed.TimestampDifferentiator : int.MaxValue);
string traceFileNamePrefix = string.Format(
CultureInfo.InvariantCulture,
"{0}_{1}_{2:D20}_{3}{4}.",
TestNodeId,
Path.GetFileNameWithoutExtension(etlFileName),
lastEventIndexProcessed.Timestamp.Ticks,
differentiator,
additionalSuffix);
return string.Concat(
traceFileNamePrefix,
EtlConsumerConstants.FilteredEtwTraceFileExtension);
}
private static IDcaInMemoryConsumer CreateEtlToInMemoryBufferWriter(string logDirectory, bool? slow)
{
EventIndex globalLastEventIndexProcessed = default(EventIndex);
globalLastEventIndexProcessed.Set(DateTime.MinValue, -1);
InternalFileSink fileSink = new InternalFileSink(Utility.TraceSource, LogSourceId);
EventIndex lastEventIndexProcessed = default(EventIndex);
var onProcessingPeriodStartActionForFastWriter = new Action<string, bool, string>((traceFileName, isActiveEtl, traceFileSubFolder) =>
{
fileSink.Initialize();
lastEventIndexProcessed.Set(DateTime.MinValue, -1);
});
var maxIndexAlreadyProcessedForFastWriter = new Func<string, EventIndex>((traceFileSubFolder) =>
{
return globalLastEventIndexProcessed;
});
var consumerProcessTraceEventActionForFastWriter = new Action<DecodedEventWrapper, string>((decodedEventWrapper, traceFileSubFolder) =>
{
string etwEvent = decodedEventWrapper.StringRepresentation.Replace("\r\n", "\r\t").Replace("\n", "\t");
fileSink.WriteEvent(etwEvent);
lastEventIndexProcessed.Set(decodedEventWrapper.Timestamp, decodedEventWrapper.TimestampDifferentiator);
});
var onProcessingPeriodStopActionForFastWriter = new Action<string, bool, string>((traceFileName, isActiveEtl, traceFileSubFolder) =>
{
if (slow.HasValue && slow.Value)
{
Thread.Sleep(2000);
}
fileSink.Close();
if (fileSink.WriteStatistics.EventsWritten > 0)
{
var additionalSuffix = (slow.HasValue) ? (slow.Value ? "_slow" : "_fast") : (string.Empty);
var destFileName = CreateDestinationFileName(traceFileName, additionalSuffix, isActiveEtl, lastEventIndexProcessed);
File.Move(fileSink.TempFileName, Path.Combine(logDirectory, "output", destFileName));
globalLastEventIndexProcessed.Set(lastEventIndexProcessed.Timestamp, lastEventIndexProcessed.TimestampDifferentiator);
}
else
{
fileSink.Delete();
}
});
var dcaInMemoryConsumer = TestUtility.MockRepository.Create<IDcaInMemoryConsumer>();
dcaInMemoryConsumer.Setup(c => c.ConsumerProcessTraceEventAction)
.Returns(consumerProcessTraceEventActionForFastWriter);
dcaInMemoryConsumer.Setup(c => c.MaxIndexAlreadyProcessed)
.Returns(maxIndexAlreadyProcessedForFastWriter);
dcaInMemoryConsumer.Setup(c => c.OnProcessingPeriodStart(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>()))
.Callback((string traceFileName, bool isActiveEtl, string traceFileSubFolder) => onProcessingPeriodStartActionForFastWriter(traceFileName, isActiveEtl, traceFileSubFolder));
dcaInMemoryConsumer.Setup(c => c.OnProcessingPeriodStop(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>()))
.Callback((string traceFileName, bool isActiveEtl, string traceFileSubFolder) => onProcessingPeriodStopActionForFastWriter(traceFileName, isActiveEtl, traceFileSubFolder));
return dcaInMemoryConsumer.Object;
}
}
} |
using System;
namespace ESFA.DC.CrossLoad.Dto
{
[Serializable]
public sealed class MessageCrossLoadDcftToDctDto
{
/// <summary>
/// Unique job id of job.
/// </summary>
public long JobId { get; set; }
/// <summary>
/// [Optional] An error message if the job failed.
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// The storage container where the report zip file is stored.
/// </summary>
public string StorageContainerName { get; set; }
/// <summary>
/// The file name of the report zip file 1.
/// </summary>
public string StorageFileNameReport1 { get; set; }
/// <summary>
/// The file name of the report zip file 2.
/// </summary>
public string StorageFileNameReport2 { get; set; }
/// <summary>
/// dcft system job id for reference
/// </summary>
public string DcftJobId { get; set; }
}
}
|
// ┌∩┐(◣_◢)┌∩┐
// \\
// SimpleCarga.cs (30/05/2017) \\
// Autor: Antonio Mateo (Moon Antonio) antoniomt.moon@gmail.com \\
// Descripcion: Ejemplo Carga simple \\
// Fecha Mod: 30/05/2017 \\
// Ultima Mod: Version Inicial \\
//******************************************************************************\\
#region Librerias
using UnityEngine;
#endregion
namespace MoonAntonio
{
/// <summary>
/// <para>Ejemplo Carga simple</para>
/// </summary>
public class SimpleCarga : MonoBehaviour
{
#region Variables
/// <summary>
/// <para>Manager de la escena</para>
/// </summary>
public GameObject manager; // Manager de la escena
#endregion
#region Metodos
/// <summary>
/// <para>Carga los datos</para>
/// </summary>
public void Cargar()// Carga los datos
{
// Accedemos al manager
ManagerTest script = manager.GetComponent<ManagerTest>();
// Cargamos el valor de vida con el nombre vida
script.vida = ES2.Load<int>("vida");
// Guardamos el valor de mana con el nombre mana
script.mana = ES2.Load<int>("mana");
// Guardamos el valor de isAtaque con el nombre atack
script.isAtaque = ES2.Load<bool>("atack");
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using VividboxBlazor.Shared;
namespace VividboxBlazor.Client.Services.ProductService
{
public class ProductService : IProductService
{
private readonly HttpClient _http;
public event Action OnChange;
public List<Product> Products { get; set; } = new List<Product>();
public ProductService(HttpClient http)
{
_http = http;
}
public async Task LoadProducts(string categoryUrl = null)
{
if (categoryUrl == null)
{
Products = await _http.GetFromJsonAsync<List<Product>>($"api/Product/");
}
else
{
Products = await _http.GetFromJsonAsync<List<Product>>($"api/Product/Category/{categoryUrl}");
}
OnChange.Invoke();
}
public async Task<Product> GetProduct(int id)
{
return await _http.GetFromJsonAsync<Product>($"api/Product/{id}") ;
}
}
} |
using FoodVault.Framework.Application.FileUploads;
using MediatR;
using System.Threading;
using System.Threading.Tasks;
namespace FoodVault.Modules.Storage.Application.Products.RemoveProductImage
{
/// <summary>
/// Notification handler for <see cref="ProductImageRemovedNotification"/>.
/// </summary>
internal class ProductImageRemovedNotificationHandler : INotificationHandler<ProductImageRemovedNotification>
{
private readonly IFileStorage _fileStorage;
/// <summary>
/// Initializes a new instance of the <see cref="ProductImageRemovedNotificationHandler" /> class.
/// </summary>
/// <param name="fileStorage">Applications file storage.</param>
public ProductImageRemovedNotificationHandler(IFileStorage fileStorage)
{
_fileStorage = fileStorage;
}
/// <inheritdoc />
public async Task Handle(ProductImageRemovedNotification notification, CancellationToken cancellationToken)
{
await _fileStorage.DeleteFileAsync(notification.ImageId);
}
}
}
|
using CharacterCreator.Port;
using Archai.CharacterCreator.Domain.Entity;
namespace CharacterCreator.Port
{
public interface IProjectRepository<L>
{
void LoadProject(L path);
void SaveProject(L path);
L GetLocator(Project project);
}
}
|
namespace ClientRepository.Model.Interfaces
{
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>
/// Interface IDbClient
/// </summary>
public interface IDbClient
{
/// <summary>
/// Gets the asynchronous.
/// </summary>
/// <returns>Task<IEnumerable<Ad>>.</returns>
Task<IEnumerable<Ad>> GetAsync();
}
}
|
namespace SWAC
{
using System;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
public static class ProtPlayerPrefs
{
private const int salt = 678309397;
public static void SetInt(string key, int value)
{
int salted = value ^ salt;
PlayerPrefs.SetInt(StringHash(key), salted);
PlayerPrefs.SetInt(StringHash("_" + key), IntHash(value));
}
public static int GetInt(string key)
{
return GetInt(key, 0);
}
public static int GetInt(string key, int defaultValue)
{
string hashedKey = StringHash(key);
if (!PlayerPrefs.HasKey(hashedKey)) return defaultValue;
int salted = PlayerPrefs.GetInt(hashedKey);
int value = salted ^ salt;
int loadedHash = PlayerPrefs.GetInt(StringHash("_" + key));
if (loadedHash != IntHash(value)) return defaultValue;
return value;
}
public static void SetFloat(string key, float value)
{
int intValue = BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
int salted = intValue ^ salt;
PlayerPrefs.SetInt(StringHash(key), salted);
PlayerPrefs.SetInt(StringHash("_" + key), IntHash(intValue));
}
public static float GetFloat(string key)
{
return GetFloat(key, 0);
}
public static float GetFloat(string key, float defaultValue)
{
string hashedKey = StringHash(key);
if (!PlayerPrefs.HasKey(hashedKey)) return defaultValue;
int salted = PlayerPrefs.GetInt(hashedKey);
int value = salted ^ salt;
int loadedHash = PlayerPrefs.GetInt(StringHash("_" + key));
if (loadedHash != IntHash(value)) return defaultValue;
return BitConverter.ToSingle(BitConverter.GetBytes(value), 0);
}
private static int IntHash(int x)
{
x = ((x >> 16) ^ x) * 0x45d9f3b;
x = ((x >> 16) ^ x) * 0x45d9f3b;
x = (x >> 16) ^ x;
return x;
}
private static string StringHash(string x)
{
HashAlgorithm algorithm = SHA256.Create();
StringBuilder sb = new StringBuilder();
var bytes = algorithm.ComputeHash(Encoding.UTF8.GetBytes(x));
foreach (byte b in bytes) sb.Append(b.ToString("X2"));
return sb.ToString();
}
public static void DeleteKey(string key)
{
PlayerPrefs.DeleteKey(StringHash(key));
PlayerPrefs.DeleteKey(StringHash("_" + key));
}
public static bool HasKey(string key)
{
string hashedKey = StringHash(key);
if (!PlayerPrefs.HasKey(hashedKey)) return false;
int salted = PlayerPrefs.GetInt(hashedKey);
int value = salted ^ salt;
int loadedHash = PlayerPrefs.GetInt(StringHash("_" + key));
return loadedHash == IntHash(value);
}
}
} |
using System.Net;
using System.Net.Http;
namespace Blazor.YouTubeDownloader.Api.HttpClientHandlers
{
/// <summary>
/// https://github.com/Tyrrrz/YoutubeExplode/issues/529
/// https://github.com/omansak/libvideo/issues/201
/// </summary>
public class YouTubeCookieConsentHandler : HttpClientHandler
{
public YouTubeCookieConsentHandler()
{
UseCookies = true;
CookieContainer = new CookieContainer();
CookieContainer.Add(new Cookie("CONSENT", "YES+cb", "/", "youtube.com"));
}
}
} |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TMS.NET06.CaloriesCounter.MVC.Models;
namespace TMS.NET06.CaloriesCounter.MVC.Controllers
{
[Authorize(Roles = "Admin")]
public class AnalizationController : Controller
{
[HttpGet]
[ActionName("Index")]
public ActionResult GetIndex()
{
var list = TempData["DataBetweenRequests"];
if (list != null)
return View(list as IList<ProductRow>);
return View();
}
[HttpPost]
[ActionName("Index")]
public ActionResult PostIndex(IList<ProductRow> entries)
{
entries.Add(new ProductRow());
TempData["DataBetweenRequests"] = entries.ToArray();
return Redirect("Index");
//return View(entries);
}
[HttpPost]
public ActionResult DeleteLastRow(IList<ProductRow> entries)
{
if (entries.Count > 0)
entries.RemoveAt(entries.Count - 1);
return Redirect("Index");
//return View("Index", entries);
}
// GET: AnalizationController/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: AnalizationController/Create
public ActionResult Create()
{
return View();
}
// POST: AnalizationController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: AnalizationController/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: AnalizationController/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: AnalizationController/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: AnalizationController/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
}
}
|
using System;
using Tailviewer.BusinessLogic;
namespace TablePlayground
{
/// <summary>
/// A collection of columns which every log file provides.
/// It is possible that log files don't provide any data in a column, however.
/// </summary>
public sealed class DefaultLogColumns
{
public static readonly ILogColumn<DateTime> Timestamp;
public static readonly ILogColumn<TimeSpan> ElapsedDelta;
public static readonly ILogColumn<LevelFlags> Level;
public static readonly ILogColumn<int> LineNumber;
public static readonly ILogColumn<LogLineIndex> LineIndex;
public static readonly ILogColumn<int> OriginalLineNumber;
public static readonly ILogColumn<LogLineIndex> OriginalLineIndex;
public static readonly ILogColumn<LogLineSourceId> Source;
public static readonly ILogColumn<string> RawLine;
public static readonly ILogColumn<string> Logger;
public static readonly ILogColumn<string> Thread;
public static readonly ILogColumn<string> Message;
static DefaultLogColumns()
{
Timestamp = new LogColumn<DateTime>();
ElapsedDelta = new LogColumn<TimeSpan>();
Level = new LogColumn<LevelFlags>();
LineNumber = new LogColumn<int>();
LineIndex = new LogColumn<LogLineIndex>();
OriginalLineNumber = new LogColumn<int>();
OriginalLineIndex = new LogColumn<LogLineIndex>();
Source = new LogColumn<LogLineSourceId>();
RawLine = new LogColumn<string>();
Logger = new LogColumn<string>();
Thread = new LogColumn<string>();
Message = new LogColumn<string>();
}
}
} |
using Machine.Specifications;
using Should.Fluent.Model;
namespace Should.Fluent.UnitTests
{
public class be_double_test_base : test_base<double>
{
protected static BeBase<double> be;
}
public class should_be_double_context : be_double_test_base
{
Establish context = () => be = new Should<double, BeBase<double>>(target, mockAssertProvider.Object).Be;
}
public class should_not_be_double_context : be_double_test_base
{
Establish context = () => be = new Should<double, BeBase<double>>(target, mockAssertProvider.Object).Not.Be;
}
public class when_calling_double_positive : should_be_double_context
{
Because of = () => result = be.Positive();
Behaves_like<result_should_be_target<double>> yes;
It should_assert_greater_than = () => Called(x => x.GreaterThan<double>(target, 0));
}
public class when_calling_double_not_positive : should_not_be_double_context
{
Because of = () => result = be.Positive();
Behaves_like<result_should_be_target<double>> yes;
It should_assert_lessorequal = () => Called(x => x.LessThanOrEqual<double>(target, 0));
}
public class when_calling_double_negative : should_be_double_context
{
Because of = () => result = be.Negative();
Behaves_like<result_should_be_target<double>> yes;
It should_assert_greater = () => Called(x => x.LessThan<double>(target, 0));
}
public class when_calling_double_not_negative : should_not_be_double_context
{
Because of = () => result = be.Negative();
Behaves_like<result_should_be_target<double>> yes;
It should_assert_lessorequal = () => Called(x => x.GreaterThanOrEqual<double>(target, 0));
}
} |
/*
* Experimental script. This scripts creates a Generate Skeletons button in the Experimental scene.
*/
using UnityEngine;
using UnityEditor;
namespace Riggingtools.Skeletons
{
[CustomEditor(typeof(PluginLoaderEditor))]
public class SpawnSkeletons : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
PluginLoaderEditor loadSkeletons = (PluginLoaderEditor)target;
if (GUILayout.Button("Generate Skeletons"))
{
loadSkeletons.GenerateSkeletons();
}
}
}
}
|
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.
namespace Aqua.AccessControl.Predicates
{
using System;
using System.Linq.Expressions;
using System.Reflection;
internal sealed class PropertyProjection : IPropertyProjection
{
internal PropertyProjection(MemberInfo property, Type type, Type propertyType, LambdaExpression projection)
{
Assert.ArgumentNotNull(property, nameof(property));
Type = Assert.ArgumentNotNull(type, nameof(type));
Property = Assert.PropertyInfoArgument(property, nameof(property));
PropertyType = Assert.ArgumentNotNull(propertyType, nameof(propertyType));
Projection = Assert.ArgumentNotNull(projection, nameof(projection));
}
public Type Type { get; }
public MemberInfo Property { get; }
public Type PropertyType { get; }
public LambdaExpression Projection { get; }
public Expression ApplyTo(Expression expression)
=> PropertyProjectionHelper.Apply(
new[] { this },
Assert.ArgumentNotNull(expression, nameof(expression)),
Property.DeclaringType);
}
}
|
using UnityEngine;
using System.Collections;
public class Colorable : MonoBehaviour {
public MeshRenderer[] renderers;
Material[] localMaterials = null;
private Color color = Color.white;
public Color Color {
get { return color; }
set {
if(value != null) {
SetColor(value);
color = value;
}
}
}
void CopyMaterials() {
if (localMaterials == null) {
localMaterials = new Material[renderers.Length];
for(int i = 0; i < renderers.Length; i++) {
localMaterials[i] = new Material(renderers[i].material);
renderers[i].material = localMaterials[i];
}
}
}
void SetColor(Color color) {
if (localMaterials == null) {
CopyMaterials();
}
foreach (Material material in localMaterials) {
//material.SetColor ("_Color",color);
material.color = color;
material.shader = material.shader;
//print (material.GetFloat("_BumpScale"));
//material.SetTexture ("_BumpMap", material.GetTexture("_BumpMap"));
}
}
}
|
namespace Lsquared.SmartHome.Zigbee.ZCL
{
public sealed record AttributeResponsePayload(ushort ID, byte Flags, AttributeValue Value) : Zigbee.ICommandPayload
{
public override string ToString() =>
$"- ID: {ID:X4}, Flags: {Flags:X2}, {Value}";
}
}
|
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\d3dcompiler.h(467,9)
namespace DirectN
{
public enum D3D_BLOB_PART
{
D3D_BLOB_INPUT_SIGNATURE_BLOB = 0,
D3D_BLOB_OUTPUT_SIGNATURE_BLOB = 1,
D3D_BLOB_INPUT_AND_OUTPUT_SIGNATURE_BLOB = 2,
D3D_BLOB_PATCH_CONSTANT_SIGNATURE_BLOB = 3,
D3D_BLOB_ALL_SIGNATURE_BLOB = 4,
D3D_BLOB_DEBUG_INFO = 5,
D3D_BLOB_LEGACY_SHADER = 6,
D3D_BLOB_XNA_PREPASS_SHADER = 7,
D3D_BLOB_XNA_SHADER = 8,
D3D_BLOB_PDB = 9,
D3D_BLOB_PRIVATE_DATA = 10,
D3D_BLOB_ROOT_SIGNATURE = 11,
D3D_BLOB_DEBUG_NAME = 12,
D3D_BLOB_TEST_ALTERNATE_SHADER = 32768,
D3D_BLOB_TEST_COMPILE_DETAILS = 32769,
D3D_BLOB_TEST_COMPILE_PERF = 32770,
D3D_BLOB_TEST_COMPILE_REPORT = 32771,
}
}
|
using Enemies;
using Helpers.Settings;
using UnityEngine;
namespace Helpers.StateMachine.States
{
public class Attack : IState
{
private readonly Enemy _enemy;
private readonly float _spawnRate;
/// <summary>
/// Mimics Enemy reaction time.
/// </summary>
private float firstTimeDelay = 0.5f;
private float timer = 0.3f;
public Attack(Enemy enemy)
{
_enemy = enemy;
_spawnRate = GameSettings.Get.EnemyConfig.SpawnRate;
}
public void OnEnter(){ }
public void OnExit() { }
/// <summary>
/// Shoots at player
/// </summary>
public void Tick()
{
_enemy.LookAt();
if (timer < _spawnRate + firstTimeDelay)
{
timer += Time.deltaTime;
return;
}
firstTimeDelay = 0;
timer = 0;
_enemy.SpawnProjectile();
}
}
} |
namespace Rotation
{
partial class Form1
{
/// <summary>
/// 必要なデザイナー変数です。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 使用中のリソースをすべてクリーンアップします。
/// </summary>
/// <param name="disposing">マネージ リソースを破棄する場合は true を指定し、その他の場合は false を指定します。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows フォーム デザイナーで生成されたコード
/// <summary>
/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
/// コード エディターで変更しないでください。
/// </summary>
private void InitializeComponent()
{
this.button_draw = new System.Windows.Forms.Button();
this.pictureBox_Source = new System.Windows.Forms.PictureBox();
this.textBox_angle = new System.Windows.Forms.TextBox();
this.textBox_loadfiepath = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.button_Save = new System.Windows.Forms.Button();
this.pictureBox_Dest = new System.Windows.Forms.PictureBox();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.textBox_OriginY = new System.Windows.Forms.TextBox();
this.textBox_OriginX = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.textBox_savefiepath = new System.Windows.Forms.TextBox();
this.panel_Dest = new System.Windows.Forms.Panel();
((System.ComponentModel.ISupportInitialize)(this.pictureBox_Source)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox_Dest)).BeginInit();
this.SuspendLayout();
//
// button_draw
//
this.button_draw.Location = new System.Drawing.Point(370, 39);
this.button_draw.Name = "button_draw";
this.button_draw.Size = new System.Drawing.Size(75, 21);
this.button_draw.TabIndex = 2;
this.button_draw.Text = "load";
this.button_draw.UseVisualStyleBackColor = true;
this.button_draw.Click += new System.EventHandler(this.button_ClickDraw);
//
// pictureBox_Source
//
this.pictureBox_Source.Location = new System.Drawing.Point(12, 63);
this.pictureBox_Source.Name = "pictureBox_Source";
this.pictureBox_Source.Size = new System.Drawing.Size(433, 402);
this.pictureBox_Source.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox_Source.TabIndex = 1;
this.pictureBox_Source.TabStop = false;
//
// textBox_angle
//
this.textBox_angle.Location = new System.Drawing.Point(767, 40);
this.textBox_angle.Name = "textBox_angle";
this.textBox_angle.Size = new System.Drawing.Size(46, 19);
this.textBox_angle.TabIndex = 11;
this.textBox_angle.Text = "0";
this.textBox_angle.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox_angle_KeyDown);
//
// textBox_loadfiepath
//
this.textBox_loadfiepath.Location = new System.Drawing.Point(114, 16);
this.textBox_loadfiepath.Name = "textBox_loadfiepath";
this.textBox_loadfiepath.Size = new System.Drawing.Size(331, 19);
this.textBox_loadfiepath.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(26, 19);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(82, 12);
this.label1.TabIndex = 0;
this.label1.Text = "読込ファイルパス";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(546, 43);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(36, 12);
this.label2.TabIndex = 6;
this.label2.Text = "原点X";
//
// button_Save
//
this.button_Save.Location = new System.Drawing.Point(819, 15);
this.button_Save.Name = "button_Save";
this.button_Save.Size = new System.Drawing.Size(75, 44);
this.button_Save.TabIndex = 5;
this.button_Save.Text = "save";
this.button_Save.UseVisualStyleBackColor = true;
this.button_Save.Click += new System.EventHandler(this.button_ClickSave);
//
// pictureBox_Dest
//
this.pictureBox_Dest.Location = new System.Drawing.Point(461, 63);
this.pictureBox_Dest.Name = "pictureBox_Dest";
this.pictureBox_Dest.Size = new System.Drawing.Size(433, 402);
this.pictureBox_Dest.TabIndex = 8;
this.pictureBox_Dest.TabStop = false;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(732, 43);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(29, 12);
this.label3.TabIndex = 10;
this.label3.Text = "角度";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(639, 43);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(36, 12);
this.label4.TabIndex = 8;
this.label4.Text = "原点Y";
//
// textBox_OriginY
//
this.textBox_OriginY.Location = new System.Drawing.Point(681, 40);
this.textBox_OriginY.Name = "textBox_OriginY";
this.textBox_OriginY.Size = new System.Drawing.Size(46, 19);
this.textBox_OriginY.TabIndex = 9;
this.textBox_OriginY.Text = "0";
this.textBox_OriginY.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox_OriginY_KeyDown);
//
// textBox_OriginX
//
this.textBox_OriginX.Location = new System.Drawing.Point(588, 40);
this.textBox_OriginX.Name = "textBox_OriginX";
this.textBox_OriginX.Size = new System.Drawing.Size(46, 19);
this.textBox_OriginX.TabIndex = 7;
this.textBox_OriginX.Text = "0";
this.textBox_OriginX.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox_OriginX_KeyDown);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(459, 19);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(82, 12);
this.label5.TabIndex = 3;
this.label5.Text = "保存ファイルパス";
//
// textBox_savefiepath
//
this.textBox_savefiepath.Location = new System.Drawing.Point(547, 16);
this.textBox_savefiepath.Name = "textBox_savefiepath";
this.textBox_savefiepath.Size = new System.Drawing.Size(266, 19);
this.textBox_savefiepath.TabIndex = 4;
//
// panel_Dest
//
this.panel_Dest.AutoScroll = true;
this.panel_Dest.Location = new System.Drawing.Point(12, 480);
this.panel_Dest.Name = "panel_Dest";
this.panel_Dest.Size = new System.Drawing.Size(433, 305);
this.panel_Dest.TabIndex = 12;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(910, 811);
this.Controls.Add(this.panel_Dest);
this.Controls.Add(this.label5);
this.Controls.Add(this.textBox_savefiepath);
this.Controls.Add(this.textBox_OriginX);
this.Controls.Add(this.label4);
this.Controls.Add(this.textBox_OriginY);
this.Controls.Add(this.label3);
this.Controls.Add(this.pictureBox_Dest);
this.Controls.Add(this.button_Save);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox_loadfiepath);
this.Controls.Add(this.textBox_angle);
this.Controls.Add(this.pictureBox_Source);
this.Controls.Add(this.button_draw);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.pictureBox_Source)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox_Dest)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button_draw;
private System.Windows.Forms.PictureBox pictureBox_Source;
private System.Windows.Forms.TextBox textBox_angle;
private System.Windows.Forms.TextBox textBox_loadfiepath;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button_Save;
private System.Windows.Forms.PictureBox pictureBox_Dest;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox textBox_OriginY;
private System.Windows.Forms.TextBox textBox_OriginX;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox textBox_savefiepath;
private System.Windows.Forms.Panel panel_Dest;
}
}
|
using System.Text;
using EventoCore.Domain;
using EventoCore.Extensions;
using EventoCore.Repositories;
using EventoInfrastructure.Mappers;
using EventoInfrastructure.Repositories;
using EventoInfrastructure.Services.Events;
using EventoInfrastructure.Services.Initializers;
using EventoInfrastructure.Services.Jwt;
using EventoInfrastructure.Services.Tickets;
using EventoInfrastructure.Services.Users;
using EventoInfrastructure.Settings;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using static EventoApi.Constants.Constants;
namespace EventoApi {
public class Startup {
/*------------------------ FIELDS REGION ------------------------*/
private readonly string _applicationUrl;
private readonly string _securityKey;
private readonly int _expiryTimeInMinutes;
public IConfiguration Configuration { get; }
/*------------------------ METHODS REGION ------------------------*/
public Startup(IConfiguration configuration) {
Configuration = configuration;
_securityKey = Configuration.GetValue<string>("JWT:SecurityKey");
_applicationUrl = Configuration.GetValue<string>("JWT:ApplicationUrl");
_expiryTimeInMinutes = Configuration.GetValue<int>("JWT:ExpiryTimeInMinutes");
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
SetupScopedServices(services);
SetupSingletonServices(services);
SetupAuthentication(services);
SetupOthers(services);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
SetupApplicationBuilder(app);
SeedData(app);
}
private void SetupScopedServices(IServiceCollection services) {
services.AddScoped<IEventRepository, InMemoryEventRepository>();
services.AddScoped<IUserRepository, InMemoryUserRepository>();
services.AddScoped<IEventService, EventService>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<ITicketService, TicketService>();
services.AddScoped<IDataInitializer, DataInitializer>();
}
private void SetupSingletonServices(IServiceCollection services) {
services.Configure<AppSettings>(Configuration.GetSection("App"));
services.AddSingleton(AutoMapperConfig.Initialize());
services.AddSingleton<IJwtService, JwtService>();
services.AddSingleton(new JwtSettings(_securityKey, _applicationUrl, _expiryTimeInMinutes));
// This is another approach when you cast automatically sub-object from appsettings.json
// services.Configure<JwtSettings>(Configuration.GetSection("JWT"));
}
private void SetupAuthentication(IServiceCollection services) {
services.AddAuthentication(option => {
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer((option) => {
option.TokenValidationParameters = new TokenValidationParameters {
ValidateAudience = false,
ValidIssuer = _applicationUrl,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_securityKey))
};
});
}
private void SetupOthers(IServiceCollection services) {
services.AddControllers();
services.AddAuthorization((option) => {
option.AddPolicy(
POLICY_HAS_ADMIN_ROLE,
(policy) => policy.RequireRole(UserRole.Admin.FromEnumToString())
);
});
services.AddMemoryCache();
}
private void SetupApplicationBuilder(IApplicationBuilder app) {
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
private void SeedData(IApplicationBuilder app) {
IOptions<AppSettings> appSettings = app.ApplicationServices
.GetService<IOptions<AppSettings>>();
if (appSettings.Value.SeedData) {
app.ApplicationServices
.GetService<IDataInitializer>()
.SeedDataAsync();
}
}
}
}
|
using System.Collections.Immutable;
using SleepingBearSystems.Tools.Common;
namespace SleepingBearSystems.CraftingTools.Domain.Test;
internal sealed class TestItemRepository : IItemRepository
{
public Maybe<Item> GetItemById(Guid id)
{
return TestItemRepository.Items.TryGetValue(id, out var item)
? item.ToMaybe()
: Maybe<Item>.None;
}
public ImmutableList<Item> GetItems()
{
return TestItemRepository.Items.Values.ToImmutableList();
}
private static readonly ImmutableDictionary<Guid, Item> Items = new[]
{
Item.FromParameters(new Guid(g: "5E1BDF20-E35D-4238-B453-F486F299054B"), name: "Flour").Unwrap(),
Item.FromParameters(new Guid(g: "24244AA3-409B-4C1F-842B-95C174518525"), name: "Sugar").Unwrap(),
Item.FromParameters(new Guid(g: "A552F0B7-8A74-45F8-81B5-0C1404D79F04"), name: "Salt").Unwrap(),
Item.FromParameters(new Guid(g: "A913792D-1428-478E-9BC2-B34120ADC192"), name: "Egg").Unwrap(),
Item.FromParameters(new Guid(g: "73541F4E-8E46-438D-85B8-28D5A1094B51"), name: "Water").Unwrap(),
Item.FromParameters(new Guid(g: "E3A93EAF-E4EA-488B-A177-3B1EA35F027C"), name: "Pepper").Unwrap(),
Item.FromParameters(new Guid(g: "5932A384-D670-412B-A86D-D059CEA26834"), name: "Garlic").Unwrap(),
Item.FromParameters(new Guid(g: "4EF846B3-A7BA-4250-9E0C-075A8EAF0E23"), name: "Thyme").Unwrap(),
Item.FromParameters(new Guid(g: "0F670E6C-A554-4F3E-A578-3B1E5A6186A6"), name: "Onion").Unwrap(),
Item.FromParameters(new Guid(g: "0F670E6C-A554-4F3E-A578-3B1E5A6186A6"), name: "Potato").Unwrap(),
Item.FromParameters(new Guid(g: "94082299-5761-44F2-9714-064F07026199"), name: "Milk").Unwrap(),
Item.FromParameters(new Guid(g: "D701D917-0133-4F82-A4F8-46752A0D0FE6"), name: "Apple").Unwrap(),
Item.FromParameters(new Guid(g: "FC440E16-A393-48F1-AC02-430F89673E8A"), name: "Lemon").Unwrap(),
Item.FromParameters(new Guid(g: "2551B773-BF7E-46F1-AA9D-5054ADBBDFC7"), name: "Tomato").Unwrap(),
Item.FromParameters(new Guid(g: "D67191AE-7EAA-4E2D-8CFE-517BDEC3C533"), name: "Cinnamon").Unwrap()
}.ToImmutableDictionary(i => i.Id, i => i);
}
|
using System.Collections.Generic;
using System.Linq;
namespace Domain.Interfaces
{
public static class CollectionExtensions
{
public static Dictionary<TKey, TValue> AsDictionary<TKey, TValue>(
this IReadOnlyDictionary<TKey, TValue> readOnlyDictionary)
{
return readOnlyDictionary
.ToDictionary(pair => pair.Key, pair => pair.Value);
}
public static IReadOnlyDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(
this IReadOnlyDictionary<TKey, TValue> readOnlyDictionary)
{
return readOnlyDictionary
.ToDictionary(pair => pair.Key, pair => pair.Value);
}
}
} |
namespace TemplateMethod
{
public class BeverageTestDrive
{
private static void Main()
{
var myTea = new Tea();
myTea.PrepareRecipe();
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public static class ExList
{
public static int IndexOf<T>(this IList<T> _array, T _value)
{
if (_array == null)
return -1;
for (int i = _array.Count - 1; i >= 0; i--)
{
if (Equals(_array[i], _value))
return i;
}
return -1;
}
public static int IndexOf<T>(this IList<T> _array, Func<T, bool> _value)
{
if (_array == null)
return -1;
for (int i = _array.Count - 1; i >= 0; i--)
{
if (_value(_array[i]))
return i;
}
return -1;
}
public static bool Contains<T>(this IList<T> _array, T _value)
{
return IndexOf(_array, _value) >= 0;
}
public static bool Contains<T>(this IList<T> _array, IList<T> _values)
{
for (int i = _values.Count - 1; i >= 0; i--)
{
if (IndexOf(_array, _values[i]) >= 0)
return true;
}
return false;
}
public static bool Contains<T>(this IList<T> _array, Func<T, bool> _value)
{
if (_array == null)
return false;
for (int i = _array.Count - 1; i >= 0; i--)
{
if (_value(_array[i]))
return true;
}
return false;
}
public static void AddOnce<T>(this IList<T> _list, T _value)
{
if (!_list.Contains(_value))
_list.Add(_value);
}
public static void AddOnce(this IList _list, object _value)
{
if (!_list.Contains(_value))
_list.Add(_value);
}
public static void AddNotNull(this IList _list, object _value)
{
if (_value != null)
_list.Add(_value);
}
public static void AddCast<T>(this IList<T> _list, object _value)
{
_list.Add((T)_value);
}
public static T[] Remove<T>(this T[] _array, T _value)
{
if (_array == null)
return null;
return RemoveAt(_array, _array.IndexOf(_value));
}
public static T[] RemoveAt<T>(this T[] _array, int _index )
{
if (_array == null || _index < 0)
return _array;
T[] result = new T[_array.Length - 1];
for (int i = 0; i < _index; i++) result[i] = _array[i];
for (int i = _index + 1; i < _array.Length; i++) result[i - 1] = _array[i];
return result;
}
public static T GetRandom<T>(this IList<T> _list, T _onEmpty = default(T))
{
if (_list == null || _list.Count == 0)
return _onEmpty;
var index = Random.Range(0, _list.Count);
return _list[index];
}
public static object GetRandom(this IList _list, object _onEmpty)
{
if (_list.Count == 0)
return _onEmpty;
var index = Random.Range(0, _list.Count);
return _list[index];
}
public static T GetOrInsert<T>(this IList<T> _list, int _index, T _def = default(T))
{
if ((uint)_index >= (uint)_list.Count)
_list.Insert(_index, _def);
return _list[_index];
}
public static T Get<T>(this IList<T> _list, int _index, T _def = default(T))
{
if (_list == null || (uint)_index >= (uint)_list.Count)
return _def;
return _list[_index];
}
public static T Get<T>(this T[,] _array, int _pos1, int _pos2, T _def = default(T))
{
if (_array != null && _array.IsInRange(_pos1, _pos2))
return _array[_pos1, _pos2];
return _def;
}
public static T GetClamped<T>(this IList<T> _list, int _index, T _def = default(T))
{
return Get(_list, Mathf.Clamp(_index, 0, _list.Count - 1), _def);
}
public static T Last<T>(this IList<T> _list, T _def = default(T))
{
return _list.Get(_list.Count - 1, _def);
}
public static T First<T>(this IList<T> _list, T _def = default(T))
{
return _list.Get(0, _def);
}
/// <summary>
/// Возвращает первое значение, отвечающее условию сортировки
/// </summary>
public static T First<T>(this IList<T> _list, Func<T, T, bool> _condition, T _default = default(T))
{
if (_list == null || _list.Count == 0)
return _default;
List<T> lst = new List<T>(_list);
lst.Sort((_x, _y) => _condition(_x, _y) ? -1 : 1);
return lst[0];
}
public static void Set<T>(this IList<T> _list, int _index, T _value)
{
if ((uint)_index >= (uint)_list.Count)
_list.Insert(_index, _value);
else
_list[_index] = _value;
}
public static void Replace<T>(this IList<T> _list, T _valueSource, T _valueNew)
{
int index = _list.IndexOf(_valueSource);
if (index >= 0)
_list[index] = _valueNew;
}
/// <summary>
/// Меняет два элемента из позициями в списке
/// </summary>
public static void Exchange<T>(this IList<T> _list, T _first, T _second)
{
if (_list == null)
return;
int index1 = _list.IndexOf(_first);
int index2 = _list.IndexOf(_second);
if (index1 < 0 || index2 < 0)
return;
_list[index1] = _second;
_list[index2] = _first;
}
/// <summary>
/// Меняет два элемента из позициями в списке
/// </summary>
public static void Exchange<T>(this IList<T> _list, int _index1, int _index2)
{
if (_list == null)
return;
if (_index1 < 0 || _index2 < 0)
return;
T e1 = _list[_index1];
_list[_index1] = _list[_index2];
_list[_index2] = e1;
}
/// <summary>
/// Перемешивает элементы списка в случайном порядке. Возвращает тот же список.
/// </summary>
public static IList<T> Shuffle<T>(this IList<T> _list)
{
List<T> tlist = new List<T>(_list);
_list.Clear();
while (tlist.Count > 0)
{
int pos = Random.Range(0, tlist.Count);
_list.Add(tlist[pos]);
tlist.RemoveAt(pos);
}
return _list;
}
public static int CountSafe(this IList _list)
{
return _list != null ? _list.Count : 0;
}
public static bool IsInRange(this IList _list, int _index)
{
return _list != null && ((uint)_index) < _list.Count;
}
public static bool IsInRange<T>(this T[,] _array, int _pos1, int _pos2)
{
return _array != null && ((uint)_pos1) < _array.GetLength(0) && ((uint)_pos2) < _array.GetLength(1);
}
public static TResult[] Select<TSource, TResult>(this IList<TSource> source, Func<TSource, TResult> selector)
{
TResult[] res = new TResult[source.Count];
for (int i = source.Count - 1; i >= 0; i--)
res[i] = selector(source[i]);
return res;
}
public static TSource Aggregate<TSource>(this IList<TSource> _source, Func<TSource, TSource, TSource> _func)
{
if (_source.Count == 0)
return default(TSource);
TSource source1 = _source[0];
for (int i = 1; i < _source.Count; i++)
source1 = _func(source1, _source[i]);
return source1;
}
/// <summary>
/// Выполнить функция с объектом. Просто для удобства - чтобы можно было в одну строчку всё вписать.
/// </summary>
public static TResult DoWith<TSource, TResult>(this TSource _source, Func<TSource, TResult> _operator)
{
return _operator(_source);
}
public static T GetPrev<T>(this IList<T> _list, T _current)
{
return _list.IndexOf(_current) < 1 ? _list.Last() : _list[_list.IndexOf(_current) - 1];
}
public static T GetNext<T>(this IList<T> _list, T _current)
{
int idx = _list.IndexOf(_current);
return (idx < 0 || idx == _list.Count - 1) ? _list.First() : _list[idx + 1];
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text.RegularExpressions;
using KeySkills.Core.Models;
namespace KeySkills.Crawler.Core.Services
{
/// <summary>
/// Implements <see cref="IKeywordsExtractor"/>
/// </summary>
public class KeywordsExtractor : IKeywordsExtractor
{
private readonly IEnumerable<(Keyword keyword, Regex regex)> _keywords;
/// <summary>
/// Initializes instance of keyword extractor
/// </summary>
/// <param name="keywords">Collection of the keywords to be extracted</param>
public KeywordsExtractor(IEnumerable<Keyword> keywords) =>
_keywords = keywords.Select(keyword => (
keyword,
new Regex(keyword.Pattern,
RegexOptions.Compiled | RegexOptions.IgnoreCase)
));
/// <inheritdoc/>
public IObservable<Keyword> Extract(Vacancy vacancy) =>
Observable.Return(String.Concat(vacancy.Title, " ", vacancy.Description))
.SelectMany(vacancyText =>
_keywords.ToObservable()
.Where(k => k.regex.IsMatch(vacancyText))
.Select(k => k.keyword));
}
} |
#region License
// Pomona is open source software released under the terms of the LICENSE specified in the
// project's repository, or alternatively at http://pomona.io/
#endregion
using System;
using System.Collections.Generic;
namespace Pomona.Common.TypeSystem
{
public class ComplexType : StructuredType
{
public ComplexType(IStructuredTypeResolver typeResolver,
Type type,
Func<IEnumerable<TypeSpec>> genericArguments = null)
: base(typeResolver, type, genericArguments)
{
}
}
} |
namespace MediatorPattern
{
public class Message2 : Message
{
public string NotSoSecretMessage { get; set; }
}
} |
using DeltaEngine.Content;
using DeltaEngine.Datatypes;
using DeltaEngine.Rendering3D.Particles;
namespace DeltaEngine.Editor.ContentManager.Previewers
{
public class ParticlePreviewer : ContentPreview
{
protected override void Init() {}
protected override void Preview(string contentName)
{
var particleEmitterData = ContentLoader.Load<ParticleEmitterData>(contentName);
currentDisplayParticle2D = new ParticleEmitter(particleEmitterData,
new Vector3D(0.5f, 0.5f, 0));
}
public ParticleEmitter currentDisplayParticle2D;
}
} |
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
Rigidbody2D rb;
Animator animator;
[Range(0, 5)]
public float speed = 2.5f;
[Range(0, 7)]
public float rotationSpeed = 5;
void Awake() {
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
animator.SetBool("accelerate", (vertical != 0));
transform.Rotate(Vector3.forward, horizontal * rotationSpeed * -1);
rb.AddRelativeForce(new Vector2(0, vertical * speed));
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
using VRStandardAssets.Utils;
public class LookManager : MonoBehaviour
{
public Canvas instructionCanvas;
public VRInteractiveItem rearView;
public VRInteractiveItem sideView;
public VRInteractiveItem blindspot;
public VideoPlayer player;
private float elapsedTime = 0;
private bool finished = false;
// Start is called before the first frame update
void Awake()
{
instructionCanvas.enabled = true;
rearView.enabled = false;
sideView.enabled = false;
blindspot.enabled = false;
}
// Update is called once per frame
void Update()
{
elapsedTime += Time.deltaTime;
if (elapsedTime > 23 && !finished)
{
player.Pause();
instructionCanvas.enabled = true;
rearView.enabled = true;
sideView.enabled = true;
blindspot.enabled = true;
}
if (!rearView.enabled && !sideView.enabled && !blindspot.enabled && elapsedTime > 23)
{
instructionCanvas.enabled = false;
finished = true;
player.Play();
}
}
void OnEnable()
{
rearView.OnOver += HideDotRear;
sideView.OnOver += HideDotSide;
blindspot.OnOver += HideDotBlind;
}
void HideDotRear()
{
rearView.enabled = false;
}
void HideDotSide()
{
sideView.enabled = false;
}
void HideDotBlind()
{
blindspot.enabled = false;
}
}
|
using System.Text.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Text;
namespace KyivSmartCityApi.Models
{
public class AddressPart
{
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonPropertyName("text")]
public string Text { get; set; }
}
} |
using System;
using Newtonsoft.Json;
using System.Xml.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// MybankCreditLoantradeLoanarQueryModel Data Structure.
/// </summary>
[Serializable]
public class MybankCreditLoantradeLoanarQueryModel : AlipayObject
{
/// <summary>
/// 客户的角色编号
/// </summary>
[JsonProperty("iproleid")]
[XmlElement("iproleid")]
public string Iproleid { get; set; }
/// <summary>
/// 合约编号
/// </summary>
[JsonProperty("loanarno")]
[XmlElement("loanarno")]
public string Loanarno { get; set; }
}
}
|
using tvn.cosine.ai.agent.api;
using tvn.cosine.ai.agent;
namespace tvn.cosine.ai.environment.map
{
/**
* Represents the environment a SimpleMapAgent can navigate.
*
* @author Ciaran O'Reilly
*
*/
public class MapEnvironment : EnvironmentBase
{
private Map map = null;
private MapEnvironmentState state = new MapEnvironmentState();
public MapEnvironment(Map map)
{
this.map = map;
}
public void addAgent(IAgent a, string startLocation)
{
// Ensure the agent state information is tracked before
// adding to super, as super will notify the registered
// EnvironmentViews that is was added.
state.setAgentLocationAndTravelDistance(a, startLocation, 0.0);
base.AddAgent(a);
}
public string getAgentLocation(IAgent a)
{
return state.getAgentLocation(a);
}
public double getAgentTravelDistance(IAgent a)
{
return state.getAgentTravelDistance(a);
}
public override void executeAction(IAgent agent, IAction a)
{
if (!a.IsNoOp())
{
MoveToAction act = (MoveToAction)a;
string currLoc = getAgentLocation(agent);
double? distance = map.getDistance(currLoc, act.getToLocation());
if (distance != null)
{
double currTD = getAgentTravelDistance(agent);
state.setAgentLocationAndTravelDistance(agent,
act.getToLocation(), currTD + distance.Value);
}
}
}
public override IPercept getPerceptSeenBy(IAgent anAgent)
{
return new DynamicPercept(DynAttributeNames.PERCEPT_IN, getAgentLocation(anAgent));
}
public Map getMap()
{
return map;
}
}
}
|
@model bool?
@{
var status = Model.HasValue && Model.Value ? "CoAuthor" : "Author";
}
@status
|
using System.Globalization;
namespace Majorsoft.Blazor.Components.Maps
{
/// <summary>
/// Represents a Geolocation Coordinate.
/// </summary>
public class GeolocationCoordinate
{
/// <summary>
/// Representing the latitude of the position in decimal degrees.
/// </summary>
public double? Latitude { get; init; }
/// <summary>
/// Represents the longitude of a geographical position, specified in decimal degrees.
/// </summary>
public double? Longitude { get; init; }
/// <summary>
/// Checks to <see cref="Latitude"/> and <see cref="Longitude"/> are defined.
/// </summary>
public bool HasCoordinates => Latitude.HasValue && Longitude.HasValue;
public GeolocationCoordinate(double? latitude, double? longitude)
{
Latitude = latitude;
Longitude = longitude;
}
/// <summary>
/// Formats coordinates to Maps specific string or return Empty.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return HasCoordinates
? $"{Latitude.Value.ToString(CultureInfo.InvariantCulture)},{Longitude.Value.ToString(CultureInfo.InvariantCulture)}"
: string.Empty;
}
}
} |
namespace Bakery.Areas.Task.Models
{
public class OrganizeViewModel
{
public decimal TottalPrice { get; set; }
public DateTime DayOfOrder { get; set; }
public DateTime? FromDate { get; set; }
public DateTime? ToDate { get; set; }
public string ColapsValue { get; set; }
public Dictionary<string, Dictionary<decimal, int>> Items { get; set; } =
new Dictionary<string, Dictionary<decimal, int>>();
}
}
|
using System;
using System.Collections.Generic;
namespace EasyGelf.Core
{
public sealed class GelfMessageBuilder
{
private readonly Dictionary<string, object> additionalFields = new Dictionary<string, object>();
private readonly string message;
private readonly string host;
private readonly DateTime timestamp;
private readonly GelfLevel level;
public GelfMessageBuilder(string message, string host, DateTime timestamp, GelfLevel level)
{
this.message = message;
this.host = host;
this.timestamp = timestamp;
this.level = level;
}
public GelfMessageBuilder SetAdditionalField(string key, object value)
{
if (string.IsNullOrEmpty(key))
return this;
if (value == null)
return this;
additionalFields.Add(key, value);
return this;
}
public GelfMessage ToMessage()
{
return new GelfMessage
{
Host = host,
FullMessage = message,
ShortMessage = message.Truncate(200),
Level = level,
Timestamp = timestamp,
AdditionalFields = additionalFields
};
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Principio_LSP_Aderente
{
class ContaComum : Conta
{
public override double Saldo { get; set ; }
public void Saque(double valor)
{
Saldo -= valor;
}
}
}
|
using Carupano;
using Carupano.Configuration;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text;
namespace CarupanoAir.Passenger.Projections
{
public class Startup
{
IConfiguration Config;
public Startup()
{
var cfg = new ConfigurationBuilder();
cfg.AddInMemoryCollection(new Dictionary<string, string> {
{ "Mongo", "mongodb://localhost/passengers" },
{ "SqlServer", "data source=.\\sqlexpress;initial catalog=CarupanoAir;trusted_connection=true" }
});
Config = cfg.Build();
}
public void Configure(BoundedContextModelBuilder builder)
{
var mongo = Config["Mongo"];
var sql = Config["SqlServer"];
builder.WithSqlServerEventStore(sql);
builder.Projection(
svcs=>new PassengerList(mongo),
cfg =>
{
cfg
.WithMongoState(mongo)
.SubscribesTo<Events.PassengerCreated>(c => c.On)
.RespondsTo<Queries.FindPassengerByEmail>();
});
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
namespace PJ
{
public static class Utils
{
public static bool CompareEqual(float a, float b, float epsilon = .001f)
{
return Mathf.Abs(Mathf.Abs(a) - Mathf.Abs(b)) < epsilon;
}
}
public static class EditorUtils
{
public enum RenderState
{
Default,
Selected
}
// FUTURE: support this (but Unity can't fill circles)
public enum ShapeStyle
{
Outline,
OutlineAndArea
}
public static void RenderLinesBetweenObjects(List<GameObject> objects, RenderState renderState)
{
if (objects.Count == 0) { return; }
bool hasFirstPosition = false;
Vector3 prevPosition = new Vector3();
Vector3 positionStart, positionEnd;
foreach (GameObject go in objects)
{
Vector3 position = go.transform.position;
positionStart = prevPosition;
positionEnd = position;
if (hasFirstPosition)
{
switch (renderState)
{
case EditorUtils.RenderState.Default:
Gizmos.color = Color.white;
break;
case EditorUtils.RenderState.Selected:
Gizmos.color = GUI.skin.settings.selectionColor;
break;
}
Gizmos.DrawLine(positionStart, positionEnd);
}
hasFirstPosition = true;
prevPosition = position;
}
}
public static void RenderCircleGizmo(Vector3 center, float radius, RenderState renderState)
{
switch (renderState)
{
case RenderState.Default:
Gizmos.color = Color.white;
break;
case RenderState.Selected:
Gizmos.color = GUI.skin.settings.selectionColor;
break;
}
float theta = 0.0f;
float x = radius * Mathf.Cos(theta);
float y = radius * Mathf.Sin(theta);
Vector3 pos = center + new Vector3(x, y, 0);
Vector3 newPos = pos;
Vector3 lastPos = pos;
for (theta = 0.1f; theta < Mathf.PI * 2; theta += 0.1f)
{
x = radius * Mathf.Cos(theta);
y = radius * Mathf.Sin(theta);
newPos = center + new Vector3(x, y, 0);
Gizmos.DrawLine(pos, newPos);
pos = newPos;
}
Gizmos.DrawLine(pos, lastPos);
}
public static void RenderRectGizmo(Vector3 center, float width, float height, RenderState renderState)
{
switch (renderState)
{
case RenderState.Default:
Gizmos.color = Color.white;
break;
case RenderState.Selected:
Gizmos.color = GUI.skin.settings.selectionColor;
break;
}
float halfWidth = width / 2.0f;
float halfHeight = height / 2.0f;
Vector3 topLeft = new Vector3(center.x - halfWidth, center.y - halfHeight, 0);
Vector3 topRight = new Vector3(center.x + halfWidth, center.y - halfHeight, 0);
Vector3 bottomRight = new Vector3(center.x + halfWidth, center.y + halfHeight, 0);
Vector3 bottomLeft = new Vector3(center.x - halfWidth, center.y + halfHeight, 0);
Gizmos.DrawLine(topLeft, topRight);
Gizmos.DrawLine(topRight, bottomRight);
Gizmos.DrawLine(bottomRight, bottomLeft);
Gizmos.DrawLine(bottomLeft, topLeft);
}
}
}
|
// Colorado (c) 2015 Baltasar MIT License <baltasarq@gmail.com>
namespace Colorado.Core {
using System.Collections.ObjectModel;
public class Delimiter {
public const string TabDelimiterName = "<TAB>";
public const char CommaDelimiter = ',';
public const char SemicolonDelimiter = ';';
public const char ColonDelimiter = ':';
public const char TabDelimiter = '\t';
public static readonly ReadOnlyCollection<char> PredefinedDelimiters =
new ReadOnlyCollection<char>(
new char[]{ TabDelimiter, ColonDelimiter, SemicolonDelimiter, CommaDelimiter }
);
public static readonly ReadOnlyCollection<string> PredefinedDelimiterNames =
new ReadOnlyCollection<string>(
new string[]{ TabDelimiterName,
ColonDelimiter.ToString(),
SemicolonDelimiter.ToString(),
CommaDelimiter.ToString() }
);
/// <summary>
/// Initializes a new instance of the <see cref="Colorado.Core.Delimiter"/> class.
/// </summary>
/// <param name="c">The delimiter to use, as char.</param>
public Delimiter(char c = CommaDelimiter)
: this( c.ToString() )
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Colorado.Core.Delimiter"/> class.
/// </summary>
/// <param name="d">The delimiter to use, as a string (can be special).</param>
public Delimiter(string d)
{
this.Name = d;
}
/// <summary>
/// Gets or sets the name of the char used as delimiter.
/// Most delimiters are used by themselves, except tabs.
/// </summary>
/// <value>The name.</value>
/// <seealso cref="TabDelimiterName"/>
public string Name {
get {
return GetName( this.Raw );
}
set {
if ( !string.IsNullOrEmpty( value ) ) {
if ( value == TabDelimiterName ) {
value = "\t";
}
this.Raw = value[ 0 ];
}
return;
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current
/// <see cref="Colorado.Core.Delimiter"/>.
/// </summary>
/// <returns>A <see cref="System.String"/>
/// that represents the current <see cref="Colorado.Core.Delimiter"/>.</returns>
public override string ToString()
{
return Raw.ToString();
}
/// <summary>
/// Gets the raw char used as delimiter
/// </summary>
/// <value>The raw.</value>
public char Raw {
get; private set;
}
/// <summary>
/// Gets the name of a given delimiter.
/// </summary>
/// <returns>The name.</returns>
/// <param name="delimiter">Delimiter.</param>
public static string GetName(string delimiter)
{
var toret = TabDelimiterName;
if ( !string.IsNullOrWhiteSpace( delimiter ) ) {
if ( delimiter == TabDelimiterName) {
toret = TabDelimiter.ToString();
} else {
toret = GetName( delimiter[ 0 ] );
}
}
return toret;
}
public static string GetName(char delimiter)
{
var toret = delimiter.ToString();
if ( toret == TabDelimiter.ToString() ) {
toret = TabDelimiterName;
}
return toret;
}
}
}
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
namespace Convience.ManagentApi.Infrastructure.Authorization
{
public static class PermissionAuthorizationExtension
{
public static IServiceCollection AddPermissionAuthorization(this IServiceCollection services)
{
services.AddScoped<IAuthorizationHandler, PermissionAuthorizationHandler>();
return services;
}
}
}
|
using System.Diagnostics;
namespace LittleWeebLibrary
{
public class LittleWeeb
{
private readonly StartUp startUp;
public LittleWeeb()
{
startUp = new StartUp();
Debug.WriteLine("Starting littleweeb");
startUp.Start();
}
public void Stop()
{
startUp.Stop();
}
}
}
|
using Draven.ServerModels;
using Draven.Structures;
using RtmpSharp.Messaging;
using RtmpSharp.Net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace Draven.Messages.LoginService
{
using Draven.DatabaseManager;
using Draven.Structures.Platform.Account;
using Draven.Structures.Platform.Login;
class Login : IMessage
{
public RemotingMessageReceivedEventArgs HandleMessage(object sender, RemotingMessageReceivedEventArgs e)
{
object[] body = e.Body as object[];
AuthenticationCredentials creds = body[0] as AuthenticationCredentials;
//Console.WriteLine("Login von: " + creds.Username + " : " + creds.Password);
RtmpClient client = sender as RtmpClient;
SummonerClient newClient = new SummonerClient(client, creds.Username);
Dictionary<string, string> Data = DatabaseManager.getAccountData(creds.Username, creds.Password);
Dictionary<string, string> SummonerData = DatabaseManager.getSummonerData(Data["summonerId"]);
Session session = new Session
{
Password = creds.Password,
Summary = new AccountSummary
{
AccountId = Convert.ToDouble(Data["id"]),
Username = creds.Username,
HasBetaAccess = true,
IsAdministrator = true,
PartnerMode = true,
NeedsPasswordReset = false
},
Token = creds.AuthToken
};
newClient.setSession(session);
newClient._accId = Convert.ToDouble(Data["id"]);
newClient._sumId = Convert.ToDouble(SummonerData["id"]);
newClient._summonername = SummonerData["summonerName"];
newClient._sumIcon = Convert.ToDouble(SummonerData["icon"]);
newClient._IP = Convert.ToDouble(Data["IP"]);
newClient._RP = Convert.ToDouble(Data["RP"]);
e.ReturnRequired = true;
e.Data = session;
return e;
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Search.Fluent.SearchService.Definition
{
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Search.Fluent;
using Microsoft.Azure.Management.Search.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.GroupableResource.Definition;
public interface IWithReplicasAndCreate :
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithCreate
{
/// <summary>
/// Specifies the SKU of the Search service.
/// </summary>
/// <param name="count">The number of replicas to be created.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithCreate WithReplicaCount(int count);
}
/// <summary>
/// The stage of the definition which contains all the minimum required inputs for the resource to be created
/// (via WithCreate.create()), but also allows for any other optional settings to be specified.
/// </summary>
public interface IWithCreate :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.ICreatable<Microsoft.Azure.Management.Search.Fluent.ISearchService>,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithTags<Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithCreate>
{
}
/// <summary>
/// The stage of the Search service definition allowing to specify the SKU.
/// </summary>
public interface IWithSku
{
/// <summary>
/// Specifies the SKU of the Search service.
/// </summary>
/// <param name="skuName">The SKU.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithCreate WithSku(SkuName skuName);
/// <summary>
/// Specifies to use a basic SKU type for the Search service.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithReplicasAndCreate WithBasicSku();
/// <summary>
/// Specifies to use a free SKU type for the Search service.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithCreate WithFreeSku();
/// <summary>
/// Specifies to use a standard SKU type for the Search service.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithPartitionsAndCreate WithStandardSku();
}
/// <summary>
/// The first stage of the Search service definition.
/// </summary>
public interface IBlank :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithRegion<Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithGroup>
{
}
/// <summary>
/// The entirety of the Search service definition.
/// </summary>
public interface IDefinition :
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IBlank,
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithGroup,
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithSku,
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithPartitionsAndCreate,
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithReplicasAndCreate,
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithCreate
{
}
public interface IWithPartitionsAndCreate :
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithReplicasAndCreate
{
/// <summary>
/// Specifies the SKU of the Search service.
/// </summary>
/// <param name="count">The number of partitions to be created.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithReplicasAndCreate WithPartitionCount(int count);
}
/// <summary>
/// The stage of the Search service definition allowing to specify the resource group.
/// </summary>
public interface IWithGroup :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.GroupableResource.Definition.IWithGroup<Microsoft.Azure.Management.Search.Fluent.SearchService.Definition.IWithSku>
{
}
} |
using SimpleMvvmWpfLib;
using SimpleMvvmWpfLib.Commands;
using SimpleMvvmWpfLib.WindowEvents;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestApp
{
public class MainWindowViewModel : BaseViewModel
{
public MainWindowViewModel()
{
}
public ObservableCollection<ListItemViewModel> ListItems { get; private set; } =
new ObservableCollection<ListItemViewModel>();
private DelegateLoadedAction _testLoadedAction = null;
public DelegateLoadedAction TestLoadedAction
{
get
{
return _testLoadedAction ??
(_testLoadedAction = new DelegateLoadedAction(
async () =>
{
/// test async op
await Task.Delay(2500);
TestLabel = "Finished loading";
LoadListItems();
}));
}
}
private string _testLabel = "not loaded yet";
public string TestLabel
{
get => _testLabel;
set => SetPropVal<string>(ref _testLabel, value);
}
private bool _canWeClose = false;
public bool CanWeClose
{
get => _canWeClose;
set => SetPropVal<bool>(ref _canWeClose, value);
}
private string _selectionText = null;
public string SelectionText
{
get => _selectionText;
set => SetPropVal<string>(ref _selectionText, value);
}
private ListItemViewModel _selectedListItem = null;
public ListItemViewModel SelectedListItem
{
get => _selectedListItem;
set
{
if (SetPropVal<ListItemViewModel>(ref _selectedListItem, value))
{
if (_selectedListItem == null)
{
SelectionText = "nothing selected";
}
else
{
SelectionText = $"{_selectedListItem.Label} -> {_selectedListItem.IsChecked}";
}
CommandClearSelectionParameter.RaiseCanExecuteChanged();
}
}
}
private CanCloseResult _canCloseParameter = new CanCloseResult { Cancel = false };
public CanCloseResult CanCloseParameter
{
get => _canCloseParameter;
set => SetPropVal<CanCloseResult>(ref _canCloseParameter, value);
}
private DelegateCanCloseCheck _testCanCloseCheck = null;
public DelegateCanCloseCheck TestCanCloseCheck
{
get
{
return _testCanCloseCheck ??
(_testCanCloseCheck = new DelegateCanCloseCheck(
result => result.Cancel = !CanWeClose));
}
}
private void LoadListItems()
{
ListItems.Clear();
for (int i = 0; i < 15; i++)
{
var item = new ListItemViewModel()
{
IsChecked = (i % 2 == 0),
Label = $"My Item {i}",
};
ListItems.Add(item);
}
}
private ActionCommand _commandClearSelection = null;
public ActionCommand CommandClearSelection
{
get
{
return _commandClearSelection ??
(_commandClearSelection = new ActionCommand(() => SelectedListItem = null));
}
}
private ActionCommand<ListItemViewModel> _commandClearSelectionParameter = null;
public ActionCommand<ListItemViewModel> CommandClearSelectionParameter
{
get
{
return _commandClearSelectionParameter ??
(_commandClearSelectionParameter = new ActionCommand<ListItemViewModel>(
(p) =>
{
SelectedListItem = null;
},
(p) =>
{
return (SelectedListItem != null);
}));
}
}
}
}
|
using System.Collections.Generic;
namespace MLSoftware.OTA
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "4.2.0.31")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.opentravel.org/OTA/2003/05")]
public partial class PTCFareBreakdownType
{
private PassengerTypeQuantityType _passengerTypeQuantity;
private List<FareBasisCodeType> _fareBasisCodes;
private List<PTCFareBreakdownTypePassengerFare> _passengerFare;
private List<PTCFareBreakdownTypeTravelerRefNumber> _travelerRefNumber;
private List<PTCFareBreakdownTypeTicketDesignator> _ticketDesignators;
private PTCFareBreakdownTypeEndorsements _endorsements;
private List<PTCFareBreakdownTypeFareInfo> _fareInfo;
private List<PTCFareBreakdownTypePricingUnit> _pricingUnit;
private PricingSourceType _pricingSource;
private List<string> _flightRefNumberRPHList;
public PTCFareBreakdownType()
{
this._flightRefNumberRPHList = new List<string>();
this._pricingUnit = new List<PTCFareBreakdownTypePricingUnit>();
this._fareInfo = new List<PTCFareBreakdownTypeFareInfo>();
this._endorsements = new PTCFareBreakdownTypeEndorsements();
this._ticketDesignators = new List<PTCFareBreakdownTypeTicketDesignator>();
this._travelerRefNumber = new List<PTCFareBreakdownTypeTravelerRefNumber>();
this._passengerFare = new List<PTCFareBreakdownTypePassengerFare>();
this._fareBasisCodes = new List<FareBasisCodeType>();
this._passengerTypeQuantity = new PassengerTypeQuantityType();
}
public PassengerTypeQuantityType PassengerTypeQuantity
{
get
{
return this._passengerTypeQuantity;
}
set
{
this._passengerTypeQuantity = value;
}
}
[System.Xml.Serialization.XmlArrayItemAttribute("FareBasisCode", IsNullable=false)]
public List<FareBasisCodeType> FareBasisCodes
{
get
{
return this._fareBasisCodes;
}
set
{
this._fareBasisCodes = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("PassengerFare")]
public List<PTCFareBreakdownTypePassengerFare> PassengerFare
{
get
{
return this._passengerFare;
}
set
{
this._passengerFare = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("TravelerRefNumber")]
public List<PTCFareBreakdownTypeTravelerRefNumber> TravelerRefNumber
{
get
{
return this._travelerRefNumber;
}
set
{
this._travelerRefNumber = value;
}
}
[System.Xml.Serialization.XmlArrayItemAttribute("TicketDesignator", IsNullable=false)]
public List<PTCFareBreakdownTypeTicketDesignator> TicketDesignators
{
get
{
return this._ticketDesignators;
}
set
{
this._ticketDesignators = value;
}
}
public PTCFareBreakdownTypeEndorsements Endorsements
{
get
{
return this._endorsements;
}
set
{
this._endorsements = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("FareInfo")]
public List<PTCFareBreakdownTypeFareInfo> FareInfo
{
get
{
return this._fareInfo;
}
set
{
this._fareInfo = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("PricingUnit")]
public List<PTCFareBreakdownTypePricingUnit> PricingUnit
{
get
{
return this._pricingUnit;
}
set
{
this._pricingUnit = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public PricingSourceType PricingSource
{
get
{
return this._pricingSource;
}
set
{
this._pricingSource = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public List<string> FlightRefNumberRPHList
{
get
{
return this._flightRefNumberRPHList;
}
set
{
this._flightRefNumberRPHList = value;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Wartorn.ScreenManager;
using Wartorn.Drawing.Animation;
using Wartorn.Utility;
using Wartorn.GameData;
using Wartorn;
using Wartorn.Drawing;
using Wartorn.PathFinding.Dijkstras;
using Wartorn.PathFinding;
using Wartorn.UIClass;
using Wartorn.SpriteRectangle;
namespace Wartorn.Drawing
{
class MovingUnitAnimation
{
public bool IsArrived
{
get
{
return isArrived;
}
}
Unit movingUnit = null;
List<Point> movementPath = null;
Point movingUnitPosition;
int currentdest = 0;
bool isArrived = false;
float totalElapsedTime = 0;
float delay = 25; //ms
public MovingUnitAnimation(Unit unit,List<Point> movementPath,Point startingPoint)
{
movingUnit = UnitCreationHelper.Instantiate(unit.UnitType, unit.Owner);
movingUnit.Animation.Depth = LayerDepth.Unit + 0.001f;
this.movementPath = movementPath;
movingUnitPosition = startingPoint;
}
public void Update(GameTime gameTime)
{
totalElapsedTime += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
AnimationName anim = movingUnit.Animation.CurntAnimationName.ToEnum<AnimationName>();
bool isLeft = movingUnit.Animation.FlipEffect == SpriteEffects.FlipHorizontally ? true : false;
if (totalElapsedTime >= delay)
{
if (currentdest < movementPath.Count)
{
int currentdestX = movementPath[currentdest].X * Constants.MapCellWidth;
int currentdestY = movementPath[currentdest].Y * Constants.MapCellHeight;
if (movingUnitPosition.X < currentdestX)
{
//to the right
anim = AnimationName.right;
movingUnitPosition.X += 12;
}
else
{
if (movingUnitPosition.X > currentdestX)
{
//to the left
anim = AnimationName.right;
movingUnitPosition.X -= 12;
isLeft = true;
}
}
if (movingUnitPosition.Y < currentdestY)
{
//down
movingUnitPosition.Y += 12;
anim = AnimationName.down;
}
else
{
if (movingUnitPosition.Y > currentdestY)
{
//up
movingUnitPosition.Y -= 12;
anim = AnimationName.up;
}
}
if (movingUnitPosition.X == currentdestX
&& movingUnitPosition.Y == currentdestY)
{
currentdest++;
}
}
else
{
isArrived = true;
currentdest = 0;
}
totalElapsedTime -= totalElapsedTime;
}
movingUnit.Animation.PlayAnimation(anim.ToString());
movingUnit.Animation.FlipEffect = isLeft ? SpriteEffects.FlipHorizontally : SpriteEffects.None;
movingUnit.Animation.Update(gameTime);
}
public void Draw(SpriteBatch spriteBatch,GameTime gameTime)
{
movingUnit.Animation.Position = movingUnitPosition.ToVector2();
movingUnit.Animation.Draw(gameTime, CONTENT_MANAGER.spriteBatch);
}
}
}
|
using System;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using TellagoStudios.Hermes.Business.Model;
using TellagoStudios.Hermes.Business.Data.Queries;
using TellagoStudios.Hermes.DataAccess.MongoDB;
namespace TellagoStudios.Hermes.DataAccess.MongoDB.Queries
{
public class ExistGroupByGroupName : MongoDbRepository, IExistsGroupByGroupName
{
public ExistGroupByGroupName(string connectionString)
: base(connectionString)
{}
public bool Execute(string groupName, Identity? excludeId = null)
{
var query = QueryDuplicatedName(groupName, excludeId);
return DB.GetCollection(MongoDbConstants.Collections.Groups).Exists(query);
}
public IMongoQuery QueryDuplicatedName(string groupName, Identity? excludeId = null)
{
return excludeId.HasValue ?
Query.And(Query.EQ("Name", BsonString.Create(groupName)), Query.NE("_id", excludeId.Value.ToBson())) :
Query.EQ("Name", BsonString.Create(groupName));
}
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using DroidExplorer.Core.Configuration.Handlers;
using Newtonsoft.Json;
using Camalot.Common.Extensions;
using Camalot.Common.Serialization;
namespace DroidExplorer.Core.Net {
public class VersionCheckService {
public delegate void AsyncVersionCheck ( SoftwareRelease release );
private VersionCheckService ( ) {
var config = (CloudConfiguration)ConfigurationManager.GetSection ( "droidexplorer/cloud" );
HostUrl = new UriBuilder ( "http", config.Host, config.Port, config.Path ).Uri.ToString ( );
}
private String HostUrl { get; set; }
private static VersionCheckService _instance = null;
public static VersionCheckService Instance {
get { return _instance ?? (_instance = new VersionCheckService ( )); }
}
public SoftwareRelease GetLatestVersion ( ) {
try {
var req = HttpWebRequest.Create ( HostUrl + "update/latest/" ) as HttpWebRequest;
var resp = req.GetResponse ( ) as HttpWebResponse;
using ( var sr = new StreamReader ( resp.GetResponseStream ( ) ) ) {
using ( var jr = new JsonTextReader ( sr ) ) {
var serializer = JsonSerializationBuilder.Build().Create();
return serializer.Deserialize<SoftwareRelease> ( jr );
}
}
} catch ( Exception ex ) {
this.LogWarn ( ex.Message, ex );
return new SoftwareRelease {
ID = 0,
Description = "N/A",
Name = "N/A",
TimeStamp = DateTime.UtcNow,
Version = new Version ( 0, 0, 0, 0 )
};
}
}
public void BeginGetLatestVersion ( AsyncVersionCheck callback ) {
try {
var req = HttpWebRequest.Create ( HostUrl + "update/latest/" ) as HttpWebRequest;
req.Timeout = 15 * 1000;
req.BeginGetResponse(delegate ( IAsyncResult result ) {
try {
var resp = ( result.AsyncState as HttpWebRequest ).EndGetResponse ( result ) as HttpWebResponse;
using ( var sr = new StreamReader ( resp.GetResponseStream ( ) ) ) {
using ( var jr = new JsonTextReader ( sr ) ) {
var serializer = JsonSerializationBuilder.Build().Create();
var version = serializer.Deserialize<SoftwareRelease>(jr);
if ( callback != null ) {
callback ( version );
}
}
}
} catch ( Exception e ) {
this.LogWarn ( e.Message, e );
}
}, req );
} catch ( Exception ex ) {
this.LogWarn ( ex.Message, ex );
}
}
public Version GetVersion ( Type type ) {
return type.Assembly.GetName ( ).Version;
}
public Version GetVersion ( ) {
return this.GetVersion ( this.GetType ( ) );
}
}
}
|
using NaughtyAttributes;
using UnityEngine;
namespace GameplayIngredients.Events
{
public class OnTriggerEvent : EventBase
{
[ReorderableList]
public Callable[] onTriggerEnter;
[ReorderableList]
public Callable[] onTriggerExit;
public bool OnlyInteractWithTag = true;
[EnableIf("OnlyInteractWithTag")]
public string Tag = "Player";
private void OnTriggerEnter(Collider other)
{
if (OnlyInteractWithTag && other.tag == Tag )
{
Callable.Call(onTriggerEnter, other.gameObject);
}
if (!OnlyInteractWithTag)
{
Callable.Call(onTriggerEnter, other.gameObject);
}
}
private void OnTriggerExit(Collider other)
{
if (OnlyInteractWithTag && other.tag == Tag )
{
Callable.Call(onTriggerExit, other.gameObject);
}
if (!OnlyInteractWithTag)
{
Callable.Call(onTriggerExit, other.gameObject);
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace Rhit.Applications.Model.Events {
public delegate void SearchEventHandler(Object sender, SearchEventArgs e);
public class SearchEventArgs : ServiceEventArgs {
public List<RhitLocation> Places { get; set; }
}
}
|
using System.Windows.Forms;
using System.Drawing;
namespace ProSnap
{
/// <summary>
/// http://stackoverflow.com/a/442828/1569
/// </summary>
public class ListView : System.Windows.Forms.ListView
{
public ListView()
{
//Activate double buffering
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
//Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
}
protected override void OnNotifyMessage(Message m)
{
//Filter out the WM_ERASEBKGND message
if (m.Msg != 0x14)
{
base.OnNotifyMessage(m);
}
}
protected override void WndProc(ref Message m)
{
//Suppress mouse messages that are OUTSIDE of the items area
//http://stackoverflow.com/a/7138106/1569
if (m.Msg >= 0x201 && m.Msg <= 0x209)
{
Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);
var hit = this.HitTest(pos);
switch (hit.Location)
{
case ListViewHitTestLocations.AboveClientArea:
case ListViewHitTestLocations.BelowClientArea:
case ListViewHitTestLocations.LeftOfClientArea:
case ListViewHitTestLocations.RightOfClientArea:
case ListViewHitTestLocations.None:
return;
}
}
base.WndProc(ref m);
}
}
}
|
using System;
using Knet.Kudu.Client.Util;
using Xunit;
namespace Knet.Kudu.Client.Tests;
public class DecimalUtilTests
{
[Theory]
[InlineData(6023345402697246, 15782978151453050464, 10)] // 11111111111111111111111111.11111
[InlineData(-6023345402697247, 2663765922256501152, 10)] //-11111111111111111111111111.11111
[InlineData(667386670618854951, 11070687437558349184, 35)] // 123.1111111111111111111111111111
[InlineData(-667386670618854952, 7376056636151202432, 35)] //-123.1111111111111111111111111111
public void KuduDecimalTooLarge(long high, ulong low, int scale)
{
var value = new KuduInt128(high, low);
Assert.Throws<OverflowException>(
() => DecimalUtil.DecodeDecimal128(value, scale));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using Universe.YetAnotherComparerBuilder.Tests;
namespace Universe.YetAnotherComparerBuilder.Benchmark
{
[MemoryDiagnoser]
public class SortingBenchmark
{
private PersonClass[] Persons;
private static readonly IComparer<PersonClass> YAC_Comparer = PersonComparers.GetDemoComparer("Dr", 42);
private static readonly IComparer<PersonClass> Manual_Comparer = PersonComparers.ManualPersonClassComparer;
[GlobalSetup]
public void Setup()
{
Persons = PersonsGenerator.Generate(666).ToArray();
}
[Benchmark]
public void YAC_Sort()
{
var length = Persons.Length;
var copy = new PersonClass[length];
for (int i = 0; i < length; i++) copy[i] = Persons[i];
Array.Sort(copy, YAC_Comparer);
}
[Benchmark]
public void Manual_Sort()
{
var length = Persons.Length;
var copy = new PersonClass[length];
for (int i = 0; i < length; i++) copy[i] = Persons[i];
Array.Sort(copy, Manual_Comparer);
}
[Benchmark]
public int Linq_OrderBy()
{
var copy = Persons.Order().ToArray();
return copy.Length;
}
}
} |
using MedicalAppointment.Core.DTOs.Gender;
using MedicalAppointment.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace MedicalAppointment.Core.Services
{
public class GenderPatientReportService
{
private readonly IGenderService _genderService;
public GenderPatientReportService(IGenderService genderService)
{
_genderService = genderService;
}
public async Task<GenderReportDto> CreateAsync()
{
return new GenderReportDto()
{
MaleNumber = await _genderService.GetMalePatientNumberAsync(),
MalePercent = await _genderService.GetPercentOfMalePatientGenderAsync(),
FemaleNumber = await _genderService.GetFemalePatientNumberAsync(),
FemalePercent = await _genderService.GetPercentOfFemalePatientGenderAsync()
};
}
}
}
|
using Windows.UI.Xaml.Controls;
namespace TeamVault.Pages
{
public sealed partial class SignIn : Page
{
public SignIn()
{
this.InitializeComponent();
}
}
}
|
using System;
using Xunity.ScriptableVariables;
namespace Xunity.ScriptableReferences
{
[Serializable]
public class IntReference : VariableReference<IntVariable, int, IntReference> { }
} |
using System;
using System.Linq;
using System.Threading.Tasks;
using API.Application;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace API.Controllers
{
[Route("/api/sse")]
public class ServerSentEventController : Controller
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ServerSentEventController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
[HttpGet]
public async Task<IActionResult> RegisterChannel([FromQuery]Guid channelId)
{
var response = _httpContextAccessor.HttpContext.Response;
response.Headers.Add("Content-Type", "text/event-stream");
MessageManager.Current.RegisterChannel(channelId, response);
while (true)
{
await Task.Delay(100);
}
return Ok();
}
private static Task WriteSseEventFieldAsync(HttpResponse response, string field, string data)
{
return response.WriteAsync($"{field}: {data}\n\n");
}
[HttpGet]
[Route("subscribe")]
public IActionResult SubscribeClientToChannel([FromQuery]Guid channelId, [FromQuery]int clientId)
{
MessageManager.Current.SubscribeClientToChannel(channelId, clientId);
return Content("OK");
}
[HttpGet]
[Route("version")]
public IActionResult GetVersion()
{
return Content("2.0.2");
}
}
} |
using System.Collections.Generic;
using GloWS_REST_Library.Objects.Plumbing;
using GloWS_REST_Library.Objects.Tracking;
using Newtonsoft.Json;
namespace GloWS_REST_Library.Objects.RateQuery.Response {
public class Charges {
public string Currency { get; set; }
[JsonConverter(typeof(SingleOrArrayConverter<Charge>))]
public List<Charge> Charge { get; set; } = new List<Charge>();
/// <inheritdoc />
public override string ToString()
{
return $"Currency: {Currency} | # of Charges: {Charge.Count}";
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace RouteManagement
{
public class Route
{
List<Point> points = new List<Point>();
public void AddPoint(Point point)
{
points.Add(point);
}
public double GetLength()
{
double length = 0.0;
for (int idx = 0; idx < points.Count - 1; ++idx)
{
length += points[idx].GetDistance(points[idx + 1]);
}
return length;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EXERCICE1_int_simple
{
public class Program
{
static void Main(string[] args)
{
//Déclaration des variables
double capital;
double tx;
uint duree;
double interet;//calcul des intêrets
double resultat;//calcul de la somme placéé plus les intêrets
//Saisie des entrées
Console.WriteLine ("Entrez le capital à placer :");
capital= double.Parse(Console.ReadLine());
Console.WriteLine("Entrez le taux d'intêret annuel en %:");
tx = double.Parse(Console.ReadLine());
Console.WriteLine("Entrez la durée d'épargne en nombre d'années:");
duree = uint.Parse(Console.ReadLine());
//Traitement...
interet = InteretsSIMPLES(capital,tx,duree); //appel de la méthode Intêrets
Console.WriteLine("Les intêrets sont de :"+interet);
resultat = InteretsComposes(capital,tx,duree);
Console.WriteLine("Le capital valorisé au bout de "+duree+" an(s) est de :" + resultat);
Console.ReadKey();
}
public static double InteretsSIMPLES(double _capital, double _tx, double _duree)
{
double resultat;
resultat = _capital+((_capital * (_tx) / 100)*_duree);
return resultat;
}
public static double InteretsComposes(double _capital, double _tx, uint _duree)
{
double resultat;
resultat= (_capital * Math.Pow(1+(_tx/100), _duree));
return resultat;
}
}
}
|
using Gecko.Interop;
namespace Gecko
{
/// <summary>
/// May be for future use (tabbed browser)
/// </summary>
public static class WindowMediator
{
private static ServiceWrapper<nsIWindowMediator> _windowMediator;
static WindowMediator()
{
_windowMediator = new ServiceWrapper<nsIWindowMediator>( Contracts.WindowMediator );
}
public static void RegisterWindow(nsIXULWindow window)
{
_windowMediator.Instance.RegisterWindow(window);
}
public static void UnregisterWindow(nsIXULWindow window)
{
_windowMediator.Instance.UnregisterWindow( window );
}
/// <summary>
/// Get most recent window
/// types:
/// "navigator:browser"
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static nsIDOMWindow GetMostRecentWindow(string type)
{
return _windowMediator.Instance.GetMostRecentWindow( type );
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Stateflow.Fields.DataStores;
namespace Stateflow.Fields
{
public class FieldDefinitionCollection<TIdentifier>: Dictionary<TIdentifier, IFieldDefinition<TIdentifier>>
{
IDataStore<TIdentifier> _store;
ITemplate<TIdentifier> _type;
public FieldDefinitionCollection (IDataStore<TIdentifier> store, ITemplate<TIdentifier> type)
{
_store = store;
_type = type;
}
public void Add(IFieldDefinition<TIdentifier> fieldDefinition)
{
if (fieldDefinition == null)
throw new ArgumentNullException ("fieldDefinition");
base.Add (fieldDefinition.Id, fieldDefinition);
}
public void AddRange(IEnumerable<IFieldDefinition<TIdentifier>> fieldDefinitions)
{
foreach (var fieldDefinition in fieldDefinitions)
{
this.Add(fieldDefinition);
}
}
public IFieldDefinition<TIdentifier> this [string name] {
get {
if (name == null) {
throw new ArgumentNullException ("name");
}
var fd = this.FirstOrDefault(a=>a.Value.Name.Equals(name));
if (!fd.Equals(default(KeyValuePair<TIdentifier, IFieldDefinition<TIdentifier> >)))
return fd.Value;
return null;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlacementManager : MonoBehaviour
{
//public Placement placement;
public string type { get; set; }
public string position { get; set; }
public int frequency { get; set; }
public int limit { get; set; }
public int promoID { get; set; }
private bool isVisible = false;
private GameManager gameManager;
void Start()
{
gameManager = GameObject.FindObjectOfType<GameManager>();
SetVisibility(isVisible);
}
public void Show()
{
isVisible = true;
SetVisibility(isVisible);
}
public void Hide()
{
isVisible = false;
SetVisibility(isVisible);
}
private void SetVisibility(bool v)
{
gameObject.SetActive(v);
}
public void FreeCoins()
{
gameManager.player.AddCoins(50);
Hide();
}
}
|
using MCDSaveEdit.Save.Models.Profiles;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
#nullable enable
namespace MCDSaveEdit
{
/// <summary>
/// Interaction logic for NetheriteEnchantmentControl.xaml
/// </summary>
public partial class NetheriteEnchantmentControl : UserControl
{
public NetheriteEnchantmentControl()
{
InitializeComponent();
gildedButtonCheckBox.Content = R.getString("iteminspector_gilded") ?? R.GILDED;
}
private Item? _item;
public Item? item {
get { return _item; }
set { _item = value; updateUI(); }
}
public Enchantment? enchantment {
get { return _item?.NetheriteEnchant; }
set { if (_item != null) { _item!.NetheriteEnchant = value; updateUI(); } }
}
public void updateUI()
{
if (_item == null)
{
gildedButton.IsEnabled = false;
gildedButtonCheckBox.IsEnabled = false;
gildedButton.Visibility = Visibility.Visible;
netheriteEnchantmentStack.Visibility = Visibility.Collapsed;
netheriteEnchantmentRemoveButton.Visibility = Visibility.Collapsed;
return;
}
if(_item.NetheriteEnchant == null)
{
gildedButton.IsEnabled = AppModel.gameContentLoaded;
gildedButton.Visibility = Visibility.Visible;
netheriteEnchantmentStack.Visibility = Visibility.Collapsed;
netheriteEnchantmentRemoveButton.Visibility = Visibility.Collapsed;
return;
}
gildedButton.IsEnabled = false;
gildedButton.Visibility = Visibility.Collapsed;
netheriteEnchantmentStack.Visibility = Visibility.Visible;
netheriteEnchantmentButton.IsEnabled = AppModel.gameContentLoaded;
netheriteEnchantmentRemoveButton.Visibility = Visibility.Visible;
netheriteEnchantmentRemoveButton.IsEnabled = AppModel.gameContentLoaded;
netheriteEnchantmentImage.Source = AppModel.instance.imageSourceForEnchantment(enchantment!);
netheriteEnchantmentTextBox.Text = enchantment!.Level.ToString();
netheriteEnchantmentLabel.Content = R.enchantmentName(enchantment!.Id);
}
private void gildedButton_Click(object sender, RoutedEventArgs e)
{
EventLogger.logEvent("gildedButton_Click");
selectedEnchantmentId(Constants.DEFAULT_ENCHANTMENT_ID);
}
private void upButton_Click(object sender, RoutedEventArgs e)
{
if (enchantment == null) { return; }
if (int.TryParse(netheriteEnchantmentTextBox.Text, out int level) && level < Constants.MAXIMUM_ENCHANTMENT_TIER)
{
int newLevel = level + 1;
EventLogger.logEvent("netheriteEnchantmentStepper_UpButtonClick", new Dictionary<string, object>() { { "newLevel", newLevel } });
netheriteEnchantmentTextBox.Text = newLevel.ToString();
}
}
private void downButton_Click(object sender, RoutedEventArgs e)
{
if (enchantment == null) { return; }
if (int.TryParse(netheriteEnchantmentTextBox.Text, out int level) && level > Constants.MINIMUM_ENCHANTMENT_TIER)
{
int newLevel = level - 1;
EventLogger.logEvent("netheriteEnchantmentStepper_DownButtonClick", new Dictionary<string, object>() { { "newLevel", newLevel } });
netheriteEnchantmentTextBox.Text = newLevel.ToString();
}
}
private void tierTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (enchantment == null) { return; }
if (int.TryParse(netheriteEnchantmentTextBox.Text, out int level) && enchantment.Level != level)
{
EventLogger.logEvent("netheriteEnchantmentTierTextBox_TextChanged", new Dictionary<string, object>() { { "level", level } });
enchantment.Level = level;
this.saveChanges?.Execute(item);
//updateTierUI();
}
}
private void enchantmentImageButton_Click(object sender, RoutedEventArgs e)
{
if (!AppModel.gameContentLoaded) { return; }
EventLogger.logEvent("netheriteEnchantmentImageButton_Click", new Dictionary<string, object>() { { "enchantment", enchantment?.Id ?? "null" } });
var selectionWindow = WindowFactory.createSelectionWindow();
selectionWindow.loadEnchantments(enchantment?.Id);
selectionWindow.onSelection = selectedEnchantmentId;
selectionWindow.Show();
}
public ICommand? saveChanges { get; set; }
private void selectedEnchantmentId(string? enchantmentId)
{
if (enchantmentId == null)
{
enchantment = null;
}
else
{
if (enchantment == null)
{
enchantment = new Enchantment() { Id = enchantmentId!, Level = 0, };
}
else
{
enchantment.Id = enchantmentId!;
}
}
this.saveChanges?.Execute(item);
updateUI();
}
private void netheriteEnchantmentRemoveButton_Click(object sender, RoutedEventArgs e)
{
EventLogger.logEvent("netheriteEnchantmentRemoveButton_Click");
selectedEnchantmentId(null);
}
}
}
|
using System.Runtime.InteropServices;
using System.Xml.Serialization;
namespace Diadoc.Api.Com
{
[ComVisible(true)]
[Guid("FB300E42-1ABF-4553-8882-3692ACA21F48")]
//NOTE: Это хотели, чтобы можно было использовать XML-сериализацию для классов
[XmlType(TypeName = "RoamingNotificationStatus", Namespace = "https://diadoc-api.kontur.ru")]
public enum RoamingNotificationStatus
{
UnknownRoamingNotificationStatus = Diadoc.Api.Proto.Documents.RoamingNotificationStatus.UnknownRoamingNotificationStatus,
RoamingNotificationStatusNone = Diadoc.Api.Proto.Documents.RoamingNotificationStatus.RoamingNotificationStatusNone,
RoamingNotificationStatusSuccess = Diadoc.Api.Proto.Documents.RoamingNotificationStatus.RoamingNotificationStatusSuccess,
RoamingNotificationStatusError = Diadoc.Api.Proto.Documents.RoamingNotificationStatus.RoamingNotificationStatusError
}
}
|
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using ICSharpCode.SharpDevelop.Gui;
using ICSharpCode.SharpDevelop.Services;
namespace Debugger.AddIn.Options
{
/// <summary>
/// Interaction logic for DebuggingOptionsPanel.xaml
/// </summary>
public partial class DebuggingOptionsPanel : OptionPanel
{
public DebuggingOptionsPanel()
{
InitializeComponent();
ChbStepOverAllProperties_CheckedChanged(null, null);
}
/// <summary>
/// If stepOverAllProperties is true when the panel is opened then the CheckChanged event is
/// fired during the InitializeComponent method call before the remaining check boxes are created.
/// So check if the remaining check boxes have been created.
/// </summary>
void ChbStepOverAllProperties_CheckedChanged(object sender, RoutedEventArgs e)
{
if (IsPanelInitialized()) {
bool stepOverAllProperties = chbStepOverAllProperties.IsChecked.GetValueOrDefault(false);
chbStepOverSingleLineProperties.IsEnabled = !stepOverAllProperties;
chbStepOverFieldAccessProperties.IsEnabled = !stepOverAllProperties;
}
}
bool IsPanelInitialized()
{
return chbStepOverSingleLineProperties != null;
}
public override bool SaveOptions()
{
bool result = base.SaveOptions();
DebuggingOptions.ResetStatus(proc => proc.Debugger.ResetJustMyCodeStatus());
return result;
}
}
} |
using BB.Memory.Base;
using System.Collections.Generic;
namespace BB.Memory.Abstract
{
public interface ILogManager
{
void Flush(int lsn);
bool Append(object[] records, out int lsn);
IEnumerator<BasicLogRecord> GetEnumerator();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grammophone.Domos.Domain.Accounting
{
/// <summary>
/// Abstract base for a tax component of an invoice line.
/// </summary>
/// <typeparam name="U">The type of users, derived from <see cref="User"/>.</typeparam>
/// <typeparam name="P">The type of postings, derived from <see cref="Posting{U}"/>.</typeparam>
/// <typeparam name="R">the type of remittances, derived from <see cref="Remittance{U}"/>.</typeparam>
[Serializable]
public abstract class InvoiceLineTaxComponent<U, P, R> : TrackingEntityWithID<U, long>
where U : User
where P : Posting<U>
where R : Remittance<U>
{
#region Constants
/// <summary>
/// Maximum length of the <see cref="Description"/> property.
/// </summary>
public const int DescriptionLength = 32;
#endregion
#region Primitive properties
/// <summary>
/// The description of the tax component.
/// </summary>
[Required]
[MaxLength(DescriptionLength)]
[Display(
ResourceType = typeof(InvoiceLineTaxComponentResources),
Name = nameof(InvoiceLineTaxComponentResources.Description_Name),
Description = nameof(InvoiceLineTaxComponentResources.Description_Description))]
public virtual string Description { get; set; }
/// <summary>
/// The rate of the tax as a percentage.
/// </summary>
[Display(
ResourceType = typeof(InvoiceLineTaxComponentResources),
Name = nameof(InvoiceLineTaxComponentResources.RatePercentFactor_Name),
Description = nameof(InvoiceLineTaxComponentResources.RatePercentFactor_Description))]
public virtual decimal? RatePercentFactor { get; set; }
/// <summary>
/// The tax amount charged.
/// </summary>
[Display(
ResourceType = typeof(InvoiceLineTaxComponentResources),
Name = nameof(InvoiceLineTaxComponentResources.Amount_Name),
Description = nameof(InvoiceLineTaxComponentResources.Amount_Description))]
public virtual decimal Amount { get; set; }
#endregion
#region Relations
/// <summary>
/// ID of the invoice line where the tax component belongs.
/// </summary>
[Display(
ResourceType = typeof(InvoiceLineTaxComponentResources),
Name = nameof(InvoiceLineTaxComponentResources.LineID_Name),
Description = nameof(InvoiceLineTaxComponentResources.LineID_Description))]
public virtual long LineID { get; set; }
/// <summary>
/// Optional ID of the posting related to the tax.
/// </summary>
public virtual long? PostingID { get; set; }
/// <summary>
/// Optional posting related to the tax.
/// </summary>
public virtual P Posting { get; set; }
/// <summary>
/// Optional ID of the remittance related to the tax.
/// </summary>
public virtual long? RemittanceID { get; set; }
/// <summary>
/// Optional remittance related to the tax.
/// </summary>
public R Remittance { get; set; }
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Abp.Application.Services;
using Abp.Localization;
namespace LanguageOmg.Services
{
public interface ITesting : IApplicationService
{
void CreateLanguage(LanguageInfo input)
}
}
|
using RLabs.Cielo.SDK.Enum;
using RLabs.Cielo.SDK.Model.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PaymentClass = RLabs.Cielo.SDK.Model.Entity.Payment;
namespace RLabs.Cielo.SDK.Test.Factory
{
internal class PaymentCreator
{
private PaymentClass createdPayment;
public PaymentCreator()
{
createdPayment = new PaymentClass();
createdPayment.Type = PaymentType.CreditCard;
createdPayment.Amount = 15700;
createdPayment.Installments = 1;
createdPayment.CreditCard = new CreditCardCreator().Result;
}
public PaymentCreator WithType(PaymentType newPaymentType)
{
createdPayment.Type = newPaymentType;
return this;
}
public PaymentCreator WithAmount(int newAmount)
{
createdPayment.Amount = newAmount;
return this;
}
public PaymentCreator WithInstallments(int newInstallments)
{
createdPayment.Installments = newInstallments;
return this;
}
public PaymentCreator WithCreditCard(CreditCard creditCard)
{
createdPayment.CreditCard = creditCard;
return this;
}
public PaymentClass Result
{
get
{
return createdPayment;
}
}
}
}
|
namespace BinarySerializer.Klonoa.DTP
{
/// <summary>
/// A vector with 16-bit values
/// </summary>
public class KlonoaVector16 : BinarySerializable
{
public KlonoaVector16()
{
}
public KlonoaVector16(short x, short y, short z)
{
X = x;
Y = y;
Z = z;
}
public short X { get; set; }
public short Y { get; set; }
public short Z { get; set; }
public override void SerializeImpl(SerializerObject s)
{
X = s.Serialize<short>(X, name: nameof(X));
Y = s.Serialize<short>(Y, name: nameof(Y));
Z = s.Serialize<short>(Z, name: nameof(Z));
}
public static KlonoaVector16 operator +(KlonoaVector16 v1, KlonoaVector16 v2) =>
new KlonoaVector16((short)(v1.X + v2.X), (short)(v1.Y + v2.Y), (short)(v1.Z + v2.Z));
public override bool UseShortLog => true;
public override string ToString() => $"({X}, {Y}, {Z})";
}
} |
using System.Collections.Generic;
using GigHub.Core.Models;
namespace GigHub.Core.Repositories
{
public interface IFollowingRepository
{
IEnumerable<Following> GetFollowingsByUserId(string userId);
Following GetFollowing(string userId, string artistId);
}
} |
using System;
using System.Runtime.Serialization;
namespace NTI.iMeter
{
/// <summary>
/// Reference a component which is represented uniquely by a combination of <see cref="LibraryId" /> and
/// <see cref="ComponentId" />.
/// </summary>
[Serializable]
[DataContract]
public struct LibraryComponentId : IEquatable<LibraryComponentId>
{
public static bool operator ==(LibraryComponentId left, LibraryComponentId right)
{
return left.Equals(right);
}
public static bool operator !=(LibraryComponentId left, LibraryComponentId right)
{
return !left.Equals(right);
}
/// <summary>
/// Get the associated library ID for a component reference.
/// </summary>
[DataMember]
public Guid LibraryId { get; }
/// <summary>
/// Get the associated component ID for a component reference.
/// </summary>
[DataMember]
public Guid ComponentId { get; }
public LibraryComponentId(Guid libraryId, Guid componentId)
{
LibraryId = libraryId;
ComponentId = componentId;
}
/// <inheritdoc />
public bool Equals(LibraryComponentId other)
{
return LibraryId.Equals(other.LibraryId) && ComponentId.Equals(other.ComponentId);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
return obj is LibraryComponentId other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
return LibraryId.GetHashCode() ^ ComponentId.GetHashCode();
}
/// <summary>
/// Deconstruction method used for C# 7.0 deconstruction syntax.
/// </summary>
/// <param name="libraryId">The output library ID value.</param>
/// <param name="componentId">The output component ID value.</param>
public void Deconstruct(out Guid libraryId, out Guid componentId)
{
libraryId = LibraryId;
componentId = ComponentId;
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace HttpConnect.HttpUtil.Data
{
public class ReceivedRequestData
{
/// <summary>
/// リクエスト送信元クライアントPCのIPアドレス
/// </summary>
public string ClientIPAddress { get; set; }
/// <summary>
/// urlから取得した実行対象API名
/// </summary>
public string APIName { get; set; }
/// <summary>
/// HTTPリクエストから取り出したクエリストリング
/// </summary>
public string QueryString { get; set; }
/// <summary>
/// リクエストデータを解析する。
/// </summary>
/// <param name="request"></param>
public void SetQuery(HttpListenerRequest request)
{
//API名を取得
APIName = request.RawUrl.ToString().Replace("/", "");
ClientIPAddress = request.RemoteEndPoint.ToString();
StreamReader reader = new StreamReader(request.InputStream);
QueryString = reader.ReadToEnd();
}
/// <summary>
/// リクエストパラメータを取得する
/// </summary>
/// <returns></returns>
public List<string> GetQueryArgList()
{
//操作対象チャンネルと変更要素が結合した状態で送信されるので
//対応する変数へ格納する
string[] paramList = QueryString.Split('&');
return paramList.ToList();
}
}
}
|
namespace AngleSharp.Dom
{
using AngleSharp.Attributes;
using AngleSharp.Dom.Css;
using System;
/// <summary>
/// The Element interface represents an object within a DOM document.
/// </summary>
[DomName("Element")]
public interface IElement : INode, IParentNode, IChildNode, INonDocumentTypeChildNode, IElementCssInlineStyle
{
/// <summary>
/// Gets the namespace prefix of this element.
/// </summary>
[DomName("prefix")]
String Prefix { get; }
/// <summary>
/// Gets the local part of the qualified name of this element.
/// </summary>
[DomName("localName")]
String LocalName { get; }
/// <summary>
/// Gets the namespace URI of this element.
/// </summary>
[DomName("namespaceURI")]
String NamespaceUri { get; }
/// <summary>
/// Gets the sequence of associated attributes.
/// </summary>
[DomName("attributes")]
INamedNodeMap Attributes { get; }
/// <summary>
/// Gets the list of class names.
/// </summary>
[DomName("classList")]
ITokenList ClassList { get; }
/// <summary>
/// Gets or sets the value of the class attribute.
/// </summary>
[DomName("className")]
String ClassName { get; set; }
/// <summary>
/// Gets or sets the id value of the element.
/// </summary>
[DomName("id")]
String Id { get; set; }
/// <summary>
/// Inserts new HTML elements specified by the given HTML string at
/// a position relative to the current element specified by the
/// position.
/// </summary>
/// <param name="position">The relation to the current element.</param>
/// <param name="html">The HTML code to generate elements for.</param>
[DomName("insertAdjacentHTML")]
void Insert(AdjacentPosition position, String html);
/// <summary>
/// Returns a boolean value indicating whether the specified element
/// has the specified attribute or not.
/// </summary>
/// <param name="name">The attributes name.</param>
/// <returns>The return value of true or false.</returns>
[DomName("hasAttribute")]
Boolean HasAttribute(String name);
/// <summary>
/// Returns a boolean value indicating whether the specified element
/// has the specified attribute or not.
/// </summary>
/// <param name="namespaceUri">
/// A string specifying the namespace of the attribute.
/// </param>
/// <param name="localName">The attributes name.</param>
/// <returns>The return value of true or false.</returns>
[DomName("hasAttributeNS")]
Boolean HasAttribute(String namespaceUri, String localName);
/// <summary>
/// Returns the value of the named attribute on the specified element.
/// </summary>
/// <param name="name">
/// The name of the attribute whose value you want to get.
/// </param>
/// <returns>
/// If the named attribute does not exist, the value returned will be
/// null, otherwise the attribute's value.
/// </returns>
[DomName("getAttribute")]
String GetAttribute(String name);
/// <summary>
/// Returns the value of the named attribute on the specified element.
/// </summary>
/// <param name="namespaceUri">
/// A string specifying the namespace of the attribute.
/// </param>
/// <param name="localName">
/// The name of the attribute whose value you want to get.
/// </param>
/// <returns>
/// If the named attribute does not exist, the value returned will be
/// null, otherwise the attribute's value.
/// </returns>
[DomName("getAttributeNS")]
String GetAttribute(String namespaceUri, String localName);
/// <summary>
/// Adds a new attribute or changes the value of an existing attribute
/// on the specified element.
/// </summary>
/// <param name="name">The name of the attribute as a string.</param>
/// <param name="value">The desired new value of the attribute.</param>
/// <returns>The current element.</returns>
[DomName("setAttribute")]
void SetAttribute(String name, String value);
/// <summary>
/// Adds a new attribute or changes the value of an existing attribute
/// on the specified element.
/// </summary>
/// <param name="namespaceUri">
/// A string specifying the namespace of the attribute.
/// </param>
/// <param name="name">The name of the attribute as a string.</param>
/// <param name="value">The desired new value of the attribute.</param>
[DomName("setAttributeNS")]
void SetAttribute(String namespaceUri, String name, String value);
/// <summary>
/// Removes an attribute from the specified element.
/// </summary>
/// <param name="name">
/// Is a string that names the attribute to be removed.
/// </param>
/// <returns>True if an attribute was removed, otherwise false.</returns>
[DomName("removeAttribute")]
Boolean RemoveAttribute(String name);
/// <summary>
/// Removes an attribute from the specified element.
/// </summary>
/// <param name="namespaceUri">
/// A string specifying the namespace of the attribute.
/// </param>
/// <param name="localName">
/// Is a string that names the attribute to be removed.
/// </param>
/// <returns>True if an attribute was removed, otherwise false.</returns>
[DomName("removeAttributeNS")]
Boolean RemoveAttribute(String namespaceUri, String localName);
/// <summary>
/// Returns a set of elements which have all the given class names.
/// </summary>
/// <param name="classNames">
/// A string representing the list of class names to match; class names
/// are separated by whitespace.
/// </param>
/// <returns>A collection of elements.</returns>
[DomName("getElementsByClassName")]
IHtmlCollection<IElement> GetElementsByClassName(String classNames);
/// <summary>
/// Returns a NodeList of elements with the given tag name. The
/// complete document is searched, including the root node.
/// </summary>
/// <param name="tagName">
/// A string representing the name of the elements. The special string
/// "*" represents all elements.
/// </param>
/// <returns>
/// A collection of elements in the order they appear in the tree.
/// </returns>
[DomName("getElementsByTagName")]
IHtmlCollection<IElement> GetElementsByTagName(String tagName);
/// <summary>
/// Returns a list of elements with the given tag name belonging to the
/// given namespace. The complete document is searched, including the
/// root node.
/// </summary>
/// <param name="namespaceUri">
/// The namespace URI of elements to look for.
/// </param>
/// <param name="tagName">
/// Either the local name of elements to look for or the special value
/// "*", which matches all elements.
/// </param>
/// <returns>
/// A collection of elements in the order they appear in the tree.
/// </returns>
[DomName("getElementsByTagNameNS")]
IHtmlCollection<IElement> GetElementsByTagNameNS(String namespaceUri, String tagName);
/// <summary>
/// Checks if the element is matched by the given selector.
/// </summary>
/// <param name="selectors">Represents the selector to test.</param>
/// <returns>
/// True if the element would be selected by the specified selector,
/// otherwise false.
/// </returns>
[DomName("matches")]
Boolean Matches(String selectors);
/// <summary>
/// Gets or sets the inner HTML (excluding the current element) of the
/// element.
/// </summary>
[DomName("innerHTML")]
String InnerHtml { get; set; }
/// <summary>
/// Gets or sets the outer HTML (including the current element) of the
/// element.
/// </summary>
[DomName("outerHTML")]
String OuterHtml { get; set; }
/// <summary>
/// Gets the name of the tag that represents the current element.
/// </summary>
[DomName("tagName")]
String TagName { get; }
/// <summary>
/// Creates a pseudo element for the current element.
/// </summary>
/// <param name="pseudoElement">
/// The element to create (e.g. ::after).
/// </param>
/// <returns>The created element or null, if not possible.</returns>
[DomName("pseudo")]
IPseudoElement Pseudo(String pseudoElement);
/// <summary>
/// Creates a new shadow root for the current element, if there is none
/// already.
/// </summary>
/// <param name="mode">The mode of the shadow root.</param>
/// <returns>The new shadow root.</returns>
[DomName("attachShadow")]
[DomInitDict]
IShadowRoot AttachShadow(ShadowRootMode mode = ShadowRootMode.Open);
/// <summary>
/// Gets the assigned slot of the current element, if any.
/// </summary>
[DomName("assignedSlot")]
IElement AssignedSlot { get; }
/// <summary>
/// Gets the value of the slot attribute.
/// </summary>
[DomName("slot")]
String Slot { get; set; }
/// <summary>
/// Gets the shadow root of the current element, if any.
/// </summary>
[DomName("shadowRoot")]
IShadowRoot ShadowRoot { get; }
/// <summary>
/// Gets if the element is currently focused.
/// </summary>
Boolean IsFocused { get; }
}
}
|
using Cindy.Logic.ReferenceValues;
using Cindy.Util.Serializables;
using System;
using UnityEngine;
namespace Cindy.Logic.VariableObjects
{
/// <summary>
/// Vector3变量
/// </summary>
[AddComponentMenu("Cindy/Logic/VariableObject/Vector3Object (Vector3)")]
public class Vector3Object : VariableObject<Vector3>
{
public override Type GetStorableObjectType()
{
return typeof(SerializedVector3);
}
public override object GetStorableObject()
{
return new SerializedVector3(value);
}
protected override bool TramsformValue(object obj, out Vector3 output)
{
if(obj is SerializedVector3 s)
{
output = s.ToVector3();
return true;
}
else
{
output = default;
return false;
}
}
public void SetPosition(Transform transform)
{
if (transform != null)
SetValue(transform.position);
}
public void SetRotation(Transform transform)
{
if (transform != null)
SetValue(transform.rotation.eulerAngles);
}
public void SetScale(Transform transform)
{
if (transform != null)
SetValue(transform.localScale);
}
}
/// <summary>
/// Vector3分量
/// </summary>
[AddComponentMenu("Cindy/Logic/VariableObject/Vector3Value (Float)")]
public class Vector3Value : FloatObject
{
[Header("Vector3Value")]
public ReferenceVector3 vector;
public Vector3Components component;
protected void ApplyToVector(float value)
{
Vector3 v = vector.Value;
switch (component)
{
case Vector3Components.X:
v.x = value;
break;
case Vector3Components.Y:
v.y = value;
break;
case Vector3Components.Z:
v.z = value;
break;
}
vector.Value = v;
}
public override void SetValue(float value)
{
ApplyToVector(value);
base.SetValue(value);
}
protected override void OnValueChanged(bool save = true, bool notify = true)
{
ApplyToVector(value);
base.OnValueChanged(save, notify);
}
protected override void OnValueLoad(float val)
{
ApplyToVector(val);
base.OnValueLoad(val);
}
protected override void OnValueLoadEmpty()
{
GetValue();
}
public override float GetValue()
{
switch (component)
{
case Vector3Components.X:
value = vector.Value.x;
break;
case Vector3Components.Y:
value = vector.Value.y;
break;
case Vector3Components.Z:
value = vector.Value.z;
break;
}
return base.GetValue();
}
public enum Vector3Components
{
X,Y,Z
}
}
/// <summary>
/// Vector3长度
/// </summary>
[AddComponentMenu("Cindy/Logic/VariableObject/Vector3Magnitude (Float)")]
public class Vector3Magnitude : FloatObject
{
[Header("Vector3Magnitude")]
public ReferenceVector3 vector;
public override void SetValue(float value)
{
}
public override float GetValue()
{
value = vector.Value.magnitude;
return base.GetValue();
}
}
/// <summary>
/// 相对Vector3
/// </summary>
[AddComponentMenu("Cindy/Logic/VariableObject/RelativedVector3 (Vector3)")]
public class RelativedVector3 : Vector3Object
{
[Header("RelativedVector3")]
public ReferenceVector3 start, end;
public override void SetValue(Vector3 value)
{
}
public override Vector3 GetValue()
{
value = end.Value - start.Value;
return base.GetValue();
}
}
/// <summary>
/// Vector2变量
/// </summary>
[AddComponentMenu("Cindy/Logic/VariableObject/Vector2Object (Vector2)")]
public class Vector2Object : VariableObject<Vector2>
{
public override Type GetStorableObjectType()
{
return typeof(SerializedVector2);
}
public override object GetStorableObject()
{
return new SerializedVector2(value);
}
protected override bool TramsformValue(object obj, out Vector2 output)
{
if(obj is SerializedVector2 v)
{
output = v.ToVector2();
return true;
}
else
{
output = default;
return false;
}
}
}
/// <summary>
/// Vector2分量
/// </summary>
[AddComponentMenu("Cindy/Logic/VariableObject/Vectors/Vector2Value (Float)")]
public class Vector2Value : FloatObject
{
[Header("Vector2Value")]
public ReferenceVector2 vector;
public Vector2Components component;
protected void ApplyToVector(float value)
{
Vector2 v = vector.Value;
switch (component)
{
case Vector2Components.X:
v.x = value;
break;
case Vector2Components.Y:
v.y = value;
break;
}
vector.Value = v;
}
public override void SetValue(float value)
{
ApplyToVector(value);
base.SetValue(value);
}
protected override void OnValueChanged(bool save = true, bool notify = true)
{
ApplyToVector(value);
base.OnValueChanged(save, notify);
}
protected override void OnValueLoad(float val)
{
ApplyToVector(value);
base.OnValueLoad(val);
}
protected override void OnValueLoadEmpty()
{
GetValue();
}
public override float GetValue()
{
switch (component)
{
case Vector2Components.X:
value = vector.Value.x;
break;
case Vector2Components.Y:
value = vector.Value.y;
break;
}
return base.GetValue();
}
public enum Vector2Components
{
X, Y
}
}
/// <summary>
/// 相对Vector2
/// </summary>
[AddComponentMenu("Cindy/Logic/VariableObject/RelativedVector2 (Vector2)")]
public class RelativedVector2 : Vector2Object
{
[Header("RelativedVector2")]
public ReferenceVector2 start, end;
public override void SetValue(Vector2 value)
{
}
public override Vector2 GetValue()
{
value = end.Value - start.Value;
return base.GetValue();
}
}
/// <summary>
/// Vector2长度
/// </summary>
[AddComponentMenu("Cindy/Logic/VariableObject/Vector2Magnitude (Float)")]
public class Vector2Magnitude : FloatObject
{
[Header("Vector2Magnitude")]
public ReferenceVector2 vector;
public override void SetValue(float value)
{
}
public override float GetValue()
{
value = vector.Value.magnitude;
return base.GetValue();
}
}
}
|
using Microsoft.Playwright;
namespace pre.test.pages
{
public class BasePage
{
protected IPage Page;
public BasePage(IPage page) => Page = page;
public IPage GetPage() => Page;
}
}
|
/*********************************************
作者:曹旭升
QQ:279060597
访问博客了解详细介绍及更多内容:
http://blog.shengxunwei.com
**********************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Sheng.SailingEase.Kernal;
namespace Sheng.SailingEase.Core
{
[Serializable]
[EventProvide("验证窗体数据", 0x000071,"验证窗体元素中的数据的有效性")]
public class ValidateFormDataEvent : EventBase
{
private EnumValidateFormDataMode _validateMode;
public EnumValidateFormDataMode ValidateMode
{
get
{
return this._validateMode;
}
set
{
this._validateMode = value;
}
}
private string _validateSetXml;
public string ValidateSetXml
{
get
{
return this._validateSetXml;
}
set
{
this._validateSetXml = value;
}
}
public ValidateFormDataEvent()
{
}
public override void FromXml(string strXml)
{
base.FromXml(strXml);
SEXElement xmlDoc = SEXElement.Parse(strXml);
this.ValidateMode = (EnumValidateFormDataMode)xmlDoc.GetInnerObject<int>("/Mode", 0);
this.ValidateSetXml = xmlDoc.SelectSingleNode("/ValidateSet").ToString();
}
public override string ToXml()
{
SEXElement xmlDoc = SEXElement.Parse(base.ToXml());
xmlDoc.AppendChild(String.Empty, "Mode", (int)this.ValidateMode);
if (this.ValidateSetXml == String.Empty)
{
this.ValidateSetXml = "<ValidateSet/>";
}
xmlDoc.AppendInnerXml(this.ValidateSetXml);
return xmlDoc.ToString();
}
public enum EnumValidateFormDataMode
{
[LocalizedDescription("EnumValidateFormDataMode_All")]
All = 0,
[LocalizedDescription("EnumValidateFormDataMode_Appoint")]
Appoint = 1
}
}
}
|
using Contracts;
using Contracts.Api;
using Contracts.Models;
using Contracts.Requests;
using Core.Extensions;
using SocketClient.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SocketClient.Api
{
class UserApi : IUserApi
{
private readonly Client _client;
public UserApi(Client client)
{
_client = client;
}
public async Task<User> Add(CreateUserRequest request)
{
_client.Connect();
return await _client.UserAdd(request);
}
public Task ChangePassword(ChangePasswordRequest request)
{
_client.Connect();
return _client.UserChangePassword(request);
}
public Task Delete(IdRequest request)
{
_client.Connect();
return _client.UserDelete(request);
}
public async Task<User> Get(IdRequest request)
{
_client.Connect();
return await _client.UserGet(request);
}
public async Task<List<CompanyUser>> GetCompanies(BearerTokenRequest request)
{
_client.Connect();
return (await _client.UserGetCompanies(request))
.ToList();
}
public async Task<User> Update(UserRequest request)
{
_client.Connect();
return (await _client.UserUpdate(request)).ToDto();
}
}
}
|
using Bookshelf.API.Entities.Concrete;
namespace Bookshelf.API.DataAccess.Interfaces
{
public interface IGenreDal : IGenericDal<Genre>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Appwidget;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace WidgetPractice01
{
/// <summary>
/// ウィジェットのビューの更新を行うクラス
/// ウィジェット実装する上で必須ではない
/// </summary>
[IntentFilter(new string[] {"Update_Time"})]
[Service] // AndroidManifestに追記する代わりにAttributeを設定する(xamarin)
class UpdateService : Service
{
public override void OnCreate()
{
base.OnCreate();
}
public override StartCommandResult OnStartCommand(Intent intent,[GeneratedEnum] StartCommandFlags flags,int startId)
{
RemoteViews updateViews = BuildUpdate(intent);
ComponentName widget = new ComponentName(this, Java.Lang.Class.FromType(typeof(AppWidget)).Name);
AppWidgetManager manager = AppWidgetManager.GetInstance(this);
manager.UpdateAppWidget(widget, updateViews);
// Toast.MakeText(this, "UpdateService:OnstartCommand", ToastLength.Long).Show();
// とくにserviceを複数回スタートさせてないならこれで十分だと思う
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent)
{
// バインドされたくない場合はnullを返す
return null;
}
public RemoteViews BuildUpdate(Intent intent)
{
RemoteViews updateViews = new RemoteViews(this.PackageName, Resource.Layout.widget_app_layout2);
System.DateTime time = System.DateTime.Now;
string text = $"{time}";// string.Format("now time : {0}", time);
updateViews.SetTextViewText(Resource.Id.Text2, text);
// ウィジェットのUI処理の登録なんかは一度やったら必要なさそうに感じるが、
// AppWidgetProvider::OnEnabled()なんかでやろうとすると、ウィジェットを2つ立ち上げると、
// OnEnabled()は一番最初に起動したウィジェットでしか呼ばれないので、あとに立ち上げたほうのボタンなんかをクリックしても反応しなくなる。
// Update処理(要はここ)で通すようにしたほうがいいのかも。
#if true
// ボタンクリックでActivityの起動
Intent WidgetIntent = new Intent(this, typeof(MainActivity));
PendingIntent appIntent = PendingIntent.GetActivity(this, 0, WidgetIntent, 0);
updateViews.SetOnClickPendingIntent(Resource.Id.TestButton2, appIntent);
// これでボタンのイメージ変えることもできる
// updateViews.SetImageViewResource(Resource.Id.TestButton2, Resource.Drawable.widget_button_focused);
// Intentに設定されたAction見てみる
System.Diagnostics.Debug.WriteLine("WidgetIntent.Action = " + WidgetIntent.Action);
// 時間書いたメッセージ部分のクリックでもActivity起動できるようにしてみる
updateViews.SetOnClickPendingIntent(Resource.Id.Text2, appIntent);
// ボタン押したら時計が更新されるようにする
Intent UpdateClockIntent = new Intent();
// ボタンを押したときにこのIntentがブロードキャストされて、それをこのクラスが直接受け取り、OnStartCommandが呼ばれる。
UpdateClockIntent.SetAction("Update_Time");
PendingIntent updateTimeIntent = PendingIntent.GetService(this, 0, UpdateClockIntent, 0); // サービスクラスへ投げるインテント作成
updateViews.SetOnClickPendingIntent(Resource.Id.TestButton3, updateTimeIntent);
#endif
if (!string.IsNullOrEmpty(intent.Action)) {
if(intent.Action.Equals("Update_Time")) {
time = System.DateTime.Now;
text = $"{time}";// string.Format("now time : {0}", time);
updateViews.SetTextViewText(Resource.Id.Text2, text);
// Toast.MakeText(this, "ClockUpdate.", ToastLength.Short).Show();
}
}
return updateViews;
}
}
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Windows;
using System.Windows.Controls;
namespace Microsoft.Test.Stability.Extensions.Actions
{
/// <summary>
/// Layout an Element in DockPanel.
/// </summary>
public class LayoutElementInDockPanelAction : SimpleDiscoverableAction
{
#region Public Members
[InputAttribute(ContentInputSource.GetFromLogicalTree)]
public DockPanel DockPanel { get; set; }
public int ChildIndex { get; set; }
public Dock Dock { get; set; }
#endregion
#region Override Members
public override bool CanPerform()
{
return DockPanel.Children.Count > 0;
}
public override void Perform()
{
ChildIndex %= DockPanel.Children.Count;
UIElement child = DockPanel.Children[ChildIndex];
DockPanel.SetDock(child, Dock);
}
#endregion
}
}
|
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Customer1.Model;
namespace Customer1.Data
{
public class Customer1Context : DbContext
{
public Customer1Context (DbContextOptions<Customer1Context> options)
: base(options)
{
}
public DbSet<Customer1.Model.Customer> Customer { get; set; }
}
}
|
using JetBrains.Annotations;
using UnityEngine;
namespace Silphid.Extensions
{
public static class RectExtensions
{
public static Rect Translate(this Rect This, Vector2 vector) =>
new Rect(This.xMin + vector.x, This.yMin + vector.y, This.width, This.height);
public static Rect FlippedY(this Rect This) =>
new Rect(This.x, -(This.y + This.height), This.width, This.height);
public static Rect FlippedXY(this Rect This) =>
new Rect(This.y, This.x, This.height, This.width);
public static Rect Union(this Rect This, Rect other) =>
This.IsEmpty()
? other
: other.IsEmpty()
? This
: Rect.MinMaxRect(
This.xMin.Min(other.xMin),
This.yMin.Min(other.yMin),
This.xMax.Max(other.xMax),
This.yMax.Max(other.yMax));
#region Comparison
public static bool IsEmpty(this Rect This) =>
This.xMin.IsAlmostEqualTo(This.xMax) || This.yMin.IsAlmostEqualTo(This.yMax);
[Pure]
public static bool IsAlmostEqualTo(this Rect This, Rect other) =>
This.min.IsAlmostEqualTo(other.min) && This.size.IsAlmostEqualTo(other.size);
[Pure]
public static bool IsAlmostEqualTo(this Rect This, Rect other, float epsilon) =>
This.min.IsAlmostEqualTo(other.min, epsilon) && This.size.IsAlmostEqualTo(other.size, epsilon);
#endregion
}
} |
using System.Data;
namespace Data.Net
{
internal sealed class Parameter
{
internal string Name { get; }
internal DbType DbType { get; }
internal ParameterDirection Direction { get; }
internal int Size { get; }
internal object Value { get; private set; }
internal Parameter(string name, object value)
{
Name = name;
Value = value;
}
internal Parameter(string name, ParameterDirection direction, DbType dbType, int size)
{
Name = name;
Direction = direction;
DbType = dbType;
Size = size;
}
internal void SetValue(object value) => Value = value;
}
} |
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Primitives;
using System.IO;
using System.Reflection.Emit;
using NetStitch.Option;
using NetStitch.Logger;
using System.Collections.Concurrent;
namespace NetStitch.Server
{
public class NetStitchMiddleware
{
static NetStitchMiddleware()
{
Servers = new ConcurrentDictionary<string, NetStitchServer>();
}
public static readonly ConcurrentDictionary<string, NetStitchServer> Servers;
readonly NetStitchServer server;
public NetStitchMiddleware(RequestDelegate next, Type type)
: this(next, type, new NetStitchOption()) { }
public NetStitchMiddleware(RequestDelegate next, Type type, NetStitchOption option)
: this(next, new[] { type.GetTypeInfo().Assembly }, option) { }
public NetStitchMiddleware(RequestDelegate next, Assembly[] assemblies, NetStitchOption option)
{
server = new NetStitchServer(assemblies, option);
if (!Servers.TryAdd(option.ServerID, server))
{
throw new InvalidOperationException($"Duplicate Server ID : {option.ServerID}");
}
}
public Task Invoke(HttpContext httpContext)
{
return server.OperationExecuteAsync(httpContext);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectiveTabSettings : MonoBehaviour
{
public string missionDescription;
public Texture[] objectiveImages;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.