content
stringlengths
23
1.05M
using jvContacts.Persistence.Infrastructure; using Microsoft.EntityFrameworkCore; namespace jvContacts.Persistence.Context { public class ContactDbContextFactory : DesignTimeDbContextFactoryBase<ContactDbContext> { protected override ContactDbContext CreateNewInstance(DbContextOptions<ContactDbContext> options) { return new ContactDbContext(options); } } }
using System; namespace Aardvark.Base { /// <summary> /// Wrappers for the best (fastest) available implementation of the respective tensor operation. /// </summary> public static partial class TensorExtensions { #region Image Scaling //# var intConfigs = new [] //# { //# Tup.Create("byte", "Byte", "Fun", "Fun"), //# Tup.Create("ushort", "UShort", "Fun", "Fun"), //# Tup.Create("float", "", "Fun", "Fun"), //# Tup.Create("byte", "Byte", "C3b", "C3f"), //# Tup.Create("ushort", "UShort", "C3us", "C3f"), //# Tup.Create("float", "", "C3f", "C3f"), //# Tup.Create("byte", "Byte", "C4b", "C4f"), //# Tup.Create("ushort", "UShort", "C4us", "C4f"), //# Tup.Create("float", "", "C4f", "C4f"), //# }; //# intConfigs.ForEach((dt, dtn, ct, fct) => { //# var fun = ct == "Fun" ? ct : "Col"; //# var clampVal = dtn != "" && ct == "Fun"; //# var clampMap = dtn != "" && ct != "Fun"; //# var rfct = dtn == "" ? "" : "RawF"; //# var dtct = ct == "Fun" ? dt : dt + ", " + ct; //# var it = ct == "Fun" ? dt : ct; public static void SetScaledNearest(this Matrix<__dtct__> targetMat, Matrix<__dtct__> sourceMat) { targetMat.SetScaledLinear(sourceMat, (x, a, b) => x < 0.5 ? a : b, (x, a, b) => x < 0.5 ? a : b); } /// <summary> /// Use supplied linear interpolators in x and y to scale the source matrix into the target /// matrix. /// </summary> public static void SetScaledLinear<T1>(this Matrix<__dtct__> targetMat, Matrix<__dtct__> sourceMat, Func<double, __it__, __it__, T1> xinterpolator, Func<double, T1, T1, __it__> yinterpolator) { var scale = sourceMat.Size.ToV2d() / targetMat.Size.ToV2d(); targetMat.SetScaled4(sourceMat, scale.X, scale.Y, 0.5 * scale.X - 0.5, 0.5 * scale.Y - 0.5, xinterpolator, yinterpolator, Tensor.Index2SamplesClamped, Tensor.Index2SamplesClamped); } /// <summary> /// Use Cubic Spline interpolation to scale the source matrix into the target matrix. /// The supplied parameter selects the spline to use. The default value of -0.5 generates /// Hermite Splines. If you call this repeatedly with the same selection parameter, /// build the cubic weighting function with 'Fun.CreateCubicTup4f(par)' and use the /// result as a paramter to the function call. /// </summary> public static void SetScaledCubic(this Matrix<__dtct__> targetMat, Matrix<__dtct__> sourceMat, double par = -0.5) { // create the cubic weighting function. Parameter a=-0.5 results in the cubic Hermite spline. var hermiteSpline = Fun.CreateCubicTup4f(par); targetMat.SetScaledCubic(sourceMat, hermiteSpline); } public static void SetScaledBSpline3(this Matrix<__dtct__> targetMat, Matrix<__dtct__> sourceMat) { targetMat.SetScaledCubic(sourceMat, Fun.BSpline3f); } /// <summary> /// Use a supplied cubic interpolator to scale the source matrix into the target matrix. /// </summary> public static void SetScaledCubic(this Matrix<__dtct__> targetMat, Matrix<__dtct__> sourceMat, Func<double, Tup4<float>> interpolator) { var scale = sourceMat.Size.ToV2d() / targetMat.Size.ToV2d(); targetMat.SetScaled16(sourceMat, scale.X, scale.Y, 0.5 * scale.X - 0.5, 0.5 * scale.Y - 0.5, interpolator, interpolator, __fun__.LinCom__rfct__, __fun__.LinCom, Tensor.Index4SamplesClamped, Tensor.Index4SamplesClamped/*# if (clampVal) { */, Col.__dtn__From__dtn__InFloatClamped/*# } else if (clampMap) { */, col => col.Map(Col.__dtn__From__dtn__InFloatClamped)/*# } */); } public static void SetScaledBSpline5(this Matrix<__dtct__> targetMat, Matrix<__dtct__> sourceMat) { targetMat.SetScaledOrder5(sourceMat, Fun.BSpline5f); } /// <summary> /// Use Lanczos Interpolation to scale the source matrix into the target matrix. /// </summary> public static void SetScaledLanczos(this Matrix<__dtct__> targetMat, Matrix<__dtct__> sourceMat) { targetMat.SetScaledOrder5(sourceMat, Fun.Lanczos3f); } public static void SetScaledOrder5(this Matrix<__dtct__> targetMat, Matrix<__dtct__> sourceMat, Func<double, Tup6<float>> interpolator) { var scale = sourceMat.Size.ToV2d() / targetMat.Size.ToV2d(); targetMat.SetScaled36(sourceMat, scale.X, scale.Y, 0.5 * scale.X - 0.5, 0.5 * scale.Y - 0.5, interpolator, interpolator, __fun__.LinCom__rfct__, __fun__.LinCom, Tensor.Index6SamplesClamped, Tensor.Index6SamplesClamped/*# if (clampVal) { */, Col.__dtn__From__dtn__InFloatClamped/*# } else if (clampMap) { */, col => col.Map(Col.__dtn__From__dtn__InFloatClamped)/*# } */); } //# }); // configs #endregion } }
using Yahoo.Yui.Compressor; using System.Text; using System.Globalization; namespace SquishIt.Framework.Minifiers.JavaScript { public class YuiMinifier : IJavaScriptMinifier { readonly JavaScriptCompressor compressor; public YuiMinifier() { compressor = new JavaScriptCompressor(); } public YuiMinifier(LoggingType loggingType, bool obfuscateJavaScript, bool preserveAllSemicolons, bool disableOptimizations, bool ignoreEval) { compressor = new JavaScriptCompressor { LoggingType = loggingType, ObfuscateJavascript = obfuscateJavaScript, PreserveAllSemicolons = preserveAllSemicolons, DisableOptimizations = disableOptimizations, IgnoreEval = ignoreEval }; } public YuiMinifier(LoggingType loggingType, bool obfuscateJavaScript, bool preserveAllSemicolons, bool disableOptimizations, bool ignoreEval, int lineBreakPosition) { compressor = new JavaScriptCompressor { LoggingType = loggingType, ObfuscateJavascript = obfuscateJavaScript, PreserveAllSemicolons = preserveAllSemicolons, DisableOptimizations = disableOptimizations, IgnoreEval = ignoreEval, LineBreakPosition = lineBreakPosition }; } public YuiMinifier(LoggingType loggingType, bool obfuscateJavaScript, bool preserveAllSemicolons, bool disableOptimizations, bool ignoreEval, int lineBreakPosition, Encoding encoding, CultureInfo cultureInfo) { compressor = new JavaScriptCompressor { LoggingType = loggingType, ObfuscateJavascript = obfuscateJavaScript, PreserveAllSemicolons = preserveAllSemicolons, DisableOptimizations = disableOptimizations, LineBreakPosition = lineBreakPosition, Encoding = encoding, ThreadCulture = cultureInfo, IgnoreEval = ignoreEval }; } public string Minify(string content) { return compressor.Compress(content); } } }
// Copyright (c) Drew Noakes and contributors. All Rights Reserved. Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace MetadataExtractor.Formats.Heif { public class HeicThumbnailTagDescriptor : TagDescriptor<HeicThumbnailDirectory> { public HeicThumbnailTagDescriptor(HeicThumbnailDirectory directory) : base(directory) { } } }
// Copyright 2010 Chris Patterson // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Stact { using System.Collections.Generic; using Magnum.Extensions; using Internal; /// <summary> /// A channel that converts a collection of messages into a dictionary of distinct /// messages by the specified key /// </summary> /// <typeparam name="T">The type of message delivered on the channel</typeparam> /// <typeparam name="TKey">The type of the key for the message</typeparam> public class DistinctChannel<T, TKey> : Channel<ICollection<T>> { readonly Fiber _fiber; readonly KeyAccessor<T, TKey> _keyAccessor; /// <summary> /// Constructs a channel /// </summary> /// <param name="fiber">The queue where consumer actions should be enqueued</param> /// <param name="keyAccessor">Returns the key for the message</param> /// <param name="output">The method to call when a message is sent to the channel</param> public DistinctChannel(Fiber fiber, KeyAccessor<T, TKey> keyAccessor, Channel<IDictionary<TKey, T>> output) { _fiber = fiber; _keyAccessor = keyAccessor; Output = output; } public Channel<IDictionary<TKey, T>> Output { get; private set; } public void Send(ICollection<T> message) { _fiber.Add(() => SendMessagesToOutputChannel(message)); } void SendMessagesToOutputChannel(IEnumerable<T> messages) { MessageDictionary<TKey, T> result = new MessageDictionaryImpl<TKey, T>(_keyAccessor); messages.Each(result.Add); Output.Send(result.RemoveAll()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using RepositoryManifest; namespace Utilities { public class MovedFileSet { public MovedFileSet() { OldFiles = new List<ManifestFileInfo>(); NewFiles = new List<ManifestFileInfo>(); } public List<ManifestFileInfo> OldFiles { private set; get; } public List<ManifestFileInfo> NewFiles { private set; get; } public List<ManifestFileInfo> SourceFiles { get { return OldFiles; } } public List<ManifestFileInfo> DestFiles { get { return NewFiles; } } } }
using System.IO; namespace DBRestorer.Ctrl.Domain { public class DbRestorOptVm : ViewModelBaseEx { private string _RelocateLdfTo; private string _RelocateMdfTo; private string _SrcPath; private string _TargetDbName; public string SrcPath { get => _SrcPath; set { RaiseAndSetIfChanged(ref _SrcPath, value); if (string.IsNullOrEmpty(_SrcPath)) { return; } var fileName = Path.GetFileNameWithoutExtension(_SrcPath); TargetDbName = fileName; } } public string TargetDbName { get => _TargetDbName; set { _TargetDbName = value; RaisePropertyChanged(); if (!string.IsNullOrWhiteSpace(value) && !string.IsNullOrWhiteSpace(_SrcPath)) { var dir = Path.GetDirectoryName(_SrcPath); RelocateLdfTo = Path.Combine(dir, TargetDbName + "_log.ldf"); RelocateMdfTo = Path.Combine(dir, TargetDbName + ".mdf"); } } } public string RelocateMdfTo { get => _RelocateMdfTo; set { _RelocateMdfTo = value; RaisePropertyChanged(); } } public string RelocateLdfTo { get => _RelocateLdfTo; set { _RelocateLdfTo = value; RaisePropertyChanged(); } } public ISqlServerUtil.DbRestorOptions GetDbRestoreOption(string serverInstName) { return new ISqlServerUtil.DbRestorOptions { SqlServerInstName = serverInstName, RelocateMdfTo = RelocateMdfTo, RelocateLdfTo = RelocateLdfTo, SrcPath = SrcPath, TargetDbName = TargetDbName }; } } }
using System; namespace Aspor.Streaming.Core.Attributes { [AttributeUsage(AttributeTargets.Method)] public class DisableStreamAttribute : Attribute { public DisableStreamAttribute() {} } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class NameManager : MonoBehaviour { public GameObject blackPanel; public GameObject nameMenu; public Text inputField; public Text userName; private string name; // Start is called before the first frame update void Start() { //blackPanel.SetActive(false); nameMenu.SetActive(false); userName.text = ProgressManager.Instance.GetName(); } public void SetActiveNamePanel(bool active) { nameMenu.SetActive(active); blackPanel.SetActive(active); } public void StoreName() { name = inputField.text; userName.text = name; ProgressManager.Instance.SetName(name); SetActiveNamePanel(false); } }
using AutoMapper; using JetBrains.Annotations; using Litium.Accelerator.Builders; using Litium.Customers; using Litium.Runtime.AutoMapper; using Litium.Web.Models.Websites; namespace Litium.Accelerator.ViewModels.MyPages { public class LoginInfoViewModel : IAutoMapperConfiguration, IViewModel { public ChangeUserNameFormViewModel UserNameForm { get; set; } = new ChangeUserNameFormViewModel(); public ChangePasswordFormViewModel PasswordForm { get; set; } = new ChangePasswordFormViewModel(); public bool IsSystemAccount { get; set; } [UsedImplicitly] void IAutoMapperConfiguration.Configure(IMapperConfigurationExpression cfg) { cfg.CreateMap<PageModel, LoginInfoViewModel>(); cfg.CreateMap<Person, LoginInfoViewModel>() .ForMember(x => x.UserNameForm, m => m.MapFrom(person => person.MapTo<ChangeUserNameFormViewModel>())); } } }
namespace CustomerManager.ViewModel { using CustomerManager.Common; using CustomerManager.DataModel; using WebApi.Models; public class NewCustomerViewModel : BindableBase { public NewCustomerViewModel() { this.Customer = new CustomerViewModel(); } public CustomerViewModel Customer { get; set; } public void CreateCustomer() { CustomersWebApiClient.CreateCustomer(new Customer { Name = this.Customer.Name, Phone = this.Customer.Phone, Address = this.Customer.Address, Email = this.Customer.Email, Company = this.Customer.Company, Title = this.Customer.Title, Image = this.Customer.ImagePath }); } } }
using System; using Cirrious.MvvmCross.ViewModels; using Cirrious.CrossCore; using MvxPageDemo.ViewModels; namespace MvxPageDemo.Shared { public class App : MvxApplication { public App () { } public override void Initialize () { base.Initialize (); //Start RegisterAppStart<StartViewModel> (); } } }
// // Copyright Seth Hendrick 2016-2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // using System.Text.RegularExpressions; namespace Chaskis.Plugins.MeetBot { public static class Regexes { // ---------------- Fields ---------------- internal static readonly Regex MeetBotRootConfigVariable = new Regex( "{%meetbotroot%}", RegexOptions.Compiled | RegexOptions.ExplicitCapture ); internal static readonly Regex TimeStampConfigVariable = new Regex( "{%timestamp%}", RegexOptions.Compiled | RegexOptions.ExplicitCapture ); internal static readonly Regex MeetingTopicConfigVariable = new Regex( "{%meetingtopic%}", RegexOptions.Compiled | RegexOptions.ExplicitCapture ); internal static readonly Regex ChannelConfigVariable = new Regex( "{%channel%}", RegexOptions.Compiled | RegexOptions.ExplicitCapture ); internal static readonly Regex GeneratorTypeConfigVariable = new Regex( "{%generatortype%}", RegexOptions.Compiled | RegexOptions.ExplicitCapture ); internal static readonly Regex FileNameConfigVariable = new Regex( "{%filename%}", RegexOptions.Compiled | RegexOptions.ExplicitCapture ); internal static readonly Regex FullFilePathConfigVariable = new Regex( "{%fullfilepath%}", RegexOptions.Compiled | RegexOptions.ExplicitCapture ); } }
namespace RpcNet.Internal { using System; using System.Net; using System.Net.Sockets; using System.Threading; // Public for tests public class RpcTcpConnection : IDisposable { private readonly Caller caller; private readonly ILogger logger; private readonly TcpReader reader; private readonly ReceivedRpcCall receivedCall; private readonly Thread receivingThread; private readonly IPEndPoint remoteIpEndPoint; private readonly Socket tcpClient; private readonly TcpWriter writer; private volatile bool stopReceiving; public RpcTcpConnection( Socket tcpClient, int program, int[] versions, Action<ReceivedRpcCall> receivedCallDispatcher, ILogger logger = default) { this.tcpClient = tcpClient; this.remoteIpEndPoint = (IPEndPoint)tcpClient.RemoteEndPoint; this.caller = new Caller(this.remoteIpEndPoint, Protocol.Tcp); this.reader = new TcpReader(tcpClient, logger); this.writer = new TcpWriter(tcpClient, logger); this.logger = logger; this.receivedCall = new ReceivedRpcCall( program, versions, this.reader, this.writer, receivedCallDispatcher); this.receivingThread = new Thread(this.Receiving) { IsBackground = true, Name = $"RpcNet TCP Connection {this.remoteIpEndPoint}" }; this.receivingThread.Start(); } public bool IsFinished { get; private set; } public void Dispose() { this.stopReceiving = true; this.tcpClient.Dispose(); this.receivingThread.Join(); } private void Receiving() { try { while (!this.stopReceiving) { NetworkReadResult readResult = this.reader.BeginReading(); if (readResult.HasError) { this.logger?.Trace( $"Could not read data from {this.caller}. " + $"Socket error: {readResult.SocketError}."); this.IsFinished = true; return; } if (readResult.IsDisconnected) { this.logger?.Trace($"{this.caller} disconnected."); this.IsFinished = true; return; } this.writer.BeginWriting(); this.receivedCall.HandleCall(this.caller); this.reader.EndReading(); NetworkWriteResult writeResult = this.writer.EndWriting(this.remoteIpEndPoint); if (writeResult.HasError) { this.logger?.Trace( $"Could not write data to {this.caller}. " + $"Socket error: {writeResult.SocketError}."); this.IsFinished = true; return; } } } catch (Exception e) { this.logger?.Error($"Unexpected exception in connection to {this.caller}: {e}"); } } } }
using System; abstract class Foo { public abstract int Bar { get; } public abstract string Baz { get; set; } public abstract string Gazonk { set; } } abstract class Bar { public abstract Foo this [int a, string s] { set; } } class Baz { public string Bingo { get; set; } }
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VectorEngine.DemoGame.Shapes; using VectorEngine; using VectorEngine.Extras; using VectorEngine.DemoGame.DemoGame.Shapes; namespace VectorEngine.DemoGame { public class SceneTechSphere { public static void Init() { // Order maters here. It's the execution order. // "Update" systems: EntityAdmin.Instance.Systems.Add(new GamepadSystem()); EntityAdmin.Instance.Systems.Add(new GamepadBasicFPSMovementSystem()); EntityAdmin.Instance.Systems.Add(new RotateSystem()); EntityAdmin.Instance.Systems.Add(new CurlyCircleSystem()); // "Draw" systems: EntityAdmin.Instance.Systems.Add(new CameraSystem()); EntityAdmin.Instance.Systems.Add(new SamplerSystem()); //EntityAdmin.Instance.CreateCommonSingletons(); // Create scene objects // Order *kinda* matters here: it's the draw order for Shapes var cameraEntity = EntityAdmin.Instance.CreateEntity("Camera"); EntityAdmin.Instance.AddComponent<Transform>(cameraEntity).LocalPosition = new Vector3(0, 0, 3f); var camera = EntityAdmin.Instance.AddComponent<Camera>(cameraEntity); camera.ProjectionType = Camera.ProjectionTypeEnum.Perspective; EntityAdmin.Instance.AddComponent<GamepadBasicFPSMovement>(cameraEntity); var shape = EntityAdmin.Instance.CreateEntity("shape"); EntityAdmin.Instance.AddComponent<Transform>(shape).LocalPosition = new Vector3(0, 0, 0); EntityAdmin.Instance.AddComponent<DemoShape>(shape); } } }
using System; namespace Neutronium.MVVMComponents.Relay { /// <summary> /// ISimpleCommand implementation based on action with no argument /// <seealso cref="ISimpleCommand"/> /// </summary> public class RelaySimpleCommand : ISimpleCommand { private readonly Action _Do; public RelaySimpleCommand(Action doAction) { _Do = doAction; } public void Execute(object argument) { _Do(); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; namespace Marble.Benchmarks.Common { [SimpleJob(RuntimeMoniker.NetCoreApp31)] [MarkdownExporterAttribute.GitHub] [MeanColumn, MemoryDiagnoser] public class Dictionaries { [Params(10, 100, 1000)] public int Count; private KeyValuePair<Type, int>[] _data; private ConcurrentDictionary<Type, int> _concurrent; private Dictionary<Type, int> _regular; [GlobalSetup] public void Init() { _data = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(assembly => assembly.DefinedTypes) .Take(Count) .Select(type => new KeyValuePair<Type, int>(type, type.GetHashCode() % 100)) .ToArray(); _concurrent = new ConcurrentDictionary<Type, int>(); _regular = new Dictionary<Type, int>(); } [Benchmark(Baseline = true)] public int Concurrent() { var sum = 0; foreach (var (key, value) in _data) { sum += _concurrent.GetOrAdd(key, value); } return sum; } [Benchmark] public int Regular() { var dictionary = _regular; var sum = 0; foreach (var (key, value) in _data) { if (dictionary.TryGetValue(key, out var exists)) { sum += exists; continue; } var lockTaken = false; Monitor.Enter(dictionary, ref lockTaken); dictionary[key] = value; if (lockTaken) Monitor.Exit(dictionary); sum += value; } return sum; } [GlobalCleanup] public void Cleanup() { _concurrent.Clear(); _concurrent = new ConcurrentDictionary<Type, int>(); _regular.Clear(); _regular = new Dictionary<Type, int>(); } } }
public abstract class Machine { private string id; protected Machine(string id) { this.id = id; } public string Id => id; }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Torch.Managers.PatchManager { internal static class NativeLibrary { private static readonly HashSet<PlatformID> WindowsPlatformIDSet = new HashSet<PlatformID> { PlatformID.Win32NT, PlatformID.Win32S, PlatformID.Win32Windows, PlatformID.WinCE }; public static bool IsWindows { get { return WindowsPlatformIDSet.Contains(Environment.OSVersion.Platform); } } [Flags] public enum Protection { PAGE_NOACCESS = 0x01, PAGE_READONLY = 0x02, PAGE_READWRITE = 0x04, PAGE_WRITECOPY = 0x08, PAGE_EXECUTE = 0x10, PAGE_EXECUTE_READ = 0x20, PAGE_EXECUTE_READWRITE = 0x40, PAGE_EXECUTE_WRITECOPY = 0x80, PAGE_GUARD = 0x100, PAGE_NOCACHE = 0x200, PAGE_WRITECOMBINE = 0x400 } [DllImport("kernel32.dll")] public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, Protection flNewProtect, out Protection lpflOldProtect); } }
using Microsoft.AspNetCore.Mvc; namespace RSql4Net.Tests.Controllers { public class MockController : Controller { } }
using Bake.API.ScriptTaskFactory; using Bake.API.Task; using Cake.Core.IO; using System.Collections.Generic; using Bake.Cake.Build.Task; namespace Bake.Cake.Build.TaskFactory.Project { public class WebDriverTestsFactory : AbstractProjectScriptTaskFactory { public override bool IsApplicable(ProjectInfo projectInfo) { return projectInfo.IsUnitTestProject() && projectInfo.IsWebDriverProject(); } public override IEnumerable<ITask> Create(ProjectInfo projectInfo) { return new List<ITask> { new MsBuildTask( taskType: MsBuildTask.MsBuildTaskType.UiTests, sourceFiles: new List<FilePath> { projectInfo.Path }, projectName: projectInfo.Name) }; } } }
 namespace ChessCompStompWithHacksLibrary { using ChessCompStompWithHacksEngine; using DTLibrary; using System; using System.Collections.Generic; public class ObjectivesScreenDisplay { private ObjectiveDisplay objectiveDisplay; private HashSet<Objective> completedObjectives; public ObjectivesScreenDisplay(SessionState sessionState) { this.objectiveDisplay = new ObjectiveDisplay(); this.completedObjectives = sessionState.GetCompletedObjectives(); } private bool HasCompletedAtLeastOneHiddenObjective() { return this.GetCompletedHiddenObjectives().Count > 0; } private List<Objective> GetCompletedHiddenObjectives() { List<Objective> completedHiddenObjectives = new List<Objective>(); foreach (Objective completedObjective in this.completedObjectives) { if (completedObjective.IsHiddenObjective()) completedHiddenObjectives.Add(completedObjective); } return completedHiddenObjectives; } public void Render(IDisplayOutput<ChessImage, ChessFont> displayOutput) { displayOutput.DrawText( x: 389, y: 675, text: "Objectives", font: ChessFont.ChessFont32Pt, color: DTColor.Black()); int row1Y; int row2Y; int row3Y; List<Objective> completedHiddenObjectives = this.GetCompletedHiddenObjectives(); completedHiddenObjectives.Sort(comparer: new ObjectiveUtil.ObjectiveComparer()); if (this.HasCompletedAtLeastOneHiddenObjective()) { row1Y = 520; row2Y = row1Y - 110; row3Y = row2Y - 110; } else { row1Y = 450; row2Y = row1Y - 130; row3Y = row2Y - 130; } this.objectiveDisplay.RenderNonFinalObjective( x: 62, y: row1Y, objective: Objective.DefeatComputer, completedObjectives: this.completedObjectives, displayOutput: displayOutput); this.objectiveDisplay.RenderNonFinalObjective( x: 375, y: row1Y, objective: Objective.DefeatComputerByPlayingAtMost25Moves, completedObjectives: this.completedObjectives, displayOutput: displayOutput); this.objectiveDisplay.RenderNonFinalObjective( x: 687, y: row1Y, objective: Objective.DefeatComputerWith5QueensOnTheBoard, completedObjectives: this.completedObjectives, displayOutput: displayOutput); this.objectiveDisplay.RenderNonFinalObjective( x: 62, y: row2Y, objective: Objective.CheckmateUsingAKnight, completedObjectives: this.completedObjectives, displayOutput: displayOutput); this.objectiveDisplay.RenderNonFinalObjective( x: 375, y: row2Y, objective: Objective.PromoteAPieceToABishop, completedObjectives: this.completedObjectives, displayOutput: displayOutput); this.objectiveDisplay.RenderNonFinalObjective( x: 687, y: row2Y, objective: Objective.LaunchANuke, completedObjectives: this.completedObjectives, displayOutput: displayOutput); if (completedHiddenObjectives.Count >= 1) this.objectiveDisplay.RenderNonFinalObjective( x: 62, y: row3Y, objective: completedHiddenObjectives[0], completedObjectives: this.completedObjectives, displayOutput: displayOutput); if (completedHiddenObjectives.Count >= 2) this.objectiveDisplay.RenderNonFinalObjective( x: 375, y: row3Y, objective: completedHiddenObjectives[1], completedObjectives: this.completedObjectives, displayOutput: displayOutput); if (completedHiddenObjectives.Count >= 3) this.objectiveDisplay.RenderNonFinalObjective( x: 687, y: row3Y, objective: completedHiddenObjectives[2], completedObjectives: this.completedObjectives, displayOutput: displayOutput); if (completedHiddenObjectives.Count >= 4) throw new Exception(); this.objectiveDisplay.RenderFinalObjective( x: 250, y: 190, completedObjectives: this.completedObjectives, displayOutput: displayOutput); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BusRouteHCM.Code { public class StationLabel { private string _stationName; private double _distanceFromStart; private int _nStop; private string _busName; private string _previousBus; public StationLabel() { _nStop = 1; } public string StationName { get { return _stationName; } set { _stationName = value; } } public double DistanceFromStart { get { return _distanceFromStart; } set { _distanceFromStart = value; } } public int NumberBusStop { get { return _nStop; } set { _nStop = value; } } public string BusName { get { return _busName; } set { _busName = value; } } public string PreviousBus { get { return _previousBus; } set { _previousBus = value; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MiniMouse : MonoBehaviour { public static List<MiniMouse> all = new List<MiniMouse>(); public static float maxDistance = 5f; public float moveSpeed = 5f; float currentDistance; float direction = 1f; void OnEnable() { all.Add(this); } void OnDisable() { all.Remove(this); } void Start() { currentDistance = Random.Range(-maxDistance/2f, maxDistance/2f); } void FixedUpdate() { var deltaD = Time.fixedDeltaTime * maxDistance * direction; currentDistance += deltaD; transform.localPosition += new Vector3(deltaD,0,0); if (Mathf.Abs(currentDistance) >= maxDistance) { direction *= -1f; currentDistance = 0f; } } public void Kill() { gameObject.SetActive(false); } }
using System.ComponentModel.DataAnnotations; using ChatWithMe.Web.ValidationAttributes; namespace ChatWithMe.Web.Models.Auth { public class ChangePasswordViewModel { [Required(ErrorMessage = "Old password is required")] public string OldPassword { get; set; } [Required(ErrorMessage = "New password is required")] [NotEqual("OldPassword", ErrorMessage = "New password is equal to old password")] public string NewPassword { get; set; } } }
using Faker; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Watchster.Application.Interfaces; using Watchster.Domain.Entities; namespace Watchster.Application.UnitTests.Fakes { public class FakeMovieRepository : IMovieRepository, IQueryable<Movie> { private List<Movie> entities = null; public FakeMovieRepository(IEnumerable<Movie> collection) { this.entities = new List<Movie>(collection); } public IEnumerator<Movie> GetEnumerator() { return entities.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return entities.GetEnumerator(); } public Task<Movie> AddAsync(Movie entity) { entities.Add(entity); return Task.Run(() => entity); } public Task<Movie> UpdateAsync(Movie entity) { throw new NotImplementedException(); } public Task<Movie> Delete(Movie entity) { throw new NotImplementedException(); } public Task<IEnumerable<Movie>> GetAllAsync() { throw new NotImplementedException(); } public Task<Movie> GetByIdAsync(int id) { if (id <= 0) { return Task.Run(() => default(Movie)); } else { return Task.Run(() => new Movie() { Id = RandomNumber.Next(0, int.MaxValue), Genres = Lorem.Sentence(), Overview = Lorem.Sentence(), Popularity = RandomNumber.Next(0, int.MaxValue), PosterUrl = Internet.Url(), ReleaseDate = DateTime.Now, Title = Lorem.Sentence(), TMDbId = RandomNumber.Next(0, int.MaxValue), TMDbVoteAverage = RandomNumber.Next(0, 10), }); } } public IQueryable<Movie> Query() { return entities.AsQueryable(); } public IQueryable<Movie> Query(Expression<Func<Movie, bool>> expression) { return entities.Where(expression.Compile()).AsQueryable(); } public Task<IList<Movie>> GetMoviesFromPage(int page) { throw new NotImplementedException(); } public Task<int> GetTotalPages() { throw new NotImplementedException(); } public Type ElementType { get { return this.entities.AsQueryable().ElementType; } } public Expression Expression { get { return this.entities.AsQueryable().Expression; } } public IQueryProvider Provider { get { return this.entities.AsQueryable().Provider; } } } }
using System; using System.Linq; using GameOfLife.Lib; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace GameOfLifeTests { [TestClass] public class ConwayLifeRulesTests { [TestMethod] public void Case_Cell_ChouldDeadThenLessThanTwoNeigbours() { var initialState = CellState.Alive; var state1 = LifeEngineRules.NextState(initialState, 1); var state2 = LifeEngineRules.NextState(initialState, 0); var expected = new[] { state1, state2 }; var actual = new[] { CellState.Dead, CellState.Dead }; Assert.IsTrue(Enumerable.SequenceEqual<CellState>(expected, actual)); } [TestMethod] public void Case_Cell_ChouldBeAliveThenNeigboursCountBetweenTwoOrThree() { var initialState = CellState.Alive; var state1 = LifeEngineRules.NextState(initialState, 2); var state2 = LifeEngineRules.NextState(initialState, 3); var expected = new[] { state1, state2 }; var actual = new[] { CellState.Alive, CellState.Alive }; Assert.IsTrue(Enumerable.SequenceEqual<CellState>(expected, actual)); } [TestMethod] public void Case_Cell_ChouldBeDeadThenNeigboursCountMoreThanThree() { var rand = new Random(System.DateTime.Now.Second); var initialState = CellState.Alive; var state1 = LifeEngineRules.NextState(initialState, rand.Next(4, int.MaxValue)); var state2 = LifeEngineRules.NextState(initialState, rand.Next(4, int.MaxValue)); var expected = new[] { state1, state2 }; var actual = new[] { CellState.Dead, CellState.Dead }; Assert.IsTrue(Enumerable.SequenceEqual<CellState>(expected, actual)); } [TestMethod] public void Case_DeadCell_ChouldBeAlibeThenNeigboursCountEqualsThree() { var initialState = CellState.Dead; var state1 = LifeEngineRules.NextState(initialState, 3); Assert.AreEqual(state1, CellState.Alive); } [TestMethod] public void Case_DeadCell_ChouldBeDeadThenNeigboursCountLessThree() { var initialState = CellState.Dead; var state1 = LifeEngineRules.NextState(initialState, 2); Assert.AreEqual(state1, CellState.Dead); } } }
// Copyright 2014 Adrian Chlubek. This file is part of GTA Multiplayer IV project. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. using MIVSDK; using MIVServer; using SharpDX; using System; using System.Linq; namespace EmptyGamemode { public class EmptyGamemode : Gamemode { public EmptyGamemode(ServerApi a) : base(a) { Console.WriteLine("Empty gamemode started"); api.onPlayerConnect += api_onPlayerConnect; api.onPlayerDisconnect += api_onPlayerDisconnect; api.onPlayerDie += api_onPlayerDie; api.onPlayerEnterVehicle += api_onPlayerEnterVehicle; api.onPlayerExitVehicle += api_onPlayerExitVehicle; api.onPlayerKeyDown += api_onPlayerKeyDown; api.onPlayerKeyUp += api_onPlayerKeyUp; api.onPlayerPause += api_onPlayerPause; api.onPlayerResume += api_onPlayerResume; api.onPlayerSendCommand += api_onPlayerSendCommand; api.onPlayerSendText += api_onPlayerSendText; api.onPlayerSpawn += api_onPlayerSpawn; api.onPlayerTakeDamage += api_onPlayerTakeDamage; api.onPlayerUpdate += api_onPlayerUpdate; } void api_onPlayerWriteConsole(ServerPlayer player, string text) { } void api_onPlayerUpdate(ServerPlayer player) { } void api_onPlayerTakeDamage(ServerPlayer player, int before, int after, int delta) { } void api_onPlayerSpawn(ServerPlayer player) { } void api_onPlayerSendText(ServerPlayer player, string text) { api.writeChat(player.Nick + "(" + player.id + "): " + text); } void api_onPlayerSendCommand(ServerPlayer player, string command, string[] param) { } void api_onPlayerResume(ServerPlayer player) { } void api_onPlayerPause(ServerPlayer player) { } void api_onPlayerKeyUp(ServerPlayer player, int key) { } void api_onPlayerKeyDown(ServerPlayer player, int key) { } void api_onPlayerExitVehicle(ServerPlayer player, ServerVehicle vehicle) { } void api_onPlayerEnterVehicle(ServerPlayer player, ServerVehicle vehicle) { } void api_onPlayerDie(ServerPlayer player, ServerPlayer killer = null, Enums.Weapon weapon = Enums.Weapon.None) { } void api_onPlayerDisconnect(ServerPlayer player) { } void api_onPlayerConnect(System.Net.EndPoint address, ServerPlayer player) { } } }
using System; namespace Adaptive.ReactiveTrader.Shared.Logging { public class DebugLoggerFactory : ILoggerFactory { public ILog Create(Type type) { return new DebugLogger(type.Name); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace ExtractIpInWinform { public partial class Form1 : Form { public Form1() { InitializeComponent(); lv_ipResult.View = View.Details; lv_ipResult.Columns.Add("IP"); lv_ipResult.Columns.Add("IP의 개수"); } private void btn_FileOpen_Clicked(object sender, EventArgs e) { OpenFileDialog OpenFileDlg = new OpenFileDialog(); OpenFileDlg.Title = "파일 열기"; OpenFileDlg.InitialDirectory = "C:\\"; OpenFileDlg.DefaultExt = "*.*"; OpenFileDlg.Filter = "All Files (*.*) | *.*"; if(OpenFileDlg.ShowDialog() == DialogResult.OK) { IpResult(OpenFileDlg.FileName); } } /// <summary> /// 함수 이름 : IpResult /// 기 능 : 로그 파일에서 IP 값과 IP 개수를 추출하여 폼에 출력한다. /// 입 력 : 로그 파일 이름 /// 출 력 : 없음 /// </summary> private void IpResult(string FileName) { ListViewItem Lvi; // 둘째 열부터 들어갈 데이터들을 담는 객체 string[] Lines; // 로그 한 줄씩 담은 배열 List<IpList> IpDatas; // IP와 IP 개수를 담은 리스트 Lines = System.IO.File.ReadAllLines(FileName); IpDatas = ExtractIp(Lines); // IP 목록을 초기화한다. if (listBox1.Items.Count != 0) listBox1.Items.Clear(); // IP 목록을 표시한다. for (int i = 0; i < IpDatas.Count; i++) { listBox1.Items.Add(IpDatas[i].Ip); } // 결과를 초기화한다. if (lv_ipResult.Items.Count != 0) lv_ipResult.Items.Clear(); // 결과를 List View에 표시 for (int i = 0; i < IpDatas.Count; i++) { Lvi = new ListViewItem(IpDatas[i].Ip); Lvi.SubItems.Add(IpDatas[i].Count); lv_ipResult.Items.Add(Lvi); } } /// <summary> ///함수 이름 : ExtractIp ///기 능 : IP를 추출하고 추출한 Ip들의 개수를 센다. ///입 력 : 한 줄 로그들 ///출 력 : IP 데이터들 /// </summary> public List<IpList> ExtractIp(string[] Lines) { List<IpList> IpDatas = new List<IpList>(); // IP 목록 - IP 값, IP의 개수 string Pattern = @"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"; List<IpList> IpValues = new List<IpList>(); // IP 값들 foreach (string line in Lines) { Match m = Regex.Match(line, Pattern); while (m.Success) { IpValues.Add(new IpList() { Ip = m.Value }); m = m.NextMatch(); } } // IP 목록을 구한다. IpDatas = IpValues.GroupBy(IpList => IpList.Ip) .Select(g => new IpList { Ip = g.Key, Count = g.Count().ToString() }).ToList(); return IpDatas; } } public class IpList { public string Ip { get; set; } public string Count { get; set; } } }
using System.Collections.Generic; namespace Burpless.Configuration { public class DialectScenarioBuilder { private readonly Dictionary<KeywordType, string[]> _keywords; internal DialectScenarioBuilder(Dictionary<KeywordType, string[]> keywords) { _keywords = keywords; } public DialectScenarioBuilder Scenario(params string[] keywords) { _keywords[KeywordType.Scenario] = keywords; return this; } public DialectScenarioBuilder ScenarioOutline(params string[] keywords) { _keywords[KeywordType.ScenarioOutline] = keywords; return this; } public DialectScenarioBuilder Examples(params string[] keywords) { _keywords[KeywordType.Examples] = keywords; return this; } } }
using System; using System.Collections.Generic; namespace Necessity.UnitOfWork.Schema { public class PropertyColumnMap : Dictionary<string, Mapping> { public PropertyColumnMap() : base(StringComparer.OrdinalIgnoreCase) { } public PropertyColumnMap(Dictionary<string, Mapping> dict) : base(dict, StringComparer.OrdinalIgnoreCase) { } } }
 namespace Wechaty.Module.Filebox { public class FileBoxOptionsBuffer : FileBoxOptions { public override FileBoxType Type => FileBoxType.Buffer; public byte[] Buffer { get; set; } } }
using System.IO; using System.Linq; namespace PhaseShift.Tools.LibrarySorter { public class EmptyDirectoryCleaner : IDirectoryCleaner { public void ClearEmptyDirectories(DirectoryInfo directoryInfo) { CleanEmptyFoldersInDirectory(directoryInfo); } private void CleanEmptyFoldersInDirectory(DirectoryInfo directoryInfo) { if (directoryInfo.EnumerateFiles().Any()) return; foreach (var childDirectory in directoryInfo.EnumerateDirectories()) { CleanEmptyFoldersInDirectory(childDirectory); } if (!directoryInfo.EnumerateFileSystemInfos().Any()) { directoryInfo.Delete(); } } } }
using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; namespace Linearstar.Core.Calendar { public class CalendarValue { public IList<string> Value { get; set; } public IDictionary<string, IList<string>> Parameters { get; set; } public CalendarValue() => Parameters = new Dictionary<string, IList<string>>(); public CalendarValue(params string[] value) : this() { if (value != null && value.Length > 0 && value[0] != null) Value = value.ToList(); } public CalendarValue(IEnumerable<string> value) : this() => Value = value?.ToList(); protected string GetParameter([CallerMemberName] string propertyName = null) { propertyName = propertyName.ToUpper(); return Parameters.ContainsKey(propertyName) ? Parameters[propertyName].First() : null; } protected string SetParameter(string value, [CallerMemberName] string propertyName = null) => (Parameters[propertyName.ToUpper()] = new List<string> { value, }).First(); public static string EscapeValueString(string s) => s.Replace("\\", "\\\\") .Replace(";", "\\;") .Replace(",", "\\,") .Replace("\r\n", "\\n") .Replace("\n", "\\n"); public static string UnescapeValueString(string s) => s.Replace("\\;", ";") .Replace("\\,", ",") .Replace("\\n", "\r\n") .Replace("\\\\", "\\"); public static CalendarValue Parse(IEnumerable<string> value, ILookup<string, string> parameters) => new CalendarValue(value) { Parameters = parameters.ToDictionary(_ => _.Key, _ => (IList<string>)_.ToList()), }; } }
namespace Microsoft.SilverlightMediaFramework.Plugins.Monitoring.Logs { /// <summary> /// The audio track has been changed to a different language /// </summary> public class AudioTrackChangedLog : VideoEventLog { public AudioTrackChangedLog(string Language) : base(VideoLogTypes.AudioTrackSelect) { this.Language = Language; } /// <summary> /// The language chosen. /// </summary> public string Language { get { return GetRefValue<string>(VideoLogAttributes.Language); } set { SetRefValue<string>(VideoLogAttributes.Language, value); } } } }
using System.Globalization; using System.Resources; using System.Threading; namespace NuGet.CommandLine { internal static class LocalizedResourceManager { private static readonly ResourceManager _resourceManager = new ResourceManager("NuGet.CommandLine.NuGetResources", typeof(LocalizedResourceManager).Assembly); public static string GetString(string resourceName) { var culture = GetLanguageName(); return _resourceManager.GetString(resourceName + '_' + culture, CultureInfo.InvariantCulture) ?? _resourceManager.GetString(resourceName, CultureInfo.InvariantCulture); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "the convention is to used lower case letter for language name.")] /// <summary> /// Returns the 3 letter language name used to locate localized resources. /// </summary> /// <returns>the 3 letter language name used to locate localized resources.</returns> public static string GetLanguageName() { var culture = Thread.CurrentThread.CurrentUICulture; while (!culture.IsNeutralCulture) { if (culture.Parent == culture) { break; } culture = culture.Parent; } return culture.ThreeLetterWindowsLanguageName.ToLowerInvariant(); } } }
using Atk.DataPortal; using Atk.DataPortal.Core; namespace DemoTools.BLL.DemoNorthwind { /// <summary> /// 订单 数据访问接口定义 /// AzItem:业务实例 /// </summary> public interface IAzOrdersDal { void DB_Insert(AzOrdersEntity azItem); void DB_Update(AzOrdersEntity azItem); void DB_Delete(AzOrdersEntity azItem); void DB_Fetch(AzOrdersEntity azItem); void DB_FetchList(AzOrdersListEntity azItems); } }
/* Exemplary file for Chapter 4 - Dictionaries and Sets. */ namespace SetPools { public enum PoolTypeEnum { RECREATION, COMPETITION, THERMAL, KIDS }; }
#region License // // PackageMatcher.cs May 2007 // // Copyright (C) 2007, Niall Gallagher <niallg@users.sf.net> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // #endregion #region Using directives using System.Collections.Generic; using System; #endregion package SimpleFramework.Xml.transform; /// <summary> /// The <c>PackageMatcher</c> object is used to match the stock /// transforms to Java packages. This is used to match useful types /// from the <c>java.lang</c> and <c>java.util</c> packages /// as well as other Java packages. This matcher groups types by their /// package names and attempts to search the stock transforms for a /// suitable match. If no match can be found this throws an exception. /// </summary> /// @author Niall Gallagher /// <seealso> /// SimpleFramework.Xml.transform.DefaultMatcher /// </seealso> class PackageMatcher : Matcher { /// <summary> /// Constructor for the <c>PackageMatcher</c> object. The /// package matcher is used to resolve a transform instance to /// convert object types to an from strings. If a match cannot /// be found with this matcher then an exception is thrown. /// </summary> public PackageMatcher() { super(); } /// <summary> /// This method attempts to perform a resolution of the transform /// based on its package prefix. This allows this matcher to create /// a logical group of transforms within a single method based on /// the types package prefix. If no transform can be found then /// this will throw an exception. /// </summary> /// <param name="type"> /// this is the type to resolve a transform for /// </param> /// <returns> /// the transform that is used to transform that type /// </returns> public Transform Match(Class type) { String name = type.getName(); if(name.startsWith("java.lang")) { return MatchLanguage(type); } if(name.startsWith("java.util")) { return MatchUtility(type); } if(name.startsWith("java.net")) { return MatchURL(type); } if(name.startsWith("java.io")) { return MatchFile(type); } if(name.startsWith("java.sql")) { return MatchSQL(type); } if(name.startsWith("java.math")) { return MatchMath(type); } return MatchEnum(type); } /// <summary> /// This is used to resolve <c>Transform</c> implementations /// that are <c>Enum</c> implementations. If the type is not /// an enumeration then this will return null. /// </summary> /// <param name="type"> /// this is the type to resolve a stock transform for /// </param> /// <returns> /// this will return a transform for the specified type /// </returns> public Transform MatchEnum(Class type) { if(type.isEnum()) { return new EnumTransform(type); } return null; } /// <summary> /// This is used to resolve <c>Transform</c> implementations /// that relate to the <c>java.lang</c> package. If the type /// does not resolve to a valid transform then this method will /// throw an exception to indicate that no stock transform exists /// for the specified type. /// </summary> /// <param name="type"> /// this is the type to resolve a stock transform for /// </param> /// <returns> /// this will return a transform for the specified type /// </returns> public Transform MatchLanguage(Class type) { if(type == Boolean.class) { return new BooleanTransform(); } if(type == Integer.class) { return new IntegerTransform(); } if(type == Long.class) { return new LongTransform(); } if(type == Double.class) { return new DoubleTransform(); } if(type == Float.class) { return new FloatTransform(); } if(type == Short.class) { return new ShortTransform(); } if(type == Byte.class) { return new ByteTransform(); } if(type == Character.class) { return new CharacterTransform(); } if(type == String.class) { return new StringTransform(); } if(type == Class.class) { return new ClassTransform(); } return null; } /// <summary> /// This is used to resolve <c>Transform</c> implementations /// that relate to the <c>java.math</c> package. If the type /// does not resolve to a valid transform then this method will /// throw an exception to indicate that no stock transform exists /// for the specified type. /// </summary> /// <param name="type"> /// this is the type to resolve a stock transform for /// </param> /// <returns> /// this will return a transform for the specified type /// </returns> public Transform MatchMath(Class type) { if(type == BigDecimal.class) { return new BigDecimalTransform(); } if(type == BigInteger.class) { return new BigIntegerTransform(); } return null; } /// <summary> /// This is used to resolve <c>Transform</c> implementations /// that relate to the <c>java.util</c> package. If the type /// does not resolve to a valid transform then this method will /// throw an exception to indicate that no stock transform exists /// for the specified type. /// </summary> /// <param name="type"> /// this is the type to resolve a stock transform for /// </param> /// <returns> /// this will return a transform for the specified type /// </returns> public Transform MatchUtility(Class type) { if(type == Date.class) { return new DateTransform(type); } if(type == Locale.class) { return new LocaleTransform(); } if(type == Currency.class) { return new CurrencyTransform(); } if(type == GregorianCalendar.class) { return new GregorianCalendarTransform(); } if(type == TimeZone.class) { return new TimeZoneTransform(); } return null; } /// <summary> /// This is used to resolve <c>Transform</c> implementations /// that relate to the <c>java.sql</c> package. If the type /// does not resolve to a valid transform then this method will /// throw an exception to indicate that no stock transform exists /// for the specified type. /// </summary> /// <param name="type"> /// this is the type to resolve a stock transform for /// </param> /// <returns> /// this will return a transform for the specified type /// </returns> public Transform MatchSQL(Class type) { if(type == Time.class) { return new DateTransform(type); } if(type == java.sql.Date.class) { return new DateTransform(type); } if(type == Timestamp.class) { return new DateTransform(type); } return null; } /// <summary> /// This is used to resolve <c>Transform</c> implementations /// that relate to the <c>java.io</c> package. If the type /// does not resolve to a valid transform then this method will /// throw an exception to indicate that no stock transform exists /// for the specified type. /// </summary> /// <param name="type"> /// this is the type to resolve a stock transform for /// </param> /// <returns> /// this will return a transform for the specified type /// </returns> public Transform MatchFile(Class type) { if(type == File.class) { return new FileTransform(); } return null; } /// <summary> /// This is used to resolve <c>Transform</c> implementations /// that relate to the <c>java.net</c> package. If the type /// does not resolve to a valid transform then this method will /// throw an exception to indicate that no stock transform exists /// for the specified type. /// </summary> /// <param name="type"> /// this is the type to resolve a stock transform for /// </param> /// <returns> /// this will return a transform for the specified type /// </returns> public Transform MatchURL(Class type) { if(type == URL.class) { return new URLTransform(); } return null; } } }
namespace AdsPortal.WebPortal.Models.Category { using AdsPortal.WebPortal.Models; using AdsPortal.WebPortal.Models.Base; using MagicOperations.Attributes; [OperationGroup(OperationGroups.Category)] [CreateOperation(ResponseType = typeof(IdResult), DisplayName = "Create category")] public class CreateCategory { public string? Name { get; set; } = string.Empty; public string? Description { get; set; } = string.Empty; } }
<style type="text/css"> .#@(Model.Prefix)form-spinner-up, .#@(Model.Prefix)form-spinner-down { font-size: 0; // prevents the spinner trigger from being to tall in IE } </style>
namespace BalanceCheck.ViewModels { public class IncomeVM { public int IncomeId { get; set; } public decimal IncomeValue { get; set; } public Boolean IsRepeated { get; set; } public DateTime IncomeDate { get; set; } public DateTime? EndIncomeDate { get; set; } } }
// <copyright file="TypeUtilTest.cs" company="Fubar Development Junker"> // Copyright (c) 2016 Fubar Development Junker. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using System; using System.Collections; using System.Collections.Generic; using NodaTime; using Xunit; namespace BeanIO.Internal.Util { public class TypeUtilTest { [Fact] public void TestToType() { Assert.Equal(typeof(string), "string".ToType()); Assert.Equal(typeof(bool), "bool".ToType()); Assert.Equal(typeof(byte), "byte".ToType()); Assert.Equal(typeof(sbyte), "sbyte".ToType()); Assert.Equal(typeof(char), "char".ToType()); Assert.Equal(typeof(char), "character".ToType()); Assert.Equal(typeof(short), "short".ToType()); Assert.Equal(typeof(ushort), "ushort".ToType()); Assert.Equal(typeof(int), "int".ToType()); Assert.Equal(typeof(int), "integer".ToType()); Assert.Equal(typeof(uint), "uint".ToType()); Assert.Equal(typeof(long), "long".ToType()); Assert.Equal(typeof(ulong), "ulong".ToType()); Assert.Equal(typeof(float), "float".ToType()); Assert.Equal(typeof(double), "double".ToType()); Assert.Equal(typeof(decimal), "decimal".ToType()); Assert.Equal(typeof(DateTime), "datetime".ToType()); Assert.Equal(typeof(DateTimeOffset), "datetimeoffset".ToType()); Assert.Equal(typeof(LocalDate), "date".ToType()); Assert.Equal(typeof(LocalTime), "time".ToType()); Assert.Equal(GetType(), "BeanIO.Internal.Util.TypeUtilTest, FubarDev.BeanIO.Test".ToType()); Assert.Equal(typeof(List<>), "System.Collections.Generic.List`1".ToType()); Assert.Equal(typeof(IList<>), "System.Collections.Generic.IList`1".ToType()); } [Fact] public void TestToTypeClassNotFound() { Assert.Null("BeanIO.Types.NoClass".ToType()); } [Fact] public void TestToAggregation() { Assert.Equal(typeof(IList), "list".ToAggregationType(null)); Assert.Equal(typeof(IList), "collection".ToAggregationType(null)); Assert.Equal(typeof(ISet<object>), "set".ToAggregationType(null)); Assert.Equal(typeof(Array), "array".ToAggregationType(null)); Assert.Equal(typeof(IList<>), "System.Collections.Generic.IList`1".ToAggregationType(null)); Assert.Equal(typeof(ArrayList).FullName, "System.Collections.ArrayList".ToAggregationType(null).FullName); Assert.Equal(typeof(IDictionary<,>), "map".ToAggregationType(null)); Assert.Equal(typeof(IDictionary<,>), "System.Collections.Generic.IDictionary`2".ToAggregationType(null)); Assert.Null("BeanIO.Types.NoClass".ToAggregationType(null)); } } }
using System; using Microsoft.SPOT; using Netduino.Foundation.Displays; using Microsoft.SPOT.Hardware; using SecretLabs.NETMF.Hardware.Netduino; using System.Threading; namespace PCD8544Sample { public class Program { public static void Main() { Debug.Print(Resources.GetString(Resources.StringResources.String1)); var display = new PCD8544(chipSelectPin: Pins.GPIO_PIN_D9, dcPin: Pins.GPIO_PIN_D8, resetPin: Pins.GPIO_PIN_D10, spiModule: SPI.SPI_module.SPI1); var gl = new GraphicsLibrary(display); gl.CurrentFont = new Font8x8(); gl.DrawText(0, 0, "PCD8544"); gl.CurrentFont = new Font4x8(); gl.DrawText(0, 10, "Nokia 3110 & 5110"); gl.DrawRectangle(20, 20, 10, 10); gl.DrawCircle(60, 30, 12, true, false); gl.Show(); Thread.Sleep(-1); } } }
using System.Collections.Generic; namespace Lithnet.ResourceManagement.Client.Help.Examples { class ResourceManagementClient_GetResourceByKeyExamples { #region GetResourceByKey(String, String, String) public ResourceObject GetPersonByUsername(string username) { ResourceManagementClient client = new ResourceManagementClient(); // Specify the list of attributes that we are interested in List<string> attributesToGet = new List<string>() { "DisplayName", "FirstName", "LastName" }; try { ResourceObject resource = client.GetResourceByKey("Person", "AccountName", username, attributesToGet); if (resource == null) { // The resource was not found, throw an exception throw new ResourceNotFoundException(); } return resource; } catch (TooManyResultsException) { // More than one match was found throw; } } #endregion #region GetResourceByKey(String, Dictionary{String, String}) public ResourceObject GetPersonByUsernameAndDomain(string username, string domain) { ResourceManagementClient client = new ResourceManagementClient(); Dictionary<string, object> anchorPairs = new Dictionary<string, object>(); anchorPairs.Add("AccountName", username); anchorPairs.Add("Domain", domain); // Specify the list of attributes that we are interested in List<string> attributesToGet = new List<string>() { "DisplayName", "FirstName", "LastName" }; try { ResourceObject resource = client.GetResourceByKey("Person", anchorPairs, attributesToGet); if (resource == null) { // The resource was not found, throw an exception throw new ResourceNotFoundException(); } return resource; } catch (TooManyResultsException) { // More than one match was found throw; } } #endregion } }
//----------------------------------------------------------------------- // <copyright> // Copyright (C) Ruslan Yakushev for the PHP Manager for IIS project. // // This file is subject to the terms and conditions of the Microsoft Public License (MS-PL). // See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; namespace Web.Management.PHP { public sealed class RemoteObjectCollection<T> : IRemoteObject, ICollection, IList<T> where T : IRemoteObject, new() { private List<T> _list; public RemoteObjectCollection(ArrayList sourceList) { if (sourceList != null) { Initialize(sourceList); } else { _list = new List<T>(); } } public RemoteObjectCollection() { _list = new List<T>(); } public int Count { get { return _list.Count; } } public bool IsReadOnly { get { return ((IList)_list).IsReadOnly; } } public T this[int index] { get { return _list[index]; } set { _list[index] = value; } } public void Add(T item) { _list.Add(item); } public void Clear() { _list.Clear(); } public bool Contains(T item) { return _list.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } public object GetData() { var items = new ArrayList(_list.Count); foreach (T item in _list) { items.Add(item.GetData()); } return items; } public IEnumerator<T> GetEnumerator() { return _list.GetEnumerator(); } public int IndexOf(T item) { return _list.IndexOf(item); } private void Initialize(ArrayList sourceList) { _list = new List<T>(sourceList.Count); foreach (object o in sourceList) { var item = new T(); item.SetData(o); _list.Add(item); } } public void Insert(int index, T item) { _list.Insert(index, item); } public bool Remove(T item) { return _list.Remove(item); } public void RemoveAt(int index) { _list.RemoveAt(index); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void SetData(object o) { Initialize((ArrayList)o); } #region ICollection Members void ICollection.CopyTo(Array array, int index) { ((ICollection)_list).CopyTo(array, index); } bool ICollection.IsSynchronized { get { return ((ICollection)_list).IsSynchronized; } } object ICollection.SyncRoot { get { return ((ICollection)_list).SyncRoot; } } #endregion } public interface IRemoteObject { object GetData(); void SetData(object o); } }
namespace ArdalisRating { public abstract class Rater { public ILogger Logger {get; set;} public Rater(ILogger logger) { this.Logger = logger; } public abstract decimal Rate(Policy policy); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RangoEnemigo2D : MonoBehaviour { public Animator ani; public Enemigo enemigo; void OnTriggerEnter2D(Collider2D coll) { if (coll.CompareTag("Player")) { ani.SetBool("walk", false); ani.SetBool("run", false); ani.SetBool("attack", true); enemigo.atacando = true; GetComponent<BoxCollider2D>().enabled = false; } } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
using Fambda.Contracts; using FluentAssertions; using Xunit; namespace Fambda.Tests.Contracts { public class ErrorTests { [Fact] public void GuardExceptionMustNotBeNullReturnsExpectedException() { // Arrange var expectedExceptionType = typeof(GuardExceptionMustNotBeNullException); // Act var exception = Error.GuardExceptionMustNotBeNull(); // Assert exception.Should().BeOfType(expectedExceptionType); } [Fact] public void OptionSomeValueMustNotBeNullReturnsExpectedException() { // Arrange var expectedExceptionType = typeof(OptionSomeValueMustNotBeNullException); // Act var exception = Error.OptionSomeValueMustNotBeNull(); // Assert exception.Should().BeOfType(expectedExceptionType); } [Fact] public void OptionValueMustNotBeNullReturnsExpectedException() { // Arrange var expectedExceptionType = typeof(OptionValueMustNotBeNullException); // Act var exception = Error.OptionValueMustNotBeNull(); // Assert exception.Should().BeOfType(expectedExceptionType); } [Fact] public void ExceptionalExceptionMustNotBeNullReturnsExpectedException() { // Arrange var expectedExceptionType = typeof(ExceptionalExceptionMustNotBeNullException); // Act var exception = Error.ExceptionalExceptionMustNotBeNull(); // Assert exception.Should().BeOfType(expectedExceptionType); } [Fact] public void EnumerationKeyMustNotBeNullReturnsExpectedException() { // Arrange var expectedExceptionType = typeof(EnumerationKeyMustNotBeNullException); // Act var exception = Error.EnumerationKeyMustNotBeNull(); // Assert exception.Should().BeOfType(expectedExceptionType); } [Fact] public void EnumerationKeyMustNotBeEmptyReturnsExpectedException() { // Arrange var expectedExceptionType = typeof(EnumerationKeyMustNotBeEmptyException); // Act var exception = Error.EnumerationKeyMustNotBeEmpty(); // Assert exception.Should().BeOfType(expectedExceptionType); } [Fact] public void EnumerationKeyMustNotBeWhiteSpaceReturnsExpectedException() { // Arrange var expectedExceptionType = typeof(EnumerationKeyMustNotBeWhiteSpaceException); // Act var exception = Error.EnumerationKeyMustNotBeWhiteSpace(); // Assert exception.Should().BeOfType(expectedExceptionType); } [Fact] public void EnumerationKeyMustNotContainLeadingSpaceReturnsExpectedException() { // Arrange var expectedExceptionType = typeof(EnumerationKeyMustNotContainLeadingSpaceException); // Act var exception = Error.EnumerationKeyMustNotContainLeadingSpace(); // Assert exception.Should().BeOfType(expectedExceptionType); } [Fact] public void EnumerationKeyMustNotContainTrailingSpaceReturnsExpectedException() { // Arrange var expectedExceptionType = typeof(EnumerationKeyMustNotContainTrailingSpaceException); // Act var exception = Error.EnumerationKeyMustNotContainTrailingSpace(); // Assert exception.Should().BeOfType(expectedExceptionType); } } }
using Microsoft.Owin.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SelfHost { public class OwinService { private IDisposable _webApp; public void Start() { // TODO:Mani following code required admin rights for vs // _webApp = WebApp.Start<ApiConfiguration>("http://+:9000"); _webApp = WebApp.Start<ApiConfiguration>("http://localhost:9000"); } public void Stop() { _webApp.Dispose(); } } }
using DN.WebApi.Application.Common.Interfaces; using FluentAssertions; using Xunit; namespace Infrastructure.Test.Caching; public abstract class CacheServiceTests<TCacheService> where TCacheService : ICacheService { private record TestRecord(Guid id, string stringValue, DateTime dateTimeValue); private static string _testKey = "testkey"; private static string _testValue = "testvalue"; protected abstract TCacheService CreateCacheService(); [Fact] public void GettingANonExistingValueReturnsNull() { var sut = CreateCacheService(); string? test = sut.Get<string>(_testKey); Assert.Null(test); } /// <summary> /// Sample Test Case using Fluent Assertions. /// </summary> /// <param name="testKey"></param> /// <param name="testValue"></param> /// <param name="expectedCacheValue"></param> [Theory] [InlineData("testKey", "testValue", "testValue")] [InlineData("someKey", "helloWorld", "helloWorld")] public void GettingAnExistingValueReturnsThatValue(string testKey, string testValue, string expectedCacheValue) { var sut = CreateCacheService(); sut.Set(testKey, testValue); string? result = sut.Get<string>(testKey); result.Should().Be(expectedCacheValue); } [Fact] public async Task GettingAnExpiredValueReturnsNull() { var sut = CreateCacheService(); sut.Set(_testKey, _testValue, TimeSpan.FromMilliseconds(200)); string? actual = sut.Get<string>(_testKey); Assert.Equal(_testValue, actual); await Task.Delay(200); actual = sut.Get<string>(_testKey); Assert.Null(actual); } [Fact] public void GettingAnExistingObjectReturnsThatObject() { var expected = new TestRecord(Guid.NewGuid(), _testValue, DateTime.UtcNow); var sut = CreateCacheService(); sut.Set(_testKey, expected); var actual = sut.Get<TestRecord>(_testKey); Assert.Equal(expected, actual); } }
using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LivingDocumentation.Analyzer.Tests { [TestClass] public class EnumModifierTests { [TestMethod] public void EnumWithoutModifier_Should_HaveDefaultInternalModifier() { // Assign var source = @" enum Test { } "; // Act var types = TestHelper.VisitSyntaxTree(source); // Assert types[0].Modifiers.Should().Be(Modifier.Internal); } [TestMethod] public void PublicEnum_Should_HavePublicModifier() { // Assign var source = @" public enum Test { } "; // Act var types = TestHelper.VisitSyntaxTree(source); // Assert types[0].Modifiers.Should().Be(Modifier.Public); } [TestMethod] public void EnumMembers_Should_HavePublicModifier() { // Assign var source = @" public enum Test { Value } "; // Act var types = TestHelper.VisitSyntaxTree(source); // Assert types[0].EnumMembers[0].Modifiers.Should().Be(Modifier.Public); } } }
using Microsoft.AspNetCore.Http; using Oyooni.Server.Common; using System.Threading; using System.Threading.Tasks; namespace Oyooni.Server.Services.General { /// <summary> /// Represents an image service contract /// </summary> public interface IImageService { /// <summary> /// Gets the base64 data of the image bytes /// </summary> /// <param name="imageFile">The image file containing the image data</param> /// <returns>Base64 representation of the image data</returns> Task<string> GetBase64ImageDataAsync(IFormFile imageFile, CancellationToken token = default); /// <summary> /// Create a temp file of the passed form file and returned its absolute path /// </summary> /// <param name="imageFile"></param> /// <param name="token"></param> /// <returns>The absolute path of the newly created temp file</returns> Task<DisposableTempFile> GetTempFileOfImage(IFormFile imageFile, CancellationToken token = default); } }
using System.Collections.Generic; using EagleRepair.Ast.Url; namespace EagleRepair.IntegrationTests.Url.DataProvider { public class SonarQubeUrlDataProvider { public static IEnumerable<object[]> TestCases() { yield return new object[] { SonarQube.BaseUrl }; } } }
// This software is part of the IoC.Configuration library // Copyright © 2018 IoC.Configuration Contributors // http://oroptimizer.com // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. using System; namespace IoC.Configuration.ConfigurationFile { public static class ConfigurationFileAttributeNames { #region Member Variables public const string ActiveDiManagerName = "activeDiManagerName"; public const string Alias = "alias"; public const string Assembly = "assembly"; public const string CollectionType = "collectionType"; public const string DeclaringClass = "class"; public const string DeclaringClassRef = "classRef"; public const string DeclaringInterface = "declaringInterface"; public const string Enabled = "enabled"; public const string Interface = "interface"; public const string InterfaceRef = "interfaceRef"; public const string ItemType = "itemType"; public const string ItemTypeAssembly = "itemTypeAssembly"; public const string ItemTypeRef = "itemTypeRef"; public const string MemberName = "memberName"; public const string Name = "name"; public const string OverrideDirectory = "overrideDirectory"; public const string ParamName = "paramName"; public const string Path = "path"; public const string Plugin = "plugin"; public const string PluginsDirPath = "pluginsDirPath"; public const string RegisterIfNotRegistered = "registerIfNotRegistered"; public const string ReturnType = "returnType"; public const string ReturnTypeRef = "returnTypeRef"; public const string ReuseValue = "reuseValue"; public const string Scope = "scope"; public const string SerializerAggregatorType = "serializerAggregatorType"; public const string SerializerAggregatorTypeRef = "serializerAggregatorTypeRef"; public const string SettingName = "settingName"; public const string Type = "type"; public const string TypeRef = "typeRef"; public const string Value = "value"; #endregion } }
using System.IO; using System.Text; namespace RVCore.RvDB { public class RvTreeRow { public enum TreeSelect { UnSelected, Selected, Locked } private long _filePointer = -1; private bool _pTreeExpanded; private TreeSelect _pChecked; public object UiObject; public RvTreeRow() { _pTreeExpanded = true; _pChecked = TreeSelect.Selected; } public bool TreeExpanded { get => _pTreeExpanded; set { if (_pTreeExpanded == value) return; _pTreeExpanded = value; CacheUpdate(); } } public TreeSelect Checked { get => _pChecked; set { if (_pChecked == value) return; _pChecked = value; CacheUpdate(); } } /* public JObject WriteJson() { JObject jObj = new JObject(); jObj.Add("TreeExpanded", _pTreeExpanded); jObj.Add("Checked", _pChecked.ToString()); return jObj; } */ public void Write(BinaryWriter bw) { _filePointer = bw.BaseStream.Position; bw.Write(_pTreeExpanded); bw.Write((byte)_pChecked); } public void Read(BinaryReader br) { _filePointer = br.BaseStream.Position; _pTreeExpanded = br.ReadBoolean(); _pChecked = (TreeSelect)br.ReadByte(); } private static FileStream fsl; private static BinaryWriter bwl; public static void OpenStream() { fsl = new FileStream(Settings.rvSettings.CacheFile, FileMode.Open, FileAccess.Write); bwl = new BinaryWriter(fsl, Encoding.UTF8, true); } public static void CloseStream() { bwl?.Flush(); bwl?.Close(); bwl?.Dispose(); fsl?.Close(); fsl?.Dispose(); bwl = null; fsl = null; } private void CacheUpdate() { if (_filePointer < 0) return; if (fsl != null && bwl != null) { fsl.Position = _filePointer; bwl.Write(_pTreeExpanded); bwl.Write((byte)_pChecked); return; } using (FileStream fs = new FileStream(Settings.rvSettings.CacheFile, FileMode.Open, FileAccess.Write)) { using (BinaryWriter bw = new BinaryWriter(fs, Encoding.UTF8, true)) { fs.Position = _filePointer; bw.Write(_pTreeExpanded); bw.Write((byte)_pChecked); bw.Flush(); bw.Close(); } fs.Close(); } } } }
// #NVJOB Dynamic Sky (for Demo) // Full Asset #NVJOB Dynamic Sky - https://nvjob.github.io/unity/nvjob-dynamic-sky-lite // #NVJOB Nicholas Veselov - https://nvjob.github.io using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEditor; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [CanEditMultipleObjects] internal class NVDSkyDemoMaterials : MaterialEditor { /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// enum DSKYType { Cloud1 = 0, Cloud2, Horizon } DSKYType[] skyTypes; string[] DSKYGTypeString = { "DSKY_CLOUD_1", "DSKY_CLOUD_2", "DSKY_HORIZON" }; bool renderQueueOffset(DSKYType skyType) { return skyType == DSKYType.Horizon; } Color smLineColor = Color.HSVToRGB(0, 0, 0.55f), bgLineColor = Color.HSVToRGB(0, 0, 0.3f); int smLinePadding = 20, bgLinePadding = 35; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public override void OnInspectorGUI() { //-------------- SetDefaultGUIWidths(); serializedObject.Update(); SerializedProperty shaderFind = serializedObject.FindProperty("m_Shader"); if (!isVisible || shaderFind.hasMultipleDifferentValues || shaderFind.objectReferenceValue == null) return; //-------------- List<MaterialProperty> allProps = new List<MaterialProperty>(GetMaterialProperties(targets)); //-------------- EditorGUI.BeginChangeCheck(); Header(); DrawUILine(bgLineColor, 2, bgLinePadding); //-------------- SkyTypeCH(allProps); if (skyTypes.Contains(DSKYType.Cloud1) || skyTypes.Contains(DSKYType.Cloud2)) Clouds(allProps); if (skyTypes.Contains(DSKYType.Horizon)) Horizon(allProps); //-------------- DrawUILine(bgLineColor, 2, bgLinePadding); Information(); DrawUILine(bgLineColor, 2, bgLinePadding); RenderQueueField(); EnableInstancingField(); DoubleSidedGIField(); EditorGUILayout.Space(); EditorGUILayout.Space(); //-------------- } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void SkyTypeCH(List<MaterialProperty> allProps) { //-------------- EditorGUILayout.LabelField("Sky Type:", EditorStyles.boldLabel); DrawUILine(smLineColor, 1, smLinePadding); //-------------- skyTypes = new DSKYType[targets.Length]; for (int i = 0; i < targets.Length; ++i) { skyTypes[i] = DSKYType.Cloud1; for (int j = 0; j < DSKYGTypeString.Length; ++j) { if (((Material)targets[i]).shaderKeywords.Contains(DSKYGTypeString[j])) { skyTypes[i] = (DSKYType)j; break; } } } //-------------- DSKYType setSkyType = (DSKYType)EditorGUILayout.EnumPopup("Sky Type", skyTypes[0]); if (EditorGUI.EndChangeCheck()) { foreach (Material m in targets.Cast<Material>()) { for (int i = 0; i < DSKYGTypeString.Length; ++i) m.DisableKeyword(DSKYGTypeString[i]); m.EnableKeyword(DSKYGTypeString[(int)setSkyType]); m.renderQueue = renderQueueOffset(setSkyType) ? (int)UnityEngine.Rendering.RenderQueue.Geometry + 501 : (int)UnityEngine.Rendering.RenderQueue.Geometry + 500; } } EditorGUI.showMixedValue = false; //-------------- DrawUILine(bgLineColor, 2, bgLinePadding); //-------------- } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Clouds(List<MaterialProperty> allProps) { //-------------- EditorGUILayout.LabelField(skyTypes.Contains(DSKYType.Cloud1) ? "Clouds Type 1 (General texture mixing):" : "Clouds Type 2 (Mixing textures by channels):", EditorStyles.boldLabel); DrawUILine(smLineColor, 1, smLinePadding); //-------------- MaterialProperty texture1 = allProps.Find(prop => prop.name == "_Texture1"); MaterialProperty textureUv1 = allProps.Find(prop => prop.name == "_TextureUv1"); MaterialProperty intensityT1 = allProps.Find(prop => prop.name == "_IntensityT1"); MaterialProperty vectorX1 = allProps.Find(prop => prop.name == "_VectorX1"); MaterialProperty vectorY1 = allProps.Find(prop => prop.name == "_VectorY1"); if (texture1 != null && textureUv1 != null && intensityT1 != null && vectorX1 != null && vectorY1 != null) { allProps.Remove(texture1); allProps.Remove(textureUv1); allProps.Remove(intensityT1); allProps.Remove(vectorX1); allProps.Remove(vectorY1); ShaderProperty(texture1, texture1.displayName); ShaderProperty(textureUv1, textureUv1.displayName); ShaderProperty(intensityT1, intensityT1.displayName); ShaderProperty(vectorX1, vectorX1.displayName); ShaderProperty(vectorY1, vectorY1.displayName); } DrawUILine(smLineColor, 1, smLinePadding); //-------------- MaterialProperty texture2 = allProps.Find(prop => prop.name == "_Texture2"); MaterialProperty textureUv2 = allProps.Find(prop => prop.name == "_TextureUv2"); MaterialProperty intensityT2 = allProps.Find(prop => prop.name == "_IntensityT2"); MaterialProperty vectorX2 = allProps.Find(prop => prop.name == "_VectorX2"); MaterialProperty vectorY2 = allProps.Find(prop => prop.name == "_VectorY2"); if (texture2 != null && textureUv2 != null && intensityT2 != null && vectorX2 != null && vectorY2 != null) { allProps.Remove(texture2); allProps.Remove(textureUv2); allProps.Remove(intensityT2); allProps.Remove(vectorX2); allProps.Remove(vectorY2); ShaderProperty(texture2, texture2.displayName); ShaderProperty(textureUv2, textureUv2.displayName); ShaderProperty(intensityT2, intensityT2.displayName); ShaderProperty(vectorX2, vectorX2.displayName); ShaderProperty(vectorY2, vectorY2.displayName); } DrawUILine(smLineColor, 1, smLinePadding); //-------------- MaterialProperty texture3 = allProps.Find(prop => prop.name == "_Texture3"); MaterialProperty textureUv3 = allProps.Find(prop => prop.name == "_TextureUv3"); MaterialProperty intensityT3 = allProps.Find(prop => prop.name == "_IntensityT3"); MaterialProperty vectorX3 = allProps.Find(prop => prop.name == "_VectorX3"); MaterialProperty vectorY3 = allProps.Find(prop => prop.name == "_VectorY3"); if (texture3 != null && textureUv3 != null && intensityT3 != null && vectorX3 != null && vectorY3 != null) { allProps.Remove(texture3); allProps.Remove(textureUv3); allProps.Remove(intensityT3); allProps.Remove(vectorX3); allProps.Remove(vectorY3); ShaderProperty(texture3, texture3.displayName); ShaderProperty(textureUv3, textureUv3.displayName); ShaderProperty(intensityT3, intensityT3.displayName); ShaderProperty(vectorX3, vectorX3.displayName); ShaderProperty(vectorY3, vectorY3.displayName); } DrawUILine(smLineColor, 1, smLinePadding); //-------------- MaterialProperty color = allProps.Find(prop => prop.name == "_Color"); MaterialProperty intensityInput = allProps.Find(prop => prop.name == "_IntensityInput"); MaterialProperty fluffiness = allProps.Find(prop => prop.name == "_Fluffiness"); MaterialProperty intensityOutput = allProps.Find(prop => prop.name == "_IntensityOutput"); if (color != null && intensityInput != null && fluffiness != null && intensityOutput != null) { allProps.Remove(color); allProps.Remove(intensityInput); allProps.Remove(fluffiness); allProps.Remove(intensityOutput); ShaderProperty(color, color.displayName); ShaderProperty(intensityInput, intensityInput.displayName); ShaderProperty(fluffiness, fluffiness.displayName); ShaderProperty(intensityOutput, intensityOutput.displayName); } //-------------- } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Horizon(List<MaterialProperty> allProps) { //-------------- EditorGUILayout.LabelField("Horizon:", EditorStyles.boldLabel); DrawUILine(smLineColor, 1, smLinePadding); //-------------- MaterialProperty level1Color = allProps.Find(prop => prop.name == "_Level1Color"); MaterialProperty level1 = allProps.Find(prop => prop.name == "_Level1"); if (level1Color != null && level1 != null) { allProps.Remove(level1Color); allProps.Remove(level1); ShaderProperty(level1Color, level1Color.displayName); ShaderProperty(level1, level1.displayName); } DrawUILine(smLineColor, 1, smLinePadding); //-------------- MaterialProperty level0Color = allProps.Find(prop => prop.name == "_Level0Color"); MaterialProperty level0 = allProps.Find(prop => prop.name == "_Level0"); if (level0Color != null && level0 != null) { allProps.Remove(level0Color); allProps.Remove(level0); ShaderProperty(level0Color, level0Color.displayName); ShaderProperty(level0, level0.displayName); } //-------------- } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void Header() { //-------------- EditorGUILayout.Space(); EditorGUILayout.Space(); GUIStyle guiStyle = new GUIStyle(); guiStyle.fontSize = 17; EditorGUILayout.LabelField("#NVJOB Dynamic Sky (for Demo)", guiStyle); //-------------- } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void Information() { //-------------- if (GUILayout.Button("Full Asset #NVJOB Dynamic Sky")) Help.BrowseURL("https://nvjob.github.io/unity/nvjob-dynamic-sky-lite"); if (GUILayout.Button("#NVJOB Store")) Help.BrowseURL("https://nvjob.github.io/store/"); EditorGUILayout.Space(); EditorGUILayout.TextArea("Development of assets, scripts and shaders for Unity nvjob.dev@gmail.com", EditorStyles.textArea); //-------------- } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void DrawUILine(Color color, int thickness = 2, int padding = 10) { //-------------- Rect line = EditorGUILayout.GetControlRect(GUILayout.Height(padding + thickness)); line.height = thickness; line.y += padding / 2; line.x -= 2; EditorGUI.DrawRect(line, color); //-------------- } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [CustomEditor(typeof(DynamicSkyForDemo))] [CanEditMultipleObjects] public class DynamicSkyForDemoEditor : Editor { /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Color smLineColor = Color.HSVToRGB(0, 0, 0.55f), bgLineColor = Color.HSVToRGB(0, 0, 0.3f); int smLinePadding = 20, bgLinePadding = 35; SerializedProperty uvRotateSpeed, uvRotateDistance, player; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void OnEnable() { //-------------- uvRotateSpeed = serializedObject.FindProperty("ssgUvRotateSpeed"); uvRotateDistance = serializedObject.FindProperty("ssgUvRotateDistance"); player = serializedObject.FindProperty("player"); //-------------- } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public override void OnInspectorGUI() { //-------------- serializedObject.Update(); //-------------- EditorGUI.BeginChangeCheck(); NVDSkyDemoMaterials.Header(); NVDSkyDemoMaterials.DrawUILine(bgLineColor, 2, bgLinePadding); //-------------- EditorGUILayout.LabelField("Sky Movement:", EditorStyles.boldLabel); NVDSkyDemoMaterials.DrawUILine(smLineColor, 1, smLinePadding); EditorGUILayout.PropertyField(uvRotateSpeed, new GUIContent("Rotate Speed")); EditorGUILayout.PropertyField(uvRotateDistance, new GUIContent("Rotate Distance")); NVDSkyDemoMaterials.DrawUILine(smLineColor, 1, smLinePadding); EditorGUILayout.PropertyField(player, new GUIContent("Player")); EditorGUILayout.HelpBox("Optional. To move the sky behind the player. X and Z axis only.", MessageType.None); //-------------- serializedObject.ApplyModifiedProperties(); NVDSkyDemoMaterials.DrawUILine(bgLineColor, 2, bgLinePadding); NVDSkyDemoMaterials.Information(); EditorGUILayout.Space(); EditorGUILayout.Space(); //-------------- } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// }
using System; using System.Collections.Generic; using NUnit.Framework; using SFA.DAS.CommitmentsV2.Api.Types.Responses; using SFA.DAS.ProviderCommitments.Web.Extensions; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Extensions { [TestFixture] public class PriceEpisodeExtensionsTests { private List<GetPriceEpisodesResponse.PriceEpisode> _priceEpisodes; [SetUp] public void Arrange() { _priceEpisodes = new List<GetPriceEpisodesResponse.PriceEpisode> { CreatePriceEpisode(1, new DateTime(2018,01,01), new DateTime(2018,12,31)), CreatePriceEpisode(2, new DateTime(2019,01,01), new DateTime(2019,12,31)), CreatePriceEpisode(3, new DateTime(2020,01,01), null) }; } [TestCase("2017-01-01", 1, Description = "First price episode if all future-dated")] [TestCase("2018-01-01", 1, Description = "First day of an episode")] [TestCase("2018-12-31", 1, Description = "Last day of an episode")] [TestCase("2019-06-01", 2, Description = "Episode mid-point")] [TestCase("2020-06-01", 3, Description = "Within an episode without an end date")] public void PriceIsDeterminedCorrectly(DateTime effectiveDate, decimal expectedCost) { Assert.AreEqual(expectedCost, _priceEpisodes.GetPrice(effectiveDate)); } private GetPriceEpisodesResponse.PriceEpisode CreatePriceEpisode(decimal cost, DateTime from, DateTime? to) { return new GetPriceEpisodesResponse.PriceEpisode {Cost = cost, FromDate = from, ToDate = to}; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; #if EASY_MOBILE using EasyMobile; #endif namespace SgLib { public class StoreUIController : MonoBehaviour { public GameObject coinPackPrefab; public Transform productList; public InAppPurchaser purchaser; // Use this for initialization void Start() { for (int i = 0; i < purchaser.coinPacks.Length; i++) { InAppPurchaser.CoinPack pack = purchaser.coinPacks[i]; GameObject newPack = Instantiate(coinPackPrefab, Vector3.zero, Quaternion.identity) as GameObject; Transform newPackTf = newPack.transform; newPackTf.Find("Button/CoinValue").GetComponent<Text>().text = pack.coinValue.ToString(); newPackTf.Find("Button/PriceSection/PriceString").GetComponent<Text>().text = pack.priceString; newPackTf.SetParent(productList, true); newPackTf.localScale = Vector3.one; // Add button listener newPackTf.Find("Button").GetComponent<Button>().onClick.AddListener(() => { Utilities.ButtonClickSound(); #if EASY_MOBILE purchaser.Purchase(pack.productName); #endif }); } } } }
using AmaknaProxy.API.Utils.Logger; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AmaknaProxy.API.Managers { public static class ConsoleManager { private static ContainerLogger Logger; static ConsoleManager() { Logger = null; } public static void InitLogger(ContainerLogger logger) { Logger = logger; } public static void Info(string Text) { if (Logger != null) Logger.Info(Text); } public static void Error(string Text) { if (Logger != null) Logger.Error(Text); } public static void Warning(string Text) { if (Logger != null) Logger.Warning(Text); } public static void Debug(string Text) { if (Logger != null) Logger.Debug(Text); } public static void Chat(string Text, string Prefix) { if (Logger != null) Logger.Chat(Text, Prefix); } } }
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using System; using ClearCanvas.Web.Client.Silverlight.Command; namespace ClearCanvas.Web.Client.Silverlight.ViewModel { public class LogPanelViewModel : ViewModelBase, IDisposable { public LogPanelViewModel() { ClearLogCommand = new RelayCommand(OnClearLog); Platform.Logger += Logger; } public void Dispose() { Platform.Logger -= Logger; } private void Logger(string msg) { LogContents = msg + "\n" + LogContents; } private void OnClearLog() { LogContents = string.Empty; } public RelayCommand ClearLogCommand { get; private set; } private string _logContents = string.Empty; public string LogContents { get { return _logContents; } set { if (_logContents == value) return; _logContents = value; RaisePropertyChanged(() => LogContents); } } public bool DebugLevel { get { return Platform.IsDebugEnabled; } set { if (Platform.IsDebugEnabled == value) return; Platform.IsDebugEnabled = value; RaisePropertyChanged(() => DebugLevel); } } public bool InfoLevel { get { return Platform.IsInfoEnabled; } set { if (Platform.IsInfoEnabled == value) return; Platform.IsInfoEnabled = value; RaisePropertyChanged(() => InfoLevel); } } public bool WarnLevel { get { return Platform.IsWarnEnabled; } set { if (Platform.IsWarnEnabled == value) return; Platform.IsWarnEnabled = value; RaisePropertyChanged(() => WarnLevel); } } public bool ErrorLevel { get { return Platform.IsErrorEnabled; } set { if (Platform.IsErrorEnabled == value) return; Platform.IsErrorEnabled = value; RaisePropertyChanged(() => ErrorLevel); } } public bool FatalLevel { get { return Platform.IsFatalEnabled; } set { if (Platform.IsFatalEnabled == value) return; Platform.IsFatalEnabled = value; RaisePropertyChanged(() => FatalLevel); } } } }
using System.Net; using PowerUtils.Validations; using PowerUtils.Validations.Exceptions; using PowerUtils.Validations.GuardClauses; namespace PowerUtils.GuardClauses.Validations.Tests.GuardClausesTests; [Trait("Type", "Guards")] public class GuardValidationGeolocationExtensionsTests { [Fact] public void FloatLatitude_Small_Exception() { // Arrange var degree = -90.1f; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>( HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LATITUDE ); } [Fact] public void FloatLatitude_Large_Exception() { // Arrange var degree = 90.1f; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>( HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LATITUDE ); } [Fact] public void FloatLatitude_Valid_NotException() { // Arrange var degree = 18.1f; // Act var act = Guard.Validate.IfLatitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } [Fact] public void FloatLongitude_Small_Exception() { // Arrange var degree = -180.1f; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>( HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LONGITUDE ); } [Fact] public void FloatLongitude_Large_Exception() { // Arrange var degree = 180.1f; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>( HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LONGITUDE ); } [Fact] public void FloatLongitude_Valid_NotException() { // Arrange var degree = 18.1f; // Act var act = Guard.Validate.IfLongitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } [Fact] public void FloatLatitudeNullable_Null_NotException() { // Arrange float? degree = null; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Should() .Be(degree); } [Fact] public void FloatLatitudeNullable_Small_Exception() { // Arrange float? degree = -90.1f; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>( HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LATITUDE ); } [Fact] public void FloatLatitudeNullable_Large_Exception() { // Arrange float? degree = 90.1f; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>( HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LATITUDE ); } [Fact] public void FloatLatitudeNullable_Valid_NotException() { // Arrange float? degree = 18.1f; // Act var act = Guard.Validate.IfLatitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } [Fact] public void FloatLongitudeNullable_Null_NotException() { // Arrange float? degree = null; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Should() .Be(degree); } [Fact] public void FloatLongitudeNullable_Small_Exception() { // Arrange float? degree = -180.1f; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LONGITUDE); } [Fact] public void FloatLongitudeNullable_Large_Exception() { // Arrange float? degree = 180.1f; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LONGITUDE); } [Fact] public void FloatLongitudeNullable_Valid_NotException() { // Arrange float? degree = 18.1f; // Act var act = Guard.Validate.IfLongitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } [Fact] public void DoubleLatitude_Small_Exception() { // Arrange var degree = -90.1; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LATITUDE); } [Fact] public void DoubleLatitude_Large_Exception() { // Arrange var degree = 90.1; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LATITUDE); } [Fact] public void DoubleLatitude_Valid_NotException() { // Arrange var degree = 18.1; // Act var act = Guard.Validate.IfLatitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } [Fact] public void DoubleLongitude_Small_Exception() { // Arrange var degree = -180.1; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LONGITUDE); } [Fact] public void DoubleLongitude_Large_Exception() { // Arrange var degree = 180.1; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LONGITUDE); } [Fact] public void DoubleLongitude_Valid_NotException() { // Arrange var degree = 18.1; // Act var act = Guard.Validate.IfLongitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } [Fact] public void DoubleLatitudeNullable_Null_NotException() { // Arrange double? degree = null; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Should() .Be(degree); } [Fact] public void DoubleLatitudeNullable_Small_Exception() { // Arrange double? degree = -90.1; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LATITUDE); } [Fact] public void DoubleLatitudeNullable_Large_Exception() { // Arrange double? degree = 90.1; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LATITUDE); } [Fact] public void DoubleLatitudeNullable_Valid_NotException() { // Arrange double? degree = 18.1; // Act var act = Guard.Validate.IfLatitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } [Fact] public void DoubleLongitudeNullable_Null_NotException() { // Arrange double? degree = null; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Should() .Be(degree); } [Fact] public void DoubleLongitudeNullable_Small_Exception() { // Arrange double? degree = -180.1; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LONGITUDE); } [Fact] public void DoubleLongitudeNullable_Large_Exception() { // Arrange double? degree = 180.1; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LONGITUDE); } [Fact] public void DoubleLongitudeNullable_Valid_NotException() { // Arrange double? degree = 18.1; // Act var act = Guard.Validate.IfLongitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } [Fact] public void DecimalLatitude_Small_Exception() { // Arrange var degree = -90.1m; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LATITUDE); } [Fact] public void DecimalLatitude_Large_Exception() { // Arrange var degree = 90.1m; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LATITUDE); } [Fact] public void DecimalLatitude_Valid_NotException() { // Arrange var degree = 18.1m; // Act var act = Guard.Validate.IfLatitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } [Fact] public void DecimalLongitude_Small_Exception() { // Arrange var degree = -180.1m; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LONGITUDE); } [Fact] public void DecimalLongitude_Large_Exception() { // Arrange var degree = 180.1m; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LONGITUDE); } [Fact] public void DecimalLongitude_Valid_NotException() { // Arrange var degree = 18.1m; // Act var act = Guard.Validate.IfLongitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } [Fact] public void DecimalLatitudeNullable_Null_NotException() { // Arrange decimal? degree = null; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Should() .Be(degree); } [Fact] public void DecimalLatitudeNullable_Small_Exception() { // Arrange decimal? degree = -90.1m; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LATITUDE); } [Fact] public void DecimalLatitudeNullable_Large_Exception() { // Arrange decimal? degree = 90.1m; // Act var act = Record.Exception(() => Guard.Validate.IfLatitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LATITUDE); } [Fact] public void DecimalLatitudeNullable_Valid_NotException() { // Arrange decimal? degree = 18.1m; // Act var act = Guard.Validate.IfLatitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } [Fact] public void DecimalLongitudeNullable_Null_NotException() { // Arrange decimal? degree = null; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Should() .Be(degree); } [Fact] public void DecimalLongitudeNullable_Small_Exception() { // Arrange decimal? degree = -180.1m; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MIN_LONGITUDE); } [Fact] public void DecimalLongitudeNullable_Large_Exception() { // Arrange decimal? degree = 180.1m; // Act var act = Record.Exception(() => Guard.Validate.IfLongitudeOutOfRange(degree)); // Assert act.Validate<PropertyException>(HttpStatusCode.BadRequest, nameof(degree), ErrorCodes.MAX_LONGITUDE); } [Fact] public void DecimalLongitudeNullable_Valid_NotException() { // Arrange decimal? degree = 18.1m; // Act var act = Guard.Validate.IfLongitudeOutOfRange(degree); // Assert act.Should() .Be(degree); } }
/// <author>Parmanand Kumar</author> /// <created>03/11/2021</created> /// <summary> /// It contains the public interface required by Summary Module to save Summary data. /// It exposes the basic functinality of Telemetry Module /// </summary> /// namespace Dashboard.Server.Persistence { //SummaryPersistence Interface public interface ISummaryPersistence { /// <summary> /// saves the summary of the session into a summary file /// </summary> /// <param name="message"> takes message string that need to be saved </param> /// <returns> return true if succesfully saved else return false </returns> public bool SaveSummary(string message); } }
using Bootstrapper.Interface; using DatabaseInteraction.Interface; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Utilities; namespace DatabaseInteraction { public class DatabaseBootstrapper : IBootstrapper { private const string _cachedConfiguration = "CACHED_DATABASE"; public void ConfigureServices(IServiceCollection services, IConfiguration configuration) { services.AddSingleton<IContext, ConfiguratedContext>(); var isCached = configuration.ReadBool(_cachedConfiguration); if (isCached) { services.AddHostedSingletonService<IRepositoryFactory, CachedRepositoryFactory>(); } else { services.AddHostedSingletonService<IRepositoryFactory, RepositoryFactory>(); } services.AddSingleton<IEntityFactory, EntityFactory>(); services.AddSingleton<IDataBaseUpdater, DataBaseUpdater>(); } } }
#region Copyright // Copyright (c) 2020 TonesNotes // Distributed under the Open BSV software license, see the accompanying file LICENSE. #endregion using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace KZJ { /// <summary> /// For prototyping support. /// Allows simple input dialogs to be created directly by minimal code. /// Example: /// var newName = string.Empty; /// if (new DynamicDialog("Rename Wallet") /// .AddLabel($"Renaming wallet currently named \"{w.Name}\".") /// .AddTextBox("New name for wallet:", 300, s => newName = s) /// .AddButtons(okLabel: "Rename") /// .GetResults() == DialogResult.OK) { /// w.Name = newName; /// } /// Note that the lambda action passed to the AddTextBox method causes the local variable /// to be updated only when "OK" button or return key are pressed. /// </summary> public class DynamicDialog : Form { private System.Windows.Forms.FlowLayoutPanel flowLayoutPanelMain; int itemCount = 0; List<Action> results = new List<Action>(); public DynamicDialog(string title = null) { this.flowLayoutPanelMain = new System.Windows.Forms.FlowLayoutPanel(); this.flowLayoutPanelMain.SuspendLayout(); this.SuspendLayout(); // // flowLayoutPanelMain // this.flowLayoutPanelMain.AutoSize = true; this.flowLayoutPanelMain.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.flowLayoutPanelMain.FlowDirection = System.Windows.Forms.FlowDirection.TopDown; this.flowLayoutPanelMain.Location = new System.Drawing.Point(0, 0); this.flowLayoutPanelMain.Name = "flowLayoutPanelMain"; this.flowLayoutPanelMain.Size = new System.Drawing.Size(309, 93); this.flowLayoutPanelMain.TabIndex = 0; // // DynamicDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.ClientSize = new System.Drawing.Size(876, 489); this.ControlBox = false; this.Controls.Add(this.flowLayoutPanelMain); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DynamicDialog"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = title; this.TopMost = true; this.StartPosition = FormStartPosition.CenterParent; this.flowLayoutPanelMain.ResumeLayout(false); this.flowLayoutPanelMain.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } /// <summary> /// Use \r\n to insert a line break in labelText. /// </summary> /// <param name="labelText"></param> /// <returns></returns> public DynamicDialog AddLabel(string labelText) { itemCount++; var label = new Label() { AutoSize = true, Location = new System.Drawing.Point(3, 0), Name = $"label{itemCount}", Margin = new Padding(3, 5, 3, 0), Size = new System.Drawing.Size(303, 26), TabIndex = itemCount, Text = labelText, TextAlign = System.Drawing.ContentAlignment.MiddleLeft, }; flowLayoutPanelMain.Controls.Add(label); return this; } public DynamicDialog AddTextBox( string labelText, int width = 200, Action<string> result = null, bool readOnly = false, string initialText = null) { itemCount++; var label = new Label() { AutoSize = true, Location = new System.Drawing.Point(3, 7), Margin = new System.Windows.Forms.Padding(3, 7, 3, 0), Name = $"label{itemCount}", Size = new System.Drawing.Size(35, 13), TabIndex = itemCount, Text = labelText, TextAlign = System.Drawing.ContentAlignment.MiddleLeft, }; itemCount++; var textBox = new TextBox() { Location = new System.Drawing.Point(44, 3), Name = $"textBox1{itemCount}", Size = new System.Drawing.Size(width, 20), TabIndex = itemCount, ReadOnly = readOnly, Text = initialText }; if (result != null) results.Add(() => result(textBox.Text)); itemCount++; var panel = new FlowLayoutPanel() { AutoSize = true, AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink, Location = new System.Drawing.Point(3, 29), Name = $"panel{itemCount}", Size = new System.Drawing.Size(247, 26), TabIndex = itemCount, }; panel.Controls.Add(label); panel.Controls.Add(textBox); flowLayoutPanelMain.Controls.Add(panel); return this; } public DialogResult GetResults() { var r = ShowDialog(); if (r == DialogResult.OK) { foreach (var a in results) a(); } return r; } public DynamicDialog AddButtons(string okLabel = "OK", string cancelLabel = "Cancel") { itemCount++; var panel = new FlowLayoutPanel() { AutoSize = true, AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink, Location = new System.Drawing.Point(3, 29), Name = $"panel{itemCount}", Size = new System.Drawing.Size(247, 26), TabIndex = itemCount, }; foreach (var buttonText in new[] { okLabel, cancelLabel }) { if (buttonText != null) { itemCount++; var button = new Button() { Location = new System.Drawing.Point(3, 3), Name = $"button{itemCount}", Size = new System.Drawing.Size(75, 23), TabIndex = itemCount, Text = buttonText, UseVisualStyleBackColor = true, }; if (buttonText == okLabel) { button.DialogResult = System.Windows.Forms.DialogResult.OK; AcceptButton = button; } if (buttonText == cancelLabel) { button.DialogResult = System.Windows.Forms.DialogResult.Cancel; CancelButton = button; } panel.Controls.Add(button); } } flowLayoutPanelMain.Controls.Add(panel); return this; } } }
// <copyright file="DatePickerControlTestsWpf.cs" company="Automate The Planet Ltd."> // Copyright 2020 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>https://bellatrix.solutions/</site> using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Bellatrix.Desktop.Tests { [TestClass] [App(Constants.WpfAppPath, Lifecycle.RestartEveryTime)] [AllureSuite("DatePicker Control")] [AllureTag("WPF")] public class DatePickerControlTestsWpf : BellatrixBaseTest { [TestMethod] [TestCategory(Categories.Desktop)] public void MessageChanged_When_DateHovered_Wpf() { var datePicker = App.ElementCreateService.CreateByAutomationId<Date>("DatePicker"); datePicker.Hover(); var label = App.ElementCreateService.CreateByAutomationId<Label>("ResultLabelId"); Assert.AreEqual("edatepickerHovered", label.InnerText); } [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Desktop)] public void IsDisabledReturnsFalse_When_DatePickerIsNotDisabled_Wpf() { var datePicker = App.ElementCreateService.CreateByAutomationId<Date>("DatePicker"); Assert.AreEqual(false, datePicker.IsDisabled); } [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Desktop)] public void IsDisabledReturnsTrue_When_DatePickerIsDisabled_Wpf() { var datePicker = App.ElementCreateService.CreateByAutomationId<Date>("DatePickerDisabled"); Assert.AreEqual(true, datePicker.IsDisabled); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; enum EMoveType { GIVE_FIRST_STEP, GIVE_SECOND_STEP, RECEIVE } public class Inventory : MonoBehaviour { [Header("Trade Animations")] [SerializeField] Vector3 spawnPos = new Vector3(6.25f, 1.95f, 1); [SerializeField] Vector3 receiveEndPos = new Vector3(6.25f, 1.95f, -1.2f); Vector3 targetPos; [SerializeField] float drag = 7.37f; [SerializeField] GameObject previousObject; [Header("References")] [SerializeField] InspectionInterface inspectionInterface; [SerializeField] TutorialManager tutorialManager; GameObject prefabToGive; GameObject newObject; Collider[] colliders; Rigidbody rb; bool moving; EMoveType move; bool waiting; float waitTime; float currentTime; void Start() { moving = false; waiting = false; waitTime = 0.7f; currentTime = 0; if (previousObject) { colliders = previousObject.GetComponents<Collider>(); rb = previousObject.GetComponent<Rigidbody>(); } } public void HandleBerth(bool berth) { if (previousObject) { Island2Object0 lastObject = previousObject.GetComponent<Island2Object0>(); if (lastObject) lastObject.HandleBerth(berth); } } public bool TradeObjects(GameObject prefab) { prefabToGive = prefab; if (previousObject) RemoveLastObjectFromInventory(); else AddObjectToInventory(true); return (previousObject && prefabToGive); } public void RemoveLastObjectFromInventory() { moving = true; move = EMoveType.GIVE_FIRST_STEP; colliders = previousObject.GetComponents<Collider>(); foreach (Collider collider in colliders) collider.isTrigger = true; rb = previousObject.GetComponent<Rigidbody>(); rb.useGravity = false; rb.drag = 0; targetPos = previousObject.transform.position; targetPos.y += 1; rb.velocity = (targetPos - previousObject.transform.position); } public void AddObjectToInventory(bool trade, GameObject prefab = null) { if (trade) prefab = prefabToGive; if (prefab) { moving = true; move = EMoveType.RECEIVE; newObject = Instantiate(prefab, transform); if (trade) previousObject = newObject; colliders = newObject.GetComponents<Collider>(); foreach (Collider collider in colliders) collider.isTrigger = true; rb = newObject.GetComponent<Rigidbody>(); rb.useGravity = false; rb.drag = 0; newObject.transform.localPosition = spawnPos; targetPos = receiveEndPos; rb.velocity = (targetPos - spawnPos); Interactible interactible = newObject.GetComponent<Interactible>(); interactible.inspectionInterface = inspectionInterface; interactible.tutorialManager = tutorialManager; } else { moving = false; waiting = false; currentTime = 0; EventManager.Instance.Raise(new BlockInputEvent() { block = false, navigation = false }); } } void Update() { if (waiting) { currentTime += Time.deltaTime; if (currentTime >= waitTime) { waiting = false; currentTime = 0; EventManager.Instance.Raise(new BlockInputEvent() { block = false, navigation = false }); } } if (moving) { if (move == EMoveType.RECEIVE && newObject.transform.localPosition.z <= targetPos.z) { rb.velocity = Vector3.zero; rb.useGravity = true; rb.drag = drag; foreach (Collider collider in colliders) collider.isTrigger = false; moving = false; waiting = true; } else if (move == EMoveType.GIVE_FIRST_STEP && previousObject.transform.localPosition.y >= targetPos.y) { move = EMoveType.GIVE_SECOND_STEP; targetPos = spawnPos; targetPos.x = previousObject.transform.localPosition.x; rb.velocity = (targetPos - previousObject.transform.localPosition); } else if (move == EMoveType.GIVE_SECOND_STEP && previousObject.transform.localPosition.z >= targetPos.z) { Destroy(previousObject); AddObjectToInventory(true); } } } }
using System; namespace Scanbot.ImagePicker.Droid.Utils { public class Platform { public static Android.App.Application Context { get => (Android.App.Application)Android.App.Application.Context; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Xml.Serialization; using Cinema.Data.Models; using Cinema.Data.Models.Enums; using Cinema.DataProcessor.ImportDto; using Newtonsoft.Json; namespace Cinema.DataProcessor { using System; using Data; public class Deserializer { private const string ErrorMessage = "Invalid data!"; private const string SuccessfulImportMovie = "Successfully imported {0} with genre {1} and rating {2}!"; private const string SuccessfulImportHallSeat = "Successfully imported {0}({1}) with {2} seats!"; private const string SuccessfulImportProjection = "Successfully imported projection {0} on {1}!"; private const string SuccessfulImportCustomerTicket = "Successfully imported customer {0} {1} with bought tickets: {2}!"; public static string ImportMovies(CinemaContext context, string jsonString) { var sb = new StringBuilder(); var jsonDto = JsonConvert.DeserializeObject<ImportMovieDto[]>(jsonString); foreach (var movie in jsonDto) { var isValid = IsValid(movie, out var validationResults); var isMovieIn = context.Movies.FirstOrDefault(x => x.Title == movie.Title); var isGenreValid = Enum.TryParse<Genre>(movie.Genre, out Genre genre); if (isValid && isMovieIn == null && isGenreValid) { var currentMovie = new Movie { Genre = genre, Title = movie.Title, Rating = movie.Rating, Director = movie.Director, Duration = movie.Duration }; context.Movies.Add(currentMovie); context.SaveChanges(); sb.AppendLine(string.Format(SuccessfulImportMovie, movie.Title, movie.Genre, movie.Rating.ToString("F2"))); } else { sb.AppendLine(ErrorMessage); continue; } } return sb.ToString().TrimEnd(); } public static string ImportHallSeats(CinemaContext context, string jsonString) { var sb = new StringBuilder(); var hallDtos = JsonConvert.DeserializeObject<ImportHallDto[]>(jsonString); foreach (var dto in hallDtos) { var isValid = IsValid(dto, out var validationResults); if (isValid) { var currentHall = new Hall { Is3D = dto.Is3D, Is4Dx = dto.Is4Dx, Name = dto.Name, }; var seatsCollection = new List<Seat>(); for (int i = 0; i < dto.Seats; i++) { seatsCollection.Add(new Seat { Hall = currentHall }); } currentHall.Seats = seatsCollection; context.Halls.Add(currentHall); context.SaveChanges(); string type = currentHall.Is3D == true ? "3D" : currentHall.Is4Dx == true ? "4Dx" : "Normal"; sb.AppendLine(string.Format(SuccessfulImportHallSeat, currentHall.Name, type, currentHall.Seats.Count)); } else { sb.AppendLine(ErrorMessage); continue; } } return sb.ToString().TrimEnd(); } public static string ImportProjections(CinemaContext context, string xmlString) { var serializer = new XmlSerializer(typeof(ImportProjectionDto[]), new XmlRootAttribute("Projections")); var projectionDtos = (ImportProjectionDto[]) serializer.Deserialize(new StringReader(xmlString)); var sb = new StringBuilder(); var moviesIds = context.Movies.Select(x => x.Id).ToArray(); var hallIds = context.Halls.Select(x => x.Id).ToArray(); foreach (var dto in projectionDtos) { bool isValid = IsValid(dto, out var validationResults); bool isMovieValid = moviesIds.Contains(dto.MovieId); bool isHallValid = hallIds.Contains(dto.HallId); var dateTime = DateTime.ParseExact(dto.DateTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); if (isValid && isMovieValid && isHallValid) { var currentProjection = new Projection { HallId = dto.HallId, MovieId = dto.MovieId, DateTime = dateTime }; context.Projections.Add(currentProjection); context.SaveChanges(); var result = string.Format(SuccessfulImportProjection, currentProjection.Movie.Title, currentProjection.DateTime.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)); sb.AppendLine(result); } else { sb.AppendLine(ErrorMessage); continue; } } return sb.ToString().TrimEnd(); } public static string ImportCustomerTickets(CinemaContext context, string xmlString) { var serializer = new XmlSerializer(typeof(ImportCustomerDto[]), new XmlRootAttribute("Customers")); var customerDtos = (ImportCustomerDto[]) serializer.Deserialize(new StringReader(xmlString)); var sb = new StringBuilder(); foreach (var dto in customerDtos) { bool isValid = IsValid(dto, out var validationResults); bool isValidTickets = dto.Tickets.All(x => IsValid(x, out var validationResults1)); if (isValid && isValidTickets) { var customer = new Customer { Age = dto.Age, Balance = dto.Balance, FirstName = dto.FirstName, LastName = dto.LastName, Tickets = dto.Tickets.Select(t=>new Ticket { ProjectionId = t.ProjectionId, Price = t.Price }).ToArray() }; context.Customers.Add(customer); context.SaveChanges(); var result = string.Format(SuccessfulImportCustomerTicket, customer.FirstName, customer.LastName, customer.Tickets.Count); sb.AppendLine(result); } else { sb.AppendLine(ErrorMessage); } } return sb.ToString().TrimEnd(); } private static bool IsValid(object testObj, out List<ValidationResult> validationResults) { validationResults = new List<ValidationResult>(); var context = new ValidationContext(testObj); return Validator.TryValidateObject(testObj, context, validationResults, validateAllProperties: true); } } }
using Newtonsoft.Json; namespace PholioVisualisation.PholioObjects { public class ComparatorMethod { [JsonProperty] public int Id { get; set; } [JsonProperty] public string Name { get; set; } [JsonProperty] public string ShortName { get; set; } [JsonProperty] public string Description { get; set; } [JsonProperty] public string Reference { get; set; } [JsonIgnore] public bool IsCurrent { get; set; } } }
using System; using System.Collections.Generic; using mCore.Domain.Entities; using mCore.Services.Process.Core.Definition; namespace mCore.Services.Process.Core.Runtime { public class Exexution : Entity { protected Exexution() { IsActive = true; Executions = new List<Exexution>(); } public string Name { get; private set; } public ProcessInstance ProcessInstance { get; private set; } public Exexution Parent { get; private set; } public ICollection<Exexution> Executions { get; private set; } public ActivityDefinition ActivityDefinition { get; private set; } public bool IsActive { get; private set; } public bool IsEnded { get; private set; } public bool IsConcurrent { get; private set; } public Exexution CreateExecution() { var createdExecution = new Exexution() { Parent = this, ProcessInstance = ProcessInstance, ActivityDefinition = ActivityDefinition, }; Executions.Add(createdExecution); // Event: entity created return createdExecution; } public void End() { IsActive = false; IsEnded = true; // perform activity_end throw new NotImplementedException(); } public void Take(Transition transition, bool fireActivityCompletionEvent = true) { if (fireActivityCompletionEvent) { // FireActivityCompletionEvent } ActivityDefinition = transition.Source; // perform transition_notify_listener_end } } }
using System; using System.Collections.Generic; using System.Data; using Newtonsoft.Json; using static Dapper.SqlMapper; namespace Dapper.Json { public abstract class CollectionTypeHandler<T> : ITypeHandler { public abstract void SetValue(IDbDataParameter parameter, IEnumerable<T> value); public abstract IEnumerable<T> Parse(object value); void ITypeHandler.SetValue(IDbDataParameter parameter, object value) { if (value is DBNull) { parameter.Value = value; } else { SetValue(parameter, (IEnumerable<T>)value); } } object ITypeHandler.Parse(Type destinationType, object value) { return Parse(value); } } }
namespace H_Solution_2 { public abstract class AbstractCommand { private string command; private Square square; public AbstractCommand(string command, Square square) { this.command = command; this.square = square; } public string getCommand() { return command; } public Square getSquare() { return square; } } }
using Kartrider.Api.Endpoints.Interfaces; using Kartrider.Api.Http.Interfaces; using System.Text.Json; using System.Threading.Tasks; namespace Kartrider.Api.Endpoints.UserEndpoint { /// <summary> /// 유저 정보 API Endpoint /// </summary> public class UserEndpoint : IUserEndpoint { private const string AccountRootUrl = "/users"; private const string ByNickname = "/nickname/{0}"; private readonly IRequester _requester; /// <summary> /// /// </summary> /// <param name="requester"></param> public UserEndpoint(IRequester requester) { _requester = requester; } /// <inheritdoc/> public async Task<User> GetUserByAccessIdAsync(string accessId) { var json = await _requester.CreateGetRequestAsync($"{AccountRootUrl}/{accessId}").ConfigureAwait(false); return JsonSerializer.Deserialize<User>(json); } /// <inheritdoc/> public async Task<User> GetUserByNicknameAsync(string nickname) { var json = await _requester.CreateGetRequestAsync($"{AccountRootUrl}{string.Format(ByNickname, nickname)}") .ConfigureAwait(false); return JsonSerializer.Deserialize<User>(json); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Jurassic; using Jurassic.Library; namespace UnitTests { /// <summary> /// Test the type utility routines. /// </summary> [TestClass] public class TypeUtilitiesTests : TestBase { [TestMethod] public void CreateListFromArrayLike() { // Basic array. var result = TypeUtilities.CreateListFromArrayLike((ObjectInstance)Evaluate("[1, 2, 3]")); Assert.AreEqual(3, result.Length); Assert.AreEqual(1, result[0]); Assert.AreEqual(2, result[1]); Assert.AreEqual(3, result[2]); // Array with holes. result = TypeUtilities.CreateListFromArrayLike((ObjectInstance)Evaluate("[3, , 5]")); Assert.AreEqual(3, result.Length); Assert.AreEqual(3, result[0]); Assert.AreEqual(Undefined.Value, result[1]); Assert.AreEqual(5, result[2]); // Array-like. result = TypeUtilities.CreateListFromArrayLike((ObjectInstance)Evaluate("({ })")); Assert.AreEqual(0, result.Length); // Array-like. result = TypeUtilities.CreateListFromArrayLike((ObjectInstance)Evaluate("({ length: 3, 0: 4, 1: 2, 2: 0 })")); Assert.AreEqual(3, result.Length); Assert.AreEqual(4, result[0]); Assert.AreEqual(2, result[1]); Assert.AreEqual(0, result[2]); // Array-like with holes. result = TypeUtilities.CreateListFromArrayLike((ObjectInstance)Evaluate("({ length: 3, 0: 2, 2: 3 })")); Assert.AreEqual(3, result.Length); Assert.AreEqual(2, result[0]); Assert.AreEqual(Undefined.Value, result[1]); Assert.AreEqual(3, result[2]); } } }
/* Copyright 2020 Leaping Gorilla LTD Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Diagnostics; using System.Threading.Tasks; using LeapingGorilla.Testing.Core.Attributes; using LeapingGorilla.Testing.NUnit.Attributes; using LeapingGorilla.Testing.NUnit.Tests.Mocks; using NUnit.Framework; namespace LeapingGorilla.Testing.NUnit.Tests { public class WhenGivenMethodAwaitsTask : WhenTestingTheBehaviourOf { private int _newValue; private int _newValuePlusFive; private long _msPassed; private ClassWithAsyncMethods _classWithAsyncMethods; [Given(0)] public void WeHaveClassWithAsyncMethods() { _classWithAsyncMethods = new ClassWithAsyncMethods(); } [Given(1)] public async Task WeCanAwaitMethod() { _newValue = await _classWithAsyncMethods.ReturnSomeNumberPlusOne(3); } [Given(1)] public async Task WeCanAwaitAsyncMethod() { var sw = Stopwatch.StartNew(); _newValuePlusFive = await _classWithAsyncMethods.DelayThenReturnSomeNumberPlusFive(3); _msPassed = sw.ElapsedMilliseconds; } [Then] public void NewValueUpdated() { Assert.That(_newValue, Is.EqualTo(4)); } [Then] public void AsyncClassCreated() { Assert.That(_classWithAsyncMethods, Is.Not.Null); } [Then] public void AsyncMethodReturnsResult() { Assert.That(_newValuePlusFive, Is.EqualTo(8)); } [Then] public void AsyncMethodCorrectlyDelayed() { Console.WriteLine("Time taken: {0}", _msPassed); Assert.That(_msPassed, Is.GreaterThanOrEqualTo(ClassWithAsyncMethods.DelayInMilliseconds)); } } }
namespace Bakery.Models { public class Bread { public int LoafCount {get; set;} public Bread(int loafCount) { LoafCount = loafCount; } public int BreadCost() { int loafCost = 5; if (LoafCount <= 2) { return loafCost * LoafCount; } else if (LoafCount % 3 != 0) { int breadSpecial = loafCost * ((LoafCount - (LoafCount % 3)) / 3); return (LoafCount * loafCost) - breadSpecial; } else { return (LoafCount / 3) * 10; } } } }
namespace NBaseRepository.SQL { using System; using System.Collections.Generic; using Common; public abstract class SqlBuilder<T, TId> where T : IEntity<TId> { private readonly string _tableName; private readonly IEnumerable<string> _columns; private string _query; protected SqlBuilder(string tableName, params string[] columns) { _tableName = tableName; _columns = columns; } public string Query { get { var toReturn = _query; _query = string.Empty; return toReturn; } } protected Func<T, IReadOnlyList<string>> EntityProperties { get; } public SqlBuilder<T, TId> SelectAll() { _query = $"SELECT * FROM {_tableName}"; return this; } public SqlBuilder<T, TId> GetById(TId id) { _query += $" WHERE Id == \'{id}\'"; return this; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SkillBarController : MonoBehaviour { [SerializeField] private BoterkroonSkills targetSkill = BoterkroonSkills.Baking; [SerializeField] private MultiLevelSlider multiSlider = null; [SerializeField] private CanvasGroup canvasGroup = null; private void OnEnable() { if (SaveController.Instance.GameData.BoterKroon.IsSkillActive(targetSkill)) { canvasGroup.alpha = 1; } else { canvasGroup.alpha = 0; } List<float> normalizedResults = new List<float>(); float previousValue = 0; bool hasNewValue = false; foreach (var result in SaveController.Instance.GameData.BoterKroon.GetControlResultsFor(targetSkill)) { float newValue = result.TotalXP / (float)BoterkroonValues.Values.MaxSkillXP; normalizedResults.Add(newValue - previousValue); previousValue = newValue; if (result.IsNew) { hasNewValue = true; result.IsNew = false; } } multiSlider.UpdateValues(hasNewValue, normalizedResults.ToArray()); } }
using System; namespace RRLab.PhysiologyWorkbench.Data { /// <summary> /// <c>Annotation</c> objects store commentary information about a physiology data object. /// </summary> [Serializable()] public class Annotation { /** * <summary> * <c>Annotation(String text)</c> creates an <c>Annotation</c> object with the <c>Text</c> * property set to <c>text</c>. The <c>Time</c> property is set to <c>DateTime.Now</c>. * </summary> **/ public Annotation(String text, string user) { this.Text = text; this.Time = DateTime.Now; this.User = user; } /** * <summary> * <c>Annotation(DateTime time, String text)</c> creates an <c>Annotation</c> object with the <c>Text</c> * property set to <c>text</c> and the <c>Time</c> property set to <c>time</c>. <c>time</c> should be in Utc format. * </summary> **/ public Annotation(DateTime time, String text, string user) { this.Text = text; this.Time = time; this.User = user; } /** * <summary> * <c>ToString()</c> returns the Annotation as {Time}: {Text}. * </summary> **/ public override string ToString() { return this.Time.ToLocalTime().ToString("t") + ": " + this.Text; } private String _Text; /** * <summary> * <c>Text</c> contains the Annotation's message.</c> * </summary> **/ public String Text { get { return _Text; } set { _Text = value; } } private DateTime _Time = DateTime.Now; /** * <summary> * <c>Time</c> contains the <c>DateTime</c> corresponding with the time the annotation was created. * The default value is <c>DateTime.Now</c>. **/ public DateTime Time { get { return _Time; } set { _Time = value; } } private string _User; public string User { get { return _User; } set { _User = value; } } } }
using System; namespace Mason.Core.Thunderstore { public sealed class DescriptionString : ConstrainedString<DescriptionString> { public static DescriptionString? TryParse(string value) { return value.Length > 250 ? null : new DescriptionString(value); } public static DescriptionString Parse(string value) { return TryParse(value) ?? throw new ArgumentException("Not a valid description", nameof(value)); } private DescriptionString(string value) : base(value) { } } }
using System; namespace Softing.OPCToolbox.Server { /// <summary> /// Describes the possible Address space type /// </summary> /// <include /// file='TBNS.doc.xml' /// path='//enum[@name="EnumAddressSpaceType"]/doc/*' /// /> public enum EnumAddressSpaceType : byte { /// <summary>The Address space is based on objects</summary> OBJECT_BASED = 0x01, /// <summary>The address space consists of strings</summary> STRING_BASED = 0x02, /// <summary>The Namespace consists of objects and strings</summary> OBJECT_STRING_BASED = 0x03 } // end EnumAddressSpaceType /// <summary> /// The type of the address space element. exclusively used in the OTB interogations. /// </summary> internal enum EnumAddressSpaceElementType : byte { DA = 0x01, AE = 0x02 } // EnumAddressSpaceElementType /// <summary> /// The type of Application. /// </summary> /// <include /// file='TBNS.doc.xml' /// path='//enum[@name="EnumApplicationType"]/doc/*' /// /> public enum EnumApplicationType : byte { /// <summary>The OPC server application is an executable.</summary> EXECUTABLE = 1, /// <summary>The OPC server application is an library.</summary> LIBRARY = 0 } // end ApplicationType /// <summary> /// Special cache expiry settings for the string-based (syntax-based) namespace object data. /// If not using below enums, a value in milliseconds is expected. /// </summary> /// <include /// file='TBNS.doc.xml' /// path='//enum[@name="StringBasedExpiryTimeout"]/doc/*' /// /> public enum StringBasedExpiryTimeout: ulong { /// <summary>The internal OPC DA Server cache for string-based object data is disabled. /// Every time the CORE needs any data it will invoke vendor-application callbacks.</summary> DISABLED = 0xFFFFFFFFUL, /// <summary>The internal OPC DA Server cache for string-based object data is set to never expire. /// Data provided once will never be requested again.</summary> INFINITE = 0x0UL } // end StringBasedExpiryTimeout /// <summary> /// Possible the Input/Outpus modes /// </summary> /// <include /// file='TBNS.doc.xml' /// path='//enum[@name="EnumIoMode"]/doc/*' /// /> public enum EnumIoMode : byte { /// <summary> No IO </summary> NONE = 0x00, /// <summary> Client driven </summary> POLL = 0x01, /// <summary> Server reports changes </summary> REPORT = 0x02, /// <summary> Polled own cache </summary> POLL_OWNCACHE = 0x11, /// <summary> Server reports changes for cyclic data</summary> REPORT_CYCLIC = 0x22 } // end IoMode /// <summary> /// The type (direction) of the transaction /// </summary> /// <include /// file='TBNS.doc.xml' /// path='//enum[@name="EnumTransactionType"]/doc/*' /// /> public enum EnumTransactionType : byte { /// <summary>The client asked for some value(s)</summary> READ = 0x01, /// <summary>The client attempts to write some value(s)</summary> WRITE = 0x02 } // end TransactionType /// <summary> /// Request's possible states /// </summary> /// <include /// file='TBNS.doc.xml' /// path='//enum[@name="EnumRequestState"]/doc/*' /// /> public enum EnumRequestState : byte { /// <summary> The request has just been created</summary> CREATED = 0x01, /// <summary> The request is about to be processed</summary> PENDING = 0x03, /// <summary> The request is being processed by the vendor application</summary> INPROGRESS = 0x04, /// <summary> The request was processed and is now completed</summary> COMPLETED = 0x05 } // end EnumRequestState /// <summary> /// Type of a connected session /// </summary> /// <include /// file='TBNS.doc.xml' /// path='//enum[@name="EnumSessionType"]/doc/*' /// /> public enum EnumSessionType : byte { /// <summary>Data Access session </summary> DA = 0x01, /// <summary>Data Access over XML</summary> XMLDA = 0x06, /// <summary>Internal XML-DA subscription</summary> XMLSUBSCRIPTIONS = 0x02, /// <summary>Alarms and events session </summary> AE = 0x08 } // end EnumSessionType /// <summary> /// Defines the <see cref="DaSession"/> possible states /// </summary> /// <include /// file='TBNS.doc.xml' /// path='//enum[@name="EnumSessionState"]/doc/*' /// /> internal enum EnumSessionState : short { /// <summary> /// Session created by the OPC client /// </summary> CREATE = 0, /// <summary> /// session is loging on /// </summary> LOGON = 1, /// <summary> /// session is logging off /// </summary> LOGOFF = 2, /// <summary> /// session information is changed /// </summary> MODIFY = 3, /// <summary> /// session is destroyed by the OPC client /// </summary> DESTROY = -1 } // end EnumSessionState } // end namespace Softing.OPCToolbox.Server
using VCSFramework; using VCSFramework.Templates.Standard; using static VCSFramework.Registers; namespace Samples { [TemplatedProgram(typeof(StandardTemplate))] public static class StandardTemplateSample { private static byte BackgroundColor; [VBlank] public static void ResetBackgroundColor() => BackgroundColor = 0; [Kernel(KernelType.EveryScanline)] [KernelScanlineRange(192, 96)] public static void KernelAscend() { ColuBk = BackgroundColor; BackgroundColor++; } [Kernel(KernelType.EveryScanline)] [KernelScanlineRange(96, 0)] public static void KernelDescend() { ColuBk = BackgroundColor; BackgroundColor--; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Web; using Server.MasterData.DTO.Data; using Server.MasterData.DTO.Data.Game; using Server.MasterData.DTO.Response; namespace Server.MasterData.DTO.Request { /// <summary> /// Game requests relate to actions or queries that relate to non-user specific game data /// </summary> public interface IGameDataRequest<T> : IRequest<T> { int? AdminId { get; set; } } [DataContract] public class GameDataRequest<T> : IGameDataRequest<IGameData> { public RequestType RequestType { get; set; } public IGameData Payload { get; set; } public Type PayloadType { get; set; } public int? AdminId { get; set; } } // // public class GameDataRequest : , IGameDataRequest // { // public GameDataRequest(RequestType requestType) // { // RequestType = requestType; // } // // public GameData Payload { get; set; } // } }
namespace CaseManagement.HumanTask.Domains { public enum NotificationInstanceStatus { READY = 0, REMOVED = 1 } }
using System; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.SIP.Stack { /// <summary> /// This class holds known SIP timer constant values. /// </summary> internal class SIP_TimerConstants { public const int T1 = 500; public const int T2 = 4000; public const int T4 = 5000; } }
using System; using iSukces.Parsers.TokenParsers; using Xunit; namespace SimpleParser.Tests { public class DateTokenizerTests { [Fact] public void T01_Should_parse_date() { var t = new RegexpDateTokenizer(); var c = t.Parse("2020-01-03"); Assert.Equal(new DateTime(2020, 1, 3), (DateTime)c.Token); } [Fact] public void T02_Should_parse_date() { var t = new ManualDateTokenizer(); var c = t.Parse("2020-01-03"); Assert.Equal(new DateTime(2020, 1, 3), (DateTime)c.Token); } [Fact] public void T03_Should_handle_overflow_excption() { var t = new RegexpDateTokenizer(); var c = t.Parse("2020-31-03"); Assert.Null(c); } [Fact] public void T04_Should_handle_overflow_excption() { var t = new ManualDateTokenizer(); var c = t.Parse("2020-31-03"); Assert.Null(c); } } }
namespace Noise.Infrastructure.Dto { public class StreamInfo { public int Channel { get; private set; } public string Artist { get; private set; } public string Album { get; private set; } public string Title { get; private set; } public string Genre { get; private set; } public StreamInfo( int channel, string artist, string album, string title, string genre ) { Channel = channel; Artist = artist; Album = album; Title = title; Genre = genre; } } }
using System.Text.RegularExpressions; namespace JonasSchubert.Snippets.String { /// <summary> /// Partial class for string snippets /// </summary> public static partial class String { /// <summary> /// Splits a multiline string into an array of lines. /// </summary> public static string[] SplitLines(this string input) => Regex.Split(input, "\r?\n"); } }
using System; using System.IO; using System.Text; using FluentAssertions; using NUnit.Framework; using Vostok.Logging.Abstractions; using Vostok.Logging.Formatting.Tokens; namespace Vostok.Logging.Formatting.Tests.Tokens { [TestFixture] internal class PropertyToken_Tests { private PropertyToken token; private LogEvent @event; [SetUp] public void TestSetup() { token = new PropertyToken("prop", "D5"); @event = new LogEvent(LogLevel.Info, DateTimeOffset.Now, null); } [Test] public void Should_render_nothing_for_event_without_properties() { Render().Should().BeEmpty(); } [Test] public void Should_not_insert_surrounding_spaces_around_missing_property() { token = new PropertyToken("prop", "wW"); Render().Should().BeEmpty(); } [Test] public void Should_render_nothing_for_event_without_needed_property() { @event = @event .WithProperty("anotherProp1", 1) .WithProperty("anotherProp2", 2); Render().Should().BeEmpty(); } [Test] public void Should_render_value_of_existing_property_using_provided_format() { @event = @event.WithProperty("prop", 1); Render().Should().Be("00001"); } private string Render() { var stringBuilder = new StringBuilder(); var stringWriter = new StringWriter(stringBuilder); token.Render(@event, stringWriter, null); return stringBuilder.ToString(); } } }
using System.Text.Json.Serialization; namespace PaninApi.Abstractions.Dtos { public class InputStudentClassDto { [JsonPropertyName("class")] public int Class { get; set; } [JsonPropertyName("section")] public string Section { get; set; } } }
// // ListViewGroupCollection.cs // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (c) 2006 Daniel Nauck // // Author: // Daniel Nauck (dna(at)mono-project(dot)de) // Carlos Alberto Cortez <calberto.cortez@gmail.com> using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.ComponentModel; namespace System.Windows.Forms { [ListBindable(false)] public class ListViewGroupCollection : IList, ICollection, IEnumerable { private List<ListViewGroup> list = null; private ListView list_view_owner = null; private ListViewGroup default_group; ListViewGroupCollection() { list = new List<ListViewGroup> (); default_group = new ListViewGroup ("Default Group"); default_group.IsDefault = true; } internal ListViewGroupCollection(ListView listViewOwner) : this() { list_view_owner = listViewOwner; default_group.ListViewOwner = listViewOwner; } internal ListView ListViewOwner { get { return list_view_owner; } set { list_view_owner = value; } } #region IEnumerable Members public IEnumerator GetEnumerator() { return list.GetEnumerator(); } #endregion #region ICollection Members public void CopyTo(Array array, int index) { ((ICollection) list).CopyTo(array, index); } public int Count { get { return list.Count; } } bool ICollection.IsSynchronized { get { return true; } } object ICollection.SyncRoot { get { return this; } } #endregion #region IList Members int IList.Add(object value) { if (!(value is ListViewGroup)) throw new ArgumentException("value"); return Add((ListViewGroup)value); } public int Add(ListViewGroup group) { if (Contains(group)) return -1; AddGroup (group); if (this.list_view_owner != null) list_view_owner.Redraw(true); return list.Count - 1; } public ListViewGroup Add(string key, string headerText) { ListViewGroup newGroup = new ListViewGroup(key, headerText); Add(newGroup); return newGroup; } public void Clear() { foreach (ListViewGroup group in list) group.ListViewOwner = null; list.Clear (); if(list_view_owner != null) list_view_owner.Redraw(true); } bool IList.Contains(object value) { if (value is ListViewGroup) return Contains((ListViewGroup)value); else return false; } public bool Contains(ListViewGroup value) { return list.Contains(value); } int IList.IndexOf(object value) { if (value is ListViewGroup) return IndexOf((ListViewGroup)value); else return -1; } public int IndexOf(ListViewGroup value) { return list.IndexOf(value); } void IList.Insert(int index, object value) { if (value is ListViewGroup) Insert(index, (ListViewGroup)value); } public void Insert(int index, ListViewGroup group) { if (Contains(group)) return; CheckListViewItemsInGroup(group); group.ListViewOwner = list_view_owner; list.Insert(index, group); if(list_view_owner != null) list_view_owner.Redraw(true); } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } void IList.Remove(object value) { Remove((ListViewGroup)value); } public void Remove (ListViewGroup group) { int idx = list.IndexOf (group); if (idx != -1) RemoveAt (idx); } public void RemoveAt (int index) { if (list.Count <= index || index < 0) return; ListViewGroup group = list [index]; group.ListViewOwner = null; list.RemoveAt (index); if (list_view_owner != null) list_view_owner.Redraw (true); } object IList.this[int index] { get { return this[index]; } set { if (value is ListViewGroup) this[index] = (ListViewGroup)value; } } public ListViewGroup this[int index] { get { if (list.Count <= index || index < 0) throw new ArgumentOutOfRangeException("index"); return list [index]; } set { if (list.Count <= index || index < 0) throw new ArgumentOutOfRangeException("index"); if (Contains (value)) return; if (value != null) CheckListViewItemsInGroup (value); list [index] = value; if (list_view_owner != null) list_view_owner.Redraw(true); } } public ListViewGroup this [string key] { get { int idx = IndexOfKey (key); if (idx != -1) return this [idx]; return null; } set { int idx = IndexOfKey (key); if (idx == -1) return; this [idx] = value; } } int IndexOfKey (string key) { for (int i = 0; i < list.Count; i++) if (list [i].Name == key) return i; return -1; } #endregion public void AddRange(ListViewGroup[] groups) { foreach (ListViewGroup group in groups) AddGroup (group); if (list_view_owner != null) list_view_owner.Redraw (true); } public void AddRange(ListViewGroupCollection groups) { foreach (ListViewGroup group in groups) AddGroup (group); if (list_view_owner != null) list_view_owner.Redraw (true); } internal ListViewGroup GetInternalGroup (int index) { if (index == 0) return default_group; return list [index - 1]; } internal int InternalCount { get { return list.Count + 1; } } internal ListViewGroup DefaultGroup { get { return default_group; } } void AddGroup (ListViewGroup group) { if (Contains (group)) return; CheckListViewItemsInGroup (group); group.ListViewOwner = list_view_owner; list.Add (group); } private void CheckListViewItemsInGroup(ListViewGroup value) { //check for correct ListView foreach (ListViewItem item in value.Items) { if (item.ListView != null && item.ListView != this.list_view_owner) throw new ArgumentException("ListViewItem belongs to a ListView control other than the one that owns this ListViewGroupCollection.", "ListViewGroup"); } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace DiscoveryTestProject3 { [TestClass] public class LongDiscoveryTestClass { [MyTestMethod] public void CustomTestMethod() { } } internal class MyTestMethodAttribute : TestMethodAttribute { public MyTestMethodAttribute() { Thread.Sleep(10000); } } }
// 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.Diagnostics; using System.IO; using System.Text; using ICSharpCode.AvalonEdit.Xml; using ICSharpCode.SharpZipLib.Zip; using NUnit.Framework; namespace ICSharpCode.AvalonEdit.Xml { class TestFile { public string Name { get; set; } public string Content { get; set; } public string Canonical { get; set; } public string Description { get; set; } } [TestFixture] public class ParserTests { readonly string zipFileName = @"XmlParser\W3C.zip"; List<TestFile> xmlFiles = new List<TestFile>(); [TestFixtureSetUp] public void OpenZipFile() { ZipFile zipFile = new ZipFile(zipFileName); Dictionary<string, TestFile> xmlFiles = new Dictionary<string, TestFile>(); // Decompress XML files foreach(ZipEntry zipEntry in zipFile.Cast<ZipEntry>().Where(zip => zip.IsFile && zip.Name.EndsWith(".xml"))) { Stream stream = zipFile.GetInputStream(zipEntry); string content = new StreamReader(stream).ReadToEnd(); xmlFiles.Add(zipEntry.Name, new TestFile { Name = zipEntry.Name, Content = content }); } // Add descriptions foreach(TestFile metaData in xmlFiles.Values.Where(f => f.Name.StartsWith("ibm/ibm_oasis"))) { var doc = System.Xml.Linq.XDocument.Parse(metaData.Content); foreach(var testElem in doc.Descendants("TEST")) { string uri = "ibm/" + testElem.Attribute("URI").Value; string description = testElem.Value.Replace("\n ", "\n").TrimStart('\n'); if (xmlFiles.ContainsKey(uri)) xmlFiles[uri].Description = description; } } // Copy canonical forms foreach(TestFile canonical in xmlFiles.Values.Where(f => f.Name.Contains("/out/"))) { string uri = canonical.Name.Replace("/out/", "/"); if (xmlFiles.ContainsKey(uri)) xmlFiles[uri].Canonical = canonical.Content; } // Copy resuts to field this.xmlFiles.AddRange(xmlFiles.Values.Where(f => !f.Name.Contains("/out/"))); } IEnumerable<TestFile> GetXmlFilesStartingWith(string directory) { return xmlFiles.Where(f => f.Name.StartsWith(directory)); } [Test] public void W3C_Valid() { string[] exclude = { // NAME in DTD infoset "ibm02v01", "ibm03v01", "ibm85v01", "ibm86v01", "ibm87v01", "ibm88v01", "ibm89v01", }; TestFiles(GetXmlFilesStartingWith("ibm/valid/"), true, exclude); } [Test] public void W3C_Invalid() { string[] exclude = { // Default attribute value "ibm56i03", }; TestFiles(GetXmlFilesStartingWith("ibm/invalid/"), true, exclude); } [Test] public void W3C_NotWellformed() { string[] exclude = { // XML declaration well formed "ibm23n", "ibm24n", "ibm26n01", "ibm32n", "ibm80n06", "ibm81n01", "ibm81n02", "ibm81n03", "ibm81n04", "ibm81n05", "ibm81n06", "ibm81n07", "ibm81n08", "ibm81n09", // Invalid chars in a comment - do we care? "ibm02n", // Invalid char ref - do we care? "ibm66n12", "ibm66n13", "ibm66n14", "ibm66n15", // DTD in wrong location "ibm27n01", "ibm43n", // Entity refs depending on DTD "ibm41n10", "ibm41n11", "ibm41n12", "ibm41n13", "ibm41n14", "ibm68n04", "ibm68n06", "ibm68n07", "ibm68n08", "ibm68n09", "ibm68n10", // DTD Related tests "ibm09n01", "ibm09n02", "ibm13n01", "ibm13n02", "ibm13n03", "ibm28n01", "ibm28n02", "ibm28n03", "ibm29n01", "ibm29n03", "ibm29n04", "ibm29n07", "ibm30n01", "ibm31n01", "ibm45n01", "ibm45n02", "ibm45n03", "ibm45n04", "ibm45n05", "ibm45n06", "ibm46n01", "ibm46n02", "ibm46n03", "ibm46n04", "ibm46n05", "ibm47n01", "ibm47n02", "ibm47n03", "ibm47n04", "ibm47n05", "ibm47n06", "ibm48n01", "ibm48n02", "ibm48n03", "ibm48n04", "ibm48n05", "ibm48n06", "ibm48n07", "ibm49n01", "ibm49n02", "ibm49n03", "ibm49n04", "ibm49n05", "ibm49n06", "ibm50n01", "ibm50n02", "ibm50n03", "ibm50n04", "ibm50n05", "ibm50n06", "ibm50n07", "ibm51n01", "ibm51n02", "ibm51n03", "ibm51n04", "ibm51n05", "ibm51n06", "ibm51n07", "ibm52n01", "ibm52n02", "ibm52n03", "ibm53n01", "ibm53n02", "ibm53n03", "ibm53n04", "ibm53n05", "ibm53n06", "ibm53n07", "ibm53n08", "ibm54n01", "ibm54n02", "ibm55n01", "ibm55n02", "ibm55n03", "ibm56n01", "ibm56n02", "ibm56n03", "ibm56n04", "ibm56n05", "ibm56n06", "ibm56n07", "ibm57n01", "ibm58n01", "ibm58n02", "ibm58n03", "ibm58n04", "ibm58n05", "ibm58n06", "ibm58n07", "ibm58n08", "ibm59n01", "ibm59n02", "ibm59n03", "ibm59n04", "ibm59n05", "ibm59n06", "ibm60n01", "ibm60n02", "ibm60n03", "ibm60n04", "ibm60n05", "ibm60n06", "ibm60n07", "ibm60n08", "ibm61n01", "ibm62n01", "ibm62n02", "ibm62n03", "ibm62n04", "ibm62n05", "ibm62n06", "ibm62n07", "ibm62n08", "ibm63n01", "ibm63n02", "ibm63n03", "ibm63n04", "ibm63n05", "ibm63n06", "ibm63n07", "ibm64n01", "ibm64n02", "ibm64n03", "ibm65n01", "ibm65n02", "ibm66n01", "ibm66n03", "ibm66n05", "ibm66n07", "ibm66n09", "ibm66n11", "ibm69n01", "ibm69n02", "ibm69n03", "ibm69n04", "ibm69n05", "ibm69n06", "ibm69n07", "ibm70n01", "ibm71n01", "ibm71n02", "ibm71n03", "ibm71n04", "ibm71n05", "ibm72n01", "ibm72n02", "ibm72n03", "ibm72n04", "ibm72n05", "ibm72n06", "ibm72n09", "ibm73n01", "ibm73n03", "ibm74n01", "ibm75n01", "ibm75n02", "ibm75n03", "ibm75n04", "ibm75n05", "ibm75n06", "ibm75n07", "ibm75n08", "ibm75n09", "ibm75n10", "ibm75n11", "ibm75n12", "ibm75n13", "ibm76n01", "ibm76n02", "ibm76n03", "ibm76n04", "ibm76n05", "ibm76n06", "ibm76n07", "ibm77n01", "ibm77n02", "ibm77n03", "ibm77n04", "ibm78n01", "ibm78n02", "ibm79n01", "ibm79n02", "ibm82n01", "ibm82n02", "ibm82n03", "ibm82n04", "ibm82n08", "ibm83n01", "ibm83n03", "ibm83n04", "ibm83n05", "ibm83n06", // No idea what this is "misc/432gewf", "ibm28an01", }; TestFiles(GetXmlFilesStartingWith("ibm/not-wf/"), false, exclude); } StringBuilder errorOutput; void TestFiles(IEnumerable<TestFile> files, bool areWellFormed, string[] exclude) { errorOutput = new StringBuilder(); int testsRun = 0; int ignored = 0; foreach (TestFile file in files) { if (exclude.Any(exc => file.Name.Contains(exc))) { ignored++; } else { testsRun++; TestFile(file, areWellFormed); } } if (testsRun == 0) { Assert.Fail("Test files not found"); } if (errorOutput.Length > 0) { // Can not output ]]> otherwise nuint will crash Assert.Fail(errorOutput.Replace("]]>", "]]~NUNIT~>").ToString()); } } /// <remarks> /// If using DTD, canonical representation is not checked /// If using DTD, uknown entiry references are not error /// </remarks> bool TestFile(TestFile testFile, bool isWellFormed) { bool passed = true; string content = testFile.Content; Debug.WriteLine("Testing " + testFile.Name + "..."); AXmlParser parser = new AXmlParser(); bool usingDTD = content.Contains("<!DOCTYPE") && (content.Contains("<!ENTITY") || content.Contains(" SYSTEM ")); if (usingDTD) parser.UnknownEntityReferenceIsError = false; AXmlDocument document; parser.Lock.EnterWriteLock(); try { document = parser.Parse(content, null); } finally { parser.Lock.ExitWriteLock(); } string printed = PrettyPrintAXmlVisitor.PrettyPrint(document); if (content != printed) { errorOutput.AppendFormat("Output of pretty printed XML for \"{0}\" does not match the original.\n", testFile.Name); errorOutput.AppendFormat("Pretty printed:\n{0}\n", Indent(printed)); passed = false; } if (isWellFormed && !usingDTD) { string canonicalPrint = CanonicalPrintAXmlVisitor.Print(document); if (testFile.Canonical != null) { if (testFile.Canonical != canonicalPrint) { errorOutput.AppendFormat("Canonical XML for \"{0}\" does not match the excpected.\n", testFile.Name); errorOutput.AppendFormat("Expected:\n{0}\n", Indent(testFile.Canonical)); errorOutput.AppendFormat("Seen:\n{0}\n", Indent(canonicalPrint)); passed = false; } } else { errorOutput.AppendFormat("Can not find canonical output for \"{0}\"", testFile.Name); errorOutput.AppendFormat("Suggested canonical output:\n{0}\n", Indent(canonicalPrint)); passed = false; } } bool hasErrors = document.SyntaxErrors.FirstOrDefault() != null; if (isWellFormed && hasErrors) { errorOutput.AppendFormat("Syntax error(s) in well formed file \"{0}\":\n", testFile.Name); foreach (var error in document.SyntaxErrors) { string followingText = content.Substring(error.StartOffset, Math.Min(10, content.Length - error.StartOffset)); errorOutput.AppendFormat("Error ({0}-{1}): {2} (followed by \"{3}\")\n", error.StartOffset, error.EndOffset, error.Message, followingText); } passed = false; } if (!isWellFormed && !hasErrors) { errorOutput.AppendFormat("No syntax errors reported for mallformed file \"{0}\"\n", testFile.Name); passed = false; } // Epilog if (!passed) { if (testFile.Description != null) { errorOutput.AppendFormat("Test description:\n{0}\n", Indent(testFile.Description)); } errorOutput.AppendFormat("File content:\n{0}\n", Indent(content)); errorOutput.AppendLine(); } return passed; } string Indent(string text) { return " " + text.TrimEnd().Replace("\n", "\n "); } } }
using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading.Tasks; using WebWallet.Data.Contracts; using WebWallet.Models.Contracts; namespace WebWallet.Data.Repositories { public class Repository<TEntity> : BaseRepository, IRepository<TEntity> where TEntity : class, IEntity { private readonly WebWalletDBContext _dbContext; public Repository(WebWalletDBContext dbContext) { this._dbContext = dbContext; } public async Task<bool> Create(TEntity entity) { await this._dbContext.Set<TEntity>().AddAsync(entity); return (await this._dbContext.SaveChangesAsync()) > 0; } public async Task<bool> Delete(string id) { var entity = await this.GetById(id); ThrowIfIsNull(entity); this._dbContext.Set<TEntity>().Remove(entity); return (await this._dbContext.SaveChangesAsync()) > 0; } public IQueryable<TEntity> GetAll() { return _dbContext.Set<TEntity>().AsNoTracking(); } public async Task<TEntity> GetById(string id) { var entity = await _dbContext.Set<TEntity>() .AsNoTracking() .FirstOrDefaultAsync(e => e.Id == id); ThrowIfIsNull(entity); return entity; } public async Task<bool> Update(TEntity entity) { this._dbContext.Set<TEntity>().Update(entity); return (await this._dbContext.SaveChangesAsync()) > 0; } } }
using Microsoft.Extensions.Caching.Memory; using System; using System.Collections.Generic; using WebArchivProject.Contracts; using WebArchivProject.Models.DTO; namespace WebArchivProject.Services { class ServStartItemsCash : IServStartItemsCash { private readonly IMemoryCache _cache; private readonly IServUserSession _userSession; private string KeyId => string .Format("StartItems_{0}", _userSession.User.Id); public ServStartItemsCash( IMemoryCache cache, IServUserSession userSession) { _cache = cache; _userSession = userSession; } public DtoStartItem StartItem => GetStartItem(); /// <summary> /// Инициализируем кеш /// </summary> public void InitStartItemCash() { UpdateStartItem(EmptyStartItem); } /// <summary> /// Обновление кеша /// </summary> public void UpdateStartItem(DtoStartItem dtoStartItem) { _cache.Remove(KeyId); _cache.Set(KeyId, dtoStartItem, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds ( value: _userSession.User.Expirate - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() ) }); } /// <summary> /// Получение объекта из кеша /// </summary> private DtoStartItem GetStartItem() { object obj = _cache.Get(KeyId); return obj as DtoStartItem; } /// <summary> /// Создание пустого объекта кеша /// </summary> private DtoStartItem EmptyStartItem => new DtoStartItem { Name = string.Empty, Year = string.Empty, ItemType = string.Empty, Authors = new List<DtoAuthor> { new DtoAuthor { NameUa = string.Empty, NameRu = string.Empty, NameEn = string.Empty, IsEmptyObj = true } } }; } }
using UAIC.RealEstateAgency.EstatesBase; namespace UAIC.RealEstateAgency.Agents { public class ImmobileAgent : EstateAgent, IImmobileAgent { public string GetAddress(Immobile immobile) { return immobile.address; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharpGL { /// <summary> /// Storage of *.DDS file. /// </summary> public class DDSStorage : TexStorageBase { private vglImageData imageData; public DDSStorage(vglImageData imageData) : base((TextureTarget)imageData.target, imageData.internalFormat, imageData.mipLevels, false) { this.imageData = imageData; } public override void Apply() { vglImageData imageData = this.imageData; IntPtr ptr = imageData.mip[0].data; int level; GL gl = GL.Instance; switch (imageData.target) { case GL.GL_TEXTURE_1D: glTexStorage1D(imageData.target, imageData.mipLevels, imageData.internalFormat, imageData.mip[0].width); for (level = 0; level < imageData.mipLevels; ++level) { gl.TexSubImage1D(GL.GL_TEXTURE_1D, level, 0, imageData.mip[level].width, imageData.format, imageData.type, imageData.mip[level].data); } break; case GL.GL_TEXTURE_1D_ARRAY: glTexStorage2D(imageData.target, imageData.mipLevels, imageData.internalFormat, imageData.mip[0].width, imageData.slices); for (level = 0; level < imageData.mipLevels; ++level) { gl.TexSubImage2D(GL.GL_TEXTURE_1D, level, 0, 0, imageData.mip[level].width, imageData.slices, imageData.format, imageData.type, imageData.mip[level].data); } break; case GL.GL_TEXTURE_2D: glTexStorage2D(imageData.target, imageData.mipLevels, imageData.internalFormat, imageData.mip[0].width, imageData.mip[0].height); for (level = 0; level < imageData.mipLevels; ++level) { gl.TexSubImage2D(GL.GL_TEXTURE_2D, level, 0, 0, imageData.mip[level].width, imageData.mip[level].height, imageData.format, imageData.type, imageData.mip[level].data); } break; case GL.GL_TEXTURE_CUBE_MAP: for (level = 0; level < imageData.mipLevels; ++level) { ptr = imageData.mip[level].data; for (int face = 0; face < 6; face++) { gl.TexImage2D((uint)(GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X + face), level, imageData.internalFormat, imageData.mip[level].width, imageData.mip[level].height, 0, imageData.format, imageData.type, new IntPtr(ptr.ToInt32() + imageData.sliceStride * face)); } } break; case GL.GL_TEXTURE_2D_ARRAY: glTexStorage3D(imageData.target, imageData.mipLevels, imageData.internalFormat, imageData.mip[0].width, imageData.mip[0].height, imageData.slices); for (level = 0; level < imageData.mipLevels; ++level) { glTexSubImage3D(GL.GL_TEXTURE_2D_ARRAY, level, 0, 0, 0, imageData.mip[level].width, imageData.mip[level].height, imageData.slices, imageData.format, imageData.type, imageData.mip[level].data); } break; case GL.GL_TEXTURE_CUBE_MAP_ARRAY: glTexStorage3D(imageData.target, imageData.mipLevels, imageData.internalFormat, imageData.mip[0].width, imageData.mip[0].height, imageData.slices); break; case GL.GL_TEXTURE_3D: glTexStorage3D(imageData.target, imageData.mipLevels, imageData.internalFormat, imageData.mip[0].width, imageData.mip[0].height, imageData.mip[0].depth); for (level = 0; level < imageData.mipLevels; ++level) { glTexSubImage3D(GL.GL_TEXTURE_3D, level, 0, 0, 0, imageData.mip[level].width, imageData.mip[level].height, imageData.mip[level].depth, imageData.format, imageData.type, imageData.mip[level].data); } break; default: throw new Exception(string.Format("Not deal with {0}!", imageData.target)); } } internal static readonly GLDelegates.void_uint_int_uint_int glTexStorage1D; internal static readonly GLDelegates.void_uint_int_uint_int_int glTexStorage2D; internal static readonly GLDelegates.void_uint_int_uint_int_int_int glTexStorage3D; internal static readonly GLDelegates.void_uint_int_int_int_int_int_int_int_uint_uint_IntPtr glTexSubImage3D; static DDSStorage() { glTexStorage1D = GL.Instance.GetDelegateFor("glTexStorage1D", GLDelegates.typeof_void_uint_int_uint_int) as GLDelegates.void_uint_int_uint_int; glTexStorage2D = GL.Instance.GetDelegateFor("glTexStorage2D", GLDelegates.typeof_void_uint_int_uint_int_int) as GLDelegates.void_uint_int_uint_int_int; glTexStorage3D = GL.Instance.GetDelegateFor("glTexStorage3D", GLDelegates.typeof_void_uint_int_uint_int_int_int) as GLDelegates.void_uint_int_uint_int_int_int; glTexSubImage3D = GL.Instance.GetDelegateFor("glTexSubImage3D", GLDelegates.typeof_void_uint_int_int_int_int_int_int_int_uint_uint_IntPtr) as GLDelegates.void_uint_int_int_int_int_int_int_int_uint_uint_IntPtr; } } }