text
stringlengths
13
6.01M
using GUI.dto; using System; using System.Text.Json; namespace GUI.Util { class IO { public T ReadFromSerial<T>() { throw new NotImplementedException(); } public bool WriteToSerial<T>(T dto) where T : IWritable { throw new NotImplementedException(); } private string InputSerialData(int port) { throw new NotImplementedException(); } } }
using Oop._11_ChainOfRules.Rules; using Oop._8_Null; using Oop._9_OptionalObjects; using System; namespace Oop._11_ChainOfRules { class Program { static void MainX(string[] args) { var moneyBackGuaraantee = new TimeLimitedWarranty(DateTime.Today, TimeSpan.FromDays(7)); var expressWarranty = new TimeLimitedWarranty(DateTime.Today, TimeSpan.FromDays(365)); var circuitryWarranty = new LifetimeWarranty(DateTime.Today); var article = new SoldArticle(moneyBackGuaraantee, expressWarranty, new DefaultRules()); article.InstallCircuitry(new Part(DateTime.Now), circuitryWarranty); Console.ReadLine(); } } }
using Data.Utils; using Infrastructure.Encryption; using Infrastructure.PasswordPolicies; using NHibernate; using NHibernate.Context; using NUnit.Framework; namespace Tests.Utils.TestFixtures { public abstract class DataTestFixture : BaseTestFixture { protected ISession Session; protected ISessionFactory SessionFactory; protected IPasswordPolicy PasswordPolicy = new RegularExpressionPasswordPolicy(".{5,}$"); protected IEncryptor Encryptor { get { return new DefaultEncryptor();} } [SetUp] public void Setup() { NHibernateHelper.CreateDatabaseSchema(); SessionFactory = NHibernateHelper.SessionFactory; Session = NHibernateHelper.SessionFactory.OpenSession(); CurrentSessionContext.Bind(Session); } [TearDown] public void TearDown() { var session = CurrentSessionContext.Unbind(SessionFactory); session.Close(); Session.Dispose(); } } }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Ascii - Image Effect. // Copyright (c) Ibuprogames. All rights reserved. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Do not activate. Only for promotional videos. //#define ENABLE_DEMO using UnityEngine; using UnityEditor; namespace AsciiImageEffect { /// <summary> /// Ascii editor. /// </summary> [CustomEditor(typeof(Ascii))] public sealed class AsciiEditor : Editor { /// <summary> /// Desc. /// </summary> private readonly string asciiDesc = @"Text based render."; /// <summary> /// Help text. /// </summary> public string Help { get; set; } /// <summary> /// Warnings. /// </summary> public string Warnings { get; set; } /// <summary> /// Errors. /// </summary> public string Errors { get; set; } /// <summary> /// OnInspectorGUI. /// </summary> public override void OnInspectorGUI() { EditorGUIUtility.LookLikeControls(); EditorGUI.indentLevel = 0; EditorGUIUtility.labelWidth = 100.0f; EditorGUILayout.BeginVertical(); { EditorGUILayout.Separator(); #if (UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6) if (EditorGUIUtility.isProSkin == true) #endif { Ascii thisTarget = (Ascii)target; EditorGUILayout.BeginVertical(); { thisTarget.amount = AsciiEditorHelper.IntSliderWithReset(@"Amount", "The strength of the effect.\nFrom 0 (no effect) to 100 (full effect).", Mathf.RoundToInt(thisTarget.amount * 100.0f), 0, 100, 100) * 0.01f; thisTarget.saturation = AsciiEditorHelper.IntSliderWithReset(@"Saturation", "The saturation.\nFrom 0 (grey) to 100 (color).", Mathf.RoundToInt(thisTarget.saturation * 100.0f), 0, 100, 100) * 0.01f; thisTarget.brightness = AsciiEditorHelper.IntSliderWithReset(@"Brightness", "The Screen appears to be more o less radiating light.\nFrom -100 (dark) to 100 (full light).", Mathf.RoundToInt(thisTarget.brightness * 100.0f), -100, 100, 0) * 0.01f; thisTarget.contrast = AsciiEditorHelper.IntSliderWithReset(@"Contrast", "The difference in color and brightness.\nFrom -100 (no constrast) to 100 (full constrast).", Mathf.RoundToInt(thisTarget.contrast * 100.0f), -100, 100, 0) * 0.01f; thisTarget.gamma = AsciiEditorHelper.SliderWithReset(@"Gamma", "Optimizes the contrast and brightness in the midtones.\nFrom 0.01 to 10.", thisTarget.gamma, 0.01f, 10.0f, 1.0f); thisTarget.invertVCoord = (EditorGUILayout.Toggle(new GUIContent(@"Invert V Coord", @"Inverts V coordinate of font."), thisTarget.invertVCoord == -1.0f) == true ? -1.0f : 1.0f); thisTarget.color = EditorGUILayout.ColorField(new GUIContent(@"Color", @"Text color"), thisTarget.color); Ascii.AsciiCharset charset = (Ascii.AsciiCharset)EditorGUILayout.EnumPopup(new GUIContent(@"Charset", @"Characters to be used."), thisTarget.Charset); if (charset != thisTarget.Charset) thisTarget.Charset = charset; if (thisTarget.Charset == Ascii.AsciiCharset.Custom) { EditorGUI.indentLevel++; thisTarget.fontCount = EditorGUILayout.IntField(new GUIContent(@"Char count", @"The number of characters in the texture."), (int)thisTarget.fontCount); thisTarget.fontTexture = EditorGUILayout.ObjectField(new GUIContent(@"Font texture", @"The texture with the characters."), thisTarget.fontTexture, typeof(Texture), false) as Texture; EditorGUI.indentLevel--; } #if ENABLE_DEMO thisTarget.showGUI = EditorGUILayout.Toggle("Show GUI", thisTarget.showGUI); thisTarget.musicClip = EditorGUILayout.ObjectField("Music", thisTarget.musicClip, typeof(AudioClip)) as AudioClip; #endif } EditorGUILayout.EndVertical(); EditorGUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); if (GUILayout.Button(new GUIContent(@"[info]", @"Open website"), GUI.skin.label) == true) Application.OpenURL(@"http://labs.ibuprogames.com/ascii"); } EditorGUILayout.EndHorizontal(); Help += asciiDesc; } #if (UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6) else { this.Help = string.Empty; this.Errors += @"'Ascii - Image Effect' require Unity Pro version!"; } #endif if (string.IsNullOrEmpty(Warnings) == false) { EditorGUILayout.HelpBox(Warnings, MessageType.Warning); EditorGUILayout.Separator(); } if (string.IsNullOrEmpty(Errors) == false) { EditorGUILayout.HelpBox(Errors, MessageType.Error); EditorGUILayout.Separator(); } if (string.IsNullOrEmpty(Help) == false) EditorGUILayout.HelpBox(Help, MessageType.Info); } EditorGUILayout.EndVertical(); if (GUI.changed == true) EditorUtility.SetDirty(target); EditorGUIUtility.LookLikeControls(); Help = Warnings = Errors = string.Empty; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Foundry.Security { public static class Operation { public readonly static string All = "*"; public readonly static string Read = "Read"; public readonly static string Write = "Write"; public readonly static string Create = "Create"; public readonly static string Delete = "Delete"; } }
namespace pi_mqtt.Entity { public class PC { public int Id { get; set; } = 0; public string CPU { get; set; } public int Core { get; set; } = 0; public int Thread { get; set; } = 0; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using TaskMaster.Validation; namespace TaskMaster.Models { [CompletionDateNotEarlyThenBeggingDate] public class Project { /// <summary> /// Identifier of project. /// </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } /// <summary> /// Project name. /// </summary> [Required] [MinLength(5)] public string Name { get; set; } /// <summary> /// Name of customer company. /// </summary> [Required] [MinLength(5)] public string CustomerCompanyName { get; set; } /// <summary> /// Name of executor company. /// </summary> [Required] [MinLength(5)] public string ExecutorCompanyName { get; set; } /// <summary> /// Date of project beginning. /// </summary> [Required] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] [DataType(DataType.Date)] public DateTime BegginingDate { get; set; } = DateTime.Today; /// <summary> /// Date of project completion. /// </summary> [Required] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] [DataType(DataType.Date)] public DateTime CompletionDate { get; set; } = DateTime.Today; /// <summary> /// Identifier of project leader. /// </summary> public int LeaderId { get; set; } /// <summary> /// Leader of project. /// </summary> [ForeignKey(nameof(LeaderId))] public Employee Leader { get; set; } /// <summary> /// Priority of project. /// </summary> [Required] [Range(1, 10)] public int Priority { get; set; } = 5; /// <summary> /// Project members. /// </summary> public ICollection<Employee> Members { get; set; } /// <summary> /// Checks if this a new project. /// </summary> /// <returns><see langword="true"/> if this project is new. Otherwise <see langword="false"/>.</returns> public bool IsNew() { return Id == 0; } } }
using UnityEngine; using System.Collections; public class OnStepFunction : MonoBehaviour { public StepperSound leftStep; public StepperSound rightStep; private Animator animator; private float animationSpeed; void Start() { animator = GetComponent<Animator>(); } void Update() { // 37.5hrs worth of jamming gift you with this code, oh Rob if (animator.GetFloat("Speed") > 0.75f) { animationSpeed = 0.2f; } else if (animator.GetFloat("Speed") > 0.5) { animationSpeed = 0.25f; } else { animationSpeed = 0.3f; } } void Step(AnimationEvent animationEvent) { leftStep.PlayStep(); StartCoroutine("StepRight"); } IEnumerator StepRight() { yield return new WaitForSeconds(animationSpeed); rightStep.PlayStep(); } }
namespace Crystal.Plot2D { /// <summary> /// Interaction logic for LineLegendItem.xaml /// </summary> public partial class LineLegendItem : LegendItem { public LineLegendItem() { InitializeComponent(); } public LineLegendItem(Description description) : base(description) { InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems.AdventOfCode.Y2020 { public class Problem04 : AdventOfCodeBase { private List<string> _requiredKeys; public override string ProblemName => "Advent of Code 2020: 4"; public override string GetAnswer() { return Answer2(Input()).ToString(); } private int Answer1(List<string> input) { SetRequiredKeys(); var passports = GetPassports(input); int count = 0; foreach (var passport in passports) { if (HasRequiredKeys(passport)) { count++; } } return count; } private int Answer2(List<string> input) { SetRequiredKeys(); var passports = GetPassports(input); int count = 0; foreach (var passport in passports) { if (HasRequiredKeys(passport) && IsValid(passport)) { count++; } } return count; } private bool IsValid(Dictionary<string, string> passport) { if (!IsValidBirthYear(passport["byr"])) { return false; } if (!IsValidIssueYear(passport["iyr"])) { return false; } if (!IsValidExpirationYear(passport["eyr"])) { return false; } if (!IsValidHeight(passport["hgt"])) { return false; } if (!IsValidHairColor(passport["hcl"])) { return false; } if (!IsValidEyeColor(passport["ecl"])) { return false; } if (!IsValidPassportId(passport["pid"])) { return false; } return true; } private bool IsValidBirthYear(string value) { if (value.Length != 4) { return false; } var valueNum = Convert.ToInt32(value); if (valueNum < 1920 || valueNum > 2002) { return false; } return true; } private bool IsValidIssueYear(string value) { if (value.Length != 4) { return false; } var valueNum = Convert.ToInt32(value); if (valueNum < 2010 || valueNum > 2020) { return false; } return true; } private bool IsValidExpirationYear(string value) { if (value.Length != 4) { return false; } var valueNum = Convert.ToInt32(value); if (valueNum < 2020 || valueNum > 2030) { return false; } return true; } private bool IsValidHeight(string value) { var height = Convert.ToInt32(value.Substring(0, value.Length - 2)); var scale = value.Substring(value.Length - 2, 2); if (scale == "cm") { return height >= 150 && height <= 193; } else if (scale == "in") { return height >= 59 && height <= 76; } return false; } private bool IsValidHairColor(string value) { int index = 0; foreach (char digit in value) { if (index == 0) { if (digit != '#') { return false; } } else { switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': break; default: return false; } } index++; } return true; } private bool IsValidEyeColor(string value) { switch (value) { case "amb": case "blu": case "brn": case "gry": case "grn": case "hzl": case "oth": break; default: return false; } return true; } private bool IsValidPassportId(string value) { if (value.Length != 9) { return false; } foreach (char digit in value) { switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; default: return false; } } return true; } private bool HasRequiredKeys(Dictionary<string, string> passport) { foreach (var key in _requiredKeys) { if (!passport.ContainsKey(key)) { return false; } } return true; } private List<Dictionary<string, string>> GetPassports(List<string> input) { var passports = new List<Dictionary<string, string>>(); var current = new Dictionary<string, string>(); passports.Add(current); foreach (var line in input) { if (line == "") { current = new Dictionary<string, string>(); passports.Add(current); } else { var split = line.Split(' '); foreach (var set in split) { var nextSplit = set.Split(':'); current.Add(nextSplit[0], nextSplit[1]); } } } return passports; } private void SetRequiredKeys() { _requiredKeys = new List<string>() { "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid" }; } private List<string> Test1Input() { return new List<string>() { "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd", "byr:1937 iyr:2017 cid:147 hgt:183cm", "", "iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884", "hcl:#cfa07d byr:1929", "", "hcl:#ae17e1 iyr:2013", "eyr:2024", "ecl:brn pid:760753108 byr:1931", "hgt:179cm", "", "hcl:#cfa07d eyr:2025 pid:166559648", "iyr:2011 ecl:brn hgt:59in" }; } private List<string> Test2Input() { return new List<string>() { "eyr:1972 cid:100", "hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926", "", "iyr:2019", "hcl:#602927 eyr:1967 hgt:170cm", "ecl:grn pid:012533040 byr:1946", "", "hcl:dab227 iyr:2012", "ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277", "", "hgt:59cm ecl:zzz", "eyr:2038 hcl:74454a iyr:2023", "pid:3556412378 byr:2007" }; } private List<string> Test3Input() { return new List<string>() { "pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980", "hcl:#623a2f", "", "eyr:2029 ecl:blu cid:129 byr:1989", "iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm", "", "hcl:#888785", "hgt:164cm byr:2001 iyr:2015 cid:88", "pid:545766238 ecl:hzl", "eyr:2022", "", "iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719" }; } } }
namespace ContestsPortal.Domain.DataAccess.Providers.Interfaces { public interface IProviderFactory { IContestsProvider CreateIContestProvider(); } }
using System; using Zesty.Core.Common; namespace Zesty.Core.Integration { public class Skebby : IAuthProcessor { public void GenerateAuth(string username) { Entities.User user = Business.User.Get(username); if (user != null) { string random = RandomHelper.GenerateSecureRandom(); long.TryParse(user.Properties["Mobile"].Substring(1), out long mobile); Guid resetToken = Business.User.SetResetToken(user.Email); SmsHelper.SendSms($"Your resetToken: {resetToken}", mobile); } } public void GenerateOtp(Guid user, Guid domain) { string otp = RandomHelper.GenerateSecureRandom(); Business.OneTimePassword.Add(user, domain, otp); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class Info : MonoBehaviour { public GameObject Yes; public GameObject No; private void OnEnable() { } public void OnClickYes() { SceneManager.LoadScene("MainMenu"); } public void OnClickNo() { gameObject.SetActive(false); } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OurClassLibrary; using System.Collections.Generic; namespace TheTestFrameWork { [TestClass] public class tstStockCollection { [TestMethod] public void InstanceOK() { //this creates an instance of the class we want to create clsStockCollection AllStock = new clsStockCollection(); //test to see if it exists Assert.IsNotNull(AllStock); } [TestMethod] public void CountPropertyOK() { //this creates an instance of the class we want to create clsStockCollection AllStock = new clsStockCollection(); //create some test data to assign the property Int32 SomeCount = 4; //assign data to the property AllStock.Count = SomeCount; //test to see if it exists Assert.AreEqual(AllStock.Count, SomeCount); } [TestMethod] public void StockListOK() { //this creates an instance of the class we want to create clsStockCollection Stock = new clsStockCollection(); //create some test data to assign the property //this time it needs to be a list type of data List<clsStock> TestStockList = new List<clsStock>(); //add an item to the list //create the item of test data clsStock TestItem = new clsStock(); //set the properties TestItem.ItemNo = 1; TestItem.ItemName = "Overwatch"; TestItem.Genre = "First Person Shooter"; TestItem.AgeRating = 13; TestItem.Condition = "Good"; //add the item to the test list TestStockList.Add(TestItem); //assign the data to the property Stock.AllStock = TestStockList; //test to see if it exists Assert.AreEqual(Stock.Count, TestStockList.Count); } //[TestMethod] //public void TwoStockItemsPresent() //{ // //this creates an instance of the class we want to create // clsStockCollection AllStock = new clsStockCollection(); // //test to see if the values are the same // Assert.AreEqual(AllStock.Count, 2); //} } }
using UnityEngine; public class HackableDoor : MonoBehaviour { [Min(1)] public int arrowsCount = 6; [Min(1)] public float time = 4; private Door door; private bool isFinished = false; private GameObject doorHackDevice; private void Start() { door = GetComponent<Door>(); doorHackDevice = GameObject.FindGameObjectWithTag("HackingDevice"); } private void OnTriggerEnter2D(Collider2D collision) { if (checkCanHack() && !door.isOpen && !isFinished) { ArrowsPuzzle.instance.StartPuzzle(arrowsCount, time, Success, Fail); } if (!door.isOpen && isFinished) { door.Open(); } } private void OnTriggerExit2D(Collider2D collision) { if (checkCanHack() && !door.isOpen && !isFinished) { if (ArrowsPuzzle.instance.isRunning()) { ArrowsPuzzle.instance.StopPuzzle(); } } } private void Success() { door.Open(); GetComponent<Animator>().SetBool("hacked", true); isFinished = true; } private void Fail() { print("FAIL"); } private bool checkCanHack() { return !doorHackDevice.activeInHierarchy; } }
using System; using System.Net.Http; using System.Net.Http.Headers; namespace CountdownLettersWPF.API { public class APIHelper : IAPIHelper { private readonly HttpClient _apiClient; private const string _url = "http://www.anagramica.com"; public HttpClient ApiClient { get { return _apiClient; } } public APIHelper() { _apiClient = new HttpClient { BaseAddress = new Uri(_url) }; _apiClient.DefaultRequestHeaders.Accept.Clear(); _apiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } } }
using System; using System.Collections.Generic; using System.Linq; using TheMapToScrum.Back.DAL; using TheMapToScrum.Back.DAL.Entities; using TheMapToScrum.Back.Repositories.Contract; namespace TheMapToScrum.Back.Repositories.Repo { public class ProductOwnerRepository : IProductOwnerRepository { private readonly ApplicationContext _context; public ProductOwnerRepository(ApplicationContext context) { _context = context; } public ProductOwner Create(ProductOwner objet) { _context.ProductOwner.Add(objet); _context.SaveChanges(); return objet; } public ProductOwner Get(int Id) { return _context.ProductOwner .Where(x => x.Id == Id).FirstOrDefault(); } public List<ProductOwner> GetAll() { return _context.ProductOwner .OrderByDescending(x => x.FirstName) .ToList(); } public List<ProductOwner> GetAllActive() { return _context.ProductOwner .OrderByDescending(x => x.FirstName) .Where(x => !x.IsDeleted) .ToList(); } public ProductOwner Update(ProductOwner entity) { _context.Update(entity); _context.SaveChanges(); return entity; } public bool Delete(int Id) { bool resultat = false; try { ProductOwner entite = _context.ProductOwner.Where(x => x.Id == Id).First(); entite.IsDeleted = true; entite.DateModification = DateTime.UtcNow; _context.Update(entite); _context.SaveChanges(); resultat = true; } catch (Exception ex) { } return resultat; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Data.Linq; using System.Data.Linq.Mapping; namespace StoreFront.Models { //[Table(Name ="Users")] //public class CustomerBase //{ // [Column(IsPrimaryKey = true)] // public int UserId { get; set;} // [Column] // public string FirstName { get; set; } // [Column] // public string LastName { get; set; } // [Column] // public string UserName { get; set; } // [Column] // public string EmailAddress { get; set; } //} public class CustomerBase { public string Name { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactoryProject { class RawMaterialOffer { private double pricePerKilo; //sxolioz public double PricePerKilo { get { return pricePerKilo; } set { pricePerKilo = value * (1 + quality / 100); } } private double quality; public double Quality //Quality is an indicator meaning price should be either a derivative or influenced by it { get { return quality; } set { if ( value < 0 || value > 10) { Console.WriteLine("Quality indicator cannot exceed 10 or be less than 0"); } else quality = value; } } private double rawMaterialAmount; public double RawMaterialAmount { get { return rawMaterialAmount; } set { rawMaterialAmount = value; } } public Supplier SupplierRelated { get; set; } public RawMaterialOffer(double price, double amount, Supplier supplierRelated) { Quality = quality; PricePerKilo = price; RawMaterialAmount = amount; //in units SupplierRelated = supplierRelated; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Mathes : MonoBehaviour { public Button[] num = new Button[16]; public int[] a; [SerializeField] private GameObject starLight; public void KhoiTaoMathGame() { a = new int[num.Length];//a chua cac so dung vi tri, num.length - 1 loai bo phan tu la button close //Gan gia tri ngau nhien cho cac bien ket qua a[12] = Random.Range(150, 250); a[13] = Random.Range(150, 250); a[14] = Random.Range(150, 250); a[15] = Random.Range(150, 250); int[] dd = new int[500];//ham danh dau phan tu da dung //Gan gia tri cac bien ket qua cho mang num (dao vi tri) for(int i = 12; i < a.Length; i++) { int r = Random.Range(12, 16); while (dd[a[r]] == -1)//trong khi so a[r] da duoc dung thi random so khac { r = Random.Range(12, 16); } num[i].GetComponentInChildren<Text>().text = a[r].ToString();//gan gia cho b dd[a[r]] = -1;//danh dau la da dung } //Gan gia tri cho ham a int j = 0;//Chi so index cho cac số hạng int k = 0;//chỉ số index cho kết quả //Khoi tao cac gia tri mang a while (j<12) { int t = a[k + 12];//chua ket qua a[j] = Random.Range(1, 80);//Random so dau tien tren hang t -= a[j];//tru so do if (k == 3)//kiem tra xem da la ket qua cuoi chua { //Chua lai 1 o trong (mot bien bang 0) a[j + 1] = t; a[j + 2] = 0; } else { do { a[j + 1] = Random.Range(1, 80); } while (a[j + 1] >= t); t -= a[j + 1]; a[j + 2] = t; } j += 3; k++; } //Gan gia tri cac phan tu a cho cac button num hien thi len man hinh (ngoai tru ket qua da gan) for (int i = 0; i < 12; i++) { int r = Random.Range(0, 12); while (dd[r] == -1)//trong khi vi tri r da duoc dung thi random vi tri khac { r = Random.Range(0, 12); } num[i].GetComponentInChildren<Text>().text = a[r].ToString();//gan gia tri cho num dd[r] = -1;//danh dau vi tri la da dung if (a[r] == 0) { num[i].GetComponentInChildren<Text>().text = ""; } } } public void DaoViTri(int buttonIndex)//Khi bam chuot thi dao vi tri cua phan tu trong o vua bam vao voi o trong { //Kiem tra cac o gan ke cua o bam vao if (buttonIndex - 1 >= 0) { //Neu co o trong thi thuc hien doi vi tri if (num[buttonIndex - 1].GetComponentInChildren<Text>().text == "") { num[buttonIndex - 1].GetComponentInChildren<Text>().text = num[buttonIndex].GetComponentInChildren<Text>().text; num[buttonIndex].GetComponentInChildren<Text>().text = ""; } } if (buttonIndex + 1 <= 11) { if (num[buttonIndex + 1].GetComponentInChildren<Text>().text == "") { num[buttonIndex + 1].GetComponentInChildren<Text>().text = num[buttonIndex].GetComponentInChildren<Text>().text; num[buttonIndex].GetComponentInChildren<Text>().text = ""; } } if (buttonIndex - 3 >= 0) { if (num[buttonIndex - 3].GetComponentInChildren<Text>().text == "") { num[buttonIndex - 3].GetComponentInChildren<Text>().text = num[buttonIndex].GetComponentInChildren<Text>().text; num[buttonIndex].GetComponentInChildren<Text>().text = ""; } } if (buttonIndex + 3 <= 11) { if (num[buttonIndex + 3].GetComponentInChildren<Text>().text == "") { num[buttonIndex + 3].GetComponentInChildren<Text>().text = num[buttonIndex].GetComponentInChildren<Text>().text; num[buttonIndex].GetComponentInChildren<Text>().text = ""; } } } public bool KiemTra() { int[] t = new int[17]; for (int i = 0; i < num.Length; i++) { if (num[i].GetComponentInChildren<Text>().text == "") t[i] = 0; else t[i] = IntParseFast(num[i].GetComponentInChildren<Text>().text); } //Kiem tra tong cac phan tu tren mot hang co bang ket qua hay khong, neu khong bang thi return false if ((t[0] + t[1] + t[2]) != t[12]) return false; if ((t[3] + t[4] + t[5]) != t[13]) return false; if ((t[6] + t[7] + t[8]) != t[14]) return false; if ((t[9] + t[10] + t[11]) != t[15]) return false; //sau khi kiem tra het ma khong vao cac truong hop tren thi return true return true; } public static int IntParseFast(string value)//chuyen doi chuoi string sang kieu so int { int result = 0; for (int i = 0; i < value.Length; i++) { char letter = value[i]; result = 10 * result + (letter - 48); } return result; } private void Update() { if (KiemTra())//Kiem tra xem neu hoan thanh bang { Vector3 pos = new Vector3(0, 0, 0); GameObject star = Instantiate(starLight, pos, Quaternion.identity) as GameObject;//Tao hieu ung chuc mung star.GetComponent<ParticleSystem>().Play(); Destroy(star, 3); gameObject.transform.parent.gameObject.SetActive(false); } } }
using System; using System.Collections.Generic; using System.Text; using DBDiff.Schema.SQLServer2000.Model; namespace DBDiff.Schema.SQLServer2000.Compare { internal class CompareColumnsConstraints { public ColumnConstraints GenerateDiferences(ColumnConstraints CamposOrigen, ColumnConstraints CamposDestino) { foreach (ColumnConstraint node in CamposDestino) { if (!CamposOrigen.Find(node.Name)) { node.Status = StatusEnum.ObjectStatusType.CreateStatus; CamposOrigen.Parent.Status = StatusEnum.ObjectStatusType.OriginalStatus; CamposOrigen.Parent.Parent.Status = StatusEnum.ObjectStatusType.AlterStatus; CamposOrigen.Add(node); } else { if (!ColumnConstraint.Compare(CamposOrigen[node.Name], node)) { node.Status = StatusEnum.ObjectStatusType.AlterStatus; //Indico que hay un ALTER TABLE, pero sobre la columna, no seteo ningun estado. CamposOrigen[node.Name].Parent.Parent.Status = StatusEnum.ObjectStatusType.AlterStatus; CamposOrigen[node.Name] = node.Clone((Column)CamposOrigen[node.Name].Parent); } } } foreach (ColumnConstraint node in CamposOrigen) { if (!CamposDestino.Find(node.Name)) { node.Status = StatusEnum.ObjectStatusType.DropStatus; CamposOrigen.Parent.Status = StatusEnum.ObjectStatusType.OriginalStatus; CamposOrigen.Parent.Parent.Status = StatusEnum.ObjectStatusType.AlterStatus; } } return CamposOrigen; } } }
using System; using Atc.Rest.Extended.Options; using Atc.Rest.Options; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Logging; // ReSharper disable UnusedMethodReturnValue.Global // ReSharper disable once CheckNamespace namespace Microsoft.AspNetCore.Builder { public static class RestApiExtendedBuilderExtensions { public static IApplicationBuilder ConfigureRestApi(this IApplicationBuilder app, IWebHostEnvironment env) { return app.ConfigureRestApi(env, new RestApiExtendedOptions(), _ => { }); } public static IApplicationBuilder ConfigureRestApi( this IApplicationBuilder app, IWebHostEnvironment env, RestApiExtendedOptions restApiOptions) { return app.ConfigureRestApi(env, restApiOptions, _ => { }); } public static IApplicationBuilder ConfigureRestApi( this IApplicationBuilder app, IWebHostEnvironment env, RestApiExtendedOptions restApiOptions, Action<IApplicationBuilder> setupAction) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (env == null) { throw new ArgumentNullException(nameof(env)); } if (restApiOptions == null) { throw new ArgumentNullException(nameof(restApiOptions)); } if (setupAction == null) { throw new ArgumentNullException(nameof(setupAction)); } if (env.IsDevelopment()) { IdentityModelEventSource.ShowPII = true; } // Cast to base-restApiOptions to force to use ConfigureRestApi in RestApiBuilderExtensions app.ConfigureRestApi(env, restApiOptions as RestApiOptions, setupAction); if (restApiOptions.UseOpenApiSpec) { app.UseOpenApiSpec(env, restApiOptions); } return app; } } }
using System; using FunctionalProgramming.Basics; namespace FunctionalProgramming.Monad { public class Lens<TEntity, TProperty> { private readonly Func<TEntity, TProperty, TEntity> _mutator; private readonly Func<TEntity, TProperty> _accessor; public Lens(Func<TEntity, TProperty, TEntity> mutator, Func<TEntity, TProperty> accessor) { _mutator = mutator; _accessor = accessor; } public TProperty Get(TEntity e) { return _accessor(e); } public State<TEntity, TProperty> GetS() { return _accessor.Get(); } public TEntity Set(TEntity e, TProperty value) { return _mutator(e, value); } public State<TEntity, Unit> SetS(TProperty value) { return new State<TEntity, Unit>(e => Tuple.Create(_mutator(e, value), Unit.Only)); } public TEntity Mod(TEntity e, Func<TProperty, TProperty> updater) { return _mutator(e, updater(_accessor(e))); } public State<TEntity, TProperty> ModS(Func<TProperty, TProperty> updater) { return new State<TEntity, TProperty>(e => Tuple.Create(_mutator(e, updater(_accessor(e))), updater(_accessor(e)))); } public Lens<TEntity, TChildProperty> AndThen<TChildProperty>(Lens<TProperty, TChildProperty> otherLens) { return new Lens<TEntity, TChildProperty>((e, cpv) => Set(e, otherLens.Set(_accessor(e), cpv)), e => otherLens.Get(_accessor(e))); } public Lens<TParent, TProperty> Compose<TParent>(Lens<TParent, TEntity> otherLens) { return new Lens<TParent, TProperty>((pe, p) => otherLens.Set(pe, Set(otherLens.Get(pe), p)), pe => Get(otherLens.Get(pe))); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.IO; namespace Labyrinth { public partial class Character { KeyboardState kbState; bool kbPressed = false; public Rectangle rectPos; public bool Moving() { kbState = Keyboard.GetState(); var keysPressed = kbState.GetPressedKeys(); if (keysPressed.Length == 0) { kbPressed = false; return false; } if (kbPressed) { return false; } kbPressed = true; switch(keysPressed[0]) { case Keys.S: if(C.lbrnt[(int)C.guyPos.X+1, (int)C.guyPos.Y] == '0' || C.lbrnt[(int)C.guyPos.X + 1, (int)C.guyPos.Y] == 'C') { currentAnimation = walkDown; lastAnimation = standDown; C.movingDir = new Point(1, 0); return true; } break; case Keys.W: if (C.lbrnt[(int)C.guyPos.X - 1, (int)C.guyPos.Y] == '0' || C.lbrnt[(int)C.guyPos.X - 1, (int)C.guyPos.Y] == 'C') { currentAnimation = walkUp; lastAnimation = standUp; C.movingDir = new Point(-1, 0); return true; } break; case Keys.A: if ((C.guyPos != C.startGuyPos) && (C.lbrnt[(int)C.guyPos.X, (int)C.guyPos.Y - 1] == '0' || C.lbrnt[(int)C.guyPos.X, (int)C.guyPos.Y - 1] == 'C')) { currentAnimation = walkLeft; lastAnimation = standLeft; C.movingDir = new Point(0, -1); return true; } break; case Keys.D: if (C.guyPos == C.endGuyPos) { if(C.keys > 0) { C.level++; if (C.level == C.MAXLEVEL) { C.finalTime = C.timeElapsed; if(C.finalTime < C.bestTime) { C.bestTime = (int)C.finalTime; Save.SaveBestTime(C.bestTime.ToString()); } C.gameStatus = GameStatus.ENDGAME; } else { C.keys--; C.openLookEffect.Play(); C.gameStatus = GameStatus.ENDLEVEL; } } return false; } if ((C.guyPos != C.endGuyPos) && (C.lbrnt[(int)C.guyPos.X, (int)C.guyPos.Y + 1] == '0' || C.lbrnt[(int)C.guyPos.X, (int)C.guyPos.Y + 1] == 'C' || C.lbrnt[(int)C.guyPos.X, (int)C.guyPos.Y + 1] == 'P')) { currentAnimation = walkRight; lastAnimation = standRight; C.movingDir = new Point(0, 1); rectPos = new Rectangle(C.guyPos.X, C.guyPos.Y, 40, 40); return true; } break; } return false; } } }
namespace Morales.CompulsoryPetShop.UI { public class StringConstans { public const string WelcomeGreeting = "Welcome to the PetShop"; public static string Lines = "-----------------------------------------------"; public static string DeletePetText = "Enter ID of the pet you wist to delete"; public static string SearchByPriceMenuText = "Select Pet type Id to search for pet type:"; public static string ShowPetsMenuMessage = "Press 1 to see a list of all pets"; public static string SearchPetsByTypeMenuMessage = "Press 2 to search pets by type"; public static string CreatePetMenuMessage = "Press 3 to create a new pet"; public static string DeletePetMenuMessage = "Press 4 to delete a pet"; public static string UpdatePetMenuMessage = "Press 5 to update a pet"; public static string SortPetsByPriceMessage = "Press 6 to sort pets by price"; public static string ShowCheapestPetsMenuMessage = "Press 7 to show the five cheapest pets"; public static string CreatePetType = "Choose pet type by ID:"; public static string CreatePetPrice = "Enter the price of the pet:"; public static string SelectPetToUpate = "Select the ID of the pet you want to update:"; public static string CreatePetColor = "Enter the color of the pet:"; public static string CreatePetText = " Create a new Pet"; public static string CreatePetName = "Enter the name of your pet:"; public static string ErrorMessage =" Invalid input - press 0-7"; public static string CreateOwnerText = "Create a Owner"; public static string CreateOwnerName = "Enter the name of the owner"; public static string CreateOwnerMenuMessage = "Press 9 to create a owner"; public static string ShowOwnerMenuMessage = "Press 8 to See a List of all owner"; public static string SelectOwnerToUpdate = "Select the Id of the Owner you want to update"; } }
using ISE.Framework.Common.CommonBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ISE.SM.Common.DTO { public partial class UserToCompanyDto:BaseDto { public UserToCompanyDto() { this.PrimaryKeyName = "UserToCompanyId"; } } }
using System; using System.IO; namespace BPMInterfaceToolkit { public class Log { static string logpath = System.AppDomain.CurrentDomain.BaseDirectory;//软件所在路径 static string filename = "Log.txt"; static string recordpath = System.AppDomain.CurrentDomain.BaseDirectory + "Record\\"; static string recordfilename = DateTime.Today.ToString("yyyy-MM-dd") + ".txt"; //public string logmessage; //public string logname; public static void WriteLog(string logmessage) { //判断日志文件是否存在,不存在,就创建 if (File.Exists(logpath + filename)) { FileInfo fi = new FileInfo(logpath + filename); if (fi.Length / 1024 / 1024 > 5) //大于5M则备份日志 { fi.MoveTo(logpath + DateTime.Now.Year.ToString().Trim() + DateTime.Now.Month.ToString().Trim() + DateTime.Now.Day.ToString().Trim()); } } File.AppendAllText(logpath + filename, logmessage + " " + DateTime.Now.ToString().Trim() + "\r\n"); } public static void WriteRecord(string message) { if (!Directory.Exists(recordpath)) { Directory.CreateDirectory(recordpath); } File.AppendAllText(recordpath + recordfilename, message); } } }
// // Copyright (c) Autodesk, Inc. All rights reserved. // // This computer source code and related instructions and comments are the // unpublished confidential and proprietary information of Autodesk, Inc. // and are protected under Federal copyright and state trade secret law. // They may not be disclosed to, copied or used by any third party without // the prior written consent of Autodesk, Inc. // using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Autodesk.Forge.ARKit { public static class TransformExtensions { public static void FromMatrix (this Transform transform, Matrix4x4 matrix) { transform.localScale = matrix.ExtractScale (); transform.rotation = matrix.ExtractRotation (); transform.position = matrix.ExtractPosition (); } } }
namespace DelftTools.Utils.Collections.Generic { public interface IEnumerableListCache { INotifyCollectionChange CollectionChangeSource { get; set; } } }
using CYJ.DingDing.Api.IApiService; using CYJ.DingDing.Application.IAppService; using CYJ.DingDing.Dto.Dto; namespace CYJ.DingDing.Api.ApiService { public class DepartmentApiService : IDepartmentApiService { private readonly IDepartmentAppService _departmentAppService; public DepartmentApiService(IDepartmentAppService departmentAppService) { _departmentAppService = departmentAppService; } public DepartmentCreateResponse Create(DepartmentCreateRequest request) { return _departmentAppService.Create(request); } public DepartmentUpdateResponse Update(int id, DepartmentUpdateRequest request) { return _departmentAppService.Update(id, request); } public DepartmentDeleteResponse Delete(long id) { return _departmentAppService.Delete(id); } public DepartmentDetailResponse GetModel(long id) { return _departmentAppService.GetModel(id); } public DepartmentListResponse GetList(DepartmentListRequest request) { return _departmentAppService.GetList(request); } } }
using System.Collections.Generic; using System.Linq; using CoherentSolutions.Extensions.Configuration.AnyWhere.Abstractions; using CoherentSolutions.Extensions.Configuration.AnyWhere.Tests.Tools; using Moq; using Xunit; namespace CoherentSolutions.Extensions.Configuration.AnyWhere.Tests { public class AnyWhereConfigurationEnvironmentWithPostfixTests { [Fact] public void Should_get_value_of_item_with_postfix_When_called_GetValue_with_item_name_without_postfix() { var environment = AnyWhereConfigurationEnvironmentMockFactory.Create( new[] { ("name", "false"), ("name_POSTFIX", "true") }); var env = new AnyWhereConfigurationEnvironmentWithPostfix(environment, "POSTFIX"); Assert.Equal("true", env.GetValue("name", s => (s, true))); } [Fact] public void Should_get_values_of_items_with_postfix_When_called_GetValues() { var environment = AnyWhereConfigurationEnvironmentMockFactory.Create( new[] { ("one", "one false"), ("two", "two false"), ("one_POSTFIX", "one true"), ("two_POSTFIX", "two true") }); var env = new AnyWhereConfigurationEnvironmentWithPostfix(environment, "POSTFIX"); var values = env.GetValues().ToArray(); Assert.Equal(2, values.Length); Assert.Equal("one", values[0].Key); Assert.Equal("one true", values[0].Value); Assert.Equal("two", values[1].Key); Assert.Equal("two true", values[1].Value); } } }
using AutoService.Core.Contracts; using AutoService.Models.Common.Enums; using System; using System.Linq; using System.Text; using AutoService.Core.Validator; namespace AutoService.Core.Commands { public class ShowAllEmployeesAtDepartment : ICommand { private DepartmentType department; private readonly IDatabase database; private readonly IValidateCore coreValidator; private readonly IWriter writer; public ShowAllEmployeesAtDepartment(IProcessorLocator processorLocator) { if (processorLocator == null) throw new ArgumentNullException(); this.database = processorLocator.GetProcessor<IDatabase>() ?? throw new ArgumentNullException(); this.coreValidator = processorLocator.GetProcessor<IValidateCore>() ?? throw new ArgumentNullException(); this.writer = processorLocator.GetProcessor<IWriter>() ?? throw new ArgumentNullException(); } public void ExecuteThisCommand(string[] commandParameters) { this.coreValidator.ExactParameterLength(commandParameters, 2); department = this.coreValidator.DepartmentTypeFromString(commandParameters[1], "department"); var employeesInDepartment = database.Employees.Where(x => x.Department == department).ToList(); if (employeesInDepartment.Count == 0) { throw new ArgumentException($"The are no employees at department: {department}!"); } StringBuilder str = new StringBuilder(); str.AppendLine($"Employees at: {department} department:"); var counter = 1; foreach (var employee in employeesInDepartment) { str.AppendLine($"{counter}. {employee.ToString()}"); counter++; } this.writer.Write(str.ToString()); } } }
using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver; using System; namespace DTO { class Program { static void Main(string[] args) { MongoCRUD db = new MongoCRUD("NewsCrawl"); db.InsertRecord("Users", new PersonModel { FirstName = "tim", LastName = "cool" }); } } public class PersonModel { [BsonId] public Guid Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public class MongoCRUD { private IMongoDatabase db; public MongoCRUD(string database) { var client = new MongoClient(); db = client.GetDatabase(database); } public void InsertRecord<T>(string table, T record) { var collection = db.GetCollection<T>(table); collection.InsertOne(record); } } }
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; [assembly: InternalsVisibleTo("TestHouse.Domain.Tests")] namespace TestHouse.Domain.Models { /// <summary> /// Test case /// </summary> public class TestCase { //for ef private TestCase() { } public TestCase(string name, string description, string expectedResult, Suit suit, int order) { if (string.IsNullOrEmpty(name)) throw new ArgumentException("Name is not specified", "name"); Name = name; Description = description; Order = order; CreatedAt = DateTime.UtcNow; ExpectedResult = expectedResult; Steps = new List<Step>(); Suit = suit ?? throw new ArgumentException("Test case must belogs to suit", "suit"); } /// <summary> /// Test case id /// </summary> public long Id { get; internal set; } /// <summary> /// Test case name /// </summary> public string Name { get; private set; } /// <summary> /// Test case description /// </summary> public string Description { get; private set; } /// <summary> /// Test suite (Parent category) /// </summary> public Suit Suit { get; private set; } /// <summary> /// Creation date /// </summary> public DateTime CreatedAt { get; private set; } /// <summary> /// Test case expected result /// </summary> public string ExpectedResult { get; private set; } /// <summary> /// Order in a suit /// </summary> public int Order { get; private set; } /// <summary> /// Test case steps /// </summary> public List<Step> Steps { get; private set; } /// <summary> /// Add step /// </summary> /// <param name="step"></param> internal void AddStep(Step step) { Steps.Add(step); } /// <summary> /// Add steps /// </summary> /// <param name="steps"></param> internal void AddSteps(IEnumerable<Step> steps) { Steps.AddRange(steps); } } }
using Repository.Interface; using Repository.Interface.Base; using System; using System.Collections.Generic; using System.Text; using TestApp4.conext; using TestApp4.Models; namespace Repository.Implementation { public class UserRoleRepository : Repository<UserRole> , IUserRoleRepository { private AppDbContext _db; public UserRoleRepository(AppDbContext db) : base(db) { } } }
using System; using System.Collections.Generic; using System.Text; namespace TalkExamples.SOLID.LSP.Example1.Wrong { public abstract class Passaro { public abstract void Voar(); } public class Papagaio : Passaro { public override void Voar() { //Pode Voar } } public class Pato : Passaro { public override void Voar() { // Não é possivel implementar, pato não voa throw new NotSupportedException(); } } }
using Andr3as07.Logging.Enrichment; using Andr3as07.Logging.Sink; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; namespace Andr3as07.Logging { public class Logger : ISink, IDisposable { public List<ISink> Sinks; public List<IEnricher> Enrichers; public Dictionary<string, object> Properties; public LogLevel Level; public Logger(LogLevel level) { Sinks = new List<ISink>(); Enrichers = new List<IEnricher>(); Properties = new Dictionary<string, object>(); Level = level; } public void Log(LogLevel level, string message, params object[] data) { if (level < Level) { return; } DateTime time = DateTime.UtcNow; // Create a copy of the properties to protect against enrichers modifing constant properties. Dictionary<string, object> context = Properties.ToDictionary(entry => entry.Key, entry => entry.Value); if (data.Length >= 1) { // Merge old context if (data[0] is Dictionary<string, object> dictionary) { // Merge contexts dictionary.ToList().ForEach(x => context[x.Key] = x.Value); // Remove first element data = data.Skip(1).ToArray(); } // Resolve data for (int i = 0; i < data.Length; i++) { #if !(NETFRAMEWORK || NETSTANDARD) if (data[i] is ITuple dataEntry1) { context[(string)dataEntry1[0]] = dataEntry1[1]; } else #endif if (data[i] is Tuple<string, object> dataEntry2) { context[dataEntry2.Item1] = dataEntry2.Item2; } } } // Run Enrichers foreach (IEnricher enricher in Enrichers) { enricher.Enrich(context, data); } // Output to sinks foreach (ISink sink in Sinks) { sink.Dispatch(level, time, message, context, data); } } public void Trace(string message, params object[] data) { Log(LogLevel.Trace, message, data); } public void Debug(string message, params object[] data) { Log(LogLevel.Debug, message, data); } public void Info(string message, params object[] data) { Log(LogLevel.Info, message, data); } public void Warn(string message, params object[] data) { Log(LogLevel.Warning, message, data); } public void Error(string message, params object[] data) { Log(LogLevel.Error, message, data); } public void Critical(string message, params object[] data) { Log(LogLevel.Critical, message, data); } public void Emergency(string message, params object[] data) { Log(LogLevel.Emergency, message, data); } public virtual void Flush() { foreach (ISink sink in Sinks) { (sink as IFlushable)?.Flush(); } } public void Dispatch(LogLevel level, DateTime time, string message, Dictionary<string, object> context, params object[] data) { Log(level, message, context, data); } public void Dispose() { foreach (ISink sink in Sinks) { (sink as IDisposable)?.Dispose(); } foreach (IEnricher enricher in Enrichers) { (enricher as IDisposable)?.Dispose(); } } } }
using System; using System.Collections.Generic; using System.Text; namespace DesignPatterns.Command.Example3 { public abstract class RobotCommandBase { protected Robot _robot; public RobotCommandBase(Robot robot) { _robot = robot; } public abstract void Execute(); public abstract void Undo(); } public class MoveCommand : RobotCommandBase { public int ForwardDistance { get; set; } public MoveCommand(Robot robot) : base(robot) { } public override void Execute() { _robot.Move(ForwardDistance); } public override void Undo() { _robot.Move(-ForwardDistance); } } public class RotateLeftCommand : RobotCommandBase { public double LeftRotationAngle { get; set; } public RotateLeftCommand(Robot robot) : base(robot) { } public override void Execute() { _robot.RotateLeft(LeftRotationAngle); } public override void Undo() { _robot.RotateRight(LeftRotationAngle); } } public class RotateRightCommand : RobotCommandBase { public double RightRotationAngle { get; set; } public RotateRightCommand(Robot robot) : base(robot) { } public override void Execute() { _robot.RotateRight(RightRotationAngle); } public override void Undo() { _robot.RotateLeft(RightRotationAngle); } } public class TakeSampleCommand : RobotCommandBase { public bool TakeSample { get; set; } public TakeSampleCommand(Robot robot) : base(robot) { } public override void Execute() { _robot.TakeSample(true); } public override void Undo() { _robot.TakeSample(false); } } public class RobotController { public Queue<RobotCommandBase> Commands; private Stack<RobotCommandBase> _undoStack; public RobotController() { Commands = new Queue<RobotCommandBase>(); _undoStack = new Stack<RobotCommandBase>(); } public void ExecuteCommands() { Console.WriteLine("EXECUTING COMMANDS."); while (Commands.Count > 0) { RobotCommandBase command = Commands.Dequeue(); command.Execute(); _undoStack.Push(command); } } public void UndoCommands(int numUndos) { Console.WriteLine("REVERSING {0} COMMAND(S).", numUndos); while (numUndos > 0 && _undoStack.Count > 0) { RobotCommandBase command = _undoStack.Pop(); command.Undo(); numUndos--; } } } public class Robot { public void Move(int distance) { if (distance > 0) Console.WriteLine("Robot moved forwards {0}mm.", distance); else Console.WriteLine("Robot moved backwards {0}mm.", -distance); } public void RotateLeft(double angle) { if (angle > 0) Console.WriteLine("Robot rotated left {0} degrees.", angle); else Console.WriteLine("Robot rotated right {0} degrees.", -angle); } public void RotateRight(double angle) { if (angle > 0) Console.WriteLine("Robot rotated right {0} degrees.", angle); else Console.WriteLine("Robot rotated left {0} degrees.", -angle); } public void TakeSample(bool take) { if (take) Console.WriteLine("Robot took sample"); else Console.WriteLine("Robot released sample"); } } public class PlayRobot { public static void Run() { var robot = new Robot(); var controller = new RobotController(); var move = new MoveCommand(robot); move.ForwardDistance = 1000; controller.Commands.Enqueue(move); var rotate = new RotateLeftCommand(robot); rotate.LeftRotationAngle = 45; controller.Commands.Enqueue(rotate); var scoop = new TakeSampleCommand(robot); scoop.TakeSample = true; controller.Commands.Enqueue(scoop); controller.ExecuteCommands(); controller.UndoCommands(3); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using DelftTools.Functions.Filters; using DelftTools.Functions.Generic; using DelftTools.TestUtils; using DelftTools.Utils.Collections; using log4net; using NUnit.Framework; namespace DelftTools.Functions.Tests { [TestFixture] public class MemoryFunctionStoreTest { private static readonly ILog log = LogManager.GetLogger(typeof(MemoryFunctionStore)); [TestFixtureSetUp] public void SetUp() { LogHelper.ConfigureLogging(); } [TestFixtureTearDown] public void TearDown() { LogHelper.ResetLogging(); } [Test] public void DefaultVariableStore() { IVariable x = new Variable<double>(); Assert.IsTrue(x.Store is MemoryFunctionStore, "default value store of the variable should be MemoryFunctionStore"); } [Test] public void SetSingleVariableValues() { IVariable x = new Variable<double>(); var values = new[] { 1.0, 2.0, 3.0 }; x.Store.SetVariableValues(x, values); Assert.AreEqual(3, x.Values.Count, "values assigned directly to store must appear in the variable"); //redefine value values = new[] { 4.0, 5.0, 6.0 }; x.Store.SetVariableValues(x, values); Assert.AreEqual(6, x.Values.Count); } [Test] public void CheckFunctionValuesChangedConsistency() { //assert we only get a FunctionValuesChanged event when the function is consistent. IFunction func = new Function(); IVariable x = new Variable<int>("x"); IVariable y = new Variable<int>("y"); func.Arguments.Add(x); func.Components.Add(y); func[0] = 2; func.Store.FunctionValuesChanged += delegate { Assert.IsTrue(func.Components[0].Values.Count == func.Arguments[0].Values.Count); }; func.Clear(); } [Test] public void CopyComponentWhenAssignedToDifferentStore() { IFunction func = new Function(); IVariable y = new Variable<int>("y"); IVariable x = new Variable<int>("x"); IVariable h = new Variable<int>("H"); func.Arguments.Add(x); func.Arguments.Add(y); func.Components.Add(h); h[1, 1] = 1; Assert.AreEqual(1, h[1, 1]); //switch store IFunctionStore functionStore = new MemoryFunctionStore(); functionStore.Functions.Add(func); Assert.AreEqual(4,functionStore.Functions.Count); Assert.AreEqual(1,func.Components[0][1,1]); } [Test] public void CopyDependendFunctionValuesWhenAdded() { //depended variable IVariable y = new Variable<int>("y"); IVariable x = new Variable<int>("x"); y.Arguments.Add(x); y.SetValues(new[] { 10, 20, 30 }, new VariableValueFilter<int>(x, new[] { 1, 2, 3 })); //switch store var store = new MemoryFunctionStore(); store.Functions.Add(y); //get values for x and y Assert.AreEqual(3, store.GetVariableValues(x).Count); Assert.AreEqual(3, store.GetVariableValues(y).Count); Assert.AreEqual(30,y[3]); } [Test] public void CopyIndependendFunctionValuesWhenAdded() { //indep variable IVariable x = new Variable<double>(); var values = new[] { 1.0, 2.0, 3.0 }; x.Store.SetVariableValues(x, values); var store = new MemoryFunctionStore(); store.Functions.Add(x); Assert.AreEqual(3.0, store.GetVariableValues(x)[2]); Assert.AreEqual(3, store.GetVariableValues(x).Count); } [Test] public void StoreTwoIndependentVariables() { IVariable x = new Variable<double>(); IVariable y = new Variable<double>(); x.Store.Functions.Add(y); // use store from x x.SetValues(new[] { 1.0, 2.0, 3.0 }); y.SetValues(new[] { 10.0, 20.0, 30.0, 40.0 }); var store = x.Store; Assert.AreEqual(2, store.Functions.Count); Assert.AreEqual(3, store.GetVariableValues(x).Count); Assert.AreEqual(4, store.GetVariableValues(y).Count); } [Test] public void ShareArgumentVariablesBetweenFunctionsInOneValueStore() { IVariable xVariable = new Variable<double>("x"); IVariable tVariable = new Variable<double>("t"); IVariable f1Variable = new Variable<double>("f1"); IVariable f2Variable = new Variable<double>("f2"); IVariable f3Variable = new Variable<double>("f2"); IFunction f1 = new Function(); f1.Arguments.Add(xVariable); f1.Arguments.Add(tVariable); f1.Components.Add(f1Variable); f1.Components.Add(f2Variable); IFunction f2 = new Function(); IFunctionStore store = f1.Store; store.Functions.Add(f2); // add it to the same store where f1 is stored f2.Arguments.Add(xVariable); f2.Arguments.Add(tVariable); f2.Components.Add(f3Variable); // Assert the store is the same for every thing Assert.AreSame(f1.Store,f2.Store); Assert.AreSame(f1.Store, xVariable.Store); Assert.AreSame(f1.Store, tVariable.Store); Assert.AreSame(f1.Store, f1Variable.Store); Assert.AreSame(f1.Store, f2Variable.Store); Assert.AreSame(f1.Store, f3Variable.Store); } [Test] public void SimpleDependendVariable() { //create a single variable dependency. IVariable<double> x = new Variable<double>("x"); IVariable<double> y = new Variable<double>("y"); y.Arguments.Add(x); IFunctionStore store = y.Store; store.SetVariableValues(x, new[] {0.0, 0.1, 0.2}); Assert.AreEqual(3, store.GetVariableValues(y).Count); } [Test] public void DependentOn2Variables() { IVariable<double> x1 = new Variable<double>("x1"); IVariable<double> x2 = new Variable<double>("x2"); IVariable<double> y = new Variable<double>("y"); y.Arguments.Add(x1); y.Arguments.Add(x2); IFunctionStore store = y.Store; store.SetVariableValues(x1, new[] { 0.0, 0.1, 0.2 }); store.SetVariableValues(x2, new[] { 0.0, 0.1 }); Assert.AreEqual(6, store.GetVariableValues(y).Count); } private class TestNode : IComparable { public string Name { get; set; } public int CompareTo(object obj) { return obj is TestNode ? 0 : -1; } } [Test] [Ignore("Used for code behavior mimicing in rewrite of GetVariableValueFilterIndexes (and that works now), but test as a whole failes due to non-comparability in other code parts")] public void GetVariableValueFiltersShouldDealWithNonValueComparableValues() { IVariable<TestNode> x = new Variable<TestNode>("x"); IVariable<double> y = new Variable<double>("y"); var amount = 2; y.Arguments.Add(x); var node1 = new TestNode { Name = "1" }; var node2 = new TestNode { Name = "2" }; var node3 = new TestNode { Name = "3" }; var node4 = new TestNode { Name = "4" }; y[node1] = 2.0; y[node2] = 5.0; y[node3] = 8.0; y[node4] = 10.0; IFunctionStore store = y.Store; IList<TestNode> valuesToSelect = new List<TestNode>(); valuesToSelect.Add(node1); valuesToSelect.Add(node2); valuesToSelect.Add(node3); valuesToSelect.Add(node4); IMultiDimensionalArray array = store.GetVariableValues(x, new VariableValueFilter<TestNode>(x, valuesToSelect)); array[0].Should("1").Be.EqualTo(node1); array[1].Should("2").Be.EqualTo(node2); array[2].Should("3").Be.EqualTo(node3); array[3].Should("4").Be.EqualTo(node4); } [Test] [Category(TestCategory.Performance)] [Category(TestCategory.WorkInProgress)] // slow public void GetVariableValueFilterIndexesShouldBeFast() { IVariable<double> x = new Variable<double>("x"); IVariable<double> y = new Variable<double>("y"); var amount = 5000; IList<double> allValues = new List<double>(amount); for (int i = 0; i < amount; i++) allValues.Add(i); x.AddValues(allValues); y.Arguments.Add(x); IFunctionStore store = y.Store; IList<double> valuesToSelect = new List<double>(); valuesToSelect.Add(allValues[0]); valuesToSelect.Add(allValues[50]); valuesToSelect.Add(allValues[amount-1]); IMultiDimensionalArray array = null; TestHelper.AssertIsFasterThan(125, () => { for (int i = 0; i < 5000; i++) { array = store.GetVariableValues(x,new VariableValueFilter<double>(x,valuesToSelect)); } }); //orig: 600ms //now: 15ms Assert.AreEqual(3,array.Count); } [Test] public void FunctionContainingTwoComponents() { IVariable x1= new Variable<double>("x"); IVariable x2 = new Variable<double>("x"); IVariable f1 = new Variable<double>("f1"); IVariable f2 = new Variable<double>("f2"); IFunction function = new Function(); function.Arguments.Add(x1); function.Arguments.Add(x2); function.Components.Add(f1); function.Components.Add(f2); Assert.AreEqual(2,function.Components[0].Values.Rank); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Value of type System.String, but expected type System.Int32 for variable variable")] public void SetValuesWithAWrongTypeGivesFormatException() { IVariable<int> x = new Variable<int>(); //go and put a bad string in there x.SetValues(new [] {"lalala"}); } [Test] public void SetValuesUsingFilters2D() { //Y is dependend of x1 and x2. IVariable<int> y = new Variable<int>(); IVariable<int> x1 = new Variable<int>(); IVariable<int> x2 = new Variable<int>(); y.Arguments.Add(x1); y.Arguments.Add(x2); x1.SetValues(new[] { 0, 1, 2 }); x2.SetValues(new[] { 0, 1, 2 }); Assert.AreEqual(9,y.Values.Count); //set y = 2 where x = 0 or x=2 //or is this call wrong and should it be {5,5} or setfunctionValue y.Store.SetVariableValues(y, new[] { 5 }, new VariableValueFilter<int>(x1, new[] { 0 })); //check values of y using MDA interface. The first argument is x1 Assert.AreEqual(5,y.Values[0, 0]); Assert.AreEqual(5,y.Values[0, 1]); Assert.AreEqual(5,y.Values[0, 2]); y.Store.SetVariableValues(y, new[] { 3,2,1 }, new VariableValueFilter<int>(x2, new[] { 0 })); Assert.AreEqual(3, y.Values[0, 0]); Assert.AreEqual(2, y.Values[1, 0]); Assert.AreEqual(1, y.Values[2, 0]); Assert.AreEqual(5, y.Values[0, 1]); Assert.AreEqual(5, y.Values[0, 2]); } [Test] public void GetIndependentValuesFiltersGeneric() { IFunctionStore store = new MemoryFunctionStore(); IVariable<double> x1 = new Variable<double>("x1"); //add one independent variable store.Functions.Add(x1); x1.SetValues(new[] { 0.0d, 1.0d, 2.0d }); Assert.AreEqual(0.0, x1.Values[0]); IMultiDimensionalArray<double> filteredValues = store.GetVariableValues<double>(x1, new VariableValueFilter<double>(x1, new[] {0.0d, 2.0d})); Assert.AreEqual(0.0, filteredValues[0]); Assert.AreEqual(2.0, filteredValues[1]); } [Test] public void GetIndependentValuesUsingMultipleFilters() { Variable<int> x = new Variable<int>(); x.SetValues(new[] {1, 2, 3, 4, 5}); IFunctionStore store = x.Store; IMultiDimensionalArray<int> filteredValues; filteredValues = store.GetVariableValues<int>( x, new VariableValueFilter<int>(x, new[] {1, 2, 3}) ); Assert.AreEqual(3, filteredValues.Count); Assert.AreEqual(1, filteredValues[0]); //same filters different ordering filteredValues = store.GetVariableValues<int>( x, new VariableValueFilter<int>(x, new[] {3, 2, 1}) ); Assert.AreEqual(3, filteredValues.Count); Assert.AreEqual(1, filteredValues[0]); } [Test] public void SetDependendVariable() { // y = f(x) //IFunctionStore store = new MemoryFunctionStore(); IVariable<double> x = new Variable<double>("x"); IVariable<double> y = new Variable<double>("y"); y.Arguments.Add(x); x.SetValues(new [] {1.0d,2.0d,3.0d}); y.SetValues(new [] {2.0d,4.0d,6.0d}); //store.Functions.Add(y); //what value for y where x = 3? IMultiDimensionalArray<double> xValues = y.Store.GetVariableValues<double>(x, new VariableValueFilter<double>(x, new[] { 3.0d })); double d = xValues[0]; Assert.AreEqual(3.0,d); //TODO : refactor to getvalue<TEventArgs> IMultiDimensionalArray<double> yValues = y.Store.GetVariableValues<double>(y, new VariableValueFilter<double>(x, new[] {3.0d})); Assert.AreEqual(6.0,yValues[0]); } [Test,Explicit("Is this really a nice feature?")] public void MakeFilteringLessTypeSensitive() { IVariable<double> x = new Variable<double>(); x.SetValues(new[] { 1.0, 2.0, 3.0 }); IMultiDimensionalArray<double> xValues = x.Store.GetVariableValues<double>(x, new VariableValueFilter<double>(x, 2)); Assert.AreEqual(2.0, xValues[0]); } [Test] public void MultiDimensionalIndexOnFunctionValuesChanged() { IVariable xVariable = new Variable<double>("x"); IVariable tVariable = new Variable<double>("t"); IVariable f1Variable = new Variable<double>("f1"); IFunction f1 = new Function(); f1.Arguments.Add(xVariable); f1.Arguments.Add(tVariable); f1.Components.Add(f1Variable); f1[1.0d, 2.0d] = 25.0; f1.Store.FunctionValuesChanged += ((sender, e) => Assert.AreEqual(new[] {0, 0}, e.MultiDimensionalIndex)); f1[1.0d, 2.0d] = 25.0; } [Test] public void RemoveValues() { IVariable<double> x = new Variable<double>("x"); IVariable<double> y = new Variable<double>("y"); IFunction f = new Function(); f.Arguments.Add(x); f.Components.Add(y); f.SetValues(new[] { 100.0, 200.0, 300.0 }, new VariableValueFilter<double>(x, new[] { 1.0, 2.0, 3.0 })); //update argument f.Store.RemoveFunctionValues(x); //component resizes Assert.AreEqual(0,y.Values.Count); } [Test] public void RemovingAFunctionRemovesFunctionValues() { MemoryFunctionStore store= new MemoryFunctionStore(); IFunction f = new Function(); IVariable<double> x = new Variable<double>("x"); store.Functions.Add(f); f.Components.Add(x); Assert.AreEqual(2,store.Functions.Count); f.Components.Clear(); //store.Functions.Remove(x); Assert.AreEqual(1, store.Functions.Count); } [Test] public void Clone() { IVariable<int> x = new Variable<int>("x") { Values = { 1, 2, 3 } }; IVariable<double> y = new Variable<double>("y"); IFunction f = new Function { Arguments = {x}, Components = {y} }; f.SetValues(new[] { 100.0, 200.0, 300.0 }); var store = (MemoryFunctionStore)f.Store; var clone = (MemoryFunctionStore)store.Clone(); // clone it! clone.Functions.Count .Should().Be.EqualTo(3); clone.Functions[0] .Should("check f").Be.OfType<Function>(); clone.Functions[1] .Should("check x").Be.OfType<Variable<int>>(); clone.Functions[2] .Should("check y").Be.OfType<Variable<double>>(); Assert.AreEqual(new [] { 100.0, 200.0, 300.0}, clone.Functions[0].GetValues()); } [Test] public void CopyConstructor() { IVariable<int> x = new Variable<int>("x") { Values = { 1, 2, 3 } }; IVariable<double> y = new Variable<double>("y"); IFunction f = new Function { Arguments = { x }, Components = { y } }; f.SetValues(new[] { 100.0, 200.0, 300.0 }); var store = (MemoryFunctionStore)f.Store; var copy = new MemoryFunctionStore(store); // copy copy.Functions.Count .Should().Be.EqualTo(3); copy.Functions[0] .Should("check f").Be.OfType<Function>(); copy.Functions[1] .Should("check x").Be.OfType<Variable<int>>(); copy.Functions[2] .Should("check y").Be.OfType<Variable<double>>(); var variables = copy.Functions.OfType<IVariable>(); variables.ForEach(v => v.Values.Count.Should().Be.EqualTo(0)); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Number of values to be written to dependent variable 'y' exceeds argument values range. Got 3 values expected at most 1.")] public void FunctionStoreShouldThrowExceptionIfNumberOfValuesExceedsArgumentRange() { var f = FunctionHelper.Get1DFunction<int, int>(); //setting 3 values for a single argument value doesn't fit f[1] = new[] {1, 2, 3}; } [Test] [Category(TestCategory.Performance)] public void AddIndependentVariableValuesScalesWell() { var x = new Variable<double>("x"); var y = new Variable<double>("x"); y.Arguments.Add(x); // add an remove one value to make sure that all internal caches are initialized (TypeUtils.CallGeneric) x.Values.Add(0); x.Values.Clear(); var memoryStore = y.Store; var values = new List<double>(); for (int i = 0; i < 10000; i++) { values.Add(i); } var stopwatch = new Stopwatch(); stopwatch.Start(); memoryStore.AddIndependendVariableValues(x, values); stopwatch.Stop(); var dt1 = stopwatch.ElapsedMilliseconds; log.DebugFormat("First call took {0} ms", dt1); stopwatch.Reset(); for (int i = 0; i < 10000; i++) { values[i] = i + 10000; } stopwatch.Start(); memoryStore.AddIndependendVariableValues(x, values); stopwatch.Stop(); var dt2 = stopwatch.ElapsedMilliseconds; log.DebugFormat("Second call took {0} ms", dt2); var percentage = 100.0 * (dt2 - dt1) / dt1; log.DebugFormat("Difference is: {0}%", percentage); Assert.IsTrue(percentage < 30, "Adding 10000 values second time is almost as fast as adding them second time, should be < 30% but was: " + percentage + "%"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entity.MDM { /// <summary> /// 操作工技能矩阵 /// </summary> public class OperatorSkillMatrix { /// <summary> /// 序号 /// </summary> public int Ordinal { get; set; } /// <summary> /// 工序叶标识 /// </summary> public int T216LeafID { get; set; } /// <summary> /// 工序代码 /// </summary> public string T216Code { get; set; } /// <summary> /// 工序名称 /// </summary> public string T216Name { get; set; } /// <summary> /// 员工工号 /// </summary> public string UserCode { get; set; } /// <summary> /// 员工姓名 /// </summary> public string UserName { get; set; } /// <summary> /// 是否线长/拉长/班长 /// </summary> public bool IsTeamLeader { get; set; } /// <summary> /// 资质等级 /// 1=优秀(绿卡) 2=合格(黄卡) 3=培训(红卡) /// </summary> public int QualificationLevel { get; set; } /// <summary> /// 是否在岗(在本产线签到未签退) /// </summary> public bool IsOnLine { get; set; } public OperatorSkillMatrix Clone() { return MemberwiseClone() as OperatorSkillMatrix; } } }
#if UNITY_2018_1_OR_NEWER using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; using UnityEngine; namespace AlmenaraGames.Tools { public class MLPASAnimatorPreProcess : IPreprocessBuildWithReport { public int callbackOrder { get { return 0; } } public void OnPreprocessBuild(BuildReport report) { if (!MLPASAnimatorSFXController.UpdateValues(true)) { //Stop Build Process } } } } #else using UnityEditor; using UnityEditor.Build; using UnityEngine; namespace AlmenaraGames.Tools { public class MLPASAnimatorPreProcess : IPreprocessBuild { public int callbackOrder { get { return 0; } } public void OnPreprocessBuild(BuildTarget target, string path) { if (!MLPASAnimatorSFXController.UpdateValues(true)) { //Stop Build Process } } } } #endif
using System; namespace Models.DTO { public class ChallengeProgress : IChallengeProgress { public Guid Id { get; set; } public int UserId { get; set; } public int ChallengeId { get; set; } public ProgressStatus Status { get; set; } public DateTime LastModified { get; set; } } }
using NStandard.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace NStandard { public class State { public delegate void ValueReceivedHandler<T>(T value); public static State<TValue> Use<TValue>() => new(); public static State<TValue> Use<TValue>(TValue value) => new(value); public static State<TValue> From<TValue>(Expression<Func<TValue>> value) => new(value); } public interface IState { event State.ValueReceivedHandler<object> Updating; event State.ValueReceivedHandler<object> Changed; event Action Noticing; IState[] Dependencies { get; } object Value { get; set; } Type ValueType { get; } bool CanSetValue { get; } } public sealed class State<T> : IState, IDisposable { public event Action Noticing; public event State.ValueReceivedHandler<T> Updating; private event State.ValueReceivedHandler<object> ValueUpdating; event State.ValueReceivedHandler<object> IState.Updating { add => ValueUpdating += value; remove => ValueUpdating -= value; } public event State.ValueReceivedHandler<T> Changed; private event State.ValueReceivedHandler<object> ValueChanged; event State.ValueReceivedHandler<object> IState.Changed { add => ValueChanged += value; remove => ValueChanged -= value; } private bool disposedValue; private readonly HashSet<IState> _dependencyList = new(); public IState[] Dependencies => _dependencyList.ToArray(); private readonly Func<T> _getValue; private T _value; #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET40_OR_GREATER private readonly Lazy<Type> _valueType = new(() => typeof(T)); public Type ValueType => _valueType.Value; #else public Type ValueType => typeof(T); #endif public bool IsValueCreated { get; private set; } public void Update() { IsValueCreated = false; if (Updating is not null || ValueUpdating is not null) { var value = Value; Updating?.Invoke(value); ValueUpdating?.Invoke(value); } } public bool CanSetValue { get; } private T GetStoredValue() => _value; internal State() : this(default(T)) { } internal State(T value) { IsValueCreated = true; CanSetValue = true; _value = value; _getValue = GetStoredValue; } internal State(Expression<Func<T>> getValue) { CanSetValue = false; CollectDependencies(getValue); _getValue = getValue.Compile(); } /// <summary> /// Sets the specified <see cref="IState"/> as a dependency. /// </summary> /// <param name="dependency"></param> public void Watch(IState dependency) { _dependencyList.Add(dependency); dependency.Noticing += Update; } /// <summary> /// Removes the specified <see cref="IState"/> from the list of dependencies. /// </summary> /// <param name="dependency"></param> public void Unwatch(IState dependency) { _dependencyList.Remove(dependency); dependency.Noticing -= Update; } public void CollectDependencies(Expression<Func<T>> getValue) { _dependencyList.Clear(); void InnerCollectDependencies(IState[] dependencies) { foreach (var dependency in dependencies) { if (dependency.Dependencies.Length == 0) { Watch(dependency); } else InnerCollectDependencies(dependency.Dependencies); } } var collector = new DependencyCollector(); collector.Collect(getValue, typeof(State<>)); var dependencies = collector.GetDependencies().OfType<IState>().ToArray(); InnerCollectDependencies(dependencies); } public T Value { get { if (!IsValueCreated) { _value = _getValue(); IsValueCreated = true; } return _value; } set { if (!CanSetValue) throw new InvalidOperationException("Cannot set value for state which is calculated from other object."); if (!_value.Equals(value)) { _value = value; Changed?.Invoke(value); ValueChanged?.Invoke(value); Noticing?.Invoke(); } } } object IState.Value { get => Value; set => Value = (T)value; } /// <summary> /// Set value to Expired. /// </summary> public void Expire() => IsValueCreated = false; /// <summary> /// Cancel all subscriptions that depend on the object. /// </summary> public void Release() => Noticing = null; /// <summary> /// Subscribe to update notifications for all dependencies. /// </summary> public void Rebind() { foreach (var dependency in Dependencies) { Watch(dependency); } } public static implicit operator T(State<T> @this) { return @this.Value; } protected void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { Updating = null; Changed = null; ValueUpdating = null; ValueChanged = null; foreach (var dependency in Dependencies) { dependency.Noticing -= Update; } } disposedValue = true; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } }
//------------------------------------------------------------------------------ // <copyright file="MainPage.xaml.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.ComponentModel; using System.IO; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel.Resources; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Imaging; using WindowsPreview.Kinect; namespace Microsoft.Samples.Kinect.ColorBasics { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page, INotifyPropertyChanged { /// <summary> /// Resource loader for string resources /// </summary> private ResourceLoader resourceLoader = new ResourceLoader("Resources"); /// <summary> /// Size of the RGB pixel in the bitmap /// </summary> private readonly uint bytesPerPixel; /// <summary> /// Active Kinect sensor /// </summary> private KinectSensor kinectSensor = null; /// <summary> /// Reader for color frames /// </summary> private ColorFrameReader colorFrameReader = null; /// <summary> /// Bitmap to display /// </summary> private WriteableBitmap bitmap = null; /// <summary> /// Intermediate storage for receiving frame data from the sensor /// </summary> private byte[] colorPixels = null; /// <summary> /// Current status text to display /// </summary> private string statusText = null; /// <summary> /// Initializes a new instance of the MainPage class. /// </summary> public MainPage() { // get the kinectSensor object this.kinectSensor = KinectSensor.GetDefault(); // open the reader for the color frames this.colorFrameReader = this.kinectSensor.ColorFrameSource.OpenReader(); // wire handler for frame arrival this.colorFrameReader.FrameArrived += this.Reader_ColorFrameArrived; // create the colorFrameDescription from the ColorFrameSource using rgba format FrameDescription colorFrameDescription = this.kinectSensor.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Rgba); // rgba is 4 bytes per pixel this.bytesPerPixel = colorFrameDescription.BytesPerPixel; // allocate space to put the pixels to be rendered this.colorPixels = new byte[colorFrameDescription.Width * colorFrameDescription.Height * this.bytesPerPixel]; // create the bitmap to display this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); // set IsAvailableChanged event notifier this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged; // open the sensor this.kinectSensor.Open(); // set the status text this.StatusText = this.kinectSensor.IsAvailable ? resourceLoader.GetString("RunningStatusText") : resourceLoader.GetString("NoSensorStatusText"); // use the window object as the view model in this simple example this.DataContext = this; // initialize the components (controls) of the window this.InitializeComponent(); theImage.Source = this.bitmap; } /// <summary> /// INotifyPropertyChangedPropertyChanged event to allow window controls to bind to changeable data. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the current status text to display /// </summary> public string StatusText { get { return this.statusText; } set { if (this.statusText != value) { this.statusText = value; // notify any bound elements that the text has changed if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText")); } } } } /// <summary> /// Execute shutdown tasks. /// </summary> /// <param name="sender">object sending the event</param> /// <param name="e">event arguments</param> private void MainPage_Unloaded(object sender, RoutedEventArgs e) { if (this.colorFrameReader != null) { // ColorFrameReder is IDisposable this.colorFrameReader.Dispose(); this.colorFrameReader = null; } if (this.kinectSensor != null) { this.kinectSensor.Close(); this.kinectSensor = null; } } /// <summary> /// Handles the color frame data arriving from the sensor. /// </summary> /// <param name="sender">object sending the event</param> /// <param name="e">event arguments</param> private void Reader_ColorFrameArrived(object sender, ColorFrameArrivedEventArgs e) { bool colorFrameProcessed = false; // ColorFrame is IDisposable using (ColorFrame colorFrame = e.FrameReference.AcquireFrame()) { if (colorFrame != null) { FrameDescription colorFrameDescription = colorFrame.FrameDescription; // verify data and write the new color frame data to the Writeable bitmap if ((colorFrameDescription.Width == this.bitmap.PixelWidth) && (colorFrameDescription.Height == this.bitmap.PixelHeight)) { if (colorFrame.RawColorImageFormat == ColorImageFormat.Bgra) { colorFrame.CopyRawFrameDataToBuffer(this.bitmap.PixelBuffer); } else { colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); } colorFrameProcessed = true; } } } // we got a frame, render if (colorFrameProcessed) { this.bitmap.Invalidate(); } } /// <summary> /// Handles the event which the sensor becomes unavailable (E.g. paused, closed, unplugged). /// </summary> /// <param name="sender">object sending the event</param> /// <param name="e">event arguments</param> private void Sensor_IsAvailableChanged(object sender, IsAvailableChangedEventArgs e) { // on failure, set the status text this.StatusText = this.kinectSensor.IsAvailable ? resourceLoader.GetString("RunningStatusText") : resourceLoader.GetString("SensorNotAvailableStatusText"); } } }
namespace DistCWebSite.Core.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; public partial class M_SFEDistributor { public int ID { get; set; } [StringLength(200)] public string SFEDistributorName { get; set; } [StringLength(200)] public string SFEDistributorCode { get; set; } public DateTime? CreateDate { get; set; } [StringLength(200)] public string CreateBy { get; set; } public bool? Active { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BacheloretteManager.Models.AccountViewModels { public class RegisterStudViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [Display(Name = "Nume")] public string Nume { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [Display(Name = "Prenume")] public string Prenume { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Parola")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirma parola")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Required] [Display(Name = "Media An I")] public double MedAn1 { get; set; } [Required] [Display(Name = "Media An II")] public double MedAn2 { get; set; } [Display(Name = "Preferinte")] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] public string Preferinte { get; set; } } }
using ThunderRoad; namespace RealisticBleeding.Components { public struct DisposeWithCreature { public Creature Creature; public DisposeWithCreature(Creature creature) { Creature = creature; } } }
using Piovra.Json; using Xunit; namespace Piovra.Tests; public class JsonTests { [Fact] public void Test() { var person = new Person { Name = "Test", Age = 100, Passport = ("123", "45", ("any", 10)) }; var json = JSON.To(person); var tmp = json; } public class Person { public string Name { get; set; } public int Age { get; set; } public (string Series, string Number, (string Street, int House) Address) Passport { get; set; } } }
namespace ChatBot.Migrations { using System; using System.Data.Entity.Migrations; public partial class courseNumberAdded1 : DbMigration { public override void Up() { AddColumn("dbo.Courses", "time", c => c.String()); AddColumn("dbo.Courses", "location", c => c.String()); AddColumn("dbo.Courses", "noOfUnits", c => c.Int(nullable: false)); } public override void Down() { DropColumn("dbo.Courses", "noOfUnits"); DropColumn("dbo.Courses", "location"); DropColumn("dbo.Courses", "time"); } } }
using System.Collections.Generic; using System.Threading.Tasks; using WebApi.Services.Dto.MercadoLibre.Country; namespace WebApi.Services.Contract { public interface IMercadoLibre { Task<IEnumerable<Country>> Countries(); Task<dynamic> Search(string query); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AccelerometerControl : MonoBehaviour { public float speed = 2f; public bool isFlat = true; private Rigidbody rigid; private void Start() { rigid = GetComponent<Rigidbody>(); } private void Update() { Vector3 tilt = Input.acceleration; if (isFlat) tilt = Quaternion.Euler(90, 0, 0) * tilt * speed; rigid.AddForce(tilt); Debug.DrawRay(transform.position + Vector3.up, tilt); } }
using Fingo.Auth.AuthServer.Services; using Fingo.Auth.AuthServer.Services.Implementation; using Xunit; namespace Fingo.Auth.AuthServer.Tests.Services.Implementation { public class JwtLibraryWrapperServiceTest { public JwtLibraryWrapperServiceTest() { _secretKey = "TOP_SECRET_f!ngo_S3cr3+_P@ssW@rd~<i|\\|t3rn$hIp>/1337/"; _jwtLibraryWrapperService = new JwtLibraryWrapperService(); } private readonly JwtLibraryWrapperService _jwtLibraryWrapperService; private readonly string _secretKey; [Fact] public void DecodeShouldReturnTokenExpired() { // arrange /* "login": "czwarty", * "password": "czwarty", * "project-guid": "01234567-89AB-CDEF-0123-456789ABCDEF" * "exp": 1469539121 -- 26-07-2016 15:18:41 * and our key was used * * variable "jwtValidButExpired" generated by jwt.io website */ var jwtValidButExpired = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbiI6ImN6d2FydHkiLCJwYXNzd29yZCI6ImN6d2FydHkiLCJwcm9qZWN0LWd1aWQiOiIwMTIzNDU2Ny04OUFCLUNERUYtMDEyMy00NTY3ODlBQkNERUYiLCJleHAiOjE0Njk1MzkxMjF9.CGtKXTlYWgx2ZNdGShFlXm7Tl0yNv6TlaYesUQGzvJY"; // act var decodeResult = _jwtLibraryWrapperService.Decode(jwtValidButExpired , _secretKey); // assert Assert.Equal(decodeResult , DecodeResult.TokenExpired); } [Fact] public void DecodeShouldReturnTokenInvalid() { // arrange /* "login": "czwarty", * "password": "czwarty", * "project-guid": "01234567-89AB-CDEF-0123-456789ABCDEF" * "exp": 2132226191 -- should work till 26-07-2037 13:03:11 :-) * and "definitely_not_our_key" key was used * * variable "jwtSignedWithWrongKey" generated by jwt.io website */ var jwtSignedWithWrongKey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbiI6ImN6d2FydHkiLCJwYXNzd29yZCI6ImN6d2FydHkiLCJwcm9qZWN0LWd1aWQiOiIwMTIzNDU2Ny04OUFCLUNERUYtMDEyMy00NTY3ODlBQkNERUYiLCJleHAiOjIxMzIyMjYxOTF9.bDlcSdMQMGuSZUmU7QhS1bjeHbNxSt23HiO28mxtR0M"; // act var decodeResult = _jwtLibraryWrapperService.Decode(jwtSignedWithWrongKey , _secretKey); // assert Assert.Equal(decodeResult , DecodeResult.TokenInvalid); } [Fact] public void DecodeShouldReturnTokenValid() { // arrange /* "login": "czwarty", * "password": "czwarty", * "project-guid": "01234567-89AB-CDEF-0123-456789ABCDEF" * "exp": 2132226191 -- should work till 26-07-2037 13:03:11 :-) * and our key was used * * variable "jwtValid" generated by jwt.io website */ var jwtValid = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbiI6ImN6d2FydHkiLCJwYXNzd29yZCI6ImN6d2FydHkiLCJwcm9qZWN0LWd1aWQiOiIwMTIzNDU2Ny04OUFCLUNERUYtMDEyMy00NTY3ODlBQkNERUYiLCJleHAiOjIxMzIyMjYxOTF9.HsVHbmWTCf1zfe2jjA3PKQZLONh4IzT-iu-LR8Trkhc"; // act var decodeResult = _jwtLibraryWrapperService.Decode(jwtValid , _secretKey); // assert Assert.Equal(decodeResult , DecodeResult.TokenValid); } } }
// <copyright file="TableOfMORT.cs" company="WaterTrans"> // © 2020 WaterTrans // </copyright> using System; using System.Collections.Generic; using System.Text; using WaterTrans.GlyphLoader.Internal.AAT; namespace WaterTrans.GlyphLoader.Internal { /// <summary> /// Table of MORT. /// </summary> internal sealed class TableOfMORT { /// <summary> /// Initializes a new instance of the <see cref="TableOfMORT"/> class. /// </summary> /// <param name="reader">The <see cref="TypefaceReader"/>.</param> internal TableOfMORT(TypefaceReader reader) { TableVersionNumberMajor = reader.ReadUInt16(); TableVersionNumberMinor = reader.ReadUInt16(); NChains = reader.ReadUInt32(); for (int i = 1; i <= NChains; i++) { Chains.Add(new Chain(reader)); } } /// <summary>Gets the metamorphosis chains.</summary> public List<Chain> Chains { get; } = new List<Chain>(); /// <summary>Gets a major table version.</summary> public ushort TableVersionNumberMajor { get; } /// <summary>Gets a minor table version.</summary> public ushort TableVersionNumberMinor { get; } /// <summary>Gets a number of metamorphosis chains contained in this table.</summary> public uint NChains { get; } } }
using System; using System.Collections.Generic; using TraceWizard.Entities; using TraceWizard.Data; using TraceWizard.Analyzers; using TraceWizard.Environment; using TraceWizard.Logging.Adapters.MeterMasterCsv; using TraceWizard.Logging.Adapters.MeterMasterJet; using TraceWizard.Logging.Adapters.Telematics; using TraceWizard.Logging.Adapters.ManuFlo; namespace TraceWizard.Logging { public class Log : IDatabase { public Log(string dataSource) { DataSource = dataSource; } public Log() {} public virtual List<Flow> Flows { get; set; } public double Volume { get; protected set; } public double Peak { get; protected set; } public const string StartTimeLabel = "LogStartTime"; public DateTime StartTime { get; set; } public const string EndTimeLabel = "LogEndTime"; public DateTime EndTime { get; set; } public TimeFrame TimeFrame { get { return new TimeFrame(StartTime, EndTime); } } public const string FileNameLabel = "LogFileName"; public string FileName { get; set; } public string DataSource { get; set; } public string DataSourceFileNameWithoutExtension { get { return System.IO.Path.GetFileNameWithoutExtension(DataSource); } set { } } public string DataSourceWithFullPath { get { return System.IO.Path.GetFullPath(DataSource); } set { } } public double[] HoursVolume; public Dictionary<DateTime,double> DailyVolume; public void UpdateHourlyTotals() { HoursVolume = new double[24]; foreach (Flow flow in Flows) { HoursVolume[flow.StartTime.Hour] += flow.Volume; } } public void UpdateDailyTotals() { DailyVolume = GetFullDays(); foreach (Flow flow in Flows) { if (DailyVolume.ContainsKey(flow.StartTime.Date)) DailyVolume[flow.StartTime.Date] += flow.Volume; } } Dictionary<DateTime, double> GetFullDays() { var dictionary = new Dictionary<DateTime, double>(); var startDate = StartTime.Date; var endDate = EndTime.Date; var runningDate = startDate.AddDays(1); while (runningDate < endDate) { dictionary.Add(runningDate, 0.0); runningDate = runningDate.AddDays(1); } return dictionary; } public void Update() { Volume = CalcVolume(); Peak = CalcPeak(); } private double CalcVolume() { double vol = 0.0; foreach (Flow flow in Flows) vol += flow.Volume; return vol; } private double CalcPeak() { double peak = 0.0; foreach (Flow flow in Flows) if (flow.Peak > peak) peak = flow.Peak; return peak; } } } namespace TraceWizard.Logging.Adapters { public class LogAdapterFactory : AdapterFactory { public override Adapter GetAdapter(string dataSource) { string extension = System.IO.Path.GetExtension(dataSource).ToLower().Trim('.'); switch (extension) { case (TwEnvironment.MeterMasterJetLogExtension): return new MeterMasterJetLogAdapter(); case (TwEnvironment.CsvLogExtension): case (TwEnvironment.TelematicsLogExtension): case (TwEnvironment.TextLogExtension): { var adapter = new MeterMasterCsvLogAdapter(); if (adapter.CanLoad(dataSource)) return adapter; } { var adapter = new ManuFloLogAdapter(); if (adapter.CanLoad(dataSource)) return adapter; } { var adapter = new TelematicsLogAdapter(); if (adapter.CanLoad(dataSource)) return adapter; } return null; } return null; } } public abstract class LogAdapter : Adapter { public LogAdapter() { } public abstract bool CanLoad(string dataSource); public abstract Logging.Log Load(string dataSource); } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using SharpShapes; namespace TestSharpShapes { [TestClass] public class UnitTestSquare { [TestMethod] public void TestSquareConstructor() { Square square = new Square(40); Assert.AreEqual(40, square.Width); Assert.AreEqual(40, square.Height); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestSquareConstructorSanityChecksWidth() { Square square = new Square(0); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestSquareConstructorSanityChecksWidthPositivity() { Square square = new Square(-1); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestSquareConstructorSanityChecksHeight() { Square square = new Square(0); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestSquareConstructorSanityChecksHeightPositivity() { Square square = new Square(-1); } [TestMethod] public void TestScaleSquare200Percent() { Square square = new Square(20); square.Scale(200); Assert.AreEqual(40, square.Width); Assert.AreEqual(40, square.Height); } [TestMethod] public void TestScaleSquare150Percent() { Square square = new Square(20); square.Scale(150); Assert.AreEqual((decimal)30, square.Width); Assert.AreEqual((decimal)30, square.Height); } [TestMethod] public void TestScaleSquare100Percent() { Square square = new Square(20); square.Scale(100); Assert.AreEqual(20, square.Width); Assert.AreEqual(20, square.Height); } [TestMethod] public void TestScaleSquare37Percent() { Square square = new Square(20); square.Scale(37); Assert.AreEqual((decimal)7.4, square.Width); Assert.AreEqual((decimal)7.4, square.Height); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestScaleSquareTo0Percent() { Square square = new Square(20); square.Scale(0); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestScaleSquareToNegativePercent() { Square square = new Square(20); square.Scale(-5); } [TestMethod] public void TestSidesCount() { Square square = new Square(20); Assert.AreEqual(4, square.SidesCount); } [TestMethod] public void TestSquareArea() { Square square = new Square(20); Assert.AreEqual(400, square.Area()); } [TestMethod] public void TestBiggerSquareArea() { Square square = new Square(100); Assert.AreEqual(10000, square.Area()); } [TestMethod] public void TestSquarePerimeter() { Square square = new Square(20); Assert.AreEqual(80, square.Perimeter()); } [TestMethod] public void TestBiggerSquarePerimeter() { Square square = new Square(100); Assert.AreEqual(400, square.Perimeter()); } [TestMethod] public void TestDefaultColor() { Square shape = new Square(20); Assert.AreEqual(System.Drawing.Color.Bisque, shape.FillColor); Assert.AreEqual(System.Drawing.Color.Tomato, shape.BorderColor); } } }
namespace Entoarox.ShopExpander { internal class Reference { /********* ** Accessors *********/ public string Owner; public int Item; public int Amount; public string Conditions = null; /********* ** Public methods *********/ public Reference(string owner, int item, int amount, string conditions = null) { this.Owner = owner; this.Item = item; this.Amount = amount; this.Conditions = conditions; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Linq08_6_IQueryable { class Program { private static void TestIEnumerable() { using (NorthwindEntities ctx = new NorthwindEntities()) { IEnumerable<Employee> emps = ctx.Employees; int count = emps.Where(x => x.EmployeeID == 2).Count(); Console.WriteLine("Count={0}", count); } } private static void TestIQueryable() { using (NorthwindEntities ctx = new NorthwindEntities()) { IQueryable<Employee> emps = ctx.Employees; int count = emps.Where(x => x.EmployeeID == 2).Count(); Console.WriteLine("Count={0}", count); } } private static void TestVar() { using (NorthwindEntities ctx = new NorthwindEntities()) { //如果是用 var 宣告, 則 emps 變數的型別會是 IQueryable // System.Data.Entity.DbSet<Linq08_6_IQueryable.Employee> var emps = ctx.Employees; int count = emps.Where(x => x.EmployeeID == 2).Count(); Console.WriteLine("Count={0}", count); } } static void Main(string[] args) { TestIEnumerable(); TestIQueryable(); TestVar(); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DBDiff.Schema.SQLServer.Generates.Model; using DBDiff.Schema.Model; namespace DBDiff.Schema.SQLServer.Generates.Compare { internal class CompareUsers : CompareBase<User> { } }
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; //using WebSim.Application.Interfaces; using WebSim.Domain.Common; using WebSim.Domain.CoreIdentity; using WebSim.Domain.Customers; using WebSim.Domain.Orders; using WebSim.Domain.Products; using WebSim.Persistence.CoreIdentity; using WebSim.Persistence.Customers; using WebSim.Persistence.Orders; using WebSim.Persistence.Products; namespace WebSim.Persistence { public class DatabaseService : IdentityDbContext<ApplicationUser, ApplicationRole, string> { public DatabaseService(DbContextOptions<DatabaseService> options) : base(options) { } public string CurrentUserId { get; set; } public DbSet<Customer> Customers { get; set; } public DbSet<ProductCategory> ProductCategories { get; set; } public DbSet<Product> Products { get; set; } public DbSet<Order> Orders { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfiguration(new ApplicationUserConfiguration()); modelBuilder.ApplyConfiguration(new ApplicationRoleConfiguration()); modelBuilder.Entity<IdentityUserRole<string>>(entity => { entity.ToTable(name: "ApplicationUserRoles"); }); modelBuilder.Entity<IdentityRoleClaim<string>>(entity => { entity.ToTable(name: "ApplicationRoleClaims"); }); modelBuilder.Entity<IdentityUserClaim<string>>(entity => { entity.ToTable(name: "ApplicationUserClaims"); }); modelBuilder.Entity<IdentityUserLogin<string>>(entity => { entity.ToTable(name: "ApplicationUserLogins"); }); modelBuilder.Entity<IdentityUserToken<string>>(entity => { entity.ToTable(name: "ApplicationUserTokens"); }); modelBuilder.ApplyConfiguration(new CustomerConfiguration()); modelBuilder.ApplyConfiguration(new ProductCategoryConfiguration()); modelBuilder.ApplyConfiguration(new ProductConfiguration()); modelBuilder.ApplyConfiguration(new OrderConfiguration()); modelBuilder.ApplyConfiguration(new OrderDetailConfiguration()); } public int Save() { return SaveChanges(); } public override int SaveChanges() { UpdateAuditEntities(); return base.SaveChanges(); } public override int SaveChanges(bool acceptAllChangesOnSuccess) { UpdateAuditEntities(); return base.SaveChanges(acceptAllChangesOnSuccess); } public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken)) { UpdateAuditEntities(); return base.SaveChangesAsync(cancellationToken); } public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken)) { UpdateAuditEntities(); return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); } private void UpdateAuditEntities() { var modifiedEntries = ChangeTracker.Entries() .Where(x => x.Entity is IAuditableEntity && (x.State == EntityState.Added || x.State == EntityState.Modified)); foreach (var entry in modifiedEntries) { var entity = (IAuditableEntity)entry.Entity; DateTime now = DateTime.UtcNow; if (entry.State == EntityState.Added) { entity.CreatedDate = now; entity.CreatedBy = CurrentUserId; } else { base.Entry(entity).Property(x => x.CreatedBy).IsModified = false; base.Entry(entity).Property(x => x.CreatedDate).IsModified = false; } entity.UpdatedDate = now; entity.UpdatedBy = CurrentUserId; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using RWCustom; using Rainbow.Enum; using Rainbow.CreatureOverhaul; namespace Rainbow.CreatureAddition { public class Hornest : Creature { public Hornest(AbstractCreature abstractCreature, World world) : base(abstractCreature, world) { this.size = -1f; this.bodyChunks = new BodyChunk[2]; this.bodyChunks[0] = new BodyChunk(this, 0, new Vector2(0f, 0f), 30f, 5f); this.bodyChunks[1] = new BodyChunk(this, 1, new Vector2(0f, -50f), 0.1f, 5f); this.bodyChunkConnections = new BodyChunkConnection[1]; this.bodyChunkConnections[0] = new BodyChunkConnection(this.bodyChunks[0], this.bodyChunks[1], 100f, BodyChunkConnection.Type.Pull, 0.8f, -1f); base.airFriction = 0.999f; base.gravity = 1.0f; this.bounce = 0.01f; this.surfaceFriction = 0.999f; this.collisionLayer = 1; base.waterFriction = 0.96f; base.buoyancy = 0.96f; this.bees = new List<Hornest.Bee>(); this.attachedBees = new List<Hornest.AttachedBee>(); this.fruits = new List<AbstractCreature>(); this.fruitOffset = new Dictionary<AbstractCreature, Vector2>(); this.released = false; int seed = UnityEngine.Random.seed; UnityEngine.Random.seed = abstractPhysicalObject.ID.RandomSeed; UnityEngine.Random.seed = seed; this.hoverOffsetCounter = UnityEngine.Random.value * 100f; this.hoverPhase = 10000 + UnityEngine.Random.Range(0, 4); } public float size; public override void InitiateGraphicsModule() { if (base.graphicsModule == null && this.size > 0f) { base.graphicsModule = new HornestGraphics(this); } } /* public override Vector2 VisionPoint { get { return this.bodyChunks[0].pos - new Vector2(0f, -40f); } }*/ public override float VisibilityBonus { get { return -0.8f; } } public override void NewRoom(Room newRoom) { base.NewRoom(newRoom); this.Initiate(); } private void Initiate() { UnityEngine.Random.seed = this.abstractCreature.ID.RandomSeed; int num = Mathf.RoundToInt(Mathf.Pow(UnityEngine.Random.Range(12f, 37f), 0.75f)); /* if (base.abstractCreature.spawnData != null && base.abstractCreature.spawnData.Length > 2) { string text = base.abstractCreature.spawnData.Substring(1, base.abstractCreature.spawnData.Length - 2); try { num = int.Parse(text); } catch { num = 50; } }*/ this.plantTile = this.room.LocalCoordinateOfNode(base.abstractCreature.pos.abstractNode).Tile; IntVector2 b = this.room.ShorcutEntranceHoleDirection(this.plantTile); this.stickOutDir = b.ToVector2(); this.plantSpot = this.room.MiddleOfTile(this.room.LocalCoordinateOfNode(base.abstractCreature.pos.abstractNode)) + this.stickOutDir * 30f; IntVector2 intVector = this.plantTile; List<IntVector2> list = new List<IntVector2>(); bool flag = false; int num2 = 0; while (!this.room.GetTile(intVector + b).Solid && this.room.IsPositionInsideBoundries(intVector + b)) { intVector += b; if (flag) { list.Add(intVector); } flag = !flag; num2++; if (num2 >= num) { //big break; } } if (list.Count < 2) { list.Insert(0, this.plantTile); } this.tilePositions = list.ToArray(); this.capSpot = this.room.MiddleOfTile(intVector) + this.stickOutDir * 10f; this.size = Vector2.Distance(this.plantSpot, this.capSpot); this.bodyChunkConnections[0] = new BodyChunkConnection(this.bodyChunks[0], this.bodyChunks[1], this.size, BodyChunkConnection.Type.Pull, 0.8f, -1f); this.bodyChunks[1].HardSetPosition(this.plantSpot); this.bodyChunks[0].pos = this.capSpot; this.justOutOfShortcut = true; this.InitiateGraphicsModule(); this.room.drawableObjects.Add(base.graphicsModule); for (int l = 0; l < this.room.game.cameras.Length; l++) { if (this.room.game.cameras[l].room == this.room) { this.room.game.cameras[l].NewObjectInRoom(base.graphicsModule); } } } public Vector2 stickOutDir; //public bool planted; private int plantCount; public Vector2 plantSpot; public IntVector2 plantTile; public IntVector2[] tilePositions; public Vector2 capSpot; public void AddFruit() { WorldCoordinate coord = this.room.GetWorldCoordinate(this.bodyChunks[0].pos); AbstractCreature abstractCreature = new AbstractCreature(this.room.world, StaticWorld.creatureTemplates[(int)EnumExt_Rainbow.HornestFruit], null, coord, this.room.game.GetNewID()); this.room.abstractRoom.AddEntity(abstractCreature); //Hornest creature = new Hornest(abstractCreature, this.room.world); //this.room.AddObject(creature); //creature.abstractCreature.abstractAI.RealAI = new HornestAI(abstractCreature, this.room.world); //creature.abstractCreature.RealizeInRoom(); if (this.room != null) { abstractCreature.Realize(); abstractCreature.RealizeInRoom(); } this.fruits.Add(abstractCreature); this.fruitOffset.Add(abstractCreature, new Vector2(UnityEngine.Random.Range(-60f, 60f), UnityEngine.Random.Range(-10f, -30f))); //(abstractCreature.realizedCreature as HornestFruit).nest = this; } public void RemoveFruit(HornestFruit fruit) { this.fruitOffset.Remove(fruit.abstractCreature); this.fruits.Remove(fruit.abstractCreature); fruit.nest = null; this.angry += 0.8f; if (fruit.attacker != null) { this.AI.tracker.SeeCreature(fruit.attacker.abstractCreature); this.AI.targetCreature = fruit.attacker; } } public bool justOutOfShortcut; public override void SpitOutOfShortCut(IntVector2 pos, Room newRoom, bool spitOutAllSticks) { base.SpitOutOfShortCut(pos, newRoom, spitOutAllSticks); this.justOutOfShortcut = true; } public override void Update(bool eu) { base.Update(eu); if (this.room == null || this.enteringShortCut != null) { return; } if (this.justOutOfShortcut && this.fruits.Count < 1) { for (int i = Mathf.FloorToInt(Mathf.Pow(UnityEngine.Random.Range(2, 12), 0.5f)); i > 0; i--) { this.AddFruit(); } this.justOutOfShortcut = false; } /* if (!planted) { if(this.plantTile != this.room.GetTilePosition(this.bodyChunks[1].pos + new Vector2(0f, 10f))) { this.plantCount = 0; this.plantTile = this.room.GetTilePosition(this.bodyChunks[1].pos + new Vector2(0f, 10f)); } else { plantCount++; } if (plantCount > 200) { this.planted = true; this.plantSpot = this.bodyChunks[1].pos; this.bodyChunks[1].HardSetPosition(this.plantSpot); this.bodyChunks[0].pos.y += 60f; for (int i = Mathf.FloorToInt(Mathf.Pow(UnityEngine.Random.Range(2, 12), 0.5f)); i > 0; i--) { this.AddFruit(); } } return; } //this.bodyChunks[1].pos = this.plantSpot; */ this.bodyChunks[1].HardSetPosition(this.plantSpot); this.bodyChunks[0].vel *= 0.5f; if (this.Consious) { if (this.grasps[0] == null && this.succFailCounter > 0) { this.succFailCounter--; } if (this.releaseBeesDelay > 0) { this.releaseBeesDelay--; } else { this.released = false; } if (this.grasps[0] != null) { this.Succ(); } this.Act(); base.abstractCreature.abstractAI.RealAI.Update(); } else { if (this.grasps[0] != null) { this.ReleaseGrasp(0); } } if (this.fruits.Count > 0) { this.HoldFruit(); } if (this.AI.behavior != HornestAI.Behavior.EscapeRain) { this.bodyChunks[0].HardSetPosition(this.capSpot); //this.bodyChunks[0].vel.y += 0.5f; } else { this.bodyChunks[0].vel.y = 0f; this.bodyChunks[0].vel.x = 0f; this.bodyChunks[0].pos.y -= 0.1f; } } public void Act() { switch (this.AI.behavior) { case HornestAI.Behavior.Idle: case HornestAI.Behavior.Anticipate: case HornestAI.Behavior.Digest: break; case HornestAI.Behavior.Release: break; case HornestAI.Behavior.EscapeRain: break; } } public void HoldFruit() { foreach (AbstractCreature fruit in this.fruits) { if (fruit.realizedCreature != null) { HornestFruit real = fruit.realizedCreature as HornestFruit; real.nest = this; real.bodyChunks[0].pos = Vector2.Lerp(real.bodyChunks[0].pos, this.bodyChunks[0].pos + this.fruitOffset[fruit], 0.05f); real.bodyChunks[0].vel *= 0.5f; } } } public int[,] floodFillMatrix; private IntVector2 fillMatrixOffset; public List<IntVector2> possibleDestinations; public List<IntVector2> swarmTrail; public int releaseBeesCounter; public int releaseBeesDelay; public bool released; public void ReleaseBees() { if (this.releaseBeesDelay > 0) { return; } float num = float.MaxValue; IntVector2 intVector = this.room.GetTilePosition(this.bodyChunks[0].pos); for (int i = 0; i < 5; i++) { float num2 = Vector2.Distance(base.firstChunk.pos, this.room.MiddleOfTile(this.room.GetTilePosition(base.firstChunk.pos) + Custom.eightDirectionsAndZero[i])) + Vector2.Distance(base.firstChunk.pos, this.room.MiddleOfTile(this.room.GetTilePosition(base.firstChunk.lastPos) + Custom.eightDirectionsAndZero[i])); if (this.room.GetTile(this.room.GetTilePosition(base.firstChunk.pos) + Custom.eightDirectionsAndZero[i]).Terrain == Room.Tile.TerrainType.Air && num2 < num) { intVector = this.room.GetTilePosition(base.firstChunk.pos) + Custom.eightDirectionsAndZero[i]; num = num2; } } if (this.room.GetTile(intVector).Solid) { return; } this.swarmPos = new Vector2?(base.firstChunk.pos); Debug.Log("RELEASE BEES"); this.releaseBeesDelay = UnityEngine.Random.Range(900, 1500); //base.ChangeCollisionLayer(0); //this.canBeHitByWeapons = false; this.floodFillMatrix = new int[17, 17]; IntVector2 b = new IntVector2(this.floodFillMatrix.GetLength(0) / 2, this.floodFillMatrix.GetLength(1) / 2); this.fillMatrixOffset = intVector - b; for (int j = 0; j < this.floodFillMatrix.GetLength(0); j++) { for (int k = 0; k < this.floodFillMatrix.GetLength(1); k++) { if (!Custom.DistLess(new Vector2((float)j, (float)k), b.ToVector2(), (float)this.floodFillMatrix.GetLength(0) / 2f) || (this.room.water && intVector.y - b.y + k <= this.room.defaultWaterLevel) || (this.room.GetTile(intVector.x - b.x + j, intVector.y - b.y + k).Terrain != Room.Tile.TerrainType.Air && this.room.GetTile(intVector.x - b.x + j, intVector.y - b.y + k).Terrain != Room.Tile.TerrainType.Floor)) { this.floodFillMatrix[j, k] = -1; } } } List<IntVector2> list = new List<IntVector2> { intVector }; List<IntVector2> list2 = list; this.possibleDestinations = new List<IntVector2>(); this.SetFloodFillMatrixValue(intVector.x, intVector.y, 1); int num3 = 0; while (list2.Count > 0 && num3 < 10000) { int num4 = UnityEngine.Random.Range(0, list2.Count); IntVector2 a = list2[num4]; list2.RemoveAt(num4); int floodFillMatrixValue = this.GetFloodFillMatrixValue(a.x, a.y); for (int l = 0; l < 4; l++) { if (this.GetFloodFillMatrixValue(a.x + Custom.fourDirections[l].x, a.y + Custom.fourDirections[l].y) == 0) { this.SetFloodFillMatrixValue(a.x + Custom.fourDirections[l].x, a.y + Custom.fourDirections[l].y, floodFillMatrixValue + 1); list2.Add(a + Custom.fourDirections[l]); this.possibleDestinations.Add(a + Custom.fourDirections[l]); } } num3++; } if (this.possibleDestinations.Count == 0) { this.possibleDestinations = null; return; } list = new List<IntVector2> { intVector }; this.swarmTrail = list; for (int m = 10; m > 0; m--) { this.AddDestinationBee(); } this.releaseBeesCounter = UnityEngine.Random.Range(25, 35); this.room.PlaySound(SoundID.Spore_Bees_Emerge, base.firstChunk); } public void AddDestinationBee() { if (this.possibleDestinations == null || this.possibleDestinations.Count == 0) { return; } Hornest.Bee bee = this.AddBee(Hornest.Bee.Mode.FollowPath); int num = UnityEngine.Random.Range(0, this.possibleDestinations.Count); for (int i = 0; i < 10; i++) { int num2 = UnityEngine.Random.Range(0, this.possibleDestinations.Count); if (this.GetFloodFillMatrixValue(this.possibleDestinations[num2].x, this.possibleDestinations[num2].y) > this.GetFloodFillMatrixValue(this.possibleDestinations[num].x, this.possibleDestinations[num].y)) { num = num2; } } List<IntVector2> list = new List<IntVector2> { this.possibleDestinations[num] }; List<IntVector2> list2 = list; IntVector2 intVector = this.possibleDestinations[num]; this.possibleDestinations.RemoveAt(num); if (this.possibleDestinations.Count == 0) { for (int j = 0; j < this.floodFillMatrix.GetLength(0); j++) { for (int k = 0; k < this.floodFillMatrix.GetLength(1); k++) { if (this.floodFillMatrix[j, k] > 0) { this.possibleDestinations.Add(new IntVector2(j, k) + this.fillMatrixOffset); } } } } for (int l = 0; l < 100; l++) { int num3 = int.MaxValue; int num4 = UnityEngine.Random.Range(0, 4); for (int m = 0; m < 4; m++) { int floodFillMatrixValue = this.GetFloodFillMatrixValue(intVector.x + Custom.fourDirections[m].x, intVector.y + Custom.fourDirections[m].y); if (floodFillMatrixValue > 0 && floodFillMatrixValue < num3) { num4 = m; num3 = floodFillMatrixValue; } } intVector += Custom.fourDirections[num4]; if (this.GetFloodFillMatrixValue(intVector.x, intVector.y) < 2) { break; } list2.Add(intVector); } for (int n = 0; n < this.swarmTrail.Count; n++) { list2.Add(this.swarmTrail[n]); } bee.travelDist = list2.Count; if (list2.Count > 2) { int num5 = list2.Count / 2; if (this.room.VisualContact(bee.pos, this.room.MiddleOfTile(list2[num5]))) { for (int num6 = list2.Count - 1; num6 > num5; num6--) { list2.RemoveAt(num5); } } } bee.path = list2; } public int GetFloodFillMatrixValue(int x, int y) { x -= this.fillMatrixOffset.x; y -= this.fillMatrixOffset.y; if (x < 0 || x >= this.floodFillMatrix.GetLength(0) || y < 0 || y >= this.floodFillMatrix.GetLength(1)) { return -1; } return this.floodFillMatrix[x, y]; } public void SetFloodFillMatrixValue(int x, int y, int value) { x -= this.fillMatrixOffset.x; y -= this.fillMatrixOffset.y; if (x < 0 || x >= this.floodFillMatrix.GetLength(0) || y < 0 || y >= this.floodFillMatrix.GetLength(1)) { return; } this.floodFillMatrix[x, y] = value; } public float succProgress; public int succWait; public int succFailCounter; public void Succ() { if (this.grasps[0] == null || !(this.grasps[0].grabbed is Creature) || succFailCounter > 40) { this.ReleaseGrasp(0); succProgress = 0f; return; } if (succWait > 0) { succWait--; Creature crt0 = this.grasps[0].grabbed as Creature; if (!Custom.DistLess(this.bodyChunks[0].pos, crt0.mainBodyChunk.pos, this.bodyChunks[0].rad * 1.5f)) { this.succFailCounter++; } for (int j = 0; j < crt0.bodyChunks.Length; j++) { crt0.bodyChunks[j].vel *= 0.8f; crt0.bodyChunks[j].pos = Vector2.Lerp(crt0.bodyChunks[j].pos, this.bodyChunks[0].pos, 0.2f); } return; } Creature crt = this.grasps[0].grabbed as Creature; succProgress += 0.05f; for (int j = 0; j < crt.bodyChunks.Length; j++) { crt.bodyChunks[j].collideWithTerrain = false; crt.bodyChunks[j].vel *= 1f - this.succProgress; crt.bodyChunks[j].pos = Vector2.Lerp(crt.bodyChunks[j].pos, this.bodyChunks[0].pos, this.succProgress / 3); } if (crt.graphicsModule != null && crt.graphicsModule.bodyParts != null) { for (int k = 0; k < crt.graphicsModule.bodyParts.Length; k++) { crt.graphicsModule.bodyParts[k].vel *= 1f - this.succProgress; crt.graphicsModule.bodyParts[k].pos = Vector2.Lerp(crt.graphicsModule.bodyParts[k].pos, this.bodyChunks[0].pos, this.succProgress / 3); } } if (this.succProgress >= 1f) { IRainbowState cs = crt.abstractCreature.state as IRainbowState; //Digest! this.AI.digesting = cs.boneLeft * 60; //this.room.PlaySound(SoundID.Daddy_Digestion_Init, this.bodyChunks[0]); this.ReleaseGrasp(0); this.succProgress = 0f; crt.Die(); crt.Destroy(); } } public override bool SpearStick(Weapon source, float dmg, BodyChunk chunk, Appendage.Pos appPos, Vector2 direction) { this.room.PlaySound(SoundID.Lizard_Head_Shield_Deflect, base.mainBodyChunk); return false; } public override void Violence(BodyChunk source, Vector2? directionAndMomentum, BodyChunk hitChunk, Appendage.Pos hitAppendage, DamageType type, float damage, float stunBonus) { if (hitChunk.index == 1) { return; } if (type == Creature.DamageType.Bite || type == Creature.DamageType.Stab) { type = Creature.DamageType.Blunt; } //Insert angry if (directionAndMomentum != null) { hitChunk.vel += directionAndMomentum.Value / 30f; } if (source != null && source.owner is Rock) { this.angry += 0.3f; //this.room.PlaySound(SoundID.Rock_Bounce_Off_Creature_Shell, hitChunk); } else { this.angry += 0.4f * damage; } base.Violence(source, directionAndMomentum, hitChunk, hitAppendage, type, damage, stunBonus); } public override void Collide(PhysicalObject otherObject, int myChunk, int otherChunk) { if (myChunk == 1) { return; } base.Collide(otherObject, myChunk, otherChunk); if (otherObject is Creature) { if (otherObject.bodyChunks[otherChunk].pos.y < this.bodyChunks[0].pos.y - this.bodyChunks[0].rad && (this.AI.behavior != HornestAI.Behavior.Digest && this.AI.behavior != HornestAI.Behavior.EscapeRain)) { if ((otherObject as Creature).Template.type != CreatureTemplate.Type.GreenLizard && (otherObject as Creature).Template.type != CreatureTemplate.Type.RedLizard && !(otherObject as Creature).Template.IsVulture) { if (otherObject is HornestFruit || this.succFailCounter > 0) { return; } this.Grab(otherObject, 0, otherChunk, Grasp.Shareability.CanNotShare, UnityEngine.Random.value * 0.4f + 0.2f, true, false); this.succWait = (int)otherObject.TotalMass * 200; this.succFailCounter = 0; if (otherObject is Player) { succWait = 500; } } } } } public static bool NestInterested(CreatureTemplate.Type tp) { return tp != CreatureTemplate.Type.Overseer && tp != CreatureTemplate.Type.PoleMimic; } public Vector2 HoverOffset(int group) { switch ((group + this.hoverPhase) % 4) { case 0: return new Vector2(-Mathf.Lerp(-25f, 25f, Mathf.PingPong(this.hoverOffsetCounter * 100f, 100f) / 100f), Mathf.Lerp(-15f, 15f, Mathf.PingPong(this.hoverOffsetCounter * 100f, 100f) / 100f)); case 1: return new Vector2(-Mathf.Lerp(-25f, 25f, Mathf.PingPong(this.hoverOffsetCounter * 100f, 100f) / 100f), -Mathf.Lerp(-15f, 15f, Mathf.PingPong(this.hoverOffsetCounter * 100f, 100f) / 100f)); case 2: return new Vector2(Mathf.Lerp(-25f, 25f, Mathf.PingPong(this.hoverOffsetCounter * 100f, 100f) / 100f), -Mathf.Lerp(-15f, 15f, Mathf.PingPong(this.hoverOffsetCounter * 100f, 100f) / 100f)); default: return new Vector2(Mathf.Lerp(-25f, 25f, Mathf.PingPong(this.hoverOffsetCounter * 100f, 100f) / 100f), Mathf.Lerp(-15f, 15f, Mathf.PingPong(this.hoverOffsetCounter * 100f, 100f) / 100f)); } } public List<Hornest.Bee> bees; public List<Hornest.AttachedBee> attachedBees; private Vector2? swarmPos; public float hoverOffsetCounter; private readonly int hoverPhase; public List<AbstractCreature> fruits; public Dictionary<AbstractCreature, Vector2> fruitOffset; public HornestAI AI; public float angry { get { return this.AI.angry; } set { this.AI.angry = value; } } public Hornest.Bee AddBee(Hornest.Bee.Mode mode) { Vector2 beePos = Vector2.Lerp(this.bodyChunks[0].pos, this.bodyChunks[1].pos, UnityEngine.Random.Range(0.2f, 0.8f)); beePos += Custom.RNV() * UnityEngine.Random.value * 10f; Hornest.Bee bee = new Hornest.Bee(this, beePos, this.firstChunk.vel, mode); this.bees.Add(bee); this.room.AddObject(bee); return bee; } public void RemoveBee(Hornest.Bee beeToRemove) { for (int i = this.bees.Count - 1; i >= 0; i--) { if (this.bees[i] == beeToRemove) { this.bees[i].owner = null; this.bees.RemoveAt(i); } } } public class Bee : UpdatableAndDeletable, IDrawable, Explosion.IReactToExplosions { public Bee(Hornest owner, Vector2 pos, Vector2 vel, Hornest.Bee.Mode initMode) { this.owner = owner; this.pos = pos; this.lastPos = pos; this.lastLastPos = this.lastPos; this.vel = vel; this.hoverPos = pos; this.angry = true; this.ChangeMode(initMode); this.flyDir = Custom.RNV(); this.blink = UnityEngine.Random.value; this.lastBlink = this.blink; this.flySpeed = Mathf.Lerp(0.1f, 1.1f, UnityEngine.Random.value); this.group = UnityEngine.Random.Range(0, 4); this.life = 1f; this.lifeTime = Mathf.Lerp(300f, 600f, Custom.ClampedRandomVariation(0.5f, 0.5f, 0.3f)); this.targetCreature = this.owner.AI.targetCreature; } public Creature targetCreature; public void DebugShowPath() { this.dbSprts = new List<DebugSprite>(); for (int i = 0; i < this.path.Count; i++) { DebugSprite debugSprite = new DebugSprite(this.room.MiddleOfTile(this.path[i]), new FSprite("pixel", true), this.room); this.room.AddObject(debugSprite); debugSprite.sprite.scale = 16f; debugSprite.sprite.alpha = 0.4f; this.dbSprts.Add(debugSprite); } } public override void Update(bool eu) { base.Update(eu); this.inModeCounter++; this.lastLastLastPos = this.lastLastPos; this.lastLastPos = this.lastPos; this.lastPos = this.pos; this.pos += this.vel; this.vel *= 0.9f; this.flyDir.Normalize(); this.lastFlyDir = this.flyDir; this.vel += this.flyDir * this.flySpeed; this.flyDir += Custom.RNV() * UnityEngine.Random.value * ((this.mode != Hornest.Bee.Mode.LostHive) ? 0.6f : 1.2f); this.lastBlink = this.blink; this.blink += this.blinkFreq; this.lastBoostTrail = this.boostTrail; this.boostTrail = Mathf.Max(0f, this.boostTrail - 0.3f); SharedPhysics.TerrainCollisionData terrainCollisionData = new SharedPhysics.TerrainCollisionData(this.pos, this.lastPos, this.vel, 1f, new IntVector2(0, 0), true); SharedPhysics.VerticalCollision(this.room, terrainCollisionData); SharedPhysics.HorizontalCollision(this.room, terrainCollisionData); this.pos = terrainCollisionData.pos; this.vel = terrainCollisionData.vel; if (this.mode != Hornest.Bee.Mode.BuzzAroundHive || this.mode != Hornest.Bee.Mode.GetBackToHive) { this.life -= 1f / this.lifeTime; } if (this.life < 0.2f * UnityEngine.Random.value) { this.vel.y -= Mathf.InverseLerp(0.2f, 0f, this.life); if (this.life <= 0f && (terrainCollisionData.contactPoint.y < 0 || this.pos.y < -100f)) { this.Destroy(); } this.flySpeed = Mathf.Min(this.flySpeed, Mathf.Max(0f, this.life) * 3f); if (this.room.water && this.pos.y < this.room.FloatWaterLevel(this.pos.x)) { this.Destroy(); } return; } if (this.room.water && this.pos.y < this.room.FloatWaterLevel(this.pos.x)) { this.pos.y = this.room.FloatWaterLevel(this.pos.x) + 1f; this.vel.y += 1f; this.flyDir.y += 1f; } if (terrainCollisionData.contactPoint.x != 0) { this.flyDir.x -= terrainCollisionData.contactPoint.x; } if (terrainCollisionData.contactPoint.y != 0) { this.flyDir.y -= (float)terrainCollisionData.contactPoint.y; } if (this.owner != null) { if (UnityEngine.Random.value < Mathf.Pow(this.owner.angry, 7f) / 40f) { this.angry = true; } if (UnityEngine.Random.value < 0.025f && (this.mode == Hornest.Bee.Mode.BuzzAroundHive || this.mode == Hornest.Bee.Mode.GetBackToHive) && (!Custom.DistLess(this.pos, this.owner.firstChunk.pos, 300f) || this.owner.room != this.room)) { this.LoseOwner(); } } if (this.huntChunk != null && this.mode != Hornest.Bee.Mode.Hunt) { this.ChangeMode(Hornest.Bee.Mode.Hunt); } if (this.mode != Hornest.Bee.Mode.LostHive && this.owner == null) { this.LoseOwner(); } switch (this.mode) { case Hornest.Bee.Mode.LostHive: this.blinkFreq = Custom.LerpAndTick(this.blinkFreq, 0.0333333351f, 0.05f, 0.0333333351f); this.flySpeed = Custom.LerpAndTick(this.flySpeed, 0.9f, 0.08f, UnityEngine.Random.value / 30f); if (UnityEngine.Random.value < 0.2f && (terrainCollisionData.contactPoint.x != 0 || terrainCollisionData.contactPoint.y != 0)) { this.Destroy(); } break; case Hornest.Bee.Mode.BuzzAroundHive: case Hornest.Bee.Mode.GetBackToHive: { this.blinkFreq = Custom.LerpAndTick(this.blinkFreq, (!this.angry) ? 0f : 0.166666672f, 0.05f, 0.0125f); if (UnityEngine.Random.value < 0.0125f) { this.blinkFreq = Mathf.Max(this.blinkFreq, UnityEngine.Random.value / 30f); } float num = Mathf.InverseLerp(10f, Mathf.Min(15f + Vector2.Distance(this.owner.firstChunk.lastPos, this.owner.firstChunk.pos) * 10f, 150f), Vector2.Distance(this.pos, this.owner.firstChunk.pos)); if (UnityEngine.Random.value < 0.0025f) { this.ChangeMode(Hornest.Bee.Mode.GetBackToHive); } if ((terrainCollisionData.contactPoint.x != 0 || terrainCollisionData.contactPoint.y != 0) && (!Custom.DistLess(this.pos, this.owner.firstChunk.pos, 300f) || (UnityEngine.Random.value < 0.1f && !Custom.DistLess(this.pos, this.owner.firstChunk.pos, 50f) && !this.room.VisualContact(this.pos, this.owner.firstChunk.pos)))) { this.LoseOwner(); return; } if (num > 0f) { this.flySpeed = Custom.LerpAndTick(this.flySpeed, Mathf.Clamp(Vector2.Distance(this.owner.firstChunk.lastPos, this.owner.firstChunk.pos) * num * Mathf.InverseLerp(-1f, 1f, Vector2.Dot(this.flyDir.normalized, Custom.DirVec(this.pos, this.owner.firstChunk.pos))), 0.4f, 1.1f), 0.08f, UnityEngine.Random.value / 30f); this.flyDir += Custom.DirVec(this.pos, this.owner.firstChunk.pos) * num * UnityEngine.Random.value; } else if (this.mode == Hornest.Bee.Mode.GetBackToHive) { this.flySpeed = Custom.LerpAndTick(this.flySpeed, Mathf.Clamp(Mathf.InverseLerp(-1f, 1f, Vector2.Dot(this.flyDir.normalized, Custom.DirVec(this.pos, this.owner.firstChunk.pos))), 0.4f, 1.1f), 0.08f, UnityEngine.Random.value / 30f); this.flyDir = Vector2.Lerp(this.flyDir, Custom.DirVec(this.pos, this.owner.firstChunk.pos), 0.6f); this.vel *= 0.8f; if (Custom.DistLess(this.pos, this.owner.firstChunk.pos, 6f)) { this.Destroy(); } } break; } case Hornest.Bee.Mode.FollowPath: this.blinkFreq = Custom.LerpAndTick(this.blinkFreq, 0.333333343f, 0.05f, 0.0333333351f); this.vel *= 0.9f; if (this.inModeCounter > UnityEngine.Random.Range(0, 15)) { if (this.path == null || this.path.Count == 0) { this.ChangeMode(Hornest.Bee.Mode.Hover); this.path = null; return; } this.flySpeed = Custom.LerpAndTick(this.flySpeed, Custom.LerpMap(((float)this.travelDist + Vector2.Distance(this.room.MiddleOfTile(this.path[this.path.Count - 1]), this.pos) / 20f) / 2f, 2f, 20f, 0.4f, 3.2f, 0.6f), 0.08f, UnityEngine.Random.value / 30f); this.flyDir = Vector2.Lerp(this.flyDir, Custom.DirVec(this.pos, this.room.MiddleOfTile(this.path[this.path.Count - 1])), Mathf.Lerp(0.5f, 1f, UnityEngine.Random.value)); if (UnityEngine.Random.value < 0.0166666675f) { this.room.PlaySound(SoundID.Spore_Bee_Angry_Buzz, this.pos, Custom.LerpMap(this.life, 0f, 0.25f, 0.1f, 0.5f) + UnityEngine.Random.value * 0.5f, Custom.LerpMap(this.life, 0f, 0.5f, 0.8f, 0.9f, 0.4f)); } if (this.room.GetTilePosition(this.pos) == this.path[this.path.Count - 1]) { this.path.RemoveAt(this.path.Count - 1); } if (this.path.Count > 1) { int num2 = UnityEngine.Random.Range(1, this.path.Count); if (this.room.VisualContact(this.pos, this.room.MiddleOfTile(this.path[num2]))) { for (int i = this.path.Count - 1; i > num2; i--) { this.path.RemoveAt(num2); } } } if ((UnityEngine.Random.value < 0.05f && (terrainCollisionData.contactPoint.x != 0 || terrainCollisionData.contactPoint.y != 0)) || (this.room.water && this.pos.y < this.room.FloatWaterLevel(this.pos.x) + 5f)) { this.ChangeMode(Hornest.Bee.Mode.Hover); this.path = null; return; } } break; case Hornest.Bee.Mode.Hover: this.vel *= 0.82f; this.flySpeed = 0f; this.vel += Vector2.ClampMagnitude(this.hoverPos + this.owner.HoverOffset(this.group) - this.pos, 60f) / 20f * 3f; this.flyDir += this.vel * 0.5f; this.vel += Custom.RNV() * 0.3f; this.flyDir.y += 0.75f; this.blinkFreq = Custom.LerpAndTick(this.blinkFreq, 0.166666672f, 0.05f, 0.0333333351f); if (this.blink % 4f > (float)this.group) { this.blink -= 0.01f; } if (UnityEngine.Random.value < 0.0025f) { this.room.AddObject(new Hornest.BeeSpark(this.pos)); } if (UnityEngine.Random.value < 0.0166666675f) { this.room.PlaySound(SoundID.Spore_Bee_Angry_Buzz, this.pos, Custom.LerpMap(this.life, 0f, 0.25f, 0.1f, 0.5f) + UnityEngine.Random.value * 0.5f, Custom.LerpMap(this.life, 0f, 0.5f, 0.8f, 0.9f, 0.4f)); } if (this.owner.bees.Count > 1) { Hornest.Bee bee = this.owner.bees[UnityEngine.Random.Range(0, this.owner.bees.Count)]; if (bee != this && (bee.mode == Hornest.Bee.Mode.Hover || bee.huntChunk != null) && Custom.DistLess(this.pos, bee.pos, (bee.mode != Hornest.Bee.Mode.Hover || bee.huntChunk != null) ? 300f : 60f) && this.room.VisualContact(this.pos, bee.pos)) { if (bee.huntChunk != null && bee.huntChunk.owner.TotalMass > 0.3f && UnityEngine.Random.value < this.CareAboutChunk(bee.huntChunk)) { if (this.HuntChunkIfPossible(bee.huntChunk)) { return; } if (Vector2.Distance(bee.pos, bee.huntChunk.pos) < Vector2.Distance(this.hoverPos, bee.huntChunk.pos)) { this.hoverPos = bee.pos; } } else if (bee.mode == Hornest.Bee.Mode.Hover && UnityEngine.Random.value < 0.1f) { Vector2 vector = this.hoverPos; this.hoverPos = bee.hoverPos; bee.hoverPos = vector; } } } break; case Hornest.Bee.Mode.Hunt: { this.blinkFreq = Custom.LerpAndTick(this.blinkFreq, 0.333333343f, 0.05f, 0.0333333351f); float num3 = Mathf.InverseLerp(-1f, 1f, Vector2.Dot(this.flyDir.normalized, Custom.DirVec(this.pos, this.huntChunk.pos))); this.flySpeed = Custom.LerpAndTick(this.flySpeed, Mathf.Clamp(Mathf.InverseLerp(this.huntChunk.rad, this.huntChunk.rad + 110f, Vector2.Distance(this.pos, this.huntChunk.pos)) * 2f + num3, 0.4f, 2.2f), 0.08f, UnityEngine.Random.value / 30f); this.flySpeed = Custom.LerpAndTick(this.flySpeed, Custom.LerpMap(Vector2.Dot(this.flyDir.normalized, Custom.DirVec(this.pos, this.huntChunk.pos)), -1f, 1f, 0.4f, 1.8f), 0.08f, UnityEngine.Random.value / 30f); this.vel *= 0.9f; this.flyDir = Vector2.Lerp(this.flyDir, Custom.DirVec(this.pos, this.huntChunk.pos), UnityEngine.Random.value * 0.4f); if (UnityEngine.Random.value < 0.0333333351f) { this.room.PlaySound(SoundID.Spore_Bee_Angry_Buzz, this.pos, Custom.LerpMap(this.life, 0f, 0.25f, 0.1f, 1f), Custom.LerpMap(this.life, 0f, 0.5f, 0.8f, 1.2f, 0.25f)); } if (UnityEngine.Random.value < 0.1f && this.lastBoostTrail <= 0f && num3 > 0.7f && Custom.DistLess(this.pos, this.huntChunk.pos, this.huntChunk.rad + 150f) && !Custom.DistLess(this.pos, this.huntChunk.pos, this.huntChunk.rad + 50f) && this.room.VisualContact(this.pos, this.huntChunk.pos)) { Vector2 a = Vector3.Slerp(Custom.DirVec(this.pos, this.huntChunk.pos), this.flyDir.normalized, 0.5f); float num4 = Vector2.Distance(this.pos, this.huntChunk.pos) - this.huntChunk.rad; Vector2 b = this.pos + a * num4; if (num4 > 30f && !this.room.GetTile(b).Solid && !this.room.PointSubmerged(b) && this.room.VisualContact(this.pos, b)) { this.boostTrail = 1f; this.pos = b; this.vel = a * 10f; this.flyDir = a; this.room.AddObject(new Hornest.BeeSpark(this.lastPos)); this.room.PlaySound(SoundID.Spore_Bee_Dash, this.lastPos); this.room.PlaySound(SoundID.Spore_Bee_Spark, this.pos, 0.2f, 1.5f); } } for (int j = 0; j < this.huntChunk.owner.bodyChunks.Length; j++) { if (Custom.DistLess(this.pos, this.huntChunk.owner.bodyChunks[j].pos, this.huntChunk.owner.bodyChunks[j].rad)) { this.Attach(this.huntChunk.owner.bodyChunks[j]); return; } } if (!Custom.DistLess(this.pos, this.huntChunk.pos, this.huntChunk.rad + 400f) || (UnityEngine.Random.value < 0.1f && this.huntChunk.submersion > 0.8f) || !this.room.VisualContact(this.pos, this.huntChunk.pos)) { this.huntChunk = null; this.ChangeMode(Hornest.Bee.Mode.Hover); return; } break; } } if (this.angry && this.huntChunk == null) { this.FindCreatureToHunt(); } } private float CareAboutChunk(BodyChunk chunk) { if (this.owner == null) { return 1f; } float num = Vector2.Distance(chunk.pos, this.owner.firstChunk.pos); if (this.owner.swarmPos != null) { num = Mathf.Min(num, Vector2.Distance(chunk.pos, this.owner.swarmPos.Value)); } if (num < 190f) { return 1f; } return Mathf.InverseLerp(Custom.LerpMap(chunk.owner.TotalMass, 0.3f, 2f, 191f, 420f, 0.45f), 190f, num); } private bool FindCreatureToHunt() { if (this.huntChunk != null) { return false; } for (int i = 0; i < targetCreature.bodyChunks.Length; i++) { if (Custom.DistLess(this.pos, targetCreature.bodyChunks[i].pos, targetCreature.bodyChunks[i].rad)) { this.Attach(targetCreature.bodyChunks[i]); return true; } } return this.HuntChunkIfPossible(targetCreature.bodyChunks[UnityEngine.Random.Range(0, targetCreature.bodyChunks.Length)]); /* if (UnityEngine.Random.value < 0.1f && this.owner != null && this.owner.attachedBees.Count > 0) { Hornest.AttachedBee attachedBee = this.owner.attachedBees[UnityEngine.Random.Range(0, this.owner.attachedBees.Count)]; if (!attachedBee.slatedForDeletetion && attachedBee.attachedChunk != null) { return this.HuntChunkIfPossible(attachedBee.attachedChunk.owner.bodyChunks[UnityEngine.Random.Range(0, attachedBee.attachedChunk.owner.bodyChunks.Length)]); } } return false;*/ } private bool HuntChunkIfPossible(BodyChunk potentialHuntChunk) { if (UnityEngine.Random.value > 0.2f + 0.8f * this.CareAboutChunk(potentialHuntChunk)) { return false; } if (potentialHuntChunk.submersion > 0.9f) { return false; } if (potentialHuntChunk.owner is Creature && !Hornest.NestInterested((potentialHuntChunk.owner as Creature).Template.type)) { return false; } if (potentialHuntChunk != null && Custom.DistLess(this.pos, potentialHuntChunk.pos, 300f) && this.room.VisualContact(this.pos, potentialHuntChunk.pos)) { this.huntChunk = potentialHuntChunk; this.ChangeMode(Hornest.Bee.Mode.Hunt); return true; } return false; } public void Attach(BodyChunk chunk) { if (base.slatedForDeletetion) { return; } Hornest.AttachedBee attachedBee = new Hornest.AttachedBee(this.owner, this.room, new AbstractPhysicalObject(this.room.world, AbstractPhysicalObject.AbstractObjectType.AttachedBee, null, this.room.GetWorldCoordinate(this.pos), this.room.game.GetNewID()), chunk, this.pos, Custom.DirVec(this.lastLastPos, this.pos), this.life, this.lifeTime, this.boostTrail > 0f); this.room.AddObject(attachedBee); if (this.owner != null) { this.owner.attachedBees.Add(attachedBee); } this.room.PlaySound(SoundID.Spore_Bee_Attach_Creature, chunk); this.Destroy(); } public void ChangeMode(Hornest.Bee.Mode newMode) { if (this.mode == newMode) { return; } if (newMode != Hornest.Bee.Mode.FollowPath) { if (newMode == Hornest.Bee.Mode.Hover) { this.hoverPos = this.room.MiddleOfTile(this.pos) + new Vector2(Mathf.Lerp(-9f, 9f, UnityEngine.Random.value), Mathf.Lerp(-9f, 9f, UnityEngine.Random.value)); if (this.room.water && this.room.PointSubmerged(this.hoverPos)) { this.hoverPos.y = this.room.FloatWaterLevel(this.hoverPos.x) + 5f; } this.angry = true; } } else { this.angry = true; } this.mode = newMode; this.inModeCounter = 0; } public void LoseOwner() { this.ChangeMode(Hornest.Bee.Mode.LostHive); if (this.owner != null) { this.owner.RemoveBee(this); } } public override void Destroy() { base.Destroy(); if (this.owner != null) { this.owner.RemoveBee(this); } } public void InitiateSprites(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam) { sLeaser.sprites = new FSprite[2]; sLeaser.sprites[0] = new FSprite("bee", true); sLeaser.sprites[1] = new FSprite("pixel", true); this.AddToContainer(sLeaser, rCam, null); } public void DrawSprites(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, float timeStacker, Vector2 camPos) { Vector2 vector = Vector2.Lerp(this.lastPos, this.pos, timeStacker); Vector2 vector2 = Vector2.Lerp(this.lastLastLastPos, this.lastLastPos, timeStacker); sLeaser.sprites[0].x = vector.x - camPos.x; sLeaser.sprites[0].y = vector.y - camPos.y; float num = Mathf.Lerp(this.lastBoostTrail, this.boostTrail, timeStacker); Vector2 v = Vector3.Slerp(Vector3.Slerp(this.lastFlyDir.normalized, this.flyDir.normalized, timeStacker), Custom.DirVec(vector2, vector), 0.5f + 0.5f * num); sLeaser.sprites[0].rotation = Custom.VecToDeg(v); float num2 = Custom.Decimal(Mathf.Lerp(this.lastBlink, this.blink, timeStacker)); float num3 = Mathf.InverseLerp(0f, 0.5f, this.life); if ((this.blinkFreq > 0f && num2 < 0.5f * num3) || num > 0f) { float num4 = Mathf.Clamp(Mathf.Sin(Mathf.InverseLerp(0f, 0.5f * num3, num2) * 3.14159274f), 0f, 1f); num4 = Mathf.Max(num4, num); sLeaser.sprites[1].x = vector.x - camPos.x; sLeaser.sprites[1].y = vector.y - camPos.y; sLeaser.sprites[1].rotation = Custom.AimFromOneVectorToAnother(vector, vector2); sLeaser.sprites[1].scaleY = (Vector2.Distance(vector, vector2) + 2f) * Mathf.Pow(num4, 0.25f); sLeaser.sprites[1].anchorY = 0f; sLeaser.sprites[1].color = Color.Lerp(new Color(0.7f, 1f, 0f), new Color(1f, 1f, 1f), Mathf.Pow(num4, 3f) * num3); sLeaser.sprites[1].isVisible = true; sLeaser.sprites[0].color = Color.Lerp(this.blackColor, new Color(0.7f, 1f, 0f), Mathf.Pow(Mathf.InverseLerp(0.5f, 1f, num4), 3f)); } else { sLeaser.sprites[1].isVisible = false; sLeaser.sprites[0].color = this.blackColor; } if (base.slatedForDeletetion || this.room != rCam.room) { sLeaser.CleanSpritesAndRemove(); } } public void ApplyPalette(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, RoomPalette palette) { this.blackColor = palette.blackColor; } public void AddToContainer(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, FContainer newContatiner) { if (newContatiner == null) { newContatiner = rCam.ReturnFContainer("Items"); } for (int i = 0; i < sLeaser.sprites.Length; i++) { sLeaser.sprites[i].RemoveFromContainer(); newContatiner.AddChild(sLeaser.sprites[i]); } } public void Explosion(Explosion explosion) { if (Custom.DistLess(this.pos, explosion.pos, explosion.rad)) { this.vel += Custom.DirVec(explosion.pos, this.pos) * Mathf.Min(20f, explosion.force * Mathf.InverseLerp(explosion.rad, explosion.rad / 2f, Vector2.Distance(this.pos, explosion.pos)) * 2f); this.life -= 1f; } } public Vector2 pos; public Vector2 lastPos; public Vector2 lastLastPos; public Vector2 lastLastLastPos; public Vector2 vel; public Vector2 flyDir; public Vector2 lastFlyDir; public Vector2 hoverPos; public BodyChunk huntChunk; public Hornest.Bee.Mode mode; public Hornest owner; public float flySpeed; public List<IntVector2> path; public int travelDist; public int inModeCounter; private readonly int group; private float blinkFreq; private float blink; private float lastBlink; public float life; public float lifeTime; private float boostTrail; private float lastBoostTrail; public bool angry; private List<DebugSprite> dbSprts; private Color blackColor; public enum Mode { LostHive, BuzzAroundHive, GetBackToHive, FollowPath, Hover, Hunt } } public class AttachedBee : PhysicalObject, IDrawable { public AttachedBee(Hornest owner, Room room, AbstractPhysicalObject abstrObj, BodyChunk attachedChunk, Vector2 beePos, Vector2 beeDir, float life, float lifeTime, bool beeBosting) : base(abstrObj) { this.owner = owner; this.attachedChunk = attachedChunk; this.life = life; this.lifeTime = lifeTime; base.bodyChunks = new BodyChunk[1]; base.bodyChunks[0] = new BodyChunk(this, 0, beePos, 1f, 0.01f); this.bodyChunkConnections = new PhysicalObject.BodyChunkConnection[0]; base.airFriction = 0.999f; base.gravity = 0.5f; this.bounce = 0.2f; this.surfaceFriction = 0.7f; this.collisionLayer = 0; base.waterFriction = 0.95f; base.buoyancy = 1.1f; base.CollideWithTerrain = false; this.idealStingerDir = Custom.DegToVec(Mathf.Lerp(-60f, 60f, UnityEngine.Random.value)); this.attachedPos = Custom.RotateAroundOrigo((beePos - attachedChunk.pos) * 1f, -Custom.VecToDeg(attachedChunk.Rotation)); this.stinger = new Vector2[3, 3]; if (beeBosting) { attachedChunk.vel += beeDir.normalized * 0.4f / attachedChunk.mass; if (UnityEngine.Random.value < 0.5f) { if (attachedChunk.owner is Creature) { (attachedChunk.owner as Creature).Violence(null, default, attachedChunk, null, Creature.DamageType.Stab, 0.001f, 0f); //stun: 10f * UnityEngine.Random.value * UnityEngine.Random.value } this.popped = true; room.AddObject(new Hornest.BeeSpark(beePos)); room.PlaySound(SoundID.Spore_Bee_Spark, base.firstChunk); } } new Hornest.AttachedBee.BeeStick(this.abstractPhysicalObject, attachedChunk.owner.abstractPhysicalObject); this.visible = UnityEngine.Random.value < 0.07f; } public bool visible; public Hornest owner; public override void Update(bool eu) { base.Update(eu); this.lastRot = this.rot; this.lastStingerOut = this.stingerOut; float num = 0f; if (this.attachedChunk != null) { Vector2 vector = this.attachedChunk.pos; if (this.attachedChunk.owner is Player && this.attachedChunk.owner.graphicsModule != null) { vector = Vector2.Lerp(this.attachedChunk.pos, (this.attachedChunk.owner.graphicsModule as PlayerGraphics).drawPositions[this.attachedChunk.index, 0], (this.attachedChunk.index != 0) ? 0.2f : 0.8f); } Vector2 vector2 = vector + Custom.RotateAroundOrigo(this.attachedPos, Custom.VecToDeg(this.attachedChunk.Rotation)); float num2 = 3f; float num3 = Vector2.Distance(base.bodyChunks[0].pos, (vector + vector2) / 2f); this.rot = Custom.DirVec(base.bodyChunks[0].pos, vector2); if (num3 > num2) { base.bodyChunks[0].pos -= this.rot * (num2 - num3); base.bodyChunks[0].vel -= this.rot * (num2 - num3); } if (!this.stingerOut) { base.bodyChunks[0].vel += Custom.RNV() * UnityEngine.Random.value * 0.4f; this.stingerWaitCounter++; if (UnityEngine.Random.value < Mathf.InverseLerp(0f, 30f, (float)this.stingerWaitCounter) / 10f && this.attachedChunk.owner.room == this.room && (!(this.attachedChunk.owner is Creature) || ((this.attachedChunk.owner as Creature).enteringShortCut == null && !(this.attachedChunk.owner as Creature).inShortcut))) { //Vector2 v = Vector3.Slerp(Custom.DirVec(vector, vector2), new Vector2(0f, 1f), 0.4f); //Vector2 vector3 = vector.ToVector3InMeters() + Vector3.Slerp(Vector3.Slerp(v, this.idealStingerDir, 0.2f), Custom.RNV(), 0.2f) * Mathf.Lerp(30f, 160f, UnityEngine.Random.value); IntVector2 intVector = this.room.GetTilePosition(this.owner.bodyChunks[0].pos); // (UnityEngine.Random.value >= 0.5f) ? SharedPhysics.RayTraceTilesForTerrainReturnFirstSolidOrPole(this.room, vector2, vector3) : SharedPhysics.RayTraceTilesForTerrainReturnFirstSolid(this.room, vector2, vector3); if (intVector != null && !Custom.DistLess(base.firstChunk.pos, this.room.MiddleOfTile(intVector), 80f)) { //if (this.room.GetTile(intVector.Value).Solid) //{ // FloatRect floatRect = Custom.RectCollision(vector3, vector2, this.room.TileRect(intVector)); //this.stingerAttachPos = new Vector2(floatRect.left, floatRect.bottom); //} //else //{ this.stingerAttachPos = this.room.MiddleOfTile(intVector); //if (this.room.GetTile(intVector.Value).horizontalBeam) //{ this.stingerAttachPos.x += Mathf.Lerp(-15f, 15f, UnityEngine.Random.value); //} //if (this.room.GetTile(intVector.Value).verticalBeam) //{ this.stingerAttachPos.y += Mathf.Lerp(-30f, -5f, UnityEngine.Random.value); //} //} this.ropeLength = Mathf.Max(10f, Vector2.Distance(this.attachedChunk.pos, this.stingerAttachPos) + 5f); //Mathf.Max(40f, Vector2.Distance(this.attachedChunk.pos, this.stingerAttachPos) + 5f); this.shrinkTo = Mathf.Max(10f, this.ropeLength * 0.3f); //Mathf.Max(40f, this.ropeLength * 0.5f); this.room.PlaySound(SoundID.Spore_Bee_Attach_Wall, this.stingerAttachPos); if (!this.popped) { this.popped = true; if (this.attachedChunk.owner is Creature) { (this.attachedChunk.owner as Creature).Violence(null, default, this.attachedChunk, null, Creature.DamageType.Stab, 0.002f, 10f * UnityEngine.Random.value * UnityEngine.Random.value); } this.attachedChunk.vel += Custom.DirVec(this.stingerAttachPos, this.attachedChunk.pos) * 0.4f / this.attachedChunk.mass; this.room.AddObject(new Hornest.BeeSpark(base.firstChunk.pos)); this.room.PlaySound(SoundID.Spore_Bee_Spark, base.firstChunk); } this.stingerOut = true; } } } else { if (this.attachedChunk.owner is Creature && (this.attachedChunk.owner as Creature).enteringShortCut != null) { this.stingerOut = false; } else { base.firstChunk.vel += Custom.DirVec(vector, this.stingerAttachPos) * 10f; num3 = Vector2.Distance(this.attachedChunk.pos, this.stingerAttachPos); num = Mathf.InverseLerp(this.ropeLength * 1.6f + 40f, this.ropeLength * 2f + 90f, num3); this.ropeLength = Mathf.Max(this.shrinkTo, this.ropeLength - 0.4f); if (UnityEngine.Random.value < num) { this.BreakStinger(); } else if (num3 > this.ropeLength) { Vector2 a = Custom.DirVec(this.attachedChunk.pos, this.stingerAttachPos); this.attachedChunk.vel -= a * Mathf.Min((this.ropeLength - num3) * 0.0045f, 0.75f) / this.attachedChunk.mass; } } if (this.attachedChunk != null && this.attachedChunk.owner.slatedForDeletetion) { this.BreakStinger(); } } } else if (this.stingerOut) { this.rot = Custom.DirVec(base.bodyChunks[0].pos, this.stingerAttachPos); float num4 = Vector2.Distance(base.bodyChunks[0].pos, this.stingerAttachPos); if (num4 > this.ropeLength) { Vector2 a2 = Custom.DirVec(base.bodyChunks[0].pos, this.stingerAttachPos); base.bodyChunks[0].vel -= a2 * (this.ropeLength - num4) * 0.45f; base.bodyChunks[0].pos -= a2 * (this.ropeLength - num4) * 0.45f; } this.ropeLength = Mathf.Max(0f, this.ropeLength - 2f); if (this.ropeLength == 0f) { this.stingerOut = false; } } else if (base.firstChunk.ContactPoint.y < 0 || base.firstChunk.pos.y < -100f || base.firstChunk.submersion > 0f) { this.Destroy(); } if (this.stingerOut) { float num5 = Vector2.Distance(base.firstChunk.pos, this.stingerAttachPos); for (int i = 0; i < this.stinger.GetLength(0); i++) { this.stinger[i, 2] = this.stinger[i, 0]; this.stinger[i, 0] += this.stinger[i, 1]; this.stinger[i, 1] *= 0.95f; Vector2 vector4 = Vector2.Lerp(base.firstChunk.pos, this.stingerAttachPos, Mathf.Pow(Mathf.InverseLerp(-1f, (float)this.stinger.GetLength(0), (float)i), 0.5f)); this.stinger[i, 1] += (vector4 - this.stinger[i, 0]) * 0.4f; this.stinger[i, 0] += (vector4 - this.stinger[i, 0]) * Mathf.Max(Mathf.InverseLerp(num5 / 100f, num5 / 15f, Vector2.Distance(this.stinger[i, 0], vector4)), num); } if (this.life <= 0f) { this.BreakStinger(); } } else { for (int j = 0; j < this.stinger.GetLength(0); j++) { this.stinger[j, 2] = this.stinger[j, 0]; this.stinger[j, 0] = base.bodyChunks[0].pos; this.stinger[j, 1] *= 0f; } } this.life -= 1f / (this.lifeTime * ((!this.stingerOut) ? 2f : 1f)); } public void BreakStinger() { if (this.attachedChunk == null) { return; } this.ropeLength = Mathf.Clamp(Vector2.Distance(base.firstChunk.pos, this.stingerAttachPos), this.ropeLength - 30f, this.ropeLength + 30f); this.attachedChunk = null; base.CollideWithTerrain = true; base.gravity = 0.9f; this.room.PlaySound(SoundID.Spore_Bee_Fall_Off, base.firstChunk); if (UnityEngine.Random.value < 0.5f) { this.stingerOut = false; } } public override void HitByExplosion(float hitFac, Explosion explosion, int hitChunk) { base.HitByExplosion(hitFac, explosion, hitChunk); this.life -= 1f; } public void InitiateSprites(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam) { sLeaser.sprites = new FSprite[5]; sLeaser.sprites[0] = new FSprite("bee", true); for (int i = 1; i < 5; i++) { sLeaser.sprites[i] = new FSprite("pixel", true) { anchorY = 0f }; } this.AddToContainer(sLeaser, rCam, null); } public void DrawSprites(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, float timeStacker, Vector2 camPos) { Vector2 vector = Vector2.Lerp(base.firstChunk.lastPos, base.firstChunk.pos, timeStacker); if (this.attachedChunk != null) { Vector2 vector2 = Vector2.Lerp(this.attachedChunk.lastPos, this.attachedChunk.pos, timeStacker); Vector2 v = (this.attachedChunk.rotationChunk != null) ? Custom.DirVec(vector2, Vector2.Lerp(this.attachedChunk.rotationChunk.lastPos, this.attachedChunk.rotationChunk.pos, timeStacker)) : this.attachedChunk.Rotation; if (this.attachedChunk.owner is Player && this.attachedChunk.owner.graphicsModule != null) { vector2 = Vector2.Lerp(vector2, Vector2.Lerp((this.attachedChunk.owner.graphicsModule as PlayerGraphics).drawPositions[this.attachedChunk.index, 1], (this.attachedChunk.owner.graphicsModule as PlayerGraphics).drawPositions[this.attachedChunk.index, 0], timeStacker), (this.attachedChunk.index != 0) ? 0.2f : 0.8f); } Vector2 vector3 = vector2 + Custom.RotateAroundOrigo(this.attachedPos, Custom.VecToDeg(v)); if (!Custom.DistLess(vector, vector3, 3f)) { vector = vector3 + Custom.DirVec(vector3, vector) * 3f; } } sLeaser.sprites[0].x = vector.x - camPos.x; sLeaser.sprites[0].y = vector.y - camPos.y; sLeaser.sprites[0].rotation = Custom.VecToDeg(Vector3.Slerp(this.lastRot, this.rot, timeStacker)); float num = Mathf.Lerp((!this.lastStingerOut) ? 0f : 1f, (!this.stingerOut) ? 0f : 1f, timeStacker); if (num > 0f) { for (int i = 0; i < this.stinger.GetLength(0) + 1; i++) { if (this.visible) { Vector2 vector4 = (i != 0) ? Vector2.Lerp(this.stinger[i - 1, 2], this.stinger[i - 1, 0], timeStacker) : vector; vector4 = Vector2.Lerp(vector, vector4, num); sLeaser.sprites[i + 1].x = vector4.x - camPos.x; sLeaser.sprites[i + 1].y = vector4.y - camPos.y; Vector2 vector5 = (i != this.stinger.GetLength(0)) ? Vector2.Lerp(this.stinger[i, 2], this.stinger[i, 0], timeStacker) : this.stingerAttachPos; vector5 = Vector2.Lerp(vector, vector5, num); sLeaser.sprites[i + 1].rotation = Custom.AimFromOneVectorToAnother(vector4, vector5); sLeaser.sprites[i + 1].scaleY = Vector2.Distance(vector4, vector5) + 1f; sLeaser.sprites[i + 1].isVisible = true; } else { sLeaser.sprites[i + 1].isVisible = true; } } } else { for (int j = 0; j < this.stinger.GetLength(0) + 1; j++) { sLeaser.sprites[j + 1].isVisible = false; } } if (base.slatedForDeletetion || this.room != rCam.room) { sLeaser.CleanSpritesAndRemove(); } } public void ApplyPalette(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, RoomPalette palette) { for (int i = 0; i < sLeaser.sprites.Length; i++) { sLeaser.sprites[i].color = palette.blackColor; } } public void AddToContainer(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, FContainer newContatiner) { bool flag = UnityEngine.Random.value < 0.5f; if (newContatiner == null) { newContatiner = rCam.ReturnFContainer((!flag) ? "Background" : "Items"); } for (int i = 0; i < sLeaser.sprites.Length; i++) { sLeaser.sprites[i].RemoveFromContainer(); newContatiner.AddChild(sLeaser.sprites[i]); } } public BodyChunk attachedChunk; public Vector2 attachedPos; public Vector2 rot; public Vector2 lastRot; public Vector2 idealStingerDir; private bool stingerOut; private bool lastStingerOut; private Vector2 stingerAttachPos; private float ropeLength; private float shrinkTo; public int stingerWaitCounter; public Vector2[,] stinger; private bool popped; public float life; public float lifeTime; public class BeeStick : AbstractPhysicalObject.AbstractObjectStick { public BeeStick(AbstractPhysicalObject A, AbstractPhysicalObject B) : base(A, B) { } public override string SaveToString(int roomIndex) { return string.Concat(new string[] { roomIndex.ToString(), "<stkA>beeStk<stkA>", this.A.ID.ToString(), "<stkA>", this.B.ID.ToString() }); } } } public class BeeSpark : CosmeticSprite { public BeeSpark(Vector2 pos) { this.pos = pos; this.lastPos = pos; this.lifeTime = Mathf.Lerp(2f, 6f, UnityEngine.Random.value); this.life = 1f; this.lastLife = 1f; this.randomRotat = UnityEngine.Random.value; } public override void Update(bool eu) { base.Update(eu); this.lastLife = this.life; this.life -= 1f / this.lifeTime; if (this.lastLife < 0f) { this.Destroy(); } } public override void InitiateSprites(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam) { sLeaser.sprites = new FSprite[3]; sLeaser.sprites[0] = new FSprite("Futile_White", true) { color = new Color(0.7f, 1f, 0f), shader = rCam.room.game.rainWorld.Shaders["FlatLight"] }; sLeaser.sprites[1] = new FSprite("pixel", true); sLeaser.sprites[2] = new FSprite("pixel", true); this.AddToContainer(sLeaser, rCam, rCam.ReturnFContainer("Foreground")); } public override void DrawSprites(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, float timeStacker, Vector2 camPos) { for (int i = 0; i < sLeaser.sprites.Length; i++) { sLeaser.sprites[i].x = Mathf.Lerp(this.lastPos.x, this.pos.x, timeStacker) - camPos.x; sLeaser.sprites[i].y = Mathf.Lerp(this.lastPos.y, this.pos.y, timeStacker) - camPos.y; } float num = Mathf.Lerp(this.lastLife, this.life, timeStacker); //float value = Mathf.Pow(num, 3f) * UnityEngine.Random.value; //float num2 = Mathf.Pow(Mathf.InverseLerp(0f, 0.5f, value), 0.4f); sLeaser.sprites[1].color = new Color(0.7f, 1f, num); sLeaser.sprites[1].scaleX = 18f * UnityEngine.Random.value * num; sLeaser.sprites[1].rotation = 360f * (2f * Custom.SCurve(num, 0.3f) + this.randomRotat); sLeaser.sprites[2].color = new Color(0.7f, 1f, num); sLeaser.sprites[2].scaleY = 18f * UnityEngine.Random.value * num; sLeaser.sprites[2].rotation = 360f * (2f * Custom.SCurve(num, 0.3f) + this.randomRotat); sLeaser.sprites[0].alpha = UnityEngine.Random.value * num; sLeaser.sprites[0].scale = (26f * UnityEngine.Random.value + 18f * Mathf.Pow(UnityEngine.Random.value, 3f)) * num / 10f; base.DrawSprites(sLeaser, rCam, timeStacker, camPos); } private float lastLife; private float life; private readonly float lifeTime; private readonly float randomRotat; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using AmericanF2.Modelo; namespace AmericanF2 { public partial class Login : System.Web.UI.Page { AmericanFEntities contexto = new AmericanFEntities(); protected void Page_Load(object sender, EventArgs e) { } protected void btnIniciar_Click(object sender, EventArgs e) { try { Usuario u = contexto.Usuario.Find(txtRut.Text); if (u != null) { if (u.Rol == "Administrador") { Administrador a = contexto.Administrador.Find(txtRut.Text); if (u.Clave == txtClave.Text) { Session["Rut"] = a.RutA; Session["Nombre"] = a.Nombre; Session["Rol"] = "Administrador"; Session.Timeout = 20; // tiempo en minutos Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Redirect(@"~/Vistas/Administrador.aspx"); } } else if (u.Rol == "Bodeguero") { Bodeguero b = contexto.Bodeguero.Find(txtRut.Text); if (u.Clave == txtClave.Text) { Session["Rut"] = b.RutB; Session["Nombre"] = b.Nombre; Session["Rol"] = "Bodeguero"; Session.Timeout = 20; // tiempo en minutos Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Redirect(@"~/Vistas/Bodeguero.aspx"); } } else if (u.Rol == "Vendedor") { Vendedor v = contexto.Vendedor.Find(txtRut.Text); if (u.Clave == txtClave.Text) { Session["Rut"] = v.RutV; Session["Nombre"] = v.Nombre; Session["Rol"] = "Vendedor"; Session.Timeout = 20; // tiempo en minutos Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Redirect(@"~/Vistas/Vendedor.aspx"); } } } else { Panel_error.CssClass = "alert alert-danger"; } } catch (Exception) { Panel_error.CssClass = "alert alert-danger"; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //********************************************************************** // // 文件名称(File Name):PageInfoResponse.CS // 功能描述(Description): // 作者(Author):Aministrator // 日期(Create Date): 2017-05-04 13:21:02 // // 修改记录(Revision History): // R1: // 修改作者: // 修改日期:2017-05-04 13:21:02 // 修改理由: //********************************************************************** namespace ND.FluentTaskScheduling.Model.response { public class PageInfoResponse<T> { public int sEcho { get; set; } /// <summary> /// 过滤前总条数 /// </summary> public int iTotalRecords { get; set; } /// <summary> /// 过滤后总条数 /// </summary> public int iTotalDisplayRecords { get; set; } public T aaData { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Foundry.SourceControl { public interface ISourceDirectory : ISourceObject { IEnumerable<ISourceObject> Children { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using OnlineOrdersMS; namespace KartSystem { interface IOnlineOrderEditView { OnlineOrder ActiveOrder { get; set; } OrderLine ActiveOrderLine { get; set; } } }
using System.Web.Mvc; namespace DevExpress.Web.Demos { public partial class DockingController : DemoController { public ActionResult ForbiddenZones() { return DemoView("ForbiddenZones"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Caching; using Microsoft.SharePoint.Client; namespace DistCWebSite.SharePoint.Utility { public class SPHelper { /// <summary> /// 缓存过期时间(为0时,表示不会缓存) /// </summary> private const double CacheExpireMinutes = 1; /// <summary> /// 分隔符 /// </summary> private const string ListSeperateString = "#@*"; private const string UserSeperateString = "#@#"; /// <summary> /// 不缓存的SharePoint list /// </summary> private static List<string> _noCacheList = new List<string>() { "" }; /// <summary> /// Get SharePoint ListItems of list /// </summary> /// <param name="title">list name</param> /// <returns></returns> public static ListItemCollection GetListByTitle(string title) { return GetListByTitle(title, string.Empty); } /// <summary> /// Get SharePoint ListItems of list with filter /// </summary> /// <param name="title">list name</param> /// <param name="viewXML">caml query xml</param> /// <returns></returns> public static ListItemCollection GetListByTitle(string title, string viewXML) { ListItemCollection listItem = null; if (_noCacheList.Contains(title)) { listItem = GetListByTitleImpl(title, viewXML); } else { var key = title + ListSeperateString + viewXML; listItem = HttpRuntime.Cache[key] as ListItemCollection; if (listItem == null) { listItem = GetListByTitleImpl(title, viewXML); HttpRuntime.Cache.Insert(key, listItem, null, DateTime.Now.AddMinutes(CacheExpireMinutes), Cache.NoSlidingExpiration); } } return listItem; } private static ListItemCollection GetListByTitleImpl(string title, string viewXML) { ListItemCollection listItem = null; using (SPContext spContext = new SPContext()) { var context = spContext.Context; List list = context.Web.Lists.GetByTitle(title); if (list != null) { CamlQuery camlQuery = new CamlQuery(); if (!string.IsNullOrEmpty(viewXML)) { camlQuery.ViewXml = viewXML; } listItem = list.GetItems(camlQuery); context.Load(listItem); context.ExecuteQuery(); } } return listItem; } /// <summary> /// Get SharePoint ListItem of list by id /// </summary> /// <param name="title">list name</param> /// <param name="id">item id</param> /// <returns></returns> public static ListItem GetListItemById(string title, int id) { ListItem item = null; using (SPContext spContext = new SPContext()) { var context = spContext.Context; List list = context.Web.Lists.GetByTitle(title); if (list != null) { item = list.GetItemById(id); } context.ExecuteQuery(); } return item; } /// <summary> /// Update listItem /// </summary> /// <param name="listName">list name</param> /// <param name="id">item id</param> /// <param name="fileds">column internal name and value</param> public static void UpdateListItem(string listName, int id, Dictionary<string, object> fileds) { using (SPContext spContext = new SPContext()) { var context = spContext.Context; List list = context.Web.Lists.GetByTitle(listName); if (list != null) { ListItem item = list.GetItemById(id); if (item != null) { foreach (var filed in fileds) { item[filed.Key] = filed.Value; } item.Update(); } } context.ExecuteQuery(); } } /// <summary> /// Add listItem /// </summary> /// <param name="listName"></param> /// <param name="fileds"></param> /// <returns></returns> public static string AddListItem(string listName, Dictionary<string, object> fileds) { string id = ""; using (SPContext spContext = new SPContext()) { var context = spContext.Context; List list = context.Web.Lists.GetByTitle(listName); if (list != null) { ListItemCreationInformation info = new ListItemCreationInformation(); var item = list.AddItem(info); foreach (var filed in fileds) { item[filed.Key] = filed.Value; } item.Update(); context.ExecuteQuery(); id = item.Id.ToString(); } } return id; } /// <summary> /// Add listItem /// </summary> /// <param name="listName"></param> /// <param name="fileds"></param> /// <returns></returns> public static string AddListItem(ClientContext context, string listName, Dictionary<string, object> fileds) { string id = ""; List list = context.Web.Lists.GetByTitle(listName); if (list != null) { ListItemCreationInformation info = new ListItemCreationInformation(); var item = list.AddItem(info); foreach (var filed in fileds) { item[filed.Key] = filed.Value; } item.Update(); context.ExecuteQuery(); id = item.Id.ToString(); } return id; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using HHY.Models; using static Microsoft.AspNetCore.Http.StatusCodes; using System.IO; using HHY_NETCore.Attributes; using HHY.Models.Product; namespace HHY_NETCore.Controllers { [Authorize] public class ProductsController : Controller { private readonly HHYContext _context; public ProductsController(HHYContext context) { _context = context; } #region View public IActionResult Index() { return View(); } public IActionResult Edit() { return View(); } public IActionResult Create() { return View(); } #endregion [HttpGet("api/admin/getproduct")] public IActionResult Get(string id) { if (id == null) { return Ok(_context.Products.ToList()); } else { var products = _context.Products.Where(r => r.ID == Guid.Parse(id)); if (products.Any()) { var result = products.Select(r => new ProductView() { ID = r.ID.ToString(), BuyUrl = r.BuyUrl, SubTitle = r.SubTitle, DownDate = r.DownDate, ImgUrl = r.ImgUrl, Information = r.Information, IsPromotion = r.IsPromotion, Name = r.Name, Price = r.Price, PublishDate = r.PublishDate, SalePrice = r.SalePrice, Weight = r.Weight, Standard = r.Standard, ReportFiles = _context.ReportFile.Where(s => s.ProductID == r.ID).ToList() }).FirstOrDefault(); return Ok(result); } else { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } } } [HttpPost("api/admin/createproduct")] public async Task<IActionResult> Create(RequestPD product) { var ProductID = Guid.NewGuid(); product.ID = ProductID.ToString(); var reportFiles = new List<ReportFile>(); if (product.file != null) { var savePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Upload", product.file.FileName); using (var stream = new FileStream(savePath, FileMode.Create)) { await product.file.CopyToAsync(stream); } product.ImgUrl = "/Upload/" + product.file.FileName; } if (product.Reportfile != null) { foreach (var item in product.Reportfile) { var savePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Upload", item.FileName); using (var stream = new FileStream(savePath, FileMode.Create)) { await item.CopyToAsync(stream); } reportFiles.Add(new ReportFile() { ProductID = ProductID, FileName = item.FileName, Path = "/Upload/" + item.FileName }); _context.ReportFile.AddRange(reportFiles); await _context.SaveChangesAsync(); } } try { var target = new Products() { ID = ProductID, BuyUrl = product.BuyUrl, ImgUrl = product.ImgUrl, DownDate = product.DownDate, Information = product.Information, IsPromotion = product.IsPromotion, Name = product.Name, Price = product.Price, PublishDate = product.PublishDate, SalePrice = product.SalePrice.Value, SubTitle = product.SubTitle, Weight = product.Weight, Standard = product.Standard }; _context.Products.Add(target); await _context.SaveChangesAsync(); return Ok(); } catch (Exception ex) { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } } [HttpPut("api/admin/editproduct")] public async Task<IActionResult> Edit(RequestPD product) { var reportFiles = new List<ReportFile>(); var products = _context.Products.Where(r => r.ID == Guid.Parse(product.ID)); if (products.Any()) { try { var data = products.FirstOrDefault(); if (product.file != null) { var savePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Upload", product.file.FileName); using (var stream = new FileStream(savePath, FileMode.Create)) { await product.file.CopyToAsync(stream); } data.ImgUrl = "/Upload/" + product.file.FileName; } if (product.Reportfile != null) { foreach (var item in product.Reportfile) { var savePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Upload", item.FileName); using (var stream = new FileStream(savePath, FileMode.Create)) { await item.CopyToAsync(stream); } reportFiles.Add(new ReportFile() { ProductID = Guid.Parse(product.ID), FileName = item.FileName, Path = "/Upload/" + item.FileName }); } _context.ReportFile.AddRange(reportFiles); _context.SaveChanges(); } data.Name = product.Name; data.Weight = product.Weight; data.Price = product.Price; data.SalePrice = product.SalePrice.Value; data.Information = product.Information; data.PublishDate = product.PublishDate; data.DownDate = product.DownDate; data.BuyUrl = product.BuyUrl; data.Standard = product.Standard; data.SubTitle = product.SubTitle; data.IsPromotion = product.IsPromotion; await _context.SaveChangesAsync(); return Ok(); } catch (Exception ex) { return StatusCode(Status400BadRequest, new ResponseMessage { Message = ex.Message }); } } else { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } } [HttpDelete("api/admin/delproduct")] public async Task<IActionResult> Delete(string id) { if (id == null) { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } var about = _context.Products.Where(r => r.ID == Guid.Parse(id)); if (about.Any()) { _context.Products.Remove(about.FirstOrDefault()); await _context.SaveChangesAsync(); return Ok(); } else { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } } [HttpDelete("api/admin/delproductfile")] public async Task<IActionResult> DeleteFile(string ProductID, string ID) { if (ID == null) { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } var about = _context.ReportFile.Where(r => r.ProductID == Guid.Parse(ProductID) && r.ID.ToString() == ID); if (about.Any()) { _context.ReportFile.Remove(about.FirstOrDefault()); await _context.SaveChangesAsync(); return Ok(); } else { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } } } }
using Anywhere2Go.Business.Utility; using Anywhere2Go.DataAccess; using Anywhere2Go.DataAccess.Entity; using Anywhere2Go.DataAccess.Object; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anywhere2Go.Business.Master { public class DamageLevelLogic { MyContext _context = null; public DamageLevelLogic() { _context = new MyContext(); } public DamageLevelLogic(MyContext context) { _context = context; } public DamageLevel GetDamageLevelById(string DamageLevelCode) { List<DamageLevel> result = ApplicationCache.GetMaster<DamageLevel>(); var damageLevel = result .Where(t => t.DamageLevelCode == DamageLevelCode) .SingleOrDefault(); return damageLevel; } public List<SyncDamageLevel> GetDamageLevel(DateTime? lastSyncedDateTime) { List<DamageLevel> result = ApplicationCache.GetMaster<DamageLevel>(); if (lastSyncedDateTime == null) { return result .Select(t => new SyncDamageLevel { DamageLevelCode = t.DamageLevelCode, DamageLevelDescription = t.DamageLevelDescription, Sort = t.Sort, isActive = t.IsActive }) .OrderByDescending(s => s.Sort).ThenBy(s => s.DamageLevelCode) .ToList(); } else { return result .Where(x => (x.UpdateDate ?? x.CreateDate) > lastSyncedDateTime.Value) .OrderBy(x => (x.UpdateDate ?? x.CreateDate)) .Select(t => new SyncDamageLevel { DamageLevelCode = t.DamageLevelCode, DamageLevelDescription = t.DamageLevelDescription, Sort = t.Sort, isActive = t.IsActive }) .ToList(); } } public List<SyncDamageLevel> GetDamageLevel() { List<DamageLevel> result = ApplicationCache.GetMaster<DamageLevel>(); return result .Where(x => x.IsActive == true) .OrderBy(x => (x.DamageLevelCode)) .Select(t => new SyncDamageLevel { DamageLevelCode = t.DamageLevelCode, DamageLevelDescription = t.DamageLevelDescription, Sort = t.Sort, isActive = t.IsActive }) .ToList(); } } }
using System.Reactive.Concurrency; using System.Threading; namespace InstrumentationSample.Infrastructure { //Example of an ISchedulerProvider public sealed class SchedulerProvider : ISchedulerProvider { public IScheduler CurrentThread { get { return Scheduler.CurrentThread; } } public IScheduler NewThread { get { return Scheduler.NewThread; } } public IScheduler TaskPool { get { return Scheduler.TaskPool; } } //Should really expose that this is IDisposable too. Skipped for sample code. public IScheduler CreateEventLoopScheduler(string name, bool isBackground = true) { return new EventLoopScheduler(ts => new Thread(ts) { IsBackground = isBackground, Name = name }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using MessageCentre.Services; namespace MessageCentre.Controllers { [Route("api/[controller]")] public class MessagesController : Controller { readonly IMessageService MessageService; public MessagesController(IMessageService messageService) : base() { this.MessageService = messageService; } // GET api/values [HttpGet] public string Get() { return ""; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chapter1 { /// <summary> /// /// </summary> public class Q1dot2 { public string ReverseString(string stringToReverse) { int length = stringToReverse.Length - 2; int midpoint = length / 2; char[] array = stringToReverse.ToCharArray(); for (int i = 0; i <= length; i++) { array[i] = stringToReverse[length - i]; array[length-i] = stringToReverse[i]; } return new string(array); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameTime : MonoBehaviour { public static GameTime instance=null; GameManager manager; Teachermanager teacher; SchoolEventManager eventmanager; weatherManager wmanager; EndOfTheDayReportManager reportManager; private void Awake() { if (instance == null) { instance = this; } else if (instance != this) { Destroy(gameObject); } } private int Timescale = 400;//default45 [Header("amount of money increase overtime")] [SerializeField] private float amount; private Text clockTxt, seasonTxt, dayTxt,datetxt; private int daysSurv; private float minute, day, second, month, year; public float hour; //private float resetdays = 0; [SerializeField] private GameObject[] suns; public int Timescale1 { get => Timescale; set => Timescale = value; } public float Day { get => day; set => day = value; } public float Month { get => month; set => month = value; } public float Year { get => year; set => year = value; } void Start() { Month = 1; Day = 1; Year = 2000; clockTxt = GameObject.Find("Clock").GetComponent<Text>(); dayTxt = GameObject.Find("DaysSurv").GetComponent<Text>(); seasonTxt = GameObject.Find("Season").GetComponent<Text>(); datetxt = GameObject.Find("Date").GetComponent<Text>(); CalculateSeason(); hour = 0; manager = GameManager.instance; teacher = Teachermanager.instance; eventmanager = SchoolEventManager.instance; wmanager = weatherManager.instance; reportManager = EndOfTheDayReportManager.instance; } void Update() { CalculateTime(); } private void CalculateTime() { second += Time.deltaTime * Timescale1; Mathf.Round(second); //if (second >= 10&& Lobby.instance.StudentsInLine.Count > 0 ) //{ // Lobby.instance.Register(); //} if (second >= 60) { minute++; //GameManager.gameManager.AddMoneyOvertime(amount); Not using singleton //manager.AddMoneyOvertime(amount); second = 0; UpdateText(); }else if (minute >= 60) { // if(manager.AvalableClases[1].) //if (GameObject.Find("Lobby") != null) //{ // manager.SpawnCode(); //} hour++; if (hour == 4) { Reputation.instance.Spawnstudents(); } //if (hour == 6) //{ // Time.timeScale = 0; //} //BroadcastMessage("DetermineHappines", SendMessageOptions.DontRequireReceiver); // give XP manager.addExp(5); minute = 0; UpdateText(); StudentShow.instance.RefreshPannels(); } else if(hour >= 24) { //manager.Gopay(); Day++; foreach(GameObject sun in suns) { sun.GetComponent<daycicle>().Restartvalues(); } //teacher generator per day teacher.RandomGenNum(); //random event triggered at 50% if (hour == 12 && Random.Range(0, 2) == 1) { eventmanager.eventTriggered(); } //Breakdown report! reportManager.BreakdownReport(); //weather generator per day wmanager.RandomWeather(); //remove publicty 5 per day manager.removePub(5); //total teacher salary paid per day manager.SumofSalary(manager.GrandtotalSalary1); //students will pay if(hour == 23) { manager.getPaid(); } if (manager.playerPaidSalary == true) { Debug.Log("Already paid!"); } else { //total teacher salary paid per day manager.paySumofSalary(); manager.playerPaidSalary = false; } hour = 0; UpdateText(); } else if (Day >= 28) { CalcMonth(); } else if(Month >= 12) { Month = 1; Year++; UpdateText(); CalculateSeason(); } } private void CalcMonth() { if (Month == 1 || Month == 3 || Month == 5||Month == 7 || Month == 8 || Month == 10 || Month == 12 ) { if (Day >= 32) { daysSurv++; Month++; Day = 1; UpdateText(); CalculateSeason(); } } if (Month == 4 || Month == 6 || Month == 9 || Month == 11) { if (Day >= 31) { daysSurv++; Month++; Day = 1; UpdateText(); CalculateSeason(); } } if (Month == 2) { if (Day >= 29) { daysSurv++; Month++; Day = 1; UpdateText(); CalculateSeason(); } } } private void CalculateSeason() { if( Month == 2 || Month == 3|| Month == 4) { seasonTxt.text = "Spring"; } else if( Month == 5 || Month == 7|| Month == 8|| Month == 6) { seasonTxt.text = "Summer"; } else if ( Month == 9||Month == 10) { seasonTxt.text = "Autum"; } else if (Month == 1 || Month == 11 || Month == 12) { seasonTxt.text = "Winter"; } } private void UpdateText() { dayTxt.text = "Days survived: "+daysSurv; if (minute >= 0&&minute<10) { clockTxt.text = "Time: " + hour + ":"+"0"+minute; } else { clockTxt.text = "Time: " + hour + ":" + minute; } datetxt.text = "Date: " + Day+"/"+Month + "/" + Year; // monthtxt.text="Month" } }
using System; namespace CardCompiler.DirectoryComponents { public class FileInfoEventArgs : EventArgs { public FileInfoEventArgs(string fullFileName, string fileExtension) { this.FullFileName = fullFileName; this.FileExtension = fileExtension; } public string FullFileName { get; set; } public string FileExtension { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DistCWebSite.Core.Entities { public class M_User { public int ID { get; set; } public string UserAccount { get; set; } public string DisplayName { get; set; } public string UserRole { get; set; } public string DistributorCode { get; set;} public string Email { get; set;} public bool Active { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Net; using System.Net.Sockets; using System.IO; namespace ChatServer { class Server { private List<string> history = new List<string>(); private object myLock = new object(); public void Run() { TcpListener serverSocket = new TcpListener(IPAddress.Any, 1234); serverSocket.Start(); while (true) { Socket clientSocket = serverSocket.AcceptSocket(); new Thread(new ThreadStart(() => ClientThread(clientSocket))).Start(); } } private void ClientThread(Socket socket) { Client c = new Client(socket); try { bool stop = false; while (!stop) { string msg = c.ReceiveFrom(); if (msg != null) { if (msg.Substring(0, 3) == "msg") { string actualMsg = msg.Substring(3); Console.WriteLine("From " + c.Name + " received " + actualMsg); lock (myLock) { history.Add(msg); } } else if (msg == "history") { Console.WriteLine("History request from " + c.Name); List<string> hCopy; lock (myLock) { hCopy = new List<string>(history); } foreach (string s in hCopy) { c.SendTo(s); } c.SendTo("end"); } } else { stop = true; } } } catch (Exception ex) when (ex is ArgumentOutOfRangeException || ex is IOException) { } c.Close(); } } }
using AdminWebsite.Security; using FluentAssertions; using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using System.Collections.Generic; using System.Text.Encodings.Web; using System.Threading.Tasks; using BookingsApi.Client; using BookingsApi.Contract.Responses; namespace AdminWebsite.UnitTests.Controllers { public class BookingListControllerTest { private Mock<IBookingsApiClient> _bookingsApiClient; private Mock<IUserIdentity> _userIdentity; private AdminWebsite.Controllers.BookingListController _controller; [SetUp] public void Setup() { _bookingsApiClient = new Mock<IBookingsApiClient>(); _userIdentity = new Mock<IUserIdentity>(); _controller = new AdminWebsite.Controllers.BookingListController(_bookingsApiClient.Object, _userIdentity.Object, JavaScriptEncoder.Default); } [Test] public async Task Should_return_booking_list_if_cursor_is_null() { _userIdentity.Setup(x => x.IsAdministratorRole()).Returns(true); _bookingsApiClient.Setup(x => x.GetHearingsByTypesAsync(It.IsAny<List<int>>(), It.IsAny<string>(), It.IsAny<int>())) .ReturnsAsync(new BookingsResponse()); var result = await _controller.GetBookingsList(null, 100); var okResult = (OkObjectResult) result; okResult.StatusCode.Should().Be(200); } [Test] public async Task Should_return_booking_list_if_cursor_is_not_null() { _userIdentity.Setup(x => x.IsAdministratorRole()).Returns(true); _bookingsApiClient.Setup(x => x.GetHearingsByTypesAsync(It.IsAny<List<int>>(), It.IsAny<string>(), It.IsAny<int>())) .ReturnsAsync(new BookingsResponse()); _userIdentity.Setup(x => x.GetGroupDisplayNames()).Returns(new List<string> {"type1", "type2"}); _bookingsApiClient.Setup(s => s.GetCaseTypesAsync()).ReturnsAsync(new List<CaseTypeResponse>()); var result = await _controller.GetBookingsList("cursor", 100); var okResult = (OkObjectResult) result; okResult.StatusCode.Should().Be(200); } [Test] public async Task Should_return_unauthorized_for_booking_list_if_user_is_not_admin() { _userIdentity.Setup(x => x.IsAdministratorRole()).Returns(false); _bookingsApiClient.Setup(x => x.GetHearingsByTypesAsync(It.IsAny<List<int>>(), It.IsAny<string>(), It.IsAny<int>())) .ReturnsAsync(new BookingsResponse()); var result = await _controller.GetBookingsList("cursor", 100); var unauthorizedResult = (UnauthorizedResult) result; unauthorizedResult.StatusCode.Should().Be(401); } [Test] public async Task Should_throw_exception_for_booking_list_and_returns_bad_result() { _userIdentity.Setup(x => x.IsAdministratorRole()).Returns(true); _bookingsApiClient.Setup(x => x.GetHearingsByTypesAsync(It.IsAny<List<int>>(), It.IsAny<string>(), It.IsAny<int>())) .Throws(new BookingsApiException("Error", 400, "response", null, null)); var result = await _controller.GetBookingsList("cursor", 100); var badResult = (BadRequestObjectResult) result; badResult.StatusCode.Should().Be(400); } [Test] public async Task Should_return_ok_for_booking_list_with_null_types_in_database() { SetupTestCase(); List<CaseTypeResponse> response = null; _bookingsApiClient.Setup(s => s.GetCaseTypesAsync()).ReturnsAsync(response); var result = await _controller.GetBookingsList("cursor", 100); var okResult = (OkObjectResult) result; okResult.StatusCode.Should().Be(200); } [Test] public async Task Should_return_ok_for_booking_list_with_empty_list_of_types() { SetupTestCase(); var response = new List<CaseTypeResponse>(); _bookingsApiClient.Setup(s => s.GetCaseTypesAsync()).ReturnsAsync(response); var result = await _controller.GetBookingsList("cursor", 100); var okResult = (OkObjectResult) result; okResult.StatusCode.Should().Be(200); } [Test] public async Task Should_return_ok_for_booking_list_if_no_parameters_case_types_are_matched_with_database_types() { SetupTestCase(); var response = new List<CaseTypeResponse> { new CaseTypeResponse { HearingTypes = new List<HearingTypeResponse>(), Id = 1, Name = "type3" }, new CaseTypeResponse { HearingTypes = new List<HearingTypeResponse>(), Id = 2, Name = "type4" } }; _bookingsApiClient.Setup(s => s.GetCaseTypesAsync()).ReturnsAsync(response); var result = await _controller.GetBookingsList("cursor", 100); var okResult = (OkObjectResult) result; okResult.StatusCode.Should().Be(200); } [Test] public async Task Should_return_ok_for_booking_list_with_defined_types_list() { _userIdentity.Setup(x => x.IsAdministratorRole()).Returns(true); var hearingTypesIds = new List<int> {1, 2}; _bookingsApiClient.Setup(x => x.GetHearingsByTypesAsync(hearingTypesIds, It.IsAny<string>(), It.IsAny<int>())) .ReturnsAsync(new BookingsResponse()); _userIdentity.Setup(x => x.GetGroupDisplayNames()).Returns(new List<string> {"type1", "type2"}); var response = GetCaseTypesList(); _bookingsApiClient.Setup(s => s.GetCaseTypesAsync()).ReturnsAsync(response); var result = await _controller.GetBookingsList("cursor", 100); var okResult = (OkObjectResult) result; okResult.StatusCode.Should().Be(200); _bookingsApiClient.Verify(x => x.GetHearingsByTypesAsync(hearingTypesIds, "cursor", 100), Times.Once); } [Test] public async Task Should_return_ok_for_booking_list_and_exclude_repeted_types() { _userIdentity.Setup(x => x.IsAdministratorRole()).Returns(true); var hearingTypesIds = new List<int> {1, 2}; _bookingsApiClient.Setup(x => x.GetHearingsByTypesAsync(hearingTypesIds, It.IsAny<string>(), It.IsAny<int>())) .ReturnsAsync(new BookingsResponse()); _userIdentity.Setup(x => x.GetGroupDisplayNames()).Returns(new List<string> {"type1", "type2", "type2"}); var response = GetCaseTypesList(); _bookingsApiClient.Setup(s => s.GetCaseTypesAsync()).ReturnsAsync(response); var result = await _controller.GetBookingsList("cursor", 100); var okResult = (OkObjectResult) result; okResult.StatusCode.Should().Be(200); _bookingsApiClient.Verify(x => x.GetHearingsByTypesAsync(hearingTypesIds, "cursor", 100), Times.Once); } private List<CaseTypeResponse> GetCaseTypesList() { return new List<CaseTypeResponse> { new CaseTypeResponse { HearingTypes = new List<HearingTypeResponse>(), Id = 1, Name = "type1" }, new CaseTypeResponse { HearingTypes = new List<HearingTypeResponse>(), Id = 2, Name = "type2" }, new CaseTypeResponse { HearingTypes = new List<HearingTypeResponse>(), Id = 3, Name = "type3" } }; } private void SetupTestCase() { _userIdentity.Setup(x => x.IsAdministratorRole()).Returns(true); _userIdentity.Setup(x => x.GetGroupDisplayNames()).Returns(new List<string> {"type1", "type2"}); _bookingsApiClient.Setup(x => x.GetHearingsByTypesAsync(It.IsAny<List<int>>(), It.IsAny<string>(), It.IsAny<int>())) .ReturnsAsync(new BookingsResponse()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UNO.Model.Karten { class ZweiZiehenKarte : IKarte { public KartenTyp Typ => KartenTyp.Ziehen; public KartenFarbe Farbe { get; set; } public int Anzahl { get; } = 2; public ZweiZiehenKarte(KartenFarbe farbe) { Farbe = farbe; } } }
/* Dataphor © Copyright 2000-2008 Alphora This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt */ using System; using System.Text; using System.Web; using System.Xml; using System.IO; using System.Net; using System.Net.Mail; using System.Net.Mime; using Alphora.Dataphor; using Alphora.Dataphor.DAE; using Alphora.Dataphor.DAE.Server; using Alphora.Dataphor.DAE.Runtime; using Alphora.Dataphor.DAE.Runtime.Data; using Alphora.Dataphor.DAE.Runtime.Instructions; using Schema = Alphora.Dataphor.DAE.Schema; namespace Alphora.Dataphor.Libraries.System.Internet { // operator System.Internet.SendEmail(const ASmtpServer: System.String, const AFromEmailAddress: System.String, const AToEmailAddress: System.String, const ASubject: System.String, const AMessage: System.String); // operator System.Internet.SendEmail(const ASmtpServer: System.String, const AFromEmailAddress: System.String, const AToEmailAddress: System.String, const ASubject: System.String, const AMessage: System.String, const AIsBodyHtml : Boolean); // operator System.Internet.SendEmail(const ASmtpServer: System.String, const AFromEmailAddress: System.String, const AToEmailAddress: System.String, const ASubject: System.String, const AMessage: System.String, const AHtmlAlternateView : String); public class SendEmailNode : InstructionNode { public override object InternalExecute(Program program, object[] arguments) { //MailMessage constructor does not support semi-colon seperated list of "To" addresses MailMessage mailMessage = new MailMessage(); mailMessage.From = new MailAddress((string)arguments[1]); foreach (string emailAddress in ((string)arguments[2]).Split(';')) mailMessage.To.Add(new MailAddress(emailAddress.Trim())); mailMessage.Subject = (string)arguments[3]; //if using AlternateView don't set Body properties (this and the order of the addition of the AlternateViews has an effect on what some clients display). if ((arguments.Length == 6) && (!Operator.Operands[5].DataType.Is(program.DataTypes.SystemBoolean))) { mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString((string)arguments[4], null, MediaTypeNames.Text.Plain)); mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString((string)arguments[5], null, MediaTypeNames.Text.Html)); } else { mailMessage.Body = (string)arguments[4]; mailMessage.IsBodyHtml = (arguments.Length == 6) ? (bool)arguments[5] : false; } new SmtpClient((string)arguments[0]).Send(mailMessage); return null; } } // operator HTMLAttributeEncode(const AValue : String) : String public class HTMLAttributeEncodeNode : InstructionNode { public override object InternalExecute(Program program, object[] arguments) { // I would have thought that the framework implementation of HtmlAttributeEncode would, // well, encode html attributes. However, it does not seem to replace carriage-returns // or line feeds, so I'm doing that here. string encodedString = HttpUtility.HtmlAttributeEncode((string)arguments[0]); StringBuilder result = new StringBuilder(encodedString.Length); for (int index = 0; index < encodedString.Length; index++) switch (encodedString[index]) { case '\r': result.Append("&#xD;"); break; case '\n': result.Append("&#xA;"); break; default : result.Append(encodedString[index]); break; } return result.ToString(); } } // operator HTMLEncode(const AValue : String) : String public class HTMLEncodeNode : InstructionNode { public override object InternalExecute(Program program, object[] arguments) { return HttpUtility.HtmlEncode((string)arguments[0]); } } // operator HTMLDecode(const AValue : String) : String public class HTMLDecodeNode : InstructionNode { public override object InternalExecute(Program program, object[] arguments) { return HttpUtility.HtmlDecode((string)arguments[0]); } } // operator URLEncode(const AValue : String) : String public class URLEncodeNode : InstructionNode { public override object InternalExecute(Program program, object[] arguments) { return HttpUtility.UrlEncode((string)arguments[0]); } } // operator URLDecode(const AValue : String) : String public class URLDecodeNode : InstructionNode { public override object InternalExecute(Program program, object[] arguments) { return HttpUtility.UrlDecode((string)arguments[0]); } } // operator HTTP(const AVerb : String, const AURL : String, const AHeaders : table { Header : String, Value : String }, const ABody : String) : String public class HTTPNode : InstructionNode { public override object InternalExecute(Program program, object[] arguments) { string result; string verb = (string)arguments[0]; string uRL = (string)arguments[1]; TableValue headersTable = (TableValue)arguments[2]; ITable headers = headersTable != null ? headersTable.OpenCursor() : null; string body = (string)arguments[3]; // Prepare the request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uRL); request.Method = verb; request.ProtocolVersion = new Version(1, 1); request.KeepAlive = false; if (headers != null) { using (Row row = new Row(program.ValueManager, headers.DataType.RowType)) { while (headers.Next()) { headers.Select(row); request.Headers[(HttpRequestHeader)Enum.Parse(typeof(HttpRequestHeader), (string)row["Header"])] = (string)row["Value"]; } } } // Write the body if (!String.IsNullOrEmpty(body)) using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) writer.Write(body); // Get and read the response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream); result = reader.ReadToEnd(); reader.Close(); } return result; } } // operator PostHTTP(const AURL : String, AFields : table { FieldName : String, Value : String }) : String public class PostHTTPNode : InstructionNode { public override object InternalExecute(Program program, object[] arguments) { string result; string uRL = (string)arguments[0]; TableValue fieldsTable = (TableValue)arguments[1]; ITable fields = fieldsTable.OpenCursor(); // Build the URL encoding for the body StringBuilder body = new StringBuilder(); using (Row row = new Row(program.ValueManager, fields.DataType.RowType)) { while (fields.Next()) { fields.Select(row); if (body.Length > 0) body.Append("&"); body.Append(HttpUtility.UrlEncode((string)row["FieldName"])); body.Append("="); body.Append(HttpUtility.UrlEncode((string)row["Value"])); } } // Prepare the request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uRL); request.Method = "POST"; request.ProtocolVersion = new Version(1, 1); request.KeepAlive = false; request.ContentType = "application/x-www-form-urlencoded"; // Write the body using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) writer.Write(body.ToString()); // Get and read the response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream); result = reader.ReadToEnd(); reader.Close(); } return result; } } // operator LoadXML(ADocument : String) : XMLDocumentID public class LoadXMLNode : InstructionNode { private static void WriteContent(IServerProcess process, Guid elementID, string content, int childSequence, byte type) { DataParams paramsValue = new DataParams(); paramsValue.Add(DataParam.Create(process, "AElementID", elementID)); paramsValue.Add(DataParam.Create(process, "ASequence", childSequence)); paramsValue.Add(DataParam.Create(process, "AContent", content)); paramsValue.Add(DataParam.Create(process, "AType", type)); process.Execute ( "insert table { row { AElementID Element_ID, ASequence Sequence, AContent Content, AType Type }, key { } } into .System.Internet.XMLContent", paramsValue ); } private static Guid InsertElement(IServerProcess process, Guid documentID, XmlTextReader reader, Guid parentID, int sequence) { Guid elementID = Guid.NewGuid(); DataParams paramsValue = new DataParams(); // Insert the element paramsValue.Add(DataParam.Create(process, "AElementID", elementID)); paramsValue.Add(DataParam.Create(process, "ADocumentID", documentID)); paramsValue.Add(DataParam.Create(process, "ANamespaceAlias", reader.Prefix)); paramsValue.Add(DataParam.Create(process, "AName", reader.LocalName)); process.Execute ( "insert table { row { AElementID ID, ADocumentID Document_ID, ANamespaceAlias NamespaceAlias, " + "AName Name }, key { } } into .System.Internet.XMLElement", paramsValue ); // Attach to parent if (parentID != Guid.Empty) { paramsValue.Clear(); paramsValue.Add(DataParam.Create(process, "AElementID", elementID)); paramsValue.Add(DataParam.Create(process, "AParentElementID", parentID)); paramsValue.Add(DataParam.Create(process, "ASequence", sequence)); process.Execute ( "insert table { row { AElementID Element_ID, AParentElementID Parent_Element_ID, ASequence Sequence }, key { } } into .System.Internet.XMLElementParent", paramsValue ); } // Add attributes while (reader.MoveToNextAttribute()) { paramsValue.Clear(); paramsValue.Add(DataParam.Create(process, "AElementID", elementID)); paramsValue.Add(DataParam.Create(process, "AValue", reader.Value)); if (String.Compare(reader.Name, "xmlns", true) == 0) // Default namespace process.Execute ( "insert table { row { AElementID Element_ID, AValue URI }, key { } } into .System.Internet.XMLDefaultNamespace", paramsValue ); else if (String.Compare(reader.Prefix, "xmlns", true) == 0) // Namespace alias { paramsValue.Add(DataParam.Create(process, "ANamespaceAlias", reader.LocalName)); process.Execute ( "insert table { row { AElementID Element_ID, ANamespaceAlias NamespaceAlias, AValue URI }, key { } } into .System.Internet.XMLNamespaceAlias", paramsValue ); } else // regular attribute { paramsValue.Add(DataParam.Create(process, "ANamespaceAlias", reader.Prefix)); paramsValue.Add(DataParam.Create(process, "AName", reader.LocalName)); process.Execute ( "insert table { row { AElementID Element_ID, ANamespaceAlias NamespaceAlias, AName Name, AValue Value }, key { } } into .System.Internet.XMLAttribute", paramsValue ); } } reader.MoveToElement(); if (!reader.IsEmptyElement) { int childSequence = 0; XmlNodeType nodeType; // Add child elements do { reader.Read(); nodeType = reader.NodeType; switch (nodeType) { case XmlNodeType.Text : WriteContent(process, elementID, reader.Value, childSequence++, 0); break; case XmlNodeType.CDATA : WriteContent(process, elementID, reader.Value, childSequence++, 1); break; case XmlNodeType.Element : InsertElement(process, documentID, reader, elementID, childSequence++); break; } } while (nodeType != XmlNodeType.EndElement); } return elementID; } private static void InsertDocument(IServerProcess process, Guid documentID, Guid rootElementID) { DataParams paramsValue = new DataParams(); paramsValue.Add(DataParam.Create(process, "ADocumentID", documentID)); paramsValue.Add(DataParam.Create(process, "AElementID", rootElementID)); process.Execute ( "insert table { row { ADocumentID ID, AElementID Root_Element_ID }, key { } } into .System.Internet.XMLDocument", paramsValue ); } public override object InternalExecute(Program program, object[] arguments) { XmlTextReader reader = new XmlTextReader(new StringReader((string)arguments[0])); reader.WhitespaceHandling = WhitespaceHandling.None; // Move to the root element reader.MoveToContent(); Guid documentID = Guid.NewGuid(); program.ServerProcess.BeginTransaction(IsolationLevel.Isolated); try { InsertDocument(program.ServerProcess, documentID, InsertElement(program.ServerProcess, documentID, reader, Guid.Empty, 0)); program.ServerProcess.CommitTransaction(); } catch { program.ServerProcess.RollbackTransaction(); throw; } return documentID; } } // operator SaveXML(ADocumentID : XMLDocumentID) : String public class SaveXMLNode : InstructionNode { private void WriteElement(Program program, XmlTextWriter writer, Guid elementID) { // Write the element header DataParams paramsValue = new DataParams(); paramsValue.Add(DataParam.Create(program.ServerProcess, "AElementID", elementID)); using ( IRow element = (IRow)((IServerProcess)program.ServerProcess).Evaluate ( "row from (XMLElement where ID = AElementID)", paramsValue ) ) { string namespaceAlias = (string)element["NamespaceAlias"]; if (namespaceAlias != String.Empty) namespaceAlias = namespaceAlias + ":"; writer.WriteStartElement(namespaceAlias + (string)element["Name"]); } // Write any default namespace changes IScalar defaultValue = (IScalar)((IServerProcess)program.ServerProcess).Evaluate ( "URI from row from (XMLDefaultNamespace where Element_ID = AElementID)", paramsValue ); if (defaultValue != null) writer.WriteAttributeString("xmlns", defaultValue.AsString); // Write namespace aliases IServerCursor aliases = (IServerCursor)((IServerProcess)program.ServerProcess).OpenCursor ( "XMLNamespaceAlias where Element_ID = AElementID", paramsValue ); try { while (aliases.Next()) { using (IRow row = aliases.Select()) writer.WriteAttributeString("xmlns:" + (string)row["NamespaceAlias"], (string)row["URI"]); } } finally { ((IServerProcess)program.ServerProcess).CloseCursor(aliases); } // Write the attributes IServerCursor attributes = (IServerCursor)((IServerProcess)program.ServerProcess).OpenCursor ( "XMLAttribute where Element_ID = AElementID", paramsValue ); try { while (attributes.Next()) { using (IRow row = attributes.Select()) { string alias = (string)row["NamespaceAlias"]; if (alias != String.Empty) alias = alias + ":"; writer.WriteAttributeString(alias + (string)row["Name"], (string)row["Value"]); } } } finally { ((IServerProcess)program.ServerProcess).CloseCursor(attributes); } // Write the child content and elements IServerCursor children = (IServerCursor)((IServerProcess)program.ServerProcess).OpenCursor ( @" (XMLContent where Element_ID = AElementID over { Element_ID, Sequence }) union ( XMLElementParent where Parent_Element_ID = AElementID over { Parent_Element_ID, Sequence } rename { Parent_Element_ID Element_ID } ) left join (XMLContent rename { Element_ID Content_Element_ID, Sequence Content_Sequence }) by Element_ID = Content_Element_ID and Sequence = Content_Sequence left join (XMLElementParent rename { Element_ID Child_Element_ID, Sequence Child_Sequence }) by Element_ID = Parent_Element_ID and Sequence = Child_Sequence order by { Element_ID, Sequence } ", paramsValue ); try { while (children.Next()) { using (IRow row = children.Select()) { if (row.HasValue("Content_Element_ID")) // Content { if ((byte)row["Type"] == 0) writer.WriteString((string)row["Content"]); else writer.WriteCData((string)row["Content"]); } else // Child element { WriteElement(program, writer, (Guid)row["Child_Element_ID"]); } } } } finally { ((IServerProcess)program.ServerProcess).CloseCursor(children); } // Write the end element writer.WriteEndElement(); } public override object InternalExecute(Program program, object[] arguments) { StringWriter text = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(text); writer.Formatting = Formatting.Indented; // Find the root element DataParams paramsValue = new DataParams(); paramsValue.Add(DataParam.Create(program.ServerProcess, "ADocumentID", (Guid)arguments[0])); Guid rootElementID = ((IScalar) ((IServerProcess)program.ServerProcess).Evaluate ( "Root_Element_ID from row from (XMLDocument where ID = ADocumentID)", paramsValue ) ).AsGuid; // Write the root element WriteElement(program, writer, rootElementID); writer.Flush(); return text.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ShootingGame.Core; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace ShootingGame.GameComponent { public class InputHandler { KeyboardState previousKeySate; private int timeSinceLastShoot; private int nextShootTime; public InputHandler() { timeSinceLastShoot = 0; nextShootTime = 500; } public void UpdateWorld(GameTime gameTime, FirstPersonCamera camera, SceneManager scene, Music music) { timeSinceLastShoot += gameTime.ElapsedGameTime.Milliseconds; KeyboardState kState = Keyboard.GetState(); if (previousKeySate.IsKeyDown(Keys.C) && kState.IsKeyUp(Keys.C)) { if (!scene.GetOctreeWorld().IsControlTankEnabled()) scene.GetOctreeWorld().EnableControlTank(); else scene.GetOctreeWorld().DisableControlTank(); } if (previousKeySate.IsKeyDown(Keys.D1) && kState.IsKeyUp(Keys.D1)) { if (scene.GetOctreeWorld().IsControlTankEnabled()) scene.GetOctreeWorld().GetTank().ActivateWanderMode(); scene.GetOctreeWorld().DisableControlTank(); } if (previousKeySate.IsKeyDown(Keys.D2) && kState.IsKeyUp(Keys.D2)) { if (scene.GetOctreeWorld().IsControlTankEnabled()) scene.GetOctreeWorld().GetTank().ActivateFollowMode(); scene.GetOctreeWorld().DisableControlTank(); } if (previousKeySate.IsKeyDown(Keys.D3) && kState.IsKeyUp(Keys.D3)) { if (scene.GetOctreeWorld().IsControlTankEnabled()) scene.GetOctreeWorld().UseHealthGlobe(); scene.GetOctreeWorld().DisableControlTank(); } if (previousKeySate.IsKeyDown(Keys.D4) && kState.IsKeyUp(Keys.D4)) { if (scene.GetOctreeWorld().IsControlTankEnabled()) scene.GetOctreeWorld().GetTank().DeactiveActionMode(); scene.GetOctreeWorld().DisableControlTank(); } if (previousKeySate.IsKeyDown(Keys.D9) && kState.IsKeyUp(Keys.D9)) { scene.DeductPlayerHealth(10); } if (Mouse.GetState().LeftButton == ButtonState.Pressed) { if (timeSinceLastShoot >= nextShootTime) { music.PlayShootingEffect(); Vector3 direction = camera.ViewDirection; scene.AddPlayerBulletModel(camera.Position, direction); timeSinceLastShoot = 0; } } previousKeySate = kState; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace QuanLySinhVien { static class Program { public static Thread th; public static Thread th1; [STAThread] static void Main() { th = new Thread(new ThreadStart(openform)); th1 = new Thread(new ThreadStart(openform1)); th1.Start(); } static void openform() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new QuanLyDiem()); } static void openform1() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
namespace Sky { public interface IRotatingObject : IObjectInSpace { void MoveAlong(); void RotateAround(); } }
namespace Properties.Core.Objects { public class PropertyItem { public string ItemReference { get; set; } public ItemType ItemType { get; set; } public string Url { get; set; } } }
using Pe.Stracon.Politicas.Aplicacion.Core.ServiceContract; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General; using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual; using Pe.Stracon.SGC.Application.Core.ServiceContract; using Pe.Stracon.SGC.Cross.Core.Base; using Pe.Stracon.SGC.Infraestructura.Core.Context; using Pe.Stracon.SGC.Presentacion.Core.Controllers.Base; using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Base; using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.ReporteContratoPendienteElaborar; using Pe.Stracon.SGC.Presentacion.Recursos.Base; using Pe.Stracon.SGC.Presentacion.Recursos.Contractual; using System.Web.Mvc; namespace Pe.Stracon.SGC.Presentacion.Core.Controllers.Contractual { /// <summary> /// Controladora de Reporte de Contrato Pendiente de Elaborar /// </summary> /// <remarks> /// Creación: GMD 20150630 </br> /// Modificación: </br> /// </remarks> public class ReporteContratoPendienteElaborarController : GenericController { #region Parámetros /// <summary> /// Servicio de manejo de parametro valor /// </summary> public IPoliticaService politicaService { get; set; } /// <summary> /// Servicio de manejo de Unidad Operativa /// </summary> public IUnidadOperativaService unidadOperativaService { get; set; } /// <summary> /// Interfaz para el manejo de auditoría /// </summary> public IEntornoActualAplicacion entornoActualAplicacion { get; set; } #endregion #region Vistas /// <summary> /// Muestra la vista Index /// </summary> /// <returns>Vista Index</returns> public ActionResult Index(ReporteContratoPendienteElaborarRequest filtro) { if (filtro != null) { TempData["DataReport"] = CrearModelo(filtro); } var tipoOrden = politicaService.ListarTipoOrden(); var moneda = politicaService.ListarMoneda(); var modelo = new ReporteContratoPendienteElaborarBusqueda(tipoOrden.Result, moneda.Result); return View(modelo); } #endregion /// <summary> /// Asigna los parámetros necesarios para el reporte /// </summary> /// <param name="filtro">Filtro de Búsqueda para el reporte</param> /// <returns>Modelo con parámetros para el reporte</returns> private ReporteViewModel CrearModelo(ReporteContratoPendienteElaborarRequest filtro) { var reporteModel = new ReporteViewModel(); reporteModel.RutaReporte += DatosConstantes.ReporteNombreArchivo.ReporteContratoPendienteElaborar; reporteModel.AgregarParametro("CODIGO_LENGUAJE", DatosConstantes.Iternacionalizacion.ES_PE); reporteModel.AgregarParametro("USUARIO", entornoActualAplicacion.UsuarioSession); reporteModel.AgregarParametro("NOMBRE_REPORTE", ReporteContratoPendienteElaborarResource.EtiquetaTitulo.ToUpper()); reporteModel.AgregarParametro("FORMATO_FECHA_CORTA", DatosConstantes.Formato.FormatoFecha); reporteModel.AgregarParametro("FORMATO_HORA_CORTA", DatosConstantes.Formato.FormatoHora); reporteModel.AgregarParametro("FORMATO_NUMERO_ENTERO", DatosConstantes.Formato.FormatoNumeroEntero); reporteModel.AgregarParametro("FORMATO_NUMERO_DECIMAL", DatosConstantes.Formato.FormatoNumeroDecimal); reporteModel.AgregarParametro("PIE_REPORTE", string.Format(GenericoResource.EtiquetaFinReporte, ReporteContratoPendienteElaborarResource.EtiquetaTitulo.ToUpper())); reporteModel.AgregarParametro("RUC_PROVEEDOR", filtro.RucProveedor); reporteModel.AgregarParametro("NOMBRE_PROVEEDOR", filtro.NombreProveedor); reporteModel.AgregarParametro("TIPO_ORDEN", filtro.CodigoTipoOrden); reporteModel.AgregarParametro("DESCRIPCION_TIPO_ORDEN", filtro.DescripcionTipoOrden); reporteModel.AgregarParametro("PERIODO_ANIO", filtro.Anio); reporteModel.AgregarParametro("PERIODO_MES", filtro.Mes); reporteModel.AgregarParametro("NOMBRE_MES", filtro.NombreMes); reporteModel.AgregarParametro("MONEDA", filtro.CodigoMoneda); reporteModel.AgregarParametro("DESCRIPCION_MONEDA", filtro.DescripcionMoneda); return reporteModel; } } }
using AspNetCore.Identity.Mongo.Model; using DamianTourBackend.Api.Helpers; using DamianTourBackend.Application; using DamianTourBackend.Application.UpdateProfile; using DamianTourBackend.Core.Entities; using DamianTourBackend.Core.Interfaces; using FluentValidation; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using DamianTourBackend.Application.Helpers; namespace DamianTourBackend.Api.Controllers { [ApiConventionType(typeof(DefaultApiConventions))] [Produces("application/json")] [Route("api/[controller]")] [ApiController] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class ProfileController : ControllerBase { private readonly UserManager<AppUser> _userManager; private readonly IUserRepository _userRepository; private readonly IValidator<UpdateProfileDTO> _updateProfileValidator; private readonly RoleManager<MongoRole> _roleManager; private readonly IRegistrationRepository _registrationRepository; public ProfileController(IUserRepository userRepository, IValidator<UpdateProfileDTO> updateProfileValidator, UserManager<AppUser> userManager, RoleManager<MongoRole> roleManager, IRegistrationRepository registrationRepository) { _userRepository = userRepository; _updateProfileValidator = updateProfileValidator; _userManager = userManager; _roleManager = roleManager; _registrationRepository = registrationRepository; } /// <summary> /// Gets the currently logged in user /// </summary> /// <returns>Ok with user or Unauthorized if user isn't logged in or BadRequest if user can't be found</returns> [HttpGet("")] public IActionResult Get() { if (!User.Identity.IsAuthenticated) return Unauthorized("You need to be logged on to perform this action"); string mailAdress = User.Identity.Name; if (mailAdress == null) return BadRequest("User not found"); var user = _userRepository.GetBy(mailAdress); if (user == null) return BadRequest("User not found"); return Ok(user); } /// <summary> /// Deletes the currently logged in user /// </summary> /// <returns>Ok or Unauthorized if user isn't logged in or BadRequest if user can't be found</returns> [HttpDelete(nameof(Delete))] public async Task<IActionResult> Delete() { if (!User.Identity.IsAuthenticated) return Unauthorized("You need to be logged on to perform this action"); string mailAdress = User.Identity.Name; if (mailAdress == null) return BadRequest("User not found"); var user = _userRepository.GetBy(mailAdress); var identityUser = await _userManager.FindByNameAsync(mailAdress); if (user == null || identityUser == null) return BadRequest("User not found"); // Delete User _userRepository.Delete(user); // Delete IdentityUser var result = await _userManager.DeleteAsync(identityUser); if (!result.Succeeded) return BadRequest("Not able to delete the user, internal error"); return Ok(); } /// <summary> /// Updates the user using the UpdateProfileDTO /// </summary> /// <param name="updateProfileDTO">UpdateProfileDTO containing email, name, date of birth and phonenumber</param> /// <returns>updated user</returns> [HttpPut(nameof(Update))] public async Task<IActionResult> Update(UpdateProfileDTO updateProfileDTO) { if (!User.Identity.IsAuthenticated) return Unauthorized("You need to be logged in to perform this action"); var validation = _updateProfileValidator.Validate(updateProfileDTO); if (!validation.IsValid) return BadRequest(validation); string mailAdress = User.Identity.Name; if (mailAdress == null) return BadRequest("User not found"); var user = _userRepository.GetBy(mailAdress); var identityUser = await _userManager.FindByNameAsync(mailAdress); if (user == null || identityUser == null) return BadRequest("User not found"); // Update User updateProfileDTO.UpdateUser(ref user); _userRepository.Update(user); // Update IdentityUser updateProfileDTO.UpdateIdentityUser(ref identityUser); var result = await _userManager.UpdateAsync(identityUser); if (!result.Succeeded) return BadRequest("Unable to update the user, internal error"); return Ok(user); } [HttpPut(nameof(UpdateFriends))] public IActionResult UpdateFriends(ICollection<string> friends) { if (!User.Identity.IsAuthenticated) return Unauthorized("You need to be logged in to perform this action"); string mailAdress = User.Identity.Name; if (mailAdress == null) return BadRequest("User not found"); var user = _userRepository.GetBy(mailAdress); if (user == null) return BadRequest("User not found"); user.Friends = friends; // Update User _userRepository.Update(user); return Ok(user.Friends); } [HttpPut(nameof(UpdatePrivacy))] public IActionResult UpdatePrivacy(string privacy) { if (!User.Identity.IsAuthenticated) return Unauthorized("You need to be logged in to perform this action"); string mailAdress = User.Identity.Name; if (mailAdress == null) return BadRequest("User not found"); var user = _userRepository.GetBy(mailAdress); if (user == null) return BadRequest("User not found"); Privacy updatedPrivacy = Privacy.PRIVATE; Enum.TryParse(privacy, out updatedPrivacy); user.Privacy = updatedPrivacy; var last = _registrationRepository.GetLast(mailAdress); if (last != null) { last.Privacy = updatedPrivacy; _registrationRepository.Update(last, mailAdress); user.Registrations = _registrationRepository.GetAllFromUser(mailAdress); } // Update User _userRepository.Update(user); return Ok(user.Privacy); } /// <summary> /// Adds Admin role to user with given email /// </summary> /// <param name="email">Email of user that needs to become an admin</param> /// <returns>Ok, or NotFound if email isn't known, or Unauthorized if current user isn't admin or BadRequest if current user doesn't exist</returns> [HttpPost(nameof(AddAdmin))] public async Task<ActionResult> AddAdmin(string email) { AppUser user = await _userManager.FindByEmailAsync(email); if (user == null) return NotFound("User not found"); string mailAddressCurrentUser = User.Identity.Name; if (mailAddressCurrentUser == null || mailAddressCurrentUser.Equals("")) return Unauthorized("User not found"); //Checks if current user exists AppUser admin = await _userManager.FindByEmailAsync(mailAddressCurrentUser); if (admin == null ) return BadRequest("User not found"); //Create Admin role if (!await _roleManager.RoleExistsAsync("admin")) await _roleManager.CreateAsync(new MongoRole("admin")); //Checks if current user is admin if (!admin.IsAdmin()) return Unauthorized("You need admin permissions to perform this action"); //Add to be updated user to admin role await _userManager.AddToRoleAsync(user, "admin"); await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, "admin")); return Ok(); } /// <summary> /// Removes Admin role from user with given email /// </summary> /// <param name="email">Email of user that needs to be removed</param> /// <returns>Ok or NotFound if user isn't valid, or Unauthorized if current user isn't valid/admin or NotFound if given email isn't valid</returns> [HttpPost(nameof(RemoveAdmin))] public async Task<ActionResult> RemoveAdmin(string email) { //Checks if given email is valid AppUser user = await _userManager.FindByEmailAsync(email); if (user == null) return NotFound("User not found"); //Checks if current user is admin string mailAdress = User.Identity.Name; if (mailAdress == null || mailAdress.Equals("")) return Unauthorized("User not found"); AppUser admin = await _userManager.FindByEmailAsync(mailAdress); if (admin == null) return BadRequest("User not found"); if (!admin.IsAdmin()) return Unauthorized("You need admin permissions to perform this action"); //Remove user from role await _userManager.RemoveFromRoleAsync(user, "admin"); await _userManager.RemoveClaimAsync(user, new Claim(ClaimTypes.Role, "admin")); return Ok(); } /// <summary> /// Checks if currents user is admin /// </summary> /// <returns>ok with boolean if user is admin</returns> [HttpGet(nameof(IsAdmin))] public async Task<ActionResult> IsAdmin() { string mailAdress = User.Identity.Name; if (mailAdress == null || mailAdress.Equals("")) return Unauthorized("User not found"); AppUser admin = await _userManager.FindByEmailAsync(mailAdress); if (admin == null) return BadRequest("User not found"); return Ok(admin.IsAdmin()); } } }
// <copyright file="ViewDataExtensionsTests.cs" company="Morten Larsen"> // Copyright (c) Morten Larsen. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // </copyright> using System; using FluentAssertions; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Xunit; namespace AspNetWebpack.AssetHelpers.Tests { public sealed class ViewDataExtensionsTests { [Fact] public void GetBundleName_Null_ShouldThrowArgumentNullException() { // Act Action act = () => ((ViewDataDictionary)null!).GetBundleName(); // Assert act.Should().ThrowExactly<ArgumentNullException>(); } [Fact] public void GetBundleName_Null_ShouldReturnNull() { // Arrange var viewData = new ViewDataDictionary<dynamic>(new EmptyModelMetadataProvider(), new ModelStateDictionary()); // Act var result = viewData.GetBundleName(); // Assert result.Should().BeNull(); } [Fact] public void GetBundleName_Int_ShouldReturnNull() { // Arrange var viewData = new ViewDataDictionary<dynamic>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { { "Bundle", 123 }, }; // Act var result = viewData.GetBundleName(); // Assert result.Should().BeNull(); } [Fact] public void GetBundleName_Bundle_ShouldReturnBundleName() { // Arrange const string bundle = "TestBundle"; var viewData = new ViewDataDictionary<dynamic>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { { "Bundle", bundle }, }; // Act var result = viewData.GetBundleName(); // Assert result.Should().Be(bundle); } [Fact] public void GetBundleName_RazorPageBundle_ShouldReturnBundleName() { // Arrange const string bundle = "/Test/Bundle"; var viewData = new ViewDataDictionary<dynamic>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { { "Bundle", bundle }, }; // Act var result = viewData.GetBundleName(); // Assert result.Should().Be("Test_Bundle"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnalyticHierarchyProcess { class Program { public static void printResult(AnalyticHierarchyManager AHM) { Console.Clear (); printLogo (); try { Console.WriteLine ("Ваш выбор - {0}",AHM.OptionsList[AHM.Process()]); } catch(Exception e) { Console.WriteLine (e); } } public static void printLogo() { Console.WriteLine ("*******************"); Console.WriteLine ("TV SELECTOR v0.001"); Console.WriteLine ("*******************\n"); } public static void printScale() { Console.WriteLine ("ШКАЛА ОТНОСИТЕЛЬНОЙ ВАЖНОСТИ"); Console.WriteLine ("//////////////////////////////////////////////////////////////////////////"); Console.WriteLine ("1-равнозначно\t3-умеренно\t5-существенно\t7-значительное\t9-очевидное"); Console.WriteLine ("2,4,6,8 - промежуточные значения"); Console.WriteLine ("//////////////////////////////////////////////////////////////////////////\n"); } public static void fillCriteriasCompares(AnalyticHierarchyManager AHM) { for(int expert=0;expert<AHM.NumExpert;expert++) { AHM.PairComparisonList.Add (new PairComparison (AHM.NumCriteria)); Console.Clear (); printLogo (); printScale (); Console.WriteLine ("Отвечает эксперт №{0}",expert+1); for (int i = 0; i < AHM.NumCriteria-1; i++) { for (int j = i+1; j < AHM.NumCriteria; j++) { Console.WriteLine ("Насколько {0} важнее, чем {1}?",AHM.CriteriaData[i],AHM.CriteriaData[j]); double value = Convert.ToDouble (Console.ReadLine ()); AHM.PairComparisonList [expert].AddElement (i, j, value); } } Console.Clear (); } } public static void fillOptionsCompares(AnalyticHierarchyManager AHM) { for (int criteria = 0; criteria < AHM.NumCriteria;criteria++) { AHM.OptionsList.Add (new System.Collections.Generic.List<PairComparison>()); for (int expert = 0; expert < AHM.NumExpert; expert++) { Console.Clear (); printLogo (); printScale (); AHM.OptionsList [criteria].Add (new PairComparison (AHM.NumOptions)); Console.WriteLine ("Отвечает эксперт №{0}",expert+1); for (int i = 0; i < AHM.NumOptions-1; i++) { for (int j = i+1; j < AHM.NumOptions; j++) { Console.WriteLine ("Насколько {0} у {1} лучше, чем у {2}?",AHM.CriteriaData[criteria],AHM.OptionsData[i],AHM.OptionsData[j]); double value = Convert.ToDouble (Console.ReadLine ()); AHM.OptionsList [criteria] [expert].AddElement (i, j, value); } } } } } public static void Main (string[] args) { int NumExperts = 3; int NumCriterias = 4; int NumOptions = 3; AnalyticHierarchyManager AHM = new AnalyticHierarchyManager (); AHM.NumExpert = NumExperts; AHM.NumCriteria = NumCriterias; //AHM.CriteriaData.Add ("Диагональ"); //AHM.CriteriaData.Add ("Разрешение"); //AHM.CriteriaData.Add ("Производитель"); //AHM.CriteriaData.Add ("Цена"); //test data AHM.CriteriaData.Add ("A"); AHM.CriteriaData.Add ("B"); AHM.CriteriaData.Add ("C"); AHM.CriteriaData.Add ("D"); AHM.NumOptions = NumOptions; AHM.OptionsData.Add ("Samsung"); AHM.OptionsData.Add ("LG"); AHM.OptionsData.Add ("Sony"); fillCriteriasCompares (AHM); fillOptionsCompares (AHM); printResult (AHM); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Windows.Forms; using System.ComponentModel; using System.Collections.ObjectModel;//ObservableCollection namespace 重写音乐播放器 { class List { //public List<Music> MusicList = new System.Collections.Generic.List<Music>();//基本列表 //public List<Music> RandomList = new List<Music>();//乱序列表 //ObservableCollection表示一个动态数据集合,它可在添加、删除项目或刷新整个列表时提供通知。总之强烈推荐 public ObservableCollection<Music> MusicList = new ObservableCollection<Music>();//基本列表 public ObservableCollection<Music> RandomList = new ObservableCollection<Music>();//乱序列表 public void MakeMusicList(string directory)//将文件夹中音乐制成列表 { MusicList.Clear(); string[] fileArray = Directory.GetFiles(directory, "*.mp3");//GetFiles函数获得文件的名称(包含其路径) foreach(string file in fileArray) { FileInfo fileInfo = new FileInfo(file); MusicList.Add(new Music() { Title = fileInfo.Name, Path = Convert.ToString(fileInfo), AddTime= DateTime.Now});//依次写入文件名、文件地址、添加时间 #region /* FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read); fs.Seek(-128, SeekOrigin.End);//将读取位置移动至倒数128位 byte[] InfoByte=new byte[128]; fs.Read(InfoByte, 0, 128); fs.Close(); MusicList.Add(new Music() { Title = Encoding.Default.GetString(InfoByte, 3, 30), Artist = Encoding.Default.GetString(InfoByte, 33, 30), Album = Encoding.Default.GetString(InfoByte, 63, 30), }); */ #endregion//整个代码都是无效的 #region /*byte[] titleByte = new byte[30];//取出歌曲名byte int j = 0; int i; for (i = 2; i < 32; i++) { titleByte[j] = InfoByte[i]; j++; } byte[] artistByte = new byte[30];//取出艺术家byte j = 0; for (; i < 62; i++) { artistByte[j] = InfoByte[i]; j++; } byte[] albumByte = new byte[30]; j = 0; for (; i < 92; i++) { albumByte[j] = InfoByte[i]; j++; } MusicList.Add(new Music() { Title = Convert.ToString(titleByte), Artist = Convert.ToString(artistByte), Album = Convert.ToString(albumByte)});*/ #endregion } if (MusicList.Count == 0) { MessageBox.Show("所选文件夹内没有音乐文件", "垃圾播放器"); } } public void MakeRandomList() { ObservableCollection<Music> TempList = new ObservableCollection<Music>();//临时列表 foreach(Music music in MusicList)//不知道怎样快速做复制,只好这样了 { TempList.Add(new Music() { Title = music.Title, Path = music.Path, AddTime = music.AddTime }); } Random random = new Random(); for (int i = 0; i < MusicList.Count() ; i++) //循环次数为整个列表长度 { int j = random.Next(TempList.Count());//随机选中一个,为第j位 RandomList.Add(new Music() { Title = TempList[j].Title, Path = TempList[j].Path, AddTime = TempList[j].AddTime });//移到乱序表中 //TempList[j] = TempList[TempList.Count() - 1 - i];//将临时表中的第j位等于第【长度-i】位,下次循环i加1,第[长度-1]位就不考虑了 TempList[j] = TempList[TempList.Count() - 1];//将临时表中的第j位等于最后一位 TempList.RemoveAt(TempList.Count() - 1);//将最后一位移除 } } } }
using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TransferData.DataAccess.Entity.Mapping { public class MappingCarCapacity : MappingBase { } public class MappingCarCapacityConfig : EntityTypeConfiguration<MappingCarCapacity> { public MappingCarCapacityConfig() { ToTable("MappingCarCapacity"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Library.Models; namespace Library.Forms { public partial class Useres : Form { LibraryEntities3 db = new LibraryEntities3(); public Useres() { InitializeComponent(); Filladd(); } public void resetTo() { Filladd(); } public void Filladd() { dgvUserslist.Rows.Clear(); foreach (var item in db.Users.ToList()) { dgvUserslist.Rows.Add(item.Name, item.Surname, item.Phone, item.Id); } db.SaveChanges(); } private void btnBlack_Click(object sender, EventArgs e) { Home home = new Home(); home.Show(); this.Hide(); } private void btnAdd_Click(object sender, EventArgs e) { Users users = new Users(); if(string.IsNullOrEmpty(txtPhone.Text)|| string.IsNullOrEmpty(txtSurname.Text)|| string.IsNullOrEmpty(txtName.Text)) { MessageBox.Show("Bosluq buraxmayin"); } else { users.Phone = txtPhone.Text; users.Surname = txtSurname.Text; dgvUserslist.Rows.Add(users.Name, users.Surname, users.Phone); db.Users.Add(users); users.Name = txtName.Text; } if (txtName.Text != null ||txtPhone.Text!=null|| txtSurname.Text!=null) { txtName.Text = ""; txtSurname.Text = ""; txtPhone.Text = ""; db.SaveChanges(); resetTo(); } } private void Useres_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } private void btnDelet_Click(object sender, EventArgs e) { DialogResult d = MessageBox.Show("Istifadəçini silmək istyisizmi?", "İstifadəçi silindi", MessageBoxButtons.YesNo); if (d == DialogResult.Yes) { Models.Users toRemove = db.Users.Find(dgvUserslist.CurrentRow.Cells[3].Value); dgvUserslist.Rows.RemoveAt(dgvUserslist.CurrentRow.Index); db.Users.Remove(toRemove); db.SaveChanges(); MessageBox.Show("İstifadəçi silindi"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ImmigrantQuestions : AllQuestions { public ImmigrantQuestions() { this.allPossibleQuestions = new List<QuestionObject>(); Effect decreaseGold = new Effect(0, -10, 0); Effect hiredFriend = new Effect(0, 20, 30); Effect getFreeMoney = new Effect(15, 0, 0); Effect startedPayingMore = new Effect(0, 0, 10); Effect nothingNew = new Effect(0, 0, 0); Effect kickedOutNatives = new Effect(0, 20, 0); Effect joinedSmallCompany = new Effect(10, -5, -3); Effect gotSickForAWhile = new Effect(0, -20, 5); Effect claimBoughtOut = new Effect(30, -30, 5); Effect payTheMob = new Effect(0, 0, 30); Effect resistTheMob = new Effect(0, -5, 45); Effect payOffCredit = new Effect(0, 0, 5); Effect smallGoldDecrease = new Effect(0, -5, 0); Effect cheapSupplies = new Effect(0, 0, -10); Effect gotMoreGold = new Effect(0, 5, 0); Effect failedCompany = new Effect(0, -5, 50); Effect leftWhileYouHadTheChance = new Effect(5, -5, 10); QuestionObject q1 = new QuestionObject(getFreeMoney, nothingNew, "You are offered a job as a laundry worker for your camp.", "Accept", "Decline", "You manage to have steady work for a little while", "you continue to try to get gold"); QuestionObject q2 = new QuestionObject(payTheMob, resistTheMob, "An angry mob approaches your camp demanding you stop stealing the gold from California", "Try to pay them off", "Assert your right to mine here too", "They leave at great expence", "They take a lot of money's worth of supplies and equipment and force you to a different plot"); QuestionObject q3 = new QuestionObject(startedPayingMore, startedPayingMore, "Part of the debt from your crossing has come due", "Pay", "Try to dodge it", "You pay the ammount in full.", "Your attempts fail and you pay the ammount in full"); QuestionObject q6 = new QuestionObject(startedPayingMore, decreaseGold, "Your cradle breaks. You need a cradle to seperate dirt and gold, so you decide to replace it.", "You buy a new one", "You attempt to fixes yourself", "It costs you some money but you get back to work", "It doesn't work very well for some time and eventually you get one from someone going back east"); QuestionObject q7 = new QuestionObject(smallGoldDecrease, decreaseGold, "You are not eating right and feel your teeth loosening from scurvy.", "Eat grass, it might help", "Try to find better food", "It does help...", "You are unable to find a fruit vendor and you loose some teeth."); QuestionObject q8 = new QuestionObject(gotSickForAWhile, decreaseGold, "The wet season creates sickness throughout the camp and you become very sick.", "Rest to try to recover", "Keep working", "You recover, but find little gold", "You don't recover soon. You collect little and end up never fully recovering"); QuestionObject q9 = new QuestionObject(cheapSupplies, nothingNew, "A steam boat comes down the river", "Try to trade with it", "ignore it and stick with your current supplies", "The boat has cheap supplies that it is selling!", "Life goes on unchanged"); QuestionObject q10 = new QuestionObject(nothingNew, decreaseGold, "Your claim seems like it has no gold", "Stick with it and hope you eventually find gold", "try a new claim", "Your claim stays about the same", "Your new claim is worse than your original"); QuestionObject q11 = new QuestionObject(nothingNew, gotMoreGold, "Your claim seems like it has no gold", "Stick with it and hope you eventually find gold", "try a new claim", "Your claim stays about the same", "Your new claim is better than the last"); QuestionObject q12 = new QuestionObject(failedCompany, gotMoreGold, "One of your friends offers to let you buy into his company and work there for the next couple of months. Alternatively you could continue to work at prospecting.", "Sign on to your Friend's company", "Prospect in the nearby river", "Your group's attempts to divert water and mine a riverbed failed due to the heavy riverbed rocks and you make no money.", "The River had too much water and you have difficulty finding gold."); QuestionObject q13 = new QuestionObject(leftWhileYouHadTheChance, payTheMob, "You are informed the local government has banned Chinese miners from the county.", "Leave", "Try to stay", "You grab as much money as possible and move to another county", "You are are driven from the town by a mob. You left a lot behind"); QuestionObject q14 = new QuestionObject(startedPayingMore, payTheMob, "You decide to send some gold back home.", "Send a few small nuggets", "Send much of what you have", "Your family's status back in China slightly improves", "Your family's status back in China greatly improves and you recieve a letter informing you that you have a marriage planned if you return"); this.allPossibleQuestions.Add(q3); this.allPossibleQuestions.Add(q1); this.allPossibleQuestions.Add(q2); this.allPossibleQuestions.Add(q6); this.allPossibleQuestions.Add(q7); this.allPossibleQuestions.Add(q8); this.allPossibleQuestions.Add(q9); this.allPossibleQuestions.Add(q10); this.allPossibleQuestions.Add(q11); this.allPossibleQuestions.Add(q12); this.allPossibleQuestions.Add(q13); this.allPossibleQuestions.Add(q14); this.lastQuestion = new QuestionObject(null, null, "", "", "", "", ""); } protected override QuestionObject GetQuestionObject(int year) { QuestionObject q4 = new QuestionObject(new Effect(0, 0, 20), new Effect(-1000, -1000, -1000), "California passes the Foreign Miners Tax of 1850. You are forced to pay a large fee on your claims. It is $20.", "Pay", "Don't pay", "You pay the tax", "you are deported"); QuestionObject q5 = new QuestionObject(new Effect(0, 0, 10), new Effect(-1000, -1000, -1000), "The original Foreign Miners Tax has been was repealed, but has now been replaced with a new Foreign Miners Tax.", "Pay now and live on less supplies in the future", "Don't pay", "You pay the new monthly fee", "you are deported"); QuestionObject potential; if (year == 1850) { potential = q4; } else if (year == 1852) { potential = q5; } else { potential = this.allPossibleQuestions[Random.Range(0, allPossibleQuestions.Count)]; } while (potential.question == this.lastQuestion.question) { potential = this.allPossibleQuestions[Random.Range(0, this.allPossibleQuestions.Count)]; } this.lastQuestion = potential; return potential; } }
using System; using System.Windows; using System.Windows.Shapes; using System.Windows.Controls; namespace MinecraftToolsBoxSDK { public class DragChangedEventArgs : RoutedEventArgs { public DragChangedEventArgs(RoutedEvent Event, Rect NewBound, object Target = null) : base(Event) { this.NewBound = NewBound; DragTargetElement = Target; } public Rect NewBound { get; private set; } public object DragTargetElement { get; private set; } } public delegate void DragChangedEventHandler(object Sender, DragChangedEventArgs e); }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameManager : MonoBehaviour { public static GameManager Instance; public static string currentToll = "nenhuma"; public Image Select; public Image Select1; public Image Select2; public Image Select3; public Image Select4; public Image Select5; public float venda = 0; public Text DinheiroTXT; public int energia = 100; public Text energiaPorcentagem; public int sementesRestantes = 3; public Text sementesDisponiveis; public int sementesRestantes2 = 0; public Text sementesDisponiveis2; public int sementesRestantes3 = 0; public Text sementesDisponiveis3; public GameObject gameover; private void Awake() { if (!Instance) { Instance = this; } DesativaSelects(); } private void Update() { Loja.carteira = venda; sementesDisponiveis.text = sementesRestantes.ToString(); sementesDisponiveis2.text = sementesRestantes2.ToString(); sementesDisponiveis3.text = sementesRestantes3.ToString(); GameOver(); } public void AddPoint(float value) { venda += value; DinheiroTXT.text = venda.ToString(); } public void RemovePoint(float value) { venda -= value; DinheiroTXT.text = venda.ToString(); } public void EnergyLost(int energiaGasta) { energia -= energiaGasta; energiaPorcentagem.text = energia.ToString(); } public void RechargedEnergy(int recharge) { energia = recharge; energiaPorcentagem.text = energia.ToString(); } public void Plantado(int plantou) { sementesRestantes -= plantou; sementesDisponiveis.text = sementesRestantes.ToString(); } public void Plantado2(int plantou) { sementesRestantes2 -= plantou; sementesDisponiveis2.text = sementesRestantes2.ToString(); } public void Plantado3(int plantou) { sementesRestantes3 -= plantou; sementesDisponiveis3.text = sementesRestantes3.ToString(); } public void DesativaSelects() { Select.enabled = false; Select1.enabled = false; Select2.enabled = false; Select3.enabled = false; Select4.enabled = false; Select5.enabled = false; } public void GameOver() { if (PlantControl.temsementenochao == false && venda <= 0.4 && sementesRestantes == 0 && sementesRestantes2 == 0 && sementesRestantes3 == 0 && Calendario.hour == 02 || energia <= 0) { gameover.SetActive(true); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Data.SqlClient; namespace SoundServant { /// <summary> /// Interaction logic for LoadWindow.xaml /// </summary> public partial class ChangePasswordWindow : SSWindow { Congregation congregation; public ChangePasswordWindow(Congregation _congregation) { InitializeComponent(); congregation = _congregation; } public static new void Show(Congregation _cong) { ChangePasswordWindow changePasswordWindow = new ChangePasswordWindow(_cong); changePasswordWindow.ShowDialog(); } private void OkButton_Click(object sender, RoutedEventArgs e) { if (OldPasswordTouchBox.Text == congregation.Password) { if (NewPassword1TouchBox.Text == NewPassword2TouchBox.Text) { congregation.Password = NewPassword1TouchBox.Text; Logs.Information("Password", "Congregation Password Changed"); this.Closing -= Window_Closing; this.Close(); } else { SSMessageBox.Show("Passwords Don't Match", "The new passwords you have enetered do not match. Try again!.", SSMessageBoxType.Ok); } } else { SSMessageBox.Show("Incorrect Password", "The old password you have entered is not correct. Try again!", SSMessageBoxType.Ok); } } private void CancelButton_Click(object sender, RoutedEventArgs e) { this.Closing -= Window_Closing; this.Close(); } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { e.Cancel = true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CameraTestManager : MonoBehaviour { [Header("Canvasses")] [SerializeField] private GameObject CameraCanvas; [SerializeField] private Canvas GalleryCanvas; [Header("PhoneCamera")] [SerializeField] private GameObject CameraPlane; private Animator CameraCanvasAnimator; void Start() { CameraPlane.transform.position = new Vector3(0, 0, 5); //CameraCanvas.SetActive(true); //GalleryCanvas.enabled = false; CameraCanvasAnimator = CameraCanvas.GetComponent<Animator>(); OpenCamera(); } private void Update() { if (CameraCanvas.activeSelf) CameraPlane.SetActive(true); else CameraPlane.SetActive(false); } public void OpenGallery() { CameraCanvas.SetActive(false); GalleryCanvas.enabled = true; } public void OpenCamera() { CameraCanvas.SetActive(true); GalleryCanvas.enabled = false; CameraCanvasAnimator.SetTrigger("StartEnter"); } }
using UnityEngine; /// <summary> /// 自動生成のテスト用スクリプト /// </summary> public class TestCreater : MonoBehaviour { public FieldBlockMeshCombine blockMap = new FieldBlockMeshCombine(); void Start() { GameObject parentTemp = new GameObject("FieldObjectTemp"); BlockCreater.GetInstance().AutoGenerate(AutoGeneration.Generate(3, 0.9f), parentTemp.transform, blockMap); parentTemp.isStatic = true; blockMap.BlockIsSurroundUpdate(); blockMap.BlockRendererOff(); GameObject parent = new GameObject("FieldObject"); blockMap.Initialize(parent); } void Update() { blockMap.CreateMesh(); } }
#region License /** * Copyright (c) 2013 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file). * Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SharpNav { /// <summary> /// A class where all the small, miscellaneous math functions are stored. /// </summary> internal static class MathHelper { private static readonly int[] DirOffsetsX = { -1, 0, 1, 0 }; private static readonly int[] DirOffsetsY = { 0, 1, 0, -1 }; /// <summary> /// Gets an X offset. /// </summary> /// <remarks> /// The directions cycle between the following, starting from 0: west, north, east, south. /// </remarks> /// <param name="dir">The direction.</param> /// <returns>The offset for the X coordinate.</returns> internal static int GetDirOffsetX(int dir) { return DirOffsetsX[dir % 4]; } /// <summary> /// Get a Y offset. /// </summary> /// <remarks> /// The directions cycle between the following, starting from 0: west, north, east, south. /// </remarks> /// <param name="dir">The direction.</param> /// <returns>The offset for the Y coordinate.</returns> internal static int GetDirOffsetY(int dir) { return DirOffsetsY[dir % 4]; } /// <summary> /// Clamps an integer value to be within a specified range. /// </summary> /// <param name="val">The value to clamp.</param> /// <param name="min">The inclusive minimum of the range.</param> /// <param name="max">The inclusive maximum of the range.</param> /// <returns>The clamped value.</returns> internal static int Clamp(int val, int min, int max) { return val < min ? min : (val > max ? max : val); } /// <summary> /// Clamps an integer value to be within a specified range. /// </summary> /// <param name="val">The value to clamp.</param> /// <param name="min">The inclusive minimum of the range.</param> /// <param name="max">The inclusive maximum of the range.</param> internal static void Clamp(ref int val, int min, int max) { val = val < min ? min : (val > max ? max : val); } /// <summary> /// Clamps an integer value to be within a specified range. /// </summary> /// <param name="val">The value to clamp.</param> /// <param name="min">The inclusive minimum of the range.</param> /// <param name="max">The inclusive maximum of the range.</param> /// <returns>The clamped value.</returns> internal static uint Clamp(uint val, uint min, uint max) { return val < min ? min : (val > max ? max : val); } /// <summary> /// Clamps an integer value to be within a specified range. /// </summary> /// <param name="val">The value to clamp.</param> /// <param name="min">The inclusive minimum of the range.</param> /// <param name="max">The inclusive maximum of the range.</param> internal static void Clamp(ref uint val, uint min, uint max) { val = val < min ? min : (val > max ? max : val); } } }
using CC.Web.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CC.Web.Dao.Core { public class BaseDao<T> : IBaseDao<T> where T : class, IEntity { public IRepository<T> Repository { get; set; } /// <inheritdoc /> public void Delete(Guid Id) { Repository.Delete(Id); } /// <inheritdoc /> public void Delete(IEnumerable<Guid> Ids) { Repository.Delete(Ids); } /// <inheritdoc /> public T Find(Guid Id, bool includeDel = false) { if (includeDel) { return Repository.Find(Id); } else { var entity = Repository.Find(Id); return entity.Deleted ? null : entity; } } /// <inheritdoc /> public IQueryable<T> Find(IEnumerable<Guid> Ids, bool includeDel = false) { if (includeDel) return Repository.Find(Ids); else return Repository.Find(Ids).Where(e => !e.Deleted); } public Guid Insert(T entity) { return Repository.Insert(entity); } public IEnumerable<Guid> Insert(IEnumerable<T> entities) { return Repository.Insert(entities); } public void Remove(Guid Id) { Repository.Remove(Id); } public void Remove(IEnumerable<Guid> Ids) { Repository.Remove(Ids); } public void Update(T entity) { Repository.Update(entity); } public void Update(IEnumerable<T> entity) { Repository.Update(entity); } } }
using System; using System.Collections.Generic; using Object = UnityEngine.Object; namespace Daz3D { [Serializable] public class ImportEventRecord { public DateTime Timestamp = DateTime.Now; public struct Token { public string Text; public Object Selectable; public bool EndLine; } public List<Token> Tokens = new List<Token>(); public bool Unfold = true; internal void AddToken(string str, Object obj = null, bool endline = false) { Tokens.Add(new Token {Text = str, Selectable = obj, EndLine = endline}); } } public static class RecordExtensions { public static void FoldAll(this Queue<ImportEventRecord> records) { foreach (var record in records) record.Unfold = false; } } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace testMonogame { class GoriyaEnemy : ISprite, IEnemy { public int X { get; set; } public int Y { get; set; } Random randomNumber = new Random(); int directionCounter; int directionFrame; int direction; int health; public IGoriyaState state; Texture2D texture; Texture2D projTexture; bool throwing; int throwCounter; public GoriyaEnemy(Texture2D inTexture, Texture2D inProjTexture, Vector2 position) { texture = inTexture; projTexture = inProjTexture; state = new GoriyaWL(texture, projTexture, this); health = 3; X = (int)position.X; Y = (int)position.Y; directionCounter = 0; directionFrame = randomNumber.Next(200); direction = randomNumber.Next(1, 4); } public int getHealth() { return health; } public void Move(int xChange, int yChange) { X += xChange * (int)GameplayConstants.ENEMY_SPEED_MODIFIER; Y += yChange * (int)GameplayConstants.ENEMY_SPEED_MODIFIER; directionCounter += 1; if (directionCounter > directionFrame) { directionCounter = 0; directionFrame = randomNumber.Next(200); direction = randomNumber.Next(1, 4); changeState(direction); } } public void takeDamage(int dmg) { health -= dmg; } public void Attack(IPlayer player) { player.TakeDamage(2); } public void setThrow(bool isThrow) { throwing = isThrow; } public bool getThrow() { return throwing; } public void changeState(int direction) { /* * 1 = Down * 2 = Up * 4 = Right * 3 = Left * Default = Down */ switch (direction) { case 1: state = new GoriyaWD(texture, projTexture, this); break; case 2: state = new GoriyaWU(texture, projTexture, this); break; case 3: state = new GoriyaWL(texture, projTexture, this); break; case 4: state = new GoriyaWR(texture, projTexture, this); break; default: state = new GoriyaWD(texture, projTexture, this); break; } } //public int getX() //{ // return x; //} //public int getY() //{ // return y; //} public void Draw(SpriteBatch spriteBatch) { state.Draw(spriteBatch); } public void Update(GameManager game) { throwCounter += 1; if (throwCounter > 600) { setThrow(true); state.spawnBoomerang(game); throwCounter = 0; } state.Update(game); } public void Move() { //Do Nothing, movement is handled by the other move method recieving values that are passed in by states } public Rectangle getDestRect() { return state.getDestRect(); } } }
using GodaddyWrapper.Responses; using GodaddyWrapper.Requests; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using GodaddyWrapper.Helper; namespace GodaddyWrapper { public partial class Client { /// <summary> /// Add expiry listings into GoDaddy Auction /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task<AftermarketListingActionResponse> AddExpiryAuction(List<AftermarketListingExpiryCreate> request) { var client = GetBaseHttpClient(); var response = await client.PostAsync($"aftermarket/listings/expiry", request); await CheckResponseMessageIsValid(response); return await response.Content.ReadAsAsync<AftermarketListingActionResponse>(); } /// <summary> /// Remove listings from GoDaddy Auction /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task<ListingActionResponse> RemoveAuctionListings(AggreementRetrieve request) { var client = GetBaseHttpClient(); var response = await client.DeleteAsync($"aftermarket/listings{QueryStringBuilder.RequestObjectToQueryString(request)}"); await CheckResponseMessageIsValid(response); return await response.Content.ReadAsAsync<ListingActionResponse>(); } } }