content
stringlengths
23
1.05M
namespace UnbeatableTicTacToe.GameCore.GameMode { public interface IPlayableGameMode { void Loop(); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Text; namespace DataRamp { public interface IParameterMapper { void AssignParameters(IDbCommand command, params Object[] parameterValues); } }
using System; namespace Prometheus.DotNetRuntime.EventListening.Parsers { internal static class DelegateExtensions { internal static void InvokeManyTimes<T>(this Action<T> d, int count, T payload) { for (int i = 0; i < count; i++) { d(payload); } } } }
using System; using System.Net.Http; using System.Threading.Tasks; namespace JsonHCSNet { public interface IRequestMiddleware { Task<HttpRequestMessage> HandleRequestAsync(JsonHCS jsonHCS, HttpRequestMessage request); } }
using BootstrapTagHelpers.Extensions; using Microsoft.AspNetCore.Razor.TagHelpers; namespace BootstrapTagHelpers.Navigation { using BootstrapTagHelpers.Attributes; [HtmlTargetElement(ParentTag = "breadcrumbs")] [OutputElementHint("li")] public class BreadcrumbTagHelper : BootstrapTagHelper { public string Href { get; set; } [HtmlAttributeNotBound] [HtmlAttributeMinimizable] public bool Active { get; set; } protected override void BootstrapProcess(TagHelperContext context, TagHelperOutput output) { output.TagName = "li"; if (Active) output.AddCssClass("active"); if (!string.IsNullOrEmpty(Href)) { output.PreContent.SetHtmlContent($"<a href=\"{Href}\">"); output.PostContent.SetHtmlContent("</a>"); } } } }
using ContactsSync.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Identity.Client; using Microsoft.Identity.Web; using Microsoft.Graph; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Text.Json; using System.Linq; using Microsoft.EntityFrameworkCore; using System.IO; namespace ContactsSync.Controllers { public class ContactsController : Controller { private readonly ITokenAcquisition _tokenAcquisition; private readonly patientInfoContext _context; public ContactsController( ITokenAcquisition tokenAcquisition, patientInfoContext context) { _tokenAcquisition = tokenAcquisition; _context = context; } public async Task<IActionResult> Initialize() { //initialize the MS Graph API client to connect to Graph var graphClient = GraphServiceClientFactory .GetAuthenticatedGraphClient(async () => { return await _tokenAcquisition .GetAccessTokenForUserAsync(GraphConstants.Scopes); }); //Get Data - see function below IEnumerable<Patients> sql = await GetDataFromDB(); foreach (Patients patient in sql) { try { //make a new MS Contact Object using the patient data from sql query Contact contact = new PatientContact().NewContact(patient); //send the Contact Object to Microsoft People await graphClient.Me.Contacts .Request() .AddAsync(contact); } catch (ServiceException ex) { return RedirectToAction("Index") .WithError("Error With the Contact", ex.Error.Message); } } return RedirectToAction("Index", "Home"); } //IMPORT list of contacts from SQL and turn into JsonPerson Objects private async Task<IEnumerable<Patients>> GetDataFromDB() { return await _context.Patients.Select(p => p).ToListAsync(); } } }
using System; using System.Globalization; using System.Windows.Data; using DDictionary.Domain.Entities; namespace DDictionary.Presentation.Converters { public sealed class WordGroupConverter: IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { //https://stackoverflow.com/questions/3978937/how-to-pass-an-integer-as-converterparameter System.Diagnostics.Debug.Assert(value is WordGroup && (targetType == typeof(string) || targetType == typeof(object))); System.Diagnostics.Debug.Assert(parameter is null || parameter is bool?); if(targetType == typeof(object)) return value; else return ((bool?)parameter == true) ? ((WordGroup)value).ToFullStr() : ((WordGroup)value).ToGradeStr(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { //WordGroupTranslator.FromGradeStr() ?.. throw new NotSupportedException(); } } }
using System; namespace PcapDotNet.Packets { internal sealed class OptionTypeRegistrationAttribute : Attribute { public OptionTypeRegistrationAttribute(Type optionTypeType, object optionType) { OptionTypeType = optionTypeType; OptionType = optionType; } public object OptionType { get; private set; } public Type OptionTypeType { get; private set; } } }
/* This file is part of the "Simple Waypoint System" project by Rebound Games. * You are only allowed to use these resources if you've bought them from the Unity Asset Store. * You shall not license, sublicense, sell, resell, transfer, assign, distribute or * otherwise make available to any third party the Service or the Content. */ using UnityEngine; using UnityEngine.Events; using System.Collections; using SWS; #if UNITY_5_5_OR_NEWER using UnityEngine.AI; #endif /// <summary> /// Example: some methods invoked by events, demonstrating runtime adjustments. /// <summary> public class EventReceiver : MonoBehaviour { public void MyMethod() { //your own method! } //prints text to the console public void PrintText(string text) { Debug.Log(text); } //sets the transform's y-axis to the desired rotation //could be used in 2D for rotating a sprite at path ends public void RotateSprite(float newRot) { Vector3 currentRot = transform.eulerAngles; currentRot.y = newRot; transform.eulerAngles = currentRot; } //sets a new destination for a navmesh agent, //leaving its path and returning to it after a few seconds. //used in the event sample for redirecting the agent public void SetDestination(Object target) { StartCoroutine(SetDestinationRoutine(target)); } private IEnumerator SetDestinationRoutine(Object target) { //get references NavMeshAgent agent = GetComponent<NavMeshAgent>(); navMove myMove = GetComponent<navMove>(); GameObject tar = (GameObject)target as GameObject; //increase agent speed myMove.ChangeSpeed(4); //set new destination of the navmesh agent agent.SetDestination(tar.transform.position); //wait until the path has been calculated while (agent.pathPending) yield return null; //wait until agent reached its destination float remain = agent.remainingDistance; while (remain == Mathf.Infinity || remain - agent.stoppingDistance > float.Epsilon || agent.pathStatus != NavMeshPathStatus.PathComplete) { remain = agent.remainingDistance; yield return null; } //wait a few seconds at the destination, //then decrease agent speed and restart movement routine yield return new WaitForSeconds(4); myMove.ChangeSpeed(1.5f); myMove.moveToPath = true; myMove.StartMove(); } //activates an object for an amount of time //used in the event sample for activating a particle effect public void ActivateForTime(Object target) { StartCoroutine(ActivateForTimeRoutine(target)); } private IEnumerator ActivateForTimeRoutine(Object target) { GameObject tar = (GameObject)target as GameObject; tar.SetActive(true); yield return new WaitForSeconds(6); tar.SetActive(false); } }
using System; using System.Data; namespace MigSharp.Process { internal class DbConnectionWrapper : IDbConnection { private readonly IDbConnection _connection; internal DbConnectionWrapper(IDbConnection connection) { if (connection == null) throw new ArgumentNullException("connection"); _connection = connection; } public void Dispose() { // ignore } public IDbTransaction BeginTransaction() { return _connection.BeginTransaction(); } public IDbTransaction BeginTransaction(IsolationLevel il) { return _connection.BeginTransaction(il); } public void Close() { // ignore } public void ChangeDatabase(string databaseName) { _connection.ChangeDatabase(databaseName); } public IDbCommand CreateCommand() { return _connection.CreateCommand(); } public void Open() { throw new InvalidOperationException("Open should not be called on the DbConnectionWrapper."); } public string ConnectionString { get { return _connection.ConnectionString; } set { _connection.ConnectionString = value; } } public int ConnectionTimeout { get { return _connection.ConnectionTimeout; } } public string Database { get { return _connection.Database; } } public ConnectionState State { get { return _connection.State; } } } }
//------------------------------------------------------------------------------ // <copyright company="LeanKit Inc."> // Copyright (c) LeanKit Inc. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; namespace LeanKit.API.Client.Library.TransferObjects { public class BoardHistoryEvent { public long CardId { get; set; } public string EventType { get; set; } public DateTime EventDateTime { get; set; } public string Message { get; set; } public long ToLaneId { get; set; } public long? FromLaneId { get; set; } public bool RequiresBoardRefresh { get; set; } public bool IsBlocked { get; set; } public string BlockedComment { get; set; } public long UserId { get; set; } public long AssignedUserId { get; set; } public bool IsUnassigning { get; set; } public string CommentText { get; set; } public string WipOverrideComment { get; set; } public long WipOverrideLane { get; set; } public long WipOverrideUser { get; set; } public string FileName { get; set; } public bool IsFileBeingDeleted { get; set; } } }
using System; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using TT.Abp.Shops; using TT.Extensions; using Volo.Abp; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Repositories; using Volo.Abp.Features; namespace TT.Abp.AuditManagement.Audits { public class AuditCrudAppService<TEntity, TEntityDto, TPrimaryKey, TGetAllInput, TCreateInput, TUpdateInput> : CrudAppService<TEntity, TEntityDto, TPrimaryKey, TGetAllInput, TCreateInput, TUpdateInput> where TEntity : class, IEntity<TPrimaryKey>, INeedAudit where TEntityDto : IEntityDto<TPrimaryKey> where TUpdateInput : IEntityDto<TPrimaryKey>, INeedAuditBase where TCreateInput : INeedAuditBase { private readonly ICurrentShop _currentShop; private readonly IAuditProvider _auditProvider; private readonly AuditManager _auditManager; public string CurrentAuditName { get; set; } public AuditCrudAppService( IRepository<TEntity, TPrimaryKey> repository, IServiceProvider serviceProvider ) : base(repository) { _currentShop = serviceProvider.GetRequiredService<ICurrentShop>(); _auditProvider = serviceProvider.GetRequiredService<IAuditProvider>(); _auditManager = serviceProvider.GetRequiredService<AuditManager>(); } public virtual async Task StartAudit(TEntityDto input) { if (CurrentAuditName.IsNullOrEmptyOrWhiteSpace()) { throw new UserFriendlyException("CurrentAuditName is not set"); } var dbEntity = await GetEntityByIdAsync(input.Id); if (dbEntity == null) { throw new UserFriendlyException("NotFind"); } if (dbEntity is IMultiShop && HasShopIdProperty(dbEntity)) { var propertyInfo = dbEntity.GetType().GetProperty(nameof(IMultiShop.ShopId)); if (propertyInfo != null) { if (propertyInfo.GetValue(dbEntity) is Guid shopId) { _currentShop.Change(shopId); } } } dbEntity.AuditFlowId = await _auditProvider.GetOrNullAsync(CurrentAuditName); await _auditManager.StartAudit<TEntity, TPrimaryKey>(dbEntity); } public virtual async Task Agree() { await Task.CompletedTask; } protected virtual bool HasShopIdProperty(TEntity entity) { return entity.GetType().GetProperty(nameof(IMultiShop.ShopId)) != null; } } }
using System; using System.Runtime.InteropServices; namespace ScannitSharp { [StructLayout(LayoutKind.Sequential)] internal struct RustBuffer { private IntPtr Data; private UIntPtr Len; private UIntPtr Capacity; internal byte[] AsByteArray() { uint length = Len.ToUInt32(); byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = Marshal.ReadByte(Data, i); } return bytes; } internal FFIHistory[] AsFFIHistoryArray() { int historyStructSize = Marshal.SizeOf(typeof(FFIHistory)); uint length = Len.ToUInt32(); FFIHistory[] ffiHistories = new FFIHistory[length]; for (int i = 0; i < length; i++) { IntPtr structData = new IntPtr(Data.ToInt64() + historyStructSize * i); ffiHistories[i] = Marshal.PtrToStructure<FFIHistory>(structData); } return ffiHistories; } } }
using System; using Syn.Speech.Logging; using Syn.Speech.FrontEnds; using Syn.Speech.Util; //PATROLLED + REFACTORED namespace Syn.Speech.Linguist.Acoustic.Tiedstate { public class GaussianMixture : ScoreCachingSenone { // these data element in a senone may be shared with other senones // and therefore should not be written to. protected GaussianWeights MixtureWeights; private readonly MixtureComponent[] _mixtureComponents; protected int _Id; protected LogMath LogMath; /// <summary> /// Initializes a new instance of the <see cref="GaussianMixture"/> class. /// </summary> /// <param name="mixtureWeights">The mixture weights for this senone in LogMath log base.</param> /// <param name="mixtureComponents">The mixture components for this senone.</param> /// <param name="id">The identifier.</param> public GaussianMixture(GaussianWeights mixtureWeights, MixtureComponent[] mixtureComponents, int id) { LogMath = LogMath.GetLogMath(); _mixtureComponents = mixtureComponents; MixtureWeights = mixtureWeights; _Id = id; } /// <summary> /// Dumps a senone /// </summary> /// <param name="msg">Annotation message.</param> public override void Dump(String msg) { this.LogInfo(msg + " GaussianMixture: ID " + ID); } /// <summary> /// Determines whether the specified <see cref="System.Object" />, is equal to this instance. /// </summary> /// <param name="o">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object o) { if (!(o is ISenone)) { return false; } var other = (ISenone)o; return ID == other.ID; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { var _id = ID; var high = (int)((_id >> 32)); var low = (int)(_id); return high + low; } public override long ID { get { return _Id; } } /// <summary> /// Retrieves a string form of this object. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { return "senone id: " + ID; } public override float CalculateScore(IData feature) { if (feature is DoubleData) this.LogInfo("DoubleData conversion required on mixture level!"); var featureVector = FloatData.ToFloatData(feature).Values; var logTotal = LogMath.LogZero; for (var i = 0; i < _mixtureComponents.Length; i++) { // In linear form, this would be: // // Total += Mixture[i].score * MixtureWeight[i] logTotal = LogMath.AddAsLinear(logTotal, _mixtureComponents[i].GetScore(featureVector) + MixtureWeights.Get(_Id, 0, i)); } return logTotal; } /// <summary> /// Calculates the scores for each component in the senone. /// </summary> /// <param name="feature">The feature to score.</param> /// <returns>The LogMath log scores for the feature, one for each component.</returns> public override float[] CalculateComponentScore(IData feature) { if (feature is DoubleData) this.LogInfo("DoubleData conversion required on mixture level!"); var featureVector = FloatData.ToFloatData(feature).Values; var logComponentScore = new float[_mixtureComponents.Length]; for (var i = 0; i < _mixtureComponents.Length; i++) { // In linear form, this would be: // // Total += Mixture[i].score * MixtureWeight[i] logComponentScore[i] = _mixtureComponents[i].GetScore(featureVector) + MixtureWeights.Get(_Id, 0, i); } return logComponentScore; } public override MixtureComponent[] MixtureComponents { get { return _mixtureComponents; } } /// <summary> /// Gets the dimension of the modeled feature space /// </summary> public virtual int GetDimension() { return _mixtureComponents[0].Mean.Length; } /// <summary> /// Numbers the number of component densities of this <code>GaussianMixture</code>. /// </summary> /// <value></value> public virtual int NumComponents { get { return _mixtureComponents.Length; } } public override float[] GetLogMixtureWeights() { var logWeights = new float[MixtureComponents.Length]; for (var i = 0; i < logWeights.Length; i++) logWeights[i] = MixtureWeights.Get(_Id, 0, i); return logWeights; } /// <summary> /// Gets the (linearly scaled) mixture weights of the component densities /// </summary> /// <returns></returns> public float[] GetComponentWeights() { var mixWeights = new float[MixtureComponents.Length]; for (var i = 0; i < mixWeights.Length; i++) mixWeights[i] = (float)LogMath.LogToLinear(MixtureWeights.Get(_Id, 0, i)); return mixWeights; } /// <summary> /// the (log-scaled) mixture weight of the component density<code>index</code>. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> public float GetLogComponentWeight(int index) { return MixtureWeights.Get(_Id, 0, index); } } }
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.ComponentModel; using Xenko.Core.Assets; using Xenko.Core; using Xenko.Core.Annotations; using Xenko.Core.Serialization; using Xenko.Core.Serialization.Contents; namespace Xenko.Rendering.Materials { /// <summary> /// A descriptor of a <see cref="Material"/>. /// </summary> [ReferenceSerializer, DataSerializerGlobal(typeof(ReferenceSerializer<MaterialDescriptor>), Profile = "Content")] [ContentSerializer(typeof(DataContentSerializer<MaterialDescriptor>))] [DataContract("MaterialDescriptor")] public class MaterialDescriptor : IMaterialDescriptor { /// <summary> /// Initializes a new instance of the <see cref="MaterialDescriptor"/> class. /// </summary> public MaterialDescriptor() { Attributes = new MaterialAttributes(); Layers = new MaterialBlendLayers(); // An instance id, only used to match descriptor MaterialId = AssetId.New(); } [DataMemberIgnore] public AssetId MaterialId { get; set; } /// <summary> /// Gets or sets the material attributes. /// </summary> /// <value>The material attributes.</value> [DataMember(10)] [NotNull] [Display("Attributes", Expand = ExpandRule.Always)] public MaterialAttributes Attributes { get; set; } /// <summary> /// Gets or sets the material compositor. /// </summary> /// <value>The material compositor.</value> [DefaultValue(null)] [DataMember(20)] [NotNull] [MemberCollection(NotNullItems = true)] public MaterialBlendLayers Layers { get; set; } public void Visit(MaterialGeneratorContext context) { if (Attributes != null) { Attributes.Visit(context); } if (Layers != null) { Layers.Visit(context); } } } }
using System.Collections.Generic; using System.Text.Json.Serialization; namespace OriinDic.Models { public record RootObject<T> { [JsonPropertyName("pages")] // ReSharper disable once UnusedAutoPropertyAccessor.Global public long Pages { get; set; } [JsonPropertyName("count")] // ReSharper disable once UnusedAutoPropertyAccessor.Global public int Count { get; set; } [JsonPropertyName("current_page")] // ReSharper disable once UnusedMember.Global public long CurrentPage { get; set; } [JsonPropertyName("results")] // ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global public List<T> Results { get; set; } public RootObject() { Results = new List<T>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Effekseer.Utl; namespace Effekseer.Data.Value { public class Float { float _value = 0; float _max = float.MaxValue; float _min = float.MinValue; public float Value { get { return GetValue(); } set { SetValue(value); } } /// <summary> /// 変更単位量 /// </summary> public float Step { get; set; } internal float DefaultValue { get; private set; } public event ChangedValueEventHandler OnChanged; internal Float(float value = 0, float max = float.MaxValue, float min = float.MinValue, float step = 1.0f) { _max = max; _min = min; _value = value.Clipping(_max, _min); Step = step; DefaultValue = _value; } protected void CallChanged(object value, ChangedValueType type) { if (OnChanged != null) { OnChanged(this, new ChangedValueEventArgs(value, type)); } } public float GetValue() { return _value; } public void SetValue(float value, bool isCombined = false) { value = value.Clipping(_max, _min); if (value == _value) return; float old_value = _value; float new_value = value; var cmd = new Command.DelegateCommand( () => { _value = new_value; CallChanged(new_value, ChangedValueType.Execute); }, () => { _value = old_value; CallChanged(old_value, ChangedValueType.Unexecute); }, this, isCombined); Command.CommandManager.Execute(cmd); } public void SetValueDirectly(float value) { var converted = value.Clipping(_max, _min); if (_value == converted) return; _value = converted; CallChanged(_value, ChangedValueType.Execute); } public static implicit operator float(Float value) { return value._value; } public static explicit operator byte[](Float value) { byte[] values = new byte[sizeof(float) * 1]; BitConverter.GetBytes(value.Value).CopyTo(values, sizeof(float) * 0); return values; } public byte[] GetBytes(float mul = 1.0f) { byte[] values = new byte[sizeof(float) * 1]; BitConverter.GetBytes(Value * mul).CopyTo(values, sizeof(float) * 0); return values; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Countdown.net.Model; using Xunit; namespace Countdown.net.Test { public class TestCollectionsHelpers { private readonly CollectionsHelper Helper = new CollectionsHelper(); [Theory] [InlineData(new int[] { 1, 2, 3 }, 6)] [InlineData(new int[] { 1, 1, 1 }, 6)] [InlineData(new int[] { 1, 2, 3, 4, 5, 6 }, 720)] public void TestPermute(IEnumerable<int> input, int expectedCount) { // IEnumerable<int> input = new List<int>() {1,2,3}; List<int> numbersList = input.ToList(); IEnumerable<IList<int>> output = Helper.Permute(numbersList, numbersList.Count); Assert.True(output.Count() == expectedCount); } [Theory] [InlineData(1, 1)] [InlineData(2, 2)] [InlineData(3, 6)] [InlineData(6, 720)] [InlineData(10, 3628800)] public void TestFactorial(int input, int output) { int actualOutput = Helper.Factorial(input); Assert.Equal(output, actualOutput); } [Theory] [InlineData(-1)] [InlineData(0)] public void TestDuffInputToFactorial(int input) { Assert.Throws<InvalidOperationException>(() => Helper.Factorial(input)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace TD.BlazorTestApp { public class Program { public static object Task { get; private set; } public static void Main(string[] args) { // Task [] = {'Writing a book', 'Listening to a song', 'Sweeping the floor', 'Listening to Music' }; try { for (int i = 0; i <= 10; i ++) { Console.WriteLine("This is the task that was completed"); } } catch (NotImplementedException notImpt) { Console.WriteLine(notImpt.Message); } // CreateHostBuilder(args).Build().Run(); } private static void presentFeature() { try { presentFeature(); } catch { Console.WriteLine("This is the exception error"); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
using System.Runtime.Serialization; using Logy.Maps.Coloring; namespace Logy.Maps.ReliefMaps.Basemap { public abstract class DataEarth { // to store max and min at least [IgnoreDataMember] public ColorsManager Colors { get; set; } public string Dimension { get; set; } = "m"; } }
using Autodesk.DesignScript.Runtime; using Dynamo.Engine; namespace Dynamo.Graph.Nodes.ZeroTouch { /// <summary> /// DesignScript function node. All functions from DesignScript share the /// same function node but internally have different procedure. /// </summary> [NodeName("Function Node"), NodeDescription("DSFunctionNodeDescription",typeof(Properties.Resources)), IsInteractive(false), IsVisibleInDynamoLibrary(false), NodeSearchable(false), IsMetaNode] [AlsoKnownAs("Dynamo.Nodes.DSFunction")] public class DSFunction : DSFunctionBase { public override bool IsInputNode { get { return false; } } public DSFunction(FunctionDescriptor descriptor) : base(new ZeroTouchNodeController<FunctionDescriptor>(descriptor)) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.TeamFoundation.VersionControl.Client; namespace VS_DiffAllFiles.Adapters { public interface ITfsFileChange : IFileChange { /// <summary> /// Gets the version. /// </summary> int Version { get; } /// <summary> /// Gets the name of the shelveset. /// </summary> string ShelvesetName { get; } /// <summary> /// Gets the TFS version control server. /// </summary> VersionControlServer VersionControlServer { get; } /// <summary> /// Gets the deletion identifier. /// </summary> int DeletionId { get; } /// <summary> /// Gets if this file is being branched or not. /// </summary> bool IsBranch { get; } /// <summary> /// Gets if this file is being undeleted or not. /// </summary> bool IsUndelete { get; } /// <summary> /// Downloads the base file. /// </summary> /// <param name="filePathToDownloadFileTo">The file path to download file to.</param> void DownloadBaseFile(string filePathToDownloadFileTo); /// <summary> /// Downloads the shelved file. /// </summary> /// <param name="filePathToDownloadFileTo">The file path to download file to.</param> void DownloadShelvedFile(string filePathToDownloadFileTo); } }
using Classic.Shared; namespace Classic.World.Packets.Client { public class CMSG_PLAYER_LOGIN { public CMSG_PLAYER_LOGIN(byte[] data) { using (var reader = new PacketReader(data)) { CharacterID = reader.ReadUInt32(); } } public uint CharacterID { get; } } }
using Comet.Styles.Material; using System; using System.Collections.Generic; using System.Text; namespace Comet.Samples { public class MaterialStylePicker : View { public MaterialStylePicker() { this.Title("Material Style Picker"); } List<ColorPalette> colorPalettes = new List<ColorPalette> { ColorPalette.Amber, ColorPalette.Blue, ColorPalette.Cyan, ColorPalette.DeepOrange, ColorPalette.DeepPurple, ColorPalette.Green, ColorPalette.Indigo, ColorPalette.LightBlue, ColorPalette.LightGreen, ColorPalette.Lime, ColorPalette.Orange, ColorPalette.Pink, ColorPalette.Purple, ColorPalette.Red, ColorPalette.Teal, ColorPalette.Yellow, }; [Body] View body() => new ListView<ColorPalette>(colorPalettes) { ViewFor = (colorPalette) => new Text(colorPalette.Name).Background(colorPalette.P900).Color(colorPalette.PD900), }.OnSelectedNavigate((colorPallete) => new MaterialSample().ApplyStyle(new MaterialStyle(colorPallete)) ); } }
 @{ ViewBag.Title = "ViewDataList"; } <div class="jumbotron alert-success"> <h2>View Data List</h2> </div> @if (ViewData.Count() > 0) { <h2>ViewData 共有 @ViewData.Count() 筆資料</h2> <ul> @*ViewData*@ <li>Name : @(ViewData["Name"] ?? "無資料")</li> <li>Age : @(ViewData["Age"] ?? "無資料")</li> <li>Single : @(ViewData["Single"] ?? "無資料")</li> <li>Money : @(ViewData["Money"] ?? "無資料")</li> @*ViewBag*@ <li>Nickname : @(ViewData["Nickname"] ?? "無資料")</li> <li>Height : @(ViewData["Height"] ?? "無資料")</li> <li>Weight : @(ViewData["Weight"] ?? "無資料")</li> <li>Married : @(ViewData["Married"] ?? "無資料")</li> </ul> <hr /> <ul> @if (ViewData.ContainsKey("Name")) { <li>Name : @ViewData["Name"]</li> } else { <li>Name : 無資料</li> } @if (ViewData.ContainsKey("Age")) { <li>Age : @ViewData["Age"]</li> } else { <li>Age : 無資料</li> } @if (ViewData.ContainsKey("Single")) { <li>Single : @ViewData["Single"]</li> } else { <li>Single : 無資料</li> } @if (ViewData.ContainsKey("Money")) { <li>Money : @ViewData["Money"]</li> } else { <li>Money : 無資料</li> } <li>Nickname : @(ViewData.ContainsKey("Nickname") ? ViewData["Nickname"] : "無資料")</li> <li>Height: @(ViewData.ContainsKey("Height") ? ViewData["Height"] : "無資料")</li> <li>Weight : @(ViewData.ContainsKey("Weight") ? ViewData["Weight"] : "無資料")</li> <li>Married :@(ViewData.ContainsKey("Married") ? ViewData["Married"] : "無資料")</li> </ul> } <hr /> @foreach (var item in ViewData) { <li>@item.Key, @item.Value</li> } <hr /> <ul> @{ var enumerator = ViewData.GetEnumerator(); } @while (enumerator.MoveNext()) { var item = enumerator.Current; <li>@item.Key, @item.Value</li> } </ul>
using Rex.Models; using Microsoft.AspNetCore.Mvc.Testing; using Xunit.Abstractions; namespace Rex.Tests.Controllers { public class HealthControllerV2Tests : HealthControllerTests<Health.Version1> { public HealthControllerV2Tests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } protected override string Version => "v1"; } }
namespace GitDiffMargin.Commands { using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; internal class ShowPopupCommandArgs : EditorCommandArgs { public ShowPopupCommandArgs(ITextView textView, ITextBuffer subjectBuffer) : base(textView, subjectBuffer) { } } }
using FluentMigrator; using Nop.Core.Domain.Catalog; using Nop.Data.Mapping; namespace Nop.Data.Migrations.Indexes { [NopMigration("2020/03/13 11:35:09:1647938")] public class AddProductManufacturerMappingIsFeaturedProductIX : AutoReversingMigration { #region Methods public override void Up() { Create.Index("IX_Product_Manufacturer_Mapping_IsFeaturedProduct") .OnTable(NameCompatibilityManager.GetTableName(typeof(ProductManufacturer))) .OnColumn(nameof(ProductManufacturer.IsFeaturedProduct)).Ascending() .WithOptions().NonClustered(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using SqlDataCompare.Core.Enums; using SqlDataCompare.Core.Models; using SqlDataCompare.Core.Services; namespace SqlDataCompare.UnitTests { [TestFixtureSource(typeof(Assetts.TestSqlProvider))] public class ComparableSqlParserTests { private readonly ParseResultValue parseResult; private readonly string comment; private readonly string sql; private readonly List<string> columns; private readonly ParsedSql actualResult; public ComparableSqlParserTests(ParseResultValue parseResult, string comment, string sql, List<string> columns) { this.parseResult = parseResult; this.comment = comment; this.sql = sql; this.columns = columns; this.actualResult = ComparableSqlParser.ParseAndValidate(sql); } [Test] public void ParseAndValidate_ParseResult_MatchesExpected() { Assert.AreEqual(parseResult, actualResult.ParseResult, $"Message: {actualResult.ValidationMessage}"); } [Test] public void ParseAndValidate_Columns_MatchesExpected() { // Not all cases need to have defined columns, but if we have them, they must match. if (columns.Any()) { Assert.AreEqual(columns.OrderBy(x => x), actualResult.ColumnNames.OrderBy(x => x)); } } [Test] public void TestDataAreInternallyConsistent() { if (columns.Any()) { Assert.AreEqual(parseResult, ParseResultValue.Valid, "Only valid sql can have columns defined"); } } } }
using System; using System.Collections.Generic; using MbUnit.Framework; using Moq; using Ninject; using Ninject.Activation; using Ninject.Parameters; using Ninject.Planning.Bindings; using Subtext.Framework.Infrastructure; namespace UnitTests.Subtext.Framework.Infrastructure { [TestFixture] public class NinjectServiceLocatorTests { [Test] public void GetService_WithKernel_DelegatesToKernel() { // arrange Func<IEnumerable<object>> returnFunc = () => new[] {new TestService()}; var request = new Mock<IRequest>(); var kernel = new Mock<IKernel>(); kernel.Setup( k => k.CreateRequest(typeof(ITestService), It.IsAny<Func<IBindingMetadata, bool>>(), It.IsAny<IEnumerable<IParameter>>(), It.IsAny<bool>())).Returns(request.Object); kernel.Setup(k => k.Resolve(It.IsAny<IRequest>())).Returns(returnFunc); var serviceLocator = new NinjectServiceLocator(kernel.Object); // act var service = serviceLocator.GetService<ITestService>(); // assert Assert.IsNotNull(service); Assert.AreEqual(typeof(TestService), service.GetType()); } [Test] public void GetService_WithServiceTypeAndKernel_DelegatesToKernel() { // arrange Func<IEnumerable<object>> returnFunc = () => new[] { new TestService() }; var request = new Mock<IRequest>(); var kernel = new Mock<IKernel>(); kernel.Setup( k => k.CreateRequest(typeof(ITestService), It.IsAny<Func<IBindingMetadata, bool>>(), It.IsAny<IEnumerable<IParameter>>(), It.IsAny<bool>())).Returns(request.Object); kernel.Setup(k => k.Resolve(It.IsAny<IRequest>())).Returns(returnFunc); var serviceLocator = new NinjectServiceLocator(kernel.Object); // act var service = serviceLocator.GetService(typeof(ITestService)); // assert Assert.IsNotNull(service); Assert.AreEqual(typeof(TestService), service.GetType()); } } public interface ITestService { } public interface IDerivedService : ITestService {} public class TestService : IDerivedService {} }
// Copyright 2013 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 cgo handles cgo preprocessing of files containing `import "C"`. // // DESIGN // // The approach taken is to run the cgo processor on the package's // CgoFiles and parse the output, faking the filenames of the // resulting ASTs so that the synthetic file containing the C types is // called "C" (e.g. "~/go/src/net/C") and the preprocessed files // have their original names (e.g. "~/go/src/net/cgo_unix.go"), // not the names of the actual temporary files. // // The advantage of this approach is its fidelity to 'go build'. The // downside is that the token.Position.Offset for each AST node is // incorrect, being an offset within the temporary file. Line numbers // should still be correct because of the //line comments. // // The logic of this file is mostly plundered from the 'go build' // tool, which also invokes the cgo preprocessor. // // // REJECTED ALTERNATIVE // // An alternative approach that we explored is to extend go/types' // Importer mechanism to provide the identity of the importing package // so that each time `import "C"` appears it resolves to a different // synthetic package containing just the objects needed in that case. // The loader would invoke cgo but parse only the cgo_types.go file // defining the package-level objects, discarding the other files // resulting from preprocessing. // // The benefit of this approach would have been that source-level // syntax information would correspond exactly to the original cgo // file, with no preprocessing involved, making source tools like // godoc, guru, and eg happy. However, the approach was rejected // due to the additional complexity it would impose on go/types. (It // made for a beautiful demo, though.) // // cgo files, despite their *.go extension, are not legal Go source // files per the specification since they may refer to unexported // members of package "C" such as C.int. Also, a function such as // C.getpwent has in effect two types, one matching its C type and one // which additionally returns (errno C.int). The cgo preprocessor // uses name mangling to distinguish these two functions in the // processed code, but go/types would need to duplicate this logic in // its handling of function calls, analogous to the treatment of map // lookups in which y=m[k] and y,ok=m[k] are both legal. // package cgo -- go2cs converted at 2020 October 09 06:03:52 UTC // import "golang.org/x/tools/go/internal/cgo" ==> using cgo = go.golang.org.x.tools.go.@internal.cgo_package // Original source: C:\Users\ritchie\go\src\golang.org\x\tools\go\internal\cgo\cgo.go using fmt = go.fmt_package; using ast = go.go.ast_package; using build = go.go.build_package; using parser = go.go.parser_package; using token = go.go.token_package; using ioutil = go.io.ioutil_package; using log = go.log_package; using os = go.os_package; using exec = go.os.exec_package; using filepath = go.path.filepath_package; using regexp = go.regexp_package; using strings = go.strings_package; using static go.builtin; using System; namespace go { namespace golang.org { namespace x { namespace tools { namespace go { namespace @internal { public static partial class cgo_package { // ProcessFiles invokes the cgo preprocessor on bp.CgoFiles, parses // the output and returns the resulting ASTs. // public static (slice<ptr<ast.File>>, error) ProcessFiles(ptr<build.Package> _addr_bp, ptr<token.FileSet> _addr_fset, Func<@string, @string> DisplayPath, parser.Mode mode) => func((defer, _, __) => { slice<ptr<ast.File>> _p0 = default; error _p0 = default!; ref build.Package bp = ref _addr_bp.val; ref token.FileSet fset = ref _addr_fset.val; var (tmpdir, err) = ioutil.TempDir("", strings.Replace(bp.ImportPath, "/", "_", -1L) + "_C"); if (err != null) { return (null, error.As(err)!); } defer(os.RemoveAll(tmpdir)); var pkgdir = bp.Dir; if (DisplayPath != null) { pkgdir = DisplayPath(pkgdir); } var (cgoFiles, cgoDisplayFiles, err) = Run(_addr_bp, pkgdir, tmpdir, false); if (err != null) { return (null, error.As(err)!); } slice<ptr<ast.File>> files = default; foreach (var (i) in cgoFiles) { var (rd, err) = os.Open(cgoFiles[i]); if (err != null) { return (null, error.As(err)!); } var display = filepath.Join(bp.Dir, cgoDisplayFiles[i]); var (f, err) = parser.ParseFile(fset, display, rd, mode); rd.Close(); if (err != null) { return (null, error.As(err)!); } files = append(files, f); } return (files, error.As(null!)!); }); private static var cgoRe = regexp.MustCompile("[/\\\\:]"); // Run invokes the cgo preprocessor on bp.CgoFiles and returns two // lists of files: the resulting processed files (in temporary // directory tmpdir) and the corresponding names of the unprocessed files. // // Run is adapted from (*builder).cgo in // $GOROOT/src/cmd/go/build.go, but these features are unsupported: // Objective C, CGOPKGPATH, CGO_FLAGS. // // If useabs is set to true, absolute paths of the bp.CgoFiles will be passed in // to the cgo preprocessor. This in turn will set the // line comments // referring to those files to use absolute paths. This is needed for // go/packages using the legacy go list support so it is able to find // the original files. public static (slice<@string>, slice<@string>, error) Run(ptr<build.Package> _addr_bp, @string pkgdir, @string tmpdir, bool useabs) { slice<@string> files = default; slice<@string> displayFiles = default; error err = default!; ref build.Package bp = ref _addr_bp.val; var (cgoCPPFLAGS, _, _, _) = cflags(_addr_bp, true); var (_, cgoexeCFLAGS, _, _) = cflags(_addr_bp, false); if (len(bp.CgoPkgConfig) > 0L) { var (pcCFLAGS, err) = pkgConfigFlags(bp); if (err != null) { return (null, null, error.As(err)!); } cgoCPPFLAGS = append(cgoCPPFLAGS, pcCFLAGS); } // Allows including _cgo_export.h from .[ch] files in the package. cgoCPPFLAGS = append(cgoCPPFLAGS, "-I", tmpdir); // _cgo_gotypes.go (displayed "C") contains the type definitions. files = append(files, filepath.Join(tmpdir, "_cgo_gotypes.go")); displayFiles = append(displayFiles, "C"); foreach (var (_, fn) in bp.CgoFiles) { // "foo.cgo1.go" (displayed "foo.go") is the processed Go source. var f = cgoRe.ReplaceAllString(fn[..len(fn) - len("go")], "_"); files = append(files, filepath.Join(tmpdir, f + "cgo1.go")); displayFiles = append(displayFiles, fn); } slice<@string> cgoflags = default; if (bp.Goroot && bp.ImportPath == "runtime/cgo") { cgoflags = append(cgoflags, "-import_runtime_cgo=false"); } if (bp.Goroot && bp.ImportPath == "runtime/race" || bp.ImportPath == "runtime/cgo") { cgoflags = append(cgoflags, "-import_syscall=false"); } slice<@string> cgoFiles = bp.CgoFiles; if (useabs) { cgoFiles = make_slice<@string>(len(bp.CgoFiles)); foreach (var (i) in cgoFiles) { cgoFiles[i] = filepath.Join(pkgdir, bp.CgoFiles[i]); } } var args = stringList("go", "tool", "cgo", "-objdir", tmpdir, cgoflags, "--", cgoCPPFLAGS, cgoexeCFLAGS, cgoFiles); if (false) { log.Printf("Running cgo for package %q: %s (dir=%s)", bp.ImportPath, args, pkgdir); } var cmd = exec.Command(args[0L], args[1L..]); cmd.Dir = pkgdir; cmd.Stdout = os.Stderr; cmd.Stderr = os.Stderr; { var err = cmd.Run(); if (err != null) { return (null, null, error.As(fmt.Errorf("cgo failed: %s: %s", args, err))!); } } return (files, displayFiles, error.As(null!)!); } // -- unmodified from 'go build' --------------------------------------- // Return the flags to use when invoking the C or C++ compilers, or cgo. private static (slice<@string>, slice<@string>, slice<@string>, slice<@string>) cflags(ptr<build.Package> _addr_p, bool def) { slice<@string> cppflags = default; slice<@string> cflags = default; slice<@string> cxxflags = default; slice<@string> ldflags = default; ref build.Package p = ref _addr_p.val; @string defaults = default; if (def) { defaults = "-g -O2"; } cppflags = stringList(envList("CGO_CPPFLAGS", ""), p.CgoCPPFLAGS); cflags = stringList(envList("CGO_CFLAGS", defaults), p.CgoCFLAGS); cxxflags = stringList(envList("CGO_CXXFLAGS", defaults), p.CgoCXXFLAGS); ldflags = stringList(envList("CGO_LDFLAGS", defaults), p.CgoLDFLAGS); return ; } // envList returns the value of the given environment variable broken // into fields, using the default value when the variable is empty. private static slice<@string> envList(@string key, @string def) { var v = os.Getenv(key); if (v == "") { v = def; } return strings.Fields(v); } // stringList's arguments should be a sequence of string or []string values. // stringList flattens them into a single []string. private static slice<@string> stringList(params object[] args) => func((_, panic, __) => { args = args.Clone(); slice<@string> x = default; { var arg__prev1 = arg; foreach (var (_, __arg) in args) { arg = __arg; switch (arg.type()) { case slice<@string> arg: x = append(x, arg); break; case @string arg: x = append(x, arg); break; default: { var arg = arg.type(); panic("stringList: invalid argument"); break; } } } arg = arg__prev1; } return x; }); } }}}}}}
using UnityEngine; namespace Project.Scripts.Runtime.effect.Temp { public class BabbleDirt : MonoBehaviour { [SerializeField] private Bubble.Bubble bubble; [SerializeField] private Dirt.Dirt dirt; [SerializeField] internal bool emit = false; private Rigidbody rigid; private Vector3 pos; private Quaternion rot; // Start is called before the first frame update void Start() { rigid = dirt.gameObject.GetComponent<Rigidbody>(); pos = rigid.gameObject.transform.localPosition; rot = rigid.gameObject.transform.localRotation; } // Update is called once per frame void Update() { rigid.useGravity = bubble.emit; bubble.emit = emit; if (!bubble.emit) { rigid.gameObject.transform.localPosition = pos; rigid.gameObject.transform.localRotation = rot; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StealthItem : PlayerItem { protected Stealth stealth; protected bool timerStarted; void Start() { stealth = GameObject.FindGameObjectWithTag("Player").GetComponentInChildren<Stealth>(); StartTimer(); } void Update() { if (timerStarted) { if (stealth.currentTime > 0) stealth.currentTime -= Time.deltaTime * stealth.deltaT; else OnTimerEnd(); } } protected void StartTimer() { timerStarted = true; stealth.currentTime = stealth.stealthTime; } protected void OnTimerEnd() { stealth.GetPlayerController().GetPlayer().visible = true; stealth.GetPlayerController().GetPlayer().RemoveCollectable(stealth.itemName); Destroy(this.gameObject); } }
[assembly:Xamarin.Forms.Dependency(typeof(GeofencesSample.Droid.Services.Geofences.GeofencesService))] namespace GeofencesSample.Droid.Services.Geofences { using Android.App; using Android.Content; using Android.Gms.Location; using Android.Locations; using GeofencesSample.Services.Geofences; using System.Collections.Generic; using System.Linq; using Xamarin.Forms.Maps; public class GeofencesService : IGeofencesService { private GeofencingClient geofencingClient; private PendingIntent geofencePendingIntent; private int numberOfGeofences = 10; public GeofencesService() { geofencingClient = LocationServices.GetGeofencingClient(MainActivity.MainContext); } public void SetGeofences(List<Position> targets, Position currentPosition) { List<Position> nearTargets = GetCloseTargets(targets, currentPosition); List<IGeofence> geofences = new List<IGeofence>(); foreach (Position item in nearTargets) { IGeofence geofence = new GeofenceBuilder() .SetRequestId($"{item.Latitude}_{item.Longitude}") .SetCircularRegion(item.Latitude, item.Longitude, 1000) .SetLoiteringDelay(60 * 1000) .SetTransitionTypes(Geofence.GeofenceTransitionEnter | Geofence.GeofenceTransitionExit | Geofence.GeofenceTransitionDwell) .SetExpirationDuration((long)365 * 24 * 60 * 60 * 1000) .Build(); geofences.Add(geofence); } GeofencingRequest geofencingRequest = new GeofencingRequest.Builder() .AddGeofences(geofences) .Build(); geofencingClient.AddGeofences(geofencingRequest, GetGeofencePendingIntent()); } private PendingIntent GetGeofencePendingIntent() { if (geofencePendingIntent != null) return geofencePendingIntent; Intent intent = new Intent(MainActivity.MainContext, Java.Lang.Class.FromType(typeof(GeofenceBroadcastReceiver))); // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling addGeofences() and removeGeofences(). geofencePendingIntent = PendingIntent.GetBroadcast(MainActivity.MainContext, 0, intent, PendingIntentFlags.UpdateCurrent); return geofencePendingIntent; } private List<Position> GetCloseTargets(List<Position> targets, Position position) { List<KeyValuePair<double, Position>> distanceAndTargetList = new List<KeyValuePair<double, Position>>(); Location currentLocation = new Location(string.Empty) { Longitude = position.Longitude, Latitude = position.Latitude }; foreach (Position item in targets) { Location location = new Location(string.Empty) { Latitude = item.Latitude, Longitude = item.Longitude }; distanceAndTargetList.Add(new KeyValuePair<double, Position>(currentLocation.DistanceTo(location), item)); } IEnumerable<Position> items = distanceAndTargetList.OrderBy(x => x.Key).Select(x => x.Value); return items.Count() > numberOfGeofences ? items.Take(numberOfGeofences).ToList() : items.ToList(); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class BubbleManager : MonoBehaviour { public bool debug = false; public bool spawnBubbles = true; public GameObject[] bubbleTypes; private void Awake() { bubbleTypes = new GameObject[4]; bubbleTypes[0] = Resources.Load("Prefabs/Bubble") as GameObject; bubbleTypes[1] = Resources.Load("Prefabs/Slide") as GameObject; bubbleTypes[2] = Resources.Load("Prefabs/Swish") as GameObject; bubbleTypes[3] = Resources.Load("Prefabs/Pop") as GameObject; } public void ClearAllBubbles() { GameObject[] currentBubbles = GameObject.FindGameObjectsWithTag("Bubble"); foreach (GameObject bubble in currentBubbles) { Destroy(bubble); } } private void HandleInput() { if (Input.GetKeyDown(KeyCode.Alpha1)) { SpawnBubble("Bubble"); } else if (Input.GetKeyDown(KeyCode.Alpha2)) { SpawnBubble("Slide"); } else if (Input.GetKeyDown(KeyCode.Alpha3)) { SpawnBubble("Swish"); } else if (Input.GetKeyDown(KeyCode.Alpha4)) { SpawnBubble("Pop"); } } private void SpawnBubble(int i) { if (debug) Debug.Log("Bubble spawned"); GameObject bubble = GameObject.Instantiate(bubbleTypes[i]) as GameObject; bubble.tag = "Bubble"; } private void SpawnBubble(string bubbleType) { if (debug) Debug.Log("Bubble spawned"); GameObject bubble = GameObject.Instantiate(Resources.Load("Prefabs/" + bubbleType)) as GameObject; bubble.tag = "Bubble"; } private void SpawnRandomBubble() { int randIndex = Random.Range(0, bubbleTypes.Length); SpawnBubble(randIndex); } // Update is called once per frame private void Update() { if (!GameManager.instance.isPlaying) { return; } if (Input.anyKeyDown) { HandleInput(); } GameObject[] currentBubbles = GameObject.FindGameObjectsWithTag("Bubble"); if (currentBubbles == null || currentBubbles.Length == 0) { SpawnRandomBubble(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu] public class RecordingEvent : ScriptableObject { private List<RecordingEventListener> listeners = new List<RecordingEventListener>(); private bool recording = false; private void OnEnable() { recording = false; } public void Raise() { recording = !recording; foreach (RecordingEventListener listener in listeners) { listener.OnRecordRaised(); } } public void RegisterListener(RecordingEventListener l) { listeners.Add(l); } public void UnregisterListener(RecordingEventListener l) { listeners.Remove(l); } public bool isRecording() => recording; }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector.UnitTests { using System; using System.ComponentModel; using System.IO; using System.Threading; using Microsoft.VisualStudio.TestPlatform.Common.DataCollector.Interfaces; using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; [TestClass] public class DataCollectionAttachmentManagerTests { private const int Timeout = 10 * 60 * 1000; private DataCollectionAttachmentManager attachmentManager; private Mock<IMessageSink> messageSink; private SessionId sessionId; private static readonly string TempDirectoryPath = Path.GetTempPath(); public DataCollectionAttachmentManagerTests() { this.attachmentManager = new DataCollectionAttachmentManager(); this.messageSink = new Mock<IMessageSink>(); var guid = Guid.NewGuid(); this.sessionId = new SessionId(guid); } [TestCleanup] public void Cleanup() { File.Delete(Path.Combine(TempDirectoryPath, "filename.txt")); File.Delete(Path.Combine(TempDirectoryPath, "filename1.txt")); } [TestMethod] public void InitializeShouldThrowExceptionIfSessionIdIsNull() { Assert.ThrowsException<ArgumentNullException>(() => { this.attachmentManager.Initialize((SessionId)null, string.Empty, this.messageSink.Object); }); } [TestMethod] public void InitializeShouldThrowExceptionIfMessageSinkIsNull() { Assert.ThrowsException<ArgumentNullException>(() => { this.attachmentManager.Initialize(this.sessionId, string.Empty, null); }); } [TestMethod] public void InitializeShouldSetDefaultPathIfOutputDirectoryPathIsNull() { this.attachmentManager.Initialize(this.sessionId, string.Empty, this.messageSink.Object); Assert.AreEqual(this.attachmentManager.SessionOutputDirectory, Path.Combine(Path.GetTempPath(), "TestResults", this.sessionId.Id.ToString())); } [TestMethod] public void InitializeShouldSetCorrectGuidAndOutputPath() { this.attachmentManager.Initialize(this.sessionId, TempDirectoryPath, this.messageSink.Object); Assert.AreEqual(Path.Combine(TempDirectoryPath, this.sessionId.Id.ToString()), this.attachmentManager.SessionOutputDirectory); } [TestMethod] public void AddAttachmentShouldNotAddNewFileTransferIfSessionIsNotConfigured() { var filename = "filename.txt"; File.WriteAllText(Path.Combine(TempDirectoryPath, filename), string.Empty); var datacollectioncontext = new DataCollectionContext(this.sessionId); var friendlyName = "TestDataCollector"; var uri = new Uri("datacollector://Company/Product/Version"); var dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, Path.Combine(TempDirectoryPath, filename), false); this.attachmentManager.AddAttachment(dataCollectorDataMessage, null, uri, friendlyName); Assert.AreEqual(0, this.attachmentManager.AttachmentSets.Count); } [TestMethod] public void AddAttachmentShouldAddNewFileTransferAndCopyFileToOutputDirectoryIfDeleteFileIsFalse() { var filename = "filename.txt"; File.WriteAllText(Path.Combine(TempDirectoryPath, filename), string.Empty); this.attachmentManager.Initialize(this.sessionId, TempDirectoryPath, this.messageSink.Object); var datacollectioncontext = new DataCollectionContext(this.sessionId); var friendlyName = "TestDataCollector"; var uri = new Uri("datacollector://Company/Product/Version"); EventWaitHandle waitHandle = new AutoResetEvent(false); var handler = new AsyncCompletedEventHandler((a, e) => { waitHandle.Set(); }); var dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, Path.Combine(TempDirectoryPath, filename), false); this.attachmentManager.AddAttachment(dataCollectorDataMessage, handler, uri, friendlyName); // Wait for file operations to complete waitHandle.WaitOne(Timeout); Assert.IsTrue(File.Exists(Path.Combine(TempDirectoryPath, filename))); Assert.IsTrue(File.Exists(Path.Combine(TempDirectoryPath, this.sessionId.Id.ToString(), filename))); Assert.AreEqual(1, this.attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments.Count); } [TestMethod] public void AddAttachmentsShouldAddFilesCorrespondingToDifferentDataCollectors() { var filename = "filename.txt"; var filename1 = "filename1.txt"; File.WriteAllText(Path.Combine(TempDirectoryPath, filename), string.Empty); File.WriteAllText(Path.Combine(TempDirectoryPath, filename1), string.Empty); this.attachmentManager.Initialize(this.sessionId, TempDirectoryPath, this.messageSink.Object); var datacollectioncontext = new DataCollectionContext(this.sessionId); var friendlyName = "TestDataCollector"; var uri = new Uri("datacollector://Company/Product/Version"); var uri1 = new Uri("datacollector://Company/Product/Version1"); EventWaitHandle waitHandle = new AutoResetEvent(false); var handler = new AsyncCompletedEventHandler((a, e) => { waitHandle.Set(); }); var dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, Path.Combine(TempDirectoryPath, filename), false); this.attachmentManager.AddAttachment(dataCollectorDataMessage, handler, uri, friendlyName); // Wait for file operations to complete waitHandle.WaitOne(Timeout); waitHandle.Reset(); dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, Path.Combine(TempDirectoryPath, filename1), false); this.attachmentManager.AddAttachment(dataCollectorDataMessage, handler, uri1, friendlyName); // Wait for file operations to complete waitHandle.WaitOne(Timeout); Assert.AreEqual(1, this.attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments.Count); Assert.AreEqual(1, this.attachmentManager.AttachmentSets[datacollectioncontext][uri1].Attachments.Count); } [TestMethod] public void AddAttachmentShouldAddNewFileTransferAndMoveFileToOutputDirectoryIfDeleteFileIsTrue() { var filename = "filename1.txt"; File.WriteAllText(Path.Combine(TempDirectoryPath, filename), string.Empty); this.attachmentManager.Initialize(this.sessionId, TempDirectoryPath, this.messageSink.Object); var datacollectioncontext = new DataCollectionContext(this.sessionId); var friendlyName = "TestDataCollector"; var uri = new Uri("datacollector://Company/Product/Version"); var waitHandle = new AutoResetEvent(false); var handler = new AsyncCompletedEventHandler((a, e) => { waitHandle.Set(); }); var dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, Path.Combine(TempDirectoryPath, filename), true); this.attachmentManager.AddAttachment(dataCollectorDataMessage, handler, uri, friendlyName); // Wait for file operations to complete waitHandle.WaitOne(Timeout); Assert.AreEqual(1, this.attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments.Count); Assert.IsTrue(File.Exists(Path.Combine(TempDirectoryPath, this.sessionId.Id.ToString(), filename))); Assert.IsFalse(File.Exists(Path.Combine(TempDirectoryPath, filename))); } [TestMethod] public void AddAttachmentShouldAddMultipleAttachmentsForSameDC() { var filename = "filename.txt"; var filename1 = "filename1.txt"; File.WriteAllText(Path.Combine(TempDirectoryPath, filename), string.Empty); File.WriteAllText(Path.Combine(TempDirectoryPath, filename1), string.Empty); this.attachmentManager.Initialize(this.sessionId, TempDirectoryPath, this.messageSink.Object); var datacollectioncontext = new DataCollectionContext(this.sessionId); var friendlyName = "TestDataCollector"; var uri = new Uri("datacollector://Company/Product/Version"); EventWaitHandle waitHandle = new AutoResetEvent(false); var handler = new AsyncCompletedEventHandler((a, e) => { waitHandle.Set(); }); var dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, Path.Combine(TempDirectoryPath, filename), false); this.attachmentManager.AddAttachment(dataCollectorDataMessage, handler, uri, friendlyName); // Wait for file operations to complete waitHandle.WaitOne(Timeout); waitHandle.Reset(); dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, Path.Combine(TempDirectoryPath, filename1), false); this.attachmentManager.AddAttachment(dataCollectorDataMessage, handler, uri, friendlyName); // Wait for file operations to complete waitHandle.WaitOne(Timeout); Assert.AreEqual(2, this.attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments.Count); } [TestMethod] public void AddAttachmentShouldNotAddNewFileTransferIfNullIsPassed() { Assert.ThrowsException<ArgumentNullException>(() => { this.attachmentManager.AddAttachment(null, null, null, null); }); } [TestMethod] public void GetAttachmentsShouldReturnAllAttachmets() { var filename = "filename1.txt"; File.WriteAllText(Path.Combine(TempDirectoryPath, filename), string.Empty); this.attachmentManager.Initialize(this.sessionId, TempDirectoryPath, this.messageSink.Object); var datacollectioncontext = new DataCollectionContext(this.sessionId); var friendlyName = "TestDataCollector"; var uri = new Uri("datacollector://Company/Product/Version"); var dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, Path.Combine(TempDirectoryPath, filename), true); this.attachmentManager.AddAttachment(dataCollectorDataMessage, null, uri, friendlyName); Assert.AreEqual(1, this.attachmentManager.AttachmentSets.Count); var result = this.attachmentManager.GetAttachments(datacollectioncontext); Assert.AreEqual(0, this.attachmentManager.AttachmentSets.Count); Assert.AreEqual(1, result.Count); Assert.AreEqual(friendlyName, result[0].DisplayName); Assert.AreEqual(uri, result[0].Uri); Assert.AreEqual(1, result[0].Attachments.Count); } [TestMethod] public void GetAttachmentsShouldNotReutrnAnyDataWhenActiveFileTransferAreNotPresent() { this.attachmentManager.Initialize(this.sessionId, TempDirectoryPath, this.messageSink.Object); var datacollectioncontext = new DataCollectionContext(this.sessionId); var result = this.attachmentManager.GetAttachments(datacollectioncontext); Assert.AreEqual(0, result.Count); } [TestMethod] public void GetAttachmentsShouldNotReturnAttachmentsAfterCancelled() { var fileHelper = new Mock<IFileHelper>(); var testableAttachmentManager = new TestableDataCollectionAttachmentManager(fileHelper.Object); var attachmentPath = Path.Combine(TempDirectoryPath, "filename.txt"); File.WriteAllText(attachmentPath, string.Empty); var datacollectioncontext = new DataCollectionContext(this.sessionId); var friendlyName = "TestDataCollector"; var uri = new Uri("datacollector://Company/Product/Version"); var dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, attachmentPath, true); var waitHandle = new AutoResetEvent(false); var handler = new AsyncCompletedEventHandler((a, e) => { Assert.Fail("Handler shouldn't be called since operation is canceled."); }); // We cancel the operation in the actual operation. This ensures the follow up task to is never called, attachments // are not added. Action cancelAddAttachment = () => testableAttachmentManager.Cancel(); fileHelper.Setup(fh => fh.MoveFile(It.IsAny<string>(), It.IsAny<string>())).Callback(cancelAddAttachment); testableAttachmentManager.Initialize(this.sessionId, TempDirectoryPath, this.messageSink.Object); testableAttachmentManager.AddAttachment(dataCollectorDataMessage, handler, uri, friendlyName); // Wait for the attachment transfer tasks to complete var result = testableAttachmentManager.GetAttachments(datacollectioncontext); Assert.AreEqual(0, result[0].Attachments.Count); } private class TestableDataCollectionAttachmentManager : DataCollectionAttachmentManager { public TestableDataCollectionAttachmentManager(IFileHelper fileHelper) : base(fileHelper) { } } } }
using Arragro.Common.BusinessRules; using Arragro.Common.Repository; using Arragro.Common.ServiceBase; using Arragro.TestBase; using Unity; using Xunit; namespace Arragro.Common.Tests.Unity.UseCases { public class UnityUseCase { // A contract for the unity (ioc) container to use private interface IModelFooRepository : IRepository<ModelFoo, int> { } // An implementation of the contract IModelFooRepository using the InMemoryRepository private class InMemoryModelFooRepository : InMemoryRepository<ModelFoo, int>, IModelFooRepository { } /* * An implementation of the contract IModelFooService using the Service base abstract class. * All interaction with the Repository should be provided through this Service. */ private class ModelFooService : Service<IModelFooRepository, ModelFoo, int> { public const string INVALIDLENGTH = "The Name must be less than 4 characters"; public ModelFooService(IModelFooRepository modelFooRepository) : base(modelFooRepository) { } protected override void ValidateModelRules(ModelFoo model) { if (model.Name.Length > 4) RulesException.ErrorFor(x => x.Name, INVALIDLENGTH); } public override ModelFoo InsertOrUpdate(ModelFoo model) { return Repository.InsertOrUpdate(model, model.Id == default(int)); } } private IUnityContainer GetInMemoryContainerExample() { // Instantiate a new unity container var unityContainer = new UnityContainer(); // Register the Interfaces and their Implementations: /* * The InMemoryModelFooRepository which has minimal implementation code * can be switch for a EFModelFooRepository in production, by simply * switching the class below for the same interface */ unityContainer.RegisterType<IModelFooRepository, InMemoryModelFooRepository>(); /* * ModelFooService is registered as the unity container will resolve it's * constructor upon instantiation which has a dependency on IModelFooRepository. * Which is registered above. */ unityContainer.RegisterType<ModelFooService, ModelFooService>(); return unityContainer; } [Fact] public void UnityUseCaseExample() { var unityContainer = GetInMemoryContainerExample(); // Get a ModelFooService using the container, which will then resolve dependencies var modelFooService = unityContainer.Resolve<ModelFooService>(); var modelFoo = modelFooService.InsertOrUpdate(new ModelFoo { Name = "Test" }); Assert.NotEqual(default(int), modelFoo.Id); var findModelFoo = modelFooService.Find(modelFoo.Id); Assert.NotNull(findModelFoo); Assert.Throws<RulesException<ModelFoo>>(() => { try { modelFooService.ValidateAndInsertOrUpdate(new ModelFoo { Name = "Test too big" }); } catch (RulesException ex) { Assert.Equal(ModelFooService.INVALIDLENGTH, ex.Errors[1].Message); throw; } }); } } }
using System.Runtime.Serialization; namespace LogicMonitor.Api.Settings { /// <summary> /// An PagerDuty integration /// </summary> [DataContract] public class PagerDutyIntegration : HttpIntegration { /// <summary> /// Service Key /// </summary> [DataMember(Name = "serviceKey")] public string ServiceKey { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ElasticSearch7Template.Core; using ElasticSearch7Template.Filters; using ElasticSearch7Template.IBLL; using ElasticSearch7Template.Utility; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace ElasticSearch7Template.Controllers { /// <summary> /// 索引文件通用接口 /// </summary> [ApiExplorerSettings(GroupName = "Index")] [Route("BaseIndex")] [ApiController] [ModelValidation] public class BaseIndexController : ControllerBase { private readonly IIndexFileBaseService indexFileBaseService; public BaseIndexController(IIndexFileBaseService indexFileBaseService) { this.indexFileBaseService = indexFileBaseService; } /// <summary> /// 关闭索引文件((默认创建ElasticsearchIndex特性上对应的索引) /// </summary> /// <param name="indexName">索引名</param> /// <returns></returns> [Route("CloseIndexFile")] [HttpPost] [ProducesResponseType(typeof(HttpResponseResultModel<bool>), 200)] public async Task<IActionResult> CloseIndexFileAsync(string indexName) { var result = await indexFileBaseService.CloseIndexFileAsync(indexName).ConfigureAwait(false); return Ok(result); } /// <summary> /// 打开索引文件((默认创建ElasticsearchIndex特性上对应的索引) /// </summary> /// <param name="indexName">索引名</param> /// <returns></returns> [Route("OpenIndexFile")] [HttpPost] [ProducesResponseType(typeof(HttpResponseResultModel<bool>), 200)] public async Task<IActionResult> OpenIndexFileAsync(string indexName) { if (string.IsNullOrEmpty(indexName)) { return BadRequest(MessageFactory.CreateParamsIsNullMessage()); } var result = await indexFileBaseService.OpenIndexFileAsync(indexName).ConfigureAwait(false); return Ok(result); } /// <summary> /// 删除索引文件((默认创建ElasticsearchIndex特性上对应的索引) /// </summary> /// <param name="indexName">索引名</param> /// <returns></returns> [Route("DeleteIndexFile")] [HttpDelete] [ProducesResponseType(typeof(HttpResponseResultModel<bool>), 200)] public async Task<IActionResult> DeleteIndexFileAsync(string indexName) { if (string.IsNullOrEmpty(indexName)) { return BadRequest(MessageFactory.CreateParamsIsNullMessage()); } var result = await indexFileBaseService.DeleteIndexFileAsync(indexName).ConfigureAwait(false); return Ok(result); } /// <summary> /// 获取所有的索引 /// </summary> /// <returns></returns> [Route("CatAllIndex")] [HttpGet] [ProducesResponseType(typeof(bool), 200)] public async Task<IActionResult> CatAllIndexAsync() { var result = await indexFileBaseService.CatAllIndexAsync().ConfigureAwait(false); return Ok(result); } /// <summary> /// 根据别名获得索引名称 /// </summary> /// <param name="aliasName"></param> /// <returns></returns> [Route("CatAliases")] [HttpGet] [ProducesResponseType(typeof(bool), 200)] public async Task<IActionResult> CatAliasesAsync(string aliasName) { var result = await indexFileBaseService.CatAliasesAsync(aliasName).ConfigureAwait(false); return Ok(result); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using cs_sdk.Builder; using cs_sdk.Exceptions; using cs_sdk.Models; using Newtonsoft.Json; using RestSharp; namespace cs_sdk { public class KoreanbotsRequester { public string BaseUrl { get; set; } = Constants.APIV2; /// <summary> /// _b가 설정되지 않으면 기본 URL을 사용합니다. /// </summary> /// <param name="baseurl"></param> public KoreanbotsRequester(string _b= null) { if (_b != null) BaseUrl = _b; } public async Task<KoreanbotsBotModel> RequestBotByIdAsync(ulong id) { RestClient client = new RestClient(BaseUrl); RestRequest request = new RestRequest(string.Format(Constants.V2BOTBYID, id), Method.GET); IRestResponse response = await client.ExecuteAsync(request); Utils.CheckHttpException(response); return KoreanbotsBotBuilder.BuildModel(response.Content); } public async Task<IReadOnlyCollection<KoreanbotsBotModel>> SearchBotByIdAsync(string query, int page = 1) { if (string.IsNullOrEmpty(query) || string.IsNullOrWhiteSpace(query)) { throw new KoreanbotsSearchException("Query cannot be null or whitespace"); } RestClient client = new RestClient(BaseUrl); RestRequest request = new RestRequest(Constants.V2BOTSEARCH, Method.GET); request.AddQueryParameter("query", query); request.AddQueryParameter("page", page.ToString()); IRestResponse response = await client.ExecuteAsync(request); Utils.CheckHttpException(response, true); if (response.StatusCode == HttpStatusCode.NotFound) { return new ReadOnlyCollection<KoreanbotsBotModel>(new List<KoreanbotsBotModel>()); } return KoreanbotsBotBuilder.BuildListModels(response.Content); } public async Task<IReadOnlyCollection<KoreanbotsBotModel>> GetBotsByNewAsync() { RestClient client = new RestClient(BaseUrl); RestRequest request = new RestRequest(Constants.V2BOTLISTNEW, Method.GET); IRestResponse response = await client.ExecuteAsync(request); Utils.CheckHttpException(response); return KoreanbotsBotBuilder.BuildListModels(response.Content); } public async Task<IReadOnlyCollection<KoreanbotsBotModel>> GetBotsByVotedAsync() { RestClient client = new RestClient(BaseUrl); RestRequest request = new RestRequest(Constants.V2BOTLISTVOTE, Method.GET); IRestResponse response = await client.ExecuteAsync(request); Utils.CheckHttpException(response); return KoreanbotsBotBuilder.BuildListModels(response.Content); } public async Task<KoreanbotsUserVote> CheckVoteAsync(ulong botId, ulong userId) { RestClient client = new RestClient(BaseUrl); RestRequest request = new RestRequest(string.Format(Constants.V2USERVOTE, botId), Method.GET); request.AddHeader("Authorization", Koreanbots.Token); request.AddQueryParameter("userID", userId.ToString()); IRestResponse response = await client.ExecuteAsync(request); Utils.CheckHttpException(response); return KoreanbotsBotBuilder.BuildVoteModel(response.Content); } public async Task<KoreanbotsDefaultResponse> UpdateBotAsync(ulong botId, KoreanbotsUpdateModel data) { RestClient client = new RestClient(BaseUrl); RestRequest request = new RestRequest(string.Format(Constants.V2BOTUPDATE, botId), Method.POST); request.AddHeader("Authorization", Koreanbots.Token); request.AddParameter("shards", data.Shards); request.AddParameter("servers", data.Servers); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); IRestResponse response = await client.ExecuteAsync(request); Utils.CheckHttpException(response, ignoreTooMany:true); return KoreanbotsBuilder.BuildResponse(response.Content); } public async Task<KoreanbotsUserModel> RequestUserByIdAsync(ulong userid) { RestClient client = new RestClient(BaseUrl); RestRequest request = new RestRequest(string.Format(Constants.V2USERBYID, userid), Method.GET); IRestResponse response = await client.ExecuteAsync(request); Utils.CheckHttpException(response); return KoreanbotsUserBuilder.BuildModel(response.Content); } } }
namespace Library.Web.Infrastructure.Extensions { using Microsoft.AspNetCore.Http; using Microsoft.Net.Http.Headers; using System.IO; using System.Threading.Tasks; public static class FormFileExtensions { public static string GetFileType(this IFormFile file) { var fileName = ContentDispositionHeaderValue.Parse( file.ContentDisposition).FileName.ToString().Trim('"'); return fileName.Substring(fileName.Length - 4, 4); } public static async Task<MemoryStream> GetFileStream(this IFormFile file) { MemoryStream filestream = new MemoryStream(); await file.CopyToAsync(filestream); return filestream; } public static async Task<byte[]> GetFileArray(this IFormFile file) { MemoryStream filestream = new MemoryStream(); await file.CopyToAsync(filestream); return filestream.ToArray(); } public static string ReadTxtFile(string path) { path = string.Format(path, Directory.GetCurrentDirectory()); return File.ReadAllText(path); } } }
namespace RefactorDataAccess.RepositoryPattern { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Domain; using Infrastructure; using Microsoft.EntityFrameworkCore; public class WidgetRepository : IWidgetRepository { private readonly ApplicationContext _context; public WidgetRepository(ApplicationContext context) { _context = context; } public async Task<IReadOnlyList<Widget>> SearchTypeWithBatchNumber(WidgetType widgetType, int batchNumber) { return await _context.Widgets .Where(widget => widget.WidgetType == widgetType) .Where(widget => widget.BatchNumber == batchNumber) .ToListAsync(); } public async Task<IReadOnlyList<Widget>> SearchBatchNumber(int batchNumber) { return await _context.Widgets .Where(widget => widget.BatchNumber == batchNumber) .ToListAsync(); } public async Task<IReadOnlyList<Widget>> SearchCreationDate(DateTime createdOn) { return await _context.Widgets .Where(widget => widget.CreatedOn == createdOn) .ToListAsync(); } public async Task<IReadOnlyList<Widget>> SearchBatchNumberOnDate(int batchNumber, DateTime createdOn) { return await _context.Widgets .Where(widget => widget.BatchNumber == batchNumber) .Where(widget => widget.CreatedOn == createdOn) .ToListAsync(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace _05 { class Program { static void Main(string[] args) { var input = File.ReadAllLines("input.txt"); var forbiddenStrings = new [] { "ab", "cd", "pq", "xy" }; var part1Criteria = new List<Func<string, bool>> { str => str.Count(ch => ("aeiou").Contains(ch)) >= 3, str => Regex.Match(str, @"(\w)\1").Success, str => !forbiddenStrings.Any(str.Contains) }; var part2Criteria = new List<Func<string, bool>> { str => Regex.IsMatch(str, @"(..).*\1"), str => Regex.IsMatch(str, @"(.).\1") }; var part1NiceCount = input.Count(str => part1Criteria.All(crit => crit(str))); var part2NiceCount = input.Count(str => part2Criteria.All(crit => crit(str))); Console.WriteLine("Nice lines 1: {0}", part1NiceCount); Console.WriteLine("Nice lines 2: {0}", part2NiceCount); Console.ReadLine(); } } }
using Grpc.Core; namespace Spacetime.Core.gRPC.Dynamic; public interface IDynamicGrpcWrapper { Task<IDictionary<string, object>> AsyncUnaryCall(string serviceName, string methodName, IDictionary<string, object> request); IAsyncEnumerable<IDictionary<string, object>> AsyncDynamicCall(string serviceName, string methodName, IAsyncEnumerable<IDictionary<string, object>> input, string? host = null, CallOptions? options = null); Task<GrpcExploreResult> Explore(); }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(Text))] public class Print_Text : MonoBehaviour { private Text textbox; private bool unwrite_l2r = false; bool text_finished_editing = true; private string leftover_text = ""; private void Start() { textbox = GetComponent<Text>(); } //Returns if it finishes editing the text. public bool IsFinished() { return text_finished_editing; } private IEnumerator writeText() { char tmp = leftover_text[0]; textbox.text += leftover_text[0]; leftover_text = leftover_text.Substring(1); if (tmp == '\n') { yield return new WaitForSeconds(0.6525f); } else { yield return new WaitForSeconds(0.1225f); } if (leftover_text.Length > 0) { yield return writeText(); } else { text_finished_editing = true; } } private IEnumerator unwriteText() { if(!unwrite_l2r) { textbox.text = textbox.text.Substring(0, textbox.text.Length - 2); } else { textbox.text = textbox.text.Substring(1, textbox.text.Length-1); } yield return new WaitForSeconds(0.1225f); if (textbox.text.Length > 0) { yield return unwriteText(); } else { text_finished_editing = true; } } //bool : Should the text be removed left to right or vise versa? public void RemoveText(bool isL2R) { StopAllCoroutines(); unwrite_l2r = isL2R; StartCoroutine(unwriteText()); } public void SetText(string txt) { StopAllCoroutines(); if (txt == "") { textbox.text = ""; return; } if (!text_finished_editing) { StopCoroutine("writeText"); textbox.text += leftover_text; leftover_text = ""; text_finished_editing = true; } else { leftover_text = txt; textbox.text = ""; text_finished_editing = false; StartCoroutine("writeText"); } } }
using System.Collections.Generic; namespace CSharpToday.Blazor.MultiLang.Resources.Tree { internal interface IResourceTreeBuilder { IResourceTree BuildTree(IEnumerable<string> resources); } }
// ----------------------------------------------------------------------- // <copyright file="AuditController.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- namespace Microsoft.Store.PartnerCenter.Explorer.Controllers { using System; using System.Threading.Tasks; using System.Web.Mvc; using Models; using Providers; using Security; /// <summary> /// Controller for Audit views. /// </summary> /// <seealso cref="System.Web.Mvc.Controller" /> [AuthorizationFilter(Roles = UserRoles.Partner)] public class AuditController : BaseController { /// <summary> /// Initializes a new instance of the <see cref="AuditController"/> class. /// </summary> /// <param name="service">Provides access to core services.</param> public AuditController(IExplorerProvider provider) : base(provider) { } /// <summary> /// Get the audit records for the specified date range using the Partner Center API. /// </summary> /// <param name="endDate">The end date of the audit record logs.</param> /// <param name="startDate">The start date of the audit record logs.</param> /// <returns>A partial view containing the requested audit record logs.</returns> public async Task<PartialViewResult> GetRecords(DateTime endDate, DateTime startDate) { AuditRecordsModel auditRecordsModel = new AuditRecordsModel() { Records = await Provider.PartnerOperations.GetAuditRecordsAsync(startDate, endDate).ConfigureAwait(false) }; return PartialView("Records", auditRecordsModel); } /// <summary> /// Handles the request for the Search view. /// </summary> /// <returns>Returns an empty view.</returns> public ActionResult Search() { return View(); } } }
using System; using System.Collections.Generic; using System.Text; using NBitcoin; using Stratis.Bitcoin.Features.SmartContracts.Networks; using Stratis.SmartContracts; using Stratis.SmartContracts.Executor.Reflection.ContractLogging; using Stratis.SmartContracts.Executor.Reflection.Serialization; using Xunit; namespace Stratis.Bitcoin.Features.SmartContracts.Tests.Logs { public class RawLogTests { public struct Example { [Index] public string Name; [Index] public uint Amount; public Example(string name, uint amount) { this.Name = name; this.Amount = amount; } } [Fact] public void RawLog_With_Null_Value_Serializes() { var serializer = new ContractPrimitiveSerializer(new SmartContractPosRegTest()); var exampleLog = new Example(null, 0); var rawLog = new RawLog(uint160.One, exampleLog); var log = rawLog.ToLog(serializer); Assert.Equal(3, log.Topics.Count); Assert.Equal(nameof(Example), Encoding.UTF8.GetString(log.Topics[0])); // Check that null has been serialized correctly Assert.Equal(new byte[0], log.Topics[1]); Assert.Equal(exampleLog.Amount, BitConverter.ToUInt32(log.Topics[2])); } } }
using System; using System.Collections.Generic; using ReactiveDomain.Util; namespace ReactiveDomain.Messaging.Bus { public abstract class QueuedSubscriber : IDisposable { private readonly List<IDisposable> _subscriptions = new List<IDisposable>(); private readonly QueuedHandler _messageQueue; private readonly IBus _externalBus; private readonly InMemoryBus _internalBus; protected object Last = null; public bool Starving => _messageQueue.Idle; protected QueuedSubscriber(IBus bus, bool idempotent = false) { _externalBus = bus ?? throw new ArgumentNullException(nameof(bus)); _internalBus = new InMemoryBus("SubscriptionBus"); if (idempotent) _messageQueue = new QueuedHandler( new IdempotentHandler<IMessage>( new AdHocHandler<IMessage>(_internalBus.Publish) ), "SubscriptionQueue"); else _messageQueue = new QueuedHandler( new AdHocHandler<IMessage>(_internalBus.Publish), "SubscriptionQueue"); _messageQueue.Start(); } public IDisposable Subscribe<T>(IHandle<T> handler) where T : class,IMessage { var internalSub = _internalBus.Subscribe(handler); var externalSub = _externalBus.Subscribe(new AdHocHandler<T>(_messageQueue.Handle)); _subscriptions.Add(internalSub); _subscriptions.Add(externalSub); return new Disposer(() => { internalSub?.Dispose(); externalSub?.Dispose(); return Unit.Default; }); } public IDisposable Subscribe<T>(IHandleCommand<T> handler) where T : class,ICommand { var internalSub = _internalBus.Subscribe(new CommandHandler<T>(_externalBus, handler)); var externalSub = _externalBus.Subscribe(new AdHocHandler<T>(_messageQueue.Handle)); _subscriptions.Add(internalSub); _subscriptions.Add(externalSub); return new Disposer(() => { internalSub?.Dispose(); externalSub?.Dispose(); return Unit.Default; }); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private bool _disposed; protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { _messageQueue.RequestStop(); _subscriptions?.ForEach(s => s.Dispose()); _internalBus?.Dispose(); _disposed = true; } } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.ServiceModel.Discovery.Configuration { static class ConfigurationStrings { public const string AnnouncementEndpoints = "announcementEndpoints"; public const string DiscoveryClient = "discoveryClient"; public const string DiscoveryClientSettings = "discoveryClientSettings"; public const string DiscoveryVersion = "discoveryVersion"; public const string Duration = "duration"; public const string Enabled = "enabled"; public const string Endpoint = "endpoint"; public const string Extensions = "extensions"; public const string FindCriteria = "findCriteria"; public const string IsSystemEndpoint = "isSystemEndpoint"; public const string MaxAnnouncementDelay = "maxAnnouncementDelay"; public const string MaxResponseDelay = "maxResponseDelay"; public const string MaxResults = "maxResults"; public const string MulticastAddress = "multicastAddress"; public const string Name = "name"; public const string Namespace = "namespace"; public const string DiscoveryMode = "discoveryMode"; public const string Scopes = "scopes"; public const string Scope = "scope"; public const string ScopeMatchBy = "scopeMatchBy"; public const string Types = "types"; public const string UdpDiscoveryEndpoint = "udpDiscoveryEndpoint"; // UDP transport settings public const string TransportSettings = "transportSettings"; public const string DuplicateMessageHistoryLength = "duplicateMessageHistoryLength"; public const string MaxPendingMessageCount = "maxPendingMessageCount"; public const string MaxReceivedMessageSize = "maxReceivedMessageSize"; public const string MaxBufferPoolSize = "maxBufferPoolSize"; public const string MaxMulticastRetransmitCount = "maxMulticastRetransmitCount"; public const string MaxUnicastRetransmitCount = "maxUnicastRetransmitCount"; public const string MulticastInterfaceId = "multicastInterfaceId"; public const string SocketReceiveBufferSize = "socketReceiveBufferSize"; public const string TimeToLive = "timeToLive"; public const string TimeSpanZero = "00:00:00"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NiceHashMiner.Interfaces.DataVisualizer { interface IDataVisualizer { // TODO for now this one is just a stub // add TAG or if currently visible maybe?? } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using starsky.foundation.metathumbnail.Interfaces; namespace starskytest.FakeMocks { public class FakeIMetaExifThumbnailService : IMetaExifThumbnailService { public List<(string, string)> Input { get; set; } = new (string, string)[0].ToList(); public Task<bool> AddMetaThumbnail(IEnumerable<(string, string)> subPathsAndHash) { Input.AddRange(subPathsAndHash); return Task.FromResult(true); } public Task<bool> AddMetaThumbnail(string subPath) { Input.Add((subPath, null)); return Task.FromResult(true); } public Task<bool> AddMetaThumbnail(string subPath, string fileHash) { Input.Add((subPath, fileHash)); return Task.FromResult(true); } } }
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aiven.Outputs { [OutputType] public sealed class GetServiceIntegrationEndpointExternalKafkaUserConfigResult { public readonly string? BootstrapServers; public readonly string? SaslMechanism; public readonly string? SaslPlainPassword; public readonly string? SaslPlainUsername; public readonly string? SecurityProtocol; public readonly string? SslCaCert; public readonly string? SslClientCert; public readonly string? SslClientKey; public readonly string? SslEndpointIdentificationAlgorithm; [OutputConstructor] private GetServiceIntegrationEndpointExternalKafkaUserConfigResult( string? bootstrapServers, string? saslMechanism, string? saslPlainPassword, string? saslPlainUsername, string? securityProtocol, string? sslCaCert, string? sslClientCert, string? sslClientKey, string? sslEndpointIdentificationAlgorithm) { BootstrapServers = bootstrapServers; SaslMechanism = saslMechanism; SaslPlainPassword = saslPlainPassword; SaslPlainUsername = saslPlainUsername; SecurityProtocol = securityProtocol; SslCaCert = sslCaCert; SslClientCert = sslClientCert; SslClientKey = sslClientKey; SslEndpointIdentificationAlgorithm = sslEndpointIdentificationAlgorithm; } } }
namespace Dadata { public class SuggestClient : SuggestClientSync { public SuggestClient(string token, string baseUrl = BASE_URL) : base(token, baseUrl) { } } }
namespace Gimme.Oracle.Adapter.Infrastructure { public class DataBaseSettings { public string TemporaryEmail { get; set; } public bool SendOnlyToTemporaryEmail { get; set; } public bool SendMailEnabled { get; set; } } }
using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; using TOTVS.Fullstack.Challenge.AuctionHouse.Domain.Models.Auctions; namespace TOTVS.Fullstack.Challenge.AuctionHouse.Infrastructure.Persistence.Mappings.MongoDb.Auctions { /// <summary> /// Classe de mapeamento para o usuário responsável por um leilão /// </summary> public static class AuctionResponsibleUserMap { /// <summary> /// Configura o mapeamento da entidade AuctionResponsibleUser para o MongoDB /// </summary> public static void Configure() { if (BsonClassMap.IsClassMapRegistered(typeof(AuctionResponsibleUser))) { return; } try { BsonClassMap.RegisterClassMap<AuctionResponsibleUser>(map => { map.AutoMap(); map.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId)); map.SetIgnoreExtraElements(true); map.MapIdProperty(auctionResponsibleUser => auctionResponsibleUser.Id); map.MapMember(auctionResponsibleUser => auctionResponsibleUser.Name).SetIsRequired(true); }); } catch { // Exceção ignorada porque a verificação no início do mapeamento não é suficiente // Isso é necessáiro somente para executar os testes em paralelo // Se deve ao fato do objeto de registo é estático, logo sofre de concorrência entre cada teste de API } } } }
using System; using System.Collections.ObjectModel; using System.Threading.Tasks; using RusfootballMobile.Logging; using Xamarin.Forms; using RusfootballMobile.Services; namespace RusfootballMobile.ViewModels { public abstract class ItemsViewModelBase<T, TVM> : ViewModelBase { private readonly Lazy<IDataProvider<T>> _dataProvider; private readonly ILogger _logger; protected ItemsViewModelBase() { Items = new ObservableCollection<TVM>(); LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand(false)); LoadMoreItemsCommand = new Command(async () => await ExecuteLoadItemsCommand(true)); _logger = LoggerFactory.GetLogger(GetType()); _dataProvider = new Lazy<IDataProvider<T>>(GetProvider, true); } protected abstract IDataProvider<T> GetProvider(); protected abstract TVM CreateItem(T source); public ObservableCollection<TVM> Items { get; } public Command LoadItemsCommand { get; } public Command LoadMoreItemsCommand { get; } public BusyObject Busy { get; } = new BusyObject(); private async Task ExecuteLoadItemsCommand(bool nextPage) { if (Busy.IsBusy) return; Busy.IsBusy = true; try { if (!nextPage) { Items.Clear(); } await _dataProvider.Value.GetItemsAsync(nextPage, delegate(T obj) { Items.Add(CreateItem(obj)); }); } catch (Exception ex) { _logger.Error("Load items failure", ex); } finally { Busy.IsBusy = false; } } } }
using System.Threading.Tasks; using CRM.Domain.Users; using CRM.Integration.Tests.Framework; using CRM.Web.Features.Users; using CRM.Web.Infrastructure; using FluentAssertions; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Moq; using Xunit; namespace CRM.Integration.Tests.Users; public class UserTests : IntegrationTest { [Fact] public async Task Changing_email_from_corporate_to_non_corporate() { var user = await CreateUser("user@mycompany.com", UserType.Employee); var company = await CreateCompany("mycompany.com", 1); var busSpy = new BusSpy(); var messageBus = new FakeMessageBus(busSpy); var domainLoggerMock = new Mock<IDomainLogger>(); var sut = new UsersController(Database, messageBus, domainLoggerMock.Object); var result = await sut.ChangeEmail(company.Id, user.Id, "new@gmail.com"); result.Should().BeOfType<OkResult>(); var userFromDb = await Database.Users.FirstOrDefaultAsync(u => u.Id == user.Id); userFromDb .ShouldExist() .WithEmail("new@gmail.com") .WithType(UserType.Customer); var companyFromDb = await Database.Companies.FirstOrDefaultAsync(c => c.Id == company.Id); companyFromDb .ShouldExist() .WithNumberOfEmployees(0); busSpy.ShouldSendNumberOfMessages(1).WithEmailChangedMessage(user.Id, "new@gmail.com"); domainLoggerMock.Verify(_ => _.UserTypeHasChanged(user.Id, UserType.Employee, UserType.Customer), Times.Once); } }
using Newtonsoft.Json; using System.Collections.Generic; namespace DontPanic.TumblrSharp.Client { /// <summary> /// The blog from Trail /// </summary> public class TrailBlog { /// <summary> /// the name of the blog /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// is Blog active /// </summary> [JsonConverter(typeof(BoolConverter))] [JsonProperty(PropertyName = "active")] public bool Active { get; set; } /// <summary> /// theme of the blog /// </summary> [JsonConverter(typeof(TrailThemeConverter))] [JsonProperty(PropertyName = "theme")] public TrailTheme Theme { get; set; } /// <summary> /// share likes /// </summary> [JsonConverter(typeof(BoolConverter))] [JsonProperty(PropertyName = "share_likes")] public bool ShareLikes { get; set; } /// <summary> /// share following /// </summary> [JsonConverter(typeof(BoolConverter))] [JsonProperty(PropertyName = "share_following")] public bool ShareFollowing { get; set; } /// <summary> /// can be followed /// </summary> [JsonConverter(typeof(BoolConverter))] [JsonProperty(PropertyName = "can_be_followed")] public bool CanBeFollowed { get; set; } /// <summary> /// Compare a trailblog with another /// </summary> /// <param name="obj">Object to be equals</param> /// <returns>bool</returns> public override bool Equals(object obj) { return obj is TrailBlog blog && Name == blog.Name && Active == blog.Active && Theme.Equals(blog.Theme) && ShareLikes == blog.ShareLikes && ShareFollowing == blog.ShareFollowing && CanBeFollowed == blog.CanBeFollowed; } /// <summary> /// return a hash code /// </summary> /// <returns>hashcode as <cref>int</cref></returns> public override int GetHashCode() { var hashCode = 1185437142; hashCode = hashCode * -1521134295 + Name.GetHashCode(); hashCode = hashCode * -1521134295 + Active.GetHashCode(); hashCode = hashCode * -1521134295 + Theme.GetHashCode(); hashCode = hashCode * -1521134295 + ShareLikes.GetHashCode(); hashCode = hashCode * -1521134295 + ShareFollowing.GetHashCode(); hashCode = hashCode * -1521134295 + CanBeFollowed.GetHashCode(); return hashCode; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03.School_Camp { class SchoolCamp { static void Main(string[] args) { string season = Console.ReadLine().ToLower(); string groupType= Console.ReadLine().ToLower(); int students = int.Parse(Console.ReadLine()); int nights = int.Parse(Console.ReadLine()); double price = 0.0; string sport=""; //13:55 pause //14:02 resume if (season == "winter") { if (groupType == "boys") { sport = "Judo"; price = 9.60; } else if (groupType == "girls") { sport = "Gymnastics"; price = 9.60; } else { sport = "Ski"; price = 10; } } else if (season == "spring") { if (groupType == "boys") { sport = "Tennis"; price = 7.20; } else if (groupType == "girls") { sport = "Athletics"; price = 7.20; } else { sport = "Cycling"; price = 9.50; } } else { if (groupType == "boys") { sport = "Football"; price = 15; } else if (groupType == "girls") { sport = "Volleyball"; price = 15; } else { sport = "Swimming"; price = 20; } } var total = price * nights * students; if (students >= 50) { total *= 0.5; } else if (students < 50 && students >= 20) { total *= 0.85; } else if (students < 20 && students >= 10) { total *= 0.95; } Console.WriteLine($"{ sport} { total:f2} lv."); } } }
 @{ ViewBag.Title = "Prayer"; } <h2>Prayer</h2>
using Xunit; using System; using System.Linq.Expressions; namespace BitHelp.Core.Extend.Test.ExpressionExtendTest { public class PropertyTypeTest { private Type PropertyType<T>(Expression<Func<T, object>> expression) { return expression.PropertyType(); } [Fact] public void Check_property_name() { Assert.Equal(typeof(char), this.PropertyType<SingleValues>(x => x.Char)); Assert.Equal(typeof(string), this.PropertyType<SingleValues>(x => x.String)); Assert.Equal(typeof(int), this.PropertyType<SingleValues>(x => x.Int)); Assert.Equal(typeof(int?), this.PropertyType<SingleValues>(x => x.IntNull)); Assert.Equal(typeof(long), this.PropertyType<SingleValues>(x => x.Long)); Assert.Equal(typeof(long?), this.PropertyType<SingleValues>(x => x.LongNull)); Assert.Equal(typeof(decimal), this.PropertyType<SingleValues>(x => x.Decimal)); Assert.Equal(typeof(decimal?), this.PropertyType<SingleValues>(x => x.DecimalNull)); Assert.Equal(typeof(uint), this.PropertyType<SingleValues>(x => x.Uint)); Assert.Equal(typeof(uint?), this.PropertyType<SingleValues>(x => x.UintNull)); Assert.Equal(typeof(DateTime), this.PropertyType<SingleValues>(x => x.DateTime)); Assert.Equal(typeof(DateTime?), this.PropertyType<SingleValues>(x => x.DateTimeNull)); Assert.Equal(typeof(Guid), this.PropertyType<SingleValues>(x => x.Guid)); Assert.Equal(typeof(Guid?), this.PropertyType<SingleValues>(x => x.GuidNull)); Assert.Equal(typeof(bool), this.PropertyType<SingleValues>(x => x.Bool)); Assert.Equal(typeof(bool?), this.PropertyType<SingleValues>(x => x.BoolNull)); Assert.Equal(typeof(char[]), this.PropertyType<ArrayValues>(x => x.Char)); Assert.Equal(typeof(string[]), this.PropertyType<ArrayValues>(x => x.String)); Assert.Equal(typeof(int[]), this.PropertyType<ArrayValues>(x => x.Int)); Assert.Equal(typeof(long[]), this.PropertyType<ArrayValues>(x => x.Long)); Assert.Equal(typeof(decimal[]), this.PropertyType<ArrayValues>(x => x.Decimal)); Assert.Equal(typeof(uint[]), this.PropertyType<ArrayValues>(x => x.Uint)); Assert.Equal(typeof(DateTime[]), this.PropertyType<ArrayValues>(x => x.DateTime)); Assert.Equal(typeof(Guid[]), this.PropertyType<ArrayValues>(x => x.Guid)); Assert.Equal(typeof(bool[]), this.PropertyType<ArrayValues>(x => x.Bool)); } [Fact] public void Check_property_name_in_subclass() { Assert.Equal(typeof(int), this.PropertyType<AllValues>(x => x.SingleValues.Int)); Assert.Equal(typeof(int?), this.PropertyType<AllValues>(x => x.SingleValues.IntNull)); Assert.Equal(typeof(int[]), this.PropertyType<AllValues>(x => x.ArrayValues.Int)); } } }
namespace FileSystemModels.Utils { using FileSystemModels.Interfaces; using FileSystemModels.Models.FSItems.Base; using System; /// <summary> /// Implements simple method based extensions that can be used for classes /// implementing the <see cref="IItem"/> interface. /// </summary> public class IItemExtension { /// <summary> /// Gets a display string for a file system item (file, folder, drive). /// /// The string for display is not necessarily the same as the actual name /// of the item - drives for example are named like 'F:\' but an intended /// display string may be 'F:\ (drive is not ready)'. /// /// The label is displayed in brackets if supplied to this call of if it /// can be determined, for examples, for drives. /// </summary> /// <param name="item"></param> /// <param name="label"></param> /// <returns></returns> public static string GetDisplayString(IItem item, string label = null) { switch (item.ItemType) { case FSItemType.LogicalDrive: try { if (label == null) { var di = new System.IO.DriveInfo(item.ItemName); if (di.IsReady == true) label = di.VolumeLabel; else return string.Format("{0} ({1})", item.ItemName, "device is not ready"); } return string.Format("{0} {1}", item.ItemName, (string.IsNullOrEmpty(label) ? string.Empty : string.Format("({0})", label))); } catch (Exception exp) { // Just return a folder name if everything else fails (drive may not be ready etc). return string.Format("{0} ({1})", item.ItemName, exp.Message.Trim()); } case FSItemType.Folder: case FSItemType.Unknown: default: return item.ItemName; } } } }
namespace Messiah { using UnityEngine; using DG.Tweening; using UnityEngine.UI; public class CardUI : MonoBehaviour { public Card card; public Sequence seq; Image image; void Start() { image = GetComponent<Image>(); } public void SetCardByID(uint id) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SunSpawner : MonoBehaviour { [SerializeField] SunMove sunPrefab = null; [SerializeField] int minWaitTime = 15; [SerializeField] int maxWaitTime = 30; bool spawn = true; float randomSpawnTime; IEnumerator Start() { while (spawn) { yield return new WaitForSeconds(Random.Range(minWaitTime, maxWaitTime)); SpawnSuns(); } } private void SpawnSuns() { SunMove oneSun = Instantiate(sunPrefab, transform.position, Quaternion.identity) as SunMove; oneSun.transform.parent = transform; } }
namespace Microsoft.AspNetCore.OData.Conventions.Controllers { using Microsoft.AspNet.OData; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.OData.Models; public class CustomersController : ODataController { public IActionResult Get() => Ok(); public IActionResult Get( int key ) => Ok(); public IActionResult Post( [FromBody] Customer customer ) { customer.Id = 42; return Created( customer ); } public IActionResult Put( int key, [FromBody] Customer customer ) => NoContent(); public IActionResult Delete( int key ) => NoContent(); } }
namespace DotNetBungieAPI; internal static class Conditions { internal static string NotNullOrWhiteSpace(string value) { return !string.IsNullOrWhiteSpace(value) ? value : throw new ArgumentException(); } internal static int Int32MoreThan(int value, int comparedAgainst) { return value > comparedAgainst ? value : throw new ArgumentException(); } internal static T NotNull<T>(T value) { return value is not null ? value : throw new ArgumentNullException(nameof(value)); } }
namespace MyShirtsApp.Data { using MyShirtsApp.Data.Models; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; public class MyShirtsAppDbContext : IdentityDbContext<User> { public MyShirtsAppDbContext(DbContextOptions<MyShirtsAppDbContext> options) : base(options) { } public DbSet<Shirt> Shirts { get; init; } public DbSet<Size> Sizes { get; init; } public DbSet<Cart> Carts { get; init; } public DbSet<ShirtSize> ShirtSizes { get; init; } public DbSet<ShirtCart> ShirtCarts { get; init; } public DbSet<Favorite> Favorites { get; init; } public DbSet<ShirtFavorite> ShirtFavorites { get; init; } protected override void OnModelCreating(ModelBuilder builder) { builder .Entity<ShirtSize>() .HasKey(ss => new { ss.ShirtId, ss.SizeId }); builder.Entity<ShirtSize>() .HasOne(ss => ss.Shirt) .WithMany(s => s.ShirtSizes) .HasForeignKey(ss => ss.ShirtId) .OnDelete(DeleteBehavior.Restrict); builder.Entity<ShirtSize>() .HasOne(ss => ss.Size) .WithMany(s => s.ShirtSizes) .HasForeignKey(ss => ss.SizeId) .OnDelete(DeleteBehavior.Restrict); builder .Entity<ShirtCart>() .HasKey(sc => new { sc.ShirtId, sc.CartId, sc.SizeName }); builder.Entity<ShirtCart>() .HasOne(sc => sc.Shirt) .WithMany(s => s.ShirtCarts) .HasForeignKey(sc => sc.ShirtId) .OnDelete(DeleteBehavior.Restrict); builder.Entity<ShirtCart>() .HasOne(sc => sc.Cart) .WithMany(s => s.ShirtCarts) .HasForeignKey(sc => sc.CartId) .OnDelete(DeleteBehavior.Restrict); builder .Entity<ShirtFavorite>() .HasKey(sf => new { sf.ShirtId, sf.FavoriteId }); builder.Entity<ShirtFavorite>() .HasOne(sf => sf.Shirt) .WithMany(s => s.ShirtFavorites) .HasForeignKey(sf => sf.ShirtId) .OnDelete(DeleteBehavior.Restrict); builder.Entity<ShirtFavorite>() .HasOne(sf => sf.Favorite) .WithMany(s => s.ShirtFavorites) .HasForeignKey(sf => sf.FavoriteId) .OnDelete(DeleteBehavior.Restrict); base.OnModelCreating(builder); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TinaXEditor.VFSKitInternal { [Serializable] public class VFSProfileModel { #region 序列化存储用 /// <summary> /// 外部不要直接操作它!!!! /// </summary> public ProfileRecord[] Profiles; //存储 序列化 #endregion #region 作为对象时的运算用 private Dictionary<string, ProfileRecord> _dict_profiles; private Dictionary<string, ProfileRecord> dict_profiles { get { if(_dict_profiles == null) { if (Profiles == null) Profiles = new ProfileRecord[0]; _dict_profiles = new Dictionary<string, ProfileRecord>(); foreach (var item in Profiles) { if (!_dict_profiles.ContainsKey(item.ProfileName)) _dict_profiles.Add(item.ProfileName, item); } } return _dict_profiles; } } public bool TryGetProfille(string name,out ProfileRecord profile) { return dict_profiles.TryGetValue(name,out profile); } public void AddProfileIfNotExists(ProfileRecord pr) { if (!dict_profiles.ContainsKey(pr.ProfileName)) { dict_profiles.Add(pr.ProfileName,pr); } } public void ReadySave() { List<ProfileRecord> temp = new List<ProfileRecord>(); foreach(var item in dict_profiles) { temp.Add(item.Value); } Profiles = temp.ToArray(); } #endregion } }
namespace MatchThree.Core.Enum { public enum GemState { Move, Idle, Destroy, Swap } }
using System.Linq; public static class Kata { public static string FormatWords(string[] words) { var all = words?.Where(x => x != "").ToArray(); if (!all?.Any() ?? true) { return ""; } if (all.Length == 1) { return all[0]; } return $"{string.Join(", ", all.Take(all.Length - 1))} and {all.Last()}"; } }
using ABCo.ABSharedKV.Background.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ABCo.ABSharedKV.Background.Interfaces { public interface IKVCommunicationMechanism { object WaitForNewCommunication(CancellationToken src); Task<MessageResponse> WaitForMessage(object obj); void CloseConnection(object obj); } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Rocket.Battlerite.Converters; namespace Rocket.Battlerite { public partial class RoundFinishedEvent : ITelemetryObject { [JsonProperty("time")] [JsonConverter(typeof(EpochMsConverter))] public DateTime Time { get; set; } [JsonProperty("matchID")] public string MatchId { get; set; } [JsonProperty("externalMatchID")] public string ExternalMatchId { get; set; } [JsonProperty("round")] public int Round { get; set; } [JsonProperty("roundLength")] public int RoundLength { get; set; } [JsonProperty("winningTeam")] public int WinningTeam { get; set; } [JsonProperty("playerStats")] public List<PlayerStat> PlayerStats { get; set; } } public partial class PlayerStat { [JsonProperty("userID")] public string UserId { get; set; } [JsonProperty("kills")] public int Kills { get; set; } [JsonProperty("deaths")] public int Deaths { get; set; } [JsonProperty("score")] public int Score { get; set; } [JsonProperty("damageDone")] public int DamageDone { get; set; } [JsonProperty("damageReceived")] public int DamageReceived { get; set; } [JsonProperty("healingDone")] public int HealingDone { get; set; } [JsonProperty("healingReceived")] public int HealingReceived { get; set; } [JsonProperty("disablesDone")] public int DisablesDone { get; set; } [JsonProperty("disablesReceived")] public int DisablesReceived { get; set; } [JsonProperty("energyGained")] public int EnergyGained { get; set; } [JsonProperty("energyUsed")] public int EnergyUsed { get; set; } [JsonProperty("timeAlive")] public int TimeAlive { get; set; } [JsonProperty("abilityUses")] public int AbilityUses { get; set; } } }
using System; using UnityEngine; namespace Marvelous { public static partial class Marvelous { /// <summary> /// Traverse all the children of the transform and executes the Action on this transform, /// as well as on all the children recursively. /// </summary> /// <param name="current">The current Transform to execute the Action on.</param> /// <param name="action">The Action to executed.</param> public static void TraverseAndExecute(Transform current, Action<Transform> action) { action(current); for (int i = 0; i < current.childCount; ++i) { TraverseAndExecute(current.GetChild(i), action); } } } public static partial class Extensions { /// <summary> /// Traverse all the children of the transform and executes the Action on this transform, /// as well as on all the children recursively. /// </summary> /// <param name="current">The current Transform to execute the Action on.</param> /// <param name="action">The Action to executed.</param> public static void TraverseAndExecute(this Transform current, Action<Transform> action) { Marvelous.TraverseAndExecute(current, action); } } }
using System.Collections.Generic; using System.Linq; using Antlr4.Runtime.Tree; using Graphs; namespace Engine { public class NfaOptimizer { private readonly Dictionary<State, SmartSet<State>> _closure = new Dictionary<State, SmartSet<State>>(); private readonly Dictionary<SmartSet<State>, State> _hash_sets = new Dictionary<SmartSet<State>, State>(); public State CreateInitialState(Automaton nfa, Automaton dfa) { /** get closure of initial state from nfa. */ var initialStates = nfa.StartStates; var initialClosure = ClosureTaker.GetClosure(initialStates, nfa); var state = AddHashSetState(dfa, initialClosure); dfa.AddStartState(state); return state; } public bool HasFinalState(IEnumerable<State> states, Automaton automaton) { foreach (var state in states) if (automaton.IsFinalState(state)) return true; return false; } public State AddHashSetState(Automaton dfa, SmartSet<State> states) { var result = FindHashSetState(dfa, states); if (result != null) return result; result = new State(dfa); _hash_sets.Add(states, result); return result; } public State FindHashSetState(Automaton dfa, SmartSet<State> states) { _hash_sets.TryGetValue(states, out State result); return result; } public SmartSet<State> FindHashSet(State state) { foreach (var hs in _hash_sets) if (hs.Value == state) return hs.Key; return null; } /* Apply powerset construction to the NFA to convert to a DFA. * Note, the result of this method isn't strictly a DFA because * edges in the automaton can be text or code, which function just like * epsilon transitions--no input is consumed for the edge. */ public Automaton Optimize(Automaton nfa) { var dfa = new Automaton(); // For every state s, compute collection of states along epsilon edges // to get an initial computation of dfa states. foreach (var s in nfa.Vertices) { var c = ClosureTaker.GetClosure(new List<State> {s}, nfa); _closure[s] = c; } // For every state set, compute sums and fix up state sets. foreach (var p in _closure) { var key = p.Key; var set = p.Value; foreach (var s in set) _closure[s].UnionWith(set); } // For every state in nfa using Tarjan walk, // sum sets with common transitions. var ordered_list = new TarjanNoBackEdges<State, Edge>(nfa).ToList(); ordered_list.Reverse(); var changed = true; while (changed) { changed = false; foreach (var s in ordered_list) { var closure = _closure[s]; var transitions = ClosureTaker.GatherTransitions(closure); foreach (var transition_set in transitions) { var key = transition_set.Key; var value = transition_set.Value; var state_set = new SmartSet<State>(); // All states in value must have common set in dfa. foreach (var e in value) { var c = e.To; var cl = _closure[c]; state_set.UnionWith(cl); } foreach (var c in state_set) if (!_closure[c].Equals(state_set)) { _closure[c] = state_set; changed = true; } } } } var initialState = CreateInitialState(nfa, dfa); foreach (var p in _closure) { var state_set = p.Value; var new_dfa_state = FindHashSetState(dfa, state_set); if (new_dfa_state == null) { var state = AddHashSetState(dfa, state_set); { var mark = false; foreach (var s in state_set) if (nfa.FinalStates.Contains(s)) mark = true; if (mark && !dfa.FinalStates.Contains(state)) dfa.AddFinalState(state); } } } //System.Console.Error.WriteLine(dfa.ToString()); foreach (var p in _closure) { var k = p.Key; var state_set = p.Value; var dfa_state = FindHashSetState(dfa, state_set); // System.Console.Error.WriteLine("State " + dfa_state.Id + ":" // + state_set.Aggregate( // "", // start with empty string to handle empty list case. // (current, next) => current + ", " + next)); } //System.Console.Error.WriteLine(dfa.ToString()); foreach (var from_dfa_state in dfa.Vertices) { var nfa_state_set = FindHashSet(from_dfa_state); var transitions = ClosureTaker.GatherTransitions(nfa_state_set); foreach (var transition_set in transitions) { // Note, transitions is a collection of edges for a given string. // For the NFA, an edge has one Ast for the edge because it came from one pattern. // But, for the DFA, there could be multiple edges for the same string, // each from a different pattern! Compute the set of Asts for // all edges. var key = transition_set.Key; var value = transition_set.Value; var state_set = new HashSet<State>(); foreach (var e in value) state_set.Add(e.To); // Find in all previous states. var new_state_set = _hash_sets.Where(hs => state_set.IsSubsetOf(hs.Key)).FirstOrDefault().Key; if (new_state_set == null) new_state_set = _closure[state_set.First()]; var to_dfa_state = FindHashSetState(dfa, new_state_set); var mods = value.First().EdgeModifiers; var asts = new List<IParseTree>(); foreach (var v in value) foreach (var v2 in v.AstList) asts.Add(v2); var he = new Edge(dfa, from_dfa_state, to_dfa_state, asts, mods); } } // Add in "any" fragment in order to match tree nodes that aren't in pattern. //{ // State s3 = new State(dfa); s3.Commit(); // var e1 = new Edge(dfa, s3, s3, null, Edge.EmptyAst, (int)Edge.EdgeModifiers.Any); e1.Commit(); // var f = new Fragment(s3); //} return dfa; } } }
using Microsoft.IdentityModel.Tokens; using System; using System.Text; namespace MGC.WEBAPI.Helpers { public class TokenOptions { public TokenOptions(string issuer, string audience, string signingKey, int tokenExpiryInMinutes = 15) { if (string.IsNullOrWhiteSpace(audience)) { throw new ArgumentNullException( $"{nameof(Audience)} is mandatory in order to generate a JWT!"); } if (string.IsNullOrWhiteSpace(issuer)) { throw new ArgumentNullException( $"{nameof(Issuer)} is mandatory in order to generate a JWT!"); } Audience = audience; Issuer = issuer; SigningKey = new SymmetricSecurityKey( Encoding.ASCII.GetBytes(signingKey)) ?? throw new ArgumentNullException( $"{nameof(SigningKey)} is mandatory in order to generate a JWT!"); TokenExpiryInMinutes = tokenExpiryInMinutes; } public SecurityKey SigningKey { get; } public string Issuer { get; } public string Audience { get; } public int TokenExpiryInMinutes { get; } } public struct TokenConstants { public const string TokenName = "jwt"; } }
namespace MVVM_DEMO.Commands { using System; using System.Windows.Input; using MVVM_DEMO.ViewModels; internal class UpdateCustomerCommand : ICommand { private CustomerViewModel viewModel; /// <summary> /// Initialize a new instance of the CustomerUpdateCommand class /// </summary> /// <param name="viewModel"></param> public UpdateCustomerCommand(CustomerViewModel viewModel) { this.viewModel = viewModel; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public bool CanExecute(object parameter) { return String.IsNullOrWhiteSpace(viewModel.Customer.Error); } public void Execute(object parameter) { viewModel.SaveChanges(); } } }
using Confluent.Kafka; using Confluent.Kafka.Admin; using GPS.JT808PubSubToKafka.JT808Partitions; using GPS.PubSub.Abstractions; using Microsoft.Extensions.Options; using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace GPS.JT808PubSubToKafka { public class JT808_MsgId_Producer : IJT808Producer { public string TopicName => JT808PubSubConstants.JT808TopicName; private Producer<string, byte[]> producer; private IJT808ProducerPartitionFactory jT808ProducerPartitionFactory; private ConcurrentDictionary<string, TopicPartition> TopicPartitionCache = new ConcurrentDictionary<string, TopicPartition>(); public JT808_MsgId_Producer( IOptions<ProducerConfig> producerConfigAccessor) { producer = new Producer<string, byte[]>(producerConfigAccessor.Value); this.jT808ProducerPartitionFactory = new JT808MsgIdProducerPartitionFactoryImpl(); using (var adminClient = new AdminClient(producer.Handle)) { try { adminClient.CreateTopicsAsync(new TopicSpecification[] { new TopicSpecification { Name = TopicName, NumPartitions = 1, ReplicationFactor = 1 } }).Wait(); } catch (AggregateException ex) { //{Confluent.Kafka.Admin.CreateTopicsException: An error occurred creating topics: [jt808]: [Topic 'jt808' already exists.].} if (ex.InnerException is Confluent.Kafka.Admin.CreateTopicsException exception) { } else { //记录日志 //throw ex.InnerException; } } try { //topic IncreaseTo 只增不减 adminClient.CreatePartitionsAsync( new List<PartitionsSpecification> { new PartitionsSpecification { IncreaseTo = 8, Topic=TopicName } } ).Wait(); } catch (AggregateException ex) { //记录日志 // throw ex.InnerException; } } } public void Dispose() { producer.Dispose(); } public void ProduceAsync(string msgId, string terminalNo, byte[] data) { TopicPartition topicPartition; if (!TopicPartitionCache.TryGetValue(terminalNo,out topicPartition)) { topicPartition = new TopicPartition(TopicName,new Partition(jT808ProducerPartitionFactory.CreatePartition(TopicName, msgId, terminalNo))); TopicPartitionCache.TryAdd(terminalNo, topicPartition); } producer.ProduceAsync(topicPartition, new Message<string, byte[]> { Key = msgId, Value = data }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Hosting; using System.Web.Mvc; using System.Xml.Linq; namespace Conti.Massimiliano._5I.XMLReadWrite2 { public class DefaultController : Controller { // GET: Default public ActionResult Index() { return View(); } /// <summary> /// /// /// </summary> private string nomeFile = HostingEnvironment.MapPath(@"~/App_Data/Persone.xml"); public ActionResult PersoneXMLWeb() { XElement data = XElement.Load(nomeFile); var persone = (from l in data.Elements("Persona") select new Persona(l)).ToList(); return View(persone); } public ActionResult XMLReadWrite() { var p = new Persone(nomeFile); return View("XMLReadWrite", p); } /// <summary> /// - XMLReadWrite2 /// </summary> /// public ActionResult XMLReadWrite2() { var p = new Persone(nomeFile); return View(p); } public ActionResult AddPredefinito() { var p = new Persone(nomeFile); p.AggiungiPredefinito(); return View("XMLReadWrite2", p); } public ActionResult DelSelected(int IdToDel) { var p = new Persone(nomeFile); p.RemoveAll(x => x.IdPersona == IdToDel); p.Save(); return View("XMLReadWrite2", p); } public ActionResult XML_AddContact() { return View(); } public ActionResult RetContatto(Persona ctn) { var p = new Persone(nomeFile); p.MyAdd(ctn); p.Save(); return View("XMLReadWrite2", p); } public ActionResult XML_ViewContact(int ctn) { var p = new Persone(nomeFile); Persona temp = p.FirstOrDefault(x => x.IdPersona == ctn); return View(temp); } public ActionResult XML_EditContact(int ctn) { var p = new Persone(nomeFile); Persona temp = p.FirstOrDefault(x => x.IdPersona == ctn); return View("XML_AddContact", temp); } } }
using System; using System.Buffers; using System.IO.Pipelines; using System.Text; using System.Text.Json; using System.Threading.Tasks; using App.Metrics; using Microsoft.AspNetCore.Connections; using Microsoft.Extensions.Logging; namespace Frontend { public sealed class MCConnectionHandler : ConnectionHandler { private ILogger _logger; private readonly IPacketReaderFactory _packetReaderFactory; private readonly IPacketQueueFactory _packetQueueFactory; private readonly IMetrics _metrics; private readonly IPacketHandler _packetHandler; public MCConnectionHandler(ILogger<MCConnectionHandler> logger, IPacketReaderFactory packetReaderFactory, IPacketHandler packetHandler, IPacketQueueFactory packetQueueFactory, IMetrics metrics) { _packetQueueFactory = packetQueueFactory; _metrics = metrics; _packetHandler = packetHandler; _packetReaderFactory = packetReaderFactory; _logger = logger; } public override Task OnConnectedAsync(ConnectionContext connection) { _metrics.Measure.Counter.Increment(MetricsRegistry.ActiveConnections); try { return HandleConnection( new MCConnectionContext(connection, _packetQueueFactory.CreateQueue(connection.Transport.Output))); } finally { _metrics.Measure.Counter.Decrement(MetricsRegistry.ActiveConnections); } } private async Task HandleConnection(MCConnectionContext ctx) { var packetQueue = ctx.PacketQueue; while (!ctx.ConnectionClosed.IsCancellationRequested) { var readResult = await ctx.Transport.Input.ReadAsync(ctx.ConnectionClosed); if (readResult.IsCanceled || readResult.IsCompleted) { _logger.LogInformation("Connection Closed"); return; } var buffer = readResult.Buffer; HandlePacket(buffer, ctx, packetQueue); if (packetQueue.NeedsWriting) { packetQueue.WriteQueued(); await ctx.Transport.Output.FlushAsync(); } } } private void HandlePacket(ReadOnlySequence<byte> buffer, MCConnectionContext ctx, IPacketQueue packetQueue) { var reader = _packetReaderFactory.CreateReader(buffer); var length = reader.ReadVarInt(); if (length > reader.Buffer.Length || length < 1 /* 1 = small ID but no fields*/) { _logger.LogCritical($"Read Invalid length {length:X}. Aborting"); ctx.Abort(); return; } var lengthLength = buffer.Length - reader.Buffer.Length; reader = new MCPacketReader(reader.Buffer.Slice(0, length)); var id = reader.ReadVarInt(); using var packetIdScope = _logger.BeginScope($"Packet ID: {id:x2}"); _packetHandler.HandlePacket(ctx, reader, packetQueue, id); // NOT IDEAL, but easiest var packetSize = length + lengthLength; ctx.Transport.Input.AdvanceTo(buffer.GetPosition(packetSize)); _metrics.Measure.Histogram.Update(MetricsRegistry.ReadPacketSize, packetSize); } } }
using System.Collections.Generic; using Edge = System.Tuple<int ,int>; namespace Mediapipe { public class FullBodyPoseLandmarkListAnnotationController : LandmarkListAnnotationController { protected static readonly IList<Edge> _Connections = new List<Edge> { // Right Arm new Edge(11, 13), new Edge(13, 15), // Left Arm new Edge(12, 14), new Edge(14, 16), // Torso new Edge(11, 12), new Edge(12, 24), new Edge(24, 23), new Edge(23, 11), // Right Leg new Edge(23, 25), new Edge(25, 27), new Edge(27, 29), new Edge(29, 31), new Edge(31, 27), // Left Leg new Edge(24, 26), new Edge(26, 28), new Edge(28, 30), new Edge(30, 32), new Edge(32, 28), }; protected override IList<Edge> Connections { get { return _Connections; } } protected override int NodeSize { get { return 33; } } } }
using System; using expense.web.api.Values.Aggregate.Constants; using expense.web.api.Values.Aggregate.Events.Base; using expense.web.api.Values.Aggregate.Model; namespace expense.web.api.Values.Aggregate.Events.Childs.Comment { public class CommentAddedEvent : EventBase { public string UserName { get; set; } public int Dislikes { get; set; } public int Likes { get; set; } public string CommentText { get; set; } public Guid ParentId { get; set; } public CommentAddedEvent() { } public CommentAddedEvent(IValueCommentAggregateChildDataModel model) : base(model, CommentAggConstants.EventType.CommentAdded, typeof(CommentAddedEvent).AssemblyQualifiedName) { this.ParentId = model.ParentId; this.CommentText = model.CommentText; this.Likes = model.Likes; this.Dislikes = model.Dislikes; this.UserName = model.UserName; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using FODT.Models; namespace FODT.Views.Toaster { public class HuntViewModel { public HuntViewModel() { Shows = new List<Show>(); } public List<Show> Shows { get; set; } public class Show { public int ShowId { get; set; } public string ShowName { get; set; } public Quarter ShowQuarter { get; set; } public short ShowYear { get; set; } public string Toaster { get; set; } } } }
using Savvyio.Commands; namespace Savvyio.Assets.Commands { public class UpdateAccount : Command { public UpdateAccount(long id, string fullName, string emailAddress) { Id = id; FullName = fullName; EmailAddress = emailAddress; } public long Id { get; } public string FullName { get; } public string EmailAddress { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Labuladong { public class Code0124 { private static int result = int.MinValue; public static void Exection() { var tree = BaseTree.DefaultTree; Maxpathsum(tree); Console.WriteLine(result); } private static int Maxpathsum(BaseTree tree) { if (tree == null) { return 0; } var left = Math.Max(0, Maxpathsum(tree.Left)); var right = Math.Max(0, Maxpathsum(tree.Right)); result = Math.Max(result, tree.Value + left + right); return Math.Max(left, right) + tree.Value; } } }
using Net.FreeORM.Logic.BaseDal; namespace Net.FreeORM.TestWFA.Source.DL { public class MainDL : MainMySqlDL { public MainDL() : base() { } } }
namespace NServiceBus.Transports.Msmq.Config { /// <summary> /// Runtime settings for the Msmq transport /// </summary> public class MsmqSettings { /// <summary> /// Constructs the settings class with defaults /// </summary> public MsmqSettings() { UseDeadLetterQueue = true; UseConnectionCache = true; UseTransactionalQueues = true; } /// <summary> /// Determines if the dead letter queue should be used /// </summary> public bool UseDeadLetterQueue { get; set; } /// <summary> /// Determines if journaling should be activated /// </summary> public bool UseJournalQueue { get; set; } /// <summary> /// Gets or sets a value that indicates whether a cache of connections will be maintained by the application. /// </summary> public bool UseConnectionCache { get; set; } /// <summary> /// Determines if the system uses transactional queues /// </summary> public bool UseTransactionalQueues { get; set; } } }
using System.Collections; using UnityEngine; public class King : Chessman { public override bool[,] PossibleMoves() { bool[,] r = new bool[8, 8]; // up Move(CurrentX + 1, CurrentY, ref r); // down Move(CurrentX - 1, CurrentY, ref r); // left Move(CurrentX, CurrentY - 1, ref r); // right Move(CurrentX, CurrentY + 1, ref r); // up left Move(CurrentX + 1, CurrentY - 1, ref r); // down left Move(CurrentX - 1, CurrentY - 1, ref r); // up right Move(CurrentX + 1, CurrentY + 1, ref r); // down right Move(CurrentX - 1, CurrentY + 1, ref r); return r; } }
// This file is part of HPGE, an Haptic Plugin for Game Engines // ----------------------------------------- // Software License Agreement (BSD License) // Copyright (c) 2017-2019, // Istituto Italiano di Tecnologia (IIT), All rights reserved. // (iit.it, contact: gabriel.baud-bovy <at> iit.it) // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of HPGE, Istituto Italiano di Tecnologia nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System.IO; using UnityEngine; public class HapticTool : MonoBehaviour { public enum Tick { No, Update, FixedUpdate }; public enum WaitForces { No, Small, Rise }; private bool Started = false; private bool Running = false; [Header("Hardware Info")] /// <summary> /// Show the frequency the haptic loop is running at (Hz) /// </summary> [ReadOnly] public double LoopFrequencyHz = 0.0; // This counts the passed loops and is used to update the // LoopFrequencyHz variable private int LoopNumber = 0; /// <summary> /// Haptic device to use. By default, /// the first it can find (0-based index) /// </summary> public int DeviceId = 0; [InspectorButton("ScanDevices")] public bool Scan; [Header("Tool Properties")] /// <summary> /// If the object has an attached collider and it's a /// sphere collider, use it's radius for the tool /// </summary> public bool UseSphereRadius = true; /// <summary> /// If UseSphereRadius is false, use this value instead /// </summary> public float Radius = 0.5f; public bool EnableDynamicObjects = true; // TODO: a possible implementation of this is to use something like PhysiX maximum velocity /// <summary> /// Don't apply any force until the force to apply is small /// or increase the force gradually at start /// </summary> public WaitForces WaitForForces = WaitForces.Small; /// <summary> /// If this is true, instead of using the real device position, /// uses the proxy to update the tool position and rotation /// </summary> public bool UseProxyPosition = false; [Header("Workspace Properties")] //[ReadOnly] // FIXME: This should be removed! public double WorkspaceSize = 10; // meters [ReadOnly] public Transform HapticWorkspace; // TODO: This would be better if grouped // but it's too much work for now. See // https://forum.unity.com/threads/multiple-bools-in-one-line-in-inspector.181778/ [Header("Logging Options")] public bool EnableLog = false; /// <summary> /// Whether to use unity coordinates or chai3d ones /// </summary> public bool DeviceCoordinates = false; /// <summary> /// How many loops (in the haptic thread) should we save information? /// Its unit depends on the loop frequency, so it's approximately in ms /// </summary> [Range(1,200)] // FIXME: this could even go beyond public int LogDownsampling = 1; /// <summary> /// This log is a csv file created by the library. /// Position relative to the main program /// </summary> public string LogBasename = "output"; // number to append to log file to prevent overwrites private int LogNumber = 0; /// <summary> /// Useful to know how many times the (fixed)update is called. /// If logging is enabled, /// </summary> public Tick EnableTick = Tick.No; /// <summary> /// Filter information and debug messages shown in unity /// </summary> [Header("Debug Settings")] [Range(0,3)] public int Verbosity = 0; // FIXME: still not implemented //bool LogPositions = false; //bool LogVelocity = false; //bool LogForces = false; // FIXME: implement this. We should find all Touchable object, find those that are // enabled, get their id. // The problem is that should happen _before_ the logging starts /// <summary> /// To log interaction forces, each object must have the /// "LogInteractionForces" toggle enabled /// </summary> // bool LogInteractionForces = false; private string GenLogName() { return LogBasename + "." + LogNumber + ".csv"; } public void ScanDevices() { int devices = HapticNativePlugin.count_devices(); // Get all devices names and print them here if (devices < 0) { Debug.LogError(HapticNativePlugin.GetLastErrorMsg()); return; } else if (devices == 0) { Debug.LogError("No devices found!"); return; } else if (devices == 1) { Debug.LogWarning("Only one device found (Probably no real devices attached!)"); } for (int device = -1; device < devices - 1; ++device) { Debug.Log("Found device #" + device + " (" + HapticNativePlugin.GetDeviceName(device) + ")"); CheckCompatibility(); } } public void ForceWorkspaceUpdate() { if (HapticWorkspace != null) { UnityHaptics.SetHapticWorkspace(HapticWorkspace); } } private void CheckCompatibility() { if (!HapticNativePlugin.IsLibraryCompatible()) { Debug.LogError("Library version is incompatible! " + HapticNativePlugin.GetVersionInfo().ToString()); } else { if (Verbosity > 2) { Debug.Log("Haptic Library Version (HGPE) is: " + HapticNativePlugin.GetVersionInfo().ToString()); } } } private void SetWaitForForces() { if (WaitForForces == WaitForces.No) { HapticNativePlugin.disable_wait_for_small_forces(); // HapticNativePlugin.disable_rise_forces(); return; } if (WaitForForces == WaitForces.Small) { HapticNativePlugin.enable_wait_for_small_forces(); } else { Debug.LogWarning("Not checked yet (might not work)"); HapticNativePlugin.enable_rise_forces(); } } private void UpdateToolPositionAndRotation() { // Debug.Log(UnityHaptics.GetToolPosition()); transform.SetPositionAndRotation(UseProxyPosition ? UnityHaptics.GetToolProxyPosition() : UnityHaptics.GetToolPosition(), UnityHaptics.GetToolRotation()); } private void Awake() { CheckCompatibility(); if (UseSphereRadius) { //// This can only render a sphere. //// Warn if attached to something else (maybe they just want to get the input position) if (GetComponent<MeshFilter>().name != "Sphere" && Verbosity > 0) { Debug.LogWarning("This script is not attached to a sphere " + "but you are trying to use the sphere radius. You should" + "instead set the radius manually"); } // The sphere size in unity is 0.5 units. // We use the Transform scale on the X axis to get the real size Radius = transform.lossyScale.x * 0.5f; } SetWaitForForces(); // FIXME: what to do with workspace radius? UnityHaptics.SetUnityWorldCoordinates(); int res = HapticNativePlugin.Initialize(DeviceId, WorkspaceSize, Radius); if (res != HapticNativePlugin.SUCCESS) { // success silently, fail loudly Debug.LogError("Could not start haptics"); UnityHaptics.LogMessage(res, false); return; } // ForceWorkspaceUpdate(); if (EnableDynamicObjects) { HapticNativePlugin.enable_dynamic_objects(); } else { HapticNativePlugin.disable_dynamic_objects(); } // FIXME: move to UnityHaptics, enable things we want to log and so on if (EnableLog && LogDownsampling != 0) { HapticNativePlugin.SetupLogging(LogDownsampling, DeviceCoordinates); } // Set initial position UpdateToolPositionAndRotation(); } private void SaveLogIfLogging() { if (HapticNativePlugin.is_logging() != HapticNativePlugin.SUCCESS) { return; } // Create the file name string LogName; do { LogName = GenLogName(); LogNumber += 1; } while (File.Exists(LogName)); if (HapticNativePlugin.StopLoggingAndSave(LogName)) { if (Verbosity > 0) { Debug.Log(LogName); } } else { // TODO: get error message and print Debug.LogError("Could not save log!"); } } // Use this for initialization void Start() { // FIXME: Not working# //HapticNativePlugin.setHook(HapticNativePlugin.exampleHook); // Update position (if device has been moved between Awake and Start) UpdateToolPositionAndRotation(); } private void OnDestroy() { if ((!HapticNativePlugin.IsInitialized() || !HapticNativePlugin.IsRunning())) { Started = false; return; } int res = HapticNativePlugin.deinitialize(); UnityHaptics.LogMessage(res, true); SaveLogIfLogging(); HapticNativePlugin.stop(); Started = false; Running = false; } // Update is called once per frame private void Update() { //Debug.Log(UnityHaptics.GetToolVelocity()); LoopNumber += 1; if (LoopNumber % 100 == 0) { LoopFrequencyHz = HapticNativePlugin.get_loop_frequency(); if (Verbosity > 1) { Debug.Log(LoopFrequencyHz); } } if (EnableTick == Tick.Update) { HapticNativePlugin.tick(); } if (! Started || ! Running) { int res = HapticNativePlugin.start(); UnityHaptics.LogMessage(res, true); Started = res == HapticNativePlugin.SUCCESS; Running = Started; UpdateToolPositionAndRotation(); } } void FixedUpdate () { if (!Running) { return; } UpdateToolPositionAndRotation(); if (EnableTick == Tick.FixedUpdate) { HapticNativePlugin.tick(); } } }
namespace Microsoft.Azure.Batch.Common { /// <summary> /// The storage account type for use in creating data disks. /// </summary> public enum StorageAccountType { /// <summary> /// The data disk should use standard locally redundant storage. /// </summary> StandardLrs, /// <summary> /// The data disk should use premium locally redundant storage. /// </summary> PremiumLrs } }
 namespace BeatPulse { public class BeatPulseOptionsConfiguration: BeatPulseOptions { public new bool DetailedOutput { get => base.DetailedOutput; set => base.DetailedOutput = value; } public new string Path { get => base.Path; set => base.Path = value; } public new int? Port { get => base.Port; set => base.Port = value; } public new int Timeout { get => base.Timeout; set => base.Timeout = value; } public new int CacheDuration { get => base.CacheDuration; set => base.CacheDuration = value; } public new bool CacheOutput { get => base.CacheOutput; set => base.CacheOutput = value; } public new CacheMode CacheMode { get => base.CacheMode; set => base.CacheMode = value; } public new bool DetailedErrors { get => base.DetailedErrors; set => base.DetailedErrors = value; } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AmbientDbContextConfigurator; using AutoMapper; using Microsoft.EntityFrameworkCore; using StarCommander.Domain; using StarCommander.Domain.Ships; using StarCommander.Shared.Model.Query; namespace StarCommander.Infrastructure.Persistence.Projection.ShipLocations { public class ShipLocationRepository : RepositoryBase<ProjectionDataContext>, IShipLocationRepository { readonly IMapper mapper; public ShipLocationRepository(IAmbientDbContextConfigurator ambientDbContextConfigurator, IMapper mapper) : base(ambientDbContextConfigurator) { this.mapper = mapper; } public async Task Delete(List<ShipLocation> shipLocations) { DataContext.RemoveRange( (await DataContext.ShipLocations.ToListAsync()).Where(a => shipLocations.Any(b => b.HasSamePrimaryKeyAs(a)))); } public async Task Insert(List<ShipLocation> shipLocations) { await DataContext.AddRangeAsync(shipLocations); } public async Task Update(List<ShipLocation> shipLocations) { foreach (var shipLocation in shipLocations) { var entity = (await DataContext.ShipLocations.ToListAsync()).SingleOrDefault(a => a.HasSamePrimaryKeyAs(shipLocation)); if (entity == null) { continue; } mapper.Map(shipLocation, entity); DataContext.Update(entity); } await Task.CompletedTask; } public async Task<IEnumerable<ShipLocation>> Fetch(Reference<Ship> ship) { return await DataContext.ShipLocations.AsNoTracking() .Where(s => s.ShipId == ship.Id) .OrderBy(s => s.ShipLocationId) .ToListAsync(); } public async Task<IEnumerable<ScanResult>> ScanForNearbyShips(Reference<Ship> ship) { //TODO Filter on range... //const long range = 1000; var query = from sl in DataContext.ShipLocations.AsNoTracking() join ol in DataContext.ShipLocations.AsNoTracking() on 1 equals 1 where sl.ShipId == ship.Id where sl.ShipId != ol.ShipId select new ScanResult { X = ol.X - sl.X, Y = ol.Y - sl.Y }; return await query.ToListAsync(); } } }
#region License & Metadata // The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // // Created On: 2018/12/24 02:02 // Modified On: 2019/01/14 15:02 // Modified By: Alexis #endregion using System; using System.Collections.Generic; // ReSharper disable ArrangeRedundantParentheses // ReSharper disable BitwiseOperatorOnEnumWithoutFlags namespace SuperMemoAssistant.Sys { public class Span<T> : Span { #region Constructors public Span() { } public Span(T obj, Span other) : base(other) { Object = obj; } public Span(Span<T> other) : base(other) { Object = other.Object; } public Span(Span other) : base(other) { } public Span(int startIdx, int endIdx) : base(startIdx, endIdx) { } public Span(T obj, int startIdx, int endIdx) : base(startIdx, endIdx) { Object = obj; } #endregion #region Properties & Fields - Public public T Object { get; set; } #endregion #region Methods public static Span<T> operator +(Span<T> span, int n) { return new Span<T>(span.Object, span.StartIdx + n, span.EndIdx + n); } public static Span<T> operator -(Span<T> span, int n) { return new Span<T>(span.Object, span.StartIdx - n, span.EndIdx - n); } public static Span<T> operator +(Span<T> span1, Span span2) { if (span1.Adjacent(span2) == false && span1.Overlaps(span2, out _) == false) throw new ArgumentException("Spans must be adjacent to be merged"); return new Span<T>(span1.Object, Math.Min(span1.StartIdx, span2.StartIdx), Math.Max(span1.EndIdx, span2.EndIdx)); } public bool Overlaps<TOtherSpan, TRetSpan>(TOtherSpan other, out TRetSpan overlap, Func<int, int, Span<T>, TOtherSpan, TRetSpan> selector) where TOtherSpan : Span where TRetSpan : Span { if (StartIdx >= other.StartIdx && StartIdx <= other.EndIdx) { overlap = selector(StartIdx, Math.Min(EndIdx, other.EndIdx), this, other); return true; } if (EndIdx >= other.StartIdx && EndIdx <= other.EndIdx) { overlap = selector(Math.Max(StartIdx, other.StartIdx), EndIdx, this, other); return true; } if (StartIdx <= other.StartIdx && EndIdx >= other.EndIdx) { overlap = selector(other.StartIdx, other.EndIdx, this, other); return true; } overlap = null; return false; } #endregion } public class Span { #region Constructors public Span() { StartIdx = EndIdx = -1; } public Span(Span other) { StartIdx = other.StartIdx; EndIdx = other.EndIdx; } public Span(int startIdx, int endIdx) { StartIdx = startIdx; EndIdx = endIdx; } #endregion #region Properties & Fields - Public public int StartIdx { get; } public int EndIdx { get; } public int Length => EndIdx - StartIdx + 1; #endregion #region Methods Impl public override bool Equals(object obj) { Span other = obj as Span; if (other == null) return false; return StartIdx == other.StartIdx && EndIdx == other.EndIdx; } /// <inheritdoc /> public override int GetHashCode() { unchecked { return (StartIdx * 397) ^ EndIdx; } } #endregion #region Methods public bool Adjacent(Span other) { return StartIdx == other.EndIdx + 1 || EndIdx == other.StartIdx - 1; } public bool Overlaps(Span other, out Span overlap) { if (StartIdx >= other.StartIdx && StartIdx <= other.EndIdx) { overlap = new Span(StartIdx, Math.Min(EndIdx, other.EndIdx)); return true; } if (EndIdx >= other.StartIdx && EndIdx <= other.EndIdx) { overlap = new Span(Math.Max(StartIdx, other.StartIdx), EndIdx); return true; } if (StartIdx <= other.StartIdx && EndIdx >= other.EndIdx) { overlap = new Span(other); return true; } overlap = null; return false; } public bool IsWithin(int idx) => StartIdx <= idx && EndIdx >= idx; public bool IsWithin(Span other) => StartIdx <= other.StartIdx && EndIdx >= other.EndIdx; protected bool Equals(Span other) { return ReferenceEquals(other, null) == false && StartIdx == other.StartIdx && EndIdx == other.EndIdx; } public static bool operator ==(Span span1, Span span2) { return ReferenceEquals(span1, span2) || (span1?.Equals(span2) ?? false); } public static bool operator !=(Span span1, Span span2) { return !(span1 == span2); } public static Span operator +(Span span, int n) { return new Span(span.StartIdx + n, span.EndIdx + n); } public static Span operator -(Span span, int n) { return new Span(span.StartIdx - n, span.EndIdx - n); } public static Span operator +(Span span1, Span span2) { if (span1.Adjacent(span2) == false && span1.Overlaps(span2, out _) == false) throw new ArgumentException("Spans must be adjacent to be merged"); return new Span(Math.Min(span1.StartIdx, span2.StartIdx), Math.Max(span1.EndIdx, span2.EndIdx)); } #endregion public class PositionalComparer : Comparer<Span> { #region Methods Impl public override int Compare(Span x, Span y) { if (x == null) throw new ArgumentNullException(nameof(x)); if (y == null) throw new ArgumentNullException(nameof(y)); return x.IsWithin(y.StartIdx) || y.IsWithin(x.StartIdx) ? 0 : x.StartIdx - y.StartIdx; } #endregion } } }
using System; using System.Threading.Tasks; using NUnit.Framework; using UIForia.DataSource; #pragma warning disable 1998,0649 [TestFixture] public class DataSourceTests { private class TestException : Exception { } private class TestData : IRecord { public string data; public TestData(long id, string data) { Id = id; this.data = data; } public long Id { get; set; } } private class TestAdapter<T> : Adapter<T> where T : class, IRecord { public Action<T> addRecordHandler; public Action<long, T> getRecordHandler; public Func<T, T, bool> recordChanged; public override async Task<T> AddRecord(T record) { addRecordHandler?.Invoke(record); return record; } public override async Task<T> GetRecord(long id, T currentRecord) { getRecordHandler?.Invoke(id, currentRecord); return currentRecord; } public override bool RecordChanged(T a, T b) { if (recordChanged == null) return base.RecordChanged(a, b); return recordChanged.Invoke(a, b); } } // having issues with deadlock, figure this out later // [Test] // public void AddRecord_WaitForAdapterConfig() { // TestAdapterWithConfig<TestData> adapter = new TestAdapterWithConfig<TestData>(); // DataSource<TestData> ds = new DataSource<TestData>(adapter); // TestData data = ds.AddRecord(new TestData(0, "wait")).Result; // Assert.AreEqual(1, adapter.configureCount); // } [Test] public void AddRecord_UseInternalStore() { TestAdapter<TestData> adapter = new TestAdapter<TestData>(); int getCall = 0; adapter.getRecordHandler = (long id, TestData record) => { if (getCall == 0) { Assert.IsNull(record); } else if (getCall == 1) { Assert.AreEqual("hello", record.data); } getCall++; }; DataSource<TestData> ds = new DataSource<TestData>(adapter); TestData d0 = ds.GetRecord(0).Result; Assert.IsNull(d0); Assert.AreEqual(1, getCall); TestData d1 = ds.AddRecord(new TestData(0, "hello")).Result; TestData d2 = ds.GetRecord(0).Result; Assert.AreEqual(2, getCall); } [Test] public void AddRecord_AndGet() { DataSource<TestData> ds = new DataSource<TestData>(); TestData d0 = ds.AddRecord(new TestData(0, "hello")).Result; TestData d1 = ds.AddRecord(new TestData(1, "world")).Result; TestData r0 = ds.GetRecord(0).Result; TestData r1 = ds.GetRecord(1).Result; Assert.AreEqual(r0, d0); Assert.AreEqual(r1, d1); } [Test] public void AddRecord_AddNullReturnsNull() { DataSource<TestData> ds = new DataSource<TestData>(); Assert.IsNull(ds.AddRecord(null).Result); } [Test] public void AddRecord_EmitEventOnRecordAdded() { DataSource<TestData> ds = new DataSource<TestData>(); TestData add0 = null; TestData add1 = null; int addCalls = 0; ds.onRecordAdded += (TestData t) => { if (addCalls == 0) { add0 = t; } else if (addCalls == 1) { add1 = t; } addCalls++; }; TestData d0 = ds.AddRecord(new TestData(0, "hello")).Result; TestData d1 = ds.AddRecord(new TestData(1, "world")).Result; Assert.AreEqual(add0, d0); Assert.AreEqual(add1, d1); Assert.AreEqual(2, addCalls); } [Test] public void AddRecord_AddsLotsOfRecords() { DataSource<TestData> ds = new DataSource<TestData>(); int addCalls = 0; ds.onRecordAdded += (TestData t) => { addCalls++; }; for (int i = 0; i < 100; i++) { TestData result = ds.AddRecord(new TestData(i, i.ToString())).Result; } Assert.AreEqual(100, ds.RecordCount); Assert.AreEqual(100, addCalls); } [Test] public void AddRecord_CanThrowFromAdapter() { var ex = Assert.Throws<AggregateException >(() => { DataSource<TestData> ds = new DataSource<TestData>(); ds.onRecordAdded += (TestData t) => { throw new TestException(); }; TestData result = ds.AddRecord(new TestData(0, "throw")).Result; }); Assert.AreEqual(1, ex.InnerExceptions.Count); Assert.IsInstanceOf<TestException>(ex.InnerExceptions[0]); } // // [Test] // public void UpsertRecord() { // // TestAdapter<TestData> adapter = new TestAdapter<TestData>(); // // adapter.recordChanged = (a, b) => a.data != b.data; // // DataSource<TestData> ds = new DataSource<TestData>(adapter); // // int addCalls = 0; // int changeCalls = 0; // // ds.onRecordAdded += (record) => { addCalls++; }; // ds.onRecordChanged += (record) => { changeCalls++; }; // // TestData result = ds.UpsertRecord(new TestData(0, "value0")).Result; // Assert.AreEqual(1, addCalls); // result = ds.UpsertRecord(new TestData(0, "value1")).Result; // Assert.AreEqual(1, addCalls); // result = ds.GetRecord(0).Result; // Assert.AreEqual("value1", result.data); // Assert.AreEqual(1, changeCalls); // } [Test] public void SetRecord_RemoveIfValueIsNull() { TestAdapter<TestData> adapter = new TestAdapter<TestData>(); adapter.recordChanged = (a, b) => a.data != b.data; int addCount = 0; int changeCount = 0; int removeCount = 0; DataSource<TestData> ds = new DataSource<TestData>(adapter); ds.onRecordAdded += (r) => { addCount++; }; ds.onRecordChanged += (r) => { changeCount++; }; ds.onRecordRemoved += (r) => { removeCount++; }; var result1 = ds.SetRecord(0, new TestData(0, "hello")).Result; Assert.AreEqual(0, removeCount); Assert.AreEqual(0, changeCount); Assert.AreEqual(1, addCount); var result2 = ds.SetRecord(0, null).Result; Assert.AreEqual(1, addCount); Assert.AreEqual(1, removeCount); var result3 = ds.GetRecord(0).Result; Assert.IsNull(result3); } [Test] public void SetRecord_AddRecordToStore() { TestAdapter<TestData> adapter = new TestAdapter<TestData>(); ListRecordStore<TestData> store = new ListRecordStore<TestData>(); DataSource<TestData> ds = new DataSource<TestData>(adapter, store); var result = ds.SetRecord(100, new TestData(100, "data here")).Result; Assert.AreEqual(result, store.GetRecord(100)); } [Test] public void SetRecord_EmitRecordAddedWhenAdded() { TestAdapter<TestData> adapter = new TestAdapter<TestData>(); adapter.recordChanged = (a, b) => a.data != b.data; int addCount = 0; DataSource<TestData> ds = new DataSource<TestData>(adapter); ds.onRecordAdded += (r) => { addCount++; }; var result1 = ds.SetRecord(0, new TestData(0, "hello")).Result; Assert.AreEqual(1, addCount); var result2 = ds.SetRecord(0, new TestData(0, "goodbye")).Result; Assert.AreEqual(1, addCount); } [Test] public void SetRecord_EmitRecordChangedWhenChanged() { TestAdapter<TestData> adapter = new TestAdapter<TestData>(); adapter.recordChanged = (a, b) => a.data != b.data; int changeCount = 0; DataSource<TestData> ds = new DataSource<TestData>(adapter); ds.onRecordChanged += (r) => { changeCount++; }; var result1 = ds.SetRecord(0, new TestData(0, "hello")).Result; Assert.AreEqual(0, changeCount); var result2 = ds.SetRecord(0, new TestData(0, "goodbye")).Result; } [Test] public void SetRecord_EmitRecordRemovedWhenRemoved() { TestAdapter<TestData> adapter = new TestAdapter<TestData>(); adapter.recordChanged = (a, b) => a.data != b.data; int removedCount = 0; DataSource<TestData> ds = new DataSource<TestData>(adapter); ds.onRecordRemoved += (r) => { removedCount++; }; var result1 = ds.SetRecord(0, new TestData(0, "hello")).Result; Assert.AreEqual(0, removedCount); var result2 = ds.SetRecord(0, null); Assert.AreEqual(1, removedCount); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RenderShadowMap : MonoBehaviour { public Shader shadowMapshader; private Material shadowMapMaterial; public RenderTexture depthTexture; void Awake() { shadowMapMaterial = new Material(shadowMapshader); shadowMapMaterial.SetTexture("_LightDepthTex", depthTexture); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnRenderImage(RenderTexture src,RenderTexture dest) { Graphics.Blit(src, dest, shadowMapMaterial); } }
//----------------------------------------------------------------------- // <copyright file="IncidentOrganization.cs" company="EDXLSharp"> // Licensed under Apache 2.0 // </copyright> //----------------------------------------------------------------------- using System; using System.Xml.Serialization; namespace EDXLSharp.NIEMEMLCLib.Incident { /// <summary> /// Represents the organization who owns an incident /// </summary> [Serializable] public class IncidentOrganization { /// <summary> /// Initializes instance of the Incident Organization class /// </summary> public IncidentOrganization() { OrgIDSerialized = new IdentificationID(); IncidentIDSerialized = new IdentificationID(); } /// <summary> /// Gets or sets the status of this incident /// </summary> [XmlElement(ElementName = "OrganizationIdentification", Namespace = Constants.NiemcoreNamespace)] public IdentificationID OrgIDSerialized { get; set; } /// <summary> /// Gets of sets the organization's id /// </summary> [XmlIgnore] public string OrgID { get { return OrgIDSerialized != null ? OrgIDSerialized.ID : ""; } set { if (this.OrgIDSerialized == null) { this.OrgIDSerialized = new IdentificationID(value); } else { this.OrgIDSerialized.ID = value; } } } /// <summary> /// Gets or sets the owning organization for this incident /// Optional Element /// </summary> [XmlElement(ElementName = "IncidentIdentifier")] public IdentificationID IncidentIDSerialized { get; set; } /// <summary> /// Gets or sets the organization's id for this resource /// </summary> [XmlIgnore] public string IncidentID { get { return IncidentIDSerialized != null ? IncidentIDSerialized.ID : ""; } set { if (this.IncidentIDSerialized == null) { this.IncidentIDSerialized = new IdentificationID(value); } else { this.IncidentIDSerialized.ID = value; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.IO; using Microsoft.Test.CommandLineParsing; using System; namespace Microsoft.Test.Commands { /// <summary/> [Description("Merges results from a set of parallel test executions.")] public class MergeResultsCommand : Command { /// <summary> /// RunDirectory points to the directory where the TestCollection files are stored. /// </summary> [Description("Centralized directory where run data is stored.")] [Required()] public DirectoryInfo RunDirectory { get; set; } /// <summary> /// Enables CodeCoverage when set true. /// </summary> [Description("Enables CodeCoverage when set true")] public bool CodeCoverage { get; set; } /// <summary> /// Specifies database connection string with quotes. Required when doing CC runs. /// </summary> [Description("Specifies database connection string with quotes. Required when doing CC runs.")] public string CodeCoverageImport { get; set; } /// <summary> /// Encapsulates logic of merging results. /// </summary> public override void Execute() { CodeCoverageUtilities.ValidateForCodeCoverage(CodeCoverage, CodeCoverageImport); TestRecords.Merge(RunDirectory, CodeCoverage, CodeCoverageImport); //Record the lab Run information at this stage. We assume homogeneous configuration. RunInfo.FromEnvironment().Save(RunDirectory); } } }
// Automatically generated by xdrgen // DO NOT EDIT or your changes may be overwritten using System; namespace stellar_dotnet_sdk.xdr { // === xdr source ============================================================ // struct ManageSellOfferOp // { // Asset selling; // Asset buying; // int64 amount; // amount being sold. if set to 0, delete the offer // Price price; // price of thing being sold in terms of what you are buying // // // 0=create a new offer, otherwise edit an existing offer // int64 offerID; // }; // =========================================================================== public class ManageSellOfferOp { public ManageSellOfferOp() { } public Asset Selling { get; set; } public Asset Buying { get; set; } public Int64 Amount { get; set; } public Price Price { get; set; } public Int64 OfferID { get; set; } public static void Encode(XdrDataOutputStream stream, ManageSellOfferOp encodedManageSellOfferOp) { Asset.Encode(stream, encodedManageSellOfferOp.Selling); Asset.Encode(stream, encodedManageSellOfferOp.Buying); Int64.Encode(stream, encodedManageSellOfferOp.Amount); Price.Encode(stream, encodedManageSellOfferOp.Price); Int64.Encode(stream, encodedManageSellOfferOp.OfferID); } public static ManageSellOfferOp Decode(XdrDataInputStream stream) { ManageSellOfferOp decodedManageSellOfferOp = new ManageSellOfferOp(); decodedManageSellOfferOp.Selling = Asset.Decode(stream); decodedManageSellOfferOp.Buying = Asset.Decode(stream); decodedManageSellOfferOp.Amount = Int64.Decode(stream); decodedManageSellOfferOp.Price = Price.Decode(stream); decodedManageSellOfferOp.OfferID = Int64.Decode(stream); return decodedManageSellOfferOp; } } }
using UnityEngine; namespace Demonixis.Toolbox.VR { public sealed class OSVRManager : MonoBehaviour { void Awake() { if (!GameVRSettings.HasOSVRHMDEnabled(true)) { DestroyImmediate(GetComponent<OSVR.Unity.DisplayController>()); DestroyImmediate(GetComponentInChildren<OSVR.Unity.VRViewer>()); DestroyImmediate(this); } } } }