text
stringlengths
13
6.01M
//@Author Justin Scott Bieshaar. //For further questions please read comments or reach me via mail contact@justinbieshaar.com using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Camera))] [ExecuteInEditMode] public class EdgeDetectionController : MonoBehaviour { public float sensitivityDepth = 1.0f; public float sensitivityNormals = 1.0f; public float lumThreshold = 0.2f; public float edgeExp = 1.0f; public float sampleDist = 1.0f; public float edgesOnly = 0.0f; public Color edgesOnlyBgColor = Color.black; public Color edgesColor = Color.red; public Shader edgeDetectShader; public Material edgeDetectMaterial = null; void SetCameraFlag() { // if (mode == EdgeDetectMode.SobelDepth || mode == EdgeDetectMode.SobelDepthThin) // GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth; //else } void OnEnable() { SetCameraFlag(); } [ImageEffectOpaque] void OnRenderImage(RenderTexture source, RenderTexture destination) { Vector2 sensitivity = new Vector2(sensitivityDepth, sensitivityNormals); edgeDetectMaterial.SetVector("_Sensitivity", new Vector4(sensitivity.x, sensitivity.y, 1.0f, sensitivity.y)); edgeDetectMaterial.SetFloat("_BgFade", edgesOnly); edgeDetectMaterial.SetFloat("_SampleDistance", sampleDist); edgeDetectMaterial.SetVector("_BgColor", edgesOnlyBgColor); edgeDetectMaterial.SetFloat("_Exponent", edgeExp); edgeDetectMaterial.SetFloat("_Threshold", lumThreshold); edgeDetectMaterial.SetVector("_Color", edgesColor); Graphics.Blit(source, destination, edgeDetectMaterial); } }
using System.Collections.Generic; namespace ConsoleApp1 { /// <summary> /// 神经层 /// 这将用于传递脉冲或将学习命令应用于层中的每个神经元 /// </summary> public interface INeuralLayer : IList<INeuron> { /// <summary> /// 传递脉冲 /// </summary> /// <param name="net">神经网络</param> void Pulse(INeuralNet net); /// <summary> /// 将学习命令应用于层中的每个神经元 /// </summary> /// <param name="net">神经网络</param> void ApplyLearning(INeuralNet net); /// <summary> /// 初始化学习 /// </summary> /// <param name="net">神经网络</param> void InitializeLearning(INeuralNet net); } }
using System; namespace Conditions { class Program { static void Main(string[] args) { Console.WriteLine("Zadej hodnotu a:"); int a = Convert.ToInt32(Console.ReadLine()); //<, >, >=, <=, ==, != if (a > 10) Console.WriteLine("a je větší než 10"); else Console.WriteLine("a je menší nebo rovno 10"); Console.ReadKey(true); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AFPABNB.Entities { public class Hebergement { public int IdHebergement { get; set; } public string Photo { get; set; } public string Nom { get; set; } public string Type { get; set; } public int Prix { get; set; } public int IdClient { get; set; } public string Description { get; set; } public Adresse adresse { get; set; } public Reservation reservation { get; set; } } }
using System.Collections.Generic; using System.Drawing; using Autofac; using Tests.Pages.ActionID; using Framework.Core.Common; using NUnit.Framework; using Tests.Data.Oberon; using Tests.Pages.Oberon.Contact; using Tests.Pages.Oberon.Search; namespace Tests.Projects.Oberon.Search { public class VerifySearchOnContributionDateRange : BaseTest { private Driver Driver {get { return Scope.Resolve<Driver>(); }} private ActionIdLogIn LogIn { get { return Scope.Resolve<ActionIdLogIn>(); } } [Test] [Category("oberon"), Category("oberon_search")] public void TestCaseVerifySearchOnContributionDateRange() { LogIn.LogInTenant(); // execute search var search = Scope.Resolve<SearchCreate>(); search.GoToThisPage(); search.ClickContributionFieldSet(); search.SelectContributionDateRange("This Week"); Driver.ScrollToBottomOfPage(); search.ClickSearchButton(); //verify user redirected to search results page var results = Scope.Resolve<SearchResults>(); Assert.IsTrue(results.VerifySearchResults()); } } }
using System; namespace GreatestCommonDivisor2Num { class Program { static void Main(string[] args) { Console.Write("Enter number 1: "); int number1 = int.Parse(Console.ReadLine()); Console.Write("Enter number 2: "); int number2 = int.Parse(Console.ReadLine()); if (number2>number1) { int temp = number1; number1 = number2; number2 = temp; } int commonDivisor = number2; bool greatestDivisor = false; while (commonDivisor > 1 && greatestDivisor == false) { if (number1 % commonDivisor == 0 && number2 % commonDivisor == 0) greatestDivisor = true; else commonDivisor--; } if (commonDivisor > 1) Console.WriteLine("Greatest divisor of two numbers is " + commonDivisor); else Console.WriteLine("There is no common divisor"); } } }
using FluentValidation; using System; using System.Linq; using CalculatorServices.WebAPI.DTOs; namespace CalculatorServices.WebAPI.Validation { public class SumRequestValidator : AbstractValidator<SumRequest> { public SumRequestValidator() { RuleFor(m => m.Addends).Must(c => c == null || c.Count <= 9).WithMessage("The addends cannot be empty or greater than 9").WithErrorCode("2.1"); RuleForEach(m => m.Addends).LessThanOrEqualTo(9).WithMessage("The addends cannot be greater than 9 (index {CollectionIndex})").WithErrorCode("2.2"); } } }
using System; using System.Collections.Generic; using System.Text; using Autofac; using FakeItEasy; using IFS.Controllers; using IFS.Models; using IFS.Requests; using IFS.Services; using Microsoft.AspNetCore.Mvc; using NFluent; using TestUtilities; using Xunit; namespace IFS.Test.Controllers { public class HintControllerTest : BaseTest { private IHintService _hintService; private HintController _target; public HintControllerTest() { _hintService = A.Fake<IHintService>(); _testContainerBuilder.RegisterInstance(_hintService); _testContainerBuilder.RegisterType<HintController>(); _container = _testContainerBuilder.Build(); _target = _container.Resolve<HintController>(); } [Fact] public void GetHint() { // Arrange // Act var result = _target.GetHintsForMission("02"); // Assert Check.That(result).IsInstanceOf<OkObjectResult>(); A.CallTo(() => _hintService.GetHintsForMission(A<string>._)).MustHaveHappened(); } [Fact] public void AddHint() { // Arrange var addHintRequest = new AddHintRequest() { MissionIndex = "02", Text = "toto", TrueHint = true}; // Act var result = _target.AddHint(addHintRequest); // Assert A.CallTo(() => _hintService.Add(A<Hint>._)).MustHaveHappened(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; namespace Restaurant.Models { public class Member : IdentityUser { public int MemberID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime Joined { get; set; } // public List<Member> Members { get; set; } public override bool Equals(object mem) { var other = mem as Member; if (other == null) return false; return this.FirstName == other.FirstName && this.LastName == other.LastName && this.Email == other.Email; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Web.Http; using System.Web.Mvc; using Animal.Mammal; using Autofac; using Autofac.Features.Indexed; using Autofac.Integration.Mvc; using Autofac.Integration.WebApi; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Animal { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //RegisterContainer(); //RegisterContainer2(); RegisterPerson(); } public void RegisterPerson() { //注册IOC容器 var builder = new ContainerBuilder(); //告诉autofac将来要创建的控制器类存放在哪个程序集 builder.RegisterControllers(Assembly.GetExecutingAssembly());//注册MVC控制器 builder.RegisterApiControllers(Assembly.GetExecutingAssembly());//注册WebAPI控制器 //注册Repository和Service builder.RegisterType<PersonRepository>().As<IRepository>().InstancePerDependency(); builder.RegisterType<PersonService>().As<IService>().InstancePerDependency(); var container = builder.Build(); //将当前容器交给MVC底层,保证容器不被销毁,控制器由autofac来创建 GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);//先给WebAPI注册 DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//再给MVC注册 } public void RegisterContainer2() { var builder = new ContainerBuilder();//准备容器 builder.RegisterType<Person>().UsingConstructor(typeof(string)); var container = builder.Build();//创建容器完毕 //var doge = container.Resolve<Person>();//通过IOC容器创建对象 //doge.SayHello(); List<NamedParameter> pars = new List<NamedParameter>() { new NamedParameter("Age", 20), new NamedParameter("Name", "张三") }; builder.RegisterType<Person>().WithParameters(pars);  } public void RegisterContainer() { var builder = new ContainerBuilder();//准备容器 builder.RegisterType<Doge>();//注册对象 builder.RegisterInstance(new Doge());//实例注入 //builder.RegisterInstance(Singleton.GetInstance()).ExternallyOwned();//将单例对象托管到IOC容器 //builder.Register(c => new Person() { Name = "张三", Age = 20 });//Lambda表达式创建 //Person p1 = container.Resolve<Person>(); //builder.Register(c => new Person() { Name = "张三", Age = 20 });//Lambda表达式创建 //Person p2 = container.Resolve<Person>(); builder.RegisterGeneric(typeof(List<>)); //var builder = new ContainerBuilder();//准备容器 builder.RegisterType<Doge>().As<IAnimal>();//映射对象 //如果一个类型被多次注册,以最后注册的为准。 ////var container = builder.Build();//创建容器完毕 builder.RegisterType<Doge>().Named<IAnimal>("doge");//映射对象 builder.RegisterType<Pig>().Named<IAnimal>("pig");//映射对象 builder.RegisterType<Cat>().As<IAnimal>().PreserveExistingDefaults();//指定Cat为非默认值 builder.RegisterType<Doge>().Keyed<IAnimal>(AnumalType.Doge);//映射对象 builder.RegisterType<Pig>().Keyed<IAnimal>(AnumalType.Pig);//映射对象 builder.RegisterType<Cat>().Keyed<IAnimal>(AnumalType.Cat);//映射对象 //通过使用PreserveExistingDefaults() 修饰符,可以指定某个注册为非默认值。 //不过这种方式是不推荐使用的,因为autofac容器会被当作Service Locator使用, // 推荐的做法是通过索引类型来实现, //Autofac.Features.Indexed.IIndex<K, V> 是Autofac自动实现的一个关联类型。 // 使用IIndex<K, V> 作为参数的构造函数从基于键的服务中选择需要的实现: var container = builder.Build();//创建容器完毕 List<string> list = container.Resolve<List<string>>(); var adog = container.Resolve<IAnimal>();//通过IOC容器创建对象 adog.SayHello(); var doge = container.Resolve<Doge>();//通过IOC容器创建对象 doge.SayHello(); var dog = container.ResolveNamed<IAnimal>("pig");//通过IOC容器创建对象 dog.SayHello(); var dogAble = container.ResolveKeyed<IAnimal>(AnumalType.Cat);//通过IOC容器创建对象 dogAble.SayHello(); var animal = container.Resolve<IIndex<AnumalType, IAnimal>>(); var cat = animal[AnumalType.Cat]; cat.SayHello(); } public enum AnumalType { Doge, Pig, Cat } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using FiiiCoin.Models; using FiiiCoin.Wallet.Win.Common; using FiiiCoin.Wallet.Win.Common.Utils; using FiiiCoin.Wallet.Win.Models; using GalaSoft.MvvmLight.Command; using Microsoft.Win32; using System.IO; using System.Windows.Input; namespace FiiiCoin.Wallet.Win.ViewModels.ShellPages { public class RequestPayViewModel : PopupShellBase { protected override string GetPageName() { return Pages.RequestPayPage; } public override void Init() { base.Init(); RegeistMessenger<PayRequest>(OnGetRequest); CopyAccountCommand = new RelayCommand(OnCopyAccount); CopyURLCommand = new RelayCommand(OnCopyURL); SaveImageCommand = new RelayCommand(OnSaveImage); } private string _qrCodePath; public string QrCodePath { get { return _qrCodePath; } set { _qrCodePath = value; RaisePropertyChanged("QrCodePath"); } } private string _qrCodeStr; public string QrCodeStr { get { return _qrCodeStr; } set { _qrCodeStr = value; RaisePropertyChanged("QrCodeStr"); } } private PayRequest _payRequest; public PayRequest PayRequest { get { return _payRequest; } set { _payRequest = value; RaisePropertyChanged("PayRequest"); } } void OnGetRequest(PayRequest request) { var qrCodeStr =string.Format("fiiicoin:{0}?amount={1}&label={2}&message={3}", request.AccountId, request.Amount, request.Tag, request.Comment); var path = QRCodeUtil.Default.GenerateQRCodes(request.AccountId); QrCodeStr = qrCodeStr; PayRequest = request; QrCodePath = path; } public ICommand CopyAccountCommand { get; private set; } public ICommand CopyURLCommand { get; private set; } public ICommand SaveImageCommand { get; private set; } void OnCopyAccount() { ClipboardUtil.SetText(PayRequest.AccountId); } void OnCopyURL() { ClipboardUtil.SetText(QrCodeStr); } void OnSaveImage() { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "PNG(*.png)|*.png"; saveFileDialog.FilterIndex = 1; saveFileDialog.RestoreDirectory = true; var result = saveFileDialog.ShowDialog(BootStrapService.Default.Shell.GetWindow()); if (result.HasValue && result.Value) { var file = saveFileDialog.FileName; FileInfo imageFile = new FileInfo(QrCodePath); imageFile.CopyTo(file); } } public override void OnClosePopup() { base.OnClosePopup(); SendMessenger(Pages.ReceiveAddressPage, SendMessageTopic.Refresh); } } }
using Google; using Google.Apis.Auth.OAuth2; using Google.Apis.Storage.v1.Data; using Google.Cloud.Storage.V1; using HCore.Web.Exceptions; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace HCore.Storage.Client.Impl { public class GoogleCloudStorageClientImpl : IStorageClient { private const int ChunkSize = 5 * 1024 * 1024; // 5 MB private readonly string _projectId; private readonly string _credentialsJson; public GoogleCloudStorageClientImpl(string connectionString) { int firstIndex = connectionString.IndexOf(":"); if (firstIndex == -1) throw new Exception("Google Cloud connection string is invalid"); _projectId = connectionString.Substring(0, firstIndex); if (string.IsNullOrEmpty(_projectId)) throw new Exception("The Google Cloud project ID is invalid"); _credentialsJson = connectionString.Substring(firstIndex + 1); if (string.IsNullOrEmpty(_credentialsJson)) throw new Exception("The Google Cloud credentials JSON is invalid"); } public async Task DownloadToStreamAsync(string containerName, string fileName, Stream stream) { var credential = GoogleCredential.FromJson(_credentialsJson); try { using (var storageClient = await StorageClient.CreateAsync(credential).ConfigureAwait(false)) { var blockBlob = await storageClient.GetObjectAsync(containerName, fileName).ConfigureAwait(false); await storageClient.DownloadObjectAsync(blockBlob, stream, new DownloadObjectOptions() { ChunkSize = ChunkSize }).ConfigureAwait(false); } } catch (GoogleApiException e) { if (e.HttpStatusCode == HttpStatusCode.NotFound) { throw new ExternalServiceApiException(ExternalServiceApiException.CloudStorageFileNotFound, "The file was not found"); } else if (e.HttpStatusCode == HttpStatusCode.Forbidden || e.HttpStatusCode == HttpStatusCode.Unauthorized) { throw new ExternalServiceApiException(ExternalServiceApiException.CloudStorageFileAccessDenied, "Access to the file was denied"); } else { throw e; } } } public async Task UploadFromStreamAsync(string containerName, string fileName, string mimeType, Dictionary<string, string> additionalHeaders, Stream stream, bool overwriteIfExists) { var credential = GoogleCredential.FromJson(_credentialsJson); using (var storageClient = await StorageClient.CreateAsync(credential).ConfigureAwait(false)) { try { await storageClient.GetBucketAsync(containerName).ConfigureAwait(false); } catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.NotFound) { // we need to create the bucket try { var bucket = new Bucket() { Name = containerName, Location = "eu" }; await storageClient.CreateBucketAsync(_projectId, bucket).ConfigureAwait(false); } catch (GoogleApiException) when (e.HttpStatusCode == HttpStatusCode.Conflict) { // bucket already exists, that's fine } } // check if object exists try { await storageClient.GetObjectAsync(containerName, fileName).ConfigureAwait(false); // exists if (!overwriteIfExists) throw new Exception("The target storage object already exists"); await storageClient.DeleteObjectAsync(containerName, fileName).ConfigureAwait(false); } catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.NotFound) { // not found, that's fine } var blockBlob = new Google.Apis.Storage.v1.Data.Object { Bucket = containerName, Name = fileName, ContentType = mimeType }; if (additionalHeaders != null) { blockBlob.Metadata = additionalHeaders; } await storageClient.UploadObjectAsync(blockBlob, stream, new UploadObjectOptions() { ChunkSize = ChunkSize }).ConfigureAwait(false); } } public async Task UploadFromStreamLowLatencyProfileAsync(string containerName, string fileName, string mimeType, Dictionary<string, string> additionalHeaders, Stream stream) { var credential = GoogleCredential.FromJson(_credentialsJson); using (var storageClient = await StorageClient.CreateAsync(credential).ConfigureAwait(false)) { try { await storageClient.GetBucketAsync(containerName).ConfigureAwait(false); } catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.NotFound) { // we need to create the bucket try { var bucket = new Bucket() { Name = containerName, Location = "eu" }; await storageClient.CreateBucketAsync(_projectId, bucket).ConfigureAwait(false); } catch (GoogleApiException) when (e.HttpStatusCode == HttpStatusCode.Conflict) { // bucket already exists, that's fine } } var blockBlob = new Google.Apis.Storage.v1.Data.Object { Bucket = containerName, Name = fileName, ContentType = mimeType }; if (additionalHeaders != null) { blockBlob.Metadata = additionalHeaders; } await storageClient.UploadObjectAsync(blockBlob, stream, new UploadObjectOptions() { ChunkSize = ChunkSize }).ConfigureAwait(false); } } public async Task<string> GetSignedDownloadUrlAsync(string containerName, string fileName, TimeSpan validityTimeSpan) { var credential = GoogleCredential.FromJson(_credentialsJson) .CreateScoped(new string[] { "https://www.googleapis.com/auth/devstorage.read_only" }) .UnderlyingCredential as ServiceAccountCredential; var urlSigner = UrlSigner.FromServiceAccountCredential(credential); string signedUrl = await urlSigner.SignAsync(containerName, fileName, validityTimeSpan, HttpMethod.Get).ConfigureAwait(false); return signedUrl; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { public class FakeContext { public List<Document> Documents = new List<Document>() { new Document() { DateTime = DateTime.Now, Id = 1, Name = "Doc1", Status = DocumentStatus.Draft, }, new Document() { DateTime = DateTime.Now, Id = 2, Name = "Doc2", Status = DocumentStatus.Accepted, }, new Document() { DateTime = DateTime.Now, Id = 3, Name = "Doc3", Status = DocumentStatus.Finished, }, new Document() { DateTime = DateTime.Now, Id = 4, Name = "Doc4", Status = DocumentStatus.New, } }; public void SaveChanges() { } } }
namespace HTTPServer.core { public interface IHttpHandler { Reply Execute(Request request); } }
using System; using System.Collections.Generic; namespace ServiceDeskSVC.DataAccess.Models { public partial class AssetManager_Software_AssetType { public AssetManager_Software_AssetType() { this.AssetManager_Software = new List<AssetManager_Software>(); } public int Id { get; set; } public string Name { get; set; } public string DescriptionNotes { get; set; } public Nullable<int> EndOfLifeMo { get; set; } public int CategoryCode { get; set; } public virtual ICollection<AssetManager_Software> AssetManager_Software { get; set; } } }
using System; using System.IO; using System.Text; using System.Xml.Linq; using Messaging.Resolvers; namespace Messaging { /// <summary> /// Extension methods to support usage of validator and transformer /// </summary> public static class Extensions { /// <summary> /// Used to convert a stream to text representation /// </summary> /// <param name="stream">Stream input</param> /// <returns>Return the equivalent text</returns> public static string GetText(this Stream stream) => new StreamReader(stream).ReadToEnd(); /// <summary> /// Used to convert from string to stream representation /// </summary> /// <param name="content">input in text representation</param> /// <returns>Return the equivalent stream</returns> public static Stream GetStream(this string content) => new MemoryStream(UTF8Encoding.UTF8.GetBytes(content)); /// <summary> /// Get stream from embedded resource in the current code assembly /// </summary> /// <param name="resourceName"></param> /// <returns></returns> public static Stream GetStreamFromAssembly(this string resourceName) => EmbeddedResourceResolver.Create(AssemblyType.Library).GetResourceStream(resourceName); /// <summary> /// Check filename, if it does not have extension append with xsd extension /// </summary> /// <param name="filename">Filename</param> /// <returns>Return filename with xsd extension</returns> public static string MakeSureHasSchemaExtension(this string filename) => Path.HasExtension(filename) ? filename : filename + ".xsd"; /// <summary> /// Check if xml is a valid XML content /// </summary> /// <param name="xml">input XML</param> /// <returns>Return true or false</returns> public static bool IsValidXml(string xml) { try { XDocument xd1 = new XDocument(); xd1 = XDocument.Load(xml.GetStream()); return true; } catch (Exception) { return false; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using BladeCast; using UnityEngine.UI; public class GameManager : MonoBehaviour { [System.NonSerialized] public List<string> playersRegistered = new List<string>(); public GameObject playerPrefab; public GameObject disablePowerupPrefab; public GameObject replayAttackPrefab; public bool isSavingJson = false; BCListener.Listener movementListener; BCListener.Listener jumpingListener; public string theNonPlayerId; BladeCast.BCSender sender; [System.NonSerialized] public int victoryPointsCondition = 4; //is actually 5 points public List<JSONObject> recentJsons = new List<JSONObject> (); static public GameManager Instance; public List<Player> playerList = new List<Player>(); private GameObject gameOverCanvas; public Camera mainCamera; public GameObject floor1Obj; public GameObject floor2Obj; void Awake() { Instance = this; gameOverCanvas = GameObject.Find ("GameOverCanvas"); mainCamera = GameObject.Find ("Main Camera").GetComponent<Camera> (); floor1Obj = GameObject.Find ("Floor1"); floor2Obj = GameObject.Find ("Floor2"); } public bool powerUpInPlay = false; void Start () { Application.runInBackground = true; gameOverCanvas.SetActive (false); //how to do stuffff BladeCast.BCListener listener = GetComponent<BladeCast.BCListener>(); sender = GetComponent<BladeCast.BCSender>(); //sender.SendToListeners("disabled", "playerId", "ten", 1); //immune player listener.Add ("connect", 0, "SpawnAPlayer"); movementListener = new BCListener.Listener ("movement", 0, "SaveJson"); listener.Add (movementListener); //listener.Add("movement", 0, "Move"); jumpingListener = new BCListener.Listener ("jump", 0, "SaveJson"); //listener.Add("jump", 0, "Jump"); listener.Add(jumpingListener); StartCoroutine (SpawnPowerUpsForever ()); } public IEnumerator SpawnPowerUpsForever() { while (true) { Debug.Log ("spawning power up"); yield return new WaitForSeconds (15.0f); if (!powerUpInPlay) SpawnRandomPowerUp (); } } void Update() { if (Input.GetKeyDown (KeyCode.Space)) { SpawnAPlayer0 (); } } public void ExecuteReplayPowerUp(Player ply) { ply.myPoints++; ply.UpdateHHOnPoints (); isSavingJson = true; theNonPlayerId = ply.playerId; recentJsons.Clear (); } public IEnumerator ExecuteDisablePlayersPowerUp(Player play) { play.myPoints++; play.UpdateHHOnPoints (); theNonPlayerId = play.playerId; Debug.Log ("the players id: " + theNonPlayerId); //disable players for a little sender.SendToListeners("disabled", "playerId", theNonPlayerId, 1); //immune player foreach (Player ply in playerList) { if (ply.playerId != theNonPlayerId) { ply.listener.Remove (ply.movementListener); ply.listener.Remove (ply.jumpingListener); } } //disables for 5 seconds Debug.LogError("disabled"); yield return new WaitForSeconds (5.0f); Debug.LogError ("should be enabled"); //send re-enable message to players sender.SendToListeners ("enabled", "playerId", theNonPlayerId, 1); foreach (Player ply in playerList) { Debug.Log ("trying to add listeners"); if (ply.playerId != theNonPlayerId) { ply.listener.Add (ply.movementListener); ply.listener.Add (ply.jumpingListener); } } yield return new WaitForSeconds (0.1f); } public void CheckPlayersWinCondition() { foreach (Player ply in playerList) { if (ply.myPoints >= victoryPointsCondition) { GameOver (ply); } } } public void SpawnRandomPowerUp() { powerUpInPlay = true; Debug.Log ("actually doing power up"); //change this if (Random.value > 0.30f) { GameObject power = Instantiate (disablePowerupPrefab) as GameObject; power.transform.position = floor1Obj.transform.position + Vector3.up * 2.0f; } else { GameObject replayThing = Instantiate (replayAttackPrefab) as GameObject; replayThing.transform.position = floor2Obj.transform.position + Vector3.up * 2.0f; //replayThing.transform.position = floor2Obj.transform.position - Vector3.up * 3.0f; } } void SpawnAPlayer0() { string tempPlayerId = Random.value.ToString (); playersRegistered.Add (tempPlayerId); GameObject newPlayer = Instantiate (playerPrefab) as GameObject; newPlayer.GetComponent<Player> ().playerId = tempPlayerId; playerList.Add (newPlayer.GetComponent<Player> ()); } void SaveJson(ControllerMessage msg) { if (isSavingJson) { Debug.Log ("saving a message"); recentJsons.Add (msg.Payload); } if (recentJsons.Count > 100) { Debug.LogError ("done saving message"); isSavingJson = false; StartCoroutine (ReplayToPlayer ()); } } public IEnumerator ReplayToPlayer() { //disable players for a little sender.SendToListeners("disabled", "playerId", theNonPlayerId, 1); //immune player foreach (Player ply in playerList) { if (ply.playerId != theNonPlayerId) { ply.listener.Remove (ply.movementListener); ply.listener.Remove (ply.jumpingListener); } } foreach(JSONObject jo in recentJsons) { foreach (Player ply in playerList) { if (ply.playerId != theNonPlayerId) { ControllerMessage cm = new ControllerMessage (1, 0, jo.GetField ("type").str, jo); if (jo.GetField ("type").str == "move") { ply.Move (cm); } else if (jo.GetField ("type").str == "jump") { ply.Jump (cm); } } } yield return new WaitForSeconds(0.01f); } //send re-enable message to players sender.SendToListeners ("enabled", "playerId", theNonPlayerId, 1); foreach (Player ply in playerList) { if (ply.playerId != theNonPlayerId) { ply.listener.Add (ply.movementListener); ply.listener.Add (ply.jumpingListener); } } } void SpawnAPlayer(ControllerMessage msg) { Debug.Log ("connect detected by game manager, its controller source is: " + msg.ControllerSource.ToString()); if (msg.ControllerSource == Player.playerIndex) { Debug.Log ("thign"); if (msg.Payload.HasField ("playerId") && !playersRegistered.Contains(msg.Payload.GetField ("playerId").str)) { playersRegistered.Add (msg.Payload.GetField ("playerId").str); GameObject newPlayer = Instantiate (playerPrefab) as GameObject; newPlayer.GetComponent<Player> ().playerId = msg.Payload.GetField ("playerId").str; newPlayer.name = msg.Payload.GetField ("playerName").str; newPlayer.transform.GetChild (0).GetChild (0).GetComponent<Text> ().text = newPlayer.name; playerList.Add (newPlayer.GetComponent<Player> ()); } } } void GameOver(Player winnerPlayer) { gameOverCanvas.SetActive (true); string buildGameOverText = "GameOver! \n"; buildGameOverText = buildGameOverText + winnerPlayer.name + " has won the game!"; gameOverCanvas.transform.GetChild(0).gameObject.GetComponent<Text>().text = buildGameOverText; } }
using System; using System.Numerics; using System.Threading; using System.Windows.Forms; using MiNETDevTools.Graphics.Components; using SharpDX; using SharpDX.Direct2D1; using SharpDX.Direct3D; using SharpDX.Direct3D11; using SharpDX.DXGI; using AlphaMode = SharpDX.Direct2D1.AlphaMode; using Device = SharpDX.Direct3D11.Device; using DeviceContext = SharpDX.Direct2D1.DeviceContext; using Factory = SharpDX.DXGI.Factory; using FeatureLevel = SharpDX.Direct3D.FeatureLevel; using Filter = SharpDX.Direct3D11.Filter; using Resource = SharpDX.Direct3D11.Resource; using Vector2 = SharpDX.Vector2; namespace MiNETDevTools.Graphics.Internal { public class GraphicsDevice : DisposeWrapper { public event Action<GraphicsDevice> OnInitialize; public bool FPSCounter { get; set; } = true; public bool VSync { get; set; } public SharpDX.Direct3D11.Device1 D3Device { get { return _d3dDevice; } } public SharpDX.Direct3D11.DeviceContext1 D3Context { get { return _d3dContext; } } public SharpDX.Direct2D1.Device D2Device { get { return _d2dDevice; } } public DeviceContext D2Context { get { return _d2dContext; } } public SharpDX.Direct2D1.Factory D2Factory { get { return _d2dFactory; } } public Size2 WindowSize { get; private set; } public Vector2 WindowCenter => new Vector2(WindowSize.Width/2f, WindowSize.Height/2f); public Bitmap1 Target2D { get { return _target; } } public bool IsRunning { get; private set; } public SharpDX.DirectWrite.Factory DwFactory { get { return _dwFactory; } } public Rectangle RenderTargetBounds { get; private set; } protected SharpDX.DirectWrite.Factory _dwFactory; private IntPtr _outputHandle { get; } private Control _dummyControl; protected SharpDX.Direct3D11.Device1 _d3dDevice; protected SharpDX.Direct3D11.DeviceContext1 _d3dContext; protected SharpDX.Direct2D1.Factory1 _d2dFactory; protected SharpDX.Direct2D1.Device _d2dDevice; protected DeviceContext _d2dContext; private SwapChain1 _swapChain; private Texture2D _backBuffer; private DepthStencilView _depthStencilView; private RenderTargetView _renderTargetView; private Surface _surface; private FpsCounter _fpsCounter; private Bitmap1 _target; internal GraphicsDevice(Control control) { _outputHandle = control.Handle; WindowSize = new Size2(control.Width, control.Height); } /* protected SwapChainDescription CreateSwapChainDescription() { return new SwapChainDescription() { ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.B8G8R8A8_UNorm), OutputHandle = _outputHandle, IsWindowed = true, //Width = WindowSize.Width, //Height = WindowSize.Height, //Format = Format.R8G8B8A8_UNorm, //Stereo = false, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 2, SwapEffect = SwapEffect.Discard, //Scaling = SharpDX.DXGI.Scaling.Stretch, Flags = SwapChainFlags.AllowModeSwitch, }; }*/ protected SwapChainDescription1 CreateSwapChainDescription() { var desc = new SwapChainDescription1() { // Automatic sizing Width = WindowSize.Width, Height = WindowSize.Height, Format = Format.B8G8R8A8_UNorm, Stereo = false, SampleDescription = new SampleDescription(1, 0), Usage = Usage.BackBuffer | Usage.RenderTargetOutput, // Use two buffers to enable flip effect. BufferCount = 2, Scaling = Scaling.Stretch, //Scaling = SharpDX.DXGI.Scaling.None, SwapEffect = SwapEffect.Discard, }; return desc; } internal void Initialise() { RemoveAndDispose(ref _d2dFactory); RemoveAndDispose(ref _dwFactory); _d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory1(FactoryType.SingleThreaded)); _dwFactory = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared)); RemoveAndDispose(ref _d3dDevice); RemoveAndDispose(ref _d3dContext); RemoveAndDispose(ref _d2dDevice); RemoveAndDispose(ref _d2dContext); //var desc = CreateSwapChainDescription(); using (var device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport)) // | DeviceCreationFlags.Debug, { _d3dDevice = ToDispose(device.QueryInterface<SharpDX.Direct3D11.Device1>()); } _d3dContext = ToDispose(_d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>()); using (var dxgiDevice = _d3dDevice.QueryInterface<SharpDX.DXGI.Device>()) { _d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice)); } _d2dContext = ToDispose(new DeviceContext(_d2dDevice, DeviceContextOptions.None)); /* D2Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new [] { FeatureLevel.Level_10_0 }, desc, out _device, out _swapChain); ToDispose(_device); ToDispose(_swapChain); var d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory()); Factory factory = ToDispose(_swapChain.GetParent<Factory>()); factory.MakeWindowAssociation(_outputHandle, WindowAssociationFlags.IgnoreAll); _backBuffer = ToDispose(Texture2D.FromSwapChain<Texture2D>(_swapChain, 0)); _renderTargetView = ToDispose(new RenderTargetView(_device, _backBuffer)); _surface = ToDispose(_backBuffer.QueryInterface<Surface>()); _target = ToDispose(new RenderTarget(d2dFactory, _surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)))); */ InitialiseResources(); RemoveAndDispose(ref _fpsCounter); _fpsCounter = new FpsCounter(); _fpsCounter.InitialiseGraphics(this); OnInitialize?.Invoke(this); } protected void InitialiseResources() { RemoveAndDispose(ref _backBuffer); RemoveAndDispose(ref _renderTargetView); RemoveAndDispose(ref _surface); RemoveAndDispose(ref _target); _d2dContext.Target = null; var desc = CreateSwapChainDescription(); if (_swapChain != null) { _swapChain.ResizeBuffers( _swapChain.Description.BufferCount, WindowSize.Width, WindowSize.Height, _swapChain.Description.ModeDescription.Format, _swapChain.Description.Flags); } else { using (var dxgiDevice2 = _d3dDevice.QueryInterface<SharpDX.DXGI.Device2>()) using (var dxgiAdapter = dxgiDevice2.Adapter) using (var dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>()) { _swapChain = ToDispose(new SwapChain1(dxgiFactory2, _d3dDevice, _outputHandle, ref desc)); //_swapChain = ToDispose(new SwapChain1(dxgiFactory2, _d3dDevice, _outputHandle, ref desc)); } } _backBuffer = ToDispose(Resource.FromSwapChain<Texture2D>(_swapChain, 0)); { // Create a view interface on the rendertarget to use on bind. _renderTargetView = new RenderTargetView(_d3dDevice, _backBuffer); // Cache the rendertarget dimensions in our helper class for convenient use. var backBufferDesc = _backBuffer.Description; RenderTargetBounds = new Rectangle(0, 0, backBufferDesc.Width, backBufferDesc.Height); } using (var depthBuffer = new Texture2D(_d3dDevice, new Texture2DDescription() { Format = Format.D24_UNorm_S8_UInt, ArraySize = 1, MipLevels = 1, Width = (int)WindowSize.Width, Height = (int)WindowSize.Height, SampleDescription = new SampleDescription(1, 0), BindFlags = BindFlags.DepthStencil, })) _depthStencilView = new DepthStencilView(_d3dDevice, depthBuffer, new DepthStencilViewDescription() { Dimension = DepthStencilViewDimension.Texture2D }); var viewport = new ViewportF((float)RenderTargetBounds.X, (float)RenderTargetBounds.Y, (float)RenderTargetBounds.Width, (float)RenderTargetBounds.Height, 0.0f, 1.0f); _d3dContext.Rasterizer.SetViewport(viewport); var bitmapProperties = new BitmapProperties1( new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), _d2dFactory.DesktopDpi.Width, _d2dFactory.DesktopDpi.Height, BitmapOptions.Target | BitmapOptions.CannotDraw); using (var dxgiBackBuffer = _swapChain.GetBackBuffer<Surface>(0)) _target = new Bitmap1(_d2dContext, dxgiBackBuffer, bitmapProperties); _d2dContext.Target = _target; _d2dContext.TextAntialiasMode = TextAntialiasMode.Grayscale; /*_backBuffer = ToDispose(Resource.FromSwapChain<Texture2D>(_swapChain, 0)); _renderTargetView = ToDispose(new RenderTargetView(_d3dDevice, _backBuffer)); _surface = ToDispose(_backBuffer.QueryInterface<Surface>()); using (var dxgiBackBuffer = _swapChain.GetBackBuffer<Surface>(0)) _target = ToDispose(new RenderTarget(_d2dFactory, dxgiBackBuffer, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)))); */ OnInitialize?.Invoke(this); } public void Resize(Size2 newSize) { if (WindowSize.Width == newSize.Width && WindowSize.Height == newSize.Height) return; WindowSize = newSize; InitialiseResources(); } internal void Present() { if (FPSCounter) { _fpsCounter.DrawFrame(this); } try { _swapChain.Present(VSync ? 1 : 0, PresentFlags.None); } catch (SharpDXException ex) { if (ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceRemoved || ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceReset) { Initialise(); } else throw; } } } }
using Microsoft.Xna.Framework; using System; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Caserraria.NPCs { public class Cryomancer : ModNPC { int shootTimer; public override void SetStaticDefaults() { DisplayName.SetDefault("Cryomancer"); } public override void SetDefaults() { npc.width = 42; npc.height = 76; npc.damage = 60; npc.defense = 3; npc.lifeMax = 100; npc.HitSound = SoundID.NPCHit1; npc.DeathSound = SoundID.NPCDeath6; npc.value = 500f; npc.knockBackResist = 0f; npc.aiStyle = 2; npc.noTileCollide = true; npc.scale = .75f; } public override void AI() { shootTimer++; float Speed = 10; Player P = Main.player[npc.target]; Vector2 vector8 = new Vector2(npc.position.X + (npc.width / 2), npc.position.Y + (npc.height / 2)); float rotation = (float)Math.Atan2(vector8.Y - (P.position.Y + (P.height * 0.5f)), vector8.X - (P.position.X + (P.width * 0.5f))); if (shootTimer == 100) { shootTimer = 0; Projectile.NewProjectile(vector8.X, vector8.Y, (float)((Math.Cos(rotation) * Speed) * -1), (float)((Math.Sin(rotation) * Speed) * -1), ProjectileID.Fireball, 15, 0f, 0); } if (P.position.X > npc.position.X) { npc.spriteDirection = 1; } if (P.position.X < npc.position.X) { npc.spriteDirection = -1; } Dust dust; // You need to set position depending on what you are doing. You may need to subtract width/2 and height/2 as well to center the spawn rectangle. Vector2 position = npc.position + npc.velocity; dust = Main.dust[Terraria.Dust.NewDust(position, npc.width, npc.height, 127, 0f, 0f, 0, new Color(255, 255, 255), 1f)]; } public override void NPCLoot() { Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ItemID.GuideVoodooDoll, 1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Moudou.CodeGenerator.AbstractionClasses { public interface ITemplate { IInjector GetInjector(); string TransformText(); } }
using System; using System.Linq; using LightingBook.Test.Api.Common.Dto; using LightingBook.Tests.Api.Helper; using TechTalk.SpecFlow; using LightingBook.Tests.Api.Dto.Dto.HotelSelection; using LightingBook.Tests.Api.Dto.GetItinerary; using LightingBook.Tests.Api.Product.Hotel; using LightingBook.Tests.Api.SpecDto; using TechTalk.SpecFlow.Assist; using NUnit.Framework; using LightingBook.Test.Api.Common; using GlobalSettings = LightingBook.Test.Api.Client.v10.Models.TravelCTMOBTApiModelsv10SettingsGlobalSettings; using LightingBook.Tests.Api.Product.V10; using LightingBook.Test.Api.Common.Extensions; namespace LightingBook.Tests.Api.Steps { [Binding] public class HotelSearchStepDefinition { private ScenarioContext _scenarioContext; public HotelSearchStepDefinition(ScenarioContext scenarioContext) { if (scenarioContext == null) throw new ArgumentNullException("scenarioContext"); _scenarioContext = scenarioContext; } [Given(@"I enter search results for hotels from between (.*) and (.*) and as mentioned below:")] public void GivenIEnterSearchResultsForHotelsAsMentionedBelow(int weeksFromTodaysDate, int weeksToTodaysDate, Table table) { var tokenResponse = _scenarioContext.Get<TokenResponse>("TokenDetails"); var globalSettings = _scenarioContext.Get<GlobalSettings>("GlobalSettings"); var parameter = table.CreateInstance<HotelInputs>(); var dateFrom = DateTime.Now.AddWeeks(weeksFromTodaysDate); var dateTo = DateTime.Now.AddWeeks(weeksToTodaysDate); // get itinerary var tripIdentifier = new Itinerary(tokenResponse, ConfigurationBase.AppConfigDetails).GetItineraryHotel(globalSettings, parameter.PickUpCity, dateFrom.ToString(), dateTo.ToString(), parameter.HotelLat, parameter.HotelLong); _scenarioContext.Set(tripIdentifier, "TripIdentifierHotels"); _scenarioContext.Set(parameter, "HotelInputs"); } [When(@"I entered the hotel search results from between (.*) and (.*) and as mentioned below:")] public void WhenIEnteredTheHotelSearchResultsAsMentionedBelow(int weeksFromTodaysDate, int weeksToTodaysDate, Table table) { var loginCredentials = _scenarioContext.Get<TokenResponse>("TokenDetails"); var tripIdentifiers = _scenarioContext.Get<TripIdentifiers>("TripIdentifierHotels"); var hotelInputs = _scenarioContext.Get<HotelInputs>("HotelInputs"); var dateFrom = DateTime.Now.AddWeeks(weeksFromTodaysDate); var dateTo = DateTime.Now.AddWeeks(weeksToTodaysDate); var hotelSelections = new HotelBooking(tripIdentifiers, loginCredentials, ConfigurationBase.AppConfigDetails).HotelDetails(dateFrom.ToString(), dateTo.ToString(), hotelInputs.HotelLat, hotelInputs.HotelLong); _scenarioContext.Set(hotelSelections, "HotelSelectionDetails"); } [Then(@"the results should return list of hotels with price range (.*) to (.*)")] public void ThenTheResultsShouldReturnListOfHotelsWithPriceRangeTo(int minPrice, int maxPrice) { var HotelDetails = _scenarioContext.Get<HotelSelectionResponse>("HotelSelectionDetails"); // find all the rooms between minimum and maximum price var RoomRates = HotelDetails?.Hotels?.SelectMany(x => x.Rooms)?.SelectMany(x => x.Rates) ?.Where(x => (x.Amount >= minPrice && x.Amount <= maxPrice)); // check if there are more than one results found between that price Assert.IsTrue(RoomRates?.Count() > 0); var rateCodes = HotelDetails?.Hotels?.SelectMany(x => x.Rooms)?.SelectMany(x => x.Rates); } [Then(@"the results should return hotels with RateCode as (.*)")] public void ThenTheResultsShouldReturnHotelsWithRateCodeAs(string RateCode) { var HotelDetails = _scenarioContext.Get<HotelSelectionResponse>("HotelSelectionDetails"); var rate = HotelDetails?.Hotels?.SelectMany(x => x.Rooms)?.SelectMany(x => x.Rates)?.Where(x => x.RateCode == RateCode); //check if the hotel results return the expected RateCode as per my policy Assert.IsTrue(rate?.Count() > 0); } //===== -- 2nd test starts here -- ======================================================================================================================= // Checks for preferred chains. [Then(@"the results should return a preferred Hotel chain (.*)")] public void ThenTheResultsShouldReturnAPreferredHotelChain(string preferredHotelChainCode) { var HotelDetails = _scenarioContext.Get<HotelSelectionResponse>("HotelSelectionDetails"); var n = HotelDetails.Hotels?.Where(x => x.ChainCode == preferredHotelChainCode && x.Preferred.Equals(true)); Assert.IsTrue(n?.Count() > 0); } // Check min star rating [Then(@"the results should return hotels above (.*) minimum star rating")] public void ThenTheResultsShouldReturnHotelsAboveMinimumStarRating(double minimumStarRating) { var HotelDetails = _scenarioContext.Get<HotelSelectionResponse>("HotelSelectionDetails"); var minStarRT = HotelDetails.Hotels?.Where(x => x.Rating >= minimumStarRating); Assert.IsTrue(minStarRT?.Count() > 0); } [Then(@"the results should not return any Hotels with (.*) and is (.*)")] public void ThenTheResultsShouldNotReturnAnyHotelsWithAndIs(string notpreferredRoomType, string preferredRoomType) { var HotelDetails = _scenarioContext.Get<HotelSelectionResponse>("HotelSelectionDetails"); // Checking there are no notpreferredRoomType Rates var testRoomType = HotelDetails.Hotels?.SelectMany(x => x.Rooms).Where(x => x.Identification.Contains(preferredRoomType) || x.RoomName.Contains(preferredRoomType)); //Check we only have preferredRoomType rates Assert.IsTrue(testRoomType?.Count() >= 1); var testRoomNameNotEqual = HotelDetails.Hotels?.SelectMany(x => x.Rooms) ?.Where(x => !x.Identification.Contains(notpreferredRoomType)); Assert.IsTrue(testRoomNameNotEqual?.Count() >= 1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace Lab5 { class Program { static void Main(string[] args) { Stock st = new Stock(); Menu(st); } public static void Menu(Stock st) { Console.Clear(); Console.WriteLine("---------------------------------------------------------------"); Console.WriteLine("| 1: Create Item | 2: Item Inventory | 3: List Item | 4: Exit |"); Console.WriteLine("---------------------------------------------------------------"); int input = int.Parse(Console.ReadLine()); switch (input) { case 1: CreateItem(st); break; case 2: Console.WriteLine("What item?"); int choice = int.Parse(Console.ReadLine()); Console.WriteLine("How much?"); int amount = int.Parse(Console.ReadLine()); st.Inventory(choice: choice, newAmount: amount); break; case 3: st.ListItem(); break; case 4: Environment.Exit(0); break; default: Menu(st); break; } Console.ReadKey(); Console.Clear(); } private static void CreateItem(Stock st) { Console.Clear(); Console.WriteLine("| 1: Juice | 2: Plate |"); int input = int.Parse(Console.ReadLine()); switch (input) { case 1: AddJuice(st); break; default: AddPlate(st); break; } } private static void AddPlate(Stock st) { Console.WriteLine("Id is..."); int ID = int.Parse(Console.ReadLine()); Console.WriteLine("Name is..."); string name = Console.ReadLine(); Console.WriteLine("StockCount is..."); int stockCount = int.Parse(Console.ReadLine()); Console.WriteLine("Type is..."); string type = Console.ReadLine(); Plate plate = new Plate() {Id = ID, Name = name, StockCount = stockCount, Type = type}; //Stock st = new Stock(); st.AddItem(plate); //StockItem[plateItems] = new Plate() { Id = ID, }; } private static void AddJuice(Stock st) { Console.WriteLine("Id is..."); int ID = int.Parse(Console.ReadLine()); Console.WriteLine("Name is..."); string name = Console.ReadLine(); Console.WriteLine("StockCount is..."); int stockCount = int.Parse(Console.ReadLine()); Console.WriteLine("Mark is..."); string mark = Console.ReadLine(); Console.WriteLine("Type is..."); string type = Console.ReadLine(); Juice juice = new Juice() { Id = ID, Mark = mark, Name = name, StockCount = stockCount, Type = type }; st.AddItem(juice); Menu(st); } } }
namespace Groundwork.Domain { public interface IRepository<TEntity, in TopLevelDomain> : IReadOnlyRepository<TEntity, TopLevelDomain> where TEntity : IEntity<TopLevelDomain> { void Add(TEntity entity); void Remove(TopLevelDomain id); void Update(TEntity entity); } }
using System; using System.Collections.Generic; namespace DemoApp.Entities { public partial class OfficeStates { public Guid Id { get; set; } public Guid? StateId { get; set; } public Guid? OfficeId { get; set; } public virtual Offices Office { get; set; } public virtual States State { get; set; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; /* * This script creates an entirefield of gameobjects depending on the size of the terrain width and length */ public class EditLevel : MonoBehaviour { // .txt file to load you level from public string levelName = "Assets/Resources/Level1.txt"; private string waypointStringDifference = "PatrolWaypoints"; public string waypointName; // our selection according to the user public int userSelection = 2; // the height and the length of the terrain to obtain size use these values and times private int terrainHeight = 0; private int terrainLength = 0; // Size of the final prefab object private float i_SizeDiff = 1.0f; // storing all the level details List<List<GameObject>> levelNodes = new List<List<GameObject>>(); // Our clickable object container that stores all the rest of our display prefabs! public Object emptyNode; private GameObject previousNode; public int playerPrefabNumber = 4; public int enemyPrefabNumber = 5; // Line positions for waypoints public List<Vector3> lineConnector = new List<Vector3> (); // stores the new level's data if theres such a thing public List<List<int>> newLevelNodes = new List<List<int>> (); public void CreateNewLevel(string newMapName, int newTerrainWidth, int newTerrainHeight) { newLevelNodes.Clear (); string newWaypointName = newMapName; newWaypointName = newWaypointName.Insert (newWaypointName.Length - 4, waypointStringDifference); // Initialise the list of new level nodes for(int i = 0; i < newTerrainWidth; i++) { List<int> row = new List<int>(); for(int j = 0; j < newTerrainHeight; j++) { row.Add(0); } newLevelNodes.Add(row); } string saveText = ""; // Write the string to a file. System.IO.StreamWriter file = new System.IO.StreamWriter(newMapName); // concentanate the entire string into one long ass line for(int i = 0; i < newLevelNodes.Count; i++) { for(int j = 0; j < newLevelNodes[0].Count; j++) { saveText += newLevelNodes[i][j]; if(j != newLevelNodes.Count - 1) { saveText += " "; } } if(i != newLevelNodes.Count - 1) { saveText += "\n"; } } file.WriteLine(saveText); file.Close(); saveText = ""; // Write the string to the waypoint file System.IO.StreamWriter waypointFile = new System.IO.StreamWriter(newWaypointName); // concentanate the entire string into one long ass line for(int i = 0; i < newLevelNodes.Count; i++) { for(int j = 0; j < newLevelNodes[0].Count; j++) { saveText += newLevelNodes[i][j]; if(j != newLevelNodes.Count - 1) { saveText += " "; } } if(i != newLevelNodes.Count - 1) { saveText += "\n"; } } waypointFile.WriteLine(saveText); waypointFile.Close(); } // Reading from text file, through " " delim. string[][] readFile(string file) { string text = System.IO.File.ReadAllText(file); string[] lines = Regex.Split(text,"\n"); int rows = lines.Length; string[][] levelBase = new string[rows][]; for (int i = 0; i < lines.Length; i++) { string[] stringsOfLine = Regex.Split(lines[i], " "); levelBase[i] = stringsOfLine; } return levelBase; } // Clears the pathnamed text file to be completely empty void ClearTextFile(string path) { System.IO.File.WriteAllText(path, string.Empty); } void SaveFile() { string saveText = ""; // Write the string to a file. System.IO.StreamWriter file = new System.IO.StreamWriter(levelName); // concentanate the entire string into one long ass line for(int i = 0; i < levelNodes.Count; i++) { for(int j = 0; j < levelNodes[0].Count; j++) { saveText += (levelNodes[i][j].GetComponent<NodeDetails>().id).ToString(); if(j != levelNodes.Count - 1) { saveText += " "; } } if(i != levelNodes.Count - 1) { saveText += "\n"; } } if(saveText.EndsWith("\n")) { //Debug.Log("There is a carriage return"); } file.WriteLine(saveText); file.Close(); } void SaveWaypointFile() { string saveText = ""; // Write the string to a file. System.IO.StreamWriter file = new System.IO.StreamWriter(waypointName); // concentanate the entire string into one long ass line for(int i = 0; i < levelNodes.Count; i++) { for(int j = 0; j < levelNodes[0].Count; j++) { saveText += (levelNodes[i][j].GetComponent<NodeDetails>().waypointID).ToString(); if(j != levelNodes.Count - 1) { saveText += " "; } } if(i != levelNodes.Count - 1) { saveText += "\n"; } } if(saveText.EndsWith("\n")) { //Debug.Log("There is a carriage return"); } file.WriteLine(saveText); file.Close(); } public void SaveLevel() { ClearTextFile(levelName); SaveFile(); SaveWaypointFile (); } public void LoadChoosenLevel() { // if there were any old gameobjects that were loaded then we delete them all for (int i = 0; i < levelNodes.Count; i++) { for (int j = 0; j < levelNodes[0].Count; j++) { Destroy(levelNodes[i][j]); } } levelNodes.Clear (); // read the text file to check what is the height and length string[][] jagged = readFile(levelName); waypointName = levelName; waypointName = waypointName.Insert (waypointName.Length - 4, waypointStringDifference); string[][] jaggedWaypoints = readFile (waypointName); //Debug.Log (jagged.Length); //Debug.Log (jagged[0].Length); // assign how big our terrain should be! [: terrainLength = jagged[0].Length; terrainHeight = jagged.Length; //Debug.Log("Terrain Height: " + terrainHeight); //Debug.Log("Terrain Length: " + terrainLength); //Debug.Log("Waypoint Height: " + jaggedWaypoints[0].Length); //Debug.Log("Waypoint Length: " + jaggedWaypoints.Length); for (int y = 0; y < jagged.Length - 1; y++) { List<GameObject> firstDimensionArray = new List<GameObject>(); for (int x = 0; x < jagged[0].Length; x++) { int Value = int.Parse(jagged[y][x]); ////Debug.Log("X: " + x); ////Debug.Log("Y: " + y); GameObject assignedNode = Instantiate(emptyNode, new Vector3(x * i_SizeDiff, 0, y * i_SizeDiff), Quaternion.identity) as GameObject; //Assign the node a specific colour! assignedNode.GetComponent<NodeDetails>().id = int.Parse(jagged[y][x]); assignedNode.GetComponent<NodeDetails>().x = x; assignedNode.GetComponent<NodeDetails>().y = y; assignedNode.GetComponent<NodeDetails>().waypointID = int.Parse(jaggedWaypoints[y][x]); // assign the waypoint to the node assignedNode.GetComponent<NodeDetails>().SetTypeOfPrefab(); // Finally store the node firstDimensionArray.Add(assignedNode); } levelNodes.Add(firstDimensionArray); } // set terrain variables here // Terrain height has to minus one because of the EXTRA LINE SPACE IN THE TEXT FILE! GameObject.Find ("Terrain").GetComponent<Terrain> ().terrainData.size = new Vector3 ((float)terrainLength, 1.0f, (float)terrainHeight - 1); } // Checks if the last checkpoint is valid for the user to place for the AI to move from the previous point int CheckIfWaypointIsValid(int x, int y) { int latestWaypoint = 0; int enemyStartX = 0; int enemyStartY = 0; // list of passable tiles the Ai can walk through List<int> passableTiles = new List<int>(); passableTiles.Add (0); passableTiles.Add (4); passableTiles.Add (5); passableTiles.Add (6); for (int i = 0; i < levelNodes.Count; i++) { for (int j = 0; j < levelNodes[0].Count; j++) { // first we check what is the latest waypoint we have specified in the list if(levelNodes[i][j].GetComponent<NodeDetails>().waypointID > latestWaypoint) { // save the latest waypoint's position into memory latestWaypoint = levelNodes[i][j].GetComponent<NodeDetails>().waypointID; enemyStartX = j; enemyStartY = i; } } } //Debug.Log ("Latest Waypoint in the CSV: " + latestWaypoint); if(levelNodes[y][x].GetComponent<NodeDetails>().waypointID == 0) { // this means that we have not specified a waypoint before [: if(latestWaypoint == 0) { // obtain the location of the enemy spawn point for (int i = 0; i < levelNodes.Count; i++) { for (int j = 0; j < levelNodes[0].Count; j++) { // we check where is the enemy spawn point and we obtain x and y coordinates if(levelNodes[i][j].GetComponent<NodeDetails>().id == enemyPrefabNumber) { enemyStartX = levelNodes[i][j].GetComponent<NodeDetails>().x; enemyStartY = levelNodes[i][j].GetComponent<NodeDetails>().y; break; } } } //compare if the waypoint declared by the user is possible to move to from the enemy location on the map // First we compare to see if the row or column that the user has picked is within the same row or column if(x == enemyStartX|| y == enemyStartY) { // Next we check if theres anything inbetween the two nodes that we cannot walk through if(x == enemyStartX) { // We can confirm that the user has clicked on the left side of the starting node if(y < enemyStartY) { // Check everything between both nodes if there are any nodes that are impassable for(int i = y; i < enemyStartY; i++) { if(!passableTiles.Contains(levelNodes[i][x].GetComponent<NodeDetails>().id)) { return 0; } } } else { // Check everything between both nodes if there are any nodes that are impassable for(int i = enemyStartY; i <= y; i++) { if(!passableTiles.Contains(levelNodes[i][x].GetComponent<NodeDetails>().id)) { return 0; } } } } else if(y == enemyStartY) { // We can confirm that the user has clicked on the left side of the starting node if(x < enemyStartX) { // Check everything between both nodes if there are any nodes that are impassable for(int i = x; i < enemyStartX; i++) { if(!passableTiles.Contains(levelNodes[y][i].GetComponent<NodeDetails>().id)) { return 0; } } } else { // Check everything between both nodes if there are any nodes that are impassable for(int i = enemyStartX; i <= x; i++) { if(!passableTiles.Contains(levelNodes[y][i].GetComponent<NodeDetails>().id)) { return 0; } } } } return 1; } } else { // // it's not our first waypoint // // so we take the latest waypoint's node's position and we compare it to our clicked position! // // compare if the waypoint declared by the user is possible to move to from the enemy location on the map // // First we compare to see if the row or column that the user has picked is within the same row or column // The user has selected another waypoint if(x == enemyStartX && y == enemyStartY) { // remove that waypoint and another other waypoint numbers that are after this waypoint //UnselectedWaypoint(x, y); return 0; } else if(x == enemyStartX || y == enemyStartY) { // Next we check if theres anything inbetween the two nodes that we cannot walk through if(x == enemyStartX) { // We can confirm that the user has clicked on the left side of the starting node if(y < enemyStartY) { // Check everything between both nodes if there are any nodes that are impassable for(int i = y; i < enemyStartY; i++) { if(!passableTiles.Contains(levelNodes[i][x].GetComponent<NodeDetails>().id)) { return 0; } } } else { // Check everything between both nodes if there are any nodes that are impassable for(int i = enemyStartY; i <= y; i++) { if(!passableTiles.Contains(levelNodes[i][x].GetComponent<NodeDetails>().id)) { return 0; } } } } else if(y == enemyStartY) { // We can confirm that the user has clicked on the left side of the starting node if(x < enemyStartX) { // Check everything between both nodes if there are any nodes that are impassable for(int i = x; i < enemyStartX; i++) { if(!passableTiles.Contains(levelNodes[y][i].GetComponent<NodeDetails>().id)) { return 0; } } } else { // Check everything between both nodes if there are any nodes that are impassable for(int i = enemyStartX; i <= x; i++) { if(!passableTiles.Contains(levelNodes[y][i].GetComponent<NodeDetails>().id)) { return 0; } } } } return latestWaypoint + 1; } } } // this means that the user is attempting to delete a waypoint else { UnselectedWaypoint(x, y); } return 0; } // remove all waypoints that are after this node's waypoint ID void UnselectedWaypoint(int x, int y) { int removeFromWaypointID = levelNodes [y] [x].GetComponent<NodeDetails> ().waypointID; //Debug.Log ("Remove from CSV any waypoint above: " + removeFromWaypointID); // do until the waypoints id in the levelNodes list doesnt increase again for (int i = 0; i < levelNodes.Count; i++) { for (int j = 0; j < levelNodes[0].Count; j++) { // we get the next waypoint in the list (IF THERE SUCH A WAYPOINT HAHA) if(levelNodes[i][j].GetComponent<NodeDetails>().waypointID > removeFromWaypointID) { // set the waypoint value to 0 levelNodes[i][j].GetComponent<NodeDetails>().waypointID = 0; } } } } void Awake() { GameObject.Find ("Terrain").transform.position -= new Vector3 (0.5f, 0.0f, 0.5f); LoadChoosenLevel (); } // store the waypoint positions into a List void StoreWaypointLine() { lineConnector.Clear (); // obtain the location of the enemy spawn point for (int i = 0; i < levelNodes.Count; i++) { for (int j = 0; j < levelNodes[0].Count; j++) { // we check where is the enemy spawn point and we obtain x and y coordinates if(levelNodes[i][j].GetComponent<NodeDetails>().id == enemyPrefabNumber) { lineConnector.Add(levelNodes[i][j].transform.position + new Vector3(0.0f, 0.5f, 0.0f)); break; } } } int previousWaypointFigure = 0; int currentWaypointFigure = 0; // do until the waypoints id in the levelNodes list doesnt increase again do { previousWaypointFigure++; for (int i = 0; i < levelNodes.Count; i++) { for (int j = 0; j < levelNodes[0].Count; j++) { // we get the next waypoint in the list (IF THERE SUCH A WAYPOINT HAHA) if(levelNodes[i][j].GetComponent<NodeDetails>().waypointID == currentWaypointFigure + 1) { // save the latest waypoint's position into memory lineConnector.Add(levelNodes[i][j].transform.position + new Vector3(0.0f, 0.5f, 0.0f)); currentWaypointFigure++; break; } } } }while(currentWaypointFigure >= previousWaypointFigure); } // Update is called once per frame void Update () { // Hover ray for object outline Ray ray1 = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit1 = new RaycastHit(); if (Physics.Raycast (ray1, out hit1)) { //Debug.Log("Hit something"); // if we hit a transformable gameobject if(hit1.collider.transform.gameObject.GetComponent<ToggleOutline>() != null) { if(previousNode == hit1.collider.gameObject) { hit1.transform.gameObject.GetComponent<NodeDetails>().OnNodeOutline(); } else { // can optimise this to change only the old node's shader! for(int i = 0; i < levelNodes.Count; i++) { for(int j = 0; j < levelNodes[0].Count; j++) { levelNodes[i][j].GetComponent<NodeDetails>().OffNodeOutline(); } } } previousNode = hit1.collider.gameObject; //Debug.Log("Turn on the outline!"); } } else { for(int i = 0; i < levelNodes.Count; i++) { for(int j = 0; j < levelNodes[0].Count; j++) { levelNodes[i][j].GetComponent<NodeDetails>().OffNodeOutline(); } } } // Click to change a node's prefab if(Input.GetMouseButtonDown(0) && GUIUtility.hotControl == 0) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit = new RaycastHit(); if (Physics.Raycast (ray, out hit)) { // if we have a gameobject that is not null if(hit.collider.transform.gameObject.GetComponent<NodeDetails>() != null) { // if we hit a transformable gameobject and we've not selected a waypoint if(GetComponent<DisplayEditorGUI>().inputType == TypeOfInput.NORMAL_TILE) { if(userSelection == playerPrefabNumber || userSelection == enemyPrefabNumber) // this we have specified a player/enemy spawn location we have to remove any other player/enemy start points { for(int i = 0; i < levelNodes.Count; i++) { for(int j = 0; j < levelNodes[0].Count; j++) { if(levelNodes[i][j].GetComponent<NodeDetails>().id == userSelection) { levelNodes[i][j].GetComponent<NodeDetails>().id = 0; levelNodes[i][j].GetComponent<NodeDetails>().SetTypeOfPrefab(); } } } } hit.transform.gameObject.GetComponent<NodeDetails>().id = userSelection; hit.transform.gameObject.GetComponent<NodeDetails>().SetTypeOfPrefab(); // if we accidentally tried to place a block on a waypoint remove the rest of the waypoints! if(hit.transform.gameObject.GetComponent<NodeDetails>().waypointID != 0) { UnselectedWaypoint(hit.transform.gameObject.GetComponent<NodeDetails>().x, hit.transform.gameObject.GetComponent<NodeDetails>().y); hit.transform.gameObject.GetComponent<NodeDetails>().waypointID = 0; } } // We check if the waypoint is valid and then we apply the waypoint indication number and then we set that node in the level to 0 which is clear block else if(GetComponent<DisplayEditorGUI>().inputType == TypeOfInput.WAYPOINT) { // calculate if we can set a waypoint here! hit.transform.gameObject.GetComponent<NodeDetails>().waypointID = CheckIfWaypointIsValid(hit.transform.gameObject.GetComponent<NodeDetails>().x, hit.transform.gameObject.GetComponent<NodeDetails>().y); //Debug.Log("New Waypoint number is : " + hit.transform.gameObject.GetComponent<NodeDetails>().waypointID); } } } } // Detection for mouse scrolling the camera top and down if(!GetComponent<DisplayEditorGUI>().showLevelsList) { // Dont scroll on the camera Camera.main.transform.position += -(Vector3.up * Input.GetAxis("Mouse ScrollWheel")); } //Debug.Log ("Mouse Scroll Wheel value : " + (Vector3.forward * Input.GetAxis ("Mouse ScrollWheel"))); if(Input.GetKey(KeyCode.Alpha1)) { SaveLevel(); } StoreWaypointLine (); } }
using System; using GrapeCity.Documents.Excel; namespace DioDocs2 { class Program { static void Main(string[] args) { Workbook workbook = new Workbook(); workbook.Open(@"Book1.xlsx"); IWorksheet worksheet = workbook.Worksheets[0]; // numeric 5.2 int rowIndex = 0; for (decimal dec = 999.99M; dec > -1000M; dec -= 0.01M) { float f = (float)dec; worksheet.Cells[rowIndex, 0].Value = f; worksheet.Cells[rowIndex, 4].Value = f.ToString(); worksheet.Cells[rowIndex, 1].Value = (decimal)f; worksheet.Cells[rowIndex, 2].Value = dec; rowIndex++; } workbook.Save(@"Book2.xlsx"); } } }
using System.Collections.Generic; using System.Runtime.Serialization; namespace JenkinsBuildNotifier.Entities { [DataContract] internal sealed class ChangeSetModel { [DataMember] public List<ChangeSetItemModel> items { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Node : MonoBehaviour { private Renderer rend; public Sprite startSprite; public Color hoverColor; public Color noColor; public Color startColor; public Color notEnoughMoneyColor; public Sprite buildSprite; public Sprite endSprite; public GameObject turret; public GameObject tower; public bool path = false; private void Start() { startSprite = this.GetComponent<SpriteRenderer>().sprite; startColor = this.GetComponent<SpriteRenderer>().color; } void OnMouseDown() { // if (EventSystem.current.IsPointerOverGameObject()) // return; // if (turret != null) // { // buildManager.SelectNode(this); // return; // } // if (!buildManager.CanBuild) // return; // BuildTurret(buildManager.GetTurretToBuild()); if (turret == null && !path) { buildTurret(); } } void buildTurret() { // if (PlayerStats.Money < blueprint.cost) // { // Debug.Log("Not enough money to build that!"); // return; // } if (PlayerStats.Energy < BuildManager.towerCost) { Debug.Log("Not enough money to build that!"); gameObject.GetComponent<SpriteRenderer>().color = hoverColor; gameObject.GetComponent<SpriteRenderer>().color = noColor; return; } // PlayerStats.Money -= blueprint.cost; tower = BuildManager.currentTower; turret = (GameObject) Instantiate(tower, transform.position, Quaternion.identity); gameObject.GetComponent<SpriteRenderer>().sprite = buildSprite; gameObject.GetComponent<SpriteRenderer>().color = noColor; startSprite = buildSprite; path = true; PlayerStats.Energy -= BuildManager.towerCost; } void OnMouseEnter() { // if (buildManager.HasMoney) { // rend.material.color = hoverColor; // } else { // rend.material.color = notEnoughMoneyColor; // } if (!path && PlayerStats.Energy >= BuildManager.towerCost) { //gameObject.GetComponent<SpriteRenderer>().sprite = buildSprite; gameObject.GetComponent<SpriteRenderer>().color = hoverColor; } else if (!path && PlayerStats.Energy < BuildManager.towerCost) { gameObject.GetComponent<SpriteRenderer>().sprite = endSprite; gameObject.GetComponent<SpriteRenderer>().color = noColor; } } void OnMouseExit() { //gameObject.GetComponent<SpriteRenderer>().sprite = startSprite; if (turret == null) { gameObject.GetComponent<SpriteRenderer>().sprite = startSprite; gameObject.GetComponent<SpriteRenderer>().color = startColor; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using WolframAlpha.Api.v2; using WolframAlpha.Api.v2.Requests; namespace WolframAlphaAPI { public class WolframAlphaClient { public int CurrentAnswerIndex = 0; public bool HasAnswers { get { return Answers.Any(); } } public string CurrentAnswer { get { return Answers[CurrentAnswerIndex]; } } public string CurrentImageUrl { get { return AnswerImageUrls[CurrentAnswerIndex]; } } public List<string> Answers = new List<string>(); public List<string> AnswerImageUrls = new List<string>(); public bool QueryInProgress; private async Task<string> SendQuery(string query) { CurrentAnswerIndex = 0; Answers.Clear(); AnswerImageUrls.Clear(); QueryInProgress = true; QueryBuilder builder = new QueryBuilder(new Uri(ApiConstants.QueryBaseUrl)); builder.Input = query; builder.AppId = WolframAlphaConfig.AppId; QueryRequest request = new QueryRequest(); var uri = builder.QueryUri; var response = await request.ExecuteAsync(uri); if (response == null || response.Pods == null) { throw new InvalidOperationException("No Results Found."); } foreach (var pod in response.Pods) { if (pod.SubPods.Length == 0) { throw new InvalidOperationException("No Results Found."); } Answers.Add(pod.SubPods[0].PlainText); AnswerImageUrls.Add(pod.SubPods[0].Img.Src); } QueryInProgress = false; return CurrentAnswer; } public async Task<string> SendQueryAsync(string query) { try { await SendQuery(query); } catch { QueryInProgress = false; throw; } return CurrentAnswer; } } }
using webapi.Models; using webapi.Data; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace webapi.Controllers { [Route("api/[controller]")] [ApiController] public class alumnosController : ControllerBase { private readonly alumnosContext context; public alumnosController(alumnosContext contexto) { context = contexto; } /* [HttpGet] public IEnumerable<alumnos> GetAlumnosItems() { return context.alumnos.ToList(); }*/ [HttpGet] public async Task<ActionResult<IEnumerable<alumnos>>>GetAlumnosItemsAll() { return await context.alumnos.ToListAsync(); } [HttpGet("{id2}")] public async Task<ActionResult<alumnos>> GetAlumnosItems(int id2) { var PersonaItem = await context.alumnos.FirstOrDefaultAsync(x => x.id.Equals(id2)); if (PersonaItem == null) { return NoContent(); } return PersonaItem; } [HttpPost] public async Task<ActionResult<alumnos>> PostAlumnosItems(alumnos item) { context.alumnos.Add(item); await context.SaveChangesAsync(); return CreatedAtAction(nameof(GetAlumnosItems),new { id2 = item.id}, item); } [HttpDelete("{id}")] public async Task<IActionResult>DeleteAlumnosItems(int id) { var AlumnoItem = await context.alumnos.FindAsync(id); if (AlumnoItem == null) { return NotFound(); } context.alumnos.Remove(AlumnoItem); await context.SaveChangesAsync(); return NoContent(); } [HttpPut("{id}")] public async Task<IActionResult> PutCuestionarioItem(int id, alumnos item) { if (id != item.id) { return BadRequest(); } context.Entry(item).State = EntityState.Modified; await context.SaveChangesAsync(); return NoContent(); } } }
namespace AssessmentApp.Services.Data { using System.Collections.Generic; using System.Linq; using AssessmentApp.Data.Common.Repositories; using AssessmentApp.Data.Models; using AssessmentApp.Services.Mapping; using AssessmentApp.Web.ViewModels.Assessments; public class StoresService : IStoresService { private readonly IDeletableEntityRepository<Store> storeRepository; public StoresService(IDeletableEntityRepository<Store> storeRepository) { this.storeRepository = storeRepository; } public IEnumerable<T> GetAll<T>(int? count = null) { IQueryable<Store> stores = this.storeRepository.All().OrderBy(x => x.Name); return stores.To<T>().ToList(); } } }
using Cs_Notas.Dominio.Entities; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Notas.Infra.Data.EntityConfig { public class CertidaoProcuracaoConfig: EntityTypeConfiguration<CertidaoProcuracao> { public CertidaoProcuracaoConfig() { HasKey(p => p.CertidaoProcuracaoId); Property(p => p.CertidaoProcuracaoId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(p => p.Data) .HasColumnType("Date"); Property(p => p.Selo) .HasMaxLength(9); Property(p => p.Cpf1) .HasMaxLength(11); Property(p => p.Cpf2) .HasMaxLength(11); Property(p => p.Cpf3) .HasMaxLength(11); Property(p => p.TipoCobranca) .HasMaxLength(2); Property(p => p.DataModificado) .HasColumnType("Date") .IsOptional(); Property(p => p.HoraModificado) .HasColumnType("DateTime") .IsOptional(); Property(p => p.Emolumentos) .IsOptional(); Property(p => p.Fetj) .IsOptional(); Property(p => p.Fundperj) .IsOptional(); Property(p => p.Funprj) .IsOptional(); Property(p => p.Funarpen) .IsOptional(); Property(p => p.Pmcmv) .IsOptional(); Property(p => p.Iss) .IsOptional(); Property(p => p.Aleatorio) .HasMaxLength(3); Property(p => p.UF_Origem) .HasMaxLength(2); Property(p => p.Recibo) .HasMaxLength(20); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Resources; namespace Meshop.Framework.Translation { public class DBResourceReader : DisposableBaseType, IResourceReader, IEnumerable<KeyValuePair<string, object>> { private ListDictionary m_resourceDictionary; public DBResourceReader(ListDictionary resourceDictionary) { this.m_resourceDictionary = resourceDictionary; } public void Close() { throw new NotImplementedException(); } IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() { throw new NotImplementedException(); } public IDictionaryEnumerator GetEnumerator() { return this.m_resourceDictionary.GetEnumerator(); } // other methods IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
namespace DelftTools.Utils.Serialization { /// <summary> /// Interface to implement on a compressor class which can be used to compress/decompress the resulting byte array of the Fast serializer. /// </summary> public interface IByteCompressor { /// <summary> /// Compresses the specified serialized data. /// </summary> /// <param name="serializedData">The serialized data.</param> /// <returns>The passed in serialized data in compressed form</returns> byte[] Compress(byte[] serializedData); /// <summary> /// Decompresses the specified compressed data. /// </summary> /// <param name="compressedData">The compressed data.</param> /// <returns>The passed in de-serialized data in compressed form</returns> byte[] Decompress(byte[] compressedData); } }
using System.Collections.Generic; using Airelax.Domain.Houses.Defines; namespace Airelax.Application.Houses.Dtos.Request { public class UpdateHouseFacilitiesInput { public List<Facility> ProvideFacilities { get; set; } } }
using System.Collections.Generic; using System.Linq; namespace vrp { public class SimpleVrpSolver : VrpSolverBase { public override VrpResult Solve(VrpData data) { var sortedCustomers = data.Customers.OrderByDescending(c => c.Demand).ToArray(); var result = new VrpResult(); result.Routes = new List<int>[data.V]; var n = data.N; var v = data.V; var used = new bool[n]; used[0] = true; for (int i = 0; i < v; i++) { var route = new List<int> { 0 }; var cap = data.C; foreach (var customer in sortedCustomers.Where(c => !used[c.Id]).ToList()) { if (customer.Demand <= cap) { cap -= customer.Demand; route.Add(customer.Id); used[customer.Id] = true; } } route.Add(0); result.Routes[i] = route; } ApplyTsp(data, result); CalcTotalDist(data, result); return result; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using MultiplechoiseSystem.DTO; namespace MultiplechoiseSystem.DAO { class TestDAO { private static TestDAO instance; public static TestDAO Instance { get { if (instance == null) instance = new TestDAO(); return TestDAO.instance; } private set { TestDAO.instance = value; } } public List<TestDTO> getListTestByExamID_courseID(string examID, string courseID) { List<TestDTO> lst = new List<TestDTO>(); string query = $"SELECT * from TEST join COURSE on COURSE.courseID= test.courseID where TEST.examID='{examID}' and TEST.courseID='{courseID}'"; DataTable result = DataProvider.Instance.ExecuteQuery(query); foreach (DataRow i in result.Rows) { TestDTO t = new TestDTO(); t.code = i["Code"].ToString().Trim(); t.examID = i["examID"].ToString().Trim(); t.courseID = i["courseID"].ToString().Trim(); t.DateAppove = (DateTime)i["DateApprove"]; t.DateComfirm = (DateTime)i["DateConfirm"]; t.corseName = i["CourseName"].ToString(); lst.Add(t); } return lst; } public List<TestDTO> getListFullTestbyManager(string idmanager) { List<TestDTO> lst = new List<TestDTO>(); string query = $" select * from test join COURSE on COURSE.courseID= test.courseID where test.courseID in (select courseID from course where IDmngLecturer='{UserDTO.Instance.userID}') "; DataTable result = DataProvider.Instance.ExecuteQuery(query); foreach (DataRow i in result.Rows) { TestDTO t = new TestDTO(); t.courseID = i["courseID"].ToString().Trim(); t.code = i["Code"].ToString().Trim(); t.DateComfirm = (DateTime)i["DateConfirm"]; t.examID = i["examID"].ToString().Trim(); t.corseName = i["CourseName"].ToString().Trim(); try { t.DateAppove = (DateTime)i["DateAppove1"]; } catch { } lst.Add(t); } return lst; } } }
using EntVenta; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DatVentas { public class DatUser { public static string AUX_CONEXION; public DataTable getUsers(User u) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { DataTable dt = new DataTable(); try { SqlDataAdapter da = new SqlDataAdapter("EXEC sp_Mostrar_Usuario '" + u.Usuario + "' , '"+u.Contraseña+"'", conn); da.Fill(dt); return dt; } catch (Exception ) { conn.Close(); // throw ex; } return dt; } } public int AddUser(User u) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { try { int resultado = 0; conn.Open(); SqlCommand sc = new SqlCommand("sp_insertar_usuario", conn); sc.CommandType = CommandType.StoredProcedure; sc.Parameters.AddWithValue("@nombre",u.Nombre); sc.Parameters.AddWithValue("@apellidos", u.Apellidos); sc.Parameters.AddWithValue("@localidad",u.Direccion); sc.Parameters.AddWithValue("@foto", u.Foto); sc.Parameters.AddWithValue("@nombre_foto", u.NombreFoto); sc.Parameters.AddWithValue("@usuario",u.Usuario); sc.Parameters.AddWithValue("@contrasenia",u.Contraseña); sc.Parameters.AddWithValue("@correo",u.Correo); sc.Parameters.AddWithValue("@rol",u.RolID); sc.Parameters.AddWithValue("@estado", true); resultado = sc.ExecuteNonQuery(); conn.Close(); return resultado; } catch (Exception ex) { conn.Close(); throw ex; } } } public int DeleteUser(User u) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { try { int resultado = 0; conn.Open(); SqlCommand sc = new SqlCommand("UPDATE tb_Usuario SET Estado = 0 WHERE Id_Usuario = '"+u.Id+"'", conn); resultado = sc.ExecuteNonQuery(); conn.Close(); return resultado; } catch (Exception ex) { conn.Close(); throw ex; } } } public int EditUser(User u) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { try { int resultado = 0; conn.Open(); SqlCommand sc = new SqlCommand("sp_editar_usuario", conn); sc.CommandType = CommandType.StoredProcedure; sc.Parameters.AddWithValue("@idusuario", u.Id); sc.Parameters.AddWithValue("@nombre", u.Nombre); sc.Parameters.AddWithValue("@apellidos", u.Apellidos); sc.Parameters.AddWithValue("@localidad", u.Direccion); sc.Parameters.AddWithValue("@foto", u.Foto); sc.Parameters.AddWithValue("@nombre_foto", u.NombreFoto); sc.Parameters.AddWithValue("@usuario", u.Usuario); sc.Parameters.AddWithValue("@contrasenia", u.Contraseña); sc.Parameters.AddWithValue("@correo", u.Correo); sc.Parameters.AddWithValue("@rol", u.RolID); sc.Parameters.AddWithValue("@estado", true); resultado = sc.ExecuteNonQuery(); conn.Close(); return resultado; } catch (Exception ex) { conn.Close(); throw ex; } } } public string ShowPremission(string user) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { try { string resultado; conn.Open(); SqlCommand sc = new SqlCommand("SELECT TU.Nombre AS Rol FROM tb_Usuario U INNER JOIN Cat_Tipo_Usuario TU ON TU.Id_Rol = U.Rol_Id WHERE U.Usuario='" + user + "' AND U.Estado = 1", conn); resultado = sc.ExecuteScalar().ToString(); conn.Close(); return resultado; } catch (Exception ex) { conn.Close(); throw ex; } } } public DataTable MostrarUsuarios() { DataTable dt = new DataTable(); try { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tb_Usuario", conn); da.Fill(dt); AUX_CONEXION = "CORRECTO"; } } catch { AUX_CONEXION = "INCORRECTO"; } return dt; } } }
using System; namespace Boxofon.Web.Model { public class TwilioPhoneNumber { public string PhoneNumber { get; set; } public string FriendlyName { get; set; } public string TwilioAccountSid { get; set; } public Guid UserId { get; set; } } }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright 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. */ namespace AudienceNetwork.Editor { using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; using AudienceNetwork; public class AudienceNetworkSettingsEditor : UnityEditor.Editor { private static string title = "Audience Network SDK"; [MenuItem("Tools/Audience Network/About")] private static void AboutGUI () { string aboutString = System.String.Format ("Facebook Audience Network Unity SDK Version {0}", AudienceNetwork.SdkVersion.Build); EditorUtility.DisplayDialog (title, aboutString, "Okay"); } [MenuItem("Tools/Audience Network/Regenerate Android Manifest")] private static void RegenerateManifest () { bool updateManifest = EditorUtility.DisplayDialog (title, "Are you sure you want to regenerate your Android Manifest.xml?", "Okay", "Cancel"); if (updateManifest) { AudienceNetwork.Editor.ManifestMod.GenerateManifest (); EditorUtility.DisplayDialog (title, "Android Manifest updated. \n \n If interstitial ads still throw ActivityNotFoundException, " + "you may need to copy the generated manifest at " + ManifestMod.AndroidManifestPath + " to /Assets/Plugins/Android.", "Okay"); } } [MenuItem("Tools/Audience Network/Build SDK Package")] private static void BuildGUI () { try { string exportedPath = AudienceNetworkBuild.ExportPackage (); EditorUtility.DisplayDialog (title, "Exported to " + exportedPath, "Okay"); } catch (System.Exception e) { EditorUtility.DisplayDialog (title, e.Message, "Okay"); } } } }
using Microsoft.Extensions.Logging; using Sentry.Extensibility; namespace Sentry.Extensions.Logging; /// <summary> /// MEL => Microsoft.Extensions.Logging /// </summary> /// <remarks> /// Replaces the default Console logger as early as the logging factory is built /// </remarks> public class MelDiagnosticLogger : IDiagnosticLogger { private readonly ILogger<ISentryClient> _logger; private readonly SentryLevel _level; /// <summary> /// Creates a new instance of <see cref="MelDiagnosticLogger"/>. /// </summary> public MelDiagnosticLogger(ILogger<ISentryClient> logger, SentryLevel level) { _logger = logger; _level = level; } /// <summary> /// Whether this logger is enabled for the provided level /// </summary> /// <remarks> /// Enabled if the level is equal or higher than then both <see cref="SentryLevel"/> /// set via the options and also the inner <see cref="ILogger{TCategoryName}"/> /// </remarks> /// <param name="level"></param> public bool IsEnabled(SentryLevel level) => _logger.IsEnabled(level.ToMicrosoft()) && level >= _level; /// <summary> /// Logs the message. /// </summary> public void Log(SentryLevel logLevel, string message, Exception? exception = null, params object?[] args) { if (!IsEnabled(logLevel)) { return; } _logger.Log(logLevel.ToMicrosoft(), exception, message, args); } }
using UnityEngine; using UnityAtoms.BaseAtoms; using UnityAtoms.Mobile; namespace UnityAtoms.Mobile { /// <summary> /// Set variable value Action of type `TouchUserInput`. Inherits from `SetVariableValue&lt;TouchUserInput, TouchUserInputPair, TouchUserInputVariable, TouchUserInputConstant, TouchUserInputReference, TouchUserInputEvent, TouchUserInputPairEvent, TouchUserInputVariableInstancer&gt;`. /// </summary> [EditorIcon("atom-icon-purple")] [CreateAssetMenu(menuName = "Unity Atoms/Actions/Set Variable Value/TouchUserInput", fileName = "SetTouchUserInputVariableValue")] public sealed class SetTouchUserInputVariableValue : SetVariableValue< TouchUserInput, TouchUserInputPair, TouchUserInputVariable, TouchUserInputConstant, TouchUserInputReference, TouchUserInputEvent, TouchUserInputPairEvent, TouchUserInputTouchUserInputFunction, TouchUserInputVariableInstancer> { } }
using System; using Xunit; using Rhino.Mocks.Interfaces; namespace Rhino.Mocks.Tests.FieldsProblem { public class FieldProblem_MichaelC { [Fact] public void EventRaiser_ShouldRaiseEvent_OnlyOnce() { IWithEvent mock = MockRepository.GenerateStrictMock<IWithEvent>(); int countOne = 0; int countTwo = 0; IEventRaiser raiser = mock.Expect(x => x.Load += null).IgnoreArguments().Repeat.Twice().GetEventRaiser(); mock.Load += delegate { countOne++; }; mock.Load += delegate { countTwo++; }; raiser.Raise(this, EventArgs.Empty); Assert.Equal(1, countOne); Assert.Equal(1, countTwo); raiser.Raise(this, EventArgs.Empty); Assert.Equal(2, countOne); Assert.Equal(2, countTwo); raiser.Raise(this, EventArgs.Empty); Assert.Equal(3, countOne); Assert.Equal(3, countTwo); } } }
namespace Tutorial.Tests.LinqToEntities { using System; #if NETFX using System.Data.Entity.Core; #endif using System.Diagnostics; using Tutorial.LinqToEntities; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class LoadingTests { [TestMethod] public void DisposableTest() { try { UI.RenderCategoryProducts("Bikes"); Assert.Fail(); } catch (InvalidOperationException exception) { Trace.WriteLine(exception); } } [TestMethod] public void DeferredExecutionTest() { Loading.DeferredExecution(new AdventureWorks()); } [TestMethod] public void ExplicitLoadingTest() { Loading.ExplicitLoading(new AdventureWorks()); Loading.ExplicitLoadingWithQuery(new AdventureWorks()); } [TestMethod] public void LazyLoadingTest() { #if NETFX Loading.LazyLoading(new AdventureWorks()); #else try { Loading.LazyLoading(new AdventureWorks()); Assert.Fail(); } catch (NullReferenceException exception) { Trace.WriteLine(exception); } #endif #if NETFX Loading.MultipleLazyLoading(new AdventureWorks()); try { Loading.LazyLoadingAndDeferredExecution(new AdventureWorks()); } catch (EntityCommandExecutionException exception) { Trace.WriteLine(exception); } Loading.LazyLoadingAndImmediateExecution(new AdventureWorks()); #endif } [TestMethod] public void EagerLoadingTest() { Loading.EagerLoadingWithInclude(new AdventureWorks()); Loading.EagerLoadingMultipleLevels(new AdventureWorks()); #if NETFX Loading.EagerLoadingWithIncludeAndSelect(new AdventureWorks()); #endif Loading.EagerLoadingWithSelect(new AdventureWorks()); #if NETFX Loading.PrintSubcategoriesWithLazyLoading(new AdventureWorks()); Loading.PrintSubcategoriesWithEagerLoading(new AdventureWorks()); Loading.ConditionalEagerLoadingWithSelect(new AdventureWorks()); try { Loading.ConditionalEagerLoadingWithInclude(new AdventureWorks()); } catch (ArgumentException exception) { Trace.WriteLine(exception); } #endif } [TestMethod] public void DisableLazyLoadingTest() { #if NETFX Loading.DisableLazyLoading(new AdventureWorks()); Loading.DisableProxy(new AdventureWorks()); #endif } } }
using System.Collections.Generic; public class EmployeePositionEqualityComparer : IEqualityComparer<Employee> { public bool Equals(Employee x, Employee y) { return x.Id.Equals(y.Id) && x.Position.Equals(y.Position); } public int GetHashCode(Employee obj) { return obj.Id.GetHashCode() ^ obj.Position.GetHashCode(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; using TMPro; using GodMorgon.Models; using GodMorgon.StateMachine; /** * Présent sur chaque carte * Gère l'affichage des infos Name, Description, Artwork et Template sur le prefab Card * Gère aussi le drag and drop de la carte, et les effets qui en découlent * On peut déclencher des évènements liés au drag and drop dans les autres scripts grâce aux delegate */ public class CardDisplay : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { public BasicCard card; public int cardId; public TextMeshProUGUI nameText; public TextMeshProUGUI descriptionText; public TextMeshProUGUI costText; public Image artworkImage; public Image template; public bool isHover = false; public float timeHover = 1.0f; private static bool cardIsDragging = false; public GameObject display = null; /** * Load the data of the card in the gameObject at start, if the card exist. */ void Start() { if (card) { nameText.text = card.name; descriptionText.text = card.description; artworkImage.sprite = card.artwork; cardId = card.id; costText.text = card.actionCost.ToString(); } UpdateDescription(); } /** * update the card gameObject using the card data */ public void UpdateCard(BasicCard cardData) { //Debug.Log("on lolololol : " + cardData.name); //Save the scriptableObject used by this card gameObject card = cardData; nameText.text = cardData.name; descriptionText.text = cardData.description; if (cardData.template) template.sprite = cardData.template; if (cardData.artwork) artworkImage.sprite = cardData.artwork; costText.text = card.actionCost.ToString(); UpdateDescription(); } /** * met les données dans la description à jour : * 1)met à jour la data par rapport aux buffs du player (exemple : killer instinct...) * 2)met à jour la data par rapport aux effets de la carte ( exemple : shiver, trust....) */ public void UpdateDescription() { if (card != null) { string cardDescription = card.description; //damage int actualDamage = BuffManager.Instance.getModifiedDamage(card.GetRealDamage()); cardDescription = cardDescription.Replace("[nbDamage]", "<b>" + actualDamage.ToString() + "</b>"); //block int actualBlock = BuffManager.Instance.getModifiedBlock(card.GetRealBlock()); cardDescription = cardDescription.Replace("[nbBlock]", "<b>" + actualBlock.ToString() + "</b>"); //Move int actualMove = BuffManager.Instance.getModifiedMove(card.GetRealMove()); cardDescription = cardDescription.Replace("[nbMove]", "<b>" + actualMove.ToString() + "</b>"); //Heal int actualHeal = BuffManager.Instance.getModifiedHeal(card.GetRealHeal()); cardDescription = cardDescription.Replace("[nbHeal]", "<b>" + actualHeal.ToString() + "</b>"); //carte à piocher cardDescription = cardDescription.Replace("[nbCardToDraw]", "<b>" + card.GetRealNbDraw().ToString() + "</b>"); descriptionText.text = cardDescription; } } /** * doit activer l'animation de l'agrandissement de la carte */ public void OnPointerEnter(PointerEventData pointerEventData) { if(!cardIsDragging) { isHover = true; StartCoroutine(ScaleCardIn()); } } public void OnPointerExit(PointerEventData eventData) { if (!cardIsDragging) { isHover = false; StartCoroutine(ScaleCardOut()); } } public IEnumerator ScaleCardIn() { GetComponent<Canvas>().sortingOrder = 1; Vector3 originalScale = display.transform.localScale; Vector3 destinationScale = new Vector3(2.0f, 2.0f, 0); Vector3 originalPosition = display.transform.localPosition; Vector3 destinationPosition = new Vector3(0, 215, -100); float currentTime = 0.0f; while (currentTime <= timeHover && isHover) { display.transform.localScale = Vector3.Lerp(originalScale, destinationScale, currentTime); display.transform.localPosition = Vector3.Lerp(originalPosition, destinationPosition, currentTime); currentTime += Time.deltaTime * 4; yield return null; } } public IEnumerator ScaleCardOut() { GetComponent<Canvas>().sortingOrder = 0; Vector3 originalScale = display.transform.localScale; Vector3 destinationScale = new Vector3(1, 1, 1); Vector3 originalPosition = display.transform.localPosition; Vector3 destinationPosition = new Vector3(0, 0, 0); float currentTime = 0.0f; while (currentTime <= timeHover && !isHover) { display.transform.localScale = Vector3.Lerp(originalScale, destinationScale, currentTime); display.transform.localPosition = Vector3.Lerp(originalPosition, destinationPosition, currentTime); currentTime += Time.deltaTime * 4; yield return null; } } //quand la carte est drag, elle reprend sa taille normale public void OnCardDrag(bool isCardDrag) { if (isCardDrag) { cardIsDragging = true; isHover = false; StopCoroutine(ScaleCardIn()); StopCoroutine(ScaleCardOut()); display.transform.localScale = new Vector3(1, 1, 1); display.transform.localPosition = new Vector3(0, 0, 0); } else cardIsDragging = false; } }
using UnityEngine; using System.Collections; public class BgScaler : MonoBehaviour { // Use this for initialization void Start () { float heightWorld = Camera.main.orthographicSize * 2f; float widthWorld = heightWorld / Screen.height * Screen.width; float width = GetComponent<BoxCollider2D>().size.x; Vector3 tmp = transform.localScale; tmp.x = widthWorld / width; transform.localScale = tmp; } // Update is called once per frame void Update () { } }
using JT808.Protocol.Attributes; using JT808.Protocol.Formatters; using JT808.Protocol.MessagePack; namespace JT808.Protocol.MessageBody { /// <summary> /// 监控平台 SMS 电话号码 /// </summary> public class JT808_0x8103_0x0043 : JT808_0x8103_BodyBase, IJT808MessagePackFormatter<JT808_0x8103_0x0043> { public override uint ParamId { get; set; } = 0x0043; /// <summary> /// 数据 长度 /// </summary> public override byte ParamLength { get; set; } /// <summary> /// 监控平台 SMS 电话号码 /// </summary> public string ParamValue { get; set; } public JT808_0x8103_0x0043 Deserialize(ref JT808MessagePackReader reader, IJT808Config config) { JT808_0x8103_0x0043 jT808_0x8103_0x0043 = new JT808_0x8103_0x0043(); jT808_0x8103_0x0043.ParamId = reader.ReadUInt32(); jT808_0x8103_0x0043.ParamLength = reader.ReadByte(); jT808_0x8103_0x0043.ParamValue = reader.ReadString(jT808_0x8103_0x0043.ParamLength); return jT808_0x8103_0x0043; } public void Serialize(ref JT808MessagePackWriter writer, JT808_0x8103_0x0043 value, IJT808Config config) { writer.WriteUInt32(value.ParamId); writer.Skip(1, out int skipPosition); writer.WriteString(value.ParamValue); int length = writer.GetCurrentPosition() - skipPosition - 1; writer.WriteByteReturn((byte)length, skipPosition); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Moulinette { class Correction { //FIX ME private string name; private string folder; private string stdout; private string stderr; //FIX ME public string getName() { return name; } public string getStdout() { return stdout; } public string getStderr() { return stderr; } public Correction(string folderName) { DirectoryInfo my_DIR = new DirectoryInfo(folderName); name = my_DIR.Name; folder = folderName; } public bool init() { try { StreamReader stdo = new StreamReader("Correction/Exo_0/stdout.txt"); StreamReader stde = new StreamReader("Correction/Exo_0/stderr.txt"); stderr = stde.ReadToEnd(); stdout = stdo.ReadToEnd(); stdo.Close(); stde.Close(); return true; } catch (Exception) { return false; } } } }
using Backend.Model.Pharmacies; using IntegrationAdapters.Adapters; using IntegrationAdapters.Dtos; using IntegrationAdapters.MicroserviceComunicator; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Threading.Tasks; namespace IntegrationAdapters.Controllers { [ApiController] [Route("api/[controller]")] public class HelpController : ControllerBase { private readonly IPharmacySystemService _pharmacySystemService; private readonly IAdapterContext _adapterContext; public HelpController(IPharmacySystemService pharmacySystemService, IAdapterContext adapterContext) { _pharmacySystemService = pharmacySystemService; _adapterContext = adapterContext; } [HttpGet("{id}", Name = "GetDrugsFromPharmacy")] public async Task<ActionResult<List<DrugListDTO>>> GetDrugsFromPharmacy(int id) { List<DrugListDTO> ret = new List<DrugListDTO>(); PharmacySystem pharmacySystem = await _pharmacySystemService.Get(id); if (_adapterContext.SetPharmacySystemAdapter(pharmacySystem) != null) ret.AddRange(_adapterContext.PharmacySystemAdapter.GetAllDrugs()); return Ok(ret); } } }
using System; namespace NetCore.Utlity { public class StaticConstraint { public static string CustomConnection = null; public static void Init(Func<string,string> func) { CustomConnection = func.Invoke("ConnectionStrings:CustomersConnectionString"); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using log4net; using MiNET.Blocks; using MiNET.Utils; using MiNET.Worlds; using MiNETDevTools.Graphics.Components; using MiNETDevTools.Graphics.Internal; using MiNETDevTools.Plugin; using MiNETDevToolsPlugin.Interfaces; using MiNETDevToolsPlugin.Models; using Newtonsoft.Json; using SharpDX; using SharpDX.Direct2D1; using WinApi.DxUtils.Component; using WinApi.Windows; using Color = System.Drawing.Color; using Point = SharpDX.Point; namespace MiNETDevTools.Graphics.Biomes { public class BiomeMapComponent : ViewportComponent { private static readonly ILog Log = LogManager.GetLogger(typeof(BiomeMapComponent)); IBiomeMapRenderer[] Chunks { get { lock (_renderSync) { return _cachedChunks.Values.ToArray(); } } } private Point _minChunk = Point.Zero; private Point _maxChunk = Point.Zero; private LevelData _level; private BiomeUtils _biomeUtils; private readonly object _renderSync = new object(); private bool _fetchAll = true; public BiomeMapComponent() { _biomeUtils = new BiomeUtils(); _biomeUtils.PrecomputeBiomeColors(); } public void Init(LevelData level) { Name = level.Id; Text = level.Name; _level = level; } private Dictionary<ChunkCoordinates, IBiomeMapRenderer> _cachedChunks = new Dictionary<ChunkCoordinates, IBiomeMapRenderer>(); internal void UpdateMap() { if (_level == null) return; using (var client = PluginClient.LevelService) { ChunkData[] chunks; if (_fetchAll) { chunks = client.Proxy.FetchAllChunksForLevel(_level.Id); } else { chunks = client.Proxy.FetchUpdatedChunksForLevel(_level.Id); } if (chunks == null || chunks.Length == 0) return; foreach (var chunk in chunks) { InitChunk(chunk); } } } private void InitChunk(ChunkData chunk) { var k = new ChunkCoordinates(chunk.X, chunk.Z); lock (_renderSync) { IBiomeMapRenderer renderer; if (!_cachedChunks.TryGetValue(k, out renderer)) { renderer = new BiomeHeightMapRenderer(this, chunk); _cachedChunks.Add(k, renderer); Log.InfoFormat("Cached chunk {0},{1} ({2}) {3}", chunk.X, chunk.Z, Chunks.Length, JsonConvert.SerializeObject(chunk.ColumnInfo)); } else { renderer.Update(chunk); } } } internal Color GetBiomeColor(byte biomeId) { var biome = _biomeUtils.GetBiome(biomeId); var c = biome.Grass; //if (Mode == DisplayMode.BiomeFoilage) { // c = biome.Foliage; } int r = (int)((c >> 16) & 0xff); int g = (int)((c >> 8) & 0xff); int b = (int)c & 0xff; //Debug.WriteLine("Biome {0}: {1} {2}", biomeId, biome.Grass, biome.Foliage); return Color.FromArgb(r, g, b); } protected override void OnPaintView(DeviceContext context) { if (_level == null) return; foreach (var chunk in Chunks) { chunk.Render(context); } } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } class BiomeMapChunk { public int X { get; } public int Y { get; } public byte[] BitmapCache { get; set; } } interface IBiomeMapRenderer : IDisposable { int X { get; } int Y { get; } void Update(ChunkData data); void Render(DeviceContext context); } }
using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using tellick_admin.Repository; namespace tellick_admin.Controllers { [Authorize] [Route("api/[controller]")] public class CustomerController : Controller { private GenericRepository<Customer> _customerRepository; public CustomerController(TellickAdminContext context) { _customerRepository = new GenericRepository<Customer>(context); } [HttpGet(Name = "GetAllCustomers")] public IActionResult GetAllCustomers() { return Ok(_customerRepository.SearchFor()); } [HttpGet("{name}", Name = "GetCustomer")] public IActionResult GetCustomer(string name) { Customer c = _customerRepository.SearchFor(i => i.Name == name).SingleOrDefault(); if (c == null) return NotFound(); return Ok(c); } [HttpPost] public IActionResult Create([FromBody] Customer item) { if (item == null) return BadRequest("No customer data provided."); Customer c = _customerRepository.SearchFor(i => i.Name == item.Name).SingleOrDefault(); if (c != null) return BadRequest("Customer name already exists."); _customerRepository.Insert(item); _customerRepository.Save(); return CreatedAtRoute("GetCustomer", new { id = item.Id }, item); } } }
using System; namespace Public_Transport { class Program { static void Main(string[] args) { string lineChosen = Console.ReadLine(); string season = Console.ReadLine(); double time = 0.0; if (season == "Winter") { if (lineChosen == "208") { time = 65; } else if (lineChosen == "15") { time = 57; } else if (lineChosen == "240") { time = 48; } else if (lineChosen == "Subway") { time = 35; } } else if (season == "Autumn") { if (lineChosen == "208") { time = 45; } else if (lineChosen == "15") { time = 42; } else if (lineChosen == "240") { time = 37; } else if (lineChosen == "Subway") { time = 35; } } else if (season == "Spring") { if (lineChosen == "208") { time = 39; } else if (lineChosen == "15") { time = 36; } else if (lineChosen == "240") { time = 31; } else if (lineChosen == "Subway") { time = 35; } } else if (season == "Summer") { Console.WriteLine("No lectures! It's summer!"); return; } if (lineChosen == "15" || lineChosen == "Subway") { time = time + 21; } else { time = time + 18; } Console.WriteLine($"Total travel time: {time} minutes"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Foundation; using SQLite; using UIKit; using Welic.App.Services.ServicesViewModels; [assembly: Xamarin.Forms.Dependency(typeof(Welic.App.iOS.Services.SQLite))] namespace Welic.App.iOS.Services { public class SQLite : ISQLite { public SQLite() { } public SQLiteConnection GetConnection() { var sqliteFilename = "localData.db"; string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string libFolder = Path.Combine(docFolder, "..", "Library", "Databases"); if (!Directory.Exists(libFolder)) { Directory.CreateDirectory(libFolder); } string path = Path.Combine(libFolder, sqliteFilename); // This is where we copy in the pre-created database // if (!File.Exists(path)) // { // var existingDb = NSBundle.MainBundle.PathForResource("Employee", "db"); // File.Copy(existingDb, path); // } //var platform = new SQLitePlatformIOS(); //var param = new SQLiteConnectionString(path, false); var connection = new SQLiteConnection(path); return connection; } } }
using System; using System.Collections.Generic; using System.Text; namespace Pythonware.Resolvers { public interface IScriptNameResolver { string ResolveScriptName(); } }
using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Windows.Markup; using System.Windows.Media; namespace Crystal.Plot2D.Common { [ContentProperty("Steps")] public class DiscretePalette : IPalette { [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public ObservableCollection<LinearPaletteColorStep> Steps { get; } = new ObservableCollection<LinearPaletteColorStep>(); public DiscretePalette() { } public DiscretePalette(params LinearPaletteColorStep[] steps) => Steps.AddMany(steps); public Color GetColor(double t) { if (t <= 0) { return Steps[0].Color; } if (t >= Steps.Last().Offset) { return Steps.Last().Color; } int i = 0; double x = 0; while (x < t && i < Steps.Count) { x = Steps[i].Offset; i++; } Color result = Steps[i - 1].Color; return result; } #region IPalette Members #pragma warning disable CS0067 // The event 'DiscretePalette.Changed' is never used public event EventHandler Changed; #pragma warning restore CS0067 // The event 'DiscretePalette.Changed' is never used #endregion } }
/// <summary> /// 2015 /// Ben Redahan, redahanb@gmail.com /// Project: Spectral - The Silicon Domain (Unity) /// Guard AI: decision making / state machine /// </summary> using UnityEngine; using System.Collections; public class GuardAI : MonoBehaviour { // public variables public bool patrolling; public bool alerted; public bool aggro; public bool curious; public Vector3 lastSighting; // cache references private GuardSensing sensing; private GuardBehaviour behaviour; private HealthManager pHealth; public AlertManager alertSystem; void Start () { sensing = GetComponent<GuardSensing> (); behaviour = GetComponent<GuardBehaviour> (); alerted = false; alertSystem = GameObject.Find ("Alert System").GetComponent<AlertManager>(); pHealth = GameObject.Find ("Health Manager").GetComponent<HealthManager> (); // Set default state: patrol or sentry (stationary) if (patrolling) { behaviour.guardState = GuardBehaviour.GuardState.Patrol; } else { behaviour.guardState = GuardBehaviour.GuardState.Sentry; } } // end Start void Update () { // if the guard sees the player, trigger the alert and aggro the guard if(sensing.playerDetected) { alerted = true; aggro = true; alertSystem.TriggerAlert(); sensing.playerDetected = false; curious = false; sensing.playerHeard = false; } // if the guard is not alerted and hears the player, set curious state if (sensing.playerHeard && !alerted) { curious = true; sensing.playerHeard = false; } // if the alert system is active, go into alert patrol if (alertSystem.alertActive) { alerted = true; curious = false; } else { alerted = false; sensing.playerDetected = false; aggro = false; } /// State machine if (alerted) { if (sensing.playerInSight) { behaviour.guardState = GuardBehaviour.GuardState.Attack; } else { if (aggro) { behaviour.guardState = GuardBehaviour.GuardState.Search; } else { behaviour.guardState = GuardBehaviour.GuardState.AlertPatrol; } } } else { if(patrolling) { behaviour.guardState = GuardBehaviour.GuardState.Patrol; } else { behaviour.guardState = GuardBehaviour.GuardState.Sentry; } } // if there is not alert but the guard hears a noise, investigate the location of the noise if(curious && !alerted && !aggro){ behaviour.guardState = GuardBehaviour.GuardState.Investigate; } // switch to idle state if the player is killed if(pHealth.playerDead){ behaviour.guardState = GuardBehaviour.GuardState.Idle; } } // end Update }
using System; using System.Collections.Generic; using System.Text; namespace FiiiChain.Framework { public class GlobalFunctions { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TrackScript : MonoBehaviour { [SerializeField] private GameObject Car; private TrackGenerator _trackGenerator; private float _trackLenght; void Start() { _trackGenerator = gameObject.GetComponentInParent<TrackGenerator>(); _trackLenght = _trackGenerator.TrackLenght; } void FixedUpdate() { if (Car.transform.position.x - transform.position.x > 1.5f * _trackLenght || transform.position.x - Car.transform.position.x > 0.5f * _trackLenght) { gameObject.SetActive(false); } } }
using System; using FillWords.Logic; namespace FillWords.Consos { static class Program { public static Screen ActiveScreen { get; private set; } static void Main(string[] args) { Console.CursorVisible = false; Console.WindowHeight = Console.LargestWindowHeight; Console.WindowWidth = Console.LargestWindowWidth; } } }
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json; using System.Threading.Tasks; using Kulula.com.Helpers; using Kulula.com.Models; namespace Kulula.com.Services { class CreditCardService { private string rootUrl = "http://192.168.1.203:45455/"; // POST CreditCard public async Task AddCreditCards(CreditCard creditCard) { var httpClient = new HttpClient(); var json = JsonConvert.SerializeObject(creditCard); Debug.WriteLine(json); StringContent stringContent = new StringContent(json); stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = await httpClient.PostAsync(rootUrl + "api/CreditCards", stringContent); } // PUT InternetPaymentSID public async Task UpdateCreditCardsD(int id, CreditCard creditCard) { var httpClient = new HttpClient(); var json = JsonConvert.SerializeObject(creditCard); StringContent stringContent = new StringContent(json); stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = await httpClient.PutAsync(rootUrl + "api/CreditCards/" + id, stringContent); } // GET InternetPaymentSID public async Task<List<CreditCard>> GetCreditCardsByID(int id) { var httpClient = new HttpClient(); var json = await httpClient.GetStringAsync(rootUrl + "api/CreditCards/" + id); var creditCards = JsonConvert.DeserializeObject<List<CreditCard>>(json); return creditCards; } //Get By Payment ID public async Task<List<CreditCard>> GetCreditCards() { var httpClient = new HttpClient(); var json = await httpClient.GetStringAsync(rootUrl + "api/CreditCard?id=" + Settings.PaymentID); var creditCards = JsonConvert.DeserializeObject<List<CreditCard>>(json); return creditCards; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Maximum_and_Minimum_Element { class Program { static void Main(string[] args) { var numberOfOperations = int.Parse(Console.ReadLine()); var stack = new Stack<int>(); for (int n = 0; n < numberOfOperations; n++) { var input = Console.ReadLine().Split().Select(int.Parse).ToArray(); var command = input[0]; if (command == 1) { stack.Push(input[1]); } else if (command == 2) { if (stack.Count > 0) { stack.Pop(); } } else if (command == 3) { if (stack.Count > 0) { Console.WriteLine(MaxElement(stack)); } } else { if (stack.Count > 0) { Console.WriteLine(MinElement(stack)); } } } Console.WriteLine(String.Join(", ",stack)); } static int MaxElement(Stack<int> collection) { var stackCopy = new Stack<int>(collection); var max = int.MinValue; while (stackCopy.Count > 0) { max = Math.Max(max, stackCopy.Pop()); } return max; } static int MinElement(Stack<int> collection) { var stackCopy = new Stack<int>(collection); var min = int.MaxValue; while (stackCopy.Count > 0) { min = Math.Min(min, stackCopy.Pop()); } return min; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Salle.View { internal class MaterielView : AbstractView { public MaterielView() { } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using SGCFT.Dominio.Contratos.Repositorios; using SGCFT.Dominio.Contratos.Servicos; using SGCFT.Dominio.Entidades; using SGCFT.Dominio.Servicos; using SGCFT.Utilitario; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SGCFT.Dominio.Teste { [TestClass] public class UsuarioServicoTeste { [TestMethod] public void CriarNovoUsuarioComEmailJaExistente() { string nome = "Vanessa"; string senha = "valuneca"; string email = "teste@teste.com"; long cpf = 12904202625; Usuario usuario = new Usuario(nome, senha, email, cpf, true); IUsuarioRepositorio usuarioRepositorio = new UsuarioRepositorioMock(true,false); IUsuarioServico usuarioServico = new UsuarioServico(usuarioRepositorio); Retorno retorno = usuarioServico.InserirUsuario(usuario); Assert.AreEqual(false, retorno.Sucesso); Assert.AreEqual("Email já cadastrado", retorno.Mensagens.First()); } [TestMethod] public void CriarNovoUsuarioComCpfJaExistente() { string nome = "Vanessa"; string senha = "valuneca"; string email = "teste@teste.com"; long cpf = 12904202625; Usuario usuario = new Usuario(nome, senha, email, cpf, true); IUsuarioRepositorio usuarioRepositorio = new UsuarioRepositorioMock(false, true); IUsuarioServico usuarioServico = new UsuarioServico(usuarioRepositorio); Retorno retorno = usuarioServico.InserirUsuario(usuario); Assert.AreEqual(false, retorno.Sucesso); Assert.AreEqual("Cpf já cadastrado", retorno.Mensagens.First()); } [TestMethod] public void CriarNovoUsuarioValido() { string nome = "Vanessa"; string senha = "valuneca"; string email = "teste@teste.com"; long cpf = 12904202625; Usuario usuario = new Usuario(nome, senha, email, cpf, true); IUsuarioRepositorio usuarioRepositorio = new UsuarioRepositorioMock(false, false); IUsuarioServico usuarioServico = new UsuarioServico(usuarioRepositorio); Retorno retorno = usuarioServico.InserirUsuario(usuario); Assert.AreEqual(true, retorno.Sucesso); Assert.AreEqual(false, retorno.Mensagens.Any()); } } public class UsuarioRepositorioMock : IUsuarioRepositorio { private bool resultadoEsperadoEmailCadastrado; private bool resultadoEsperadoDocumentoCadastrado; public UsuarioRepositorioMock(bool resultadoEsperadoEmailCadastrado, bool resultadoEsperadoDocumentoCadastrado) { this.resultadoEsperadoEmailCadastrado = resultadoEsperadoEmailCadastrado; this.resultadoEsperadoDocumentoCadastrado = resultadoEsperadoDocumentoCadastrado; } public void Inserir(Usuario usuario) { //FALTA FAZER********* } public void Alterar(Usuario usuario) { //FALTA FAZER********* } public bool ValidarDocumentoCadastrado(long documento, bool isCpf) { return this.resultadoEsperadoDocumentoCadastrado; } public bool ValidarEmailCadastrado(string email) { return this.resultadoEsperadoEmailCadastrado; } public int ObterIdUsuarioPorEmail(string email) { throw new NotImplementedException(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class SignUp : MonoBehaviour { public InputField usernameField; public InputField emailField; public InputField passwordField; public InputField categoryField; public Button submitButton; public GameObject Panel; public GameObject AddPanel; public void CallRegister() { StartCoroutine(Register()); } IEnumerator Register() { WWWForm form = new WWWForm(); form.AddField("username", usernameField.text); form.AddField("email", emailField.text); form.AddField("password", passwordField.text); WWW www = new WWW("https://organizacijaradaknjiznice.000webhostapp.com/SignUp.php", form); yield return www; if (www.text == "0") { Debug.Log("User created seccessfully"); Panel.gameObject.SetActive(true); } else { Debug.Log("User creation faild"); } } public void CallAddUser() { StartCoroutine(AddUser()); } IEnumerator AddUser() { WWWForm form = new WWWForm(); form.AddField("username", usernameField.text); form.AddField("email", emailField.text); form.AddField("password", passwordField.text); form.AddField("category", categoryField.text); WWW www = new WWW ("https://organizacijaradaknjiznice.000webhostapp.com/AddNewUser.php", form); yield return www ; if (www.text == "0") { Debug.Log("User created seccessfully"); AddPanel.gameObject.SetActive(true); } else { Debug.Log("User creation faild"); } } public void VerifyInput() { submitButton.interactable = (usernameField.text.Length >= 4 && passwordField.text.Length >= 7 && emailField.text.Length > 0); } }
using MVP.Base.BasePresenter; using MVP.Sample.Web.IRepositories; using MVP.Sample.Web.IViews; using MVP.Sample.Web.Repositories; namespace MVP.Sample.Web.Presenters { public class DependencyUC2Presenter : BasePresenter<IDependencyUC2View, IDependencyUC2Repository> { #region Constructors public DependencyUC2Presenter(IDependencyUC2View view) : base(view) { Repository = new DependencyUC2Repository(); } public DependencyUC2Presenter(IDependencyUC2View view, IDependencyUC2Repository repository): base(view, repository) { } #endregion #region Overrides of BasePresenter<IDependencyUC2View,object> protected override void ViewAction() { } protected override void UpdateAction() { } protected override void DeleteAction() { } protected override void InsertAction() { //throw new NotImplementedException(); } protected override void InitializeAction() { } protected override void SearchAction() { } public override void Validate() { } #endregion } }
using EntMob_Uni.Services; using EntMob_Uni.ViewModel; using Jogging.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EntMob_Uni { public class ViewModelLocator { private static IUserService userService = new UserService(new UserRepository()); private static ISessionService sessionService = new SessionService(new SessionRepository()); private static LoginViewModel loginViewModel; private static DetailViewModel detailViewModel; private static ValuesViewModel valuesViewModel; //private static IDialogService dialogService = new DialogService(parkingLotSelectionViewModel.SelectedParking, routeDetailViewModel.selectedRoute); //private static IParkingLotDataService parkingLotDataService = new ParkingLotDataService(new ParkingsRepository()); public static LoginViewModel LoginViewModel { get { return loginViewModel ?? (loginViewModel = new LoginViewModel(userService)); } } public static DetailViewModel DetailViewModel { get { return detailViewModel ?? (detailViewModel = new DetailViewModel(sessionService)); } } public static ValuesViewModel ValuesViewModel { get { return valuesViewModel ?? (valuesViewModel = new ValuesViewModel(sessionService)); } } } }
using System; using StackExchange.Redis; using System.Threading.Tasks; using System.IO; namespace Microsoft.UnifiedRedisPlatform.Core.Database { public partial class UnifiedRedisDatabase { public long StreamAcknowledge(RedisKey key, RedisValue groupName, RedisValue messageId, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamAcknowledge(CreateAppKey(key), groupName, messageId, flags)); public long StreamAcknowledge(RedisKey key, RedisValue groupName, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamAcknowledge(CreateAppKey(key), groupName, messageIds, flags)); public Task<long> StreamAcknowledgeAsync(RedisKey key, RedisValue groupName, RedisValue messageId, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamAcknowledgeAsync(CreateAppKey(key), groupName, messageId, flags)); public Task<long> StreamAcknowledgeAsync(RedisKey key, RedisValue groupName, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamAcknowledgeAsync(CreateAppKey(key), groupName, messageIds, flags)); public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId = null, int? maxLength = null, bool useApproximateMaxLength = false, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamAdd(CreateAppKey(key), streamField, streamValue, messageId, maxLength, useApproximateMaxLength, flags)); public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId = null, int? maxLength = null, bool useApproximateMaxLength = false, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamAdd(CreateAppKey(key), streamPairs, messageId, maxLength, useApproximateMaxLength, flags)); public Task<RedisValue> StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId = null, int? maxLength = null, bool useApproximateMaxLength = false, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamAddAsync(CreateAppKey(key), streamField, streamValue, messageId, maxLength, useApproximateMaxLength, flags)); public Task<RedisValue> StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId = null, int? maxLength = null, bool useApproximateMaxLength = false, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamAddAsync(CreateAppKey(key), streamPairs, messageId, maxLength, useApproximateMaxLength, flags)); public StreamEntry[] StreamClaim(RedisKey key, RedisValue consumerGroup, RedisValue claimingConsumer, long minIdleTimeInMs, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamClaim(CreateAppKey(key), consumerGroup, claimingConsumer, minIdleTimeInMs, messageIds, flags)); public Task<StreamEntry[]> StreamClaimAsync(RedisKey key, RedisValue consumerGroup, RedisValue claimingConsumer, long minIdleTimeInMs, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamClaimAsync(CreateAppKey(key), consumerGroup, claimingConsumer, minIdleTimeInMs, messageIds, flags)); public RedisValue[] StreamClaimIdsOnly(RedisKey key, RedisValue consumerGroup, RedisValue claimingConsumer, long minIdleTimeInMs, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamClaimIdsOnly(CreateAppKey(key), consumerGroup, claimingConsumer, minIdleTimeInMs, messageIds, flags)); public Task<RedisValue[]> StreamClaimIdsOnlyAsync(RedisKey key, RedisValue consumerGroup, RedisValue claimingConsumer, long minIdleTimeInMs, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamClaimIdsOnlyAsync(CreateAppKey(key), consumerGroup, claimingConsumer, minIdleTimeInMs, messageIds, flags)); public bool StreamConsumerGroupSetPosition(RedisKey key, RedisValue groupName, RedisValue position, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamConsumerGroupSetPosition(CreateAppKey(key), groupName, position, flags)); public Task<bool> StreamConsumerGroupSetPositionAsync(RedisKey key, RedisValue groupName, RedisValue position, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamConsumerGroupSetPositionAsync(CreateAppKey(key), groupName, position, flags)); public StreamConsumerInfo[] StreamConsumerInfo(RedisKey key, RedisValue groupName, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamConsumerInfo(CreateAppKey(key), groupName, flags)); public Task<StreamConsumerInfo[]> StreamConsumerInfoAsync(RedisKey key, RedisValue groupName, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamConsumerInfoAsync(CreateAppKey(key), groupName, flags)); public bool StreamCreateConsumerGroup(RedisKey key, RedisValue groupName, RedisValue? position = null, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamCreateConsumerGroup(CreateAppKey(key), groupName, position, flags)); public Task<bool> StreamCreateConsumerGroupAsync(RedisKey key, RedisValue groupName, RedisValue? position = null, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamCreateConsumerGroupAsync(CreateAppKey(key), groupName, position, flags)); public long StreamDelete(RedisKey key, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamDelete(CreateAppKey(key), messageIds, flags)); public Task<long> StreamDeleteAsync(RedisKey key, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamDeleteAsync(CreateAppKey(key), messageIds, flags)); public long StreamDeleteConsumer(RedisKey key, RedisValue groupName, RedisValue consumerName, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamDeleteConsumer(CreateAppKey(key), groupName, consumerName, flags)); public Task<long> StreamDeleteConsumerAsync(RedisKey key, RedisValue groupName, RedisValue consumerName, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamDeleteConsumerAsync(CreateAppKey(key), groupName, consumerName, flags)); public bool StreamDeleteConsumerGroup(RedisKey key, RedisValue groupName, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamDeleteConsumerGroup(CreateAppKey(key), groupName, flags)); public Task<bool> StreamDeleteConsumerGroupAsync(RedisKey key, RedisValue groupName, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamDeleteConsumerGroupAsync(CreateAppKey(key), groupName, flags)); public StreamGroupInfo[] StreamGroupInfo(RedisKey key, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamGroupInfo(CreateAppKey(key), flags)); public Task<StreamGroupInfo[]> StreamGroupInfoAsync(RedisKey key, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamGroupInfoAsync(CreateAppKey(key), flags)); public StreamInfo StreamInfo(RedisKey key, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamInfo(CreateAppKey(key), flags)); public Task<StreamInfo> StreamInfoAsync(RedisKey key, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamInfoAsync(CreateAppKey(key), flags)); public long StreamLength(RedisKey key, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamLength(CreateAppKey(key), flags)); public Task<long> StreamLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamLengthAsync(CreateAppKey(key), flags)); public StreamPendingInfo StreamPending(RedisKey key, RedisValue groupName, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamPending(CreateAppKey(key), groupName, flags)); public Task<StreamPendingInfo> StreamPendingAsync(RedisKey key, RedisValue groupName, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamPendingAsync(CreateAppKey(key), groupName, flags)); public StreamPendingMessageInfo[] StreamPendingMessages(RedisKey key, RedisValue groupName, int count, RedisValue consumerName, RedisValue? minId = null, RedisValue? maxId = null, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamPendingMessages(CreateAppKey(key), groupName, count, consumerName, minId, maxId, flags)); public Task<StreamPendingMessageInfo[]> StreamPendingMessagesAsync(RedisKey key, RedisValue groupName, int count, RedisValue consumerName, RedisValue? minId = null, RedisValue? maxId = null, CommandFlags flags = CommandFlags.None)=> ExecuteAsync(() => _baseDatabase.StreamPendingMessagesAsync(CreateAppKey(key), groupName, count, consumerName, minId, maxId, flags)); public StreamEntry[] StreamRange(RedisKey key, RedisValue? minId = null, RedisValue? maxId = null, int? count = null, Order messageOrder = Order.Ascending, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamRange(CreateAppKey(key), minId, maxId, count, messageOrder, flags)); public Task<StreamEntry[]> StreamRangeAsync(RedisKey key, RedisValue? minId = null, RedisValue? maxId = null, int? count = null, Order messageOrder = Order.Ascending, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamRangeAsync(CreateAppKey(key), minId, maxId, count, messageOrder, flags)); public StreamEntry[] StreamRead(RedisKey key, RedisValue position, int? count = null, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamRead(CreateAppKey(key), position, count, flags)); public RedisStream[] StreamRead(StreamPosition[] streamPositions, int? countPerStream = null, CommandFlags flags = CommandFlags.None) => throw new NotImplementedException(); public Task<StreamEntry[]> StreamReadAsync(RedisKey key, RedisValue position, int? count = null, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamReadAsync(CreateAppKey(key), position, count, flags)); public Task<RedisStream[]> StreamReadAsync(StreamPosition[] streamPositions, int? countPerStream = null, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamReadAsync(streamPositions, countPerStream, flags)); public StreamEntry[] StreamReadGroup(RedisKey key, RedisValue groupName, RedisValue consumerName, RedisValue? position = null, int? count = null, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamReadGroup(CreateAppKey(key), groupName, consumerName, position, count, flags)); public RedisStream[] StreamReadGroup(StreamPosition[] streamPositions, RedisValue groupName, RedisValue consumerName, int? countPerStream = null, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamReadGroup(streamPositions, groupName, consumerName, countPerStream, flags)); public Task<StreamEntry[]> StreamReadGroupAsync(RedisKey key, RedisValue groupName, RedisValue consumerName, RedisValue? position = null, int? count = null, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamReadGroupAsync(CreateAppKey(key), groupName, consumerName, position, count, flags)); public Task<RedisStream[]> StreamReadGroupAsync(StreamPosition[] streamPositions, RedisValue groupName, RedisValue consumerName, int? countPerStream = null, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamReadGroupAsync(streamPositions, groupName, consumerName, countPerStream, flags)); public long StreamTrim(RedisKey key, int maxLength, bool useApproximateMaxLength = false, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.StreamTrim(CreateAppKey(key), maxLength, useApproximateMaxLength, flags)); public Task<long> StreamTrimAsync(RedisKey key, int maxLength, bool useApproximateMaxLength = false, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.StreamTrimAsync(CreateAppKey(key), maxLength, useApproximateMaxLength, flags)); } }
using System; using System.Collections.Generic; using System.Text; namespace ORM.Models { public class Supplier { public int Id { get; set; } public string SupplierName { get; set; } public string ContactPerson { get; set; } public string Email { get; set; } public string Phone { get; set; } public Supplier () { } public Supplier(string supplierName, string phone, string contactPerson = "ingen", string email = "ingen") { SupplierName = supplierName; Phone = phone; ContactPerson = contactPerson; Email = email; } public Supplier(int id, string supplierName, string phone, string contactPerson = "ingen", string email = "ingen") { Id = id; SupplierName = supplierName; Phone = phone; ContactPerson = contactPerson; Email = email; } } }
using System; using System.Windows.Forms; using Project.Forms.Layouts; using Project.Models; using Project.Services; using Project.Helpers; using Project.Errors; namespace Project.Forms { public class UserChangePassword : BaseLayout { // Frontend private Panel panel; private Label currentPasswordLabel; private TextBox currentPasswordInput; private Label newPasswordLabel; private TextBox newPasswordInput; private Button saveButton; private Button cancelButton; private Label title; // Backend private User user; public UserChangePassword() { InitializeComponent(); } public override string GetHandle() { return "userChangePassword"; } public override void OnShow() { UserService userService = Program.GetInstance().GetService<UserService>("users"); User currentUser = userService.GetCurrentUser(); base.OnShow(); currentPasswordInput.Text = ""; newPasswordInput.Text = ""; if (user.id != currentUser.id && !currentUser.admin) { throw new PermissionException("Je kunt alleen je eigen account bewerken"); } } private void InitializeComponent() { this.panel = new System.Windows.Forms.Panel(); this.title = new System.Windows.Forms.Label(); this.cancelButton = new System.Windows.Forms.Button(); this.saveButton = new System.Windows.Forms.Button(); this.newPasswordLabel = new System.Windows.Forms.Label(); this.newPasswordInput = new System.Windows.Forms.TextBox(); this.currentPasswordLabel = new System.Windows.Forms.Label(); this.currentPasswordInput = new System.Windows.Forms.TextBox(); this.panel.SuspendLayout(); this.SuspendLayout(); // // panel // this.panel.Controls.Add(this.title); this.panel.Controls.Add(this.cancelButton); this.panel.Controls.Add(this.saveButton); this.panel.Controls.Add(this.newPasswordLabel); this.panel.Controls.Add(this.newPasswordInput); this.panel.Controls.Add(this.currentPasswordLabel); this.panel.Controls.Add(this.currentPasswordInput); this.panel.Location = new System.Drawing.Point(42, 106); this.panel.Name = "panel"; this.panel.Size = new System.Drawing.Size(715, 443); this.panel.TabIndex = 2; // // title // this.title.AutoEllipsis = true; this.title.AutoSize = true; this.title.BackColor = System.Drawing.SystemColors.Control; this.title.Font = new System.Drawing.Font("Microsoft Sans Serif", 30F); this.title.Location = new System.Drawing.Point(-8, 0); this.title.Name = "title"; this.title.Size = new System.Drawing.Size(445, 46); this.title.TabIndex = 8; this.title.Text = "wachtwoord veranderen"; // // cancelButton // this.cancelButton.Location = new System.Drawing.Point(218, 186); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(140, 23); this.cancelButton.TabIndex = 7; this.cancelButton.Text = "Annuleren"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.CancelButton_Click); // // saveButton // this.saveButton.Location = new System.Drawing.Point(44, 186); this.saveButton.Name = "saveButton"; this.saveButton.Size = new System.Drawing.Size(140, 23); this.saveButton.TabIndex = 6; this.saveButton.Text = "Opslaan"; this.saveButton.UseVisualStyleBackColor = true; this.saveButton.Click += new System.EventHandler(this.SaveButton_Click); // // newPasswordLabel // this.newPasswordLabel.AutoSize = true; this.newPasswordLabel.Location = new System.Drawing.Point(-3, 142); this.newPasswordLabel.Name = "newPasswordLabel"; this.newPasswordLabel.Size = new System.Drawing.Size(98, 13); this.newPasswordLabel.TabIndex = 5; this.newPasswordLabel.Text = "Nieuw wachtwoord"; // // newPasswordInput // this.newPasswordInput.Location = new System.Drawing.Point(118, 139); this.newPasswordInput.Name = "newPasswordInput"; this.newPasswordInput.PasswordChar = '*'; this.newPasswordInput.Size = new System.Drawing.Size(272, 20); this.newPasswordInput.TabIndex = 4; // // currentPasswordLabel // this.currentPasswordLabel.AutoSize = true; this.currentPasswordLabel.Location = new System.Drawing.Point(-3, 99); this.currentPasswordLabel.Name = "currentPasswordLabel"; this.currentPasswordLabel.Size = new System.Drawing.Size(98, 13); this.currentPasswordLabel.TabIndex = 1; this.currentPasswordLabel.Text = "Huidig wachtwoord"; // // currentPasswordInput // this.currentPasswordInput.Location = new System.Drawing.Point(118, 96); this.currentPasswordInput.Name = "currentPasswordInput"; this.currentPasswordInput.PasswordChar = '*'; this.currentPasswordInput.Size = new System.Drawing.Size(272, 20); this.currentPasswordInput.TabIndex = 0; // // UserChangePassword // this.ClientSize = new System.Drawing.Size(1217, 599); this.Controls.Add(this.panel); this.Name = "UserChangePassword"; this.Controls.SetChildIndex(this.panel, 0); this.panel.ResumeLayout(false); this.panel.PerformLayout(); this.ResumeLayout(false); } public void SetUser(User user) { this.user = user; } private void SaveButton_Click(object sender, EventArgs e) { Program app = Program.GetInstance(); UserService userService = app.GetService<UserService>("users"); User currentUser = userService.GetCurrentUser(); // Get values string currentPassword = currentPasswordInput.Text; string newPassword = newPasswordInput.Text; if (!currentUser.Authenticate(currentPassword)) { GuiHelper.ShowError("Huidig wachtwoord is ongeldig"); return; } // Update and save user user.SetPassword(newPassword); if (userService.SaveUser(user)) { UserEdit userEdit = app.GetScreen<UserEdit>("userEdit"); userEdit.SetUser(user); app.ShowScreen(userEdit); GuiHelper.ShowInfo("Wachtwoord succesvol aangepast"); } else { GuiHelper.ShowError("Kon het wachtwoord niet aanpassen"); } } private void CancelButton_Click(object sender, EventArgs e) { Program app = Program.GetInstance(); UserEdit userEdit = app.GetScreen<UserEdit>("userEdit"); userEdit.SetUser(user); app.ShowScreen(userEdit); } } }
using System; using CoherentSolutions.Extensions.Configuration.AnyWhere.Abstractions; using Microsoft.Extensions.Configuration; namespace CoherentSolutions.Extensions.Configuration.AnyWhere.KeyPerFile { public class AnyWhereKeyPerFileConfigurationSourceAdapter : IAnyWhereConfigurationAdapter { public void ConfigureAppConfiguration( IConfigurationBuilder configurationBuilder, IAnyWhereConfigurationEnvironmentReader environmentReader) { if (configurationBuilder == null) { throw new ArgumentNullException(nameof(configurationBuilder)); } if (environmentReader == null) { throw new ArgumentNullException(nameof(environmentReader)); } configurationBuilder.AddKeyPerFile( environmentReader.GetString("DIRECTORY_PATH"), environmentReader.GetBool("OPTIONAL", optional: true)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem294 : ProblemBase { public override string ProblemName { get { return "294: Sum of digits - experience #23"; } } public override string GetAnswer() { FindTwentyThreeFact(); FindDigitSums(1, 0, new int[9]); return ""; } private Dictionary<int, BigInteger> _factorial = new Dictionary<int, BigInteger>(); private void FindTwentyThreeFact() { BigInteger num = 1; for (BigInteger next = 1; next <= 23; next++) { num *= next; _factorial.Add((int)next, num); } } private void FindDigitSums(int currentNum, int sum, int[] digits) { int max = (23 - sum) / currentNum; var tempSum = sum; for (int num = 1; num <= max; num++) { sum += currentNum; digits[currentNum - 1]++; if (sum == 23) { FoundCombo(digits); } else if (currentNum < 9) { FindDigitSums(currentNum + 1, sum, digits); } } digits[currentNum - 1] = 0; if (currentNum < 9) { FindDigitSums(currentNum + 1, tempSum, digits); } digits[currentNum - 1] = 0; } private void FoundCombo(int[] digits) { } private ulong BruteForceS(ulong n) { ulong count = 0; ulong max = (ulong)Math.Pow(10, n); for (ulong k = 23; k <= max; k += 23) { if (BruteForceD(k) == 23) { count++; } } return count; } private ulong BruteForceD(ulong n) { ulong sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } } }
 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IDALRepository { public partial interface IDBSession { IFW_AUDIT_RECORD_REPOSITORY IFW_AUDIT_RECORD_REPOSITORY {get;set;} IFW_GEO_NODE_REPOSITORY IFW_GEO_NODE_REPOSITORY {get;set;} IFW_GEO_NODE_CUST_REPOSITORY IFW_GEO_NODE_CUST_REPOSITORY {get;set;} IFW_GEO_TREE_REPOSITORY IFW_GEO_TREE_REPOSITORY {get;set;} IFW_GEO_TREE_LEVEL_REPOSITORY IFW_GEO_TREE_LEVEL_REPOSITORY {get;set;} IFW_MODULE_REPOSITORY IFW_MODULE_REPOSITORY {get;set;} IFW_MODULEPERMISSION_REPOSITORY IFW_MODULEPERMISSION_REPOSITORY {get;set;} IFW_OPERATELOG_REPOSITORY IFW_OPERATELOG_REPOSITORY {get;set;} IFW_PERMISSION_REPOSITORY IFW_PERMISSION_REPOSITORY {get;set;} IFW_ROLE_REPOSITORY IFW_ROLE_REPOSITORY {get;set;} IFW_ROLEPERMISSION_REPOSITORY IFW_ROLEPERMISSION_REPOSITORY {get;set;} IFW_USER_REPOSITORY IFW_USER_REPOSITORY {get;set;} IFW_USER_ASSIGN_REPOSITORY IFW_USER_ASSIGN_REPOSITORY {get;set;} IFW_USER_ROLE_REPOSITORY IFW_USER_ROLE_REPOSITORY {get;set;} IJF_Order_REPOSITORY IJF_Order_REPOSITORY {get;set;} IJF_Product_REPOSITORY IJF_Product_REPOSITORY {get;set;} IMST_ARTICLE_REPOSITORY IMST_ARTICLE_REPOSITORY {get;set;} IMST_ATTACHMENTS_REPOSITORY IMST_ATTACHMENTS_REPOSITORY {get;set;} IMST_CAR_REPOSITORY IMST_CAR_REPOSITORY {get;set;} IMST_CATALOG_REPOSITORY IMST_CATALOG_REPOSITORY {get;set;} IMST_CATEGORY_REPOSITORY IMST_CATEGORY_REPOSITORY {get;set;} IMST_COMPANY_REPOSITORY IMST_COMPANY_REPOSITORY {get;set;} IMST_COMPANY_MEM_REPOSITORY IMST_COMPANY_MEM_REPOSITORY {get;set;} IMST_MEMBER_REPOSITORY IMST_MEMBER_REPOSITORY {get;set;} IMST_MUSTSELL_REPOSITORY IMST_MUSTSELL_REPOSITORY {get;set;} IMST_MUSTSELL_DTL_REPOSITORY IMST_MUSTSELL_DTL_REPOSITORY {get;set;} IMST_MUSTSELL_PRD_REPOSITORY IMST_MUSTSELL_PRD_REPOSITORY {get;set;} IMST_POSITION_REPOSITORY IMST_POSITION_REPOSITORY {get;set;} IMST_PRD_REPOSITORY IMST_PRD_REPOSITORY {get;set;} IMST_PRD_CATE_REPOSITORY IMST_PRD_CATE_REPOSITORY {get;set;} IMST_PRD_IMG_REPOSITORY IMST_PRD_IMG_REPOSITORY {get;set;} IMST_RESUME_REPOSITORY IMST_RESUME_REPOSITORY {get;set;} IMST_RESUME_DTL_REPOSITORY IMST_RESUME_DTL_REPOSITORY {get;set;} IMST_SUPPLIER_REPOSITORY IMST_SUPPLIER_REPOSITORY {get;set;} ISET_COUNTRY_REPOSITORY ISET_COUNTRY_REPOSITORY {get;set;} ISET_NAVIGATION_ITEM_REPOSITORY ISET_NAVIGATION_ITEM_REPOSITORY {get;set;} ISET_REGION_REPOSITORY ISET_REGION_REPOSITORY {get;set;} ISYS_REF_REPOSITORY ISYS_REF_REPOSITORY {get;set;} ISYS_USERLOGIN_REPOSITORY ISYS_USERLOGIN_REPOSITORY {get;set;} ITG_Address_REPOSITORY ITG_Address_REPOSITORY {get;set;} ITG_BankCrad_REPOSITORY ITG_BankCrad_REPOSITORY {get;set;} ITG_Car_REPOSITORY ITG_Car_REPOSITORY {get;set;} ITG_fenxiaoConfig_REPOSITORY ITG_fenxiaoConfig_REPOSITORY {get;set;} ITG_jifenLog_REPOSITORY ITG_jifenLog_REPOSITORY {get;set;} ITG_order_REPOSITORY ITG_order_REPOSITORY {get;set;} ITG_pic_REPOSITORY ITG_pic_REPOSITORY {get;set;} ITG_product_REPOSITORY ITG_product_REPOSITORY {get;set;} ITG_productBrand_REPOSITORY ITG_productBrand_REPOSITORY {get;set;} ITG_productCate_REPOSITORY ITG_productCate_REPOSITORY {get;set;} ITG_productColor_REPOSITORY ITG_productColor_REPOSITORY {get;set;} ITG_QD_REPOSITORY ITG_QD_REPOSITORY {get;set;} ITG_redPaperLog_REPOSITORY ITG_redPaperLog_REPOSITORY {get;set;} ITG_review_REPOSITORY ITG_review_REPOSITORY {get;set;} ITG_SCproduct_REPOSITORY ITG_SCproduct_REPOSITORY {get;set;} ITG_Thing_REPOSITORY ITG_Thing_REPOSITORY {get;set;} ITG_transactionLog_REPOSITORY ITG_transactionLog_REPOSITORY {get;set;} ITG_tuihuo_REPOSITORY ITG_tuihuo_REPOSITORY {get;set;} ITG_TXmoney_REPOSITORY ITG_TXmoney_REPOSITORY {get;set;} ITG_wuliu_REPOSITORY ITG_wuliu_REPOSITORY {get;set;} ITokenConfig_REPOSITORY ITokenConfig_REPOSITORY {get;set;} IYX_Event_REPOSITORY IYX_Event_REPOSITORY {get;set;} IYX_image_REPOSITORY IYX_image_REPOSITORY {get;set;} IYX_music_REPOSITORY IYX_music_REPOSITORY {get;set;} IYX_news_REPOSITORY IYX_news_REPOSITORY {get;set;} IYX_sysConfigs_REPOSITORY IYX_sysConfigs_REPOSITORY {get;set;} IYX_sysLog_REPOSITORY IYX_sysLog_REPOSITORY {get;set;} IYX_sysNews_REPOSITORY IYX_sysNews_REPOSITORY {get;set;} IYX_text_REPOSITORY IYX_text_REPOSITORY {get;set;} IYX_video_REPOSITORY IYX_video_REPOSITORY {get;set;} IYX_voice_REPOSITORY IYX_voice_REPOSITORY {get;set;} IYX_weiUser_REPOSITORY IYX_weiUser_REPOSITORY {get;set;} IYX_weiXinMenus_REPOSITORY IYX_weiXinMenus_REPOSITORY {get;set;} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BikeDistributor.Interfaces.CommonServices; using Moq; namespace BikeDistributor.Test { public class BaseTest { public Mock<ILogService> LogServiceMock { get; set; } public BaseTest() { LogServiceMock = new Mock<ILogService>(); LogServiceMock.Setup(x => x.Error(It.IsAny<Exception>(), It.IsAny<string>())); LogServiceMock.Setup(x => x.Info(It.IsAny<string>())); LogServiceMock.Setup(x => x.Warn(It.IsAny<string>())); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace OrbisEngine.ItemSystem { public static class ItemExtensions { // I feel very smart about this one :) public static T GetComponent<T>(this IItem item) where T: class { for (int i = 0; i < item.Components.Count; i++) { T component = item.Components[i] as T; if (component != null) { return component; } } return null; } } }
namespace TennisTests { using NUnit.Framework; [TestFixture] public class GameTests { } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Threading; using Microsoft.Xna.Framework.Input; namespace Labyrinth { public static class Status { public static void DrawSatus( SpriteBatch _spriteBatch, GraphicsDevice GraphicsDevice, Character character) { switch (C.gameStatus) { case GameStatus.PLAY: GraphicsDevice.Clear(Color.CornflowerBlue); DrawLabyrinth(_spriteBatch); DrawBullets(_spriteBatch); DrawKey(_spriteBatch); DrawLife(_spriteBatch); C.timeLabel.Draw(); C.levelLabel.Draw(); C.health.Draw(); C.keyLabel.Draw(); _spriteBatch.Draw(C.lifeImag, new Rectangle(30, 40, 60, 60), Color.White); _spriteBatch.Draw(C.keyImag, new Rectangle(30, 100, 60, 60), Color.White); C.backMenu2Button.Draw(); character.Draw(_spriteBatch); break; case GameStatus.MENU: GraphicsDevice.Clear(Color.AntiqueWhite); _spriteBatch.Draw(C.labImage, new Rectangle(new Point(((int)C.DISPLAYDIM.X - 1600) / 2, 0), new Point(1600, 900)), new Rectangle(new Point(0, 0), new Point(C.labImage.Width, C.labImage.Height)), Color.White); C.startButton.Draw(); C.quitButton.Draw(); C.instructionButton.Draw(); C.creditButton.Draw(); break; case GameStatus.INSTRUCTION: GraphicsDevice.Clear(Color.Green); _spriteBatch.Draw(C.instructionImage, new Rectangle(new Point(((int)C.DISPLAYDIM.X - 1500) / 2, 0), new Point(1500, 900)), new Rectangle(new Point(0, 0), new Point(C.instructionImage.Width, C.instructionImage.Height)), Color.White); C.backMenuButton.Draw(); break; case GameStatus.CREDITS: GraphicsDevice.Clear(Color.Green); _spriteBatch.Draw(C.creditsImage, new Rectangle(new Point(((int)C.DISPLAYDIM.X - 1500) / 2, 0), new Point(1500, 900)), new Rectangle(new Point(0, 0), new Point(C.creditsImage.Width, C.creditsImage.Height)), Color.White); C.backMenuButton.Draw(); break; case GameStatus.LOSE: GraphicsDevice.Clear(Color.AntiqueWhite); _spriteBatch.Draw(C.background, new Rectangle(new Point(((int)C.DISPLAYDIM.X - 1600) / 2, 0), new Point(1600, 900)), new Rectangle(new Point(0, 0), new Point(C.background.Width, C.background.Height)), Color.White); _spriteBatch.Draw(C.finalScoreImag, new Rectangle(new Point(((int)C.DISPLAYDIM.X - 1150) / 2, 10), new Point(3000, 2000)), new Rectangle(new Point(0, 0), new Point(C.background.Width, C.background.Height)), Color.White); _spriteBatch.Draw(C.gameOver, new Rectangle(new Point(((int)C.DISPLAYDIM.X - 850) / 2, 65), new Point(800, 500)), new Rectangle(new Point(0, 0), new Point(C.background.Width, C.background.Height)), Color.White); C.backMenu3Button.Draw(); C.retry.Draw(); break; case GameStatus.ENDGAME: GraphicsDevice.Clear(Color.AntiqueWhite); _spriteBatch.Draw(C.background, new Rectangle(new Point(((int)C.DISPLAYDIM.X - 1600) / 2, 0), new Point(1600, 900)), new Rectangle(new Point(0, 0), new Point(C.background.Width, C.background.Height)), Color.White); _spriteBatch.Draw(C.finalScoreImag, new Rectangle(new Point(((int)C.DISPLAYDIM.X - 1150) / 2, 10), new Point(3000, 2000)), new Rectangle(new Point(0, 0), new Point(C.background.Width, C.background.Height)), Color.White); DrawFinalString(_spriteBatch); C.backMenu3Button.Draw(); C.retry.Draw(); break; } } private static void DrawLabyrinth(SpriteBatch _spriteBatch) { Vector2 pos = C.ORGLAB; for (int i = 0; i < C.rowsNb; i++, pos.Y += C.multFactor, pos.X = C.ORGLAB.X) { for (int j = 0; j < C.colsNb; j++, pos.X += C.multFactor) { switch (C.lbrnt[i, j]) { case '1': _spriteBatch.Draw(C.wallTile, pos, Color.White); break; case '0': _spriteBatch.Draw(C.grassTile, pos, Color.White); break; case 'C': _spriteBatch.Draw(C.grassTile, pos, Color.White); break; case 'U': _spriteBatch.Draw(C.cannonU, pos, Color.White); break; case 'D': _spriteBatch.Draw(C.cannonD, pos, Color.White); break; case 'L': _spriteBatch.Draw(C.cannonL, pos, Color.White); break; case 'R': _spriteBatch.Draw(C.cannonR, pos, Color.White); break; case 'P': _spriteBatch.Draw(C.wallTile, pos, Color.White); _spriteBatch.Draw(C.padlockImag, pos, Color.White); break; } } } } private static void DrawBullets(SpriteBatch _spriteBatch) { foreach (Bullet bullut in C.listBulletR) { _spriteBatch.Draw(C.bulletImag, bullut.bulletPosA, Color.White); if (C.isExplotion) { //C.guyPos = C.startGuyPos; C.isExplotion = false; Thread.Sleep(1000); } } foreach (Bullet bullut in C.listBulletL) { _spriteBatch.Draw(C.bulletImag, bullut.bulletPosA, Color.White); if (C.isExplotion) { //C.guyPos = C.startGuyPos; C.isExplotion = false; Thread.Sleep(1000); } } foreach (Bullet bullut in C.listBulletU) { _spriteBatch.Draw(C.bulletImag, bullut.bulletPosA, Color.White); if (C.isExplotion) { //C.guyPos = C.startGuyPos; C.isExplotion = false; Thread.Sleep(1000); } } foreach (Bullet bullut in C.listBulletD) { _spriteBatch.Draw(C.bulletImag, bullut.bulletPosA, Color.White); if (C.isExplotion) { //C.guyPos = C.startGuyPos; C.isExplotion = false; Thread.Sleep(1000); } } } private static void DrawLife(SpriteBatch _spriteBatch) { foreach (Life life in C.listLife) { _spriteBatch.Draw(C.lifeImag, life.HealthPosA, Color.White); } } private static void DrawKey(SpriteBatch _spriteBatch) { foreach (Key key in C.listKeys) { _spriteBatch.Draw(C.keyImag, key.KeyPosA, Color.White); } } private static void DrawFinalString(SpriteBatch _spriteBatch) { _spriteBatch.DrawString(C.font, "CONGRATULATION", new Vector2(550, 100), Color.Black); _spriteBatch.DrawString(C.font, "You have finished all the labyrinths", new Vector2(400, 200), Color.Black); _spriteBatch.DrawString(C.font, "Your time: " + (int)C.finalTime, new Vector2(620, 300), Color.Black); _spriteBatch.DrawString(C.font, "Best time: " + C.bestTime, new Vector2(620, 400), Color.Black); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MyClassLibrary; namespace Les6Exercise1 { //Ронжин Л. //1. Изменить программу вывода таблицы функции так, чтобы можно было передавать функции типа double (double, double). //Продемонстрировать работу на функции с функцией a* x^2 и функцией a* sin(x). public delegate double Fun(double x, double a); class Program { // Создаем метод, который принимает делегат // На практике этот метод сможет принимать любой метод // с такой же сигнатурой, как у делегата public static void Table(Fun F, double a, double start, double end) { Console.WriteLine("----- X ----- Y -----"); while (start <= end) { Console.WriteLine($"| {start,8:0.000} | {F(start, a),8:0.000} |"); start += 0.5; } Console.WriteLine("---------------------"); } // Методы для передачи его в качестве параметра в Table public static double MyFuncPow(double x, double a) { return a * Math.Pow(x,2); } public static double MyFuncSin(double x, double a) { return a * Math.Sin(x); } static void Plot(List<Fun> t, double a, double start, double end) { for (int i = 0; i < t.Count; i++) { for (double x = start; x <= end; x += 0.5) { //Console.WriteLine($"y = {x*x} + {x}"); Console.WriteLine($"f({x,3},{a,3} ) = {t[i](x, a),5:0.000}"); } Console.WriteLine(); Console.WriteLine(); } } static void Main() { // Создаем новый делегат и передаем ссылку на него в метод Table Console.WriteLine("Таблица функции MyFunc:"); // Параметры метода и тип возвращаемого значения, должны совпадать с делегатом Table(new Fun(MyFuncPow), 5, -2, 2); Console.WriteLine("Еще раз та же таблица, но вызов организован по новому"); // Упрощение(c C# 2.0).Делегат создается автоматически. Table(MyFuncPow, 5, -2, 2); Console.WriteLine("Таблица функции a*Sin:"); Table(MyFuncSin, 5, -2, 2); // Можно передавать уже созданные методы Console.WriteLine("Таблица функции a*x^2:"); //Упрощение(с C# 2.0). Использование анонимного метода Table(delegate (double x, double a) { return a * x * x; }, 5, 0, 3); //Список методов в делегате Console.WriteLine("Работа делегата со списком методов:"); List<Fun> methods = new List<Fun>() { MyFuncPow }; methods.Add(MyFuncSin); Plot(methods, 5, 0, 3); MyMetods.Pause(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.SceneManagement; using UObject = UnityEngine.Object; namespace TG.AssetBundleRM { /// <summary> /// ab 数据模型 /// 一个ab 对应对个依赖,过个asset name /// </summary> public class ABUnitModel { /// <summary> /// ab 变体名 /// </summary> public string abVariant; /// <summary> /// ab path /// </summary> public string abPath; public List<int> depIndexs; /// <summary> /// 当前ab包含的所有asset /// </summary> public List<AssetUnitModel> assetList = new List<AssetUnitModel>(); public ABUnitModel(string assetPath, string abPath) { this.abPath = abPath; this.abVariant = ""; AssetUnitModel assetUnitModel = new AssetUnitModel(assetPath,abPath); this.assetList.Add(assetUnitModel); } public void AddDependenciesIndex(int index) { if (depIndexs == null) depIndexs = new List<int>(); depIndexs.Add(index); } public void AddAsset(string assetPath,string abPath) { if (!string.IsNullOrEmpty(assetPath)) { AssetUnitModel assetUnitModel = new AssetUnitModel(assetPath,abPath); if (!Utility.IsContains<AssetUnitModel>(assetList ,assetUnitModel,(a,b)=> { return a.abPath == b.abPath && a.assetPath == b.assetPath ? true: false; })) { assetList.Add(assetUnitModel); } } } } /// <summary> /// asset 数据模型 /// </summary> public class AssetUnitModel { /// <summary> /// ab asset path : 相对于Assets文件夹 /// eg:Assets/Res/Prefab/UI/Main/MainWindow.prefab /// </summary> public string assetPath; /// <summary> /// asset path hash 值 /// </summary> public int assetPathHash; /// <summary> /// eg:res/prefabs/ui/main/mainwindow.ab /// </summary> public string abPath; /// <summary> /// eg:Res/Prefabs/UI/Main/MainWindow /// </summary> public string assetName; public AssetUnitModel(string assetPath,string abPath) { this.assetPath = assetPath; this.abPath = abPath; this.assetName = Utility.ConvertAssetPath2AssetName(assetPath); this.assetPathHash = assetName.CustomStringHashIgnoreCase(); } } /// <summary> /// Asset 单元 /// </summary> public class AssetUnit { public UObject asset; public AssetUnit(UObject obj) { this.asset = obj; } public UObject Load(bool intantiate) { return intantiate ? GameObject.Instantiate(asset, null, false) : asset; } } /// <summary> /// AB 单元 /// </summary> public class ABUnit { /// <summary> /// AB加载的状态 /// </summary> internal enum LoadState { None, Loaded, Loading, LoadFailed, } private ABUnitModel model; public ABUnitModel ABModel { set { model = value; } get { return model; } } private LoadState loadState; /// <summary> /// 当前 asset bundle 实体 /// </summary> private AssetBundle assetBundle; /// <summary> /// 当前AB依赖列表 /// </summary> private List<ABUnit> dependencies = new List<ABUnit>(); private Promise loadABPro = null; private Promise LoadABPro { get { return loadABPro ?? (loadABPro = new Promise()); } } public ABUnit(string abPath) { model = new ABUnitModel("", abPath); } /// <summary> /// 异步加载资源 /// </summary> public void LoadAssetAsync(string assetPath, Type type, bool instantiate, Action<UObject> onLoaded) { AssetUnit assetUnit; if (RM.Instance.TryGetAssetUnit(assetPath, out assetUnit)) { InternalLoadAssetFromCacheAsync(assetPath, type, instantiate, onLoaded, assetUnit); } else { InternalLoadAssetAsync(assetPath, type, instantiate, onLoaded); } } #region Internal AB Load Functions /// <summary> /// 异步加载主AB和依赖ABs /// </summary> /// <param name="assetPath"></param> /// <returns></returns> internal Promise InternalLoadMainAndDependenciesABAsync(string assetPath) { this.loadState = LoadState.Loading; return InternalLoadMainABAsync() .ContinueWith(_ => GetDependenciesABUnitAsync(assetPath)) .ContinueWith(mainAB => { Promise dependenciesPromise = new Promise(); if (mainAB != null) { InternaleLoadDependenciesABAsync(assetPath) .Then(_ => { InternaleOnABLoaded(this, LoadState.Loaded); dependenciesPromise.Resolve(mainAB); }); } else { InternaleOnABLoaded(this, LoadState.LoadFailed); dependenciesPromise.Resolve(mainAB); } return dependenciesPromise; }); } /// <summary> /// 异步加载主AB /// </summary> /// <returns></returns> internal Promise InternalLoadMainABAsync() { return Utility.LoadABAsync(this.model.abPath) .ContinueWith(objAB => { assetBundle = objAB as AssetBundle; Promise pro = new Promise(); pro.Resolve(objAB); return pro; }); } /// <summary> /// 异步加载依赖ABs /// </summary> /// <param name="assetPath"></param> /// <returns></returns> internal Promise InternaleLoadDependenciesABAsync(string assetPath) { HashSet<Promise> promiseList = new HashSet<Promise>(); foreach (var depUnit in dependencies) { switch (depUnit.loadState) { case LoadState.Loaded: continue; case LoadState.LoadFailed: Utility.Log(Utility.LogLevel.Error, $"LoadDependenciesABAsync:: load failed ,abPath = {depUnit.ABModel.abPath}"); continue; case LoadState.Loading: { Utility.Log(Utility.LogLevel.Error, $"LoadDependenciesABAsync:: loading, abPath = {depUnit.ABModel.abPath}"); Promise pro = new Promise(); Defer.RunCoroutine(WaitForDependenciesAsyncLoading(depUnit, pro)); promiseList.Add(pro); } continue; default: { depUnit.loadState = LoadState.Loading; Promise pro = depUnit.InternalLoadMainABAsync() .ContinueWith(_ => depUnit.GetDependenciesABUnitAsync(assetPath)) .ContinueWith(_ => { Promise depPro = new Promise(); var finalLoadState = depUnit.assetBundle != null ? LoadState.Loaded : LoadState.LoadFailed; InternaleOnABLoaded(depUnit, finalLoadState); depPro.Resolve(depUnit.assetBundle); return depPro; }); promiseList.Add(pro); } continue; } } return Promise.All(promiseList); } /// <summary> /// AB 加载完全处理 /// </summary> /// <param name="unit"></param> /// <param name="state"></param> internal void InternaleOnABLoaded(ABUnit unit, LoadState state) { if (unit.loadState != state) { unit.loadState = state; unit.LoadABPro.Resolve(unit.assetBundle); } else { Utility.Log(Utility.LogLevel.Error, $"InternaleOnABLoaded::assetPath = {unit.model.abPath} ,state = {state}"); } } internal IEnumerator<float> WaitForDependenciesAsyncLoading(ABUnit unit, Promise pro) { while (unit.loadState == LoadState.Loading) { yield return Defer.WaitForOneFrame; } pro.Resolve(unit.assetBundle); } /// <summary> /// 异步获取AB依赖列表 /// </summary> /// <param name="assetPath"></param> /// <returns></returns> internal Promise GetDependenciesABUnitAsync(string assetPath) { Promise pro = new Promise(); if (assetBundle != null && dependencies.Count == 0) { List<ABUnitModel> modelList = RM.Instance.GetAllDependencies(assetPath); foreach (var m in modelList) { if (model.abPath != m.abPath) { ABUnit unit = RM.Instance.TryGetABUnit(m.abPath); if (!dependencies.Contains(unit)) { dependencies.Add(unit); } else { Utility.Log(Utility.LogLevel.Warning, $"assetPath = {assetPath} , is already contains in dependencies"); } } } } pro.Resolve(assetBundle); return pro; } #endregion #region Internal Asset Load Functions /// <summary> /// 异步加载asset /// </summary> /// <param name="assetPath">asset path , eg:Res/UI/Main/MainWindow</param> /// <param name="type">资源类型</param> /// <param name="instantiate">是否实例化</param> /// <param name="onLoaded">加载完成回调</param> internal void InternalLoadAssetAsync(string assetPath, Type type, bool instantiate, Action<UObject> onLoaded) { switch (this.loadState) { case LoadState.None: loadABPro = InternalLoadMainAndDependenciesABAsync(assetPath); LoadABPro.Then(_ => { ExtractAssetFromAB(assetPath, type, instantiate, onLoaded); }); break; case LoadState.Loading: LoadABPro.Then(_ => { ExtractAssetFromAB(assetPath, type, instantiate, onLoaded); }); break; case LoadState.LoadFailed: LoadABPro.Then(_ => { ExtractAssetFromAB(assetPath, type, instantiate, onLoaded); }); break; case LoadState.Loaded: LoadABPro.Then(_ => { ExtractAssetFromAB(assetPath, type, instantiate, onLoaded); }); break; default: Utility.Log(Utility.LogLevel.Error, $"InternalLoadAssetAsync::loadState = {this.loadState}"); break; } } /// <summary> /// 从缓存中异步加载asset /// </summary> /// <param name="assetPath"></param> /// <param name="type"></param> /// <param name="instantiate"></param> /// <param name="onLoaded"></param> /// <param name="assetUnit"></param> internal void InternalLoadAssetFromCacheAsync(string assetPath, Type type, bool instantiate, Action<UObject> onLoaded, AssetUnit assetUnit) { if (type == typeof(Scene)) { Utility.Log(Utility.LogLevel.Error, $"InternalLoadAssetFromCacheAsync::assetPath = {assetPath} ,type = {type} , 场景资源加载待拓展"); } else { InternalOnAssetLoaded(assetUnit, onLoaded, instantiate); } } /// <summary> /// asset 加载完全处理 /// </summary> /// <param name="assetUnit"></param> /// <param name="onloaded"></param> /// <param name="instantiate"></param> internal void InternalOnAssetLoaded(AssetUnit assetUnit, System.Action<UObject> onloaded, bool instantiate = false) { if (onloaded != null) { if (assetUnit != null) { UObject obj = assetUnit.Load(instantiate); onloaded(obj); } else { onloaded(assetBundle); } } } /// <summary> /// 从AB中提取Asset /// </summary> /// <param name="assetPath"></param> /// <param name="type"></param> /// <param name="instantiate"></param> /// <param name="onLoaded"></param> internal void ExtractAssetFromAB(string assetPath, Type type, bool instantiate, Action<UObject> onLoaded) { string assetName = Path.GetFileNameWithoutExtension(assetPath).ToLower(); if (!string.IsNullOrEmpty(assetName) && assetBundle != null) { if (type == typeof(Scene)) { } else { Utility.LoadAssetAsync(assetBundle, assetName, type) .Then(obj => { UObject asset = (UObject)obj; if (asset != null) { AssetUnit assetUnit = new AssetUnit(asset); RM.Instance.AddLoadedAsset(assetPath, assetUnit); InternalOnAssetLoaded(assetUnit, onLoaded, instantiate); } else { Utility.Log(Utility.LogLevel.Error, $"ExtractAssetFromAB::load ab failed,assetPath = {assetPath} ,assetName = {assetName} ,type = {type}"); InternalOnAssetLoaded(null, onLoaded, instantiate); } }); } } else { Utility.Log(Utility.LogLevel.Error, $"ExtractAssetFromAB::assetPath = {assetPath} ,assetName = {assetName} ,type = {type}"); } } #endregion } /// <summary> /// asset bundle manager /// </summary> public class RM : MonoSingleton<RM> { /// <summary> /// ab 依赖关系数据 assetPath hash for key /// </summary> private Dictionary<int, int> hash2IndexDic; /// <summary> /// ab unit model list /// </summary> private List<ABUnitModel> abUnitModelList; /// <summary> /// ab unit dictionary, abPath for key /// </summary> private Dictionary<string, ABUnit> abUnitsDic = new Dictionary<string, ABUnit>(); /// <summary> /// 已经加载的asset unit dictionary /// </summary> private Dictionary<string, AssetUnit> loadedAssetUnitDic = new Dictionary<string, AssetUnit>(); public void Init() { string dependenciesMapName = "dependenciesMap.ab"; string dependenciesMapDir = Path.Combine(Application.dataPath, "../DependenciesMap/"); ParseDependenciesMap(Path.Combine(dependenciesMapDir, dependenciesMapName)); } #region Parse Dependencies Map /// <summary> /// 依赖关系文件解析 /// </summary> /// <param name="path"></param> public void ParseDependenciesMap(string path) { if (!File.Exists(path)) { Utility.Log(Utility.LogLevel.Error, $"ParseDependenciesMap::file is not exist ,path = {path}"); return; } using (BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open))) { int allABPathLength = reader.ReadInt32(); if (hash2IndexDic == null) { hash2IndexDic = new Dictionary<int, int>(allABPathLength); } if (abUnitModelList == null) { abUnitModelList = new List<ABUnitModel>(allABPathLength); } for (int i = 0; i < allABPathLength; i++) { string abPath = reader.ReadString(); ABUnitModel model = new ABUnitModel("", abPath); int dependenciesLength = reader.ReadInt32(); for (int j = 0; j < dependenciesLength; j++) { int index = reader.ReadInt32(); model.AddDependenciesIndex(index); } abUnitModelList.Add(model); } int length = reader.ReadInt32(); int assetPathHash; int modelIndex; for (int i = 0; i < length; i++) { assetPathHash = reader.ReadInt32(); modelIndex = reader.ReadInt32(); if (!hash2IndexDic.ContainsKey(assetPathHash)) { hash2IndexDic.Add(assetPathHash, modelIndex); } } } } /// <summary> /// 根据assetpath 获取所有资源依赖(包括自己) /// </summary> /// <param name="assetPath"></param> /// <returns></returns> public List<ABUnitModel> GetAllDependencies(string assetPath) { List<ABUnitModel> resultList = new List<ABUnitModel>(); int assetPathHash = assetPath.CustomStringHashIgnoreCase(); if (hash2IndexDic.ContainsKey(assetPathHash)) { int index = hash2IndexDic[assetPathHash]; if (index < abUnitModelList.Count) { ABUnitModel mainModel = abUnitModelList[index]; if (mainModel != null) { resultList.Add(mainModel); if (mainModel.depIndexs != null && mainModel.depIndexs.Count > 0) { for (int i = 0; i < mainModel.depIndexs.Count; i++) { ABUnitModel model = GetModelByIndex(mainModel.depIndexs[i]); if (model != null) { resultList.Add(model); } } } } else { Utility.Log(Utility.LogLevel.Error, $"GetAllDependencies::model is null , assetPathHash = {assetPathHash} , assetPath = {assetPath} ,index = {index} , length = {abUnitModelList.Count}"); } } else { Utility.Log(Utility.LogLevel.Error, $"GetAllDependencies::out of range , assetPathHash = {assetPathHash} , assetPath = {assetPath} ,index = {index} , length = {abUnitModelList.Count}"); } } return resultList; } #endregion #region Load Asset Async /// <summary> /// 异步加载资源 /// </summary> /// <param name="assetPath">例如:Res/Prefabs/UI/Main/MainWindow</param> /// <param name="type"></param> public void LoadAsync(string assetPath, System.Type type,Action<UObject> onLoaded,bool instantiate) { if (string.IsNullOrEmpty(assetPath)) { Utility.Log(Utility.LogLevel.Error, $"LoadAsync::asset path is null"); return; } ABUnitModel model = GetModel(assetPath); ABUnit unit; if (model != null) { unit = TryGetABUnit(model.abPath); unit.LoadAssetAsync(assetPath,type,instantiate,onLoaded); } } #endregion #region Loaded ABUnit /// <summary> /// 根据index 获取model 数据 /// </summary> /// <param name="index"></param> /// <returns></returns> private ABUnitModel GetModelByIndex(int index) { ABUnitModel model = null; if (index < abUnitModelList.Count) { model = abUnitModelList[index]; if (model != null) { if (model.depIndexs != null && model.depIndexs.Count > 0) { for (int i = 0; i < model.depIndexs.Count; i++) { } } } else { Utility.Log(Utility.LogLevel.Error, $"GetModelByIndex::model is null , index = {index} , length = {abUnitModelList.Count}"); } } else { Utility.Log(Utility.LogLevel.Error, $"GetModelByIndex::out of range ,index = {index} , length = {abUnitModelList.Count}"); } return model; } private ABUnitModel GetModel(string assetPath) { ABUnitModel model = null; int assetPathHash = assetPath.CustomStringHashIgnoreCase(); if (hash2IndexDic.ContainsKey(assetPathHash)) { int index = hash2IndexDic[assetPathHash]; if (index < abUnitModelList.Count) { model = abUnitModelList[index]; } else { Utility.Log(Utility.LogLevel.Error, $"GetModel::out of range , assetPathHash = {assetPathHash} , assetPath = {assetPath} ,index = {index} , length = {abUnitModelList.Count}"); } } else { Utility.Log(Utility.LogLevel.Error, $"GetModel::assetPath not find , assetPathHash = {assetPathHash} , assetPath = {assetPath} , length = {abUnitModelList.Count}"); } return model; } /// <summary> /// 根据abPath 获取ABUnit /// </summary> /// <param name="abPath"></param> /// <returns></returns> public ABUnit TryGetABUnit(string abPath) { ABUnit unit; if (!abUnitsDic.TryGetValue(abPath, out unit)) { abUnitsDic.Add(abPath, unit = new ABUnit(abPath)); } return unit; } #endregion #region Loaded AssetUnit /// <summary> /// 获取已经加载的asset /// </summary> /// <param name="uuid"></param> /// <param name="result"></param> /// <returns></returns> public bool TryGetAssetUnit(string assetPath, out AssetUnit result) { return loadedAssetUnitDic.TryGetValue(assetPath, out result); } /// <summary> /// 添加已经加载的asset 进缓存 /// </summary> /// <param name="assetPath"></param> /// <param name="assetUnit"></param> public void AddLoadedAsset(string assetPath, AssetUnit assetUnit) { if (loadedAssetUnitDic.ContainsKey(assetPath)) { loadedAssetUnitDic[assetPath] = assetUnit; } else { loadedAssetUnitDic.Add(assetPath, assetUnit); } } #endregion } }
namespace DAL { using System; using System.Data.Entity.Migrations; public partial class InitialCreate3 : DbMigration { public override void Up() { DropIndex("dbo.Careers", new[] { "Title" }); DropIndex("dbo.Countries", new[] { "Title" }); DropIndex("dbo.Genres", new[] { "Title" }); AlterColumn("dbo.Careers", "Title", c => c.String(nullable: false, maxLength: 100)); AlterColumn("dbo.Movies", "Title", c => c.String(nullable: false, maxLength: 100)); AlterColumn("dbo.Countries", "Title", c => c.String(nullable: false, maxLength: 100)); AlterColumn("dbo.Genres", "Title", c => c.String(nullable: false, maxLength: 100)); AlterColumn("dbo.UserComments", "Comment", c => c.String(nullable: false)); AlterColumn("dbo.People", "FirstName", c => c.String(nullable: false, maxLength: 100)); AlterColumn("dbo.People", "LastName", c => c.String(nullable: false, maxLength: 100)); CreateIndex("dbo.Careers", "Title", unique: true); CreateIndex("dbo.Countries", "Title", unique: true); CreateIndex("dbo.Genres", "Title", unique: true); } public override void Down() { DropIndex("dbo.Genres", new[] { "Title" }); DropIndex("dbo.Countries", new[] { "Title" }); DropIndex("dbo.Careers", new[] { "Title" }); AlterColumn("dbo.People", "LastName", c => c.String(maxLength: 100)); AlterColumn("dbo.People", "FirstName", c => c.String(maxLength: 100)); AlterColumn("dbo.UserComments", "Comment", c => c.String()); AlterColumn("dbo.Genres", "Title", c => c.String(maxLength: 100)); AlterColumn("dbo.Countries", "Title", c => c.String(maxLength: 100)); AlterColumn("dbo.Movies", "Title", c => c.String(maxLength: 100)); AlterColumn("dbo.Careers", "Title", c => c.String(maxLength: 100)); CreateIndex("dbo.Genres", "Title", unique: true); CreateIndex("dbo.Countries", "Title", unique: true); CreateIndex("dbo.Careers", "Title", unique: true); } } }
namespace Alabo.Industry.Shop.Activitys.Modules.ProductNumberLimit.Dtos { /// <summary> /// 用户购买商品数量 /// </summary> public class UserProductCount { public long UserId { get; set; } public long ProductId { get; set; } public long Count { get; set; } } }
 namespace Profiling2.Domain.DTO { public class ObjectSourceDuplicateDTO { public int ObjectID { get; set; } public int SourceID { get; set; } public int Count { get; set; } public ObjectSourceDuplicateDTO() { } } }
namespace Aps.Models.api { public class DenunciaForm { public string TextoDenuncia { get; set; } public int PaisId { get; set; } public int ContinenteId { get; set; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0 // Changes may cause incorrect behavior and will be lost if the code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using ApartmentApps.Client.Models; using Microsoft.Rest; namespace ApartmentApps.Client { public partial interface ICourtesy { /// <param name='id'> /// Required. /// </param> /// <param name='unitId'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<object>> AssignUnitToIncidentReportWithOperationResponseAsync(int id, int unitId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <param name='id'> /// Required. /// </param> /// <param name='comments'> /// Required. /// </param> /// <param name='images'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<object>> CloseIncidentReportWithOperationResponseAsync(int id, string comments, IList<string> images, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <param name='id'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IncidentReportBindingModel>> GetWithOperationResponseAsync(int id, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<IncidentIndexBindingModel>>> ListRequestsWithOperationResponseAsync(CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <param name='id'> /// Required. /// </param> /// <param name='comments'> /// Required. /// </param> /// <param name='images'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<object>> OpenIncidentReportWithOperationResponseAsync(int id, string comments, IList<string> images, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <param name='id'> /// Required. /// </param> /// <param name='comments'> /// Required. /// </param> /// <param name='images'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<object>> PauseIncidentReportWithOperationResponseAsync(int id, string comments, IList<string> images, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <param name='request'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<object>> SubmitIncidentReportWithOperationResponseAsync(IncidentReportModel request, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.IO; using System.Windows.Forms; using GBA; using MOTHER3; using Extensions; namespace MOTHER3Funland { public partial class frmCompression : M3Form { public frmCompression() { InitializeComponent(); ModuleArbiter.FormLoading(this); } private void btnDecomp_Click(object sender, EventArgs e) { int address = GetInt(txtAddress); if (address == -1) { txtAddress.SelectAll(); return; } // Try to decomp byte[] output; int res = LZ77.Decompress(M3Rom.Rom, address, out output); if (res == -1) { MessageBox.Show("There was an error decompressing the data!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show("Decompressed " + output.Length + " bytes from " + res + " bytes.", "Success"); if (dlgSave.ShowDialog() == DialogResult.OK) File.WriteAllBytes(dlgSave.FileName, output); } } private void txtAddress_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { btnDecomp_Click(null, null); } } public override void SelectIndex(int[] index) { int a = index[0]; if (a >= 0) txtAddress.Text = a.ToString("X"); } public override int[] GetIndex() { return new int[] { GetInt(txtAddress) }; } private int GetInt(TextBox t) { int address = 0; try { address = int.Parse(t.Text, System.Globalization.NumberStyles.HexNumber); if ((address < 0) || (address >= 0x1ffffff)) return -1; } catch { return -1; } return address; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using ProjetoMVC.Repositorio; namespace ProjetoMVC.Models { public class Livro { private string autor, editora, titulo; private int id; private DateTime dtPublicacao; [Display(Name = "Autor: ")] [Required(ErrorMessage = "Este campo é obrigatório")] public string Autor { get => autor; set => autor = value; } [Display(Name = "Editora: ")] [Required(ErrorMessage = "Este campo é obrigatório")] public string Editora { get => editora; set => editora = value; } [Display(Name = "Título: ")] [Required(ErrorMessage = "Este campo é obrigatório")] public string Titulo { get => titulo; set => titulo = value; } [ScaffoldColumn(false)] public int Id { get => id; set => id = value; } [Display(Name = "Data de Publicação: ")] [Required(ErrorMessage = "Este campo é obrigatório")] public DateTime DtPulicacao { get => dtPublicacao; set => dtPublicacao = value; } public Emprestimo ObjEmprestimo { get; set; } public Livro Objlivro { get; set; } public Livro BuscarLivroPorID(int id) { return Banco.Livros.First(x => x.id == id); } public void Delete(Livro id) { return; } public Livro Update(Livro livro) { return livro; } public void Inserir() { if (this.Id == 0) { Random r = new Random(); this.id = r.Next(1, 9999); Banco.Livros.Add(this); } } public IList<Livro> BuscarTodos() { return Banco.Livros; } } }
using UnityEngine; using System.Collections; public class BotonBar : MonoBehaviour { private float timeBar; public Camera cameraBar; public static bool upBar, downBar, leftBar, rightBar = false; void Start() { timeBar = 0f; } void LateUpdate() { timeBar += Time.deltaTime; if (timeBar < 2f) { this.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f, -0.45f * timeBar + 1f); } } bool HizoClick(Vector3 mouse) { if ((cameraBar.ScreenToWorldPoint(mouse).x > (this.GetComponent<Renderer>().bounds.min.x)) && (cameraBar.ScreenToWorldPoint(mouse).x < (this.GetComponent<Renderer>().bounds.max.x)) && (cameraBar.ScreenToWorldPoint(mouse).y > (this.GetComponent<Renderer>().bounds.min.y)) && (cameraBar.ScreenToWorldPoint(mouse).y < (this.GetComponent<Renderer>().bounds.max.y))) return true; else return false; } void Update() { Vector3 mouse = Input.mousePosition; if (Input.GetMouseButtonDown(0) )//Lee si se hizo click { if (HizoClick(mouse) && this.name == "Bot_UpBar" && !DialogBar.Fade && !SalPol.FadeFin) { Debug.Log("arriba"); timeBar = 0f; upBar = true; rightBar = leftBar = downBar = false; } else if (HizoClick(mouse) && this.name == "Bot_LeftBar" && !DialogBar.Fade && !SalPol.FadeFin) { timeBar = 0f; leftBar = true; rightBar = upBar = downBar = false; } else if (HizoClick(mouse) && this.name == "Bot_RightBar" && !DialogBar.Fade && !SalPol.FadeFin) { timeBar = 0f; rightBar = true; leftBar = upBar = downBar = false; } } if(Input.GetMouseButtonUp(0)) { upBar = rightBar = leftBar = false; GameObject.Find("Perro").GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("DogSit"); GameObject.Find("Ojos Perro").GetComponent<SpriteRenderer>().enabled = false; } } }
using Microsoft.Extensions.DependencyInjection; using SimplySqlSchema.Extractor; namespace SimplySqlSchema { public static class ExtractorExtensions { public static IServiceCollection AddDataAnnotationExtractor(this IServiceCollection services) { return services.AddScoped<IObjectSchemaExtractor, DataAnnotationsSchemaExtractor>(); } } }
using UnityEngine; using System.Collections; using DG.Tweening; public class DanglingWindowEffect : EffectBase { private RectTransform _rectTransform; void OnEnable() { _rectTransform = transform.GetComponent<RectTransform>(); _rectTransform.localScale = Vector3.one * 0.6f; In(); } public override void In() { _rectTransform.DOScale(Vector3.one, 0.6f).SetEase(Ease.OutBounce); _rectTransform.DOPlay(); } public override void Out(GameObject outGameObject) { outGameObject.SetActive(false); //_rectTransform.DOScale(Vector3.one * 0.6f, 0.6f).SetEase(Ease.InBounce); //_rectTransform.DOPlay(); } }
using System; using System.Xml.Linq; using JetBrains.Annotations; namespace iSukces.Code.VsSolutions { public class AssemblyBinding { [CanBeNull] public static AssemblyBinding ParseDependentAssembly(XElement dependentAssemblyXElement) { var ns = dependentAssemblyXElement.Name.Namespace; var assemblyIdentity = dependentAssemblyXElement.Element(ns + "assemblyIdentity"); if (assemblyIdentity == null) throw new NullReferenceException("assemblyIdentity"); var bindingRedirect = dependentAssemblyXElement.Element(ns + "bindingRedirect"); if (bindingRedirect == null) return null; // throw new NullReferenceException("bindingRedirect"); return new AssemblyBinding { Name = (string)assemblyIdentity.Attribute("name"), OldVersion = (string)bindingRedirect.Attribute("oldVersion"), NewVersion = NugetVersion.Parse((string)bindingRedirect.Attribute("newVersion")), XmlElement = dependentAssemblyXElement }; } public void SetPackageId(string name) { Name = name; var ns = XmlElement.Name.Namespace; var node = XmlElement.Element(ns + "assemblyIdentity"); node.SetAttributeValue("name", name); } public void SetRedirection([NotNull] string version) { if (version == null) throw new ArgumentNullException(nameof(version)); var ns = XmlElement.Name.Namespace; var node = XmlElement.Element(ns + "bindingRedirect"); var ver = version; node.SetAttributeValue("oldVersion", "0.0.0.0-" + ver); node.SetAttributeValue("newVersion", ver); } public override string ToString() => string.Format("{0} from {1} to {2}", Name, OldVersion, NewVersion); public string Name { get; private set; } public string OldVersion { get; set; } public NugetVersion NewVersion { get; private set; } public XElement XmlElement { get; set; } } }
using System.Collections.Generic; using System.Threading.Tasks; using AcoesDotNet.Model; using AcoesDotNet.Repository.Base; using Microsoft.AspNetCore.Mvc; namespace AcoesDotNet.Web.Controllers { [Route("api/[controller]")] [ApiController] public class AcoesController : BaseController { private readonly IGenericRepository<Acao> repo; public AcoesController(IGenericRepository<Acao> repo) { this.repo = repo; } [HttpGet] public async Task<ActionResult<IEnumerable<Acao>>> Get() { var acoes = await repo.GetAllAsyc(); return new ObjectResult(acoes); } [HttpGet("{id}")] public async Task<ActionResult<Acao>> Get(int id) { var Acao = await repo.GetById(id); return new ObjectResult(Acao); ; } [HttpGet("verifica/{codigoAcao}")] public async Task<bool> AcaoExiste(string codigoAcao) { return await repo .ExistsAsync(a => a.CodigoDaAcao == codigoAcao); } [HttpPost] public async Task<IActionResult> Post([FromBody] Acao acao) { var mensagemErro = ValidaEntidade(acao); if (mensagemErro != null) { return BadRequest(mensagemErro); } await repo.InsertAsync(acao); return Ok(); } [HttpPut("{id}")] public async Task<ActionResult> Put(int id, [FromBody] Acao acao) { var acaoExiste = await repo.ExistsAsync(a => a.Id == id); if (id != acao.Id) return BadRequest("Código da ação é invalido"); var mensagemErro = ValidaEntidade(acao); if (mensagemErro != null) { return BadRequest(mensagemErro); } await repo.UpdateAsync(acao); return Ok(); } [HttpDelete("{id}")] public async Task Delete(int id) { await repo.DeleteAsync(id); } } }
using KRPC.Client; using System.Threading; using kRPCUtilities; using KRPC.Client.Services.SpaceCenter; namespace kRPC.Programs { public class CraftControls { public CraftControls(Connection Connection, FlightParameters FlightParams) { connection = Connection; flightParams = FlightParams; var spaceCenter = connection.SpaceCenter(); vessel = spaceCenter.ActiveVessel; } private Connection connection; private Vessel vessel; private FlightParameters flightParams; #region Properties public bool PassedMachOne { get; private set; } = false; public bool SolidsJettisoned { get; private set; } = false; public bool FairingsJettisoned { get; private set; } = false; public bool HasMECO { get; private set; } = false; public bool ApproachingTargetApoapsis { get; private set; } = false; public bool TargetApoapsisMet { get; private set; } = false; public bool SecondStageIgnited { get; private set; } = false; public bool PanelsExtended { get; private set; } = false; #endregion public void JettisonSRBs() { var resourcesSolidFuel = vessel.ResourcesInDecoupleStage(7, false); var currentSolidFuel = connection.AddStream(() => resourcesSolidFuel.Amount("SolidFuel")); if (!SolidsJettisoned && currentSolidFuel.Get() <= 12) { Message.SendMessage("SRB's Jettisoned", connection); vessel.Control.ActivateNextStage(); SolidsJettisoned = true; currentSolidFuel.Remove(); } } public void JettisonFairings() { var flight = vessel.Flight(); var altitudeASL = connection.AddStream(() => flight.MeanAltitude); if (!FairingsJettisoned && altitudeASL.Get() >= 85000) { Message.SendMessage("Fairings Jettisoned", connection); vessel.Control.SetActionGroup(1, true); FairingsJettisoned = true; altitudeASL.Remove(); } } public void MaxQThrottleSegment() { var flight = vessel.Flight(vessel.Orbit.Body.ReferenceFrame); var currentSpeed = connection.AddStream(() => flight.Speed); if (!PassedMachOne && currentSpeed.Get() >= 320) { Message.SendMessage("MaxQ Throttle Segment", connection); vessel.Control.Throttle = 0.5f; PassedMachOne = true; currentSpeed.Remove(); } } public void MECO(int FuelForLanding, Stream<float> FuelInStage) { if (!HasMECO && FuelInStage.Get() <= FuelForLanding) { vessel.Control.Throttle = 0; Message.SendMessage("MECO", connection); Thread.Sleep(2000); vessel.Control.ActivateNextStage(); //vessel.AutoPilot.Engage(); //vessel.Control.SASMode = SASMode.StabilityAssist; HasMECO = true; } } public void ReachingTargetApoapsis(Stream<double> vesselApoapsisAltitude) { if (!TargetApoapsisMet) { if (vesselApoapsisAltitude.Get() >= flightParams.TargetApoapsis * 0.9 && !ApproachingTargetApoapsis) { vessel.Control.Throttle = 0.75f; ApproachingTargetApoapsis = true; Message.SendMessage("Approaching Target Apoapsis", connection); } if (vesselApoapsisAltitude.Get() >= flightParams.TargetApoapsis && !TargetApoapsisMet) { vessel.Control.Throttle = 0; TargetApoapsisMet = true; Message.SendMessage("SECO 1", connection); Message.SendMessage("Target Apoapsis Met", connection); } } } public void SecondStageIgnition() { if (HasMECO && !SecondStageIgnited) { vessel.Control.Throttle = 1; Thread.Sleep(3000); Message.SendMessage("Second Stage Ignition", connection); vessel.Control.ActivateNextStage(); SecondStageIgnited = true; } } public void ExtendSolarPanels(Stream<double> vesselAltitude) { if (vesselAltitude.Get() >= 105000 && !PanelsExtended) { Message.SendMessage("Extending Solar Panels", connection); vessel.Control.SetActionGroup(2, true); PanelsExtended = true; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class bullet : MonoBehaviour { public GameObject spark; Quaternion angle, angle2; Vector3 offset; float speed; // Start is called before the first frame update void Start() { Destroy(gameObject,0.2f); //speed = PlayerPrefs.GetInt("bulletSpeed"); //if (speed == 0) //{ speed = 50f; // } angle = Quaternion.Euler(0f, 0f, 180f); angle2 = Quaternion.Euler(180f, 0f, 180f); Destroy(gameObject, 3f); offset = new Vector3(0f, .5f, 0f); } // Update is called once per frame void Update() { if (!manager.screenPressed) { Destroy(gameObject); } transform.Translate(Vector3.up * Time.deltaTime * speed); } void OnTriggerEnter(Collider other) { if ( other.CompareTag("destroyBullet")) { // player.canMove = true; GameObject go = Instantiate(spark, transform.position, angle); Destroy(go, 0.1f); Destroy(gameObject); } } }
using System; using System.Linq; using System.Collections.Generic; namespace E9 { class Program { static void Main(string[] args) { List<int> numeros = new List<int>(); Console.WriteLine("Ingrese los numeros que desee y 0 para finalizar los ingresos"); int ingresos = 0; int seguir = 1; while(seguir != 0){ ingresos = Int32.Parse(Console.ReadLine()); switch(ingresos){ case 0: seguir = 0; break; default: numeros.Add(ingresos); break; } } Console.WriteLine("Los numeros ingresados fueron:"); numeros.ForEach(i => Console.WriteLine(i)); Console.WriteLine("\nDe ellos, la cantidad de impares es:"); Console.WriteLine(numeros.Count(x => x % 2 != 0)); Console.WriteLine("\nEl primer par es:"); Console.WriteLine(numeros.First(x => x % 2 == 0)); Console.WriteLine("\nLos numeros mayores a 50 son:"); numeros.Where(x => x > 50).ToList().ForEach(i => Console.WriteLine(i)); Console.WriteLine("\nSiendo un total de:"); Console.WriteLine(numeros.Count(x => x > 50) + " numeros mayores a 50"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace otoKiralama { public partial class patronArac : Form { MySqlConnection baglanti = new MySqlConnection("server=localhost; database=otoKiralama;uid=root;pwd=emre"); public patronArac() { InitializeComponent(); } int arac_id = 0; private void button1_Click(object sender, EventArgs e) { if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || textBox5.Text == "") { MessageBox.Show("Lütfen Boş Bıkamayınız", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else{ string filmEkle = "insert into araclar (a_ad,a_plaka,a_model,a_km,a_fiyat) values(@a_ad,@a_plaka,@a_model,@a_km,@a_fiyat)"; MySqlCommand komut = new MySqlCommand(filmEkle, baglanti); komut.Parameters.AddWithValue("@a_ad", textBox1.Text); komut.Parameters.AddWithValue("@a_plaka", textBox2.Text); komut.Parameters.AddWithValue("@a_model", textBox3.Text); komut.Parameters.AddWithValue("@a_km", textBox4.Text); komut.Parameters.AddWithValue("@a_fiyat", textBox5.Text); baglanti.Open(); komut.ExecuteNonQuery(); baglanti.Close(); textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; button2_Click(sender, e); } } private void button2_Click(object sender, EventArgs e) { string aracGoster = "select * from araclar"; MySqlDataAdapter adaptor = new MySqlDataAdapter(aracGoster, baglanti); DataTable tabloGoster = new DataTable(); adaptor.Fill(tabloGoster); baglanti.Open(); dataGridView1.DataSource = tabloGoster; baglanti.Close(); } private void button3_Click(object sender, EventArgs e) { string araciguncelle = "update araclar set a_ad = @a_ad, a_plaka = @a_plaka,a_model =@a_model,a_km = @a_km where a_fiyat=@a_fiyat"; MySqlCommand komut = new MySqlCommand(araciguncelle, baglanti); komut.Parameters.AddWithValue("@a_ad", textBox1.Text); komut.Parameters.AddWithValue("@a_plaka", textBox2.Text); komut.Parameters.AddWithValue("@a_model", textBox3.Text); komut.Parameters.AddWithValue("@a_km", textBox4.Text); komut.Parameters.AddWithValue("@a_fiyat", textBox5.Text); baglanti.Open(); komut.ExecuteNonQuery(); baglanti.Close(); textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; button2_Click(sender, e); } private void button4_Click(object sender, EventArgs e) { string arac_sil = "delete from araclar where a_id = @a_id"; MySqlCommand komut = new MySqlCommand(arac_sil, baglanti); komut.Parameters.AddWithValue("@a_id",arac_id); baglanti.Open(); komut.ExecuteNonQuery(); baglanti.Close(); button2_Click(sender, e); textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { arac_id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value); textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString(); textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString(); textBox4.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString(); textBox5.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString(); //<> //kımrmızı var ise for (int i = 0; i < dataGridView1.Rows.Count; i++) if (dataGridView1.Rows[i].DefaultCellStyle.BackColor == Color.Pink) dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.White; dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Pink; } } }
namespace RadioactiveMutantVampireBunnies { using System; using System.Collections.Generic; using System.Text; public class Startup { static int n; static int m; static int playerRow; static int playerCol; static char[,] matrix; static bool[,] bunnies; public static void Main(string[] args) { Execute(); } private static void Execute() { Initialize(); MovePlayer(); } private static void MovePlayer() { var directions = Console.ReadLine(); for (int i = 0; i < directions.Length; i++) { matrix[playerRow, playerCol] = '.'; Mark(); switch (directions[i]) { case 'U': if (playerRow == 0) { Print("won"); return; } playerRow--; break; case 'L': if (playerCol == 0) { Print("won"); return; } playerCol--; break; case 'D': if (playerRow == n - 1) { Print("won"); return; } playerRow++; break; case 'R': if (playerCol == m - 1) { Print("won"); return; } playerCol++; break; default: break; } if (matrix[playerRow, playerCol] == 'B') { Print("dead"); return; } else { matrix[playerRow, playerCol] = 'P'; } } } private static void Mark() { var newBunnies = new List<KeyValuePair<int, int>>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (bunnies[i, j]) { bunnies[i, j] = false; newBunnies.Add(new KeyValuePair<int, int>(i - 1, j)); newBunnies.Add(new KeyValuePair<int, int>(i, j - 1)); newBunnies.Add(new KeyValuePair<int, int>(i, j + 1)); newBunnies.Add(new KeyValuePair<int, int>(i + 1, j)); } } } foreach (var newBunny in newBunnies) { var row = newBunny.Key; var col = newBunny.Value; if (row >= 0 && row < n && col >= 0 && col < m) { bunnies[row, col] = true; matrix[row, col] = 'B'; } } } private static void Print(string message) { var builder = new StringBuilder(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { builder.Append(matrix[i, j]); } builder.AppendLine(); } builder.AppendLine($"{message}: {playerRow} {playerCol}"); Console.WriteLine(builder); } private static void Initialize() { var args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); n = int.Parse(args[0]); m = int.Parse(args[1]); matrix = new char[n, m]; bunnies = new bool[n, m]; for (int i = 0; i < n; i++) { var line = Console.ReadLine(); for (int j = 0; j < m; j++) { matrix[i, j] = line[j]; bunnies[i, j] = matrix[i, j] == 'B'; if (matrix[i, j] == 'P') { playerRow = i; playerCol = j; } } } } } }
using System; namespace ShapesApp.App { static class Program { static void Main(string[] args) { double length; string input; do { Console.WriteLine("Enter a Length: "); input = Console.ReadLine(); } while (!double.TryParse(input, out length)); double width; do { Console.WriteLine("Enter a Width: "); input = Console.ReadLine(); } while (!double.TryParse(input, out width)); var rectangle = new Rectangle { Length = length, Width = width }; rectangle.PrintRectangle(); double radius; do { Console.WriteLine("Enter a radius: "); input = Console.ReadLine(); } while (!double.TryParse(input, out radius)); ColorCircle colorCircle = new ColorCircle(radius: radius, colorCircle: "black"); Console.WriteLine(colorCircle.GetPerimeter()); Console.WriteLine(ShapeDetails(colorCircle)); } public static void PrintRectangle(this Rectangle r) { Console.WriteLine($"{r.Length}x{r.Width} rectangle ({ShapeDetails(r)})"); 10.ToString(); int thirtythree = 10.Triple(3); } public static string ShapeDetails(IShape shape) { return $"area {shape.Area}, perimeter {shape.GetPerimeter()}, {shape.Sides}"; } } }
using System.Linq; using UBaseline.Core.Node; using UBaseline.Shared.Node; using Uintra.Features.Groups.Models; namespace Uintra.Features.Groups.ContentServices { public class GroupContentProvider : IGroupContentProvider { private readonly INodeModelService _nodeModelService; public GroupContentProvider(INodeModelService nodeModelService) { _nodeModelService = nodeModelService; } public NodeModel GetGroupsOverviewPage() { return _nodeModelService.AsEnumerable().OfType<UintraGroupsPageModel>().First(); } public NodeModel GetGroupCreatePage() { return _nodeModelService.AsEnumerable().OfType<UintraGroupsCreatePageModel>().First(); } public NodeModel GetMyGroupsPage() { return _nodeModelService.AsEnumerable().OfType<UintraMyGroupsPageModel>().First(); } public NodeModel GetGroupRoomPage() => _nodeModelService.AsEnumerable().OfType<UintraGroupsRoomPageModel>().First(); public NodeModel GetGroupEditPage() => _nodeModelService.AsEnumerable().OfType<UintraGroupsEditPageModel>().First(); public NodeModel GetGroupDocumentsPage() => _nodeModelService.AsEnumerable().OfType<UintraGroupsDocumentsPageModel>().First(); public NodeModel GetGroupMembersPage() => _nodeModelService.AsEnumerable().OfType<UintraGroupsMembersPageModel>().First(); } }
using System; using System.Text.RegularExpressions; class chapter8 { static void Main() { Regex reg = new Regex("the"); string str1 = "the quick brown fox jumped over the lazy dog"; MatchCollection matchSet; matchSet = reg.Matches(str1); if (matchSet.Count > 0) foreach (Match aMatch in matchSet) Console.WriteLine("found a match at: " + aMatch.Index); Console.ReadKey(); } }