content
stringlengths
23
1.05M
using De.Osthus.Ambeth.Cache.Model; using De.Osthus.Ambeth.Model; namespace De.Osthus.Ambeth.Cache { public delegate IServiceResult ExecuteServiceDelegate(IServiceDescription serviceDescription); }
using Game.Managers; using Mirror; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class UIHostGameMenu : MonoBehaviour { public void HostGame() { var newNetworkDiscovery = FindObjectOfType<NewNetworkDiscovery>(); StartCoroutine(LoadGamViewScene()); NetworkManager.singleton.StartHost(); newNetworkDiscovery.AdvertiseServer(); } IEnumerator LoadGamViewScene() { yield return SceneManager.LoadSceneAsync("GameView"); } }
using Microsoft.Xna.Framework; namespace Raytracer.Scene { public class Light : ILight { public Light(Vector3 pos, float intensity, Color color) { Position = pos; Intensity = intensity; Color = color; } public Vector3 Position { get; } public float Intensity { get; } public Color Color { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class sceneManager : MonoBehaviour { public GameObject levelsPanel; public AudioSource mainAudioSource; public AudioClip buttonClick; public GameObject GDPRpanel; public GameObject Setingpanel; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void starting() { mainAudioSource.clip = buttonClick; mainAudioSource.Play (); levelsPanel.SetActive (true); } public void changeScene(int lvlID) { mainAudioSource.clip = buttonClick; mainAudioSource.Play (); SceneManager.LoadScene (lvlID); } public void GDPRpannel() { GDPRpanel.SetActive(true); } public void Setpanel() { Setingpanel.SetActive(true); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PixelComrades { public struct TagTimerEvent : IEntityMessage { public Entity Entity { get; } public float TimeEnd { get; } public int Tag { get; } public TagTimerEvent(Entity entity, float timeEnd, int tag) { Entity = entity; TimeEnd = timeEnd; Tag = tag; } } public struct ConfusionEvent : IEntityMessage { public float Length { get; } public Entity Entity { get; } public bool Active { get; } public ConfusionEvent(Entity entity, float length, bool active) { Length = length; Entity = entity; Active = active; } } public struct TagChangeEvent : IEntityMessage { public Entity Entity { get; } public bool Active { get; } public int Tag { get; } public TagChangeEvent(Entity entity, int tag, bool active) { Tag = tag; Entity = entity; Active = active; } } }
using System; using System.Net; using System.Threading; using System.Threading.Tasks; namespace CoAPNet.Dtls.Server { public class CoapDtlsServerEndPoint : ICoapEndpoint { public bool IsSecure => true; public bool IsMulticast => false; public Uri BaseUri { get; } public IPEndPoint IPEndPoint { get; } public CoapDtlsServerEndPoint(IPAddress address = null, int port = Coap.PortDTLS) { address = address ?? IPAddress.IPv6Any; BaseUri = new UriBuilder() { Scheme = "coaps://", Host = address.ToString(), Port = port }.Uri; IPEndPoint = new IPEndPoint(address, port); } public void Dispose() { } public Task<CoapPacket> ReceiveAsync(CancellationToken tokens) { throw new InvalidOperationException("Receiving can only be done via a DTLS session"); } public async Task SendAsync(CoapPacket packet, CancellationToken token) { //packet has the CoapDtlsServerClientEndPoint which we have to respond to. await packet.Endpoint.SendAsync(packet, token); } public string ToString(CoapEndpointStringFormat format) { return BaseUri.ToString(); } } }
using NeuralSharp.Activation; using NeuralSharp.Generators; using NeuralSharp.Serialization; using Newtonsoft.Json.Linq; namespace NeuralSharp; public sealed class NeuralNetwork { #region Properties private readonly float _learningRate = 0.1f; public readonly Layer[] Layers; #endregion #region Construction /// <summary> /// Create and connect each layer & neuron /// Given random weights & bias' /// </summary> /// <param name="weightGenerator"></param> /// <param name="biasGenerator"></param> /// <param name="activationFunction"></param> /// <param name="layers"></param> public NeuralNetwork( IWeightGenerator weightGenerator, IBiasGenerator biasGenerator, params int[] layers) { Layers = new Layer[layers.Length]; for (var i = 0; i < layers.Length; i++) { //Create the layer Layers[i] = Layer.Create(biasGenerator, layers[i]); if (i > 0) { //Connect the last layer to the current layer Layers[i - 1].Connect(weightGenerator, Layers[i]); } } } /// <summary> /// Create a neural network from the given network configuration /// </summary> /// <param name="activationFunction"></param> /// <param name="networkConfig"></param> public NeuralNetwork(NetworkConfig networkConfig) { Layers = new Layer[networkConfig.Layers.Count]; for (var i = 0; i < Layers.Length; i++) { var layerData = networkConfig.Layers[i]; //Create the layer from the layer data Layers[i] = Layer.Create(layerData); if (i > 0) { //Connect the last layer to the current layer var previousLayer = Layers[i - 1]; previousLayer.Connect(Layers[i], networkConfig.Layers[i - 1]); } } } public NeuralNetwork(Layer[] layers) { Layers = layers; } public static NeuralNetwork From(object o) { return new NeuralNetwork(JObject.FromObject(o).ToObject<NetworkConfig>()); } #endregion #region Learning /// <summary> /// Feed the inputs into the network /// </summary> /// <param name="activationFunction"></param> /// <param name="inputs"></param> /// <returns>Output neuron activations</returns> public float[] FeedForward(IActivationFunction activationFunction, float[] inputs) { //Activate input layer Layers[0].Activate(activationFunction, inputs); //Activate each layer of the network for (var i = 1; i < Layers.Length; i++) { Layers[i].Activate(activationFunction); } //return output activations return Layers[^1].Neurons.Select(n => n.Activation).ToArray(); } /// <summary> /// Train the network /// </summary> /// <param name="activationFunction"></param> /// <param name="inputs"></param> /// <param name="expected"></param> /// <returns></returns> public float[] BackPropagate(IActivationFunction activationFunction, float[] inputs, float[] expected) { //Feed forward to activate neurons var output = FeedForward(activationFunction, inputs); //Initialize the error matrix var layerErrors = new float[Layers.Length][]; for (var i = 0; i < Layers.Length; i++) { layerErrors[i] = new float[Layers[i].Neurons.Length]; } //Calculate the error for the output neurons var outputLayer = Layers[^1]; var outputLayerError = layerErrors[^1]; for (var i = 0; i < output.Length; i++) { var outputNeuron = outputLayer.Neurons[i]; var actualOutput = output[i]; var error = outputLayerError[i] = (actualOutput - expected[i]) * activationFunction.Derivative(actualOutput); //Update the bias for the output neuron outputNeuron.Adjust(error, _learningRate); } //runs on all hidden layers for (var i = Layers.Length - 2; i > 0; i--) { var layer = Layers[i]; for (var j = 0; j < layer.Neurons.Length; j++) //outputs { var layerError = layerErrors[i]; var nextLayerErrors = layerErrors[i + 1]; var neuron = layer.Neurons[j]; //Calculate the neurons error as the sum of errors x weights for each output var error = 0.0f; for (var k = 0; k < neuron.Out.Count; k++) { error += nextLayerErrors[k] * neuron.Out[k].Weight; } layerError[j] = error * activationFunction.Derivative(neuron.Activation); //calculate gamma //Adjust the bias and weight for the neuron layer.Neurons[j].Adjust(layerError[j], _learningRate); } } return output; } #endregion #region Equality public bool Equals(NeuralNetwork other) { return (object)other != null && Layers.SequenceEqual(other.Layers); } public override int GetHashCode() { return HashCode.Combine(Layers); } public static bool operator ==(NeuralNetwork b1, NeuralNetwork b2) { if ((object)b1 == null) { return (object)b2 == null; } return b1.Equals(b2); } public static bool operator !=(NeuralNetwork b1, NeuralNetwork b2) { return !(b1 == b2); } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ConsensusCore.Node { public class ClusterOptions { public string NodeUrls { get; set; } public int MinimumNodes { get; set; } public int LatencyToleranceMs { get; set; } = 3000; public int ElectionTimeoutMs { get; set; } = 1000; public int DataTransferTimeoutMs { get; set; } = 30000; public int NumberOfShards { get; set; } = 1; public int ConcurrentTasks { get; set; } = 4; public bool TestMode { get; set; } public int CommitsTimeout { get; set; } = 10000; public int MaxLogsToSend { get; set; } = 100; public int MaxObjectSync { get; set; } = 100; public int MetricsIntervalMs { get; set; } = 5000; public int SnapshottingInterval { get; set; } = 50; public int SnapshottingTrailingLogCount { get; set; } = 10; /// <summary> /// How many positions to validate when recovering a shard /// </summary> public int ShardRecoveryValidationCount { get; set; } = 50; public bool DebugMode { get; set; } = false; public string[] GetClusterUrls() { return NodeUrls.Split(','); } } }
using System; using System.Threading; using ReactiveDomain.Util; // ReSharper disable once CheckNamespace namespace ReactiveDomain.Foundation { public abstract class SnapshotReadModel : ReadModelBase { protected ReadModelState StartingState { get; private set; } protected SnapshotReadModel( string name, Func<IListener> getListener) : base(name, getListener) { } protected virtual void Restore( ReadModelState snapshot, bool startListeners = true, bool block = false, CancellationToken cancelWaitToken = default(CancellationToken)) { if(StartingState != null) { throw new InvalidOperationException("ReadModel has already been restored."); } Ensure.NotNull(snapshot, nameof(snapshot)); StartingState = snapshot; ApplyState(StartingState); if (!startListeners || StartingState.Checkpoints == null) return; foreach (var stream in StartingState.Checkpoints) { Start(stream.Item1,stream.Item2,block, cancelWaitToken); } } protected abstract void ApplyState(ReadModelState snapshot); public abstract ReadModelState GetState(); private bool _disposed; protected override void Dispose(bool disposing) { if (_disposed) return; _disposed = true; if (disposing) { } base.Dispose(disposing); } } }
using System.Collections.Generic; using Moq; using NUnit.Framework; using PropHunt.UI; using PropHunt.Utils; using UnityEngine; using static PropHunt.UI.MenuController; namespace Tests.EditMode.UI.Actions { /// <summary> /// Tests for Menu Controller Tests /// </summary> [TestFixture] public class MenuControllerTests { /// <summary> /// Object to hold menu controller /// </summary> private GameObject menuControllerObject; /// <summary> /// Menu controller object /// </summary> private MenuController menuController; /// <summary> /// UIManager for managing previous screens /// </summary> private UIManager uiManager; /// <summary> /// Current screen /// </summary> private string currentScreen; /// <summary> /// List of supported screen names /// </summary> private string[] screenNames; [SetUp] public void Setup() { this.menuControllerObject = new GameObject(); this.uiManager = this.menuControllerObject.AddComponent<UIManager>(); this.menuController = this.menuControllerObject.AddComponent<MenuController>(); this.uiManager.screenPrefabs = new List<GameScreen>(); this.menuController.actionDelay = -10.0f; this.screenNames = new string[10]; for (int i = 0; i < screenNames.Length; i++) { this.screenNames[i] = "Screen " + i.ToString(); GameObject screen = new GameObject(); screen.name = this.screenNames[i]; screen.transform.parent = this.menuControllerObject.transform; this.uiManager.screenPrefabs.Add(screen.AddComponent<GameScreen>()); } Assert.Throws<System.InvalidOperationException>(() => this.uiManager.Start()); // Listen to requested screen change events UIManager.RequestScreenChange += (object source, RequestScreenChangeEventArgs args) => { this.currentScreen = args.newScreen; }; } [TearDown] public void TearDown() { // Cleanup game object this.uiManager.OnDestroy(); GameObject.DestroyImmediate(this.menuControllerObject); } [Test] public void SetScreenTests() { this.menuController.SetScreen(screenNames[0]); Assert.IsTrue(this.currentScreen == screenNames[0]); this.menuController.SetScreen(screenNames[1]); Assert.IsTrue(this.currentScreen == screenNames[1]); this.menuController.SetScreen(this.uiManager.screenPrefabs[2].gameObject); Assert.IsTrue(this.currentScreen == screenNames[2]); this.menuController.PreviousScreen(); Assert.IsTrue(this.currentScreen == screenNames[1]); } [Test] public void TestRestrictScreenChanges() { this.menuController.SetScreen(screenNames[0]); Assert.IsTrue(this.currentScreen == screenNames[0]); this.menuController.allowInputChanges = false; this.menuController.SetScreen(screenNames[1]); Assert.IsTrue(this.currentScreen == screenNames[0]); this.menuController.allowInputChanges = true; this.menuController.SetScreen(screenNames[1]); Assert.IsTrue(this.currentScreen == screenNames[1]); this.menuController.allowInputChanges = false; this.menuController.PreviousScreen(); Assert.IsTrue(this.currentScreen == screenNames[1]); this.menuController.allowInputChanges = true; this.menuController.PreviousScreen(); Assert.IsTrue(this.currentScreen == screenNames[0]); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NewRequestView : UIPanel { [SerializeField] private TMPro.TMP_Text titleText; [SerializeField] private TMPro.TMP_Text descText; [SerializeField] private TMPro.TMP_Text goalText; Request activeQuest; public void Show(Request q) { activeQuest = q; UpdateText(activeQuest); activeQuest.OnUpdateRequest += UpdateText; base.Show(); } public override void Hide() { activeQuest.OnUpdateRequest -= UpdateText; activeQuest = null; base.Hide(); } public void UpdateText(Request q) { this.titleText.text = q.title; if (q.isCompleted) { this.descText.text = q.description; goalText.text = "Speak to " + q.requester.CharacterName + " again."; } else { this.descText.text = q.description; string s = ""; for (int i = 0; i < q.goals.Length; i++) { s += "- " + q.goals[i].description + " " + q.goals[i].currentAmount + "/" + q.goals[i].requiredAmount; if (i + 1 < q.goals.Length) s += "\n"; } goalText.text = s; } } }
namespace Hicore.Arguments { public class ResponseArgs { public string RawText { get; set; } public string Text { get; set; } } }
#region BSD License /* * Use of this source code is governed by a BSD-style * license or other governing licenses that can be found in the LICENSE.md file or at * https://raw.githubusercontent.com/Krypton-Suite/Extended-Toolkit/master/LICENSE */ #endregion using System.ComponentModel; using System.Windows.Forms; namespace Krypton.Toolkit.Suite.Extended.Notifications { [ToolboxItem(false)] public class KryptonButtonPanel : UserControl { private KryptonBorderEdge kbeBorder; private KryptonPanel kryptonPanel1; private void InitializeComponent() { this.kryptonPanel1 = new Krypton.Toolkit.KryptonPanel(); this.kbeBorder = new Krypton.Toolkit.KryptonBorderEdge(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).BeginInit(); this.kryptonPanel1.SuspendLayout(); this.SuspendLayout(); // // kryptonPanel1 // this.kryptonPanel1.Controls.Add(this.kbeBorder); this.kryptonPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.kryptonPanel1.Location = new System.Drawing.Point(0, 0); this.kryptonPanel1.Name = "kryptonPanel1"; this.kryptonPanel1.PanelBackStyle = Krypton.Toolkit.PaletteBackStyle.PanelAlternate; this.kryptonPanel1.Size = new System.Drawing.Size(563, 50); this.kryptonPanel1.TabIndex = 0; // // kbeBorder // this.kbeBorder.BorderStyle = Krypton.Toolkit.PaletteBorderStyle.HeaderPrimary; this.kbeBorder.Dock = System.Windows.Forms.DockStyle.Top; this.kbeBorder.Location = new System.Drawing.Point(0, 0); this.kbeBorder.Name = "kbeBorder"; this.kbeBorder.Size = new System.Drawing.Size(563, 1); this.kbeBorder.Text = "kryptonBorderEdge1"; // // KryptonButtonPanel // this.BackColor = System.Drawing.Color.Transparent; this.Controls.Add(this.kryptonPanel1); this.Name = "KryptonButtonPanel"; this.Size = new System.Drawing.Size(563, 50); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).EndInit(); this.kryptonPanel1.ResumeLayout(false); this.kryptonPanel1.PerformLayout(); this.ResumeLayout(false); } } }
using UnityEngine; using UnityEngine.UI; using Z; [ZarchClass] public class runCode : MonoBehaviour { [SerializeField] InputField input; public void run_code() { string content = ZarchUnity3DConnector.instance.console.text; content = content+ "<br/>" + @"~:" + input.text + @"<br/>"; content = content.Replace("<br/>","\n"); ZarchUnity3DConnector.instance.console.text = content; Zarch.code = input.text; input.text = ""; } }
using System.Collections; using System.Collections.Generic; using System.Threading; using UnityEngine; using UnityEngine.UI; public class PlacingFurniture : MonoBehaviour { [SerializeField] int count = 3; [SerializeField] Button button; [SerializeField] Text showName; [SerializeField] Text showCountNumber; [SerializeField] GameObject furniture; static Furniture placingObject; // Start is called before the first frame update void Start() { showName.text = furniture.GetComponent<Furniture>().furnitureName; showCountNumber.text = 'x' + count.ToString(); button.onClick.AddListener(ButtonOnClick); } public PlacingFurniture Initialize(GameObject tobePlaced, int _count = 3) { furniture = tobePlaced; count = _count; return this; } void ButtonOnClick() { if (count <= 0 || placingObject) return; Furniture.CancelSelect(); FurnitureManager.PlacingFurniture = true; placingObject = Instantiate(furniture, FurnitureManager.ins.parentNode).GetComponent<Furniture>(); placingObject.pfButton = this; placingObject.onPlacingSuccess += OnPlacingSuccess; placingObject.onPlacingCancel += OnPlacingCancel; --count; showCountNumber.text = 'x' + count.ToString(); UIFurniturePanel.AllowAction(false); } void OnPlacingCancel() { FurnitureManager.PlacingFurniture = false; ++count; showCountNumber.text = 'x' + count.ToString(); UIFurniturePanel.AllowAction(true, 0.1f); } void OnPlacingSuccess() { placingObject = null; FurnitureManager.PlacingFurniture = false; UIFurniturePanel.AllowAction(true, 0.1f); } public void IncreaseCount() { ++count; showCountNumber.text = 'x' + count.ToString(); } private void OnValidate() { button = GetComponent<Button>(); Text[] uitexts = GetComponentsInChildren<Text>(); showName = uitexts[0]; showCountNumber = uitexts[1]; } }
namespace ProcessingCollections { using System.Collections.Generic; using System.Linq; using Wintellect.PowerCollections; public class Store { private OrderedBag<Product> products = new OrderedBag<Product>(); public OrderedBag<Product> Products { get { return this.products; } set { this.products = value; } } public void AddProduct(Product product) { this.products.Add(product); } public ICollection<Product> SearchInPriceRange(decimal min, decimal max) { return this.products .Range(new Product(string.Empty, min), true, new Product(string.Empty, max), true) .Take(20) .ToList(); } } }
/* Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/) Apache License Version 2.0 */ using System.Linq; namespace UninstallTools.Factory.InfoAdders { public class FileIconGetter : IMissingInfoAdder { public string[] RequiredValueNames { get; } = { nameof(ApplicationUninstallerEntry.UninstallerFullFilename), nameof(ApplicationUninstallerEntry.SortedExecutables) }; public bool RequiresAllValues { get; } = false; public bool AlwaysRun { get; } = false; public string[] CanProduceValueNames { get; } = { nameof(ApplicationUninstallerEntry.DisplayIcon), nameof(ApplicationUninstallerEntry.IconBitmap) }; public InfoAdderPriority Priority { get; } = InfoAdderPriority.RunLast; /// <summary> /// Run after DisplayIcon, DisplayName, UninstallerKind, InstallLocation, UninstallString have been initialized. /// </summary> public void AddMissingInformation(ApplicationUninstallerEntry entry) { if (entry.IconBitmap != null) return; // SdbInst uninstallers do not have any executables to check if (entry.UninstallerKind == UninstallerType.SdbInst) return; // Try getting an icon from the app's executables if (entry.SortedExecutables != null) { foreach (var executablePath in entry.SortedExecutables.Take(2)) { var exeIcon = UninstallToolsGlobalConfig.TryExtractAssociatedIcon(executablePath); if (exeIcon != null) { entry.DisplayIcon = executablePath; entry.IconBitmap = exeIcon; return; } } } var uninsIcon = UninstallToolsGlobalConfig.TryExtractAssociatedIcon(entry.UninstallerFullFilename); if (uninsIcon != null) { entry.DisplayIcon = entry.UninstallerFullFilename; entry.IconBitmap = uninsIcon; } } } }
#if FIVEM using CitizenFX.Core; using CitizenFX.Core.Native; #else using GTA; using GTA.Native; #endif using System.Collections.Generic; namespace LemonUI { /// <summary> /// Tools for dealing with controls. /// </summary> internal static class Controls { /// <summary> /// Gets if the player used a controller for the last input. /// </summary> public static bool IsUsingController { get { #if FIVEM return !API.IsInputDisabled(2); #elif SHVDN2 return !Function.Call<bool>(Hash._GET_LAST_INPUT_METHOD, 2); #elif SHVDN3 return !Function.Call<bool>(Hash._IS_INPUT_DISABLED, 2); #endif } } /// <summary> /// Checks if a control was pressed during the last frame. /// </summary> /// <param name="control">The control to check.</param> /// <returns>true if the control was pressed, false otherwise.</returns> public static bool IsJustPressed(Control control) { #if FIVEM return API.IsDisabledControlJustPressed(0, (int)control); #else return Function.Call<bool>(Hash.IS_DISABLED_CONTROL_JUST_PRESSED, 0, (int)control); #endif } /// <summary> /// Disables all of the controls during the next frame. /// </summary> public static void DisableAll(int inputGroup = 0) { #if FIVEM API.DisableAllControlActions(inputGroup); #else Function.Call(Hash.DISABLE_ALL_CONTROL_ACTIONS, inputGroup); #endif } /// <summary> /// Enables a control during the next frame. /// </summary> /// <param name="control">The control to enable.</param> public static void EnableThisFrame(Control control) { #if FIVEM API.EnableControlAction(0, (int)control, true); #else Function.Call(Hash.ENABLE_CONTROL_ACTION, 0, (int)control); #endif } /// <summary> /// Enables a specific set of controls during the next frame. /// </summary> /// <param name="controls">The controls to enable.</param> public static void EnableThisFrame(IEnumerable<Control> controls) { foreach (Control control in controls) { EnableThisFrame(control); } } } }
using Business.Domain.Models; using Microsoft.EntityFrameworkCore; using System.Reflection; namespace Infrastructure.Contexts { public class AppDbContext : DbContext { #region Constructor public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } #endregion #region Property public DbSet<Education> Educations { get; set; } public DbSet<WorkHistory> WorkHistories { get; set; } public DbSet<Certificate> Certificates { get; set; } public DbSet<Location> Locations { get; set; } public DbSet<Project> Projects { get; set; } public DbSet<CategoryPerson> CategoryPersons { get; set; } public DbSet<Category> Categories { get; set; } public DbSet<Technology> Technologies { get; set; } public DbSet<Person> People { get; set; } public DbSet<Log> Logs { get; set; } public DbSet<Account> Accounts { get; set; } #endregion #region Method // Use Fluent API protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // Finds and runs all your configuration classes in the same assembly as the DbContext builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); } #endregion } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; /// <summary> /// A custom UI event for devices that exist within 3D Unity space, separate from the camera's position. /// </summary> public class TrackedDeviceEventData : PointerEventData { public TrackedDeviceEventData(EventSystem eventSystem) : base(eventSystem) { } /// <summary> /// A series of interconnected points used to track hovered and selected UI. /// </summary> public List<Vector3> rayPoints { get; set; } /// <summary> /// Set by the raycaster, this is the index within the raypoints list that received the hit. /// </summary> public int rayHitIndex { get; set; } /// <summary> /// The physics layer mask to use when checking for hits, both in occlusion and UI objects. /// </summary> public LayerMask layerMask { get; set; } }
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Voximplant.API.Response { /// <summary> /// SmartQueueState.tasks item /// </summary> public class SmartQueueState_Task { /// <summary> /// The task type: CALL, IM. /// </summary> [JsonProperty("task_type")] public string TaskType { get; private set; } /// <summary> /// The task status: IN_QUEUE, DISTRIBUTED, IN_PROCESSING. /// </summary> [JsonProperty("status")] public string Status { get; private set; } /// <summary> /// Selected agent. /// </summary> [JsonProperty("user_id")] public long? UserId { get; private set; } /// <summary> /// Task skills. /// </summary> [JsonProperty("sq_skills")] public SmartQueueTask_Skill[] SqSkills { get; private set; } /// <summary> /// Waiting time in ms. /// </summary> [JsonProperty("waiting_time")] public long WaitingTime { get; private set; } /// <summary> /// Processing time in ms. /// </summary> [JsonProperty("processing_time")] public long ProcessingTime { get; private set; } /// <summary> /// Custom data. /// </summary> [JsonProperty("custom_data")] public Object CustomData { get; private set; } } }
// // Encog(tm) Core v3.1 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2012 Heaton Research, Inc. // // 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Encog.ML.Bayesian; using Encog.ML.Bayesian.Query.Enumeration; namespace Encog.ML.Bayes { [TestClass] public class TestBayesNet { [TestMethod] public void TestCount() { BayesianNetwork network = new BayesianNetwork(); BayesianEvent a = network.CreateEvent("a"); BayesianEvent b = network.CreateEvent("b"); BayesianEvent c = network.CreateEvent("c"); BayesianEvent d = network.CreateEvent("d"); BayesianEvent e = network.CreateEvent("e"); network.CreateDependency(a, b, d, e); network.CreateDependency(c, d); network.CreateDependency(b, e); network.CreateDependency(d, e); network.FinalizeStructure(); Assert.AreEqual(16, network.CalculateParameterCount()); } [TestMethod] public void TestIndependant() { BayesianNetwork network = new BayesianNetwork(); BayesianEvent a = network.CreateEvent("a"); BayesianEvent b = network.CreateEvent("b"); BayesianEvent c = network.CreateEvent("c"); BayesianEvent d = network.CreateEvent("d"); BayesianEvent e = network.CreateEvent("e"); network.CreateDependency(a, b, d, e); network.CreateDependency(c, d); network.CreateDependency(b, e); network.CreateDependency(d, e); network.FinalizeStructure(); Assert.IsFalse(network.IsCondIndependent(c, e, a)); Assert.IsFalse(network.IsCondIndependent(b, d, c, e)); Assert.IsFalse(network.IsCondIndependent(a, c, e)); Assert.IsTrue(network.IsCondIndependent(a, c, b)); } [TestMethod] public void TestIndependant2() { BayesianNetwork network = new BayesianNetwork(); BayesianEvent a = network.CreateEvent("a"); BayesianEvent b = network.CreateEvent("b"); BayesianEvent c = network.CreateEvent("c"); BayesianEvent d = network.CreateEvent("d"); network.CreateDependency(a, b, c); network.CreateDependency(b, d); network.CreateDependency(c, d); network.FinalizeStructure(); Assert.IsFalse(network.IsCondIndependent(b, c)); Assert.IsFalse(network.IsCondIndependent(b, c, d)); Assert.IsTrue(network.IsCondIndependent(a, c, a)); Assert.IsFalse(network.IsCondIndependent(a, c, a, d)); } } }
using System.Collections.Generic; using System.Linq; public class Repository { private readonly List<IWeapon> weapons; public void AddWeapon(IWeapon weapon) { this.weapons.Add(weapon); } public IWeapon GetWeapon(string weaponName) { return this.weapons.First(w => w.Name.Equals(weaponName)); } }
using FusionEngine.Data; using FusionEngine.Effect; namespace FusionEngine.Visuals { public class RLParticle : RenderLayer { public FXParticle fx = null; public override void Init ( ) { fx = new FXParticle ( ); } public override void Render ( Mesh3D m, Visualizer v ) { m.Mat.Bind ( ); // Lighting.GraphLight3D.Active.ShadowFB.Cube.Bind(2); fx.Bind ( ); v.SetMesh ( m ); v.Bind ( ); v.Visualize ( ); v.Release ( ); fx.Release ( ); //Lighting.GraphLight3D.Active.ShadowFB.Cube.Release(2); m.Mat.Release ( ); } } }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Repository { public class Repo { private readonly PlaybookContext _playbookContext; private readonly ILogger _logger; public DbSet<Playbook> Playbooks; public DbSet<Play> Plays; public Repo(PlaybookContext playbookContext, ILogger<Repo> logger) { _playbookContext = playbookContext; _logger = logger; this.Playbooks = _playbookContext.Playbooks; this.Plays = _playbookContext.Plays; } /// <summary> /// saves changes to the database /// </summary> /// <returns></returns> public async Task CommitSave() { await _playbookContext.SaveChangesAsync(); } /// <summary> /// returns a Playbood by the playbookID /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task<Playbook> GetPlaybookById(Guid id) { return await Playbooks.FindAsync(id); } /// <summary> /// returns all playBooks /// </summary> /// <returns></returns> public async Task<IEnumerable<Playbook>> GetPlaybooks() { return await Playbooks.ToListAsync(); } /// <summary> /// returns a play by the playID /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task<Play> GetPlayById(Guid id) { return await Plays.FindAsync(id); } /// <summary> /// returns all plays /// </summary> /// <returns></returns> public async Task<IEnumerable<Play>> GetPlays() { return await Plays.ToListAsync(); } /// <summary> /// returns all plays with the playbookID /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task<IEnumerable<Play>> GetPlaysByPlaybookId(Guid id) { return await Plays.Where(x => x.PlaybookId == id).ToListAsync(); } /// <summary> /// returns all of the playbooks where TeamID == id /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task<IEnumerable<Playbook>> GetPlaybooksByTeamId(Guid id) { return await Playbooks.Where(x => x.TeamID == id).ToListAsync(); } } }
//Author Maxim Kuzmin//makc// using Makc2020.Core.Base.Ext; using Makc2020.Core.Web.Ext; using Makc2020.Host.Web; using Makc2020.Mods.IdentityServer.Base.Enums; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Common.Jobs.Login; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Jobs.Login.Get.Process; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Jobs.Login.Get.Produce; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Jobs.Login.Post.Process; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Jobs.Login.Post.Process.Enums; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Jobs.Login.Post.Produce; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Jobs.Logout.Get; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Jobs.Logout.Post.Process; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Jobs.Logout.Post.Process.Enums; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Jobs.Logout.Post.Produce; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Views.Login; using Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account.Views.Logout; using Makc2020.Mods.IdentityServer.Web.Mvc.Security.Headers; using Makc2020.Mods.IdentityServer.Web.Mvc.Views.Redirect; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace Makc2020.Mods.IdentityServer.Web.Mvc.Parts.Account { [ModIdentityServerWebMvcSecurityHeaders] [AllowAnonymous] [Route("Account")] public abstract class ModIdentityServerWebMvcPartAccountController : Controller { #region Properties private ModIdentityServerWebMvcPartAccountModel MyModel { get; set; } #endregion Properties #region Constructors /// <summary> /// Конструктор. /// </summary> /// <param name="model">Модель.</param> public ModIdentityServerWebMvcPartAccountController(ModIdentityServerWebMvcPartAccountModel model) { MyModel = model; } #endregion Constructors #region Public methods /// <summary> /// Вход в систему. Получение. /// </summary> [HttpGet("Login")] public async Task<IActionResult> LoginGet(string returnUrl, string isFirstLogin) { MyModel.Init(HostWebState.Create(HttpContext)); var processOutput = await GetLoginGetProcessOutput(returnUrl, isFirstLogin) .CoreBaseExtTaskWithCurrentCulture(false); if (processOutput.IsWindowsAuthenticationNeeded) { var model = new ModIdentityServerWebMvcPartAccountViewLoginModel() { LoginMethod = ModIdentityServerBaseEnumLoginMethods.WindowsDomain, ReturnUrl = returnUrl }; var loginOutput = await GetLoginPostProcessOutput(model, ModIdentityServerWebMvcSettings.ACTION_Login) .CoreBaseExtTaskWithCurrentCulture(false); var produceOutput = await GetLoginPostProduceOutput(model) .CoreBaseExtTaskWithCurrentCulture(false); if (!ModelState.IsValid) { ModelState.Clear(); } return GetLoginResult(loginOutput, produceOutput); } else if (string.IsNullOrWhiteSpace(processOutput.RedirectUrl)) { var produceOutput = await GetLoginGetProduceOutput(returnUrl) .CoreBaseExtTaskWithCurrentCulture(false); return View("~/Views/Account/Login.cshtml", produceOutput); } else { return Redirect(processOutput.RedirectUrl); } } /// <summary> /// Вход в систему. Отправка. /// </summary> /// <param name="model">Модель.</param> /// <param name="action">Действие.</param> [HttpPost("Login")] [ValidateAntiForgeryToken] public async Task<IActionResult> LoginPost( ModIdentityServerWebMvcPartAccountViewLoginModel model, string action ) { MyModel.Init(HostWebState.Create(HttpContext)); var processOutput = await GetLoginPostProcessOutput(model, action) .CoreBaseExtTaskWithCurrentCulture(false); var produceOutput = await GetLoginPostProduceOutput(model) .CoreBaseExtTaskWithCurrentCulture(false); var isLoginMemorizationNeeded = processOutput.Status != ModIdentityServerWebMvcPartAccountJobLoginPostProcessEnumStatuses.Default && processOutput.Status != ModIdentityServerWebMvcPartAccountJobLoginPostProcessEnumStatuses.Windows; if (isLoginMemorizationNeeded) { var cookieOptions = CreateCookieOptions( false, DateTimeOffset.Now.AddDays(processOutput.RememberLoginDurationInDays) ); Response.Cookies.Append( processOutput.LoginMethodCookieName, ((int)model.LoginMethod).ToString(), cookieOptions ); if (model.LoginMethod != ModIdentityServerBaseEnumLoginMethods.WindowsDomain) { Response.Cookies.Append( processOutput.LoginUserNameCookieName, model.Username ?? string.Empty, cookieOptions ); } else { Response.Cookies.Delete(processOutput.LoginUserNameCookieName); } } return GetLoginResult(processOutput, produceOutput); } /// <summary> /// Выход из системы. Получение. /// </summary> [HttpGet("Logout")] public async Task<IActionResult> LogoutGet(string logoutId) { MyModel.Init(HostWebState.Create(HttpContext)); var output = await GetLogoutGetOutput(logoutId).CoreBaseExtTaskWithCurrentCulture(false); //return View("~/Views/Account/Logout.cshtml", result.Data); // страница подтверждения выхода var model = new ModIdentityServerWebMvcPartAccountViewLogoutModel { LogoutId = output.LogoutId }; return await LogoutPost(model).CoreBaseExtTaskWithCurrentCulture(false); } /// <summary> /// Выход из системы. Отправка. /// </summary> [HttpPost("Logout")] [ValidateAntiForgeryToken] public async Task<IActionResult> LogoutPost( ModIdentityServerWebMvcPartAccountViewLogoutModel model ) { MyModel.Init(HostWebState.Create(HttpContext)); var processOutput = await GetLogoutPostProcessOutput(model) .CoreBaseExtTaskWithCurrentCulture(false); var produceOutput = await GetLogoutPostProduceOutput(model) .CoreBaseExtTaskWithCurrentCulture(false); return processOutput.Status switch { ModIdentityServerWebMvcPartAccountJobLogoutPostProcessEnumStatuses.LoggedOut => produceOutput.AutomaticRedirectAfterSignOut ? ( string.IsNullOrWhiteSpace(produceOutput.PostLogoutRedirectUri) ? Redirect("/Account/Login") : Redirect(produceOutput.PostLogoutRedirectUri) ) : (IActionResult)View("~/Views/Account/LoggedOut.cshtml", produceOutput), _ => ((Func<SignOutResult>)(() => { // build a return URL so the upstream provider will redirect back // to us after the user has logged out. this allows us to then // complete our single sign-out processing. var redirectUri = Url.Action( "LogoutGet", new { logoutId = produceOutput.LogoutId }); // this triggers a redirect to the external provider for sign-out return SignOut( new AuthenticationProperties { RedirectUri = redirectUri }, produceOutput.ExternalAuthenticationScheme ); }))() }; } [HttpGet] public IActionResult AccessDenied() { return View(); } #endregion Public methods #region Private methods private void CorrectCookieOptions(string cookieKey, CookieOptions cookieOptions) { var cookieValue = Response.CoreWebExtGetCookieValue(cookieKey); Response.Cookies.Delete(cookieKey); Response.Cookies.Append(cookieKey, cookieValue, cookieOptions); } private CookieOptions CreateCookieOptions(bool httpOnly, DateTimeOffset? expires = null) { return new CookieOptions { Path = "/", HttpOnly = httpOnly, IsEssential = true, SameSite = SameSiteMode.Strict, Expires = expires }; } private async Task<ModIdentityServerWebMvcPartAccountJobLoginGetProcessOutput> GetLoginGetProcessOutput( string returnUrl, string isFirstLogin ) { var result = new ModIdentityServerWebMvcPartAccountJobLoginGetProcessResult(); var input = new ModIdentityServerWebMvcPartAccountJobLoginGetProcessInput { HttpRequest = Request, ReturnUrl = returnUrl }; if (!string.IsNullOrWhiteSpace(isFirstLogin)) { input.IsFirstLogin = isFirstLogin == "true"; } var (execute, onSuccess, onError) = MyModel.BuildActionLoginGetProcess(input); try { result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false); onSuccess(result); } catch (Exception ex) { onError(ex, result); } return result.Data ?? new ModIdentityServerWebMvcPartAccountJobLoginGetProcessOutput(); } private async Task<ModIdentityServerWebMvcPartAccountCommonJobLoginOutput> GetLoginGetProduceOutput( string returnUrl ) { var result = new ModIdentityServerWebMvcPartAccountCommonJobLoginResult(); var input = new ModIdentityServerWebMvcPartAccountJobLoginGetProduceInput { ReturnUrl = returnUrl, HttpContext = HttpContext }; var (execute, onSuccess, onError) = MyModel.BuildActionLoginGetProduce(input); try { result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false); onSuccess(result); } catch (Exception ex) { onError(ex, result); } return result.Data ?? new ModIdentityServerWebMvcPartAccountCommonJobLoginOutput(); } private async Task<ModIdentityServerWebMvcPartAccountJobLoginPostProcessOutput> GetLoginPostProcessOutput( ModIdentityServerWebMvcPartAccountViewLoginModel model, string action ) { var result = new ModIdentityServerWebMvcPartAccountJobLoginPostProcessResult(); var input = new ModIdentityServerWebMvcPartAccountJobLoginPostProcessInput { Action = action, HttpContext = HttpContext, Model = model, ModelState = ModelState, UrlHelper = Url }; var (execute, onSuccess, onError) = MyModel.BuildActionLoginPostProcess(input); try { result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false); onSuccess(result); } catch (Exception ex) { onError(ex, result); } return result.Data ?? new ModIdentityServerWebMvcPartAccountJobLoginPostProcessOutput(); } private async Task<ModIdentityServerWebMvcPartAccountCommonJobLoginOutput> GetLoginPostProduceOutput( ModIdentityServerWebMvcPartAccountViewLoginModel model ) { var result = new ModIdentityServerWebMvcPartAccountCommonJobLoginResult(); var input = new ModIdentityServerWebMvcPartAccountJobLoginPostProduceInput { Model = model, HttpContext = HttpContext, ModelState = ModelState }; var (execute, onSuccess, onError) = MyModel.BuildActionLoginPostProduce(input); try { result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false); onSuccess(result); } catch (Exception ex) { onError(ex, result); } return result.Data; } private IActionResult GetLoginResult( ModIdentityServerWebMvcPartAccountJobLoginPostProcessOutput processOutput, ModIdentityServerWebMvcPartAccountCommonJobLoginOutput produceOutput ) { IActionResult result; switch (processOutput.Status) { case ModIdentityServerWebMvcPartAccountJobLoginPostProcessEnumStatuses.Index: result = Redirect("~/"); break; case ModIdentityServerWebMvcPartAccountJobLoginPostProcessEnumStatuses.Redirect: result = View( "Redirect", new ModIdentityServerWebMvcViewRedirectModel { RedirectUrl = produceOutput.ReturnUrl }); break; case ModIdentityServerWebMvcPartAccountJobLoginPostProcessEnumStatuses.Return: result = Redirect(produceOutput.ReturnUrl); break; case ModIdentityServerWebMvcPartAccountJobLoginPostProcessEnumStatuses.Windows: result = Challenge(ModIdentityServerWebMvcSettings.AUTHENTICATION_SCHEME_Windows); break; case ModIdentityServerWebMvcPartAccountJobLoginPostProcessEnumStatuses.Default: default: result = View("~/Views/Account/Login.cshtml", produceOutput); break; } return result; } private async Task<ModIdentityServerWebMvcPartAccountJobLogoutGetOutput> GetLogoutGetOutput(string logoutId) { var result = new ModIdentityServerWebMvcPartAccountJobLogoutGetResult(); var input = new ModIdentityServerWebMvcPartAccountJobLogoutGetInput { LogoutId = logoutId, User = User }; var (execute, onSuccess, onError) = MyModel.BuildActionLogoutGet(input); try { result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false); onSuccess(result); } catch (Exception ex) { onError(ex, result); } return result.Data ?? new ModIdentityServerWebMvcPartAccountJobLogoutGetOutput(); } private async Task<ModIdentityServerWebMvcPartAccountJobLogoutPostProcessOutput> GetLogoutPostProcessOutput( ModIdentityServerWebMvcPartAccountViewLogoutModel model ) { var result = new ModIdentityServerWebMvcPartAccountJobLogoutPostProcessResult(); var input = new ModIdentityServerWebMvcPartAccountJobLogoutPostProcessInput { HttpContext = HttpContext, Model = model, ModelState = ModelState, UrlHelper = Url, User = User }; var (execute, onSuccess, onError) = MyModel.BuildActionLogoutPostProcess(input); try { result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false); onSuccess(result); } catch (Exception ex) { onError(ex, result); } return result.Data ?? new ModIdentityServerWebMvcPartAccountJobLogoutPostProcessOutput(); } private async Task<ModIdentityServerWebMvcPartAccountJobLogoutPostProduceOutput> GetLogoutPostProduceOutput( ModIdentityServerWebMvcPartAccountViewLogoutModel model ) { var result = new ModIdentityServerWebMvcPartAccountJobLogoutPostProduceResult(); var input = new ModIdentityServerWebMvcPartAccountJobLogoutPostProduceInput { HttpContext = HttpContext, Model = model, ModelState = ModelState, User = User }; var (execute, onSuccess, onError) = MyModel.BuildActionLogoutPostProduce(input); try { result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false); onSuccess(result); } catch (Exception ex) { onError(ex, result); } return result.Data; } #endregion Private methods } }
using System; namespace NgxLib { //TODO: either extend on this concept or remove it public interface IModule : IDisposable { bool IsInitialized { get; set; } void Initialize(NgxContext database); } }
using System; using Akka.Actor; using AkkaTest.Payloads; using static AkkaTest.Payloads.CommunicationPayloads; namespace AkkaTest.Actors { /// <summary> /// purpose of this actor is to communicate with users via websockets /// </summary> public class CommunicationActor : BaseActor { public CommunicationActor() : base() { Receive<SendInfoToPlayerPayload>(m => SendInfoToPlayer(m)); Receive<ActOnPlayersActionPayload>(m => ActOnPlayersAction(m)); Receive<ConnectPlayerPayload>(m => ConnectPlayer(m)); Receive<DisconnectPlayerPayload>(m => DisconnectPlayer(m)); } private void DisconnectPlayer(DisconnectPlayerPayload m) { throw new NotImplementedException(); } private void ConnectPlayer(ConnectPlayerPayload m) { throw new NotImplementedException(); } private void ActOnPlayersAction(ActOnPlayersActionPayload m) { throw new NotImplementedException(); } private void SendInfoToPlayer(SendInfoToPlayerPayload m) { throw new NotImplementedException(); } } }
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Threading; namespace Masuit.Tools.Systems { /// <summary> /// 纳秒级计时器,仅支持Windows系统 /// </summary> public class HiPerfTimer { [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceCounter(out long lpPerformanceCount); [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceFrequency(out long clock); private long _startTime; private long _stopTime; private readonly long _exFreq; /// <summary> /// 纳秒计数器 /// </summary> public HiPerfTimer() { _startTime = 0; _stopTime = 0; if (QueryPerformanceFrequency(out _exFreq) == false) { throw new Win32Exception("不支持高性能计数器"); } } /// <summary> /// 开始计时器 /// </summary> public void Start() { // 让等待线程工作 Thread.Sleep(0); QueryPerformanceCounter(out _startTime); } /// <summary> /// 开始计时器 /// </summary> public void Restart() { _startTime = 0; Start(); } /// <summary> /// 停止计时器 /// </summary> public double Stop() { QueryPerformanceCounter(out _stopTime); return Duration; } /// <summary> /// 启动一个新的计时器 /// </summary> /// <returns></returns> public static HiPerfTimer StartNew() { HiPerfTimer timer = new HiPerfTimer(); timer.Start(); return timer; } /// <summary> /// 时器经过时间(单位:秒) /// </summary> public double Duration => (_stopTime - _startTime) / (double)_exFreq; public double DurationNanoseconds => _stopTime - _startTime; /// <summary> /// 时器经过的总时间(单位:秒) /// </summary> public double Elapsed { get { Stop(); return Duration; } } /// <summary> /// 时器经过的总时间(单位:纳秒) /// </summary> public double ElapsedNanoseconds { get { Stop(); return DurationNanoseconds; } } /// <summary> /// 执行一个方法并测试执行时间 /// </summary> /// <param name="action"></param> /// <returns></returns> public static double Execute(Action action) { var timer = new HiPerfTimer(); timer.Start(); action(); timer.Stop(); return timer.Duration; } } }
using System.Linq; public class Phone : ICall, IBrowseWeb { public string BrowseWeb(string site) { if (site.Where(x=>char.IsNumber(x)).ToList().Count()==0) { return $"Browsing: {site}!"; } else { return $"Invalid URL!"; } } public string Call(string number) { if (number.Where(x => char.IsNumber(x)).ToList().Count() == number.Length) { return $"Calling... {number}"; } else { return $"Invalid number!"; } } }
using System; using System.Collections.Generic; using System.Text; namespace PMasta.LearnWithCode.DesignPatterns.Creational.FactoryMethod { /// <summary> /// Defines a generic interface for a game world enemy, the generic Product constructed by the Factory Method. /// </summary> public interface IEnemy { /// <summary> /// The name of the enemy. /// </summary> string Name { get; set; } /// <summary> /// The physical strength of the enemy. /// </summary> int Strength { get; set; } } }
// Copyright (c) 2020 Yann Crumeyrolle. All rights reserved. // Licensed under the MIT license. See LICENSE in the project root for license information. using System.Security.Cryptography; namespace JsonWebToken.Cryptography { internal static class RsaHelper { public static RSASignaturePadding GetPadding(SignatureAlgorithm algorithm) { return algorithm.Id switch { AlgorithmId.RS256 => RSASignaturePadding.Pkcs1, AlgorithmId.RS384 => RSASignaturePadding.Pkcs1, AlgorithmId.RS512 => RSASignaturePadding.Pkcs1, AlgorithmId.PS256 => RSASignaturePadding.Pss, AlgorithmId.PS384 => RSASignaturePadding.Pss, AlgorithmId.PS512 => RSASignaturePadding.Pss, _ => throw ThrowHelper.CreateNotSupportedException_Algorithm(algorithm) }; } } }
using UnityEngine; namespace BehaviorDesigner.Runtime.Tasks.Movement { [TaskDescription("Wander using the Unity NavMesh.")] [TaskCategory("Movement")] [HelpURL("http://www.opsive.com/assets/BehaviorDesigner/Movement/documentation.php?id=9")] [TaskIcon("Assets/Behavior Designer Movement/Editor/Icons/{SkinColor}WanderIcon.png")] public class Wander : Action { [Tooltip("The speed of the agent")] public SharedFloat speed; [Tooltip("Angular speed of the agent")] public SharedFloat angularSpeed; [Tooltip("How far ahead of the current position to look ahead for a wander")] public SharedFloat wanderDistance = 20; [Tooltip("The amount that the agent rotates direction")] public SharedFloat wanderRate = 2; // A cache of the NavMeshAgent private UnityEngine.AI.NavMeshAgent navMeshAgent; public override void OnAwake() { // cache for quick lookup navMeshAgent = gameObject.GetComponent<UnityEngine.AI.NavMeshAgent>(); } public override void OnStart() { // set the speed, angular speed, and destination then enable the agent navMeshAgent.speed = speed.Value; navMeshAgent.angularSpeed = angularSpeed.Value; navMeshAgent.enabled = true; navMeshAgent.destination = Target(); } // There is no success or fail state with wander - the agent will just keep wandering public override TaskStatus OnUpdate() { navMeshAgent.destination = Target(); return TaskStatus.Running; } public override void OnEnd() { // Disable the nav mesh navMeshAgent.enabled = false; } // Return targetPosition if targetTransform is null private Vector3 Target() { // point in a new random direction and then multiply that by the wander distance var direction = transform.forward + Random.insideUnitSphere * wanderRate.Value; return transform.position + direction.normalized * wanderDistance.Value; } // Reset the public variables public override void OnReset() { wanderDistance = 20; wanderRate = 2; } } }
using System; using System.Reflection; using System.IO; using PublicApiGenerator; static class Program { static int Main(string[] args) { try { var assemblyPath = args[0]; var asm = Assembly.LoadFile(assemblyPath); var options = new ApiGeneratorOptions(); switch (args[1]) { case "-": Console.WriteLine(asm.GeneratePublicApi(options)); break; case string apiFilePath: File.WriteAllText(apiFilePath, asm.GeneratePublicApi(options)); break; } return 0; } catch (Exception e) { Console.Error.WriteLine(e); return 1; } } }
using System; using System.Collections.Generic; using System.Text; namespace DemoKata.CustomTypes { public enum CoffeeBean { Java, Mocha, Dubree, Wotsit }; public class Coffee : DrinkBase { public CoffeeBean Bean; public Coffee() { Name = "Coffee"; Price = 4.0M; Bean = CoffeeBean.Mocha; DrinkType = DrinkType.Coffee; } } }
using System; using System.Linq; using Lucene.Net.Store; using NUnit.Framework; namespace Lucene.Net.Linq.Tests.Integration { [TestFixture] public class OrderByDateTimeTests : IntegrationTestBase { private static readonly DateTime time1 = new DateTime(2013, 6, 27, 18, 33, 22).ToUniversalTime(); private static readonly DateTime time2 = time1.AddDays(-1); private static readonly DateTime time3 = time1.AddDays(1); public class Sample { public DateTime DateTime { get; set; } } [SetUp] public override void InitializeLucene() { directory = new RAMDirectory(); provider = new LuceneDataProvider(directory, Net.Util.Version.LUCENE_30); AddDocument(new Sample {DateTime = time1}); AddDocument(new Sample {DateTime = time2}); AddDocument(new Sample {DateTime = time3}); } [Test] public void OrderBy() { var documents = provider.AsQueryable<Sample>(); var result = from d in documents orderby d.DateTime select d.DateTime; var sorted = new[] {time1, time2, time3}.OrderBy(t => t).ToArray(); Assert.That(result.ToArray(), Is.EqualTo(sorted)); } } }
using System.Collections.Generic; public sealed class InMemoryStorage : IStorage { private readonly Dictionary<string, object> _objects = new Dictionary<string, object>(); public bool Exists(string key) => _objects.ContainsKey(key); public void Put<T>(string key, T value) => _objects[key] = value; public void Remove(string key) => _objects.Remove(key); public T Get<T>(string key) => (T) _objects[key]; }
namespace OrderFulfillment.Core.Models.External.OrderProduction { public class SequencedData { public uint SequenceNumber { get; set; } public string Data { get; set; } } }
namespace AsyncAndParallel.Forms.Tasks { partial class PushPullForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnStopPolling = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.lblPollingLocation = new System.Windows.Forms.Label(); this.lblOnDemandLocation = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.btnStartPolling = new System.Windows.Forms.Button(); this.btnOnDemand = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btnStopPolling // this.btnStopPolling.Enabled = false; this.btnStopPolling.Location = new System.Drawing.Point(512, 276); this.btnStopPolling.Name = "btnStopPolling"; this.btnStopPolling.Size = new System.Drawing.Size(75, 23); this.btnStopPolling.TabIndex = 5; this.btnStopPolling.Text = "Stop Polling"; this.btnStopPolling.UseVisualStyleBackColor = true; this.btnStopPolling.Click += new System.EventHandler(this.btnStopPolling_Click); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(483, 151); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(155, 13); this.label3.TabIndex = 10; this.label3.Text = "Continous Retrieval of Location"; // // lblPollingLocation // this.lblPollingLocation.AutoSize = true; this.lblPollingLocation.Location = new System.Drawing.Point(509, 203); this.lblPollingLocation.Name = "lblPollingLocation"; this.lblPollingLocation.Size = new System.Drawing.Size(48, 13); this.lblPollingLocation.TabIndex = 7; this.lblPollingLocation.Text = "Location"; // // lblOnDemandLocation // this.lblOnDemandLocation.AutoSize = true; this.lblOnDemandLocation.Location = new System.Drawing.Point(180, 203); this.lblOnDemandLocation.Name = "lblOnDemandLocation"; this.lblOnDemandLocation.Size = new System.Drawing.Size(48, 13); this.lblOnDemandLocation.TabIndex = 8; this.lblOnDemandLocation.Text = "Location"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(180, 175); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(108, 13); this.label1.TabIndex = 6; this.label1.Text = "On Demand Location"; // // btnStartPolling // this.btnStartPolling.Location = new System.Drawing.Point(512, 233); this.btnStartPolling.Name = "btnStartPolling"; this.btnStartPolling.Size = new System.Drawing.Size(75, 23); this.btnStartPolling.TabIndex = 4; this.btnStartPolling.Text = "Start Polling"; this.btnStartPolling.UseVisualStyleBackColor = true; this.btnStartPolling.Click += new System.EventHandler(this.btnStartPolling_Click); // // btnOnDemand // this.btnOnDemand.Location = new System.Drawing.Point(163, 233); this.btnOnDemand.Name = "btnOnDemand"; this.btnOnDemand.Size = new System.Drawing.Size(174, 23); this.btnOnDemand.TabIndex = 9; this.btnOnDemand.Text = "GetLocationOnDemand"; this.btnOnDemand.UseVisualStyleBackColor = true; this.btnOnDemand.Click += new System.EventHandler(this.btnOnDemand_Click); // // PushPullForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.btnStopPolling); this.Controls.Add(this.label3); this.Controls.Add(this.lblPollingLocation); this.Controls.Add(this.lblOnDemandLocation); this.Controls.Add(this.label1); this.Controls.Add(this.btnStartPolling); this.Controls.Add(this.btnOnDemand); this.Name = "PushPullForm"; this.Text = "PushPullForm"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnStopPolling; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label lblPollingLocation; private System.Windows.Forms.Label lblOnDemandLocation; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnStartPolling; private System.Windows.Forms.Button btnOnDemand; } }
using RimWorld; using rjw; using System; using System.Collections.Generic; using System.Linq; using Verse; using Verse.AI; namespace RJWSexperience.Cum { public class WorkGiver_CleanSelfWithBucket : WorkGiver_Scanner { public override ThingRequest PotentialWorkThingRequest => ThingRequest.ForDef(VariousDefOf.CumBucket); public override PathEndMode PathEndMode => PathEndMode.ClosestTouch; public override bool ShouldSkip(Pawn pawn, bool forced = false) { return !pawn.health.hediffSet.HasHediff(RJW_SemenoOverlayHediffDefOf.Hediff_Bukkake); } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { if (!(t is Building_CumBucket bucket)) return false; return bucket.StoredStackCount < VariousDefOf.GatheredCum.stackLimit; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { return JobMaker.MakeJob(VariousDefOf.CleanSelfwithBucket, pawn, t); } } }
 using SF.Core.Infrastructure.Modules; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace SF.Core { public static class ExtensionManager { private static List<Assembly> assemblies; private static List<IModuleInitializer> modules; public static List<ModuleInfo> Modules { get; set; } public static List<Assembly> Assemblies { get { if (ExtensionManager.assemblies == null) throw new InvalidOperationException("Assemblies not set"); return ExtensionManager.assemblies; } } public static List<IModuleInitializer> Extensions { get { if (ExtensionManager.modules == null) ExtensionManager.modules = ExtensionManager.GetInstances<IModuleInitializer>(); return ExtensionManager.modules; } } public static void SetAssemblies(List<Assembly> assemblies) { ExtensionManager.assemblies = assemblies; } public static void SetExtension(IModuleInitializer moduleInitializer) { ExtensionManager.Extensions.Add(moduleInitializer); } public static void SetModules(List<ModuleInfo> modules) { ExtensionManager.Modules = modules; } public static Type GetImplementation<T>() { return ExtensionManager.GetImplementation<T>(null); } public static Type GetImplementation<T>(Func<Assembly, bool> predicate) { List<Type> implementations = ExtensionManager.GetImplementations<T>(predicate); if (implementations.Count() == 0) throw new ArgumentException("Implementation of " + typeof(T) + " not found"); return implementations.FirstOrDefault(); } public static List<Type> GetImplementations<T>() { return ExtensionManager.GetImplementations<T>(null); } public static List<Type> GetImplementations<T>(Func<Assembly, bool> predicate) { List<Type> implementations = new List<Type>(); foreach (Assembly assembly in ExtensionManager.GetAssemblies(predicate)) foreach (Type type in assembly.GetTypes()) if (typeof(T).GetTypeInfo().IsAssignableFrom(type) && type.GetTypeInfo().IsClass) implementations.Add(type); return implementations; } public static T GetInstance<T>() { return ExtensionManager.GetInstance<T>(null); } public static T GetInstance<T>(Func<Assembly, bool> predicate) { List<T> instances = ExtensionManager.GetInstances<T>(predicate); if (instances.Count() == 0) throw new ArgumentException("Instance of " + typeof(T) + " can't be created"); return instances.FirstOrDefault(); } public static List<T> GetInstances<T>() { return ExtensionManager.GetInstances<T>(null); } public static List<T> GetInstances<T>(Func<Assembly, bool> predicate) { List<T> instances = new List<T>(); foreach (Type implementation in ExtensionManager.GetImplementations<T>()) { if (!implementation.GetTypeInfo().IsAbstract) { T instance = (T)Activator.CreateInstance(implementation); instances.Add(instance); } } return instances; } private static List<Assembly> GetAssemblies(Func<Assembly, bool> predicate) { if (predicate == null) return ExtensionManager.Assemblies; return ExtensionManager.Assemblies.Where(predicate).ToList(); } } }
using System.Linq; using System.Xml; using Dynamo.Graph; using Dynamo.Graph.Nodes; using Dynamo.Models; using Dynamo.Migration; namespace Dynamo.Nodes { public class WallByCurve : MigrationNode { [NodeMigration(from: "0.6.3.0", to: "0.7.0.0")] public static NodeMigrationData Migrate_0630_to_0700(NodeMigrationData data) { NodeMigrationData migratedData = new NodeMigrationData(data.Document); XmlElement oldNode = data.MigratedNodes.ElementAt(0); string oldNodeId = MigrationManager.GetGuidFromXmlElement(oldNode); //create the node itself XmlElement dsRevitNode = MigrationManager.CreateFunctionNodeFrom(oldNode); MigrationManager.SetFunctionSignature(dsRevitNode, "RevitNodes.dll", "Wall.ByCurveAndHeight", "Wall.ByCurveAndHeight@Curve,double,Level,WallType"); migratedData.AppendNode(dsRevitNode); string dsRevitNodeId = MigrationManager.GetGuidFromXmlElement(dsRevitNode); //create and reconnect the connecters PortId oldInPort0 = new PortId(oldNodeId, 0, PortType.Input); XmlElement connector0 = data.FindFirstConnector(oldInPort0); PortId oldInPort1 = new PortId(oldNodeId, 1, PortType.Input); XmlElement connector1 = data.FindFirstConnector(oldInPort1); PortId oldInPort2 = new PortId(oldNodeId, 2, PortType.Input); XmlElement connector2 = data.FindFirstConnector(oldInPort2); PortId oldInPort3 = new PortId(oldNodeId, 3, PortType.Input); XmlElement connector3 = data.FindFirstConnector(oldInPort3); PortId newInPort0 = new PortId(dsRevitNodeId, 0, PortType.Input); PortId newInPort1 = new PortId(dsRevitNodeId, 1, PortType.Input); PortId newInPort2 = new PortId(dsRevitNodeId, 2, PortType.Input); PortId newInPort3 = new PortId(dsRevitNodeId, 3, PortType.Input); data.ReconnectToPort(connector0, newInPort0); data.ReconnectToPort(connector1, newInPort2); data.ReconnectToPort(connector2, newInPort3); data.ReconnectToPort(connector3, newInPort1); return migratedData; } } public class SelectWallType : MigrationNode { [NodeMigration(from: "0.6.3.0", to: "0.7.0.0")] public static NodeMigrationData Migrate_0630_to_0700(NodeMigrationData data) { NodeMigrationData migrationData = new NodeMigrationData(data.Document); migrationData.AppendNode(MigrationManager.CloneAndChangeName( data.MigratedNodes.ElementAt(0), "DSRevitNodesUI.WallTypes", "Wall Types")); return migrationData; } } }
using System; using System.Collections.Concurrent; using Yags.Annotations; using Yags.Log; namespace Yags.Session { public class SessionController { private ConcurrentDictionary<Guid, UserSession> _sessions = new ConcurrentDictionary<Guid, UserSession>(); private const int SessionTimeout = 1*60*1000; private LoggerFunc _logger; public SessionController([CanBeNull] LoggerFactoryFunc loggerFactory) { _logger = LogHelper.CreateLogger(loggerFactory, GetType()); } public bool CheckSession([CanBeNull] UserSessionData sessionData) { var session = GetSession(sessionData); var result = session != null; return result; } public UserSession GetSession([CanBeNull] UserSessionData sessionData) { if(sessionData == null) return null; UserSession session; if (!_sessions.TryGetValue(sessionData.UserId, out session)) { return null; } if (session.Key != sessionData.Key) return null; session.ResetTimeout(); return session; } public UserSessionData CreateSession(Guid userId) { var session = new UserSession(userId, SessionTimeout, TimeoutCallback); _sessions.AddOrUpdate(userId, session, (guid, userSession) => { userSession.Dispose(); return session; }); return session.SessionData; } private void TimeoutCallback(object state) { var session = (UserSession) state; if (!_sessions.TryRemove(session.UserId, out session)) return; LogHelper.LogVerbose(_logger, string.Format("User {0} disconnected by timeout", session.UserId)); session.Dispose(); } } }
using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace StreamChat.Cli.Commands.Commands { [CommandDescriptor("message", "delete", "--id={MessageId}")] public class MessageDelete : ICommand { private readonly Client _client; private readonly IConfiguration _configuration; private readonly ILogger<MessageDelete> _logger; public MessageDelete( Client client, IConfiguration configuration, ILogger<MessageDelete> logger) { _client = client; _configuration = configuration; _logger = logger; } public async Task<string> Execute() { var id = _configuration.GetValue<string>("id"); if(string.IsNullOrWhiteSpace(id)) throw Extensions.Extensions.GetInvalidParameterNullOrWhiteSpaceException(nameof(id)); _logger.LogInformation($"Message: {id}"); var message = await _client.DeleteMessage(id); return null; } } }
using HoloToolkit.Unity; using ShowNowMrKit; using System; using System.Collections.Generic; using UnityEngine; public class MessageManager : Singleton<MessageManager> { #region 原方法 //[HideInInspector] //public string MessageName; //public Animator[] acheModelAnimator; //public void Start() //{ // SyncInterface.Instance.RegistCmdHandler(this); //} //public void MessageDisphter(string msg) //{ // MessageChanged(msg); // SyncInterface.Instance.SyncOtherCmd("MessageChanged", new string[] { msg }); //} /// <summary> /// 消息分发中心(其中SetTrigger命令中可能会有多条消息并行要进行再次解析消息) /// </summary> /// <param name="message"></param> //public void MessageChanged(string message) //{ // MYDialog.Instance.Write(message); // //Debug.Log(message); // string[] ordermsg = message.Split('.'); // switch (ordermsg[0]) // { // case "SetTrigger": // SetTrigger(ordermsg); // break; // } //} //public void SetTrigger(string[] mes) //{ // Animator tempAnimator = acheModelAnimator[int.Parse(mes[1])]; // tempAnimator.SetTrigger(mes[2]); //} #endregion }
// /********************************************************************************************** // Author: Vasily Kabanov // Created 2018-01-09 // Comment // **********************************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Linq; namespace ExcelEi.Read { public class DataSetExtractor { public IDictionary<string, ITableDataSource> TableDataSourceDescriptors { get; } public DataSetExtractor() { TableDataSourceDescriptors = new Dictionary<string, ITableDataSource>(StringComparer.OrdinalIgnoreCase); } public void AddTable(ITableDataSource dataSourceDescriptor, string tableName) { Check.DoRequireArgumentNotNull(dataSourceDescriptor, nameof(dataSourceDescriptor)); Check.DoRequireArgumentNotBlank(tableName, nameof(tableName)); TableDataSourceDescriptors.Add(tableName, dataSourceDescriptor); } public DataSet ExtractDataSet(IDictionary<string, IEnumerable> dataSources) { var result = new DataSet(); foreach (var dataSourcePair in dataSources) { var dataSourceDescriptor = TableDataSourceDescriptors.TryGetValue(dataSourcePair.Key); Check.DoEnsureLambda(dataSourceDescriptor != null, () => $"No descriptor for {dataSourcePair.Key}"); var table = ExtractTable(dataSourceDescriptor, dataSourcePair.Value); table.TableName = dataSourcePair.Key; result.Tables.Add(table); } return result; } public static DataTable ExtractTable(ITableDataSource dataSource, IEnumerable data) { var result = new DataTable(); var columnDescriptors = dataSource.AllColumns.ToArray(); foreach (var sourceColumn in columnDescriptors) { result.Columns.Add(sourceColumn.Name, sourceColumn.DataType); } foreach (var dataItem in data) { var row = result.NewRow(); for (var columnIndex = 0; columnIndex < columnDescriptors.Length; ++columnIndex) { row[columnIndex] = columnDescriptors[columnIndex].GetValue(dataItem) ?? DBNull.Value; } } return result; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; namespace Domain { public struct Percentage : IEquatable<Percentage> { public int Value { get; private set; } public Percentage(int value) { Value = value; } public static Percentage From(int value) => new Percentage(value); public decimal Fraction => (decimal)Value / 100; public bool Equals(Percentage other) { return Value == other.Value; } } }
using System; namespace CsDebugScript.PdbSymbolProvider.DBI { /// <summary> /// OMF segment description flags. /// </summary> [Flags] public enum OMFSegmentDescriptionFlags : ushort { /// <summary> /// No flags. /// </summary> None = 0, /// <summary> /// Segment is readable. /// </summary> Read = 1 << 0, /// <summary> /// Segment is writable. /// </summary> Write = 1 << 1, /// <summary> /// Segment is executable. /// </summary> Execute = 1 << 2, /// <summary> /// Descriptor describes a 32-bit linear address. /// </summary> AddressIs32Bit = 1 << 3, /// <summary> /// Frame represents a selector. /// </summary> IsSelector = 1 << 8, /// <summary> /// Frame represents an absolute address. /// </summary> IsAbsoluteAddress = 1 << 9, /// <summary> /// If set, descriptor represents a group. /// </summary> IsGroup = 1 << 10, } }
using System.Data; using System.Linq; namespace FluentDataTableExtensions { public static partial class FluentDataTableExtension { /// <summary> /// Get the ordinals of specified column names of data table. /// </summary> /// <param name="dt">data table</param> /// <param name="colNames">specified column names</param> /// <returns></returns> public static int[] GetColumnOrdinals(this DataTable dt, params string[] colNames) { if (colNames == null || !colNames.Any()) return new int[0]; CheckColumnExistence(dt, colNames); return colNames.Select(colName => dt.Columns[colName].Ordinal).ToArray(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class KeyListener : MonoBehaviour { public GameObject MissionSelection; public GameObject PlayerProfile; public static bool IsProfileActive = false; public GameObject activeMissionButton; public Button activeProfileButton; public bool ProfileActive = false; public GameObject ProfileMissionsPanel; public GameObject ProfilePlayerPanel; public GameObject HUD; public GameObject Menu; public bool MenuActive = false; public Button ActiveMenuButton; public bool KeyActive = true; public void TurnOffMenu() { if (MenuActive) { IsProfileActive = false; BetaGameOptions.pause = false; Menu.SetActive(false); HUD.SetActive(true); MenuActive = false; } } void Update () { if (!KeyActive) return; if (Input.GetKeyDown(KeyCode.Backspace)) { MenuActive = !MenuActive; if (MenuActive) { GameObject.Find("Main Player").GetComponent<PlayerMotor1>().CanPlayerMove = false; HUD.SetActive(false); PlayerProfile.SetActive(false); MissionSelection.SetActive(false); IsProfileActive = false; BetaGameOptions.pause = true; MissionSelection.SetActive(false); IsProfileActive = true; Menu.SetActive(true); ActiveMenuButton.Select(); } else { GameObject.Find("Main Player").GetComponent<PlayerMotor1>().CanPlayerMove = true; IsProfileActive = false; BetaGameOptions.pause = false; Menu.SetActive(false); HUD.SetActive(true); } } if (Input.GetKeyDown(KeyCode.Tab) && !MenuActive) { GameObject.Find("Main Player").GetComponent<PlayerMotor1>().CanPlayerMove = false; //toggle profile panel ProfileActive = !ProfileActive; if (ProfileActive) { HUD.SetActive(false); IsProfileActive = true; BetaGameOptions.pause = true; MissionSelection.SetActive(false); PlayerProfile.SetActive(true); activeProfileButton.Select(); ProfileMissionsPanel.SetActive(true); ProfilePlayerPanel.SetActive(false); } else { GameObject.Find("Main Player").GetComponent<PlayerMotor1>().CanPlayerMove = true; HUD.SetActive(true); IsProfileActive = false; BetaGameOptions.pause = false; PlayerProfile.SetActive(false); } } /* if (Input.GetKeyDown(KeyCode.Q)) { //activate mission selection panel BetaGameOptions.pause = true; PlayerProfile.SetActive(false); MissionSelection.SetActive(true); activeMissionButton.GetComponent<MissionSelections>().activeMission.Select(); } if (Input.GetKeyDown(KeyCode.R)) { //clear panels BetaGameOptions.pause = false; PlayerProfile.SetActive(false); MissionSelection.SetActive(false); } */ } }
using System; using System.Threading.Tasks; namespace MAVN.Service.SmartVouchers.Domain.Repositories { public interface IPaymentRequestsRepository { Task CreatePaymentRequestAsync(Guid paymentRequestId, string voucherShortCode); Task<string> GetVoucherShortCodeAsync(Guid paymentRequestId); } }
using Quark.Core.Responses.Identity; namespace Quark.Client.HttpClients.Identity; public class UserHttpClient { private readonly HttpClient _httpClient; public UserHttpClient(HttpClient httpClient) { _httpClient = httpClient; } public async Task<IResult<List<UserResponse>>> GetAllAsync() { var response = await _httpClient.GetAsync(Routes.UserEndpoints.BaseRoute); return await response.ToResult<List<UserResponse>>(); } public async Task<IResult<UserResponse>> GetAsync(string userId) { var response = await _httpClient.GetAsync(Routes.UserEndpoints.Get(userId)); return await response.ToResult<UserResponse>(); } public async Task<IResult> RegisterUserAsync(RegisterRequest request) { var response = await _httpClient.PostAsJsonAsync(Routes.UserEndpoints.BaseRoute, request); return await response.ToResult(); } public async Task<IResult> ToggleUserStatusAsync(ToggleUserStatusRequest request) { var response = await _httpClient.PostAsJsonAsync(Routes.UserEndpoints.ToggleActivation, request); return await response.ToResult(); } public async Task<IResult<UserRolesResponse>> GetRolesAsync(string userId) { var response = await _httpClient.GetAsync(Routes.UserEndpoints.GetUserRoles(userId)); return await response.ToResult<UserRolesResponse>(); } public async Task<IResult> UpdateRolesAsync(UpdateUserRolesRequest request) { var response = await _httpClient.PutAsJsonAsync(Routes.UserEndpoints.GetUserRoles(request.UserId), request); return await response.ToResult<UserRolesResponse>(); } public async Task<IResult> ForgotPasswordAsync(ForgotPasswordRequest model) { var response = await _httpClient.PostAsJsonAsync(Routes.UserEndpoints.ForgotPassword, model); return await response.ToResult(); } public async Task<IResult> ResetPasswordAsync(ResetPasswordRequest request) { var response = await _httpClient.PostAsJsonAsync(Routes.UserEndpoints.ResetPassword, request); return await response.ToResult(); } public async Task<string> ExportToExcelAsync(string searchString = "") { var response = await _httpClient.GetAsync(string.IsNullOrWhiteSpace(searchString) ? Routes.UserEndpoints.Export : Routes.UserEndpoints.ExportFiltered(searchString)); var data = await response.Content.ReadAsStringAsync(); return data; } }
using System.Data.EntityClient; using System.Data.Objects; using System.Data.Objects.DataClasses; [assembly: EdmSchemaAttribute()] namespace api.evl.watch { public partial class EvlWatchContext : ObjectContext { public EvlWatchContext() : base("name=EvlWatchContext", "EvlWatchContext") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } public EvlWatchContext(string connectionString) : base(connectionString, "EvlWatchContext") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } public EvlWatchContext(EntityConnection connection) : base(connection, "EvlWatchContext") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } partial void OnContextCreated(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Downloader { public class DownloadThrottling : IDownloadObserver, IDisposable { private readonly int maxBytesPerSecond; private readonly List<IDownload> downloads = new List<IDownload>(); private readonly int maxSampleCount; private List<DownloadDataSample> samples; private double floatingWaitingTimeInMilliseconds = 0; private object monitor = new object(); public DownloadThrottling(int maxBytesPerSecond, int maxSampleCount) { if (maxBytesPerSecond <= 0) throw new ArgumentException("maxBytesPerSecond <= 0"); if (maxSampleCount < 2) throw new ArgumentException("sampleCount < 2"); this.maxBytesPerSecond = maxBytesPerSecond; this.maxSampleCount = maxSampleCount; this.samples = new List<DownloadDataSample>(); } public void Attach(IDownload download) { if (download == null) throw new ArgumentNullException("download"); download.DataReceived += this.downloadDataReceived; lock (this.monitor) { this.downloads.Add(download); } } public void Detach(IDownload download) { if (download == null) throw new ArgumentNullException("download"); download.DataReceived -= this.downloadDataReceived; lock (this.monitor) { this.downloads.Remove(download); } } public void DetachAll() { lock (this.monitor) { foreach (var download in this.downloads) { this.Detach(download); } } } public void Dispose() { this.DetachAll(); } private void AddSample(int count) { lock (this.monitor) { var sample = new DownloadDataSample() { Count = count, Timestamp = DateTime.UtcNow }; this.samples.Add(sample); if (this.samples.Count > this.maxSampleCount) { this.samples.RemoveAt(0); } } } private int CalculateWaitingTime() { lock (this.monitor) { if (this.samples.Count < 2) { return 0; } var averageBytesPerCall = this.samples.Average(s => s.Count); double sumOfTicksBetweenCalls = 0; // 1 tick = 100 nano seconds, 1 ms ^= 10.000 ticks for (var i = 0; i < this.samples.Count - 1; i++) { sumOfTicksBetweenCalls += (this.samples[i + 1].Timestamp - this.samples[i].Timestamp).Ticks; } var averageTicksBetweenCalls = sumOfTicksBetweenCalls / (this.samples.Count - 1); var timePerNetworkRequestInMilliseconds = averageTicksBetweenCalls / 10000 - floatingWaitingTimeInMilliseconds; var currentBytesPerMillisecond = averageBytesPerCall / averageTicksBetweenCalls * 10000; var maxBytesPerMillisecond = (double) this.maxBytesPerSecond / 1000; var waitingTimeInMilliseconds = averageBytesPerCall / maxBytesPerMillisecond - timePerNetworkRequestInMilliseconds; this.floatingWaitingTimeInMilliseconds = waitingTimeInMilliseconds * 0.6 + this.floatingWaitingTimeInMilliseconds * 0.4; return (int) waitingTimeInMilliseconds; } } private void downloadDataReceived(DownloadDataReceivedEventArgs args) { this.AddSample(args.Count); var waitingTime = this.CalculateWaitingTime(); if (waitingTime > 0) { Thread.Sleep(waitingTime); } } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using UkrainiansId.Domain.Models; namespace UkrainiansId.Infrastructure.Data.EntityFramework.Configurations { public class AppConfiguration : IEntityTypeConfiguration<App> { public void Configure(EntityTypeBuilder<App> builder) { builder.HasKey(x => x.Id); builder.HasIndex(x => new { x.Name, x.ClientId, x.ClientSecret, x.ClientSecretIsRequired }); } } }
namespace HeroVillainTour.DomainModels { public class HeroDomainModel : BaseCharacterDomainModel { //public List<string> PeopleSaved { get; set; } } }
using System.Threading.Tasks; using Covid19Api.Domain; namespace Covid19Api.Repositories.Abstractions { public interface IGlobalStatisticsWriteRepository { Task StoreAsync(GlobalStatistics globalStatistics); } }
using Microsoft.VisualStudio.Text.Editor; using System.ComponentModel.Composition; using System.Windows; using Vim; namespace Vim.UnitTest.Exports { [Export(typeof(IMouseDevice))] public sealed class TestableMouseDevice : IMouseDevice { public bool IsLeftButtonPressed { get; set; } bool IMouseDevice.IsLeftButtonPressed { get { return IsLeftButtonPressed; } } public Point? GetPosition(ITextView textView) { return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EMS.EDXL.SitRep.Reports { public enum ImmediateNeedsCategoryDefaultValues { EmergencyMedicalServices, FireAndHazardousMaterials, IncidentManagement, LawEnforcement, MassCare, MedicalAndPublicHealth, PublicWorks, SearchAndRescue } }
using CommandLine; using System; using System.Collections.Generic; using System.Text; namespace SW.Gds.Util { class Options { //[Option('v', "verbose", Required = false, HelpText = "Set output to verbose messages.")] //public bool Verbose { get; set; } //[Option('a', "accesskey", Required = true, HelpText = "Access key for storage.")] //public string AccessKeyId { get; set; } //[Option('s', "secret", Required = true, HelpText = "Secret access key for storage.")] //public string SecretAccessKey { get; set; } //[Option('b', "bucketname", Required = true, HelpText = "Bucket name for storage.")] //public string BucketName { get; set; } //[Option('u', "url", Required = true, HelpText = "Service Url for storage.")] //public string ServiceUrl { get; set; } [Value(0, Required = true, HelpText = "Type")] public string Type { get; set; } [Value(1, Required = true, HelpText = "Connection string")] public string ConnectionString { get; set; } [Value(2, Required = true, HelpText = "File path")] public string FilePath { get; set; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities.UI; namespace Microsoft.Nodejs.Tests.UI { [TestClass] public class JadeUITests : NodejsProjectTest { [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void InsertTabs() { using (new OptionHolder("TextEditor", "Jade", "InsertTabs", true)) { using (var solution = Project("TabsSpaces", Content("quox.pug", "ul\r\n li A\r\n li B")).Generate().ToVs()) { var jadeFile = solution.OpenItem("TabsSpaces", "quox.pug"); jadeFile.MoveCaret(1, 1); Keyboard.Type("\t"); Assert.AreEqual(jadeFile.Text, "\tul\r\n li A\r\n li B"); } } } [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void InsertSpaces() { using (new OptionHolder("TextEditor", "Jade", "InsertTabs", false)) { using (var solution = Project("TabsSpaces", Content("quox.pug", "ul\r\n li A\r\n li B")).Generate().ToVs()) { var jadeFile = solution.OpenItem("TabsSpaces", "quox.pug"); jadeFile.MoveCaret(1, 1); Keyboard.Type("\t"); Assert.AreEqual(jadeFile.Text, " ul\r\n li A\r\n li B"); } } } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using System; using System.Text; namespace Cache.WebApi02.Controllers { [Route("[controller]")] [ApiController] public class CacheController : Controller { private IDistributedCache cache; public CacheController(IDistributedCache cache) { this.cache = cache ?? throw new ArgumentNullException(nameof(cache)); } [HttpGet] public string Get() { //读取缓存 var now = cache.Get("cacheNow"); if (now == null) //如果没有该缓存 { cache.Set("cacheNow", Encoding.UTF8.GetBytes(DateTime.Now.ToString())); now = cache.Get("cacheNow"); return Encoding.UTF8.GetString(now); } else { return Encoding.UTF8.GetString(now); } } } }
using System.Collections.Generic; using UnityEngine; using Sharp.Core; using Newtonsoft.Json.Linq; namespace Sharp.Gameplay { [RequireComponent(typeof(Animator))] [RequireComponent(typeof(StateComponent))] [RequireComponent(typeof(AudioSource))] public class LaserObject : MonoBehaviour, ISerializable { [SerializeField] private ParticleScalerComponent distanceScaler; private Animator animator; private StateComponent state; private new AudioSource audio; private void Awake() { animator = GetComponent<Animator>(); state = GetComponent<StateComponent>(); audio = GetComponent<AudioSource>(); } private void OnTriggerEnter2D(Collider2D other) { active = true; enabled = true; var main = distanceScaler.ParticleSystem.main; main.startColor = main.startColor.color.Fade(1); distanceScaler.ParticleSystem.Refresh(); animator.SetTrigger("Burst"); audio.Play(); } private void OnTriggerStay2D(Collider2D other) { if (Persistent) active = true; } private void FixedUpdate() { if (active) { Burst(); active = false; } else { var main = distanceScaler.ParticleSystem.main; main.startColor = main.startColor.color.Fade(0.3f); enabled = false; } } private readonly static List<UnitComponent> units = new List<UnitComponent>(); private bool active; private void Burst() { var from = (Vector2)transform.position + .5f * Constants.Directions[Direction]; var to = from + Distance * Constants.Directions[Direction]; PhysicsUtility.OverlapArea(units, from, to, Constants.UnitMask); foreach (var unit in units) unit.Kill(); } public int Direction { get => state.State; private set => state.State = value; } [SerializeField] private int distance; public int Distance { get => distance; private set { distance = value; distanceScaler.Scale(new Vector3(Distance, 0, 0)); } } [SerializeField] private bool persistent; public bool Persistent { get => persistent; private set { persistent = value; animator.SetBool("Persistent", Persistent); } } public void Serialize(JToken token) { token["direction"] = Direction; token["distance"] = Distance; token["persistent"] = Persistent; } public void Deserialize(JToken token) { Direction = (int)token["direction"]; Distance = (int)token["distance"]; Persistent = (bool)token["persistent"]; } } }
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using Microsoft.WindowsAzure.MobileServices; namespace ZumoE2ETestApp.Framework { public class ZumoTestGlobals { public const string RoundTripTableName = "w8RoundTripTable"; public const string StringIdRoundTripTableName = "stringIdRoundTripTable"; public const string MoviesTableName = "intIdMovies"; public const string StringIdMoviesTableName = "stringIdMovies"; #if !WINDOWS_PHONE public const string PushTestTableName = "w8PushTest"; #else public const string PushTestTableName = "wp8PushTest"; #endif public const string ParamsTestTableName = "ParamsTestTable"; public const string ClientVersionKeyName = "clientVersion"; public const string RuntimeVersionKeyName = "x-zumo-version"; private static ZumoTestGlobals instance = new ZumoTestGlobals(); public static bool ShowAlerts = true; public const string LogsLocationFile = "done.txt"; public MobileServiceClient Client { get; private set; } public Dictionary<string, object> GlobalTestParams { get; private set; } private ZumoTestGlobals() { this.GlobalTestParams = new Dictionary<string, object>(); } public static ZumoTestGlobals Instance { get { return instance; } } public void InitializeClient(string appUrl, string appKey) { bool needsUpdate = this.Client == null || (this.Client.ApplicationUri.ToString() != appUrl) || (this.Client.ApplicationKey != appKey); if (needsUpdate) { if (string.IsNullOrEmpty(appUrl) || string.IsNullOrEmpty(appKey)) { throw new ArgumentException("Please enter valid application URL and key."); } this.Client = new MobileServiceClient(appUrl, appKey); } } } }
using System.Runtime.CompilerServices; namespace System.Html { public partial class DataTransfer { [IntrinsicProperty] public DataTransferItemList Items { get { return null; } } } }
/* * Copyright (C) Sportradar AG. See LICENSE for full license governing this code */ using Dawn; using Sportradar.OddsFeed.SDK.Entities.REST.Enums; using Sportradar.OddsFeed.SDK.Entities.REST.Internal.DTO; using Sportradar.OddsFeed.SDK.Messages; namespace Sportradar.OddsFeed.SDK.Entities.REST.Internal.EntitiesImpl { class TeamStatistics : ITeamStatisticsV2 { public URN TeamId { get; } public string Name { get; } public HomeAway? HomeAway { get; } public int? Cards { get; } public int? YellowCards { get; } public int? RedCards { get; } public int? YellowRedCards { get; } public int? CornerKicks { get; } public int? GreenCards { get; } public TeamStatistics(TeamStatisticsDTO dto) { Guard.Argument(dto, nameof(dto)).NotNull(); TeamId = dto.TeamId; Name = dto.Name; HomeAway = dto.HomeOrAway; Cards = dto.Cards; YellowCards = dto.YellowCards; RedCards = dto.RedCards; YellowRedCards = dto.YellowRedCards; CornerKicks = dto.CornerKicks; GreenCards = dto.GreenCards; } } }
/* Copyright 2020-present MongoDB Inc. * * 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.Linq; using System.Net; using System.Threading; using FluentAssertions; using MongoDB.Bson; using MongoDB.Bson.TestHelpers.XunitExtensions; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; using MongoDB.Driver.Core.TestHelpers.Logging; using MongoDB.Driver.Core.TestHelpers.XunitExtensions; using MongoDB.Driver.TestHelpers; using Xunit; using Xunit.Abstractions; namespace MongoDB.Driver.Tests.Specifications.server_discovery_and_monitoring.prose_tests { public class ServerDiscoveryProseTests : LoggableTestClass { // public constructors public ServerDiscoveryProseTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } // public methods [SkippableTheory] [ParameterAttributeData] public void Topology_secondary_discovery_with_directConnection_false_should_work_as_expected([Values(false, true, null)] bool? directConnection) { RequireServer .Check() .Supports(Feature.DirectConnectionSetting) .ClusterTypes(ClusterType.ReplicaSet) .Authentication(false); // we don't use auth connection string in this test var setupClient = DriverTestConfiguration.Client; setupClient.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName).RunCommand<BsonDocument>("{ ping : 1 }"); var setupCluster = setupClient.Cluster; SpinWait.SpinUntil(() => setupCluster.Description.State == ClusterState.Connected, TimeSpan.FromSeconds(3)); var clusterDescription = setupCluster.Description; var secondary = clusterDescription.Servers.FirstOrDefault(s => s.State == ServerState.Connected && s.Type == ServerType.ReplicaSetSecondary); if (secondary == null) { throw new Exception("No secondary was found."); } var dnsEndpoint = (DnsEndPoint)secondary.EndPoint; var replicaSetName = secondary.ReplicaSetConfig.Name; using (var client = new DisposableMongoClient(new MongoClient(CreateConnectionString(dnsEndpoint, directConnection, replicaSetName)), CreateLogger<DisposableMongoClient>())) { var database = client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName); var collection = database.GetCollection<BsonDocument>(DriverTestConfiguration.CollectionNamespace.CollectionName); var exception = Record.Exception(() => collection.InsertOne(new BsonDocument())); if (directConnection.GetValueOrDefault()) { exception.Should().BeOfType<MongoNotPrimaryException>(); exception.Message.Should().Contain("Server returned not primary error"); } else { exception.Should().BeNull(); } } } // private methods private string CreateConnectionString(DnsEndPoint endpoint, bool? directConnection, string replicaSetName) { var connectionString = $"mongodb://{endpoint.Host}:{endpoint.Port}/?replicaSet={replicaSetName}"; if (directConnection.HasValue) { connectionString += $"&directConnection={directConnection.Value}"; } return connectionString; } } }
using System; using System.Globalization; using System.Windows.Data; using NUnit3GUIWPF.Models; namespace NUnit3GUIWPF.Converters { public class ProjectStateToEnableConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { ProjectState ps = (ProjectState)value; return (ps == ProjectState.Finished || ps == ProjectState.Loaded || ps == ProjectState.NotLoaded); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
#region File Description //----------------------------------------------------------------------------- // MatchState.cs // // Ben Scharbach - XNA Community Game Platform // Copyright (C) Image-Nexus, LLC. All rights reserved. //----------------------------------------------------------------------------- #endregion namespace ImageNexus.BenScharbach.TWEngine.Utilities.Compression.Enums { internal enum MatchState { HasMatch = 2, HasSymbol = 1, HasSymbolAndMatch = 3 } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EnterIP : MonoBehaviour { [SerializeField] private InputField inputField; [SerializeField] private SocketIO.SocketIOComponent socketIO; [SerializeField] private List<GameObject> objectsToEnable; public void IpEntered() { socketIO.serverIp = inputField.text; objectsToEnable.ForEach(obj => obj.SetActive(true)); this.gameObject.SetActive(false); } }
using BrowserGameEngine.GameDefinition; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BrowserGameEngine.GameModel { public record UnitCount(UnitDefId UnitDefId, int Count); }
using DG.Tweening; using SMGCore; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Game { public sealed class PhoneHandle : MonoBehaviour { public Camera TargetCam; bool _active = false; public void Take() { _active = true; var col = GetComponentInChildren<Collider>(); if ( col ) { col.enabled = false; } SoundManager.Instance.PlaySound("item_take"); } public void Return(Transform returnPos) { _active = false; var col = GetComponentInChildren<Collider>(); if ( col ) { col.enabled = true; } var returnSeq = DOTween.Sequence(); returnSeq.AppendInterval(0.5f); returnSeq.AppendCallback(() => { SoundManager.Instance.PlaySound("phone_hit"); }); returnSeq.Append(transform.DOMove(returnPos.position, 0.5f)); returnSeq.Join(transform.DORotate(returnPos.rotation.eulerAngles, 0.4f)); } private void Update() { if ( !_active ) { return; } var camRay = TargetCam.ScreenPointToRay(Input.mousePosition); Debug.DrawRay(camRay.origin, camRay.direction * 25f, Color.green); if ( Physics.Raycast(camRay, out var hit, 30) ) { transform.rotation = Quaternion.Euler(26, 51, -83); var nearPos = (camRay.direction* 3 + camRay.origin); transform.position = Vector3.Lerp(transform.position, nearPos, Time.deltaTime * 20f); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Graded_Unit_2 { /// <summary> /// Holds patients prescription for both eyes /// </summary> public partial class Prescription { //Attributes private EyeRX rightEye { get; } private EyeRX leftEye { get; } private bool isHigh; private bool isPrism; private bool isAstig; private bool isVari; //Constructor public Prescription(EyeRX rightEye, EyeRX leftEye) { this.rightEye = rightEye; this.leftEye = leftEye; evaluatePrescription(); } //Sets important attributes based on current prescripton private void evaluatePrescription() { //If right eye or left eye has a sph value of greater thatn 4 or less than -5 if (rightEye.sph > 4 || leftEye.sph > 4 || rightEye.sph < -5 || leftEye.sph < -5) isHigh = true; else isHigh = false; //If right eye or left eye has a prism greater than 1 if (rightEye.prism > 0 || leftEye.prism > 0) isPrism = true; else isPrism = false; //If right eye or left eye has a cyl if (rightEye.cyl > 0 || leftEye.cyl > 0) isAstig = true; else isAstig = false; //If prescription has an add if (rightEye.nearAdd > 0 || leftEye.nearAdd > 0 || rightEye.intAdd > 0 || leftEye.intAdd > 0) isVari = true; else isVari = false; } //Getters public EyeRX getRightEye() { return this.rightEye; } public EyeRX getLeftEye() { return this.leftEye; } public bool isPrescriptionHigh() { return this.isHigh; } public bool isPrescriptionPrism() { return this.isPrism; } public bool isPrescriptionAstig() { return this.isAstig; } public bool isPrescriptionVari() { return this.isVari; } } }
using _000_RealQuestions; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace _000_RealQuestionsTest { [TestClass] public class AppleTest { [DataTestMethod] [DataRow(4)] [DataRow(10)] [DataRow(12)] [DataRow(16)] public void RandomInt1toNTest(int n) { // Act var results = new int[n + 1]; var resultsV2 = new int[n + 1]; int total = n * 100000; for (int i = 0; i < total; i++) { int k = Apple.RandomInt1toN(n); int k2 = Apple.RandomInt1toN_v2(n); results[k]++; resultsV2[k2]++; } // Assert double expectedProbability = (double)100 / n; double threshold = 0.2; for (int k = 1; k <= n; k++) { double probabilityV1 = (double)results[k] * 100 / total; Console.WriteLine($"V1 - Probability of {k} is {Math.Round(probabilityV1, 2)}%."); double probabilityV2 = (double)resultsV2[k] * 100 / total; Console.WriteLine($"V2 - Probability of {k} is {Math.Round(probabilityV2, 2)}%."); Assert.AreEqual(expectedProbability, probabilityV1, threshold); Assert.AreEqual(expectedProbability, probabilityV2, threshold); } } } }
using System; namespace SampleCourier.Contracts { public interface ContentRetrieved { /// <summary> /// When the content was retrieved /// </summary> DateTime Timestamp { get; } /// <summary> /// The content address /// </summary> Uri Address { get; } /// <summary> /// The local URI for the content /// </summary> Uri LocalAddress { get; } /// <summary> /// The local path of the content /// </summary> string LocalPath { get; } /// <summary> /// The length of the content /// </summary> long Length { get; } /// <summary> /// The content type /// </summary> string ContentType { get; } } }
using System; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.OData.Formatters; using Microsoft.Framework.DependencyInjection; namespace Microsoft.AspNet.OData.Extensions { public static class ServiceCollectionExtensions { public static IServiceCollection AddORest(this IServiceCollection services) { return services.Configure<MvcOptions>(options => { options.OutputFormatters.Insert(0, new ODataOutputFormatter()); }); } } }
using System.Collections; using System.Collections.Generic; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; using UnityEngine.SceneManagement; /** * This file tests scene transitions to, from, and within the rules scene * to make sure it loads and unloads properly * * @author: Jessica Su */ namespace Tests { public class RulesTest { private GameObject testObject; private Rules rules; private Scene testScene; [OneTimeSetUp] public void Init() { testScene = SceneManager.GetActiveScene(); } [SetUp] public void Setup() { testObject = MonoBehaviour.Instantiate(Resources.Load<GameObject>("Prefabs/Rules/RulesManager")); rules = testObject.GetComponent<Rules>(); rules.isTest = true; } [TearDown] public void Teardown() { foreach(GameObject obj in GameObject.FindObjectsOfType<GameObject>()) { GameObject.Destroy(obj); } } [UnityTest, Order(1)] public IEnumerator GoesToNextRulesScreen() { rules.goToRulesOrModeScreen("RulesScreen2"); yield return new WaitForSeconds(1f); Scene ruleScene2 = SceneManager.GetActiveScene(); Assert.AreEqual("RulesScreen2", ruleScene2.name); SceneManager.SetActiveScene(testScene); SceneManager.UnloadSceneAsync(ruleScene2); yield return new WaitForSeconds(1f); } [UnityTest, Order(2)] public IEnumerator GoesToFirstRulesScreen() { rules.goToRulesOrModeScreen("RulesScreen"); yield return new WaitForSeconds(1f); Scene ruleScene = SceneManager.GetActiveScene(); Assert.AreEqual("RulesScreen", ruleScene.name); SceneManager.SetActiveScene(testScene); SceneManager.UnloadSceneAsync(ruleScene); yield return new WaitForSeconds(1f); } [UnityTest, Order(3)] public IEnumerator GoesBackToModeScreen() { rules.goToRulesOrModeScreen("ModeSelection"); yield return new WaitForSeconds(1f); Scene modeScene = SceneManager.GetActiveScene(); Assert.AreEqual("ModeSelection", modeScene.name); SceneManager.SetActiveScene(testScene); SceneManager.UnloadSceneAsync(modeScene); yield return new WaitForSeconds(1f); } } }
/////////////////////////////// /// IApplyDamage.cs /// Justin Dela Cruz /// 101127646 /// Last Modified: 2021-12-17 /// This .cs file helps Apply Damage /// GAME2014 - Final ////////////////////////////// using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IApplyDamage { int ApplyDamage(); }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace System.ServiceModel.Configuration { using System.Configuration; using System.Globalization; using System.Net; using System.Xml; using System.ServiceModel; using System.ComponentModel; using System.ServiceModel.Channels; public sealed partial class XmlDictionaryReaderQuotasElement : ServiceModelConfigurationElement { // for all properties, a value of 0 means "just use the default" [ConfigurationProperty(ConfigurationStrings.MaxDepth, DefaultValue = 0)] [IntegerValidator(MinValue = 0)] public int MaxDepth { get { return (int)base[ConfigurationStrings.MaxDepth]; } set { base[ConfigurationStrings.MaxDepth] = value; } } [ConfigurationProperty(ConfigurationStrings.MaxStringContentLength, DefaultValue = 0)] [IntegerValidator(MinValue = 0)] public int MaxStringContentLength { get { return (int)base[ConfigurationStrings.MaxStringContentLength]; } set { base[ConfigurationStrings.MaxStringContentLength] = value; } } [ConfigurationProperty(ConfigurationStrings.MaxArrayLength, DefaultValue = 0)] [IntegerValidator(MinValue = 0)] public int MaxArrayLength { get { return (int)base[ConfigurationStrings.MaxArrayLength]; } set { base[ConfigurationStrings.MaxArrayLength] = value; } } [ConfigurationProperty(ConfigurationStrings.MaxBytesPerRead, DefaultValue = 0)] [IntegerValidator(MinValue = 0)] public int MaxBytesPerRead { get { return (int)base[ConfigurationStrings.MaxBytesPerRead]; } set { base[ConfigurationStrings.MaxBytesPerRead] = value; } } [ConfigurationProperty(ConfigurationStrings.MaxNameTableCharCount, DefaultValue = 0)] [IntegerValidator(MinValue = 0)] public int MaxNameTableCharCount { get { return (int)base[ConfigurationStrings.MaxNameTableCharCount]; } set { base[ConfigurationStrings.MaxNameTableCharCount] = value; } } internal void ApplyConfiguration(XmlDictionaryReaderQuotas readerQuotas) { if (readerQuotas == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("readerQuotas"); } if (this.MaxDepth != 0) { readerQuotas.MaxDepth = this.MaxDepth; } if (this.MaxStringContentLength != 0) { readerQuotas.MaxStringContentLength = this.MaxStringContentLength; } if (this.MaxArrayLength != 0) { readerQuotas.MaxArrayLength = this.MaxArrayLength; } if (this.MaxBytesPerRead != 0) { readerQuotas.MaxBytesPerRead = this.MaxBytesPerRead; } if (this.MaxNameTableCharCount != 0) { readerQuotas.MaxNameTableCharCount = this.MaxNameTableCharCount; } } internal void InitializeFrom(XmlDictionaryReaderQuotas readerQuotas) { if (readerQuotas == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("readerQuotas"); } if (readerQuotas.MaxDepth != EncoderDefaults.MaxDepth) { SetPropertyValueIfNotDefaultValue(ConfigurationStrings.MaxDepth, readerQuotas.MaxDepth); } if (readerQuotas.MaxStringContentLength != EncoderDefaults.MaxStringContentLength) { SetPropertyValueIfNotDefaultValue(ConfigurationStrings.MaxStringContentLength, readerQuotas.MaxStringContentLength); } if (readerQuotas.MaxArrayLength != EncoderDefaults.MaxArrayLength) { SetPropertyValueIfNotDefaultValue(ConfigurationStrings.MaxArrayLength, readerQuotas.MaxArrayLength); } if (readerQuotas.MaxBytesPerRead != EncoderDefaults.MaxBytesPerRead) { SetPropertyValueIfNotDefaultValue(ConfigurationStrings.MaxBytesPerRead, readerQuotas.MaxBytesPerRead); } if (readerQuotas.MaxNameTableCharCount != EncoderDefaults.MaxNameTableCharCount) { SetPropertyValueIfNotDefaultValue(ConfigurationStrings.MaxNameTableCharCount, readerQuotas.MaxNameTableCharCount); } } } }
using System.IO; namespace COL.UnityGameWheels.Core.Asset { internal class ResourceBasicInfoSerializer : IBinarySerializer<ResourceBasicInfo> { public void ToBinary(BinaryWriter bw, ResourceBasicInfo obj) { bw.Write(obj.Path); bw.Write(obj.GroupId); bw.Write(obj.DependingResourcePaths.Count); foreach (var dependingResourcePath in obj.DependingResourcePaths) { bw.Write(dependingResourcePath); } } public void FromBinary(BinaryReader br, ResourceBasicInfo obj) { obj.Path = br.ReadString(); obj.GroupId = br.ReadInt32(); obj.DependingResourcePaths.Clear(); var dependingResourcePathCount = br.ReadInt32(); for (int i = 0; i < dependingResourcePathCount; i++) { obj.DependingResourcePaths.Add(br.ReadString()); } } } }
using System.ComponentModel.DataAnnotations; namespace ContosoCrafts.WebSite.Models { /// <summary> /// Model for handling user login and user database user.json /// </summary> public class UserLoginModel { /// <summary> /// get and set user name method for user name in user services /// required field for login /// </summary> [Required(ErrorMessage = "* This field is required")] public string Username { get; set; } /// <summary> /// get and set method for password in user services /// required to min 6 characters and field is required for login /// </summary> [Required(ErrorMessage = "* This field is required")] public string Password { get; set; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Text; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using SharpShell.Attributes; using SharpShell.SharpThumbnailHandler; using TxtThumbnailHandler.Renderer; namespace TxtThumbnailHandler { /// <summary> /// The TxtThumbnailHandler is a ThumbnailHandler for text files. /// </summary> [ComVisible(true)] [COMServerAssociation(AssociationType.ClassOfExtension, ".txt")] public class TxtThumbnailHandler : SharpThumbnailHandler, IDisposable { /// <summary> /// Initializes a new instance of the <see cref="TxtThumbnailHandler"/> class. /// </summary> public TxtThumbnailHandler() { _renderer = new TextThumbnailRenderer(); } /// <summary> /// Gets the thumbnail image. /// </summary> /// <param name="width">The width of the image that should be returned.</param> /// <returns> /// The image for the thumbnail. /// </returns> protected override Bitmap GetThumbnailImage(uint width) { Log($"Creating thumbnail for '{SelectedItemStream.Name}'"); // Attempt to open the stream with a reader. try { using(var reader = new StreamReader(SelectedItemStream)) { // Read up to ten lines of text. var previewLines = new List<string>(); for (int i = 0; i < 10; i++) { var line = reader.ReadLine(); if (line == null) break; previewLines.Add(line); } // Now return a preview of the lines. return _renderer.CreateThumbnailForText(previewLines, width); } } catch (Exception exception) { // DebugLog the exception and return null for failure. LogError("An exception occured opening the text file.", exception); return null; } } /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { _renderer?.Dispose(); } /// <summary>The renderer used to create the text.</summary> private readonly TextThumbnailRenderer _renderer; } }
using Cmjimenez.PasswordResetTool.Application.PasswordReset.Model; namespace Cmjimenez.PasswordResetTool.Application.PasswordReset.Model { public class ResetResult { public string FailureMessage { get; private set; } public User User { get; private set; } public bool PasswordChanged { get; private set; } public bool HasErrorMessage { get; private set; } public ResetResult(User user, bool passwordChanged, string failureMessage) { if (failureMessage == null) { HasErrorMessage = false; } else { FailureMessage = failureMessage; HasErrorMessage = true; } User = user; PasswordChanged = passwordChanged; } } }
#region License /* ************************************************************************************** * Copyright (c) Librame Pong All rights reserved. * * https://github.com/librame * * You must not remove this notice, or any other, from this software. * **************************************************************************************/ #endregion using Librame.Extensions.Core; namespace Librame.Extensions.Data; class InternalIdentificationGeneratorFactory : IIdentificationGeneratorFactory { private readonly Dictionary<TypeNamedKey, IObjectIdentificationGenerator> _idGenerators = new(); public InternalIdentificationGeneratorFactory(IOptionsMonitor<DataExtensionOptions> dataOptions, IOptionsMonitor<CoreExtensionOptions> coreOptions) { if (_idGenerators.Count < 1) { var idOptions = dataOptions.CurrentValue.IdGeneration; var clock = coreOptions.CurrentValue.Clock; var locker = coreOptions.CurrentValue.Locker; var combIdType = typeof(CombIdentificationGenerator); // Base: IdentificationGenerator(Sqlite 使用与 MySQL 数据库相同的排序方式) _idGenerators.Add(new TypeNamedKey(combIdType, nameof(CombIdentificationGenerators.ForMySql)), CombIdentificationGenerators.ForMySql(clock, locker)); _idGenerators.Add(new TypeNamedKey(combIdType, nameof(CombIdentificationGenerators.ForOracle)), CombIdentificationGenerators.ForOracle(clock, locker)); _idGenerators.Add(new TypeNamedKey(combIdType, nameof(CombIdentificationGenerators.ForSqlServer)), CombIdentificationGenerators.ForSqlServer(clock, locker)); _idGenerators.Add(new TypeNamedKey<CombSnowflakeIdentificationGenerator>(), new CombSnowflakeIdentificationGenerator(clock, locker, idOptions)); _idGenerators.Add(new TypeNamedKey<MongoIdentificationGenerator>(), new MongoIdentificationGenerator(clock)); _idGenerators.Add(new TypeNamedKey<SnowflakeIdentificationGenerator>(), new SnowflakeIdentificationGenerator(clock, locker, idOptions)); if (dataOptions.CurrentValue.IdGenerators.Count > 0) { foreach (var idGenerator in dataOptions.CurrentValue.IdGenerators) { _idGenerators.Add(idGenerator.Key, idGenerator.Value); } } } } public IIdentificationGenerator<TId> GetIdGenerator<TId>(TypeNamedKey key) where TId : IEquatable<TId> => (IIdentificationGenerator<TId>)GetIdGenerator(key); public IObjectIdentificationGenerator GetIdGenerator(TypeNamedKey key) => _idGenerators[key]; }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: XMLCommToHTM.DOM.DocViewer File: ParameterDom.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License using System; using System.Linq; using System.Reflection; using System.Xml.Linq; using XMLCommToHTM.DOM.Internal; namespace XMLCommToHTM.DOM { public abstract class ParameterBaseDom { public XElement DocInfo; public abstract string Name { get; } public abstract Type Type { get; } } public class ParameterDictionary { private readonly Tuple<string, XElement>[] _params; public ParameterDictionary(XElement doc, string tagName) { _params=doc //Dictionary создавать не имеет смысла, т.к. параметров мало. .Elements(tagName) .Where(_ => _.Attribute("name") != null) .Select(_ => Tuple.Create(_.Attribute("name").Value, _)) .ToArray(); } public XElement this[string name] { get { foreach (var entry in _params) if (name == entry.Item1) return entry.Item2; return null; } } } public class ParameterDom : ParameterBaseDom { public ParameterDom(ParameterInfo parameterInfo) { Parameter = parameterInfo; } readonly ParameterInfo Parameter; public override string Name => Parameter.Name; public override Type Type => Parameter.ParameterType; //public string TypeName //{ // get { return TypeUtils.ToDisplayString(Parameter.ParameterType, true); } //} public static ParameterDom[] BuildParameters(ParameterInfo[] piAr, XElement parentDoc) { if(piAr==null || piAr.Length==0) return new ParameterDom[0]; if(parentDoc==null) return piAr.Select(_ => new ParameterDom(_)).ToArray(); var pd = new ParameterDictionary(parentDoc, "param"); return piAr .Select( _ => new ParameterDom(_){DocInfo = pd[_.Name]}) .ToArray(); } } public class GenericParameterDom : ParameterBaseDom { string _name; public GenericParameterDom(string name) { _name = name; } public override string Name => _name; public override Type Type => null; public static GenericParameterDom[] BuildTypeGenericParameters(Type type, XElement typeDoc) { if (!type.IsGenericType) return null; type = type.GetGenericTypeDefinition(); if (type == null) return null; return BuildGenericParameters(type.GetGenericArguments(),typeDoc); } public static GenericParameterDom[] BuildMethodGenericParameters(MethodInfo mi, XElement typeDoc) { if (!mi.IsGenericMethod) return null; mi = mi.GetGenericMethodDefinition(); if (mi == null) return null; return BuildGenericParameters(mi.GetGenericArguments(), typeDoc); } public static GenericParameterDom[] BuildGenericParameters(Type[] genericArgs, XElement typeDoc) { if (genericArgs.Length == 0) return null; if (typeDoc == null) return genericArgs.Select(_ => new GenericParameterDom(_.Name)).ToArray(); var pd = new ParameterDictionary(typeDoc, "typeparam"); return genericArgs .Select(_ => new GenericParameterDom(_.Name) { DocInfo = pd[_.Name] }) .ToArray(); } } }
using System; namespace Fergun.Attributes { /// <summary> /// Attaches an example to your command. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class ExampleAttribute : Attribute { public string Example { get; } public ExampleAttribute(string example) { Example = example; } } }
using System.Collections.Generic; namespace Alliterations.Api.Generator { internal sealed class AlliterationOptions { public IDictionary<char, string[]> Adjectives { get; set; } public IDictionary<char, string[]> Nouns { get; set; } public char[] AllowedStartingCharacters { get; set; } } }
using System; using System.Linq; namespace FM.LiveSwitch.Connect { static class IConnectionOptionsExtensions { public static AudioEncoding[] GetAudioEncodings(this IConnectionOptions options) { if (options.AudioCodec == AudioCodec.Any) { return ((AudioEncoding[])Enum.GetValues(typeof(AudioEncoding))).ToArray(); } return new[] { options.AudioCodec.ToEncoding() }; } public static VideoEncoding[] GetVideoEncodings(this IConnectionOptions options) { if (options.VideoCodec == VideoCodec.Any) { return ((VideoEncoding[])Enum.GetValues(typeof(VideoEncoding))).ToArray(); } return new[] { options.VideoCodec.ToEncoding() }; } } }
 using System; using Android.App; using Android.Content.PM; using Android.OS; using Com.Mapbox.Mapboxsdk.Maps; using Com.Mapbox.Mapboxsdk.Annotations; using Com.Mapbox.Mapboxsdk.Geometry; using static Com.Mapbox.Mapboxsdk.Maps.MapboxMap; using Android.Views; using Android.Widget; using Android.Content; using Android.Support.V4.Content; using Android.Runtime; using Android.Graphics; using MapBoxQs.Views; using Plugin.CurrentActivity; [assembly: UsesFeature("android.hardware.camera", Required = true)] [assembly: UsesFeature("android.hardware.camera.autofocus", Required = true)] namespace MapBoxQs.Droid { [Activity(Label = "MapBoxQs.Droid", Icon = "@mipmap/ic_launcher", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { new Com.Facebook.Soloader.SoLoader(); TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Com.Mapbox.Mapboxsdk.Mapbox.GetInstance(this, MapBoxQs.Services.MapBoxService.AccessToken); Com.Mapbox.Mapboxsdk.Mapbox.Telemetry.SetDebugLoggingEnabled(true); Acr.UserDialogs.UserDialogs.Init(() => this); FFImageLoading.Forms.Platform.CachedImageRenderer.Init(true); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); System.Diagnostics.Debug.WriteLine("Mapbox version: " + Com.Mapbox.Mapboxsdk.BuildConfig.MAPBOX_VERSION_STRING); Shiny.AndroidShinyHost.Init( this.Application, new MyStartup() ); Xamarin.Essentials.Platform.Init(this, savedInstanceState); CrossCurrentActivity.Current.Init(this, savedInstanceState); LoadApplication(new App()); //Shiny.Notifications.NotificationManager.TryProcessIntent(this.Intent); //SetContentView(Resource.Layout.activity_main); //mapView = (MapView)FindViewById(Resource.Id.mapView); //mapView.OnCreate(savedInstanceState); //mapView.GetMapAsync(new MapReady(this)); //mapView.OffsetTopAndBottom(0); } protected override void OnNewIntent(Intent intent) { base.OnNewIntent(intent); //Shiny.Notifications.NotificationManager.TryProcessIntent(intent); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); Shiny.AndroidShinyHost.OnRequestPermissionsResult(requestCode, permissions, grantResults); Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
using DG.Tweening; using UnityEngine; using UnityEngine.UI; public class Icon : MonoBehaviour { [SerializeField] private Image _image; public void Use() { _image.DOColor(Color.black, .5f); _image.DOFade(0.2f, .5f); } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace System.ServiceModel.Configuration { using System; using System.ServiceModel; using System.Configuration; using System.ServiceModel.Security; using System.ServiceModel.Channels; using System.Xml; using System.Security.Cryptography.X509Certificates; public sealed partial class WindowsServiceElement : ConfigurationElement { public WindowsServiceElement() { } [ConfigurationProperty(ConfigurationStrings.IncludeWindowsGroups, DefaultValue = SspiSecurityTokenProvider.DefaultExtractWindowsGroupClaims)] public bool IncludeWindowsGroups { get { return (bool)base[ConfigurationStrings.IncludeWindowsGroups]; } set { base[ConfigurationStrings.IncludeWindowsGroups] = value; } } [ConfigurationProperty(ConfigurationStrings.AllowAnonymousLogons, DefaultValue = SspiSecurityTokenProvider.DefaultAllowUnauthenticatedCallers)] public bool AllowAnonymousLogons { get { return (bool)base[ConfigurationStrings.AllowAnonymousLogons]; } set { base[ConfigurationStrings.AllowAnonymousLogons] = value; } } public void Copy(WindowsServiceElement from) { if (this.IsReadOnly()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigReadOnly))); } if (null == from) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("from"); } this.AllowAnonymousLogons = from.AllowAnonymousLogons; this.IncludeWindowsGroups = from.IncludeWindowsGroups; } internal void ApplyConfiguration(WindowsServiceCredential windows) { if (windows == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("windows"); } windows.AllowAnonymousLogons = this.AllowAnonymousLogons; windows.IncludeWindowsGroups = this.IncludeWindowsGroups; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR.Hubs; namespace WebchatBuilder.Helpers { public class HubPipelineHelper : HubPipelineModule { protected override bool OnBeforeIncoming(IHubIncomingInvokerContext context) { return base.OnBeforeIncoming(context); } protected override bool OnBeforeOutgoing(IHubOutgoingInvokerContext context) { return base.OnBeforeOutgoing(context); } } }
@using StockportWebapp.Config @model IEnumerable<StockportWebapp.Models.SubItem> @inject BusinessId BusinessId @foreach (var link in Model) { <li class="grid-50 tablet-grid-50 mobile-grid-100"> <a href="@link.NavigationLink">@link.Title</a> </li> }
using PeNet.Utilities; namespace PeNet.Structures { /// <summary> /// The NT header is the main header for modern Windows applications. /// It contains the file header and the optional header. /// </summary> public class IMAGE_NT_HEADERS : AbstractStructure { /// <summary> /// Access to the File header. /// </summary> public readonly IMAGE_FILE_HEADER FileHeader; /// <summary> /// Access to the Optional header. /// </summary> public readonly IMAGE_OPTIONAL_HEADER OptionalHeader; /// <summary> /// Create a new IMAGE_NT_HEADERS object. /// </summary> /// <param name="buff">A PE file as a byte array.</param> /// <param name="offset">Raw offset of the NT header.</param> public IMAGE_NT_HEADERS(byte[] buff, uint offset) : base(buff, offset) { FileHeader = new IMAGE_FILE_HEADER(buff, offset + 0x4); var is32Bit = FileHeader.Machine == (ushort) Constants.FileHeaderMachine.IMAGE_FILE_MACHINE_I386; OptionalHeader = new IMAGE_OPTIONAL_HEADER(buff, offset + 0x18, !is32Bit); } /// <summary> /// NT header signature. /// </summary> public uint Signature { get => Buff.BytesToUInt32(Offset); set => Buff.SetUInt32(Offset, value); } } }
using Newtonsoft.Json; using System.Collections.Generic; using TRLevelReader.Model; namespace TREnvironmentEditor.Model { public abstract class BaseEMCondition { [JsonProperty(Order = -2)] public string Comments { get; set; } [JsonProperty(Order = -2)] public EMConditionType ConditionType { get; set; } public bool Negate { get; set; } public List<BaseEMCondition> And { get; set; } public List<BaseEMCondition> Or { get; set; } public BaseEMCondition Xor { get; set; } public bool GetResult(TR2Level level) { bool result = Evaluate(level); if (Negate) { result = !result; } if (And != null) { And.ForEach(a => result &= a.GetResult(level)); } if (Or != null) { Or.ForEach(o => result |= o.GetResult(level)); } if (Xor != null) { result ^= Xor.GetResult(level); } return result; } public bool GetResult(TR3Level level) { bool result = Evaluate(level); if (Negate) { result = !result; } if (And != null) { And.ForEach(a => result &= a.GetResult(level)); } if (Or != null) { Or.ForEach(o => result |= o.GetResult(level)); } if (Xor != null) { result ^= Xor.GetResult(level); } return result; } protected abstract bool Evaluate(TR2Level level); protected abstract bool Evaluate(TR3Level level); } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.ComponentModel; using System.Drawing; using System.Security.Permissions; using System.Diagnostics; namespace JustGestures.ControlItems { class CheckComboBox : ComboBox { ToolStripDropDown m_dropDown; bool m_droppedDown = false; CheckListBox m_checkListBox; DateTime m_lastHideTime = DateTime.Now; string m_text = string.Empty; public ImageList ImageList { set { m_checkListBox.SmallImageList = value; } } public event ItemCheckedEventHandler ItemChecked; private void OnItemChecked(object sender, ItemCheckedEventArgs e) { if (ItemChecked != null) ItemChecked(sender, e); } public ListView.ListViewItemCollection ListItems { get { return m_checkListBox.Items; } } public ListView.CheckedListViewItemCollection CheckedListItems { get { return m_checkListBox.CheckedItems; } } public CheckComboBox() : base() { m_checkListBox = new CheckListBox(); m_checkListBox.Dock = DockStyle.Fill; m_checkListBox.ItemChecked += new ItemCheckedEventHandler(m_checkListBox_ItemChecked); m_dropDown = new ToolStripDropDown(); m_dropDown.Margin = new Padding(0); m_dropDown.Padding = new Padding(1); m_dropDown.Items.Add(new ToolStripControlHost(m_checkListBox)); m_dropDown.Closing += new ToolStripDropDownClosingEventHandler(m_dropDown_Closing); } void m_checkListBox_ItemChecked(object sender, ItemCheckedEventArgs e) { CheckListItems(); OnItemChecked(sender, e); //this.Text = m_text; } public void CheckListItems() { m_text = string.Empty; this.Items.Clear(); foreach (ListViewItem item in m_checkListBox.CheckedItems) m_text += item.Text + ", "; if (m_text != string.Empty) { m_text = m_text.Substring(0, m_text.Length - 2); TextFormatFlags textFlags = TextFormatFlags.EndEllipsis | TextFormatFlags.ModifyString; TextRenderer.MeasureText(m_text, this.Font, new Size(this.ClientSize.Width - 15, 0), textFlags); this.Items.Add(m_text); this.SelectedIndex = 0; } } protected override void OnSizeChanged(EventArgs e) { m_checkListBox.Width = this.ClientSize.Width - 2; } void m_dropDown_Closing(object sender, ToolStripDropDownClosingEventArgs e) { m_droppedDown = false; m_lastHideTime = DateTime.Now; } public void AddItem(string id, string caption) { m_checkListBox.AddItem(id, caption); } public virtual void ShowDropDown() { if (!m_droppedDown) { m_dropDown.Show(this, 0, this.Height); m_droppedDown = true; m_checkListBox.Focus(); m_sShowTime = DateTime.Now; } } public virtual void HideDropDown() { if (m_droppedDown) { m_dropDown.Hide(); m_droppedDown = false; } } public const uint WM_COMMAND = 0x0111; public const uint WM_USER = 0x0400; public const uint WM_REFLECT = WM_USER + 0x1C00; public const uint WM_LBUTTONDOWN = 0x0201; public const uint WM_LBUTTONDBLCLK = 0x0203; public const uint CBN_DROPDOWN = 7; public const uint CBN_CLOSEUP = 8; public static uint HIWORD(int n) { return (uint)(n >> 16) & 0xffff; } private static DateTime m_sShowTime = DateTime.Now; private void AutoDropDown() { if (m_dropDown.Visible) HideDropDown(); else if ((DateTime.Now - m_lastHideTime).Milliseconds > 50) ShowDropDown(); } protected override void WndProc(ref Message m) { if (m.Msg == WM_LBUTTONDOWN || m.Msg == WM_LBUTTONDBLCLK) { AutoDropDown(); return; } if (m.Msg == (WM_REFLECT + WM_COMMAND)) { switch (HIWORD((int)m.WParam)) { case CBN_DROPDOWN: AutoDropDown(); return; case CBN_CLOSEUP: HideDropDown(); return; } } base.WndProc(ref m); } } }
namespace Gaia.Lex { public class Token { public static readonly Token Null = new(0); public readonly int Tag; public Token(int t) { Tag = t; } public override string ToString() { return Tag.ToString(); } } }
using System.Numerics; namespace UAlbion.Game { public interface ICollider { bool IsOccupied(Vector2 tilePosition); } }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package ssa -- go2cs converted at 2020 October 09 05:24:18 UTC // import "cmd/compile/internal/ssa" ==> using ssa = go.cmd.compile.@internal.ssa_package // Original source: C:\Go\src\cmd\compile\internal\ssa\block.go using src = go.cmd.@internal.src_package; using fmt = go.fmt_package; using static go.builtin; namespace go { namespace cmd { namespace compile { namespace @internal { public static partial class ssa_package { // Block represents a basic block in the control flow graph of a function. public partial struct Block { public ID ID; // Source position for block's control operation public src.XPos Pos; // The kind of block this is. public BlockKind Kind; // Likely direction for branches. // If BranchLikely, Succs[0] is the most likely branch taken. // If BranchUnlikely, Succs[1] is the most likely branch taken. // Ignored if len(Succs) < 2. // Fatal if not BranchUnknown and len(Succs) > 2. public BranchPrediction Likely; // After flagalloc, records whether flags are live at the end of the block. public bool FlagsLiveAtEnd; // Subsequent blocks, if any. The number and order depend on the block kind. public slice<Edge> Succs; // Inverse of successors. // The order is significant to Phi nodes in the block. // TODO: predecessors is a pain to maintain. Can we somehow order phi // arguments by block id and have this field computed explicitly when needed? public slice<Edge> Preds; // A list of values that determine how the block is exited. The number // and type of control values depends on the Kind of the block. For // instance, a BlockIf has a single boolean control value and BlockExit // has a single memory control value. // // The ControlValues() method may be used to get a slice with the non-nil // control values that can be ranged over. // // Controls[1] must be nil if Controls[0] is nil. public array<ptr<Value>> Controls; // Auxiliary info for the block. Its value depends on the Kind. public long AuxInt; // The unordered set of Values that define the operation of this block. // After the scheduling pass, this list is ordered. public slice<ptr<Value>> Values; // The containing function public ptr<Func> Func; // Storage for Succs, Preds and Values. public array<Edge> succstorage; public array<Edge> predstorage; public array<ptr<Value>> valstorage; } // Edge represents a CFG edge. // Example edges for b branching to either c or d. // (c and d have other predecessors.) // b.Succs = [{c,3}, {d,1}] // c.Preds = [?, ?, ?, {b,0}] // d.Preds = [?, {b,1}, ?] // These indexes allow us to edit the CFG in constant time. // In addition, it informs phi ops in degenerate cases like: // b: // if k then c else c // c: // v = Phi(x, y) // Then the indexes tell you whether x is chosen from // the if or else branch from b. // b.Succs = [{c,0},{c,1}] // c.Preds = [{b,0},{b,1}] // means x is chosen if k is true. public partial struct Edge { public ptr<Block> b; // index of reverse edge. Invariant: // e := x.Succs[idx] // e.b.Preds[e.i] = Edge{x,idx} // and similarly for predecessors. public long i; } public static ptr<Block> Block(this Edge e) { return _addr_e.b!; } public static long Index(this Edge e) { return e.i; } public static @string String(this Edge e) { return fmt.Sprintf("{%v,%d}", e.b, e.i); } // kind controls successors // ------------------------------------------ // Exit [return mem] [] // Plain [] [next] // If [boolean Value] [then, else] // Defer [mem] [nopanic, panic] (control opcode should be OpStaticCall to runtime.deferproc) public partial struct BlockKind // : sbyte { } // short form print private static @string String(this ptr<Block> _addr_b) { ref Block b = ref _addr_b.val; return fmt.Sprintf("b%d", b.ID); } // long form print private static @string LongString(this ptr<Block> _addr_b) { ref Block b = ref _addr_b.val; var s = b.Kind.String(); if (b.Aux != null) { s += fmt.Sprintf(" {%s}", b.Aux); } { var t = b.AuxIntString(); if (t != "") { s += fmt.Sprintf(" [%s]", t); } } { var c__prev1 = c; foreach (var (_, __c) in b.ControlValues()) { c = __c; s += fmt.Sprintf(" %s", c); } c = c__prev1; } if (len(b.Succs) > 0L) { s += " ->"; { var c__prev1 = c; foreach (var (_, __c) in b.Succs) { c = __c; s += " " + c.b.String(); } c = c__prev1; } } if (b.Likely == BranchUnlikely) s += " (unlikely)"; else if (b.Likely == BranchLikely) s += " (likely)"; return s; } // NumControls returns the number of non-nil control values the // block has. private static long NumControls(this ptr<Block> _addr_b) { ref Block b = ref _addr_b.val; if (b.Controls[0L] == null) { return 0L; } if (b.Controls[1L] == null) { return 1L; } return 2L; } // ControlValues returns a slice containing the non-nil control // values of the block. The index of each control value will be // the same as it is in the Controls property and can be used // in ReplaceControl calls. private static slice<ptr<Value>> ControlValues(this ptr<Block> _addr_b) { ref Block b = ref _addr_b.val; if (b.Controls[0L] == null) { return b.Controls[..0L]; } if (b.Controls[1L] == null) { return b.Controls[..1L]; } return b.Controls[..2L]; } // SetControl removes all existing control values and then adds // the control value provided. The number of control values after // a call to SetControl will always be 1. private static void SetControl(this ptr<Block> _addr_b, ptr<Value> _addr_v) { ref Block b = ref _addr_b.val; ref Value v = ref _addr_v.val; b.ResetControls(); b.Controls[0L] = v; v.Uses++; } // ResetControls sets the number of controls for the block to 0. private static void ResetControls(this ptr<Block> _addr_b) { ref Block b = ref _addr_b.val; if (b.Controls[0L] != null) { b.Controls[0L].Uses--; } if (b.Controls[1L] != null) { b.Controls[1L].Uses--; } b.Controls = new array<ptr<Value>>(new ptr<Value>[] { }); // reset both controls to nil } // AddControl appends a control value to the existing list of control values. private static void AddControl(this ptr<Block> _addr_b, ptr<Value> _addr_v) { ref Block b = ref _addr_b.val; ref Value v = ref _addr_v.val; var i = b.NumControls(); b.Controls[i] = v; // panics if array is full v.Uses++; } // ReplaceControl exchanges the existing control value at the index provided // for the new value. The index must refer to a valid control value. private static void ReplaceControl(this ptr<Block> _addr_b, long i, ptr<Value> _addr_v) { ref Block b = ref _addr_b.val; ref Value v = ref _addr_v.val; b.Controls[i].Uses--; b.Controls[i] = v; v.Uses++; } // CopyControls replaces the controls for this block with those from the // provided block. The provided block is not modified. private static void CopyControls(this ptr<Block> _addr_b, ptr<Block> _addr_from) { ref Block b = ref _addr_b.val; ref Block from = ref _addr_from.val; if (b == from) { return ; } b.ResetControls(); foreach (var (_, c) in from.ControlValues()) { b.AddControl(c); } } // Reset sets the block to the provided kind and clears all the blocks control // and auxiliary values. Other properties of the block, such as its successors, // predecessors and values are left unmodified. private static void Reset(this ptr<Block> _addr_b, BlockKind kind) { ref Block b = ref _addr_b.val; b.Kind = kind; b.ResetControls(); b.Aux = null; b.AuxInt = 0L; } // resetWithControl resets b and adds control v. // It is equivalent to b.Reset(kind); b.AddControl(v), // except that it is one call instead of two and avoids a bounds check. // It is intended for use by rewrite rules, where this matters. private static void resetWithControl(this ptr<Block> _addr_b, BlockKind kind, ptr<Value> _addr_v) { ref Block b = ref _addr_b.val; ref Value v = ref _addr_v.val; b.Kind = kind; b.ResetControls(); b.Aux = null; b.AuxInt = 0L; b.Controls[0L] = v; v.Uses++; } // resetWithControl2 resets b and adds controls v and w. // It is equivalent to b.Reset(kind); b.AddControl(v); b.AddControl(w), // except that it is one call instead of three and avoids two bounds checks. // It is intended for use by rewrite rules, where this matters. private static void resetWithControl2(this ptr<Block> _addr_b, BlockKind kind, ptr<Value> _addr_v, ptr<Value> _addr_w) { ref Block b = ref _addr_b.val; ref Value v = ref _addr_v.val; ref Value w = ref _addr_w.val; b.Kind = kind; b.ResetControls(); b.Aux = null; b.AuxInt = 0L; b.Controls[0L] = v; b.Controls[1L] = w; v.Uses++; w.Uses++; } // truncateValues truncates b.Values at the ith element, zeroing subsequent elements. // The values in b.Values after i must already have had their args reset, // to maintain correct value uses counts. private static void truncateValues(this ptr<Block> _addr_b, long i) { ref Block b = ref _addr_b.val; var tail = b.Values[i..]; foreach (var (j) in tail) { tail[j] = null; } b.Values = b.Values[..i]; } // AddEdgeTo adds an edge from block b to block c. Used during building of the // SSA graph; do not use on an already-completed SSA graph. private static void AddEdgeTo(this ptr<Block> _addr_b, ptr<Block> _addr_c) { ref Block b = ref _addr_b.val; ref Block c = ref _addr_c.val; var i = len(b.Succs); var j = len(c.Preds); b.Succs = append(b.Succs, new Edge(c,j)); c.Preds = append(c.Preds, new Edge(b,i)); b.Func.invalidateCFG(); } // removePred removes the ith input edge from b. // It is the responsibility of the caller to remove // the corresponding successor edge. private static void removePred(this ptr<Block> _addr_b, long i) { ref Block b = ref _addr_b.val; var n = len(b.Preds) - 1L; if (i != n) { var e = b.Preds[n]; b.Preds[i] = e; // Update the other end of the edge we moved. e.b.Succs[e.i].i = i; } b.Preds[n] = new Edge(); b.Preds = b.Preds[..n]; b.Func.invalidateCFG(); } // removeSucc removes the ith output edge from b. // It is the responsibility of the caller to remove // the corresponding predecessor edge. private static void removeSucc(this ptr<Block> _addr_b, long i) { ref Block b = ref _addr_b.val; var n = len(b.Succs) - 1L; if (i != n) { var e = b.Succs[n]; b.Succs[i] = e; // Update the other end of the edge we moved. e.b.Preds[e.i].i = i; } b.Succs[n] = new Edge(); b.Succs = b.Succs[..n]; b.Func.invalidateCFG(); } private static void swapSuccessors(this ptr<Block> _addr_b) { ref Block b = ref _addr_b.val; if (len(b.Succs) != 2L) { b.Fatalf("swapSuccessors with len(Succs)=%d", len(b.Succs)); } var e0 = b.Succs[0L]; var e1 = b.Succs[1L]; b.Succs[0L] = e1; b.Succs[1L] = e0; e0.b.Preds[e0.i].i = 1L; e1.b.Preds[e1.i].i = 0L; b.Likely *= -1L; } // LackingPos indicates whether b is a block whose position should be inherited // from its successors. This is true if all the values within it have unreliable positions // and if it is "plain", meaning that there is no control flow that is also very likely // to correspond to a well-understood source position. private static bool LackingPos(this ptr<Block> _addr_b) { ref Block b = ref _addr_b.val; // Non-plain predecessors are If or Defer, which both (1) have two successors, // which might have different line numbers and (2) correspond to statements // in the source code that have positions, so this case ought not occur anyway. if (b.Kind != BlockPlain) { return false; } if (b.Pos != src.NoXPos) { return false; } foreach (var (_, v) in b.Values) { if (v.LackingPos()) { continue; } return false; } return true; } private static @string AuxIntString(this ptr<Block> _addr_b) { ref Block b = ref _addr_b.val; switch (b.Kind.AuxIntType()) { case "int8": return fmt.Sprintf("%v", int8(b.AuxInt)); break; case "uint8": return fmt.Sprintf("%v", uint8(b.AuxInt)); break; case "": // no aux int type return ""; break; default: // type specified but not implemented - print as int64 return fmt.Sprintf("%v", b.AuxInt); break; } } private static void Logf(this ptr<Block> _addr_b, @string msg, params object[] args) { args = args.Clone(); ref Block b = ref _addr_b.val; b.Func.Logf(msg, args); } private static bool Log(this ptr<Block> _addr_b) { ref Block b = ref _addr_b.val; return b.Func.Log(); } private static void Fatalf(this ptr<Block> _addr_b, @string msg, params object[] args) { args = args.Clone(); ref Block b = ref _addr_b.val; b.Func.Fatalf(msg, args); } public partial struct BranchPrediction // : sbyte { } public static readonly var BranchUnlikely = BranchPrediction(-1L); public static readonly var BranchUnknown = BranchPrediction(0L); public static readonly var BranchLikely = BranchPrediction(+1L); } }}}}
using Rasberry.Cli; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; namespace Rasberry.Cli.Tests { [TestClass] public class ExtraParsersTest { [DataTestMethod] [DataRow("1%",0.01)] [DataRow("100%",1.0)] [DataRow("125%",1.25)] [DataRow("0.1%",0.001)] [DataRow("1e10%",1e8)] [DataRow("-1%",-0.01)] [DataRow("0.1",0.1)] [DataRow("1e10",1e10)] public void TryParseNumberPercentSuccess(string raw, double expected) { bool w = ExtraParsers.TryParseNumberPercent(raw,out double parsed); Assert.IsTrue(w); Assert.AreEqual(expected,parsed); } [DataTestMethod] [DataRow("a1%")] [DataRow("a%")] [DataRow("%")] [DataRow("")] [DataRow(null)] [DataRow("10% ")] [DataRow("Infinity")] public void TryParseNumberPercentFail(string raw) { bool w = ExtraParsers.TryParseNumberPercent(raw,out double _); Assert.IsFalse(w); } [DataTestMethod] [DataRow(false,"b",FoodStuff.Bread)] [DataRow(false,"B",FoodStuff.Bread)] [DataRow(false,"Bread",FoodStuff.Bread)] [DataRow(false,"BonBons",FoodStuff.BonBons)] [DataRow(false,"d",FoodStuff.Donut)] [DataRow(false,"0",FoodStuff.Donut)] [DataRow(false,"4",FoodStuff.Bread)] [DataRow(true,"d",FoodStuff.Dumplings)] public void TryParseEnumFirstLetterSuccess(bool igz, string raw, FoodStuff expected) { bool w = ExtraParsers.TryParseEnumFirstLetter(raw,out FoodStuff parsed,igz); Assert.IsTrue(w); Assert.AreEqual(expected,parsed); } [DataTestMethod] [DataRow(false,"q")] [DataRow(true,"0")] [DataRow(true,"Donut")] public void TryParseEnumFirstLetterFail(bool igz, string raw) { bool w = ExtraParsers.TryParseEnumFirstLetter(raw,out FoodStuff _, igz); Assert.IsFalse(w); } [DataTestMethod] [DynamicData(nameof(GetSuccessData), DynamicDataSourceType.Method)] public void TryParseSequenceSuccess(string raw, FoodStuff[] expected) { var parser = new ParseParams.Parser<FoodStuff>((string arg, out FoodStuff val) => { return ExtraParsers.TryParseEnumFirstLetter(arg,out val); }); bool w = ExtraParsers.TryParseSequence(raw,new char[] { ' ' }, out var list,parser); Assert.IsTrue(w); var wrapList = new List<FoodStuff>(list); CollectionAssert.AreEqual(expected,wrapList); } static IEnumerable<object[]> GetSuccessData() { yield return new object[] { "b d f m BonBons", new[] { FoodStuff.Bread, FoodStuff.Donut, FoodStuff.Fish, FoodStuff.Milk, FoodStuff.BonBons } }; } [DataTestMethod] [DynamicData(nameof(GetFailData), DynamicDataSourceType.Method)] public void TryParseSequenceFail(string raw) { var parser = new ParseParams.Parser<FoodStuff>((string arg, out FoodStuff val) => { return ExtraParsers.TryParseEnumFirstLetter(arg,out val); }); bool w = ExtraParsers.TryParseSequence(raw,new char[] { ' ' }, out var _, parser); Assert.IsFalse(w); } static IEnumerable<object[]> GetFailData() { yield return new object[] { "q" }; } } }