text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class Activity : MonoBehaviour { [SerializeField] private Nutrient.NutrientType _nutrientType; [SerializeField] private UnityEvent OnStartHold = new UnityEvent(); [SerializeField] private UnityEvent OnHoldEnd = new UnityEvent(); private float _startTime; private bool _isHold; public void Update() { if (!_isHold) return; if (_startTime + GameManager.Instance.GetActivityHoldTimeForNutrient() < Time.time) { _startTime = Time.time; NutrientsManager.Instance.AddToStorage(_nutrientType, 1); } } public void StartHold() { _isHold = true; _startTime = Time.time; OnStartHold.Invoke(); } public void EndHold() { OnHoldEnd.Invoke(); _isHold = false; } }
using DDDStore.Domain.Interfaces.Repositories; namespace DDDStore.Domain.Interfaces.Services.Department { public class RelationshipService : IRelationshipService { readonly ICustomerRepository _customerRepository; public RelationshipService(ICustomerRepository customerRepository) { _customerRepository = customerRepository; } public void SendBirthdayCommunication(int customerId, string message) { var customer = _customerRepository.GetById(customerId); } public void SendDowngradeCommunication(int customerId, string message) { var customer = _customerRepository.GetById(customerId); } public void ToggleAutoCommunication(int customerId) { var customer = _customerRepository.GetById(customerId); customer.IsCommunicationEnabled = !customer.IsCommunicationEnabled; _customerRepository.Update(customer); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media.Media3D; namespace advCG.Background { class Color { public static Color operator /(Color lhs, int fac) { Color ret = new Color(); ret.r = lhs.r / fac; ret.g = lhs.g / fac; ret.b = lhs.b / fac; return ret; } public static Color operator *(Color lhs, Color rhs) { Color ret = new Color(); ret.r = lhs.r * rhs.r; ret.g = lhs.g * rhs.g; ret.b = lhs.b * rhs.b; return ret; } public static Color operator *(Color lhs, double fac) { Color ret = new Color(); ret.r = lhs.r * fac; ret.g = lhs.g * fac; ret.b = lhs.b * fac; return ret; } public static Color operator *(double fac, Color lhs) { return lhs * fac; } public static Color operator +(Color lhs, Color rhs) { Color ret = new Color(); ret.r = lhs.r + rhs.r; ret.g = lhs.g + rhs.g; ret.b = lhs.b + rhs.b; return ret; } public static Color operator -(Color lhs, Color rhs) { Color ret = new Color(); ret.r = lhs.r - rhs.r; ret.g = lhs.g - rhs.g; ret.b = lhs.b - rhs.b; return ret; } public static byte DoubletoByte(double d) { d = d * 255.0; if (d > 255) return (byte)255; else return (byte)d; } public static double BytetoDouble(byte b) { return (int)b / 255.0f; } public int ARGB { get { return ( (A << 24) + (R << 16) + (G << 8) + B ); } } public double Rf { get { return r; } } public double Gf { get { return g; } } public double Bf { get { return b; } } public byte R { get { return DoubletoByte(r); } } public byte G { get { return DoubletoByte(g); } } public byte B { get { return DoubletoByte(b); } } public byte A { get { return DoubletoByte(a); } } double a, r, g, b; public Color() { r = g = b = 0.0; a = 1.0; } public Color(byte R, byte G, byte B, byte A = 255) { a = BytetoDouble(A); r = BytetoDouble(R); g = BytetoDouble(G); b = BytetoDouble(B); } public Color(double R, double G, double B, double A = 1.0f) { a = A; r = R; g = G; b = B; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; public partial class AARMSPage : System.Web.UI.Page { string obj_Authenticated; PlaceHolder maPlaceHolder; UserControl obj_Tabs; UserControl obj_LoginCtrl; UserControl obj_WelcomCtrl; UserControl obj_Navi; UserControl obj_Navihome; AarmsUser obj_Class = new AarmsUser(); BizConnectClass obj = new BizConnectClass(); string Transporter; protected void Page_Load(object sender, EventArgs e) { if (Session["UserID"] != string.Empty && Convert.ToInt32(Session["UserID"].ToString()) > 0) { if (!IsPostBack) { ChkAuthentication(); txtappdate.Text=DateTime.Now.ToString(); pnloperate.Visible = false; txtcalendar.Text = DateTime.Now.ToString("MM/dd/yyyy"); txtactiondate.Text = DateTime.Now.ToString("MM/dd/yyyy"); } } else { Response.Redirect("Index.html"); } } public void ChkAuthentication() { obj_LoginCtrl = null; obj_WelcomCtrl = null; obj_Navi = null; obj_Navihome = null; if (Session["Authenticated"] == null) { Session["Authenticated"] = "0"; } else { obj_Authenticated = Session["Authenticated"].ToString(); } maPlaceHolder = (PlaceHolder)Master.FindControl("P1"); if (maPlaceHolder != null) { obj_Tabs = (UserControl)maPlaceHolder.FindControl("loginheader1"); if (obj_Tabs != null) { obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1"); obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1"); // obj_Navi = (UserControl)obj_Tabs.FindControl("Navii"); //obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1"); if (obj_LoginCtrl != null & obj_WelcomCtrl != null) { if (obj_Authenticated == "1") { SetVisualON(); } else { SetVisualOFF(); } } } else { } } else { } } public void SetVisualON() { obj_LoginCtrl.Visible = false; obj_WelcomCtrl.Visible = true; } public void SetVisualOFF() { obj_LoginCtrl.Visible = true; obj_WelcomCtrl.Visible = false; } protected void Button1_Click(object sender, EventArgs e) { if (Session["UserID"] != string.Empty && Convert.ToInt32(Session["UserID"].ToString()) > 0) { try { int resp = obj_Class.Bizconnect_InsertActivity(txtclient.Text, txtlocation.Text, txtindustry.Text, txtcontactperson.Text, txtMobile.Text, txtDept.Text, Session["name"].ToString(), Convert.ToDateTime(txtappdate.Text),txtemail.Text,ddlActionList.SelectedItem.Text,txtremarks.Text); if(resp==1) { txtclient.Text=""; txtlocation.Text=""; txtindustry.Text=""; txtcontactperson.Text=""; txtMobile.Text=""; txtDept.Text=""; txtemail.Text=""; txtremarks.Text=""; ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Insert Successfully');</script>"); } } catch(Exception ex) { } } else { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Session Expired! Please Login again');</script>"); } } protected void Butstatus_Click(object sender, EventArgs e) { Response.Redirect("statusUpdate.aspx"); } protected void radoperations_CheckedChanged(object sender, EventArgs e) { Get_transporter(); pnlmarket.Visible = false; pnloperate.Visible = true; } protected void radmarketing_CheckedChanged(object sender, EventArgs e) { pnloperate.Visible = false; pnlmarket.Visible = true; } public void Get_transporter() { DataSet ds = new DataSet(); ds = obj.Get_BizConnect_Transporter(); chkbl_Transporter.DataSource = ds; chkbl_Transporter.DataValueField = "TID"; chkbl_Transporter.DataTextField = "Tname"; chkbl_Transporter.DataBind(); } protected void btnsave_Click(object sender, EventArgs e) { try { int rebid=0; if(radYes.Checked == true) { rebid = 1; } else if(radYes.Checked== true) { rebid =2; } int resp = obj_Class.Bizconnect_InsertAARMSOperation(Convert.ToDateTime(txtcalendar.Text), txtclientname.Text, Convert.ToDateTime(txttripdate.Text),save_Transporter(), Convert.ToInt32(txtquotereceived.Text), Convert.ToDateTime(txtactiondate.Text), rebid, txtaction.Text,Session["name"].ToString()); if (resp == 1) { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Insert Successfully');</script>"); clearfields(); } } catch (Exception ex) { } } public string save_Transporter() { for (int i = 0; i < chkbl_Transporter.Items.Count; i++) { if (chkbl_Transporter.Items[i].Selected) { Transporter = Transporter + chkbl_Transporter.Items[i].Text + ","; } } int j = Transporter.Length; Transporter = Transporter.Remove(j - 1); return Transporter; } protected void btn_Report_Click(object sender, EventArgs e) { Response.Redirect("~/AARMSPageReport.aspx"); } public void clearfields() { txtcalendar.Text = ""; txtclientname.Text = ""; txttripdate.Text = ""; chkbl_Transporter.SelectedIndex = -1; chkbl_Transporter.ClearSelection(); txtquotereceived.Text = ""; txtaction.Text = ""; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CTCT.Util; using CTCT.Components.EmailCampaigns; using CTCT.Components; using CTCT.Exceptions; namespace CTCT.Services { /// <summary> /// Performs all actions pertaining to the Contacts Collection. /// </summary> public class EmailCampaignService : BaseService, IEmailCampaignService { /// <summary> /// Get a set of campaigns. /// </summary> /// <param name="accessToken">Access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="status">Returns list of email campaigns with specified status.</param> /// <param name="limit">Specifies the number of results per page in the output, from 1 - 500, default = 500.</param> /// <param name="modifiedSince">limit campaigns to campaigns modified since the supplied date</param> /// <returns>Returns a ResultSet of campaigns.</returns> public ResultSet<EmailCampaign> GetCampaigns(string accessToken, string apiKey, CampaignStatus? status, int? limit, DateTime? modifiedSince) { return this.GetCampaigns(accessToken, apiKey, status, limit, modifiedSince, null); } /// <summary> /// Get a set of campaigns. /// </summary> /// <param name="accessToken">Access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="status">Returns list of email campaigns with specified status.</param> /// <param name="limit">Specifies the number of results per page in the output, from 1 - 500, default = 500.</param> /// <param name="modifiedSince">limit campaigns to campaigns modified since the supplied date</param> /// <param name="pag">Pagination object returned by a previous call to GetCampaigns</param> /// <returns>Returns a ResultSet of campaigns.</returns> public ResultSet<EmailCampaign> GetCampaigns(string accessToken, string apiKey, CampaignStatus? status, int? limit, DateTime? modifiedSince, Pagination pag) { ResultSet<EmailCampaign> results = null; string url = (pag == null) ? String.Concat(Config.Endpoints.BaseUrl, Config.Endpoints.Campaigns, GetQueryParameters(new object[] { "status", status, "limit", limit, "modified_since", Extensions.ToISO8601String(modifiedSince) })) : pag.GetNextUrl(); CUrlResponse response = RestClient.Get(url, accessToken, apiKey); if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } if (response.HasData) { results = response.Get<ResultSet<EmailCampaign>>(); } return results; } /// <summary> /// Get campaign details for a specific campaign. /// </summary> /// <param name="accessToken">Access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="campaignId">Campaign id.</param> /// <returns>Returns a campaign.</returns> public EmailCampaign GetCampaign(string accessToken, string apiKey, string campaignId) { EmailCampaign campaign = null; string url = String.Concat(Config.Endpoints.BaseUrl, String.Format(Config.Endpoints.Campaign, campaignId)); CUrlResponse response = RestClient.Get(url, accessToken, apiKey); if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } if (response.HasData) { campaign = response.Get<EmailCampaign>(); } return campaign; } /// <summary> /// Create a new campaign. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="campaign">Campign to be created</param> /// <returns>Returns a campaign.</returns> public EmailCampaign AddCampaign(string accessToken, string apiKey, EmailCampaign campaign) { EmailCampaign emailcampaign = null; string url = String.Concat(Config.Endpoints.BaseUrl, Config.Endpoints.Campaigns); string json = campaign.ToJSON(); CUrlResponse response = RestClient.Post(url, accessToken, apiKey, json); if (response.HasData) { emailcampaign = response.Get<EmailCampaign>(); } else if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } return emailcampaign; } /// <summary> /// Delete an email campaign. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="campaignId">Valid campaign id.</param> /// <returns>Returns true if successful.</returns> public bool DeleteCampaign(string accessToken, string apiKey, string campaignId) { string url = String.Concat(Config.Endpoints.BaseUrl, String.Format(Config.Endpoints.Campaign, campaignId)); CUrlResponse response = RestClient.Delete(url, accessToken, apiKey); if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } return (!response.IsError && response.StatusCode == System.Net.HttpStatusCode.NoContent); } /// <summary> /// Update a specific email campaign. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="campaign">Campaign to be updated.</param> /// <returns>Returns a campaign.</returns> public EmailCampaign UpdateCampaign(string accessToken, string apiKey, EmailCampaign campaign) { EmailCampaign emailCampaign = null; string url = String.Concat(Config.Endpoints.BaseUrl, String.Format(Config.Endpoints.Campaign, campaign.Id)); // Invalidate data that are not supported by the update API procedure campaign.CreatedDate = null; campaign.TrackingSummary = null; campaign.ModifiedDate = null; campaign.IsVisibleInUI = null; // Convert to JSON string string json = campaign.ToJSON(); CUrlResponse response = RestClient.Put(url, accessToken, apiKey, json); if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } if (response.HasData) { emailCampaign = response.Get<EmailCampaign>(); } return emailCampaign; } } }
using System; using System.Drawing; using System.Windows.Forms; namespace FreeUI.Controls.Label { public class FreeUILabel : System.Windows.Forms.Label{ public FreeUILabel() { SetStyle( ControlStyles.UserPaint, true ); } /// <summary> /// Sobrescreve a alteração de cor quando um Label está desablilitado /// </summary> protected override void OnPaint(PaintEventArgs e) { if (!Enabled) { SolidBrush brush = new SolidBrush( ForeColor ); e.Graphics.DrawString( Text, Font, brush, 0f, 0f ); return; } base.OnPaint( e ); } } }
namespace _6.BirthdayCelebrations.Models { public interface IBirthday { string Birthday { get; } } }
using UnityEngine; using System; [CreateAssetMenu(fileName = "Input" , menuName = "Input")] public sealed class MobileInput : ScriptableObject { public const int DeadZoneSqr = 125 * 125; /// <summary> /// Indicates if most input controls shall be returned inverted /// </summary> public bool InvertedControls { get; set; } /// <summary> /// Tells if a touch is continuous /// </summary> public bool IsDraging { get; private set; } /// <summary> /// Initial touching point /// </summary> public Vector2 StartTouch { get; private set; } /// <summary> /// Difference between current and initial touch positions. Affected by InvertedControls (-SwipeDelta) /// </summary> public Vector2 SwipeDelta { get { return InvertedControls ? -swipeDelta : swipeDelta; } } /// <summary> /// Indicates the first frame in which a tap occurred. Affected by InvertedControls (DoubleTap) /// </summary> public bool Tap { get { return InvertedControls ? doubleTap : tap; } } /// <summary> /// Indicates if there have been 2 or more consecutive taps. Affected by InvertedControls (Tap) /// </summary> public bool DoubleTap { get { return InvertedControls ? tap : doubleTap; } } /// <summary> /// Indicates if a valid swipe has been performed. Affected by InvertedControls (SwipeRight) /// </summary> public bool SwipeLeft { get { return InvertedControls ? swipeRight : swipeLeft; } } /// <summary> /// Indicates if a valid swipe has been performed. Affected by InvertedControls (SwipeLeft) /// </summary> public bool SwipeRight { get { return InvertedControls ? swipeLeft : swipeRight; } } /// <summary> /// Indicates if a valid swipe has been performed. Affected by InvertedControls (SwipeDown) /// </summary> public bool SwipeUp { get { return InvertedControls ? swipeDown : swipeUp; } } /// <summary> /// Indicates if a valid swipe has been performed. Affected by InvertedControls (SwipeUp) /// </summary> public bool SwipeDown { get { return InvertedControls ? swipeUp : swipeDown; } } /// <summary> /// Current touch unique id /// </summary> public int CurrentFingerId { get { return currentFingerId; } } private Vector2 swipeDelta; private bool swipeLeft, swipeRight, swipeUp, swipeDown, tap, doubleTap; private int currentFingerId; /// <summary> /// Initializes several fields /// </summary> public void PreUpdate() { tap = doubleTap = swipeLeft = swipeRight = swipeDown = swipeUp = false; this.swipeDelta = Vector2.zero; } /// <summary> /// Given the SwipeDelta checks if a valid swipe has been performed /// </summary> public void SwipeStatusCheck() { if (swipeDelta.sqrMagnitude > DeadZoneSqr) { //direction? float x = swipeDelta.x; float y = swipeDelta.y; if (Mathf.Abs(x) > Mathf.Abs(y)) { //left or right? if (x < 0) swipeLeft = true; else swipeRight = true; } else { //up or down? if (y > 0) swipeUp = true; else swipeDown = true; } } } #if UNITY_STANDALONE /// <summary> /// Updates most fields given input data /// </summary> /// <param name="buttonDown">indicates if this is the first frame the button has been pressed</param> /// <param name="buttonUp">indicates if this is the first frame the button has been released</param> /// <param name="buttonPressed">indicates if the button is pressed</param> /// <param name="doubleTap">indicates if a double tap has been performed</param> /// <param name="cursorPosition">cursor current position</param> public void UpdatePCTouchStatus(bool buttonDown, bool buttonUp, bool buttonPressed, bool doubleTap, Vector2 cursorPosition) { this.doubleTap = doubleTap; if (buttonDown) { tap = true; IsDraging = true; StartTouch = cursorPosition; } //releasing else if (buttonUp) { StartTouch = Vector2.zero; IsDraging = false; } //calculate the distance if (IsDraging && buttonPressed) { swipeDelta = cursorPosition - StartTouch; } } #else /// <summary> /// Updates most fields given input data /// </summary> /// <param name="touchesList">list of input touches</param> public void UpdateMobileTouchStatus(Touch[] touchesList) { //Se non ci sono tocchi non fare niente int touches = touchesList.Length; if (touches == 0) return; //Inizializzo Touch toUse e verifico se corrisponde al tocco preso in considerazione nel frame precedente Touch toUse = touchesList[0]; bool done = toUse.fingerId == currentFingerId; //Se l'id non corrisponde cerco l'id giusto fra tutti i vari touch if (!done) { for (int i = 1; i < touches; i++) { toUse = touchesList[i]; if (toUse.fingerId == currentFingerId) { done = true; break; } } } //Se non ho trovato una corrispondenza significa che il touch del frame precedente non c'è più, per cui prendo un nuovo touch ,mi salvo il nuovo id e resetto i vari valori if (!done) { toUse = touchesList[0]; currentFingerId = toUse.fingerId; IsDraging = false; StartTouch = toUse.position; } //tapping this.doubleTap = toUse.tapCount > 1; if (toUse.phase == TouchPhase.Began) { tap = true; IsDraging = true; StartTouch = toUse.position; } //releasing else if (toUse.phase == TouchPhase.Ended || toUse.phase == TouchPhase.Canceled) { IsDraging = false; StartTouch = Vector2.zero; } //calculate the distance if (IsDraging) { swipeDelta = toUse.position - StartTouch; } } private void UpdateMobileTouchStatus() { //Se non ci sono tocchi non fare niente int touches = Input.touchCount; if (touches == 0) return; //Inizializzo Touch toUse e verifico se corrisponde al tocco preso in considerazione nel frame precedente Touch toUse = Input.GetTouch(0); bool done = toUse.fingerId == currentFingerId; //Se l'id non corrisponde cerco l'id giusto fra tutti i vari touch if (!done) { for (int i = 1; i < touches; i++) { toUse = Input.GetTouch(i); if (toUse.fingerId == currentFingerId) { done = true; break; } } } //Se non ho trovato una corrispondenza significa che il touch del frame precedente non c'è più, per cui prendo un nuovo touch e mi salvo il nuovo id if (!done) { toUse = Input.GetTouch(0); currentFingerId = toUse.fingerId; IsDraging = false; StartTouch = toUse.position; } //tapping this.doubleTap = toUse.tapCount > 1; if (toUse.phase == TouchPhase.Began) { tap = true; IsDraging = true; StartTouch = toUse.position; } //releasing else if (toUse.phase == TouchPhase.Ended || toUse.phase == TouchPhase.Canceled) { IsDraging = false; StartTouch = Vector2.zero; } //calculate the distance if (IsDraging) { swipeDelta = toUse.position - StartTouch; } } #endif public void UpdateInput(float deltaTime) { //Initialize values PreUpdate(); //clicking #if UNITY_STANDALONE UpdatePCTouchStatus(Input.GetMouseButtonDown(0), Input.GetMouseButtonUp(0), Input.GetMouseButton(0), Input.GetMouseButtonDown(1), Input.mousePosition); #else UpdateMobileTouchStatus(); #endif //did we cross the deadzone? SwipeStatusCheck(); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.IO; namespace Benchmarks.Utility.Helpers { public class DotnetHelper { private static readonly DotnetHelper _default = new DotnetHelper(); private readonly string _executablePath = Path.Combine("cli", "bin", "dotnet.exe"); private readonly string _defaultDotnetHome = Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), "Microsoft", "dotnet"); public static DotnetHelper GetDefaultInstance() => _default; private DotnetHelper() { } public ProcessStartInfo BuildStartInfo( string appbasePath, string argument) { var dnxPath = GetDotnetExecutable(); var psi = new ProcessStartInfo(dnxPath, argument) { WorkingDirectory = appbasePath, UseShellExecute = false }; return psi; } public bool Restore(string workingDir, bool quiet = false) { var psi = new ProcessStartInfo(GetDotnetExecutable()) { Arguments = "restore" + (quiet ? " --quiet" : ""), WorkingDirectory = workingDir, UseShellExecute = false }; var proc = Process.Start(psi); var exited = proc.WaitForExit(300 * 1000); return exited && proc.ExitCode == 0; } public bool Publish(string workingDir, string outputDir, string framework) { var psi = new ProcessStartInfo(GetDotnetExecutable()) { Arguments = $"publish --output {outputDir}", WorkingDirectory = workingDir, UseShellExecute = false }; if (!string.IsNullOrEmpty(framework)) { psi.Arguments = $"{psi.Arguments} --framework {framework}"; } var proc = Process.Start(psi); var exited = proc.WaitForExit((int)TimeSpan.FromMinutes(5).TotalMilliseconds); return exited && proc.ExitCode == 0; } public bool Publish(string workingDir, string outputDir) { return Publish(workingDir, outputDir, framework: null); } public string GetDotnetPath() { var envDotnetHome = Environment.GetEnvironmentVariable("DOTNET_INSTALL_DIR"); var dotnetHome = envDotnetHome != null ? Environment.ExpandEnvironmentVariables(envDotnetHome) : _defaultDotnetHome; if (Directory.Exists(dotnetHome)) { return dotnetHome; } else { return null; } } public string GetDotnetExecutable() { var dnxPath = GetDotnetPath(); if (dnxPath != null) { return Path.Combine(dnxPath, _executablePath); } else { return null; } } } }
using System; namespace RMAT3.Common { public class RmatException: Exception { public RmatException(string errDesc, Exception e):base(errDesc,e) { } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class MageQ : Ability { private float duration; private float durationRemaining; private float damageReduction; private float healPercentOnCast; private MageQ() { usesLeft = 1; duration = 10; damageReduction = 1; healPercentOnCast = 100; baseCooldown = 45; cooldown = baseCooldown; } protected override void Awake() { base.Awake(); cooldownReduction = 0.5f; damageAmplification = 1.5f; } protected override void UseAbilityEffect(Vector3 mousePosition, bool isPressed, bool forceAbility = false) { foreach (Player p in player.Party) { p.Health.Restore(healPercentOnCast, true); } player.SetDamageReduction(damageReduction); player.PlayerMovementManager.SetCanMove(false); player.PlayerAbilityManager.SetAbilityActive(1, false); player.PlayerAbilityManager.SetAbilityActive(2, false); player.PlayerAbilityManager.SetAbilityActive(3, false); player.PlayerAbilityManager.UseAbilityWithoutLimitation(1, new Vector2(Screen.width * 0.5f, Screen.height * 0.5f)); StartCoroutine(EndBuff()); } private IEnumerator EndBuff() { durationRemaining = duration; yield return null; while (durationRemaining > 0) { durationRemaining -= Time.deltaTime; yield return null; } player.PlayerAbilityManager.SetAbilityActive(1, true); player.PlayerAbilityManager.SetAbilityActive(2, true); player.PlayerAbilityManager.SetAbilityActive(3, true); player.PlayerMovementManager.SetCanMove(true); player.SetDamageReduction(-damageReduction); } }
using System.Collections.Generic; namespace SLua { public class CjsonLib { public static void Reg(Dictionary<string, LuaCSFunction> reg_functions) { reg_functions.Add("cjson", LuaDLL.luaopen_cjson); } } }
using UnityEngine; using System.Collections; public class Enemy : MonoBehaviour { public Nexus Nexus; private Vector2 vector; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void FixedUpdate () { move (); turn (); } void move () { //Need to do real A* here eventually float moveX = Nexus.transform.position.x - this.transform.position.x; float moveY = Nexus.transform.position.y - this.transform.position.y; vector = new Vector2 (moveX, moveY).normalized; rigidbody2D.velocity = vector; } void turn () { float angle = Mathf.Atan2(vector.y, vector.x) * Mathf.Rad2Deg; this.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using lianda.Component; namespace lianda.LD40 { /// <summary> /// LD401010 的摘要说明。 /// </summary> public class LD401010 : BasePage { protected System.Web.UI.WebControls.Button bt_new; protected System.Web.UI.WebControls.Button bt_del; protected System.Web.UI.WebControls.TextBox XH; protected System.Web.UI.WebControls.Label lbLRR; protected System.Web.UI.WebControls.Label lbLRSJ; protected System.Web.UI.WebControls.Label lfXGR; protected System.Web.UI.WebControls.DropDownList YLX; protected Infragistics.WebUI.WebDataInput.WebNumericEdit SS; protected Infragistics.WebUI.WebDataInput.WebNumericEdit DJ; protected Infragistics.WebUI.WebDataInput.WebNumericEdit JE; protected System.Web.UI.WebControls.TextBox GS; protected Infragistics.WebUI.WebSchedule.WebDateChooser RQ; protected System.Web.UI.WebControls.Button Button1; protected System.Web.UI.WebControls.DataGrid DataGrid1; protected System.Web.UI.WebControls.Label lbXGSJ; private void Page_Load(object sender, System.EventArgs e) { // 在此处放置用户代码以初始化页面 if(!this.IsPostBack) { // 加载油类型资料 YLX_Load(); if (Request.Params["XH"]!=null) { this.XH.Enabled=false; bt_ask(Request.Params["XH"].ToString().Trim()); } else { //控件初始化 init(); } ask_ku_cun(); } } private void Panel1_load() { //this.Panel1.Controls.Add(); } #region 油类型 private void YLX_Load() { // 数据绑定 this.YLX.Items.Clear(); this.YLX.DataTextField = "YLX"; this.YLX.DataValueField = "YLX"; this.YLX.DataSource = Common.getYLX(); this.YLX.DataBind(); // 插入空白选项 this.YLX.Items.Insert(0,""); } #endregion #region 控件初始化 private void init() { this.XH.Text=""; this.DJ.Value=0; this.JE.Value=0; this.SS.Value=0; this.GS.Text=""; this.RQ.Value = DateTime.Now; } #endregion #region Web 窗体设计器生成的代码 override protected void OnInit(EventArgs e) { // // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 // InitializeComponent(); base.OnInit(e); } /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.Button1.Click += new System.EventHandler(this.Button1_Click); this.bt_new.Click += new System.EventHandler(this.bt_new_Click); this.bt_del.Click += new System.EventHandler(this.bt_del_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion #region 查询 /// <summary> /// /// </summary> /// <param name="bm"></param> private void bt_ask(string bm) { string strSQL; // SQL语句 // 查询数据 strSQL = "select * from Y_ZJYL where XH = @DM AND SC<>'Y';"; SqlParameter[] prams = { new SqlParameter("@DM",SqlDbType.VarChar,10) }; prams[0].Value= bm; SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSQL,prams);// //赋值 if(dr.Read()) { this.XH.Text=dr["XH"].ToString();//序号 int index=this.YLX.Items.IndexOf(this.YLX.Items.FindByValue(dr["YLX"].ToString().Trim())); if(index>0) this.YLX.Items[index].Selected =true; //油类型 this.DJ.Value=dr["DJ"].ToString(); //单价 this.JE.Value=dr["JE"].ToString(); //金额 this.SS.Value=dr["SS"].ToString(); //升数 this.GS.Text= dr["GS"].ToString(); //公司 this.RQ.Value =dr["RQ"].ToString(); //日期 //下面系统信息 this.lbLRR.Text=dr["LRR"].ToString(); //录入人 this.lbLRSJ.Text=dr["LRSJ"].ToString(); //录入时间 this.lbXGSJ.Text=dr["XGSJ"].ToString(); //修改人 this.lfXGR.Text=dr["XGR"].ToString(); //修改时间 } else { init(); } ask_ku_cun(); } #endregion #region 保存 private void bt_new_Click(object sender, System.EventArgs e) { if(!My_Check()) return; // 参数创建 SqlParameter[] parms; parms = new SqlParameter[] { new SqlParameter("@ReturnValue",SqlDbType.Int), // 返回值 new SqlParameter("@XH",SqlDbType.Decimal), //序号 new SqlParameter("@YLX",SqlDbType.VarChar,20), //油类型 new SqlParameter("@RQ",SqlDbType.DateTime), //日期 new SqlParameter("@GS",SqlDbType.VarChar,50), //公司 new SqlParameter("@SS",SqlDbType.Decimal), //升数 new SqlParameter("@DJ",SqlDbType.Decimal), //单价 new SqlParameter("@JE",SqlDbType.Decimal), //金额 new SqlParameter("@OPR",SqlDbType.VarChar,10), // 操作人 }; // 参数赋值 parms[0].Direction = ParameterDirection.ReturnValue; parms[1].Direction = ParameterDirection.InputOutput; int n=1; if(this.XH.Text.Trim()==null||this.XH.Text.Trim()=="") parms[n++].Value=0; else parms[n++].Value=int.Parse(this.XH.Text.Trim()); //序号 parms[n++].Value=this.YLX.SelectedItem.Text.ToString(); //油类型 parms[n++].Value=this.RQ.Value; //日期 parms[n++].Value=this.GS.Text; //公司 parms[n++].Value=this.SS.Value; //升数 parms[n++].Value=this.DJ.Value; //单价 parms[n++].Value=this.JE.Value; //金额 parms[n++].Value=this.Session["UserName"].ToString(); //操作人 using(SqlConnection cn = new SqlConnection(SqlHelper.CONN_STRING)) { cn.Open(); // 连接数据库 try { // 托运单摘要过程调用 SqlHelper.ExecuteNonQuery(SqlHelper.CONN_STRING,CommandType.StoredProcedure,"sp_ZJYL",parms); if ((int)parms[0].Value !=0) { // 保存失败,取消数据库操作 this.msgbox("数据保存时错误,如有疑问请与系统管理员联系!"); return ; } // 号获取 this.XH.Text = parms[1].Value.ToString(); } catch (Exception ex) { string ss=ex.Message; // 事件回滚,取消数据库操作 // 日志写入 this.msgbox("数据保存时错误,如有疑问请与系统管理员联系!"); return ; } } bt_ask(this.XH.Text); ask_ku_cun(); this.msgbox("数据保存成功!"); } #endregion #region 检查 private bool My_Check() { //作业日期 if(this.RQ.Value==System.DBNull.Value) { this.msgbox("选择日期"); goto falseFlag; } //驾驶员 if(this.YLX.SelectedIndex==-1 || this.YLX.SelectedValue==null|| this.YLX.SelectedValue.ToString()=="") { this.msgbox("选择油类型"); goto falseFlag; } if(this.SS.Text==null) this.SS.Value=0; if(this.DJ.Text==null) this.DJ.Value=0; if(this.JE.Text==null) this.JE.Value=0; if(this.GS.Text==null) this.GS.Text=""; return true; falseFlag: return false; } #endregion #region 删除 private void bt_del_Click(object sender, System.EventArgs e) { //检查序号是否存在 if(this.XH.Text==null || this.XH.Text.Trim()=="") { this.msgbox("没有记录可以删除!"); return ; } // 托运单参数创建并赋值 SqlParameter[] parmsTYD = { new SqlParameter("@ReturnValue",SqlDbType.Int), // 返回值 new SqlParameter("@XH",SqlDbType.Decimal), // 序号 new SqlParameter("@SCR",SqlDbType.VarChar,10) }; parmsTYD[0].Direction = ParameterDirection.ReturnValue; if(this.XH.Text.Trim()==null||this.XH.Text.Trim()=="") parmsTYD[1].Value=0; else parmsTYD[1].Value=int.Parse(this.XH.Text.Trim()); //序号 parmsTYD[2].Value=this.Session["UserName"].ToString(); //删除人 using(SqlConnection cn = new SqlConnection(SqlHelper.CONN_STRING)) { cn.Open(); // 连接数据库 try { SqlHelper.ExecuteNonQuery(SqlHelper.CONN_STRING,CommandType.StoredProcedure,"sp_ZJYL_DEL",parmsTYD); if ((int)parmsTYD[0].Value !=0) { return ; } } catch { // 日志写入 this.msgbox("数据删除时错误,如有疑问请与系统管理员联系!"); return ; } } bt_ask(this.XH.Text); this.msgbox("删除成功!"); } #endregion private void ask_ku_cun() { string strSQL; // SQL语句 // 查询数据 strSQL = "select * from J_YLX ;"; SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSQL,null);// //赋值 this.DataGrid1.DataSource=dr; this.DataGrid1.DataBind(); } private void Button1_Click(object sender, System.EventArgs e) { init(); } } }
using MetroFramework; using MetroFramework.Forms; using PDV.CONTROLER.Funcoes; using PDV.DAO.DB.Utils; using PDV.DAO.Entidades; using PDV.DAO.Enum; using PDV.VIEW.App_Context; using System; using System.Windows.Forms; namespace PDV.VIEW.Forms.Cadastro { public partial class FCA_Portaria : DevExpress.XtraEditors.XtraForm { private string NOME_TELA = "CADASTRO DE PORTARIA"; private Portaria PORTARIA = null; public FCA_Portaria(Portaria _Portaria) { InitializeComponent(); PORTARIA = _Portaria; PreencherTela(); } private void PreencherTela() { ovTXT_Titulo.Text = PORTARIA.Titulo; ovTXT_Descricao.Text = PORTARIA.Descricao; } private void metroButton5_Click(object sender, EventArgs e) { Close(); } private void metroButton4_Click(object sender, EventArgs e) { try { PDVControlador.BeginTransaction(); if (string.IsNullOrEmpty(ovTXT_Titulo.Text.Trim())) throw new Exception("Informe o Título."); PORTARIA.Titulo = ovTXT_Titulo.Text; PORTARIA.Descricao = ovTXT_Descricao.Text; DAO.Enum.TipoOperacao Op = DAO.Enum.TipoOperacao.UPDATE; if (!FuncoesPortaria.Existe(PORTARIA.IDPortaria)) { PORTARIA.IDPortaria = Sequence.GetNextID("PORTARIA", "IDPORTARIA"); Op = DAO.Enum.TipoOperacao.INSERT; } if (!FuncoesPortaria.Salvar(PORTARIA, Op)) throw new Exception("Não foi possível salvar a Portaria."); PDVControlador.Commit(); MessageBox.Show(this, "Portaria salva com sucesso.", NOME_TELA, MessageBoxButtons.OK, MessageBoxIcon.Information); Close(); } catch (Exception Ex) { PDVControlador.Rollback(); MessageBox.Show(this, Ex.Message, NOME_TELA, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void FCA_Portaria_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Escape: this.Close(); break; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Note : MonoBehaviour { [SerializeField] private float speed = -4; [SerializeField] private GameObject deathParticles; private NoteType noteType; private Rigidbody2D rb; void Start() { rb = GetComponent<Rigidbody2D>(); } void Update() { } private void FixedUpdate() { rb.velocity = new Vector2(speed, 0.0f); } public void Death() { Instantiate(deathParticles, gameObject.transform.position, Quaternion.identity); Destroy(gameObject); } public void SetSpeed(float newSpeed) { speed = newSpeed; } public void SetNoteType(NoteType type) { noteType = type; } public NoteType GetNoteType() { return noteType; } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using Voronov.Nsudotnet.BuildingCompanyIS.Entities; using Voronov.Nsudotnet.BuildingCompanyIS.Logic.DbInterfaces; namespace Voronov.Nsudotnet.BuildingCompanyIS.Logic.Impl.DbImpl { class SqlResourceResultsService: CrudServiceBase<ResourceResult>, IResourceResultsService { public SqlResourceResultsService(DatabaseModel context) : base(context) { } public IQueryable<ResourceResult> GetResourceResultsByBuildingId(int buildingId) { return BaseSet.Include(e => e.BuildPlan).Where(e => e.BuildPlan.BuildingId == buildingId); } public IQueryable<ResourceResult> GetResourcesWithOverExpenditure() { return BaseSet.Include(e => e.ResourcePlan).Where(e => e.ResourceCount > e.ResourcePlan.ResourceCount); } public IQueryable<ResourceResult> GetResourcesWithOverExpenditureBySiteId(int siteId) { return BaseSet.Include(e => e.ResourcePlan) .Include(e => e.BuildPlan) .Include(e => e.BuildPlan.Building) .Where(e => e.BuildPlan.Building.SiteId == siteId && e.ResourceCount > e.ResourcePlan.ResourceCount); } public IQueryable<ResourceResult> GetResourceWithOverExpenditureByOrganizationId(int organizationUnitId) { return BaseSet.Include(e => e.ResourcePlan) .Include(e => e.BuildPlan) .Include(e => e.BuildPlan.Building) .Where( e => e.BuildPlan.Building.OrganizationUnitId == organizationUnitId && e.ResourceCount > e.ResourcePlan.ResourceCount); } } }
namespace MobileService45.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("APP.LOGS")] public partial class LOG { public decimal ID { get; set; } public decimal? USERID { get; set; } public decimal? MENUID { get; set; } public DateTime? LOGTIME { get; set; } [StringLength(100)] public string IP { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web; using System.Web.Caching; using System.Web.Mvc; namespace App.Server.Models.Markup { public class TemplateProvider { //private CxSlMetadataHolder m_Holder; public TemplateProvider() { //m_Holder = holder; } protected const string HtmlCachePrefix = "html_"; protected const string HtmlDefaultCachePrefix = "html_#def#_"; protected const string CssCachePrefix = "css_"; protected const string CssDefaultCacheKey = "css_def"; private string GetSkinPath(string skinId) { // CxSlSkinMetadata skinMeta = m_Holder.SlSkins[skinId]; // string skinFolder = skinMeta["skin_folder"]; return Path.Combine("~/Content/Skins", "Default" /*skinFolder*/); } public string GetTemplate(string templateId, string skinId, Controller controller, bool noCache = false) { MarkupCacheItem template = GetTemplateFromCache(skinId, templateId); if (template != null) return template.Markup; string templateString = GetTemplateFromSkin(skinId, templateId); if (!string.IsNullOrEmpty(templateString)) { templateString = CombineCssAndTemplate(templateString, skinId); MarkupCacheItem item = new MarkupCacheItem() { Markup = templateString }; PutTemplateToCache(skinId, templateId, item); return templateString; } template = GetDefaultTemplateFromCache(templateId); if (template != null) { PutTemplateToCache(skinId, templateId, template); return template.Markup; } templateString = GetDefaultTemplate(templateId, controller); templateString = CombineCssAndTemplate(templateString, skinId); MarkupCacheItem itemDef = new MarkupCacheItem() { Markup = templateString }; if (noCache == false) { PutTemplateToCache(skinId, templateId, itemDef); PutDefaultHtmlToCache(templateId, itemDef); } return templateString; } private string GetCss(string cssFile, string skinId, Controller controller, bool noCache = false) { string pathToFile = Path.Combine( HttpContext.Current.Server.MapPath( GetSkinPath(skinId) ), cssFile ); if ( File.Exists( pathToFile ) ) return File.ReadAllText( pathToFile ); pathToFile = Path.Combine(HttpContext.Current.Server.MapPath(GetSkinPath("Default")), cssFile); if (File.Exists(pathToFile)) return File.ReadAllText(pathToFile); return string.Empty; } private string CombineCssAndTemplate(string template, string skinId) { Regex r = new Regex("<!--css file:(.*?)-->"); var found = r.Matches(template); string templateWithCss = template; foreach (Match mach in found) { string fileName = mach.Value.Replace("<!--", "").Replace("css file:", "").Replace("-->", "").TrimStart().TrimEnd(); string css = GetCssString(fileName, skinId); if (!string.IsNullOrEmpty(css)) templateWithCss = templateWithCss.Replace(mach.Value, string.Concat("<style type=\"text/css\">", css, "</style>")); } return templateWithCss; } private string GetCssString(string cssFileName, string skinId) { string pathToSkin = HttpContext.Current.Server.MapPath(GetSkinPath(skinId)); string pathToCssFile = Path.Combine(pathToSkin, cssFileName); if (File.Exists(pathToCssFile)) return File.ReadAllText(pathToCssFile); else { pathToSkin = HttpContext.Current.Server.MapPath(GetSkinPath("Default")); pathToCssFile = Path.Combine(pathToSkin, cssFileName); if (File.Exists(pathToCssFile)) return File.ReadAllText(pathToCssFile); return string.Empty; } } private string GetTemplateFromSkin(string skinId, string templateId) { string htmlFileName = Path.GetFileName(templateId + ".html"); string pathToSkin = HttpContext.Current.Server.MapPath(GetSkinPath(skinId)); string pathToHtmlFile = Path.Combine(pathToSkin, "html", htmlFileName); string result = null; if (File.Exists(pathToHtmlFile)) result = File.ReadAllText(pathToHtmlFile); return result; } private string GetDefaultTemplate(string templateId, Controller controller) { return controller.RenderViewToString(templateId); } private MarkupCacheItem GetTemplateFromCache(string skinId, string templateId) { return HttpContext.Current.Cache[HtmlCachePrefix + skinId + templateId] as MarkupCacheItem; } private void PutTemplateToCache(string skinId, string templateId, MarkupCacheItem item) { #if (!DEBUG) HttpContext.Current.Cache.Insert(HtmlCachePrefix + skinId + templateId, item, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10)); #endif } private MarkupCacheItem GetDefaultTemplateFromCache(string templateId) { return HttpContext.Current.Cache[HtmlDefaultCachePrefix + templateId] as MarkupCacheItem; } private void PutDefaultHtmlToCache(string templateId, MarkupCacheItem item) { #if (!DEBUG) HttpContext.Current.Cache.Insert(HtmlDefaultCachePrefix + templateId, item, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (10)); #endif } public string GetSkinCss(string skinId) { MarkupCacheItem css = GetSkinCssFromCache(skinId); if (css != null) return css.Markup; string cssStr = GetCssFromSkin(skinId); if (!string.IsNullOrEmpty(cssStr)) { MarkupCacheItem item = new MarkupCacheItem() { Markup = cssStr }; PutSkinCssToCache(skinId, item); return cssStr; } css = GetDefaultCssFromCache(); if (css != null) { PutSkinCssToCache(skinId, css); return css.Markup; } cssStr = GetDefaultCss(); MarkupCacheItem itemDef = new MarkupCacheItem() { Markup = cssStr }; PutSkinCssToCache(skinId, itemDef); // PutDefaultCssToCache(itemDef); return cssStr; } private string GetCssFromSkin(string skinId) { string pathToFile = HttpContext.Current.Server.MapPath(Path.Combine(GetSkinPath(skinId), "skin.css")); if (!File.Exists(pathToFile)) return null; return File.ReadAllText(pathToFile); } private string GetDefaultCss() { string pathToFile = HttpContext.Current.Server.MapPath("~/Content/index.css"); if (!File.Exists(pathToFile)) return null; return File.ReadAllText(pathToFile); } private MarkupCacheItem GetSkinCssFromCache(string skinId) { return HttpContext.Current.Cache[CssCachePrefix + skinId] as MarkupCacheItem; } private void PutSkinCssToCache(string skinId, MarkupCacheItem item) { #if (!DEBUG) HttpContext.Current.Cache.Insert(CssCachePrefix + skinId, item, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5)); #endif } private MarkupCacheItem GetDefaultCssFromCache() { return HttpContext.Current.Cache[CssDefaultCacheKey] as MarkupCacheItem; } // private void PutDefaultCssToCache(MarkupCacheItem item) // { //#if (!DEBUG) // HttpContext.Current.Cache.Insert(DefaultCssCacheKey, css, null, // Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (5)); //#endif // } } public class MarkupCacheItem { public string Markup { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; //計算系をまとめる namespace Smy.Math { public class MathExtension { /// <summary> /// 3次元のベジェ曲線 /// </summary> /// <param name="ct">現在時間</param> /// <param name="et">終了時間</param> /// <param name="points">辿る位置</param> /// <returns></returns> public static Vector3 BezierCurve(float ct, float et, params Vector3[] points) { //時間になったら一番最後の位置を返す if (ct > et) return points[points.Length - 1]; //数値を0 ~ 1に納める float t = ct / et; float oneMinusT = 1.0f - t; Vector3 point = Vector3.zero; //最初と最後でかける数値を変更するため int d = 0; //ベジェ曲線の計算 for (int i = 0; i < points.Length; i++) { d = (i == 0 || i == points.Length - 1) ? 0 : 1; point += Mathf.Pow(3.0f, d) * Mathf.Pow(oneMinusT, points.Length - i - 1) * Mathf.Pow(t, i) * points[i]; } return point; } } public static class VectorExtension { /// <summary> /// 距離計算 /// </summary> /// <param name="pos1">自身の位置</param> /// <param name="pos2">相手の位置</param> /// <returns></returns> public static float Distance(this Vector3 pos1, Vector3 pos2) => (pos1 - pos2).sqrMagnitude; /// <summary> /// Vector2をVector3に変換 /// 計算時に使用 /// </summary> /// <param name="vec"></param> /// <returns></returns> public static Vector3 Vec2to3(this Vector2 vec) => new Vector3(vec.x, vec.y,0.0f); /// <summary> /// Vector3をVector2に変換 /// 計算時に使用 /// </summary> /// <param name="vec"></param> /// <returns></returns> public static Vector2 Vec3to2(this Vector3 vec) => new Vector2(vec.x, vec.y); public static Vector2 Clamp(this Vector2 vec, float min, float max) => new Vector2(Mathf.Clamp(vec.x, min, max), Mathf.Clamp(vec.y, min, max)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief 入力。インプットマネージャ編集。 */ /** NInput */ namespace NInput { /** EditInputManager_Item */ #if(UNITY_EDITOR) public class EditInputManager_Item { /** Type */ public enum Type { KeyOrMouseButton = 0, MouseMovement = 1, JoyStickAxis = 2, }; /** Axis */ public enum Axis { None = 0, XAxis = 0, YAxis = 1, Axis3 = 2, Axis4 = 3, Axis5 = 4, Axis6 = 5, Axis7 = 6, Axis8 = 7, Axis9 = 8, Axis10 = 9, Axis11 = 10, Axis12 = 11, Axis13 = 12, Axis14 = 13, Axis15 = 14, Axis16 = 15, Axis17 = 16, Axis18 = 17, Axis19 = 18, Axis20 = 19, Axis21 = 20, Axis22 = 21, Axis23 = 22, Axis24 = 23, Axis25 = 24, Axis26 = 25, Axis27 = 26, Axis28 = 27, }; /** ButtonName */ public class ButtonName { public const string LEFT = "left"; public const string RIGHT = "right"; public const string UP = "up"; public const string DOWN = "down"; public const string ENTER = "enter"; public const string ESCAPE = "escape"; public const string SUB1 = "sub1"; public const string SUB2 = "sub2"; public const string LEFT_MENU = "left_menu"; public const string RIGHT_MENU = "right_menu"; public const string LEFT_STICK_AXIS_X = "left_stick_axis_x"; public const string LEFT_STICK_AXIS_Y = "left_stick_axis_y"; public const string RIGHT_STICK_AXIS_X = "right_stick_axis_x"; public const string RIGHT_STICK_AXIS_Y = "right_stick_axis_y"; public const string LEFT_STICK_BUTTON = "left_stick_button"; public const string RIGHT_STICK_BUTTON = "right_stick_button"; public const string LEFT_TRIGGER1_BUTTON = "left_trigger1_button"; public const string RIGHT_TRIGGER1_BUTTON = "right_trigger1_button"; public const string LEFT_TRIGGER2_AXIS = "left_trigger2_axis"; public const string RIGHT_TRIGGER2_AXIS = "right_trigger2_axis"; } /** member */ public string m_Name; public string descriptiveName; public string descriptiveNegativeName; public string negativeButton; public string positiveButton; public string altNegativeButton; public string altPositiveButton; public float gravity; public float dead; public float sensitivity; public bool snap; public bool invert; public Type type; public Axis axis; public int joyNum; /** constructor */ public EditInputManager_Item() { this.m_Name = ""; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = ""; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = Type.KeyOrMouseButton; this.axis = Axis.XAxis; this.joyNum = 0; } /** デジタルボタン。左。 */ public void CreateDigitalButtonLeft() { this.m_Name = ButtonName.LEFT; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = ""; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = true; this.invert = false; this.type = NInput.EditInputManager_Item.Type.JoyStickAxis; this.axis = NInput.EditInputManager_Item.Axis.Axis6; this.joyNum = 0; } /** デジタルボタン。右。 */ public void CreateDigitalButtonRight() { this.m_Name = ButtonName.RIGHT; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = ""; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = true; this.invert = false; this.type = NInput.EditInputManager_Item.Type.JoyStickAxis; this.axis = NInput.EditInputManager_Item.Axis.Axis6; this.joyNum = 0; } /** デジタルボタン。上。 */ public void CreateDigitalButtonUp() { this.m_Name = ButtonName.UP; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = ""; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = true; this.invert = false; this.type = NInput.EditInputManager_Item.Type.JoyStickAxis; this.axis = NInput.EditInputManager_Item.Axis.Axis7; this.joyNum = 0; } /** デジタルボタン。下。 */ public void CreateDigitalButtonDown() { this.m_Name = ButtonName.DOWN; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = ""; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = true; this.invert = false; this.type = NInput.EditInputManager_Item.Type.JoyStickAxis; this.axis = NInput.EditInputManager_Item.Axis.Axis7; this.joyNum = 0; } /** デジタルボタン。Enter。 */ public void CreateDigitalButtonEnter() { this.m_Name = ButtonName.ENTER; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = "joystick button 0"; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.KeyOrMouseButton; this.axis = NInput.EditInputManager_Item.Axis.None; this.joyNum = 0; } /** デジタルボタン。Escape。 */ public void CreateDigitalButtonEscape() { this.m_Name = ButtonName.ESCAPE; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = "joystick button 1"; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.KeyOrMouseButton; this.axis = NInput.EditInputManager_Item.Axis.None; this.joyNum = 0; } /** デジタルボタン。Sub1。 */ public void CreateDigitalButtonSub1() { this.m_Name = ButtonName.SUB1; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = "joystick button 2"; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.KeyOrMouseButton; this.axis = NInput.EditInputManager_Item.Axis.None; this.joyNum = 0; } /** デジタルボタン。Sub2。 */ public void CreateDigitalButtonSub2() { this.m_Name = ButtonName.SUB2; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = "joystick button 3"; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.KeyOrMouseButton; this.axis = NInput.EditInputManager_Item.Axis.None; this.joyNum = 0; } /** デジタルボタン。左メニュー。 */ public void CreateDigitalButtonLeftMenu() { this.m_Name = ButtonName.LEFT_MENU; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = "joystick button 6"; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.KeyOrMouseButton; this.axis = NInput.EditInputManager_Item.Axis.None; this.joyNum = 0; } /** デジタルボタン。右メニュー。 */ public void CreateDigitalButtonRightMenu() { this.m_Name = ButtonName.RIGHT_MENU; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = "joystick button 7"; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.KeyOrMouseButton; this.axis = NInput.EditInputManager_Item.Axis.None; this.joyNum = 0; } /** ジョイスティック。左スティックX。 */ public void CreateLeftStickAxisX() { this.m_Name = ButtonName.LEFT_STICK_AXIS_X; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = ""; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.JoyStickAxis; this.axis = NInput.EditInputManager_Item.Axis.XAxis; this.joyNum = 0; } /** ジョイスティック。左スティックY。 */ public void CreateLeftStickAxisY() { this.m_Name = ButtonName.LEFT_STICK_AXIS_Y; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = ""; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.JoyStickAxis; this.axis = NInput.EditInputManager_Item.Axis.YAxis; this.joyNum = 0; } /** ジョイスティック。右スティックX。 */ public void CreateRightStickAxisX() { this.m_Name = ButtonName.RIGHT_STICK_AXIS_X; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = ""; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.JoyStickAxis; this.axis = NInput.EditInputManager_Item.Axis.Axis4; this.joyNum = 0; } /** ジョイスティック。右スティックY。 */ public void CreateRightStickAxisY() { this.m_Name = ButtonName.RIGHT_STICK_AXIS_Y; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = ""; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.JoyStickAxis; this.axis = NInput.EditInputManager_Item.Axis.Axis5; this.joyNum = 0; } /** ジョイスティック。左スティックボタン。 */ public void CreateLeftStickButton() { this.m_Name = ButtonName.LEFT_STICK_BUTTON; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = "joystick button 8"; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.KeyOrMouseButton; this.axis = NInput.EditInputManager_Item.Axis.None; this.joyNum = 0; } /** ジョイスティック。右スティックボタン。 */ public void CreateRightStickButton() { this.m_Name = ButtonName.RIGHT_STICK_BUTTON; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = "joystick button 9"; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.KeyOrMouseButton; this.axis = NInput.EditInputManager_Item.Axis.None; this.joyNum = 0; } /** ジョイスティック。左トリガー1ボタン。 */ public void CreateLeftTrigger1Button() { this.m_Name = ButtonName.LEFT_TRIGGER1_BUTTON; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = "joystick button 4"; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.KeyOrMouseButton; this.axis = NInput.EditInputManager_Item.Axis.None; this.joyNum = 0; } /** ジョイスティック。右トリガー1ボタン。 */ public void CreateRightTrigger1Button() { this.m_Name = ButtonName.RIGHT_TRIGGER1_BUTTON; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = "joystick button 5"; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.KeyOrMouseButton; this.axis = NInput.EditInputManager_Item.Axis.None; this.joyNum = 0; } /** ジョイスティック。左トリガー2ボタン。 */ public void CreateLeftTrigger2Button() { this.m_Name = ButtonName.LEFT_TRIGGER2_AXIS; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = ""; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = true; this.type = NInput.EditInputManager_Item.Type.JoyStickAxis; this.axis = NInput.EditInputManager_Item.Axis.Axis3; this.joyNum = 0; } /** ジョイスティック。右トリガー2ボタン。 */ public void CreateRightTrigger2Button() { this.m_Name = ButtonName.RIGHT_TRIGGER2_AXIS; this.descriptiveName = ""; this.descriptiveNegativeName = ""; this.negativeButton = ""; this.positiveButton = ""; this.altNegativeButton = ""; this.altPositiveButton = ""; this.gravity = 0.0f; this.dead = 0.001f; this.sensitivity = 1.0f; this.snap = false; this.invert = false; this.type = NInput.EditInputManager_Item.Type.JoyStickAxis; this.axis = NInput.EditInputManager_Item.Axis.Axis3; this.joyNum = 0; } } #endif }
using System; using System.Collections.Generic; using System.Text; namespace SafeSpace.core.Models { public class AppUserReportItemDetail { public long Id { get; set; } public long ReportId { get; set; } public long ItemDefinitionId { get; set; } public bool? BoolValue { get; set; } public int? IntValue { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _17单例模式 { class Program { static void Main(string[] args) { Console.WriteLine(A.Instance.volume); } } /// <summary> /// 泛型单例 /// </summary> /// <typeparam name="T"></typeparam> public class SingleTon<T> where T : new() { private static T m_instance; private static object lockObj=new object(); public static T Instance { get { if (m_instance==null) { lock (lockObj) { if (m_instance==null) { m_instance = new T(); } } } return m_instance; } } } public class A : SingleTon<A> { public int volume; /// <inheritdoc /> public A(int volume) { this.volume = volume; Console.WriteLine("Im birth"); } public EventHandler e; public void Ctor() { if (e!=null) { } } public A() { Ctor(); Console.WriteLine("Im birth"); } } /// <summary> /// 在内存里将自己实例化,称之为懒汉式单例 参见SingleTon /// </summary> public class LazySingleTon { private readonly static LazySingleTon instance=new LazySingleTon(); /// <inheritdoc /> public LazySingleTon() { } public static LazySingleTon Instance => instance; } }
//using System.Collections.Generic; //using System.Net; //using System.Web.Mvc; //using DevDevDev.Infrastructure; //using DevDevDev.Models; //using DevDevDev.Services; //namespace DevDevDev.Controllers //{ // public class VotingController : Controller // { // private readonly VoteService _voteService = new VoteService(); // private readonly SubmittedSessionsService _submittedSessionsService = new SubmittedSessionsService(); // public ActionResult SessionsToVoteFor() // { // return View(); // } // [OutputCache(Duration = 3600)] // public ActionResult GetSessionsAsJson() // { // var model = _submittedSessionsService.GetSessionsForVoting(); // return Json(model, JsonRequestBehavior.AllowGet); // } // [Throttle(Name = "ThrottleVote", Message = "Request throttled", Seconds = 5)] // [HttpPost] // public ActionResult SubmitVote(string[] sessionIds) // { // if (sessionIds.Length != EventConfig.TotalVotes) // { // return new HttpStatusCodeResult(HttpStatusCode.Forbidden); // } // var votes = new List<Vote>(); // for (var i = 0; i < EventConfig.TotalVotes; i++) // { // votes.Add(new Vote(sessionIds[i], System.Web.HttpContext.Current.Request.UserHostAddress)); // } // _voteService.AddVotes(votes); // return new HttpStatusCodeResult(HttpStatusCode.OK); // } // public ActionResult VotedSuccessfully() // { // return View(); // } // public ActionResult VotingFailure() // { // return View(); // } // } //}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SharpDX; using SharpDX.Direct3D11; using SharpDX.DXGI; using Buffer = SharpDX.Direct3D11.Buffer; using Common; namespace LoadMeshes.Application { class MeshRenderer: Common.RendererBase { // Vertex buffer List<Buffer> vertexBuffers = new List<Buffer>(); // Index Buffer List<Buffer> indexBuffers = new List<Buffer>(); // Texture resources List<ShaderResourceView> textureViews = new List<ShaderResourceView>(); // Sampler state SamplerState samplerState; // Create and allow access to a timer System.Diagnostics.Stopwatch clock = new System.Diagnostics.Stopwatch(); public System.Diagnostics.Stopwatch Clock { get { return clock; } set { clock = value; } } public Common.Mesh.Animation? CurrentAnimation { get; set; } public bool PlayOnce { get; set; } // Loaded mesh Common.Mesh mesh; public Common.Mesh Mesh { get { return mesh; } } // Per material buffer to use so that the mesh parameters can be used public Buffer PerMaterialBuffer { get; set; } public Buffer PerArmatureBuffer { get; set; } public MeshRenderer(Common.Mesh mesh) { this.mesh = mesh; } protected override void CreateDeviceDependentResources() { base.CreateDeviceDependentResources(); // release resources vertexBuffers.ForEach(b => RemoveAndDispose(ref b)); vertexBuffers.Clear(); indexBuffers.ForEach(b => RemoveAndDispose(ref b)); indexBuffers.Clear(); textureViews.ForEach(t => RemoveAndDispose(ref t)); textureViews.Clear(); RemoveAndDispose(ref samplerState); var device = DeviceManager.Direct3DDevice; // Create the vertex buffers for (int i = 0; i < mesh.VertexBuffers.Count; i++) { var vb = mesh.VertexBuffers[i]; Vertex[] vertices = new Vertex[vb.Length]; for (var j = 0; j < vb.Length; j++) { // Retrieve skinning info for vertex Common.Mesh.SkinningVertex skin = new Common.Mesh.SkinningVertex(); if (mesh.SkinningVertexBuffers.Count > 0) skin = mesh.SkinningVertexBuffers[i][j]; // create vertex vertices[j] = new Vertex(vb[j].Position, vb[j].Normal, vb[j].Color, vb[j].UV, skin); } vertexBuffers.Add(ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, vertices.ToArray()))); vertexBuffers[vertexBuffers.Count - 1].DebugName = "VertexBuffer_" + vertexBuffers.Count.ToString(); } // Create the index buffers foreach (var ib in mesh.IndexBuffers) { indexBuffers.Add(ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, ib))); indexBuffers[indexBuffers.Count - 1].DebugName = "IndexBuffer_" + (indexBuffers.Count - 1).ToString(); } // Create the textures resources views // The CMO file format supports up to 8 per material foreach (var m in mesh.Materials) { // Diffuse color for (var i = 0; i < m.Textures.Length; i++) { textureViews.Add(SharpDX.IO.NativeFile.Exists(m.Textures[i]) ? ToDispose(ShaderResourceView.FromFile(device, m.Textures[i])) : null); } } // Create the sampler state samplerState = ToDispose(new SamplerState(device, new SamplerStateDescription { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, BorderColor = Color.Black, ComparisonFunction = Comparison.Never, Filter = Filter.MinMagMipLinear, MaximumAnisotropy = 16, MaximumLod = float.MaxValue, MinimumLod = 0, MipLodBias = 0.0f })); } //protected override void DoRender() //{ // var time = clock.ElapsedMilliseconds / 1000.0f; // var context = DeviceManager.Direct3DContext; // //Calculate skin matrices for each bone // ConstantBuffer.PerArmature skinMatrices = new ConstantBuffer.PerArmature(); // if(mesh.Bones !=null) // { // // Retrieve bone local transform // for(var i=0;i<mesh.Bones.Count;i++) // { // skinMatrices.Bones[i]=mesh.Bones[i].BoneLocalTransform; // } // if(CurrentAnimation.HasValue) // { // Common.Mesh.Keyframe?[] lastKeyForBones = new Common.Mesh.Keyframe?[mesh.Bones.Count]; // bool[] lerpedBones = new bool[mesh.Bones.Count]; // for (var i = 0; i < CurrentAnimation.Value.Keyframes.Count; i++) // { // var frame = CurrentAnimation.Value.Keyframes[i]; // if (frame.Time <= time) // { // skinMatrices.Bones[frame.BoneIndex] = frame.Transform; // lastKeyForBones[frame.BoneIndex] = frame; // } // else // { // //perform future frame interpolation // if(!lerpedBones[frame.BoneIndex]) // { // Common.Mesh.Keyframe prevFrame; // if (lastKeyForBones[frame.BoneIndex] != null) // { // prevFrame = lastKeyForBones[frame.BoneIndex].Value; // } // else // continue; // lerpedBones[frame.BoneIndex] = true; // var frameLength = frame.Time - prevFrame.Time; // var timeDiff = time - prevFrame.Time; // var amount = timeDiff / frameLength; // Vector3 t1, t2; // Quaternion q1, q2; // float s1, s2; // prevFrame.Transform.DecomposeUniformScale(out s1, out q1, out t1); // frame.Transform.DecomposeUniformScale(out s2, out q2, out t2); // skinMatrices.Bones[frame.BoneIndex] = Matrix.Scaling(MathUtil.Lerp(s1, s2, amount)) * // Matrix.RotationQuaternion(Quaternion.Slerp(q1, q2, amount)) * // Matrix.Translation(Vector3.Lerp(t1, t2, amount)); // } // } // } // } // for(var i=0;i<mesh.Bones.Count;i++) // { // var bone = mesh.Bones[i]; // if(bone.ParentIndex>-1) // { // var parentTransform = skinMatrices.Bones[bone.ParentIndex]; // skinMatrices.Bones[i] = skinMatrices.Bones[i] * parentTransform; // } // } // for (var i = 0; i < mesh.Bones.Count; i++) // { // skinMatrices.Bones[i] = Matrix.Transpose(mesh.Bones[i].InvBindPose* skinMatrices.Bones[i]); // } // // Check need to loop animation // if (!PlayOnce && CurrentAnimation.HasValue && CurrentAnimation.Value.EndTime <= time) // { // this.Clock.Restart(); // } // } // // Update constant buffer // context.UpdateSubresource(skinMatrices.Bones, PerArmatureBuffer); // // Draw sub-meshes grouped by material // for (var m = 0; m < mesh.Materials.Count; m++) // { // //var subMeshesForMaterial = mesh.SubMeshes; // var subMeshesForMaterial = // (from sm in mesh.SubMeshes // where sm.MaterialIndex == m // select sm).ToArray(); // // if material buffer is assigned // if (PerMaterialBuffer != null && subMeshesForMaterial.Length > 0) // { // // update the PerMaterialBuffer constant buffer // var material = new ConstantBuffer.PerMaterial() // { // Ambient = new Color4(mesh.Materials[m].Ambient), // Diffuse = new Color4(mesh.Materials[m].Diffuse), // Emissive = new Color4(mesh.Materials[m].Emissive), // Specular = new Color4(mesh.Materials[m].Specular), // Shininess = mesh.Materials[m].SpecularPower, // UVTransform = mesh.Materials[m].UVTransform, // }; // // Bind textures to the pixel shader // int texIndxOffset = m * Common.Mesh.MaxTextures; // material.HasTexture = (uint)(textureViews[texIndxOffset] != null ? 1 : 0); // 0=false // context.PixelShader.SetShaderResources(0, textureViews.GetRange(texIndxOffset, Common.Mesh.MaxTextures).ToArray()); // // Set texture sampler state // context.PixelShader.SetSampler(0, samplerState); // // Update material buffer // context.UpdateSubresource(ref material, PerMaterialBuffer); // } // // for each submeshes // foreach (var subMesh in subMeshesForMaterial) // { // // render each submesh // // Ensure the vertex buffer and index buffers are in range // if (subMesh.VertexBufferIndex < vertexBuffers.Count && subMesh.IndexBufferIndex < indexBuffers.Count) // { // // Retrieve and set the vertex and index buffers // var vertexBuffer = vertexBuffers[(int)subMesh.VertexBufferIndex]; // context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0)); // context.InputAssembler.SetIndexBuffer(indexBuffers[(int)subMesh.IndexBufferIndex], Format.R16_UInt, 0); // // Set topology // context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; // } // // Draw the sub-mesh (includes Primitive count which we multiply by 3) // // The submesh also includes a start index into the vertex buffer // context.DrawIndexed((int)subMesh.PrimCount * 3, (int)subMesh.StartIndex, 0); // } // } //} protected override void DoRender() { // Calculate elapsed seconds var time = clock.ElapsedMilliseconds / 1000.0f; // Retrieve device context var context = this.DeviceManager.Direct3DContext; // Calculate skin matrices for each bone ConstantBuffer.PerArmature skinMatrices = new ConstantBuffer.PerArmature(); if (mesh.Bones != null) { // Retrieve each bone's local transform for (var i = 0; i < mesh.Bones.Count; i++) { skinMatrices.Bones[i] = mesh.Bones[i].BoneLocalTransform; } // Load bone transforms from animation frames if (CurrentAnimation.HasValue) { // Keep track of the last key-frame used for each bone Mesh.Keyframe?[] lastKeyForBones = new Mesh.Keyframe?[mesh.Bones.Count]; // Keep track of whether a bone has been interpolated bool[] lerpedBones = new bool[mesh.Bones.Count]; for (var i = 0; i < CurrentAnimation.Value.Keyframes.Count; i++) { // Retrieve current key-frame var frame = CurrentAnimation.Value.Keyframes[i]; // If the current frame is not in the future if (frame.Time <= time) { // Keep track of last key-frame for bone lastKeyForBones[frame.BoneIndex] = frame; // Retrieve transform from current key-frame skinMatrices.Bones[frame.BoneIndex] = frame.Transform; } // Frame is in the future, check if we should interpolate else { // Only interpolate a bone's key-frames ONCE if (!lerpedBones[frame.BoneIndex]) { // Retrieve the previous key-frame if exists Mesh.Keyframe prevFrame; if (lastKeyForBones[frame.BoneIndex] != null) prevFrame = lastKeyForBones[frame.BoneIndex].Value; else continue; // nothing to interpolate // Make sure we only interpolate with // one future frame for this bone lerpedBones[frame.BoneIndex] = true; // Calculate time difference between frames var frameLength = frame.Time - prevFrame.Time; var timeDiff = time - prevFrame.Time; var amount = timeDiff / frameLength; // Interpolation using Lerp on scale and translation, and Slerp on Rotation (Quaternion) Vector3 t1, t2; // Translation Quaternion q1, q2;// Rotation float s1, s2; // Scale // Decompose the previous key-frame's transform prevFrame.Transform.DecomposeUniformScale(out s1, out q1, out t1); // Decompose the current key-frame's transform frame.Transform.DecomposeUniformScale(out s2, out q2, out t2); // Perform interpolation and reconstitute matrix skinMatrices.Bones[frame.BoneIndex] = Matrix.Scaling(MathUtil.Lerp(s1, s2, amount)) * Matrix.RotationQuaternion(Quaternion.Slerp(q1, q2, amount)) * Matrix.Translation(Vector3.Lerp(t1, t2, amount)); } } } } // Apply parent bone transforms // We assume here that the first bone has no parent // and that each parent bone appears before children for (var i = 1; i < mesh.Bones.Count; i++) { var bone = mesh.Bones[i]; if (bone.ParentIndex > -1) { var parentTransform = skinMatrices.Bones[bone.ParentIndex]; skinMatrices.Bones[i] = (skinMatrices.Bones[i] * parentTransform); } } // Change the bone transform from rest pose space into bone space (using the inverse of the bind/rest pose) for (var i = 0; i < mesh.Bones.Count; i++) { skinMatrices.Bones[i] = Matrix.Transpose(mesh.Bones[i].InvBindPose * skinMatrices.Bones[i]); } // Check need to loop animation if (!PlayOnce && CurrentAnimation.HasValue && CurrentAnimation.Value.EndTime <= time) { this.Clock.Restart(); } } // Update the constant buffer with the skin matrices for each bone context.UpdateSubresource(skinMatrices.Bones, PerArmatureBuffer); // Draw sub-meshes grouped by material for (var mIndx = 0; mIndx < mesh.Materials.Count; mIndx++) { // Retrieve sub meshes for this material var subMeshesForMaterial = (from sm in mesh.SubMeshes where sm.MaterialIndex == mIndx select sm).ToArray(); // If the material buffer is available and there are submeshes // using the material update the PerMaterialBuffer if (PerMaterialBuffer != null && subMeshesForMaterial.Length > 0) { // update the PerMaterialBuffer constant buffer var material = new ConstantBuffer.PerMaterial() { Ambient = new Color4(mesh.Materials[mIndx].Ambient), Diffuse = new Color4(mesh.Materials[mIndx].Diffuse), Emissive = new Color4(mesh.Materials[mIndx].Emissive), Specular = new Color4(mesh.Materials[mIndx].Specular), Shininess = mesh.Materials[mIndx].SpecularPower, UVTransform = mesh.Materials[mIndx].UVTransform, }; // Bind textures to the pixel shader int texIndxOffset = mIndx * Common.Mesh.MaxTextures; material.HasTexture = (uint)(textureViews[texIndxOffset] != null ? 1 : 0); // 0=false context.PixelShader.SetShaderResources(0, textureViews.GetRange(texIndxOffset, Common.Mesh.MaxTextures).ToArray()); // Set texture sampler state context.PixelShader.SetSampler(0, samplerState); // Update material buffer context.UpdateSubresource(ref material, PerMaterialBuffer); } // For each sub-mesh foreach (var subMesh in subMeshesForMaterial) { // Ensure the vertex buffer and index buffers are in range if (subMesh.VertexBufferIndex < vertexBuffers.Count && subMesh.IndexBufferIndex < indexBuffers.Count) { // Retrieve and set the vertex and index buffers var vertexBuffer = vertexBuffers[(int)subMesh.VertexBufferIndex]; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0)); context.InputAssembler.SetIndexBuffer(indexBuffers[(int)subMesh.IndexBufferIndex], Format.R16_UInt, 0); // Set topology context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; } // Draw the sub-mesh (includes Primitive count which we multiply by 3) // The submesh also includes a start index into the vertex buffer context.DrawIndexed((int)subMesh.PrimCount * 3, (int)subMesh.StartIndex, 0); } } } } }
using Hl7.Fhir.Model; using Hl7.Fhir.Rest; using LockStepBlazor.Application; using LockStepBlazor.Application.Fhir.Queries; using LockStepBlazor.Application.Interfaces; using LockStepBlazor.Data.Models; using LockStepBlazor.Data.Services; using System.Collections.Generic; using System.Threading.Tasks; namespace LockStepBlazor.Data { public interface IPatientDataService { Task<IGetDrugInteractions.Model> GetDrugInteractionListAsync(List<string> rxcuis); Task<IGetFhirMedications.Model> GetMedicationRequestsAsync(string id); Task<GetPatientList.Model> GetPatientListAsync(string firstName = null, string lastName = null); Task<GetPatient.Model> GetPatientAsync(string id); Task<NavigateBundle.Model> NavigateBundleAsync(Bundle bundle, PageDirection nav); Task<GetRxCuiListAPI.Model> GetRxCuisAsync(List<MedicationConceptDTO> requests); } }
using UnityEngine; using UnityEngine.Events; namespace ACO.Helper { public class ObjectActivator : MonoBehaviour { public bool DefaultState = true; public bool InvertEvent = false; public UnityEvent OnActivate = new UnityEvent(); public UnityEvent OnDeactivate = new UnityEvent(); private bool _activatorChanged = false; private void Awake() { if (_activatorChanged) return; gameObject.SetActive(DefaultState); } public void Activate(bool state) { _activatorChanged = true; var res = InvertEvent ? !state : state; gameObject.SetActive(res); if (res) { OnActivate.Invoke(); } else { OnDeactivate.Invoke(); } } } }
using Eventual.EventStore.Core; using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Text; namespace Eventual.EventStore.Readers.Reactive { public static class EventStoreObservables { private const int NumberOfResultsPerRequest = 2; private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(15); private const int DefaultRetries = 3; private static readonly TimeSpan DefaultPollingInterval = TimeSpan.FromSeconds(5); #region Individual event stream catch-up observables public static IObservable<Revision> EventStreamFrom(IEventStreamReader eventStoreClient, EventStreamCheckpoint checkpoint, int retries = DefaultRetries, IScheduler scheduler = null) { return EventStreamFrom(eventStoreClient, checkpoint, DefaultTimeout, retries, scheduler); } public static IObservable<Revision> EventStreamFrom(IEventStreamReader eventStoreClient, EventStreamCheckpoint checkpoint, TimeSpan timeout, int retries = DefaultRetries, IScheduler scheduler = null) { return Observable.Create<Revision>(observer => { var poll = EventStreamBatchesFrom(eventStoreClient, checkpoint, timeout, retries, scheduler); return poll.Subscribe( value => { foreach (var revision in value) { observer.OnNext(revision); } }, ex => observer.OnError(ex), () => observer.OnCompleted()); }); } public static IObservable<Revision> ContinuousEventStreamFrom(IEventStreamReader eventStoreClient, EventStreamCheckpoint checkpoint, int retries = DefaultRetries, IScheduler scheduler = null) { return ContinuousEventStreamFrom(eventStoreClient, checkpoint, DefaultTimeout, DefaultPollingInterval, retries, scheduler); } public static IObservable<Revision> ContinuousEventStreamFrom(IEventStreamReader eventStoreClient, EventStreamCheckpoint checkpoint, TimeSpan timeout, int retries = DefaultRetries, IScheduler scheduler = null) { return ContinuousEventStreamFrom(eventStoreClient, checkpoint, timeout, DefaultPollingInterval, retries, scheduler); } public static IObservable<Revision> ContinuousEventStreamFrom(IEventStreamReader eventStoreClient, EventStreamCheckpoint checkpoint, TimeSpan timeout, TimeSpan pollingInterval, int retries = DefaultRetries, IScheduler scheduler = null) { return Observable.Create<Revision>(observer => { var poll = ContinuousEventStreamBatchesFrom(eventStoreClient, checkpoint, pollingInterval, timeout, retries, scheduler); return poll.Subscribe( value => { foreach (var revision in value) { observer.OnNext(revision); } }, ex => observer.OnError(ex), () => observer.OnCompleted()); }); } #region Private observables (supporting catch-up individual event stream observables) private static IObservable<IEnumerable<Revision>> EventStreamBatchesFrom(IEventStreamReader eventStoreClient, EventStreamCheckpoint checkpoint, TimeSpan timeout, int retries = DefaultRetries, IScheduler scheduler = null) { return EventStreamBatchesFrom(eventStoreClient, checkpoint, timeout, TimeSpan.Zero, false, retries, scheduler); } private static IObservable<IEnumerable<Revision>> ContinuousEventStreamBatchesFrom(IEventStreamReader eventStoreClient, EventStreamCheckpoint checkpoint, TimeSpan timeout, TimeSpan pollingInterval, int retries = DefaultRetries, IScheduler scheduler = null) { return EventStreamBatchesFrom(eventStoreClient, checkpoint, timeout, pollingInterval, true, retries, scheduler); } private static IObservable<IEnumerable<Revision>> EventStreamBatchesFrom(IEventStreamReader eventStoreClient, EventStreamCheckpoint checkpoint, TimeSpan timeout, TimeSpan pollingInterval, bool infinitePollingEnabled = false, int retries = DefaultRetries, IScheduler scheduler = null) { scheduler = scheduler ?? Scheduler.Default; return ObservableExtensions.Generate(async () => { IEnumerable<Revision> result = await EventStreamSingleBatch(eventStoreClient, checkpoint, NumberOfResultsPerRequest, timeout, retries, scheduler); return new EventStreamPollingState { LastCheckpoint = EventStreamCheckpoint.CreateStreamCheckpoint(checkpoint.StreamId, checkpoint.RevisionId + result.Count(), 0), LastStreamBatch = result }; }, value => (value.LastStreamBatch != null && value.LastStreamBatch.Count() > 0) || infinitePollingEnabled, async value => { var streamBatch = EventStreamSingleBatch(eventStoreClient, value.LastCheckpoint, NumberOfResultsPerRequest, timeout, retries, scheduler); IEnumerable<Revision> result = null; //Introduce delay before performing next request (if required) var delay = Observable.Empty<IEnumerable<Revision>>().Delay(pollingInterval); if (value.LastStreamBatch == null || value.LastStreamBatch.Count() == 0 && infinitePollingEnabled) { result = await delay.Concat(streamBatch); } else { result = await streamBatch; } if (result != null && result.Count() > 0) { return new EventStreamPollingState { LastCheckpoint = EventStreamCheckpoint.CreateStreamCheckpoint(value.LastCheckpoint.StreamId, value.LastCheckpoint.RevisionId + result.Count(), 0), LastStreamBatch = result }; } else { return new EventStreamPollingState { LastCheckpoint = EventStreamCheckpoint.CreateStreamCheckpoint(value.LastCheckpoint.StreamId, value.LastCheckpoint.RevisionId, 0), LastStreamBatch = Enumerable.Empty<Revision>() }; } }, value => value.LastStreamBatch, scheduler); } public static IObservable<IEnumerable<Revision>> EventStreamSingleBatch(IEventStreamReader eventStoreClient, EventStreamCheckpoint checkpoint, int numberOfResults, TimeSpan timeout, int retries, IScheduler scheduler) { return Observable.Return(1, scheduler) .SelectMany(_ => { return eventStoreClient.GetEventStreamFromAsync(checkpoint.StreamId, checkpoint.RevisionId, numberOfResults); }) .Do(_ => Console.WriteLine(string.Format("Requested event stream range [{0} - {1}]", checkpoint.RevisionId, checkpoint.RevisionId + numberOfResults - 1))) .Timeout(timeout, scheduler) .Retry(retries) .Select(stream => stream.Revisions.AsEnumerable()); } #endregion #endregion #region All event streams catch-up observables public static IObservable<Revision> AllEventStreamsFrom(IEventStreamReader eventStoreClient, GlobalCheckpoint checkpoint, int retries = DefaultRetries, IScheduler scheduler = null) { return AllEventStreamsFrom(eventStoreClient, checkpoint, DefaultTimeout, retries, scheduler); } public static IObservable<Revision> AllEventStreamsFrom(IEventStreamReader eventStoreClient, GlobalCheckpoint checkpoint, TimeSpan timeout, int retries = DefaultRetries, IScheduler scheduler = null) { return Observable.Create<Revision>(observer => { var poll = AllEventStreamBatchesFrom(eventStoreClient, checkpoint, timeout, retries, scheduler); return poll.Subscribe( value => { foreach (var revision in value) { observer.OnNext(revision); } }, ex => observer.OnError(ex), () => observer.OnCompleted()); }); } public static IObservable<Revision> ContinuousAllEventStreamsFrom(IEventStreamReader eventStoreClient, GlobalCheckpoint checkpoint, int retries = DefaultRetries, IScheduler scheduler = null) { return ContinuousAllEventStreamsFrom(eventStoreClient, checkpoint, DefaultTimeout, DefaultPollingInterval, retries, scheduler); } public static IObservable<Revision> ContinuousAllEventStreamsFrom(IEventStreamReader eventStoreClient, GlobalCheckpoint checkpoint, TimeSpan timeout, int retries = DefaultRetries, IScheduler scheduler = null) { return ContinuousAllEventStreamsFrom(eventStoreClient, checkpoint, timeout, DefaultPollingInterval, retries, scheduler); } public static IObservable<Revision> ContinuousAllEventStreamsFrom(IEventStreamReader eventStoreClient, GlobalCheckpoint checkpoint, TimeSpan timeout, TimeSpan pollingInterval, int retries = DefaultRetries, IScheduler scheduler = null) { return Observable.Create<Revision>(observer => { var poll = ContinuousAllEventStreamBatchesFrom(eventStoreClient, checkpoint, timeout, pollingInterval, retries, scheduler); return poll.Subscribe( value => { foreach (var revision in value) { observer.OnNext(revision); } }, ex => observer.OnError(ex), () => observer.OnCompleted()); }); } #region Private observables (supporting catch-up all event streams observables) private static IObservable<IEnumerable<Revision>> AllEventStreamBatchesFrom(IEventStreamReader eventStoreClient, GlobalCheckpoint checkpoint, TimeSpan timeout, int retries, IScheduler scheduler) { return AllEventStreamBatchesFrom(eventStoreClient, checkpoint, timeout, TimeSpan.Zero, false, retries, scheduler); } private static IObservable<IEnumerable<Revision>> ContinuousAllEventStreamBatchesFrom(IEventStreamReader eventStoreClient, GlobalCheckpoint checkpoint, TimeSpan timeout, TimeSpan pollingInterval, int retries = DefaultRetries, IScheduler scheduler = null) { return AllEventStreamBatchesFrom(eventStoreClient, checkpoint, timeout, pollingInterval, true, retries, scheduler); } private static IObservable<IEnumerable<Revision>> AllEventStreamBatchesFrom(IEventStreamReader eventStoreClient, GlobalCheckpoint checkpoint, TimeSpan timeout, TimeSpan pollingInterval, bool infinitePollingEnabled = false, int retries = DefaultRetries, IScheduler scheduler = null) { scheduler = scheduler ?? Scheduler.Default; return ObservableExtensions.Generate(async () => { IEnumerable<Revision> result = await AllEventStreamsSingleBatch(eventStoreClient, checkpoint, NumberOfResultsPerRequest, timeout, retries, scheduler); return new AllEventStreamsPollingState { LastCheckpoint = GlobalCheckpoint.Create(checkpoint.CommitId + result.Count()), LastStreamBatch = result }; }, value => (value.LastStreamBatch != null && value.LastStreamBatch.Count() > 0) || infinitePollingEnabled, async value => { var streamBatch = AllEventStreamsSingleBatch(eventStoreClient, value.LastCheckpoint, NumberOfResultsPerRequest, timeout, retries, scheduler); IEnumerable<Revision> result = null; //Introduce delay before performing next request (if required) var delay = Observable.Empty<IEnumerable<Revision>>().Delay(pollingInterval); if (value.LastStreamBatch == null || value.LastStreamBatch.Count() == 0 && infinitePollingEnabled) { result = await delay.Concat(streamBatch); } else { result = await streamBatch; } if (result != null && result.Count() > 0) { return new AllEventStreamsPollingState { LastCheckpoint = GlobalCheckpoint.Create(value.LastCheckpoint.CommitId + result.Count()), LastStreamBatch = result }; } else { return new AllEventStreamsPollingState { LastCheckpoint = GlobalCheckpoint.Create(value.LastCheckpoint.CommitId), LastStreamBatch = Enumerable.Empty<Revision>() }; } }, value => value.LastStreamBatch, scheduler); } private static IObservable<IEnumerable<Revision>> AllEventStreamsSingleBatch(IEventStreamReader eventStoreClient, GlobalCheckpoint checkpoint, int numberOfResults, TimeSpan timeout, int retries, IScheduler scheduler) { return Observable.Return(1, scheduler) .SelectMany(_ => { return eventStoreClient.GetAllEventStreamsFromAsync(checkpoint.CommitId, numberOfResults); }) .Do(_ => Console.WriteLine(string.Format("Requested all event streams range (commit) [{0} - {1}]", checkpoint.CommitId, checkpoint.CommitId + numberOfResults - 1))) .Timeout(timeout, scheduler) .Retry(retries) .Select(stream => stream.Revisions.AsEnumerable()); } #endregion #endregion } }
using Enrollment.Bsl.Business.Requests; using Enrollment.Bsl.Business.Responses; using Enrollment.Forms.Configuration; using Enrollment.Forms.Configuration.DataForm; using Enrollment.XPlatform.Directives; using Enrollment.XPlatform.Directives.Factories; using Enrollment.XPlatform.Flow.Requests; using Enrollment.XPlatform.Flow.Settings.Screen; using Enrollment.XPlatform.Services; using Enrollment.XPlatform.Utils; using Enrollment.XPlatform.ViewModels.Factories; using Microsoft.Extensions.DependencyInjection; using System; using System.Windows.Input; using Xamarin.Forms; namespace Enrollment.XPlatform.ViewModels.DetailForm { public class DetailFormViewModel<TModel> : DetailFormViewModelBase, IDisposable where TModel : Domain.EntityModelBase { public DetailFormViewModel( ICollectionBuilderFactory collectionBuilderFactory, IDirectiveManagersFactory directiveManagersFactory, IHttpService httpService, IReadOnlyPropertiesUpdater readOnlyPropertiesUpdater, IUiNotificationService uiNotificationService, ScreenSettings<DataFormSettingsDescriptor> screenSettings) : base(screenSettings, uiNotificationService) { FormLayout = collectionBuilderFactory.GetReadOnlyFieldsCollectionBuilder ( typeof(TModel), this.FormSettings.FieldSettings, this.FormSettings, null, null ).CreateFields(); this.httpService = httpService; this.propertiesUpdater = readOnlyPropertiesUpdater; this.directiveManagers = (ReadOnlyDirectiveManagers<TModel>)directiveManagersFactory.GetReadOnlyDirectiveManagers ( typeof(TModel), FormLayout.Properties, FormSettings ); GetEntity(); } private readonly IHttpService httpService; private readonly IReadOnlyPropertiesUpdater propertiesUpdater; private readonly ReadOnlyDirectiveManagers<TModel> directiveManagers; private TModel? entity; private ICommand? _deleteCommand; public ICommand DeleteCommand { get { if (_deleteCommand != null) return _deleteCommand; _deleteCommand = new Command<CommandButtonDescriptor> ( async (button) => { BaseResponse response = await BusyIndicatorHelpers.ExecuteRequestWithBusyIndicator ( () => this.httpService.DeleteEntity ( new DeleteEntityRequest { Entity = entity }, this.FormSettings.RequestDetails.DeleteUrl ) ); if (response.Success == false) { await App.Current!.MainPage!.DisplayAlert/*App.Current.MainPage is not null at this point*/ ( "Errors", string.Join(Environment.NewLine, response.ErrorMessages), "Ok" ); } Next(button); } ); return _deleteCommand; } } private ICommand? _editCommand; public ICommand EditCommand { get { if (_editCommand != null) return _editCommand; _editCommand = new Command<CommandButtonDescriptor> ( Edit, (button) => this.entity != null ); return _editCommand; } } public override DetailFormLayout FormLayout { get; set; } public void Dispose() { Dispose(this.directiveManagers); foreach (var property in FormLayout.Properties) { if (property is IDisposable disposable) Dispose(disposable); } GC.SuppressFinalize(this); } protected void Dispose(IDisposable disposable) { if (disposable != null) disposable.Dispose(); } private void Edit(CommandButtonDescriptor button) { SetEntityAndNavigateNext(button); } private async void GetEntity() { if (this.FormSettings.RequestDetails.Filter == null) throw new ArgumentException($"{nameof(this.FormSettings.RequestDetails.Filter)}: 51755FE3-099A-44EB-A59B-3ED312EDD8D1"); BaseResponse baseResponse = await BusyIndicatorHelpers.ExecuteRequestWithBusyIndicator ( () => this.httpService.GetEntity ( new GetEntityRequest { Filter = this.FormSettings.RequestDetails.Filter, SelectExpandDefinition = this.FormSettings.RequestDetails.SelectExpandDefinition, ModelType = this.FormSettings.RequestDetails.ModelType, DataType = this.FormSettings.RequestDetails.DataType } ) ); if (baseResponse.Success == false) { await App.Current!.MainPage!.DisplayAlert/*App.Current.MainPage is not null at this point*/ ( "Errors", string.Join(Environment.NewLine, baseResponse.ErrorMessages), "Ok" ); return; } GetEntityResponse getEntityResponse = (GetEntityResponse)baseResponse; this.entity = (TModel)getEntityResponse.Entity; ((Command)EditCommand).ChangeCanExecute(); this.propertiesUpdater.UpdateProperties ( FormLayout.Properties, getEntityResponse.Entity, this.FormSettings.FieldSettings ); } private void SetEntityAndNavigateNext(CommandButtonDescriptor button) { if (entity == null) throw new ArgumentException($"{nameof(entity)}: {{97F661A5-1AE3-4A85-8083-438B665A58B7}}"); using IScopedFlowManagerService flowManagerService = App.ServiceProvider.GetRequiredService<IScopedFlowManagerService>(); flowManagerService.CopyFlowItems(); flowManagerService.SetFlowDataCacheItem ( typeof(TModel).FullName!, this.entity ); flowManagerService.Next ( new CommandButtonRequest { NewSelection = button.ShortString } ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataLayer.PerfilesData { public class PerfilesData:DataBase { #region Constructores public PerfilesData(Conexion.DAOFactory factory) : base(factory) { } #endregion #region Metodos y funciones /// <summary> /// Método para consultar a las personas de la tabla Areas /// </summary> public void ConsultarPerfiles() { ConsultarGenerico(Constantes.spApoyoDBAObtenerPerfiles); } #endregion } }
namespace BankSYS { class Transaction { public string TransactionID { get; set; } public string account { get; set; } public string type { get; set; } public string amount { get; set; } public string note { get; set; } public string debtor { get; set; } public string timestamp { get; set; } } }
using System; using UnityEngine; namespace syscrawl.Game.Models.Levels { public class CreateNodeConnection { public Vector3 From { get; set; } public Vector3 To { get; set; } public GameObject Container { get; set; } } }
using System; using Pidgin; using ODataQuery.Nodes; using static Pidgin.Parser; using static Pidgin.Parser<char>; namespace ODataQuery.Parsers { static class Literals { // Required Whitespace public static readonly Parser<char, Unit> RWS = Char(' ').SkipAtLeastOnce(); // Bad Whitespace public static readonly Parser<char, Unit> BWS = Char(' ').SkipMany(); public static Parser<char, T> BetweenParen<T>(this Parser<char, T> x) => x.Between( Char('(').Before(BWS), BWS.Before(Char(')')) ); public static readonly Parser<char, Node> Identifier = Token(c => ((uint)c - 'a') < 26 || ((uint)c - 'A') < 26 || c == '_') .Then(Token(c => ((uint)c - 'a') < 26 || ((uint)c - 'A') < 26 || ((uint)c - '0') < 10 || c == '_').ManyString(), (first, rest) => (Node)new IdentifierNode(first + rest)); public static readonly Parser<char, Node> StringLiteral = AnyCharExcept('\'') .Or(Try(String("''").WithResult('\''))) .ManyString() .Between(Char('\'')) .Select<Node>(s => new ConstantNode(s)); public static readonly Parser<char, Node> NumberLiteral = Map((s, m, f) => (Node)new ConstantNode(decimal.Parse((s.HasValue ? "-" : "") + m + (f.HasValue ? "." + f.Value : ""))), Char('-').Optional(), Digit.AtLeastOnceString(), Char('.').Then(Digit.AtLeastOnceString()).Optional() ); public static readonly Parser<char, Node> DateLiteral = Map((y, m, d) => new DateTime(int.Parse(y), int.Parse(m), int.Parse(d)), Digit.RepeatString(4).Before(Char('-')), Digit.RepeatString(2).Before(Char('-')), Digit.RepeatString(2)) .Then( Map((_, h, m, s, f) => new TimeSpan(0, int.Parse(h), int.Parse(m), int.Parse(s), !f.HasValue ? 0 : int.Parse(f.Value.PadRight(3, '0').Substring(0, 3))), Char('T'), Digit.RepeatString(2).Before(Char(':')), Digit.RepeatString(2).Before(Char(':')), Digit.RepeatString(2), Char('.').Then(Digit.AtLeastOnceString()).Optional()) .Optional(), (dt, ts) => ts.HasValue ? dt.Add(ts.Value) : dt ) .Then( OneOf( Char('Z').WithResult(TimeSpan.Zero), Char('+').Then(Digit.RepeatString(4)).Select(tz => new TimeSpan(int.Parse(tz.Substring(0, 2)), int.Parse(tz.Substring(2, 2)), 0)), Char('-').Then(Digit.RepeatString(4)).Select(tz => - new TimeSpan(int.Parse(tz.Substring(0, 2)), int.Parse(tz.Substring(2, 2)), 0)) ).Optional(), (dt, tz) => tz.HasValue ? new DateTimeOffset(dt, tz.Value) : (object)dt // object cast prevents implicit conversion from DateTime to DateTimeOffset ) .Select<Node>(d => new ConstantNode(d)); public static readonly Parser<char, Node> KeywordLiteral = OneOf( String("false").WithResult(ConstantNode.False), String("null").WithResult(ConstantNode.Null), String("true").WithResult(ConstantNode.True) ); public static readonly Parser<char, Node> Constant = OneOf(StringLiteral, Try(DateLiteral), // Try -> ambiguous with ints as both start with a digit NumberLiteral, KeywordLiteral); } }
using System.Collections.Generic; using System.Linq; using StreetFinder.AbbreviationsFilter; namespace StreetFinder.CombineFilter { public class StreetTokenCombiner { private readonly List<string> _tokensList = new List<string>(); private int _index = -1 ; private string lastToken; readonly AbbreviationsEngine _abbreviationsEngine = new AbbreviationsEngine(); public void Add(string token) { if (_tokensList.Count == 0) { _tokensList.Add(token); lastToken = token; return; } if (_abbreviationsEngine.HasAbbreviationsOrIsAbbreviation(_tokensList.Last())) { _tokensList.Add(token); lastToken = token; return; } if (lastToken.Equals(_tokensList.Last())) { _tokensList.RemoveAt(_tokensList.Count -1); } _tokensList.Add(lastToken + token); _tokensList.Add(token); lastToken = token; } public bool NextElement() { _index++; if (_tokensList.Count <= 0 || _index >= _tokensList.Count ) { return false; } return true; } public string ElementAt(int position) { if (_tokensList.Count <= 0 || position >= _tokensList.Count || position < 0) { return null; } return _tokensList.ElementAt(position); } public string CurrentElement() { if (_tokensList.Count <= 0 || _index >= _tokensList.Count) { return null; } return _tokensList.ElementAt(_index); } public int Count() { return _tokensList.Count; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SSOProjectOne.Models { public class UserTotenInput { public string UserCode { get; set; } public string Toten { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ServerMonitor.Lib; using ServerMonitor.Lib.Data; using ServerMonitor.Lib.Network; namespace ServerMonitor.NetworkAccess { public class Monitor : IMonitor { public Monitor() { ServerList = new List<IServer>(); } #region Члены IMonitor public List<IServer> ServerList { get; private set; } public void Add(IServer pServer) { if (pServer.Address != null && pServer.Port != 0) ServerList.Add(pServer); } public void Remove(IServer pServer) { ServerList.Remove(pServer); } public void Refresh() { IWatcher watcher = new Watcher(); foreach (IServer srv in ServerList) { srv.State = ServerState.Updating; watcher.Update(srv); } } #endregion } }
using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using PokuponTestAutomation.Driver; namespace PokuponTestAutomation.Pages { class MainPage : BasePage { private const string BASE_URL = "https://pokupon.by/"; private const string LOGOUT_XPATH = ".//*[@id='b-outer']/div[1]/div/div/div[2]/div/ul/li[1]/ul/li[11]/a"; private const string BALANCE_XPATH = ".//*[@id='b-outer']/div[1]/div/div/div[2]/div/ul/li[1]/ul/li[1]/a"; private const string BONUS_XPATH = ".//*[@id='b-outer']/div[1]/div/div/div[2]/div/ul/li[1]/ul/li[2]/a"; [FindsBy(How = How.XPath, Using = ".//*[@id='b-outer']/div[1]/div/div/div[2]/div/ul/li[1]/a")] private IWebElement userMenu; [FindsBy(How = How.Id, Using = "q")] private IWebElement searchInput; [FindsBy(How = How.XPath, Using = ".//*[@id='search-form']/div[3]/input")] private IWebElement searchButt; public MainPage(IWebDriver driver) : base(driver) { } public void Open() { driver.Navigate().GoToUrl(BASE_URL); } public string GetUserName() { return userMenu.Text; } public void OpenUserMenu() { userMenu.Click(); } public void LogOutClick() { IWebElement logout = driver.FindElement(By.XPath(LOGOUT_XPATH)); logout.Click(); } public void FillSearchInput(string query) { searchInput.SendKeys(query); } public void SearchButtClick() { searchButt.Click(); } public string GetBalance() { IWebElement balance = driver.FindElement(By.XPath(BALANCE_XPATH)); return balance.Text; } public string GetBonus() { IWebElement bonus = driver.FindElement(By.XPath(BONUS_XPATH)); return bonus.Text; } } }
namespace JarvOS { public class Location { public string Address { get; private set; } public float Latitude { get; private set; } public float Longitude { get; private set; } public Location(string address) { Address = address; } public void SetLatitudeAndLongitude(float latitude, float longitude) { Latitude = latitude; Longitude = longitude; } } }
using System; using System.Collections.Generic; using System.Fabric; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Services.Communication.Runtime; using Microsoft.ServiceFabric.Services.Runtime; using Microsoft.ServiceBus.Messaging; using ProvisionApp.Model; using Microsoft.ServiceBus; using System.Text; using Newtonsoft.Json.Linq; using CDSShareLib.Helper; using CDSShareLib.ServiceBus; namespace ProvisionApp { /// <summary> /// An instance of this class is created for each service instance by the Service Fabric runtime. /// </summary> internal sealed class ProvisionApp : StatelessService { public static LogHelper _appLogger = null; public static String _sbConnectionString, _sbProvisionQueue; public static QueueClient _sbQueueClient = null; public static bool _isRunning = false; public static int _incomeMessage, _processedMessage, _failMessage, _ignoreMessage; public ProvisionApp(StatelessServiceContext context) : base(context) { } /// <summary> /// Optional override to create listeners (e.g., TCP, HTTP) for this service replica to handle client or user requests. /// </summary> /// <returns>A collection of listeners.</returns> protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners() { return new ServiceInstanceListener[0]; } /// <summary> /// This is the main entry point for your service instance. /// </summary> /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param> protected override async Task RunAsync(CancellationToken cancellationToken) { // TODO: Replace the following sample code with your own logic // or remove this RunAsync override if it's not needed in your service. /***** Start here *****/ try { InitialProgram(); Heartbeat.Start(); ListenOnServiceBusQueue(); } catch (Exception) { } } void InitialProgram() { try { String logStorageConnectionString = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("SystemStorageConnectionString"); String logStorageContainer = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("ProvisionLogStorageContainerApp"); LogLevel logLevel = (LogLevel)Enum.Parse(typeof(LogLevel), AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("ProvisionLogLevel")); _appLogger = new LogHelper(logStorageConnectionString, logStorageContainer, logLevel); _appLogger.Info("Initial Program Start..."); _sbConnectionString = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("ServiceBusConnectionString"); _sbProvisionQueue = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("ProvisionQueue"); Heartbeat._superadminHeartbeatURL = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("SuperAdminHeartbeatURL"); Heartbeat._sbNameSpaceMgr = NamespaceManager.CreateFromConnectionString(_sbConnectionString); Heartbeat._heartbeatIntervalinSec = int.Parse(AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("ProvisionAppHeartbeatIntervalinSec")); _appLogger.Info("Initial Program Done."); } catch (Exception ex) { Console.WriteLine("Exception on Initial Program. Error:" + ex.Message); } } void ListenOnServiceBusQueue() { /* Create Queue client and listen on message */ _sbQueueClient = QueueClient.CreateFromConnectionString(_sbConnectionString, _sbProvisionQueue); OnMessageOptions options = new OnMessageOptions(); options.MaxConcurrentCalls = 1; options.AutoComplete = false; string messageBody = ""; _isRunning = true; _sbQueueClient.OnMessage((message) => { string task; int taskId = 0; try { // Process message from queue. messageBody = message.GetBody<string>(); _appLogger.Info("Provision Task onMessage: " + messageBody); _incomeMessage++; JObject jsonMessage = JObject.Parse(messageBody); if (jsonMessage["taskId"] == null || jsonMessage["task"] == null) { _appLogger.Warn("Incomplete message:" + messageBody); _ignoreMessage++; message.Complete(); } else { taskId = int.Parse(jsonMessage["taskId"].ToString()); task = jsonMessage["task"].ToString().ToLower(); _appLogger.Info("Received task: " + task); switch (task) { case TaskName.CosmosdbCollection_Create: case TaskName.CosmosdbCollection_Delete: case TaskName.CosmosdbCollection_Update: string CosmosDBConnectionString = jsonMessage["cosmosDBConnectionString"].ToString(); if (String.IsNullOrEmpty(CosmosDBConnectionString)) CosmosDBConnectionString = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("CosmosDBConnectionString"); DocumentDBThread docDB = new DocumentDBThread(CosmosDBConnectionString, jsonMessage, task, taskId); Thread docDBthread = new Thread(new ThreadStart(docDB.ThreadProc)); docDBthread.IsBackground = false; docDBthread.Start(); message.Complete(); break; case TaskName.IoTDevice_Register: case TaskName.IoTDevice_Delete: { string IoTHubConnectionString = jsonMessage["Content"]["IothubConnectionString"].ToString(); if (String.IsNullOrEmpty(IoTHubConnectionString)) { _appLogger.Warn("IoT Hub Connection is NULL."); message.Complete(); } else { IoTHubDeviceRegisterThread iotDeviceRegister = new IoTHubDeviceRegisterThread(IoTHubConnectionString, jsonMessage, task, taskId); Thread iotDeviceRegisterThread = new Thread(new ThreadStart(iotDeviceRegister.ThreadProc)); iotDeviceRegisterThread.IsBackground = false; iotDeviceRegisterThread.Start(); message.Complete(); } } break; case TaskName.IoTHubReceiver_Launch: case TaskName.IoTHubReceiver_Shutdown: message.Complete(); //The following task may take longer, let message complete first IoTHubReceiverThread iotHubReceiver = new IoTHubReceiverThread(messageBody); Thread iotHubReceiverThread = new Thread(new ThreadStart(iotHubReceiver.ThreadProc)); iotHubReceiverThread.IsBackground = false; iotHubReceiverThread.Start(); break; } _processedMessage++; } } catch (Exception ex) { // Indicates a problem, unlock message in subscription. _failMessage++; message.Complete(); StringBuilder logMessage = new StringBuilder(); logMessage.AppendLine("Provision Task Exception: " + ex.Message); logMessage.AppendLine("Provision Task Message: " + messageBody); _appLogger.Error(logMessage); AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel(); operationTask.UpdateTaskByFail(taskId, ex.Message); } }, options); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CHSystem.Models { public class Event : BaseModel { public string Name { get; set; } public int HallID { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public virtual Hall Hall { get; set; } public virtual List<User> Users { get; set; } } }
using System; namespace IMDB.Api.Repositories.Interfaces { public interface IMovieGenreRepository : IGenericRepository<Entities.MovieGenre> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HackerrankSolutionConsole { class strange_advertising : Challenge { public override void Main(string[] args) { int n = Convert.ToInt32(Console.ReadLine()); int totalPeopleLiked = 0; int peopleSharedToday = 5; int peopleLikedToday; for (int i = 0; i < n; i++) { peopleLikedToday = (int)(peopleSharedToday / 2); peopleSharedToday = peopleLikedToday * 3; totalPeopleLiked += peopleLikedToday; } Console.WriteLine(totalPeopleLiked); } public strange_advertising() { Name = "Viral Advertising"; Path = "strange-advertising"; Difficulty = Difficulty.Easy; Domain = Domain.Algorithms; Subdomain = Subdomain.Implementation; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Duello { //inheritance dari class budget public class Expense : Budget { //penerapan liskov substitution berupa class income dan expense dapat digunakan tanpa mengubah behavior budget public string infoExpense = ""; public Expense(string namaBudget, double jumlahUang, string inforExpense) : base(namaBudget, jumlahUang) => infoExpense = inforExpense; public override void LakukanPenjumlahanBudget() { tambahExpense(0, DateTime.Now, ""); } } }
/////////////////////////////////////////////////////////// // OneDimensional.cs // Implementation of the Class OneDimensional // Generated by Enterprise Architect // Created on: 05-???-2018 19:15:47 // Original author: HP /////////////////////////////////////////////////////////// public abstract class OneDimensional : Shape { public OneDimensional(){ } ~OneDimensional(){ } public override void Dispose(){ } }//end OneDimensional
using DataModel; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; namespace WebMarket.api { public class MenuController : ApiController { public LetterMenu Get() { return new LetterMenu(); } } }
using System; using System.Collections.Generic; namespace BankClassLib { public class Bank : IBank { public string BankName { get; } public double Inventory { get; } int accountCounter; List<Account> Accounts; #region Constructor public Bank(string bankName, double inventory) { BankName = bankName; Inventory = inventory; Accounts = new List<Account>(); } #endregion Constructor public int CreateAccount(string name, AccountType type) { switch (type) { // Create a new CheckingAccount and add to accounts list. case AccountType.CheckingAccount: Accounts.Add(new CheckingAccount(++accountCounter, name)); break; // Create a new SavingsAccount and add to accounts list. case AccountType.SavingsAccount: Accounts.Add(new SavingsAccount(++accountCounter, name)); break; // Create a new MoneyMarketAccount and add to accounts list. case AccountType.MoneyMarketAccount: Accounts.Add(new MoneyMarketAccount(++accountCounter, name)); break; // In case if user types anything other than any types of account from AccountType. default: return 0; } return accountCounter; } public double InsertAmount(int accountNumber, double amount) { // Find the specific account from the list by account number. Account foundAccount = Accounts.Find(a => a.AccountNumber == accountNumber); // Add the amount to the account that was found from the list. foundAccount.Balance += amount; // Returns account's balance. return foundAccount.Balance; } public double WithdrawAmount(int accountNumber, double amount) { // Find the specific account from the list by account number. Account foundAccount = Accounts.Find(a => a.AccountNumber == accountNumber); // Withdraw the amount from the account that was found from the list. foundAccount.Balance -= amount; // Returns account's balance. return foundAccount.Balance; } public Account Balance(int accountNumber) { // Find the specific account from the list by account number. Account foundAccount = Accounts.Find(a => a.AccountNumber == accountNumber); // Return the account object. return foundAccount; } public void InterestCalculating() { foreach (Account acc in Accounts) { acc.CalculateInterest(); } } public List<AccountListItem> AccountLookUpList() { List<AccountListItem> accountList = new List<AccountListItem>(); foreach (Account acc in Accounts) { accountList.Add(new AccountListItem { AccountNumber = acc.AccountNumber, Name = acc.Name }); } return accountList; } public List<AccountListItem> GetAccountList() { List<AccountListItem> accountList = new List<AccountListItem>(); foreach (Account acc in Accounts) { accountList.Add(new AccountListItem { AccountNumber = acc.AccountNumber, Name = acc.Name, Balance = acc.Balance, AccountType = acc.AccountType }); } return accountList; } } }
using System.Collections.Generic; public class SplitString { public static string[] Solution(string str) { List<char> list = new List<char>(); List<char> list1 = new List<char>(); List<string> list2 = new List<string>(); string[] strArray; char character = '_'; if(str.Length % 2 == 0){ for(var i = 0; i<str.Length; i++){ list.Add(str[i]); i++; list1.Add(str[i]); } string merge = null; for(int i=0; i<list.Count; i++){ for(int n=i; n<list1.Count; n++){ merge += list[i]; merge+= list1[n]; for(int m=0; m<list1.Count; m++){ list2.Add(merge); merge = null; break; } break; } } return strArray = list2.ToArray(); }else{ str += character; for(var i = 0; i<str.Length; i++){ list.Add(str[i]); i++; list1.Add(str[i]); } string see = null; for(int i=0; i<list.Count; i++){ for(int n=i; n<list1.Count; n++){ see += list[i]; see+= list1[n]; for(int m=0; m<list1.Count; m++){ list2.Add(see); see = null; break; } break; } } return strArray = list2.ToArray(); } return null; } } /* Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). SplitString.Solution("abc"); // should return ["ab", "c_"] SplitString.Solution("abcdef"); // should return ["ab", "cd", "ef"] */ /* ##### BEST PRACTICE if (str.Length % 2 == 1) str += "_"; List<string> list = new List<string>(); for (int i = 0; i < str.Length; i += 2) { list.Add(str[i].ToString() + str[i+1]); } return list.ToArray(); */
using Common; using Models.DAO; using Models.EF; using OnlineShop.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace OnlineShop.Areas.Admin.Controllers { public class UserController : BaseController { // Trang danh sách User [HasCredential(RoleID = "VIEW_USER")] public ActionResult Index(string stringSearch, int page = 1, int pageSize = 4) { var model = new UserDAO().ListAllPaging(stringSearch, page, pageSize); return View(model); } // Trang Thêm Mới User // GET: Admin/User [HttpGet] [HasCredential(RoleID = "ADD_USER")] public ActionResult Create() { SetViewBag(); return View(); } // Action thêm mới User [HttpPost] [HasCredential(RoleID = "ADD_USER")] public ActionResult Create(User user) { if (ModelState.IsValid) { var dao = new UserDAO(); if (dao.CheckUserName(user.UserName)) // Đã Tồn Tại UserName { ModelState.AddModelError("", "UserName Đã Tồn Tại"); } else if (dao.CheckEmail(user.Email)) { ModelState.AddModelError("", "Email Đã Được Đăng Ký"); } else { var userSession = (UserLogin)Session[Common.SessionCommonConstants.USER_SESSION]; user.Password = Encryptor.MD5Hash(user.Password); user.CreateDate = DateTime.Now; user.CreateBy = user.UserName; if (user.GroupID == null) user.GroupID = "MEMBER"; var result = dao.Insert(user); if (result > 0) { SetAlert("Thêm User Thành Công", "success"); // Hàm kế thừa từ BaseController return RedirectToAction("Index", "User"); } else { ModelState.AddModelError("", "Thêm Thất Bại"); } } } SetViewBag(); return View(user); } // public void SetViewBag(string selectedId = null) { var dao = new UserGroupDAO(); ViewBag.GroupID = new SelectList(dao.ListAll(), "ID", "Name", selectedId); } // Action trả về View Update [HasCredential(RoleID = "EDIT_USER")] public ActionResult Edit(long id) { var model = new UserDAO().GetByID(id); SetViewBag(model.GroupID); return View(model); } // Action Update [HttpPost] [HasCredential(RoleID = "EDIT_USER")] public ActionResult Edit(User user) { if (ModelState.IsValid) { var userSession = (UserLogin)Session[SessionCommonConstants.USER_SESSION]; if (!string.IsNullOrEmpty(user.Password)) { User model = new UserDAO().GetByID(user.ID); user.Password = Encryptor.MD5Hash(model.Password); } user.ModifiedBy = userSession.UserName; user.ModifiedDate = DateTime.Now; var result = new UserDAO().Update(user); if (result) { SetAlert("Edit User Thành Công", "success"); return RedirectToAction("Index", "User"); } else { ModelState.AddModelError("", "Cập Nhật Thất Bại"); } } SetViewBag(); return View("Edit"); } // Action Delete [HttpDelete] [HasCredential(RoleID = "DELETE_USER")] public ActionResult Delete(long id) { var result = new UserDAO().Delete(id); if (result) { SetAlert("Xóa User Thành Công", "success"); return RedirectToAction("Index"); } else { ModelState.AddModelError("", "Xóa Thất Bại"); } return View("Index"); } // Thay đổi trạng thái hoạt động của user [HttpPost] [HasCredential(RoleID = "EDIT_USER")] public JsonResult ChangeStatus(long id) { var result = new UserDAO().ChangeStatus(id); return Json(new { status = result }); } } }
using System; using System.Collections.Generic; using UnityEngine; public class Ctrl : MonoBehaviour { [HideInInspector] public Model Model => FindObjectOfType<Model>(); [HideInInspector] public View View => FindObjectOfType<View>(); [HideInInspector] public AudioManager audioManager; [HideInInspector] public AudioSource audioSource; [HideInInspector] public PlayerControl player; [HideInInspector] public int loseHearts = 0; [HideInInspector] public event Action OnPlayerBeHurt_UI; [HideInInspector] public event Action OnPlayerPassLevel; [HideInInspector] public event Action OnPlayerBeDead; private UIManager UIManager => FindObjectOfType<GameRoot>().UIManager; private List<Enemy> enemies = new List<Enemy>(); private List<Coin> coins = new List<Coin>(); private void Awake() { audioManager = GetComponent<AudioManager>(); audioSource = GetComponent<AudioSource>(); Enemy[] emys = GetComponentsInChildren<Enemy>(); Coin[] cons = GetComponentsInChildren<Coin>(); enemies.CopyFrom(emys); coins.CopyFrom(cons); OnPlayerPassLevel += View.OnPlayerPassLevel; OnPlayerBeDead += View.OnPlayerBeDead; Transform PlayerTrans = transform.Find("PlayerTrans"); foreach (var item in GameRecord.PlayerPrefabPathList) { GameObject playerPrefab = Resources.Load(item) as GameObject; if (playerPrefab == null) Debug.LogFormat("Can't find the prefab in the path of {0}", item); if (playerPrefab.GetComponent<PlayerControl>().playerInfo.isSelect) { player = Instantiate(playerPrefab, PlayerTrans.position, Quaternion.identity, transform).GetComponent<PlayerControl>(); } if (player == null) Debug.Log("This player is null,don't select!"); } } private void Update() { loseHearts = player.playerInfo.maxHP - player.HP; Enemy deadEnemy = null; Coin deadReward = null; //通关,保存记录 if (player.isPassLevel) { if (!UIManager.CheckPanelExist(UIPanelInfo.PanelType.EndingPanel)) { OnPlayerPassLevel(); Model.SaveScore(); audioManager.Play(audioManager.passLevel, player.audioSource); } } //死亡 if (player.isDead) { if (!UIManager.CheckPanelExist(UIPanelInfo.PanelType.EndingPanel)) { OnPlayerBeDead(); foreach (var item in enemies) item.enabled = false; } } else { #region check dead enemy and hurt player foreach (var enemy in enemies) { deadEnemy = enemy.CheckDeadEnemy(); if (enemy.CheckPlayBeHurt(player)) { OnPlayerBeHurt_UI?.Invoke(); } if (deadEnemy != null) { break; } } if (deadEnemy != null) { Model.GetScore(deadEnemy.tag); deadEnemy.OnEnemyDead(); enemies.Remove(deadEnemy); } #endregion #region check reward foreach (var coin in coins) { if (coin.checkCoin) { deadReward = coin; if (deadReward != null) { break; } } } if (deadReward != null) { audioManager.Play(audioManager.commonCoin, deadReward.GetComponent<AudioSource>()); Model.GetScore(deadReward.tag); deadReward.OnGetCoins(); coins.Remove(deadReward); } #endregion } } }
// Contains types that are common among RF Toolkits and Modular Instruments wrappers. using System; using System.Runtime.InteropServices; namespace NationalInstruments.ModularInstruments.Interop { [StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 8)] public struct NiComplexNumber { public double Real; public double Imaginary; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Doppler { public class DopplerListener : MonoBehaviour { private Vector3 prevPosition; private Vector3 position; private float moveDist; private float speed; private void Start() { prevPosition = transform.position; position = prevPosition; DopplerEmitter.AddListener(this); } private void Update() { moveDist = (prevPosition - transform.position).magnitude; speed = moveDist / Time.deltaTime; UpdatePosition(); } public void UpdatePosition() { prevPosition = position; position = transform.position; } public Vector3 GetPosition() { return position; } public Vector3 GetPrevPosition() { return prevPosition; } } }
using System; using System.IO; using System.Threading.Tasks; using System.Xml; using System.Xml.Schema; using System.Xml.Xsl; namespace TransformerXML { public class Transformer { public string InputXML { get; set; } public string InputXSD { get; set; } public string OutputXML { get; set; } public string OutputXSD { get; set; } public string TemplateXSL { get; set; } public async void TransformAsync() { if (!(await Task.Run(() => ValidateSchema(InputXSD, InputXML)))) return; if (!(await Task.Run(() => TransformFile(TemplateXSL, InputXML, OutputXML)))) return; if (!(await Task.Run(() => ValidateSchema(OutputXSD, OutputXML)))) return; } private bool TransformFile(string xsl, string input, string output) { if (!File.Exists(xsl)) { Console.WriteLine("WARNING: TransformFile. File {0} does not exist!", xsl); return false; } try { XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(xsl); xslt.Transform(input, output); Console.WriteLine("OK: TransformFile"); return true; } catch (Exception ex) { Console.WriteLine("ERROR: TransformFile. " + ex.Message); return false; } } private bool ValidateSchema(string xsd, string xml) { if (!File.Exists(xsd)) { Console.WriteLine("WARNING: ValidateSchema. File {0} does not exist!", xsd); return false; } if (!File.Exists(xml)) { Console.WriteLine("WARNING: ValidateSchema. File {0} does not exist!", xml); return false; } try { XmlReaderSettings settings = new XmlReaderSettings(); settings.Schemas.Add(null, xsd); settings.ValidationType = ValidationType.Schema; settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler); XmlReader reader = XmlReader.Create(xml, settings); XmlDocument document = new XmlDocument(); document.Load(reader); Console.WriteLine("OK: ValidateSchema {0}", xsd); return true; } catch (Exception ex) { Console.WriteLine("ERROR: ValidateSchema {0}, {1}. ", xsd, ex.Message); return false; } } private void ValidationEventHandler(object sender, ValidationEventArgs e) { if (e.Severity == XmlSeverityType.Warning) { Console.WriteLine("WARNING: ValidationEventHandler. " + e.Message); } else if (e.Severity == XmlSeverityType.Error) { Console.WriteLine("ERROR: ValidationEventHandler. " + e.Message); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ArmadaEngine.TileMaps; using ArmadaEngine.Helpers; using Microsoft.Xna.Framework.Input; namespace ArmadaEngine.Scenes.TestScenes { class tmTestScene : Scenes.Scene { TilemapManager _MapManager; List<Tile> path; Tile TileOne; Tile TileTwo; Texture2D rectTex; Rectangle tileRect; bool diagonalPaths = false; public tmTestScene(Microsoft.Xna.Framework.Content.ContentManager c, Scenes.SceneManager sm, Camera.ArmadaCamera ca) : base(c, sm, ca) { _Name = "TmTest"; } public override void LoadContent() { base.LoadContent(); _MapManager = new TilemapManager(); _MapManager.LoadMap("ProtoLevel", _Content); rectTex = _Content.Load<Texture2D>(@"Art/edgeTex"); } public override void UnloadContent() { base.UnloadContent(); _MapManager = null; path = null; TileOne = null; TileTwo = null; rectTex = null; tileRect = Rectangle.Empty; } public override void Update(GameTime gt) { base.Update(gt); if (Helpers.InputHelper.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.Space)) { _SM.ActivateScene("Mega"); return; } Tile hoveredTile = _MapManager.findTile(InputHelper.MouseScreenPos); if (InputHelper.IsKeyPressed(Keys.D1)) { TileOne = hoveredTile; if (TileOne != null && TileTwo != null) { _MapManager.ResetTileColors(); path = _MapManager.AStarTwo(TileOne, TileTwo, diagonalPaths); } } if (InputHelper.IsKeyPressed(Keys.D2)) { TileTwo = hoveredTile; if (TileOne != null && TileTwo != null) { _MapManager.ResetTileColors(); path = _MapManager.AStarTwo(TileOne, TileTwo, diagonalPaths); } } if (InputHelper.IsKeyPressed(Keys.T)) { diagonalPaths = !diagonalPaths; if (TileOne != null && TileTwo != null) { _MapManager.ResetTileColors(); path = _MapManager.AStarTwo(TileOne, TileTwo, diagonalPaths); } } if (InputHelper.IsKeyPressed(Keys.O)) { TileOne = null; TileTwo = null; path = null; } } public override void Draw(SpriteBatch sb, Rectangle bounds) { base.Draw(sb, bounds); // TODO: Add your drawing code here _MapManager.Draw(sb, bounds); //if(hoveredTile != null) //{ // spriteBatch.Draw(rectTex, hoveredTile.destRect, Color.White); //} if (TileOne != null) { sb.Draw(rectTex, TileOne.destRect, Color.White); } if (TileTwo != null) { sb.Draw(rectTex, TileTwo.destRect, Color.Blue); } if (TileOne != null && TileTwo != null) { Tile prevTile = TileOne; if (path != null) { foreach (Tile t in path) { DrawLine(sb, prevTile.tileCenter, t.tileCenter); prevTile = t; } } } } void DrawLine(SpriteBatch sb, Vector2 start, Vector2 end) { Vector2 edge = end - start; // calculate angle to rotate line float angle = (float)Math.Atan2(edge.Y, edge.X); sb.Draw(rectTex, new Rectangle(// rectangle defines shape of line and position of start of line (int)start.X, (int)start.Y, (int)edge.Length(), //sb will strech the texture to fill this rectangle 1), //width of line, change this to make thicker line null, Color.Red, //colour of line angle, //angle of line (calulated above) new Vector2(0, 0), // point in line about which to rotate SpriteEffects.None, 0); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TelemetryBsonSerializationConfiguration.cs" company="Naos Project"> // Copyright (c) Naos Project 2019. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Telemetry.Serialization.Bson { using System; using System.Collections.Generic; using Naos.Diagnostics.Serialization.Bson; using Naos.Telemetry.Domain; using OBeautifulCode.Serialization.Bson; /// <summary> /// Implementation for the <see cref="Telemetry" /> domain. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Telemetry", Justification = "Spelling/name is correct.")] public class TelemetryBsonSerializationConfiguration : BsonSerializationConfigurationBase { /// <inheritdoc /> protected override IReadOnlyCollection<string> TypeToRegisterNamespacePrefixFilters => new[] { typeof(DiagnosticsTelemetry).Namespace, }; /// <inheritdoc /> protected override IReadOnlyCollection<BsonSerializationConfigurationType> DependentBsonSerializationConfigurationTypes => new[] { typeof(DiagnosticsBsonSerializationConfiguration).ToBsonSerializationConfigurationType(), }; /// <inheritdoc /> protected override IReadOnlyCollection<TypeToRegisterForBson> TypesToRegisterForBson => new[] { typeof(DiagnosticsTelemetry).ToTypeToRegisterForBson(), typeof(EventTelemetry).ToTypeToRegisterForBson(), typeof(StopwatchSnapshot).ToTypeToRegisterForBson(), }; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ServiceModel; using DataBase; namespace Contract { /// <summary> /// An interface with abstract methods /// </summary> [ServiceContract] public interface IContract { /// <summary> /// An abstract method for getting all user information /// </summary> /// <returns></returns> [OperationContract] string GetAll(); /// <summary> /// An abstract method for getting a user information /// </summary> /// <param name="a"></param> /// <returns></returns> [OperationContract] string GetOne(string a); /// <summary> /// An abstract method for a user adding /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> [OperationContract] string AddUser(string a, string b); /// <summary> /// An abstract method for a user removing /// </summary> /// <param name="a"></param> /// <returns></returns> [OperationContract] string DelUser(string a); /// <summary> /// An abstract method for a user updating /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="c"></param> /// <returns></returns> [OperationContract] string PutUser(string a, string b, string c); } class Contract { static void Main(string[] args) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; using Xceed.Wpf.Toolkit; using System.Windows; class Validator_cpf_cnpj { public void alertaCPFInvalido() { //Insira CPF //var tx_NumeroCPF = "766.096.040-70"; //CPF valido var tx_NumeroCPF = "123.096.040-70"; //CPF invalido //Mensagem de Alerta var alertaCpfInvalido = "CPF fornecido é inválido"; if (ValidadorCPF(tx_NumeroCPF) is false) { Console.WriteLine(tx_NumeroCPF + " - CPF invalido"); Console.WriteLine(alertaCpfInvalido); MessageBoxResult result = System.Windows.MessageBox.Show(alertaCpfInvalido, "Alerta", MessageBoxButton.YesNo); Console.ReadKey(); } else { Console.WriteLine(tx_NumeroCPF + " CPF é valido"); Console.ReadKey(); } } public void alertaCnpjInvalido() { //Insira CNPJ var tx_NumeroCNPJ = "01.928.374/6501-92"; //cnpj invalido para teste //var tx_NumeroCNPJ = "21.422.050/0001-37"; //cnpj valido //Mensagem de Alerta var alertaCnpjInvalido = "CNPJ fornecido é inválido"; if (ValidadorCnpj(tx_NumeroCNPJ) is false) { Console.WriteLine(tx_NumeroCNPJ + " - CNPJ invalido"); Console.WriteLine(alertaCnpjInvalido); MessageBoxResult result = System.Windows.MessageBox.Show(alertaCnpjInvalido, "Alerta", MessageBoxButton.YesNo); Console.ReadKey(); } else { Console.WriteLine(tx_NumeroCNPJ + " CNPJ é valido"); Console.ReadKey(); } } //Validador CPF public static bool ValidadorCPF(string cpf) { int[] multiplicador1 = new int[9] { 10, 9, 8, 7, 6, 5, 4, 3, 2 }; int[] multiplicador2 = new int[10] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 }; string cpfSemDigito; string digito; int soma; int resto; cpf = cpf.Trim(); cpf = cpf.Replace(".", "").Replace("-", ""); if (cpf.Length != 11) return false; cpfSemDigito = cpf.Substring(0, 9); soma = 0; for (int i = 0; i < 9; i++) soma += int.Parse(cpfSemDigito[i].ToString()) * multiplicador1[i]; resto = soma % 11; if (resto < 2) resto = 0; else resto = 11 - resto; digito = resto.ToString(); cpfSemDigito = cpfSemDigito + digito; soma = 0; for (int i = 0; i < 10; i++) soma += int.Parse(cpfSemDigito[i].ToString()) * multiplicador2[i]; resto = soma % 11; if (resto < 2) resto = 0; else resto = 11 - resto; digito = digito + resto.ToString(); return cpf.EndsWith(digito); } //Validador CNPJ public static bool ValidadorCnpj(string cnpj) { int[] multiplicador1 = new int[12] { 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 }; int[] multiplicador2 = new int[13] { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 }; int soma; int resto; string digito; string tempCnpj; cnpj = cnpj.Trim(); cnpj = cnpj.Replace(".", "").Replace("-", "").Replace("/", ""); if (cnpj.Length != 14) return false; tempCnpj = cnpj.Substring(0, 12); soma = 0; for (int i = 0; i < 12; i++) soma += int.Parse(tempCnpj[i].ToString()) * multiplicador1[i]; resto = (soma % 11); if (resto < 2) resto = 0; else resto = 11 - resto; digito = resto.ToString(); tempCnpj = tempCnpj + digito; soma = 0; for (int i = 0; i < 13; i++) soma += int.Parse(tempCnpj[i].ToString()) * multiplicador2[i]; resto = (soma % 11); if (resto < 2) resto = 0; else resto = 11 - resto; digito = digito + resto.ToString(); return cnpj.EndsWith(digito); } }
namespace LearningSignalR.Db { public enum DbRepositoryResultStatus { Success, Error, NotFound, Created, Updated, Deleted, NotAuthorized, InvalidToken, TokenExpired, Unknown, } }
namespace Unosquare.WaveShare.FingerprintModule { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using SerialPort; /// <summary> /// Our main character representing the WaveShare Fingerprint reader module. /// /// Reference: http://www.waveshare.com/w/upload/6/65/UART-Fingerprint-Reader-UserManual.pdf /// WIKI: http://www.waveshare.com/wiki/UART_Fingerprint_Reader. /// </summary> /// <seealso cref="IDisposable" /> public sealed class FingerprintReader : IDisposable { /// <summary> /// The read buffer length of the serial port. /// </summary> private const int ReadBufferLength = 1024 * 16; private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(2); private static readonly TimeSpan BaudRateProbeTimeout = TimeSpan.FromMilliseconds(250); private static readonly TimeSpan AcquireTimeout = TimeSpan.MaxValue; private static readonly ManualResetEventSlim SerialPortDone = new ManualResetEventSlim(true); private bool _disposedValue; // To detect redundant calls /// <summary> /// Gets the serial port associated with this reader. /// </summary> public ISerialPort SerialPort { get; private set; } #region Open and Close Methods /// <summary> /// Gets an array of serial port names for the current computer. /// /// This method is just a shortcut for Microsoft and RJCP libraries, /// you may use your SerialPort library to enumerate the available ports. /// </summary> /// <returns>An array of serial port names for the current computer.</returns> public static string[] GetPortNames() => #if NET461 MsSerialPort.GetPortNames(); #else RjcpSerialPort.GetPortNames(); #endif /// <summary> /// Opens the serial port with the specified port name. /// Under Windows it's something like COM3. On Linux, it's something like /dev/ttyS0. /// </summary> /// <param name="portName">Name of the port.</param> /// <param name="baudRate">The baud rate.</param> /// <param name="probeBaudRates">if set to <c>true</c> [probe baud rates].</param> /// <param name="ct">An instance of <see cref="CancellationToken"/>.</param> /// <exception cref="System.InvalidOperationException">Device is already open. Call the Close method first.</exception> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task OpenAsync(string portName, BaudRate baudRate, bool probeBaudRates, CancellationToken ct = default) { if (SerialPort != null) throw new InvalidOperationException("Device is already open. Call the Close method first."); SerialPort = #if NET461 new MsSerialPort(portName, baudRate.ToInt()) #else new RjcpSerialPort(portName, baudRate.ToInt()) #endif { ReadBufferSize = ReadBufferLength, }; SerialPort.Open(); await Task.Delay(100, ct); if (probeBaudRates) { System.Diagnostics.Debug.WriteLine("Will probe baud rates."); await GetBaudRate(ct); } } /// <summary> /// Opens the serial port with the specified port name. /// Under Windows it's something like COM3. On Linux, it's something like /dev/ttyS0. /// </summary> /// <param name="portName">Name of the port.</param> /// <param name="ct">An instance of <see cref="CancellationToken"/>.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public Task OpenAsync(string portName, CancellationToken ct = default) => OpenAsync(portName, BaudRate.Baud19200, true, ct); /// <summary> /// Closes serial port communication if open. /// </summary> private void Close() { if (SerialPort == null) return; try { if (SerialPort.IsOpen) SerialPort.Close(); } finally { SerialPort.Dispose(); SerialPort = null; } } /// <inheritdoc /> public void Dispose() => Dispose(true); /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"> /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> private void Dispose(bool disposing) { if (_disposedValue) return; if (disposing) Close(); _disposedValue = true; } #endregion #region Fingerprint Reader Protocol /// <summary> /// Gets the version number of the DSP module. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous get DSP version number operation. /// The result of the task contains an instance of <see cref="GetDspVersionNumberResponse"/>. /// </returns> public Task<GetDspVersionNumberResponse> GetDspVersionNumber(CancellationToken ct = default) => GetResponseAsync<GetDspVersionNumberResponse>(Command.Factory.CreateGetDspVersionNumberCommand(), ct); /// <summary> /// Makes the module go to sleep and stop processing commands. The only way to bring it back /// online is by resetting it. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous sleep operation. /// The result of the task contains an instance of <see cref="Response"/>. /// </returns> public Task<Response> Sleep(CancellationToken ct = default) => GetResponseAsync<Response>(Command.Factory.CreateSleepCommand(), ct); /// <summary> /// Gets the baud rate. /// This method probes the serial port at different baud rates until communication is correctly established. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous get baud rate operation. /// The result of the task contains an instance of <see cref="GetSetBaudRateResponse"/>. /// </returns> public async Task<GetSetBaudRateResponse> GetBaudRate(CancellationToken ct = default) { if (SerialPort.IsOpen == false) { throw new InvalidOperationException( $"Call the {nameof(OpenAsync)} method before attempting communication with the module"); } var portName = SerialPort.PortName; var baudRates = Enum.GetValues(typeof(BaudRate)).Cast<BaudRate>().ToArray(); var result = new GetSetBaudRateResponse( Command.CreateFixedLengthPayload(OperationCode.ChangeBaudRate, 0, 0, (byte)SerialPort.BaudRate.ToBaudRate())); var probeCommand = Command.Factory.CreateGetUserCountCommand(); var probeResponse = await GetResponseAsync<GetUserCountResponse>(probeCommand, BaudRateProbeTimeout, ct); if (probeResponse != null) return result; foreach (var baudRate in baudRates) { Close(); await OpenAsync(portName, baudRate, false, ct); probeResponse = await GetResponseAsync<GetUserCountResponse>(probeCommand, BaudRateProbeTimeout, ct); if (probeResponse != null) { var baudRateResponse = new GetSetBaudRateResponse( Command.CreateFixedLengthPayload(OperationCode.ChangeBaudRate, 0, 0, (byte)baudRate)); System.Diagnostics.Debug.WriteLine($"RX: {baudRateResponse}"); return baudRateResponse; } } return null; } /// <summary> /// Sets the baud rate of the module. /// This closes and re-opens the serial port. /// </summary> /// <param name="baudRate">The baud rate.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous set baud rate operation. /// The result of the task contains an instance of <see cref="GetSetBaudRateResponse"/>. /// </returns> public async Task<GetSetBaudRateResponse> SetBaudRate(BaudRate baudRate, CancellationToken ct = default) { var currentBaudRate = await GetBaudRate(ct); if (currentBaudRate.BaudRate == baudRate) { return new GetSetBaudRateResponse( Command.CreateFixedLengthPayload(OperationCode.ChangeBaudRate, 0, 0, (byte) baudRate)); } var response = await GetResponseAsync<GetSetBaudRateResponse>(Command.Factory.CreateChangeBaudRateCommand(baudRate), ct); if (response != null) { var portName = SerialPort.PortName; Close(); await OpenAsync(portName, baudRate, false, ct); } return response; } /// <summary> /// Gets the registration mode which specifies if a fingerprint can be registered more than once. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous get registration mode operation. /// The result of the task contains an instance of <see cref="GetSetRegistrationModeResponse"/>. /// </returns> public Task<GetSetRegistrationModeResponse> GetRegistrationMode(CancellationToken ct = default) => GetResponseAsync<GetSetRegistrationModeResponse>( Command.Factory.CreateGetSetRegistrationModeCommand(GetSetMode.Get, false), ct); /// <summary> /// Sets the registration mode. Prohibit repeat disallows registration of the same fingerprint for more than 1 user. /// </summary> /// <param name="prohibitRepeat">if set to <c>true</c> [prohibit repeat].</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous set registration mode operation. /// The result of the task contains an instance of <see cref="GetSetRegistrationModeResponse"/>. /// </returns> public Task<GetSetRegistrationModeResponse> SetRegistrationMode(bool prohibitRepeat, CancellationToken ct = default) => GetResponseAsync<GetSetRegistrationModeResponse>( Command.Factory.CreateGetSetRegistrationModeCommand(GetSetMode.Set, prohibitRepeat), ct); /// <summary> /// Registers a fingerprint. You have to call this method 3 times specifying the corresponding iteration 1, 2, or 3. /// </summary> /// <param name="iteration">The iteration.</param> /// <param name="userId">The user identifier.</param> /// <param name="userPrivilege">The user privilege.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous add fingerprint operation. /// The result of the task contains an instance of <see cref="AddFingerprintResponse"/>. /// </returns> /// <exception cref="System.ArgumentException"> /// iteration /// or /// userId /// or /// userPrivilege. /// </exception> public Task<AddFingerprintResponse> AddFingerprint(int iteration, int userId, int userPrivilege, CancellationToken ct = default) { if (iteration < 0 || iteration > 3) throw new ArgumentException($"{nameof(iteration)} must be a number between 1 and 3"); if (userId < 1 || userId > 4095) throw new ArgumentException($"{nameof(userId)} must be a number between 1 and 4095"); if (userPrivilege < 0 || userPrivilege > 3) throw new ArgumentException($"{nameof(userPrivilege)} must be a number between 1 and 3"); var command = Command.Factory.CreateAddFingerprintCommand( Convert.ToByte(iteration), Convert.ToUInt16(userId), Convert.ToByte(userPrivilege)); return GetResponseAsync<AddFingerprintResponse>(command, AcquireTimeout, ct); } /// <summary> /// Deletes the specified user. /// </summary> /// <param name="userId">The user identifier.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous delete user operation. /// The result of the task contains an instance of <see cref="Response"/>. /// </returns> public Task<Response> DeleteUser(int userId, CancellationToken ct = default) => GetResponseAsync<Response>(Command.Factory.CreateDeleteUserCommand(Convert.ToUInt16(userId)), ct); /// <summary> /// Deletes all users. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous delete all users operation. /// The result of the task contains an instance of <see cref="Response"/>. /// </returns> public Task<Response> DeleteAllUsers(CancellationToken ct = default) => GetResponseAsync<Response>(Command.Factory.CreateDeleteAllUsersCommand(), AcquireTimeout, ct); /// <summary> /// Gets the user count. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous get user count operation. /// The result of the task contains an instance of <see cref="GetUserCountResponse"/>. /// </returns> public Task<GetUserCountResponse> GetUserCount(CancellationToken ct = default) => GetResponseAsync<GetUserCountResponse>(Command.Factory.CreateGetUserCountCommand(), ct); /// <summary> /// Returns a User id after acquiring an image from the sensor. Match 1:N. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous match one to n operation. /// The result of the task contains an instance of <see cref="MatchOneToNResponse"/>. /// </returns> public Task<MatchOneToNResponse> MatchOneToN(CancellationToken ct = default) => GetResponseAsync<MatchOneToNResponse>(Command.Factory.CreateMatchOneToNCommand(), AcquireTimeout, ct); /// <summary> /// Acquires an image from the sensor and tests if it matches the supplied user id. Match 1:1. /// </summary> /// <param name="userId">The user identifier.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous match one to one operation. /// The result of the task contains an instance of <see cref="Response"/>. /// </returns> public Task<Response> MatchOneToOne(int userId, CancellationToken ct = default) => GetResponseAsync<Response>(Command.Factory.CreateMatchOneToOneCommand(Convert.ToUInt16(userId)), AcquireTimeout, ct); /// <summary> /// Gets the user privilege given its id. /// </summary> /// <param name="userId">The user identifier.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous get user privilege operation. /// The result of the task contains an instance of <see cref="GetUserPrivilegeResponse"/>. /// </returns> public Task<GetUserPrivilegeResponse> GetUserPrivilege(int userId, CancellationToken ct = default) => GetResponseAsync<GetUserPrivilegeResponse>(Command.Factory.CreateGetUserPrivilegeCommand(Convert.ToUInt16(userId)), ct); /// <summary> /// Gets the matching level. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous get matching level operation. /// The result of the task contains an instance of <see cref="GetSetMatchingLevelResponse"/>. /// </returns> public Task<GetSetMatchingLevelResponse> GetMatchingLevel(CancellationToken ct = default) => GetResponseAsync<GetSetMatchingLevelResponse>(Command.Factory.CreateGetSetMatchingLevelCommand(GetSetMode.Get, 0), ct); /// <summary> /// Sets the matching level. 0 is the loosest, 9 is the strictest. /// </summary> /// <param name="matchingLevel">The matching level.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous set matching level operation. /// The result of the task contains an instance of <see cref="GetSetMatchingLevelResponse"/>. /// </returns> public Task<GetSetMatchingLevelResponse> SetMatchingLevel(int matchingLevel, CancellationToken ct = default) => GetResponseAsync<GetSetMatchingLevelResponse>(Command.Factory.CreateGetSetMatchingLevelCommand(GetSetMode.Set, Convert.ToByte(matchingLevel)), ct); /// <summary> /// Acquires an image from the sensor and returns the image bytes in grayscale nibbles. This operation is fairly slow. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous adquire image operation. /// The result of the task contains an instance of <see cref="AcquireImageResponse"/>. /// </returns> public Task<AcquireImageResponse> AcquireImage(CancellationToken ct = default) => GetResponseAsync<AcquireImageResponse>(Command.Factory.CreateAcquireImageCommand(), AcquireTimeout, ct); /// <summary> /// Acquires an image from the sensor and returns the computed eigenvalues. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous adquire image eigenvalues operation. /// The result of the task contains an instance of <see cref="AcquireImageEigenvaluesResponse"/>. /// </returns> public Task<AcquireImageEigenvaluesResponse> AcquireImageEigenvalues(CancellationToken ct = default) => GetResponseAsync<AcquireImageEigenvaluesResponse>(Command.Factory.CreateAcquireImageEigenvaluesCommand(), AcquireTimeout, ct); /// <summary> /// Acquires an image from the sensor and determines if the supplied eigenvalues match. Match 1:1. /// </summary> /// <param name="eigenvalues">The eigenvalues.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous match image to eigenvalues operation. /// The result of the task contains an instance of <see cref="Response"/>. /// </returns> public Task<Response> MatchImageToEigenvalues(byte[] eigenvalues, CancellationToken ct = default) => GetResponseAsync<Response>(Command.Factory.CreateMatchImageToEigenvaluesCommand(eigenvalues), AcquireTimeout, ct); /// <summary> /// Provides a method to test if the given user id matches the specified eigenvalues. Match 1:1. /// </summary> /// <param name="userId">The user identifier.</param> /// <param name="eigenvalues">The eigenvalues.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous match user to eigenvalues operation. /// The result of the task contains an instance of <see cref="Response"/>. /// </returns> public Task<Response> MatchUserToEigenvalues(int userId, byte[] eigenvalues, CancellationToken ct = default) => GetResponseAsync<Response>(Command.Factory.CreateMatchUserToEigenvaluesCommand(Convert.ToUInt16(userId), eigenvalues), ct); /// <summary> /// Finds a user id for the given eigenvalues. Match 1:N. /// </summary> /// <param name="eigenvalues">The eigenvalues.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous match eigenvalues to user operation. /// The result of the task contains an instance of <see cref="MatchEigenvaluesToUserResponse"/>. /// </returns> public Task<MatchEigenvaluesToUserResponse> MatchEigenvaluesToUser(byte[] eigenvalues, CancellationToken ct = default) => GetResponseAsync<MatchEigenvaluesToUserResponse>(Command.Factory.CreateMatchEigenvaluesToUserCommand(eigenvalues), ct); /// <summary> /// Gets a user's privilege and eigenvalues. /// </summary> /// <param name="userId">The user identifier.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous get user properties operation. /// The result of the task contains an instance of <see cref="GetUserPropertiesResponse"/>. /// </returns> public Task<GetUserPropertiesResponse> GetUserProperties(int userId, CancellationToken ct = default) => GetResponseAsync<GetUserPropertiesResponse>(Command.Factory.CreateGetUserPropertiesCommand(Convert.ToUInt16(userId)), ct); /// <summary> /// Sets or overwrites a specified user with the given privilege and eigenvalues. /// </summary> /// <param name="userId">The user identifier.</param> /// <param name="privilege">The privilege.</param> /// <param name="eigenvalues">The eigenvalues.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous set user properties operation. /// The result of the task contains an instance of <see cref="SetUserPropertiesResponse"/>. /// </returns> public Task<SetUserPropertiesResponse> SetUserProperties(int userId, int privilege, byte[] eigenvalues, CancellationToken ct = default) => GetResponseAsync<SetUserPropertiesResponse>(Command.Factory.CreateSetUserPropertiesCommand( Convert.ToUInt16(userId), Convert.ToByte(privilege), eigenvalues), ct); /// <summary> /// Gets the capture timeout. Timeout is between 0 to 255. 0 denotes to wait indefinitely for a capture. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous get capture timeout operation. /// The result of the task contains an instance of <see cref="GetSetCaptureTimeoutResponse"/>. /// </returns> public Task<GetSetCaptureTimeoutResponse> GetCaptureTimeout(CancellationToken ct = default) => GetResponseAsync<GetSetCaptureTimeoutResponse>(Command.Factory.CreateGetSetCaptureTimeoutCommand(GetSetMode.Get, 0), ct); /// <summary> /// Sets the capture timeout. Timeout must be 0 to 255. 0 denotes to wait indefinitely for a capture. /// </summary> /// <param name="timeout">The timeout.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous set capture timeout operation. /// The result of the task contains an instance of <see cref="GetSetCaptureTimeoutResponse"/>. /// </returns> public Task<GetSetCaptureTimeoutResponse> SetCaptureTimeout(int timeout, CancellationToken ct = default) => GetResponseAsync<GetSetCaptureTimeoutResponse>(Command.Factory.CreateGetSetCaptureTimeoutCommand(GetSetMode.Set, Convert.ToByte(timeout)), ct); /// <summary> /// Gets all users and their permissions. It does not retrieve User eigenvalues. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous get all users operation. /// The result of the task contains an instance of <see cref="GetAllUsersResponse"/>. /// </returns> public Task<GetAllUsersResponse> GetAllUsers(CancellationToken ct = default) => GetResponseAsync<GetAllUsersResponse>(Command.Factory.CreateGetAllUsersCommand(), ct); #endregion #region Read and Write Methods /// <summary> /// Gets a response with the default timeout. /// </summary> /// <typeparam name="T">A final response type.</typeparam> /// <param name="command">The command.</param> /// <param name="ct">An instance of <see cref="CancellationToken"/>.</param> /// <returns>A task that represents the asynchronous get response operation. /// The result of the task contains an instance of a response type T. /// </returns> private Task<T> GetResponseAsync<T>(Command command, CancellationToken ct) where T : ResponseBase => GetResponseAsync<T>(command, DefaultTimeout, ct); /// <summary> /// Given a command, gets a response object asynchronously. /// </summary> /// <typeparam name="T">A final response type.</typeparam> /// <param name="command">The command.</param> /// <param name="responseTimeout">The response timeout.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous get response operation. /// The result of the task contains an instance of a response type T. /// </returns> /// <exception cref="System.InvalidOperationException">Open.</exception> private async Task<T> GetResponseAsync<T>(Command command, TimeSpan responseTimeout, CancellationToken ct) where T : ResponseBase { if (SerialPort == null || SerialPort.IsOpen == false) throw new InvalidOperationException($"Call the {nameof(OpenAsync)} method before attempting communication"); var startTime = DateTime.UtcNow; var discardedBytes = await FlushReadBufferAsync(ct); #if DEBUG if (discardedBytes.Length > 0) { System.Diagnostics.Debug.WriteLine( $"RX: Discarded {discardedBytes.Length} bytes: {BitConverter.ToString(discardedBytes).Replace("-", " ")}"); } #endif await WriteAsync(command.Payload, ct); System.Diagnostics.Debug.WriteLine($"TX: {command}"); var responseBytes = await ReadAsync(responseTimeout, ct); if (responseBytes == null || responseBytes.Length <= 0) { System.Diagnostics.Debug.WriteLine( $"RX: No response received after {responseTimeout.TotalMilliseconds} ms"); return null; } var response = Activator.CreateInstance(typeof(T), responseBytes) as T; System.Diagnostics.Debug.WriteLine($"RX: {response}"); System.Diagnostics.Debug.WriteLine( $"Request-Response cycle took {DateTime.UtcNow.Subtract(startTime).TotalMilliseconds} ms"); return response; } /// <summary> /// Writes data to the serial port asynchronously. /// </summary> /// <param name="payload">The payload.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous write operation.</returns> /// <exception cref="System.InvalidOperationException">Open.</exception> private async Task WriteAsync(byte[] payload, CancellationToken ct) { if (SerialPort == null || SerialPort.IsOpen == false) throw new InvalidOperationException($"Call the {nameof(OpenAsync)} method before attempting communication"); SerialPortDone.Wait(ct); SerialPortDone.Reset(); try { await SerialPort.WriteAsync(payload, 0, payload.Length, ct); await SerialPort.FlushAsync(ct); } finally { SerialPortDone.Set(); } } /// <summary> /// Flushes the serial port read data discarding all bytes in the read buffer. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> private async Task<byte[]> FlushReadBufferAsync(CancellationToken ct) { if (SerialPort == null || SerialPort.IsOpen == false) return new byte[] { }; SerialPortDone.Wait(ct); SerialPortDone.Reset(); try { var count = 0; var buffer = new byte[SerialPort.ReadBufferSize]; var offset = 0; while (SerialPort.BytesToRead > 0) { count += await SerialPort.ReadAsync(buffer, offset, buffer.Length, ct); offset += count; } return buffer.Take(count).ToArray(); } finally { SerialPortDone.Set(); } } /// <summary> /// Reads data from the serial port asynchronously with the default timeout. /// </summary> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous read operation.</returns> private Task<byte[]> ReadAsync(CancellationToken ct) => ReadAsync(DefaultTimeout, ct); /// <summary> /// Reads bytes from the serial port. /// </summary> /// <param name="timeout">The timeout.</param> /// <param name="ct">The cancellation token.</param> /// <returns>A task that represents the asynchronous read operation.</returns> /// <exception cref="System.InvalidOperationException">Open.</exception> private async Task<byte[]> ReadAsync(TimeSpan timeout, CancellationToken ct) { if (SerialPort == null || SerialPort.IsOpen == false) throw new InvalidOperationException($"Call the {nameof(OpenAsync)} method before attempting communication"); SerialPortDone.Wait(ct); SerialPortDone.Reset(); try { var response = new List<byte>(1024 * 10); var expectedBytes = 8; var iteration = 0; var isVariableLengthResponse = false; var largePacketDelayMilliseconds = 0; const int largePacketSize = 500; var startTime = DateTime.UtcNow; var buffer = new byte[SerialPort.ReadBufferSize]; while (SerialPort.IsOpen && response.Count < expectedBytes && ct.IsCancellationRequested == false) { if (SerialPort.BytesToRead > 0) { var readBytes = await SerialPort.ReadAsync(buffer, 0, buffer.Length, ct); response.AddRange(buffer.Skip(0).Take(readBytes)); var remainingBytes = expectedBytes - response.Count; startTime = DateTime.UtcNow; // for larger data packets we want to give it a nicer breather if (isVariableLengthResponse && response.Count < expectedBytes && expectedBytes > largePacketSize) { System.Diagnostics.Debug.WriteLine( $"RX: Received {readBytes} bytes. Length: {response.Count} of {expectedBytes}; {remainingBytes} remaining - Delay: {largePacketDelayMilliseconds} ms"); await Task.Delay(largePacketDelayMilliseconds, ct); } if (response.Count >= 4 && iteration == 0) { iteration++; isVariableLengthResponse = ResponseBase.ResponseLengthCategories[(OperationCode) response[1]] == MessageLengthCategory.Variable; if (isVariableLengthResponse) { var headerByteCount = new[] {response[2], response[3]}.BigEndianArrayToUInt16(); if (headerByteCount > 0) { expectedBytes = 8 + 3 + headerByteCount; largePacketDelayMilliseconds = (int) Math.Max((double) expectedBytes / SerialPort.BaudRate * 1000d, 100d); System.Diagnostics.Debug.WriteLine( $"RX: Expected Bytes: {expectedBytes}. Large Packet delay: {largePacketDelayMilliseconds} ms"); } else { expectedBytes = 8; isVariableLengthResponse = false; } } } } else { await Task.Delay(10, ct); } if (DateTime.UtcNow.Subtract(startTime) > timeout) { System.Diagnostics.Debug.WriteLine( $"RX: Did not receive enough bytes. Received: {response.Count} Expected: {expectedBytes}"); System.Diagnostics.Debug.WriteLine( $"RX: {BitConverter.ToString(response.ToArray()).Replace("-", " ")}"); return null; } } return response.ToArray(); } finally { SerialPortDone.Set(); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DataStructures.Utility { /*public class Int32EqualityComparer : EqualityComparer<int> { /// <summary>Empty constructor.</summary> public Int32EqualityComparer() { } /// <summary>Checks whether two numbers are equal.</summary> /// <param name='x'>First number.</param><param name='y'>Second number.</param> /// <returns>true if x equals y; false otherwise.</returns> public override bool Equals(int x, int y) { return x == y; } /// <summary>Gets a hash code for the specified number.</summary> /// <param name='obj'>Value.</param> /// <returns>The hash code for the specified value.</returns> public override int GetHashCode(int obj) { return obj; } }*/ }
using System; using UnityEngine; public class UIManager : MonoBehaviour { [SerializeField] protected GameObject mainUIParent = null; private bool isShowed = false; public event Action OnShowUI = null; public event Action OnHideUI = null; public virtual void ShowUI(bool useEvent) { isShowed = true; if (mainUIParent != null) { mainUIParent.SetActive(true); if (useEvent) OnShowUI?.Invoke(); } else Debug.LogWarning("No reference to UIParent", mainUIParent.gameObject); } public virtual void ShowUI() { ShowUI(true); } public virtual void HideUI(bool useEvent = true) { isShowed = false; if (mainUIParent != null) { mainUIParent.SetActive(false); if (useEvent) OnHideUI?.Invoke(); } else Debug.LogWarning("No reference to UIParent", gameObject); } public virtual void HideUI() { HideUI(true); } public virtual void ToggleUI() { if (isShowed) HideUI(); else ShowUI(); } }
using System.Net; namespace MvcMonitor.Models.Factories { public class StatusCodeFactory : IStatusCodeFactory { public HttpStatusCode Create(string httpStatusCode) { int statusCode; if (!int.TryParse(httpStatusCode, out statusCode)) { return HttpStatusCode.Unused; } return (HttpStatusCode)statusCode; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using BusinessLogic.Common; using BusinessLogic; using DataAccess; using MediathekClient.Common; namespace MediathekClient.Forms { public partial class FrmMediaBookBase : FrmMediaOverviewBase { #region Constructors /// <summary> /// Constructor /// </summary> public FrmMediaBookBase() { InitializeComponent(); } /// <summary> /// Constructor /// </summary> /// <param name="session">The current session</param> /// <param name="mediaTypeId">The media type that is being handled</param> public FrmMediaBookBase(SessionInfo session, int mediaTypeId) : base(session, mediaTypeId) { InitializeComponent(); } #endregion #region Methods /// <summary> /// Marks/unmarks all media according to the current media basket /// </summary> protected void MarkSelectedMedias() { if (this.session != null) { DataGridViewCellStyle csDef = new DataGridViewCellStyle(this.dgvMedia.DefaultCellStyle); DataGridViewCellStyle csSelected = new DataGridViewCellStyle(csDef); csSelected.BackColor = Color.LightGreen; foreach (DataGridViewRow dgvRow in this.dgvMedia.Rows) { if (dgvRow.Cells[clmMediaId.Name].Value != null) { // get media ID int mediaId = (int)dgvRow.Cells[clmMediaId.Name].Value; if (this.session.MediaBasket.Contains(mediaId)) { // mark row dgvRow.DefaultCellStyle = csSelected; } else { // clear row mark dgvRow.DefaultCellStyle = csDef; } } } } } /// <summary> /// Starts the search and populates the datagrid with result that /// matches the criterias /// </summary> private void StartSearch() { try { this.Cursor = Cursors.WaitCursor; // search int? publishingYear = null; if (!string.IsNullOrEmpty(this.txtPublishingYear.Text)) { int pubYear; if (int.TryParse(this.txtPublishingYear.Text, out pubYear)) { publishingYear = pubYear; } } this.bsResult.DataSource = bl.SearchBooks(this.txtTitle.Text, this.txtDesc.Text, this.txtAuthor.Text, this.txtPublisher.Text, publishingYear, this.txtTag.Text); } finally { this.Cursor = Cursors.Default; } } /// <summary> /// Clear the content of the search related fields /// </summary> private void ClearSearchFields() { this.txtAuthor.Clear(); this.txtDesc.Clear(); this.txtPublisher.Clear(); this.txtPublishingYear.Clear(); this.txtTag.Clear(); this.txtTitle.Clear(); } /// <summary> /// Get category ID value from a given row /// </summary> /// <param name="row"></param> /// <returns></returns> protected int GetCategoryIdFromRow(DataGridViewRow row) { if (row == null) throw new ArgumentNullException("row"); return (int)row.Cells[clmCategoryUnbound.Index].Value; } /// <summary> /// Shows a media by it's ID /// </summary> /// <param name="mediaId"></param> protected void ShowMediaById(int mediaId) { this.bsResult.DataSource = bl.GetMediaBookById(mediaId); } #endregion #region Properties /// <summary> /// Get or set if the "AddToBasket" column is visible /// </summary> public bool IsAddToBasketClmVisible { set { this.clmAddToBasket.Visible = value; } get { return this.clmAddToBasket.Visible; } } #endregion #region Event handlers /// <summary> /// On form load /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FrmMediaBase_Load(object sender, EventArgs e) { if (!this.DesignMode) { FillCategories(); // set categories this.categoryBindingSource.DataSource = bl.GetCategoriesByMediaTypeId(this.mediaTypeId); MarkSelectedMedias(); } } /// <summary> /// Cell content clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dgvMedia_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0 && e.ColumnIndex >= 0) { int mediaId = (int)this.dgvMedia[clmMediaId.Index, e.RowIndex].Value; if (e.ColumnIndex == clmImageChg.Index) { // image change button clicked if (mediaId > 0) { new FrmMediaImgChanger(this.session, mediaId).ShowDialog(this); } else { // media image can only be shown for already saved media Tools.ShowMessageBox(MessageBoxType.Info, Localization.MsgMediaImageNotShowable, this); } } else if (e.ColumnIndex == clmAddToBasket.Index && this.session != null) { // add selected item to basket if (!this.session.MediaBasket.Contains(mediaId)) { // add to basket this.session.AddMediaToBasket(mediaId); } else { // remove from basket this.session.RemoveMediaFromBasket(mediaId); } // highlight selected media MarkSelectedMedias(); } } } /// <summary> /// Button "search" clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void butSearchOk_Click(object sender, EventArgs e) { StartSearch(); } /// <summary> /// Button "clear filter" clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void butSearchClear_Click(object sender, EventArgs e) { ClearSearchFields(); } private void dgvMedia_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { // select the correct category for databound media if (dgvMedia.Rows[e.RowIndex].DataBoundItem != null) { //get a reference to the reservation currently being painted var media = (MediaBook)(dgvMedia.Rows[e.RowIndex].DataBoundItem); //push the categories's navigation properties into the correct cells var grid = dgvMedia; DataGridViewComboBoxCell cbCell = (DataGridViewComboBoxCell)grid.Rows[e.RowIndex].Cells[clmCategoryUnbound.Index]; cbCell.Value = media.CategoryReference.EntityKey.EntityKeyValues[0].Value; } } /// <summary> /// DGV DataBinding completed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dgvMedia_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { // set the correct category name foreach (DataGridViewRow row in this.dgvMedia.Rows) { // select the correct category for databound media if (row.DataBoundItem != null) { //get a reference to the reservation currently being painted var media = (MediaBook)row.DataBoundItem; //push the categories's navigation properties into the correct cells var grid = dgvMedia; DataGridViewComboBoxCell cbCell = (DataGridViewComboBoxCell)row.Cells[clmCategoryUnbound.Index]; cbCell.Value = media.CategoryReference.EntityKey.EntityKeyValues[0].Value; } } } /// <summary> /// BS result, data source changed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void bsResult_DataSourceChanged(object sender, EventArgs e) { // refresh marked items MarkSelectedMedias(); } /// <summary> /// DGV cell begin init /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dgvMedia_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { if (this.dgvMedia != null && this.dgvMedia.Rows.Count > 0 && e.RowIndex >= 0) { AddChangedRow(e.RowIndex); } } #endregion } }
using System; using System.Drawing; using System.Collections.Generic; using System.IO; using Grasshopper.Kernel; using Rhino.Geometry; namespace Aggregator { public class Aggregator : GH_Component { /// <summary> /// Each implementation of GH_Component must provide a public /// constructor without any arguments. /// Category represents the Tab in which the component will appear, /// Subcategory the panel. If you use non-existing tab or panel names, /// new tabs/panels will automatically be created. /// </summary> public Aggregator() : base("Aggregator", "Aggregator", "Aggregates design input data, performance metrics, image & json filemanes into a data.csv file for Design Explorer to open.", "Colibri", "Colibri") { } public override GH_Exposure Exposure { get {return GH_Exposure.tertiary;} } /// <summary> /// Registers all the input parameters for this component. /// </summary> protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) { pManager.AddTextParameter("FolderPath", "Folder", "Folder path", GH_ParamAccess.item); pManager.AddTextParameter("inputsDataSet", "Inputs", "Inputs data", GH_ParamAccess.list); pManager.AddTextParameter("outputsDataSet", "Outputs", "Outputs data", GH_ParamAccess.list); pManager.AddTextParameter("imageParams", "ImgParams", "ImageParams like height, width of output images", GH_ParamAccess.list); pManager.AddBooleanParameter("writeFile", "WriteFile", "Set to yes to run", GH_ParamAccess.item); //pManager.AddTextParameter("imgName", "name", "imgName", GH_ParamAccess.item); } /// <summary> /// Registers all the output parameters for this component. /// </summary> protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) { pManager.AddTextParameter("writeInData", "WriteInData", "Use panel to check current data", GH_ParamAccess.item); pManager.AddTextParameter("SpectaclesFileName", "SpectaclesFileName", "Feed this into the Spectacles_SceneCompiler component downstream.", GH_ParamAccess.item); } /// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object can be used to retrieve data from input parameters and /// to store data in output parameters.</param> protected override void SolveInstance(IGH_DataAccess DA) { //input variables string folder = ""; List<string> inputs = new List<string>(); List<string> outputs = new List<string>(); List<string> imgParams = new List<string>(); bool writeFile = false; //get data DA.GetData(0, ref folder); DA.GetDataList(1, inputs); DA.GetDataList(2, outputs); DA.GetDataList(3, imgParams); DA.GetData(4, ref writeFile); //operations string csvPath = folder + "/data.csv"; var rawData = inputs; int inDataLength = rawData.Count; rawData.AddRange(outputs); int allDataLength = rawData.Count; string imgName = ""; string imgPath = ""; string keyReady = ""; string valueReady = ""; //format write in data for (int i = 0; i < rawData.Count; i++) { string item = Convert.ToString(rawData[i]).Replace("[", "").Replace("]", "").Replace(" ", ""); string dataKey = item.Split(',')[0]; string dataValue = item.Split(',')[1]; if (i > 0) { if (i < inDataLength) { keyReady += ",in:" + dataKey; } else { keyReady += ",out:" + dataKey; } valueReady = valueReady + "," + dataValue; imgName = imgName + "_" + dataValue; } else { //the first set keyReady = "in:" + dataKey; valueReady += dataValue; imgName = dataValue; } } bool run = writeFile; string fileName = imgName; imgPath = folder+"/"+imgName + ".png"; imgName += ".png"; string jsonFilePath = folder + "/" + fileName + ".json"; string jsonFileName = fileName + ".json"; string writeInData = ""; //int width = 500; //int height = 500; List<int> cleanedImgParams = new List<int>(); foreach (string item in imgParams) { string cleanItem = Convert.ToString(item).Replace("[", "").Replace("]", "").Replace(" ", ""); //string dataValue = cleanItem.Split(',')[1]; cleanedImgParams.Add(Convert.ToInt32(cleanItem.Split(',')[1])); } Size viewSize = new Size(cleanedImgParams[0], cleanedImgParams[1]); //string imagePath = @"C:\Users\Mingbo\Documents\GitHub\Colibri.Grasshopper\src\MP_test\01.png"; if (run) { //check csv file if (!File.Exists(csvPath)) { keyReady = keyReady + ",img,threeD" + Environment.NewLine; File.WriteAllText(csvPath, keyReady); } //save imgs var pic = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.CaptureToBitmap(viewSize); pic.Save(imgPath); //save csv writeInData = string.Format("{0},{1},{2}\n", valueReady, imgName, jsonFileName); File.AppendAllText(csvPath, writeInData); } //set output DA.SetData(0, writeInData); DA.SetData(1, jsonFilePath); } /// <summary> /// Provides an Icon for every component that will be visible in the User Interface. /// Icons need to be 24x24 pixels. /// </summary> protected override System.Drawing.Bitmap Icon { get { // You can add image files to your project resources and access them like this: //return Resources.IconForThisComponent; return Colibri.Grasshopper.Properties.Resources.Colibri_logobase_4; } } /// <summary> /// Each component must have a unique Guid to identify it. /// It is vital this Guid doesn't change otherwise old ghx files /// that use the old ID will partially fail during loading. /// </summary> public override Guid ComponentGuid { get { return new Guid("{787196c8-5cc8-46f5-b253-4e63d8d271e1}"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Game; using Game.Characters; using Game.Interfaces; using Game.Objects; namespace Game { class HeroMove : IMove { public bool Block(Position _position, string _move, Generics[,] _generic) { int x = _position.X; int y = _position.Y; Position position = new Position(x, y); position = SwitchMove(position, _move); return _generic[position.X, position.Y].Body == " "; } public Position Move(Position _positionHero, Generics[,] _generic) { string _move = Console.ReadKey().KeyChar.ToString(); while (!CorrectKey(_move) || !Block(_positionHero, _move, _generic)) { _move = Console.ReadKey().KeyChar.ToString(); } return SwitchMove(_positionHero, _move); } public bool CorrectKey(string _movement) { List<string> _Movements = new List<string>() { "w", "a", "s", "d", "A", "W", "S", "D" }; return _Movements.Any(x => x == _movement); } Position SwitchMove(Position position, string _move) { Position _position = position; switch (_move) { case "w": case "W": _position.X = _position.X - 1; break; case "a": case "A": _position.Y = _position.Y - 1; break; case "s": case "S": _position.X = _position.X + 1; break; case "d": case "D": _position.Y = _position.Y + 1; break; } return _position; } } }
using Infrastructure.Configuration; namespace Infrastructure.UserIdentity { public static class DomainUserExtensions { public static bool IsBan(this DomainUser user) { return user.IsMemberOf(Configurations.BanGroup); } public static bool IsGiperAdmin(this DomainUser user) { return user.IsMemberOf(Configurations.GiperAdminGroup); } public static bool IsOfficeWorker(this DomainUser user) { return user.IsMemberOf(Configurations.OfficeGroup) || user.IsGiperAdmin(); } public static bool IsChief(this DomainUser user) { return user.IsMemberOf(Configurations.ChiefGroup) || user.IsGiperAdmin(); } public static bool IsFinancialWorker(this DomainUser user) { return user.IsMemberOf(Configurations.FinancialGroup) || user.IsGiperAdmin(); } public static bool IsCashContractsReader(this DomainUser user) { return user.IsMemberOf(Configurations.ContractReadersGroup) || user.IsGiperAdmin(); } public static bool IsGip(this DomainUser user) { return user.IsMemberOf(Configurations.GipGroup) || user.IsGiperAdmin(); } public static bool IsPhotoAdmin(this DomainUser user) { return user.IsMemberOf(Configurations.PhotoAdminGroup) || user.IsGiperAdmin(); } public static bool IsInfoMaterialAdmin(this DomainUser user) { return user.IsMemberOf(Configurations.InfoMaterialAdminGroup) || user.IsGiperAdmin(); } public static bool IsTemplatesAdministrator(this DomainUser user) { return user.IsMemberOf(Configurations.TemplatesAdministrator) || user.IsGiperAdmin(); } public static bool IsDivisionChief(this DomainUser user) { return user.IsMemberOf(Configurations.DivisionChiefsGroup) || user.IsGiperAdmin(); } public static bool IsDocFlowFullAccess(this DomainUser user) { return user.IsMemberOf(Configurations.DocFlowFullAccessGroup) || user.IsGiperAdmin(); } public static bool IsDocFlowLimitedAccess(this DomainUser user) { return user.IsMemberOf(Configurations.DocFlowLimitedAccessGroup) || user.IsGiperAdmin(); } public static bool IsTdmsEditor(this DomainUser user) { return user.IsMemberOf(Configurations.EditorGroup); } public static bool IsTdmsViewer(this DomainUser user) { return user.IsMemberOf(Configurations.ViewerGroup) || user.IsTdmsEditor(); } public static bool IsAdminBuildingDepartment(this DomainUser user) { return user.IsMemberOf(Configurations.AdminBuildingDepartment) || user.IsGiperAdmin(); } public static bool IsAdminDepartmentSubstation(this DomainUser user) { return user.IsMemberOf(Configurations.AdminDepartmentSubstation) || user.IsGiperAdmin(); } public static bool IsAdminManualBuildingDepartment(this DomainUser user) { return user.IsMemberOf(Configurations.AdminManualBuildingDepartment) || user.IsGiperAdmin(); } public static bool IsDispatchGroup(this DomainUser user) { return user.IsMemberOf(Configurations.DispatchGroup) || user.IsGiperAdmin(); } public static bool IsElectronicArchive(this DomainUser user) { return user.IsMemberOf(Configurations.ElectronicArchive) || user.IsGiperAdmin(); } public static bool IsGroupConfiguration(this DomainUser user) { return user.IsMemberOf(Configurations.GroupConfiguration) || user.IsGiperAdmin(); } public static bool IsSiteInputDocCreatorAdmin(this DomainUser user) { return user.IsMemberOf(Configurations.SiteInputDocCreatorAdmin) || user.IsGiperAdmin(); } public static bool IsSiteOutputDocCreator(this DomainUser user) { return user.IsMemberOf(Configurations.SiteOutputDocCreator) || user.IsGiperAdmin(); } public static bool IsSiteOutputDocCreatorAdmin(this DomainUser user) { return user.IsMemberOf(Configurations.SiteOutputDocCreatorAdmin) || user.IsGiperAdmin(); } public static bool CanDownloadDocFile(this DomainUser user) { return user.IsMemberOf(Configurations.CanDownloadDocFile) || user.IsGiperAdmin(); } public static bool IsContractAdministrator(this DomainUser user) { return user.IsMemberOf(Configurations.ContractAdministrator) || user.IsGiperAdmin(); } public static bool IsMakeAddSitesToDocs(this DomainUser user) { return user.IsMemberOf(Configurations.IsMakeAddSitesToDocs) || user.IsGiperAdmin(); } public static bool IsPublicationsAdmin(this DomainUser user) { return user.IsMemberOf(Configurations.AdminPublications) || user.IsGiperAdmin(); } //todo: нужно исправить public static bool IsDepartmentSubstationUser(this DomainUser user) { return user.DivisionGroup.DivisionId == 7; } //todo: нужно исправить public static bool IsBuildingDepartmentUser(this DomainUser user) { return user.DivisionGroup.DivisionId == 13; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Text; using VSchool.Data.Entities; namespace VSchool.Data.Mapping { public class StudentMap : EntityConfiguration<Student> { public override void Configure(EntityTypeBuilder<Student> builder) { builder.ToTable("Student"); builder.HasKey(a => a.ID); builder.Property(a => a.FirstName).HasMaxLength(20).IsRequired(); builder.Property(a => a.LastName).HasMaxLength(20).IsRequired(); builder.Property(a => a.Age); builder.Property(a => a.Timestamp).IsRowVersion(); builder.HasOne(a => a.Class).WithMany(a => a.Students).HasForeignKey(a => a.ClassID).IsRequired(); base.Configure(builder); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Calcifer.Engine.Scenery { public class MapBuilder { private readonly Stack<EntityDefinition> entityStack; private readonly Map map; private string currentComponent; public MapBuilder() { map = new Map(); entityStack = new Stack<EntityDefinition>(); } public void BeginEntity(string name) { entityStack.Push(new EntityDefinition(name)); } public void EndEntity() { if (entityStack.Count == 0) { throw new InvalidOperationException("EndEntity called before BeginEntity"); } var def = entityStack.Pop(); // entity names are usually "<classname>.NNN", so we extract the class name var pos = def.Name.LastIndexOf('.'); var entityName = def.Name; var entityClass = (entityName.Contains(".node")) ? "node" : (pos < 0) ? entityName : entityName.Substring(0, pos); if (!map.Definitions.Contains(entityClass)) { def.Name = entityClass; map.Definitions.Add(def); } var instance = CalculateDelta(entityName, map.Definitions[entityClass], def); map.Instances.Add(instance); } private EntityInstance CalculateDelta(string name, EntityDefinition def, EntityDefinition instance) { var result = new EntityInstance(); foreach (var param in instance.Parameters) if (!def.Parameters.Contains(param.Component + ":" + param.Name) || (def.Parameters[param.Component + ":" + param.Name].Value != param.Value)) result.Deltas.Add(new DeltaEntry(DeltaType.Add, param.Component, param.Name, param.Value)); foreach (var param in def.Parameters) if (!instance.Parameters.Contains(param.Component + ":" + param.Name)) result.Deltas.Add(new DeltaEntry(DeltaType.Remove, param.Component, param.Name, param.Value)); result.Name = name; result.ClassName = def.Name; return result; } public void BeginComponent(string type) { if (currentComponent != null) throw new InvalidOperationException("Component stack not empty."); currentComponent = type; } public void BeginComponent<T>() { var type = typeof(T).Name; BeginComponent(type); } public void EndComponent() { if (!entityStack.Peek().Parameters.GetComponents().Contains(currentComponent)) { entityStack.Peek().Parameters.Add(new Parameter(currentComponent, null, null)); } currentComponent = null; } public void AddParameter(string name, string value) { entityStack.Peek().Parameters.Add(new Parameter(currentComponent, name, value)); } public Map GetMap() { if (entityStack.Count != 0) { throw new InvalidOperationException("Entity stack not empty."); } return map; } public void AddAsset(string alias, bool composite, string source) { if (!map.Assets.Contains(alias)) map.Assets.Add(new AssetReference {Name = alias, Source = source, Composite = composite}); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SFP.SIT.SERV.Model.SNT { public class SIT_SNT_MUNICIPIO { public Int64? edoclave { set; get; } public Int64? paiclave { set; get; } public DateTime munfecbaja { set; get; } public string mundescripcion { set; get; } public Int64 munclave { set; get; } public SIT_SNT_MUNICIPIO () {} } }
using System; namespace Panoptes.Model.Charting { public struct InstantChartPoint : IInstantChartPoint { public DateTimeOffset X { get; set; } public decimal Y { get; set; } public InstantChartPoint(DateTimeOffset x, decimal y) { X = x; Y = y; } public override string ToString() { return $"{X} - {Y}"; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using TMPro; public class PutMessenger : MonoBehaviour { public TextMeshPro textBox; readonly string getURL = "https://us-central1-affable-armor-266916.cloudfunctions.net/hello-world-function"; void Start() { StartCoroutine(SimpleGetRequest()); } IEnumerator SimpleGetRequest() { byte[] myData = System.Text.Encoding.UTF8.GetBytes("This is some test data"); UnityWebRequest www = UnityWebRequest.Put(getURL, myData); yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.LogError(www.error); } else { string result = www.downloadHandler.text; textBox.text = result; } } }
using System; using System.Data; using System.Collections.Generic; namespace DriveMgr.IDAL { /// <summary> /// 角色接口(不同的数据库访问类实现接口达到多数据库的支持) /// </summary> public interface IRole { /// <summary> /// 根据用户id获取用户角色 /// </summary> DataTable GetRoleByUserId(int id); /// <summary> /// 根据条件获取角色 /// </summary> DataTable GetAllRole(string where); /// <summary> /// 根据角色名获取角色 /// </summary> DriveMgr.Model.Role GetRoleByRoleName(string roleName); /// <summary> /// 添加角色 /// </summary> int AddRole(DriveMgr.Model.Role role); /// <summary> /// 删除角色(删除角色同时删除对应的:用户角色/角色菜单按钮【即权限】) /// </summary> bool DeleteRole(int id); /// <summary> /// 修改角色 /// </summary> bool EditRole(DriveMgr.Model.Role role); /// <summary> /// 根据角色Id获取对应的菜单按钮权限 /// </summary> DataTable GetMenuButtonIdByRoleId(int roleId); /// <summary> /// 角色授权 /// </summary> bool Authorize(List<DriveMgr.Model.RoleMenuButton> role_menu_button_addlist, List<DriveMgr.Model.RoleMenuButton> role_menu_button_deletelist); /// <summary> /// 获取父节点Id /// </summary> int GetParentMenuId(int roleId, int menuId); /// <summary> /// 获取权限下的用户个数 /// </summary> int GetRoleUserCount(int roleId); /// <summary> /// 获取权限下的用户(分页) /// </summary> DataTable GetPagerRoleUser(int roleId, string order, int pageSize, int pageIndex); } }
namespace Logic.TechnologyClasses { public class ResearchArchive { } }
using UnityEngine; using System.Collections; public class Tile : MonoBehaviour { Base baseObject; public GameObject buildingDisplay; public GameObject house; public GameObject tile; GameController gameController; Tile tileSpawn; // Use this for initialization void Start () { baseObject = GameObject.FindGameObjectWithTag("Base").GetComponent<Base>(); gameController = GameObject.FindGameObjectWithTag("GameController").GetComponent<GameController>(); tileSpawn = GameObject.FindGameObjectWithTag("tileSpawn").GetComponent<Tile>(); } // Update is called once per frame void Update () { } void OnMouseOver() { if(Input.GetMouseButtonDown(0)) { if (baseObject.building == 1 && gameController.wood >= 100) { gameController.wood -= 100; Instantiate(house, transform.position, transform.rotation); } } } public void UpgradeClick() { tileSpawn.Upgrade(); } public void Upgrade() { Instantiate(tile, new Vector3(transform.position.x - 5f, transform.position.y - 1f, transform.position.z), transform.rotation); Instantiate(tile, new Vector3(transform.position.x + 5f, transform.position.y - 1f, transform.position.z), transform.rotation); Instantiate(tile, new Vector3(transform.position.x, transform.position.y - 1f, transform.position.z + 5f), transform.rotation); Instantiate(tile, new Vector3(transform.position.x, transform.position.y - 1f, transform.position.z - 5f), transform.rotation); } void OnMouseEnter() { //Used for adding an object overaly when you select the tile to use //Instantiate(buildingDisplay, transform.position, transform.rotation); } }
// <copyright file="MonitorService.cs" company="kf corp"> // Licensed under the Apache 2.0 license // </copyright> namespace McServerStarter { using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Options; internal class MonitorService : IMonitorService { private readonly MonitorServiceOptions _options; private readonly ILog<MonitorService> _logger; private Process _process; private TaskCompletionSource<EventArgs> _tcs; public MonitorService(IOptions<MonitorServiceOptions> options, ILog<MonitorService> logger) { _options = options.Value; _logger = logger; _logger.LogDebug($"{nameof(MonitorService)} created"); } ~MonitorService() { _logger.LogDebug($"{nameof(MonitorService)} destroyed"); } public async Task RunAsync(CancellationToken shutdownToken, bool interativeMode) { if (_tcs != null) { await _tcs.Task; return; } _logger.LogInformation("Starting ..."); try { using (var process = new Process()) { process.EnableRaisingEvents = true; process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { _logger.LogError($"> {e.Data}"); }; process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { _logger.LogInformation($"> {e.Data}"); }; process.Exited += (object sender, EventArgs e) => { _logger.LogDebug("worker process exit"); _tcs.TrySetResult(e); }; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { process.StartInfo = new ProcessStartInfo { FileName = _options.ProcessPath, Arguments = _options.Args, RedirectStandardError = interativeMode, RedirectStandardOutput = interativeMode, RedirectStandardInput = true, UseShellExecute = false, }; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { process.StartInfo = new ProcessStartInfo { FileName = _options.ProcessPath, Arguments = _options.Args, RedirectStandardError = interativeMode, RedirectStandardOutput = interativeMode, RedirectStandardInput = true, UseShellExecute = false, }; } else { throw new NotImplementedException($"Not implmented for this OS. {RuntimeInformation.OSDescription}"); } Directory.SetCurrentDirectory(_options.RootPath); if (!process.Start()) { return; } _process = process; _tcs = new TaskCompletionSource<EventArgs>(); if (interativeMode) { _process.BeginOutputReadLine(); _process.BeginErrorReadLine(); ReadInputAsync(shutdownToken); } using (var shutdownCtr = shutdownToken.Register(ShutDown)) { await _tcs.Task; } } } finally { _tcs = null; _process = null; } } public async ValueTask DisposeAsync() { _logger.LogDebug("Disposing ..."); if (_tcs != null) { _tcs.TrySetResult(EventArgs.Empty); await _tcs.Task; } } private async void ReadInputAsync(CancellationToken cancellationToken) { var buffer = new char[1024]; while (!cancellationToken.IsCancellationRequested) { var len = await Console.In.ReadAsync(buffer, 0, 1024); if (cancellationToken.IsCancellationRequested) { return; } if (len <= 0) { continue; } await _process.StandardInput.WriteAsync(buffer, 0, len); } } private async void ShutDown() { _logger.LogInformation("Shuting down..."); try { if (_tcs.Task.Status == TaskStatus.RanToCompletion || _tcs.Task.Status == TaskStatus.Faulted || _tcs.Task.Status == TaskStatus.Canceled) { _logger.LogWarning($"process is already not running. Task status: {_tcs.Task.Status}"); return; } _process.StandardInput.WriteLine("/stop"); _logger.LogInformation($"Stop command sent. Waiting for worker response"); await Task.WhenAny(Task.Delay(_options.ShutDownTimeout), _tcs.Task); if (_process != null) { _logger.LogWarning("Shutdown timeout reached. Killing worker process."); _process.Kill(); _process.WaitForExit(); _tcs.TrySetResult(EventArgs.Empty); } _logger.LogInformation($"worker process stopped"); } catch (Exception e) { _logger.LogError(e.ToString()); _tcs?.TrySetException(e); } } } }
using RimWorld; using Verse; using Verse.AI; namespace sd_luciprod; public class WorkGiver_sd_luciprod_TakeLuciOutOfDistillery : WorkGiver_Scanner { public override ThingRequest PotentialWorkThingRequest => ThingRequest.ForDef(ThingDefOf.sd_luciprod_distillery); public override PathEndMode PathEndMode => PathEndMode.Touch; public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { return t is Building_sd_luciprod_distillery { Distilled: true } && !t.IsBurning() && !t.IsForbidden(pawn) && pawn.CanReserveAndReach(t, PathEndMode.Touch, pawn.NormalMaxDanger()); } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { return new Job(JobDefOf.sd_luciprod_takelucioutofdistillery, t); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class ItemSpawner : MonoBehaviour { public GameObject[] items; Vector3 GetRandomPosition(float Radius) { Vector3 randomDirection = Random.insideUnitSphere * Radius; randomDirection += transform.position; NavMeshHit hit; NavMesh.SamplePosition(randomDirection, out hit, Radius, 1); return hit.position; } public void SpawnItem() { Instantiate(items[Random.Range(0, items.Length)], GetRandomPosition(40) + new Vector3(0,2,0), Quaternion.identity); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SampleList { public class List { public List next; public int value; public List(int setValue) { value = setValue; } public int Count() { int count = 0; List current = this; while (current != null) { count++; current = current.next; } return count; } public void addToEnd(int newValue) { List current = this; if (current.next == null) { current.next = new List(newValue); } current = current.next; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace sales_management_system { public partial class 出庫管理 : Form { public DBcomponent DBcomponent; public Common Common; public 出庫管理() { InitializeComponent(); DBcomponent = new DBcomponent(); Common = new Common(); } private void btn_register_Click(object sender, EventArgs e) { 商品登録_変更 formRegisterProduct = new 商品登録_変更(); DialogResult dialogResult = formRegisterProduct.ShowDialog(); if (dialogResult == DialogResult.OK) { string newProductCodeSql = Common.buildNewPrimaryCodeSql('A', "商品コード", "商品テーブル"); List<Dictionary<string, string>> issueData = DBcomponent.ExecSelectQuery(newProductCodeSql, new Dictionary<string, string>()); if (issueData[0]["商品コード"] == "") { MessageBox.Show("最新の商品コードが取得できませんでした。"); return; } string newProductCode = issueData[0]["商品コード"]; string queryString = @" INSERT INTO 商品テーブル (商品コード,メーカーコード,カテゴリーコード,ジャンルコード,商品名,著者コード,値段,原価,登録日,更新日,有・無効,出版社コード, 出版年月) VALUES (@product_code, @maker_code,@catagory_code,@genre_code,@product_name,@author_code,@price,@genka,@created_at,@updated_at,@is_active,@publisher_code,@publication_date);"; // todo 入力チェック var param = new Dictionary<string, string>() { {"@product_code" , newProductCode}, {"@maker_code" , "B00001" }, // 今は決め打ち {"@catagory_code" , formRegisterProduct.cmb_category.SelectedValue.ToString()}, {"@genre_code" , formRegisterProduct.cmb_genre.SelectedValue.ToString()}, {"@product_name" , formRegisterProduct.txt_product_name.Text}, {"@author_code" , formRegisterProduct.cmb_author.SelectedValue.ToString()}, {"@price" , formRegisterProduct.mtb_price.Text}, {"@genka" , formRegisterProduct.mtb_genka.Text}, {"@created_at" , DateTime.Now.ToString("yyyy/MM/dd")}, {"@updated_at" , DateTime.Now.ToString("yyyy/MM/dd")}, {"@is_active" , formRegisterProduct.rdo_active.Checked ? "-1" : "0"}, {"@publisher_code" , formRegisterProduct.cmb_publisher.SelectedValue.ToString()}, {"@publication_date" , formRegisterProduct.mtb_publication_date.Text} }; int rows = DBcomponent.ExecQueryForChangeTable(queryString, param); if (rows != 1) { MessageBox.Show("登録できませんでした。"); } else { MessageBox.Show("1件データを登録しました。"); fetchProductData(); } } } private void fetchProductData() { throw new NotImplementedException(); } private void btn_search_code_Click(object sender, EventArgs e) //検索ボタンのとこ //テーブルのとこ改善しないといけない { string queryString = @"  SELECT TOP 100 issue.注文コード, 商品名,従業員番号, 顧客名, 注文数, 在庫日, 注文日,キャンセル FROM (((((商品テーブル as issue LEFT JOIN 商品テーブル ON issue.商品コード     = 商品テーブル.商品コード) LEFT JOIN メーカーテーブル ON issue.メーカーコード  = メーカーテーブル.メーカーコード) LEFT JOIN 営業所テーブル ON issue.営業所コード = 営業所テーブル.営業所コード) LEFT JOIN 顧客テーブル  ON issue.顧客コード   = 顧客テーブル.顧客コード)    LEFT JOIN 従業員テーブル ON issue.従業員コード = 従業員テーブル.従業員コード) LEFT JOIN 注文テーブル    ON issue.注文コード     = 注文テーブル.注文コード) LEFT JOIN 発注テーブル   ON issue.発注コード    = 発注テーブル.発注コード) WHERE issue.出庫コード IS NOT NULL "; // 不必要だがANDに繋げるため表記 var param = new Dictionary<string, string>(); if (txt_issue_code.Text != "") { queryString += "AND issue.出庫コード = @code "; param.Add("@code", txt_issue_code.Text); } if (txt_issue_code.Text != "") { queryString += "AND 商品名 LIKE @name "; param.Add("@name", "%" + txt_issue_code.Text + "%"); } dgv_issue_item.DataSource = DBcomponent.FetcDGVData(queryString, param); dgv_issue_item.Refresh(); } private void txt_issue_code_TextChanged(object sender, EventArgs e) { } private void btn_change_Click(object sender, EventArgs e) { int nowRow = dgv_issue_item.CurrentRow.Index; string productName = dgv_issue_item.Rows[nowRow].Cells[1].Value.ToString(); string publisherName = dgv_issue_item.Rows[nowRow].Cells[8].Value.ToString(); int stock = int.Parse(dgv_issue_item.Rows[nowRow].Cells[4].Value.ToString()); int price = int.Parse(dgv_issue_item.Rows[nowRow].Cells[2].Value.ToString()); int genka = int.Parse(dgv_issue_item.Rows[nowRow].Cells[3].Value.ToString()); string author = dgv_issue_item.Rows[nowRow].Cells[7].Value.ToString(); string genre = dgv_issue_item.Rows[nowRow].Cells[5].Value.ToString(); string catagory = dgv_issue_item.Rows[nowRow].Cells[6].Value.ToString(); DateTime publicationDate = DateTime.Parse(dgv_issue_item.Rows[nowRow].Cells[9].Value.ToString()); bool isActive = bool.Parse(dgv_issue_item.Rows[nowRow].Cells[10].Value.ToString()); 商品登録_変更 formRegisterProduct = new 商品登録_変更(productName, publisherName, stock, price, genka, author, genre, catagory, publicationDate, isActive); DialogResult dialogResult = formRegisterProduct.ShowDialog(); if (dialogResult == DialogResult.OK) { string queryString = @" UPDATE 商品テーブル SET 商品名 = @product_name, 出版社コード = @publisher_code, 値段 = @price, 原価 = @genka, 著者コード = @author_code, カテゴリーコード = @catagory_code, ジャンルコード = @genre_code, 出版年月 = @publication_date, 有・無効 = @is_active WHERE 商品コード = @product_code "; // todo 入力チェック var param = new Dictionary<string, string>() { {"@product_name" , formRegisterProduct.txt_product_name.Text}, {"@publisher_code" , formRegisterProduct.cmb_publisher.SelectedValue.ToString()}, {"@price" , formRegisterProduct.mtb_price.Text}, {"@genka" , formRegisterProduct.mtb_genka.Text}, {"@author_code" , formRegisterProduct.cmb_author.SelectedValue.ToString()}, {"@catagory_code" , formRegisterProduct.cmb_category.SelectedValue.ToString()}, {"@genre_code" , formRegisterProduct.cmb_genre.SelectedValue.ToString()}, {"@publication_date" , formRegisterProduct.mtb_publication_date.Text}, {"@is_active" , formRegisterProduct.rdo_active.Checked ? "-1" : "0"}, {"@product_code" , dgv_issue_item.Rows[nowRow].Cells[0].Value.ToString()} }; int rows = DBcomponent.ExecQueryForChangeTable(queryString, param); if (rows == 0) { MessageBox.Show("更新に失敗しました。"); return; } queryString = "UPDATE 在庫テーブル SET 在庫数 = @stock WHERE 商品コード = @product_code"; param = new Dictionary<string, string>() { {"@stock", formRegisterProduct.mtb_stock.Text}, {"@product_code", dgv_issue_item.Rows[nowRow].Cells[0].Value.ToString()} }; rows = DBcomponent.ExecQueryForChangeTable(queryString, param); if (rows == 0) { MessageBox.Show("更新に失敗しました。"); return; } MessageBox.Show("データを更新しました。"); fetchProductData(); } } private void btn_detail_Click(object sender, EventArgs e) { int nowRow = dgv_issue_item.CurrentRow.Index; string productName = dgv_issue_item.Rows[nowRow].Cells[1].Value.ToString(); string publisherName = dgv_issue_item.Rows[nowRow].Cells[8].Value.ToString(); string author = dgv_issue_item.Rows[nowRow].Cells[7].Value.ToString(); DateTime publicationDate = DateTime.Parse(dgv_issue_item.Rows[nowRow].Cells[9].Value.ToString()); string genre = dgv_issue_item.Rows[nowRow].Cells[5].Value.ToString(); string catagory = dgv_issue_item.Rows[nowRow].Cells[6].Value.ToString(); string productCode = dgv_issue_item.Rows[nowRow].Cells[0].Value.ToString(); int stock = int.Parse(dgv_issue_item.Rows[nowRow].Cells[4].Value.ToString()); int price = int.Parse(dgv_issue_item.Rows[nowRow].Cells[2].Value.ToString()); int genka = int.Parse(dgv_issue_item.Rows[nowRow].Cells[3].Value.ToString()); bool isActive = bool.Parse(dgv_issue_item.Rows[nowRow].Cells[10].Value.ToString()); 商品詳細 formDetailProduct = new 商品詳細(productName, publisherName, author, publicationDate, genre, catagory, productCode, stock, price, genka, isActive); formDetailProduct.ShowDialog(); } } }
using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using CoreAnimation; using CoreGraphics; using App1; using App1.iOS.Renderers; [assembly: ExportRenderer(typeof(AboutPage), typeof(AboutPageRenderer))] namespace App1.iOS.Renderers { public class AboutPageRenderer : PageRenderer { protected override void OnElementChanged(VisualElementChangedEventArgs e) { base.OnElementChanged(e); if (e.OldElement == null) // perform initial setup { var gradientLayer = new CAGradientLayer(); gradientLayer.Frame = View.Bounds; gradientLayer.Colors = new CGColor[] { Color.FromHex("#a8d7ec").ToCGColor(), Color.FromHex("#3da0c7").ToCGColor() }; View.Layer.InsertSublayer(gradientLayer, 0); } } } }
namespace E09_FrequentNumber { using System; using System.Linq; public class FrequentNumber { public static void Main(string[] args) { // Write a program that finds the most frequent number // in an array. // Example: // input result // 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3 4 (5 times) Console.WriteLine("Please, enter an array of integer numbers !"); int[] array = Console.ReadLine() .Split(new char[] { ' ', '\t', ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(ch => int.Parse(ch.ToString())) .ToArray(); Console.WriteLine(); var number = (from numbers in array group numbers by numbers into sortedGroup orderby sortedGroup.Count() descending select new { Number = sortedGroup.Key, Frequency = sortedGroup.Count() }).First(); Console.WriteLine("The most frequent number is {0} ({1} times)", number.Number, number.Frequency); } } }
using CRM.Data; using CRM.Model; using CRM.Service.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CRM.Service { public class RegionService: IRegionService { private readonly IRepository<Region> regionRepository; private readonly IUnitOfWork unitOfWork; public RegionService(IUnitOfWork unitOfWork, IRepository<Region> regionRepository) { this.unitOfWork = unitOfWork; this.regionRepository = regionRepository; } public void Delete(Region entity) { regionRepository.Delete(entity); unitOfWork.SaveChanges(); } public void Delete(Guid id) { var region = regionRepository.Find(id); if (region != null) { this.Delete(region); } } public Region Find(Guid id) { return regionRepository.Find(id); } public IEnumerable<Region> GetAll() { return regionRepository.GetAll(); } public IEnumerable<Region> GetAllByName(string name) { return regionRepository.GetAll(w => w.Name.Contains(name)); } public void Insert(Region entity) { regionRepository.Insert(entity); unitOfWork.SaveChanges(); } public IEnumerable<Region> Search(string name) { return regionRepository.GetAll(e => e.Name.Contains(name)); } public void Update(Region entity) { var region = regionRepository.Find(entity.Id); region.Name = entity.Name; region.Employees = entity.Employees; region.Customers = entity.Customers; regionRepository.Update(region); unitOfWork.SaveChanges(); } } }
using Ghost.Utility; using System; using UnityEngine; namespace RO { public class ObjectHolder : ResourceHolder { public bool immediately; public Object obj { get; private set; } public ObjectHolder(Object o, bool imd = false) { this.obj = o; this.immediately = imd; } protected override void ReleaseUnmanagedResource() { if (null != this.obj) { if (this.immediately) { Object.DestroyImmediate(this.obj); } else { Object.Destroy(this.obj); } this.obj = null; } } } }
using System.Collections.Generic; using OwnerPets.Data; namespace OwnerPets.Services { public interface IPetsService { PetsClassified GetPetsClassified(); } }
using KnapsackProblem.Common; using KnapsackProblem.ConstructiveVersion.Strategies; using KnapsackProblem.Exceptions; using KnapsackProblem.Helpers; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace KnapsackProblem.ConstructiveVersion { class ConstructiveVersionHandler: AbstractVersionHandler<ConstructiveResult, KnapsackInstance> { public override void HandleData(CommandLineOptions options) { //Process and load input instances if (!ProcessInputInstances(out var instances, options.InputFile, InputFieldParser.ParseConstructiveKnapsackInstance)) return; var strategy = GetConstructiveStrategy(options.Strategy); if (typeof(ConstructiveFPTAS).IsInstanceOfType(strategy)) AddAproxToInstances(instances, options); //var results = strategy.SolveAll(instances, options.Strategy, options.DataSetName); var results = PerformanceTester.SolveWithPerformanceTest(instances, strategy, options); //Compare with the reference solution if specified if (options.ReferenceFile != null) { if (!ValidateResults<ConstructiveResult, KnapsackInstance>(results, options.ReferenceFile, SolutionValidator.ConstructiveComparator)) return; } //Output the solution try { OutputWriter.WriteConstructiveResults(results, options.OutputFile); } catch (IOException e) { Console.WriteLine($"Error while writing into the output file: {e.Message}"); } } private ConstructiveStrategy GetConstructiveStrategy(string strategyField) { if (strategyField.Equals("BruteForce", StringComparison.OrdinalIgnoreCase)) return new ConstructiveBruteForce(); else if (strategyField.Equals("BranchAndBound", StringComparison.OrdinalIgnoreCase)) return new ConstructiveBranchBound(); else if (strategyField.Equals("DPCapacity", StringComparison.OrdinalIgnoreCase)) return new ConstructiveDPCapacity(); else if (strategyField.Equals("DPPrice", StringComparison.OrdinalIgnoreCase)) return new ConstructiveDPPrice(); else if (strategyField.Equals("DPBoth", StringComparison.OrdinalIgnoreCase)) return new ConstructiveDPBoth(); else if (strategyField.Equals("Greedy", StringComparison.OrdinalIgnoreCase)) return new ConstructiveGreedy(); else if (strategyField.Equals("GreedyRedux", StringComparison.OrdinalIgnoreCase)) return new ConstructiveGreedyRedux(); else if (strategyField.Equals("FPTAS", StringComparison.OrdinalIgnoreCase)) return new ConstructiveFPTAS(); throw new InvalidArgumentException($"{strategyField} is not a valid strategy for decision version. Valid strategies: " + $"\n {ConstructiveVersionStrategies()}"); } private void AddAproxToInstances(IList<KnapsackInstance> instances, CommandLineOptions options) { foreach (var instance in instances) instance.ApproximationAccuracy = options.ApproximationAccuracy; } static string ConstructiveVersionStrategies() { return "BruteForce \n " + "BranchAndBound \n " + "DPCapacity \n " + "DPPrice \n " + "DPBoth \n " + "Greedy\n " + "GreedyRedux \n " + "FPTAS \n"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DataAccessLayer.Entities; using DataAccessLayer.Assets; using MySQL.Data.EntityFrameworkCore; using MySql.Data.MySqlClient; using MySql.Web; using System.Data; namespace DataAccessLayer.EOperation { public class OBilling { string con = "server=127.0.0.1;database=pharmacydb;uid=root;pwd=khan61814;"; public int IBilling(Billing Bill) { int count; using (MySqlConnection conn = new MySqlConnection(con)) { using (MySqlCommand cmd = new MySqlCommand("InsBill", conn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@id", Bill.ID); cmd.Parameters.AddWithValue("@Cname", Bill.Name); cmd.Parameters.AddWithValue("@Icode", Bill.ICode); cmd.Parameters.AddWithValue("@IQuant", Bill.IQuantity); cmd.Parameters.AddWithValue("@OStatus", Bill.Ostatus); cmd.Parameters.AddWithValue("@SDis", Bill.SDiscount); cmd.Parameters.AddWithValue("@STax", Bill.Stax); cmd.Parameters.AddWithValue("@TotalAmount", Bill.Totalamount); conn.Open(); count = cmd.ExecuteNonQuery(); } } return count; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace EscolaHeriditaria { public partial class ProfessorForm : BaseForm { public ProfessorForm() { InitializeComponent(); } public bool ValidaDisciplina() { if (cbxDisciplina.SelectedIndex == -1) { MessageBox.Show("A disciplina não foi selecionada"); cbxDisciplina.Focus(); return false; } return true; } private void btnEnviar_Click(object sender, EventArgs e) { if (ValidaNome() && ValidaDataNascimento() && ValidaDisciplina()) { string mensagem = $"Nome: {Nome}, Data de Nascimento {DataNascimento}, Disciplina: {cbxDisciplina.Text}"; MessageBox.Show(mensagem); } } private void cbxDisciplina_Leave(object sender, EventArgs e) { ValidaDisciplina(); } } }
namespace CXO.ProgrammingAssignments.ORM.Interfaces { public enum DbType { Prota, Defteros } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ComplexTerrainGen : MonoBehaviour { public ComputeShader ComplexTerrainGenerator; [Header("Terrain Settings")] public Vector3 size; [Header("Debug")] public GameObject cubePrefab; struct ComplexTerrain { public Vector3[] cubes; } void ShowTerrain(ComplexTerrain terrain) { foreach (Vector3 cube in terrain.cubes) { Instantiate(cubePrefab, cube, Quaternion.identity); } } int kernel; public RenderTexture result; public RawImage screen; public void Render() { ComplexTerrainGenerator.SetTexture(kernel, "Result", result); ComplexTerrainGenerator.Dispatch(kernel, Screen.width / 8, Screen.height / 8, 1); } private void Start() { kernel = ComplexTerrainGenerator.FindKernel("CSMain"); result = new RenderTexture(Screen.width, Screen.height, 24); result.enableRandomWrite = true; result.Create(); screen.texture = result; } private void Update() { Render(); } private void OnRenderImage(RenderTexture source, RenderTexture destination) { Graphics.Blit(result, destination); } }
using ProConstructionsManagment.Desktop.Models; using System.Collections.ObjectModel; using System.Threading.Tasks; namespace ProConstructionsManagment.Desktop.Services { public interface IProjectsService { Task<ObservableCollection<Project>> GetAllProjects(); Task<ObservableCollection<Project>> GetStartedProjects(); Task<int> GetStartedProjectsCount(); Task<ObservableCollection<Project>> GetProjectsForStart(); Task<ObservableCollection<Project>> GetProjectsForSettlement(); Task<ObservableCollection<Project>> GetSettledProjects(); Task<ObservableCollection<Project>> GetEndedProjects(); Task<Project> GetProjectById(string projectId); RequestResult<Project> AddProject(Project model); RequestResult<Project> UpdateProject(Project model, string projectId); RequestResult<ProjectCost> AddProjectCost(ProjectCost model, string projectId); Task<ObservableCollection<ProjectCost>> GetProjectCosts(string projectId); Task<ProjectRecruitment> GetProjectRecruitmentById(string projectRecruitmentId); Task<ObservableCollection<ProjectRecruitment>> GetProjectRecruitmentsById(string projectId); RequestResult<ProjectRecruitment> AddProjectRecruitment(ProjectRecruitment model, string projectId); RequestResult<ProjectRecruitment> UpdateProjectRecruitment(ProjectRecruitment model, string projectRecruitmentId); } }
using UnityEditor; using UnityEditorInternal; using UnityEngine; namespace DialogSystem.ScriptObject.Editor { [CustomEditor(typeof(DialogCharacterAsset))] public class DialogCharacterAssetEditor:UnityEditor.Editor { [MenuItem("ReadyGamerOne/DialogSystem/ShowDialogCharacters")] public static void CreateAsset() { Selection.activeInstanceID = DialogCharacterAsset.Instance.GetInstanceID(); } private Vector2 pos; private SerializedProperty nameListProp; private DialogCharacterAsset targetObject; private ReorderableList list; private void OnEnable() { this.targetObject=target as DialogCharacterAsset; this.nameListProp = serializedObject.FindProperty("characterNames"); list=new ReorderableList(serializedObject,nameListProp,true,true,true,true); list.drawElementCallback = (rect, index, isActive, isFocused) => { var itemProp = nameListProp.GetArrayElementAtIndex(index); EditorGUI.PropertyField(rect, itemProp); }; list.drawHeaderCallback = (rect) => EditorGUI.LabelField(rect, "角色名字"); } public override void OnInspectorGUI() { serializedObject.Update(); pos = EditorGUILayout.BeginScrollView(pos); list.DoLayoutList(); EditorGUILayout.EndScrollView(); serializedObject.ApplyModifiedProperties(); } } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.OpenApi.Models; namespace Iti.Challenge.RestApi.Dependencies { public static class SwaggerInjection { public static void AddSwaggerDocService(this IServiceCollection services) { if (services is null) throw new ArgumentNullException(nameof(services)); services.AddSwaggerGen(c => { c.SwaggerGeneratorOptions.IgnoreObsoleteActions = true; c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "Iti Challenge Rest API", Description = "Rest API to check if a password is valid for Iti Backend Challenge", Contact = new OpenApiContact { Name = "Bruno Romano", Email = "brunopromano@gmail.com", } }); }); } public static void UseSwaggerApiDoc(this IApplicationBuilder app) { if (app is null) throw new ArgumentException(nameof(app)); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Rest API for Iti Backend Challenge"); }); } } }
namespace Models.RegularGame { public struct StructRegularGame: IRegularGame { public string Id { get; set; } public string Name { get; set; } public int Price { get; set; } public int MaxPlayers { get; set; } public int CurrentPlayers { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking.Match; //data transfer object to handle internet and lan workspace public class WorkspaceNetworkInfo { public MatchInfoSnapshot internetMatch; public LanConnectionInfo localMatch; //returns if workspace should be online public bool IsOnline() { return internetMatch != null; } //returns name of workspace public string GetName() { //if online, return official name and amount of participants if (IsOnline()) { string workspaceName = internetMatch.name; workspaceName += " (" + internetMatch.currentSize + "/" + internetMatch.maxSize + ")"; return workspaceName; } //if local, return dedicated name of local match return localMatch.name; } } //represents internal struct for LAN connections public struct LanConnectionInfo { public string ipAddress; public int port; public string name; public LanConnectionInfo(string fromAddress, string data) { //identify ipaddress, port and name out of network information ipAddress = fromAddress.Substring(fromAddress.LastIndexOf(":") + 1, fromAddress.Length - (fromAddress.LastIndexOf(":") + 1)); string portText = data.Substring(data.LastIndexOf(":") + 1, data.Length - (data.LastIndexOf(":") + 1)); port = 7777; int.TryParse(portText, out port); name = "WS: " + ipAddress; } }
/* Copyright 2018 | 2153735 ONTARIO LTD | https://Stru.ca 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. */ #region Namespaces using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; #endregion namespace StruCa.Structureˉui.Webˉapp { public class Program { public static void Main(string[] args) { var Appˉhost = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); Appˉhost.Run(); } } }
using System; using System.Data; using System.Collections.Generic; using System.Text; using CGCN.Framework; using Npgsql; using NpgsqlTypes; using CGCN.DataAccess; namespace HoaDonDataAccess.DataAccess { /// <summary> /// Mô tả thông tin cho bảng tblhoadontra /// Cung cấp các hàm xử lý, thao tác với bảng tblhoadontra /// Người tạo (C): /// Ngày khởi tạo: 15/10/2015 /// </summary> public class tblhoadontra { #region Private Variables private string strid; private string strid_khachhang; private DateTime dtmngaytao; private string strghichu; #endregion #region Public Constructor Functions public tblhoadontra() { strid = string.Empty; strid_khachhang = string.Empty; dtmngaytao = DateTime.Now; strghichu = string.Empty; } public tblhoadontra(string strid, string strid_khachhang, DateTime dtmngaytao, string strghichu) { this.strid = strid; this.strid_khachhang = strid_khachhang; this.dtmngaytao = dtmngaytao; this.strghichu = strghichu; } #endregion #region Properties public string id { get { return strid; } set { strid = value; } } public string id_khachhang { get { return strid_khachhang; } set { strid_khachhang = value; } } public DateTime ngaytao { get { return dtmngaytao; } set { dtmngaytao = value; } } public string ghichu { get { return strghichu; } set { strghichu = value; } } #endregion #region Public Method private readonly DataAccessLayerBaseClass mDataAccess = new DataAccessLayerBaseClass(Data.ConnectionString); /// <summary> /// Lấy toàn bộ dữ liệu từ bảng tblhoadontra /// </summary> /// <returns>DataTable</returns> public DataTable GetAll() { string strFun = "fn_tblhoadontra_getall"; try { DataSet dstblhoadontra = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure); return dstblhoadontra.Tables[0]; } catch { return null; } } /// <summary> /// Hàm lấy tblhoadontra theo mã /// </summary> /// <returns>Trả về objtblhoadontra </returns> public tblhoadontra GetByID(string strid) { tblhoadontra objtblhoadontra = new tblhoadontra(); string strFun = "fn_tblhoadontra_getobjbyid"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("id", NpgsqlDbType.Varchar); prmArr[0].Value = strid; DataSet dstblhoadontra = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); if ((dstblhoadontra != null) && (dstblhoadontra.Tables.Count > 0)) { if (dstblhoadontra.Tables[0].Rows.Count > 0) { DataRow dr = dstblhoadontra.Tables[0].Rows[0]; objtblhoadontra.id = dr["id"].ToString(); objtblhoadontra.id_khachhang = dr["id_khachhang"].ToString(); try { objtblhoadontra.ngaytao = Convert.ToDateTime(dr["ngaytao"].ToString()); } catch { objtblhoadontra.ngaytao = new DateTime(1900, 1, 1); } objtblhoadontra.ghichu = dr["ghichu"].ToString(); return objtblhoadontra; } return null; } return null; } catch { return null; } } /// <summary> /// Thêm mới dữ liệu vào bảng: tblhoadontra /// </summary> /// <param name="obj">objtblhoadontra</param> /// <returns>Trả về trắng: Thêm mới thành công; Trả về khác trắng: Thêm mới không thành công</returns> public string Insert(tblhoadontra objtblhoadontra) { string strProc = "fn_tblhoadontra_insert"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[5]; prmArr[0] = new NpgsqlParameter("id", NpgsqlDbType.Varchar); prmArr[0].Value = objtblhoadontra.strid; prmArr[1] = new NpgsqlParameter("id_khachhang", NpgsqlDbType.Varchar); prmArr[1].Value = objtblhoadontra.strid_khachhang; prmArr[2] = new NpgsqlParameter("ngaytao", NpgsqlDbType.Varchar); prmArr[2].Value = objtblhoadontra.ngaytao.ToString("yyyy/MM/dd HH:mm:ss"); prmArr[3] = new NpgsqlParameter("ghichu", NpgsqlDbType.Varchar); prmArr[3].Value = objtblhoadontra.strghichu; prmArr[4] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[4].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string sKQ = prmArr[4].Value.ToString().Trim(); if (sKQ.ToUpper().Equals("Add".ToUpper()) == true) return ""; return "Thêm mới dữ liệu không thành công"; } catch (Exception ex) { return "Thêm mới dữ liệu không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Cập nhật dữ liệu vào bảng: tblhoadontra /// </summary> /// <param name="obj">objtblhoadontra</param> /// <returns>Trả về trắng: Cập nhật thành công; Trả về khác trắng: Cập nhật không thành công</returns> public string Update(tblhoadontra objtblhoadontra) { string strProc = "fn_tblhoadontra_Update"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[4]; prmArr[0] = new NpgsqlParameter("id", NpgsqlDbType.Varchar); prmArr[0].Value = objtblhoadontra.strid; prmArr[1] = new NpgsqlParameter("id_khachhang", NpgsqlDbType.Varchar); prmArr[1].Value = objtblhoadontra.strid_khachhang; prmArr[2] = new NpgsqlParameter("ghichu", NpgsqlDbType.Varchar); prmArr[2].Value = objtblhoadontra.strghichu; prmArr[3] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[3].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string sKQ = prmArr[3].Value.ToString().Trim(); if (sKQ.ToUpper().Equals("Update".ToUpper()) == true) return ""; return "Cập nhật dữ liệu không thành công"; } catch (Exception ex) { return "Cập nhật dữ liệu không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Xóa dữ liệu từ bảng tblhoadontra /// </summary> /// <returns></returns> public string Delete(string strid) { string strProc = "fn_tblhoadontra_delete"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[2]; prmArr[0] = new NpgsqlParameter("id", NpgsqlDbType.Varchar); prmArr[0].Value = strid; prmArr[1] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[1].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string KQ = prmArr[1].Value.ToString().Trim(); if (KQ.ToUpper().Equals("Del".ToUpper()) == true) return ""; return "Xóa dữ liệu không thành công"; } catch (Exception ex) { return "Xóa dữ liệu không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Hàm lấy tất cả dữ liệu trong bảng tblhoadontra /// </summary> /// <returns>Trả về List<<tblhoadontra>></returns> public List<tblhoadontra> GetList() { List<tblhoadontra> list = new List<tblhoadontra>(); string strFun = "fn_tblhoadontra_getall"; try { DataSet dstblhoadontra = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure); if ((dstblhoadontra != null) && (dstblhoadontra.Tables.Count > 0)) { for (int i = 0; i < dstblhoadontra.Tables[0].Rows.Count; i++) { tblhoadontra objtblhoadontra = new tblhoadontra(); DataRow dr = dstblhoadontra.Tables[0].Rows[i]; objtblhoadontra.id = dr["id"].ToString(); objtblhoadontra.id_khachhang = dr["id_khachhang"].ToString(); try { objtblhoadontra.ngaytao = Convert.ToDateTime(dr["ngaytao"].ToString()); } catch { objtblhoadontra.ngaytao = new DateTime(1900, 1, 1); } objtblhoadontra.ghichu = dr["ghichu"].ToString(); list.Add(objtblhoadontra); } return list; } return null; } catch { return null; } } /// <summary> /// Hàm lấy danh sách objtblhoadontra /// </summary> /// <param name="recperpage">Số lượng bản ghi kiểu integer</param> /// <param name="pageindex">Số trang kiểu integer</param> /// <returns>Trả về List<<tblhoadontra>></returns> public List<tblhoadontra> GetListPaged(int recperpage, int pageindex) { List<tblhoadontra> list = new List<tblhoadontra>(); string strFun = "fn_tblhoadontra_getpaged"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[2]; prmArr[0] = new NpgsqlParameter("recperpage", NpgsqlDbType.Integer); prmArr[0].Value = recperpage; prmArr[1] = new NpgsqlParameter("pageindex", NpgsqlDbType.Integer); prmArr[1].Value = pageindex; DataSet dstblhoadontra = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); if ((dstblhoadontra != null) && (dstblhoadontra.Tables.Count > 0)) { for (int i = 0; i < dstblhoadontra.Tables[0].Rows.Count; i++) { tblhoadontra objtblhoadontra = new tblhoadontra(); DataRow dr = dstblhoadontra.Tables[0].Rows[i]; objtblhoadontra.id = dr["id"].ToString(); objtblhoadontra.id_khachhang = dr["id_khachhang"].ToString(); try { objtblhoadontra.ngaytao = Convert.ToDateTime(dr["ngaytao"].ToString()); } catch { objtblhoadontra.ngaytao = new DateTime(1900, 1, 1); } objtblhoadontra.ghichu = dr["ghichu"].ToString(); list.Add(objtblhoadontra); } return list; } return null; } catch { return null; } } /// <summary> /// Hàm lấy danh sách objtblhoadontra /// </summary> /// <param name="recperpage">Số lượng bản ghi kiểu integer</param> /// <param name="pageindex">Số trang kiểu integer</param> /// <returns>Trả về List<<tblhoadontra>></returns> public DataTable GetDataTablePaged(int recperpage, int pageindex) { string strFun = "fn_tblhoadontra_getpaged"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[2]; prmArr[0] = new NpgsqlParameter("recperpage", NpgsqlDbType.Integer); prmArr[0].Value = recperpage; prmArr[1] = new NpgsqlParameter("pageindex", NpgsqlDbType.Integer); prmArr[1].Value = pageindex; DataSet dstblhoadontra = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); return dstblhoadontra.Tables[0]; } catch { return null; } } /// <summary> /// Hàm tìm kiếm hóa đơn trả lại hàng /// </summary> /// <param name="skeyword">Từ khóa (Tên khách hàng, dt, ghichu, diachi)</param> /// <param name="stungay">Từ ngày kiểu string format: yyyy/MM/dd</param> /// <param name="sdengay">Đến ngày kiểu string format: yyyy/MM/dd</param> /// <returns>DataTable</returns> public DataTable Filter(string skeyword, string stungay, string sdengay) { tblhoadonban objtblhoadonban = new tblhoadonban(); string strFun = "fn_tblhoadontra_filter"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[3]; prmArr[0] = new NpgsqlParameter("keyword", NpgsqlDbType.Varchar); prmArr[0].Value = skeyword; prmArr[1] = new NpgsqlParameter("tungay", NpgsqlDbType.Varchar); prmArr[1].Value = stungay; prmArr[2] = new NpgsqlParameter("dengay", NpgsqlDbType.Varchar); prmArr[2].Value = sdengay; DataSet dstblhoadonban = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); return dstblhoadonban.Tables[0]; } catch { return null; } } #endregion } }
using Emanate.Core.Configuration; namespace Emanate.Delcom.Admin.Devices { public partial class DelcomDeviceManagerView { private DelcomDeviceManagerViewModel viewModel; public DelcomDeviceManagerView() { InitializeComponent(); } public override async void SetTarget(IConfiguration moduleConfiguration) { var config = (DelcomConfiguration)moduleConfiguration; viewModel = new DelcomDeviceManagerViewModel(config); await viewModel.Initialize(); DataContext = viewModel; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace CTCT.Components.MyLibrary { /// <summary> /// Base class for MyLibrary /// </summary> [DataContract] [Serializable] public class BaseLibrary : Component { /// <summary> /// Gets or sets the id /// </summary> [DataMember(Name = "id", EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// Gets or sets the created date /// </summary> [DataMember(Name = "created_date", EmitDefaultValue = false)] public string CreatedDate { get; set; } /// <summary> /// Gets or sets the modified date /// </summary> [DataMember(Name = "modified_date", EmitDefaultValue = false)] public string ModifiedDate { get; set; } /// <summary> /// Gets or sets the name of the library item /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BarinakProjesi.DATA.Context { public class HayvanCinsleri { [Key] public int id { get; set; } [Display(Name = "Hayvanın Cinsi")] public string hayvan_cinsi { get; set; } [Display(Name = "Cinsin Genel Özellikleri")] public string cinsin_genel_ozellikleri { get; set; } [Display(Name = "Hayvan Türü")] public int hayvan_tur_id { get; set; } [ForeignKey("hayvan_tur_id")] public virtual HayvanTurleri hayvan_turu { get; set; } public virtual List<KayitliHayvanlar> kayitli_hayvanlar { get; set; } } }
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hiraya.Domain.MongoDBCollections.Entities { /// <summary> /// Individual / Business Accounts of tax paying entity /// </summary> public class TaxpayerAccount { [BsonId] public ObjectId Id { get; set; } public string TaxIdentityNumber { get; set; } } }
using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Executor.Console.Executors; using Executor.Console.Util; namespace Executor.Console.Job { public class ParentJob : VoidJob { private readonly JobExecutor _executor; private readonly string _name; public ParentJob(JobExecutor executor, string name) { _executor = executor; _name = name; } protected override async Task Execute() { Logger.Log($"{this} Starting"); var childJob = new ChildJob(_name); await _executor.SubmitJob(childJob).ConfigureAwait(false); Logger.Log($"{this} Ending"); } public override string ToString() { return $"ParentJob({_name})"; } } }