text stringlengths 13 6.01M |
|---|
//using System;
//namespace Uintra.Infrastructure.Context
//{
// [Flags]
// public enum ContextType
// {
// Empty = 0,
// News = 1,
// Events = 2,
// Social = 4,
// Activity = News | Events | Social,
// Comment = 16,
// CentralFeed = 32,
// GroupFeed = 64,
// Feed = CentralFeed | GroupFeed,
// ContentPage = 256,
// Any = int.MaxValue
// }
//} |
using INOTE.Core.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace INOTE.Core.Repository
{
public interface INoteRepository : IRepository<Note>
{
IEnumerable<Note> GetUserNotes(User user, string searchText, int pageNumber, int pageOffset);
int GetNotesCount(User user, string searchText, int pageOffset);
}
}
|
using System;
using System.IO;
using System.Threading.Tasks;
namespace ApodPcl
{
/// <summary>
/// This class handles communicating with NASA's API to retreive details
/// about the current Astronomy Picture of the Day.
/// </summary>
public sealed class API
{
/// <summary>
/// Initializes an instance of <see cref="API"/>.
/// <para>
/// <see cref="API_key"/> is set to <paramref name="key"/>
/// and <see cref="Date"/> is set to <see cref="DateTime.Today"/>.
/// </para>
/// </summary>
/// <param name="key">The api key to use when communicating with
/// NASA's API.</param>
public API(string key)
{
date = DateTime.Today;
api_key = key;
}
/// <summary>
/// Initializes an instance of <see cref="API"/>.
/// <para>
/// <see cref="API_key"/> is set to <paramref name="key"/>
/// and <see cref="Date"/> is set to <paramref name="date"/>.
/// </para>
/// </summary>
/// <param name="key">The api key to use when communicating with
/// NASA's API.</param>
/// <param name="date">The date to request the Astronomy Picture of the Day for.
/// <see cref="Date"/> is set to this value.</param>
public API(DateTime date, string key)
{
Date = date;
api_key = key;
}
/// <summary>
/// Sends a request to NASA's API for the day <see cref="Date"/>
/// and using the api key <see cref="API_key"/>.
/// <para>
/// The response is used to populate the fields of <see cref="Apod"/>.
/// </para>
/// </summary>
/// <remarks>
/// When an <see cref="System.Net.Http.HttpRequestException"/> occurs, "Error" is specifed in
/// Apod.title and the <see cref="Exception.Message"/> in Apod.explanation. All other fields are null.
/// </remarks>
public async Task sendRequest()
{
generateURL();
try
{
Stream responseStream = await Util.GetHttpResponseStream(new Uri(api_url));
myAPOD = Util.JsonToApod(responseStream);
}
catch (System.Net.Http.HttpRequestException ex)
{
myAPOD = Util.Exception2Apod(ex);
}
}
/// <summary>
/// Get the Uri to the media.
/// </summary>
/// <param name="hd">If true and media is an image, the HD uri is returned. Default is false</param>
/// <returns>A Uri pointing to the requested media.</returns>
public async Task<Uri> GetUri(bool hd = false)
{
await sendRequest();
return (hd && !(myAPOD.media_type == "video")) ? myAPOD.hdurl : myAPOD.url;
}
/// <summary>
/// Get the Uri to the media for the specified date.
/// </summary>
/// <param name="date">The value to set <see cref="Date"/> to before sending the request.</param>
/// <param name="hd">If true and media is an image, the HD uri is returned. Default is false</param>
/// <returns>A Uri pointing to the requested media.</returns>
public async Task<Uri> GetUri(DateTime date, bool hd = false)
{
Date = date;
return await GetUri(hd);
}
/// <summary>
/// Get the Uri to the media for for the date previous to the current value of <see cref="date"/>.
/// </summary>
/// <param name="hd">If true and media is an image, the HD uri is returned. Default is false</param>
/// <returns>A Uri pointing to the requested media.</returns>
public async Task<Uri> GetPrevUri(bool hd = false)
{
return await GetUri(date.AddDays(-1), hd);
}
/// <summary>
/// Get the Uri to the media for for the date proceeding the current value of <see cref="date"/>.
/// </summary>
/// <param name="hd">If true and media is an image, the HD uri is returned. Default is false</param>
/// <returns>A Uri pointing to the requested media.</returns>
public async Task<Uri> GetNextUri(bool hd = false)
{
return await GetUri(date.AddDays(1), hd);
}
/// <summary>
/// Forms the url to use for for requests to NASA's API.
/// </summary>
private void generateURL()
{
string api = "https://api.nasa.gov/planetary/apod";
api_url = api + "?api_key=" + api_key + "&date=" + date.ToString("yyyy-MM-dd");
}
/// <summary>
/// The date to request the Astronomy Picture of the Day for.
/// <para>Valid dates are between 1995-06-16 and today.</para>
/// </summary>
/// <value>Sets the value of the field, <see cref="date"/>, and ensures it is valid.</value>
public DateTime Date
{
set
{
DateTime min = new DateTime(1995, 06, 16);
date = (value > DateTime.Today) ? DateTime.Today : ((value < min) ? min : value);
}
}
/// <summary>
/// The api key to supply to NASA's API when sending requests.
/// <para>Obtain a key from http://api.nasa.gov. </para>
/// </summary>
/// <value>Sets the value of the private field, api_key.</value>
public string API_key { set { api_key = value; } }
private string api_key;
private string api_url;
private DateTime date;
private APOD myAPOD;
/// <summary>
/// Get the returned Astrononmy Picture of the Day as an <see cref="APOD"/> object.
/// </summary>
public APOD Apod { get { return myAPOD; } }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using static FlowEvent;
public class FlowManager : MonoBehaviour {
public GameObject obj;
public GameObject currentFlow;
public GameObject previousFlow;
[ReadOnly]
public GameObject[] allFlow;
void Start () {
allFlow =
GetComponentsInChildren<FlowEvent> ()
.Select (x =>
x.gameObject).ToArray ();
UpdateCurrentFlow ();
UpdatePreviousFlow ();
UpdateObjectsActive ();
}
void Update () {
UpdateObjectsActive ();
if (currentFlow == default (GameObject)) {
Debug.LogError ("流程系统中的名字无法与当前流程形成对应,可能是没有正确取名", gameObject);
Debug.Break ();
}
}
private void OnValidate () {
}
public void UpdateCurrentFlow () {
currentFlow = Array.Find (allFlow, x => GetComponent<Animator> ()
.GetCurrentAnimatorStateInfo (0)
.IsName (x.name));
}
public void UpdateCurrentFlow (AnimatorStateInfo stateInfo) {
currentFlow = Array.Find (allFlow, x =>
stateInfo.IsName (x.name));
}
public void UpdatePreviousFlow () {
previousFlow = currentFlow;
}
private void UpdateObjectsActive () {
if (EditorApplication.isPlaying) {
allFlow.ToList ()
.ForEach (x => {
x.SetActive (false);
});
currentFlow?.SetActive (true);
}
}
public void CallEvent (GameObject obj, FlowEventType et) {
var getAllActiveEvents =
obj.GetComponents<FlowEvent> ().ToList ()
.FindAll (e =>
e.enabled);
getAllActiveEvents.ForEach (e => {
bool testResult = true;
if (e.enableEnterTest &
!e.allowEnterFlow.ToList ()
.Exists (x =>
x == previousFlow
)
) {
testResult = false;
}
if (testResult) {
if (et == FlowEventType.OnEnter)
e.onEnter.Invoke ();
else if (et == FlowEventType.OnExit)
e.onExit.Invoke ();
};
});
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using VRTK;
public class LevelManager : MonoBehaviour
{
public static LevelManager Instance { get; private set; }
private void Awake()
{
Instance = this;
}
public void MainMenu ()
{
SceneManager.LoadScene("2_MainMenu");
}
}
|
using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using System.Net.Mail;
using System.Net;
namespace Thuisbegymmen.Controllers
{
[Route("api/[controller]")]
public class AccountController : Controller
{
private readonly Context _context;
byte[] saltBytes = new byte[128/8];
string salt;
public AccountController(Context context)
{
_context = context;
}
[HttpGet("login")]
public IActionResult Login(string _gebruikersnaam, string _wachtwoord)
{
Account _account = _context.Account.FirstOrDefault(a => a.Gebruikersnaam == _gebruikersnaam);
if(_account == null)
{
return NoContent();
}
if(ValidateHash(_wachtwoord, _account.Salt, _account.Wachtwoord))
{
_account.Wachtwoord = null;
HttpContext.Session.SetString("Account", JsonConvert.SerializeObject(_account));
return Ok(_account);
}
else
{
return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status206PartialContent);
}
}
[HttpGet("getAccount")]
public Account GetAccount()
{
if(HttpContext.Session.GetString("Account") != null)
{
return JsonConvert.DeserializeObject<Account>(HttpContext.Session.GetString("Account"));
}
else
{
return null;
}
}
[HttpPost("MaakAccount")]
public IActionResult MaakAccount([FromBody] Account account)
{
if(_context.Account.FirstOrDefault(a => a.Gebruikersnaam == account.Gebruikersnaam) == null && _context.Account.FirstOrDefault(a => a.EmailAdres == account.EmailAdres) == null)
{
using(_context)
{
_context.Database.EnsureCreated();
_context.Account.Add(new Account
{
Gebruikersnaam = account.Gebruikersnaam,
Wachtwoord = CreateHash(account.Wachtwoord),
Salt = salt,
Naam = account.Naam,
Tussenvoegsel = account.Tussenvoegsel,
Achternaam = account.Achternaam,
StraatHuisnr = account.StraatHuisnr,
Postcode = account.Postcode,
EmailAdres = account.EmailAdres,
Telefoonnummer = account.Telefoonnummer
});
//http://www.systemnetmail.com/ voor info over mailen
MailMessage message = new System.Net.Mail.MailMessage();
string fromEmail = "thuisbegymmen@gmail.com";
string emailPassword = "adminthuisbegymmen";
message.From = new MailAddress(fromEmail);
message.To.Add(account.EmailAdres);
message.Subject = "Account aangemaakt";
message.Body = "Bij deze willen we u laten weten dat u een account heeft op ThuisBegymmen. Log in om uw gegevens in te zien.";
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
using (SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(fromEmail, emailPassword);
smtpClient.Send(message.From.ToString(), message.To.ToString(), message.Subject, message.Body);
}
_context.SaveChanges();
}
return Ok();
}
else
{
return NoContent();
}
}
[HttpPut("VeranderAccount")]
public IActionResult VeranderAccount([FromBody] Account _account)
{
Account account = _context.Account.FirstOrDefault(a => a.Id == _account.Id);
if(!string.IsNullOrEmpty(_account.Naam)){account.Naam = _account.Naam;}
if(!string.IsNullOrEmpty(_account.Tussenvoegsel)){account.Tussenvoegsel = _account.Tussenvoegsel;}
if(!string.IsNullOrEmpty(_account.Achternaam)){account.Achternaam = _account.Achternaam;}
if(!string.IsNullOrEmpty(_account.StraatHuisnr)){account.StraatHuisnr = _account.StraatHuisnr;}
if(!string.IsNullOrEmpty(_account.Postcode)){account.Postcode = _account.Postcode;}
if(!string.IsNullOrEmpty(_account.EmailAdres)){account.EmailAdres = _account.EmailAdres;}
if(!string.IsNullOrEmpty(_account.Wachtwoord)){account.Wachtwoord = CreateHash(_account.Wachtwoord);
account.Salt = salt;}
//Alleen telefoonnr kan niet aangepast worden
_context.SaveChanges();
account.Wachtwoord = null;
return Ok(account);
}
[HttpDelete("LogOut")]
public IActionResult LogOut()
{
HttpContext.Session.Remove("Account");
return Ok();
}
[HttpGet("GetAllAccounts")]
public IActionResult GetAllAccounts()
{
List<Account> accounts;
try
{
accounts = _context.Account.ToList();
foreach(Account account in accounts)
{
account.Wachtwoord = null;
}
}
catch(MySql.Data.MySqlClient.MySqlException)
{
return BadRequest();
}
return Ok(accounts);
}
[HttpGet("GetSingleAccount")]
public IActionResult GetSingleAccount(int _accountId)
{
Account account;
try
{
account =_context.Account.FirstOrDefault(a => a.Id == _accountId);
account.Wachtwoord = null;
}
catch(MySql.Data.MySqlClient.MySqlException)
{
return BadRequest();
}
return Ok(account);
}
[HttpPut("UpdateRechten")]
public IActionResult UpdateRechten([FromBody] Account _account)
{
Account account = _context.Account.FirstOrDefault(a => a.Id == _account.Id);
account.IsAdmin = _account.IsAdmin;
// account.Rechten = _account.Rechten;
// account.ToevoegenProduct = _account.ToevoegenProduct;
// account.VerwijderProduct = _account.VerwijderProduct;
// account.ToevoegenCategorie = _account.ToevoegenCategorie;
// account.VerwijderCategorie = _account.VerwijderCategorie;
// account.VerwijderAccount = _account.VerwijderAccount;
try
{
_context.SaveChanges();
}
catch(MySql.Data.MySqlClient.MySqlException)
{
return BadRequest();
}
return Ok();
}
[HttpDelete("VerwijderAccount")]
public IActionResult VerwijderAccount([FromBody] Account _account)
{
Account account = _context.Account.FirstOrDefault(a => a.Id == _account.Id);
_context.Remove(account);
_context.SaveChanges();
return Ok();
}
[HttpPut("ResetPassword")]
public IActionResult ResetPassword(string EmailAdres)
{
Account account = _context.Account.FirstOrDefault(a => a.EmailAdres == EmailAdres);
Random rnd = new Random();
string password = rnd.Next(10,99).ToString() + account.Gebruikersnaam + rnd.Next(10,99).ToString();
account.Wachtwoord = CreateHash(password);
account.Salt = salt;
_context.SaveChanges();
//http://www.systemnetmail.com/ voor info over mailen
MailMessage message = new System.Net.Mail.MailMessage();
string fromEmail = "thuisbegymmen@gmail.com";
string emailPassword = "adminthuisbegymmen";
message.From = new MailAddress(fromEmail);
message.To.Add(account.EmailAdres);
message.Subject = "Account gereset";
message.Body =
"Goedendag,\n\n U heeft uw account gereset op thuisbegymmen.nl. Hieronder ziet u uw nieuwe wachtwoord en gebruikersnaam die aan het account zijn gekoppeld.\n\n Gebruikersnaam: \t"+ account.Gebruikersnaam + "\n Wachtwoord: \t" + password + "\n\n Met vriendelijke groet,\nThuisbegymmen.nl";
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
using (SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(fromEmail, emailPassword);
smtpClient.Send(message.From.ToString(), message.To.ToString(), message.Subject, message.Body);
}
return Ok();
}
public string CreateHash(string wachtwoord)
{
var provider = new RNGCryptoServiceProvider();
provider.GetNonZeroBytes(saltBytes);
salt = Convert.ToBase64String(saltBytes);
var rfc2898DeriveBytes = new Rfc2898DeriveBytes(wachtwoord, saltBytes, 10000);
var hashPassword = Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(256));
return hashPassword;
}
public bool ValidateHash(string enteredPassword, string salt, string hashedPassword)
{
var saltBytes = Convert.FromBase64String(salt);
var rfc2898DeriveBytes = new Rfc2898DeriveBytes(enteredPassword, saltBytes, 10000);
return Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(256)) == hashedPassword;
}
}
}
|
#load "./parameters.cake"
#load "./paths.cake"
FilePath FindToolInPath(string tool)
{
var pathEnv = EnvironmentVariable("PATH");
if (string.IsNullOrEmpty(pathEnv) || string.IsNullOrEmpty(tool)) return tool;
var paths = pathEnv.Split(new []{ IsRunningOnUnix() ? ':' : ';'}, StringSplitOptions.RemoveEmptyEntries);
return paths.Select(path => new DirectoryPath(path).CombineWithFilePath(tool)).FirstOrDefault(filePath => FileExists(filePath.FullPath));
}
void FixForMono(Cake.Core.Tooling.ToolSettings toolSettings, string toolExe)
{
if (IsRunningOnUnix())
{
var toolPath = Context.Tools.Resolve(toolExe);
toolSettings.ToolPath = FindToolInPath("mono");
toolSettings.ArgumentCustomization = args => toolPath.FullPath + " " + args.Render();
}
}
DirectoryPath HomePath()
{
return IsRunningOnWindows()
? new DirectoryPath(EnvironmentVariable("HOMEDRIVE") + EnvironmentVariable("HOMEPATH"))
: new DirectoryPath(EnvironmentVariable("HOME"));
}
void ReplaceTextInFile(FilePath filePath, string oldValue, string newValue, bool encrypt = false)
{
Information("Replacing {0} with {1} in {2}", oldValue, !encrypt ? newValue : "******", filePath);
var file = filePath.FullPath.ToString();
System.IO.File.WriteAllText(file, System.IO.File.ReadAllText(file).Replace(oldValue, newValue));
}
GitVersion GetVersion(BuildParameters parameters)
{
var settings = new GitVersionSettings
{
OutputType = GitVersionOutput.Json
};
var gitVersion = GitVersion(settings);
if (!(parameters.IsRunningOnAzurePipeline && parameters.IsPullRequest))
{
settings.UpdateAssemblyInfo = true;
settings.LogFilePath = "console";
settings.OutputType = GitVersionOutput.BuildServer;
GitVersion(settings);
}
return gitVersion;
}
void Build(FilePath projectPath, string configuration, DotNetCoreMSBuildSettings settings = null)
{
Information("Run restore for {0}", projectPath.GetFilenameWithoutExtension());
DotNetCoreRestore(projectPath.FullPath);
Information("Run build for {0}", projectPath.GetFilenameWithoutExtension());
DotNetCoreBuild(projectPath.FullPath, new DotNetCoreBuildSettings {
Configuration = configuration,
Verbosity = DotNetCoreVerbosity.Minimal,
NoRestore = true,
MSBuildSettings = settings
});
}
void GetReleaseNotes(FilePath outputPath, DirectoryPath workDir = null, string repoToken = null)
{
var toolPath = Context.Tools.Resolve("GitReleaseNotes.exe");
workDir = workDir ?? ".";
var arguments = new ProcessArgumentBuilder()
.Append(workDir.ToString())
.Append("/OutputFile")
.Append(outputPath.ToString());
if (repoToken != null)
arguments.Append("/RepoToken").Append(repoToken);
StartProcess(toolPath, new ProcessSettings { Arguments = arguments, RedirectStandardOutput = true }, out var redirectedOutput);
Information(string.Join("\n", redirectedOutput));
}
string GetDotnetVersion()
{
var toolPath = Context.Tools.Resolve("dotnet.exe");
var arguments = new ProcessArgumentBuilder()
.Append("--version");
using(var process = StartAndReturnProcess(toolPath, new ProcessSettings { Arguments = arguments, RedirectStandardOutput = true }))
{
process.WaitForExit();
return process.GetStandardOutput().LastOrDefault();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ElevatorDoor : MonoBehaviour {
private bool moving = false;
private bool triggered = false;
private GameObject leftDoor;
private GameObject rightDoor;
private GameObject redCarpet;
public GameObject heroObject;
void Start()
{
leftDoor = transform.GetChild(0).gameObject;
rightDoor = transform.GetChild(1).gameObject;
redCarpet = transform.GetChild(2).gameObject;
if(name =="StartElevator")
{
//so it's easier to test. can just have hero in scene for testing
if (GameObject.Find("Hero") == null)
{
StartCoroutine(beginLevel());
}
}
}
public void trigger(GameObject triggeringObject)
{
if (triggeringObject.tag == "Player" &&
triggeringObject.GetComponent<InputHandler>().ghostState == InputHandler.GHOST_STATE.HUMAN &&
!triggered &&
!moving)
{
StartCoroutine(finishLevel());
}
}
IEnumerator beginLevel()
{
GameObject newHero = Instantiate(heroObject);
Camera.main.GetComponent<CameraScript>().target = null;
Camera.main.orthographicSize = 1.0f; //TODO: maybe not hardcode this in the future
Vector3 spawnPos = transform.position;
spawnPos.z = -0.5f;
newHero.transform.position = spawnPos;
newHero.GetComponent<InputHandler>().changeHeroState(InputHandler.HERO_STATE.DISABLED);
Camera.main.transform.rotation = Quaternion.Euler(Vector3.left * 90);
Vector3 camSpawnPos = transform.position;
camSpawnPos.z = -1.0f;
camSpawnPos.y -= 3.0f;
Camera.main.transform.position = camSpawnPos;
StartCoroutine(Tools.moveObject(leftDoor, Vector3.left, 2, 1f));
yield return StartCoroutine(Tools.moveObject(rightDoor, Vector3.right, 2, 1f));
StartCoroutine(Camera.main.GetComponent<CameraScript>().levelTransitionZoom2(gameObject, 3,Camera.main.GetComponent<CameraScript>().getStartDistance()));
yield return StartCoroutine(redCarpet.GetComponent<RedCarpet>().openCarpet());
Vector3 moveDir = Vector3.down;
moveDir.z = 0.0f;
float moveTime = 1.5f;
newHero.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -.1f);
yield return StartCoroutine(Tools.moveObject(newHero, moveDir, moveTime, 3, Tools.INTERPOLATION_TYPE.LERP));
Camera.main.GetComponent<CameraScript>().target = newHero;
newHero.GetComponent<InputHandler>().changeHeroState(InputHandler.HERO_STATE.IDLE);
}
IEnumerator finishLevel()
{
triggered = !triggered;
MusicManager.instance.playFanfare();
GameObject hero = GameObject.Find("Hero") != null ? GameObject.Find("Hero") : GameObject.Find("Hero(Clone)");
hero.GetComponent<InputHandler>().changeHeroState(InputHandler.HERO_STATE.DISABLED);
StartCoroutine(Tools.moveObject(leftDoor, Vector3.left, 2, 1f));
StartCoroutine(Camera.main.GetComponent<CameraScript>().levelTransitionZoom(gameObject,4,-1));
yield return StartCoroutine(Tools.moveObject(rightDoor, Vector3.right, 2, 1f));
yield return StartCoroutine(redCarpet.GetComponent<RedCarpet>().openCarpet());
hero.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0.1f);
Vector3 moveDir = (-hero.transform.position + transform.position).normalized;
moveDir.z = 0.0f;
float moveTime = 2.0f;
yield return StartCoroutine(Tools.moveObject(hero, moveDir, moveTime, 3, Tools.INTERPOLATION_TYPE.LERP));
LevelManager.instance.initiateNextLevel();
}
}
|
using System.Windows;
namespace Crystal.Plot2D
{
/// <summary>
/// Provides elements that represent markers along the graph.
/// </summary>
public abstract class ElementPointMarker : DependencyObject
{
/// <summary>
/// Creates marker element at specified point.
/// </summary>
/// <returns>
/// UIElement representing marker.
/// </returns>
public abstract UIElement CreateMarker();
public abstract void SetMarkerProperties(UIElement marker);
/// <summary>
/// Moves specified marker so its center is located at specified screen point.
/// </summary>
/// <param name="marker">
/// UIElement created using CreateMarker.
/// </param>
/// <param name="screenPoint">
/// Point to center element around.
/// </param>
public abstract void SetPosition(UIElement marker, Point screenPoint);
}
}
|
namespace kindergarden
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("activitiesPicture")]
public partial class activitiesPicture
{
public int Id { get; set; }
public int? activitiesId { get; set; }
public string filePath { get; set; }
public bool? isActive { get; set; }
public virtual activities activities { get; set; }
}
}
|
using Autofac;
using Tests.Data.Van;
using Tests.Data.Van.Input;
using Tests.Data.Van.Input.Filters;
using Tests.Pages.Van.LogIn;
using Tests.Pages.Van.Main.Common.DefaultPage;
using Tests.Pages.Van.Main.VirtualPhoneBankPages;
using NUnit.Framework;
namespace Tests.Projects.Van.VirtualPhoneBankTests
{
public class EditVirtualPhoneBank : BaseTest
{
#region Test Pages
private LoginPage LogInPage { get { return Scope.Resolve<LoginPage>(); } }
private VoterDefaultPage HomePage { get { return Scope.Resolve<VoterDefaultPage>(); } }
private VirtualPhoneBankDetailsPage VirtualPhoneBankDetailsPage { get { return Scope.Resolve<VirtualPhoneBankDetailsPage>(); } }
private VirtualPhoneBankListPage VirtualPhoneBankListPage { get { return Scope.Resolve<VirtualPhoneBankListPage>(); } }
#endregion
#region Test Case Data
#region TestCase: Pending
private static readonly VanTestUser User1 = new VanTestUser
{
UserName = "TurfTester",
Password = "@uT0Te$t7InG2"
};
private static readonly VirtualPhoneBank VpbToEdit1 = new VirtualPhoneBank
{
Name = "",
};
private static readonly VirtualPhoneBank NewVpb1 = new VirtualPhoneBank
{
Name = "",
};
#endregion
private static readonly object[] TestData =
{
new object[] { User1, VpbToEdit1, NewVpb1 }
};
#endregion
/// <summary>
/// Tests the Edit Virtual Phone Bank functionality.
/// Opens a Virtual Phone Bank and edits it.
/// </summary>
[Test, TestCaseSource("TestData")]
[Ignore] // Incomplete Test. Test Data needs to be configured
[Category("van")]
public void TestCaseEditVirtualPhoneBank(
VanTestUser user,
VirtualPhoneBank vpbToEdit,
VirtualPhoneBank newVpb)
{
var filterForVpbToEdit = new VirtualPhoneBankListPageFilter { Name = vpbToEdit.Name };
LogInPage.Login(user);
HomePage.ClickVirtualPhoneBankAdminLink();
VirtualPhoneBankListPage.OpenVirtualPhoneBank(filterForVpbToEdit, vpbToEdit.Name);
VirtualPhoneBankDetailsPage.SubmitNewVirtualPhoneBank(newVpb);
VirtualPhoneBankDetailsPage.ClickSubmitButton();
Assert.That(VirtualPhoneBankListPage.VirtualPhoneBankIsPresent(filterForVpbToEdit, newVpb.Name), Is.True,
"Newly created Virtual Phone Bank was not found in the list of Virtual Phone Banks.");
}
}
}
|
using Assets.Scripts.UI;
using UnityEngine;
namespace Assets.Scripts.Controllers
{
public class TorchController : MonoBehaviour
{
public Animation Animation;
public GameObject TorchObject;
public Light Light;
public AudioSource Audio;
public ParticleSystem FireParticles;
public bool IsActive;
private GameManager _gameManager;
private UiSlot _torchSlot;
private float _currentTime;
private float _fireTime;
private float _updateDurabilityTime = 0.0f;
public void Start()
{
TorchObject.SetActive(false);
Audio.Stop();
IsActive = false;
_currentTime = 0.0f;
}
public void Init(GameManager gameManager)
{
_gameManager = gameManager;
}
public void Show(UiSlot slot)
{
IsActive = true;
TorchObject.SetActive(true);
_torchSlot = slot;
Animation.Play("ShowTorch");
Audio.Play();
FireParticles.Play();
}
public void Hide()
{
IsActive = false;
Audio.Stop();
_torchSlot = null;
Animation.Play("HideTorch");
}
public void OnHided()
{
TorchObject.SetActive(false);
}
void Update()
{
if (!IsActive ||
_torchSlot == null ||
_torchSlot.ItemModel == null ||
_torchSlot.ItemModel.Item == null)
return;
_currentTime += Time.deltaTime;
_updateDurabilityTime += Time.deltaTime;
if (_currentTime >= _torchSlot.ItemModel.Item.Durability)
{
_currentTime = 0.0f;
_gameManager.PlayerModel.Inventory.QuickSlots[_torchSlot.SlotId].ChangeAmount(1);
if (_gameManager.PlayerModel.Inventory.QuickSlots[_torchSlot.SlotId] == null)
Hide();
}
if (_updateDurabilityTime >= 1.0f)
{
_gameManager.Player.MainHud.InventoryPanel.QuickSlotsPanel.Slots[_torchSlot.SlotId].ItemModel.ChangeDurability(1);
_updateDurabilityTime = 0.0f;
}
}
}
}
|
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
namespace Spring.Messaging.Amqp.Core
{
/// <summary>
/// Acknowledge Mode Utilities
/// </summary>
/// <author>Joe Fitzgerald</author>
public static class AcknowledgeModeUtils
{
/// <summary>
/// Enumeration of Acknowledge Modes
/// </summary>
/// <author>Joe Fitzgerald</author>
public enum AcknowledgeMode
{
///<summary>
/// NONE AcknowledgeMode
///</summary>
NONE,
/// <summary>
/// NONE Acnowledge Mode
/// </summary>
MANUAL,
/// <summary>
/// MANUAL Acnowledge Mode
/// </summary>,
AUTO
}
/// <summary>
/// Determine if the acknowledge mode is transaction allowed.
/// </summary>
/// <param name="mode">
/// The mode.
/// </param>
/// <returns>
/// True if transaction allowed, else false.
/// </returns>
public static bool TransactionAllowed(this AcknowledgeMode mode)
{
return mode == AcknowledgeMode.AUTO || mode == AcknowledgeMode.MANUAL;
}
/// <summary>
/// Determine if the acknowledge mode is auto ack.
/// </summary>
/// <param name="mode">
/// The mode.
/// </param>
/// <returns>
/// True if auto ack, else false.
/// </returns>
public static bool IsAutoAck(this AcknowledgeMode mode)
{
return mode == AcknowledgeMode.NONE;
}
/// <summary>
/// Determine if the acknowledge mode is manual.
/// </summary>
/// <param name="mode">
/// The mode.
/// </param>
/// <returns>
/// True if manual, else false.
/// </returns>
public static bool IsManual(this AcknowledgeMode mode)
{
return mode == AcknowledgeMode.MANUAL;
}
}
}
|
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Ardalis.HttpClientTestExtensions;
using BlazorShared.Models.AppointmentType;
using FrontDesk.Api;
using Xunit;
using Xunit.Abstractions;
namespace FunctionalTests.Api
{
public class AppointmentTypesList : IClassFixture<CustomWebApplicationFactory<Startup>>
{
private readonly HttpClient _client;
private readonly ITestOutputHelper _outputHelper;
public AppointmentTypesList(CustomWebApplicationFactory<Startup> factory, ITestOutputHelper outputHelper)
{
_client = factory.CreateClient();
_outputHelper = outputHelper;
}
[Fact]
public async Task Returns3AppointmentTypes()
{
var result = await _client.GetAndDeserialize<ListAppointmentTypeResponse>("/api/appointment-types", _outputHelper);
Assert.Equal(3, result.AppointmentTypes.Count());
Assert.Contains(result.AppointmentTypes, x => x.Name == "Wellness Exam");
}
}
}
|
using System;
using System.Collections.Generic;
using LuaInterface;
namespace GFW
{
public class GameStateMachine
{
private class GameStateSink
{
public ushort id;
public string sink_name;
public uint cur_state_id = ushort.MaxValue;
public uint previous_state_id = 0u;
public List<uint> contain_state_id_list = new List<uint>();
}
private const ushort SINK_ID_CAPACITY = 16;
private List<ushort> m_free_sink_id_list = new List<ushort>(SINK_ID_CAPACITY);
private List<GameStateMachine.GameStateSink> m_state_sink_array = new List<GameStateMachine.GameStateSink>();
private const ushort STATE_ID_CAPACITY = 64;
private List<uint> m_free_state_id_list = new List<uint>();
private List<GameState> m_state_array = new List<GameState>();
private IGameStateListner mAllStateListener;
public GameStateMachine()
{
mAllStateListener = null;
//初始化分支
for (ushort i = 0; i < SINK_ID_CAPACITY; i++)
{
m_free_sink_id_list.Add(i);
m_state_sink_array.Add(null);
}
//初始化状态
for (ushort i = 0; i < STATE_ID_CAPACITY; i++)
{
m_free_state_id_list.Add(i);
m_state_array.Add(null);
}
}
public void Dispose()
{
for (int i = 0; i < 16; i += 1)
{
if (m_state_sink_array[i] != null)
{
m_state_sink_array[i] = null;
}
}
m_state_sink_array.Clear();
int j = 0;
while (j < 64)
{
if (m_state_array[j] != null)
{
m_state_array[j] = null;
}
j++;
}
this.m_state_array.Clear();
if (mAllStateListener != null)
{
mAllStateListener.Free();
mAllStateListener = null;
}
}
public void UpdateNow(float elapse_time)
{
for (int i = 0; i < m_state_sink_array.Count; i++)
{
GameStateMachine.GameStateSink sink = m_state_sink_array[i];
if (sink != null)
{
GameState state = FindState(sink.cur_state_id);
if (state != null)
{
state.Excute(elapse_time);
}
}
}
}
#region - 创建分支
public bool CreateSink(ushort sink_id)
{
string sink_name = GetDefaultSinkNameFromId(sink_id);
return this.CreateSinkImpl(sink_id, sink_name);
}
public bool CreateSink(string sink_name)
{
if (m_free_sink_id_list.Count > 0)
{
ushort sink_id = m_free_sink_id_list[0];
return CreateSinkImpl(sink_id, sink_name);
}
return false;
}
private bool CreateSinkImpl(ushort sink_id, string sink_name)
{
if (sink_id < SINK_ID_CAPACITY && this.m_state_sink_array[(int)sink_id] == null)
{
GameStateMachine.GameStateSink sink = new GameStateMachine.GameStateSink();
sink.id = sink_id;
sink.sink_name = sink_name;
sink.cur_state_id = ushort.MaxValue;
sink.previous_state_id = ushort.MaxValue;
this.m_state_sink_array[(int)sink_id] = sink;
this.m_free_sink_id_list.Remove(sink_id);
return true;
}
return false;
}
#endregion
#region - 创建状态
public GameState CreateNormalState(uint state_id, ushort sink_id)
{
string state_name = GetDefaultStateNameFromId(state_id);
return this.CreateStateImpl(state_id, state_name, sink_id, StateComposeType.SCT_NORMAL, ushort.MaxValue);
}
public GameState CreateNormalState(string state_name, string sink_name)
{
GameStateMachine.GameStateSink sink = FindSink(sink_name);
if (sink != null)
{
if (m_free_state_id_list.Count > 0)
{
uint state_id = m_free_state_id_list[0];
return this.CreateStateImpl(state_id, state_name, sink.id, StateComposeType.SCT_NORMAL, ushort.MaxValue);
}
}
return null;
}
private GameState CreateStateImpl(uint state_id, string state_name, ushort sink_id, StateComposeType com_type)
{
return this.CreateStateImpl(state_id, state_name, sink_id, com_type, ushort.MaxValue);
}
private GameState CreateStateImpl(uint state_id, string state_name, ushort sink_id, StateComposeType com_type, uint parent_id)
{
GameState state = null;
GameStateMachine.GameStateSink sink = FindSink(sink_id);
if (sink != null && state_id < STATE_ID_CAPACITY && m_state_array[(int)state_id] == null)
{
if (com_type == StateComposeType.SCT_COMPOSE || com_type == StateComposeType.SCT_NORMAL)
{
state = new GameState(this, state_id, state_name, sink_id, com_type);
sink.contain_state_id_list.Add(state_id);
}
else if (com_type == StateComposeType.SCT_SUB)
{
GameState parent_state = this.FindState(parent_id);
if (parent_state != null && parent_state.GetComposeType() == StateComposeType.SCT_COMPOSE && parent_state.GetSinkId() == sink_id)
{
state = new GameState(this, state_id, state_name, sink_id, com_type);
state.m_parent_state_id = parent_id;
parent_state.m_sub_state_id_list.Add(state_id);
}
}
if (state != null)
{
this.m_state_array[(int)state_id] = state;
this.m_free_state_id_list.Remove(state_id);
}
}
return state;
}
#endregion
public bool ChangeState(uint state_id)
{
return ChangeState(state_id, false);
}
public bool ChangeState(uint state_id, bool ignore_state_lock)
{
GameState state = this.FindState(state_id);
if (state != null)
{
if (IsInState(state_id))
{
if (state.IsStateReEnter())
{
state.Exit();
state.Enter();
return true;
}
return false;
}
else
{
GameStateMachine.GameStateSink sink = FindSink(state.GetSinkId());
GameState cur_sink_state = FindState(sink.cur_state_id);
if (cur_sink_state != null && cur_sink_state.IsStateLock() && !ignore_state_lock)
{
return false;
}
if (state.GetComposeType() == StateComposeType.SCT_SUB)
{
GameState parent_state = this.FindState(state.m_parent_state_id);
if (this.IsInState(parent_state.GetId()))
{
GameState cur_run_state = this.FindState(parent_state.m_cur_run_sub);
if (state.CanChangeFromState(parent_state.m_cur_run_sub))
{
parent_state.m_previous_sub = parent_state.m_cur_run_sub;
parent_state.m_cur_run_sub = state_id;
if (cur_run_state != null)
{
cur_run_state.Exit();
}
state.Enter();
return true;
}
}
else
{
if (parent_state.CanChangeFromState(sink.cur_state_id))
{
parent_state.m_previous_sub = parent_state.m_cur_run_sub;
parent_state.m_cur_run_sub = state_id;
sink.previous_state_id = sink.cur_state_id;
sink.cur_state_id = parent_state.GetId();
if (cur_sink_state != null)
{
cur_sink_state.Exit();
}
if (parent_state != null)
{
parent_state.Enter();
}
return true;
}
}
}
else
{
if (state.CanChangeFromState(sink.cur_state_id))
{
sink.previous_state_id = sink.cur_state_id;
sink.cur_state_id = state_id;
if (cur_sink_state != null)
{
cur_sink_state.Exit();
}
state.Enter();
return true;
}
}
}
}
return false;
}
public bool ChangeState(string state_name)
{
return this.ChangeState(state_name, false);
}
public bool ChangeState(string state_name, bool ignore_state_lock)
{
return this.ChangeState(GetStateIdFromName(state_name), ignore_state_lock);
}
public bool ChangeStateForce(uint state_id)
{
GameState state = this.FindState(state_id);
bool result = true;
if (state != null)
{
if (IsInState(state_id))
{
if (state.IsStateReEnter())
{
state.Exit();
state.Enter();
}
else
{
result = false;
}
}
else
{
GameStateMachine.GameStateSink sink = FindSink(state.GetSinkId());
GameState cur_sink_state = FindState(sink.cur_state_id);
if (state.GetComposeType() == StateComposeType.SCT_SUB)
{
GameState parent_state = this.FindState(state.m_parent_state_id);
if (this.IsInState(parent_state.GetId()))
{
GameState cur_run_state = this.FindState(parent_state.m_cur_run_sub);
if (cur_run_state != null)
{
cur_run_state.Exit();
}
parent_state.m_previous_sub = parent_state.m_cur_run_sub;
parent_state.m_cur_run_sub = state_id;
state.Enter();
}
else
{
parent_state.m_previous_sub = parent_state.m_cur_run_sub;
parent_state.m_cur_run_sub = state_id;
sink.previous_state_id = sink.cur_state_id;
sink.cur_state_id = parent_state.GetId();
if (cur_sink_state != null)
{
cur_sink_state.Exit();
}
if (parent_state != null)
{
parent_state.Enter();
}
}
}
else
{
sink.previous_state_id = sink.cur_state_id;
sink.cur_state_id = state_id;
if (cur_sink_state != null)
{
cur_sink_state.Exit();
}
state.Enter();
}
}
}
else
{
result = false;
}
return result;
}
public bool ChangeStateForce(string state_name)
{
return ChangeStateForce(GetStateIdFromName(state_name));
}
public bool ChangeStateTest(uint state_id)
{
return this.ChangeStateTest(state_id, false);
}
public bool ChangeStateTest(uint state_id, bool ignore_state_lock)
{
GameState state = this.FindState(state_id);
if (state != null)
{
if (this.IsInState(state_id))
{
return state.IsStateReEnter();
}
GameStateMachine.GameStateSink sink = this.FindSink(state.GetSinkId());
GameState cur_sink_state = this.FindState(sink.cur_state_id);
if (cur_sink_state != null && cur_sink_state.IsStateLock() && !ignore_state_lock)
{
return false;
}
if (state.GetComposeType() == StateComposeType.SCT_SUB)
{
GameState parent_state = this.FindState(state.m_parent_state_id);
if (this.IsInState(parent_state.GetId()))
{
if (state.CanChangeFromState(parent_state.m_cur_run_sub))
{
return true;
}
}
else
{
if (parent_state.CanChangeFromState(sink.cur_state_id))
{
return true;
}
}
}
else
{
if (state.CanChangeFromState(sink.cur_state_id))
{
return true;
}
}
}
return false;
}
public bool ChangeStateTest(string state_name)
{
return this.ChangeStateTest(state_name, false);
}
public bool ChangeStateTest(string state_name, bool ignore_state_lock)
{
return this.ChangeStateTest(this.GetStateIdFromName(state_name), ignore_state_lock);
}
public bool IsInState(uint state_id)
{
bool is_in_state = false;
GameState state = FindState(state_id);
if (state != null)
{
GameStateMachine.GameStateSink sink = FindSink(state.GetSinkId());
if (state.GetComposeType() == StateComposeType.SCT_SUB)
{
GameState parent_state = FindState(state.m_parent_state_id);
if (parent_state != null && parent_state.GetId() == sink.cur_state_id)
{
is_in_state = (parent_state.m_cur_run_sub == state_id);
}
}
else
{
is_in_state = (sink.cur_state_id == state_id);
}
}
return is_in_state;
}
public bool IsInState(string state_name)
{
return this.IsInState(this.GetStateIdFromName(state_name));
}
public GameState FindState(uint state_id)
{
GameState state = null;
if (state_id != ushort.MaxValue)
{
if (state_id < m_state_array.Count)
{
state = m_state_array[(int)state_id];
}
}
return state;
}
public GameState FindState(string name)
{
GameState state = null;
for (int i = 0; i < m_state_array.Count; i++)
{
if (m_state_array[i] != null && m_state_array[i].GetName() == name)
{
state = m_state_array[i];
break;
}
}
return state;
}
public uint GetSinkRunState(ushort sink_id)
{
uint find_id = ushort.MaxValue;
GameStateMachine.GameStateSink sink = this.FindSink(sink_id);
if (sink != null)
{
find_id = sink.cur_state_id;
}
return find_id;
}
public string GetSinkRunState(string sink_name)
{
return GetStateNameFromId(GetSinkRunState(GetSinkIdFromName(sink_name)));
}
public uint GetCurActionFlag()
{
return uint.MaxValue;
}
public void SinkToNullState(ushort sink_id)
{
GameStateMachine.GameStateSink sink = this.FindSink(sink_id);
if (sink != null)
{
sink.previous_state_id = sink.cur_state_id;
GameState state = this.FindState(sink.cur_state_id);
if (state != null)
{
state.Exit();
}
sink.cur_state_id = ushort.MaxValue;
}
}
public void SinkToNullState(string sink_name)
{
this.SinkToNullState(this.GetSinkIdFromName(sink_name));
}
public GameState CreateComposeState(uint state_id, ushort sink_id)
{
string state_name = this.GetDefaultStateNameFromId(state_id);
return this.CreateStateImpl(state_id, state_name, sink_id, StateComposeType.SCT_COMPOSE, ushort.MaxValue);
}
public GameState CreateComposeState(string state_name, string sink_name)
{
GameStateMachine.GameStateSink sink = FindSink(sink_name);
GameState result = null;
if (sink != null)
{
if (m_free_state_id_list.Count > 0)
{
uint id = m_free_state_id_list[0];
result = CreateStateImpl(id, state_name, sink.id, StateComposeType.SCT_COMPOSE, ushort.MaxValue);
}
}
return result;
}
public GameState CreateSubState(uint state_id, ushort sink_id, uint parent_id)
{
string state_name = this.GetDefaultStateNameFromId(state_id);
return this.CreateStateImpl(state_id, state_name, sink_id, StateComposeType.SCT_SUB, parent_id);
}
public GameState CreateSubState(string state_name, string sink_name, string parent_name)
{
GameStateMachine.GameStateSink sink = this.FindSink(sink_name);
GameState result;
if (sink == null)
{
result = null;
}
else
{
GameState parent_state = this.FindState(parent_name);
if (parent_state == null)
{
result = null;
}
else
{
if (this.m_free_state_id_list.Count != 0)
{
uint id = this.m_free_state_id_list[0];
result = this.CreateStateImpl(id, state_name, sink.id, StateComposeType.SCT_SUB, parent_state.GetId());
}
else
{
result = null;
}
}
}
return result;
}
public void DestroyState(uint state_id)
{
GameState state = this.FindState(state_id);
if (state != null)
{
GameStateMachine.GameStateSink sink = this.FindSink(state.GetSinkId());
uint cur_run_state_id = sink.cur_state_id;
sink.contain_state_id_list.Remove(state_id);
bool need_cancel_cur_state = false;
if (this.IsInState(state_id))
{
state.Exit();
need_cancel_cur_state = true;
}
if (state.GetComposeType() == StateComposeType.SCT_SUB)
{
GameState parent_state = this.FindState(state.m_parent_state_id);
if (need_cancel_cur_state)
{
parent_state.m_cur_run_sub = ushort.MaxValue;
parent_state.m_previous_sub = ushort.MaxValue;
}
parent_state.m_sub_state_id_list.Remove(state_id);
}
else
{
sink.contain_state_id_list.Remove(state_id);
if (need_cancel_cur_state)
{
sink.cur_state_id = ushort.MaxValue;
sink.previous_state_id = ushort.MaxValue;
}
if (state.GetComposeType() == StateComposeType.SCT_COMPOSE)
{
state.DestroyAllSubStates();
}
}
state.Dispose();
this.m_state_array[(int)state_id] = null;
this.m_free_state_id_list.Add(state_id);
}
}
public void DestroyState(string state_name)
{
this.DestroyState(this.GetStateIdFromName(state_name));
}
public string GetStateNameFromId(uint state_id)
{
string tmp_name = "";
GameState state = FindState(state_id);
if (state != null)
{
tmp_name = state.GetName();
}
return tmp_name;
}
public uint GetStateIdFromName(string name)
{
GameState state = FindState(name);
uint result = ushort.MaxValue;
if (state != null)
{
result = state.GetId();
}
return result;
}
public string GetSinkNameFromId(ushort sink_id)
{
string tmp_name = "";
GameStateMachine.GameStateSink sink = this.FindSink(sink_id);
if (sink != null)
{
tmp_name = sink.sink_name;
}
return tmp_name;
}
public ushort GetSinkIdFromName(string name)
{
GameStateMachine.GameStateSink sink = FindSink(name);
ushort result = ushort.MaxValue;
if (sink != null)
{
result = sink.id;
}
return result;
}
public void SetListener(LuaFunction enter_func, LuaFunction exit_func)
{
if (this.mAllStateListener != null)
{
this.mAllStateListener.Free();
this.mAllStateListener = null;
}
this.mAllStateListener = new ScriptAllStateListner(this, enter_func, exit_func);
}
public void OnStateEnterNotify(GameState pCurState)
{
if (this.mAllStateListener != null)
{
this.mAllStateListener.OnStateEnter(pCurState);
}
}
public void OnStateLeaveNotify(GameState pCurState)
{
if (this.mAllStateListener != null)
{
this.mAllStateListener.OnStateQuit(pCurState);
}
}
private GameStateMachine.GameStateSink FindSink(ushort sink_id)
{
GameStateMachine.GameStateSink sink = null;
if (sink_id != ushort.MaxValue)
{
if (this.m_state_sink_array.Count >= 0)
{
sink = this.m_state_sink_array[(int)sink_id];
}
}
return sink;
}
private GameStateMachine.GameStateSink FindSink(string name)
{
GameStateMachine.GameStateSink sink = null;
for (int i = 0; i < this.m_state_sink_array.Count; i++)
{
if (this.m_state_sink_array[i] != null && this.m_state_sink_array[i].sink_name == name)
{
sink = this.m_state_sink_array[i];
break;
}
}
return sink;
}
private string GetDefaultStateNameFromId(uint id)
{
return "_def_sink_" + (int)id;
}
private string GetDefaultSinkNameFromId(ushort id)
{
return "_def_sink_" + (int)id;
}
}
}
|
using Godot;
using System;
using System.Collections.Generic;
using System.Linq;
public class MusicPlayer : AudioStreamPlayer
{
private Tween _musicTween;
public float StartingVolumeDb {get; set;} = 0;
public float FadeDuration {get; set;}= 1f;
private Random _rand = new Random();
private List<AudioStream> _currentPlaylist;
private List<AudioStream> _finishedPlaylist = new List<AudioStream>();
private bool _playlistActive = false;
private bool _stop = false;
public Dictionary<AudioStream, float> PausedMusic = new Dictionary<AudioStream, float>();
public override void _Ready()
{
Tween t = new Tween();
AddChild(t);
_musicTween = t;
}
public override void _Process(float delta)
{
if (Stream == null)
{
return;
}
float timeLeft = Stream.GetLength() - GetPlaybackPosition();
if (timeLeft <= FadeDuration && timeLeft > 0.1f && !_musicTween.IsActive())
{
FadeOut();
}
}
// this works without playlist - if you want to manually control music being played e.g. based on entering an area
public async void PauseAndPlayNext(AudioStream newStream)
{
if (Stream != null)
{
if (PausedMusic.ContainsKey(Stream))
{
PausedMusic.Remove(Stream);
}
PausedMusic[Stream] = GetPlaybackPosition();
}
FadeOut();
await ToSignal(_musicTween, "tween_completed");
Stop();
Stream = newStream;
if (PausedMusic.ContainsKey(newStream))
{
FadeIn();
this.Play(PausedMusic[newStream]);
}
else
{
this.Play();
}
}
public void FadeIn()
{
_musicTween.InterpolateProperty(this, "volume_db", -50, StartingVolumeDb, FadeDuration, Tween.TransitionType.Linear, Tween.EaseType.Out);
_musicTween.Start();
}
public void FadeOut(float volDB = -50)
{
_musicTween.InterpolateProperty(this, "volume_db", StartingVolumeDb, volDB, FadeDuration, Tween.TransitionType.Linear, Tween.EaseType.In);
_musicTween.Start();
}
public async void FadeThenStop(bool freePlayer = false)
{
_stop = true;
_playlistActive = false;
FadeOut();
await ToSignal(_musicTween, "tween_completed");
Stop();
if (freePlayer)
{
QueueFree();
}
}
public new void Play(float from = 0)
{
_stop = false;
_musicTween.StopAll();
if (from == 0)
{
VolumeDb = StartingVolumeDb;
}
base.Play(from);
}
public void StartPlaylist(List<AudioStream> streams)
{
_playlistActive = true;
_currentPlaylist = streams;
// consider adding a shuffle here if we want to make it random each time
PlayNext();
}
private void PlayNext()
{
GD.Print("playing next");
Stream = _currentPlaylist[0];
Play();
_finishedPlaylist.Add(Stream);
_currentPlaylist.Remove(Stream);
if (_currentPlaylist.Count == 0)
{
GD.Print("finished");
_currentPlaylist = _finishedPlaylist.ToList();
_finishedPlaylist.Clear();
}
}
public void StopPlaylist()
{
_playlistActive = false;
_finishedPlaylist.Clear();
_currentPlaylist.Clear();
}
public void OnMusicPlayerFinished()
{
if (_stop)
{
return;
}
if (_playlistActive)
{
PlayNext();
return;
}
Play();
}
}
|
using NHibernate.Envers;
using NHibernate.Envers.Configuration.Attributes;
using SharpArch.Domain.DomainModel;
using System;
namespace Profiling2.Domain
{
[RevisionEntity(typeof(RevinfoListener))]
public class REVINFO : Entity
{
// We annotate this field as required by Envers' validation checks, but effectively this model's primary key is
// used as the revision number by other *_AUD tables.
[RevisionNumber]
public virtual int REV { get; set; }
[RevisionTimestamp]
public virtual DateTime? REVTSTMP { get; set; }
public virtual string UserName { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GroupBuilder;
namespace GrouperApp
{
public partial class ThankYou : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string id = Request.QueryString["id"].Trim().ToLower();
Student thisStudent = GrouperMethods.GetStudent(int.Parse(id));
//NameLabel.Text = " " + thisStudent.PreferredName;
}
}
}
} |
using System;
namespace DevilDaggersCore.Game
{
public class GameVersion
{
public Type Type { get; set; }
public DateTime ReleaseDate { get; set; }
public GameVersion(Type type, DateTime releaseDate)
{
Type = type;
ReleaseDate = releaseDate;
}
}
} |
using System.ComponentModel.DataAnnotations;
namespace Library.API.Models
{
public class LoginUser
{
public string UserName { get; set; }
public string Password { get; set; }
[EmailAddress]
public string Email { get; set; }
public const string demoName = "demouser";
public const string demoPwd = "demopwd";
}
}
|
using Alabo.Web.Mvc.Attributes;
using System.ComponentModel.DataAnnotations;
namespace Alabo.UI.Design.AutoReports.Enums {
/// <summary>
/// 报表运算符,支持等于和不等于两种方式即可
/// </summary>
public enum ReportOperator {
/// <summary>
/// 等于
/// </summary>
[Display(Name = "等于")]
[Field(Mark = "==")]
Equal = 1,
/// <summary>
/// 不等于
/// </summary>
[Display(Name = "不等于")]
[Field(Mark = "!=")]
NotEqual = 2
}
} |
namespace Facade
{
public class CloudConnection
{
public string Url { get; private set; }
public CloudConnection(string url)
{
Url = url;
}
public string GetAuthToken()
{
System.Console.WriteLine("Generating Auth Token");
return "Authenticated";
}
}
} |
using LHRLA.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LHRLA.LHRLA.DAL.DataAccessClasses
{
public class UserLogDataAccess
{
#region Insert
public bool AddUserLog(tbl_UserLog row)
{
try
{
using (var db = new vt_LHRLAEntities())
{
db.tbl_UserLog.Add(row);
db.SaveChanges();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
#endregion
#region Update
public bool UpdateUserLog(tbl_UserLog row)
{
try
{
using (var db = new vt_LHRLAEntities())
{
tbl_UserLog val = new tbl_UserLog();
val = db.tbl_UserLog.Where(a => a.ID == row.ID).FirstOrDefault();
val.Entity_Type = row.Entity_Type;
val.Entity_ID = row.Entity_ID;
val.Action_Timestamp = row.Action_Timestamp;
val.Description = row.Description;
val.Action_Name = row.Action_Name;
val.Action_User_ID = row.Action_User_ID;
db.SaveChanges();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
#endregion
#region Delete
#endregion
#region Select
public List<tbl_UserLog> GetAllUserLogs()
{
try
{
List<tbl_UserLog> lst = new List<tbl_UserLog>();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_UserLog.ToList();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
//public List<tbl_Branch> GetAllActiveBranches()
//{
// try
// {
// List<tbl_Branch> lst = new List<tbl_Branch>();
// using (var db = new vt_LHRLAEntities())
// {
// lst = db.tbl_UserLog.ToList().Where(a => a.Is_Active == true).ToList();
// }
// return lst;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
public List<tbl_UserLog> GetUserLogbyID(int ID)
{
try
{
List<tbl_UserLog> lst = new List<tbl_UserLog>();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_UserLog.Where(e => e.ID == ID).ToList();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
} |
using System;
using Strategy.Interfaces;
namespace Strategy.Classes
{
public class FlyRocketPowered : IFlyBehavior
{
public void fly()
{
Console.WriteLine("I'm flying with a rocket!");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using Autofac.Core;
using Autofac.Extras.DynamicProxy;
using KMS.Twelve.Test;
using Microsoft.AspNetCore.Mvc;
using TypeDemo.Domain;
using TypeDemo.Log;
namespace TypeDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Intercept(typeof(AopInterceptor))]
//public class ValuesController : Controller
public class ValuesController : ControllerBase
{
//private readonly IEnumerable<IDog> dogs;
//public ValuesController(IEnumerable<IDog> _dogs)
//{
// dogs = _dogs;
//}
/// <summary>
/// 3.使用属性注入
/// </summary>
public IEnumerable<IDog> dogs { get; set; }
// GET api/values
//public ActionResult<IEnumerable<string>> Get()
//{
// return new string[] { "value1", "value2" };
//}
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpGet]
public IEnumerable<string> Get()
{
List<string> list = new List<string>();
foreach (var dog in dogs)
{
list.Add($"名称:{dog.Name},品种:{dog.Breed}");
}
return list.ToArray(); ;
}
public void More()
{
//var iocManager = app.ApplicationServices.GetService<IIocManager>();
//List<Parameter> cparams = new List<Parameter>();
//cparams.Add(new NamedParameter("name", "张三"));
//cparams.Add(new NamedParameter("sex", "男"));
//cparams.Add(new TypedParameter(typeof(int), 2));
//var testDemo = iocManager.Resolve<TestDemo>(cparams.ToArray());
//Console.WriteLine($"姓名:{testDemo.Name},年龄:{testDemo.Age},性别:{testDemo.Sex}");
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class SaveLoad
{
public static void Save(Player player)
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath +
Path.DirectorySeparatorChar + "savedGames.gd");
PlayerData data = new PlayerData(player);
bf.Serialize(file, data);
file.Close();
}
public static PlayerData Load()
{
if (File.Exists(Application.persistentDataPath + Path.DirectorySeparatorChar +
"savedGames.gd"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + Path.DirectorySeparatorChar
+ "savedGames.gd", FileMode.Open);
PlayerData data = bf.Deserialize(file) as PlayerData;
file.Close();
return data;
}
else
{
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.OleDb;
namespace WPFDatabase
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
OleDbConnection connection;
public MainWindow()
{
InitializeComponent();
connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\EmployeeAssets.accdb");
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
}
private void ViewAssets_Click(object sender, RoutedEventArgs e)
{
string query = "Select * from Assets";
OleDbCommand cmd = new OleDbCommand(query, connection);
connection.Open();
OleDbDataReader read = cmd.ExecuteReader();
string data = "";
while (read.Read())
{
data += read[0].ToString() + " " + read[1].ToString() + " " + read[2].ToString() + "\n";
}
AssetData.Text = data;
connection.Close();
}
private void ViewEmployees_Click(object sender, RoutedEventArgs e)
{
string query = "Select * from Employees";
OleDbCommand cmd = new OleDbCommand(query, connection);
connection.Open();
OleDbDataReader read = cmd.ExecuteReader();
string data = "";
while (read.Read())
{
data += read[0].ToString() + " " + read[1].ToString() + " " + read[2].ToString() + "\n";
}
EmployeeData.Text = data;
connection.Close();
}
}
}
|
using System.Data.Entity;
using SoftUniStore.App.Model;
namespace SoftUniStore.App.Data
{
public class ExamWebContext : DbContext
{
public ExamWebContext()
: base("ExamWebContext")
{
}
public DbSet<Login> Logins { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Game> Games { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class POVCamera : MonoBehaviour
{
private float speed = 200;
public GameObject player;
public GameObject FocalPoint;
public GameObject fixedCam;
public GameObject pov;
bool fixedEnabled = true;
void Start()
{
}
// Update is called once per frame
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float vInput = Input.GetAxis("Vertical");
transform.Rotate(Vector3.up, horizontalInput * speed * Time.deltaTime);
transform.Rotate(Vector3.left, vInput * speed * Time.deltaTime);
transform.position = player.transform.position; // Move focal point with player
if (Input.GetKeyDown(KeyCode.Space))
{
print("happening");
player.GetComponent<Rigidbody>().AddForce(FocalPoint.transform.forward * 1 * speed * Time.deltaTime, ForceMode.Impulse);
}
if (Input.GetKeyDown(KeyCode.F))
{
print("butts");
print(fixedEnabled);
if (fixedEnabled)
{
pov.SetActive(true);
fixedCam.SetActive(false);
fixedEnabled = false;
}
else if (!fixedEnabled)
{
pov.SetActive(false);
fixedCam.SetActive(true);
fixedEnabled = true;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Optymalizacja_wykorzystania_pamieci.Tasks.Decision_Tree.Data_Structures;
namespace Optymalizacja_wykorzystania_pamieci.Tasks.Decision_Tree
{
class Decision_Tree
{
public Node root { get; set; }
public Decision_Tree()
{
this.root = new Node();
}
public static void TreeBuilding(Decision_Tree tree, Trees_Parameters parameters)
{
if (tree != null)
if (tree.root != null)
{
tree.root.ExtendNode();
}
}
public static void TreeBuildingWithAdditionalMemory(Decision_Tree tree, Trees_Parameters parameters)
{
if (tree != null)
if (tree.root != null)
{
tree.root.ExtendNodeWithAdditionalMemory();
}
}
public void ShowResults(Node node, int depth)
{
depth++;
if (node.node_left != null)
{
ShowResults(node.node_left, depth);
}
if(node != null)
{
for (int i = 1; i < depth; i++)
Console.Write("-----------");
Console.Write("Class: ");
foreach(Category c in node.data.categories)
{
Console.Write("{0} ", c.name);
}
Console.Write(" Cond: {0} | {1}", node.condition, node.number_of_feature);
Console.WriteLine();
}
if(node.node_right != null)
{
ShowResults(node.node_right, depth);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace NotepadBackEnd.MyFunction
{
public class FindNextResult
{
bool searchStatus;
int selectionStart;
public bool SearchStatus { get => searchStatus; set => searchStatus = value; }
public int SelectionStart { get => selectionStart; set => selectionStart = value; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class ShootingArea : MonoBehaviour
{
private BasePlayerController _moveController;
[SerializeField] private List<Enemy> _enemyList;
[Space]
[SerializeField] private BasePlayerController _shootController;
public event Action PlayerMissionCompleted;
private void OnEnable()
{
foreach (var enemy in _enemyList)
{
enemy.Hitted += OnEnemyHitted;
}
}
private void OnDisable()
{
foreach (var enemy in _enemyList)
{
enemy.Hitted -= OnEnemyHitted;
}
}
private void OnTriggerEnter(Collider other)
{
if (_enemyList.All(enemy => enemy.IsHit))
return;
var rb = other.attachedRigidbody;
if (rb == null)
return;
_moveController = rb.GetComponent<BasePlayerController>();
if (_moveController == null)
return;
_moveController.Disable();
_shootController.Enable();
}
public void Exit()
{
_shootController.Disable();
_moveController.Enable();
PlayerMissionCompleted?.Invoke();
}
private void OnEnemyHitted(Enemy hittedEnemy)
{
foreach (var enemy in _enemyList)
{
if (!enemy.IsHit)
return;
}
Exit();
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Appnotics.Library.UI.Helpers
{
public class XmlSerializerHelper<T>
{
public Type _type;
public XmlSerializerHelper()
{
_type = typeof(T);
}
public void Save(string path, object obj)
{
using (TextWriter textWriter = new StreamWriter(path))
{
XmlSerializer serializer = new XmlSerializer(_type);
serializer.Serialize(textWriter, obj);
}
}
public T Read(string path)
{
T result;
using (TextReader textReader = new StreamReader(path))
{
XmlSerializer deserializer = new XmlSerializer(_type);
result = (T)deserializer.Deserialize(textReader);
}
return result;
}
}
}
|
using System.Data;
/// <summary>
/// Summary description for FedCampGrantDA
/// </summary>
public class FedCampGrantDA
{
public static DataSet GetAllByFedID(int CampYearID, int FedID)
{
var db = new SQLDBAccess("CIPConnectionString");
db.AddParameter("@Action", "ByFedIdAndYearId");
db.AddParameter("@CampYearID", CampYearID);
db.AddParameter("@FedID", FedID);
return db.FillDataSet("usp_FedCampGrant");
}
} |
using System;
using System.Collections.Generic;
namespace CAPCO.Infrastructure.Domain
{
public class PriceCode : Entity
{
public virtual PickupLocation Location { get; set; }
public virtual DiscountCode DiscountCode { get; set; }
public string Code
{
get
{
if (Location != null && DiscountCode != null)
return String.Format("{0}{1}", Location.Code, DiscountCode.Code);
return null;
}
}
}
}
|
using System;
namespace NStandard
{
public static partial class ArrayExtensions
{
/// <summary>
/// Do action for each item of multidimensional array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="this"></param>
/// <param name="task"></param>
/// <returns></returns>
public static T[,] Each<T>(this T[,] @this, Action<T, int, int> task)
{
var stepper = new IndicesStepper(0, @this.GetLengths());
foreach (var (value, indices) in Any.Zip(@this.AsEnumerable<T>(), stepper))
{
task(value, indices[0], indices[1]);
}
return @this;
}
/// <summary>
/// Do action for each item of multidimensional array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="this"></param>
/// <param name="task"></param>
/// <returns></returns>
public static T[,,] Each<T>(this T[,,] @this, Action<T, int, int, int> task)
{
var stepper = new IndicesStepper(0, @this.GetLengths());
foreach (var (value, indices) in Any.Zip(@this.AsEnumerable<T>(), stepper))
{
task(value, indices[0], indices[1], indices[2]);
}
return @this;
}
/// <summary>
/// Do action for each item of multidimensional array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="this"></param>
/// <param name="task"></param>
/// <returns></returns>
public static Array Each<T>(this Array @this, Action<T, int[]> task)
{
var stepper = new IndicesStepper(0, @this.GetLengths());
foreach (var (value, indices) in Any.Zip(@this.AsEnumerable<T>(), stepper))
{
task(value, indices);
}
return @this;
}
}
}
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xero.Api.Core.Model;
using Xero.Api.Infrastructure.Interfaces;
using Xero.Api.Serialization;
using Xero.Api.Core.Model.Types;
using System.Reflection;
using System.IO;
namespace CoreTests.Integration.TaxRates
{
[TestFixture]
public class Deserialization
{
private IJsonObjectMapper _jsonMapper;
private IXmlObjectMapper _xmlMapper;
[TestFixtureSetUp]
public void SetUp()
{
_jsonMapper = new DefaultMapper();
_xmlMapper = new DefaultMapper();
}
[Test]
public void nullable_type_roundtrip_json()
{
var taxRate = createCreditNote();
var json = _jsonMapper.To(taxRate);
var deserialized = _jsonMapper.From<TaxRate>(json);
Assert.IsFalse(object.ReferenceEquals(taxRate, deserialized));
Assert.AreEqual(taxRate.Name, deserialized.Name);
Assert.AreEqual(taxRate.EffectiveRate, deserialized.EffectiveRate);
}
[Test]
public void nullable_type_roundtrip_xml()
{
var taxRate = createCreditNote();
var xml = _xmlMapper.To(taxRate);
var deserialized = _xmlMapper.From<TaxRate>(xml);
Assert.IsFalse(object.ReferenceEquals(taxRate, deserialized));
Assert.AreEqual(taxRate.Name, deserialized.Name);
Assert.AreEqual(taxRate.EffectiveRate, deserialized.EffectiveRate);
}
private static TaxRate createCreditNote()
{
return new TaxRate()
{
Name = Guid.NewGuid().ToString(),
EffectiveRate = 5,
};
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
namespace UnityStandardAssets.CrossPlatformInput
{
public class WormParticle : MonoBehaviour
{
public GameObject _user;
private void Start()
{
}
private void OnParticleCollision(GameObject playerObj)
{
if (playerObj.gameObject.tag == "Player" && playerObj.GetComponent<UnityChanControlScriptWithRgidBody>()._isStringed == false)
{
playerObj.GetComponent<UnityChanControlScriptWithRgidBody>().OnWormString();
}
if(this.gameObject.GetComponentInParent<PlayerTeamAI>() != null)//仲間の時
{
if (playerObj.gameObject.tag == "Enemy"){
playerObj.GetComponent<SkeletonStatus>()._isString = true;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace WebAppMedOffices.Models
{
[Table("Pacientes")]
public class Paciente
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[MaxLength(50, ErrorMessage = "El campo {0} puede contener un máximo de {1} caracteres")]
[Display(Name = "Nombre")]
public string Nombre { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[MaxLength(50, ErrorMessage = "El campo {0} puede contener un máximo de {1} caracteres")]
[Display(Name = "Apellido")]
public string Apellido { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[MaxLength(20, ErrorMessage = "El campo {0} puede contener un máximo de {1} caracteres")]
[Index("Consultorio_Nombre_Index", IsUnique = true)]
[Display(Name = "Documento")]
public string Documento { get; set; }
[Required(ErrorMessage = "Debes introducir una {0}")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Fecha de Nacimiento")]
public DateTime FechaNacimiento { get; set; }
[Required(ErrorMessage = "Debes introducir una {0}")]
[MaxLength(120, ErrorMessage = "El campo {0} puede contener un máximo de {1} caracteres")]
[Display(Name = "Dirección")]
public string Direccion { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[StringLength(30, ErrorMessage = "El campo {0} debe contener entre {2} y {1} caracteres", MinimumLength = 3)]
[DataType(DataType.PhoneNumber)]
[RegularExpression("^[0-9]*$", ErrorMessage = "No es un número de teléfono válido")]
[Display(Name = "Teléfono")]
public string Telefono { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[StringLength(30, ErrorMessage = "El campo {0} debe contener entre {2} y {1} caracteres", MinimumLength = 3)]
[DataType(DataType.PhoneNumber)]
[RegularExpression("^[0-9]*$", ErrorMessage = "No es un número de teléfono válido")]
[Display(Name = "Celular")]
public string Celular { get; set; }
[Display(Name = "Obra Social")]
public int? ObraSocialId { get; set; }
[StringLength(30, ErrorMessage = "El campo {0} debe contener entre {2} y {1} caracteres", MinimumLength = 3)]
[Display(Name = "Número de afiliado")]
public string NroAfiliado { get; set; }
[MaxLength(50, ErrorMessage = "El campo {0} puede contener un máximo de {1} caracteres")]
[Display(Name = "Contacto de Emergencia")]
public string NombreContactoEmergencia { get; set; }
[StringLength(30, ErrorMessage = "El campo {0} debe contener entre {2} y {1} caracteres", MinimumLength = 3)]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Teléfono de Emergencia")]
public string TelefonoContactoEmergencia { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[StringLength(30, ErrorMessage = "El campo {0} puede contener un máximo de {1} y un mínimo de {2} caracteres", MinimumLength = 3)]
[DataType(DataType.EmailAddress)]
[Display(Name = "E-mail")]
public string Mail { get; set; }
[Display(Name = "Nombre y Apellido")]
public virtual string NombreCompleto
{
get
{
return Nombre + " " + Apellido;
}
}
public virtual ObraSocial ObraSocial { get; set; }
public virtual ICollection<PacienteEnfermedad> Enfermedades { get; set; }
public virtual ICollection<Turno> Turnos { get; set; }
}
} |
using System;
namespace BrowseCake
{
using System.IO;
using System.Linq;
class Program
{
static void Main()
{
Console.WriteLine("Content-Type: text/html\r\n");
string htmlContent = File.ReadAllText("browseCake.html");
Console.WriteLine(htmlContent);
string getContent = Environment.GetEnvironmentVariable("QUERY_STRING");
string cakeName = getContent.Split('=')[1];
string[] databaseContent = File.ReadAllLines("database.csv");
var filtered = databaseContent.Where(s => s.Contains(cakeName));
foreach (var cake in filtered)
{
Console.WriteLine(cake);
}
}
}
}
|
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.TestHost;
using Xunit;
namespace TennisBookings.Web.IntegrationTests.Controllers
{
public class AdminHomeControllerTests : IClassFixture<CustomWebApplicationFactory<Startup>>
{
private readonly CustomWebApplicationFactory<Startup> _factory;
public AdminHomeControllerTests(CustomWebApplicationFactory<Startup> factory)
{
factory.ClientOptions.AllowAutoRedirect = false;
_factory = factory;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hose : MonoBehaviour
{
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.GetComponent<Enemy>())
{
var dir=(collision.transform.position - transform.position).normalized;
dir.y = 0.2f;
collision.gameObject.GetComponent<Rigidbody>().AddForce(dir*20, ForceMode.Impulse);
}
}
}
|
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Services;
using System.Threading.Tasks;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice.Edit;
namespace SFA.DAS.ProviderCommitments.Web.Mappers
{
public class BaseApprenticeshipRequestFromEditApprenticeshipCourseViewModelMapper : IMapper<EditApprenticeshipCourseViewModel, BaseApprenticeshipRequest>
{
private readonly ITempDataStorageService _tempData;
private const string ViewModelForEdit = "ViewModelForEdit";
public BaseApprenticeshipRequestFromEditApprenticeshipCourseViewModelMapper(ITempDataStorageService tempData)
{
_tempData = tempData;
}
public async Task<BaseApprenticeshipRequest> Map(EditApprenticeshipCourseViewModel source)
{
var data = _tempData.RetrieveFromCache<EditApprenticeshipRequestViewModel>(ViewModelForEdit);
data.CourseCode = source.CourseCode;
_tempData.AddToCache(data, ViewModelForEdit);
return new BaseApprenticeshipRequest
{
ApprenticeshipHashedId = data.ApprenticeshipHashedId,
ProviderId = data.ProviderId
};
}
}
}
|
using GeoAPI.Extensions.Feature;
using GisSharpBlog.NetTopologySuite.Geometries;
using NUnit.Framework;
using SharpMap.Data;
namespace SharpMap.Tests.Data
{
[TestFixture]
public class FeatureDataSetTest
{
[Test]
public void GetSetAttributesViaIFeature()
{
var featureTable = new FeatureDataTable();
featureTable.Columns.Add("name", typeof (string));
featureTable.Columns.Add("attribute1", typeof(int));
var feature1 = featureTable.NewRow();
feature1.Geometry = new Point(0, 0);
feature1["name"] = "feature1";
feature1["attribute1"] = 1;
featureTable.Rows.Add(feature1);
// now access it using IFeature iterfaces
IFeature f1 = feature1;
f1.Attributes.Count
.Should().Be.EqualTo(2);
f1.Attributes.Keys
.Should().Have.SameSequenceAs(new[] {"name", "attribute1"});
f1.Attributes["name"]
.Should().Be.EqualTo("feature1");
f1.Attributes["attribute1"]
.Should().Be.EqualTo(1);
}
}
} |
using InspectorServices.Domain.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace InspectorServices.SqlDataAccess.Configs
{
public class InspectionConfig : IEntityTypeConfiguration<Inspection>
{
public void Configure(EntityTypeBuilder<Inspection> builder)
{
builder.ToTable("Inspection");
builder.Property(m => m.Id).HasColumnName("Id");
builder.Property(m => m.Customer).HasColumnName("Customer");
builder.Property(m => m.Date).HasColumnName("Date")
.HasConversion<string>();
builder.Property(m => m.Observations).HasColumnName("Observations");
builder.Property(m => m.InspectorId).HasColumnName("InspectorId");
builder.Property(m => m.Status).HasColumnName("Status")
.HasConversion<int>();
builder.HasKey(a => a.Id);
}
}
}
|
using Microsoft.EntityFrameworkCore;
using SP_Medical_Grup.WebApi.Contexts;
using SP_Medical_Grup.WebApi.Domains;
using SP_Medical_Grup.WebApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SP_Medical_Grup.WebApi.Repositories
{
public class ConsultaRepository : IConsultaRepository
{
SpMedGrupContext ctx = new SpMedGrupContext();
public void Atualizar(int id, Consulta consultaAtualizada)
{
Consulta consultaBuscada = ctx.Consultas.Find(id);
if (consultaBuscada != null)
{
consultaBuscada.IdPaciente = consultaAtualizada.IdPaciente;
consultaBuscada.IdMedico = consultaAtualizada.IdMedico;
consultaBuscada.DataConsulta = consultaAtualizada.DataConsulta;
}
ctx.Consultas.Update(consultaBuscada);
ctx.SaveChanges();
}
public Consulta BuscarPorId(int id)
{
return ctx.Consultas.FirstOrDefault(c => c.IdConsulta == id);
}
public void Cadastrar(Consulta novaConsulta)
{
novaConsulta.Situacao = "Aguardando confirmação do agendamento";
ctx.Consultas.Add(novaConsulta);
ctx.SaveChanges();
}
public void Confirmação(int id, string status)
{
Consulta consultaBuscada = ctx.Consultas
.Include(c => c.IdMedicoNavigation)
.Include(c => c.IdPacienteNavigation)
.FirstOrDefault(c => c.IdConsulta == id);
switch (status)
{
case "1":
consultaBuscada.Situacao = "Agendada";
break;
case "2":
consultaBuscada.Situacao = "Realizada";
break;
default:
consultaBuscada.Situacao = consultaBuscada.Situacao;
break;
}
ctx.Consultas.Update(consultaBuscada);
ctx.SaveChanges();
}
public void Deletar(int id)
{
Consulta consultaBuscada = ctx.Consultas.Find(id);
ctx.Consultas.Remove(consultaBuscada);
ctx.SaveChanges();
}
public List<Consulta> Listar()
{
return ctx.Consultas
.Include(c => c.IdMedicoNavigation)
.Include(c => c.IdPacienteNavigation)
.Include(c => c.IdMedicoNavigation.IdEspecialidadeNavigation)
.Include(c => c.IdPacienteNavigation.IdUsuarioNavigation)
.Include(c => c.IdMedicoNavigation.IdUsuarioNavigation)
.Select(c => new Consulta
{
IdConsulta = c.IdConsulta,
DataConsulta = c.DataConsulta,
Situacao = c.Situacao,
Descricao = c.Descricao,
IdMedicoNavigation = new Medico
{
IdMedico = c.IdMedicoNavigation.IdMedico,
IdUsuario = c.IdMedicoNavigation.IdUsuario,
Crm = c.IdMedicoNavigation.Crm,
IdUsuarioNavigation = new Usuario
{
IdUsuario = c.IdMedicoNavigation.IdUsuarioNavigation.IdUsuario,
Nome = c.IdMedicoNavigation.IdUsuarioNavigation.Nome,
},
IdEspecialidadeNavigation = new Especialidade
{
IdEspecialidade = c.IdMedicoNavigation.IdEspecialidadeNavigation.IdEspecialidade,
TituloEspecialidade = c.IdMedicoNavigation.IdEspecialidadeNavigation.TituloEspecialidade,
},
},
IdPacienteNavigation = new Paciente
{
IdPaciente = c.IdPacienteNavigation.IdPaciente,
IdUsuario = c.IdPacienteNavigation.IdUsuario,
IdUsuarioNavigation = new Usuario
{
IdUsuario = c.IdPacienteNavigation.IdUsuarioNavigation.IdUsuario,
Nome = c.IdPacienteNavigation.IdUsuarioNavigation.Nome,
},
},
}).ToList();
}
public List<Consulta> ListarMinhasConsultas(int id)
{
return ctx.Consultas
.Include(c => c.IdMedicoNavigation)
.Include(c => c.IdPacienteNavigation)
.Include(c => c.IdMedicoNavigation.IdEspecialidadeNavigation)
.Include(c => c.IdPacienteNavigation.IdUsuarioNavigation)
.Include(c => c.IdMedicoNavigation.IdUsuarioNavigation)
.Select(c => new Consulta
{
IdConsulta = c.IdConsulta,
DataConsulta = c.DataConsulta,
Situacao = c.Situacao,
Descricao = c.Descricao,
IdMedicoNavigation = new Medico
{
IdMedico = c.IdMedicoNavigation.IdMedico,
IdUsuario = c.IdMedicoNavigation.IdUsuario,
Crm = c.IdMedicoNavigation.Crm,
IdUsuarioNavigation = new Usuario
{
IdUsuario = c.IdMedicoNavigation.IdUsuarioNavigation.IdUsuario,
Nome = c.IdMedicoNavigation.IdUsuarioNavigation.Nome,
},
IdEspecialidadeNavigation = new Especialidade
{
IdEspecialidade = c.IdMedicoNavigation.IdEspecialidadeNavigation.IdEspecialidade,
TituloEspecialidade = c.IdMedicoNavigation.IdEspecialidadeNavigation.TituloEspecialidade,
},
},
IdPacienteNavigation = new Paciente
{
IdPaciente = c.IdPacienteNavigation.IdPaciente,
IdUsuario = c.IdPacienteNavigation.IdUsuario,
IdUsuarioNavigation = new Usuario
{
IdUsuario = c.IdPacienteNavigation.IdUsuarioNavigation.IdUsuario,
Nome = c.IdPacienteNavigation.IdUsuarioNavigation.Nome,
},
},
}).Where(c => c.IdPacienteNavigation.IdUsuario == id || c.IdMedicoNavigation.IdUsuario == id).ToList();
}
public void Prontuario(int id, string descricao)
{
Consulta consultaBuscada = BuscarPorId(id);
if (consultaBuscada != null)
{
consultaBuscada.Descricao = descricao;
}
ctx.Consultas.Update(consultaBuscada);
ctx.SaveChanges();
}
}
}
|
using AbstractFactory2.Framework;
using System;
using System.Collections.Generic;
using System.Text;
namespace AbstractFactory2.Drivers
{
class LowPrinterDevice : PrinterDevice
{
public override PrinterSpec GetPrinterSpec()
{
return PrinterSpec.Low;
}
public override string ToString()
{
return "Low Printer Device";
}
}
}
|
using AIMLbot.Utils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AIMLbot.UnitTest.Normalize
{
[TestClass]
public class SplitIntoSentencesTests
{
private readonly string[] _goodResult =
{
"This is sentence 1", "This is sentence 2", "This is sentence 3",
"This is sentence 4"
};
private const string RawInput = "This is sentence 1. This is sentence 2! This is sentence 3; This is sentence 4?";
[TestInitialize]
public void Setup()
{
}
[TestMethod]
public void TestSplitterAllMadeFromWhiteSpace()
{
var result = " ".SplitStrings();
Assert.IsInstanceOfType(result, typeof(string[]));
Assert.IsTrue(result.Length == 0);
}
[TestMethod]
public void TestSplitterAllNoRawInput()
{
var result = "".SplitStrings();
Assert.IsInstanceOfType(result, typeof(string[]));
Assert.IsTrue(result.Length == 0);
}
[TestMethod]
public void TestSplitterAllNoSentenceToSplit()
{
var result = "This is a sentence without splitters".SplitStrings();
Assert.AreEqual("This is a sentence without splitters", result[0]);
}
[TestMethod]
public void TestSplitterAllSentenceMadeOfSplitters()
{
var result = "!?.;".SplitStrings();
Assert.IsInstanceOfType(result, typeof(string[]));
Assert.IsTrue(result.Length == 0);
}
[TestMethod]
public void TestSplitterAllSentenceWithSplitterAtEnd()
{
var result = "This is a sentence without splitters.".SplitStrings();
Assert.AreEqual("This is a sentence without splitters", result[0]);
}
[TestMethod]
public void TestSplitterAllSentenceWithSplitterAtStart()
{
var result = ".This is a sentence without splitters".SplitStrings();
Assert.AreEqual("This is a sentence without splitters", result[0]);
}
[TestMethod]
public void TestSplitterAllTokensPassedByMethod()
{
var result = RawInput.SplitStrings();
for (var i = 0; i < _goodResult.Length; i++)
{
Assert.AreEqual(_goodResult[i], result[i]);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Impulso : MonoBehaviour {
public Resortera _touchGlobal;
public GameObject _flecha;
public Rigidbody2D _rb;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void FixedUpdate ()
{
if (!_touchGlobal.canDrag)
{
_rb.constraints = ~RigidbodyConstraints2D.FreezePosition;
_rb.gravityScale = 1.3f;
_rb.AddForce(-_flecha.transform.up * 500);
_touchGlobal.canDrag = true;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "wall")
{
_rb.constraints = ~RigidbodyConstraints2D.FreezePositionX;
_rb.gravityScale = 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace Donnee
{
/// <summary>
/// Cette classe permet la connexion a la base de donnée
/// </summary>
public class CADClass
{
private string cnx;
private string SQLRequest;
private SqlDataAdapter dataAdaptater;
private SqlConnection connection;
private SqlCommand command;
private DataSet data;
//constructeur
public CADClass()
{
this.cnx = @"Data Source=DESKTOP-KA3MQL1\SQLEXPRESS;Initial Catalog=RedX;Integrated Security=True";
this.SQLRequest = null;
this.connection = new SqlConnection(this.cnx);
this.dataAdaptater = null;
this.command = null;
this.data = new DataSet();
}
//fonction pour requetes d'actions
public void ActionRows(string SQLRequest)
{
this.data = new DataSet();
this.SQLRequest = SQLRequest;
this.command = new SqlCommand(this.SQLRequest, this.connection);
this.dataAdaptater = new SqlDataAdapter(this.command);
this.dataAdaptater.Fill(this.data, "rows");
}
//fonction pour requetes de récupération de données
public DataSet getRows(string SQLRequest)
{
this.data.Clear();
this.SQLRequest = SQLRequest;
this.command = new SqlCommand(this.SQLRequest, this.connection);
this.connection.Open();
this.dataAdaptater = new SqlDataAdapter(this.command);
this.dataAdaptater.Fill(this.data, "rows");
connection.Close();
return this.data;
}
}
} |
using Restaurants.Domain;
using System;
using System.Collections.Generic;
using System.Text;
namespace Restaurants.Application
{
public class ReviewAppService : AppServiceBase<Review>, IReviewAppService
{
private readonly IReviewService _appService;
public ReviewAppService(IReviewService appService) : base(appService)
{
_appService = appService;
}
}
}
|
using System.Collections.Generic;
namespace Profiling2.Domain.Contracts.Search
{
/// <summary>
/// Implementing components must be manually registered in ComponentRegistrar class.
/// </summary>
/// <typeparam name="E"></typeparam>
public interface ILuceneIndexer<E>
{
/// <summary>
/// Add a single entity to Lucene index. Commits IndexWriter after adding.
/// </summary>
/// <param name="entity"></param>
void Add<T>(T entity);
/// <summary>
/// Add multiple entities to Lucene index. Commits IndexWriter after adding.
/// </summary>
/// <param name="multiple"></param>
void AddMultiple<T>(IEnumerable<T> multiple);
/// <summary>
/// Delete entire Lucene index.
/// </summary>
void DeleteIndex();
/// <summary>
/// Delete single entity from Lucene index.
/// TODO do we need to catch OutOfMemoryException and close the writer, according to comment in IndexWriter.DeleteDocuments()?
/// </summary>
/// <param name="id"></param>
void Delete<T>(int id);
/// <summary>
/// Delete and add an entity to the Lucene index (no true 'update' exists in Lucene).
/// </summary>
/// <param name="entity"></param>
void Update<T>(T entity);
}
}
|
using System;
using System.Threading.Tasks;
namespace sma
{
class Program
{
static async Task Main(string[] args)
{
TimeSpan smaDuration = TimeSpan.FromSeconds(3);
SMA sma = new SMA(11, smaDuration);
Random rand = new Random();
DateTimeOffset lastWait = DateTimeOffset.UtcNow;
while (true)
{
int addend = rand.Next(100) + 1;
Console.WriteLine($"Adding {addend}");
sma.IncrementCurrentBucket(addend);
Console.Write("Buckets: ");
foreach (int bucket in sma._tracker.Buckets)
{
Console.Write($"{bucket} ");
}
Console.WriteLine();
Console.WriteLine($"SMA: {sma.GetLatestAverage()}");
await Task.Delay(500);
if (DateTimeOffset.UtcNow - lastWait > 5 * smaDuration)
{
lastWait = DateTimeOffset.UtcNow;
TimeSpan delay = 2 * smaDuration + TimeSpan.FromMilliseconds(100);
Console.WriteLine($"Waiting {delay.TotalMilliseconds} ms");
//
// Demonstrate dead intervals
await Task.Delay(delay);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Otiport.API.Contract.Request.ProfileItems
{
public class DeleteProfileItemRequest : RequestBase
{
public int ProfileItemId { get; set; }
}
}
|
namespace ZoomitTest.Model
{
public class Rule
{
public string Url { get; set; }
public long Limit { get; set; }
public long Duration { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace WziumStars.Models
{
public class OrderDetails
{
[Key]
public int Id { get; set; }
[Required]
public int OrderId { get; set; }
[ForeignKey("OrderId")]
public virtual OrderHeader OrderHeader { get; set; }
[Required]
public int ProduktId { get; set; }
[ForeignKey("ProduktId")]
public virtual Produkt Produkt { get; set; }
[Display(Name = "Ilość")]
public int Count { get; set; }
[Display(Name = "Nazwa")]
public string Name { get; set; }
[Required]
[Display(Name = "Cena")]
public double Price { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Interface
{
class Batman:SuperHeroi
{
public override void ObterDados()
{
this.NomeFicticio = "Batman";
this.Identidade = "Bruce Wayne";
this.Cidade = "Gothan";
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _7DRL_2021
{
class ActActionNew
{
public Action<TextBuilder> Text;
public Action Action = () => { };
public Func<bool> Enabled = () => true;
public ActActionNew(Action<TextBuilder> text, Action action = null, Func<bool> enabled = null)
{
Text = text;
if (action != null)
Action = action;
if (enabled != null)
Enabled = enabled;
}
public virtual void Slide(int n)
{
}
}
class MenuActNew : Menu
{
public override FontRenderer FontRenderer => Scene.FontRenderer;
Scene Scene;
LabelledUI UI;
TextBuilder Text;
public Vector2 Position;
List<ActActionNew> Actions = new List<ActActionNew>();
Dictionary<int, MenuAreaText> SelectionAreas = new Dictionary<int, MenuAreaText>();
public int Selection;
public int SelectionCount => Actions.Count;
public LerpFloat Scroll = new LerpFloat(0);
int SlideCount;
public int DefaultSelection = -1;
bool Dirty = true;
protected override IEnumerable<IMenuArea> MenuAreas => Text.MenuAreas;
public TextFormatting FormatDescription = new TextFormatting()
{
GetParams = (pos) => new DialogParams()
{
Scale = Vector2.One,
Color = Color.DarkGray,
Border = Color.Black,
}
};
public MenuActNew(Scene scene, Action<TextBuilder> name, Vector2 position, SpriteReference label, SpriteReference ui, int width, int height)
{
Scene = scene;
Position = position;
Width = width;
Height = height;
UI = new LabelledUI(label, ui, name, () => new Point(Width, Height));
Init();
}
private void Init()
{
var cursor = SpriteLoader.Instance.AddSprite("content/cursor");
Text = new TextBuilder(Width, float.MaxValue);
int index = 0;
foreach(var action in Actions)
{
Text.StartTableRow(Width, new ColumnConfigs(new IColumnWidth[] {
new ColumnFixedWidth(16, true),
new ColumnFixedWidth(0, false),
new ColumnFixedWidth(16, true),
}) { Padding = 0 });
Text.StartTableCell();
Text.AppendElement(new TextElementCursor(cursor, 16, 16, () => IsSelected(action)));
Text.EndTableCell();
Text.StartTableCell();
action.Text(Text);
Text.EndTableCell();
Text.StartTableCell();
Text.EndTableCell();
var row = Text.EndTableRow();
var selectionArea = new MenuAreaText(Text, 0, null);
selectionArea.Add(row);
SelectionAreas.Add(index, selectionArea);
index++;
}
Text.EndContainer();
Text.Finish();
Dirty = false;
}
private bool IsSelected(ActActionNew action)
{
return Actions[Selection] == action;
}
public void Add(ActActionNew action)
{
Actions.Add(action);
Dirty = true;
}
public void AddDefault(ActActionNew action)
{
DefaultSelection = Actions.Count;
Add(action);
}
public void Select(int selection)
{
if (Actions[selection].Enabled())
Actions[selection].Action();
}
public void Slide(int selection, int slide)
{
if (Actions[selection].Enabled())
Actions[selection].Slide(slide);
}
public override void Update(Scene scene)
{
base.Update(scene);
Scroll.Update();
if (Dirty)
{
Init();
}
}
public override void HandleInput(Scene scene)
{
base.HandleInput(scene);
if (InputBlocked)
return;
if (scene.InputState.IsKeyPressed(Keys.Enter) && Selection < SelectionCount)
Select(Selection);
if (scene.InputState.IsKeyPressed(Keys.Escape) && DefaultSelection >= 0)
Select(DefaultSelection);
if (scene.InputState.IsKeyPressed(Keys.W, 15, 5))
Selection--;
if (scene.InputState.IsKeyPressed(Keys.S, 15, 5))
Selection++;
HandleSlide(scene);
Selection = SelectionCount <= 0 ? 0 : (Selection + SelectionCount) % SelectionCount;
UpdateScroll();
//Scroll = MathHelper.Clamp(Scroll, Math.Max(0, Selection * LineHeight - Height + LineHeight), Math.Min(Selection * LineHeight, SelectionCount * LineHeight - Height));
}
public void HandleSlide(Scene scene)
{
bool left = scene.InputState.IsKeyPressed(Keys.A, 15, 5);
bool right = scene.InputState.IsKeyPressed(Keys.D, 15, 5);
//Either key is released or both are down at the same time, set counter to 0;
if (scene.InputState.IsKeyReleased(Keys.A) || scene.InputState.IsKeyReleased(Keys.D) || (scene.InputState.IsKeyDown(Keys.A) && scene.InputState.IsKeyDown(Keys.D)))
{
SlideCount = 0;
}
else if (left)
{
SlideCount--;
Slide(Selection, SlideCount);
}
else if (right)
{
SlideCount++;
Slide(Selection, SlideCount);
}
}
public void UpdateScroll()
{
if (SelectionAreas.Empty())
return;
var currentTop = SelectionAreas[Selection].GetTop();
var currentBottom = SelectionAreas[Selection].GetBottom();
if (currentTop < Scroll)
{
Scroll.Set(currentTop, LerpHelper.Linear, 5);
}
if (currentBottom > Scroll + Height)
{
Scroll.Set(currentBottom - Height, LerpHelper.Linear, 5);
}
}
public override void PreDraw(Scene scene)
{
base.PreDraw(scene);
scene.PushSpriteBatch(blendState: scene.NonPremultiplied, samplerState: SamplerState.PointWrap, projection: Projection);
scene.GraphicsDevice.Clear(Color.TransparentBlack);
Text.Draw(new Vector2(0, -Scroll), FontRenderer);
scene.PopSpriteBatch();
}
public override void Draw(Scene scene)
{
int x = (int)Position.X - Width / 2;
int y = (int)Position.Y - Height / 2;
float openCoeff = Math.Min(Ticks / 7f, 1f);
UI.Draw(FontRenderer, x, y, openCoeff);
if (openCoeff >= 1)
{
scene.SpriteBatch.Draw(RenderTarget, new Rectangle(x, y, RenderTarget.Width, RenderTarget.Height), RenderTarget.Bounds, Color.White);
}
}
}
}
|
namespace SubC.Attachments {
public enum RigidbodyRestoreBehavior {
DoNothing = 0,
Desimulate = 1,
Destroy = 2,
Restore = 3,
SetDynamic = 4,
SetKinematic = 5
}
[System.Serializable]
public struct SnapshotRestoreOptions {
public RigidbodyRestoreBehavior rigidbodyBehavior;
public bool restorePosition;
public bool restoreRotation;
public bool restoreScale;
public bool restoreLayer;
public bool restoreSortingOrder;
public bool restoreFlipX;
public bool restoreFlipY;
public MoveMethod moveMethod;
public RotateMethod rotateMethod;
public TweenOptions tweenPositionOptions, tweenRotationOptions;
public void Reset() {
tweenPositionOptions.Reset();
tweenRotationOptions.Reset();
}
}
} |
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Input;
using UdpSimulator.Components;
namespace UdpSimulator.Models
{
/// <summary>
/// UDP送信処理 DataContext対応用インターフェース.
/// </summary>
public interface IUdpTransmitter : INotifyPropertyChanged
{
bool Connected { get; set; }
string DestinationIpAddress { get; set; }
int DestinationPort { get; set; }
int TransmissionInterval { get; set; }
IEnumerable<SimulationObject> SimulationObjects { get; }
ICommand CommandConnection { get; }
ICommand CommandSaveObjects { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace Crystal.Plot2D.Charts
{
public class GenericLocationalLabelProvider<TItem, TAxis> : LabelProviderBase<TAxis>
{
private readonly IList<TItem> collection;
private readonly Func<TItem, string> displayMemberMapping;
public GenericLocationalLabelProvider(IList<TItem> collection, Func<TItem, string> displayMemberMapping)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
if (displayMemberMapping == null)
{
throw new ArgumentNullException("displayMemberMapping");
}
this.collection = collection;
this.displayMemberMapping = displayMemberMapping;
}
int startIndex;
public override UIElement[] CreateLabels(ITicksInfo<TAxis> ticksInfo)
{
var ticks = ticksInfo.Ticks;
if (ticks.Length == 0)
{
return EmptyLabelsArray;
}
startIndex = (int)ticksInfo.Info;
UIElement[] result = new UIElement[ticks.Length];
LabelTickInfo<TAxis> labelInfo = new() { Info = ticksInfo.Info };
for (int i = 0; i < result.Length; i++)
{
var tick = ticks[i];
labelInfo.Tick = tick;
labelInfo.Index = i;
string labelText = GetString(labelInfo);
TextBlock label = new() { Text = labelText };
ApplyCustomView(labelInfo, label);
result[i] = label;
}
return result;
}
protected override string GetStringCore(LabelTickInfo<TAxis> tickInfo)
{
return displayMemberMapping(collection[tickInfo.Index + startIndex]);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalendarApp.Model
{
public class CalendarModel
{
public CalendarModel(int year, int monthNumber)
{
CalendarMonth = new CalendarMonthModel(monthNumber, year);
}
public CalendarMonthModel CalendarMonth
{
get; set;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Program : Cylinder
/// @author : Taekyung Kil
/// Date : 04/Oct/2019
///
/// Purpose : To set the class of Cylinder
///
/// I, Taekyung Kil, student number 000799798 , certify that all code submitted is my own work;
/// that I have not copied it from any other source.
/// I also certify that I have not allowed my work to be copied by others.
/// </summary>
namespace Lab2A
{
public class Cylinder : ThreeDimensional
{
private double radiusOfCylinder; // Backing variable
public double RadiusOfCylinder
{
get
{
return radiusOfCylinder; // return baking variable
}
set // set the backing variable with the data validation.
{
if (value < 0 || value > 100)
throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(value)} must be < 100 or > 0");
else
radiusOfCylinder = value;
}
}
private double heightOfCylinder; // Backing variable
public double HeightOfCylinder
{
get
{
return heightOfCylinder; // return baking variable
}
set // set the backing variable with the data validation.
{
if (value < 0 || value > 100)
throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(value)} must be < 100 or > 0");
else
heightOfCylinder = value;
}
}
/// <summary>
/// Set the type into Cylinder
/// To create Cylinder object with radius and height
/// </summary>
/// <param name="radiusOfCylinder"></param>
/// <param name="heightOfCylinder"></param>
public Cylinder(double radiusOfCylinder, double heightOfCylinder)
{
Type = "Cylinder";
RadiusOfCylinder = radiusOfCylinder;
HeightOfCylinder = heightOfCylinder;
}
/// <summary>
/// To calcualate the surface area of this object
/// </summary>
/// <returns>double</returns>
public override double CalculateArea() => (((double)2 * PI * radiusOfCylinder * radiusOfCylinder) + ((double)2 * PI * radiusOfCylinder * heightOfCylinder));
/// <summary>
/// To calculate the volume of this object
/// </summary>
/// <returns>double</returns>
public override double CalculateVolume() => (PI * radiusOfCylinder * radiusOfCylinder * heightOfCylinder);
/// <summary>
/// To print out all variables and the area of this object.
/// </summary>
/// <returns>Type,radiusOfCylinder, heightOfCylinder, CalculateArea(), CalculateVolume() </returns>
public override string ToString()
{
return $"[TYPE = {Type}], Radius : {radiusOfCylinder} , Height : {heightOfCylinder} , Surface Area : {CalculateArea()} , Volume : {CalculateVolume()}";
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace SuperMarket
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var today = DateTime.Now;
label11.Text = today.Date.ToString("d");
}
class MasterDetail
{
public string contactName { get; set; }
public string companyName { get; set; }
public string city;
public string cityp // property
{
get { return city; } // get method
set { city = value; } // set method
}
public string country { get; set; }
public MasterDetail(string contactN, string companyN, string CityN, string countryN)
{
contactName = contactN;
companyName = companyN;
country = countryN;
city = CityN;
}
}
public static int count = 0;
List<MasterDetail> masterItem = new List<MasterDetail>();
private void button1_Click(object sender, EventArgs e)
{
MasterDetail master = new MasterDetail(textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
masterItem.Add(master);
//Console.WriteLine(masterItem[0].contactName);
dataGridView1.Rows.Clear();
List<MasterDetail> SortedList = masterItem.OrderBy(o => o.companyName).ToList();
for (int i = 0; i < SortedList.Count; i++)
{
dataGridView1.Rows.Add(SortedList[i].contactName, SortedList[i].companyName, SortedList[i].city, SortedList[i].country);
}
comboBox1.Items.Add(masterItem[count].companyName);
count++;
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
MessageBox.Show("New entry added");
}
public static int id = 100;
class OrderDetail
{
public int orderId { get; set; }
public DateTime date;
public string productName { get; set; }
public string company;
public int quantity { get; set; }
public double price { get; set; }
public string total { get; set; }
public OrderDetail(string productN, string companyN, int quantityO, double unitP)
{
orderId = id++;
date = DateTime.Now;
company = companyN;
productName = productN;
quantity = quantityO;
price = unitP;
total = "Rs. " + quantity * price + "/-";
}
}
List<OrderDetail> orderItem = new List<OrderDetail>();
public static int orderCount = 0;
private void button2_Click(object sender, EventArgs e)
{
OrderDetail order = new OrderDetail(textBox5.Text, comboBox1.SelectedItem + "", int.Parse(textBox7.Text), double.Parse(textBox8.Text));
orderItem.Add(order);
/*List<OrderDetail> SortedList = orderItem.OrderBy(o => o.company).ToList();
for (int i = 0; i < SortedList.Count; i++)
{
dataGridView2.Rows.Add(SortedList[i].orderId, SortedList[i].date, SortedList[i].productName, SortedList[i].quantity, SortedList[i].price, SortedList[i].total);
}*/
label10.Text = id + "";
label11.Text = DateTime.Now.Date.ToString("d") + "";
textBox7.Text = "";
textBox8.Text = "";
textBox5.Text = "";
MessageBox.Show($"New entry added\nTotal={orderItem[orderCount].total}");
orderCount++;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView2.Visible == true)
dataGridView2.Visible = false;
else
{
dataGridView2.Visible = true;
List<OrderDetail> SortedList = orderItem.OrderBy(o => o.company).ToList();
dataGridView2.Rows.Clear();
var com = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["Column4"].Value.ToString();
foreach (var p in SortedList)
{
Console.WriteLine("Company " + p.company + "name " + com);
if (p.company.Equals(com))
{
//Console.WriteLine("true");
dataGridView2.Rows.Add(p.orderId, p.date, p.company,p.productName, p.quantity, p.price, p.total);
}
else continue;
}
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BanSupport
{
/// <summary>
/// 用于文字上显示倒计时
/// </summary>
public class TextCountDownWidget : TimeWidget
{
/// <summary>
/// 使用的格式
/// </summary>
public class Format : IDisposable
{
public static List<char> KEY = new List<char> { 'd', 'h', 'm', 's' };
public static int[] KEY_UNIT_REVERSE = new int[] { 60, 60, 24 };//多少个秒组成分,多少个分组成时,多少个时组成一天
public int index;
public string formatStr;
private List<string> replacement;
public Format(string formatStr)
{
this.formatStr = formatStr;
//检查这个格式对应的Index
this.index = int.MaxValue;
bool indexMatched = false;
for (int i = 0; i < KEY.Count; i++)
{
if (formatStr.Contains(KEY[i].ToString()))
{
this.index = i;
indexMatched = true;
break;
}
}
if (!indexMatched)
{
Debug.LogError("wrong format :" + formatStr);
}
//Get replacement
this.replacement = ListPool<string>.Get();
var curKey = "";
for (int i = 0; i < formatStr.Length; i++)
{
char c = formatStr[i];
//连接
if (curKey == "")
{
if (KEY.Contains(c))
{
curKey += c;
}
}
else if (curKey[0] == c)
{
curKey += c;
}
//截断
if (curKey != "" && ((i == formatStr.Length - 1) || (curKey[0] != c)))
{
if (!replacement.Contains(curKey))
{
replacement.Add(curKey);
}
curKey = "";
}
}
}
public string GetTime(List<int> numbers)
{
string result = formatStr;
foreach (var str in replacement)
{
int curNumber = numbers[KEY.IndexOf(str[0])];
result = result.Replace(str, curNumber.ToString("D" + str.Length));
}
return result;
}
public void Dispose()
{
ListPool<string>.Release(this.replacement);
this.replacement = null;
}
}
private int lastLeftSeconds;
private List<int> numbers;
private int minFormatIndex;//用于处理比如格式只有秒的话,那么这个秒可以用于表示全部时间
private List<Format> formats;
private TextEx textEx;
public TextCountDownWidget(TextEx textEx, float time, string[] formatStrs, Action completeAction, bool timeScaleEnable) :
base(textEx, completeAction, time, timeScaleEnable)
{
this.lastLeftSeconds = int.MaxValue;
this.numbers = ListPool<int>.Get();
for (int i = 0; i < Format.KEY.Count; i++)
{
this.numbers.Add(0);
}
this.minFormatIndex = int.MaxValue;
this.formats = ListPool<Format>.Get();
for (int i = 0; i < formatStrs.Length; i++)
{
var aFormat = new Format(formatStrs[i]);
if (this.minFormatIndex > aFormat.index)
{
this.minFormatIndex = aFormat.index;
}
this.formats.Add(aFormat);
}
this.textEx = textEx;
}
public override void Dispose()
{
base.Dispose();
//release number
ListPool<int>.Release(this.numbers);
this.numbers = null;
//release formats
foreach (var aFormat in this.formats)
{
aFormat.Dispose();
}
ListPool<Format>.Release(this.formats);
this.formats = null;
}
public override bool OnUpdate()
{
base.UpdateTime();
int leftSeconds = this.GetLeftSeconds();
if (this.lastLeftSeconds != leftSeconds)
{
this.lastLeftSeconds = leftSeconds;
ParseTime(this.lastLeftSeconds);
}
return base.OnUpdate();
}
private void ParseTime(int totalSeconds)
{
for (int i = 0; i < numbers.Count; i++)
{
var numberIndex = numbers.Count - 1 - i;
if (i < Format.KEY_UNIT_REVERSE.Length && this.minFormatIndex < numberIndex)
{
numbers[numberIndex] = totalSeconds % Format.KEY_UNIT_REVERSE[i];
totalSeconds /= Format.KEY_UNIT_REVERSE[i];
}
else
{
numbers[numberIndex] = totalSeconds;
totalSeconds = 0;
}
}
//查看哪个格式被匹配了
int formatIndex = -1;
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] > 0)
{
for (int j = 0; j < formats.Count; j++)
{
var curFormat = formats[j];
if (curFormat.index == i)
{
formatIndex = j;
break;
}
}
}
if (formatIndex >= 0) { break; }
}
if (formatIndex < 0) { formatIndex += formats.Count; }
var finalStr = this.formats[formatIndex].GetTime(this.numbers);
this.textEx?.SetTextValue(finalStr);
}
}
} |
using Microsoft.Extensions.DependencyInjection;
namespace MazeApp
{
internal static class Program
{
private static void Main()
{
var serviceCollection = new ServiceCollection(); // create new ServiceCollection object
serviceCollection.AddSingleton<IMazeSolver, MazeSolver>(); // add MazeSolver class to service collection and include the interface
serviceCollection.AddSingleton<IMazeCreator, MazeCreator>();
var serviceProvider = serviceCollection.BuildServiceProvider(); // build the service provider
var mazeSolver = serviceProvider.GetService<IMazeSolver>(); // initialize mazeSolver as the MazeSolver class through the IMazeSolver interface in serviceProvider
var mazeCreator = serviceProvider.GetService<IMazeCreator>();
var maze = mazeCreator?.Create();
mazeSolver?.Run(maze);
}
}
}
|
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Extensions.Configuration;
using WebStore.DomainNew.Dto;
using WebStore.DomainNew.Entities;
using WebStore.DomainNew.Filters;
using WebStore.Interfaces;
namespace WebStore.Clients.Services
{
public class ProductsClient : BaseClient, IProductService
{
public ProductsClient(IConfiguration configuration) : base(configuration)
{
ServiceAddress = "api/products";
}
public IEnumerable<Category> GetCategories()
{
var categories = Get<List<Category>>($"{ServiceAddress}/categories");
return categories;
}
public IEnumerable<Brand> GetBrands()
{
var brands = Get<List<Brand>>($"{ServiceAddress}/brands");
return brands;
}
public IEnumerable<ProductDto> GetProducts(ProductsFilter filter)
{
var response = Post($"{ServiceAddress}", filter);
var products = response.Content.ReadAsAsync<List<ProductDto>>().Result;
return products;
}
public ProductDto GetProductById(int id)
{
var product = Get<ProductDto>($"{ServiceAddress}/{id}");
return product;
}
public Category GetCategoryById(int id)
{
var url = $"{ServiceAddress}/categories/{id}";
var category = Get<Category>(url);
return category;
}
public Brand GetBrandById(int id)
{
var url = $"{ServiceAddress}/brands/{id}";
var brand = Get<Brand>(url);
return brand;
}
}
}
|
using GisSharpBlog.NetTopologySuite.Geometries;
using NUnit.Framework;
namespace NetTopologySuite.Tests.Geometry
{
[TestFixture]
public class MultiPointTest
{
[Test]
public void GetHashCodeShoulBeComputed()
{
var multiPoint = new MultiPoint(new[] { new Point(1.0, 2.0), new Point(3.0, 4.0) });
Assert.AreEqual(2024009049, multiPoint.GetHashCode());
}
}
} |
namespace Saato.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class start : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.UserProfile",
c => new
{
UserId = c.Int(nullable: false, identity: true),
UserName = c.String(nullable: false),
FirstName = c.String(),
LastName = c.String(),
Address = c.String(),
PostCode = c.String(),
City = c.String(),
Phone = c.String(),
Mobile = c.String(),
Email = c.String(nullable: false),
})
.PrimaryKey(t => t.UserId);
CreateTable(
"dbo.Language",
c => new
{
Id = c.Int(nullable: false, identity: true),
IdentifierString = c.String(),
en_US = c.String(),
da_DK = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Car",
c => new
{
Id = c.Int(nullable: false, identity: true),
NewPrice = c.Decimal(precision: 18, scale: 2),
Hk = c.Int(),
Nm = c.Int(),
ZeroToHundred = c.Decimal(precision: 18, scale: 2),
TopSpeed = c.Int(),
Kml = c.Decimal(precision: 18, scale: 2),
Width = c.Int(),
Length = c.Int(),
Height = c.Int(),
Payload = c.Int(),
Sprockets = c.String(),
Cylinders = c.Int(),
AbsBrakes = c.Boolean(nullable: false),
MaxTrailer = c.Int(),
Airbags = c.Int(),
Esp = c.Boolean(nullable: false),
ncap = c.Boolean(nullable: false),
Tank = c.Int(),
Gear = c.String(),
Geartype = c.Int(nullable: false),
Weight = c.Int(),
Doors = c.Int(),
Year = c.Int(),
Bodywork = c.String(),
Type = c.String(),
Color = c.String(),
Fuel = c.String(),
Miles = c.Int(nullable: false),
Description = c.String(),
Price = c.Decimal(nullable: false, precision: 18, scale: 2),
NumberOfAirbags = c.Int(),
Alarm = c.Boolean(nullable: false),
Traction = c.Boolean(nullable: false),
Immobiliser = c.Boolean(nullable: false),
RimsSize = c.String(),
RimsType = c.String(),
FogLights = c.Boolean(nullable: false),
XenonLights = c.Boolean(nullable: false),
Towbar = c.Boolean(nullable: false),
DetachableTowbar = c.Boolean(nullable: false),
RoofRails = c.Boolean(nullable: false),
LoweredSuspension = c.Boolean(nullable: false),
CurveLight = c.Boolean(nullable: false),
WoodenInteriors = c.Boolean(nullable: false),
LeatherSteeringWheel = c.Boolean(nullable: false),
LeatherSeats = c.Boolean(nullable: false),
SplitFoldingRearSeat = c.Boolean(nullable: false),
HeightAdjustableFrontSeats = c.Boolean(nullable: false),
Isofix = c.Boolean(nullable: false),
Aircondition = c.Boolean(nullable: false),
Climate = c.Boolean(nullable: false),
GlassRoof = c.Boolean(nullable: false),
Sunroof = c.Boolean(nullable: false),
SeatHeating = c.Boolean(nullable: false),
ElectricMirrors = c.Boolean(nullable: false),
ElectricMirrorsWithHeat = c.Boolean(nullable: false),
EngineBlockHeater = c.Boolean(nullable: false),
RemoteCentralLocking = c.Boolean(nullable: false),
CruiseControl = c.Boolean(nullable: false),
MultifunctionalSteeringWheel = c.Boolean(nullable: false),
ElectricLiftFront = c.Boolean(nullable: false),
ElectricLiftBehind = c.Boolean(nullable: false),
ParkingSensor = c.Boolean(nullable: false),
RainSensor = c.Boolean(nullable: false),
TripComputer = c.Boolean(nullable: false),
Navigation = c.Boolean(nullable: false),
Servo = c.Boolean(nullable: false),
RearViewCamera = c.Boolean(nullable: false),
KeylessEntry = c.Boolean(nullable: false),
NewInspected = c.Boolean(nullable: false),
OneOwner = c.Boolean(nullable: false),
ImportCar = c.Boolean(nullable: false),
ServiceOk = c.Boolean(nullable: false),
DemoCar = c.Boolean(nullable: false),
NonSmoking = c.Boolean(nullable: false),
BuyerId = c.Int(),
CreatedDate = c.DateTime(nullable: false),
MakerId = c.Int(nullable: false),
ModelId = c.Int(nullable: false),
UserId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.UserProfile", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.Maker", t => t.MakerId, cascadeDelete: true)
.ForeignKey("dbo.Model", t => t.ModelId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.MakerId)
.Index(t => t.ModelId);
CreateTable(
"dbo.Maker",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Model",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
MakerId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AdTypes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false),
Description = c.String(nullable: false),
Price = c.Decimal(nullable: false, precision: 18, scale: 2),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Logs",
c => new
{
Id = c.Int(nullable: false, identity: true),
Description = c.String(),
CreatedDate = c.DateTime(nullable: false),
UserId = c.Int(nullable: false),
FunctionName = c.String(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropIndex("dbo.Car", new[] { "ModelId" });
DropIndex("dbo.Car", new[] { "MakerId" });
DropIndex("dbo.Car", new[] { "UserId" });
DropForeignKey("dbo.Car", "ModelId", "dbo.Model");
DropForeignKey("dbo.Car", "MakerId", "dbo.Maker");
DropForeignKey("dbo.Car", "UserId", "dbo.UserProfile");
DropTable("dbo.Logs");
DropTable("dbo.AdTypes");
DropTable("dbo.Model");
DropTable("dbo.Maker");
DropTable("dbo.Car");
DropTable("dbo.Language");
DropTable("dbo.UserProfile");
}
}
}
|
namespace Sfa.Poc.ResultsAndCertification.Dfe.Models
{
public class TqAwardingOrganisationDetails
{
public int Id { get; set; }
public string UkAon { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
}
}
|
using System.Net.Sockets;
using HiLoSocket.SocketApp;
namespace HiLoSocket.Model.InternalOnly
{
/// <summary>
/// StateObjectModel for socket async communication.
/// </summary>
/// <typeparam name="T">User define type.</typeparam>
internal class StateObjectModel<T>
where T : class
{
/// <summary>
/// The data information size
/// </summary>
public const int DataInfoSize = 4;
/// <summary>
/// Gets or sets the buffer.
/// </summary>
/// <value>
/// The buffer.
/// </value>
public byte[ ] Buffer { get; set; } = new byte[ DataInfoSize ];
/// <summary>
/// Gets or sets the timeout checker.
/// </summary>
/// <value>
/// The timeout checker.
/// </value>
public TimeoutChecker<T> TimeoutChecker { get; set; }
/// <summary>
/// Gets or sets the work socket.
/// </summary>
/// <value>
/// The work socket.
/// </value>
public Socket WorkSocket { get; set; }
}
} |
using Service;
using DataLayer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.IO;
using Data.Entities;
using System.Net;
namespace StoreUI
{
public class MenuFactory
{
public static IMenu GetMenu(string menuType)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
string connectionString = configuration.GetConnectionString("p0running");
DbContextOptions<p0runningContext> options = new DbContextOptionsBuilder<p0runningContext>()
.UseSqlServer(connectionString)
.Options;
var context = new p0runningContext(options);
switch(menuType.ToLower()){
case "mainmenu":
return new MainMenu(new Services(new RepoDB(context)), new ValidationUI());
case "adminmenu":
return new AdminMenu(new Services(new RepoDB(context)), new ValidationUI());
case "inventorymenu":
return new InventoryMenu(new Services(new RepoDB(context)), new ValidationUI());
default:
return null;
}
}
}
} |
using UnityEngine;
using System.Collections;
public class Asteroid : SpaceObject
{
float speed = 1f;
int life = 2;
Vector3 movedir = Vector3.zero;
bool isFragment = false;
public static int objectCount = 0;
public static int maxObjectCount = 20;
public override int ObjectCount
{
get { return Asteroid.objectCount; }
set { Asteroid.objectCount = value; }
}
public override int MaxObjectCount
{
get { return Asteroid.maxObjectCount; }
set { Asteroid.maxObjectCount = value; }
}
protected override void Start(){
base.Start();
RewardPoints = 20;
movedir = (Vector3)(new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f)));
}
// Update is called once per frame
void Update () {
transform.Translate(movedir * Time.deltaTime * speed, Space.World);
}
public override bool Damage()
{
life--;
if(life>0){
CreateFragments(UnityEngine.Random.Range(2,4));
}
Destroy(gameObject);
return true;
}
public override bool Damage(SpaceObject owner)
{
if (owner && owner.GetComponent<SpaceShip>()&&!isDamagedYet)
{
isDamagedYet = true;
return Damage();
}
return false;
}
void Initialize(int life,float speed,Vector2 scale,bool isFragment = false){
this.life = life;
this.speed = speed;
this.isFragment = isFragment;
transform.localScale = scale;
int directionLeftOrRight = UnityEngine.Random.Range(0, 2) == 1 ? -1 : 1;
transform.Rotate(new Vector3(0, 0, directionLeftOrRight * UnityEngine.Random.Range(0, 90)));
}
void CreateFragments(int quantity){
for (int i=0;i<quantity;i++){
((GameObject)Instantiate(gameObject,transform.position,transform.rotation)).GetComponent<Asteroid>().Initialize(
life,
speed*UnityEngine.Random.Range(1f,1.5f),
transform.localScale*UnityEngine.Random.Range(.3f,.8f),
true
);
}
}
void OnTriggerEnter2D(Collider2D other){
if (other.GetComponent<SpaceObject>())
{
other.GetComponent<SpaceObject>().Damage(this);
Damage(other.GetComponent<SpaceObject>());
}
}
void OnDestroy() {
ObjectDestroyed(this);
if (!isFragment)
{
objectCount = Mathf.Clamp(--objectCount, 0, maxObjectCount);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ManageWeb
{
[Authorize]
public class ManageBaseController : Controller
{
public ManageDomain.Entity.LoginTokenModel Token;
protected override void OnException(ExceptionContext filterContext)
{
int code = (int)ManageDomain.MExceptionCode.ServerError;
if (filterContext.Exception is ManageDomain.MException)
{
code = (filterContext.Exception as ManageDomain.MException).Code;
}
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 200;
var vresult = Json(new JsonEntity() { code = code, data = null, msg = filterContext.Exception.Message }, JsonRequestBehavior.AllowGet);
vresult.ExecuteResult(filterContext.Controller.ControllerContext);
filterContext.Controller.ControllerContext.HttpContext.Response.End();
}
else
{
var vresult = View("Error", filterContext.Exception);
vresult.ExecuteResult(filterContext.Controller.ControllerContext);
filterContext.Controller.ControllerContext.HttpContext.Response.End();
}
}
protected override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (User != null)
if (User.Identity.IsAuthenticated)
{
Token = ManageDomain.Pub.GetTokenModel(User.Identity.Name);
filterContext.HttpContext.Session["CurrUserId"] = Token.Id;
}
}
public JsonResult JsonE(object data)
{
return Json(new JsonEntity() { code = 1, data = data, msg = "" });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Colours
{
class Enemy
{
//position and scale
const int BLOCKWIDTH = 8;
const int BLOCKHEIGHT = 8;
const byte TINY = 1, SMAL = 2, MEDI = 4, LARG = 8, HUGE = 16, XBOX = 32;
byte size;
public byte Size { get { return size; } }
Texture2D enemyTexTiny, enemyTexSmal, enemyTexMedi, enemyTexLarg, enemyTexHuge, enemytexXbox;
Vector2 pos;
public Vector2 Pos { get { return pos; } }
Vector2 posadj = new Vector2(BLOCKWIDTH / 2, BLOCKHEIGHT / 2);
public Vector2 Posadj { get { return posadj; } }
Vector2 origin = new Vector2(0, 0);
Random rng = new Random();
//movement
float speed;
float patternTime;
//int tempPatternTime;
float horTime;
float verTime;
sbyte movePattern;
//sbyte tempPattern;
const byte MAXPATTERNS = 0;
const int UPDATE = 60;
sbyte dirX = 1;// -1 left, 0 none, 1 right
sbyte dirY = 1;// -1 up, 0 none, 1 down
public sbyte DirX{ get { return dirX; } }
public sbyte DirY{ get { return dirY; } }
//combat
bool alive;
bool active;
public bool Alive{ get { return alive; } }
public bool Active{ get { return active; } }
int healthmax;
int health;
public int HealthMax{ get { return healthmax; } }
public int Health{ get { return health; } }
const byte WHT = 0, RED = 1, GRN = 2, BLU = 3, CYN = 4, MGN = 5, YLO = 6, BLK = 7;
byte colour;
public byte Colour{ get { return colour; } }
UI hud;
/// <summary>
/// Constructs an enemy with default values.
/// </summary>
public Enemy(UI ui, Texture2D[] textures)
{
hud = ui;
enemyTexTiny = textures[0];
enemyTexSmal = textures[1];
enemyTexMedi = textures[2];
enemyTexLarg = textures[3];
enemyTexHuge = textures[4];
enemytexXbox = textures[5];
pos.X = rng.Next(0, 641);
pos.Y = 500;
size = TINY;
colour = WHT;
healthmax = size * 8;
health = healthmax;
alive = true;
active = true;
}
public Enemy(UI ui, Texture2D[] textures, byte startsize, byte startcolour)
{
hud = ui;
enemyTexTiny = textures[0];
enemyTexSmal = textures[1];
enemyTexMedi = textures[2];
enemyTexLarg = textures[3];
enemyTexHuge = textures[4];
enemytexXbox = textures[5];
pos.X = rng.Next(0, 641);
pos.Y = 500;
if (startsize == TINY || startsize == SMAL || startsize == MEDI || startsize == LARG || startsize == HUGE || startsize == XBOX)
{
size = startsize;
}
else
{
size = TINY;
}
if (startcolour > 0 && startcolour < 7)
{
colour = startcolour;
}
healthmax = size * 8;
health = healthmax;
alive = true;
active = true;
}
public Enemy(UI ui, Texture2D[] textures, byte startsize, byte startcolour, int posX, int posY)
{
hud = ui;
enemyTexTiny = textures[0];
enemyTexSmal = textures[1];
enemyTexMedi = textures[2];
enemyTexLarg = textures[3];
enemyTexHuge = textures[4];
enemytexXbox = textures[5];
pos.X = posX;
pos.Y = posY;
if (startsize == TINY || startsize == SMAL || startsize == MEDI || startsize == LARG || startsize == HUGE || startsize == XBOX)
{
size = startsize;
}
else
{
size = TINY;
}
if (startcolour > 0 && startcolour < 7)
{
colour = startcolour;
}
healthmax = size * 8;
health = healthmax;
alive = true;
active = true;
}
/// <summary>
/// Creates a new enemy with passed values
/// </summary>
/// <param name="ui">UI for drawing status</param>
/// <param name="textures">Array of enemy textures</param>
/// <param name="startsize">Start size, 1 Tiny, 2 Small, 4 Medium, 8 Large, 16 Huge, 32 Xbox, 64 RNG</param>
/// <param name="startcolour">Start colour, 0 White, 1 Red, 2 Green, 3 Blue, 4 Cyan, 5 Magenta, 6 Yellow, 7 Black, 8 RNG RGBCMY, 9 RNG All</param>
/// <param name="posX">X position, use 9999 to RNG</param>
/// <param name="posY">Y position, use 9999 to RNG near top, 99999 to RNG anywhere</param>
/// <param name="startpattern">Start move pattern, 0 to 5, straight, zigzag1, zigdownzagdown, downleftdownright, dldldrdr, wavy</param>
public Enemy(UI ui, Texture2D[] textures, byte startsize, byte startcolour, int posX, int posY, sbyte startpattern)
{
hud = ui;
enemyTexTiny = textures[0];
enemyTexSmal = textures[1];
enemyTexMedi = textures[2];
enemyTexLarg = textures[3];
enemyTexHuge = textures[4];
enemytexXbox = textures[5];
if (posX == 9999)
{
pos.X = rng.Next(0, 641);
}
else
{
pos.X = posX;
}
if (posY == 9999)
{
pos.Y = rng.Next(0, 100);
}
else if (posY == 99999)
{
pos.Y = rng.Next(0, 800);
}
else
{
pos.Y = posY;
}
if (startsize == TINY || startsize == SMAL || startsize == MEDI || startsize == LARG || startsize == HUGE || startsize == XBOX)
{
size = startsize;
}
else if (startsize == 64)
{
switch (RollNumber(1, 6))
{
case 1:
size = TINY;
break;
case 2:
size = SMAL;
break;
case 3:
size = MEDI;
break;
case 4:
if (RollDice(1, 16))
{
size = LARG;
}
else
{
size = MEDI;
}
break;
case 5:
if (RollDice(1, 16))
{
size = HUGE;
}
else
{
size = LARG;
}
break;
case 6:
if (RollDice(1, 16))
{
size = XBOX;
}
else
{
size = HUGE;
}
break;
}
}
else
{
size = TINY;
}
if (startcolour > 0 && startcolour < 7)
{
colour = startcolour;
}
else if (startcolour == 8)
{
colour = (byte)RollNumber(1, 6);
}
else if (startcolour == 9)
{
colour = (byte)RollNumber(0, 7);
}
if (startpattern >= 0 && startpattern <= MAXPATTERNS)
{
movePattern = startpattern;
}
healthmax = size * 8;
health = healthmax;
alive = true;
active = true;
}
/// <summary>
/// Draws the enemy.
/// </summary>
public void Draw(SpriteBatch sprbat)
{
if (active)
{
switch (size)
{
case TINY:
sprbat.Draw(enemyTexTiny, new Rectangle((int)(pos.X - posadj.X * size), (int)(pos.Y - posadj.Y * size), BLOCKWIDTH * size, BLOCKHEIGHT * size), new Rectangle(colour * BLOCKWIDTH * size, 0, BLOCKWIDTH * size, BLOCKHEIGHT * size), Color.White);
break;
case SMAL:
sprbat.Draw(enemyTexSmal, new Rectangle((int)(pos.X - posadj.X * size), (int)(pos.Y - posadj.Y * size), BLOCKWIDTH * size, BLOCKHEIGHT * size), new Rectangle(colour * BLOCKWIDTH * size, 0, BLOCKWIDTH * size, BLOCKHEIGHT * size), Color.White);
break;
case MEDI:
sprbat.Draw(enemyTexMedi, new Rectangle((int)(pos.X - posadj.X * size), (int)(pos.Y - posadj.Y * size), BLOCKWIDTH * size, BLOCKHEIGHT * size), new Rectangle(colour * BLOCKWIDTH * size, 0, BLOCKWIDTH * size, BLOCKHEIGHT * size), Color.White);
break;
case LARG:
sprbat.Draw(enemyTexLarg, new Rectangle((int)(pos.X - posadj.X * size), (int)(pos.Y - posadj.Y * size), BLOCKWIDTH * size, BLOCKHEIGHT * size), new Rectangle(colour * BLOCKWIDTH * size, 0, BLOCKWIDTH * size, BLOCKHEIGHT * size), Color.White);
break;
case HUGE:
sprbat.Draw(enemyTexHuge, new Rectangle((int)(pos.X - posadj.X * size), (int)(pos.Y - posadj.Y * size), BLOCKWIDTH * size, BLOCKHEIGHT * size), new Rectangle(colour * BLOCKWIDTH * size, 0, BLOCKWIDTH * size, BLOCKHEIGHT * size), Color.White);
break;
case XBOX:
sprbat.Draw(enemytexXbox, new Rectangle((int)(pos.X - posadj.X * size), (int)(pos.Y - posadj.Y * size), BLOCKWIDTH * size, BLOCKHEIGHT * size), new Rectangle(colour * BLOCKWIDTH * size, 0, BLOCKWIDTH * size, BLOCKHEIGHT * size), Color.White);
break;
}
}
}
/// <summary>
/// Moves the enemy.
/// </summary>
public void Move()
{
switch (size)
{
case TINY:
speed = 1;
break;
case SMAL:
speed = 0.5f;;
break;
case MEDI:
speed = 0.25f;
break;
case LARG:
speed = 0.5f;
break;
case HUGE:
speed = 0.25f;
break;
case XBOX:
speed = 0.125f;
break;
}
if (pos.Y > 800)
{
speed = size;
}
if (active)
{
pos.Y += dirY * speed;
//while (horTime > 0)
//{
// pos.X += dirX * speed;
// horTime--;
// if (movePattern != -1 && horTime <= 0)
// {
// UpdatePattern(1);
// }
//}
//while (verTime > 0)
//{
// pos.Y += dirY * speed;
// verTime--;
// if (movePattern != -1 && verTime <= 1)
// {
// UpdatePattern(0);
// }
//}
//if (movePattern == -1 && patternTime <= 0)
//{
// patternTime = tempPatternTime;
// movePattern = tempPattern;
//}
//if (patternTime <= 0)
//{
// ChangePattern();
//}
//if (movePattern != -1 && verTime == 0 && horTime == 0)
//{
// UpdatePattern(2);
//}
}
}
///// <summary>
///// Updates move pattern
///// </summary>
///// <param name="dir">0 = ver, 1 = hor, 2 = both</param>
//private void UpdatePattern(byte dir)
//{
// switch (movePattern)
// {
// case 0://straight down
// dirY = 1;
// dirX = 0;
// horTime = patternTime;
// verTime = patternTime;
// patternTime--;
// break;
// case 1://Zig zag
// break;
// case 2://zig straight zag straight
// break;
// case 3://down left down right
// break;
// case 4://down left down left down right down right
// break;
// case 5://smooth
// break;
// case 6:
// break;
// case 7:
// break;
// case 8:
// break;
// }
//}
private void ChangePattern()
{
movePattern = 0;
patternTime = (int)rng.Next(3, 10) * UPDATE;
}
/// <summary>
/// Moves the enemy.
/// </summary>
public void MoveRandom(Vector2 target, int speed)
{
}
/// <summary>
/// Will attempt to avoid any bullets moving within a certain distance of Enemy, depending on passes.
/// </summary>
public void AvoidSide(Vector2 avoidPos)
{
//if (movePattern != -1)
//{
// tempPattern = movePattern;
// movePattern = -1;
//}
if (pos.X < avoidPos.X)
{
horTime = 0.1f * UPDATE;
dirX = -1;
}
else if (pos.X < avoidPos.X)
{
horTime = 0.1f * UPDATE;
dirX = 1;
}
//else if (pos.X < avoidPos.X)
//{
// if (RollDice(1, 2))
// {
// dirX = 1;
// }
// else
// {
// dirX = -1;
// }
//}
}
/// <summary>
/// Will attempt to avoid any bullets moving within a certain distance of Enemy, depending on passes.
/// </summary>
public void AvoidFront()
{
//verTime = 0.1f * UPDATE;
//dirY = -1;
}
public void CycleColour()
{
if (colour < BLK)
{
colour++;
}
else
{
colour = WHT;
}
}
public Rectangle GetRect()
{
return new Rectangle((int)(pos.X - posadj.X * size), (int)(pos.Y - posadj.Y * size), BLOCKWIDTH * size, BLOCKHEIGHT * size);
}
public Rectangle GetAvoidFrontRect()
{
return new Rectangle((int)(pos.X - posadj.X * size), (int)(pos.Y - posadj.Y * size), BLOCKWIDTH * size, BLOCKHEIGHT * size);
}
public Rectangle GetAvoidSideRect()
{
return new Rectangle((int)(pos.X - posadj.X * size * 2), (int)(pos.Y - posadj.Y * size), BLOCKWIDTH * size * 2, BLOCKHEIGHT * size * 1);
}
public Rectangle GetAvoidLeftRect()
{
return new Rectangle((int)(pos.X - posadj.X * size), (int)(pos.Y - posadj.Y * size), (BLOCKWIDTH * size) / 2, BLOCKHEIGHT * size * 1);
}
public Rectangle GetAvoidRightRect()
{
return new Rectangle((int)(pos.X + posadj.X * size), (int)(pos.Y - posadj.Y * size), (BLOCKWIDTH * size) / 2, BLOCKHEIGHT * size * 1);
}
/// <summary>
/// Changes size of Enemy
/// </summary>
/// <param name="mode">0 = down, 1 = up, 2 = assign</param>
/// <param name="newsize">TINY (1), SMALL (2), MEDIUM (4), LARGE (8), HUGE (16), XBOX (32)</param>
public void ChangeSize(byte mode, byte newsize)
{
switch(mode)
{
case 0:
switch (size)
{
case TINY:
break;
case SMAL:
size = TINY;
break;
case MEDI:
size = SMAL;
break;
case LARG:
size = MEDI;
break;
case HUGE:
size = LARG;
break;
case XBOX:
size = HUGE;
break;
}
UpdateHealth();
break;
case 1:
switch (size)
{
case TINY:
size = SMAL;
break;
case SMAL:
size = MEDI;
break;
case MEDI:
size = LARG;
break;
case LARG:
size = HUGE;
break;
case HUGE:
size = XBOX;
break;
case XBOX:
break;
}
UpdateHealth();
break;
case 3:
if (newsize == TINY || newsize == SMAL || newsize == MEDI || newsize == LARG || newsize == HUGE || newsize == XBOX)
{
size = newsize;
}
UpdateHealth();
break;
}
}
/// <summary>
/// Routines to be completed on spawn.
/// </summary>
public void Spawn()
{
}
public void Death()
{
active = false;
}
public void GlomTest(Enemy other)
{
if (RollDice(1, size))
{
Glom(other);
}
else
{
switch (dirX)
{
case -1:
dirX = 1;
horTime = 3 * UPDATE;
break;
case 1:
dirX = -1;
horTime = 3 * UPDATE;
break;
}
}
}
private void Glom(Enemy other)
{
}
//private Enemy Split()
//{
// return;
//}
public void Hit(int damage, byte hitcolour)
{
bool healed = false;
if (colour == hitcolour)
{
Heal(damage);
healed = true;
}
if (colour == BLK)
{
if (hitcolour == WHT)
{
Hurt(damage * 2);
}
}
else if (colour == WHT)
{
if (hitcolour == BLK)
{
Hurt(damage * 2);
}
}
else if (hitcolour == BLK)
{
Hurt(damage * 4);
}
else if (hitcolour == WHT)
{
Heal(damage * 4);
}
else if (colour == hitcolour + 3 || colour == hitcolour - 3)
{
Hurt(damage * 2);
}
else if(!healed)
{
Hurt(damage);
}
}
public void Hurt(int damage)
{
health -= damage;
}
private void UpdateHealth()//REMOVE
{
healthmax = size * 8;
health = healthmax;
}
public void Heal(int damage)
{
if (health + damage < healthmax)
{
health += damage;
}
else if (health + damage >= healthmax)
{
health = healthmax;
}
}
public void CheckPos()
{
if (pos.Y - posadj.Y * size > 896)
{
active = false;
}
}
public void CheckHealth()
{
if (health <= 0)
{
if (alive)
{
alive = false;
Death();
}
}
}
private bool RollDice(int chance, int sides)
{
int roll = rng.Next(0, sides + 1);
if (roll <= chance)
{
return true;
}
else
{
return false;
}
}
private int RollNumber(int min, int max)
{
return (int)rng.Next(min, max + 1);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using Xamarin.Forms;
using KSF_Surf.ViewModels;
using KSF_Surf.Models;
using System.Collections.ObjectModel;
namespace KSF_Surf.Views
{
[DesignTimeVisible(false)]
public partial class RecordsMostPage : ContentPage
{
private readonly RecordsViewModel recordsViewModel;
private bool hasLoaded = false;
private bool isLoading = false;
private readonly int CALL_LIMIT = 500;
// objects possibly used by "Most By Type" calls
private List<MostPCDatum> mostPCData;
private List<MostCountDatum> mostCountData;
private List<MostTopDatum> mostTopData;
private List<MostGroupDatum> mostGroupData;
private List<MostContWrDatum> mostContWrData;
private List<MostContZoneDatum> mostContZoneData;
private List<MostTimeDatum> mostTimeData;
private int list_index = 1;
// variables for filters
private readonly EFilter_Game defaultGame;
private readonly EFilter_Mode defaultMode;
private EFilter_Game game;
private EFilter_Mode mode;
private EFilter_MostType mostType;
private string mostTypeString;
// collection view
public ObservableCollection<Tuple<string, string, string>> recordsMostCollectionViewItemsSource { get; }
= new ObservableCollection<Tuple<string, string, string>>();
public RecordsMostPage(EFilter_Game game, EFilter_Mode mode, EFilter_Game defaultGame, EFilter_Mode defaultMode)
{
this.game = game;
this.mode = mode;
this.defaultGame = defaultGame;
this.defaultMode = defaultMode;
mostType = EFilter_MostType.wr;
mostTypeString = "Current WRs";
recordsViewModel = new RecordsViewModel();
InitializeComponent();
Title = "Records [" + EFilter_ToString.toString2(game) + ", " + EFilter_ToString.toString(mode) + "]";
MostTypePicker.ItemsSource = EFilter_ToString.mosttype_arr;
RecordsMostCollectionView.ItemsSource = recordsMostCollectionViewItemsSource;
}
// UI -----------------------------------------------------------------------------------------------
#region UI
private async Task ChangeMostByType(bool clearPrev)
{
List<string> players = new List<string>();
List<string> values = new List<string>();
List<string> links = new List<string>();
switch (mostType)
{
case EFilter_MostType.pc:
{
var mostPCDatum = await recordsViewModel.GetMostPC(game, mode, list_index);
mostPCData = mostPCDatum?.data;
if (mostPCData is null || mostPCData.Count < 1) return;
foreach (MostPCDatum datum in mostPCData)
{
players.Add(String_Formatter.toEmoji_Country(datum.country) + " " + datum.name);
values.Add((double.Parse(datum.percentCompletion) * 100).ToString("0.00") + "%");
links.Add(datum.steamID);
}
break;
}
case EFilter_MostType.wr:
case EFilter_MostType.wrcp:
case EFilter_MostType.wrb:
case EFilter_MostType.mostwr:
case EFilter_MostType.mostwrcp:
case EFilter_MostType.mostwrb:
{
var mostCountDatum = await recordsViewModel.GetMostCount(game, mostType, mode, list_index);
mostCountData = mostCountDatum?.data;
if (mostCountData is null || mostCountData.Count < 1) return;
foreach (MostCountDatum datum in mostCountData)
{
players.Add(String_Formatter.toEmoji_Country(datum.country) + " " + datum.name);
values.Add(String_Formatter.toString_Int(datum.total));
links.Add(datum.steamID);
}
break;
}
case EFilter_MostType.top10:
{
var mostTopDatum = await recordsViewModel.GetMostTop(game, mode, list_index);
mostTopData = mostTopDatum?.data;
if (mostTopData is null || mostTopData.Count < 1) return;
foreach (MostTopDatum datum in mostTopData)
{
players.Add(String_Formatter.toEmoji_Country(datum.country) + " " + datum.name);
values.Add(String_Formatter.toString_Points(datum.top10Points));
links.Add(datum.steamID);
}
break;
}
case EFilter_MostType.group:
{
var mostGroupDatum = await recordsViewModel.GetMostGroup(game, mode, list_index);
mostGroupData = mostGroupDatum?.data;
if (mostGroupData is null || mostGroupData.Count < 1) return;
foreach (MostGroupDatum datum in mostGroupData)
{
players.Add(String_Formatter.toEmoji_Country(datum.country) + " " + datum.name);
values.Add(String_Formatter.toString_Points(datum.groupPoints));
links.Add(datum.steamID);
}
break;
}
case EFilter_MostType.mostcontestedwr:
{
var mostContWrDatum = await recordsViewModel.GetMostContWr(game, mode, list_index);
mostContWrData = mostContWrDatum?.data;
if (mostContWrData is null || mostContWrData.Count < 1) return;
foreach (MostContWrDatum datum in mostContWrData)
{
players.Add(datum.mapName);
values.Add(String_Formatter.toString_Int(datum.total));
links.Add(datum.mapName);
}
break;
}
case EFilter_MostType.mostcontestedwrcp:
case EFilter_MostType.mostcontestedwrb:
{
var mostContZoneDatum = await recordsViewModel.GetMostContZone(game, mostType, mode, list_index);
mostContZoneData = mostContZoneDatum?.data;
if (mostContZoneData is null || mostContZoneData.Count < 1) return;
foreach (MostContZoneDatum datum in mostContZoneData)
{
string zoneString = EFilter_ToString.zoneFormatter(datum.zoneID, false, false);
players.Add(datum.mapName + " " + zoneString);
values.Add(String_Formatter.toString_Int(datum.total));
links.Add(datum.mapName);
}
break;
}
case EFilter_MostType.playtimeday:
case EFilter_MostType.playtimeweek:
case EFilter_MostType.playtimemonth:
{
var mostTimeDatum = await recordsViewModel.GetMostTime(game, mostType, mode, list_index);
mostTimeData = mostTimeDatum?.data;
if (mostTimeData is null || mostTimeData.Count < 1) return;
foreach (MostTimeDatum datum in mostTimeData)
{
players.Add(datum.mapName);
values.Add(String_Formatter.toString_PlayTime(datum.totalplaytime.ToString(), true));
links.Add(datum.mapName);
}
break;
}
default: return;
}
if (clearPrev) recordsMostCollectionViewItemsSource.Clear();
LayoutMostByType(players, values, links);
MostTypeOptionLabel.Text = "Type: " + EFilter_ToString.toString2(mostType);
Title = "Records [" + EFilter_ToString.toString2(game) + ", " + EFilter_ToString.toString(mode) + "]";
}
// Displaying Changes -------------------------------------------------------------------------------
private void LayoutMostByType(List<string> players, List<string> values, List<string> links)
{
for (int i = 0; i < players.Count && i < values.Count && i < links.Count; i++, list_index++)
{
recordsMostCollectionViewItemsSource.Add(new Tuple<string, string, string>(list_index + ". " + players[i], values[i], links[i]));
}
}
#endregion
// Event Handlers ----------------------------------------------------------------------------------
#region events
protected override async void OnAppearing()
{
if (!hasLoaded)
{
hasLoaded = true;
await ChangeMostByType(false);
LoadingAnimation.IsRunning = false;
RecordsMostStack.IsVisible = true;
}
}
private void MostTypeOptionLabel_Tapped(object sender, EventArgs e)
{
MostTypePicker.SelectedItem = mostTypeString;
MostTypePicker.Focus();
}
private async void MostTypePicker_Unfocused(object sender, FocusEventArgs e)
{
string selected = (string)MostTypePicker.SelectedItem;
if (selected == mostTypeString) return;
switch (selected)
{
case "Completion": mostType = EFilter_MostType.pc; break;
case "Current WRs": mostType = EFilter_MostType.wr; break;
case "Current WRCPs": mostType = EFilter_MostType.wrcp; break;
case "Current WRBs": mostType = EFilter_MostType.wrb; break;
case "Top10 Points": mostType = EFilter_MostType.top10; break;
case "Group Points": mostType = EFilter_MostType.group; break;
case "Broken WRs": mostType = EFilter_MostType.mostwr; break;
case "Broken WRCPs": mostType = EFilter_MostType.mostwrcp; break;
case "Broken WRBs": mostType = EFilter_MostType.mostwrb; break;
case "Contested WR": mostType = EFilter_MostType.mostcontestedwr; break;
case "Contested WRCP": mostType = EFilter_MostType.mostcontestedwrcp; break;
case "Contested WRB": mostType = EFilter_MostType.mostcontestedwrb; break;
case "Play Time Day": mostType = EFilter_MostType.playtimeday; break;
case "Play Time Week": mostType = EFilter_MostType.playtimeweek; break;
case "Play Time Month": mostType = EFilter_MostType.playtimemonth; break;
default: return;
}
mostTypeString = selected;
list_index = 1;
LoadingAnimation.IsRunning = true;
isLoading = true;
await ChangeMostByType(true);
LoadingAnimation.IsRunning = false;
isLoading = false;
}
private async void RecordsMost_ThresholdReached(object sender, EventArgs e)
{
if (isLoading || !BaseViewModel.hasConnection() || list_index == CALL_LIMIT) return;
if (mostType == EFilter_MostType.playtimeday
|| mostType == EFilter_MostType.playtimeweek
|| mostType == EFilter_MostType.playtimemonth) return;
// calling with these ^ types again leads to JSON deserialization errors
isLoading = true;
LoadingAnimation.IsRunning = true;
await ChangeMostByType(false);
LoadingAnimation.IsRunning = false;
isLoading = false;
}
private async void RecordsMost_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.CurrentSelection.Count == 0) return;
Tuple<string, string, string> selection = (Tuple<string, string, string>)RecordsMostCollectionView.SelectedItem;
RecordsMostCollectionView.SelectedItem = null;
string linkValue = selection.Item3;
bool linkIsSteamId = linkValue.StartsWith("STEAM");
if (BaseViewModel.hasConnection())
{
if (linkIsSteamId) await Navigation.PushAsync(new RecordsPlayerPage(game, mode, linkValue));
else await Navigation.PushAsync(new MapsMapPage(linkValue, game));
}
else
{
await DisplayNoConnectionAlert();
}
}
private async void Filter_Pressed(object sender, EventArgs e)
{
if (hasLoaded && BaseViewModel.hasConnection())
{
await Navigation.PushAsync(new RecordsFilterPage(ApplyFilters, game, mode, defaultGame, defaultMode));
}
else
{
await DisplayNoConnectionAlert();
}
}
internal async void ApplyFilters(EFilter_Game newGame, EFilter_Mode newMode)
{
if (newGame == game && newMode == mode) return;
if (BaseViewModel.hasConnection())
{
game = newGame;
mode = newMode;
list_index = 1;
LoadingAnimation.IsRunning = true;
isLoading = true;
await ChangeMostByType(true);
LoadingAnimation.IsRunning = false;
isLoading = true;
}
else
{
await DisplayNoConnectionAlert();
}
}
private async Task DisplayNoConnectionAlert()
{
await DisplayAlert("Could not connect to KSF!", "Please connect to the Internet.", "OK");
}
#endregion
}
} |
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Text;
using TeamCss__Registration.Hooks;
using TeamCss__Registration.Utilities;
namespace TeamCss__Registration.PageObject
{
class LogInPage
{
IWebDriver driver;
Wait wait = new Wait();
public LogInPage()
{
driver = Hook.driver;
}
public void NavigateToWebsite()
{
driver.Navigate().GoToUrl("https://www.qa.giftrete.com/home");
}
IWebElement clickOnSignIn => driver.FindElement(By.XPath("/html/body/section[1]/nav/div/div[1]/a[3]"));
IWebElement enterEmailAddress => driver.FindElement(By.XPath("//*[@id='user_email'] "));
IWebElement enterPassword => driver.FindElement(By.XPath("//*[@id='user_password']"));
IWebElement clickOnSignInlink => driver.FindElement(By.XPath("(//input[@class='add-p new-add-p'])[1]"));
IWebElement dashboardElementDisplayed => driver.FindElement(By.XPath("//*[@id='content']/div/div/div/div/div/div[1]/div[1]/div/div[2]/h2/span"));
IWebElement ClickOnProfileName => driver.FindElement(By.XPath("/html/body/div[1]/header[1]/div/div[2]/div/div[3]/ul/li[4]/span"));
IWebElement ClickOnLogout => driver.FindElement(By.XPath("/html/body/div[1]/header[1]/div/div[2]/div/div[3]/ul/li[4]/span"));
IWebElement logoutelementDisplayed => driver.FindElement(By.XPath("(//*[@href='/home'])[1]"));
IWebElement WebHomePageDisplayed => driver.FindElement(By.XPath("(//a[@href='/Account/profile'])[3]"));
IWebElement ClickOnCommunity => driver.FindElement(By.XPath("//*[@id='mycommunity']/div[2]/a"));
IWebElement Communitydashboarddisplayed => driver.FindElement(By.XPath("//*[@id='content']/div/div/div/div/div/div[2]/div[1]/div/div[1]/h2"));
IWebElement ClickOnSearch => driver.FindElement(By.XPath("html/body/div[1]/header[1]/div/div[2]/div/div[3]/ul/li[2]/a"));
IWebElement SearchListShouldBeDisplayed => driver.FindElement(By.XPath("//*[@id='content']/div/div/div/div/div[1]/div/h2"));
public bool LogoutElementDisplayed()
{
return wait.WaitForElement(driver, logoutelementDisplayed).Displayed;
}
public void SignInLink()
{
clickOnSignIn.Click();
}
public void ValidEmailAddress()
{
enterEmailAddress.SendKeys("Sophia.john@gmail.com");
}
public void Validpassword()
{
enterPassword.SendKeys("bluesky");
}
public void SignInButton()
{
clickOnSignInlink.Click();
}
public bool DashboardElementDisplayed()
{
return dashboardElementDisplayed.Displayed;
}
public void clickOnProfileName()
{
wait.WaitForElement(driver, ClickOnProfileName).Click();
}
internal bool? ItemsShouldBeDisplayed()
{
throw new NotImplementedException();
}
public void clickOnLogout()
{
ClickOnLogout.Click();
}
public bool WebPageDisplayed()
{
return wait.WaitForElement(driver, WebHomePageDisplayed).Displayed;
}
public void ClickOnCommunityLink()
{
ClickOnCommunity.Click();
}
public bool CommunityDashboardDisplayed()
{
return Communitydashboarddisplayed.Displayed;
}
public void ClickOnSearchButton()
{
ClickOnSearch.Click();
}
public bool SearchListDisplayed()
{
return SearchListShouldBeDisplayed.Displayed;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace com.Sconit.Web.Models.SearchModels.MD
{
public class CustomerShipAddressSearchModel : SearchModelBase
{
public string AddressCode { get; set; }
public string AddressContent { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gView.Framework.UI.Controls
{
internal partial class CatalogComboBox : UserControl
{
public delegate void SelectedItemChangedEvent(CatalogComboItem item);
public event SelectedItemChangedEvent SelectedItemChanged = null;
public CatalogComboBox()
{
InitializeComponent();
//if (ExplorerImageList.List.CountImages == 0)
//{
// ExplorerImageList.List.AddImages(imageList1);
//}
//if (FormExplorer.globalImageList == null) FormExplorer.globalImageList = imageList1;
using (Graphics graphics = this.CreateGraphics())
{
this.FontScaleFactor = graphics.DpiX / 96f;
}
cmbCatalog.ItemHeight = (int)(cmbCatalog.ItemHeight * this.FontScaleFactor);
}
private float FontScaleFactor { get; set; }
private void CatalogComboBox_Load(object sender, EventArgs e)
{
}
async public Task InitComboBox()
{
cmbCatalog.Items.Clear();
ComputerObject computer = new ComputerObject(null);
cmbCatalog.Items.Add(new ExplorerObjectComboItem(computer.Name, 0, 0, computer));
foreach (IExplorerObject exObject in await computer.ChildObjects())
{
cmbCatalog.Items.Add(
new DriveComboItem(
exObject.Name,
((exObject is DriveObject) ? 1 : 0),
((exObject is DriveObject) ? ((DriveObject)exObject).ImageIndex : gView.Explorer.UI.Framework.UI.ExplorerIcons.ImageIndex(exObject)),
exObject
));
}
//cmbCatalog.Items.Add(new CatalogComboItem("Computer", 0, 0, null));
//ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT Name,DriveType From Win32_LogicalDisk ");
//ManagementObjectCollection collection = query.Get();
//foreach (ManagementObject manObject in collection)
//{
// DriveObject exObject = new DriveObject(manObject["Name"].ToString(), (uint)manObject["DriveType"]);
// cmbCatalog.Items.Add(new DriveComboItem(exObject.Name, 1, exObject.ImageIndex, exObject));
//}
//ComponentManager compMan = new ComponentManager();
//foreach (XmlNode exObjectNode in compMan.ExplorerObjects)
//{
// IExplorerObject exObject = (IExplorerObject)compMan.getComponent(exObjectNode);
// if (!(exObject is IExplorerGroupObject)) continue;
// cmbCatalog.Items.Add(new ExplorerObjectComboItem(exObject.Name, 0, FormExplorer.ImageIndex(exObject), exObject));
//}
cmbCatalog.SelectedIndex = 0;
}
public void AddChildNode(IExplorerObject exObject)
{
int index = cmbCatalog.SelectedIndex;
if (index == -1)
{
return;
}
int level = ((CatalogComboItem)cmbCatalog.SelectedItem).Level;
if (exObject is DirectoryObject)
{
cmbCatalog.Items.Insert(index + 1, new DirectoryComboItem(exObject.Name, level + 1, gView.Explorer.UI.Framework.UI.ExplorerIcons.ImageIndex(exObject), exObject));
}
else
{
cmbCatalog.Items.Insert(index + 1, new ExplorerObjectComboItem(exObject.Name, level + 1, gView.Explorer.UI.Framework.UI.ExplorerIcons.ImageIndex(exObject), exObject));
}
cmbCatalog.SelectedIndex = index + 1;
}
public void MoveUp()
{
if (cmbCatalog.SelectedIndex < 1)
{
return;
}
if (cmbCatalog.SelectedItem is DriveComboItem)
{
return;
}
if (cmbCatalog.SelectedItem is CatalogComboItem)
{
CatalogComboItem item = (CatalogComboItem)cmbCatalog.SelectedItem;
if (item.Level > 0)
{
cmbCatalog.SelectedIndex--;
}
}
}
public IExplorerObject SelectedExplorerObject
{
get
{
if (cmbCatalog.SelectedItem is CatalogComboItem)
{
return ((CatalogComboItem)cmbCatalog.SelectedItem).ExplorerObject;
}
return null;
}
}
private void cmbCatalog_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0 || e.Index >= cmbCatalog.Items.Count)
{
return;
}
if (!(cmbCatalog.Items[e.Index] is CatalogComboItem))
{
return;
}
//DrawItemState.
CatalogComboItem item = (CatalogComboItem)cmbCatalog.Items[e.Index];
int level = item.Level;
if ((e.State & DrawItemState.ComboBoxEdit) == DrawItemState.ComboBoxEdit)
{
level = 0;
}
using (SolidBrush brush = new SolidBrush(Color.Black))
{
Rectangle rect = new Rectangle(e.Bounds.X + level * 11 + 18, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected &&
(e.State & DrawItemState.ComboBoxEdit) != DrawItemState.ComboBoxEdit)
{
brush.Color = Color.DarkBlue;
e.Graphics.FillRectangle(brush, rect);
brush.Color = Color.White;
}
else
{
brush.Color = Color.White;
e.Graphics.FillRectangle(brush, rect);
brush.Color = Color.Black;
}
try
{
Image image = ExplorerImageList.List[item.ImageIndex];
e.Graphics.DrawImage(image, e.Bounds.X + level * 11 + 3, e.Bounds.Y);
}
catch { }
e.Graphics.DrawString(item.ToString(), cmbCatalog.Font, brush, e.Bounds.X + level * 11 + 20, e.Bounds.Y + 2);
}
}
private void cmbCatalog_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbCatalog.SelectedItem is CatalogComboItem)
{
CatalogComboItem item = (CatalogComboItem)cmbCatalog.SelectedItem;
List<CatalogComboItem> delete = new List<CatalogComboItem>();
foreach (CatalogComboItem i in cmbCatalog.Items)
{
if (i is DriveComboItem)
{
continue;
}
if (i.Level > item.Level)
{
delete.Add(i);
}
}
foreach (CatalogComboItem i in delete)
{
cmbCatalog.Items.Remove(i);
}
if (SelectedItemChanged != null)
{
SelectedItemChanged((CatalogComboItem)cmbCatalog.SelectedItem);
}
}
else
{
if (SelectedItemChanged != null)
{
SelectedItemChanged(null);
}
}
}
}
internal class CatalogComboItem
{
private string _text;
private int _level, _imageIndex;
IExplorerObject _exObject;
public CatalogComboItem(string text, int level, int imageIndex, IExplorerObject exObject)
{
_text = text;
_level = level;
_imageIndex = imageIndex;
_exObject = exObject;
}
public int Level
{
get { return _level; }
}
public int ImageIndex
{
get { return _imageIndex; }
}
public IExplorerObject ExplorerObject
{
get { return _exObject; }
}
public override string ToString()
{
return _text;
}
}
internal class DriveComboItem : CatalogComboItem
{
public DriveComboItem(string text, int level, int imageIndex, IExplorerObject exObject)
: base(text, level, imageIndex, exObject)
{
}
}
internal class DirectoryComboItem : CatalogComboItem
{
public DirectoryComboItem(string text, int level, int imageIndex, IExplorerObject exObject)
: base(text, level, imageIndex, exObject)
{
}
}
internal class ExplorerObjectComboItem : CatalogComboItem
{
public ExplorerObjectComboItem(string text, int level, int imageIndex, IExplorerObject exObject)
: base(text, level, imageIndex, exObject)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPatternsApp.Models
{
public class UserModel
{
public string Username { get; set; }
public string FullName { get; set; }
public string PhoneNumber { get; set; }
public string Adress { get; set; }
public double Amount { get; set; }
public UserModel(string Username, string FullName, string PhoneNumber , string Adress, double Amount)
{
this.Username = Username;
this.FullName = FullName;
this.PhoneNumber = PhoneNumber;
this.Adress = Adress;
this.Amount = Amount;
}
public UserModel()
{
}
public UserModel GetUser()
{
string Username, FullName, PhoneNumber, Adress;
Console.WriteLine("Insert username:");
Username = Console.ReadLine();
Console.WriteLine("Insert full name:");
FullName = Console.ReadLine();
Console.WriteLine("Insert phone number:");
PhoneNumber = Console.ReadLine();
Console.WriteLine("Insert adress:");
Adress = Console.ReadLine();
Amount = 0;
UserModel generatedUserModel = new UserModel(Username, FullName, PhoneNumber, Adress, Amount);
return generatedUserModel;
}
public UserModel GetUser(string Username, string FullName, string PhoneNumber, string Adress) // for testing purposes
{
Amount = 0;
UserModel generatedUserModel = new UserModel(Username, FullName, PhoneNumber, Adress, Amount);
return generatedUserModel;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics;
using Olive.Data.Uow;
using Olive.Data;
namespace Olive.Web.MVC.ActionFilters
{
public class HitCounter : ActionFilterAttribute
{
//public override void OnActionExecuted(ActionExecutedContext filterContext)
//{
// //var currentController = filterContext.RouteData.Values["controller"].ToString();
// //var currentAction = filterContext.RouteData.Values["action"].ToString();
// //if (currentController.Equals("Recipes") && currentAction.Equals("Details"))
// //{
// // //Debug.WriteLine(filterContext.RouteData.Values["action"].ToString());
// // //Debug.WriteLine(filterContext.RouteData.Values["recipeID"].ToString());
// // //int currentRecipeID=(int)filterContext.RouteData.Values["recipeID"];
// // int currentRecipeID = Convert.ToInt32(filterContext.RouteData.Values["recipeID"].ToString());
// // IUowData db = new UowData();
// // var oldRecipe = from rec in db.Recipes.All()
// // where rec.RecipeID == currentRecipeID
// // select rec;
// // Recipe newRecipe = oldRecipe.FirstOrDefault();
// // newRecipe.NumberOfHits = newRecipe.NumberOfHits + 1;
// // db.Recipes.Update(newRecipe);
// // int result = db.SaveChanges();
// //}
//}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pcCollision : MonoBehaviour
{
public pcHealthController ph;
private float playerInvincibility;
private void Update()
{
}
//Whenever the player touches the trigger on the zombie, it activates the LowerHealth method in the pcHealthController script
}
|
using OpenTK.Input;
using System.Collections.Generic;
namespace Glib.Input
{
/// <summary>
/// Obsluhuje ovládání klávesnice.
/// </summary>
public class KeyboardInput : GlibInput
{
private List<Key> keys;
private Key? pressedKey;
/// <summary>
/// Konstruktor.
/// </summary>
/// <param name="window">Herní okno.</param>
public KeyboardInput(GlibWindow window)
: base(window)
{
keys = new List<OpenTK.Input.Key>();
window.Keyboard.KeyDown += (o, e) => { KeyDown(e); };
window.Keyboard.KeyUp += (o, e) => { KeyUp(e); };
}
/// <summary>
/// Poslední stisknutá klávesa.
/// </summary>
public Key LastKey
{
get { return keys[keys.Count - 1]; }
}
/// <summary>
/// Všechny stisknuté klávesy.
/// </summary>
public Key[] AllPressedKeys
{
get { return keys.ToArray(); }
}
/// <summary>
/// Pokud je stisknuta klávesa.
/// </summary>
/// <param name="key">Klávesa.</param>
/// <returns>Vrací true, pokud je stisknuta.</returns>
public bool IsKeyDown(Key key)
{
return keys.Contains(key);
}
/// <summary>
/// Pokud je uvolněná klávesa.
/// </summary>
/// <param name="key">Klávesa.</param>
/// <returns>Vrací true, pokud je uvolněná.</returns>
public bool IsKeyUp(Key key)
{
return !keys.Contains(key);
}
/// <summary>
/// Pokud se stiskla klávesa (detekuje pouze první stisk).
/// </summary>
/// <param name="key">Klávesa.</param>
/// <returns>Vrací true, pokud se klávesa stiskla.</returns>
public bool IsKeyPress(Key key)
{
if (pressedKey == key && keys.Count == 1)
{
bool pressed = pressedKey.HasValue;
pressedKey = null;
return pressed;
}
return false;
}
/// <summary>
/// Klávesa se stiskla.
/// </summary>
/// <param name="e"></param>
private void KeyDown(KeyboardKeyEventArgs e)
{
if (!keys.Contains(e.Key))
keys.Add(e.Key);
if (!pressedKey.HasValue)
pressedKey = e.Key;
}
/// <summary>
/// Klávesa se uvolnila.
/// </summary>
/// <param name="e"></param>
private void KeyUp(KeyboardKeyEventArgs e)
{
keys.RemoveAll(key => { return (key == e.Key); });
pressedKey = null;
}
/// <summary>
/// Vypíše objekt klávesnice.
/// </summary>
/// <returns></returns>
public override string ToString()
{
string result = null;
for (int i = 0; i < keys.Count; i++)
{
result += keys[i].ToString();
if (i < keys.Count - 1)
result += " + ";
}
return (result == null) ? "None" : result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Net.NetworkInformation;
using System.IO;
using System.Net;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Media;
using System.Security.Cryptography;
namespace IRAP.Global
{
public class Tools
{
private static string className = "IRAP.Global.Tools";
public static string GetCpuID()
{
try
{
ManagementClass mc = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = mc.GetInstances();
string strCpuID = null;
foreach (ManagementObject mo in moc)
{
strCpuID = mo.Properties["ProcessorId"].Value.ToString();
break;
}
return strCpuID;
}
catch
{
return "";
}
}
//BIOS
public static List<string> GetBiosInfo()
{
List<string> list = new List<string>();
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_BIOS");
foreach (ManagementObject mo in searcher.Get())
{
list.Add(mo["Manufacturer"].ToString());
// mo["SerialNumber"]
}
return list;
}
catch (Exception err)
{
WriteLocalMsg("获取 BIOS 信息失败:" + err.Message);
return list;
}
}
public static List<string> GetMacByWMI()
{
List<string> macs = new List<string>();
try
{
string mac = "";
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
mac = mo["MacAddress"].ToString();
string[] addresses = (string[])mo["IPAddress"];
foreach (string ipaddress in addresses)
{
// MessageBox.Show(string.Format("IP Address: {0}", ipaddress));
}
macs.Add(mac);
}
}
moc = null;
mc = null;
}
catch (Exception err)
{
WriteLocalMsg("取 MAC 地址失败:" + err.Message);
//MessageBox.Show("取mac地址失败:" + err.Message);
}
return macs;
}
//返回描述本地计算机上的网络接口的对象(网络接口也称为网络适配器)。
public static NetworkInterface[] NetCardInfo()
{
return NetworkInterface.GetAllNetworkInterfaces();
}
/// <summary>
/// 通过NetworkInterface读取网卡Mac
/// </summary>
/// <returns></returns>
public static List<string> GetMacByNetworkInterface()
{
List<string> macs = new List<string>();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
macs.Add(ni.GetPhysicalAddress().ToString());
}
return macs;
}
//所有的网卡无论有没有启用的
public static List<string> GetIpAddress()
{
List<string> ipAddress = new List<string>();
string myHostName = Dns.GetHostName();
IPHostEntry ips = Dns.GetHostEntry(myHostName);
foreach (IPAddress ip in ips.AddressList)
{
string ipString = ip.ToString();
ipAddress.Add(ipString);
}
return ipAddress;
}
public static List<string> GetIpAddressByWMI()
{
List<string> ipAddress = new List<string>();
try
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
string[] addresses = (string[])mo["IPAddress"];
foreach (string ipaddress in addresses)
{
ipAddress.Add(ipaddress);
break;
}
}
}
moc = null;
mc = null;
}
catch (Exception err)
{
WriteLocalMsg("取 IP 地址失败:" + err.Message);
}
return ipAddress;
}
public static void WriteLocalMsg(string ErrText)
{
string FilePath = AppDomain.CurrentDomain.BaseDirectory + @"Log\";
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
FilePath += DateTime.Now.ToString("yyyy-MM-dd") + ".log";
StreamWriter sw = null;
try
{
if (!File.Exists(FilePath))
{
sw = File.CreateText(FilePath);
}
else
{
sw = File.AppendText(FilePath);
}
if (ErrText.Trim() == "")
sw.WriteLine(ErrText);
else
sw.WriteLine(DateTime.Now.ToString() + ":" + ErrText);
}
catch
{ ;}
finally
{
if (sw != null)
{
sw.Close();
}
}
}
public static SqlParameter CreateParam(SqlCommand sqlCommand,
SqlDbType sqlDbType,
int size,
ParameterDirection parameterDirection,
string parameterName,
object value)
{
SqlParameter newParam = sqlCommand.CreateParameter();
newParam.SqlDbType = sqlDbType;
newParam.Size = size;
newParam.Direction = parameterDirection;
newParam.ParameterName = parameterName;
newParam.Value = value;
return newParam;
}
public static DataSet ExecuteReturnDataSet(string strConnection,
CommandType commandType,
string cmdStr)
{
string strProcedureName = className + ".ExecuteReturnDataSet";
WriteLog.Instance.Write(cmdStr, strProcedureName);
DataSet returnDS = new DataSet();
SqlConnection dbConnection = new SqlConnection(strConnection);
try
{
SqlCommand cmd = new SqlCommand(cmdStr, dbConnection)
{
CommandTimeout = 120,
CommandType = commandType
};
SqlDataAdapter sda = new SqlDataAdapter(cmd);
dbConnection.Close();
dbConnection = null;
sda.Fill(returnDS);
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
throw error;
//returnDS = null;
}
return returnDS;
}
private static string GetWildcardRegexString(string wildcardStr)
{
Regex replace = new Regex("[.$^{\\[(|)*+?\\\\]");
return "^" + replace.Replace(
wildcardStr,
delegate(Match m)
{
switch (m.Value)
{
case "?":
return ".?";
case "*":
return ".*";
default:
return "\\" + m.Value;
}
}) + "$";
}
public static bool FileNameMatched(string fileName, List<string> fileExts)
{
Regex match = null;
string sortFileName = Path.GetFileName(fileName);
foreach (string fileExt in fileExts)
{
match = new Regex(GetWildcardRegexString(fileExt), RegexOptions.IgnoreCase);
if (match.IsMatch(fileName))
{
return true;
}
}
return false;
}
public static int ConvertToInt32(string value, int valueDefault = 0)
{
try { return Convert.ToInt32(value); }
catch { return valueDefault; }
}
public static long ConvertToInt64(string value, long valueDefault = 0)
{
try { return Convert.ToInt64(value); }
catch { return valueDefault; }
}
public static bool ConvertToBoolean(string value, bool valueDefault = false)
{
try { return Convert.ToBoolean(value); }
catch { return valueDefault; }
}
public static double ConvertToDouble(string value, double valueDefault = 0)
{
try { return Convert.ToDouble(value); }
catch { return valueDefault; }
}
public static DateTime ConvertToDateTime(string value)
{
try { return Convert.ToDateTime(value); }
catch { return Convert.ToDateTime("1900-1-1 00:00:00"); }
}
/// <summary>
/// 启动外部程序,不等待其运行结束
/// </summary>
/// <param name="appFileName">外部程序文件名(包括路径)</param>
/// <returns>0-外部程序正常启动</returns>
public int RunProcess(string appFileName)
{
try
{
System.Diagnostics.Process.Start(appFileName);
return 0;
}
catch (ArgumentException error)
{
throw new Exception(error.Message);
}
}
/// <summary>
/// 启动外部程序,等待指定时间后退出
/// </summary>
/// <param name="appFileName">外部程序文件名(包括路径)</param>
/// <param name="milliSeconds">等待时长(毫秒)(0-无限期等待)</param>
/// <returns>
/// 0-外部程序正常退出
/// 1-外部程序被强制终止
/// 2-外部程序没有正常运行
/// </returns>
public int RunProcessForWait(string appFileName, int milliSeconds = 0)
{
try
{
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(appFileName);
if (proc != null)
{
if (milliSeconds == 0)
{
proc.WaitForExit();
return 0;
}
else
{
proc.WaitForExit(milliSeconds);
if (proc.HasExited)
return 0;
else
{
proc.Kill();
return 1;
}
}
}
return 2;
}
catch (ArgumentException error)
{
throw new Exception(error.Message);
}
}
public static byte[] ImageToBytes(Image img)
{
MemoryStream ms = new MemoryStream();
img.Save(ms, img.RawFormat);
ms.Position = 0;
byte[] bytes = ms.ToArray();
ms.Close();
return bytes;
}
public static Image BytesToImage(byte[] datas)
{
try
{
MemoryStream ms = new MemoryStream(datas);
Image img = Image.FromStream(ms, true); // 在这里出错
ms.Close();
return img;
}
catch
{
return null;
}
}
public static void Play(Stream streamWav)
{
if (streamWav != null)
{
try
{
System.Media.SoundPlayer sp = new SoundPlayer(streamWav);
sp.Play();
}
catch { }
}
}
/// <summary>
/// 获取文件的MD5值
/// </summary>
/// <param name="fileName">传入的文件名(含路径与后缀名)</param>
/// <returns>MD5值</returns>
public static string GetMD5HashFromFile(string fileName)
{
try
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(fs);
fs.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception error)
{
throw new Exception("GetMD5HashFromFile() fail, error: " + error.Message);
}
}
/// <summary>
/// Convert a string of hex digits (ex: E4 CA B2) to a byte array.
/// </summary>
/// <param name="s">The string containing the hex digits (with or without spaces).</param>
/// <returns>Returns an arrray of bytes.</returns>
public static byte[] HexStringToByteArray(string s)
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}
public static string ConvertToUTF8(string unicodeString)
{
UTF8Encoding utf8 = new UTF8Encoding();
byte[] encodedBytes = utf8.GetBytes(unicodeString);
string decodedString = utf8.GetString(encodedBytes);
return decodedString;
}
}
}
|
// Copyright (c) 2020, mParticle, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Linq;
using Xunit;
namespace MP.Json.Validation.Test
{
public class KeywordSetTests
{
[Fact]
public void CountsAreAccurate()
{
Assert.Empty(default(KeywordSet));
Assert.Empty(new KeywordSet { });
Assert.True(new KeywordSet().IsEmpty);
Assert.Equal((int)Keyword.MAX_STORED, KeywordSet.All.Count);
Assert.False(KeywordSet.All.IsEmpty);
Assert.Single(new KeywordSet { Keyword.Properties });
Assert.Single(new KeywordSet { Keyword.Properties, Keyword.Properties });
Assert.Equal(2, new KeywordSet { Keyword.Properties, Keyword.Items }.Count);
Assert.False(new KeywordSet { Keyword.Properties }.IsEmpty);
Assert.False(new KeywordSet { Keyword.Properties, Keyword.Properties }.IsEmpty);
Assert.Equal(2, new KeywordSet { Keyword.Properties, Keyword.Items }.Count);
}
[Fact]
public void IsEmptyIsAccurate()
{
Assert.True(new KeywordSet().IsEmpty);
Assert.False(KeywordSet.All.IsEmpty);
Assert.False(new KeywordSet { Keyword.Properties }.IsEmpty);
Assert.False(new KeywordSet { Keyword.Properties, Keyword.Properties }.IsEmpty);
}
[Fact]
public void RemoveRemovesItems()
{
var set = new KeywordSet();
Assert.Empty(set);
set.Add(Keyword.Properties);
Assert.Single(set);
Assert.Equal(Keyword.Properties, set.Single());
Assert.False(set.Remove(Keyword.Items));
Assert.Single(set);
Assert.True(set.Remove(Keyword.Properties));
Assert.Empty(set);
var all = KeywordSet.All;
var prevCount = all.Count;
Assert.True(all.Remove(Keyword.Properties));
Assert.Equal(prevCount-1, all.Count);
Assert.False(all.Remove(Keyword.Properties));
}
[Fact]
public void ContainsTest()
{
Assert.Contains(Keyword.Properties, KeywordSet.All);
Assert.Contains(Keyword.Items, KeywordSet.All);
Assert.Contains(Keyword.Properties, new KeywordSet { Keyword.Properties });
Assert.Contains(Keyword.Maximum, new KeywordSet { Keyword.Properties, Keyword.Maximum });
Assert.DoesNotContain(Keyword.Properties, new KeywordSet());
Assert.DoesNotContain(Keyword.Items, new KeywordSet());
Assert.DoesNotContain(Keyword.Pattern, new KeywordSet { Keyword.Properties });
Assert.DoesNotContain(Keyword.Format, new KeywordSet { Keyword.Properties, Keyword.Items });
}
[Fact]
public void ClearTest()
{
var set = new KeywordSet { Keyword.Properties, Keyword.Items };
Assert.Equal(2, set.Count);
set.Clear();
Assert.Empty(set);
set = KeywordSet.All;
Assert.NotEmpty(set);
set.Clear();
Assert.Empty(set);
}
[Fact]
public void TestEnumerationAndCopyTo()
{
var set = KeywordSet.All;
var array = new Keyword[set.Count];
set.CopyTo(array, 0);
Assert.Equal(set.ToArray(), array);
Assert.Empty(new KeywordSet().ToArray());
}
[Fact]
public void IsSupersetTest()
{
var empty = KeywordSet.None;
var universe = KeywordSet.All;
var a = new KeywordSet { Keyword.AllOf };
var ac = new KeywordSet { Keyword.AllOf, Keyword.Const };
var ad = new KeywordSet { Keyword.AllOf, Keyword.DependentRequired};
var p = new KeywordSet { Keyword.Properties };
Assert.True(empty.IsSupersetOf(empty));
Assert.False(empty.IsSupersetOf(a));
Assert.False(empty.IsSupersetOf(ac));
Assert.False(empty.IsSupersetOf(ad));
Assert.False(empty.IsSupersetOf(universe));
Assert.True(a.IsSupersetOf(empty));
Assert.True(a.IsSupersetOf(a));
Assert.False(a.IsSupersetOf(ac));
Assert.False(a.IsSupersetOf(ad));
Assert.False(a.IsSupersetOf(p));
Assert.False(a.IsSupersetOf(universe));
Assert.True(ac.IsSupersetOf(empty));
Assert.True(ac.IsSupersetOf(a));
Assert.True(ac.IsSupersetOf(ac));
Assert.False(ac.IsSupersetOf(ad));
Assert.False(ac.IsSupersetOf(universe));
Assert.True(universe.IsSupersetOf(empty));
Assert.True(universe.IsSupersetOf(a));
Assert.True(universe.IsSupersetOf(ac));
Assert.True(universe.IsSupersetOf(ad));
Assert.True(universe.IsSupersetOf(universe));
}
[Fact]
public void IsSubsetTest()
{
var empty = KeywordSet.None;
var universe = KeywordSet.All;
var a = new KeywordSet { Keyword.AllOf };
var ac = new KeywordSet { Keyword.AllOf, Keyword.Const };
var ad = new KeywordSet { Keyword.AllOf, Keyword.DependentRequired };
var p = new KeywordSet { Keyword.Properties };
Assert.True(empty.IsSubsetOf(empty));
Assert.True(empty.IsSubsetOf(a));
Assert.True(empty.IsSubsetOf(ac));
Assert.True(empty.IsSubsetOf(ad));
Assert.True(empty.IsSubsetOf(universe));
Assert.False(a.IsSubsetOf(empty));
Assert.True(a.IsSubsetOf(a));
Assert.True(a.IsSubsetOf(ac));
Assert.True(a.IsSubsetOf(ad));
Assert.False(a.IsSubsetOf(p));
Assert.True(a.IsSubsetOf(universe));
Assert.False(ac.IsSubsetOf(empty));
Assert.False(ac.IsSubsetOf(a));
Assert.True(ac.IsSubsetOf(ac));
Assert.False(ac.IsSubsetOf(ad));
Assert.True(ac.IsSubsetOf(universe));
Assert.False(universe.IsSubsetOf(empty));
Assert.False(universe.IsSubsetOf(a));
Assert.False(universe.IsSubsetOf(ac));
Assert.False(universe.IsSubsetOf(ad));
Assert.True(universe.IsSubsetOf(universe));
}
[Fact]
public void OverlapsTest()
{
var empty = KeywordSet.None;
var universe = KeywordSet.All;
var a = new KeywordSet { Keyword.AllOf };
var ac = new KeywordSet { Keyword.AllOf, Keyword.Const };
var ad = new KeywordSet { Keyword.AllOf, Keyword.DependentRequired };
var p = new KeywordSet { Keyword.Properties };
Assert.False(empty.Overlaps(empty));
Assert.False(empty.Overlaps(a));
Assert.False(empty.Overlaps(ac));
Assert.False(empty.Overlaps(ad));
Assert.False(empty.Overlaps(universe));
Assert.False(a.Overlaps(empty));
Assert.True(a.Overlaps(a));
Assert.True(a.Overlaps(ac));
Assert.True(a.Overlaps(ad));
Assert.True(a.Overlaps(universe));
Assert.False(ac.Overlaps(empty));
Assert.True(ac.Overlaps(a));
Assert.True(ac.Overlaps(ac));
Assert.True(ac.Overlaps(ad));
Assert.True(ac.Overlaps(universe));
Assert.False(universe.Overlaps(empty));
Assert.True(universe.Overlaps(a));
Assert.True(universe.Overlaps(ac));
Assert.True(universe.Overlaps(ad));
Assert.True(universe.Overlaps(universe));
Assert.False(p.Overlaps(empty));
Assert.False(p.Overlaps(a));
Assert.False(p.Overlaps(ac));
Assert.False(p.Overlaps(ad));
Assert.True(p.Overlaps(universe));
}
[Fact]
public void EqualsTest()
{
var empty = KeywordSet.None;
var universe = KeywordSet.All;
var a = new KeywordSet { Keyword.AllOf };
var ad = new KeywordSet { Keyword.AllOf, Keyword.DependentRequired };
Assert.True(empty.Equals(empty));
Assert.True(a.Equals(a));
Assert.True(ad.Equals(ad));
Assert.True(universe.Equals(universe));
Assert.False(a.Equals(empty));
Assert.False(a.Equals(ad));
Assert.False(a.Equals(universe));
}
[Fact]
public void StringKeywordsTest()
{
var set = KeywordSet.StringKeywords;
Assert.Contains(Keyword.Pattern, set);
Assert.Contains(Keyword.Format, set);
Assert.Contains(Keyword.MinLength, set);
Assert.Contains(Keyword.MaxLength, set);
Assert.True(set.IsSubsetOf(KeywordSet.All));
Assert.False(set.Overlaps(KeywordSet.NumberKeywords));
Assert.False(set.Overlaps(KeywordSet.ObjectKeywords));
Assert.False(set.Overlaps(KeywordSet.ArrayKeywords));
Assert.False(set.Overlaps(KeywordSet.GenericKeywords));
}
[Fact]
public void NumberKeywordsTest()
{
var set = KeywordSet.NumberKeywords;
Assert.Contains(Keyword.Maximum, set);
Assert.Contains(Keyword.Minimum, set);
Assert.Contains(Keyword.ExclusiveMaximum, set);
Assert.Contains(Keyword.ExclusiveMinimum, set);
Assert.Contains(Keyword.MultipleOf, set);
Assert.True(set.IsSubsetOf(KeywordSet.All));
Assert.False(set.Overlaps(KeywordSet.StringKeywords));
Assert.False(set.Overlaps(KeywordSet.ObjectKeywords));
Assert.False(set.Overlaps(KeywordSet.ArrayKeywords));
Assert.False(set.Overlaps(KeywordSet.GenericKeywords));
}
[Fact]
public void ArrayKeywordsTest()
{
var set = KeywordSet.ArrayKeywords;
Assert.Contains(Keyword.MaxItems, set);
Assert.Contains(Keyword.MinItems, set);
Assert.Contains(Keyword.Items, set);
Assert.Contains(Keyword.AdditionalItems, set);
Assert.Contains(Keyword.UniqueItems, set);
Assert.Contains(Keyword.Contains, set);
Assert.Contains(Keyword.MaxContains, set);
Assert.Contains(Keyword.MinContains, set);
Assert.True(set.IsSubsetOf(KeywordSet.All));
Assert.False(set.Overlaps(KeywordSet.StringKeywords));
Assert.False(set.Overlaps(KeywordSet.ObjectKeywords));
Assert.False(set.Overlaps(KeywordSet.NumberKeywords));
Assert.False(set.Overlaps(KeywordSet.GenericKeywords));
}
[Fact]
public void ObjectKeywordsTest()
{
var set = KeywordSet.ObjectKeywords;
Assert.Contains(Keyword.MaxProperties, set);
Assert.Contains(Keyword.MinProperties, set);
Assert.Contains(Keyword.Properties, set);
Assert.Contains(Keyword.AdditionalProperties, set);
Assert.Contains(Keyword.DependentRequired, set);
Assert.Contains(Keyword.DependentSchemas, set);
Assert.Contains(Keyword.Required, set);
Assert.Contains(Keyword.PatternProperties, set);
Assert.Contains(Keyword.PropertyNames, set);
Assert.True(set.IsSubsetOf(KeywordSet.All));
Assert.False(set.Overlaps(KeywordSet.StringKeywords));
Assert.False(set.Overlaps(KeywordSet.ArrayKeywords));
Assert.False(set.Overlaps(KeywordSet.NumberKeywords));
Assert.False(set.Overlaps(KeywordSet.GenericKeywords));
}
[Fact]
public void GenericKeywordsTest()
{
var set = KeywordSet.GenericKeywords;
Assert.Contains(Keyword.AllOf, set);
Assert.Contains(Keyword.AnyOf, set);
Assert.Contains(Keyword.OneOf, set);
Assert.Contains(Keyword.Not, set);
Assert.Contains(Keyword.If, set);
Assert.Contains(Keyword.Then, set);
Assert.Contains(Keyword.Else, set);
Assert.Contains(Keyword.Const, set);
Assert.Contains(Keyword.Enum, set);
Assert.Contains(Keyword._Ref, set);
Assert.True(set.IsSubsetOf(KeywordSet.All));
Assert.False(set.Overlaps(KeywordSet.StringKeywords));
Assert.False(set.Overlaps(KeywordSet.ObjectKeywords));
Assert.False(set.Overlaps(KeywordSet.NumberKeywords));
Assert.False(set.Overlaps(KeywordSet.ArrayKeywords));
}
}
}
|
using UnityEngine;
using System;
using System.Collections;
using TreeSharpPlus;
public class B4Villager : MonoBehaviour {
protected int treeType;
public GameObject[] villagers;
private Hashtable types;
public Transform positionA;
public Transform positionB;
public Transform positionC;
public Transform positionD;
public Transform positionE;
public Transform positionF;
public Transform positionG;
public Transform positionH;
private BehaviorAgent behaviorAgent;
void Start () {
types = new Hashtable ();
for (int i = 0; i < villagers.Length; i++) {
this.treeType = UnityEngine.Random.Range (0, 100);
if (treeType >= 0 && treeType <= 33) {
behaviorAgent = new BehaviorAgent (this.BuildTreeType1 (i));
types.Add (i, 1);
} else if (treeType > 33 && treeType <= 66) {
behaviorAgent = new BehaviorAgent (this.BuildTreeType2 (i));
types.Add (i, 2);
} else if (treeType > 66 && treeType <= 100) {
behaviorAgent = new BehaviorAgent (this.BuildTreeType3 (i));
types.Add (i, 3);
}
BehaviorManager.Instance.Register (behaviorAgent);
behaviorAgent.StartBehavior ();
}
}
protected Node ST_Approach(Transform target, int villagerIndex)
{
Vector3 position = new Vector3(target.position.x+(UnityEngine.Random.Range(-3,3)),0,target.position.z+(UnityEngine.Random.Range(-3,3)));
return new Sequence(this.villagers[villagerIndex].GetComponent<BehaviorMecanim>().Node_GoTo(position));
}
protected int checkForPeople(int villagerIndex) {
for (int index = 0; index < villagers.Length; index++) {
if ((index != villagerIndex) && (Vector3.Distance (villagers [index].transform.position, villagers[villagerIndex].transform.position) < 2.0f)) {
//if(types[index] != types[villagerIndex])
return index;
}
}
return villagerIndex;
}
protected RunStatus changeDirection(Vector3 newDirection, int villagerIndex) {
villagers [villagerIndex].transform.forward = newDirection;
return RunStatus.Success;
}
protected RunStatus callOverAnim (int villagerIndex, int otherVilIndex) {
villagers [villagerIndex].GetComponent<Animator> ().Play ("CallOver");
villagers [otherVilIndex].GetComponent<Animator> ().Play ("CallOver");
return RunStatus.Success;
}
protected RunStatus cheerTogetherAnim(int villagerIndex, int otherVilIndex) {
villagers [villagerIndex].GetComponent<Animator> ().Play ("Cheer");
villagers [otherVilIndex].GetComponent<Animator> ().Play ("Cheer");
return RunStatus.Success;
}
protected RunStatus danceAnim(int villagerIndex, int otherVilIndex) {
villagers [villagerIndex].GetComponent<Animator> ().Play ("BD1");
villagers [otherVilIndex].GetComponent<Animator> ().Play ("BD1");
return RunStatus.Success;
}
protected RunStatus chestSaluteAnim(int villagerIndex, int otherVilIndex) {
villagers [villagerIndex].GetComponent<Animator> ().Play ("ChestPumpSalute");
villagers [otherVilIndex].GetComponent<Animator> ().Play ("ChestPumpSalute");
return RunStatus.Success;
}
protected RunStatus handsUpAnim(int villagerIndex, int otherVilIndex) {
villagers [villagerIndex].GetComponent<Animator> ().Play ("HandsUp");
villagers [otherVilIndex].GetComponent<Animator> ().Play ("HandsUp");
return RunStatus.Success;
}
protected RunStatus hitFromBehindAnim(int villagerIndex, int otherVilIndex) {
villagers [villagerIndex].GetComponent<Animator> ().Play ("HitFromBehind");
villagers [otherVilIndex].GetComponent<Animator> ().Play ("HitFromBehind");
return RunStatus.Success;
}
protected Node BuildTreeType1(int villagerIndex) {
Val<int> nearbyPerson = Val.V(() => checkForPeople(villagerIndex));
Func<RunStatus> changeFacingCurrent = () => changeDirection (villagers [nearbyPerson.Value].transform.position, villagerIndex);
Func<RunStatus> changeFacingOther = () => changeDirection (villagers [villagerIndex].transform.position, nearbyPerson.Value);
Func<RunStatus> callOver = () => callOverAnim (villagerIndex,nearbyPerson.Value);
Node callOverNode = new Sequence(new LeafInvoke(callOver), new LeafWait(4000));
Func<RunStatus> cheerTogether = () => cheerTogetherAnim (villagerIndex, nearbyPerson.Value);
Node cheerTogetherNode = new Sequence(new LeafInvoke(cheerTogether), new LeafWait(5000));
Node randomActions = new SelectorShuffle (callOverNode,cheerTogetherNode);
Node path = new SequenceShuffle (randomActions, new SelectorShuffle(this.ST_Approach(positionA, villagerIndex),this.ST_Approach(positionB, villagerIndex),this.ST_Approach(positionC, villagerIndex), this.ST_Approach(positionD, villagerIndex), this.ST_Approach(positionE, villagerIndex), this.ST_Approach(positionF, villagerIndex), this.ST_Approach(positionG, villagerIndex),this.ST_Approach(positionH, villagerIndex)));
Node root = new DecoratorLoop (path);
return root;
}
protected Node BuildTreeType2(int villagerIndex) {
Val<int> nearbyPerson = Val.V(() => checkForPeople(villagerIndex));
Func<RunStatus> changeFacingCurrent = () => changeDirection (villagers [nearbyPerson.Value].transform.position, villagerIndex);
Func<RunStatus> changeFacingOther = () => changeDirection (villagers [villagerIndex].transform.position, nearbyPerson.Value);
Func<RunStatus> dance = () => danceAnim (villagerIndex,nearbyPerson.Value);
Node danceNode = new Sequence(new LeafInvoke(dance), new LeafWait(10000));
Func<RunStatus> chestSalute = () => chestSaluteAnim (villagerIndex, nearbyPerson.Value);
Node chestSaluteNode = new Sequence(new LeafInvoke(chestSalute), new LeafWait(5000));
Node randomActions = new SelectorShuffle (danceNode,chestSaluteNode);
Node path = new SequenceShuffle (randomActions, new SelectorShuffle(this.ST_Approach(positionA, villagerIndex),this.ST_Approach(positionB, villagerIndex),this.ST_Approach(positionC, villagerIndex), this.ST_Approach(positionD, villagerIndex), this.ST_Approach(positionE, villagerIndex), this.ST_Approach(positionF, villagerIndex), this.ST_Approach(positionG, villagerIndex),this.ST_Approach(positionH, villagerIndex)));
Node root = new DecoratorLoop (path);
return root;
}
protected Node BuildTreeType3(int villagerIndex) {
Val<int> nearbyPerson = Val.V(() => checkForPeople(villagerIndex));
Func<RunStatus> changeFacingCurrent = () => changeDirection (villagers [nearbyPerson.Value].transform.position, villagerIndex);
Func<RunStatus> changeFacingOther = () => changeDirection (villagers [villagerIndex].transform.position, nearbyPerson.Value);
Func<RunStatus> handsUp = () => handsUpAnim (villagerIndex,nearbyPerson.Value);
Node handsUpNode = new Sequence(new LeafInvoke(handsUp), new LeafWait(4000));
Func<RunStatus> hitFromBehind = () => hitFromBehindAnim (villagerIndex, nearbyPerson.Value);
Node hitFromBehindNode = new Sequence(new LeafInvoke(hitFromBehind), new LeafWait(5000));
Node randomActions = new SelectorShuffle (handsUpNode,hitFromBehindNode);
Node path = new SequenceShuffle (randomActions, new SelectorShuffle(this.ST_Approach(positionA, villagerIndex),this.ST_Approach(positionB, villagerIndex),this.ST_Approach(positionC, villagerIndex), this.ST_Approach(positionD, villagerIndex), this.ST_Approach(positionE, villagerIndex), this.ST_Approach(positionF, villagerIndex), this.ST_Approach(positionG, villagerIndex),this.ST_Approach(positionH, villagerIndex)));
Node root = new DecoratorLoop (path);
return root;
}
} |
using LHRLA.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LHRLA.LHRLA.DAL
{
public class CaseRegisterationTypesDataAccess
{
#region Insert
public bool AddCaseRegisterationTypes(tbl_Case_Registeration_Types row)
{
try
{
using (var db = new vt_LHRLAEntities())
{
db.tbl_Case_Registeration_Types.Add(row);
db.SaveChanges();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
#endregion
#region Update
public bool UpdateCaseRegisterationTypes(tbl_Case_Registeration_Types row)
{
try
{
using (var db = new vt_LHRLAEntities())
{
tbl_Case_Registeration_Types val = new tbl_Case_Registeration_Types();
val = db.tbl_Case_Registeration_Types.Where(a => a.ID == row.ID).FirstOrDefault();
val.Type = row.Type;
val.Description = row.Description;
val.Is_Active = row.Is_Active;
db.SaveChanges();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
#endregion
#region Delete
#endregion
#region Select
public List<tbl_Case_Registeration_Types> GetAllCaseRegisterationTypes()
{
try
{
List<tbl_Case_Registeration_Types> lst = new List<tbl_Case_Registeration_Types>();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_Case_Registeration_Types.ToList();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
public List<tbl_Case_Registeration_Types> GetAllActiveCaseRegisterationTypes()
{
try
{
List<tbl_Case_Registeration_Types> lst = new List<tbl_Case_Registeration_Types>();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_Case_Registeration_Types.ToList().Where(a => a.Is_Active == true).ToList();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
public List<tbl_Case_Registeration_Types> CheckDuplicateData(string Type)
{
try
{
List<tbl_Case_Registeration_Types> lst = new List<tbl_Case_Registeration_Types>();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_Case_Registeration_Types.ToList().Where(a => a.Type == Type).ToList();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
public List<tbl_Case_Registeration_Types> GetCaseRegisterationTypesbyID(int ID)
{
try
{
List<tbl_Case_Registeration_Types> lst = new List<tbl_Case_Registeration_Types>();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_Case_Registeration_Types.Where(e => e.ID == ID).ToList();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
public List<tbl_Case_Registeration_Types> GetCaseRegisterationTypesbyIDOnUpdate(int ID,string type)
{
try
{
List<tbl_Case_Registeration_Types> lst = new List<tbl_Case_Registeration_Types>();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_Case_Registeration_Types.Where(e => e.ID != ID && e.Type == type).ToList();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
public List<tbl_Case_Registeration_Types> GetCaseRegisterationTypesOfExistingData(int ID, string type)
{
try
{
List<tbl_Case_Registeration_Types> lst = new List<tbl_Case_Registeration_Types>();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_Case_Registeration_Types.Where(e => e.ID == ID && e.Type == type).ToList();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
public List<tbl_Case_Registeration_Types> GetActiveCaseRegisterationTypesbyID(int ID)
{
try
{
List<tbl_Case_Registeration_Types> lst = new List<tbl_Case_Registeration_Types>();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_Case_Registeration_Types.Where(e => e.ID == ID && e.Is_Active == true).ToList();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
} |
using UnityEngine;
using UnityEditor;
using System.IO;
namespace UnityAtoms.Editor
{
[CustomEditor(typeof(DefaultAsset))]
public class AtomFolderEditor : UnityEditor.Editor
{
protected override void OnHeaderGUI()
{
base.OnHeaderGUI();
if (!Directory.Exists(AssetDatabase.GetAssetPath(target))) return;
if (!target.name.ToLowerInvariant().Contains("atom")) return;
GUILayout.Label("UNITY ATOMS", (GUIStyle) "AC BoldHeader", GUILayout.ExpandWidth(true));
if (GUILayout.Button("Add Generator", (GUIStyle) "LargeButton"))
{
var asset = CreateInstance<AtomGenerator>();
var newPath = Path.Combine(
AssetDatabase.GetAssetPath(target),
"New Atom Type.asset"
);
newPath = AssetDatabase.GenerateUniqueAssetPath(newPath);
Debug.Log(newPath);
AssetDatabase.CreateAsset(asset, newPath);
AssetDatabase.ImportAsset(newPath);
}
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace CollaborativeFiltering
{
public class RatingService : IRatingService
{
protected IRater FirstRater;
protected IRater SecondRater;
protected IEnumerable<IRating> RatingsFirstSort;
protected IEnumerable<IRating> RatingsSecondSort;
protected int IndexFirst;
protected int IndexSecond;
protected int CountFirst;
protected int CountSecond;
protected virtual void Initialize(IRater firstRater, IRater secondRater) //O(nlogn)
{
FirstRater = firstRater;
SecondRater = secondRater;
RatingsFirstSort = firstRater.Ratings.OrderBy(p => p.Subject.Id);
RatingsSecondSort = secondRater.Ratings.OrderBy(p => p.Subject.Id);
IndexFirst = 0;
IndexSecond = 0;
CountFirst = RatingsFirstSort.Count();
CountSecond = RatingsSecondSort.Count();
}
public virtual IEnumerable<Pair> GetCommonRatings(IRater firstRater, IRater secondRater) //O(n)
{
if (FirstRater != firstRater || SecondRater != secondRater)
Initialize(firstRater, secondRater);
while (IndexFirst < CountFirst && IndexSecond < CountSecond)
{
var firstRating = RatingsFirstSort.ElementAt(IndexFirst);
var secondRating = RatingsSecondSort.ElementAt(IndexSecond);
var pair = ProcessRatings(firstRating, secondRating);
if(pair != null)
yield return pair;
}
}
protected virtual Pair ProcessRatings(IRating firstRating, IRating secondRating)
{
var pair = null as Pair;
if (firstRating.Subject.Id == secondRating.Subject.Id)
{
pair = new Pair() { FirstRating = firstRating, SecondRating = secondRating };
++IndexFirst;
++IndexSecond;
}
else if (firstRating.Subject.Id < secondRating.Subject.Id)
++IndexFirst;
else
++IndexSecond;
return pair;
}
}
}
|
using System;
namespace UnityAtoms.FSM
{
/// <summary>
/// Needed in order to use our custom property drawer for states in the FSM.
/// </summary>
[Serializable]
public class FSMStateListWrapper : AtomListWrapper<FSMState> { }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Windows.Forms;
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.ActiveMQ.Commands;
namespace IRAPPrinterServer
{
internal class DoActionFromESB
{
private string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private string esbUri = "";
private string esbQueueName = "";
private string esbFilter = "";
private IConnectionFactory factory = null;
private IConnection connection = null;
private ISession session = null;
private IMessageConsumer consumer = null;
/// <summary>
/// 当前 ESB 连接状态
/// 0: 未连接;
/// 1: 正在连接中;
/// 2: 连接成功
/// </summary>
private int esbConnectStatus = 0;
/// <summary>
/// 上次尝试 ESB 连接时间
/// </summary>
private DateTime lastESBConnectTime = DateTime.Now;
/// <summary>
/// 再次尝试连接 ESB 的间隔时间
/// </summary>
private int esbReconnectSpantime = 60;
private Timer tmrReconnect = new Timer();
public DoActionFromESB(string uri, string queueName, string filter)
{
esbUri = uri;
this.esbQueueName = queueName;
this.esbFilter = filter;
tmrReconnect.Interval = 100;
tmrReconnect.Tick += TmrReconnect_Tick;
}
~DoActionFromESB()
{
tmrReconnect.Enabled = false;
tmrReconnect.Tick -= TmrReconnect_Tick;
tmrReconnect = null;
}
private void TmrReconnect_Tick(object sender, EventArgs e)
{
tmrReconnect.Enabled = false;
try
{
switch (esbConnectStatus)
{
case 0:
TimeSpan span = DateTime.Now - lastESBConnectTime;
if (span.TotalSeconds >= esbReconnectSpantime)
{
CloseConsumer();
System.Threading.Thread.Sleep(500);
InitConsumer();
}
break;
}
}
finally
{
tmrReconnect.Enabled = true;
}
}
public LogOutputHandler OutputLog = null;
public AppendMessageContext Write2Queue = null;
private void WriteLog(string msg, string modeName, ToolTipIcon icon)
{
if (OutputLog != null)
OutputLog(msg, modeName, icon);
}
private void InitConsumer()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
try
{
WriteLog("连接 ESB ......", strProcedureName, ToolTipIcon.Info);
esbConnectStatus = 1;
lastESBConnectTime = DateTime.Now;
string brokerUri =
string.Format(
"failover://({0})?&transport.startupMaxReconnectAttempts=1&" +
"transport.initialReconnectDelay=10",
esbUri);
factory = new ConnectionFactory(brokerUri);
connection = factory.CreateConnection();
connection.ClientId = System.Guid.NewGuid().ToString();
connection.Start();
session = connection.CreateSession();
consumer =
session.CreateConsumer(
new ActiveMQQueue(esbQueueName),
string.Format(
"Filter='{0}'",
esbFilter));
consumer.Listener += new MessageListener(consumer_Listener);
esbConnectStatus = 2;
WriteLog("ESB 连接成功,开始接收打印申请......", strProcedureName, ToolTipIcon.Info);
}
catch (Exception error)
{
esbConnectStatus = 0;
lastESBConnectTime = DateTime.Now;
WriteLog(
string.Format(
"EBS 连接失败:{0}",
error.Message),
strProcedureName,
ToolTipIcon.Error);
}
}
private void CloseConsumer()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
if (consumer != null)
{
consumer.Close();
consumer = null;
}
if (session != null)
{
session.Close();
session = null;
}
if (connection != null)
{
connection.Close();
connection = null;
}
factory = null;
esbConnectStatus = 0;
lastESBConnectTime = DateTime.Now;
OutputLog("停止打印服务,关闭 ESB 连接。", strProcedureName, ToolTipIcon.Info);
}
private void consumer_Listener(IMessage message)
{
ITextMessage msg = (ITextMessage)message;
if (Write2Queue != null)
Write2Queue(msg.Text);
}
public void Start()
{
if (esbConnectStatus == 1 || esbConnectStatus == 2)
return;
else
{
InitConsumer();
tmrReconnect.Enabled = true;
}
}
public void Stop()
{
tmrReconnect.Enabled = false;
CloseConsumer();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FSDP.DATA.EF//.Metadata
{
public class CourseMetadata
{
[Required(ErrorMessage = "* Course Name Required.")]
[Display(Name = "Course Name")]
[StringLength(200, ErrorMessage = "* Course Name cannot exceed 200 characters.")]
public string CourseName { get; set; }
[UIHint("MultilineText")]
[DisplayFormat(NullDisplayText = "- No description available -")]
[StringLength(500, ErrorMessage = "* Description cannot exceed 500 characters.")]
public string Description { get; set; }
//bool does not require any further data annotations
[Display(Name = "Active?")]
public bool IsActive { get; set; }
}
[MetadataType(typeof(CourseMetadata))]
public partial class Cours { }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Animal.Mammal
{
public class Doge
{
public void SayHello()
{
Console.WriteLine("我是小狗,汪汪汪~");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using V50_IDOMBackOffice.AspxArea.MasterData.Models;
using V50_IDOMBackOffice.AspxArea.MasterData.Controllers;
using V50_IDOMBackOffice.AspxArea.Helper;
using DevExpress.Web;
namespace V50_IDOMBackOffice.AspxArea.MasterData.Forms
{
public partial class PlaceView : System.Web.UI.Page
{
PlaceViewController controller = new PlaceViewController();
protected void Page_Load(object sender, EventArgs e)
{
Bind();
}
private void Bind()
{
GridPlaceView.DataSource = controller.Init();
GridPlaceView.DataBind();
}
protected void GridPlaceView_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
PlaceViewModel model = new PlaceViewModel();
model.PlaceId = e.NewValues["PlaceId"]==null? 0:(int)e.NewValues["PlaceId"];
model.RegionId = e.NewValues["RegionId"] == null ? 0 : (int)e.NewValues["RegionId"];
model.PlaceName = e.NewValues["PlaceName"].ToString()?? string.Empty;
model.ImageGalleryPath = e.NewValues["ImageGalleryPath"].ToString()?? string.Empty;
model.ImageThumbnailsPath = e.NewValues["ImageThumbnailsPath"].ToString()?? string.Empty;
controller.AddPlace(model);
e.Cancel = true;
GridPlaceView.CancelEdit();
Bind();
}
protected void GridPlaceView_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
var listSaP = (List<PlaceViewModel>)GridPlaceView.DataSource;
PlaceViewModel model = listSaP.Find(m => m.Id == e.Keys[0].ToString());
model.PlaceId = e.NewValues["PlaceId"] == null ? 0 : (int)e.NewValues["PlaceId"];
model.RegionId = e.NewValues["RegionId"] == null ? 0 : (int)e.NewValues["RegionId"];
model.PlaceName = e.NewValues["PlaceName"].ToString() ?? string.Empty;
model.ImageGalleryPath = e.NewValues["ImageGalleryPath"].ToString() ?? string.Empty;
model.ImageThumbnailsPath = e.NewValues["ImageThumbnailsPath"].ToString() ?? string.Empty;
controller.UpdatePlace(model);
e.Cancel = true;
GridPlaceView.CancelEdit();
Bind();
}
protected void GridPlaceView_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
{
string id = e.Keys[0].ToString();
controller.DeletePlace(id);
e.Cancel = true;
GridPlaceView.CancelEdit();
Bind();
}
protected void GridPlaceView_DataBinding(object sender, EventArgs e)
{
GridPlaceView.ForceDataRowType(typeof(PlaceViewModel));
}
protected void GridPlaceView_Init(object sender, EventArgs e)
{
GridPlaceView.Columns["Id"].Visible = false;
GridPlaceView.Columns["ImageGalleryPath"].Visible = false;
GridPlaceView.Columns["ImageThumbnailsPath"].Visible = false;
}
protected void GridPlaceView_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
{
if (GridPlaceView.IsNewRowEditing)
GridPlaceView.DoRowValidation();
}
protected void GridPlaceView_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e)
{
GridValidation.ValidateInt("PlaceId", sender, e);
GridValidation.ValidateInt("RegionId", sender, e);
GridValidation.ValidateLength("PlaceName",2, sender, e);
GridValidation.ValidateLength("ImageThumbnailsPath",2, sender, e);
GridValidation.ValidateLength("ImageGalleryPath",2, sender, e);
}
protected void GridPlaceView_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
{
if (e.Column.FieldName == "RegionId")
{
ASPxComboBox combo = (ASPxComboBox)e.Editor;
combo.DataSource = controller.GetRegionIds();
combo.DataBind();
}
}
}
} |
using System.IO;
using System.IO.Compression;
// ReSharper disable once CheckNamespace
namespace Aquarium.Util.Extension.CompressionExtension
{
public static class DeflateExtension
{
#region Deflate
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="invokType"></param>
/// <returns></returns>
private static byte[] DeflateBytes(this byte[] bytes, CompressionMode invokType = CompressionMode.Compress)
{
if (bytes == null) return null;
if (invokType == CompressionMode.Compress)
using (var output = new MemoryStream())
{
using (
var compressor = new DeflateStream(
output, invokType))
{
compressor.Write(bytes, 0, bytes.Length);
}
return output.ToArray();
}
else
using (var output = new MemoryStream())
{
using (var ms = new MemoryStream(bytes) {Position = 0})
{
using (
var compressor = new DeflateStream(ms, invokType))
{
var buf = new byte[1024];
int len;
while ((len = compressor.Read(buf, 0, buf.Length)) > 0)
output.Write(buf, 0, len);
}
}
return output.ToArray();
}
}
/// <summary>
/// 使用Deflate压缩算法解压缩字节
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static byte[] DecompressDeflate(this byte[] bytes)
{
return bytes.DeflateBytes(CompressionMode.Decompress);
}
/// <summary>
/// 使用Deflate压缩算法压缩字节
/// </summary>
/// <param name="bytes">要压缩的字节</param>
/// <returns>压缩后的字节</returns>
public static byte[] CompressDeflate(this byte[] bytes)
{
return bytes.DeflateBytes();
}
#endregion Deflate
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.EventSystems;
public class PlayerController : MonoBehaviour {
/// <summary>
/// 射线检测的起点
/// </summary>
public Transform rayDown, rayLeft, rayRight;
/// <summary>
/// 射线检测的层级
/// </summary>
public LayerMask platformLayer, obstacleLayer;
/// <summary>
/// 是否向左跳动
/// </summary>
private bool isMoveLeft = false;
/// <summary>
/// 是否正在跳跃
/// </summary>
private bool isJumping = false;
/// <summary>
/// 是否开始移动
/// </summary>
private bool isStartMove = false;
private Rigidbody2D myBody;
private SpriteRenderer SpriteRenderer;
private Vector3 nextPlatformLeft, nextPlatformRight;
private ManagerVas vars;
private void Awake()
{
myBody = GetComponent<Rigidbody2D>();
SpriteRenderer = GetComponent<SpriteRenderer>();
vars = ManagerVas.GetManagerVas();
}
private void Update()
{
Debug.DrawRay(rayDown.position, Vector2.down * 1f, Color.red);
Debug.DrawRay(rayLeft.position, Vector2.left * 0.15f, Color.red);
Debug.DrawRay(rayRight.position, Vector2.right * 0.15f, Color.red);
//是否点击的是ui
if (EventSystem.current.IsPointerOverGameObject())
{
return;
}
//游戏未开始或已结束或暂停
if (!GameManager.Instance.IsGameStarted || GameManager.Instance.IsGameOver || GameManager.Instance.IsGamePause)
{
return;
}
if (Input.GetMouseButtonDown(0) && !isJumping)
{
if (!isStartMove)
{
isStartMove = true;
EventCenter.Broadcast(EventDefine.PlayerStartMove);
}
EventCenter.Broadcast(EventDefine.DecidePath);
isJumping = true;
Vector3 mouseClickPos = Input.mousePosition;
//点击屏幕左边
if (mouseClickPos.x <= Screen.width / 2)
{
isMoveLeft = true;
}
else
{
isMoveLeft = false;
}
Jump();
}
//游戏结束
if (myBody.velocity.y < 0 && !IsRayPlatform() && !GameManager.Instance.IsGameOver)//y方向速度小于0,代表往下落,并且没有检测到平台,游戏没有结束
{
SpriteRenderer.sortingLayerName = "Default";
GetComponent<BoxCollider2D>().enabled = false;
GameManager.Instance.IsGameOver = true;
}
if (isJumping && IsRayObstacle() && !GameManager.Instance.IsGameOver)//正在跳跃,检测到障碍物,游戏没有结束
{
GameManager.Instance.IsGameOver = true;
Destroy(gameObject);
GameObject go = ObjectPool.Instance.GetDeathEffect();
go.transform.position = transform.position;
go.SetActive(true);
}
if (transform.position.y - Camera.main.transform.position.y < -6 && !GameManager.Instance.IsGameOver)
{
gameObject.SetActive(false);
GameManager.Instance.IsGameOver = true;
}
}
/// <summary>
/// 上一次碰到的平台
/// </summary>
private GameObject lastHitGO = null;
/// <summary>
/// 是否检测到平台
/// </summary>
/// <returns></returns>
private bool IsRayPlatform()
{
RaycastHit2D hit = Physics2D.Raycast(rayDown.position, Vector2.down, 1f, platformLayer);
if(hit.collider != null)
{
if(hit.collider.tag == "Platform")
{
if(hit.collider.gameObject != lastHitGO)
{
if (lastHitGO == null)
{
lastHitGO = hit.collider.gameObject;
return true;
}
EventCenter.Broadcast(EventDefine.AddScore);
lastHitGO = hit.collider.gameObject;
}
return true;
}
}
return false;
}
/// <summary>
/// 是否检测到障碍物
/// </summary>
/// <returns></returns>
private bool IsRayObstacle()
{
RaycastHit2D hitLeft = Physics2D.Raycast(rayLeft.position, Vector2.left, 0.15f, obstacleLayer);
RaycastHit2D hitRight = Physics2D.Raycast(rayRight.position, Vector2.right, 0.15f, obstacleLayer);
if (hitLeft.collider != null)
{
if (hitLeft.collider.tag == "Obstacle")
{
return true;
}
}
if (hitRight.collider != null)
{
if (hitRight.collider.tag == "Obstacle")
{
return true;
}
}
return false;
}
private void Jump()
{
if (isMoveLeft)
{
transform.localScale = new Vector3(-1, 1, 1);
transform.DOMoveX(nextPlatformLeft.x, 0.2f);
transform.DOMoveY(nextPlatformLeft.y + 0.8f, 0.15f);
}
else
{
transform.localScale = Vector3.one;
transform.DOMoveX(nextPlatformRight.x, 0.2f);
transform.DOMoveY(nextPlatformRight.y + 0.8f, 0.15f);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Platform")
{
isJumping = false;
Vector3 curPlatformPos = collision.transform.position;
nextPlatformLeft = new Vector3(curPlatformPos.x - vars.nextXPos, curPlatformPos.y + vars.nextYPos, 0);
nextPlatformRight = new Vector3(curPlatformPos.x + vars.nextXPos, curPlatformPos.y + vars.nextYPos, 0);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
//吃到钻石
if (collision.collider.tag == "PickUp")
{
EventCenter.Broadcast(EventDefine.AddDiamond);
collision.gameObject.SetActive(false);
}
}
}
|
using Microsoft.AspNetCore.Mvc;
namespace DojoSurvey
{
public class SurveyController : Controller
{
[HttpGet("")]
public ViewResult Index()
{
return View();
}
[HttpPost("result")]
public IActionResult Result(string name, string loc, string lang, string comment)
{
ViewBag.Name = name;
ViewBag.Location = loc;
ViewBag.Language = lang;
ViewBag.Comment = comment;
return View();
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace Utilities.Serialization
{
public static class ObjectSerializer
{
public static string XmlSerialize<T>(this T objectToSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.Formatting = Formatting.Indented;
xmlSerializer.Serialize(xmlWriter, objectToSerialize);
return stringWriter.ToString();
}
public static string XmlDeserialize<T>(this T objectToSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.Formatting = Formatting.Indented;
xmlSerializer.Serialize(xmlWriter, objectToSerialize);
return stringWriter.ToString();
}
}
}
|
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
public class ItemColliction
{
private static DashData _dash;
private static DoubleData _double;
private static MagnetData _magnet;
private static ProtectData _protect;
private static SuperManData _superMan;
private static StartDashData _startDash;
private static DeadDashData _deadDash;
private List<AItemData> _colliction;
#region 数据对象
public static DashData Dash
{
get
{
if (_dash == null)
{
_dash = new DashData();
}
return _dash;
}
}
public static DoubleData Double
{
get
{
if (_double == null)
{
_double = new DoubleData();
}
return _double;
}
}
public static MagnetData Magnet
{
get
{
if (_magnet == null)
{
_magnet = new MagnetData();
}
return _magnet;
}
}
public static ProtectData Protect
{
get
{
if (_protect == null)
{
_protect = new ProtectData();
}
return _protect;
}
}
public static SuperManData SuperMan
{
get
{
if (_superMan == null)
{
_superMan = new SuperManData();
}
return _superMan;
}
}
public static StartDashData StartDash
{
get
{
if (_startDash == null)
{
_startDash = new StartDashData();
}
return _startDash;
}
}
public static DeadDashData DeadDash
{
get
{
if (_deadDash == null)
{
_deadDash = new DeadDashData();
}
return _deadDash;
}
}
public List<AItemData> Colliction
{
get
{
if (_colliction == null)
{
_colliction = new List<AItemData>();
}
return _colliction;
}
}
#endregion
public void Update()
{
for (int i = 0; i < Colliction.Count; i++)
{
AItemData temp = Colliction[i];
if (temp.IsRun())
{
temp.Update();
}
}
}
public void TheBuyItems()
{
//购买道具的实现
BuyTheItems.SetTheItems();
}
public ItemColliction()
{
Initialize(Dash);
Initialize(Double);
Initialize(Magnet);
Initialize(Protect);
Initialize(SuperMan);
Initialize(StartDash);
Initialize(DeadDash);
}
private void Initialize(AItemData item)
{
item.Initialize();
Colliction.Add(item);
}
//释放对象,清理内存
public void Clear()
{
_dash = null;
_double = null;
_magnet = null;
_protect = null;
_superMan = null;
_startDash = null;
_deadDash = null;
_colliction = null;
}
}
/// <summary>
/// 道具数据抽象类
/// </summary>
public abstract class AItemData
{
/// <summary>
/// 此道具持续时间
/// </summary>
public float Time { set; get; }
/// <summary>
/// 正在执行的协程对象
/// </summary>
protected Coroutine PreviousCoroutine { set; get; }
/// <summary>
/// 实例化
/// </summary>
public abstract void Initialize();
/// <summary>
/// 此道具是否正在运行
/// </summary>
/// <returns></returns>
public abstract bool IsRun();
/// <summary>
/// 进入道具状态
/// </summary>
public abstract void EnterState();
/// <summary>
/// 退出道具状态
/// </summary>
protected abstract void ExitState();
/// <summary>
/// 每帧执行函数
/// </summary>
public abstract void Update();
public void OpenItemCollider()
{
if (ItemColliction.Magnet.IsRun() || ItemColliction.Double.IsRun() || ItemColliction.Dash.IsRun()||ItemColliction.StartDash.IsRun()||ItemColliction.DeadDash.IsRun())
{
HumanColliderManager.Item_Collider.SetActive(true);
}
}
}
/// <summary>
/// 冲刺数据类
/// </summary>
public class DashData : AItemData
{
private StateMachine<ItemState> _dash_Machine;
public StateMachine<ItemState> Dash_Machine
{
get
{
if (_dash_Machine == null)
{
_dash_Machine = new StateMachine<ItemState>();
}
return _dash_Machine;
}
}
public override bool IsRun()
{
if (Dash_Machine.CurrentState == ItemState.Dash)
{
return true;
}
else
{
return false;
}
}
public override void EnterState()
{
if (!GameUIManager.Is_Resurgence)
{
GameGuidance.Instance.GuidanceDash++;
}
if(BuyTheItems.start_Dash_Bool)
return;
Dash_Machine.CurrentState = ItemState.Dash;
//关闭还未结束的此状态协程
if (PreviousCoroutine != null)
{
HumanManager.Nature.Human_Script.StopCoroutine(PreviousCoroutine);
}
PreviousCoroutine = HumanManager.Nature.Human_Script.StartCoroutine(DashTime());
OpenItemCollider();
}
IEnumerator DashTime()
{
float times = 0;
yield return new WaitUntil(() =>
{
if (MyKeys.Pause_Game)
return false;
times++;
return times >= ItemColliction.Dash.Time * 60;
});
ExitState();
}
protected override void ExitState()
{
Dash_Machine.CurrentState = ItemState.Null;
HumanManager.Nature.HumanManager_Script.CurrentState = HumanState.Jump;
ItemColliction.SuperMan.Time = 1.0f;
HumanManager.Nature.HumanManager_Script.ItemState = ItemState.SuperMan;
ItemCollider();
PreviousCoroutine = null;
}
public override void Update()
{
Dash_Machine.Update();
}
public override void Initialize()
{
Dash_Machine.AddState(ItemState.Dash, new Dash(HumanManager.Nature));
Dash_Machine.AddState(ItemState.Null, new Null(HumanManager.Nature));
Dash_Machine.CurrentState = ItemState.Null;
Time = HumanManager.Nature.Dash_Time;
}
//检测是否开启或关闭碰撞框
public void ItemCollider()
{
if (ItemColliction.Magnet.IsRun() || ItemColliction.Double.IsRun())
{
HumanColliderManager.Item_Collider.SetActive(true);
}
else
{
HumanColliderManager.Item_Collider.SetActive(false);
}
}
}
/// <summary>
/// 双倍数据类
/// </summary>
public class DoubleData : AItemData
{
private StateMachine<ItemState> _double_Machine;
public StateMachine<ItemState> Double_Machine
{
get
{
if (_double_Machine == null)
{
_double_Machine = new StateMachine<ItemState>();
}
return _double_Machine;
}
}
public override bool IsRun()
{
if (Double_Machine.CurrentState == ItemState.Double)
{
return true;
}
else
{
return false;
}
}
public override void EnterState()
{
GameGuidance.Instance.GuidanceDouble++;
Double_Machine.CurrentState = ItemState.Double;
//Times++;
//关闭还未结束的此状态协程
if (PreviousCoroutine != null)
{
HumanManager.Nature.Human_Script.StopCoroutine(PreviousCoroutine);
}
PreviousCoroutine = HumanManager.Nature.Human_Script.StartCoroutine(DoubleTime());
OpenItemCollider();
}
IEnumerator DoubleTime()
{
float times = 0;
yield return new WaitUntil(() =>
{
if (MyKeys.Pause_Game)
return false;
times++;
return times >= ItemColliction.Double.Time * 60;
});
ExitState();
}
protected override void ExitState()
{
Double_Machine.CurrentState = ItemState.Null;
ItemCollider();
PreviousCoroutine = null;
}
public override void Update()
{
Double_Machine.Update();
}
public override void Initialize()
{
Double_Machine.AddState(ItemState.Double, new Double(HumanManager.Nature));
Double_Machine.AddState(ItemState.Null, new Null(HumanManager.Nature));
Double_Machine.CurrentState = ItemState.Null;
Time = HumanManager.Nature.Double_Time;
}
//检测是否开启或关闭碰撞框
public void ItemCollider()
{
if (ItemColliction.Magnet.IsRun() || ItemColliction.Dash.IsRun()||ItemColliction.StartDash.IsRun())
{
HumanColliderManager.Item_Collider.SetActive(true);
}
else
{
HumanColliderManager.Item_Collider.SetActive(false);
}
}
}
/// <summary>
/// 护盾数据类
/// </summary>
public class ProtectData : AItemData
{
private StateMachine<ItemState> _protect_Machine;
private Coroutine _coroutine;
public StateMachine<ItemState> Protect_Machine
{
get
{
if (_protect_Machine == null)
{
_protect_Machine = new StateMachine<ItemState>();
}
return _protect_Machine;
}
}
public override bool IsRun()
{
if (Protect_Machine.CurrentState == ItemState.Protect)
{
return true;
}
else
{
return false;
}
}
public override void EnterState()
{
GameGuidance.Instance.GuidanceProtect++;
if (_coroutine != null)
{
HumanManager.Nature.Human_Script.StopCoroutine(_coroutine);
}
Protect_Machine.CurrentState = ItemState.Protect;
_coroutine = HumanManager.Nature.Human_Script.StartCoroutine(ProtectTime());
}
IEnumerator ProtectTime()
{
float times = 0;
yield return new WaitUntil(() =>
{
if (MyKeys.Pause_Game)
return false;
times++;
return times >= ItemColliction.Protect.Time * 60;
});
ExitState();
}
public void Exit()
{
ExitState();
}
protected override void ExitState()
{
Protect_Machine.CurrentState = ItemState.Null;
}
public override void Update()
{
Protect_Machine.Update();
}
public override void Initialize()
{
Protect_Machine.AddState(ItemState.Protect, new Protect(HumanManager.Nature));
Protect_Machine.AddState(ItemState.Null, new Null(HumanManager.Nature));
Protect_Machine.CurrentState = ItemState.Null;
Time = HumanManager.Nature.Protect_Time;
}
}
/// <summary>
/// 无敌数据类
/// </summary>
public class SuperManData : AItemData
{
private StateMachine<ItemState> _super_Machine;
public StateMachine<ItemState> Super_Machine
{
get
{
if (_super_Machine == null)
{
_super_Machine = new StateMachine<ItemState>();
}
return _super_Machine;
}
}
public override bool IsRun()
{
if (Super_Machine.CurrentState == ItemState.SuperMan)
{
return true;
}
else
{
return false;
}
}
public bool WhetherSpeedUp()
{
if (IsRun() && Time > 2)
{
return true;
}
else
{
return false;
}
}
public override void EnterState()
{
if (!GameUIManager.Is_Resurgence && Time > 2)
{
GameGuidance.Instance.GuidanceSuperMan++;
}
Super_Machine.CurrentState = ItemState.SuperMan;
//Times++;
//关闭还未结束的此状态协程
if (PreviousCoroutine != null)
{
HumanManager.Nature.Human_Script.StopCoroutine(PreviousCoroutine);
}
PreviousCoroutine = HumanManager.Nature.Human_Script.StartCoroutine(SuperTime());
}
IEnumerator SuperTime()
{
float times = 0;
yield return new WaitUntil(() =>
{
if (MyKeys.Pause_Game)
return false;
times++;
return times >= ItemColliction.SuperMan.Time * 60;
});
ExitState();
}
protected override void ExitState()
{
Super_Machine.CurrentState = ItemState.Null;
Time = HumanManager.Nature.Super_Man_Time;
PreviousCoroutine = null;
}
public override void Update()
{
Super_Machine.Update();
}
public override void Initialize()
{
Super_Machine.AddState(ItemState.SuperMan, new SuperMan(HumanManager.Nature));
Super_Machine.AddState(ItemState.Null, new Null(HumanManager.Nature));
Super_Machine.CurrentState = ItemState.Null;
Time = HumanManager.Nature.Super_Man_Time;
}
}
/// <summary>
/// 磁铁数据类
/// </summary>
public class MagnetData : AItemData
{
private StateMachine<ItemState> _magnet_Machine;
public StateMachine<ItemState> Magnet_Machine
{
get
{
if (_magnet_Machine == null)
{
_magnet_Machine = new StateMachine<ItemState>();
}
return _magnet_Machine;
}
}
public override bool IsRun()
{
if (Magnet_Machine.CurrentState == ItemState.Magnet)
{
return true;
}
else
{
return false;
}
}
public override void EnterState()
{
GameGuidance.Instance.GuidanceMagnet++;
Magnet_Machine.CurrentState = ItemState.Magnet;
//Times++;
//关闭还未结束的此状态协程
if (PreviousCoroutine != null)
{
HumanManager.Nature.Human_Script.StopCoroutine(PreviousCoroutine);
}
PreviousCoroutine = HumanManager.Nature.Human_Script.StartCoroutine(MagnetTime());
OpenItemCollider();
}
IEnumerator MagnetTime()
{
float times = 0;
yield return new WaitUntil(() =>
{
if (MyKeys.Pause_Game)
return false;
times++;
return times >= ItemColliction.Magnet.Time * 60;
});
ExitState();
}
protected override void ExitState()
{
Magnet_Machine.CurrentState = ItemState.Null;
HumanManager.Nature.Human.GetComponentInChildren<FruitCollider>().gameObject.SetActive(true);
ItemCollider();
PreviousCoroutine = null;
}
public override void Update()
{
Magnet_Machine.Update();
}
public override void Initialize()
{
Magnet_Machine.AddState(ItemState.Magnet, new Magnet(HumanManager.Nature));
Magnet_Machine.AddState(ItemState.Null, new Null(HumanManager.Nature));
Magnet_Machine.CurrentState = ItemState.Null;
Time = HumanManager.Nature.Magnet_Time;
}
//检测是否开启或关闭碰撞框
public void ItemCollider()
{
if (ItemColliction.Double.IsRun() || ItemColliction.Dash.IsRun() || ItemColliction.StartDash.IsRun())
{
HumanColliderManager.Item_Collider.SetActive(true);
}
else
{
HumanColliderManager.Item_Collider.SetActive(false);
}
}
}
/// <summary>
/// 开始冲刺类
/// </summary>
public class StartDashData : AItemData
{
private StateMachine<ItemState> _start_Dash_Machine;
public StateMachine<ItemState> Start_Dash_Machine
{
get
{
if (_start_Dash_Machine == null)
{
_start_Dash_Machine = new StateMachine<ItemState>();
}
return _start_Dash_Machine;
}
}
public override bool IsRun()
{
if (Start_Dash_Machine.CurrentState == ItemState.StartDash)
{
return true;
}
else
{
return false;
}
}
public int Steps { set; get; }
public override void EnterState()
{
Start_Dash_Machine.CurrentState = ItemState.StartDash;
OpenItemCollider();
}
protected override void ExitState()
{
BuyTheItems.start_Dash_Bool = false;
Start_Dash_Machine.CurrentState = ItemState.Null;
HumanManager.Nature.HumanManager_Script.CurrentState = HumanState.Jump;
ItemColliction.SuperMan.Time = 1.0f;
HumanManager.Nature.HumanManager_Script.ItemState = ItemState.SuperMan;
ItemCollider();
}
//因为开始冲刺判定条件是步数,所以在外部判定满足步数才退出
public void WhetherExit(int now_Steps)
{
if (now_Steps == Steps)
{
ExitState();
}
}
public override void Update()
{
Start_Dash_Machine.Update();
}
public override void Initialize()
{
Start_Dash_Machine.AddState(ItemState.StartDash, new Dash(HumanManager.Nature));
Start_Dash_Machine.AddState(ItemState.Null, new Null(HumanManager.Nature));
Start_Dash_Machine.CurrentState = ItemState.Null;
}
//检测是否开启或关闭碰撞框
public void ItemCollider()
{
if (ItemColliction.Magnet.IsRun() || ItemColliction.Double.IsRun())
{
HumanColliderManager.Item_Collider.SetActive(true);
}
else
{
HumanColliderManager.Item_Collider.SetActive(false);
}
}
}
/// <summary>
/// 死亡冲刺类
/// </summary>
public class DeadDashData : AItemData
{
private StateMachine<ItemState> _dead_Dash_Machine;
public StateMachine<ItemState> Dead_Dash_Machine
{
get
{
if (_dead_Dash_Machine == null)
{
_dead_Dash_Machine = new StateMachine<ItemState>();
}
return _dead_Dash_Machine;
}
}
/// <summary>
/// DeadDashData中的此方法,是用来判定是否可以执行死亡冲刺
/// </summary>
/// <returns></returns>
public override bool IsRun()
{
if (Dead_Dash_Machine.CurrentState == ItemState.DeadDash)
{
return true;
}
else
{
return false;
}
}
public bool IsBuy()
{
if (BuyTheItems.dead_Dash_Bool)
{
return true;
}
return false;
}
public override void EnterState()
{
Dead_Dash_Machine.CurrentState = ItemState.DeadDash;
HumanManager.Nature.Human_Script.StartCoroutine(DashTime());
OpenItemCollider();
}
IEnumerator DashTime()
{
float times = 0;
yield return new WaitUntil(() =>
{
if (MyKeys.Pause_Game)
return false;
times++;
return times >= ItemColliction.Dash.Time * 60;
});
ExitState();
}
protected override void ExitState()
{
BuyTheItems.dead_Dash_Bool = false;
Dead_Dash_Machine.CurrentState = ItemState.Null;
HumanManager.Nature.HumanManager_Script.CurrentState = HumanState.Dead;
}
public override void Update()
{
Dead_Dash_Machine.Update();
}
public override void Initialize()
{
Dead_Dash_Machine.AddState(ItemState.DeadDash, new Dash(HumanManager.Nature));
Dead_Dash_Machine.AddState(ItemState.Null, new Null(HumanManager.Nature));
Dead_Dash_Machine.CurrentState = ItemState.Null;
Time = HumanManager.Nature.Dash_Time;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Events;
public class Note_Controller : MonoBehaviour
{
private readonly QteHitEvent ev_qtehit = new QteHitEvent();
private readonly QtePlayEvent ev_qteplay = new QtePlayEvent();
private readonly QteMissEvent ev_qtemiss = new QteMissEvent();
private WaitForSecondsRealtime waitenableinput = new WaitForSecondsRealtime(0.7f);
public bool canbepressed;
private bool buttoncanbepressed;
public KeyCode keytopress;
public KeyCode keytopressAlt;
private void OnEnable()
{
EventController.AddListener<QteMissEvent>(QteMissEvent);
}
private void OnDisable()
{
EventController.RemoveListener<QteMissEvent>(QteMissEvent);
}
void Start()
{
buttoncanbepressed = true;
canbepressed = false;
PlayerOptions.QteInputEnabled = true;
}
void Update()
{
//Debug.Log("Can be pressed: " + canbepressed);
//Debug.Log("Input enabled: " + PlayerOptions.QteInputEnabled);
if (Input.GetKeyDown(keytopress) || Input.GetKeyDown(keytopressAlt))
{
if (canbepressed && buttoncanbepressed)
{
gameObject.SetActive(false);
ev_qtehit.success = true;
if(this.tag == "ArrowBlue")
{
ev_qtehit.color = 0;
}
if (this.tag == "ArrowRed")
{
ev_qtehit.color = 1;
}
if (this.tag == "ArrowYellow")
{
ev_qtehit.color = 2;
}
if (this.tag == "ArrowGreen")
{
ev_qtehit.color = 3;
}
EventController.TriggerEvent(ev_qtehit);
}
}
}
private void OnTriggerEnter(Collider other)
{
if (other.tag.StartsWith("Activator"))
{
canbepressed = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag.StartsWith("Activator"))
{
canbepressed = false;
}
}
private void QteMissEvent(QteMissEvent qtemiss)
{
if (this.gameObject.tag == "ArrowYellow" && qtemiss.color == 2)
{
buttoncanbepressed = qtemiss.enableinput;
}
else if (this.gameObject.tag == "ArrowRed" && qtemiss.color == 1)
{
buttoncanbepressed = qtemiss.enableinput;
}
else if (this.gameObject.tag == "ArrowGreen" && qtemiss.color == 3)
{
buttoncanbepressed = qtemiss.enableinput;
}
else if (this.gameObject.tag == "ArrowBlue" && qtemiss.color == 0)
{
buttoncanbepressed = qtemiss.enableinput;
}
}
IEnumerator WaitEnableInput()
{
yield return waitenableinput;
PlayerOptions.QteInputEnabled = true;
if (this.tag == "ArrowBlue")
{
ev_qtemiss.color = 0;
}
if (this.tag == "ArrowRed")
{
ev_qtemiss.color = 1;
}
if (this.tag == "ArrowYellow")
{
ev_qtemiss.color = 2;
}
if (this.tag == "ArrowGreen")
{
ev_qtemiss.color = 3;
}
ev_qtemiss.enableinput = PlayerOptions.QteInputEnabled;
EventController.TriggerEvent(ev_qtemiss);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.