text
stringlengths
13
6.01M
/// <summary> /// Player controller. /// Arlina Ramrattan /// 300799246 /// Last Modified by: A.R. /// Date last modified: October 22, 2016 /// This program is a 2D top down scroller. The plyer is a green tank and they have to try and avoid the red enemy tanks. They have 5 lives. /// </summary> using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { // PUBLIC INSTANCE VARIABLES +++++++++++++++++++++++++++++++++++++++ //public float speed; public Boundary boundary; // get a reference to the camera to make mouse input work public Camera camera; // PRIVATE INSTANCE VARIABLES private Vector2 _newPosition = new Vector2(0.0f, 0.0f); public GameController gameController; // Use this for initialization void Start () { } // Update is called once per frame void Update () { this._CheckInput (); } private void _CheckInput() { this._newPosition = gameObject.GetComponent<Transform> ().position; // current position /* movement by keyboard if (Input.GetAxis ("Horizontal") > 0) { this._newPosition.x += this.speed; // add move value to current position } if (Input.GetAxis ("Horizontal") < 0) { this._newPosition.x -= this.speed; // subtract move value to current position } */ // movement by mouse Vector2 mousePosition = Input.mousePosition; this._newPosition.x = this.camera.ScreenToWorldPoint (mousePosition).x; this._BoundaryCheck (); gameObject.GetComponent<Transform>().position = this._newPosition; } private void OnTriggerEnter2D(Collider2D other){ if(other.gameObject.CompareTag("Enemy")){ Debug.Log ("Enemy Hit!"); this.gameController.LivesValue -= 1; } } private void _BoundaryCheck() { if (this._newPosition.x < this.boundary.xMin) { this._newPosition.x = this.boundary.xMin; } if (this._newPosition.x > this.boundary.xMax) { this._newPosition.x = this.boundary.xMax; } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("DemoMgr")] public class DemoMgr : MonoClass { public DemoMgr(IntPtr address) : this(address, "DemoMgr") { } public DemoMgr(IntPtr address, string className) : base(address, className) { } public void ApplyAppleStoreDemoDefaults() { base.method_8("ApplyAppleStoreDemoDefaults", Array.Empty<object>()); } public bool ArenaIs1WinMode() { return base.method_11<bool>("ArenaIs1WinMode", Array.Empty<object>()); } public bool CantExitArena() { return base.method_11<bool>("CantExitArena", Array.Empty<object>()); } public void ChangeDemoText(string demoText) { object[] objArray1 = new object[] { demoText }; base.method_8("ChangeDemoText", objArray1); } public void CreateDemoText(string demoText) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String }; object[] objArray1 = new object[] { demoText }; base.method_9("CreateDemoText", enumArray1, objArray1); } public void CreateDemoText(string demoText, bool unclickable) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String, Class272.Enum20.Boolean }; object[] objArray1 = new object[] { demoText, unclickable }; base.method_9("CreateDemoText", enumArray1, objArray1); } public void CreateDemoText(string demoText, bool unclickable, bool shouldDoArenaInstruction) { object[] objArray1 = new object[] { demoText, unclickable, shouldDoArenaInstruction }; base.method_9("CreateDemoText", new Class272.Enum20[] { Class272.Enum20.String }, objArray1); } public void DemoTextLoaded(string actorName, GameObject actorObject, object callbackData) { object[] objArray1 = new object[] { actorName, actorObject, callbackData }; base.method_8("DemoTextLoaded", objArray1); } public static DemoMgr Get() { return MonoClass.smethod_15<DemoMgr>(TritonHs.MainAssemblyPath, "", "DemoMgr", "Get", Array.Empty<object>()); } public DemoMode GetMode() { return base.method_11<DemoMode>("GetMode", Array.Empty<object>()); } public DemoMode GetModeFromString(string modeString) { object[] objArray1 = new object[] { modeString }; return base.method_11<DemoMode>("GetModeFromString", objArray1); } public string GetStoredGameMode() { return base.method_13("GetStoredGameMode", Array.Empty<object>()); } public void Initialize() { base.method_8("Initialize", Array.Empty<object>()); } public bool IsCurrencyEnabled() { return base.method_11<bool>("IsCurrencyEnabled", Array.Empty<object>()); } public bool IsDemo() { return base.method_11<bool>("IsDemo", Array.Empty<object>()); } public bool IsExpoDemo() { return base.method_11<bool>("IsExpoDemo", Array.Empty<object>()); } public bool IsHubEscMenuEnabled() { return base.method_11<bool>("IsHubEscMenuEnabled", Array.Empty<object>()); } public bool IsSocialEnabled() { return base.method_11<bool>("IsSocialEnabled", Array.Empty<object>()); } public void MakeDemoTextClickable(bool clickable) { object[] objArray1 = new object[] { clickable }; base.method_8("MakeDemoTextClickable", objArray1); } public void NextDemoTipIsNewArenaMatch() { base.method_8("NextDemoTipIsNewArenaMatch", Array.Empty<object>()); } public void RemoveDemoTextDialog() { base.method_9("RemoveDemoTextDialog", new Class272.Enum20[0], Array.Empty<object>()); } public void RemoveDemoTextDialog(UIEvent e) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Class }; object[] objArray1 = new object[] { e }; base.method_9("RemoveDemoTextDialog", enumArray1, objArray1); } public void SetMode(DemoMode mode) { object[] objArray1 = new object[] { mode }; base.method_8("SetMode", objArray1); } public void SetModeFromString(string modeString) { object[] objArray1 = new object[] { modeString }; base.method_8("SetModeFromString", objArray1); } public bool ShouldShowWelcomeQuests() { return base.method_11<bool>("ShouldShowWelcomeQuests", Array.Empty<object>()); } public void WillReset() { base.method_8("WillReset", Array.Empty<object>()); } public static bool LOAD_STORED_SETTING { get { return MonoClass.smethod_6<bool>(TritonHs.MainAssemblyPath, "", "DemoMgr", "LOAD_STORED_SETTING"); } } public Triton.Game.Mapping.Notification m_demoText { get { return base.method_3<Triton.Game.Mapping.Notification>("m_demoText"); } } public DemoMode m_mode { get { return base.method_2<DemoMode>("m_mode"); } } public bool m_nextDemoTipIsNewArenaMatch { get { return base.method_2<bool>("m_nextDemoTipIsNewArenaMatch"); } } public bool m_nextTipUnclickable { get { return base.method_2<bool>("m_nextTipUnclickable"); } } public bool m_shouldGiveArenaInstruction { get { return base.method_2<bool>("m_shouldGiveArenaInstruction"); } } } }
using Mirror; using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameTimer : MonoBehaviour { // public NetworkManager netManager; // private float timer; // // Start is called before the first frame update // void Start() // { // timer = 0f; // } //// Update is called once per frame // void Update() // { // timer += Time.deltaTime; // if (timer > 10f) // { // timer = 0f; // CmdEndGame("Start menu"); // } // } // [Command] // public void CmdEndGame(string level) // { // NetworkManager.singleton.ServerChangeScene(level); // } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LevelChanger : MonoBehaviour { private Animator anim; private string levelName; // Start is called before the first frame update void Start() { anim = GetComponent<Animator>(); } // Update is called once per frame void Update() { } public void FadeToLevel(string name) { levelName = name; anim.SetTrigger("FadeOut"); } public void OnFadeComplete() { SceneManager.LoadScene(levelName); } }
using UnityEngine; using System.Collections; public class UIMgr : SingletonMonoBefaviour<UIMgr> { string mName = ""; //UIのプレハブを格納する変数 [SerializeField] GameObject MainCanvas; [SerializeField] GameObject TitleCanvas; //現在表示してるUIのゲームオブジェクトを格納する変数 public GameObject UIObject; public enum ButtonState { NONE = -1, FILE, //ファイル読み込み BRANCH, //分岐ボタン } public enum State { NONE = -1, TITLE, //タイトル画面 MAIN, //コンテンツ画面 } [SerializeField] ButtonState mButtonState; //今表示されているボタンの状態 [SerializeField] public State mState; //アプリの今の状態 void Start() { } //ラベル名やファイルパスを受け取ってテキストマネージャに投げる public void SetStringName(string n) { mName = n; switch (mButtonState) { case ButtonState.BRANCH: TextMgr.Instance.Branch(mName); break; case ButtonState.FILE: TextMgr.Instance.setFilePath(mName); break; case ButtonState.NONE: default: //Debug.LogError("ARIENAI"); break; } } //タイトルとゲーム画面を切り替える public void ChangeState(State s) { mState = s; switch (mState) { case State.TITLE: ChangeUI(TitleCanvas); TextMgr.Instance.DeleteAll(); ImageMgr.Instance.DeleteAll(); CharaMgr.Instance.DeleteAll(); BackGroundMgr.Instance.DeleteAll(); MusicMgr.Instance.Change(false); TextMgr.Instance.mMainFlg = false; break; case State.MAIN: ChangeUI(MainCanvas); GameObject g = UIObject.GetComponent<TextField>().mTextField; GameObject n = UIObject.GetComponent<charaname>().mNameText; BackGroundMgr.Instance.mBackGround = UIObject.GetComponent<BackGroundObj>().mBackGround; TextMgr.Instance.SetTextField(g); TextMgr.Instance.SetNameField(n); MusicMgr.Instance.Change(true); TextMgr.Instance.mMainFlg = true; break; case State.NONE: break; default: break; } } //渡されてるのはラベル名かファイル名かを設定 public void SetButtonState(ButtonState bs) { mButtonState = bs; } //ゲーム画面に切り替わるときの処理 void ChangeUI(GameObject Act) { Destroy(UIObject); UIObject = (GameObject)Instantiate(Act, Vector3.zero, Quaternion.identity); } }
using System.Collections.Generic; using MusicPlayer.Core.Models; namespace MusicPlayer.Core.SongFilesManager.Interfaces { public interface IPlaylistFilesManager { List<Playlist> ReadSongsFromFile(); void SaveNewPlaylist(); void UpdatePlaylistName(string oldName, string newName); } }
// Copyright 2017-2019 Elringus (Artyom Sovetnikov). All Rights Reserved. using System.Threading.Tasks; using UnityCommon; using UnityEngine; namespace Naninovel.UI { public class ContinueInputUI : CustomUI, IContinueInputUI { private InputManager inputManager; [SerializeField] private GameObject trigger = default; public override Task InitializeAsync () { inputManager?.Continue?.AddObjectTrigger(trigger); return Task.CompletedTask; } protected override void Awake () { base.Awake(); this.AssertRequiredObjects(trigger); inputManager = Engine.GetService<InputManager>(); } protected override void OnDestroy () { base.OnDestroy(); inputManager?.Continue?.RemoveObjectTrigger(trigger); } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MISA.BL.Interfaces; using MISA.Common.Entitis; using MISA.CukCuk.Api.Controllers; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MISA.AMIS.Api.Controllers { [Route("api/v1/[controller]s")] [ApiController] public class EmployeeDepartmentController : MISAEntityController<EmployeeDepartment> { public EmployeeDepartmentController(IBaseBL<EmployeeDepartment> baseBL):base(baseBL) { } } }
using KnapsackProblem.Common; using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnapsackProblem.ConstructiveVersion.Strategies { public class ConstructiveGreedy : ConstructiveStrategy { public override void FreeAll() { } public override ConstructiveResult Solve(KnapsackInstance instance) { //Make a shallow copy of instances list in order to not affect next possible execution var sorted = new List<KnapsackItem>(instance.Items); sorted.OrderByDescending(i => i.Price / i.Weight); var addedItemsVector = new bool[instance.ItemCount]; var currentWeight = 0; var currentPrice = 0; foreach(var item in sorted) { if (currentWeight + item.Weight > instance.KnapsackSize) break; currentPrice += item.Price; currentWeight += item.Weight; addedItemsVector[item.Id] = true; } return new ConstructiveResult { KnapsackInstance = instance, Configuration = new KnapsackConfiguration { ItemVector = addedItemsVector.ToList(), Price = currentPrice, Weight = currentWeight } }; } } }
using Assets.Scripts.Enemies.Enums; using Assets.Scripts.Enemies.Interfaces; using UnityEngine; namespace Assets.Scripts.Enemies.CommandAndControl { public class SquadronFactory { EnemyFactory enemyFactory; public SquadronFactory() { enemyFactory = new EnemyFactory(); } public Squadron CreateSquadron(int power, Vector2 squadronLocation) { var squadron = new Squadron(power); var squadronColor = new Color(Random.value, Random.value, Random.value); for (var i = 0; i < power; i++) { var result = Random.Range(0, 6); var spawnOffset = new Vector2(Random.Range(-8, 8), Random.Range(-8, 8)); IEnemy enemy = null; var shipPower = Random.Range(1, 4); switch (result) { case 0: case 1: case 2: enemy = enemyFactory.MakeEnemy(EnemyType.Kamikaze, shipPower, squadronColor, squadronLocation + spawnOffset); break; case 3: case 4: enemy = enemyFactory.MakeEnemy(EnemyType.Tank, shipPower, squadronColor, squadronLocation + spawnOffset); break; case 5: enemy = enemyFactory.MakeEnemy(EnemyType.Paladin, shipPower, squadronColor, squadronLocation + spawnOffset); break; default: break; } squadron.AddShip(enemy); } return squadron; } } }
using caterapp.Model; using caterapp.Repositories; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; namespace caterapp.Controllers { [Route("api/[controller]")] public class EventController : Controller { private IEventRepository _eventRepository; public EventController(IEventRepository eventRepository) { _eventRepository = eventRepository; } [HttpGet("[action]")] public IActionResult List() { return Json(_eventRepository.List()); } [HttpPost("[action]")] public IActionResult Create([FromBody] Event model) { if (model.Id == 0) _eventRepository.Save(model); else _eventRepository.Update(model); return Ok(model); } [HttpGet("[action]/{id}")] public IActionResult Get(int id) { var result = _eventRepository.Get(id); if (result == null) return NotFound(); return Json(result); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Excepciones { public class ArchivosException:Exception { #region constructores public ArchivosException(string menssage):base(menssage) { } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Baseball { class Bat { //uses: // delegate void BatCallback(BallEventArgs e); // //*** The easiest way to keep the wrong Ball objects from // chaining themselves onto the Bat’s delegate is for // the bat to make it private. That way, it has control // over which Ball object’s method gets called. private BatCallback del_hitBallCallback; public Bat(BatCallback callbackDelegate) { // ball creates the bat object, supplying its // OnBallInPlay event as the callbackDelegate this.del_hitBallCallback = new BatCallback(callbackDelegate); } // now that the del_hitBallCallback has ben set, // we can use it to call the Event OnBallInPlay // which Fan and Pitcher have subscribed to. public void HitTheBall(BallEventArgs e) { // ALWAYS check that an event or delegate is not null // before you use it to avoid a NullReferenceException. if (del_hitBallCallback != null) del_hitBallCallback(e); } /* * * */ }//END END }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IES.JW.Model; namespace IES.Common.Data { /// <summary> /// 通过课程获取课程的相关数据 /// </summary> public class CourseCommonData { /// <summary> /// 获取课程下教学班 /// </summary> /// <param name="userid"></param> /// <param name="courseid"></param> /// <returns></returns> public static List<TeachingClass> Course_TeachingClass_Get(string userid, string courseid) { return new List<TeachingClass>(); } } }
using System; using System.ComponentModel.DataAnnotations; namespace DemoApp.Model.ViewModels { public class Target { public int TargetId { get; set; } public Guid TargetUid { get; set; } [Required] [Display(ResourceType = typeof(ModelResources), Name = "Label_TargetSerialNumber")] public int SerialNumber { get; set; } [Required] [Display(ResourceType = typeof(ModelResources), Name = "Label_ModelType")] public int ModelTypeId { get; set; } public string ModelTypeDescription { get; set; } public Guid MezzanineUid { get; set; } [Required] [Display(ResourceType = typeof(ModelResources), Name = "Label_MezzanineDescription")] public int MezzanineId { get; set; } public int MezzanineInternalId { get; set; } public string MezzanineDescription { get; set; } [Required] [Display(ResourceType = typeof(ModelResources), Name = "Label_TargetIsActive")] public bool Active { get; set; } public DateTime DateCreated { get; set; } public DateTime DateModified { get; set; } } }
public class GameConstant { /* CONSTANT */ public static int UNLOCK_SLOT_PRICE = 500; public static int MISSION_LIST = 50; public static int TOTAL_TUTORIAL = 18; /*Screen state*/ public const string LOGO_STATE = "LOGO"; public const string MAIN_MENU = "MAIN_MENU"; public const string STORY = "STORY"; public const string MAP_STATE = "MapScreen"; public const string OPTION = "OptionScreen"; public const string RAID_NOTIFICATION = "RaidScreen"; public const string GAMEPLAY_SCENE = "GameplayScreen"; public const string REPORT_SCENE = "ReportScreen"; /*Gem id*/ public const string COMMON_GEM = "common"; public const string UNCOMMON_GEM = "uncommon"; public const string RARE_GEM = "rare"; public const string MYTHICAL_GEM = "mythical"; public const string LEGENDARY_GEM = "legendary"; public const string tutorialTextOne = "Greetings, my name is Floo. After our king died,\n"+ "the continent is divided into six kingdom. I want\n"+ "to unite it once more by conquer all of the kingdom!.\n"+ "But first, i must prove myself first to my kingdom!\n"+ "Please help me!"; public const string two = "Tap on the stage to attack and conquer!"; public const string three = "Uh oh, looks like we need company!, tap the barrack button please!"; }
using Checkout.Payment.Command.Application.Interfaces; using Checkout.Payment.Command.Application.Models; using Checkout.Payment.Command.Domain; using Checkout.Payment.Command.Domain.Models.Enums; using Checkout.Payment.Command.Seedwork.Extensions; using MediatR; using System; using System.Threading.Tasks; namespace Checkout.Payment.Command.Application.Services { public class PaymentService : IPaymentService { private readonly IMediator _mediator; public PaymentService(IMediator mediator) { _mediator = mediator; } public async Task<ITryResult<CreatePaymentResponseModel>> TryCreatePaymentAsync(int merchantId, CreatePaymentRequestModel paymentRequestModel) { var createPayment = new CreatePaymentCommand() { MerchantId = merchantId, Amount = paymentRequestModel.Amount, CardNumber = paymentRequestModel.CardNumber, CardCVV = paymentRequestModel.CardCVV, ExpiryDate = paymentRequestModel.ExpiryDate, CurrencyType = Enum.Parse<CurrencyType>(paymentRequestModel.CurrencyType.ToString()) }; var commandResponse = await _mediator.Send(createPayment); if (!commandResponse.Success) { return TryResult<CreatePaymentResponseModel>.CreateFailResult(); } return TryResult<CreatePaymentResponseModel>.CreateSuccessResult(new CreatePaymentResponseModel(commandResponse.Result.PaymentId)); } public async Task<ITryResult<bool>> TryUpdatePaymentAsync(Guid paymentId, UpdatePaymentRequestModel requestModel) { var updateCommand = new UpdatePaymentCommand() { PaymentId = paymentId, BankPaymentId = requestModel.BankPaymentId, PaymentStatus = Enum.Parse<PaymentStatus>(requestModel.PaymentStatus.ToString()), PaymentStatusDetails = requestModel.PaymentStatusDetails }; var commandResponse = await _mediator.Send(updateCommand); if (!commandResponse.Success) { return TryResult<bool>.CreateFailResult(); } return TryResult<bool>.CreateSuccessResult(commandResponse.Result.UpdateSucessful); } } }
using System; using System.Collections.Generic; using System.Text; using ENTITY; //<summary> //Summary description for SalaryPackageInfo //</summary> namespace ENTITY { public class SalaryPackageInfo { public decimal SalaryPackageId { get; set; } public string SalaryPackageName { get; set; } public bool IsActive { get; set; } public string Narration { get; set; } public decimal TotalAmount { get; set; } public DateTime ExtraDate { get; set; } public string Extra1 { get; set; } public string Extra2 { get; set; } } }
using UnityEngine; using System.Collections; [RequireComponent(typeof(tk2dSprite))] public class Leaver : MonoBehaviour { public float speed; private tk2dSprite sprite; void Awake() { sprite = GetComponent<tk2dSprite> (); } public void Leave() { if (this.gameObject.name == "hero"){ sprite.FlipX = false; } else { sprite.FlipX = true; } StartCoroutine ("ReallyLeave"); } IEnumerator ReallyLeave() { while (true) { transform.Translate(speed * Time.deltaTime, 0, 0); yield return null; } } }
using UnityEngine; using System.Collections; public class resizeelementsforgamescreen : MonoBehaviour { GameObject temp;//use this gameobject to reference the ones to be resized float calculateratio;//variable used to calculate the screen ratio public float scalefactor;//variable used to fix object size based on screenratio // Use this for initialization void Start () { //resizing the stone board temp=GameObject.Find ("gameboard"); calculateratio = (float)Screen.width / (float)Screen.height; temp.transform.localScale = new Vector3 (calculateratio*scalefactor,calculateratio*scalefactor,temp.transform.localScale.z); //end of resizing the stone board } }
using ShoppingCartLib.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShoppingCartLib.Interface { public interface IProductRepository { List<ShoppingCartItem> GetShoppingCartProducts(int shoppingCartId); ProductDetails GetProduct(int productId); } }
using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; [RequireComponent(typeof(AudioSource))] public class VideoSceneTransition : MonoBehaviour { public MovieTexture movie; private Game game; public string level; // Use this for initialization void Start () { level = SaveLoadManager.Load(); if (level == null) { movie = (MovieTexture)Resources.Load("OpeningCutscene26-3-2017", typeof(MovieTexture)); }else if(level == "Level 01(medit2)") { movie = (MovieTexture)Resources.Load("Title", typeof(MovieTexture)); } else if (level == "Level 02") { movie = (MovieTexture)Resources.Load("Title", typeof(MovieTexture)); } this.GetComponent<Renderer>().material.mainTexture = movie as MovieTexture; this.GetComponent<AudioSource>().clip = movie.audioClip; movie.Play(); this.GetComponent<AudioSource>().Play(); } // Update is called once per frame void Update () { if ((!movie.isPlaying && level == null) || (Input.anyKey && level == null)) { print("here"); Application.LoadLevel("Level 01(medit2)"); }else if ((!movie.isPlaying && level == "Level 01(medit2)") || (Input.anyKey && level == "Level 01(medit2)")) { print("here1"); Application.LoadLevel("Level 02"); }else if ((!movie.isPlaying && level == "Level 02") || (Input.anyKey && level == "Level 02")) { Application.LoadLevel("Level_03"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MicroMvvm; using FPModel.Entity; namespace FPViewModel { public class AccountForumViewModel : ObservableObject { #region Members private AccountForum _account; #endregion #region Properties public AccountForum AccountForum { get { return _account; } set { _account = value; } } public string Username { get { return _account.Username; } set { _account.Username = value; RaisePropertyChanged("Username"); } } public string Password { get { return _account.Password; } set { _account.Password = value; RaisePropertyChanged("Password"); } } public string SessionDetail { get { return _account.SessionDetail; } set { _account.SessionDetail = value; RaisePropertyChanged("SessionDetail"); } } public string Detail { get { return _account.Detail; } set { _account.Detail = value; RaisePropertyChanged("Detail"); } } #endregion } }
using UnityEngine; using System.Collections; namespace Ph.Bouncer { public class ColourChanger : MonoBehaviour { public Colour Colour; private tk2dSprite sprite; private tk2dSpriteAnimator spriteAnimator; void Start() { sprite = GetComponent<tk2dSprite>(); spriteAnimator = GetComponent<tk2dSpriteAnimator>(); SetColour(Colour); } void OnTriggerEnter(Collider other) { var ballScript = other.collider.GetComponent<Ball>(); if(!ballScript) return; ballScript.SetColour(Colour); } public void SetColour(Colour colour) { Colour = colour; // This doesn't work. Not sure why if(sprite != null) sprite.SetSprite("ColourChanger" + colour.ToString() + "F1"); if(spriteAnimator != null) spriteAnimator.Play("ColourChanger" + colour.ToString()); } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Imaging; using System.ComponentModel; using System.IO; //using System.Reflection.Metadata; using Pfim; using Pfim.dds; using System.Runtime.InteropServices; namespace P3DColourKey { public class Images { private static Bitmap CreateNonIndexedImage(Image src) { Bitmap newBmp = new Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (Graphics gfx = Graphics.FromImage(newBmp)) { gfx.DrawImage(src, 0, 0); } return newBmp; } // Method to detrmine if 1 colour is close to another static bool ColorsAreClose(Color a, Color z, int threshhold) //thersh was 50, expertiment { // work out difference between 3 channels int r = (int)a.R - z.R, g = (int)a.G - z.G, b = (int)a.B - z.B; // return if the differneces are within the threshold // they are squared so they are positive return (r * r + g * g + b * b) < threshhold * threshhold; } // Method to apply filter to a Bitmap public static Bitmap ShindlerBitmap(Bitmap image, Color baseColour, int threshhold) { image = CreateNonIndexedImage(image); for (int x=0; x<image.Width; x++) { for ( int y = 0; y<image.Height; y++){ Color pixelColour = image.GetPixel(x, y); if (!ColorsAreClose(pixelColour, baseColour, threshhold)) { int a = pixelColour.A, r = pixelColour.R, g = pixelColour.G, b = pixelColour.B; //find average int avg = (r + g + b) / 3; //set new pixel value image.SetPixel(x, y, Color.FromArgb(a, avg, avg, avg)); } } } return image; } public static Bitmap BytesToBitmap (byte[] img, int fileFormat, int w, int h) { MemoryStream mStream = new MemoryStream(img); if (fileFormat == 10) //DXT5 Use Pfim for this { using (var image = Pfim.Pfim.FromStream(mStream)) { PixelFormat format = PixelFormat.Format32bppArgb; var data = Marshal.UnsafeAddrOfPinnedArrayElement(image.Data, 0); var bitmap = new Bitmap(w, h, image.Stride, format, data); bitmap.RotateFlip(RotateFlipType.Rotate180FlipX); //For some reason Pfim will return the image flipped so we need to change it back mStream.Close(); return bitmap; } } else if (fileFormat == 6 || fileFormat == 8) //DXT1 or DXT3 { img = DDS.LoadDDS(img); //Decompress //LoadDDS will return raw argb, so we need to convert it into a Bitmap Bitmap createdBitmap = new Bitmap(w, h); int offset = 0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int r = img[offset++]; int g = img[offset++]; int b = img[offset++]; int a = img[offset++]; Color col = Color.FromArgb(a, r, g, b); createdBitmap.SetPixel(x, y, col); } } return createdBitmap; } else if (fileFormat == 1) { Bitmap bmp = (Bitmap)Bitmap.FromStream(mStream); return bmp; } else { return null; } } } }
using System; namespace B01_05_ComplexZahlen { class Complex { #region fields // Objektvariable private double a; // Realteil private double b; // Imaginärteil #endregion #region properties public double A { get { return a; } } public double B { get { return b; } } #endregion #region ctor public Complex( double a, double b ) { this.a = a; this.b = b; } #endregion #region methods // Objektmethodes public override string ToString() { return $"{a} + {b}i"; } // Überladene Operatoren public static Complex operator +( Complex z1, Complex z2 ) { // Realteile Imaginärteile addieren return new Complex( z1.A + z2.A, z1.B + z2.B) ; } public static Complex operator -( Complex z1, Complex z2 ) { return new Complex( z1.A - z2.A, z1.B - z2.B ); } public static Complex operator *( Complex z1, Complex z2 ) { double a3 = z1.A * z2.A - z1.B * z2.B; double b3 = z1.A * z2.B + z2.A * z1.B; return new Complex( a3, b3 );; } #endregion } }
using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Utility { public static class ConfigHelper { /// <summary> /// 读取appsettings.json配置 /// 调用:string str=ConfigHelper.GetAppSettings("ReflectSection:Two:Three"); /// </summary> /// <param name="domTree">完整的节点路径</param> /// <returns></returns> public static string GetAppSettings(string domTree) { try { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); var config = builder.Build(); return config[domTree]; } catch (Exception ex) { throw ex; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConPersApp { class Person { int age; string fname; string lname; string city; public Person() { } public Person(int _age, string _fname, string _lname, string _city) { age = _age; fname = _fname; lname = _lname; city = _city; } public void Display() { Console.WriteLine("age : {0}", age); Console.WriteLine("firstname : {0}", fname); Console.WriteLine("last name : {0}", lname); Console.WriteLine("city : {0}", city); } public static void Main() { List<Person> Persons = new List<Person>(); Person per1 = new Person(21, "sumit", "vera", "goa"); Person per2 = new Person(22, "harry", "david", "newyork"); Person per3 = new Person(23, "petter", "paul", "zombia"); Person per4 = new Person(24, "girl", "hash", "hyd"); Person per5 = new Person(25, "tri", "john", "usa"); Persons.Add(per1); Persons.Add(per2); Persons.Add(per3); Persons.Add(per4); Persons.Add(per5); foreach (Person p in Persons) { Console.WriteLine(); p.Display(); } } } }
using System.Collections.Generic; using System.IO; using Frontend.Core.Model.Paths.Interfaces; namespace Frontend.Core.Model.Paths { public class RequiredFile : RequiredItemBase, IRequiredFile { public RequiredFile(string tagName, string friendlyName, string description, IList<IAlternativePath> alternatives, string extension, string predefinedFileName, string internalTagName, bool isMandatory, bool hidden) : base(tagName, friendlyName, description, alternatives, internalTagName, isMandatory, hidden) { Extension = extension; PredefinedFileName = predefinedFileName; } public string Extension { get; private set; } public string PredefinedFileName { get; private set; } public override string ValidateSelectedValue() { if (IsMandatory) { var exists = File.Exists(SelectedValue); if (!exists) { return "File does not exist"; } } return null; } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using WebAppVue.Models.Entity; using WebAppVue.Models.Json; namespace WebAppVue.Models { public class NodeModel : BaseModel { public NodeModel(WebAppContext context) : base(context) { } public Json.Item[] List() { return this._context.Nodes .Where(name => !name.Deleted) .Select(name => new Json.Item { Id = name.Id, Sort = name.Sort, Name = name.Text, ImageIds = NodeModel.JsonDeserialize<List<Int64>>(name.ImageIds), TimeStamp = NodeModel.ConvertIntToDateTime(name.Date, name.Time) }) .ToArray(); } public Json.Item Get(Int64 id) { var item = this._context.Nodes.Join( this._context.Descriptions, name => name.Id, descriptions => descriptions.NamesId, (name, description) => new { Id = name.Id, Delete = name.Deleted || description.Deleted, Sort = name.Sort, Name = name.Text, ImageIds = NodeModel.JsonDeserialize<List<Int64>>(name.ImageIds), Date = name.Date, Time = name.Time, Description = description.Text }) .FirstOrDefault(item => item.Id == id && !item.Delete); return item == null ? null : new Json.Item { Id = item.Id, Sort = item.Sort, Name = item.Name, ImageIds = item.ImageIds, TimeStamp = NodeModel.ConvertIntToDateTime(item.Date, item.Time), Description = item.Description }; } public long Create(Json.Item item) { using (var tran = this._context.Database.BeginTransaction()) { var newNode = new Entity.Context.Node(); newNode.Text = item.Name; newNode.ImageIds = NodeModel.JsonSerialize(item.ImageIds); newNode.Sort = item.Sort; newNode.Date = NodeModel.ConvertDateToInt(item.TimeStamp); newNode.Time = NodeModel.ConvertTimeToInt(item.TimeStamp); this._context.Nodes.Add(newNode); if (this._context.SaveChanges() <= 0) { tran.Rollback(); return -1; } var newDescription = new Entity.Context.Description(); newDescription.NamesId = newNode.Id; newDescription.Text = item.Description; this._context.Descriptions.Add(newDescription); if (this._context.SaveChanges() <= 0) { tran.Rollback(); return -1; } var images = this._context.Images .Where(image => !image.Deleted) .Where(image => item.ImageIds.Contains(image.Id)); if (images != null) { foreach (var image in images) { image.NamesId = newNode.Id; } if (this._context.SaveChanges() <= 0) { tran.Rollback(); return -1; } } tran.Commit(); return newNode.Id; } } public long Update(Int64 id, Json.Item item) { var name = this._context.Nodes .Where(name => !name.Deleted) .FirstOrDefault(name => name.Id == id); if (name == null) return -1; var description = this._context.Descriptions .Where(description => !description.Deleted) .FirstOrDefault(description => description.NamesId == id); if (description == null) return -1; name.Text = item.Name; if (item.ImageIds != null) name.ImageIds = NodeModel.JsonSerialize(item.ImageIds); if (item.Sort == -1) name.Sort = item.Sort; if (item.TimeStamp != null) name.Date = NodeModel.ConvertDateToInt(item.TimeStamp); if (item.TimeStamp != null) name.Time = NodeModel.ConvertTimeToInt(item.TimeStamp); description.Text = item.Description; return this._context.SaveChanges() > 0 ? id : -1; } public bool Delete(Int64 id) { var node = this._context.Nodes .FirstOrDefault(name => name.Id == id && !name.Deleted); var description = this._context.Descriptions .FirstOrDefault(description => description.NamesId == id && !description.Deleted); if (node == null) return false; var timestamp = DateTime.Now; node.Deleted = true; node.Delete_at = timestamp; description.Deleted = true; description.Delete_at = timestamp; return this._context.SaveChanges() > 0; } private static DateTime ConvertIntToDateTime(int date, int time) { var dateTime = (date.ToString() + time.ToString()); var format = "yyyyMMddHHmmss"; try { // TODO: データ不正時の処理は未実装 return DateTime.ParseExact(dateTime, format, null); } catch { } return DateTime.Now; } private static int ConvertDateToInt(DateTime timeStamp) { try { // TODO: データ不正時の処理は未実装 return Convert.ToInt32(timeStamp.ToString("yyyyMMdd")); } catch { } return Convert.ToInt32(DateTime.Now.ToString("yyyyMMdd")); } private static int ConvertTimeToInt(DateTime timeStamp) { try { // TODO: データ不正時の処理は未実装 return Convert.ToInt32(timeStamp.ToString("HHmmss")); } catch { } return Convert.ToInt32(timeStamp.ToString("HHmmss")); } private static T JsonDeserialize<T>(string images) { if (images == null) return default(T); try { var options = new JsonSerializerOptions { WriteIndented = true, }; return JsonSerializer.Deserialize<T>(images, options); } catch (Exception ex) { // ToDo: エラー通知 return default(T); } } private static string JsonSerialize<T>(T images) { if (images == null) return null; try { return JsonSerializer.Serialize(images); } catch (Exception ex) { // ToDo: エラー通知 return null; } } } }
using Sitecore.Data.Items; using Sitecore.Diagnostics; namespace Aqueduct.SitecoreLib.Search.DynamicFields { public class TemplateNameField : BaseDynamicField { public override string ResolveValue(Item item) { Assert.ArgumentNotNull(item, "item"); return item.Template.Name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using QuickGraph; using Microsoft.Pex.Framework; using Microsoft.Pex.Framework.Settings; using Microsoft.Pex.Framework.Exceptions; using Microsoft.VisualStudio.TestTools.UnitTesting; using PexAPIWrapper; using QuickGraph.Interfaces; using QuickGraph.Utility; namespace QuickGraphTest { [PexClass(typeof(QuickGraph.PriorityQueue<int, int>))] [TestClass] public partial class PriorityQueueCommuteTest { /*[PexMethod(MaxConstraintSolverTime = 50, Timeout = 240)] public void TestCloneCompare([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1) { PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq1 = new PriorityQueueEqualityComparer(); BinaryHeapEqualityComparer eq2 = new BinaryHeapEqualityComparer(); PexObserve.ValueForViewing("$input_Count1", pq1.Count); PexObserve.ValueForViewing("$input_Count2", pq2.Count); PexObserve.ValueForViewing("$input_DictionaryCompare", pq1.ToStringForInts().Equals(pq2.ToStringForInts())); PexObserve.ValueForViewing("$input_HeapCompare", eq2.Equals(pq1.Heap, pq2.Heap)); PexAssert.IsTrue(eq1.Equals(pq1, pq2)); }*/ [PexMethod] public void PUT_CommutativityUpdateUpdateComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value1, int value2) { PexAssume.IsTrue(value1 > -11 && value1 < 11 && value2 > -11 && value2 < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value1", value1); PexObserve.ValueForViewing("$input_Value2", value2); PexObserve.ValueForViewing("$input_ContainsValue1", pq1.Contains(value1)); PexObserve.ValueForViewing("$input_ContainsValue2", pq1.Contains(value2)); AssumePrecondition.IsTrue( (pq1.Contains(value2) && ((pq1.Contains(value1)))) ); pq1.Update(value1); pq1.Update(value2); pq2.Update(value2); pq2.Update(value1); NotpAssume.IsTrue(eq.Equals(pq1, pq2)); PexAssert.IsTrue(eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityUpdateCountComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value) { PexAssume.IsTrue(value > -11 && value < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value", value); PexObserve.ValueForViewing("$input_ContainsValue", pq1.Contains(value)); AssumePrecondition.IsTrue(true); int c1 = 0, c2 = 0; pq1.Update(value); c1 = pq1.Count; c2 = pq2.Count; pq2.Update(value); //NotpAssume.IsTrue(c1 == c2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(c1 == c2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityUpdateContainsComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value1, int value2) { PexAssume.IsTrue(value1 > -11 && value1 < 11 && value2 > -11 && value2 < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value1", value1); PexObserve.ValueForViewing("$input_Value2", value2); PexObserve.ValueForViewing("$input_ContainsValue1", pq1.Contains(value1)); PexObserve.ValueForViewing("$input_ContainsValue2", pq1.Contains(value2)); AssumePrecondition.IsTrue( (pq1.Contains(value1)) ); bool c1 = true, c2 = true; pq1.Update(value1); c1 = pq1.Contains(value2); c2 = pq2.Contains(value2); pq2.Update(value1); NotpAssume.IsTrue(c1 == c2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(c1 == c2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityUpdateEnqueueComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value1, int value2) { PexAssume.IsTrue(value1 > -11 && value1 < 11 && value2 > -11 && value2 < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value1", value1); PexObserve.ValueForViewing("$input_Value2", value2); PexObserve.ValueForViewing("$input_ContainsValue1", pq1.Contains(value1)); PexObserve.ValueForViewing("$input_ContainsValue2", pq1.Contains(value2)); AssumePrecondition.IsTrue( (pq1.Contains(value2)) ); pq1.Update(value1); pq1.Enqueue(value2); pq2.Enqueue(value2); pq2.Update(value1); NotpAssume.IsTrue(eq.Equals(pq1, pq2)); PexAssert.IsTrue(eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityUpdateDequeueComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value) { PexAssume.IsTrue(value > -11 && value < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value", value); PexObserve.ValueForViewing("$input_ContainsValue", pq1.Contains(value)); AssumePrecondition.IsTrue( (pq1.Contains(value) && (((!(pq1.Count == value)) && ((-pq1.Count + -value <= 0))))) ); int d1 = 0, d2 = 0; pq1.Update(value); d1 = pq1.Dequeue(); d2 = pq2.Dequeue(); pq2.Update(value); NotpAssume.IsTrue(d1 == d2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(d1 == d2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityUpdatePeekComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value) { PexAssume.IsTrue(value > -11 && value < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value", value); PexObserve.ValueForViewing("$input_ContainsValue", pq1.Contains(value)); AssumePrecondition.IsTrue( (pq1.Contains(value)) ); int p1 = 0, p2 = 0; pq1.Update(value); p1 = pq1.Peek(); p2 = pq2.Peek(); pq2.Update(value); NotpAssume.IsTrue(p1 == p2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(p1 == p2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityCountCountComm([PexAssumeUnderTest]Tuple<PriorityQueue<int, int>, PriorityQueue<int, int>> pqTuple) { // PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); var pq1 = pqTuple.Item1; var pq2 = pqTuple.Item2; PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); AssumePrecondition.IsTrue(true); int c11 = 0, c12 = 0; int c21 = 0, c22 = 0; c11 = pq1.Count; c12 = pq1.Count; c22 = pq2.Count; c21 = pq2.Count; PexObserve.ValueForViewing("$input_Count", c11); PexObserve.ValueForViewing("$input_Count", c21); PexObserve.ValueForViewing("$input_Count", c12); PexObserve.ValueForViewing("$input_Count", c22); PexObserve.ValueForViewing("$input_Count", pq1.ToStringForInts()); PexObserve.ValueForViewing("$input_Count", pq2.ToStringForInts()); //NotpAssume.IsTrue(c11 == c21 && c12 == c22 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(c11 == c21 && c12 == c22 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityCountContainsComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value) { PexAssume.IsTrue(value > -11 && value < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value", value); PexObserve.ValueForViewing("$input_ContainsValue", pq1.Contains(value)); AssumePrecondition.IsTrue(!( ((!(pq1.Peek() <= -2147484000.0)) && ((pq1.Count == value) || ((!(pq1.Count == value)) && ((pq1.Count == pq1.Peek()) || ((!(pq1.Count == pq1.Peek())) && ((pq1.Count <= 1) || ((!(pq1.Count <= 1)) && ((pq1.Contains(value) && ((pq1.Count <= 2 && ((value <= 0 && (((!(-pq1.Count + -value <= 0))))) || ((!(value <= 0))))) || ((!(pq1.Count <= 2)) && (((!(pq1.Count <= 3))))))) || ((!(pq1.Contains(value))) && ((pq1.Count <= 2 && ((-pq1.Count + value <= 1))) || ((!(pq1.Count <= 2))))))))))))) )); int c11 = 0, c12 = 0; bool c21 = true, c22 = true; c11 = pq1.Count; c21 = pq1.Contains(value); c22 = pq2.Contains(value); c12 = pq2.Count; NotpAssume.IsTrue(c11 == c12 && c21 == c22 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(c11 == c12 && c21 == c22 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityCountEnqueueComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value) { PexAssume.IsTrue(value > -11 && value < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value", value); PexObserve.ValueForViewing("$input_ContainsValue", pq1.Contains(value)); AssumePrecondition.IsTrue(true); int c1 = 0, c2 = 0; c1 = pq1.Count; pq1.Enqueue(value); pq2.Enqueue(value); c2 = pq2.Count; //NotpAssume.IsTrue(c1 == c2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(c1 == c2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityCountDequeueComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1) { PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); AssumePrecondition.IsTrue(true); int c1 = 0, c2 = 0; int d1 = 0, d2 = 0; c1 = pq1.Count; d1 = pq1.Dequeue(); d2 = pq2.Dequeue(); c2 = pq2.Count; //NotpAssume.IsTrue(c1 == c2 && d1 == d2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(c1 == c2 && d1 == d2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityCountPeekComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1) { PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); AssumePrecondition.IsTrue(true); int c1 = 0, c2 = 0; int p1 = 0, p2 = 0; c1 = pq1.Count; p1 = pq1.Peek(); p2 = pq2.Peek(); c2 = pq2.Count; //NotpAssume.IsTrue(c1 == c2 && p1 == p2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(c1 == c2 && p1 == p2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityContainsContainsComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value1, int value2) { PexAssume.IsTrue(value1 > -11 && value1 < 11 && value2 > -11 && value2 < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value1", value1); PexObserve.ValueForViewing("$input_Value2", value2); PexObserve.ValueForViewing("$input_ContainsValue1", pq1.Contains(value1)); PexObserve.ValueForViewing("$input_ContainsValue2", pq1.Contains(value2)); AssumePrecondition.IsTrue(true); bool c11 = true, c12 = true; bool c21 = true, c22 = true; c11 = pq1.Contains(value1); c12 = pq1.Contains(value2); c22 = pq2.Contains(value2); c21 = pq2.Contains(value1); //NotpAssume.IsTrue(c11 == c21 && c12 == c22 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(c11 == c21 && c12 == c22 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityContainsEnqueueComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value1, int value2) { PexAssume.IsTrue(value1 > -11 && value1 < 11 && value2 > -11 && value2 < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value1", value1); PexObserve.ValueForViewing("$input_Value2", value2); PexObserve.ValueForViewing("$input_ContainsValue1", pq1.Contains(value1)); PexObserve.ValueForViewing("$input_ContainsValue2", pq1.Contains(value2)); AssumePrecondition.IsTrue(true); bool c1 = true, c2 = true; c1 = pq1.Contains(value1); pq1.Enqueue(value2); pq2.Enqueue(value2); c2 = pq2.Contains(value1); //NotpAssume.IsTrue(c1 == c2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(c1 == c2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityContainsDequeueComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value) { PexAssume.IsTrue(value > -11 && value < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value", value); PexObserve.ValueForViewing("$input_ContainsValue", pq1.Contains(value)); AssumePrecondition.IsTrue(true); bool c1 = true, c2 = true; int d1 = 0, d2 = 0; c1 = pq1.Contains(value); d1 = pq1.Dequeue(); d2 = pq2.Dequeue(); c2 = pq2.Contains(value); //NotpAssume.IsTrue(c1 == c2 && d1 == d2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(c1 == c2 && d1 == d2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityContainsPeekComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value) { PexAssume.IsTrue(value > -11 && value < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value", value); PexObserve.ValueForViewing("$input_ContainsValue", pq1.Contains(value)); AssumePrecondition.IsTrue(true); bool c1 = true, c2 = true; int p1 = 0, p2 = 0; c1 = pq1.Contains(value); p1 = pq1.Peek(); p2 = pq2.Peek(); c2 = pq2.Contains(value); //NotpAssume.IsTrue(c1 == c2 && p1 == p2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(c1 == c2 && p1 == p2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityEnqueueEnqueueComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value1, int value2) { PexAssume.IsTrue(value1 > -11 && value1 < 11 && value2 > -11 && value2 < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value1", value1); PexObserve.ValueForViewing("$input_Value2", value2); PexObserve.ValueForViewing("$input_ContainsValue1", pq1.Contains(value1)); PexObserve.ValueForViewing("$input_ContainsValue2", pq1.Contains(value2)); AssumePrecondition.IsTrue(true); pq1.Enqueue(value1); pq1.Enqueue(value2); pq2.Enqueue(value2); pq2.Enqueue(value1); //NotpAssume.IsTrue(eq.Equals(pq1, pq2)); PexAssert.IsTrue(eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityEnqueueDequeueComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value) { PexAssume.IsTrue(value > -11 && value < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value", value); PexObserve.ValueForViewing("$input_ContainsValue", pq1.Contains(value)); AssumePrecondition.IsTrue(true); int d1 = 0, d2 = 0; pq1.Enqueue(value); d1 = pq1.Dequeue(); d2 = pq2.Dequeue(); pq2.Enqueue(value); //NotpAssume.IsTrue(d1 == d2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(d1 == d2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityEnqueuePeekComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1, int value) { PexAssume.IsTrue(value > -11 && value < 11); PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); PexObserve.ValueForViewing("$input_Value", value); PexObserve.ValueForViewing("$input_ContainsValue", pq1.Contains(value)); AssumePrecondition.IsTrue(true); int p1 = 0, p2 = 0; pq1.Enqueue(value); p1 = pq1.Peek(); p2 = pq2.Peek(); pq2.Enqueue(value); //NotpAssume.IsTrue(p1 == p2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(p1 == p2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityDequeueDequeueComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1) { PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); AssumePrecondition.IsTrue(true); int d11 = 0, d12 = 0; int d21 = 0, d22 = 0; d11 = pq1.Dequeue(); d12 = pq1.Dequeue(); d22 = pq2.Dequeue(); d21 = pq2.Dequeue(); //NotpAssume.IsTrue(d11 == d21 && d12 == d22 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(d11 == d21 && d12 == d22 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityDequeuePeekComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1) { PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); AssumePrecondition.IsTrue(true); int d1 = 0, d2 = 0; int p1 = 0, p2 = 0; d1 = pq1.Dequeue(); p1 = pq1.Peek(); p2 = pq2.Peek(); d2 = pq2.Dequeue(); //NotpAssume.IsTrue(d1 == d2 && p1 == p2 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(d1 == d2 && p1 == p2 && eq.Equals(pq1, pq2)); } [PexMethod] public void PUT_CommutativityPeekPeekComm([PexAssumeUnderTest] QuickGraph.PriorityQueue<int, int> pq1) { PriorityQueue<int, int> pq2 = (PriorityQueue<int, int>)pq1.Clone(); PriorityQueueEqualityComparer eq = new PriorityQueueEqualityComparer(); PexObserve.ValueForViewing("$input_Count", pq1.Count); AssumePrecondition.IsTrue(true); int p11 = 0, p12 = 0; int p21 = 0, p22 = 0; p11 = pq1.Peek(); p12 = pq1.Peek(); p22 = pq2.Peek(); p21 = pq2.Peek(); //NotpAssume.IsTrue(p11 == p21 && p12 == p22 && eq.Equals(pq1, pq2)); PexAssert.IsTrue(p11 == p21 && p12 == p22 && eq.Equals(pq1, pq2)); } } }
namespace XMLApiProject.Services.Models.PaymentService.XML.RequestService.Responses { public class UpdatePassword { } }
using ScreeningTesterWebSite.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ScreeningTesterWebSite { public interface IFadvWebServiceCaller { String UID { get; set; } String PW { get; set; } String EnvironmentCode { get; set; } InitializeQuestionnaireOutput InitializeQuestionnaire(InputNewApplicant newApplicantIn); GetLocationByIncomingPhoneNumberOutput GetCompanyByPhoneNumber(InputGetLocationByIncomingPhoneNumber getLocIn); GetLocationByIncomingPhoneNumberOutput GetCompanyByCode(InputGetCompanyByCode getLocIn); NewApplicantOutput NewApplicant(InputNewApplicant newApplicantIn); IVRNewApplicantOutput IVRNewApplicant(InputIVRNewApplicant newApplicantIn); NewApplicantOutput PostAnswers(InputPostAnswers postAnswersIn); IVRNewApplicantOutput IVRPostAnswers(InputIVRPostAnswers postAnswersIn); HireApplicantsOutput HireApplicants(InputHireApplicants hireApplicantsIn); NewApplicantOutput GetLastQuestions(InputGetLastQuestions getLastQuestionsIn); NewApplicantOutput GetLastPageOfQuestions(InputGetLastQuestions getLastQuestionsIn); GetApplicantStatusOutput GetApplicantStatus(InputGetLastQuestions getApplicantStatusIn); } }
using System; [CustomLuaClass] public class UIInputSelectDelegate : UIInput { public delegate void SelectCallback(bool isSelected); public UIInputSelectDelegate.SelectCallback callback; protected override void OnSelect(bool isSelected) { base.OnSelect(isSelected); if (this.callback != null) { this.callback(isSelected); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Web; namespace WS_PosData_PMKT.Models.Object { [DataContract] public class DataMaterialPlacement { [DataMember] public string IdTypeMaterial { get; set; } [DataMember] public string New { get; set; } [DataMember] public string Amount { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HZGZDL.YZFJKGZXFXY.Common { public class FreqAnalyzer { /// <summary> /// 求复数myComplex.Complex数组的模modul数组 /// </summary> /// <param name="input">复数数组</param> /// <returns>模数组</returns> public static double[] Cmp2Mdl(myComplex.Complex[] input) { ///有输入数组的长度确定输出数组的长度 double[] output = new double[input.Length]; ///对所有输入复数求模 for (int i = 0; i < input.Length; i++) { if (input[i].Real > 0) { output[i] = -input[i].ToModul(); } else { output[i] = input[i].ToModul(); } } ///返回模数组 return output; } /// <summary> /// 傅立叶变换或反变换,递归实现多级蝶形运算 /// 作为反变换输出需要再除以序列的长度 /// !注意:输入此类的序列长度必须是2^n /// </summary> /// <param name="input">输入实序列</param> /// <param name="invert">false=正变换,true=反变换</param> /// <returns>傅立叶变换或反变换后的序列</returns> public static myComplex.Complex[] FFT(double[] input, bool invert) { ///由输入序列确定输出序列的长度 myComplex.Complex[] output = new myComplex.Complex[input.Length]; ///将输入的实数转为复数 for (int i = 0; i < input.Length; i++) { output[i] = new myComplex.Complex(input[i]); } ///返回FFT或IFFT后的序列 return output = FFT(output, invert); } /// <summary> /// 傅立叶变换或反变换,递归实现多级蝶形运算 /// 作为反变换输出需要再除以序列的长度 /// !注意:输入此类的序列长度必须是2^n /// </summary> /// <param name="input">复数输入序列</param> /// <param name="invert">false=正变换,true=反变换</param> /// <returns>傅立叶变换或反变换后的序列</returns> private static myComplex.Complex[] FFT(myComplex.Complex[] input, bool invert) { ///输入序列只有一个元素,输出这个元素并返回 if (input.Length == 1) { return new myComplex.Complex[] { input[0] }; } ///输入序列的长度 int length = input.Length; ///输入序列的长度的一半 int half = length / 2; ///有输入序列的长度确定输出序列的长度 myComplex.Complex[] output = new myComplex.Complex[length]; ///正变换旋转因子的基数 double fac = -2.0 * Math.PI / length; ///反变换旋转因子的基数是正变换的相反数 if (invert) { fac = -fac; } ///序列中下标为偶数的点 myComplex.Complex[] evens = new myComplex.Complex[half]; for (int i = 0; i < half; i++) { evens[i] = input[2 * i]; } ///求偶数点FFT或IFFT的结果,递归实现多级蝶形运算 myComplex.Complex[] evenResult = FFT(evens, invert); ///序列中下标为奇数的点 myComplex.Complex[] odds = new myComplex.Complex[half]; for (int i = 0; i < half; i++) { odds[i] = input[2 * i + 1]; } ///求偶数点FFT或IFFT的结果,递归实现多级蝶形运算 myComplex.Complex[] oddResult = FFT(odds, invert); for (int k = 0; k < half; k++) { ///旋转因子 double fack = fac * k; ///进行蝶形运算 myComplex.Complex oddPart = oddResult[k] * new myComplex.Complex(Math.Cos(fack), Math.Sin(fack)); output[k] = evenResult[k] + oddPart; output[k + half] = evenResult[k] - oddPart; } ///返回FFT或IFFT的结果 return output; } /// <summary> /// 频域滤波器 /// </summary> /// <param name="data">待滤波的数据</param> /// <param name="Nc">滤波器截止波数</param> /// <param name="Hd">滤波器的权函数</param> /// <returns>滤波后的数据</returns> public static double[] FreqFilter(double[] data, myComplex.Complex[] Hd) { ///最高波数==数据长度 int N = data.Length; ///输入数据进行FFT myComplex.Complex[] fData = FreqAnalyzer.FFT(data, false); ///频域滤波 for (int i = 0; i < N; i++) { fData[i] = Hd[i] * fData[i]; } ///滤波后数据计算IFFT ///!未除以数据长度 fData = FreqAnalyzer.FFT(fData, true); ///复数转成模 data = FreqAnalyzer.Cmp2Mdl(fData); ///除以数据长度 for (int i = 0; i < N; i++) { data[i] = -data[i] / N; } ///返回滤波后的数据 return data; } } }
/** 版本信息模板在安装目录下,可自行修改。 * OA_EDUQUESTION.cs * * 功 能: N/A * 类 名: OA_EDUQUESTION * * Ver 变更日期 负责人 变更内容 * ─────────────────────────────────── * V0.01 2014/7/22 15:35:35 N/A 初版 * * Copyright (c) 2012 Maticsoft Corporation. All rights reserved. *┌──────────────────────────────────┐ *│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │ *│ 版权所有:动软卓越(北京)科技有限公司              │ *└──────────────────────────────────┘ */ using System; using System.Data; using System.Text; using System.Data.OracleClient; using Maticsoft.DBUtility; using System.Collections.Generic; using System.Data.SqlClient;//Please add references namespace PDTech.OA.DAL { /// <summary> /// 数据访问类:OA_EDUQUESTION /// </summary> public partial class OA_EDUQUESTION { public OA_EDUQUESTION() {} #region BasicMethod /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(string EDU_Q_GUID) { StringBuilder strSql=new StringBuilder(); strSql.Append("select count(1) from OA_EDUQUESTION"); strSql.Append(" where EDU_Q_GUID=@EDU_Q_GUID "); SqlParameter[] parameters = { new SqlParameter("@EDU_Q_GUID", SqlDbType.NVarChar) }; parameters[0].Value = EDU_Q_GUID; return DbHelperSQL.Exists(strSql.ToString(),parameters); } /// <summary> /// 增加一条数据 /// </summary> public bool Add(PDTech.OA.Model.OA_EDUQUESTION model) { StringBuilder strSql=new StringBuilder(); strSql.Append("insert into OA_EDUQUESTION("); strSql.Append("EDU_Q_GUID,TITLE,ANSWER,OPTIONA,OPTIONB,OPTIONC,OPTIOND,CREATETIME,SCORE,WEIGHT)"); strSql.Append(" values ("); strSql.Append("@EDU_Q_GUID,@TITLE,@ANSWER,@OPTIONA,@OPTIONB,@OPTIONC,@OPTIOND,@CREATETIME,@SCORE,@WEIGHT)"); SqlParameter[] parameters = { new SqlParameter("@EDU_Q_GUID", SqlDbType.NVarChar), new SqlParameter("@TITLE", SqlDbType.NVarChar), new SqlParameter("@ANSWER", SqlDbType.Char,1), new SqlParameter("@OPTIONA", SqlDbType.NVarChar), new SqlParameter("@OPTIONB", SqlDbType.NVarChar), new SqlParameter("@OPTIONC", SqlDbType.NVarChar), new SqlParameter("@OPTIOND", SqlDbType.NVarChar), new SqlParameter("@CREATETIME", SqlDbType.DateTime), new SqlParameter("@SCORE", SqlDbType.Decimal,4), new SqlParameter("@WEIGHT", SqlDbType.Decimal,4)}; parameters[0].Value = model.EDU_Q_GUID; parameters[1].Value = model.TITLE; parameters[2].Value = model.ANSWER; parameters[3].Value = model.OPTIONA; parameters[4].Value = model.OPTIONB; parameters[5].Value = model.OPTIONC; parameters[6].Value = model.OPTIOND; parameters[7].Value = model.CREATETIME; parameters[8].Value = model.SCORE; parameters[9].Value = model.WEIGHT; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 批量添加 /// </summary> /// <param name="list"></param> public void BatchAdd(List<PDTech.OA.Model.OA_EDUQUESTION> list) { IList<sqlTrasExcuteComm> commandList = null; if(list != null && list.Count > 0) { commandList = new List<sqlTrasExcuteComm>(); foreach (PDTech.OA.Model.OA_EDUQUESTION model in list) { StringBuilder strSql=new StringBuilder(); strSql.Append("insert into OA_EDUQUESTION("); strSql.Append("EDU_Q_GUID,TITLE,ANSWER,OPTIONA,OPTIONB,OPTIONC,OPTIOND,CREATETIME,SCORE,WEIGHT)"); strSql.Append(" values ("); strSql.Append("@EDU_Q_GUID,@TITLE,@ANSWER,@OPTIONA,@OPTIONB,@OPTIONC,@OPTIOND,@CREATETIME,@SCORE,@WEIGHT)"); SqlParameter[] parameters = { new SqlParameter("@EDU_Q_GUID", SqlDbType.NVarChar), new SqlParameter("@TITLE", SqlDbType.NVarChar), new SqlParameter("@ANSWER", SqlDbType.Char,1), new SqlParameter("@OPTIONA", SqlDbType.NVarChar), new SqlParameter("@OPTIONB", SqlDbType.NVarChar), new SqlParameter("@OPTIONC", SqlDbType.NVarChar), new SqlParameter("@OPTIOND", SqlDbType.NVarChar), new SqlParameter("@CREATETIME", SqlDbType.DateTime), new SqlParameter("@SCORE", SqlDbType.Decimal,4), new SqlParameter("@WEIGHT", SqlDbType.Decimal,4)}; parameters[0].Value = model.EDU_Q_GUID; parameters[1].Value = model.TITLE; parameters[2].Value = model.ANSWER; parameters[3].Value = model.OPTIONA; parameters[4].Value = model.OPTIONB; parameters[5].Value = model.OPTIONC; parameters[6].Value = model.OPTIOND; parameters[7].Value = model.CREATETIME; parameters[8].Value = model.SCORE; parameters[9].Value = model.WEIGHT; sqlTrasExcuteComm trasComm = new sqlTrasExcuteComm(); trasComm.commandText = strSql.ToString(); trasComm.type = CommandType.Text; trasComm.parameters = parameters; commandList.Add(trasComm); } DbHelperSQL.ExecuteSqlTran(commandList); } } /// <summary> /// 更新一条数据 /// </summary> public bool Update(PDTech.OA.Model.OA_EDUQUESTION model) { StringBuilder strSql=new StringBuilder(); strSql.Append("update OA_EDUQUESTION set "); strSql.Append("TITLE=@TITLE,"); strSql.Append("ANSWER=@ANSWER,"); strSql.Append("OPTIONA=@OPTIONA,"); strSql.Append("OPTIONB=@OPTIONB,"); strSql.Append("OPTIONC=@OPTIONC,"); strSql.Append("OPTIOND=@OPTIOND,"); //strSql.Append("CREATETIME=:CREATETIME,"); strSql.Append("SCORE=@SCORE,"); strSql.Append("WEIGHT=@WEIGHT"); strSql.Append(" where EDU_Q_GUID=@EDU_Q_GUID "); SqlParameter[] parameters = { new SqlParameter("@TITLE", SqlDbType.NVarChar), new SqlParameter("@ANSWER", SqlDbType.Char,1), new SqlParameter("@OPTIONA", SqlDbType.NVarChar), new SqlParameter("@OPTIONB", SqlDbType.NVarChar), new SqlParameter("@OPTIONC", SqlDbType.NVarChar), new SqlParameter("@OPTIOND", SqlDbType.NVarChar), new SqlParameter("@SCORE", SqlDbType.Decimal,4), new SqlParameter("@WEIGHT", SqlDbType.Decimal,4), new SqlParameter("@EDU_Q_GUID", SqlDbType.NVarChar)}; parameters[0].Value = model.TITLE; parameters[1].Value = model.ANSWER; parameters[2].Value = model.OPTIONA; parameters[3].Value = model.OPTIONB; parameters[4].Value = model.OPTIONC; parameters[5].Value = model.OPTIOND; //parameters[6].Value = model.CREATETIME; parameters[6].Value = model.SCORE; parameters[7].Value = model.WEIGHT; parameters[8].Value = model.EDU_Q_GUID; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 删除一条数据 /// </summary> public bool Delete(string EDU_Q_GUID) { StringBuilder strSql=new StringBuilder(); strSql.Append("delete from OA_EDUQUESTION "); strSql.Append(" where EDU_Q_GUID=@EDU_Q_GUID "); SqlParameter[] parameters = { new SqlParameter("@EDU_Q_GUID", SqlDbType.NVarChar) }; parameters[0].Value = EDU_Q_GUID; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 批量删除数据 /// </summary> public bool DeleteList(string EDU_Q_GUIDlist ) { StringBuilder strSql=new StringBuilder(); strSql.Append("delete from OA_EDUQUESTION "); strSql.Append(" where EDU_Q_GUID in ("+EDU_Q_GUIDlist + ") "); int rows = DbHelperSQL.ExecuteSql(strSql.ToString()); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 得到一个对象实体 /// </summary> public PDTech.OA.Model.OA_EDUQUESTION GetModel(string EDU_Q_GUID) { StringBuilder strSql=new StringBuilder(); strSql.Append("select EDU_Q_GUID,TITLE,ANSWER,OPTIONA,OPTIONB,OPTIONC,OPTIOND,CREATETIME,SCORE,WEIGHT from OA_EDUQUESTION "); strSql.Append(" where EDU_Q_GUID=@EDU_Q_GUID "); SqlParameter[] parameters = { new SqlParameter("@EDU_Q_GUID", SqlDbType.NVarChar) }; parameters[0].Value = EDU_Q_GUID; PDTech.OA.Model.OA_EDUQUESTION model=new PDTech.OA.Model.OA_EDUQUESTION(); DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters); if(ds.Tables[0].Rows.Count>0) { return DataRowToModel(ds.Tables[0].Rows[0]); } else { return null; } } /// <summary> /// 得到一个对象实体 /// </summary> public PDTech.OA.Model.OA_EDUQUESTION DataRowToModel(DataRow row) { PDTech.OA.Model.OA_EDUQUESTION model=new PDTech.OA.Model.OA_EDUQUESTION(); if (row != null) { if(row["EDU_Q_GUID"]!=null) { model.EDU_Q_GUID=row["EDU_Q_GUID"].ToString(); } if(row["TITLE"]!=null) { model.TITLE=row["TITLE"].ToString(); } if(row["ANSWER"]!=null) { model.ANSWER=row["ANSWER"].ToString(); } if(row["OPTIONA"]!=null) { model.OPTIONA=row["OPTIONA"].ToString(); } if(row["OPTIONB"]!=null) { model.OPTIONB=row["OPTIONB"].ToString(); } if(row["OPTIONC"]!=null) { model.OPTIONC=row["OPTIONC"].ToString(); } if(row["OPTIOND"]!=null) { model.OPTIOND=row["OPTIOND"].ToString(); } if(row["CREATETIME"]!=null && row["CREATETIME"].ToString()!="") { model.CREATETIME=DateTime.Parse(row["CREATETIME"].ToString()); } if(row["SCORE"]!=null && row["SCORE"].ToString()!="") { model.SCORE=decimal.Parse(row["SCORE"].ToString()); } if(row["WEIGHT"]!=null && row["WEIGHT"].ToString()!="") { model.WEIGHT=decimal.Parse(row["WEIGHT"].ToString()); } } return model; } /// <summary> /// 随机获取一道试题 /// </summary> /// <returns></returns> public DataTable GetRoundObj() { string sql = "select * from (select ROW_NUMBER() OVER (ORDER BY EDU_Q_GUID) AS sort_rowno, * from (select * from OA_EDUQUESTION) as a) as b where b.sort_rowno=(select cast(ceiling(rand() * (select COUNT(1) from OA_EDUQUESTION oe)) as int))"; return DbHelperSQL.GetTable(sql); } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetList(string strWhere) { StringBuilder strSql=new StringBuilder(); strSql.Append("select EDU_Q_GUID,TITLE,ANSWER,OPTIONA,OPTIONB,OPTIONC,OPTIOND,CREATETIME,SCORE,WEIGHT "); strSql.Append(" FROM OA_EDUQUESTION "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } return DbHelperSQL.Query(strSql.ToString()); } public DataSet GetTestList(string strWhere) { StringBuilder strSql = new StringBuilder(); strSql.Append(@"select a.*,b.MAP_INDEX from OA_EDUQUESTION a left join OA_QUESTION_TEST_MAP b on a.EDU_Q_GUID = b.EDU_Q_GUID left join OA_EDUTEST c on b.EDU_T_GUID = c.EDU_T_GUID "); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere); } strSql.Append(" order by b.MAP_INDEX "); return DbHelperSQL.Query(strSql.ToString()); } /// <summary> /// 获取记录总数 /// </summary> public int GetRecordCount(string strWhere) { StringBuilder strSql=new StringBuilder(); strSql.Append("select count(1) FROM OA_EDUQUESTION "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } object obj = DbHelperSQL.GetSingle(strSql.ToString()); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// 分页获取数据列表 /// </summary> public IList<Model.OA_EDUQUESTION> Get_Paging_List_ByCondition(string strwhere, int PageSize, int PageIndex, out int totalrecord) { //string condition = DAL_Helper.GetWhereCondition(where); string strSQL = string.Empty; if (!string.IsNullOrEmpty(strwhere)) { strSQL = string.Format(@"select top (21-(select COUNT(*) from OA_EDAYQUESTION where {0})) * from OA_EDUQUESTION where EDU_Q_GUID not in (select distinct EDU_Q_GUID from OA_EDAYQUESTION where {0} )" , strwhere); } else { strSQL = string.Format(" select * from OA_EDUQUESTION where EDU_Q_GUID not in (select distinct EDU_Q_GUID from OA_EDAYQUESTION) "); } PageDescribe pdes = new PageDescribe(); pdes.CurrentPage = PageIndex; pdes.PageSize = PageSize; DataTable dt = pdes.PageDescribes(strSQL); totalrecord = pdes.RecordCount; return DAL_Helper.CommonFillList<Model.OA_EDUQUESTION>(dt); } /// <summary> /// 分页获取数据列表 /// </summary> public IList<Model.OA_EDUQUESTION> Get_Paging_List(string title, int PageSize, int PageIndex, out int totalrecord) { //string condition = DAL_Helper.GetWhereCondition(where); string strSQL = string.Empty; if (!string.IsNullOrEmpty(title)) { strSQL = string.Format("SELECT * from OA_EDUQUESTION WHERE TITLE like '%{0}%' ", title); } else { strSQL = string.Format("SELECT * from OA_EDUQUESTION ", title); } PageDescribe pdes = new PageDescribe(); pdes.CurrentPage = PageIndex; pdes.PageSize = PageSize; DataTable dt = pdes.PageDescribes(strSQL, "createtime", "desc"); totalrecord = pdes.RecordCount; return DAL_Helper.CommonFillList<Model.OA_EDUQUESTION>(dt); } /// <summary> /// 分页获取数据列表 /// </summary> public IList<Model.OA_EDUQUESTION> Get_Paging_List(decimal userId, string testId, int PageSize, int PageIndex, out int totalrecord) { string strSQL = string.Empty; strSQL = string.Format(@"SELECT TOP (100) PERCENT a.*,u.MAP_INDEX from OA_EDUQUESTION a join (select EDU_Q_GUID,MAP_INDEX from OA_QUESTION_TEST_MAP where EDU_T_GUID = '{0}' and EDU_MAP_GUID in (select EDU_MAP_GUID from OA_TEST_ANSWER where ANSWER_ID = {1})) u on u.EDU_Q_GUID = a.EDU_Q_GUID order by MAP_INDEX", testId, userId); PageDescribe pdes = new PageDescribe(); pdes.CurrentPage = PageIndex; pdes.PageSize = PageSize; DataTable dt = pdes.PageDescribes(strSQL); totalrecord = pdes.RecordCount; return DAL_Helper.CommonFillList<Model.OA_EDUQUESTION>(dt); } public IList<Model.OA_EDUQUESTION> Get_Paging_TestList(string quesIds, int PageSize, int PageIndex, out int totalrecord) { string strSQL = string.Empty; if (!string.IsNullOrEmpty(quesIds)) { strSQL = string.Format("SELECT * from OA_EDUQUESTION WHERE EDU_Q_GUID in ({0}) ", quesIds); } else { strSQL = string.Format("SELECT * from OA_EDUQUESTION "); } PageDescribe pdes = new PageDescribe(); pdes.CurrentPage = PageIndex; pdes.PageSize = PageSize; DataTable dt = pdes.PageDescribes(strSQL,"createtime", "desc"); totalrecord = pdes.RecordCount; return DAL_Helper.CommonFillList<Model.OA_EDUQUESTION>(dt); } #endregion BasicMethod #region ExtensionMethod #endregion ExtensionMethod } }
using System; using System.Linq; using UnityEngine; namespace buildings { public class BuildMarkPlatformCell : MonoBehaviour { public GroundType matchGroundType = GroundType.Ground; private string matchColliderTag; private Color _markColor; private Color _markDeniedColor; private Renderer _renderer; private GameObject _collider; private Vector3 lastPos = Vector3.zero; public virtual bool CanPlace { get { return _collider != null && _collider.tag == matchColliderTag; } } void Awake() { _renderer = GetComponent<Renderer>(); _markColor = _renderer.material.color; _markDeniedColor = new Color(255, 0, 0, 255); matchColliderTag = Enum.GetName(typeof(GroundType), matchGroundType); } void OnTriggerEnter(Collider collider) { if(collider.gameObject.name.Contains("BuildMarkPlatformCell")) return; if (Enum.GetNames(typeof(GroundType)).Any(ground_type => ground_type == collider.tag)) return; _collider = collider.gameObject; _renderer.material.color = CanPlace ? _markColor : _markDeniedColor; } void OnTriggerExit(Collider collider) { if (collider.gameObject.name.Contains("BuildMarkPlatformCell")) return; if (Enum.GetNames(typeof(GroundType)).Any(ground_type => ground_type == collider.tag)) return; lastPos = Vector3.zero; _collider = null; _renderer.material.color = CanPlace ? _markColor : _markDeniedColor; } void Update() { if(lastPos == transform.position) return; lastPos = transform.position; Ray ray = new Ray(transform.position,Vector3.down); RaycastHit hit; if (Physics.Raycast(ray, out hit, 1.0f)) { _collider = hit.collider.gameObject; } _renderer.material.color = CanPlace ? _markColor : _markDeniedColor; } } }
using System; using System.Collections.Generic; using System.Text; namespace DBStore.Models.VModels { public class RequestProductVM { public RequestProduct RequestProduct { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Physics { internal class EventManager { public static void WhatHappensNext(PhysicsObject physicsObject, GridManager gridManager, EventManager eventManager, double endTime) { var couldHits = physicsObject.AddToGrid(gridManager); var nextStep = Math.Min(endTime, physicsObject.Time + (gridManager.stepSize / physicsObject.Speed)); foreach (var couldHit in couldHits) { if (physicsObject != couldHit && physicsObject.TryNextCollision(couldHit, nextStep, out var collision)) { eventManager.AddEvent(collision); } } // we put in move events even if it is not moving so we update times if (physicsObject.Mobile && physicsObject.Time < endTime) { eventManager.AddMoveEvent(nextStep, physicsObject); } } internal readonly struct CollisiphysicsObjectEven : IEvent { public double Time { get; } private readonly PhysicsObject physicsObject1, physicsObject2; private readonly double x1, x2, y1, y2, start_x1, start_x2, start_y1, start_y2, start_vx1, start_vx2, start_vy1, start_vy2; private const double CLOSE = .01; public CollisiphysicsObjectEven(double time, PhysicsObject physicsObject1, PhysicsObject physicsObject2, double x1, double y1, double x2, double y2) { this.Time = time; this.physicsObject1 = physicsObject1; this.physicsObject2 = physicsObject2; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.start_x1 = physicsObject1.X; this.start_y1 = physicsObject1.Y; this.start_x2 = physicsObject2.X; this.start_y2 = physicsObject2.Y; this.start_vx1 = physicsObject1.Vx; this.start_vy1 = physicsObject1.Vy; this.start_vx2 = physicsObject2.Vx; this.start_vy2 = physicsObject2.Vy; } private bool IsGood(double vf, double v) { return vf != v; } public MightBeCollision Enact(GridManager gridManager, EventManager eventManager, double endTime) { if (physicsObject1.X != start_x1 || physicsObject1.Y != start_y1 || physicsObject2.X != start_x2 || physicsObject2.Y != start_y2 || physicsObject1.Vx != start_vx1 || physicsObject1.Vy != start_vy1 || physicsObject2.Vx != start_vx2 || physicsObject2.Vy != start_vy2) { return new MightBeCollision(); } physicsObject1.RemoveFromGrid(gridManager); physicsObject2.RemoveFromGrid(gridManager); physicsObject1.X = x1; physicsObject1.Y = y1; physicsObject1.Time = Time; physicsObject2.X = x2; physicsObject2.Y = y2; physicsObject2.Time = Time; // update the V of both // when a collision happen how does it go down? // the velocities we care about are normal to the line // we find the normal and take the dot product var dx = physicsObject1.X - physicsObject2.X; var dy = physicsObject1.Y - physicsObject2.Y; var normal = new Vector(dx, dy).NewUnitized(); var v1 = normal.Dot(physicsObject1.Velocity); var m1 = physicsObject1.Mass; var v2 = normal.Dot(physicsObject2.Velocity); var m2 = physicsObject2.Mass; MightBeCollision res; if (physicsObject1.Mobile == false) { physicsObject2.Velocity = normal.NewScaled(-2 * v2).NewAdded(physicsObject2.Velocity); res = new MightBeCollision(new Collision( physicsObject2.X + normal.NewScaled((physicsObject2 as PhysicsObject<Ball>).shape.Radius).x, physicsObject2.Y + normal.NewScaled((physicsObject2 as PhysicsObject<Ball>).shape.Radius).y, normal.NewScaled(-2 * v2 * m2).x, normal.NewScaled(-2 * v2 * m2).y, false )); } else if (physicsObject2.Mobile == false) { physicsObject1.Velocity = normal.NewScaled(-2 * v1).NewAdded(physicsObject1.Velocity); res = new MightBeCollision(new Collision( physicsObject2.X + normal.NewScaled((physicsObject2 as PhysicsObject<Ball>).shape.Radius).x, physicsObject2.Y + normal.NewScaled((physicsObject2 as PhysicsObject<Ball>).shape.Radius).y, normal.NewScaled(-2 * v1 * m1).x, normal.NewScaled(-2 * v1 * m1).y, false )); } else { // we do the physics and we get a quadratic for vf2 var c1 = (v1 * m1) + (v2 * m2); var c2 = (v1 * v1 * m1) + (v2 * v2 * m2); var A = (m2 * m2) + (m2 * m1); var B = -2 * m2 * c1; var C = (c1 * c1) - (c2 * m1); double vf2; if (A != 0) { // b^2 - 4acS var D = (B * B) - (4 * A * C); if (D >= 0) { var vf2_plus = (-B + Math.Sqrt(D)) / (2 * A); var vf2_minus = (-B - Math.Sqrt(D)) / (2 * A); if (IsGood(vf2_minus, v2) && IsGood(vf2_plus, v2) && vf2_plus != vf2_minus) { if (Math.Abs(v2 - vf2_plus) > Math.Abs(v2 - vf2_minus)) { if (Math.Abs(v2 - vf2_minus) > CLOSE) { throw new Exception("we are getting physicsObject2 vf2s: " + vf2_plus + "," + vf2_minus + " for vi2: " + v2); } vf2 = vf2_plus; } else { if (Math.Abs(v2 - vf2_plus) > CLOSE) { throw new Exception("we are getting physicsObject2 vf2s: " + vf2_plus + "," + vf2_minus + " for vi2: " + v2); } vf2 = vf2_minus; } } else if (IsGood(vf2_minus, v2)) { vf2 = vf2_minus; } else if (IsGood(vf2_plus, v2)) { vf2 = vf2_plus; } else { throw new Exception("we are getting no vfs"); } } else { throw new Exception("should not be negative"); } } else { throw new Exception("A should not be 0! if A is zer something has 0 mass"); } physicsObject2.Velocity = normal.NewScaled(vf2).NewAdded(normal.NewScaled(-v2)).NewAdded(physicsObject2.Velocity); var f = (vf2 - v2) * m2; var vf1 = v1 - (f / m1); physicsObject1.Velocity = normal.NewScaled(vf1).NewAdded(normal.NewScaled(-v1)).NewAdded(physicsObject1.Velocity); res =new MightBeCollision(new Collision( physicsObject2.X + normal.NewScaled((physicsObject2 as PhysicsObject<Ball>).shape.Radius).x, physicsObject2.Y + normal.NewScaled((physicsObject2 as PhysicsObject<Ball>).shape.Radius).y, normal.NewScaled(vf1).x, normal.NewScaled(vf1).y, false )); } WhatHappensNext(physicsObject1, gridManager, eventManager, endTime); WhatHappensNext(physicsObject2, gridManager, eventManager, endTime); return res; } } internal readonly struct MoveEvent : IEvent { public double Time { get; } private readonly PhysicsObject physicsObject; private readonly double x, y, start_x, start_y, start_vx, start_vy; public MoveEvent(double time, PhysicsObject physicsObject, double X, double Y) { this.Time = time; this.physicsObject = physicsObject; x = X; y = Y; start_x = physicsObject.X; start_y = physicsObject.Y; this.start_vx = physicsObject.Vx; this.start_vy = physicsObject.Vy; } public MightBeCollision Enact(GridManager gridManager, EventManager eventManager, double endtime) { if (physicsObject.X != start_x || physicsObject.Y != start_y || physicsObject.Vx != start_vx || physicsObject.Vy != start_vy) { return new MightBeCollision(); } physicsObject.RemoveFromGrid(gridManager); physicsObject.X = x; physicsObject.Y = y; physicsObject.Time = Time; WhatHappensNext(physicsObject, gridManager, eventManager, endtime); return new MightBeCollision(); } } private readonly LinkedList<IEvent> Events = new LinkedList<IEvent>(); public void AddMoveEvent(double time, PhysicsObject physicsObject) { var toAdd = new MoveEvent(time, physicsObject, physicsObject.X + ((time - physicsObject.Time) * physicsObject.Vx), physicsObject.Y + ((time - physicsObject.Time) * physicsObject.Vy)); AddEvent(toAdd); } private void AddEvent(IEvent toAdd) { if (Events.First == null) { Events.AddLast(toAdd); } else { // could be expensive var at = Events.First; while (at.Value.Time < toAdd.Time) { if (at.Next == null) { Events.AddLast(toAdd); return; } at = at.Next; } Events.AddBefore(at, toAdd); } } public Collision[] RunAll(double time, GridManager gridManager) { var list = new List<Collision>(); while (Events.Any()) { var first = Events.First.Value; Events.RemoveFirst(); var res = first.Enact(gridManager, this, time); if (res.IsIt(out var collision)) { list.Add(collision); } } return list.ToArray(); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; namespace CountryCityApp.Models { public class CityDBGateway { private static string connectionString = ConfigurationManager.ConnectionStrings["CountryConnectionStr"].ConnectionString; SqlConnection aSqlConnection = new SqlConnection(connectionString); private SqlCommand aSqlCommand; private string query; public DBGatway aDbGateway = new DBGatway(); public void Save(City aCity) { query = "INSERT INTO t_City VALUES('" + aCity.Name + "','" + aCity.About + "','" + aCity.NoOfDwellers + "','" + aCity.Location + "','" + aCity.Weather + "','" + aCity.CountryId + "')"; aSqlConnection.Open(); aSqlCommand = new SqlCommand(query, aSqlConnection); aSqlCommand.ExecuteNonQuery(); aSqlConnection.Close(); } public List<City> GetAllCity() { query = "SELECT * FROM t_City;"; aSqlConnection.Open(); aSqlCommand = new SqlCommand(query, aSqlConnection); SqlDataReader aSqlDataReader = aSqlCommand.ExecuteReader(); List<City> cities = new List<City>(); while (aSqlDataReader.Read()) { City aCity = new City(); aCity.Id = Convert.ToInt32(aSqlDataReader["id"]); aCity.Name = aSqlDataReader["name"].ToString(); aCity.About = aSqlDataReader["about"].ToString(); aCity.NoOfDwellers = Convert.ToInt32(aSqlDataReader["no_of_dwellers"]); aCity.Location = aSqlDataReader["location"].ToString(); aCity.Weather = aSqlDataReader["weather"].ToString(); aCity.CountryId = Convert.ToInt32(aSqlDataReader["countryId"]); aCity.aCountry=new Country(); aCity.aCountry.Name = aDbGateway.GetCountryByName(aCity.CountryId).Name; cities.Add(aCity); } aSqlConnection.Close(); return cities; } public int GetNoOfCities(int id) { query = "SELECT Count(countryId) As NoOfCities FROM t_City WHERE countryId='" + id + "'"; aSqlConnection.Open(); aSqlCommand = new SqlCommand(query, aSqlConnection); SqlDataReader aSqlDataReader = aSqlCommand.ExecuteReader(); int NoOfCities=0; if (aSqlDataReader.HasRows) { aSqlDataReader.Read(); NoOfCities = Convert.ToInt32(aSqlDataReader["NoOfCities"]); } aSqlDataReader.Close(); aSqlConnection.Close(); return NoOfCities; } public int GetNoOfDwellers(int id) { query = "SELECT Sum(no_of_dwellers) As NoOfDwellers FROM t_City WHERE countryId='" + id + "'"; aSqlConnection.Open(); aSqlCommand = new SqlCommand(query, aSqlConnection); SqlDataReader aSqlDataReader = aSqlCommand.ExecuteReader(); int NoOfDwellers = 0; if (aSqlDataReader.HasRows) { aSqlDataReader.Read(); if (aSqlDataReader["NoOfDwellers"] != DBNull.Value) { NoOfDwellers = Convert.ToInt32(aSqlDataReader["NoOfDwellers"]); } } aSqlDataReader.Close(); aSqlConnection.Close(); return NoOfDwellers; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RoleQuery.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using CGI.Reflex.Core.Entities; using NHibernate; using NHibernate.Criterion; namespace CGI.Reflex.Core.Queries { public class RoleQuery : BaseQueryOver<Role> { public string NameLike { get; set; } protected override IQueryOver<Role, Role> OverImpl(ISession session) { var query = session.QueryOver<Role>(); if (!string.IsNullOrEmpty(NameLike)) query.Where(Restrictions.InsensitiveLike(Projections.Property<Role>(r => r.Name), NameLike, MatchMode.Start)); return query; } } }
/********************************************************** CoxlinCore - Copyright (c) 2023 Lindsay Cox / MIT License **********************************************************/ using System; using System.IO; using UnityEngine; namespace CoxlinCore { /// <summary> /// Allows use to write to a log file that users cane easily get to /// </summary> public static class LogFileWriter { private static string _logFilePath; public static void Initialize() { if (Application.isEditor) { return; } // Get the application's data path in a platform-agnostic way string dataPath = Application.persistentDataPath; _logFilePath = Path.Combine(dataPath, "error_log.txt"); if (!File.Exists(_logFilePath)) { File.Create(_logFilePath); } // Hook into log messages Application.logMessageReceived += HandleLog; } private static void HandleLog(string logMessage, string stackTrace, LogType type) { if (type != LogType.Error && type != LogType.Exception) return; WriteToFile(logMessage, stackTrace); } private static void WriteToFile(string logMessage, string stackTrace) { try { string logContent = string.Format( "Error: {0}\nStackTrace: {1}\nTimestamp: {2}\n----------------------------------\n", logMessage, stackTrace, DateTime.Now); File.AppendAllText(_logFilePath, logContent); } catch (Exception e) { Debug.LogError("Error writing to file: " + e); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using FlagsToCheckboxBinding; namespace FlagsToCheckboxBinding { public class ViewModel :INotifyPropertyChanged { public ViewModel() { iFlags = 1; iEnabledFlags = 7; } private IList<FlagDescription> iFlagsToDisplay; public IList<FlagDescription> FlagsToDisplay { get { return iFlagsToDisplay ?? ( iFlagsToDisplay = new List<FlagDescription> { FlagDescription.FlagOne, FlagDescription.FlagTwo, FlagDescription.FlagThree, FlagDescription.FlagFour }); } } private int iFlags; public int Flags { get { return iFlags; } set { iFlags = value; OnPropertyChanged("Flags"); } } private int iEnabledFlags; public int EnabledFlags { get { return iEnabledFlags; } set { iEnabledFlags = value; OnPropertyChanged("EnabledFlags"); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test10._7 { class SQLHelper { private readonly static string conString = @"Server=LAPTOP-NA9O9SEF;DataBase=Admin_information;Uid=sa;pwd=123456"; public static SqlDataReader GetReader(string sql) { SqlConnection conn = new SqlConnection(conString); SqlCommand cmd = new SqlCommand(sql,conn); try { conn.Open(); return cmd.ExecuteReader(); } catch (Exception e) { conn.Close(); throw; } finally { } } } class Program { static void Main(string[] args) { Console.WriteLine("欢迎登录XXX系统"); Console.Write("请输入登录用户:\t"); string name = Console.ReadLine(); Console.Write("请输入登录密码:\t"); string pwd = Console.ReadLine(); string sqlStr = "select * from information where account='" + name + "' and passwords='" + pwd + "'"; SqlDataReader objDataRead = SQLHelper.GetReader(sqlStr); if (objDataRead.HasRows) { Console.WriteLine("登录成功"); } else { Console.WriteLine("账号密码错误,登录失败!"); } objDataRead.Close();//关闭数据库 Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Drawing; namespace ClassLotto { /* -vergleicht bitweise jedes Element des Wahlarrays mit jedem Element des Losungsarrays, und trägt die Value des Losungsarrays je nach Treffer oder nicht koloriert als String ins Winnerarray ein, -Deklaration des Rückgabewertes: Winnerarray + kommentierender Satz (1-7 Treffer) -Lb1.Content = Rückgabewert (Jede angeklickte Zahl bleibt an Ort und Stelle, aber nach der Losung ist sie je nach Treffer oder nicht eingefärbt, und es gibt ein Fazit unter den gewählten Zahlen) 6. Wird der 'neue Runde' Button geklickt, wird die history() funktion ausgeführt, die das WinnerArray archiviert, die arrays wiped, und die Statistik-GUI füllt 7. Statisik-GUI: Zeigt die Ergebnisse der letzten 5 Runden, eine insg. Trefferquote usw usf. =) public void ergebnisColor(Color highlightColor, string ergebnisZahl) { zahlFarbe = highlightColor; meineZahl = ergebnisZahl; } public Color zahlFarbe { get; set; } public string meineZahl { get; set; } stackoverflow.com/questions/1926264/color-different-parts-of-a-richtextbox-string */ public class LottoMGM { private List<int> losungsListe = new List<int>(); private List<int> ziehungsListe = new List<int>(); private List<string> ergebnisListe = new List<string>(); private string dieseZahl = ""; public List<int> LosungsListe { get => losungsListe; set => losungsListe = value; } public List<int> ZiehungsListe { get => ziehungsListe; set => ziehungsListe = value; } public void Ziehung() { if (this.losungsListe.Count < 6) { for (int i = 0; i < 6; i++) { Random r = new Random(); int thisRand = r.Next(1, 50); if (!(this.ziehungsListe.Contains(thisRand))) { this.ziehungsListe.Add(thisRand); if (this.losungsListe.Contains(thisRand)) { dieseZahl = Convert.ToString(thisRand); dieseZahl += " "; } } } } //.Intersect<TSource>-Methode: (IEnumerable<TSource>, IEnumerable<TSource>) } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace ConsultingManager.Infra.Migrations { public partial class addedcustomersituation : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<Guid>( name: "CityId", table: "Customers", nullable: true); migrationBuilder.AddColumn<Guid>( name: "SituationId", table: "Customers", nullable: true); migrationBuilder.CreateTable( name: "CustomerSituationPoco", columns: table => new { Id = table.Column<Guid>(nullable: false), Description = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_CustomerSituationPoco", x => x.Id); }); migrationBuilder.CreateIndex( name: "IX_Customers_CityId", table: "Customers", column: "CityId"); migrationBuilder.CreateIndex( name: "IX_Customers_SituationId", table: "Customers", column: "SituationId"); migrationBuilder.AddForeignKey( name: "FK_Customers_CustomerCategories_CityId", table: "Customers", column: "CityId", principalTable: "CustomerCategories", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Customers_CustomerSituationPoco_SituationId", table: "Customers", column: "SituationId", principalTable: "CustomerSituationPoco", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Customers_CustomerCategories_CityId", table: "Customers"); migrationBuilder.DropForeignKey( name: "FK_Customers_CustomerSituationPoco_SituationId", table: "Customers"); migrationBuilder.DropTable( name: "CustomerSituationPoco"); migrationBuilder.DropIndex( name: "IX_Customers_CityId", table: "Customers"); migrationBuilder.DropIndex( name: "IX_Customers_SituationId", table: "Customers"); migrationBuilder.DropColumn( name: "CityId", table: "Customers"); migrationBuilder.DropColumn( name: "SituationId", table: "Customers"); } } }
using UnityEngine; namespace RPG.Stats { public class BaseStats : MonoBehaviour { // config params [Range(1,30)] [SerializeField] int startingLevel = 1; [SerializeField] CharacterClass characterClass; [SerializeField] Progression progression = null; int currentLevel = 0; private void Start() { currentLevel = CalculateLevel(); Experience experience = GetComponent<Experience>(); if (experience != null) { experience.onExperienceGained += UpdateLevel; } } private void UpdateLevel() { int newLevel = CalculateLevel(); if (newLevel > currentLevel) { currentLevel = newLevel; print("Level up"); } } public int GetLevel() { if (currentLevel < 1) { currentLevel = CalculateLevel(); } return currentLevel; } public float GetStat(Stat stat) { return progression.GetStat(stat, characterClass, startingLevel); } public int CalculateLevel() { Experience experience = GetComponent<Experience>(); if (experience == null) return startingLevel; float currentXP = GetComponent<Experience>().GetPoints(); int maxLevel = progression.GetLevels(Stat.ExperienceToLevelUp, characterClass); // technically max level is one above this number. for (int levels = 1; levels < maxLevel; levels++) { float xpToLevelUp = progression.GetStat(Stat.ExperienceToLevelUp, characterClass, levels); if (xpToLevelUp > currentXP) { return levels; } } return maxLevel + 1; } } }
using System.Collections.Generic; using Microsoft.Xna.Framework; namespace BiPolarTowerDefence.Entities { public class TowerButtonMenu : BaseObject { public List<TowerButton> TowerButtons { get; set; } = new List<TowerButton>(); public Tower Tower { get; set; } public bool Active { get; set; } = false; public TowerButtonMenu(Game1 game, Vector3 position) : base(game, position) { var buttonWidth = 40; Vector3 offset = new Vector3(buttonWidth, 0, 0); width = 120; height = 20; TowerButtons.Add(new TowerButton(game , position+offset*1, "+",this)); TowerButtons.Add(new TowerButton(game , position+offset*2, "1",this)); TowerButtons.Add(new TowerButton(game , position+offset*2, "2",this)); TowerButtons.Add(new TowerButton(game , position+offset*3, "3",this)); } public void Update(GameTime gameTime) { foreach (TowerButton button in this.TowerButtons) { button.Update(gameTime); } } public void Draw(GameTime gameTime) { foreach (var button in TowerButtons) { button.Draw(gameTime); } } public void PositionUpdate(Vector3 pos) { position = pos; var buttonWidth = 40; Vector3 offset = new Vector3(buttonWidth, 0, 0); for (int i = 1; i < TowerButtons.Count+1; i++) { var ble = i - 1; var button = TowerButtons[ble]; button.PositionUpdate(position+(offset*ble)); } } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class InteractableScript : MonoBehaviour { public Animator anim; void OnTriggerEnter2D(Collider2D cologne) { if (cologne.gameObject.tag == "Player") { anim.SetTrigger("Player"); } } }
using System; using System.Collections.Generic; using System.Text; namespace TestProjects { public class Console { private Synchronizer NewSynchronizer; public Console() { NewSynchronizer = new Synchronizer(); System.Console.WriteLine("Application started at {0:HH:mm:ss.fff}", DateTime.Now); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DukcapilWS { public class Data_Penduduk { // [JsonProperty("NO_KK")] public string NO_KK { get; set; } //[JsonProperty("NIK")] public string NIK { get; set; } //[JsonProperty("NAMA_LGKP")] public string NAMA_LGKP { get; set; } //[JsonProperty("KAB_NAME")] public string KAB_NAME { get; set; } //[JsonProperty("AGAMA")] public string AGAMA { get; set; } // [JsonProperty("NO_RW")] public string NO_RW { get; set; } //[JsonProperty("KEC_NAME")] public string KEC_NAME { get; set; } //[JsonProperty("JENIS_PKRJN")] public string JENIS_PKRJN { get; set; } //[JsonProperty("NO_RT")] public string NO_RT { get; set; } //[JsonProperty("NO_KEL")] public string NO_KEL { get; set; } //[JsonProperty("ALAMAT")] public string ALAMAT { get; set; } //[JsonProperty("NO_KEC")] public string NO_KEC { get; set; } //[JsonProperty("TMPT_LHR")] public string TMPT_LHR { get; set; } //[JsonProperty("STATUS_KAWIN")] public string STATUS_KAWIN { get; set; } //[JsonProperty("NO_PROP")] public string NO_PROP { get; set; } //[JsonProperty("NAMA_LGKP_IBU")] public string NAMA_LGKP_IBU { get; set; } //[JsonProperty("PROP_NAME")] public string PROP_NAME { get; set; } //[JsonProperty("NO_KAB")] public string NO_KAB { get; set; } //[JsonProperty("KEL_NAME")] public string KEL_NAME { get; set; } // [JsonProperty("JENIS_KLMIN")] public string JENIS_KLMIN { get; set; } //[JsonProperty("TGL_LHR")] public DateTime TGL_LHR { get; set; } //public override string ToString() //{ // // return string.Format("Student Information:\n\t id: {0}, \n\t Name: {1}, \n\t Degree: {2}, \n\t Hobbies: {3}", id, Name, Degree, Hobbies); // return string.Format("\n\t NO_KK: {0}, \n\t NIK: {1}, \n\t NAMA_LGKP: {2}, \n\t KAB_NAME: {3}, \n\t NAMA_LGKP_AYAH: {4}, \n\t NO_RW: {5}, \n\t KEC_NAME: {6}, \n\t JENIS_PKRJN: {7}, \n\t NO_RT: {8}, \n\t NO_KEL: {9}, \n\t ALAMAT: {10}, \n\t NO_KEC: {11}, \n\t TMPT_LHR: {12}, \n\t NO_PROP: {13}, \n\t STATUS_KAWIN: {14}, \n\t NAMA_LGKP_IBU: {15}, \n\t PROP_NAME: {16}, \n\t NO_KAB: {17}, \n\t KEL_NAME: {18}, JENIS_KLMIN: {19}, \n\t TGL_LHR: {20}"); //} } }
using Microsoft.WindowsAzure.Storage.Table; namespace Microsoft.DataStudio.Solutions.Tables.Entities { public class TemplateEntity : TableEntity { public string DeploymentTemplateLink {get; set;} public string DeploymentParameters {get; set;} public string ResourcesTopology {get; set;} } }
using System; using System.Drawing; using System.Windows.Forms; namespace WF_02 { class Program { static void Main(string[] args) { Form form = new Form(); form.Text = "First button"; form.BackColor = Color.Beige; Button button = new Button(); button.Text = "Click me"; button.Size = new Size(100, 40); button.BackColor = Color.Olive; button.ForeColor = Color.Navy; button.Font = new Font("Comic Sans MS", 14); button.Top = form.Height / 2 - button.Height; button.Left = form.Width / 2 - button.Width / 2; form.Controls.Add(button); // приєднали кнопку до елементів керування форми button.Click += Button_Click; button.MouseClick += Button_MouseClick; form.MouseClick += Form_MouseClick; form.MouseDoubleClick += new MouseEventHandler(Form_MouseDoubleClick); form.ShowDialog(); } private static void Form_MouseDoubleClick(object sender, MouseEventArgs e) { (sender as Form).Close(); } private static void Form_MouseClick(object sender, MouseEventArgs e) { Form temp = sender as Form; temp.Text = e.Button + " " + e.Location; switch (e.Button) { case MouseButtons.Left: (sender as Form).BackColor = Color.Yellow; break; case MouseButtons.Right: temp.BackColor = Color.LightBlue; break; } } private static void Button_MouseClick(object sender, MouseEventArgs e) { ((sender as Button).Parent as Form).Text = $"Mouse Click {e.Location}"; } static bool flag = true; private static void Button_Click(object sender, EventArgs e) { if (flag) (sender as Button).BackColor = Color.Blue; else (sender as Button).BackColor = Color.Olive; flag = !flag; } } }
using System; using System.ComponentModel; using System.Collections.Generic; using System.Text; namespace RocketLauncher.ViewModels { public abstract class BaseViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void Notify(string property) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StatsMain1 { public abstract class PayOff { public abstract double Do(double spot); public abstract PayOff Clone(); } public class PayOffCall : PayOff { public PayOffCall(PayOffCall payoff) : this(payoff.strike_) { } public PayOffCall(double strike) { this.strike_ = strike; } public override double Do(double spot) { return(Math.Max(spot - strike_, 0)); } public override PayOff Clone() { return new PayOffCall(this); } private double strike_; } public class PayOffPut : PayOff { public PayOffPut(PayOffPut payoff) : this(payoff.strike_) { } public PayOffPut(double strike) { this.strike_ = strike; } public override double Do(double spot) { return(Math.Max(strike_ - spot, 0)); } public override PayOff Clone() { return new PayOffPut(this); } private double strike_; } }
using CDSShareLib.Helper; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Twilio; using Twilio.Rest.Api.V2010.Account; using Twilio.Types; namespace SMSApp.Model { public class TwilioThread { int _TaskId; string _twilioAccountId, _twilioToken; SMSModel smsCtx = new SMSModel(); public TwilioThread(string twilioAccountId, string twilioToken, string twilioPhoneNumber, JObject jsonMessage, int taskId) { _twilioAccountId = twilioAccountId; _twilioToken = twilioToken; _TaskId = taskId; smsCtx.senderPhoneNumber = twilioPhoneNumber; smsCtx.receiverPhoneNumber = jsonMessage["Content"]["receiverPhoneNumber"].ToString(); smsCtx.smsContent = jsonMessage["Content"]["smsContent"].ToString(); } public async void ThreadProc() { AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel(); try { if (!smsCtx.receiverPhoneNumber.StartsWith("+")) smsCtx.receiverPhoneNumber = "+" + smsCtx.receiverPhoneNumber; // Initialize the Twilio client TwilioClient.Init(_twilioAccountId, _twilioToken); MessageResource.Create( from: new PhoneNumber(smsCtx.senderPhoneNumber), to: new PhoneNumber(smsCtx.receiverPhoneNumber), // Message content body: smsCtx.smsContent); SMSApp._appLogger.Info("[Twilio Thread] send SMS success. Receiver PhoneNumber: " + smsCtx.receiverPhoneNumber); operationTask.UpdateTaskBySuccess(_TaskId); } catch (Exception ex) { StringBuilder logMessage = new StringBuilder(); logMessage.AppendLine("[Twilio Thread] Failed. Receiver" + smsCtx.receiverPhoneNumber); logMessage.AppendLine("\tMessage:" + JsonConvert.SerializeObject(this)); logMessage.AppendLine("\tException:" + ex.Message); SMSApp._appLogger.Error(logMessage); operationTask.UpdateTaskByFail(_TaskId, ex.Message); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CFDI.Model { public static class GlobalsVariables { public static bool Peticion { get; set; } public static string Rfc { get; set; } } }
#if CSHARP11_OR_GREATER using System.Threading.Tasks; using Meziantou.Analyzer.Rules; using TestHelper; using Xunit; namespace Meziantou.Analyzer.Test.Rules; public sealed class UseIsPatternInsteadOfSequenceEqualAnalyzerTests { private static ProjectBuilder CreateProjectBuilder() { return new ProjectBuilder() .WithAnalyzer<UseIsPatternInsteadOfSequenceEqualAnalyzer>() .WithCodeFixProvider<UseIsPatternInsteadOfSequenceEqualFixer>() .WithOutputKind(Microsoft.CodeAnalysis.OutputKind.ConsoleApplication) .WithLanguageVersion(Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp11) .WithTargetFramework(TargetFramework.Net7_0); } [Fact] public async Task EqualsOrdinal_CSharp10() { await CreateProjectBuilder() .WithSourceCode(""" using System; _ = "foo".AsSpan().Equals("bar", StringComparison.Ordinal); """) .WithLanguageVersion(Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp10) .ValidateAsync(); } [Fact] public async Task ReadOnlySpanByte_SequenceEqual() { await CreateProjectBuilder() .WithSourceCode(""" using System; _ = new byte[1].AsSpan().SequenceEqual(new byte[0].AsSpan()); """) .ValidateAsync(); } [Fact] public async Task SpanByte_SequenceEqual() { await CreateProjectBuilder() .WithSourceCode(""" using System; Span<byte> value = default; _ = value.SequenceEqual(new byte[0].AsSpan()); """) .ValidateAsync(); } [Fact] public async Task ReadOnlySpan_Equals() { await CreateProjectBuilder() .WithSourceCode(""" using System; _ = "foo".AsSpan().Equals("value"); """) .ValidateAsync(); } [Fact] public async Task EqualsOrdinal_NonConstant() { await CreateProjectBuilder() .WithSourceCode(""" using System; string value = "test"; _ = "foo".AsSpan().Equals(value, StringComparison.Ordinal); """) .ValidateAsync(); } [Fact] public async Task SequenceEquals_NonConstant() { await CreateProjectBuilder() .WithSourceCode(""" using System; string value = "test"; _ = "foo".AsSpan().SequenceEqual(value); """) .ValidateAsync(); } [Fact] public async Task SequenceEquals_Comparer() { await CreateProjectBuilder() .WithSourceCode(""" using System; string value = "test"; _ = "foo".AsSpan().SequenceEqual(value, default(System.Collections.Generic.IEqualityComparer<char>)); """) .ValidateAsync(); } [Fact] public async Task ReadOnlySpanChar_EqualsOrdinal() { await CreateProjectBuilder() .WithSourceCode(""" using System; _ = [||]"foo".AsSpan().Equals("bar", StringComparison.Ordinal); """) .ShouldFixCodeWith(""" using System; _ = "foo".AsSpan() is "bar"; """) .ValidateAsync(); } [Fact] public async Task ReadOnlySpanChar_EqualsOrdinalIgnoreCase() { await CreateProjectBuilder() .WithSourceCode(""" using System; _ = "foo".AsSpan().Equals("bar", StringComparison.OrdinalIgnoreCase); """) .ValidateAsync(); } [Fact] public async Task ReadOnlySpanChar_SequenceEqual() { await CreateProjectBuilder() .WithSourceCode(""" using System; _ = [||]"foo".AsSpan().SequenceEqual("bar"); """) .ShouldFixCodeWith(""" using System; _ = "foo".AsSpan() is "bar"; """) .ValidateAsync(); } [Fact] public async Task SpanChar_SequenceEqual() { await CreateProjectBuilder() .WithSourceCode(""" using System; Span<char> str = default; _ = [||]str.SequenceEqual("bar"); """) .ShouldFixCodeWith(""" using System; Span<char> str = default; _ = str is "bar"; """) .ValidateAsync(); } } #endif
using KsuMvcApp.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace KsuMvcApp.Controllers { [Authorize] public class UserController : Controller { internal static User CurrentUser { get; set; } public ActionResult PersonalProfile() { ViewBag.User = CurrentUser; return View(); } public ActionResult Publication() { ViewBag.UserID = CurrentUser.Id; return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Publication(Query model) { if (ModelState.IsValid) { using (UserContext db = new UserContext()) { model.Id = db.Queries.Count() + 1; db.Queries.Add(model); Notification n = new Notification(); n.Id = db.Notifications.Count() + 1; n.Notification_Date = DateTime.Now.ToString(); n.Notification_Query = model.Id; n.Message = "Запрос на " + model.Query_Type + " " + " №" + model.Id + " был создан."; n.Notification_Type = "Отчёт"; n.Id_User = model.Id_User; db.Notifications.Add(n); db.SaveChanges(); } return RedirectToAction("PersonalProfile", "User"); } return View(model); } public ActionResult Notifications() { using (UserContext db = new UserContext()) { ViewBag.Notifications_List = db.Notifications.Where(n => n.Id_User == CurrentUser.Id).ToList(); } return View(); } public ActionResult Queries() { using (UserContext db = new UserContext()) { ViewBag.Queries_List = db.Queries.Where(q => q.Id_User == CurrentUser.Id).ToList(); } return View(); } public ActionResult SiteMap() { return View(); } public ActionResult Instructions() { return View(); } } }
namespace Task04_TicTacToe { using System; public class TicTacToeLogic { public const int MaxX = 3; public const int MaxY = 3; public char[,] GameBoard; public TicTacToeLogic() { GameBoard = new char[MaxX, MaxY]; for (int i = 0; i < GameBoard.GetLength(0); i++) { for (int j = 0; j < GameBoard.GetLength(1); j++) { GameBoard[i, j] = ' '; } } } public void FirstPlayerMove(int x, int y) { if (GameBoard[x, y] != ' ') { throw new InvalidOperationException("Not valid move!"); } GameBoard[x, y] = 'X'; } public void ComputerPlayerMove() { while (true) { Random rand1 = new Random(); Random rand2 = new Random(); var x = rand1.Next(MaxX); var y = rand2.Next(MaxY); if (this.GameBoard[x, y] == ' ') { this.GameBoard[x, y] = 'O'; break; } } } public int IsGameFinished() { var cnt = 0; for (int i = 0; i < GameBoard.GetLength(0); i++) { for (int j = 0; j < GameBoard.GetLength(1); j++) { if (GameBoard[i, j] != ' ') { cnt ++; } } } if (cnt == MaxX*MaxY) { return 0; } for (int i = 0; i < GameBoard.GetLength(0); i++) { var foundEmpty = false; for (int j = 0; j < GameBoard.GetLength(1); j++) { if (GameBoard[i, j] == ' ') { foundEmpty = true; break; } } if (foundEmpty == false) { return 1; } } for (int i = 0; i < GameBoard.GetLength(1); i++) { var foundEmpty = false; for (int j = 0; j < GameBoard.GetLength(0); j++) { if (GameBoard[j, i] == ' ') { foundEmpty = true; break; } } if (foundEmpty == false) { return 1; } } return -1; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace SimpleApiService.Domain { [Table("account")] public class Account { [Key] [Column("id")] public int Id { get; set; } [Column("account_number")] public string AccountNumber { get; set; } [Column("balance")] public decimal Balance { get; set; } } }
using System; using System.IO; using BusinessLayer.Validator; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace SortinfApp.UnitTests.Utilities.Validator { /// <summary> /// Represents tests for LocalFileValidator class. /// </summary> /// <owner>Anton Petrenko</owner> [TestClass] public class LocalFileValidatorTest { /// <summary> /// Tests IsDataExist if pass empty value it will throw ArgumentNullException. /// </summary> /// <owner>Anton Petrenko</owner> [TestMethod] public void LocalFileValidator_IsDataExist_PassEmptyValue_ThrowArgumentNullException() { // // Arrange. // var localFileValidator = new LocalFileValidator(); string path = string.Empty; // // Assert. // Assert.ThrowsException<ArgumentNullException>(() => localFileValidator.IsDataExist(path)); } /// <summary> /// Tests IsDataExist if pass null value it will throw ArgumentNullException. /// </summary> /// <owner>Anton Petrenko</owner> [TestMethod] public void LocalFileValidator_IsDataExist_PassNullValue_ThrowArgumentNullException() { // // Arrange. // var localFileValidator = new LocalFileValidator(); string path = null; // // Assert. // Assert.ThrowsException<ArgumentNullException>(() => localFileValidator.IsDataExist(path)); } /// <summary> /// Tests IsDataExist if pass exist file it will get true. /// </summary> /// <owner>Anton Petrenko</owner> [TestMethod] public void LocalFileValidator_IsDataExist_PassExistFile_GetTrue() { // // Arrange. // var localFileValidator = new LocalFileValidator(); string path = Path.GetTempPath() + @"\collectionToRead.txt"; bool isDataValid; // // Act. // using (File.Create(path)) { } isDataValid = localFileValidator.IsDataExist(path); File.Delete(path); // // Assert. // Assert.IsTrue(isDataValid); } /// <summary> /// Tests IsDataExist if pass incorect format it will get false. /// </summary> /// <owner>Anton Petrenko</owner> [TestMethod] public void LocalFileValidator_IsDataExist_PassIncorectFormat_GetFalse() { // // Arrange. // var localFileValidator = new LocalFileValidator(); string path = Path.GetTempPath() + @"\collectionToRead.csv"; bool isDataValid; // // Act. // using (File.Create(path)) { } isDataValid = localFileValidator.IsDataExist(path); File.Delete(path); // // Assert. // Assert.IsFalse(isDataValid); } /// <summary> /// Tests IsDataExist if pass nonexistent file it will get false. /// </summary> /// <owner>Anton Petrenko</owner> [TestMethod] public void LocalFileValidator_IsDataExist_PassNonexistentFile_GetFalse() { // // Arrange. // var localFileValidator = new LocalFileValidator(); string path = Path.GetTempPath(); bool isDataValid; // // Act. // isDataValid = localFileValidator.IsDataExist(path); // // Assert. // Assert.IsFalse(isDataValid); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameManager : MonoBehaviour { public GameObject gameOverImage; //게임 오버가 됐을 때 화면에 보여지는 이미지 public GameObject Restarttext; //게임 오버 됐을 때 화면에 띄울 재시작 텍스트 public bool isGameOver; //게임 오버 유무를 알려주는 변수 public float score; //점수 저장 변수 //public GameObject ScoreBoard; //화면에 점수가 표시될 텍스트 public int digit_score = 0; //실수로 저장된 변수를 정수로 저장해주는 변수 public Image image1000; public Image image100; public Image image10; public Image image1; //image 1~1000자릿수를 불러옴 void Start() { isGameOver = false;//처음엔 게임 오버가 안 됨 score = 0;//스코어 0부터 시작 } public void gameOverFun()//게임 오버가 될 때 실행되는 함수 { Time.timeScale = 0;//게임 오버 되면 게임이 멈춘다 gameOverImage.SetActive(true); Restarttext.SetActive(true); isGameOver = true; } void Update() { if (isGameOver == true) { if (Input.GetKeyDown(KeyCode.R)) { Time.timeScale = 1; SceneManager.LoadScene("SampleScene"); //R키 누르면 재시작 (SampleScene을 실행) } } //ScoreBoard.gameObject.SetActive(true);//스코어보드 대신 이미지를 첨부했으니 주석처리함 //스코어의 숫자 이미지를 바꿔주는 함수 int n1000 = digit_score / 1000;//1000의 자리 숫자 int n100 = (digit_score % 1000) / 100; int n10 = (digit_score % 100) / 10;//10의 자리 숫자 int n1 = digit_score % 10;//1의 자리 숫자 string fileName = string.Format("PNG/HUD/text_{0}_small", n1000); image1000.sprite = Resources.Load<Sprite>(fileName); fileName = string.Format("PNG/HUD/text_{0}_small", n100); image100.sprite = Resources.Load<Sprite>(fileName); fileName = string.Format("PNG/HUD/text_{0}_small", n10); image10.sprite = Resources.Load<Sprite>(fileName); fileName = string.Format("PNG/HUD/text_{0}_small", n1); image1.sprite = Resources.Load<Sprite>(fileName); //파일명이 규칙성을 가지고 있다는 점을 이용하여 불러올 파일명을 //불러올 파일명을 직접 조합해서 불러오고 있다 //image1000.SetNativeSize(); //image100.SetNativeSize(); //image10.SetNativeSize(); //image1.SetNativeSize(); } }
namespace ShCore.Patterns { /// <summary> /// Pattern Chain Generic /// </summary> /// <typeparam name="T"></typeparam> public class Chain<T> { private T handler; /// <summary> /// Xử lý /// </summary> public T Handler { get { return handler; } set { handler = value; } } /// <summary> /// Thiết lập Handler /// </summary> /// <typeparam name="THandler"></typeparam> public void SetHandler<THandler>() where THandler : T, new() { // Khởi tạo Handler xử lý var handler = new THandler(); // Nếu xử lý hiện thời chưa có thì gán if (this.handler == null) this.handler = handler; // Nếu có rồi thì gán cho hàng kế tiếp else (this.handler as Chain<T>).Handler = handler; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Logic_Circuit.Parser.Validation.VisitorObjects { /// <summary> /// Checks if there are any loops between this node and the output nodes. /// </summary> public class LoopChecker : ValidationVisitor { private readonly string WholeFile; public LoopChecker(string content) { WholeFile = content; } public override (bool success, string validationError) VisitConnectionLine(ConnectionLine connectionLine) { if (!RecurseToOutput(connectionLine.Line, connectionLine.Line, WholeFile.Split('\n').Length, 0)) { return (false, "Node: '" + connectionLine.Line.Split(':')[0] + "' leads to an infinite loop."); } return (true, ""); } public override (bool success, string validationError) VisitNodeLine(NodeLine nodeLine) { return (true, ""); } private bool RecurseToOutput(string constantNode, string tmpNode, int maxDepth, int depth) { // node is ouptut so return true if (tmpNode.Contains("PROBE;")) return true; // node has itself as a dependency so return false string[] parsedTmpNode = Regex.Replace(tmpNode, @"\s+", "").Replace(";", "").Split(':'); string[] parsedConstantNode = Regex.Replace(constantNode, @"\s+", "").Replace(";", "").Split(':'); if (depth > 0 && parsedTmpNode[0].Equals(parsedConstantNode[0])) return false; // we must be stuck in an infinite loop so return false if (depth > maxDepth) return false; // node is not input so check children List<string> parentNodes = new List<string>(); string[] parentNodeNames = parsedTmpNode[1].Split(','); string[] lines = WholeFile.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); foreach (string parentNodeName in parentNodeNames) { string results = lines.Where(l => l.StartsWith(parentNodeName + ":")).ToList().Last(); parentNodes.Add(results); } foreach (string parentNode in parentNodes) { if (!RecurseToOutput(constantNode, parentNode, maxDepth, depth + 1)) { return false; } } return true; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using CP.i8n; //------------------------------------------------------------------------------ // // This code was generated by OzzCodeGen. // // Manual changes to this file will be overwritten if the code is regenerated. // //------------------------------------------------------------------------------ namespace CriticalPath.Data { [MetadataTypeAttribute(typeof(ProductDTO.ProductMetadata))] public partial class ProductDTO { internal sealed partial class ProductMetadata { // This metadata class is not intended to be instantiated. private ProductMetadata() { } [StringLength(64, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "Required")] [Display(ResourceType = typeof(EntityStrings), Name = "ProductCode")] public string ProductCode { get; set; } [StringLength(128, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "Required")] [DataType(DataType.Text)] [Display(ResourceType = typeof(EntityStrings), Name = "Description")] public string Description { get; set; } [StringLength(256, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [DataType(DataType.ImageUrl)] [Display(ResourceType = typeof(EntityStrings), Name = "ImageUrl")] public string ImageUrl { get; set; } [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "Required")] [Display(ResourceType = typeof(EntityStrings), Name = "CategoryId")] public int CategoryId { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "Licensed")] public bool Licensed { get; set; } [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "Required")] [Display(ResourceType = typeof(EntityStrings), Name = "UnitPrice")] public decimal UnitPrice { get; set; } [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "Required")] [Display(ResourceType = typeof(EntityStrings), Name = "SellingCurrencyId")] public int SellingCurrencyId { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "UnitPrice2")] public decimal UnitPrice2 { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "SellingCurrency2Id")] public int SellingCurrency2Id { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "BuyingPrice")] public decimal BuyingPrice { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "BuyingCurrencyId")] public int BuyingCurrencyId { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "BuyingPrice2")] public decimal BuyingPrice2 { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "BuyingCurrency2Id")] public int BuyingCurrency2Id { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "LicensorPrice")] public decimal LicensorPrice { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "LicensorCurrencyId")] public int LicensorCurrencyId { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "RoyaltyFee")] public decimal RoyaltyFee { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "RoyaltyCurrencyId")] public int RoyaltyCurrencyId { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "RetailPrice")] public decimal RetailPrice { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "RetailCurrencyId")] public int RetailCurrencyId { get; set; } [UIHint("BoolRed")] [Display(ResourceType = typeof(EntityStrings), Name = "Discontinued")] public bool Discontinued { get; set; } [DataType(DataType.Date)] [Display(ResourceType = typeof(EntityStrings), Name = "DiscontinueDate")] public DateTime DiscontinueDate { get; set; } [StringLength(256, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [DataType(DataType.MultilineText)] [Display(ResourceType = typeof(EntityStrings), Name = "DiscontinueNotes")] public string DiscontinueNotes { get; set; } } } }
using System; using MvvmCross.Binding.BindingContext; using MvvmCross.iOS.Views; using UIKit; using VictimApplication.Core.ViewModels; namespace VictimApplication.iOS.Views { public partial class EditUserView : MvxViewController<EditUserViewModel> { public EditUserView() : base("EditUserView", null) { } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. this.CreateBinding(VCUserName).To((EditUserViewModel vm) => vm.UserName).Apply(); this.CreateBinding(VCFirstName).To((EditUserViewModel vm) => vm.FirstName).Apply(); this.CreateBinding(VCSecondName).To((EditUserViewModel vm) => vm.SecondName).Apply(); this.CreateBinding(VCEmail).To((EditUserViewModel vm) => vm.Email).Apply(); this.CreateBinding(VCUserType).To((EditUserViewModel vm) => vm.UserType).Apply(); this.CreateBinding(VCPostEdit).To((EditUserViewModel vm) => vm.EditUserCommand).Apply(); } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } } }
using System; using System.Collections.Generic; using Acr.UserDialogs; using City_Center.Clases; using Xamarin.Forms; namespace City_Center.Page { public partial class PaginaAceptar : ContentPage { public PaginaAceptar() { InitializeComponent(); NavigationPage.SetTitleIcon(this, "logo@2x.png"); } protected override void OnDisappearing() { base.OnDisappearing(); ActualizaBarra.Cambio(VariablesGlobales.VentanaActual); GC.Collect(); } async void Handle_Clicked(object sender, System.EventArgs e) { UserDialogs.Instance.ShowLoading("Iniciando Sesion...", MaskType.Black); MasterPage fpm = new MasterPage(); //fpm.Master = new DetailPage(); // You have to create a Master ContentPage() //App.NavPage = new NavigationPage(new CustomTabPage()) { BarBackgroundColor = Color.FromHex("#23144B") }; //fpm.Detail = App.NavPage; // You have to create a Detail ContenPage() Application.Current.MainPage = fpm; UserDialogs.Instance.HideLoading(); await Mensajes.Alerta("Bienvenido " + Application.Current.Properties["NombreCompleto"].ToString()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DataObject; namespace Service.Interface { public interface IThietBi { int ThemThietBi(ThietBi tb); int XoaThietBi(int maThietBi); int CapNhatThongTinThietBi(ThietBi tb); int ThemNgaySuaChua(DateTime ngaySuaChua); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Threading.Tasks; using Oracle.ManagedDataAccess.Client; using MobileService45.DAL; namespace MobileService45.Controllers { [RoutePrefix("GIAOTIEPVersion1")] public class GiaoTiepVersion1Controller : ApiController { [HttpGet] [Route("LOAD_KH_BD")] public async Task<IHttpActionResult> LoadKHBD(string Mobile, string Password,string OTP, string SMADV, string SACC) { var CheckMobile = await Datacs.IsValidMobile(Mobile, Password, OTP); if (CheckMobile != "true") return BadRequest(CheckMobile); List<OracleParameter> param = new List<OracleParameter>(); OracleParameter p1 = new OracleParameter("SMADV", OracleDbType.Varchar2); OracleParameter p2 = new OracleParameter("SACC", OracleDbType.Varchar2); p1.Value = SMADV; p2.Value = SACC; param.Add(p1); param.Add(p2); var Result = Datacs.GetData("GIAOTIEP.", "LOAD_KH_BD", param); if (Result == null) { return BadRequest("Không thực hiện được yêu cầu, vui lòng xem lại thông tin"); } return Ok(Result); } //[HttpGet] //[Route("TestSelfBuild")] //public IHttpActionResult get() //{ // return Content(HttpStatusCode.BadRequest, "Any object"); //} [HttpGet] [Route("LOAD_MUC_PROFILE")] public async Task<IHttpActionResult> LoadMucProfile(string Mobile, string Password,string OTP, string SPROFILE, string SIDTB) { var CheckMobile = await Datacs.IsValidMobile(Mobile, Password, OTP); if (CheckMobile != "true") return BadRequest(CheckMobile); List<OracleParameter> param = new List<OracleParameter>(); OracleParameter p1 = new OracleParameter("SPROFILE", OracleDbType.Varchar2); OracleParameter p2 = new OracleParameter("SIDTB", OracleDbType.Varchar2); p1.Value = SPROFILE; p2.Value = SIDTB; param.Add(p1); param.Add(p2); var Result = Datacs.GetData("GIAOTIEP.", "LOAD_MUC_PROFILE", param); if (Result == null) { return BadRequest("Không thực hiện được yêu cầu, vui lòng xem lại thông tin"); } return Ok(Result); } [Route("XNBD_CAPDONG")] [HttpGet] public async Task<IHttpActionResult> XNBDCapDong(string Mobile, string Password,string OTP, int SLBD, int SIDTB, string SIDDT, string SPROFILE) { var CheckMobile = await Datacs.IsValidMobile(Mobile, Password, OTP); if (CheckMobile != "true") return BadRequest(CheckMobile); List<OracleParameter> param = new List<OracleParameter>(); OracleParameter p1 = new OracleParameter("SLBD", OracleDbType.Int32); OracleParameter p2 = new OracleParameter("SIDTB", OracleDbType.Int32); OracleParameter p3 = new OracleParameter("SIDDT", OracleDbType.Varchar2); OracleParameter p4 = new OracleParameter("SPROFILE", OracleDbType.Varchar2); param.Add(p1); param.Add(p2); param.Add(p3); param.Add(p4); var Result = Datacs.GetData("GIAOTIEP.", "XNBD_CAPDONG", param); if (Result == null) { return BadRequest("Không thực hiện được yêu cầu, vui lòng xem lại thông tin"); } return Ok(Result); } } }
using System; namespace Bubble_Sort { public class BubbleSort { public static void BubbleSortFirst(int[] Array,int n){ int m,i,j; for(i=n-2;i>=0;i--){ for(j=0;j<=i;j++){ if(Array[j]>=Array[j+1]){ m=Array[j]; Array[j]=Array[j+1]; Array[j+1]=m; } } } Console.Write("your answer is:"); for(i=0;i<n;i++){ Console.Write(Array[i]+"/"); } } public static void BubbleSortSecond(int[] Array,int n){ int i,j,m,z; for(i=n-2;i>=0;i--){ z=0; for(j=0;j<=i;j++){ if(Array[j]>=Array[j+1]){ m=Array[j]; Array[j]=Array[j+1]; Array[j+1]=m; z++; } } if(z==0){ break;} } for(i=0;i<n;i++){ Console.Write(Array[i]+"/"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MobileInputManager : MonoBehaviour { public static MobileInputManager instance; [HideInInspector] public bool isGamepadConnected = false; [SerializeField] private ETCTouchPad touchPad; [SerializeField] private ETCJoystick moveJoystick; [SerializeField] private Canvas virtualControlPad; [HideInInspector] public bool isAim; public Text debugInfo; private void Awake() { instance = this; } // Use this for initialization void Start () { isAim = false; } // Update is called once per frame void Update () { #if UNITY_EDITOR //ActivateVirtualGamePad(); SetUpStandaloneControllScheme(); return; #endif #if UNITY_STANDALONE SetUpStandaloneControllScheme(); return; #endif #if UNITY_ANDROID ActivateVirtualGamePad(); #endif #if UNITY_IOS ActivateVirtualGamePad(); #endif OnAim(); } private void SetUpStandaloneControllScheme() { virtualControlPad.gameObject.SetActive(false); isGamepadConnected = true; } private void ActivateVirtualGamePad() { if (Input.GetJoystickNames().Length > 0) { if (Input.GetJoystickNames()[0] != "") { //There is a controller connected to the game! debugInfo.text = Input.GetJoystickNames()[0]; virtualControlPad.gameObject.SetActive(false); isGamepadConnected = true; } else { debugInfo.text = "No GamePad connected!"; //There is no controller connected to the game! virtualControlPad.gameObject.SetActive(true); isGamepadConnected = false; } } else { debugInfo.text = "No GamePad connected!"; //There is no controller connected to the game! virtualControlPad.gameObject.SetActive(true); isGamepadConnected = false; } } public Vector2 OnTouchPadMove() { Vector2 touchPadAxis = new Vector2(touchPad.axisX.axisValue, touchPad.axisY.axisValue); return touchPadAxis; } public Vector3 OnJoystickMove() { Vector3 joystickAxis = new Vector3(moveJoystick.axisX.axisValue, 0, moveJoystick.axisY.axisValue); return joystickAxis; } public bool OnFire() { return ETCInput.GetButton("ShootButton"); } public bool OnSprint() { return ETCInput.GetButton("SprintButton"); } private bool OnAim() { if (ETCInput.GetButtonDown("AimButton")) { isAim = !isAim; } return isAim; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DistanceConverter { class Program { static void Main(string[] args) { if (args.Length >= 1 && args[0] == "-tom") { PrintFeetToMeterList(1,10); } else { PrintMeterToFeetList(1,10); } } //フィートからメートル private static void PrintFeetToMeterList(int start, int stop) { for (int feet = 1; feet <= 10; feet++) { double meter = FeetConverter.ToMeter(feet); Console.WriteLine("{0} ft={1:0.0000}m", feet, meter); } } //メートルからフィート private static void PrintMeterToFeetList(int start,int stop) { for (int meter = 1; meter <= 10; meter++) { double feet = FeetConverter.FromMeter(meter); Console.WriteLine("{0} m={1:0.0000}ft", meter, feet); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; namespace DAL.SYSTEM { /// <summary> /// 实体类 LoginModel /// 编写者: /// 日期:2013/3/15 16:38:09 /// </summary> public class LoginDAL { DBUtility.DBOperator db = DBUtility.DALFactory.GetDBOperator(DBUtility.DALFactory.strConnection0);//连接数据库 #region 取用户登录的信息 /// <summary> /// 取用户登录的信息 /// </summary> /// <returns></returns> public object GetUserLoginModel(string logincode) { string sql = " select telephone,mobile,email,userid,username,usercode,logincode,userpwd,photourl,blogin,deptID,deptname,sex,usertype,jgorbm from dbo.View_UsersLogin where logincode='" + logincode + "'"; object login = db.ExecuteEntitySQL<MODEL.SYSTEM.LoginModel>(sql, false); return login; } #endregion #region 更改用户登录状态 public int ChangeUserState(int state, string userID) { string sql = " update users set bonline=" + state + ",lastflushtime='" + System.DateTime.Now + "' where userid='" + userID + "'"; return db.ExecuteNonQuerySQL(sql); } #endregion #region 统计在线人数 public int TotalOnline(int UserID) { string sql = "select count(0) from dbo.Users where bOnline=1 and delflag=0;"; sql += "update users set lastflushtime=getdate() where UserID=" + UserID; DataTable dt = db.ExecuteSQLDataTable(sql, false); if (dt != null && dt.Rows.Count > 0) { return Convert.ToInt32(dt.Rows[0][0].ToString()); } else { return 0; } } #endregion #region 根据用户ID和部门ID获取相应的信息 /// <summary> /// 根据用户ID和部门ID获取相应的信息 /// </summary> /// <param name="UserID">用户ID</param> /// <param name="DeptID">部门ID</param> /// <returns></returns> public DataTable GetUserInfoByUIDAndDeptID(string UserID, string DeptID) { string sql = @"select telephone,mobile,email,userid,username,usercode,logincode, stationID,positionName,photourl,deptID,deptname,sex from dbo.View_Users where userid='" + UserID + "' and levelcode='" + DeptID + "'"; return db.ExecuteSQLDataTable(sql, false); } #endregion #region 单点登录验证 public string UkeyLimit(string logincode) { string sql = "select UkeyID from userLoginlimit where userid in(select userID from Users where logincode='" + logincode + "') and loginType='Ukey' and IsStart=1 ;"; DataTable dt = db.ExecuteSQLDataTable(sql, false); if (dt != null && dt.Rows.Count > 0) { return dt.Rows[0][0].ToString(); } else { return ""; } } #endregion #region 查询指定的用户信息 /// <summary> /// 查询指定的用户信息 /// </summary> /// <param name="userid"></param> /// <param name="pwd"></param> /// <returns></returns> public DataTable GetDataTable(string swhere) { string sql = " select photourl,deptID,deptname,sex,userID,UserName,logincode,usercode,dsort,uSort,levelCode,primarydept "; sql += " from dbo.View_Users "; if (swhere.Trim() != "") sql += " where " + swhere; return db.ExecuteSQLDataTable(sql, false); } #endregion #region 求出个人未阅的消息、待办的流程、个人工作 /// <summary> /// 求出个人未阅的消息、待办的流程、个人工作 /// </summary> /// <param name="id"></param> /// <returns></returns> public DataTable GetNnMsgNum(string id, string wkstarttime) { object[] obj = new object[2]; obj[0] = id; obj[1] = wkstarttime; return db.ExecutePRODataTable("pt_WCFGetUnMsgnum", obj,false); } #endregion #region 修改密码 public int UpdatePWD(int UserID, string OldPwd, string Pwd) { string sqlSel = "select count(1) from Users where UserID=" + UserID + " and userpwd='" + OldPwd + "'"; if (Convert.ToInt32(db.ExecuteScalarSQL(sqlSel)) < 1) { return -1; } string sql = "update Users set userpwd='" + Pwd + "' where UserID=" + UserID; int n = db.ExecuteNonQuerySQL(sql); return n; } #endregion } }
using Kit.Enums; using Kit.Services.Interfaces; using System; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace Kit.Forms.Pages { public class BasePage : ContentPage, INotifyPropertyChanged, IDisposable, ICrossWindow, ICrossVisualElement { #region IDisposable public virtual void Dispose() { DisposeBindingContext(); } public virtual void OnClose() { } protected override void OnParentSet() { base.OnParentSet(); if (Parent == null) { OnClose(); this.ShowDialogCallback?.Set(); DisposeBindingContext(); } } protected void DisposeBindingContext() { if (DisposeAlso != null) { foreach (IDisposable disposable in DisposeAlso) { disposable?.Dispose(); } } if (BindingContext != this && BindingContext is IDisposable disposableBindingContext) { disposableBindingContext.Dispose(); BindingContext = null; } } protected virtual IDisposable[] DisposeAlso { get; } ~BasePage() { DisposeBindingContext(); } #endregion IDisposable #region ICrossWindow public virtual Task Close() { if (Shell.Current is Shell shell) { return shell.Navigation.PopAsync(); } return Navigation.PopModalAsync(); } public virtual Task Show() { if (Shell.Current is Shell shell) { return shell.Navigation.PushAsync(this); } return Navigation.PushModalAsync(this); } public virtual async Task ShowDialog() => await Task.WhenAll(Show(), WaitUntilClose()); #endregion ICrossWindow public object Auxiliar { get; set; } private AutoResetEvent ShowDialogCallback; public class PageOrientationEventArgs : EventArgs { public PageOrientationEventArgs(PageOrientation orientation) { Orientation = orientation; } public PageOrientation Orientation { get; } } public enum PageOrientation { Horizontal = 0, Vertical = 1, } private double _width; private double _height; public event EventHandler<PageOrientationEventArgs> OnOrientationChanged = (e, a) => { }; private void InitOrientationPage() { _width = Width; _height = Height; } //protected override void OnSizeAllocated(double width, double height) //{ // try // { // double oldWidth = _width; // const double sizenotallocated = -1; // base.OnSizeAllocated(width, height); // if (Equals(_width, width) && Equals(_height, height)) return; // _width = width; // _height = height; // // ignore if the previous height was size unallocated // if (Equals(oldWidth, sizenotallocated)) return; // // Has the device been rotated ? // if (!Equals(width, oldWidth)) // OnOrientationChanged.Invoke(this, new PageOrientationEventArgs(width < height ? PageOrientation.Vertical : PageOrientation.Horizontal)); // } // catch (Exception e) // { // Log.Logger.Error(e, nameof(OnSizeAllocated)); // } //} public PageOrientation ActualOrientation { get => Width < Height ? PageOrientation.Vertical : PageOrientation.Horizontal; } public BasePage() { this.Visual = new VisualMarker.MaterialVisual(); LockedOrientation = DeviceOrientation.Other; IsModalLocked = false; InitOrientationPage(); } public DeviceOrientation LockedOrientation { get; private set; } protected BasePage LockOrientation(DeviceOrientation Orientation) { LockedOrientation = Orientation; if (Device.RuntimePlatform == Device.Android) { MessagingCenter.Send(this, LockedOrientation.ToString()); } return this; } protected override void OnAppearing() { base.OnAppearing(); CrossOnAppearing(); if (HasAppeared) { return; } OnFirstAppearing(); HasAppeared = true; } public virtual void CrossOnAppearing() { } public virtual void OnSleep() { } private bool HasAppeared; protected virtual void OnFirstAppearing() { Log.Logger.Debug("OnFirstAppearing - {0}", this); } protected override void OnDisappearing() { base.OnDisappearing(); if (LockedOrientation != DeviceOrientation.Other) { if (Device.RuntimePlatform == Device.Android) { MessagingCenter.Send(this, nameof(DeviceOrientation.Other)); } else if (Device.RuntimePlatform == Device.iOS) { } } } protected bool IsModalLocked { get; private set; } public BasePage LockModal() { IsModalLocked = !IsModalLocked; return this; } protected override bool OnBackButtonPressed() { if (Rg.Plugins.Popup.Services.PopupNavigation.Instance.PopupStack.LastOrDefault() is BasePopUp popUp) { popUp.BackButtonPressed(); return true; } if (IsModalLocked) { return true; } bool close = base.OnBackButtonPressed(); if (!close) { OnClose(); ShowDialogCallback?.Set(); } return close; } public async void MenuPrincipal() { await Navigation.PopToRootAsync(true); } public void SetScreenMode(ScreenMode Screen) { Kit.Tools.Instance.ScreenManager.SetScreenMode(Screen); } public async Task<BasePage> WaitUntilClose() { if (ShowDialogCallback is null) { this.ShowDialogCallback = new AutoResetEvent(false); } await Task.Run(() => this.ShowDialogCallback.WaitOne()); return this; } #region INotifyPropertyChanged public new event PropertyChangedEventHandler PropertyChanged; //[Obsolete("Use Raise para mejor rendimiento evitando la reflección")] protected new void OnPropertyChanged([CallerMemberName] string propertyName = null) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } private void OnPropertyChanged(PropertyChangedEventArgs args) { PropertyChangedEventHandler handler = PropertyChanged; handler?.Invoke(this, args); } #endregion INotifyPropertyChanged #region PerfomanceHelpers protected void Raise<T>(Expression<Func<T>> propertyExpression) { if (this.PropertyChanged != null) { MemberExpression body = propertyExpression.Body as MemberExpression; if (body == null) throw new ArgumentException("'propertyExpression' should be a member expression"); ConstantExpression expression = body.Expression as ConstantExpression; if (expression == null) throw new ArgumentException("'propertyExpression' body should be a constant expression"); object target = Expression.Lambda(expression).Compile().DynamicInvoke(); PropertyChangedEventArgs e = new PropertyChangedEventArgs(body.Member.Name); PropertyChanged(target, e); } } protected void Raise<T>(params Expression<Func<T>>[] propertyExpressions) { foreach (Expression<Func<T>> propertyExpression in propertyExpressions) { Raise<T>(propertyExpression); } } #endregion PerfomanceHelpers } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public static class Scenes { public static int SimulationNumber { get; set; } public static Dictionary<char, string> Rules { get; set; } public static List<Atom> StartingSequence { get; set; } public static int Steps { get; set; } public static Dictionary<string, double> Parameters { get; set; } public static List<Production> Productions { get; set; } public static SerializableDictionary Dictionary { get; set; } public static int DrawingApproach { get; set; } public static float WidthDecreaseRate { get; set; } public static IEnumerator Load(string sceneName) { AsyncOperation async = SceneManager.LoadSceneAsync(sceneName); while (!async.isDone) { yield return null; } } public static IEnumerator LoadAdditive(string sceneName) { AsyncOperation async = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive); while (!async.isDone) { yield return null; } } public static IEnumerator LoadAdditiveGoThroughEachStep(string sceneName,double timeBetweenFrames) { int repeat = Scenes.Steps; for (int i = 1; i <= repeat; i++) { Scenes.Steps = i; AsyncOperation async = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive); while (!async.isDone) { yield return null; } if(i<repeat) GameObject.Find("Canvas/GoBackButton").SetActive(false); if (i>1) SceneManager.UnloadSceneAsync("main"); yield return new WaitForSeconds((float)timeBetweenFrames); } } }
using System; using NBTM.Repository.Models; using NBTM.Repository.Interfaces; namespace NBTM.Repository.Repositories { public class SampleLogRepository : GenericRepository<SampleLogEntry>, IDisposable { #region Constructor public SampleLogRepository(SalesApp1Entities context, LoggedInUserContext loggedInUser) : base(context, loggedInUser) { } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace XamarinAwesomeBannerSlider.Entities { public class Config { /// <summary> /// رنگ متن عنوان /// </summary> public Color? TitleColor { get; set; } /// <summary> /// رنگ متن توضیحات /// </summary> public Color? DescriptionColor { get; set; } /// <summary> /// فونت عنوان /// </summary> public Typeface TitleTypeFace { get; set; } /// <summary> /// فونت توضیحات /// </summary> public Typeface DescriptionTypeFace { get; set; } //public int TitleFontSize { get; set; } //public int DescriptionFontSize { get; set; } } }
using System.Collections; using System.Collections.Generic; using System.Xml.Serialization; using UnityEngine; using UnityEngine.SceneManagement; using UIFramework; using PUIType; using PEventCenter; public class LoadingManager : MonoSingleton<LoadingManager> { private float loadPercentage; private AsyncOperation async = null; public bool loadComplete = false; public float Percentage { get { return loadPercentage; } } /// <summary> /// 设置要跳转的场景名字 /// </summary> /// <param name="sceneName"></param> public void LoadScene(string sceneName) { loadComplete = false; StartCoroutine(Load(sceneName)); } IEnumerator Load(string sceneName) { UIManager.Instance.OpenWindow(WindowType.LoadingWindow); async = SceneManager.LoadSceneAsync(sceneName); async.allowSceneActivation = false; while (!async.isDone) { if (async.progress < 0.9f) { loadPercentage = async.progress; } else { loadPercentage = 1.0f; } EventCenter.Broadcast<float>(PEventCenter.PEventType.Loading, loadPercentage); if (loadPercentage >= 0.9f) { EventCenter.Broadcast(PEventCenter.PEventType.LoadComplete); loadComplete = true; yield return new WaitForSecondsRealtime(0.5f); async.allowSceneActivation = true; } yield return null; } } }
using System; using System.Diagnostics; using System.Threading.Tasks; using ProtoHub; public class ProtoHubImpl : ProtoHubService.ProtoHubServiceBase { public override async Task<UploadSpecResponse> UploadSpec(UploadSpecRequest request, Grpc.Core.ServerCallContext context) { Process cmd = new Process(); cmd.StartInfo.FileName = "prototool"; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.Arguments = "files ../Protos"; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.UseShellExecute = false; cmd.Start(); cmd.WaitForExit(); Console.WriteLine(cmd.StandardOutput.ReadToEnd()); return await Task.FromResult(new UploadSpecResponse { Status = new Status { Code = 1, Message = "Complete", }, }); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Infra; namespace console { public class _023_Merge2SortedLinkList { /// <summary> /// Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. /// </summary> /// <param name="l1">sorted list 1</param> /// <param name="l2">sorted list 2</param> /// <returns>new list</returns> public LinkListNode Merger(LinkListNode l1, LinkListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; LinkListNode head = new LinkListNode(); LinkListNode tmp; LinkListNode cur = head; while (l1 != null && l2 != null) { if (l1.Value < l2.Value) { tmp = l1; l1 = l1.Next; } else { tmp = l2; l2 = l2.Next; } cur.Next = tmp; cur = cur.Next; } if (l1 != null) { cur.Next = l1; } if (l2 != null) { cur.Next = l2; } return head.Next; } /// <summary> /// Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. /// </summary> /// <param name="input"></param> /// <returns></returns> public LinkListNode MergerKSortedList(List<LinkListNode> input) { LinkListNode head = new LinkListNode(); LinkListNode cur = head; int tmp = int.MaxValue; int index = 0; while (index > -1) { tmp = int.MaxValue; index = -1; for (int i = 0; i < input.Count; i++) { if (input[i] != null && input[i].Value < tmp) { index = i; tmp = input[i].Value; } } if (index != -1) { LinkListNode node = input[index]; input[index] = input[index].Next; cur.Next = node; cur = cur.Next; } } return head.Next; } } }
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; namespace Racing_Game_AssignS { public partial class Form1 : Form { //global variable int selectedRat = 0; int sahilBudget = 100, dashmeshBudget = 90, higorBudget = 110; int winnerRat = 0; // object of the local class to work Ground ground_instance = new Ground(); calculateBudget budget_instane = new calculateBudget(); public Form1() { InitializeComponent(); } private void label3_Click(object sender, EventArgs e) { } private void Sahil_CheckedChanged(object sender, EventArgs e) { if (Sahil.Checked==true) { Dashmesh.Checked = false; Higor.Checked = false; } } private void setBet_Click(object sender, EventArgs e) { //check the player is selected or not if (Sahil.Checked == false && Dashmesh.Checked == false && Higor.Checked == false) { MessageBox.Show("Must Select any Player "); } else { if (Sahil.Checked == true && selectedRat > 0) { //if we choose the player then we must verify the amount for the bet if (Convert.ToInt32(nmBet.Value)<51 && Convert.ToInt32(nmBet.Value) < sahilBudget) { //after filling the amount disolay the catalog to show which player choose how much amount lblSahil.Text = "Sahil choosed " + selectedRat + " and bet Amount " + nmBet.Value; Sahil.Checked = false; Rat1.Checked = false; Rat2.Checked = false; Rat3.Checked = false; Rat4.Checked = false; nmBet.Value = 1; StartRace.Enabled = true; } else { MessageBox.Show("Bet Amount must be less than the 50 or budget "); } } else if (Dashmesh.Checked == true && selectedRat > 0) { //if we choose the player then we must verify the amount for the bet if (Convert.ToInt32(nmBet.Value) < 51 && Convert.ToInt32(nmBet.Value) < dashmeshBudget) { //after filling the amount disolay the catalog to show which player choose how much amount lblDashmesh.Text = "Dashmesh choosed " + selectedRat + " and bet Amount " + nmBet.Value; Dashmesh.Checked = false; Rat1.Checked = false; Rat2.Checked = false; Rat3.Checked = false; Rat4.Checked = false; nmBet.Value = 1; StartRace.Enabled = true; } else { MessageBox.Show("Bet Amount must be less than the 50 or budget "); } } else if (Higor.Checked == true && selectedRat > 0) { //if we choose the player then we must verify the amount for the bet if (Convert.ToInt32(nmBet.Value) < 51 && Convert.ToInt32(nmBet.Value) < higorBudget) { //after filling the amount disolay the catalog to show which player choose how much amount lblHigor.Text = "Higor choosed " + selectedRat + " and bet Amount " + nmBet.Value; Higor.Checked = false; Rat1.Checked = false; Rat2.Checked = false; Rat3.Checked = false; Rat4.Checked = false; nmBet.Value = 1; StartRace.Enabled = true; } else { MessageBox.Show("Bet Amount must be less than the 50 or budget "); } } else { MessageBox.Show("Must select the rat for the race if you want to start the bet "); } } selectedRat = 0; } private void Rat1_CheckedChanged(object sender, EventArgs e) { //if we chose the first rat if (Rat1.Checked == true) { Rat2.Checked = false; Rat3.Checked = false; Rat4.Checked = false; selectedRat = 1; } } private void Rat2_CheckedChanged(object sender, EventArgs e) { //if we chose the second rat if (Rat2.Checked == true) { Rat1.Checked = false; Rat3.Checked = false; Rat4.Checked = false; selectedRat = 2; } } private void StartRace_Click(object sender, EventArgs e) { //after all setting start the timer to start the race to move the rats timer1.Enabled = true; timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { //move the rat from one position to another using jump method PB_Rat1.Left = PB_Rat1.Left+ ground_instance.jump(); Pbrat2.Left = Pbrat2.Left + ground_instance.jump(); PBrat3.Left = PBrat3.Left + ground_instance.jump(); PBrat4.Left = PBrat4.Left + ground_instance.jump(); //when anyone of the player reach at the finish point stop the game and declare the recult //anounce the winner rat and declare the budget if (PB_Rat1.Left > 690) { timer1.Enabled = false; timer1.Stop(); MessageBox.Show("Rat 1 win the Game "); winnerRat = 1; resultAnnounce(); StartRace.Enabled = false; } if (Pbrat2.Left > 690) { timer1.Enabled = false; timer1.Stop(); MessageBox.Show("Rat 2 win the Game "); winnerRat = 2; resultAnnounce(); StartRace.Enabled = false; } if (PBrat3.Left > 690) { timer1.Enabled = false; timer1.Stop(); MessageBox.Show("Rat 3 win the Game "); winnerRat = 3; resultAnnounce(); StartRace.Enabled = false; } if (PBrat4.Left > 690) { timer1.Enabled = false; timer1.Stop(); MessageBox.Show("Rat 4 win the Game "); winnerRat = 4; resultAnnounce(); StartRace.Enabled = false; } } public void resultAnnounce() { //if the player play the game then find he is the winner or loser of the game if (lblSahil.Text.Contains("Sahil")) { String[] sahilData = lblSahil.Text.Split(' '); sahilBudget = budget_instane.BudgetCal(Convert.ToInt32(sahilData[2]), Convert.ToInt32(sahilData[6]),sahilBudget,winnerRat); Sahil.Text = "Sahil has "+sahilBudget+" Dollar"; lblSahil.Text = "PRINT MESSAGE HERE ANY"; } if (lblDashmesh.Text.Contains("Dashmesh")) { String[] DashmeshData = lblDashmesh.Text.Split(' '); dashmeshBudget = budget_instane.BudgetCal(Convert.ToInt32(DashmeshData[2]), Convert.ToInt32(DashmeshData[6]), dashmeshBudget, winnerRat); Dashmesh.Text = "Dashmesh has " + dashmeshBudget + " Dollar"; lblDashmesh.Text = "PRINT MESSAGE HERE ANY "; } if (lblHigor.Text.Contains("Higor")) { String[] HigorData = lblHigor.Text.Split(' '); higorBudget = budget_instane.BudgetCal(Convert.ToInt32(HigorData[2]), Convert.ToInt32(HigorData[6]), higorBudget, winnerRat); Higor.Text = "Higor has " + dashmeshBudget + " Dollar"; lblHigor.Text = "PRINT MESSAGE HERE ANY "; } PB_Rat1.Left = 0; Pbrat2.Left = 0; PBrat3.Left = 0; PBrat4.Left = 0; } private void Dashmesh_CheckedChanged(object sender, EventArgs e) { if (Dashmesh.Checked == true) { Sahil.Checked = false; Higor.Checked = false; } } private void Higor_CheckedChanged(object sender, EventArgs e) { if (Higor.Checked == true) { Sahil.Checked = false; Dashmesh.Checked = false; } } private void Rat3_CheckedChanged(object sender, EventArgs e) { //if we chose the third rat if (Rat3.Checked == true) { Rat2.Checked = false; Rat1.Checked = false; Rat4.Checked = false; selectedRat = 3; } } private void Rat4_CheckedChanged(object sender, EventArgs e) { //if we chose the forth rat if (Rat4.Checked == true) { Rat2.Checked = false; Rat3.Checked = false; Rat1.Checked = false; selectedRat = 4; } } } }
using System; using System.Text; using System.Net.Sockets; using System.Collections; using System.Collections.Generic; using UnityEngine; public class test : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { string str = String.Format("{0,4}", 13); Debug.Log(Encoding.UTF8.GetBytes(str)); } }
#region Copyright, Author Details and Related Context //<notice lastUpdateOn="12/20/2015"> // <solution>KozasAnt</solution> // <assembly>KozasAnt.Smarts</assembly> // <description>A modern take on Koza's connonical "Ant Foraging for Food on a Grid" problem that leverages Roslyn</description> // <copyright> // Copyright (C) 2015 Louis S. Berman // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> // <author> // <fullName>Louis S. Berman</fullName> // <email>louis@squideyes.com</email> // <website>http://squideyes.com</website> // </author> //</notice> #endregion using KozasAnt.Engine; using KozasAnt.Generic; namespace KozasAnt.Smarts { public class Settings : SettingsBase { public Settings(Trail trail) { Contract.Requires(trail != null, nameof(trail)); Contract.Requires(trail.Count > 0, "trail.Count"); FoodGoal = 0; MaxSteps = 0; foreach (var cell in trail) { switch (cell.Kind) { case CellKind.Food: FoodGoal++; MaxSteps++; break; case CellKind.Gap: MaxSteps++; break; } } Grid = Grid.Load(trail); } public Trail Trail { get; } public Grid Grid { get; } public int FoodGoal { get; } protected override void DoValidate() { } } }
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; namespace DX_QLVT_DATHANG { public partial class formNhanVien : Form { int vitri = 0; string maCN = ""; public formNhanVien() { InitializeComponent(); } private void formNhanVien_Load(object sender, EventArgs e) { DS.EnforceConstraints = false; this.nhanVienTableAdapter.Connection.ConnectionString = Program.connstr; // doi phan manh moi // TODO: This line of code loads data into the 'dS.NhanVien' table. You can move, or remove it, as needed. this.nhanVienTableAdapter.Fill(this.DS.NhanVien); this.datHangTableAdapter.Connection.ConnectionString = Program.connstr; this.datHangTableAdapter.Fill(this.DS.DatHang); this.phieuNhapTableAdapter.Connection.ConnectionString = Program.connstr; this.phieuNhapTableAdapter.Fill(this.DS.PhieuNhap); this.bdsPX.Connection.ConnectionString = Program.connstr; this.bdsPX.Fill(this.DS.PhieuXuat); maCN = ((DataRowView)bdsNV[0])["MACN"].ToString(); cmbChiNhanh.DataSource = Program.bds_dspm; cmbChiNhanh.DisplayMember = "TENCN"; cmbChiNhanh.ValueMember = "TENSERVER"; cmbChiNhanh.SelectedIndex = Program.mChinhanh; if (Program.mGroup == "CongTy") cmbChiNhanh.Enabled = true; else cmbChiNhanh.Enabled = false; //if (bdsNV.Count = 0) btnXoa.Enabled = false; groupControl1.Enabled = false; } private void nhanVienBindingNavigatorSaveItem_Click(object sender, EventArgs e) { this.Validate(); this.bdsNV.EndEdit(); this.tableAdapterManager.UpdateAll(this.DS); } private void nhanVienDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void cmbChiNhanh_SelectedIndexChanged(object sender, EventArgs e) { if (cmbChiNhanh.SelectedValue.ToString() != "System.Data.DataRowView") { Program.servername = cmbChiNhanh.SelectedValue.ToString(); } if (cmbChiNhanh.SelectedIndex != Program.mChinhanh) { Program.mlogin = Program.remotelogin; Program.password = Program.remotepassword; } else { Program.mlogin = Program.mloginDN; Program.password = Program.passwordDN; } if (Program.KetNoi() == 0) { MessageBox.Show("Loi ket noi chi nhanh moi", "", MessageBoxButtons.OK); } else { DS.EnforceConstraints = false; this.nhanVienTableAdapter.Connection.ConnectionString = Program.connstr; // doi phan manh moi // TODO: This line of code loads data into the 'dS.NhanVien' table. You can move, or remove it, as needed. this.nhanVienTableAdapter.Fill(this.DS.NhanVien); this.datHangTableAdapter.Connection.ConnectionString = Program.connstr; this.datHangTableAdapter.Fill(this.DS.DatHang); this.phieuNhapTableAdapter.Connection.ConnectionString = Program.connstr; this.phieuNhapTableAdapter.Fill(this.DS.PhieuNhap); this.bdsPX.Connection.ConnectionString = Program.connstr; this.bdsPX.Fill(this.DS.PhieuXuat); maCN = ((DataRowView)bdsNV[0])["MACN"].ToString(); } } private void groupControl1_Paint(object sender, PaintEventArgs e) { } private void btnThem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { vitri = bdsNV.Position;//so thu tu cua mau tin do trong ds groupControl1.Enabled = true; bdsNV.AddNew(); txtmaCN.Text = maCN; btnThem.Enabled = btnSua.Enabled = btnXoa.Enabled = btnReload.Enabled = false; btnGhi.Enabled = btnUndo.Enabled = true; txtmaCN.Enabled = false; gcNhanVien.Enabled = false; } private void btnSua_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { try { bdsNV.EndEdit(); //dong bo du lieu giua 2 khu vuc bdsNV.ResetCurrentItem(); this.nhanVienTableAdapter.Update(this.DS.NhanVien); } catch(Exception ex){ MessageBox.Show("Lỗi ghi nhân viên" + ex.Message, "", MessageBoxButtons.OK); } } private void btnUndo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { bdsNV.CancelEdit(); } private void btnReload_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { this.nhanVienTableAdapter.Fill(this.DS.NhanVien); } private void btnThoat_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { // bo sung khi dang sua thi close Close(); } private void btnXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { Int32 maNV = 0; if (bdsPN.Count > 0) { MessageBox.Show("Nhân viên đã lập phiếu nhập, không thể xóa"); return; } if (bdsDH.Count > 0) { MessageBox.Show("Nhân viên đã lập phiếu đặt, không thể xóa"); return; } if (bdsPN.Count > 0) { MessageBox.Show("Nhân viên đã lập phiếu xuất, không thể xóa"); return; } if (MessageBox.Show("Bạn có thật sự muốn xóa nhân viên này? ","Xác nhận", MessageBoxButtons.YesNoCancel) == DialogResult.Yes) { } } private void btnIn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { } private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { } private void btnGhi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { if (txtMaNV.Text.Trim() == "") { MessageBox.Show("Mã Nhân viên không được để trống!"); txtMaNV.Focus(); return; } if (txtHo.Text.Trim() == "") { MessageBox.Show("Họ Nhân viên không được để trống!"); txtHo.Focus(); } if (txtTen.Text.Trim() == "") { MessageBox.Show("Tên Nhân viên không được để trống!"); txtTen.Focus(); } if (txtDiaChi.Text.Trim() == "") { MessageBox.Show("Địa chỉ Nhân viên không được để trống!"); txtDiaChi.Focus(); } if (txtLuong.Text.Trim() == "") { txtLuong.Text= "0"; } if (Convert.ToInt32(txtLuong.Text) <= 0) { MessageBox.Show(""); txtLuong.Focus(); } if (Convert.ToInt32(txtLuong.Text) < 4000000) { MessageBox.Show("Lương phải lớn hơn hoặc bàng 4000000"); txtLuong.Focus(); } if (bdsNV.Find("MANV",txtMaNV.Text)>0) { MessageBox.Show("Mã Nhân viên bị trùng"); //txtLuong.Focus(); } try { bdsNV.EndEdit(); bdsNV.ResetCurrentItem(); this.nhanVienTableAdapter.Connection.ConnectionString = Program.connstr; this.nhanVienTableAdapter.Update(this.DS.NhanVien); } catch (Exception ex) { if(ex.Message.Contains("PRIMARY")){ MessageBox.Show("Mã nhân viên bị trùng"); txtMaNV.Focus(); } //bdsNV.Find("maNV",) else { bdsNV.EndEdit(); bdsNV.ResetCurrentItem(); MessageBox.Show("Lỗi ghi nhân viên" + ex.Message, "", MessageBoxButtons.OK); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LockedHack : MonoBehaviour { public GameObject locked; public string thing; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void OnTriggerEnter2D(Collider2D other) { thing = other.tag; if (other.tag == "Player") { locked.SetActive(false); } } public void OnTriggerStay2D(Collider2D other) { thing = other.tag; if (other.tag == "Player") { locked.SetActive(false); } } public void OnTriggerExit2D(Collider2D other) { thing = other.tag; if (other.tag == "Player") { locked.SetActive(true); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using FluentValidation.Results; using MeterReading.Logic; using MeterReading.Logic.Facades; using MeterReading.Logic.Validators; using MeterReadings.Repository; using MeterReadings.Schema; using Moq; using NUnit.Framework; namespace MeterReadings.Tests { [TestFixture] public class MeterReadingFacadeTests { private MeterReadingFacade _sut; private IMeterReadingsRepository _mockRepository; private IMeterReadingLenientValidator _mockValidator; private ICsvHelper _csvHelper; private readonly MeterReadingLenient _meterReading = new MeterReadingLenient() { AccountId = "2344", MeterReadingDateTime = "22/04/2019 09:24", MeterReadValue = "01002" }; private readonly Collection<HttpContent> _httpContents = new Collection<HttpContent>() { new StringContent(@"AccountId,MeterReadingDateTime,MeterReadValue 2344,22/04/2019 09:24,01002") }; [SetUp] public void Setup() { _mockRepository = Mock.Of<IMeterReadingsRepository>(MockBehavior.Strict); _mockValidator = Mock.Of<IMeterReadingLenientValidator>(MockBehavior.Strict); _csvHelper = Mock.Of<ICsvHelper>(MockBehavior.Strict); _sut = new MeterReadingFacade( _mockRepository, _mockValidator, _csvHelper); Mock.Get(_csvHelper).Setup(x => x.ReadCsvFromRequestIntoCollectionOfType<MeterReadingLenient>(_httpContents)) .ReturnsAsync(new List<MeterReadingLenient>() { _meterReading }); } [Test] public async Task AddMeterReadings_ReturnsValidationFailures_WhenValidatorProducesValidationErrors() { // Arrange var validationResult = new ValidationResult(); validationResult.Errors.Add(new ValidationFailure(nameof(MeterReadingLenient.AccountId), "Test error")); Mock.Get(_mockValidator).Setup(x => x.Validate(_meterReading)) .Returns(() => { return validationResult; }); Mock.Get(_mockRepository).Setup(x => x.AddReadings(It.IsAny<List<Schema.MeterReading>>())) .ReturnsAsync(() => new List<Schema.MeterReading>(0)); // Act var result = await _sut.AddMeterReadings(_httpContents); // Assert result.Should().NotBeNull(); result.Errors.Should().Contain("AccountId: 2344, MeterReadingDateTime: 22/04/2019 09:24, MeterReadValue: 01002 - Test error"); result.SuccessfulCount.Should().Be(0); result.FailedCount.Should().Be(1); } [Test] public async Task AddMeterReadings_ReturnsCorrectSuccessCount_WhenNoValidationAndInsertionIssuesOccur() { // Arrange Mock.Get(_mockValidator).Setup(x => x.Validate(_meterReading)) .Returns(() => new ValidationResult()); Mock.Get(_mockRepository).Setup(x => x.AddReadings(It.IsAny<List<Schema.MeterReading>>())) .ReturnsAsync(() => new List<Schema.MeterReading>(new List<Schema.MeterReading>(1) { _meterReading.ToMeterReading() })); // Act var result = await _sut.AddMeterReadings(_httpContents); // Assert result.Should().NotBeNull(); result.Errors.Count().Should().Be(0); result.SuccessfulCount.Should().Be(1); result.FailedCount.Should().Be(0); } [Test] public async Task AddMeterReadings_ReturnsError_WhenRepositoryIndicatesFailureToAdd() { // Arrange Mock.Get(_mockValidator).Setup(x => x.Validate(_meterReading)) .Returns(() => new ValidationResult()); Mock.Get(_mockRepository).Setup(x => x.AddReadings(It.IsAny<List<Schema.MeterReading>>())) .ReturnsAsync(() => new List<Schema.MeterReading>(new List<Schema.MeterReading>(0))); // Act var result = await _sut.AddMeterReadings(_httpContents); // Assert result.Should().NotBeNull(); result.Errors.Should().Contain("AccountId: 2344, MeterReadingDateTime: 22/04/2019 09:24:00, MeterReadValue: 01002 - AccountId doesn't exist or reading has already been added"); result.SuccessfulCount.Should().Be(0); result.FailedCount.Should().Be(1); } [Test] public async Task AddMeterReading_ReturnsCorrectSuccessCount_WhenNoValidationAndInsertionIssuesOccur() { // Arrange Mock.Get(_mockValidator).Setup(x => x.Validate(_meterReading)) .Returns(() => new ValidationResult()); var reading = _meterReading.ToMeterReading(); Mock.Get(_mockRepository).Setup(x => x.AddReadings(It.IsAny<Schema.MeterReading[]>())) .ReturnsAsync(() => new List<Schema.MeterReading>(new List<Schema.MeterReading>(1) { reading })); // Act var result = await _sut.AddMeterReading(reading); // Assert result.Should().NotBeNull(); } [Test] public async Task GetReadings_ReturnsReadings() { // Arrange var reading = _meterReading.ToMeterReading(); Mock.Get(_mockRepository).Setup(x => x.GetReadings()) .ReturnsAsync(() => new List<Schema.MeterReading>() { reading }); //Act var result = await _sut.GetReadings(); //Assert result.Should().Contain(reading); } [Test] public async Task DeleteReading_DeletesReading() { var readingId = Guid.NewGuid(); // Arrange Mock.Get(_mockRepository).Setup(x => x.DeleteReading(readingId)) .Returns(Task.CompletedTask) .Verifiable(); //Act await _sut.DeleteReading(readingId); //Assert Mock.Get(_mockRepository).Verify(); } [Test] public async Task GetReading_ReturnsReading() { // Arrange var readingId = Guid.NewGuid(); var reading = _meterReading.ToMeterReading(); reading.Id = readingId; Mock.Get(_mockRepository).Setup(x => x.GetReading(readingId)) .ReturnsAsync(() => reading) .Verifiable(); //Act var result = await _sut.GetReading(readingId); //Assert Mock.Get(_mockRepository).Verify(); result.Should().Be(reading); } } }
using Assets.Scripts.Overlay.Action_PopUps.TokenSelector; using Assets.Scripts.RobinsonCrusoe_Game.Characters; using Assets.Scripts.RobinsonCrusoe_Game.GameAttributes; using System.Collections; using System.Collections.Generic; using UnityEngine; public class CleanAction_Processing : MonoBehaviour { public void ProcessCleanAction(ActionContainer action) { var character = action.GetExecutingCharacter(); CharacterActions.RaiseCharacterDeterminationBy(2, character); Moral.RaiseMoral(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CareerCup150.Chapter19_Medium { public class _19_08_FrequentOfAWord { /* * Design a method to find the frequency of occurrences of any given word in a book. */ public Dictionary<string, int> FindFrequency(string[] book) { Dictionary<string, int> tracker = new Dictionary<string, int>(); foreach (string str in book) { if (tracker.ContainsKey(str)) { tracker[str]++; } else { tracker.Add(str, 1); } } return tracker; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.Shapes; using MonoGame.Extended.Sprites; using MonoGame.Extended.TextureAtlases; namespace Demo.SpaceGame.Entities { public class Meteor : Entity { private const float _radius = 55f / 4f; private readonly Sprite _sprite; public CircleF BoundingCircle; public int HealthPoints { get; private set; } public Vector2 Position { get { return _sprite.Position; } set { _sprite.Position = value; BoundingCircle.Center = _sprite.Position; } } public float Rotation { get { return _sprite.Rotation; } set { _sprite.Rotation = value; } } public float RotationSpeed { get; } public int Size { get; private set; } public Vector2 Velocity { get; set; } public Meteor(TextureRegion2D textureRegion, Vector2 position, Vector2 velocity, float rotationSpeed, int size) { _sprite = new Sprite(textureRegion); BoundingCircle = new CircleF(_sprite.Position, _radius * size); Position = position; Velocity = velocity; RotationSpeed = rotationSpeed; HealthPoints = 1; Size = size; } public void Damage(int damage) { HealthPoints -= damage; if (HealthPoints <= 0) { Destroy(); } } public override void Update(GameTime gameTime) { var deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds; Position += Velocity * deltaTime; Rotation += RotationSpeed * deltaTime; } public override void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(_sprite); } public bool Contains(Vector2 position) { return BoundingCircle.Contains(position); } } }
/* .-' '--./ / _.---. '-, (__..-` \ \ . | `,.__. ,__.--/ '._/_.'___.-` FREE WILLY */ using Renci.SshNet; namespace Automatisation.Model { public class SSH : BaseModel { #region fields private int _id; private string _description; private string _host; private string _user; private string _password; private int _port = 22; private SshClient _clientSSH; #endregion fields #region properties public int ID { get { return _id; } set { if (value != _id) { _id = value; OnPropertyChanged("ID"); } } } public string Description { get { return _description; } set { if (value != _description) { _description = value; OnPropertyChanged("Description"); } } } public string HostName { get { return _host; } set { if (value != _host) { _host = value; OnPropertyChanged("HostName"); } } } public string UserName { get { return _user; } set { if (value != _user) { _user = value; OnPropertyChanged("UserName"); } } } public string Password { get { return _password; } set { if (value != _password) { _password = value; OnPropertyChanged("Password"); } } } public int Port { get { return _port; } set { if (value != _port) { _port = value; OnPropertyChanged("Port"); } } } public SshClient ClientSSH { get { return _clientSSH; } set { if (value != _clientSSH) { _clientSSH = value; OnPropertyChanged("ClientSSH"); } } } #endregion properties #region constructor public SSH() { } public SSH(string host) { this.HostName = host; } public SSH(string host, string user, string pass, int port = 22) { this.HostName = host; this.UserName = user; this.Password = pass; this.Port = port; } #endregion constructor } }
using UnityEngine; using System.Collections; public class RespawnEnemy : MonoBehaviour { public GameObject RangeGoblin; public GameObject Demon; public GameObject Cyclop; bool RespawnOn; bool StartGame; bool GroupRespawnOn; bool FirstRespawn; public static float RespTimeRGoblin = 10f; public static float RespTimeDemon = 10f; public static float RespTimeCyclop = 40f; float TempRespTimeRGoblin; float TempRespTimeDemon; float TempRespTimeCyclop; // Периодичность респавна мобов. Vector3 RandomRespawnPosition; void Start () { RespawnOn = false; StartGame = false; GroupRespawnOn = false; FirstRespawn = false; TempRespTimeCyclop = RespTimeCyclop; TempRespTimeDemon = RespTimeDemon; TempRespTimeRGoblin = RespTimeRGoblin; } // Update is called once per frame void Update () { if (LevelScript.StartGame == true && GroupRespawnOn == false) { StartCoroutine (GroupSpawn ()); } RespawnTimer(); } void RespawnTimer() { if (FirstRespawn == false) { TempRespTimeCyclop = 20; TempRespTimeDemon = 10; TempRespTimeRGoblin = 10; } if (RespawnOn == true) { if (FirstRespawn == true) { TempRespTimeCyclop -= Time.deltaTime; TempRespTimeDemon -= Time.deltaTime; TempRespTimeRGoblin -= Time.deltaTime; } RandomRespawnPosition = new Vector3(Random.Range(-1f, 1f), transform.position.y, Random.Range(-1f, 1f)); if (TempRespTimeCyclop < 0f) { GameObject EnemyCyclop = Instantiate(Cyclop, transform.position + RandomRespawnPosition, Quaternion.identity) as GameObject; TempRespTimeCyclop = RespTimeCyclop; } if (TempRespTimeDemon < 0f) { GameObject EnemyDemon = Instantiate(Demon, transform.position + RandomRespawnPosition, Quaternion.identity) as GameObject; TempRespTimeDemon = RespTimeDemon; } if (TempRespTimeRGoblin < 0f) { GameObject EnemyDemon = Instantiate(RangeGoblin, transform.position + RandomRespawnPosition, Quaternion.identity) as GameObject; TempRespTimeRGoblin = RespTimeRGoblin; } FirstRespawn = true; } } // Таймер респавна врагов. // После запуска игры ждем 30 сек , прежде чем мобы начнут респавниться. IEnumerator GroupSpawn() { GroupRespawnOn = true; RespawnOn = true; yield return new WaitForSeconds (LevelScript.WaveTime); RespawnOn = false; GroupRespawnOn = false; } // Респавн мобов в течении времени волны. }
using System.Collections.Generic; using UnityEngine.EventSystems; using UnityEngine.UI; namespace HT.Framework { /// <summary> /// 可绑定的Selectable类型 /// </summary> public sealed class BindableSelectable : BindableType<int> { public static implicit operator int(BindableSelectable bSelectable) { return bSelectable.Value; } public static implicit operator string(BindableSelectable bSelectable) { return bSelectable.ValueString; } /// <summary> /// 数据值 /// </summary> public override int Value { get { return base.Value; } set { int newValue = value; if (newValue < 0) newValue = 0; else if (newValue >= _values.Count) newValue = _values.Count - 1; if (_value == newValue) return; _value = newValue; _onValueChanged?.Invoke(_value); } } /// <summary> /// 数据值(字符串) /// </summary> public string ValueString { get { return (Value >= 0 && Value < _values.Count) ? _values[Value] : null; } } private List<string> _values = new List<string>(); public BindableSelectable() { Value = 0; } public BindableSelectable(string[] values, int value = 0) { for (int i = 0; i < values.Length; i++) { _values.Add(values[i]); } Value = value; } public BindableSelectable(List<string> values, int value = 0) { for (int i = 0; i < values.Count; i++) { _values.Add(values[i]); } Value = value; } /// <summary> /// 绑定控件 /// </summary> /// <param name="control">绑定的目标控件</param> protected override void Binding(UIBehaviour control) { base.Binding(control); if (control is Dropdown) { Dropdown dropdown = control as Dropdown; if (dropdown.options == null) { dropdown.options = new List<Dropdown.OptionData>(); } for (int i = 0; i < _values.Count; i++) { dropdown.options.Add(new Dropdown.OptionData(_values[i])); } dropdown.value = Value; dropdown.onValueChanged.AddListener((value) => { Value = value; }); _onValueChanged += (value) => { if (dropdown) dropdown.value = value; }; } else { Log.Warning(string.Format("数据驱动器:数据绑定失败,当前不支持控件 {0} 与 BindableSelectable 类型的数据绑定!", control.GetType().FullName)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace SolarSystem { class SpaceObject { private float posX; public float x { get { return posX; } } private float posY; public float y { get { return posY; } } private float vX; public float vx { get { return vX; } set { vX = value; } } private float vY; public float vy { get { return vY; } set { vY = value; } } private float m; public float M { get { return m; } } private float rad; private objColors myColor; public void Move() { posX += vx; posY += vy; } public SpaceObject(float posX, float posY, float vX, float vY, float m, float rad, objColors myColor) { this.posX = posX; this.posY = posY; this.vX = vX; this.vY = vY; this.m = m; this.rad = rad; this.myColor = myColor; } public void Draw(Graphics ge) { Pen specPen = Pens.Black; SolidBrush myBrush = new SolidBrush(Color.Black); switch (myColor) { case objColors.blue: myBrush.Color = Color.Blue; break; case objColors.green: myBrush.Color = Color.Green; break; case objColors.purple: myBrush.Color = Color.Purple; break; case objColors.red: myBrush.Color = Color.Red; break; case objColors.yellow: myBrush.Color = Color.Yellow; break; default: myBrush = new SolidBrush(Color.White); break; } ge.FillEllipse(myBrush, posX - rad / 2, posY - rad / 2, rad, rad); ge.DrawEllipse(specPen, posX - rad / 2, posY - rad / 2, rad, rad); } } public enum objColors { red,green,blue,purple,yellow, } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyBody : MonoBehaviour { public Transform rayEmitter; public BoxCollider hitBox; public PlayerDetector playerDetector; public AIManager aiManager; private void Start() { MyEventSystem.instance.activateAI += StartAI; MyEventSystem.instance.OnEnemyStart(this); aiManager = ScriptCollection.GetScript<AIManager>(); } private void OnDisable() { MyEventSystem.instance.activateAI -= StartAI; } public void StartAI() { GetComponent<BehaviorExecutor>().paused = false; } }
using System; namespace OCP.Authentication.TwoFactorAuth { /** * Marks a 2FA provider as activale by the administrator. This means that an * admin can activate this provider without user interaction. The provider, * therefore, must not require any user-provided configuration. * * @since 15.0.0 */ interface IDeactivatableByAdmin : IProvider { /** * Disable this provider for the given user. * * @param IUser user the user to deactivate this provider for * * @return void * * @since 15.0.0 */ void disableFor(IUser user); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using eIDEAS.Data; namespace eIDEAS.Models { public class UnitDivision { public Unit unit { get; set; } public Division division { get; set; } private readonly ApplicationDbContext _context; public UnitDivision() { } public UnitDivision(ApplicationDbContext context) { _context = context; } // Return all divisions or the division specified public List<Division> GetDivisions(int? id) { if (id == null) return _context.Division.Where(division => division.DateDeleted == null).ToList(); return _context.Division.Where(division => division.ID == id).ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PayRoll.BLL { public abstract class ChangeAffiliationTransaction:ChangeEmployeeTransaction { public ChangeAffiliationTransaction(int empId, PayrollDatabase database) : base(empId, database) { } protected abstract Affiliation Affiliation { get; } protected abstract void RecordMembership(Employee emp); protected override void Change(Employee emp) { RecordMembership(emp); emp.Affiliation = Affiliation; } } }