content
stringlengths
23
1.05M
 namespace FastAndFurious.ConsoleApplication.Models.MotorVehicles { using FastAndFurious.ConsoleApplication.Models.MotorVehicles.Abstract; /// <summary> /// 45999,1850000,280,50 /// </summary> public class NissanSkylineR34 : MotorVehicle { public NissanSkylineR34() : base(45999, 1850000, 280, 50) { } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace System { using System.Globalization; // A Version object contains four hierarchical numeric components: major, minor, // revision and build. Revision and build may be unspecified, which is represented // internally as a -1. By definition, an unspecified component matches anything // (both unspecified and specified), and an unspecified component is "less than" any // specified component. public sealed class Version // : ICloneable, IComparable, IComparable<Version>, IEquatable<Version> { // AssemblyName depends on the order staying the same private int m_major; private int m_minor; private int m_build; // = -1; private int m_revision; // = -1; //--// public static bool operator==( Version v1, Version v2 ) { if(object.ReferenceEquals( v1, null )) { return object.ReferenceEquals( v2, null ); } return v1.Equals( v2 ); } public static bool operator !=( Version v1, Version v2 ) { return !( v1 == v2 ); } public static bool operator >( Version v1, Version v2 ) { return v2 < v1; } public static bool operator >=( Version v1, Version v2 ) { return v2 <= v1; } public static bool operator <( Version v1, Version v2 ) { if(v1 == null) { throw new ArgumentNullException( "v1" ); } return v1.CompareTo( v2 ) < 0; } public static bool operator <=( Version v1, Version v2 ) { if(v1 == null) { throw new ArgumentNullException( "v1" ); } return v1.CompareTo( v2 ) <= 0; } //--// public Version(int major, int minor, int build, int revision) { if(major < 0 || minor < 0 || revision < 0 || build < 0) throw new ArgumentOutOfRangeException( ); m_major = major; m_minor = minor; m_revision = revision; m_build = build; } public Version(int major, int minor) { if (major < 0) throw new ArgumentOutOfRangeException(); if (minor < 0) throw new ArgumentOutOfRangeException(); m_major = major; m_minor = minor; // Other 2 initialize to -1 as it done on desktop and CE m_build = -1; m_revision = -1; } // Properties for setting and getting version numbers public int Major { get { return m_major; } } public int Minor { get { return m_minor; } } public int Revision { get { return m_revision; } } public int Build { get { return m_build; } } public override bool Equals(Object obj) { if(((Object)obj == null ) || ( !( obj is Version ) )) { return false; } Version v = (Version)obj; // check that major, minor, build & revision numbers match if( ( this.m_major != v.m_major ) || ( this.m_minor != v.m_minor ) || ( this.m_build != v.m_build ) || ( this.m_revision != v.m_revision )) { return false; } return true; } public int CompareTo( Version value ) { if(value == null) { return 1; } if(this.m_major != value.m_major) { if(this.m_major > value.m_major) { return 1; } return -1; } else if(this.m_minor != value.m_minor) { if(this.m_minor > value.m_minor) { return 1; } return -1; } else if(this.m_build != value.m_build) { if(this.m_build > value.m_build) { return 1; } return -1; } else { if(this.m_revision == value.m_revision) { return 0; } if(this.m_revision > value.m_revision) { return 1; } return -1; } } public override int GetHashCode( ) { return 0 | (this.m_major & 15) << 28 | (this.m_minor & 255) << 20 | (this.m_build & 255) << 12 | (this.m_revision & 4095); } public override String ToString() { string retStr = m_major + "." + m_minor; // Adds m_build and then m_revision if they are positive. They could be -1 in this case not added. if (m_build >= 0) { retStr += "." + m_build; if (m_revision >= 0) { retStr += "." + m_revision; } } return retStr; } } }
using System; using Microsoft.EntityFrameworkCore; namespace BeaverLeague.Tests.Data { public class DbInstance<T> where T : DbContext { private readonly Func<DbContextOptions<T>, T> factory; public DbInstance(string name, Func<DbContextOptions<T>, T> factory) { Name = name; this.factory = factory; } public string Name { get; } public T NewContext() { var options = new DbContextOptionsBuilder<T>() .UseInMemoryDatabase(Name) .Options; return factory(options); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ACE_2D_Base.Vectors; namespace ACE_lib.Args { public class OnModifiedArgs<T> : EventArgs { public T ValueAt { get; set; } public Vec2i Index { get; set; } } }
using UnityEngine; using UnityEngine.AI; public class NavMeshAgentRandomMove : MonoBehaviour { private NavMeshAgent agent; private Animator anim; public float wanderRange = 10f; // Start is called before the first frame update void Start() { agent = GetComponent<NavMeshAgent>(); anim = GetComponent<Animator>(); if (!agent) enabled = false; } // Update is called once per frame void Update() { if (Vector3.Distance(transform.position, agent.destination) < 0.5f) { Random.InitState((int)Time.time + gameObject.GetHashCode()); var target = Random.insideUnitSphere * wanderRange; target.y = 0; NavMeshHit hit; if(NavMesh.SamplePosition(target, out hit, 1f, NavMesh.AllAreas)) agent.destination = hit.position; } anim.SetFloat("speed", agent.velocity.magnitude); } }
// DialogManager.cs // Administrator using System; using UnityEngine; public class DialogManager { private static T create<T>() { var prefab = Resources.Load<GameObject> ("Prefabs/"+typeof(T)); GameObject self = GameObject.Instantiate(prefab) as GameObject; return self.GetComponent<T>(); } public static T Show<T>(){ return create<T> (); } }
using System; /* * http://www.ietf.org/rfc/rfc2845.txt * * Field Name Data Type Notes -------------------------------------------------------------- Algorithm Name domain-name Name of the algorithm in domain name syntax. Time Signed u_int48_t seconds since 1-Jan-70 UTC. Fudge u_int16_t seconds of error permitted in Time Signed. MAC Size u_int16_t number of octets in MAC. MAC octet stream defined by Algorithm Name. Original ID u_int16_t original message ID Error u_int16_t expanded RCODE covering TSIG processing. Other Len u_int16_t length, in octets, of Other Data. Other Data octet stream empty unless Error == BADTIME */ namespace Resolution.Protocol.Records { public class RecordTsig : Record { public string Algorithmname; public long Timesigned; public UInt16 Fudge; public UInt16 Macsize; public byte[] Mac; public UInt16 Originalid; public UInt16 Error; public UInt16 Otherlen; public byte[] Otherdata; public RecordTsig(RecordReader rr) { Algorithmname = rr.ReadDomainName(); Timesigned = rr.ReadUInt32() << 32 | rr.ReadUInt32(); Fudge = rr.ReadUInt16(); Macsize = rr.ReadUInt16(); Mac = rr.ReadBytes(Macsize); Originalid = rr.ReadUInt16(); Error = rr.ReadUInt16(); Otherlen = rr.ReadUInt16(); Otherdata = rr.ReadBytes(Otherlen); } public override string ToString() { DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(Timesigned); string printDate = dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString(); return $"{Algorithmname} {printDate} {Fudge} {Originalid} {Error}"; } } }
#region using using System.Collections; using System.Collections.Generic; using System.Data; using HBD.Framework.Core; #endregion namespace HBD.Framework.Data.GetSetters { #if !NETSTANDARD1_6 internal class DataRowGetSetter : IGetSetter { public DataRowGetSetter(DataRow row) { Guard.ArgumentIsNotNull(row, nameof(row)); OrginalRow = row; } public DataRow OrginalRow { get; } public int Count => OrginalRow.ItemArray.Length; public object this[string name] { get => OrginalRow[name]; set => OrginalRow[name] = value; } public object this[int index] { get => OrginalRow[index]; set => OrginalRow[index] = value; } public IEnumerator<object> GetEnumerator() => ((IEnumerable<object>) OrginalRow.ItemArray).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } #endif }
using OSIsoft.PIDevClub.PIWebApiClient; using OSIsoft.PIDevClub.PIWebApiClient.Model; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; namespace DemoWithClientLibForChannels { class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Yellow; ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; PIWebApiClient client = new PIWebApiClient("https://localhost/piwebapi", true); PIPoint point1 = client.Point.GetByPath("\\\\SATURN-MARCOS\\sinusoid"); PIPoint point2 = client.Point.GetByPath("\\\\SATURN-MARCOS\\sinusoidu"); PIPoint point3 = client.Point.GetByPath("\\\\SATURN-MARCOS\\cdt158"); List<string> webIds = new List<string>() { point1.WebId, point2.WebId, point3.WebId }; //Example 10 - PI Web API Channels - StartStreamSets CancellationTokenSource cancellationSource = new CancellationTokenSource(); IObserver<PIItemsStreamValues> observer = new CustomChannelObserver(); Task channelTask = client.Channel.StartStreamSets(webIds, observer, cancellationSource.Token); System.Threading.Thread.Sleep(120000); cancellationSource.Cancel(); channelTask.Wait(); } } }
using IIUWr.Fereol.Interface; using IIUWr.Fereol.Model; using IIUWr.ViewModels.Interfaces; using LionCub.Patterns.DependencyInjection; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; namespace IIUWr.ViewModels.Fereol { public class SemesterViewModel : IRefreshable, INotifyPropertyChanged { private readonly ICoursesService _coursesService; public SemesterViewModel(IIUWr.Fereol.WebAPI.Interface.ICoursesService coursesService) { _coursesService = coursesService; } public event PropertyChangedEventHandler PropertyChanged; private ObservableCollection<CourseViewModel> _courses = new ObservableCollection<CourseViewModel>(); public ObservableCollection<CourseViewModel> Courses { get { return _courses; } private set { if (_courses != value) { _courses = value; PropertyChanged.Notify(this); } } } private CourseViewModel _selectedCourse; public CourseViewModel SelectedCourse { get { return _selectedCourse; } set { if (_selectedCourse != value) { _selectedCourse = value; PropertyChanged.Notify(this); } } } private Semester _semester; public Semester Semester { get { return _semester; } set { if (_semester != value) { _semester = value; PropertyChanged.Notify(this); } } } private bool _isRefreshing; public bool IsRefreshing { get { return _isRefreshing; } private set { if (_isRefreshing != value) { _isRefreshing = value; PropertyChanged.Notify(this); } } } public async void Refresh() { IsRefreshing = true; var result = await _coursesService.GetCourses(Semester); if (result != null) { foreach (Course course in result) { var courseVM = Courses.FirstOrDefault(vm => vm.Course == course); if (courseVM == null) { courseVM = IoC.Get<CourseViewModel>(); Courses.Add(courseVM); } courseVM.Course = course; } } IsRefreshing = false; } } }
using System.IO; namespace LSLib.LS.Story { public abstract class QueryNode : Node { public override void MakeScript(TextWriter writer, Story story, Tuple tuple, bool printTypes) { writer.Write("{0}(", Name); tuple.MakeScript(writer, story, printTypes); writer.WriteLine(")"); } } public class DivQueryNode : QueryNode { public override Type NodeType() { return Type.DivQuery; } public override string TypeName() { return "Div Query"; } } public class InternalQueryNode : QueryNode { public override Type NodeType() { return Type.InternalQuery; } public override string TypeName() { return "Internal Query"; } } public class UserQueryNode : QueryNode { public override Type NodeType() { return Type.UserQuery; } public override string TypeName() { return "User Query"; } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using BusinessServices.Services; using MediatR; using Domain; namespace BusinessServices.Modules.ParentModule { public class GetAllParentsHandler : IRequestHandler<GetAllParentsQuery, IEnumerable<Parent>> { private readonly ParentService parentService; public GetAllParentsHandler(ParentService parentService) { this.parentService=parentService; } public async Task<IEnumerable<Parent>> Handle(GetAllParentsQuery request, CancellationToken cancellationToken) { return await this.parentService.FindAllAsync(); } } }
using System.Threading.Tasks; namespace Aurora.Services.Tenants.Demos { public class DemoAppService : AuroraTenantAppService, IDemoAppService { public Task TestAsync() { return Task.CompletedTask; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Shouldly; using System; using System.Collections; namespace Mapster.Tests { [TestClass] public class WhenMappingIEnumerableClasses { public class ClassA { public int Id { get; set; } } public class ClassB : IEnumerable { public int Id { get; set; } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } [TestMethod] public void Map_To_IEnumerable_Class_Should_Pass() { ClassA classA = new ClassA() { Id = 123 }; ClassB classB = classA.Adapt<ClassB>(); classB.Id.ShouldBe(classA.Id); } } }
using FluentAssertions; using System; using Xunit; public sealed class StartupTaskRegistryTests { [Fact] public void ShouldAddRegistration() { // Arrange var registry = new StartupTaskRegistry(); var type = typeof(EmptyStartupTask); var isParallel = true; var registration = new StartupTaskTypedRegistration<EmptyStartupTask>(isParallel); // Act registry.AddRegistration(registration); // Assert registry.GetAll().Should().Contain(registration); registry.GetAll().Should() .ContainSingle("because we added one registration") .And.Subject.Should().Contain(registration); } [Fact] public void ShouldThrowIfRegistrationIsNull() { // Arrange var registry = new StartupTaskRegistry(); var registration = (IStartupTaskRegistration)null; // Act Action action = () => registry.AddRegistration(registration); // Assert action.Should().Throw<ArgumentNullException>("because we expected a null registration to throw"); } [Fact] public void ShouldNotAddDuplicateRegistration() { // Arrange var registry = new StartupTaskRegistry(); // Act registry.AddRegistration(new StartupTaskTypedRegistration<EmptyStartupTask>(true)); registry.AddRegistration(new StartupTaskTypedRegistration<EmptyStartupTask>(true)); // Assert registry.GetAll().Should().ContainSingle("because we added a duplicate registration"); } }
using FluentValidation; namespace Mangala.Application.Commands.PlayerMove { public class PlayerMoveCommandValidator : AbstractValidator<PlayerMoveCommand> { public PlayerMoveCommandValidator() { RuleFor(r => r.Input) .Must(IsInputValid) .WithMessage("Your input must be between 1 and 6"); } private bool IsInputValid(int input) => input <= 6 && input > 0; } }
using System; using System.Collections.Generic; using System.Text; namespace CFX.Structures.SolderPasteInspection { /// <summary> /// <para>** NOTE: ADDED in CFX 1.3 **</para> /// A class to represent the expected measurement results of an inspection process. /// This information is tranferred within the Recipe. /// Typical example: solder paste inspection (SPI) expected values for the different dimensions /// </summary> [CFX.Utilities.CreatedVersion("1.3")] public class InspectionMeasurementExpected : Measurement { /// <summary> /// The expected or nominal dimension (length) of the inspection object, expressed in millimeters (mm). /// </summary> public double EX { get; set; } /// <summary> /// The expected or nominal dimension (length) of the inspection object, expressed in millimeters (mm). /// </summary> public double EY { get; set; } /// <summary> /// The expected or nominal height of the inspection object, expressed in millimeters (mm). /// This value conforms to the stencil thickness on the position where the aperture is located /// </summary> public double EZ { get; set; } /// <summary> /// The expected or nominal X position of the inspection object, expressed in millimeters (mm). /// </summary> public double PX { get; set; } /// <summary> /// The expected or nominal Y position of the inspection object, expressed in millimeters (mm). /// </summary> public double PY { get; set; } /// <summary> /// The expected area of the inspection object, expressed in square millimeters /// </summary> public double EA { get; set; } /// <summary> /// The expected or nominal volume of the inspection object, expressed in milliliters (ml) /// </summary> public double EVol { get; set; } /// <summary> /// Area Ratio of the related Aperture (Area/WallArea) /// </summary> public double AR { get; set; } /// <summary> /// Rotation related information /// The counter-clockwise rotational offset on the X-Y plane (in degrees) /// This information is optional, if not available the angles are supposed to be zero /// </summary> public double? RXY { get; set; } /// <summary> /// Optional: List of vertices in case of a polygon shape (segments in CFX terms) /// </summary> public List<Segment> Vertices { get; set; } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Squidex.Areas.Api.Controllers.Users.Models; using Squidex.Domain.Users; using Squidex.Infrastructure; using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.Translations; using Squidex.Shared; using Squidex.Web; namespace Squidex.Areas.Api.Controllers.Users { [ApiModelValidation(true)] public sealed class UserManagementController : ApiController { private readonly IUserService userService; public UserManagementController(ICommandBus commandBus, IUserService userService) : base(commandBus) { this.userService = userService; } [HttpGet] [Route("user-management/")] [ProducesResponseType(typeof(UsersDto), StatusCodes.Status200OK)] [ApiPermission(Permissions.AdminUsersRead)] public async Task<IActionResult> GetUsers([FromQuery] string? query = null, [FromQuery] int skip = 0, [FromQuery] int take = 10) { var users = await userService.QueryAsync(query, take, skip, HttpContext.RequestAborted); var response = UsersDto.FromResults(users, users.Total, Resources); return Ok(response); } [HttpGet] [Route("user-management/{id}/")] [ProducesResponseType(typeof(UserDto), 201)] [ApiPermission(Permissions.AdminUsersRead)] public async Task<IActionResult> GetUser(string id) { var user = await userService.FindByIdAsync(id, HttpContext.RequestAborted); if (user == null) { return NotFound(); } var response = UserDto.FromUser(user, Resources); return Ok(response); } [HttpPost] [Route("user-management/")] [ProducesResponseType(typeof(UserDto), 201)] [ApiPermission(Permissions.AdminUsersCreate)] public async Task<IActionResult> PostUser([FromBody] CreateUserDto request) { var user = await userService.CreateAsync(request.Email, request.ToValues(), ct: HttpContext.RequestAborted); var response = UserDto.FromUser(user, Resources); return Ok(response); } [HttpPut] [Route("user-management/{id}/")] [ProducesResponseType(typeof(UserDto), 201)] [ApiPermission(Permissions.AdminUsersUpdate)] public async Task<IActionResult> PutUser(string id, [FromBody] UpdateUserDto request) { var user = await userService.UpdateAsync(id, request.ToValues(), ct: HttpContext.RequestAborted); var response = UserDto.FromUser(user, Resources); return Ok(response); } [HttpPut] [Route("user-management/{id}/lock/")] [ProducesResponseType(typeof(UserDto), 201)] [ApiPermission(Permissions.AdminUsersLock)] public async Task<IActionResult> LockUser(string id) { if (this.IsUser(id)) { throw new DomainForbiddenException(T.Get("users.lockYourselfError")); } var user = await userService.LockAsync(id, HttpContext.RequestAborted); var response = UserDto.FromUser(user, Resources); return Ok(response); } [HttpPut] [Route("user-management/{id}/unlock/")] [ProducesResponseType(typeof(UserDto), 201)] [ApiPermission(Permissions.AdminUsersUnlock)] public async Task<IActionResult> UnlockUser(string id) { if (this.IsUser(id)) { throw new DomainForbiddenException(T.Get("users.unlockYourselfError")); } var user = await userService.UnlockAsync(id, HttpContext.RequestAborted); var response = UserDto.FromUser(user, Resources); return Ok(response); } [HttpDelete] [Route("user-management/{id}/")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ApiPermission(Permissions.AdminUsersUnlock)] public async Task<IActionResult> DeleteUser(string id) { if (this.IsUser(id)) { throw new DomainForbiddenException(T.Get("users.deleteYourselfError")); } await userService.DeleteAsync(id, HttpContext.RequestAborted); return NoContent(); } } }
@using HairSalon.Models; @{ Layout = "_Layout"; } <h1> We are happy to welcome you at our Hair Salon</h1> <h2>Please enter client information.</h2> <form action='/clients/new?stylistId=@Context.Request.Query["stylistId"]' method='post'> <label for='name'>Enter client name:</label> <input id='name' name='name' type='text'> <button type='submit'>Add client</button> </form> <p><a href='/'>Return to Main Page</a></p>
using System; using System.Collections.Generic; using System.IO; namespace DeltaEngine.Editor.Core { public class SolutionFileLoader { public SolutionFileLoader(string solutionFilePath) { solutionContentLines = File.Exists(solutionFilePath) ? File.ReadAllLines(solutionFilePath) : new string[0]; LoadProjectEntries(); } private readonly string[] solutionContentLines; private void LoadProjectEntries() { ProjectEntries = new List<ProjectEntry>(); const string ProjectIdentifier = "Project("; foreach (string contentLine in solutionContentLines) if (contentLine.StartsWith(ProjectIdentifier)) ProjectEntries.Add(new ProjectEntry(contentLine)); } public List<ProjectEntry> ProjectEntries { get; private set; } public List<ProjectEntry> GetCSharpProjects() { var foundProjects = new List<ProjectEntry>(); foreach (var entry in ProjectEntries) if (entry.IsCSharpProject) foundProjects.Add(entry); return foundProjects; } public List<ProjectEntry> GetSolutionFolders() { var foundFolders = new List<ProjectEntry>(); foreach (var entry in ProjectEntries) if (entry.IsSolutionFolder) foundFolders.Add(entry); return foundFolders; } public ProjectEntry GetCSharpProject(string projectNameOfSolution) { foreach (var project in GetCSharpProjects()) if (project.Name == projectNameOfSolution) return project; throw new ProjectNotFoundInSolution(projectNameOfSolution); } public class ProjectNotFoundInSolution : Exception { public ProjectNotFoundInSolution(string projectName) : base(projectName) {} } } }
namespace Pluton.Events { public class CraftEvent : CountedInstance { /// <summary> /// The Player who started crafting. /// </summary> public Player Crafter; /// <summary> /// Item.Definition of the target item. /// </summary> public ItemDefinition Target; /// <summary> /// The ItemCrafter object. /// </summary> public ItemCrafter itemCrafter; /// <summary> /// The blueprint. /// </summary> public ItemBlueprint bluePrint; /// <summary> /// Amount of crafting item. /// </summary> public int Amount; /// <summary> /// Cancels teh event. /// </summary> public bool Cancel = false; /// <summary> /// Notify the Crafter about the action. /// </summary> public string cancelReason = System.String.Empty; public int SkinID; public CraftEvent(ItemCrafter self, ItemBlueprint bp, BasePlayer owner, ProtoBuf.Item.InstanceData instanceData, int amount, int skinid) { Crafter = Server.GetPlayer(owner); Target = bp.targetItem; itemCrafter = self; Amount = amount; bluePrint = bp; SkinID = skinid; } public void Stop(string reason = "A plugin stops you from crafting that!") { cancelReason = reason; Cancel = true; } /// <summary> /// Gets or sets the time needed to craft this item. NOTE: this is saved for each blueprint, so CraftTime /= 2; will make instacraft eventually. Be careful! /// </summary> /// <value>The craft time.</value> public float CraftTime { get { return bluePrint.time; } set { bluePrint.time = value; } } } }
using System.Collections.Generic; namespace umamusumeKeyCtl.CaptureScene { public class ScrapSetting { private List<ScrapInfo> _scrapInfos; public List<ScrapInfo> ScrapInfos => _scrapInfos; public ScrapSetting(List<ScrapInfo> scrapInfos) { _scrapInfos = scrapInfos; } } }
using GitHub.Shared.ViewModels; namespace GitHub.Authentication.Test.Validation { public class ValidatableTestObject : ViewModel { private string _someStringProperty; public string SomeStringProperty { get { return _someStringProperty; } set { _someStringProperty = value; RaisePropertyChangedEvent(nameof(SomeStringProperty)); } } private string _anotherStringProperty; public string AnotherStringProperty { get { return _anotherStringProperty; } set { _anotherStringProperty = value; RaisePropertyChangedEvent(nameof(AnotherStringProperty)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Windows.Forms; namespace vuRemote { class RemoteSender { private string vBaseURL; public RemoteSender() { IniFile lIni = new IniFile(); var lip = lIni.Read("IP","Receiver"); vBaseURL = "http://" + lip + ":80/api/remotecontrol?"; } public void SendCode(string ACode, Boolean blong) { string sendUrl = vBaseURL; if (blong){ sendUrl += "type=long&";} Uri lUri = new Uri(sendUrl + "command=" + ACode); WebRequest vRequest; vRequest = WebRequest.Create(lUri); //vRequest.Credentials = CredentialCache.DefaultCredentials; ((HttpWebRequest)vRequest).UserAgent = "Eigenbau"; vRequest.Method = "GET"; //lrequest.ContentLength = byteArray.Length; vRequest.ContentType = "text/html"; //Stream ldataStream = lrequest.GetRequestStream(); // Set the 'Timeout' property in Milliseconds. vRequest.Timeout = 3000; try { // Get the response. WebResponse lResponse = vRequest.GetResponse(); lResponse.Close(); lResponse = null; } catch { //Timeout abfangen MessageBox.Show("Request timed out"); } } } }
using GDPR_Chatbot.data; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; namespace GDPR_Chatbot.Dialogs { [Serializable] public class NoContextQuestionDialog : IDialog<IMessageActivity> { private string intent; public NoContextQuestionDialog(string intent) { this.intent = intent; } public Task StartAsync(IDialogContext context) { context.Wait(this.MessageReceivedAsync); return Task.CompletedTask; } private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result) { using (data.ConversationDataContext dataContext = new data.ConversationDataContext()) { Answer answer = dataContext.Answers .Where(x => x.Intent.Name == this.intent) .SingleOrDefault(); await context.PostAsync(answer.AnswerText); Microsoft.Bot.Connector.Activity activity = new Microsoft.Bot.Connector.Activity(); activity.Text = answer.AnswerText; context.Done(activity); } } } }
using System; namespace com.spacepuppy.Tween { public enum TweenWrapMode { Once = 0, Loop = 1, PingPong = 2 } [Flags()] public enum StringTweenStyle { Default = 0, LeftToRight = 0, RightToLeft = 1, Jumble = 2, LeftToRightJumble = 2, RightToLeftJumble = 3 } public enum QuaternionTweenOption { Spherical, Linear, /// <summary> /// Rotate full rotation. So if you pass in values 0,0,0 -> 0,720,0 /// it will rotate the full 720 degrees. /// </summary> Long } }
using Afonsoft.Petz.Controller; using Afonsoft.Petz.Model; using System; using System.Linq; namespace Afonsoft.Petz.Store { public partial class ClientsPage : PageBaseSecurity { public ClientEntity[] ListClientEntities { get { return Session["Clients"] as ClientEntity[]; } set { Session["Clients"] = value; } } protected void Page_Load(object sender, EventArgs e) { var store = (Store) (Page.Master); store.ChangeActiveMenu("clients"); if (UsuarioLogado == null) return; if (!IsPostBack) { ListClientEntities = null; PopularClientes(); if (Request.QueryString["ID"] != null) { int clientId = Convert.ToInt32(Request.QueryString["ID"]); var infoClient = ListClientEntities.FirstOrDefault(x => x.Id == clientId); if (infoClient != null) { ModalAjax("Cliente - " + infoClient.Name, "/Store/ClientDetail.aspx?ID=" + clientId); } } } } private void PopularClientes() { if (CompanyId > 0) { CompaniesController controller = new CompaniesController(); ListClientEntities = controller.GetCompanyClient(CompanyId); rptClientEntities.DataSource = ListClientEntities; rptClientEntities.DataBind(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms.DataVisualization.Charting; namespace MainModule.Signals { class SingleToneSignal : ISignal { Harmonic harmonic; double LeftBorder=-1, RightBorder=1; double Step=0.1; double FreqSpan = 0; double PhaseSpan = 0; const int PointOnPeriod = 100; const SeriesChartType oscType = SeriesChartType.Spline; const SeriesChartType ampSpecType = SeriesChartType.Point; const SeriesChartType phaseSpecType = SeriesChartType.Point; public SingleToneSignal(Harmonic harmonic) { this.harmonic = harmonic; double PeriodToTime = (1 * 2 * Math.PI) / harmonic.Freq; Step = PeriodToTime / PointOnPeriod; LeftBorder = PeriodToTime / -2; RightBorder = PeriodToTime / 2; } public CoordPair DrawOsc() { List<double> x = new List<double>(); List<double> y = new List<double>(); double CurrentPoint = LeftBorder; while (CurrentPoint <= RightBorder) { y.Add(CalcPoint(CurrentPoint)); x.Add(CurrentPoint); CurrentPoint += Step; } return new CoordPair(x, y); } public void SetPeriods(int periods) { double PeriodToTime = (periods * 2 * Math.PI) / harmonic.Freq; LeftBorder = PeriodToTime / -2; RightBorder = PeriodToTime / 2; } public void SetBorders(double left, double right) { LeftBorder = left; RightBorder = right; } private double CalcPoint(double t, double StartPhase = 0) { return harmonic.Amp * Math.Cos(harmonic.Freq * t + harmonic.StaPhase + StartPhase); } //линия V0 на F0 public CoordPair DrawAmpSpec() { List<double> x = new List<double>(); List<double> y = new List<double>(); x.Add(harmonic.Freq); y.Add(harmonic.Amp); return new CoordPair(x, y); } public void SetFreqSpan(double hz) { FreqSpan = hz; } public CoordPair DrawPhaSpec() { List<double> x = new List<double>(); List<double> y = new List<double>(); x.Add(harmonic.Freq); y.Add(harmonic.StaPhase); return new CoordPair(x, y); } public void SetPhaseSpan(double hz) { PhaseSpan = hz; } SeriesChartType ISignal.OscType() => oscType; SeriesChartType ISignal.AmpSpecType() => ampSpecType; SeriesChartType ISignal.PhaseSpecType() => phaseSpecType; public Pair<double, double> SpecBorders() { return new Pair<double, double>(0, 0); } } }
using System; using System.IO; using System.Text; using System.Text.Json; using Microsoft.VisualBasic.FileIO; namespace csv_table { class Program { static void Main(string[] args) { // Shift_JISを扱う為 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); StreamReader FileStreamObj; StreamReader CsvFileStreamObj; StreamWriter OutPutCsvFileObj; Encoding FileEncordObj; Encoding InputFileEncordObj; Encoding OutputFileEncordObj; // 引数取得 string JsonFilePath = args[0]; string FileEncoding = args[1]; string InputCsvFilePath = args[2]; string InputCsvFileEncode = args[3]; string OutputCsvFilePath = args[4]; string OutputCsvFileEncode = args[5]; string JsonConfigText = ""; string OutputText = ""; // 文字コードを設定 FileEncordObj = Encoding.GetEncoding(FileEncoding); InputFileEncordObj = Encoding.GetEncoding(InputCsvFileEncode); OutputFileEncordObj = Encoding.GetEncoding(OutputCsvFileEncode); // ストリームに出力 FileStreamObj = new StreamReader(JsonFilePath,FileEncordObj); // ファイルを読み込み JsonConfigText = FileStreamObj.ReadToEnd(); // JSONオブジェクトに変換 JsonDocument JsonObj = JsonDocument.Parse(JsonConfigText); var config = JsonObj.RootElement.GetProperty("column_names"); // 変換対象となるCSVを入力 CsvFileStreamObj = new StreamReader(InputCsvFilePath,InputFileEncordObj); // TextFieldParserを使う var parser = new TextFieldParser(CsvFileStreamObj); //CsvFileStreamObj.Close(); // カンマ区切りの指定 parser.SetDelimiters(","); // フィールドが引用符で囲まれているか parser.HasFieldsEnclosedInQuotes = true; // フィールドの空白トリム設定 //parser.TrimWhiteSpace = true; // 先頭行をファイルのヘッダとして認識 string[] items = parser.ReadFields(); // カラム番号を保存しておく変数 int num = 0; // カラム名を保存しておく変数 string name = ""; // カラムが一致していない場合のエラーカウント int ErrCount = 0; int ColCnt = 0; // JSONからCSVのスキーマを取得して表示 for(int cnt = 0;cnt < config.GetArrayLength();cnt++){ num = config[cnt].GetProperty("num").GetInt32(); name = config[cnt].GetProperty("name").GetString(); // 先頭行にJSONで指定したカラムがあるか確認 if(items[num]==name){ //Console.WriteLine(name + ":OK"); ColCnt = ColCnt + 1; }else{ //Console.WriteLine(name + ":NG"); ErrCount = ErrCount + 1; } } // 指定したカラムが一つでもなければ、異常終了 if(ErrCount > 0){ return ; }else{ string[] HeaderAry = new string[ColCnt]; string[] TableBody = new string[ColCnt]; string Header =""; for(int cnt = 0;cnt < config.GetArrayLength();cnt++){ num = config[cnt].GetProperty("num").GetInt32(); name = config[cnt].GetProperty("name").GetString(); HeaderAry[num] = "\"" + name + "\""; } // 指定したカラムがすべてあるならば、ヘッダ情報をファイルに出力 Header = String.Join(",",HeaderAry) + "\r\n"; // JSONで指定したカラムのみCSVで出力 - 2行目以降 while (!parser.EndOfData) { items = parser.ReadFields(); for(int cnt = 0;cnt < config.GetArrayLength();cnt++){ num = config[cnt].GetProperty("num").GetInt32(); TableBody[num] = "\"" + items[num] + "\""; } OutputText = OutputText + String.Join(",",TableBody) + "\n"; // Array.ForEach(items, p => Console.Write($"[{p}] ")); } OutPutCsvFileObj = new StreamWriter(OutputCsvFilePath,false,OutputFileEncordObj); OutPutCsvFileObj.Write(Header + OutputText); OutPutCsvFileObj.Close(); // ファイルを閉じる FileStreamObj.Close(); } } } }
#region File Description //----------------------------------------------------------------------------- // Level.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using System.Xml.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Graphics; #endregion namespace MemoryMadness { class Level : DrawableGameComponent { #region Fields/Properties public int levelNumber; LinkedList<ButtonColors[]> sequence; LinkedListNode<ButtonColors[]> currentSequenceItem; public LevelState CurrentState; public bool IsActive; /// <summary> /// The amount of moves correctly performed by the user so far /// </summary> public int MovesPerformed { get; set; } // Sequence demonstration delays are multiplied by this each level const float DifficultyFactor = 0.75f; // Define the delay between flashes when the current set of moves is // demonstrated to the player TimeSpan delayFlashOn = TimeSpan.FromSeconds(1); TimeSpan delayFlashOff = TimeSpan.FromSeconds(0.5); // Define the allowed delay between two user inputs TimeSpan delayBetweenInputs = TimeSpan.FromSeconds(5); // Define the delay per move which will be used to calculate the overall time // the player has to input the sample. For example, if this delay is 4 and the // current level has 5 steps, the user will have 20 seconds overall to complete // the level. readonly TimeSpan DelayOverallPerInput = TimeSpan.FromSeconds(4); // The display period for the user's own input (feedback) readonly TimeSpan InputFlashDuration = TimeSpan.FromSeconds(0.75); TimeSpan delayPeriod; TimeSpan inputFlashPeriod; TimeSpan elapsedPatternInput; TimeSpan overallAllowedInputPeriod; bool flashOn; bool drawUserInput; ButtonColors?[] currentTouchSampleColors = new ButtonColors?[4]; // Define spheres covering the various buttons BoundingSphere redShpere; BoundingSphere blueShpere; BoundingSphere greenShpere; BoundingSphere yellowShpere; // Rendering members SpriteBatch spriteBatch; Texture2D buttonsTexture; #endregion #region Initializaton public Level(Game game, SpriteBatch spriteBatch, int levelNumber, int movesPerformed, Texture2D buttonsTexture) : base(game) { this.levelNumber = levelNumber; this.spriteBatch = spriteBatch; CurrentState = LevelState.NotReady; this.buttonsTexture = buttonsTexture; MovesPerformed = movesPerformed; } public Level(Game game, SpriteBatch spriteBatch, int levelNumber, Texture2D buttonsTexture) : this(game, spriteBatch, levelNumber, 0, buttonsTexture) { } public override void Initialize() { //Update delays to match level difficulty UpdateDelays(); // Define button bounding spheres DefineBoundingSpheres(); // Load sequences for current level from definitions XML LoadLevelSequences(); } #endregion #region Update and Render public override void Update(GameTime gameTime) { if (!IsActive) { base.Update(gameTime); return; } switch (CurrentState) { case LevelState.NotReady: // Nothing to update in this state break; case LevelState.Ready: // Wait for a while before demonstrating the level's move set delayPeriod += gameTime.ElapsedGameTime; if (delayPeriod >= delayFlashOn) { // Initiate flashing sequence currentSequenceItem = sequence.First; PlaySequenceStepSound(); CurrentState = LevelState.Flashing; delayPeriod = TimeSpan.Zero; flashOn = true; } break; case LevelState.Flashing: // Display the level's move set. When done, start accepting // user input delayPeriod += gameTime.ElapsedGameTime; if ((delayPeriod >= delayFlashOn) && (flashOn)) { delayPeriod = TimeSpan.Zero; flashOn = false; } if ((delayPeriod >= delayFlashOff) && (!flashOn)) { delayPeriod = TimeSpan.Zero; currentSequenceItem = currentSequenceItem.Next; PlaySequenceStepSound(); flashOn = true; } if (currentSequenceItem == null) { InitializeUserInputStage(); } break; case LevelState.Started: case LevelState.InProcess: delayPeriod += gameTime.ElapsedGameTime; inputFlashPeriod += gameTime.ElapsedGameTime; elapsedPatternInput += gameTime.ElapsedGameTime; if ((delayPeriod >= delayBetweenInputs) || (elapsedPatternInput >= overallAllowedInputPeriod)) { // The user was not quick enough inputFlashPeriod = TimeSpan.Zero; CurrentState = LevelState.FinishedFail; } if (inputFlashPeriod >= InputFlashDuration) { drawUserInput = false; } break; case LevelState.Fault: inputFlashPeriod += gameTime.ElapsedGameTime; if (inputFlashPeriod >= InputFlashDuration) { drawUserInput = false; CurrentState = LevelState.FinishedFail; } break; case LevelState.Success: inputFlashPeriod += gameTime.ElapsedGameTime; if (inputFlashPeriod >= InputFlashDuration) { drawUserInput = false; CurrentState = LevelState.FinishedOk; } break; case LevelState.FinishedOk: // Gameplay screen will advance the level break; case LevelState.FinishedFail: // Gameplay screen will reset the level break; default: break; } base.Update(gameTime); } public override void Draw(GameTime gameTime) { if (IsActive) { spriteBatch.Begin(); Rectangle redButtonRectangle = Settings.RedButtonDim; Rectangle greenButtonRectangle = Settings.GreenButtonDim; Rectangle blueButtonRectangle = Settings.BlueButtonDim; Rectangle yellowButtonRectangle = Settings.YellowButtonDim; // Draw the darkened buttons DrawDarkenedButtons(redButtonRectangle, greenButtonRectangle, blueButtonRectangle, yellowButtonRectangle); switch (CurrentState) { case LevelState.NotReady: case LevelState.Ready: // Nothing extra to draw break; case LevelState.Flashing: if ((currentSequenceItem != null) && (flashOn)) { ButtonColors[] toDraw = currentSequenceItem.Value; DrawLitButtons(toDraw); } break; case LevelState.Started: case LevelState.InProcess: case LevelState.Fault: case LevelState.Success: if (drawUserInput) { List<ButtonColors> toDraw = new List<ButtonColors>(currentTouchSampleColors.Length); foreach (var touchColor in currentTouchSampleColors) { if (touchColor.HasValue) { toDraw.Add(touchColor.Value); } } DrawLitButtons(toDraw.ToArray()); } break; case LevelState.FinishedOk: break; case LevelState.FinishedFail: break; default: break; } spriteBatch.End(); } base.Draw(gameTime); } #endregion #region Public functionality /// <summary> /// Handle user presses. /// </summary> /// <param name="touchPoints">The locations touched by the user. The list /// is expected to contain at least one member.</param> public void RegisterTouch(List<TouchLocation> touchPoints) { if ((CurrentState == LevelState.Started || CurrentState == LevelState.InProcess)) { ButtonColors[] stepColors = sequence.First.Value; bool validTouchRegistered = false; if (touchPoints.Count > 0) { // Reset current touch sample for (int i = 0; i < Settings.ButtonAmount; i++) { currentTouchSampleColors[i] = null; } // Go over the touch points and populate the current touch sample for (int i = 0; i < touchPoints.Count; i++) { var gestureBox = new BoundingBox( new Vector3(touchPoints[i].Position.X - 5, touchPoints[i].Position.Y - 5, 0), new Vector3(touchPoints[i].Position.X + 10, touchPoints[i].Position.Y + 10, 0)); if (redShpere.Intersects(gestureBox)) { currentTouchSampleColors[i] = ButtonColors.Red; AudioManager.PlaySound("red"); } else if (yellowShpere.Intersects(gestureBox)) { currentTouchSampleColors[i] = ButtonColors.Yellow; AudioManager.PlaySound("yellow"); } else if (blueShpere.Intersects(gestureBox)) { currentTouchSampleColors[i] = ButtonColors.Blue; AudioManager.PlaySound("blue"); } else if (greenShpere.Intersects(gestureBox)) { currentTouchSampleColors[i] = ButtonColors.Green; AudioManager.PlaySound("green"); } CurrentState = LevelState.InProcess; } List<ButtonColors> colorsHit = new List<ButtonColors>(currentTouchSampleColors.Length); // Check if the user pressed at least one of the colored buttons foreach (var hitColor in currentTouchSampleColors) { if (hitColor.HasValue) { validTouchRegistered = true; colorsHit.Add(hitColor.Value); } } // Find the buttons which the user failed to touch List<ButtonColors> missedColors = new List<ButtonColors>(stepColors.Length); foreach (var stepColor in stepColors) { if (!colorsHit.Contains(stepColor)) { missedColors.Add(stepColor); } } // If the user failed to perform the current move, fail the level // Do nothing if no buttons were touched if (((missedColors.Count > 0) || (touchPoints.Count != stepColors.Length)) && validTouchRegistered) CurrentState = LevelState.Fault; if (validTouchRegistered) { // Show user pressed buttons, reset timeout period // for button flash drawUserInput = true; inputFlashPeriod = TimeSpan.Zero; MovesPerformed++; sequence.Remove(stepColors); if ((sequence.Count == 0) && (CurrentState != LevelState.Fault)) { CurrentState = LevelState.Success; } } } } } #endregion #region Private Functionality /// <summary> /// Load sequences for the current level from definitions XML /// </summary> private void LoadLevelSequences() { XDocument doc = XDocument.Load(@"Content\Gameplay\LevelDefinitions.xml"); var definitions = doc.Document.Descendants(XName.Get("Level")); XElement levelDefinition = null; foreach (var definition in definitions) { if (int.Parse( definition.Attribute(XName.Get("Number")).Value) == levelNumber) { levelDefinition = definition; break; } } int skipMoves = 0; // Used to skip moves if we are resuming a level mid-play // If definitions are found, create sequences if (null != levelDefinition) { sequence = new LinkedList<ButtonColors[]>(); foreach (var pattern in levelDefinition.Descendants(XName.Get("Pattern"))) { if (skipMoves < MovesPerformed) { skipMoves++; continue; } string[] values = pattern.Value.Split(','); ButtonColors[] colors = new ButtonColors[values.Length]; // Add each color to a sequence for (int i = 0; i < values.Length; i++) { colors[i] = (ButtonColors)Enum.Parse( typeof(ButtonColors), values[i], true); } // Add each sequence to the sequence list sequence.AddLast(colors); } if (MovesPerformed == 0) { CurrentState = LevelState.Ready; delayPeriod = TimeSpan.Zero; } else { InitializeUserInputStage(); } } } /// <summary> /// Define button bounding spheres /// </summary> private void DefineBoundingSpheres() { redShpere = new BoundingSphere( new Vector3( Settings.RedButtonPosition.X + Settings.ButtonSize.X / 2, Settings.RedButtonPosition.Y + Settings.ButtonSize.Y / 2, 0), Settings.ButtonSize.X / 2); blueShpere = new BoundingSphere( new Vector3( Settings.BlueButtonPosition.X + Settings.ButtonSize.X / 2, Settings.BlueButtonPosition.Y + Settings.ButtonSize.Y / 2, 0), Settings.ButtonSize.X / 2); greenShpere = new BoundingSphere( new Vector3( Settings.GreenButtonPosition.X + Settings.ButtonSize.X / 2, Settings.GreenButtonPosition.Y + Settings.ButtonSize.Y / 2, 0), Settings.ButtonSize.X / 2); yellowShpere = new BoundingSphere( new Vector3( Settings.YellowButtonPosition.X + Settings.ButtonSize.X / 2, Settings.YellowButtonPosition.Y + Settings.ButtonSize.Y / 2, 0), Settings.ButtonSize.X / 2); } /// <summary> /// Update delays to match level difficulty /// </summary> private void UpdateDelays() { delayFlashOn = TimeSpan.FromTicks( (long)(delayFlashOn.Ticks * Math.Pow(DifficultyFactor, levelNumber - 1))); delayFlashOff = TimeSpan.FromTicks( (long)(delayFlashOff.Ticks * Math.Pow(DifficultyFactor, levelNumber - 1))); } /// <summary> /// Sets various members to allow the user to supply input. /// </summary> private void InitializeUserInputStage() { elapsedPatternInput = TimeSpan.Zero; overallAllowedInputPeriod = TimeSpan.Zero; CurrentState = LevelState.Started; drawUserInput = false; // Calculate total allowed timeout period for the entire level overallAllowedInputPeriod = TimeSpan.FromSeconds( DelayOverallPerInput.TotalSeconds * sequence.Count); } /// <summary> /// Draws the set of lit buttons according to the colors specified. /// </summary> /// <param name="toDraw">The array of colors representing the lit /// buttons.</param> private void DrawLitButtons(ButtonColors[] toDraw) { Vector2 position = Vector2.Zero; Rectangle rectangle = Rectangle.Empty; for (int i = 0; i < toDraw.Length; i++) { switch (toDraw[i]) { case ButtonColors.Red: position = Settings.RedButtonPosition; rectangle = Settings.RedButtonLit; break; case ButtonColors.Yellow: position = Settings.YellowButtonPosition; rectangle = Settings.YellowButtonLit; break; case ButtonColors.Blue: position = Settings.BlueButtonPosition; rectangle = Settings.BlueButtonLit; break; case ButtonColors.Green: position = Settings.GreenButtonPosition; rectangle = Settings.GreenButtonLit; break; } spriteBatch.Draw(buttonsTexture, position, rectangle, Color.White); } } /// <summary> /// Draw the darkened buttons /// </summary> /// <param name="redButtonRectangle">Red button rectangle /// in source texture.</param> /// <param name="greenButtonRectangle">Green button rectangle /// in source texture.</param> /// <param name="blueButtonRectangle">Blue button rectangle /// in source texture.</param> /// <param name="yellowButtonRectangle">Yellow button rectangle /// in source texture.</param> private void DrawDarkenedButtons(Rectangle redButtonRectangle, Rectangle greenButtonRectangle, Rectangle blueButtonRectangle, Rectangle yellowButtonRectangle) { spriteBatch.Draw(buttonsTexture, Settings.RedButtonPosition, redButtonRectangle, Color.White); spriteBatch.Draw(buttonsTexture, Settings.GreenButtonPosition, greenButtonRectangle, Color.White); spriteBatch.Draw(buttonsTexture, Settings.BlueButtonPosition, blueButtonRectangle, Color.White); spriteBatch.Draw(buttonsTexture, Settings.YellowButtonPosition, yellowButtonRectangle, Color.White); } /// <summary> /// Plays a sound appropriate to the current color flashed by the computer /// </summary> private void PlaySequenceStepSound() { if (currentSequenceItem == null) { return; } for (int i = 0; i < currentSequenceItem.Value.Length; ++i) { switch (currentSequenceItem.Value[i]) { case ButtonColors.Red: AudioManager.PlaySound("red"); break; case ButtonColors.Yellow: AudioManager.PlaySound("yellow"); break; case ButtonColors.Blue: AudioManager.PlaySound("blue"); break; case ButtonColors.Green: AudioManager.PlaySound("green"); break; default: break; } } } #endregion } }
// Copyright (c) All contributors. All rights reserved. Licensed under the MIT license. using System; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; namespace Arc.Crypto; /// <summary> /// Represents a pseudo-random number generator based on xoshiro256**.<br/> /// This class is NOT thread-safe.<br/> /// Consider using <see langword="lock"/> statement or <see cref="RandomVault"/> in multi-threaded application. /// </summary> public class Xoshiro256StarStar : RandomUInt64 { // xoshiro256** is based on the algorithm from http://prng.di.unimi.it/xoshiro256starstar.c: // // Written in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org) // // To the extent possible under law, the author has dedicated all copyright // and related and neighboring rights to this software to the public domain // worldwide. This software is distributed without any warranty. // // See <http://creativecommons.org/publicdomain/zero/1.0/>. private ulong ss0; private ulong ss1; private ulong ss2; private ulong ss3; /// <summary> /// Initializes a new instance of the <see cref="Xoshiro256StarStar"/> class.<br/> /// The generator is initialized by random seeds (<see cref="RandomNumberGenerator"/>). /// </summary> public unsafe Xoshiro256StarStar() { this.Reset(); } /// <summary> /// Initializes a new instance of the <see cref="Xoshiro256StarStar"/> class.<br/> /// </summary> /// <param name="seed">seed.</param> public Xoshiro256StarStar(ulong seed) { this.Reset(seed); } /// <summary> /// Reset state vectors with random seeds. /// </summary> public unsafe void Reset() { Span<byte> span = stackalloc byte[4 * sizeof(ulong)]; fixed (byte* b = span) { ulong* d = (ulong*)b; do { RandomNumberGenerator.Fill(span); } while ((d[0] | d[1] | d[2] | d[3]) == 0); // at least one value must be non-zero. this.ss0 = d[0]; this.ss1 = d[1]; this.ss2 = d[2]; this.ss3 = d[3]; } } /// <summary> /// Reset state vectors with the specified seed. /// </summary> /// <param name="seed">seed.</param> public void Reset(ulong seed) { var state = seed; do { this.ss0 = SplitMix64(ref state); this.ss1 = SplitMix64(ref state); this.ss2 = SplitMix64(ref state); this.ss3 = SplitMix64(ref state); } while ((this.ss0 | this.ss1 | this.ss2 | this.ss3) == 0); // at least one value must be non-zero } /// <inheritdoc/> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override ulong NextUInt64() { var s0 = this.ss0; var s1 = this.ss1; var s2 = this.ss2; var s3 = this.ss3; var result = BitOperations.RotateLeft(s1 * 5, 7) * 9; var t = s1 << 17; s2 ^= s0; s3 ^= s1; s1 ^= s2; s0 ^= s3; s2 ^= t; s3 = BitOperations.RotateLeft(s3, 45); this.ss0 = s0; this.ss1 = s1; this.ss2 = s2; this.ss3 = s3; return result; } /// <inheritdoc/> public override unsafe void NextBytes(Span<byte> buffer) { var s0 = this.ss0; var s1 = this.ss1; var s2 = this.ss2; var s3 = this.ss3; while (buffer.Length >= sizeof(ulong)) { Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(buffer), BitOperations.RotateLeft(s1 * 5, 7) * 9); var t = s1 << 17; s2 ^= s0; s3 ^= s1; s1 ^= s2; s0 ^= s3; s2 ^= t; s3 = BitOperations.RotateLeft(s3, 45); buffer = buffer.Slice(sizeof(ulong)); } if (!buffer.IsEmpty) { var next = BitOperations.RotateLeft(s1 * 5, 7) * 9; byte* remainingBytes = (byte*)&next; for (var i = 0; i < buffer.Length; i++) { buffer[i] = remainingBytes[i]; } var t = s1 << 17; s2 ^= s0; s3 ^= s1; s1 ^= s2; s0 ^= s3; s2 ^= t; s3 = BitOperations.RotateLeft(s3, 45); } this.ss0 = s0; this.ss1 = s1; this.ss2 = s2; this.ss3 = s3; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VSX.UniversalVehicleCombat { /// <summary> /// Base class for a script that controls the camera for a specific type of vehicle. /// </summary> public class VehicleCameraController : MonoBehaviour { [Header("General")] [Tooltip("Whether to specify the vehicle classes that this camera controller is for.")] [SerializeField] protected bool specifyCompatibleVehicleClasses; [Tooltip("The vehicle classes that this camera controller is compatible with.")] [SerializeField] protected List<VehicleClass> compatibleVehicleClasses = new List<VehicleClass>(); // A reference to the vehicle camera protected VehicleCamera vehicleCamera; public VehicleCamera VehicleCamera { set { vehicleCamera = value; } } [Header("Starting Values")] [Tooltip("The camera view that is shown upon entering the vehicle.")] [SerializeField] protected VehicleCameraView startingView; [Tooltip("Whether to default to the first available view, if the startingView value is not set.")] [SerializeField] protected bool defaultToFirstAvailableView = true; // Whether this camera controller is currently activated protected bool controllerActive = false; public bool ControllerActive { get { return controllerActive; } } // Whether this camera controller is ready to be activated protected bool initialized = false; public bool Initialized { get { return initialized; } } /// <summary> /// Called to activate this camera controller (for example when the Vehicle Camera's target vehicle changes). /// </summary> public virtual void StartController() { // If this camera controller is ready, activate it. if (initialized) controllerActive = true; } /// <summary> /// Called to deactivate this camera controller. /// incompatible vehicle. /// </summary> public virtual void StopController() { controllerActive = false; } /// <summary> /// Set the target vehicle for this camera controller. /// </summary> /// <param name="vehicle">The target vehicle.</param> /// <param name="startController">Whether to start the controller immediately.</param> public virtual void SetVehicle(Vehicle vehicle, bool startController) { StopController(); initialized = false; if (vehicle == null) return; if (Initialize(vehicle)) { initialized = true; vehicleCamera.SetView(startingView); if (startController) StartController(); } } /// <summary> /// Initialize this camera controller with a vehicle. /// </summary> /// <param name="vehicle">Whether the camera controller succeeded in initializing.</param> /// <returns></returns> protected virtual bool Initialize(Vehicle vehicle) { // If compatible vehicle classes are specified, check that the list contains this vehicle's class. if (specifyCompatibleVehicleClasses) { if (compatibleVehicleClasses.IndexOf(vehicle.VehicleClass) != -1) { return true; } else { return false; } } else { return true; } } protected virtual void CameraControllerFixedUpdate() { } protected virtual void FixedUpdate() { // If not activated or no camera view target selected, exit. if (!controllerActive || !vehicleCamera.HasCameraViewTarget) return; CameraControllerFixedUpdate(); } protected virtual void CameraControllerUpdate() { } protected virtual void Update() { // If not activated or no camera view target selected, exit. if (!controllerActive || !vehicleCamera.HasCameraViewTarget) return; CameraControllerUpdate(); } protected virtual void CameraControllerLateUpdate() { } protected virtual void LateUpdate() { // If not activated or no camera view target selected, exit. if (!controllerActive || !vehicleCamera.HasCameraViewTarget) return; CameraControllerLateUpdate(); } } }
using System; using System.Collections.Generic; using Tippy.Core.Models; namespace Tippy.Pages.RecordedTransactions { public class IndexModel : PageModelBase { public List<RecordedTransaction> RecordedTransactions { get; set; } = new List<RecordedTransaction>(); public IndexModel(Tippy.Core.Data.TippyDbContext context) : base(context) { } public void OnGet() { DbContext.Entry(ActiveProject!).Collection(p => p.RecordedTransactions).Load(); RecordedTransactions = ActiveProject!.RecordedTransactions; RecordedTransactions.Reverse(); } } }
namespace RedisClient_BaiCh.CmdReturnEntities { public class RedisCmdReturnAuth : RedisCmdReturn { public RedisCmdReturnAuth(CommandMethodReturn commandMethodReturn) : base(commandMethodReturn) { } } }
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiInterface(nativeType: typeof(IDmsEndpointS3Settings), fullyQualifiedName: "aws.DmsEndpointS3Settings")] public interface IDmsEndpointS3Settings { [JsiiProperty(name: "bucketFolder", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] string? BucketFolder { get { return null; } } [JsiiProperty(name: "bucketName", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] string? BucketName { get { return null; } } [JsiiProperty(name: "compressionType", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] string? CompressionType { get { return null; } } [JsiiProperty(name: "csvDelimiter", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] string? CsvDelimiter { get { return null; } } [JsiiProperty(name: "csvRowDelimiter", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] string? CsvRowDelimiter { get { return null; } } [JsiiProperty(name: "externalTableDefinition", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] string? ExternalTableDefinition { get { return null; } } [JsiiProperty(name: "serviceAccessRoleArn", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] string? ServiceAccessRoleArn { get { return null; } } [JsiiTypeProxy(nativeType: typeof(IDmsEndpointS3Settings), fullyQualifiedName: "aws.DmsEndpointS3Settings")] internal sealed class _Proxy : DeputyBase, aws.IDmsEndpointS3Settings { private _Proxy(ByRefValue reference): base(reference) { } [JsiiOptional] [JsiiProperty(name: "bucketFolder", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public string? BucketFolder { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "bucketName", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public string? BucketName { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "compressionType", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public string? CompressionType { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "csvDelimiter", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public string? CsvDelimiter { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "csvRowDelimiter", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public string? CsvRowDelimiter { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "externalTableDefinition", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public string? ExternalTableDefinition { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "serviceAccessRoleArn", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public string? ServiceAccessRoleArn { get => GetInstanceProperty<string?>(); } } } }
/* * TestGIS_Write writes some test Atmel Generic, Intel HEX, and Motorola * S-Record records to files and reads them back to the standard output, * using LibGIS.Net. * * Authors: Jerry G. Scherer <scherej1@hotmail.com>, * Vanya A. Sergeev <vsergeev@gmail.com> */ using System; using System.Text; using System.IO; using LibGIS.Net; namespace TestLibGISdotNet { class Program { static void Main(string[] args) { byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04 }; UInt16[] data16 = new UInt16[] { 0x0101, 0x0202, 0x0303, 0x0404 }; TestAtmelGeneric("test.gen", data16); Console.WriteLine(); TestIntelHex("test.ihx", data); Console.WriteLine(); TestSRecord("TestSRecord", "test.scd", data); Console.WriteLine(); } private static void TestAtmelGeneric(string fileName, UInt16[] data16) { UInt16 address = 0; AtmelGeneric grec = new AtmelGeneric(); StreamWriter sw = new StreamWriter(fileName); // Create the first record with data AtmelGenericStructure grecs = grec.NewRecord(address++, data16[0]); grec.Write(sw); // Create another record with the next data point grec.NewRecord(address++, data16[1]); grec.Write(sw); // Create another record with the next data point grec.NewRecord(address++, data16[2]); grec.Write(sw); // Create the last data record with the last data point grec.NewRecord(address++, data16[3]); grec.Write(sw); sw.Close(); Console.WriteLine("Wrote Atmel Generic formatted file: " + fileName); Console.WriteLine("Reading back Atmel Generic file:"); // Open up the new file and attempt to read the records and print to the console StreamReader sr = new StreamReader(fileName); grecs = grec.Read(sr); Console.WriteLine((grecs != null) ? grec.Print() : "Could not read record!"); grecs = grec.Read(sr); Console.WriteLine((grecs != null) ? grec.Print() : "Could not read record!"); grecs = grec.Read(sr); Console.WriteLine((grecs != null) ? grec.Print() : "Could not read record!"); grecs = grec.Read(sr); Console.WriteLine((grecs != null) ? grec.Print() : "Could not read record!"); sr.Close(); } private static void TestIntelHex(string fileName, byte[] data) { IntelHex irec = new IntelHex(); StreamWriter sw = new StreamWriter(fileName); // Create a new type-0 record with data IntelHexStructure irecs = irec.NewRecord(0, 0, data, data.Length); irec.Write(sw); // Create another type-0 record with new data irec.NewRecord(0, 8, data, data.Length); irec.Write(sw); // Create another type-0 record with new data irec.NewRecord(0, 16, data, data.Length); irec.Write(sw); // Create an end of record type-1 record irec.NewRecord(1, 0, null, 0); irec.Write(sw); sw.Close(); Console.WriteLine("Wrote Intel HEX formatted file: " + fileName); Console.WriteLine("Reading back Intel HEX file:"); // Open up the new file and attempt to read the records and print to the console StreamReader sr = new StreamReader(fileName); irecs = irec.Read(sr); Console.WriteLine((irecs != null) ? irec.Print() : "Could not read record!"); irecs = irec.Read(sr); Console.WriteLine((irecs != null) ? irec.Print() : "Could not read record!"); irecs = irec.Read(sr); Console.WriteLine((irecs != null) ? irec.Print() : "Could not read record!"); irecs = irec.Read(sr); Console.WriteLine((irecs != null) ? irec.Print() : "Could not read record!"); sr.Close(); } private static void TestSRecord(String title, String fileName, byte[] data) { SRecord srec = new SRecord(); StreamWriter sw = new StreamWriter(fileName); // Create a new S0 record with the title SRecordStructure srecs = srec.NewRecord(0, 0, Encoding.ASCII.GetBytes(title), title.Length); srec.Write(sw); // Create a S1 data record srec.NewRecord(1, 0, data, data.Length); srec.Write(sw); // Create a S5 transmission record srec.NewRecord(5, 1, null, 0); srec.Write(sw); // Create a S9 program start record srec.NewRecord(9, 0, null, 0); srec.Write(sw); sw.Close(); Console.WriteLine("Wrote Motorola S-Record formatted file: " + fileName); Console.WriteLine("Reading back Motorola S-Record file:"); // Open up the new file and attempt to read the records and print to the console StreamReader sr = new StreamReader(fileName); srecs = srec.Read(sr); Console.WriteLine((srecs != null)? srec.Print() : "Could not read record!"); srecs = srec.Read(sr); Console.WriteLine((srecs != null) ? srec.Print() : "Could not read record!"); srecs = srec.Read(sr); Console.WriteLine((srecs != null) ? srec.Print() : "Could not read record!"); srecs = srec.Read(sr); Console.WriteLine((srecs != null) ? srec.Print() : "Could not read record!"); sr.Close(); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using PierresMenu.Models; using System; using System.Collections.Generic; namespace PierresMenu.Tests { [TestClass] public class PastryTests : IDisposable { public void Dispose() { Pastry.ClearAll(); } [TestMethod] public void PastryConstructor_CreatesInstanceOfPastry_Pastry() { Pastry newPastryOrder = new Pastry(1); Assert.AreEqual(typeof(Pastry), newPastryOrder.GetType()); } [TestMethod] public void GetAmount_ReturnsPastryAmount_Int() { int pastryAmount = 1; Pastry newPastryOrder = new Pastry(pastryAmount); int result = newPastryOrder.Amount; Assert.AreEqual(pastryAmount, result); } [TestMethod] public void SetAmount_SetAmount_Int() { int pastryAmount = 2; Pastry newPastryOrder = new Pastry(pastryAmount); int updatedAmount = 3; newPastryOrder.Amount = updatedAmount; int result = newPastryOrder.Amount; Assert.AreEqual(updatedAmount, result); } [TestMethod] public void GetAll_ReturnsEmptyList_PastryList() { List<Pastry> newList = new List<Pastry> {}; List<Pastry> result = Pastry.GetAll(); CollectionAssert.AreEqual(newList, result); } [TestMethod] public void GetAll_ReturnsPastryOrders_PastryList() { int pastryAmount1 = 1; int pastryAmount2 = 3; Pastry newPastryOrder1 = new Pastry(pastryAmount1); Pastry newPastryOrder2 = new Pastry(pastryAmount2); List<Pastry> newList = new List<Pastry> { newPastryOrder1, newPastryOrder2 }; List<Pastry> result = Pastry.GetAll(); CollectionAssert.AreEqual(newList, result); } [TestMethod] public void OrderTotal_ReturnsCostOfOrder_Int() { Pastry newPastryOrder = new Pastry(1); int result = newPastryOrder.OrderTotal(); Assert.AreEqual(2, result); } [TestMethod] public void OrdetTotal_ReturnsReducedCostOfOrder_Int() { Pastry newPastryOrder = new Pastry(10); int result = newPastryOrder.OrderTotal(); Assert.AreEqual(17, result); } } }
using System.Collections.Generic; namespace DataConnectors.Formatters.Model { public interface IHasXmlNameSpaces { List<XmlNameSpace> XmlNameSpaces { get; set; } } }
using System; namespace EventSourcingSample.UserCommandService.Entities { public class CommandResult { public CommandResult(Guid commandId) { CommandId = commandId; } public Guid CommandId { get; } } }
#region License // Copyright ©2017 Tacke Consulting (dba OpenNETCF) // // 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. // #endregion using System.Collections.Generic; using System.Linq; using System.Xml; namespace OpenNETCF.Web.Configuration { /// <summary> /// Security config for the server (enabled protocols) /// </summary> public sealed class SecurityConfig { internal SecurityConfig() { this.Tls10 = true; this.Tls11 = true; this.Tls12 = true; this.ResumeSession = true; CipherList = new List<short>(); } internal SecurityConfig(XmlNode node) : this() { ParseXml(node); } /// <summary> /// Get or the set the session resume capabilities on the server /// </summary> public bool ResumeSession { get; internal set; } /// <summary> /// Get or set the activation of TLS 1.0 /// </summary> public bool Tls10 { get; internal set; } /// <summary> /// Get or set the activation of TLS 1.1 /// </summary> public bool Tls11 { get; internal set; } /// <summary> /// Get or set the activation of TLS 1.2 /// </summary> public bool Tls12 { get; internal set; } /// <summary> /// A comma-separated list of numeric cipher suites to enable. This is Eldos-specific. /// See https://www.eldos.com/documentation/sbb/documentation/ref_cl_clientsslsocket_mtd_getciphersuites.html /// </summary> public List<short> CipherList { get; internal set; } private void ParseXml(XmlNode node) { foreach (XmlNode subnode in node.ChildNodes) { bool enabled = false; if (subnode.Attributes.Count > 0 && subnode.Attributes["Enabled"] != null) { enabled = bool.Parse(subnode.Attributes["Enabled"].Value); } switch (subnode.Name) { case "TLS10": this.Tls10 = enabled; break; case "TLS11": this.Tls11 = enabled; break; case "TLS12": this.Tls12 = enabled; break; case "ResumeSession": this.ResumeSession = enabled; break; case "CipherList": try { string list = subnode.InnerText; if (string.IsNullOrEmpty(list)) { break; } IEnumerable<string> items = list .Split(',') .Select(item => item.Trim()) .Where(item => item.Length > 0); foreach (string item in items) { try { short cipher = short.Parse(item); this.CipherList.Add(cipher); } catch { // ignore non-numerics } } } catch { // just use the defaults } break; } } } } }
using codessentials.CGM.Commands; namespace codessentials.CGM.Elements { public static class AttributeElements { public static Command CreateCommand(int elementId, int elementClass, CgmFile container) { return ((AttributeElement)elementId) switch { AttributeElement.LINE_BUNDLE_INDEX => new LineBundleIndex(container), AttributeElement.LINE_TYPE => new LineType(container), AttributeElement.LINE_WIDTH => new LineWidth(container), AttributeElement.LINE_COLOUR => new LineColour(container), AttributeElement.MARKER_BUNDLE_INDEX => new MarkerBundleIndex(container), AttributeElement.MARKER_TYPE => new MarkerType(container), AttributeElement.MARKER_SIZE => new MarkerSize(container), AttributeElement.MARKER_COLOUR => new MarkerColour(container), AttributeElement.TEXT_BUNDLE_INDEX => new TextBundleIndex(container), AttributeElement.TEXT_FONT_INDEX => new TextFontIndex(container), AttributeElement.TEXT_PRECISION => new TextPrecision(container), AttributeElement.CHARACTER_EXPANSION_FACTOR => new CharacterExpansionFactor(container), AttributeElement.CHARACTER_SPACING => new CharacterSpacing(container), AttributeElement.TEXT_COLOUR => new TextColour(container), AttributeElement.CHARACTER_HEIGHT => new CharacterHeight(container), AttributeElement.CHARACTER_ORIENTATION => new CharacterOrientation(container), AttributeElement.TEXT_PATH => new TextPath(container), AttributeElement.TEXT_ALIGNMENT => new TextAlignment(container), AttributeElement.CHARACTER_SET_INDEX => new CharacterSetIndex(container), AttributeElement.ALTERNATE_CHARACTER_SET_INDEX => new AlternateCharacterSetIndex(container), AttributeElement.FILL_BUNDLE_INDEX => new FillBundleIndex(container), AttributeElement.INTERIOR_STYLE => new InteriorStyle(container), AttributeElement.FILL_COLOUR => new FillColour(container), AttributeElement.HATCH_INDEX => new HatchIndex(container), AttributeElement.PATTERN_INDEX => new PatternIndex(container), AttributeElement.EDGE_BUNDLE_INDEX => new EdgeBundleIndex(container), AttributeElement.EDGE_TYPE => new EdgeType(container), AttributeElement.EDGE_WIDTH => new EdgeWidth(container), AttributeElement.EDGE_COLOUR => new EdgeColour(container), AttributeElement.EDGE_VISIBILITY => new EdgeVisibility(container), AttributeElement.FILL_REFERENCE_POINT => new FillReferencePoint(container), AttributeElement.PATTERN_TABLE => new PatternTable(container), AttributeElement.PATTERN_SIZE => new PatternSize(container), AttributeElement.COLOUR_TABLE => new ColourTable(container), AttributeElement.ASPECT_SOURCE_FLAGS => new AspectSourceFlags(container), AttributeElement.PICK_IDENTIFIER => new PickIdentifier(container), AttributeElement.LINE_CAP => new LineCap(container), AttributeElement.LINE_JOIN => new LineJoin(container), AttributeElement.LINE_TYPE_CONTINUATION => new LineTypeContinuation(container), AttributeElement.LINE_TYPE_INITIAL_OFFSET => new LineTypeInitialOffset(container), AttributeElement.TEXT_SCORE_TYPE => new TextScoreType(container), AttributeElement.RESTRICTED_TEXT_TYPE => new RestrictedTextType(container), AttributeElement.INTERPOLATED_INTERIOR => new InterpolatedInterior(container), AttributeElement.EDGE_CAP => new EdgeCap(container), AttributeElement.EDGE_JOIN => new EdgeJoin(container), AttributeElement.EDGE_TYPE_CONTINUATION => new EdgeTypeContinuation(container), AttributeElement.EDGE_TYPE_INITIAL_OFFSET => new EdgeTypeInitialOffset(container), AttributeElement.SYMBOL_LIBRARY_INDEX => new SymbolLibraryIndex(container), AttributeElement.SYMBOL_COLOUR => new SymbolColour(container), AttributeElement.SYMBOL_SIZE => new SymbolSize(container), AttributeElement.SYMBOL_ORIENTATION => new SymbolOrientation(container), _ => new UnknownCommand(elementId, elementClass, container), }; } } }
// Copyright (c) Rodrigo Speller. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE.txt in the project root for license information. using System; using System.IO; namespace TSqlCoverage.XEvents.Internal { public sealed class XEventUnicodeStringValue : XEventValue<string> { internal XEventUnicodeStringValue(string value) : base(value ?? throw new ArgumentNullException(nameof(value))) { } public override void WriteTo(TextWriter writer) { var value = Value; writer.Write("N\'"); var currentIndex = 0; var quoteIndex = Value.IndexOf('\''); while(quoteIndex >= 0) { var partialValue = value.Substring(currentIndex, quoteIndex - currentIndex); writer.Write(partialValue); writer.Write("''"); currentIndex = quoteIndex + 1; if (currentIndex == value.Length) break; quoteIndex = Value.IndexOf('\'', currentIndex); } if (currentIndex == 0) { writer.Write(value); } else if (currentIndex != value.Length) { var partialValue = value.Substring(currentIndex, value.Length - currentIndex); writer.Write(partialValue); } writer.Write('\''); } public static implicit operator XEventUnicodeStringValue(string value) => new XEventUnicodeStringValue(value); } }
using System; using System.IO; using System.Reflection; namespace SBRW.Nancy.Hosting.Self { /// <summary> /// /// </summary> public class FileSystemRootPathProvider : IRootPathProvider { private Lazy<string> L_RootPath { get; set; } = new Lazy<string>(ExtractRootPath); /// <summary> /// /// </summary> /// <returns></returns> public string GetRootPath() { return this.L_RootPath.Value; } private static string ExtractRootPath() { return Path.GetDirectoryName((Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()).Location); } } }
namespace RayWorkflow.Orleans.Test.Workflows { using RayWorkflow.Domain.Shared.Workflow; using RayWorkflow.Domain.Workflow; using RayWorkflow.IGrains; using Shouldly; using System; using System.Linq; using System.Threading.Tasks; using Xunit; public class WorkflowFormTests : RayWorkflowTestBase { [Fact] public async Task CanDisabled() { var id = Guid.NewGuid(); var grain = ClusterClient.GetGrain<IWorkflowFormGrain<WorkflowFormDto>>(id); var dto = new WorkflowFormDto { Id = id, Name = "Name1", Sort = 1 }; await grain.Create(dto); await grain.Disable(true); var result = await grain.Get(); result.Name.ShouldBe(dto.Name); result.Disabled.ShouldBeTrue(); await Task.Delay(500); UsingDbContext(dbContext => { dbContext.Set<WorkflowForm>().Any(x => x.Id == id).ShouldBeTrue(); var workflowForm = dbContext.Set<WorkflowForm>().First(x => x.Id == id); workflowForm.Name.ShouldBe(dto.Name); workflowForm.Disabled.ShouldBeTrue(); }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { [SerializeField] UnitCanvasController uCC = null; [SerializeField] Transform cameraChild = null; [SerializeField] float zoomingSpeed = 1f; [SerializeField] float movingSpeed = 1f; [SerializeField] float mouseSensitivityH = 1f; [SerializeField] float mouseSensitivityV = 1f; private float yaw = 0f; private float pitch = 0f; // Start is called before the first frame update private void Start() { yaw = transform.eulerAngles.y; pitch = transform.eulerAngles.x; } // Update is called once per frame private void Update() { if (Input.GetMouseButtonDown(0)) { RaycastHit hitInfo; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hitInfo)) { UnitUpgrade currentUnit = hitInfo.transform.gameObject.GetComponent<UnitUpgrade>(); if(currentUnit) { uCC.GetCurrentUnit(currentUnit); uCC.EnableUI(hitInfo.transform.position); } } } cameraChild.transform.rotation = Quaternion.Euler(new Vector3(-transform.rotation.eulerAngles.x, 0f, 0f)); if (Input.GetMouseButton(1)) { yaw += mouseSensitivityH * Input.GetAxis("Mouse X"); pitch -= mouseSensitivityV * Input.GetAxis("Mouse Y"); transform.eulerAngles = new Vector3(pitch, yaw, 0f); } if (Input.GetKey(KeyCode.W)) { transform.Translate(cameraChild.transform.forward * movingSpeed); } if (Input.GetKey(KeyCode.S)) { transform.Translate(-cameraChild.transform.forward * movingSpeed); } if (Input.GetKey(KeyCode.A)) { transform.Translate(-cameraChild.transform.right * movingSpeed); } if (Input.GetKey(KeyCode.D)) { transform.Translate(cameraChild.transform.right * movingSpeed); } if (Input.GetAxis("Mouse ScrollWheel") != 0) { transform.Translate(Vector3.forward * Input.GetAxis("Mouse ScrollWheel") * zoomingSpeed); } } }
using PP_Parser.Parser; namespace PhoenixPoint.Common.Entities { public class AmmoManager : PhonixBaseObjectBaseValue { public PhoenixGenericCollection<PhoenixObjectID> LoadedMagazines { get; set; } public PhoenixObjectID ParentItem { get; set; } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; using System.Net.Http; using System.Text; using Extensive.Pipeline.CacheControl.Pure.Enums; using Microsoft.Net.Http.Headers; namespace Extensive.Pipeline.CacheControl { public sealed class CacheControlBuilder { private HttpMethod[] supportedMethods = { HttpMethod.Get, HttpMethod.Head }; private string[] defaultVaryHeaders = { HeaderNames.ContentEncoding, HeaderNames.ContentLanguage, HeaderNames.ContentType }; /// <summary> /// Adds supported methods /// </summary> /// <param name="methods">HTTP methods</param> [return: NotNull] public CacheControlBuilder WithSupportedMethods( [DisallowNull] HttpMethod[] methods) { if (methods == null) throw new ArgumentNullException(nameof(methods)); if (methods.Length == 0) throw new ArgumentException("Value cannot be an empty collection.", nameof(methods)); this.supportedMethods = methods; return this; } /// <summary> /// Adds default vary headers /// </summary> /// <param name="headers">HTTP headers</param> public CacheControlBuilder WithDefaultVaryHeaders( [DisallowNull] string[] headers) { if (headers == null) throw new ArgumentNullException(nameof(headers)); if (headers.Length == 0) throw new ArgumentException("Value cannot be an empty collection.", nameof(headers)); this.defaultVaryHeaders = headers; return this; } [return: NotNull] public CacheControl Build() { return new CacheControl( this.supportedMethods, this.defaultVaryHeaders); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reactive.Disposables; using System.Text; using System.Threading.Tasks; namespace slimCODE.Tools { // TODO: Logs.GetLogger(log => log.ReportError("foo bar", error)); // The lambda is not called when no logger active. public static partial class Logs { private static readonly Logger __logger = new Logger(); static Logs() { AddDebugLogger(); } public static void AddLogger(ILogger logger) { __logger.AddLogger(logger); } public static void UseLogger(Action<Logger> loggerAction) { if(__logger.HasLoggers) { loggerAction(__logger); } } public static IDisposable UseLogger(Action<Logger> beginLoggerAction, Action<Logger, Stopwatch> endLoggerAction) { if (__logger.HasLoggers) { beginLoggerAction(__logger); var stopWatch = Stopwatch.StartNew(); return Disposable.Create(() => { stopWatch.Stop(); endLoggerAction(__logger, stopWatch); }); } return Disposable.Empty; } [Conditional("DEBUG")] private static void AddDebugLogger() { if(System.Diagnostics.Debugger.IsAttached) { AddLogger(new DebuggerLogger()); } } } }
using System.Diagnostics; using System.Text; namespace Roton.Emulation.Infrastructure { internal static class Utility { private static readonly Encoding CodePage437 = CodePagesEncodingProvider.Instance.GetEncoding(437); /// <summary> /// Return the absolute difference between this value and another specified value. /// </summary> [DebuggerStepThrough] public static int AbsDiff(this int a, int b) { var diff = a - b; if (diff < 0) return -diff; return diff; } /// <summary> /// Return 1 if the value is above zero, -1 if the value is below zero, and 0 otherwise. /// </summary> [DebuggerStepThrough] public static int Polarity(this int value) { if (value > 0) return 1; if (value < 0) return -1; return 0; } /// <summary> /// Return the squared result of an integer. /// </summary> [DebuggerStepThrough] public static int Square(this int i) { return i*i; } /// <summary> /// Convert a string to a byte array using code page 437. /// </summary> [DebuggerStepThrough] public static byte[] ToBytes(this string value) { return string.IsNullOrEmpty(value) ? new byte[0] : CodePage437.GetBytes(value); } /// <summary> /// Convert an integer to a character using code page 437. /// </summary> [DebuggerStepThrough] public static char ToChar(this int value) { return CodePage437.GetChars(new[] {(byte) (value & 0xFF)})[0]; } /// <summary> /// Get the lowercase representation of an ASCII char stored as a byte. /// </summary> [DebuggerStepThrough] public static int ToLowerCase(this byte value) { if (value >= 0x41 && value <= 0x5A) { value -= 0x20; } return value; } /// <summary> /// Convert an integer to a string using code page 437. /// </summary> [DebuggerStepThrough] public static string ToStringValue(this int value) { return CodePage437.GetString(new[] {(byte) (value & 0xFF)}); } /// <summary> /// Convert a byte array to a string using code page 437. /// </summary> [DebuggerStepThrough] public static string ToStringValue(this byte[] value) { return CodePage437.GetString(value); } /// <summary> /// Get the uppercase representation of an input key. /// </summary> [DebuggerStepThrough] public static EngineKeyCode ToUpperCase(this EngineKeyCode value) { return (EngineKeyCode) ((int) value).ToUpperCase(); } /// <summary> /// Get the uppercase representation of an ASCII char stored as a byte. /// </summary> [DebuggerStepThrough] public static int ToUpperCase(this byte value) => ToUpperCase((int) value); /// <summary> /// Get the uppercase representation of an ASCII char stored as an integer. /// </summary> [DebuggerStepThrough] public static int ToUpperCase(this int value) { if (value >= 0x61 && value <= 0x7A) { value -= 0x20; } return value; } /// <summary> /// Get the uppercase representation of an ASCII char stored as an integer. /// </summary> [DebuggerStepThrough] public static char ToUpperCase(this char input) { unchecked { return (char) ToUpperCase((int)input); } } /// <summary> /// Compares source string to another string, with the source UpperCased. /// </summary> [DebuggerStepThrough] public static bool CaseInsensitiveEqual(this string a, string b) { if ((a == null) != (b == null)) return false; if (a == null) return true; if (a.Length != b.Length) return false; for (var i = 0; i < a.Length; i++) { if (a[i].ToUpperCase() != b[i]) return false; } return true; } /// <summary> /// Compares source string to another string, with the source UpperCased, and only A-Z. /// </summary> [DebuggerStepThrough] public static bool CaseInsensitiveCharacterEqual(this string a, string b) { var i = 0; var j = 0; if ((a == null) != (b == null)) return false; if (a == null) return true; while (i < a.Length) { var ai = a[i].ToUpperCase(); if (ai >= 0x41 && ai <= 0x5A) { if (j >= b.Length) break; if (ai != b[j]) return false; j++; } i++; } return i == a.Length && j == b.Length; } } }
using Core.Domain; using Core.Interfaces; using System; using System.Threading.Tasks; using UserSettings.Exceptions; using UserSettings.Interfaces; namespace UserSettings { public class SettingProvider : ISettingProvider { private readonly ISettingDbContext _settingDbContext; public SettingProvider(ISettingDbContext settingDbContext) { _settingDbContext = settingDbContext; } public T GetSettingValue<T>(string key) { var result = _settingDbContext.Settings.Find(key); return ConvertToType<T>(key, result); } private static T ConvertToType<T>(string key, Setting result) { if (result == null) { throw new SettingKeyNotFoundExcetion(key); } try { return (T)Convert.ChangeType(result.Value, typeof(T)); } catch { throw new SettingTypeConvertionException(key, typeof(T)); } } public async Task<T> GetSettingValueAsync<T>(string key) { var result = await _settingDbContext.Settings.FindAsync(key); return ConvertToType<T>(key, result); } public async Task<bool> SetSettingValueAsync<T>(string key, T value) { _settingDbContext.Settings.Add(new Setting { Key = key, Value = value.ToString() }); var result = await _settingDbContext.SaveChangesAsync(); return result > 0; } } }
using BeatTogether.MasterServer.Messaging.Abstractions.Messages; using Krypton.Buffers; namespace BeatTogether.MasterServer.Messaging.Abstractions { public interface IMessageWriter { /// <summary> /// Writes a message to the given buffer. /// This will include message headers. /// </summary> /// <typeparam name="T">The type of message to serialize.</typeparam> /// <param name="buffer">The buffer to write to.</param> /// <param name="message">The message to serialize.</param> /// <param name="packetProperty">The LiteNetLib PacketProperty to compare against.</param> void WriteTo<T>(ref GrowingSpanBuffer buffer, T message, byte packetProperty = 0x08) where T : class, IMessage; } }
using System.Text; using System.Threading.Tasks; namespace DesignPatternsInCSharp.Adapter { public class StarWarsCharacterDisplayService { private readonly PeopleDataAdapter _peopleDataAdapter; public StarWarsCharacterDisplayService(PeopleDataAdapter peopleDataAdapter) { _peopleDataAdapter = peopleDataAdapter; } public async Task<string> ListCharacters() { var people = await _peopleDataAdapter.GetPeople(); var sb = new StringBuilder(); int nameWidth = 20; sb.AppendLine($"{"NAME".PadRight(nameWidth)} {"GENDER"}"); foreach (Person person in people) { sb.AppendLine($"{person.Name.PadRight(nameWidth)} {person.Gender}"); } return sb.ToString(); } } }
using Newtonsoft.Json; namespace Nindo.Net.Models { public class TiktokChannel : ChannelBase { [JsonProperty("followings")] public string Followings { get; set; } [JsonProperty("totalLikes")] public string TotalLikes { get; set; } [JsonProperty("likesGiven")] public string LikesGiven { get; set; } [JsonProperty("totalPosts")] public string TotalPosts { get; set; } [JsonProperty("avgLikes5")] public ulong AvgLikesFive { get; set; } [JsonProperty("avgComments5")] public ulong AvgCommentsFive { get; set; } [JsonProperty("avgShares5")] public ulong AvgSharesFive { get; set; } [JsonProperty("avgViews5")] public ulong AvgViewsFive { get; set; } [JsonProperty("avgEngagement5")] public double AvgEngagementFive { get; set; } [JsonProperty("rankLikes")] public ulong? RankLikes { get; set; } [JsonProperty("rankComments")] public string RankComments { get; set; } [JsonProperty("rankShares")] public string RankShares { get; set; } [JsonProperty("rankViews")] public ulong? RankViews { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeAround.FluentBatch.Infrastructure { public static class ExceptionExtension { public static string ToExceptionString(this System.Exception ex) { StringBuilder sb = new StringBuilder(); if (!String.IsNullOrEmpty(ex.Message)) { sb.AppendFormat("Message = '{0}'", ex.Message.Trim()); } if (!String.IsNullOrEmpty(ex.Source)) { if (sb.Length > 0) sb.Append(" | "); sb.AppendFormat("Source = '{0}'", ex.Source.Trim()); } if (!String.IsNullOrEmpty(ex.StackTrace)) { if (sb.Length > 0) sb.Append(" | "); sb.AppendFormat("StackTrace = '{0}'", ex.StackTrace.Trim()); } if (ex.InnerException != null) { if (sb.Length > 0) sb.Append(" | "); sb.AppendFormat("Inner Exception = '{0}'", ex.InnerException.ToExceptionString()); } return sb.ToString(); } public static string ToExceptionString(this System.Exception ex, Dictionary<string, string> fields) { StringBuilder sb = new StringBuilder(); string result = ToExceptionString(ex); if (fields != null && fields.Count > 0) { foreach (var item in fields) { if (sb.Length > 0) sb.Append(" | "); sb.AppendFormat("{0}: {1}", item.Key, item.Value); } } if (sb.Length > 0) result = String.Format("{0}. Other Fields", result, sb.ToString()); return result; } } }
namespace FisSst.BlazorMaps { /// <summary> /// It is a subset of MapOptions. /// </summary> public class MapSubOptions { public string Id { get; set; } public string Attribution { get; set; } public int MaxZoom { get; set; } public int TileSize { get; set; } public int ZoomOffset { get; set; } public string AccessToken { get; set; } } }
using System; namespace Domain.Entities { public class Alerta { public string Id { get; set; } public Ponto Ponto { get; set; } public Distrito Distrito { get; set; } public DateTime TempoInicio { get; set; } public DateTime TempoFinal { get; set; } public string Descricao { get; set; } public bool Transitividade { get; set; } public bool Atividade { get; set; } } }
using System; namespace ConventionalRegistration.TypeFiltering { /// <summary> /// Provides methods to exclude specific implementations. /// </summary> public interface IImplementationFilter { void ExcludeImplementation(Type implementation); } }
using System; namespace IoTConnect.Model { public class AllCommandResult { /// <summary> /// Command Guid. /// </summary> public string guid { get; set; } /// <summary> /// Command Name. /// </summary> public string name { get; set; } /// <summary> /// Command /// </summary> public string command { get; set; } /// <summary> /// Created Date. /// </summary> public DateTime createdDate { get; set; } /// <summary> /// Created By. /// </summary> public string createdby { get; set; } /// <summary> /// Updated Date. /// </summary> public DateTime updatedDate { get; set; } /// <summary> /// Required Param ? /// </summary> public bool requiredParam { get; set; } /// <summary> /// Required Ack ? /// </summary> public bool requiredAck { get; set; } /// <summary> /// Is OTA Command. /// </summary> public bool isOTACommand { get; set; } /// <summary> /// Template Tag. /// </summary> public string tag { get; set; } } }
using System; public struct Vector { public int X, Y; public Vector(int x, int y) { this.X = x; this.Y = y; } // this is one thing i can't do in Javascript public static Vector operator +(Vector a, Vector b) { return new Vector(a.X + b.X, a.Y + b.Y); } public static Vector operator -(Vector a, Vector b) { return new Vector(a.X - b.X, a.Y - b.Y); } public static Vector operator *(Vector a, double factor) { return new Vector((int)(a.X * factor), (int)(a.Y * factor)); } public static bool operator ==(Vector a, Vector b) { return a.X == b.X && a.Y == b.Y; } public static bool operator !=(Vector a, Vector b) { return a.X != b.X || a.Y != b.Y; } public static Vector operator -(Vector a) { return new Vector(-a.X, -a.Y); } }
namespace Chat { public interface IChatUser { string Password { get; set; } string UserId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FameBot.Data.Events { public class FameUpdateEventArgs : EventArgs { private int fame; private int fameGoal; public int Fame { get { return fame; } } public int FameGoal { get { return fameGoal; } } public FameUpdateEventArgs(int fame, int fameGoal) : base() { this.fame = fame; this.fameGoal = fameGoal; } } }
namespace CnSharp.Updater { public class ReleaseFile { public string FileName { get; set; } //public string ReleaseDate { get; set; } /// <summary> /// File size in Byte /// </summary> public long FileSize { get; set; } public string Version { get; set; } } }
namespace Vega.Schema { public struct LayoutOffset { public double? Double; public Offset Offset; public static implicit operator LayoutOffset(double Double) => new LayoutOffset { Double = Double }; public static implicit operator LayoutOffset(Offset offset) => new LayoutOffset { Offset = offset }; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace ETModel { public class CommandInput_UseSkill : ICommandInput { public string skillId; public string pipelineSignal;//输入环节的pipelineSignal public IBufferValue bufferValue;//输入的内容 } }
using BootEngine.Utils.ProfilingTools; using System.Numerics; namespace BootEngine.Renderer.Cameras { //TODO: Check the viability of merging this with Camera internal sealed class ImGuiCamera : Camera { private readonly float left; private readonly float right; private readonly float bottom; private readonly float top; public ImGuiCamera(float left, float right, float bottom, float top) : base(false) { this.left = left; this.right = right; this.top = top; this.bottom = bottom; RecalculateProjection(); } protected override void RecalculateProjection() { #if DEBUG using Profiler fullProfiler = new Profiler(GetType()); #endif if (useReverseDepth) { projectionMatrix = Matrix4x4.CreateOrthographicOffCenter(left, right, bottom, top, OrthoFar, OrthoNear); } else { projectionMatrix = Matrix4x4.CreateOrthographicOffCenter(left, right, bottom, top, OrthoNear, OrthoFar); } if (SwapYAxis) { projectionMatrix *= new Matrix4x4( 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } } } }
using Api.Controllers; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using System; using Microsoft.EntityFrameworkCore; namespace Api { public static class ApiConfiguration { public static IServiceCollection ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddApiVersioning(setup => { setup.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0); setup.AssumeDefaultVersionWhenUnspecified = true; }).AddDbContext<FooContext>(options => { options.UseSqlServer("Server=.;Initial Catalog=FooDatabase;Integrated Security=true", setup => { setup.MaxBatchSize(10); setup.MigrationsAssembly("HostApi"); }); }).AddAuthorization(setup => { setup.AddPolicy("mypolicy", builder => { builder.RequireClaim("CustomClaim"); }); }); return services; } public static void Configure(IApplicationBuilder app) { } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel { using System; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel.Channels; [Serializable] public class ActionNotSupportedException : CommunicationException { public ActionNotSupportedException() { } public ActionNotSupportedException(string message) : base(message) { } public ActionNotSupportedException(string message, Exception innerException) : base(message, innerException) { } protected ActionNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal Message ProvideFault(MessageVersion messageVersion) { Fx.Assert(messageVersion.Addressing != AddressingVersion.None, ""); FaultCode code = FaultCode.CreateSenderFaultCode(AddressingStrings.ActionNotSupported, messageVersion.Addressing.Namespace); string reason = this.Message; return System.ServiceModel.Channels.Message.CreateMessage( messageVersion, code, reason, messageVersion.Addressing.FaultAction); } } }
using CarBookingAPI.Core.Contracts.ViewModels; using System; namespace CarBookingAPI.Infrastructure.ViewModels { public class ReservationsViewModel : IViewModel { public Guid? Id { get; set; } public DateTime? ReservedAt { get; set; } public DateTime? ReservedUntil { get; set; } public Guid? CarId { get; set; } public Guid? UserId { get; set; } public CarsViewModel Car { get; set; } public UsersViewModel User { get; set; } } }
// Copyright (c) 2017 Trevor Redfern // // This software is released under the MIT License. // https://opensource.org/licenses/MIT namespace Tests.Characters.Prerequisites { using Xunit; using Moq; using SilverNeedle.Characters.Prerequisites; using SilverNeedle.Characters.Magic; public class IsSpellCasterTests { [Fact] public void IsQualifiedIfHasSpellCastingComponent() { var isSpellcaster = new IsSpellCaster(); var bob = CharacterTestTemplates.AverageBob(); Assert.False(isSpellcaster.IsQualified(bob.Components)); var sc = new Mock<ISpellCasting>(); bob.Add(sc.Object); Assert.True(isSpellcaster.IsQualified(bob.Components)); } } }
namespace BalkanAir.Api.Tests.RouteTests { using System.Net.Http; using Microsoft.VisualStudio.TestTools.UnitTesting; using MyTested.WebApi; using MyTested.WebApi.Exceptions; using Newtonsoft.Json; using Controllers; using TestObjects; [TestClass] public class NewsRouteTests { private const string CREATE_PATH = "/Api/News/Create/"; private const string GET_PATH_WITH_INVALID_ACTION = "/Api/New/"; private const string GET_PATH = "/Api/News/"; private const string GET_LATEST_NEWS_PATH = "/Api/News/Latest/"; private const string UPDATE_PATH = "/Api/News/Update/"; private const string DELETE_PATH = "/Api/News/Delete/"; [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void CreateShouldThrowExceptionWithRouteDoesNotExistWhenHttpMethodIsInvalid() { var newsRequestModel = TestObjectFactoryDataTransferModels.GetValidNewsRequestModel(); string jsonContent = JsonConvert.SerializeObject(newsRequestModel); var invalidHttpMethod = HttpMethod.Get; MyWebApi .Routes() .ShouldMap(CREATE_PATH) .WithJsonContent(jsonContent) .And() .WithHttpMethod(invalidHttpMethod) .To<NewsController>(n => n.Create(newsRequestModel)); } [TestMethod] public void CreateShouldMapCorrectAction() { var newsRequestModel = TestObjectFactoryDataTransferModels.GetValidNewsRequestModel(); string jsonContent = JsonConvert.SerializeObject(newsRequestModel); MyWebApi .Routes() .ShouldMap(CREATE_PATH) .WithJsonContent(jsonContent) .And() .WithHttpMethod(HttpMethod.Post) .To<NewsController>(n => n.Create(newsRequestModel)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void GetAllShouldThrowExceptionWithRouteDoesNotExistWhenActionIsInvalid() { MyWebApi .Routes() .ShouldMap(GET_PATH_WITH_INVALID_ACTION) .WithHttpMethod(HttpMethod.Get) .To<NewsController>(n => n.All()); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void GetAllShouldThrowExceptionWithRouteDoesNotExistWhenControllerIsInvalid() { MyWebApi .Routes() .ShouldMap(GET_PATH) .WithHttpMethod(HttpMethod.Get) .To<FlightsController>(n => n.All()); } [TestMethod] public void GetAllShouldMapCorrectAction() { MyWebApi .Routes() .ShouldMap(GET_PATH) .WithHttpMethod(HttpMethod.Get) .To<NewsController>(n => n.All()); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void GetByIdShouldThrowExceptionWithRouteDoesNotExistWhenIdIsNegative() { var negativeId = -1; MyWebApi .Routes() .ShouldMap(GET_PATH + negativeId) .WithHttpMethod(HttpMethod.Get) .To<NewsController>(n => n.Get(negativeId)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void GetByIdShouldThrowExceptionWithDifferenParameterWhenIdDoesNotMatch() { var pathId = 1; var methodId = 2; MyWebApi .Routes() .ShouldMap(GET_PATH + pathId) .WithHttpMethod(HttpMethod.Get) .To<NewsController>(n => n.Get(methodId)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void GetByIdShouldThrowExceptionWithRouteDoesNotExistWhenIdIsNotInteger() { var notIntegerId = "a"; MyWebApi .Routes() .ShouldMap(GET_PATH + notIntegerId) .WithHttpMethod(HttpMethod.Get) .To<NewsController>(n => n.Get(1)); } [TestMethod] public void GetByIdShouldMapCorrectAction() { var validId = 1; MyWebApi .Routes() .ShouldMap(GET_PATH + validId) .WithHttpMethod(HttpMethod.Get) .To<NewsController>(n => n.Get(validId)); } [TestMethod] public void GetLatestNewsShouldMapCorrectActionWhenCountIsValid() { var validCount = 1; MyWebApi .Routes() .ShouldMap(GET_LATEST_NEWS_PATH + validCount) .WithHttpMethod(HttpMethod.Get) .To<NewsController>(n => n.GetLatestNews(validCount)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void GetLatestNewsShouldThrowExceptionWithRouteDoesNotExistWhenCountIsNotSet() { var validCategory = "category"; MyWebApi .Routes() .ShouldMap(GET_LATEST_NEWS_PATH + validCategory) .WithHttpMethod(HttpMethod.Get) .To<NewsController>(n => n.GetLatesByCategory(1, validCategory)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void GetLatestNewsShouldThrowExceptionWithRouteDoesNotExistWhenCategoryIsNotSet() { var validCount = 1; MyWebApi .Routes() .ShouldMap(GET_LATEST_NEWS_PATH + validCount) .WithHttpMethod(HttpMethod.Get) .To<NewsController>(n => n.GetLatesByCategory(validCount, string.Empty)); } [TestMethod] public void GetLatestNewsShouldMapCorrectActionWhenCountAndCategoryAreValid() { var validCount = 1; var validCategory = "category"; MyWebApi .Routes() .ShouldMap(GET_LATEST_NEWS_PATH + validCount + "/" + validCategory) .WithHttpMethod(HttpMethod.Get) .To<NewsController>(n => n.GetLatesByCategory(validCount, validCategory)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void UpdateShouldThrowExceptionWithRouteDoesNotExistWhenIdIsNegative() { var updateRequestModel = TestObjectFactoryDataTransferModels.GetValidUpdateNewsRequestModel(); var jsonContent = JsonConvert.SerializeObject(updateRequestModel); var negativeId = -1; MyWebApi .Routes() .ShouldMap(UPDATE_PATH + negativeId) .WithJsonContent(jsonContent) .And() .WithHttpMethod(HttpMethod.Put) .To<NewsController>(n => n.Update(negativeId, updateRequestModel)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void UpdateShouldThrowExceptionWithDifferenParameterWhenIdDoesNotMatch() { var updateRequestModel = TestObjectFactoryDataTransferModels.GetValidUpdateNewsRequestModel(); var jsonContent = JsonConvert.SerializeObject(updateRequestModel); var pathId = 1; var methodId = 2; MyWebApi .Routes() .ShouldMap(UPDATE_PATH + pathId) .WithJsonContent(jsonContent) .And() .WithHttpMethod(HttpMethod.Put) .To<NewsController>(n => n.Update(methodId, updateRequestModel)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void UpdateShouldThrowExceptionWithRouteDoesNotExistWhenIdIsNotInteger() { var updateRequestModel = TestObjectFactoryDataTransferModels.GetValidUpdateNewsRequestModel(); var jsonContent = JsonConvert.SerializeObject(updateRequestModel); var notIntegerId = "a"; MyWebApi .Routes() .ShouldMap(UPDATE_PATH + notIntegerId) .WithJsonContent(jsonContent) .And() .WithHttpMethod(HttpMethod.Put) .To<NewsController>(n => n.Update(updateRequestModel.Id, updateRequestModel)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void UpdateShouldThrowExceptionWithRouteDoesNotExistWhenHttpMethodIsInvalid() { var updateRequestModel = TestObjectFactoryDataTransferModels.GetValidUpdateNewsRequestModel(); var jsonContent = JsonConvert.SerializeObject(updateRequestModel); var invalidHttpMethod = HttpMethod.Post; MyWebApi .Routes() .ShouldMap(UPDATE_PATH + updateRequestModel.Id) .WithJsonContent(jsonContent) .And() .WithHttpMethod(invalidHttpMethod) .To<NewsController>(n => n.Update(updateRequestModel.Id, updateRequestModel)); } [TestMethod] public void UpdateShouldMapCorrectAction() { var updateRequestModel = TestObjectFactoryDataTransferModels.GetValidUpdateNewsRequestModel(); var jsonContent = JsonConvert.SerializeObject(updateRequestModel); MyWebApi .Routes() .ShouldMap(UPDATE_PATH + updateRequestModel.Id) .WithJsonContent(jsonContent) .And() .WithHttpMethod(HttpMethod.Put) .To<NewsController>(n => n.Update(updateRequestModel.Id, updateRequestModel)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void DeleteShouldThrowExceptionWithRouteDoesNotExistWhenIdIsNegative() { var negativeId = -1; MyWebApi .Routes() .ShouldMap(DELETE_PATH + negativeId) .WithHttpMethod(HttpMethod.Delete) .To<NewsController>(n => n.Delete(negativeId)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void DeleteShouldThrowExceptionWithDifferenParameterWhenIdDoesNotMatch() { var pathId = 1; var methodId = 2; MyWebApi .Routes() .ShouldMap(DELETE_PATH + pathId) .WithHttpMethod(HttpMethod.Delete) .To<NewsController>(n => n.Delete(methodId)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void DeleteShouldThrowExceptionWithRouteDoesNotExistWhenIdIsNotInteger() { var notIntegerId = "a"; MyWebApi .Routes() .ShouldMap(DELETE_PATH + notIntegerId) .WithHttpMethod(HttpMethod.Delete) .To<NewsController>(n => n.Delete(1)); } [TestMethod] [ExpectedException(typeof(RouteAssertionException))] public void DeleteShouldThrowExceptionWithRouteDoesNotExistWhenHttpMethodIsInvalid() { var validId = 1; var invalidHttpMethod = HttpMethod.Post; MyWebApi .Routes() .ShouldMap(DELETE_PATH + validId) .WithHttpMethod(invalidHttpMethod) .To<NewsController>(n => n.Delete(validId)); } [TestMethod] public void DeleteShouldMapCorrectAction() { var validId = 1; MyWebApi .Routes() .ShouldMap(DELETE_PATH + validId) .WithHttpMethod(HttpMethod.Delete) .To<NewsController>(n => n.Delete(validId)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Dealer : MonoBehaviour,IVehicleViewChanged { public VehicleView view; public Text PriceText; List<VehicleInfo> vehicleInfoList; // Start is called before the first frame update async void OnEnable() { Resources.LoadAll<VehicleInfo>("ModSystem/Objects"); var vehicles = new List<Save.Vehicle>(); vehicleInfoList =new List<VehicleInfo>( Resources.FindObjectsOfTypeAll<VehicleInfo>()); foreach (var item in vehicleInfoList) { vehicles.Add(item.GetSaveVehicle()); } view.Vehicles = vehicles; await view.SpawnVehicle(0); } // Update is called once per frame public void BuyButton() { VehicleInfo vehicle = vehicleInfoList[view.SelectedIndex]; if (SaveSystem.GetCash()>=vehicle.Price) { Save.Vehicle v = vehicle.GetSaveVehicle(); SaveSystem.AddVehicle(v); SaveSystem.AddCash(-vehicle.Price); SaveSystem.AddLog(new Save.LogEntry("Dealer",$"Added car {v.Type}")); SaveSystem.SetSelectedVehicleIndex(SaveSystem.GetVehicles().Count-1); GarageManager.instance.CloseDealerMenu(); } else { Debug.Log("git gud fagit"); } } public void Changed(int id) { PriceText.text = $"Price: $ {vehicleInfoList[view.SelectedIndex].Price}"; } }
using iTextSharp.text; using System; using System.Collections.Generic; using System.Text; namespace Com.Danliris.Service.Packing.Inventory.Application.ToBeRefactored.GarmentShipping.Monitoring.GarmentCreditAdvice { public class GarmentCreditAdviceMonitoringViewModel { public string InvoiceNo { get; set; } public DateTimeOffset InvoiceDate { get; set; } public double Amount { get; set; } public double ToBePaid { get; set; } public double NettNego { get; set; } public string PaymentTerm { get; set; } public string BuyerName { get; set; } public string BuyerAddress { get; set; } public DateTimeOffset PaymentDate { get; set; } public string BankName { get; set; } public DateTimeOffset DocUploadDate { get; set; } // TT public double NettNegoTT { get; set; } public double BankChargeTT { get; set; } public double OtherChargeTT { get; set; } // LC public string SRNo { get; set; } public DateTimeOffset SRDate { get; set; } public string LCNo { get; set; } public double NettNegoLC { get; set; } public double BankChargeLC { get; set; } public double BankComissionLC { get; set; } public double DiscreapancyFeeLC { get; set; } public double CreditInterestLC { get; set; } } }
using System.Collections.Immutable; using System.Linq; using MyCompany.Crm.Sales.Commons; using MyCompany.Crm.Sales.Pricing; using MyCompany.Crm.TechnicalStuff.Metadata; using MyCompany.Crm.TechnicalStuff.Metadata.DDD; namespace MyCompany.Crm.Sales.Orders.PriceChanges { [Stateless] [DddPolicy] public class AllowPriceChangesIfTotalPriceIsLower : PriceChangesPolicy { public bool CanChangePrices(ImmutableArray<Quote> actualQuotes, ImmutableArray<Quote> newQuotes) => GetTotalPrice(newQuotes) < GetTotalPrice(actualQuotes); private static Money GetTotalPrice(ImmutableArray<Quote> quotes) => quotes .Select(quote => quote.Price) .Aggregate((totalPrice, price) => totalPrice + price); } }
using System; using System.Runtime.Serialization; using System.Security.Cryptography; namespace TaskyJ.Globals.Data.DataObjects { public class DBSessionJ : BaseEntity { [DataMember] public int IDUser { get; set; } [DataMember] public string UserName { get; set; } [DataMember] public DateTime CreateDate { get; set; } [DataMember] public string IpAddress { get; set; } [DataMember] public string JwtToken { get; set; } [DataMember] public DateTime Expires { get; set; } public DBRefreshTokenJ RefreshToken { get; set; } public override string ToString() { return UserName; } public override bool Equals(BaseEntity source) { if (source is DBSessionJ sourcej) { //TODO: complete equals method return UserName == sourcej.UserName && JwtToken == sourcej.JwtToken && CreateDate == sourcej.CreateDate && IpAddress == sourcej.IpAddress && base.Equals(source); } else { return base.Equals(source); } } public DBRefreshTokenJ getRefreshToken(string ipAddress) { using (var rngCryptoServiceProvider = new RNGCryptoServiceProvider()) { var randomBytes = new byte[64]; rngCryptoServiceProvider.GetBytes(randomBytes); return new DBRefreshTokenJ { Token = Convert.ToBase64String(randomBytes), Expires = DateTime.UtcNow.AddDays(7), Created = DateTime.UtcNow, CreatedByIp = ipAddress }; } } } }
using System; using System.Collections.Generic; using System.Text; namespace FluentCommands.Exceptions { /// <summary> /// This interface marks an exception as suitable for automatic logging for FluentCommands' CommandLogger. /// </summary> internal interface IFluentCommandsException { string? Description { get; } Exception? Inner { get; } } }
using System; using System.Collections.Generic; using System.Text; namespace Twetterr.Contracts { public interface IServer { void SaveToServer(string message); } }
namespace LaserCutterTools.BoxBuilder { public sealed class BoxSquare : IBoxSquare { public decimal DimensionX { get; set; } public decimal DimensionY { get; set; } public decimal DimensionZ { get; set; } public MeasurementModel MeasurementModel { get; set; } public BoxSquare() { DimensionX = 0m; DimensionY = 0m; DimensionZ = 0m; MeasurementModel = MeasurementModel.Outside; // Always default to outside model } } }
using Microsoft.AspNetCore.Mvc; using Uqs.AppointmentBooking.Domain.Services; namespace Uqs.AppointmentBooking.WebApi.Controllers; [ApiController] [Route("[controller]")] public class EmployeesController : ControllerBase { private readonly IEmployeesService _employeesService; public EmployeesController(IEmployeesService employeesService) { _employeesService = employeesService; } [HttpGet] public async Task<ActionResult<Contract.AvailableEmployees>> AvailableEmployees() { var employees = await _employeesService.GetEmployees(); Contract.Employee[] emps = employees.Select( x => new Contract.Employee(x.Id, x.Name!)).ToArray(); return new Contract.AvailableEmployees(emps); } }
using System; using System.Linq; using BinarySearchTree; var bst = new Bst<string, string>(); var input = "E A S Y Q U E S T I O N".Split(' ', StringSplitOptions.RemoveEmptyEntries); foreach (var key in input) { bst.Put(key, key); } while (!bst.IsEmpty()) { Console.WriteLine(bst); bst.Delete(bst.ToKeyArray().First()); }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; namespace SmartStore.Core.Domain.Catalog { public partial class ProductBundleItemData { public ProductBundleItemData(ProductBundleItem item) { Item = item; // can be null... test with IsValid } public ProductBundleItem Item { get; private set; } public decimal AdditionalCharge { get; set; } } public partial class ProductBundleItemOrderData { public int BundleItemId { get; set; } public int ProductId { get; set; } public string Sku { get; set; } public string ProductName { get; set; } public string ProductSeName { get; set; } public bool VisibleIndividually { get; set; } public int Quantity { get; set; } public decimal PriceWithDiscount { get; set; } public int DisplayOrder { get; set; } public string AttributesXml { get; set; } public string AttributesInfo { get; set; } public bool PerItemShoppingCart { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace MackySoft.Modiferty { [CustomPropertyDrawer(typeof(SecureModifieableProperty<>),true)] [CustomPropertyDrawer(typeof(ModifiableInt))] public class ModifiablePropertyDrawer : PropertyDrawer { public override void OnGUI (Rect position,SerializedProperty property,GUIContent label) { var baseValue = property.FindPropertyRelative("m_BaseValue"); EditorGUI.PropertyField(position,baseValue,label); } } }
using System; using System.Collections.Generic; using System.Text; namespace Dracoon.Sdk.Model { public class PublicDownloadShare { public bool IsProtected { get; internal set; } public string FileName { get; internal set; } public long Size { get; internal set; } public bool LimitReached { get; internal set; } public string CreatorName { get; internal set; } public DateTime CreatedAt { get; internal set; } public bool HasDownloadLimit { get; internal set; } public string MediaType { get; internal set; } public string Name { get; internal set; } public string CreatorUsername { get; internal set; } public DateTime? ExpireAt { get; internal set; } public string Notes { get; internal set; } public bool? IsEncrypted { get; internal set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using dfproto; using ProtoBuf; namespace DFHack { public class RemoteFunctionBase : RPCFunctionBase { public bool Bind(RemoteClient client, string name, string proto = "") { return Bind(client.DefaultOutput, client, name, proto); } public bool Bind(IDFStream output, RemoteClient client, string name, string proto = "") { if (IsValid()) { if (PClient == client && Name == name && Proto == proto) return true; output.PrintErr("Function already bound to %s::%s\n", Proto, Name); return false; } Name = name; Proto = proto; PClient = client; return client.Bind(output, this, name, proto); } public bool IsValid() { return (Id >= 0); } public RemoteFunctionBase(IExtensible input, IExtensible output) : base(input, output) { PClient = null; Id = -1; } protected IDFStream DefaultOstream { get { return PClient.DefaultOutput; } } bool SendRemoteMessage(Socket socket, Int16 id, MemoryStream msg) { var buffer = new List<byte>(); RpcMessageHeader header = new RpcMessageHeader { Id = id, Size = (Int32) msg.Length }; buffer.AddRange(header.ConvertToBtyes()); buffer.AddRange(msg.ToArray()); int fullsz = buffer.Count; int got = socket.Send(buffer.ToArray()); return (got == fullsz); } protected TOutput Execute<TInput, TOutput>(IDFStream stream, TInput input) where TInput : class, IExtensible, new() where TOutput : class, IExtensible, new() { TOutput value; var result = TryExecute(stream, input, out value); if (result == CommandResult.CrOk) return value; else throw new InvalidOperationException("Remotefunction encountered error: " + value); } protected CommandResult TryExecute<TInput, TOutput>(IDFStream outString, TInput input, out TOutput output) where TInput : class, IExtensible, new() where TOutput : class, IExtensible, new() { if (!IsValid()) { outString.PrintErr("Calling an unbound RPC function %s::%s.\n", Proto, Name); output = default(TOutput); return CommandResult.CrNotImplemented; } if (PClient.Socket == null) { outString.PrintErr("In call to %s::%s: invalid socket.\n", Proto, Name); output = default(TOutput); return CommandResult.CrLinkFailure; } MemoryStream sendStream = new MemoryStream(); Serializer.Serialize(sendStream, input); long sendSize = sendStream.Length; if (sendSize > RpcMessageHeader.MaxMessageSize) { outString.PrintErr("In call to %s::%s: message too large: %d.\n", Proto, Name, sendSize); output = default(TOutput); return CommandResult.CrLinkFailure; } if (!SendRemoteMessage(PClient.Socket, Id, sendStream)) { outString.PrintErr("In call to %s::%s: I/O error in send.\n", Proto, Name); output = default(TOutput); return CommandResult.CrLinkFailure; } ColorOstreamProxy textDecoder = new ColorOstreamProxy(outString); //output = new Output(); //return command_result.CR_OK; while (true) { RpcMessageHeader header = new RpcMessageHeader(); byte[] buffer = new byte[8]; if (!RemoteClient.ReadFullBuffer(PClient.Socket, buffer, 8)) { outString.PrintErr("In call to %s::%s: I/O error in receive header.\n", Proto, Name); output = default(TOutput); return CommandResult.CrLinkFailure; } header.Id = BitConverter.ToInt16(buffer, 0); header.Size = BitConverter.ToInt32(buffer, 4); //because something, somewhere, is fucking retarded //outString.print("Received %d:%d.\n", header.id, header.size); if ((DfHackReplyCode)header.Id == DfHackReplyCode.RpcReplyFail) { output = default(TOutput); if (header.Size == (int)CommandResult.CrOk) return CommandResult.CrFailure; else return (CommandResult)header.Size; } if (header.Size < 0 || header.Size > RpcMessageHeader.MaxMessageSize) { outString.PrintErr("In call to %s::%s: invalid received size %d.\n", Proto, Name, header.Size); output = default(TOutput); return CommandResult.CrLinkFailure; } byte[] buf = new byte[header.Size]; if (!RemoteClient.ReadFullBuffer(PClient.Socket, buf, header.Size)) { outString.PrintErr("In call to %s::%s: I/O error in receive %d bytes of data.\n", Proto, Name, header.Size); output = default(TOutput); return CommandResult.CrLinkFailure; } switch ((DfHackReplyCode)header.Id) { case DfHackReplyCode.RpcReplyResult: output = Serializer.Deserialize<TOutput>(new MemoryStream(buf)); if (output != null) return CommandResult.CrOk; outString.PrintErr("In call to %s::%s: error parsing received result.\n", Proto, Name); return CommandResult.CrLinkFailure; case DfHackReplyCode.RpcReplyText: var textData = Serializer.Deserialize<CoreTextNotification>(new MemoryStream(buf)); if (textData != null) { textDecoder.Decode(textData); } else outString.PrintErr("In call to %s::%s: received invalid text data.\n", Proto, Name); break; } } } public string Name, Proto; public RemoteClient PClient; public Int16 Id; } }
namespace Nutanix.Powershell.ModelCmdlets { using static Microsoft.Rest.ClientRuntime.Extensions; /// <summary>Cmdlet to create an in-memory instance of the <see cref="Address" /> object.</summary> [System.Management.Automation.Cmdlet(System.Management.Automation.VerbsCommon.New, @"AddressObject")] [System.Management.Automation.OutputType(typeof(Nutanix.Powershell.Models.IAddress))] public class NewAddressObject : System.Management.Automation.PSCmdlet { /// <summary>Backing field for <see cref="Address" /></summary> private Nutanix.Powershell.Models.IAddress _address = new Nutanix.Powershell.Models.Address(); /// <summary>Fully qualified domain name.</summary> [System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Fully qualified domain name.")] public string Fqdn { set { _address.Fqdn = value; } } /// <summary>IPV4 address.</summary> [System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "IPV4 address.")] public string Ip { set { _address.Ip = value; } } /// <summary>IPV6 address.</summary> [System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "IPV6 address.")] public string Ipv6 { set { _address.Ipv6 = value; } } /// <summary>Port Number</summary> [System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Port Number")] public int Port { set { _address.Port = value; } } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { WriteObject(_address); } } }
// 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; namespace Microsoft.Toolkit.Uwp.Services.Facebook { /// <summary> /// List of user related data permissions /// </summary> [Flags] public enum FacebookPermissions { /// <summary> /// Public profile /// </summary> PublicProfile = 1, /// <summary> /// Email /// </summary> Email = 2, /// <summary> /// Publish actions /// </summary> PublishActions = 4, /// <summary> /// About me /// </summary> UserAboutMe = 8, /// <summary> /// Birthday /// </summary> UserBirthday = 16, /// <summary> /// Education history /// </summary> UserEducationHistory = 32, /// <summary> /// Friends /// </summary> UserFriends = 64, /// <summary> /// Games activity /// </summary> UserGamesActivity = 128, /// <summary> /// Hometown /// </summary> UserHometown = 256, /// <summary> /// Likes /// </summary> UserLikes = 512, /// <summary> /// Location /// </summary> UserLocation = 1024, /// <summary> /// Photos /// </summary> UserPhotos = 2048, /// <summary> /// Posts /// </summary> UserPosts = 4096, /// <summary> /// Relationship details /// </summary> UserRelationshipDetails = 8192, /// <summary> /// Relationships /// </summary> UserRelationships = 16384, /// <summary> /// Religion and politics /// </summary> UserReligionPolitics = 32768, /// <summary> /// Status /// </summary> UserStatus = 65536, /// <summary> /// Tagged places /// </summary> UserTaggedPlaces = 131072, /// <summary> /// Videos /// </summary> UserVideos = 262144, /// <summary> /// Website /// </summary> UserWebsite = 524288, /// <summary> /// WorkHistory /// </summary> UserWorkHistory = 1048576 } }
namespace VRT.Resume.Application.Resumes.Queries.GetResume { public interface ISkillable { SkillDto[] Skills { get; } } }
using Dapper; using Examples.WebApp.Web.Models; using Examples.WebApp.Web.Services; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Data.Common; using System.Threading.Tasks; namespace Examples.WebApp.Web.Controllers { public class InviteController : Controller { readonly DbConnection db; readonly IJobQueue jobs; public InviteController(DbConnection db, IJobQueue jobs) { this.db = db; this.jobs = jobs; } public IActionResult Index() => View(); [HttpPost] public async Task<IActionResult> InviteUsers(InvitationModel data) { // Do the critical path work: actually get // the users/emails into the system. await InsertUsersIntoDatabase(data.EmailList); // Then queue the non-critical path work // in a separate async-job: email // invitations will be sent to each user. // This also makes the job of sending // emails fault tolerant in case of // temporary errors while sending a message. Guid runId = await jobs.SendPendingInvitations(); return View("Results", new RunResultsModel { RunId = runId }); } async Task InsertUsersIntoDatabase(IEnumerable<string> emails) { await db.OpenAsync(); using (var tx = await db.BeginTransactionAsync()) { foreach (string email in emails) { await db.ExecuteAsync("insert into [User] (Email) values (@Email)", new { email }, tx); } await tx.CommitAsync(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SudokuSolver.BL { public class Field { private List<FieldsContainer> containersWithThatField; private int? fieldValue; private List<int> possibleValues; public bool IsSet { get { return fieldValue.HasValue; } } public int? Value { get { return fieldValue; } private set { if(!IsSet) { CheckValueIsCorrect(value); } } } public List<int> PossibleValues { get { bool isNotNull = possibleValues != null; if (isNotNull) return new List<int>(possibleValues); else return null; } } public List<FieldsContainer> ContainersWithThatField { get { return new List<FieldsContainer>(containersWithThatField); } } private void CheckValueIsCorrect(int? value) { if (!value.HasValue) { fieldValue = value; } else { int valueAsInt = value.Value; if (possibleValues.Contains(valueAsInt)) { SetFieldValue(valueAsInt); } } } private void SetFieldValue(int value) { fieldValue = value; possibleValues = null; RemovePossibilitiesFromContainersWithField(value); } private void RemovePossibilitiesFromContainersWithField(int value) { foreach (var container in containersWithThatField) { container.ValueToSet.Remove(value); container.ClearPossibilities(value); // Tym powinna zajmować się kontener, nie pole. } } public Field(int? value = null, int size = 9) { possibleValues = new List<int>(); InitializePossibleValues(size); containersWithThatField = new List<FieldsContainer>(); Value = value; } private void InitializePossibleValues(int size) { for (int i = 1; i <= size; i++) possibleValues.Add(i); } public bool RemovePossibility(int valueToRemove) { bool wasRemoved = false; if(!IsSet) { wasRemoved = possibleValues.Remove(valueToRemove); CheckIfItsLastOption(); } return wasRemoved; } private void CheckIfItsLastOption() { bool isLast = possibleValues.Count == 1; if (isLast) { int onlyOption = possibleValues.First(); Value = onlyOption; } } public bool RemovePossibility(List<int> valuesToRemove) { bool wasAnyRemoved = false; foreach(var valueToRemove in valuesToRemove) { bool removeResult = RemovePossibility(valueToRemove); wasAnyRemoved |= removeResult; } return wasAnyRemoved; } public bool SetValue(int value) { Value = value; bool isSetDone = Value == value; return isSetDone; } public void AddNewContainer(FieldsContainer container) { containersWithThatField.Add(container); } public override string ToString() { if (IsSet) return Value.ToString(); else { return GetPossibilitiesString(); } } private string GetPossibilitiesString() { string longerString = string.Join(", ", possibleValues); return longerString; } public override bool Equals(object obj) { if (obj == null || obj is not Field field) return false; else { if (Value != 0) return Value.Equals(field.Value); else if (field.Value != 0) return false; else if (possibleValues.Count != field.possibleValues.Count) return false; else { for (int i = 0; i < possibleValues.Count; i++) if (possibleValues[i] != field.possibleValues[i]) return false; } } return true; } public override int GetHashCode() { int hashCode = 0; if (IsSet) hashCode = (int)Value; else foreach (var possibility in possibleValues) hashCode = hashCode * 10 + possibility; return hashCode; } } }
using UnityEngine; public class LookingDownCameraOperation : BaseInputOperation { private Plane interactPlane; private Plane cameraMovablePlane; private bool canOperate; public LookingDownCameraOperation() { interactPlane = new Plane(Vector3.up, 0f); cameraMovablePlane = new Plane(Vector3.down, 0f); } public override void OnPointerDown(InputData inputData) { base.OnPointerDown(inputData); //Objectレイヤーだと操作しない int objectLayer = 1 << LayerMask.NameToLayer("Object"); RaycastHit hit; canOperate = true; if (Utils.TryGetHitInfo(inputData.screenPosition, objectLayer, out hit)) { canOperate = false; } } public override void OnBeginDrag(InputData inputData) { if (!canOperate) { return; } base.OnBeginDrag(inputData); cameraMovablePlane.distance = CameraManager.Instance.Camera.transform.position.y; Vector3 camPos = Vector3.zero; if (TryGetCameraPositionOnCameraMovablePlane(inputData.screenPosition, out camPos)) { inputData.previousCameraPosition = camPos; } } public override void OnDrag(InputData inputData) { if (!canOperate) { return; } base.OnDrag(inputData); Vector3 camPos = Vector3.zero; if (TryGetCameraPositionOnCameraMovablePlane(inputData.screenPosition, out camPos)) { Vector3 diff = camPos - inputData.previousCameraPosition; Vector3 pos = CameraManager.Instance.Camera.transform.position - diff; CameraManager.Instance.ReservePosition(pos); } } private bool TryGetCameraPositionOnCameraMovablePlane(Vector3 screenPos, out Vector3 camPos) { camPos = Vector3.zero; var ray = CameraManager.Instance.Camera.ScreenPointToRay(screenPos); float enter = 0f; var camTrans = CameraManager.Instance.Camera.transform; if (interactPlane.Raycast(ray, out enter)) { Vector3 pos = ray.origin + enter * ray.direction; var invRay = new Ray(pos, -camTrans.forward); if (cameraMovablePlane.Raycast(invRay, out enter)) { camPos = invRay.origin + enter * invRay.direction; return true; } } return false; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Normal.UI { public class KeyboardMalletHandle : MonoBehaviour { public float worldZScale = 0.15f; void LateUpdate() { // Counter the keyboard scale in the y-direction Vector3 localScale = transform.localScale; localScale.z = worldZScale / transform.parent.lossyScale.z; transform.localScale = localScale; // Fix position Vector3 localPosition = transform.localPosition; localPosition.z = -localScale.z/2.0f; transform.localPosition = localPosition; } } }
using System.Collections.Generic; using LibMMD.Util; using UnityEngine; namespace LibMMD.Model { public class Morph { public enum MorphCategory : byte { MorphCatSystem = 0x00, MorphCatEyebrow = 0x01, MorphCatEye = 0x02, MorphCatMouth = 0x03, MorphCatOther = 0x04 } public enum MorphType : byte { MorphTypeGroup = 0x00, MorphTypeVertex = 0x01, MorphTypeBone = 0x02, MorphTypeUv = 0x03, MorphTypeExtUv1 = 0x04, MorphTypeExtUv2 = 0x05, MorphTypeExtUv3 = 0x06, MorphTypeExtUv4 = 0x07, MorphTypeMaterial = 0x08 } public abstract class MorphData { } public class GroupMorphData : MorphData { public int MorphIndex { get; set; } public float MorphRate { get; set; } } public class VertexMorphData : MorphData { public int VertexIndex { get; set; } public Vector3 Offset { get; set; } } public class BoneMorphData : MorphData { public int BoneIndex { get; set; } public Vector3 Translation { get; set; } public Quaternion Rotation { get; set; } } public class UvMorphData : MorphData { public int VertexIndex { get; set; } public Vector4 Offset { get; set; } } public class MaterialMorphData : MorphData { public enum MaterialMorphMethod : byte { MorphMatMul = 0x00, MorphMatAdd = 0x01 } public int MaterialIndex { get; set; } public bool Global { get; set; } public MaterialMorphMethod Method { get; set; } public Color Diffuse { get; set; } public Color Specular { get; set; } public Color Ambient { get; set; } public float Shiness { get; set; } public Color EdgeColor { get; set; } public float EdgeSize { get; set; } public Vector4 Texture { get; set; } public Vector4 SubTexture { get; set; } public Vector4 ToonTexture { get; set; } } public string Name { get; set; } public string NameEn { get; set; } public MorphCategory Category { get; set; } public MorphType Type { get; set; } public MorphData[] MorphDatas { get; set; } } }
using System; namespace UnrealEngine { public partial class UAnimClassData:UObject { /// <summary>Target skeleton for this blueprint class</summary> public USkeleton TargetSkeleton; /// <summary>The index of the root node in the animation tree</summary> public int RootAnimNodeIndex; public UStructProperty RootAnimNodeProperty; } }
using System; using System.Collections.Generic; using Discussion.Admin.Supporting; using Discussion.Core.Data; using Discussion.Tests.Common; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace Discussion.Admin.Tests { // Use shared context to maintain database fixture // see https://xunit.github.io/docs/shared-context.html#collection-fixture [CollectionDefinition("AdminSpecs")] public class AdminSpecsCollection : ICollectionFixture<TestDiscussionAdminApp> { // This class has no code, and is never created. Its purpose is simply // to be the place to apply [CollectionDefinition] and all the // ICollectionFixture<> interfaces. } public class TestDiscussionAdminApp : TestApplication { internal const string JwtIssuer = "testing"; internal const string JwtAudience = "specs"; public TestDiscussionAdminApp() { InitAdminApp(); } private void InitAdminApp() { this.Init<Startup>(hostBuilder => { hostBuilder.ConfigureAppConfiguration((host, config) => { var jwtOptions = new Dictionary<string, string>() { {"JwtIssuerOptions:Secret", Guid.NewGuid().ToString()}, {$"JwtIssuerOptions:{nameof(JwtIssuerOptions.Issuer)}", JwtIssuer}, {$"JwtIssuerOptions:{nameof(JwtIssuerOptions.Audience)}", JwtAudience} }; config.AddInMemoryCollection(jwtOptions); }); }); var dbContext = ApplicationServices.GetService<ApplicationDbContext>(); dbContext.Database.OpenConnection(); dbContext.Database.EnsureCreated(); } public new TestDiscussionAdminApp Reset() { base.Reset(); return this; } } }
using System.Collections.Generic; using System.Linq; namespace KangaModeling.Compiler.SequenceDiagrams { internal class AreaContainer : IArea { private readonly IEnumerable<IArea> m_Children; private readonly bool m_HasFrame; public AreaContainer(IEnumerable<IArea> children, bool hasFrame) { m_Children = children; m_HasFrame = hasFrame; } #region IArea Members public int Left { get { return m_Children.Any() ? m_Children.Select(a => a.Left).Min() : 0; } } public int Right { get { return m_Children.Any() ? m_Children.Select(a => a.Right).Max() : 0; } } public int Top { get { return m_Children.Any() ? m_Children.Select(a => a.Top).Min() : 0; } } public int Bottom { get { return m_Children.Any() ? m_Children.Select(a => a.Bottom).Max() : 0; } } public IEnumerable<IArea> Children { get { return m_Children; } } public bool HasFrame { get { return m_HasFrame; } } #endregion } }
/* * PROJECT: Atomix Development * LICENSE: BSD 3-Clause (LICENSE.md) * PURPOSE: * PROGRAMMERS: SANDEEP ILIGER <sandeep.iliger@gmail.com> * Aman Priyadarshi <aman.eureka@gmail.com> */ using System; namespace Kernel_alpha.FileSystem.FAT.Lists { public abstract class Base { protected string Name; protected Details Details; public string EntryName { get { return Name; } } public Details EntryDetails { get { return Details; } } public Base(string aName, Details aDetail) { this.Name = aName; this.Details = aDetail; } } }
namespace Foo { /// <summary> /// Does nothing. /// </summary> public class Grault { // No idea what this is. } }
using System; using System.Collections.Generic; using System.Linq; using Xunit.Extensions; using Xunit.Sdk; namespace WebStack.QA.Common.XUnitTest { /// <summary> /// Extended theory attribute allow inline data skippable /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class ExtendedTheoryAttribute : TheoryAttribute { protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method) { var commands = base.EnumerateTestCommands(method); var attrs = method.MethodInfo.GetCustomAttributes(typeof(DataAttribute), false); if (commands.Count() != attrs.Count()) { throw new InvalidOperationException("Some data attribute doesn't generate test command"); } var filteredCommands = new List<ITestCommand>(); int index = 0; foreach (var command in commands) { var theoryCmd = command as TheoryCommand; var skippableData = attrs.ElementAt(index++) as ISkippable; if (skippableData != null && !string.IsNullOrEmpty(skippableData.SkipReason)) { SkipCommand cmd = new SkipCommand(method, theoryCmd.DisplayName, skippableData.SkipReason); filteredCommands.Add(cmd); } else { filteredCommands.Add(command); } } return filteredCommands; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Practices.DataPipeline.Cars.Dispatcher.Simulator.Instrumentation { using System; public interface ISenderInstrumentationPublisher { void MessageSendRequested(); void MessageSendCompleted(long length, TimeSpan elapsed); } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace StorageImportExport.Models { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; public partial class Drive { /// <summary> /// Initializes a new instance of the Drive class. /// </summary> public Drive() { } /// <summary> /// Initializes a new instance of the Drive class. /// </summary> public Drive(string driveId, string bitLockerKey, string manifestFile, string manifestHash) { DriveId = driveId; BitLockerKey = bitLockerKey; ManifestFile = manifestFile; ManifestHash = manifestHash; } /// <summary> /// The drive's hardware serial number, without spaces. /// </summary> [JsonProperty(PropertyName = "DriveId")] public string DriveId { get; set; } /// <summary> /// The BitLocker key used to encrypt the drive. /// </summary> [JsonProperty(PropertyName = "BitLockerKey")] public string BitLockerKey { get; set; } /// <summary> /// The relative path of the manifest file on the drive. /// </summary> [JsonProperty(PropertyName = "ManifestFile")] public string ManifestFile { get; set; } /// <summary> /// The Base16-encoded MD5 hash of the manifest file on the drive. /// </summary> [JsonProperty(PropertyName = "ManifestHash")] public string ManifestHash { get; set; } /// <summary> /// Validate the object. Throws ValidationException if validation fails. /// </summary> public virtual void Validate() { if (DriveId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "DriveId"); } if (BitLockerKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "BitLockerKey"); } if (ManifestFile == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ManifestFile"); } if (ManifestHash == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ManifestHash"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnHandler : MonoBehaviour { public List<GameObject> spawners; public float spawnCooldown = 30.0f; public bool isWaveSpawn = false; private float spawnCounter; private int enemiesSpawned = 0; private int enemiesDestroyed = 0; private void Start() { spawnCounter = spawnCooldown; } void Update () { if (!isWaveSpawn) { if (spawnCounter < 0.0f) { int idx = Random.Range(0, spawners.Count); spawners[idx].SendMessage("Spawn"); spawnCounter = spawnCooldown; } else { spawnCounter -= Time.deltaTime; } } } void SpawnWave(int numToSpawn) { Debug.Log("Spawning enemy"); enemiesSpawned = numToSpawn; for (int i = 0; i < numToSpawn; i++) { spawners[i].SendMessage("Spawn"); } } void EnemyDestroyed() { enemiesDestroyed++; if (enemiesDestroyed == enemiesSpawned) { GameObject.FindGameObjectsWithTag("Manager")[0].GetComponent<SpawnCycleHandler>().SendMessage("NextWave"); } } }