text
stringlengths
13
6.01M
using SnowProCorp.DAL; 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 SnowProCorp.Factory { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void generateData_Click(object sender, EventArgs e) { var randomizer = new Random(); using (ProductionContext ctx = new ProductionContext()) { var years = new int[] { 2012, 2013, 2014 }; var factories = ctx.ProductionFactories.ToList(); var types = ctx.ProducedItemsTypes.ToList(); var colors = new string[] { "red", "blue", "green", "orange", "purple", "pink", "black", "white", "cyan", "brown", "grey", "yellow" }; var colorsCount = colors.Count(); var orderes = new string[] { "john", "joe", "sarah", "kristen", "hannah", "michael", "matthew", "joshua" }; var addresses = new string[] { "3455 rue durocher montreal", "Parc national du Mercantour, 04400 Uvernet-Fours, France", "Mont-Tremblant, QC, Canada", "4573 Chateau Boulevard Whistler, BC V0N 1B4, Canada", "2 Mount Allan Drive Kananaskis, AB T0L 2H0, Canada" }; var statuses = new ShipmentStatus[] { ShipmentStatus.Delivered, ShipmentStatus.InPreparation, ShipmentStatus.Lost, ShipmentStatus.OrderReceived, ShipmentStatus.PickepUp }; foreach (var year in years) { for (var month = 1; month < 13; month++) { if (year == DateTime.Now.Year && month > DateTime.Now.Month) break; var numberOfProducedItemsForMonth = randomizer.Next(0, 1000); for (var i = 0; i < numberOfProducedItemsForMonth; i++) { var productionDate = new DateTime(year, month, randomizer.Next(1, 28)); if (productionDate > DateTime.Now) productionDate = DateTime.Now; ctx.ProducedItems.Add(new ProducedItem() { Id = Guid.NewGuid(), ProductionDate = productionDate, Factory = factories[randomizer.Next(0, factories.Count)], Type = types[randomizer.Next(0, types.Count)], QualityOk = Convert.ToBoolean(randomizer.Next(0, 2)), Size = randomizer.Next(28, 47), Color = colors[randomizer.Next(0, colorsCount)], }); } ctx.SaveChanges(); foreach (var factory in ctx.ProductionFactories) { var numberOfDelevriesForMonth = randomizer.Next(0, 20); for (var i = 0; i < numberOfDelevriesForMonth; i++) { var numberOfItemsInShipment = randomizer.Next(0, 10); var shippedItems = ctx.ProducedItems.Where(x => x.Factory.Id == factory.Id && x.Shipment == null).Take(numberOfItemsInShipment).ToList(); var orderingDate = new DateTime(year, month, randomizer.Next(1, 28)); if (orderingDate > DateTime.Now) orderingDate = DateTime.Now; var currentShipment = new Shipment() { Items = shippedItems, Factory = factory, Id = Guid.NewGuid(), OrderedBy = orderes[randomizer.Next(0, orderes.Length)], OrderingDate = orderingDate, Address = addresses[randomizer.Next(0, addresses.Length)], Status = statuses[randomizer.Next(0, statuses.Length)] }; if (currentShipment.Status >= ShipmentStatus.PickepUp) currentShipment.PickedUpDate = orderingDate == DateTime.Now ? DateTime.Now : currentShipment.OrderingDate.AddDays(1); if (currentShipment.Status >= ShipmentStatus.Delivered && ShipmentStatus.Lost != currentShipment.Status) currentShipment.DeliveredDate = orderingDate == DateTime.Now ? DateTime.Now : currentShipment.OrderingDate.AddDays(randomizer.Next(0, 15)); ; ctx.Shipments.Add(currentShipment); shippedItems.ForEach(x => x.Shipment = currentShipment); } } ctx.SaveChanges(); } } ctx.SaveChanges(); } } private void btnItinitiateSystem_Click(object sender, EventArgs e) { using (ProductionContext ctx = new ProductionContext()) { ctx.ProducedItemsTypes.Add(new ProducedItemType() { Title = "Ski" }); ctx.ProducedItemsTypes.Add(new ProducedItemType() { Title = "Snowboard" }); ctx.ProducedItemsTypes.Add(new ProducedItemType() { Title = "Snowblade" }); ctx.ProducedItemsTypes.Add(new ProducedItemType() { Title = "Ski Competition" }); ctx.ProducedItemsTypes.Add(new ProducedItemType() { Title = "Ski Double Parabolique" }); ctx.ProductionFactories.Add(new ProductionFactory() { Name = "DORVAL", Address = "1695 Av 55E, Dorval QC H9P 2W3", ProductionLines = 0 }); ctx.ProductionFactories.Add(new ProductionFactory() { Name = "MONT TREMBLANT", Address = "1030 Emond Rue, Mont-Tremblant QC J8E 2M5", ProductionLines = 3 }); ctx.ProductionFactories.Add(new ProductionFactory() { Name = "CALGARY", Address = "14-3919 Richmond Rd SW, Calgary AB T3E 4P2", ProductionLines = 10 }); ctx.SaveChanges(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class TextMovement : MonoBehaviour { public TMP_InputField inputField; public GameController controller; RectTransform rectTransform; float startingXCoordinate; float startingYCoordinate; [HideInInspector] public float currentYCoordinate; [HideInInspector] public float fontSize; [HideInInspector] public float fontScale; [HideInInspector] public float numberOfMovements; //float startingText; //int height; //[HideInInspector] public int adjustForExtraSpace; void Start()//Awake() { rectTransform = GetComponent<RectTransform>(); TextMeshProUGUI displayText = GetComponent<TextMeshProUGUI>(); fontScale = rectTransform.localScale.y; fontSize = displayText.fontSize * fontScale;//textBox.rectTransform.localScale; int numberOfLines = controller.roomNavigation.currentRoom.description.Split('\n').Length + 1;//displayText.text.Split('\n').Length;//controller.actionLogLines();// numberOfMovements = numberOfLines; for (int i = 0; i < controller.roomNavigation.currentRoom.exits.Length; i++) { //print(controller.roomNavigation.currentRoom.exits[i].exitDescription); if(controller.roomNavigation.currentRoom.exits[i].exitDescription != "") numberOfLines += controller.roomNavigation.currentRoom.exits[i].exitDescription.Split('\n').Length; //print(numberOfLines); //print(controller.roomNavigation.currentRoom.exits[i].exitDescription); } //print(numberOfLines); float textOffset = 0; if (numberOfLines > 3) textOffset = fontSize * (numberOfLines - 3); startingXCoordinate = rectTransform.anchoredPosition.x; startingYCoordinate = rectTransform.anchoredPosition.y + textOffset - fontSize * numberOfLines; //print(rectTransform.anchoredPosition.y); //print(startingYCoordinate); currentYCoordinate = rectTransform.anchoredPosition.y; //print(fontSize); //print(numberOfLines); //print(startingXCoordinate); //print(startingYCoordinate); //RectTransform temp = GetComponent<RectTransform>(); //float height = temp.rect.height; //controller = GetComponent<GameController>(); //print(controller); //inputField.onEndEdit.AddListener(ChangeYLocation); } public void ChangeYLocation()//string ignore) { //print(controller.change); //RectTransform rectTransform1 = GetComponent<RectTransform>(); int numberOfLines = controller.displayText.text.Split('\n').Length; //print(controller.displayText.text); //print(numberOfLines); numberOfMovements = numberOfLines; currentYCoordinate = startingYCoordinate + numberOfLines * fontSize; //print(adjustForExtraSpace); //print(rectTransform1.sizeDelta); rectTransform.anchoredPosition = new Vector2(startingXCoordinate, currentYCoordinate); //rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, 123.5f - 15 * 4f + numberOfLines * 15f); //- adjustForExtraSpace); //print(rectTransform1.sizeDelta); //rectTransform1.sizeDelta = new Vector2(rectTransform1.sizeDelta.x, height + numberOfLines * 15f/2f); //rectTransform1.sizeDelta = new Vector2(rectTransform1.rect.width, (height - 15 * 4f + numberOfLines * 15f)/2); //print(rectTransform1.sizeDelta); //rectTransform1.sizeDelta = new Vector2(0, (numberOfLines * 15f) / 2); //print((height - 15 * 4f + numberOfLines * 15f) / 2); //rectTransform1.rect.Set(rectTransform1.rect.x, rectTransform1.rect.y, rectTransform1.rect.width, (height - 15 * 4f + numberOfLines * 15f) / 2f); //rectTransform1.ForceUpdateRectTransforms(); /*if(controller.change == 0) { rectTransform1.anchoredPosition = new Vector2(rectTransform1.anchoredPosition.x, rectTransform1.anchoredPosition.y + 30); } else if(controller.change == 1) { rectTransform1.anchoredPosition = new Vector2(rectTransform1.anchoredPosition.x, rectTransform1.anchoredPosition.y + 45); }*/ } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace SFP.SIT.SERV.Model.SOL { public class SolBuscarMdl { public long FolioIni { get; set; } public long FolioFin { get; set; } [DataType(DataType.Date)] public DateTime? FecIngresoIni { get; set; } [DataType(DataType.Date)] public DateTime? FecIngresoFin { get; set; } [DataType(DataType.Date)] public DateTime? FecConcIni { get; set; } [DataType(DataType.Date)] public DateTime? FecConcFin { get; set; } [DataType(DataType.Date)] public DateTime? FecRespIni { get; set; } [DataType(DataType.Date)] public DateTime? FecRespFin { get; set; } public Int32 Periodo{ get; set; } public Int32 SolicitudEstado { get; set; } public Int32 SolicitudTipo { get; set; } public String Descripcion { get; set; } public Int32 ProcesoTipo { get; set; } public Int32 Area { get; set; } public String Areas { get; set; } public Int32 Accion { get; set; } /* ---------------------------------- */ public Int32 perClave { get; set; } public Int32 araClave { get; set; } public Int32 usrclave { get; set; } public Int32 consClave { get; set; } public Dictionary<int, int> dicUsrPer { get; set; } public SolBuscarMdl() { } } }
using System.Xml; using System.Xml.Serialization; namespace TestTask.DataClasses { public class Hall { [XmlAttribute] public string plan { get; set; } [XmlText] public string Value { get; set; } } }
/* * Created by SharpDevelop. * User: Admin * Date: 22.06.2012 * Time: 21:34 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using TSF.UmlToolingFramework.Wrappers.EA; using UML = TSF.UmlToolingFramework.UML; using UML_SM = TSF.UmlToolingFramework.UML.StateMachines.BehaviorStateMachines; using UTF_EA = TSF.UmlToolingFramework.Wrappers.EA; namespace TSF.UmlToolingFramework.Wrappers.EA.BehaviorStateMachines { /// <summary> /// Description of Event. /// </summary> public class Event : UTF_EA.ElementWrapper , UML.CommonBehaviors.Communications.Event { string name; public Event(UTF_EA.Model model, global::EA.Element wrappedElement) : base(model,wrappedElement) { } } }
using System; using System.Collections.Generic; using System.Text; namespace System.Data.Linq.SqlClient { /// <summary> /// Annotation which indicates that the given node will cause a compatibility problem /// for the indicated set of providers. /// </summary> internal class SqlServerCompatibilityAnnotation : SqlNodeAnnotation { SqlProvider.ProviderMode[] providers; /// <summary> /// Constructor /// </summary> /// <param name="message">The compatibility message.</param> /// <param name="providers">The set of providers this compatibility issue applies to.</param> internal SqlServerCompatibilityAnnotation(string message, params SqlProvider.ProviderMode[] providers) : base(message) { this.providers = providers; } /// <summary> /// Returns true if this annotation applies to the specified provider. /// </summary> internal bool AppliesTo(SqlProvider.ProviderMode provider) { foreach (SqlProvider.ProviderMode p in providers) { if (p == provider) { return true; } } return false; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Data; using System.Text; using System.Drawing; using TLF.Framework.BaseFrame; using TLF.Framework.Collections; namespace LipControl { public partial class LipGroup : DevExpress.XtraEditors.XtraUserControl { public LipGroup() { InitializeComponent(); } private int cnt; private string LayerCode; private string frDate; private string toDate; private string setUserGroup; /// <summary> /// 일괄 초기화 여부를 설정합니다. /// </summary> [Category("SEMCO")] [Description("설비명을 설정합니다."), Browsable(true)] public string GroupName { get { return ButtonTitle.Text; } set { ButtonTitle.Text = value; } } [Category("SEMCO")] [Description("액조값을 설정합니다."), Browsable(true)] public string Title { get { return textLiqGroup.Text; } set { textLiqGroup.Text = value; } } [Category("SEMCO")] [Description("Detail 컨트롤 수를 받는다."), Browsable(true)] public int ConCount { get { return cnt; } set { cnt = value; } } [Category("SEMCO")] [Description("액조코드 값을 설정합니다."), Browsable(true)] public string LiqLayerCode { get { return LayerCode; } set { LayerCode = value; } } [Category("SEMCO")] [Description("FromDate값 설정"), Browsable(true)] public string FromDate { get { return frDate; } set { frDate = value; } } [Category("SEMCO")] [Description("ToDate값 설정"), Browsable(true)] public string ToDate { get { return toDate; } set { toDate = value; } } [Category("SEMCO")] [Description("UserGroup 설정"), Browsable(true)] public string UserGroup { get { return setUserGroup; } set { setUserGroup = value; } } public void LiqDisplay(string[] title, string[] UCL, string[] LCL, string[] Value, string[] AlarmFlag) { int iOneWidth = 0; if (ConCount < 3) { iOneWidth= panelControl1.Width / 3; } else { iOneWidth = panelControl1.Width / ConCount; } int iOneHeight = panelControl1.Height - 5; int pnlWidth = panelControl1.Width; int iFirstPosition = 0; int iPos = 0; for (int i = 0; i < cnt; i++) { LipDisplayControl tmpLst = new LipDisplayControl(); this.panelControl1.Controls.Add(tmpLst); iPos = tmpLst.Width; //if (i == 0) //{ // tmpLst.Location = new Point(3, 5); //} //else //{ // //tmpLst.Location = new Point(iPos * i, 5); // //ehhong modify // tmpLst.Location = new Point(iOneWidth * i, 5); //} //가운데로 배치 하기 위해서 ( 갯수가 3개 이하일경우 처음 위치 조정) if (ConCount == 1) { iFirstPosition = (pnlWidth - tmpLst.Width) / 2; tmpLst.Location = new Point(iFirstPosition, 3); } else if (ConCount == 2) { iFirstPosition = (pnlWidth - tmpLst.Width * 2) / 2; tmpLst.Location = new Point(iOneWidth * i + iFirstPosition, 3); } else { tmpLst.Location = new Point(iOneWidth * i-1, 3); } tmpLst.Size = new Size(iOneWidth, iOneHeight); tmpLst.Title = title[i]; tmpLst.UCL = UCL[i]; tmpLst.LCL = LCL[i]; tmpLst.AnalysisValue = Value[i]; tmpLst.ValueType = AlarmFlag[i]; } } private void ButtonTitle_Click(object sender, EventArgs e) { LinkEventParams linkParam = new LinkEventParams(); linkParam["LayerCode"] = LayerCode; linkParam["FromDate"] = frDate; linkParam["ToDate"] = toDate; linkParam["GroupName"] = setUserGroup; (this.ParentForm as UIFrame).ExecuteUI("Liq03", linkParam); } } }
using Aqueduct.SitecoreLib.Domain; namespace Aqueduct.SitecoreLib.DataAccess.Maps { public class FileMap : Map<File> { public override string TemplatePath { get { return ""; } } public override bool SkipTemplateChecking { get { return true; } } } }
using UnityEngine; public class PrefabTestCode : MonoBehaviour { public GameObject prefab_map; public GameObject prefab_parent; GameObject[,] map_instant = new GameObject[5, 1]; // Use this for initialization void Start () { Debug.Log("PrefabTestCode: start"); for (int i = 0; i < 5;i++){ int width = 70 * i; map_instant[i, 0] = (GameObject)Instantiate( prefab_map, new Vector3(prefab_map.transform.position.x + width, prefab_map.transform.position.y, 0), Quaternion.identity ); map_instant[i, 0].transform.SetParent(prefab_parent.transform); } Debug.Log("PrefabTestCode: Were my Prefabs created?"); } }
/** MIT LICENSE * Copyright (c) 2017 Koudura Ninci @True.Inc * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **/ using System; using System.Collections.Generic; using System.Text; namespace Fornax.Net.Util.Text { class Unicode { internal static char[] ToCharArray(int[] v1, int v2, int v3) { //if (count < 0) { // throw new System.ArgumentException(); //} //int countThreashold = 1024; // If the number of chars exceeds this, we count them instead of allocating count * 2 //if (count > countThreashold) { // arrayLength = 0; // for (int r = offset, e = offset + count; r < e; ++r) { // arrayLength += codePoints[r] < 0x010000 ? 1 : 2; // } // if (arrayLength < 1) { // arrayLength = count * 2; // } //} //// Initialize our array to our exact or oversized length. //// It is now safe to assume we have enough space for all of the characters. //char[] chars = new char[arrayLength]; //int w = 0; //for (int r = offset, e = offset + count; r < e; ++r) { // int cp = codePoints[r]; // if (cp < 0 || cp > 0x10ffff) { // throw new System.ArgumentException(); // } // if (cp < 0x010000) { // chars[w++] = (char)cp; // } else { // chars[w++] = (char)(LEAD_SURROGATE_OFFSET_ + (cp >> LEAD_SURROGATE_SHIFT_)); // chars[w++] = (char)(TRAIL_SURROGATE_MIN_VALUE + (cp & TRAIL_SURROGATE_MASK_)); // } //} // var result = new char[w]; // Array.Copy(chars, result, w); return null; } } }
#region License /* Copyright (c) 2009 - 2013 Fatjon Sakiqi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion namespace Cloo { using System; using System.Collections.Generic; using Cloo.Bindings; ///<summary> ///Represents an OpenCL 2D image. ///</summary> ///<seealso cref = "ComputeImage"/> public class ComputeImage2D : ComputeImage { #region Constructors /* ///<summary> /// Creates a new <see cref="ComputeImage2D"/> from a <c>Bitmap</c>. ///</summary> ///<para name = "context"> A valid <see cref = "ComputeContext"/> in which the <see cref = "ComputeImage 2 D"/> is created. </param> ///<para name = "flags"> A bit-field that is used to specify allocation and usage information about the <see cref = "ComputeImage 2 D"/>. </param> /// <param name="bitmap"> The bitmap to use. </param> /// <remarks> Note that only bitmaps with <c>Format32bppArgb</c> pixel format are currently supported. </remarks> public ComputeImage2D(ComputeContext context, ComputeMemoryFlags flags, Bitmap bitmap) :base(context, flags) { unsafe { if(bitmap.PixelFormat != PixelFormat.Format32bppArgb) throw new ArgumentException("Pixel format not supported."); //ComputeImageFormat format = Tools.ConvertImageFormat(bitmap.PixelFormat); ComputeImageFormat format = new ComputeImageFormat(ComputeImageChannelOrder.Bgra, ComputeImageChannelType.UnsignedInt8); BitmapData bitmapData = bitmap.LockBits(new Rectangle(new Point(), bitmap.Size), ImageLockMode.ReadOnly, bitmap.PixelFormat); try { ComputeErrorCode error = ComputeErrorCode.Success; Handle = CL12.CreateImage2D( context.Handle, flags, &format, new IntPtr(bitmap.Width), new IntPtr(bitmap.Height), new IntPtr(bitmapData.Stride), bitmapData.Scan0, &error); ComputeException.ThrowOnError(error); } finally { bitmap.UnlockBits(bitmapData); } Init(); } }*/ ///<summary> ///Creates a new <see cref = "ComputeImage 2 D"/>. ///</summary> ///<para name = "context"> A valid <see cref = "ComputeContext"/> in which the <see cref = "ComputeImage 2 D"/> is created. </param> ///<para name = "flags"> A bit-field that is used to specify allocation and usage information about the <see cref = "ComputeImage 2 D"/>. </param> ///<param name = "format"> A structure that describes the format properties of the <see cref = "ComputeImage 2 D"/>. </param> ///<param name = "width"> The width of the <see cref = "ComputeImage 2 D"/> in pixels. </param> ///<param name = "height"> The height of the <see cref = "ComputeImage 2 D"/> in pixels. </param> ///<para name = "rowPitch">> ​​The size in bytes of each row of elements of the <see cref = "ComputeImage2D"/>. If <paramref name = "rowPitch"/> is zero, OpenCL will compute the proper value based on <see cref = "ComputeImage.Width"/> and <see cref = "ComputeImage.ElementSize"/>. </param> ///<param name = "data"> The data to initialize the <see cref = "ComputeImage 2 D"/>. Can be <c> IntPtr.Zero </c>. </param> public ComputeImage2D(ComputeContext context, ComputeMemoryFlags flags, ComputeImageFormat format, int width, int height, long rowPitch, IntPtr data) : base(context, flags) { ComputeErrorCode error = ComputeErrorCode.Success; Handle = CL12.CreateImage2D(context.Handle, flags, ref format, new IntPtr(width), new IntPtr(height), new IntPtr(rowPitch), data, out error); ComputeException.ThrowOnError(error); Init(); } private ComputeImage2D(CLMemoryHandle handle, ComputeContext context, ComputeMemoryFlags flags) : base(context, flags) { Handle = handle; Init(); } #endregion #region Public methods ///<summary> ///Creates a new <see cref = "ComputeImage 2 D"/> from an OpenGL renderbuffer object. ///</summary> ///<param name = "context"> A <see cref = "ComputeContext"/> with enabled CL / GL sharing. </param> ///Only <c> ComputeMemoryFlags.ReadOnly </c>, <c> ComputeMemoryFlags.WriteOnly </c>, where <param name = "flags"> A bit-field that is used to specify usage information about the < / c> and <c> ComputeMemoryFlags.ReadWrite </c> are allowed.. </param> ///<param name = "renderbufferId"> The OpenGL renderbuffer object id to use. </param> ///<returns> The created <see cref = "ComputeImage2D"/>. </returns> public static ComputeImage2D CreateFromGLRenderbuffer(ComputeContext context, ComputeMemoryFlags flags, int renderbufferId) { ComputeErrorCode error = ComputeErrorCode.Success; CLMemoryHandle image = CL12.CreateFromGLRenderbuffer(context.Handle, flags, renderbufferId, out error); ComputeException.ThrowOnError(error); return new ComputeImage2D(image, context, flags); } ///<summary> ///Creates a new <see cref = "ComputeImage 2 D"/> from an OpenGL 2D texture object. ///</summary> ///<param name = "context"> A <see cref = "ComputeContext"/> with enabled CL / GL sharing. </param> ///Only <c> ComputeMemoryFlags.ReadOnly </c>, <c> ComputeMemoryFlags.WriteOnly </c>, where <param name = "flags"> A bit-field that is used to specify usage information about the < / c> and <c> ComputeMemoryFlags.ReadWrite </c> are allowed.. </param> ///<Param name = "textureTarget"> One of the following values:.. GL_TEXTURE_2D, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, or GL_TEXTURE_RECTANGLE Using GL_TEXTURE_RECTANGLE for texture_target requires OpenGL 3.1 Alternatively, GL_TEXTURE_RECTANGLE_ARB may be specified if the OpenGL extension GL_ARB_texture_rectangle is supported. </param> ///<param name = "mipLevel"> The mipmap level of the OpenGL 2D texture object to be used. </param> ///<param name = "textureId"> The OpenGL 2D texture object id to use. </param> ///<returns> The created <see cref = "ComputeImage2D"/>. </returns> public static ComputeImage2D CreateFromGLTexture2D(ComputeContext context, ComputeMemoryFlags flags, int textureTarget, int mipLevel, int textureId) { ComputeErrorCode error = ComputeErrorCode.Success; CLMemoryHandle image = CL12.CreateFromGLTexture2D(context.Handle, flags, textureTarget, mipLevel, textureId, out error); ComputeException.ThrowOnError(error); return new ComputeImage2D(image, context, flags); } ///<summary> ////> <See cref = "ComputeImageFormat"/> s in a <see cref = "ComputeContext"/> ///</summary> ///<para name = "context"> The <see cref = "ComputeContext"/> for which the collection of <see cref = "ComputeImageFormat"/> s is queried. </param> ///<param name = "flags"> The <c> ComputeMemoryFlags </c> for which the collection of <see cref = "ComputeImageFormat"/> s is queried. </param> ///<returns> The collection of the required <see cref = "ComputeImageFormat"/> s. </returns> public static ICollection<ComputeImageFormat> GetSupportedFormats(ComputeContext context, ComputeMemoryFlags flags) { return GetSupportedFormats(context, flags, ComputeMemoryType.Image2D); } #endregion } }
using consoleapp.Domain; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace testes { [TestClass] public class FrameTests { [TestMethod] public void NumeroArremessosValido() { // Arrange var frame1 = new Frame(); // Act frame1.DefinirQuantArremessos(2); // Assert Assert.IsTrue(frame1.Valido); } [TestMethod] public void NumeroArremessosInvalido() { // Arrange var frame1 = new Frame(); var frame2 = new Frame(); // Act frame1.DefinirQuantArremessos(0); frame2.DefinirQuantArremessos(1); // Assert Assert.IsFalse(frame1.Valido); Assert.IsFalse(frame2.Valido); } [TestMethod] public void QuantidadePinosPorFrameValido() { // Arrange var frame1 = new Frame(); // Act frame1.DefinirQuantPinosPorFrame(10); // Assert Assert.IsTrue(frame1.Valido); } [TestMethod] public void QuantidadePinosPorFrameInvalido() { // Arrange var frame1 = new Frame(); var frame2 = new Frame(); // Act frame1.DefinirQuantArremessos(0); frame2.DefinirQuantArremessos(11); // Assert Assert.IsFalse(frame1.Valido); Assert.IsFalse(frame2.Valido); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LevelManager : MonoBehaviour { public static LevelManager instance; public float waitToLoad = 1; public string nextlevel; public bool isPaused; public int currentStage = 1; public GameObject camera; public float shiftSpeed; public List<GameObject> enemiesStage1 = new List<GameObject>(); public List<GameObject> enemiesStage2 = new List<GameObject>(); public List<GameObject> enemiesStage3 = new List<GameObject>(); public List<GameObject> enemiesStage4 = new List<GameObject>(); public List<GameObject> enemiesStage5 = new List<GameObject>(); public Transform stage1; public Transform stage2; public Transform stage3; public Transform stage4; public Transform stage5; public bool loadNext = false; public bool bossDed = false; public bool destroyBullets = false; private void Awake() { instance = this; } // Start is called before the first frame update void Start() { Time.timeScale = 1f; PlayerControl.instance.canMove = true; //PlayerControl.instance.transform.position = new Vector3(0, 0, 0); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { PauseUnpause(); } if (currentStage == 1) { camera.transform.position = Vector3.MoveTowards(camera.transform.position, stage1.position, shiftSpeed * Time.deltaTime); if(camera.transform.position != stage1.position) { destroyBullets = true; } else { destroyBullets = false; } for (int i = 0; i < enemiesStage1.Count; i++) { if (enemiesStage1[i] == null) { enemiesStage1.RemoveAt(i); i--; } } if (enemiesStage1.Count == 0) { currentStage++; } } if (currentStage == 2) { if (camera.transform.position != stage2.position) { destroyBullets = true; } else { destroyBullets = false; } camera.transform.position = Vector3.MoveTowards(camera.transform.position, stage2.position, shiftSpeed * Time.deltaTime); for (int i = 0; i < enemiesStage2.Count; i++) { if (enemiesStage2[i] == null) { enemiesStage2.RemoveAt(i); i--; } } if (enemiesStage2.Count == 0) { currentStage++; } } if (currentStage == 3) { if (camera.transform.position != stage3.position) { destroyBullets = true; } else { destroyBullets = false; } camera.transform.position = Vector3.MoveTowards(camera.transform.position, stage3.position, shiftSpeed * Time.deltaTime); for (int i = 0; i < enemiesStage3.Count; i++) { if (enemiesStage3[i] == null) { enemiesStage3.RemoveAt(i); i--; } } if (enemiesStage3.Count == 0) { currentStage++; } } if (currentStage == 4) { if (camera.transform.position != stage4.position) { destroyBullets = true; } else { destroyBullets = false; } camera.transform.position = Vector3.MoveTowards(camera.transform.position, stage4.position, shiftSpeed * Time.deltaTime); for (int i = 0; i < enemiesStage4.Count; i++) { if (enemiesStage4[i] == null) { enemiesStage4.RemoveAt(i); i--; } } if (enemiesStage4.Count == 0) { currentStage++; } } if (currentStage == 5) { if (camera.transform.position != stage5.position) { destroyBullets = true; } else { destroyBullets = false; } camera.transform.position = Vector3.MoveTowards(camera.transform.position, stage5.position, shiftSpeed * Time.deltaTime); for (int i = 0; i < enemiesStage5.Count; i++) { if (enemiesStage5[i] == null) { enemiesStage5.RemoveAt(i); i--; } } if (enemiesStage5.Count == 0) { StartCoroutine(LevelEnd()); } } if (bossDed) { destroyBullets = true; StartCoroutine(LevelEnd()); } } public IEnumerator LevelEnd() { loadNext = true; // PlayerControl.instance.canMove = false; UI.instance.fadeToWin = true; UI.instance.StartFadeToBlack(); yield return new WaitForSeconds(waitToLoad); //PlayerControl.instance.transform.position = new Vector3(0, 0, 0);*/ SceneManager.LoadScene(nextlevel); PlayerControl.instance.canMove = true; UI.instance.StartFadeOutBlack(); } public void PauseUnpause() { if (!isPaused) { UI.instance.pauseMenu.SetActive(true); isPaused = true; Time.timeScale = 0f; } else { UI.instance.pauseMenu.SetActive(false); isPaused = false; Time.timeScale = 1f; } } }
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 Klases { public partial class Form1 : Form { public Form1() { InitializeComponent(); } List<Guest> GuestList = new List<Guest>(); Random rnd = new Random(); #region calc double num1, num2; private void txtFirst_TextChanged(object sender, EventArgs e) { if (!double.TryParse(txtFirst.Text, out num1) && txtFirst.TextLength > 0) { MessageBox.Show("Please enter a number", "Something went wrong"); } } private void txtSecond_TextChanged(object sender, EventArgs e) { if (!double.TryParse(txtSecond.Text, out num2) && txtSecond.TextLength > 0) { MessageBox.Show("Please enter a number", "Something went wrong"); } } private void btnreg_Click(object sender, EventArgs e) { Guest oneguest = new Guest(); oneguest.SetName(txtname.Text); oneguest.SetLastName(txtlastname.Text); oneguest.SetCompany(txtcomp.Text); GuestList.Add(oneguest); listguests.Items.Add(oneguest.GetName() + " " + oneguest.GetLastName() + " " + oneguest.GetCompany()); listView1.Items.Add(oneguest.GetName() + " " + oneguest.GetLastName() + " " + oneguest.GetCompany()); txtname.Clear(); txtlastname.Clear(); txtcomp.Clear(); } private void btnPrizes_Click(object sender, EventArgs e) { foreach (Guest item in GuestList) { item.SetWinner(false); } foreach (ListViewItem item in listView1.Items) { item.BackColor = Color.White; } int index; for (int i = 0; i < rnd.Next(1, GuestList.Count + 1); i++) { index = rnd.Next(GuestList.Count); while (GuestList[index].GetWinner() == true) { index = rnd.Next(GuestList.Count); } GuestList[index].SetWinner(true); GuestList[index].SetPrize(); listView1.Items[index].BackColor = Color.LimeGreen; } MessageBox.Show("Double click your name to show what you have won", "The lottery has concluded"); } private void listguests_DoubleClick(object sender, EventArgs e) { if (listguests.SelectedIndex == -1) return; Guest item = GuestList[listguests.SelectedIndex]; MessageBox.Show(item.GetPrize().ToString()); } private void btnGo_Click(object sender, EventArgs e) { switch (combolist.Text) { case "+": MessageBox.Show((calc.Plus(num1, num2).ToString())); break; case "-": MessageBox.Show((calc.Minus(num1, num2).ToString())); break; case "*": MessageBox.Show((calc.Multiplication(num1, num2).ToString())); break; case "/": MessageBox.Show((calc.Division(num1, num2).ToString())); break; default: MessageBox.Show("An error occured", "Something went wrong"); break; } } #endregion } }
namespace WeddingRental.Models.Product.From { public class SubmitModel { public int OrderId { get; set; } } }
using System; using System.Collections.Generic; using System.Reflection; namespace Calcifer.Engine.Content.Data { internal sealed class ProviderFactory { private static Dictionary<string, Type> providers; private static ProviderFactory instance; public static ProviderFactory Instance { get { return instance ?? (instance = new ProviderFactory()); } } private ProviderFactory() { providers = new Dictionary<string, Type>(); var assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { var types = assembly.GetTypes(); foreach (Type type in types) { var customAttributes = type.GetCustomAttributes(false); foreach (var attr in customAttributes) { if (attr.GetType() != typeof (ProviderType)) continue; var providerType = attr as ProviderType; if (providerType != null) ProviderFactory.providers.Add(providerType.Name, type); break; } } } } public IContentProvider Create(string type) { return Activator.CreateInstance(ProviderFactory.providers[type]) as IContentProvider; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterviewQuestions { public class IntegerToXBase { public void ConvertToXBase(int integer, int iBase) { string result = ""; var temp = integer; if(iBase <= 0 ||integer < 0) throw new ArgumentException("bad parameter"); while (integer > 0) { result = integer%iBase + result; integer /= iBase; } Console.WriteLine("Convert integer {0} to {1} based number is {2} ", temp, iBase, result); } //bad implementation public int ConvertToXBase2(int integer, int iBase) { int result = 0; var temp = integer; if (iBase <= 0 || integer < 0) throw new ArgumentException("bad parameter"); while (integer > 0) { result = integer % iBase + result*10; //how to handle first mode remain is 0 integer /= iBase; } Console.WriteLine("Convert integer {0} to {1} based number is {2} ", temp, iBase, result); return result; } public void ConvertToXBaseByArray(int integer, int iBase) { List<int> cResult = new List<int>(); var temp = integer; while (integer > 0) { cResult.Add(integer % iBase); integer /= iBase; } Console.Write("Convert integer {0} to {1} based number is ", temp, iBase); cResult.Reverse(); foreach (int i in cResult) { Console.Write(i); } Console.WriteLine(); } public void ConvertToXBaseRecursionWrapper(int integer, int iBase) { Console.Write("Convert integer {0} to {1} based number is ", integer, iBase); ConvertToXBaseRecursion(integer, iBase); Console.WriteLine(); } public void ConvertToXBaseRecursion(int integer, int iBase) { if (iBase <= 0 || integer < 0) throw new ArgumentException("bad base"); if (integer < iBase) { Console.Write(integer); } else { ConvertToXBaseRecursion(integer / iBase, iBase); Console.Write(integer % iBase); } } static public void Test() { //Test for _integerToXBase var integerToXBase = new IntegerToXBase(); integerToXBase.ConvertToXBase(10, 2); //integerToXBase.ConvertToXBase2(10, 2); integerToXBase.ConvertToXBaseRecursionWrapper(10, 2); integerToXBase.ConvertToXBaseByArray(10, 2); Console.WriteLine(); integerToXBase.ConvertToXBase(10, 8); //integerToXBase.ConvertToXBase2(10, 8); integerToXBase.ConvertToXBaseRecursionWrapper(10, 8); integerToXBase.ConvertToXBaseByArray(10, 8); Console.WriteLine(); integerToXBase.ConvertToXBase(10, 10); integerToXBase.ConvertToXBaseRecursionWrapper(10, 10); integerToXBase.ConvertToXBaseByArray(10, 10); Console.WriteLine(); integerToXBase.ConvertToXBase(36, 16); integerToXBase.ConvertToXBaseRecursionWrapper(36, 16); integerToXBase.ConvertToXBaseByArray(36, 16); Console.WriteLine(); Console.ReadKey(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HealthDisplay : MonoBehaviour { GameObject player; SpriteRenderer renderer; public int health; private GUIStyle guiStyle = new GUIStyle(); public Sprite zero, one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen; void Start() { player = GameObject.FindWithTag("Player"); renderer = GetComponent<SpriteRenderer>(); renderer.sprite = fifteen; health = player.GetComponent<PlayerManager>().returnHealth(); } void OnGUI() { guiStyle.fontSize = 30; GUI.Label(new Rect(10, 17, 50, 20), "LIFE", guiStyle); } void Update() { health = player.GetComponent<PlayerManager>().returnHealth(); CheckHealthBar(); } void CheckHealthBar() { switch (health) { case 0: renderer.sprite = zero; break; case 1: renderer.sprite = one; break; case 2: renderer.sprite = one; break; case 3: renderer.sprite = two; break; case 4: renderer.sprite = two; break; case 5: renderer.sprite = three; break; case 6: renderer.sprite = three; break; case 7: renderer.sprite = four; break; case 8: renderer.sprite = four; break; case 9: renderer.sprite = five; break; case 10: renderer.sprite = five; break; case 11: renderer.sprite = six; break; case 12: renderer.sprite = six; break; case 13: renderer.sprite = seven; break; case 14: renderer.sprite = seven; break; case 15: renderer.sprite = eight; break; case 16: renderer.sprite = eight; break; case 17: renderer.sprite = nine; break; case 18: renderer.sprite = nine; break; case 19: renderer.sprite = ten; break; case 20: renderer.sprite = ten; break; case 21: renderer.sprite = eleven; break; case 22: renderer.sprite = eleven; break; case 23: renderer.sprite = twelve; break; case 24: renderer.sprite = twelve; break; case 25: renderer.sprite = thirteen; break; case 26: renderer.sprite = thirteen; break; case 27: renderer.sprite = fourteen; break; case 28: renderer.sprite = fourteen; break; case 29: renderer.sprite = fifteen; break; case 30: renderer.sprite = fifteen; break; default: renderer.sprite = fifteen; break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NapierBank.Database; using NapierBank.Models; using System.Collections.ObjectModel; using System.Windows.Input; using NapierBank.Commands; using System.Windows; /// <summary> /// ViewSingleTweetViewModel - Class used to setup elements for the ViewSingleTweetView ensuring the MVVM pattern is kept. /// </summary> namespace NapierBank.ViewModels { // setup variables public class ViewSingleTweetViewModel : BaseViewModel { public ObservableCollection<Tweet> TweetList { get; set; } public Tweet MessageID { get; set; } public string NewMessageID { get; set; } public string Sender { get; set; } public string Text { get; set; } public ViewSingleTweetViewModel() { NewMessageID = ""; Sender = ""; Text = ""; // Load from file. LoadFromFile load = new LoadFromFile(); if (!load.FromJsonT()) { // create new collection TweetList = new ObservableCollection<Tweet>(); } else { // create new collection TweetList = new ObservableCollection<Tweet>(load.TweetList); } } } }
using MediatR; using Microsoft.AspNetCore.SignalR; using OrderSimulator.Hubs; using OrderSimulator.Models; using System.Threading; using System.Threading.Tasks; namespace OrderSimulator.Handlers { public class OrderCreatedHandler : IPipelineBehavior<Order, Unit> { private readonly IHubContext<OrderingHub> _hubContext; public OrderCreatedHandler(IHubContext<OrderingHub> hubContext) { _hubContext = hubContext; } public async Task<Unit> Handle(Order request, CancellationToken cancellationToken, RequestHandlerDelegate<Unit> next) { await Task.Delay(250).ConfigureAwait(false); await _hubContext.Clients.All.SendAsync("order-created", request); return await next(); } } }
using System.Text; using System; using System.Collections.Generic; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using System.Net.Http; using System.Drawing; using System.Collections.ObjectModel; using System.Xml; using System.ComponentModel; using System.Reflection; namespace LinnworksAPI { public class RefundInfo { public Guid? pkRefundRowId; public String SKU; public String ItemTitle; public Boolean IsItem; public Boolean IsService; public Double Amount; public String Reason; public Boolean Actioned; public DateTime? ActionDate; public String ReturnReference; public Double? Cost; public PostSaleStatusType RefundStatus; public Boolean IgnoredValidation; public Guid? fkOrderItemRowId; public Boolean ShouldSerializeChannelReason; public String ChannelReason; public Boolean ShouldSerializeChannelReasonSec; public String ChannelReasonSec; public Boolean IsNew; } }
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 { /** Mouse_Button */ public struct Mouse_Button { /** ボタン。 */ public bool on_old; public bool on; public bool down; public bool up; /** ダウン位置。 */ public NRender2D.Pos2D<int> last_down_pos; /** アップ位置。 */ public NRender2D.Pos2D<int> last_up_pos; /** ドラッグ時間。 */ public int drag_time; /** ドラッグ方向。 */ public Vector2 drag_dir; public float drag_dir_magnitude; public Vector2 drag_dir_normalized; /** ドラッグ総移動距離。 */ public int drag_totallength; /** リセット。 */ public void Reset() { //ボタン。 this.on_old = false; this.on = false; this.down = false; this.up = false; //ダウン位置。 this.last_down_pos.Set(0,0); //アップ位置。 this.last_up_pos.Set(0,0); //ドラッグ時間。 this.drag_time = 0; //ドラッグ方向。 this.drag_dir = Vector2.zero; this.drag_dir_magnitude = 0.0f; this.drag_dir_normalized = Vector2.zero; //ドラッグ総移動距離。 this.drag_totallength = 0; } /** 設定。 */ public void Set(bool a_flag) { this.on_old = this.on; this.on = a_flag; } /** 更新。 */ public void Main(ref Mouse_Pos a_pos) { if((this.on == true)&&(this.on_old == false)){ //ダウン。 this.down = true; this.up = false; //ダウン位置。 this.last_down_pos.Set(a_pos.x,a_pos.y); //ドラッグ情報初期化。 this.drag_time = 0; this.drag_dir = Vector2.zero; this.drag_dir_magnitude = 0.0f; this.drag_dir_normalized = Vector2.zero; this.drag_totallength = 0; }else if((this.on == false)&&(this.on_old == true)){ //アップ。 this.down = false; this.up = true; //アップ位置。 this.last_up_pos.Set(a_pos.x,a_pos.y); }else{ this.down = false; this.up = false; if(this.on == true){ //ドラッグ。 if(this.drag_time < Config.MOUSE_DRAGTIME_MAX){ this.drag_time++; } this.drag_dir = new Vector2(a_pos.x - this.last_down_pos.x,a_pos.y - this.last_down_pos.y); this.drag_dir_magnitude = this.drag_dir.magnitude; this.drag_dir_normalized = this.drag_dir.normalized; //ドラッグ総移動距離。 this.drag_totallength += Mathf.Abs(a_pos.x_old - a_pos.x); } } } } }
using LuaInterface; using SLua; using System; public class Lua_UnityEngine_ObstacleAvoidanceType : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "UnityEngine.ObstacleAvoidanceType"); LuaObject.addMember(l, 0, "NoObstacleAvoidance"); LuaObject.addMember(l, 1, "LowQualityObstacleAvoidance"); LuaObject.addMember(l, 2, "MedQualityObstacleAvoidance"); LuaObject.addMember(l, 3, "GoodQualityObstacleAvoidance"); LuaObject.addMember(l, 4, "HighQualityObstacleAvoidance"); LuaDLL.lua_pop(l, 1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using System.Web.Mvc; using ExternalApplicationAgent.Models; namespace ExternalApplicationAgent.Controllers { [HubName("RTMessageHub")] public class RTMessageHub : Hub { public void Register() { PublishMessage("{\"topic\":\"welcome\"}"); } private void PublishMessage(string message) { Clients.All.onReceivedMessage(message); } } public class RTMessageNotification { public static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<RTMessageHub>(); public void InformReceivedMessage(string message) { hubContext.Clients.All.onReceivedMessage(message); } public void InformSendEmailResult(string resultMessage, EmailModel email) { string message = "{" + String.Format("\"DateTime\":\"{0}\",\"Status\":\"{1}\", \"Sender\":\"{2}\", \"Receiver\":\"{3}\", \"Subject\":\"{4}\"",DateTime.UtcNow.ToString(), resultMessage, email.senderEmail, email.receverEmail, email.subject) + "}"; hubContext.Clients.All.onSendEmailResult(message); } public void InformSendSMSResult(string resultMessage, SMSModel sms) { string message = "{" + String.Format("\"DateTime\":\"{0}\",\"Status\":\"{1}\", \"Sender\":\"{2}\", \"Receiver\":\"{3}\", \"Content\":\"{4}\"", DateTime.UtcNow.ToString(), resultMessage, sms.senderPhoneNumber, sms.receiverPhoneNumber, sms.smsContent) + "}"; hubContext.Clients.All.onSendSMSResult(message); } public void InformSendERPResult(string resultMessage, ERPModel ERPEvent) { string message = "{" + String.Format("\"DateTime\":\"{0}\",\"Status\":\"{1}\", \"equipmentId\":\"{2}\", \"equipmentName\":\"{3}\", \"eventCode\":\"{4}\", \"eventMessage\":\"{5}\"", ERPEvent.dateTimeString, resultMessage, ERPEvent.equipmentId, ERPEvent.equipmentName, ERPEvent.eventCode, ERPEvent.eventMessage) + "}"; hubContext.Clients.All.onSendERPResult(message); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AttackDragon.Configurations { public partial class Configuration { /// <summary> /// Name of <see cref="Configuration"/> file /// </summary> private const string FileName = "App.Config.Xml"; /// <summary> /// Directory to store <see cref="Configuration"/> in it /// </summary> private static string DirectoryAddress = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "//Aryan Software//AttackDragon//"; /// <summary> /// Full path of <see cref="Configuration"/> file /// </summary> private static string FullPath = DirectoryAddress + FileName; } }
using System; using System.IO; using System.Threading.Tasks; namespace Demo.DynamicCSharp.CommandLine.Providers { public class FileSourceProvider : ISourceProvider { public async Task<string> GetSourceFor(string sourceId) { var path = Path.Combine(Environment.CurrentDirectory, "Source", $"source-{sourceId}.txt"); return await Task.FromResult(File.ReadAllText(path)); } } }
 using System; using System.Net; using System.ServiceModel; using System.ServiceModel.Description; using log4net; namespace Service.Contract { /// <summary> /// A provider of channels for a client of the DVS service. /// </summary> public sealed class ClientChannelProvider : IClientChannelProvider { /// <summary> /// The device service bootstrapper. /// </summary> private readonly IDeviceServiceBootstrapper deviceServiceBootstrapper; /// <summary> /// The service endpoint. /// </summary> private readonly IPEndPoint endpoint; /// <summary> /// The logger. /// </summary> private readonly ILog log = LogManager.GetLogger(typeof(ClientChannelProvider)); /// <summary> /// Initializes a new instance of the <see cref="ClientChannelProvider" /> class. /// </summary> /// <param name="endpoint">The service endpoint.</param> /// <param name="deviceServiceBootstrapper">The device service bootstrapper.</param> public ClientChannelProvider(IPEndPoint endpoint, IDeviceServiceBootstrapper deviceServiceBootstrapper) { if (endpoint == null) { throw new ArgumentNullException(nameof(endpoint)); } if (deviceServiceBootstrapper == null) { throw new ArgumentNullException(nameof(deviceServiceBootstrapper)); } this.log.InfoFormat("The service client will look for the WST service at {0}.", endpoint); this.endpoint = endpoint; this.deviceServiceBootstrapper = deviceServiceBootstrapper; } /// <summary> /// Gets the command channel. /// </summary> /// <param name="implementation">The client implementation.</param> /// <returns> /// The command channel. /// </returns> public ICommandContract GetCommandChannel(object implementation) { if (implementation == null) { throw new ArgumentNullException(nameof(implementation)); } this.log.Debug("Creating command contract."); var binding = new NetTcpBinding { Name = "NetTcpBinding_ICommandContract", ReceiveTimeout = TimeSpan.MaxValue, SendTimeout = TimeSpan.MaxValue, OpenTimeout = TimeSpan.MaxValue, MaxReceivedMessageSize = int.MaxValue, MaxBufferSize = int.MaxValue, MaxBufferPoolSize = int.MaxValue, }; var uriBuilder = new UriBuilder { Host = this.endpoint.Address.ToString(), Path = "/Lwi/Wst/Service/Command", Port = this.endpoint.Port, Scheme = "net.tcp" }; var endpointAddress = new EndpointAddress(uriBuilder.Uri); var contractDescription = ContractDescription.GetContract(typeof(ICommandContract)); var serviceEndpoint = new ServiceEndpoint(contractDescription, binding, endpointAddress); var instanceContext = new InstanceContext(implementation); var factory = new DuplexChannelFactory<ICommandContract>(instanceContext, serviceEndpoint); foreach (var operation in factory.Endpoint.Contract.Operations) { var dataContractSerializerBehavior = operation.Behaviors.Find<DataContractSerializerOperationBehavior>(); if (dataContractSerializerBehavior != null) { dataContractSerializerBehavior.MaxItemsInObjectGraph = int.MaxValue; } } var assemblies = this.deviceServiceBootstrapper.KnownTypeAssemblies; this.log.DebugFormat("The known assemblies are: {0}.", string.Join(", ", assemblies)); factory.Endpoint.Contract.ContractBehaviors.Add(new KnownTypeContractBehavior(assemblies)); this.log.Debug("Contract behaviors set."); return factory.CreateChannel(); } /// <summary> /// Gets the query channel. /// </summary> /// <param name="implementation">The client implementation.</param> /// <returns> /// The query channel. /// </returns> public IQueryContract GetQueryChannel(object implementation) { if (implementation == null) { throw new ArgumentNullException(nameof(implementation)); } this.log.Debug("Creating query contract."); var binding = new NetTcpBinding { ReceiveTimeout = TimeSpan.MaxValue, SendTimeout = TimeSpan.MaxValue, OpenTimeout = TimeSpan.MaxValue, MaxReceivedMessageSize = int.MaxValue, MaxBufferSize = int.MaxValue, MaxBufferPoolSize = int.MaxValue, }; var uriBuilder = new UriBuilder { Host = this.endpoint.Address.ToString(), Path = "/Lwi/Wst/Service/Query", Port = this.endpoint.Port, Scheme = "net.tcp" }; var endpointAddress = new EndpointAddress(uriBuilder.Uri); var contractDescription = ContractDescription.GetContract(typeof(IQueryContract)); var serviceEndpoint = new ServiceEndpoint(contractDescription, binding, endpointAddress); var factory = new DuplexChannelFactory<IQueryContract>( new InstanceContext(implementation), serviceEndpoint); foreach (var operation in factory.Endpoint.Contract.Operations) { var dataContractSerializerBehavior = operation.Behaviors.Find<DataContractSerializerOperationBehavior>(); if (dataContractSerializerBehavior != null) { dataContractSerializerBehavior.MaxItemsInObjectGraph = int.MaxValue; } } var assemblies = this.deviceServiceBootstrapper.KnownTypeAssemblies; this.log.DebugFormat("The known assemblies are: {0}.", string.Join(", ", assemblies)); factory.Endpoint.Contract.ContractBehaviors.Add(new KnownTypeContractBehavior(assemblies)); this.log.Debug("Contract behaviors set."); return factory.CreateChannel(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Souls : MonoBehaviour { #region Private Fields private Score score; #endregion #region SerializedFields [SerializeField]private int scoreValue = 1; //the gameobjects score Value #endregion #region Unity Functions private void Start() { score = GameObject.Find("Score").GetComponent<Score>(); //Finds the Gameobject with the name "Score" + its Components } private void OnTriggerEnter2D(Collider2D collision) //If the gameobjects collider gets triggered { score.SetScore(scoreValue); //sets the score to the gameobjects score value Destroy(gameObject); // destroys the gameobject } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using ExpVMsape.Context; using ExpVMsape.Models; namespace ExpVMsape { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { ExpContextULT db = new ExpContextULT(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); if (db.Topes.Count() == 0 | db.Topes == null) { Tope Lun = new Tope(); Tope Mar = new Tope(); Tope Mie = new Tope(); Tope Jue = new Tope(); Tope Vie = new Tope(); Tope Sab = new Tope(); Tope Dom = new Tope(); Lun.DiaTope = "Lunes"; Lun.ValorTope = 7500; Mar.DiaTope = "Martes"; Mar.ValorTope = 6500; Mie.DiaTope = "Miércoles"; Mie.ValorTope = 6100; Jue.DiaTope = "Jueves"; Jue.ValorTope = 6700; Vie.DiaTope = "Viernes"; Vie.ValorTope = 7800; Sab.DiaTope = "Sábado"; Sab.ValorTope = 11200; Dom.DiaTope = "Domingo"; Dom.ValorTope = 28500; db.Topes.Add(Lun); db.Topes.Add(Mar); db.Topes.Add(Mie); db.Topes.Add(Jue); db.Topes.Add(Vie); db.Topes.Add(Sab); db.Topes.Add(Dom); db.SaveChanges(); } if (db.VarGlobales.Count() == 0 | db.VarGlobales == null) { VarGlobales Agosto15 = new VarGlobales { Mes = 8, Año = 2015, Venta = 9735, Devolucion = 831 }; VarGlobales Septiembre15 = new VarGlobales { Mes = 9, Año = 2015, Venta = 8965, Devolucion = 672}; VarGlobales Octubre15 = new VarGlobales { Mes = 10, Año = 2015, Venta = 8827, Devolucion = 793 }; VarGlobales Noviembre15 = new VarGlobales { Mes = 11, Año = 2015, Venta = 9293, Devolucion = 694 }; VarGlobales Diciembre15 = new VarGlobales { Mes = 12, Año = 2015, Venta = 9063, Devolucion = 809 }; VarGlobales Enero16 = new VarGlobales { Mes = 1, Año = 2016, Venta = 7924, Devolucion = 760 }; VarGlobales Febrero16 = new VarGlobales { Mes = 2, Año = 2016, Venta = 8880, Devolucion = 709 }; VarGlobales Marzo16 = new VarGlobales { Mes = 3, Año = 2016, Venta = 8616, Devolucion = 874 }; VarGlobales Abril16 = new VarGlobales { Mes = 4, Año = 2016, Venta = 8704, Devolucion = 892 }; VarGlobales Mayo16 = new VarGlobales { Mes = 5, Año = 2016, Venta = 8324, Devolucion = 916 }; VarGlobales Junio16 = new VarGlobales { Mes = 6, Año = 2016, Venta = 7874, Devolucion = 880 }; VarGlobales Julio16 = new VarGlobales { Mes = 7, Año = 2016, Venta = 8566, Devolucion = 739 }; VarGlobales Agosto16 = new VarGlobales { Mes = 8, Año = 2016, Venta = 8392, Devolucion = 750 }; db.VarGlobales.Add( Agosto15); db.VarGlobales.Add( Septiembre15); db.VarGlobales.Add(Octubre15); db.VarGlobales.Add(Noviembre15); db.VarGlobales.Add(Diciembre15); db.VarGlobales.Add(Enero16); db.VarGlobales.Add(Febrero16); db.VarGlobales.Add(Marzo16); db.VarGlobales.Add(Abril16); db.VarGlobales.Add(Mayo16); db.VarGlobales.Add(Junio16); db.VarGlobales.Add(Julio16); db.VarGlobales.Add( Agosto16); db.SaveChanges(); } } protected void Application_Error(object sender, EventArgs e) { Exception exception = Server.GetLastError(); Response.Clear(); HttpException httpException = exception as HttpException; int error = httpException != null ? httpException.GetHttpCode() : 0; Server.ClearError(); Response.Redirect(String.Format("~/Error/?error={0}", error, exception.Message)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using CP.i8n; //------------------------------------------------------------------------------ // // This code was generated by OzzCodeGen. // // Manual changes to this file will be overwritten if the code is regenerated. // //------------------------------------------------------------------------------ namespace CriticalPath.Data { [MetadataTypeAttribute(typeof(AspNetUserDTO.AspNetUserMetadata))] public partial class AspNetUserDTO { internal sealed partial class AspNetUserMetadata { // This metadata class is not intended to be instantiated. private AspNetUserMetadata() { } [Key] [StringLength(48, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [Display(ResourceType = typeof(EntityStrings), Name = "Id")] public string Id { get; set; } [StringLength(256, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "Required")] [Display(ResourceType = typeof(EntityStrings), Name = "UserName")] public string UserName { get; set; } [StringLength(256, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [EmailAddress] [Display(ResourceType = typeof(EntityStrings), Name = "Email")] public string Email { get; set; } [StringLength(128, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [Display(ResourceType = typeof(EntityStrings), Name = "FirstName")] public string FirstName { get; set; } [StringLength(128, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [Display(ResourceType = typeof(EntityStrings), Name = "LastName")] public string LastName { get; set; } [StringLength(256, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [DataType(DataType.PhoneNumber)] [Display(ResourceType = typeof(EntityStrings), Name = "PhoneNumber")] public string PhoneNumber { get; set; } [DataType(DataType.PhoneNumber)] [Display(ResourceType = typeof(EntityStrings), Name = "PhoneNumberConfirmed")] public bool PhoneNumberConfirmed { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "TwoFactorEnabled")] public bool TwoFactorEnabled { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "LockoutEnabled")] public bool LockoutEnabled { get; set; } [DataType(DataType.Date)] [Display(ResourceType = typeof(EntityStrings), Name = "LockoutEndDateUtc")] public DateTime LockoutEndDateUtc { get; set; } [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "Required")] [Display(ResourceType = typeof(EntityStrings), Name = "AccessFailedCount")] public int AccessFailedCount { get; set; } } } }
using System; namespace NetFabric.Hyperlinq { public readonly struct FunctionWrapper<T, TResult> : IFunction<T, TResult> { readonly Func<T, TResult> function; public FunctionWrapper(Func<T, TResult> function) => this.function = function ?? throw new ArgumentNullException(nameof(function)); public TResult Invoke(T arg) => function(arg); } public readonly struct FunctionWrapper<T1, T2, TResult> : IFunction<T1, T2, TResult> { readonly Func<T1, T2, TResult> function; public FunctionWrapper(Func<T1, T2, TResult> function) => this.function = function ?? throw new ArgumentNullException(nameof(function)); public TResult Invoke(T1 arg1, T2 arg2) => function(arg1, arg2); } public readonly struct FunctionWrapper<T1, T2, T3, TResult> : IFunction<T1, T2, T3, TResult> { readonly Func<T1, T2, T3, TResult> function; public FunctionWrapper(Func<T1, T2, T3, TResult> function) => this.function = function ?? throw new ArgumentNullException(nameof(function)); public TResult Invoke(T1 arg1, T2 arg2, T3 arg3) => function(arg1, arg2, arg3); } public readonly struct FunctionWrapper<T1, T2, T3, T4, TResult> : IFunction<T1, T2, T3, T4, TResult> { readonly Func<T1, T2, T3, T4, TResult> function; public FunctionWrapper(Func<T1, T2, T3, T4, TResult> function) => this.function = function ?? throw new ArgumentNullException(nameof(function)); public TResult Invoke(T1 arg1, T2 arg2, T3 arg3, T4 arg4) => function(arg1, arg2, arg3, arg4); } public readonly struct FunctionWrapper<T1, T2, T3, T4, T5, TResult> : IFunction<T1, T2, T3, T4, T5, TResult> { readonly Func<T1, T2, T3, T4, T5, TResult> function; public FunctionWrapper(Func<T1, T2, T3, T4, T5, TResult> function) => this.function = function ?? throw new ArgumentNullException(nameof(function)); public TResult Invoke(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) => function(arg1, arg2, arg3, arg4, arg5); } public readonly struct FunctionWrapper<T1, T2, T3, T4, T5, T6, TResult> : IFunction<T1, T2, T3, T4, T5, T6, TResult> { readonly Func<T1, T2, T3, T4, T5, T6, TResult> function; public FunctionWrapper(Func<T1, T2, T3, T4, T5, T6, TResult> function) => this.function = function ?? throw new ArgumentNullException(nameof(function)); public TResult Invoke(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) => function(arg1, arg2, arg3, arg4, arg5, arg6); } public readonly struct FunctionWrapper<T1, T2, T3, T4, T5, T6, T7, TResult> : IFunction<T1, T2, T3, T4, T5, T6, T7, TResult> { readonly Func<T1, T2, T3, T4, T5, T6, T7, TResult> function; public FunctionWrapper(Func<T1, T2, T3, T4, T5, T6, T7, TResult> function) => this.function = function ?? throw new ArgumentNullException(nameof(function)); public TResult Invoke(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7) => function(arg1, arg2, arg3, arg4, arg5, arg6, arg7); } public readonly struct FunctionWrapper<T1, T2, T3, T4, T5, T6, T7, T8, TResult> : IFunction<T1, T2, T3, T4, T5, T6, T7, T8, TResult> { readonly Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> function; public FunctionWrapper(Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> function) => this.function = function ?? throw new ArgumentNullException(nameof(function)); public TResult Invoke(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8) => function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } public readonly struct FunctionWrapper<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> : IFunction<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> { readonly Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> function; public FunctionWrapper(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> function) => this.function = function ?? throw new ArgumentNullException(nameof(function)); public TResult Invoke(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) => function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } }
using System; using System.Collections.Generic; using System.Text; using Windows.UI.Popups; using RobotKit; using System.ComponentModel; using System.Threading; namespace SpheroProject { class SpheroManager : INotifyPropertyChanged { const int RGB_MAX = 255; const int RGB_MIN = 0; const int RGB_INTERVAL = 5; const int ROLL_INTERVAL = 50; public Sphero m_robot = null; Timer timer; bool stop_timer, stop_shaking; public string SpheroName { get { return spheroName; } set { spheroName = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("SpheroName")); } } } private string spheroName = ""; private string _GyroReading; public string GyroReading { get { return _GyroReading; } set { _GyroReading = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("GyroReading")); } } } private bool spheroConnected = false; private bool calibrationMode = false; public int calibrationAngle = 0; public bool SpheroConnected { get { return spheroConnected; } set { spheroConnected = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("SpheroConnected")); } } } internal void Pomosphero(int seconds) { ColorState color = new ColorState(0, 255, 0); int miliseconds = (seconds * 1000) / (RGB_MAX / RGB_INTERVAL); timer = new Timer(ChangeSpheroColor, color, 0, miliseconds); stop_timer = false; stop_shaking = true; } public void ChangeSpheroColor(Object tuple) { try { ColorState color = (ColorState)tuple; if (stop_timer) { RollState roll = new RollState(); stop_shaking = false; timer = new Timer(BackAndForth, roll, 0, ROLL_INTERVAL); return; } m_robot.SetRGBLED(color.Red, color.Green, color.Blue); if (color.Red == RGB_MAX && color.Green == RGB_MIN) { stop_timer = true; } if (color.Red <= (RGB_MAX - RGB_INTERVAL)) { color.Red += RGB_INTERVAL; } if (color.Green >= RGB_MIN + RGB_INTERVAL) { color.Green -= RGB_INTERVAL; } } catch(Exception e) { string s = e.Message; } } private void BackAndForth(object state) { if (!stop_shaking) { RollState roll = (RollState)state; roll.Flip(); m_robot.Roll(roll.Heading, roll.Speed); } } public event PropertyChangedEventHandler PropertyChanged; public SpheroManager() { //SetupRobotConnection(); } private const string kNoSpheroConnected = "No Sphero Connected"; //! @brief the default string to show when connecting to a sphero ({0}) private const string kConnectingToSphero = "Connecting to {0}"; //! @brief the default string to show when connected to a sphero ({0}) private const string kSpheroConnected = "Connected to {0}"; //! @brief search for a robot to connect to public void SetupRobotConnection() { SpheroName = "No Sphero Connected"; RobotProvider provider = RobotProvider.GetSharedProvider(); provider.DiscoveredRobotEvent += OnRobotDiscovered; provider.NoRobotsEvent += OnNoRobotsEvent; provider.ConnectedRobotEvent += OnRobotConnected; provider.FindRobots(); } public void OnRobotDiscovered(object sender, Robot robot) { if (m_robot == null) { RobotProvider provider = RobotProvider.GetSharedProvider(); provider.ConnectRobot(robot); m_robot = (Sphero)robot; SpheroConnected = true; SpheroName = string.Format(kConnectingToSphero, robot.BluetoothName); } } internal void StopTimer() { stop_shaking = true; timer.Change(Timeout.Infinite, Timeout.Infinite); m_robot.SetRGBLED(255, 255, 255); } private void OnNoRobotsEvent(object sender, EventArgs e) { SpheroName = "No Sphero Connected"; } //! @brief when a robot is connected, get ready to drive! private void OnRobotConnected(object sender, Robot robot) { //Debug.WriteLine(string.Format("Connected to {0}", robot)); //ConnectionToggle.IsOn = true; // ConnectionToggle.OnContent = "Connected"; SpheroConnected = true; m_robot.SetRGBLED(255, 255, 255); SpheroName = string.Format(kSpheroConnected, robot.BluetoothName); SpheroName = "Sphero Connected"; m_robot.SensorControl.Hz = 10; m_robot.SensorControl.GyrometerUpdatedEvent += SensorControl_GyrometerUpdatedEvent; //m_robot.CollisionControl.StartDetectionForWallCollisions(); //m_robot.CollisionControl.CollisionDetectedEvent += OnCollisionDetected; } private void SensorControl_GyrometerUpdatedEvent(object sender, GyrometerReading e) { GyroReading = string.Format("X:{0}" + Environment.NewLine + "Y:{1}" + Environment.NewLine + "Z:{2}", e.X, e.Y, e.Z); } public void ShutdownRobotConnection() { if (m_robot != null) { try { m_robot.SensorControl.StopAll(); m_robot.Sleep(); } catch { } // temporary while I work on Disconnect. //m_robot.Disconnect(); //ConnectionToggle.OffContent = "Disconnected"; SpheroConnected = false; SpheroName = kNoSpheroConnected; //m_robot.SensorControl.AccelerometerUpdatedEvent -= OnAccelerometerUpdated; //m_robot.SensorControl.GyrometerUpdatedEvent -= OnGyrometerUpdated; //m_robot.CollisionControl.StopDetection(); m_robot.CollisionControl.CollisionDetectedEvent -= OnCollisionDetected; RobotProvider provider = RobotProvider.GetSharedProvider(); provider.DiscoveredRobotEvent -= OnRobotDiscovered; provider.NoRobotsEvent -= OnNoRobotsEvent; provider.ConnectedRobotEvent -= OnRobotConnected; SpheroName = "Sphero Disconnected"; } } private void OnCollisionDetected(object sender, CollisionData e) { m_robot.SetRGBLED(0, 0, 255); } //public bool RobotNull() //{ // return m_robot == null; //} //public void Roll(int h, float f) //{ // if (m_robot != null) // { // m_robot.Roll(h, f); // } //} //public void SetHeading(int h) //{ // if(m_robot!=null) // { // // calibrationAngle += h; // m_robot.SetHeading(0); // } //} //public void Calibrate(bool b) //{ // if (m_robot != null) // { // if (b) // m_robot.SetBackLED(100f); // else // m_robot.SetBackLED(0f); // calibrationMode = b; // } //} //public bool inCalibration() //{ // return calibrationMode; //} } }
using AsyncAwaitBestPractices; using System.ComponentModel; using System.Linq.Expressions; using System.Runtime.CompilerServices; namespace Kit.Model { [Preserve(AllMembers = true)] public abstract class INotifyPropertyChangedModel : INotifyPropertyChanged { #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; //[Obsolete("Use Raise para mejor rendimiento evitando la reflección")] protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } private void OnPropertyChanged(PropertyChangedEventArgs args) { PropertyChangedEventHandler handler = PropertyChanged; handler?.Invoke(this, args); } #endregion INotifyPropertyChanged #region PerfomanceHelpers protected bool RaiseIfChanged<T>(ref T? backingField, T new_value, [CallerMemberName] string propertyName = null) where T : IComparable { if (new_value is null || new_value.CompareTo(backingField) != 0) { backingField = new_value; OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); return true; } return false; } public INotifyPropertyChangedModel Raise<T>(Expression<Func<T>> propertyExpression) { AsyncRaise<T>(propertyExpression).SafeFireAndForget(); return this; } protected async Task AsyncRaise<T>(Expression<Func<T>> propertyExpression) { await Task.Yield(); if (this.PropertyChanged != null) { MemberExpression body = propertyExpression.Body as MemberExpression; if (body == null) throw new ArgumentException("'propertyExpression' should be a member expression"); //ConstantExpression expression = body.Expression as ConstantExpression; //if (expression == null) //{ // throw new ArgumentException("'propertyExpression' body should be a constant expression"); //} object target = Expression.Lambda(body.Expression).Compile().DynamicInvoke(); if (target is null) return; PropertyChangedEventArgs e = new PropertyChangedEventArgs(body.Member.Name); try { PropertyChanged(target, e); OnPropertyRaised(target, e.PropertyName); } catch (Exception) { // Log.Logger.Error(ex, "On RAISE "); } } } protected void Raise<T>(params Expression<Func<T>>[] propertyExpressions) { foreach (Expression<Func<T>> propertyExpression in propertyExpressions) { Raise<T>(propertyExpression); } } protected virtual void OnPropertyRaised(object target, string PropertyName) { } #endregion PerfomanceHelpers } }
using TowerDefence; namespace TowerDefenceGame { ///<summary> ///Fast enemy class, inherites Enemy ///</summary> class FastEnemy : Enemy { public FastEnemy(double leveys, double korkeus): base(leveys, korkeus) { health = 65; speed = 2.1; } } }
namespace TeamViceWebservice { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("DepZipCode")] public partial class DepZipCode { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public DepZipCode() { Department = new HashSet<Department>(); } [Key] [Column("DepZipCode")] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int DepZipCode1 { get; set; } [Required] [StringLength(30)] public string DepCity { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Department> Department { get; set; } } }
namespace RepeatingPattern { using System; class RepeatingPattern { static void Main() { var str = Console.ReadLine(); var length = str.Length; var flag = false; for (int i = 1; i < length / 2; i++) { if (length % i > 0) { continue; } flag = true; var subStr = str.Substring(0, i); for (int j = i; j + i <= length; j += i) { if (subStr != str.Substring(j, i)) { flag = false; break; } } if (flag) { Console.WriteLine(subStr); return; } } Console.WriteLine(str); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EF { public class RepositoryProblem { SqlDbContext context = new SqlDbContext(); public List<Problem> GetBy(IList<ProblemStatus> exclude, bool hasReward, bool descByPublishTime) { List<Problem> result = context.Problems.ToList(); if (hasReward) { result = result.Where(p => p.Reward != null).ToList(); }//else nothing if (descByPublishTime) { result = result.OrderByDescending(s => s.PublishDateTime).ToList(); } else //需求模糊 假设不倒叙就是正序 { result = result.OrderBy(s => s.PublishDateTime).ToList(); } return result = result.Where(p => !exclude.Contains(p.Status)).ToList(); } } }
using CFDI.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CFDI.ViewModel { public class DetalleViewModel:ObservableObject { private DetalleFacturasModel _Detalle; //public DetalleViewModel(DetalleFacturasModel detalle) public DetalleViewModel() { //_Detalle = detalle; _Detalle = new DetalleFacturasModel(); } //Propiedads Grid public int ProductoId { get { return _Detalle.ProductoId; } set { if (_Detalle.ProductoId != value) PrecioUnitario = 0; _Detalle.ProductoId = value; ServicioWS WS = new ServicioWS("WsProductos.svc", "getProducto", _Detalle.ProductoId, typeof(ProductosModel), "id"); UnidadId = ((ProductosModel)WS.Peticion()).UnidadId; RaisePropertyChangedEvent("ProductoId"); } } public int UnidadId { get { return _Detalle.UnidadId; } set { _Detalle.UnidadId = value; RaisePropertyChangedEvent("UnidadId"); } } public decimal PrecioUnitario { get { return _Detalle.PrecioUnitario; } set { _Detalle.PrecioUnitario = value; RaisePropertyChangedEvent("PrecioUnitario"); RaisePropertyChangedEvent("Importe"); } } public decimal Cantidad { get { return _Detalle.Cantidad; } set { _Detalle.Cantidad = value; RaisePropertyChangedEvent("Cantidad"); RaisePropertyChangedEvent("Importe"); } } public decimal Importe { get { decimal descuento_decimal = 0.0m; decimal TotalAntesDescuento = _Detalle.Cantidad * _Detalle.PrecioUnitario; if (_Detalle.Descuento>0.0m) { descuento_decimal = TotalAntesDescuento*(_Detalle.Descuento/100); } _Detalle.Importe = (TotalAntesDescuento)-descuento_decimal; return _Detalle.Importe; } set{} } public decimal Descuento { get { return _Detalle.Descuento; } set { _Detalle.Descuento = value; RaisePropertyChangedEvent("Importe"); } } //Terminana Propiedades grid } }
using System.Collections.Generic; using System.Runtime.Serialization.Json; using Hammock; using System.IO; using System.Windows.Media.Imaging; using System.Windows.Resources; using System; using Microsoft.Phone; using System.Net; using Hammock.Web; namespace dailyBurnWP7 { public abstract class DailyBurnFoodResults { public event FoodSearchStarted SearchReturned; public abstract void Search(); protected dailyBurnFood[] foods; protected void OnSearchReturned() { if (SearchReturned != null) SearchReturned(this, new FoodSearchEventArgs { Search = this }); } public SearchResultItem SelectedSearchResult { get; set; } public List<SearchResultItem> SearchResults { get { List<SearchResultItem> temp = new List<SearchResultItem>(); foreach (dailyBurnFood food in foods) { temp.Add(new SearchResultItem(food.food)); } return (temp); } } } public class DailyBurnSearch : DailyBurnFoodResults { private string searchString; private dailyBurnFood[] foodsNext; private dailyBurnFood[] foodsPrevious; private int currentPage = 1; private const int PAGE_SIZE = 25; private bool canPageForward = false; private bool canPageBack = false; public bool CanPageForward { get { return canPageForward; } } public bool CanPageBack { get { return canPageBack; } } public DailyBurnSearch(string SearchString) { searchString = SearchString; } public override void Search() { Dictionary<string,string> parameters = new Dictionary<string,string>(); parameters.Add("input",searchString); parameters.Add("per_page", PAGE_SIZE.ToString()); HelperMethods.CallDailyBurnApi(DailyBurnSettings.FoodSearchAPI, searchCallback, parameters); } public string SearchString { get { return searchString; } } public void NavigateForward() { if (foodsNext != null) { foodsPrevious = foods; foods = foodsNext; currentPage++; getNextPage(); canPageBack = true; } } public void NavigateBack() { if (foodsPrevious != null) { foodsNext = foods; foods = foodsPrevious; currentPage--; getPreviousPage(); canPageForward = true; } } private void searchCallback(RestRequest request, Hammock.RestResponse response, object obj) { DataContractJsonSerializer jSon = new DataContractJsonSerializer(typeof(dailyBurnFood[])); foods = jSon.ReadObject(response.ContentStream) as dailyBurnFood[]; getNextPage(); } private void getNextPageCallback(RestRequest request, Hammock.RestResponse response, object obj) { DataContractJsonSerializer jSon = new DataContractJsonSerializer(typeof(dailyBurnFood[])); foodsNext = jSon.ReadObject(response.ContentStream) as dailyBurnFood[]; if (foodsNext.Length > 0) { canPageForward = true; } OnSearchReturned(); } private void getPrevPageCallback(RestRequest request, Hammock.RestResponse response, object obj) { DataContractJsonSerializer jSon = new DataContractJsonSerializer(typeof(dailyBurnFood[])); foodsPrevious = jSon.ReadObject(response.ContentStream) as dailyBurnFood[]; if (foodsPrevious.Length > 0) { canPageBack = true; } } private void getNextPage() { if (foods.Length == PAGE_SIZE) { int nextPage = currentPage + 1; Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters.Add("input", searchString); parameters.Add("per_page", PAGE_SIZE.ToString()); parameters.Add("page", nextPage.ToString()); HelperMethods.CallDailyBurnApi(DailyBurnSettings.FoodSearchAPI, getNextPageCallback, parameters); } else { canPageForward = false; OnSearchReturned(); } } private void getPreviousPage() { if (currentPage > 1) { int prevPage = currentPage - 1; Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters.Add("input", searchString); parameters.Add("per_page", PAGE_SIZE.ToString()); parameters.Add("page", prevPage.ToString()); HelperMethods.CallDailyBurnApi(DailyBurnSettings.FoodSearchAPI, getPrevPageCallback, parameters); } else { canPageBack = false; } } } public class SearchResultItem { public SearchResultItem(dailyBurnFoodDetails food) { Name = food.name; Brand = food.brand; Serving = food.serving_size; Calories = food.calories.ToString(); TotalFat = Decimal.Round(food.total_fat, 1).ToString(); TotalCarbs = Decimal.Round(food.total_carbs,1).ToString(); Protein = Decimal.Round(food.protein,1).ToString(); if (!string.IsNullOrEmpty(food.thumb_url)) { if (!HelperMethods.isValidPictureUrl(food.thumb_url)) Thumb = "icons/missing.png"; else Thumb = food.thumb_url; } FoodId = food.id; } public string Thumb { get; set; } public string Name {get;set;} public string Brand { get; set; } public string Serving { get; set; } public string Calories { get; set; } public string TotalFat { get; set; } public string TotalCarbs { get; set; } public string Protein { get; set; } public int FoodId { get; set; } } public class dailyBurnFood { public dailyBurnFoodDetails food; } public class dailyBurnFoodDetails { public decimal sugars; public string name; public string brand; public int calories; public decimal total_fat; public decimal total_carbs; public string serving_size; public decimal protein; public int id; public bool usda; public int user_id; public decimal sodium; public decimal dietary_fiber; public decimal cholesterol; public string thumb_url; public decimal saturated_fat; public decimal potassium; } }
namespace PlatformRacing3.Web.Controllers.DataAccess2.Procedures.Exceptions; public class DataAccessProcedureMissingData : Exception { }
using GalaSoft.MvvmLight.Command; using MultiPlatform.Domain.Code; using MultiPlatform.Domain.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MultiPlatform.Domain.ViewModels { public class Home : BaseViewModel { public Home( INavigation<Domain.Interfaces.NavigationModes> navigationService , IStorage storageService , ISettings settingsService , IUx uxService , ILocation locationService , IPeerConnector peerConnectorService ) : base( navigationService , storageService , settingsService , uxService , locationService , peerConnectorService ) { this.AppName = International.Translation.AppName; this.PageTitle = International.Translation.Home_Title; } private bool _Refesh; public bool Refesh { get { return this.IsLogged; } set { if (_Refesh != value) { _Refesh = value; NotifyPropertyChanged(); } } } private RelayCommand _GoToMap; public RelayCommand GoToMap { get { return _GoToMap ?? (_GoToMap = new RelayCommand( () => { try { _navigationService.Navigate<Map>(false); } catch (Exception ex) { throw ex; } })); } } private RelayCommand _GoDetails; public RelayCommand GoDetails { get { return _GoDetails ?? (_GoDetails = new RelayCommand( () => { try { _navigationService.Navigate<Details>(false); } catch (Exception ex) { throw ex; } })); } } private RelayCommand _GoNFCSend; public RelayCommand GoToNFCSend { get { return _GoNFCSend ?? (_GoNFCSend = new RelayCommand( () => { try { _navigationService.Navigate<NFCSend>(false); } catch (Exception ex) { throw ex; } })); } } private RelayCommand _GoToLogin; public RelayCommand GoToLogin { get { return _GoToLogin ?? (_GoToLogin = new RelayCommand( () => { try { _uxService.GoToLogin(); } catch (Exception ex) { throw ex; } })); } } private RelayCommand _GoToSQLiteDemo; public RelayCommand GoToSQLiteDemo { get { return _GoToSQLiteDemo ?? (_GoToSQLiteDemo = new RelayCommand( () => { try { _navigationService.Navigate<SQLite>(); } catch (Exception ex) { throw ex; } })); } } private RelayCommand _ShowAlert; public RelayCommand ShowAlert { get { return _ShowAlert ?? (_ShowAlert = new RelayCommand( () => { try { _uxService.ShowMessageBox("Conditional Compilation!"); _uxService.ShowToast("Conditional Compilation!"); } catch (Exception ex) { throw ex; } })); } } } }
using Contoso.XPlatform.ViewModels.ReadOnlys; using Contoso.XPlatform.ViewModels.Validatables; using System; namespace Contoso.XPlatform.Views.Factories { internal class PopupFormFactory : IPopupFormFactory { private readonly Func<IValidatable, ChildFormArrayPageCS> getChildFormArrayPage; private readonly Func<IValidatable, ChildFormPageCS> getChildFormPage; private readonly Func<IValidatable, MultiSelectPageCS> getMultiSelectPage; private readonly Func<IReadOnly, ReadOnlyChildFormArrayPageCS> getReadOnlyChildFormArrayPage; private readonly Func<IReadOnly, ReadOnlyChildFormPageCS> getReadOnlyChildFormPage; private readonly Func<IReadOnly, ReadOnlyMultiSelectPageCS> getReadOnlyMultiSelectPage; public PopupFormFactory( Func<IValidatable, ChildFormArrayPageCS> getChildFormArrayPage, Func<IValidatable, ChildFormPageCS> getChildFormPage, Func<IValidatable, MultiSelectPageCS> getMultiSelectPage, Func<IReadOnly, ReadOnlyChildFormArrayPageCS> getReadOnlyChildFormArrayPage, Func<IReadOnly, ReadOnlyChildFormPageCS> getReadOnlyChildFormPage, Func<IReadOnly, ReadOnlyMultiSelectPageCS> getReadOnlyMultiSelectPage) { this.getChildFormArrayPage = getChildFormArrayPage; this.getChildFormPage = getChildFormPage; this.getMultiSelectPage = getMultiSelectPage; this.getReadOnlyChildFormArrayPage = getReadOnlyChildFormArrayPage; this.getReadOnlyChildFormPage = getReadOnlyChildFormPage; this.getReadOnlyMultiSelectPage = getReadOnlyMultiSelectPage; } public ChildFormArrayPageCS CreateChildFormArrayPage(IValidatable formArrayValidatable) => getChildFormArrayPage(formArrayValidatable); public ChildFormPageCS CreateChildFormPage(IValidatable formValidatable) => getChildFormPage(formValidatable); public MultiSelectPageCS CreateMultiSelectPage(IValidatable multiSelectValidatable) => getMultiSelectPage(multiSelectValidatable); public ReadOnlyChildFormArrayPageCS CreateReadOnlyChildFormArrayPage(IReadOnly formArrayReadOnly) => getReadOnlyChildFormArrayPage(formArrayReadOnly); public ReadOnlyChildFormPageCS CreateReadOnlyChildFormPage(IReadOnly formReadOnly) => getReadOnlyChildFormPage(formReadOnly); public ReadOnlyMultiSelectPageCS CreateReadOnlyMultiSelectPage(IReadOnly multiSelectReadOnly) => getReadOnlyMultiSelectPage(multiSelectReadOnly); } }
using System.IO; using System.Web; using Database; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; namespace Sem { public class CreateDebate { public static void Create(IApplicationBuilder app) { app.Run(async context => { var id = context.Session.GetInt32("user_id"); if (id == null) { context.Response.Headers.Add("status", "not_registered"); return; } var title = HttpUtility.UrlDecode((string)context.Request.Headers["title"]); var text = HttpUtility.UrlDecode((string)context.Request.Headers["text"]); using var r = new StreamReader(context.Request.Body); var s = await r.ReadToEndAsync(); var tags = JsonConvert.DeserializeObject<string[]>(s/*.Headers["tags"]*/); context.Response.Headers.Add("status", "success"); context.Response.Headers.Add("id", (await Debates.Create(title, text, tags, (int)id)).ToString()); }); } } }
using System.Data.Entity; using MusicCatalogue.Data.Migrations; using MusicCatalogue.Model; namespace MusicCatalogue.Data { public class MusicCatalogueDbContext : DbContext, IMusicCatalogueDbContext { public MusicCatalogueDbContext() : base("MusicCatalogueConnection") { Database.SetInitializer(new MigrateDatabaseToLatestVersion<MusicCatalogueDbContext, Configuration>()); } public IDbSet<Artist> Artists { get; set; } public IDbSet<Album> Albums { get; set; } public IDbSet<Song> Songs { get; set; } public new IDbSet<TEntity> Set<TEntity>() where TEntity : class { return base.Set<TEntity>(); } } }
// Accord Neural Net Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Neuro.Visualization { using Accord.Math; /// <summary> /// Activation-Maximization method for visualizing neuron's roles. /// </summary> /// public class ActivationMaximization { ActivationNeuron neuron; /// <summary> /// Initializes a new instance of the <see cref="ActivationMaximization"/> class. /// </summary> /// /// <param name="neuron">The neuron to be visualized.</param> /// public ActivationMaximization(ActivationNeuron neuron) { this.neuron = neuron; } /// <summary> /// Finds the value which maximizes /// the activation of this neuron. /// </summary> /// public double[] Maximize() { // Initialize double[] value = new double[neuron.InputsCount]; for (int i = 0; i < value.Length; i++) value[i] = Accord.Math.Random.Generator.Random.NextDouble(); double[] gradient = new double[neuron.InputsCount]; for (int iter = 0; iter < 50; iter++) { // Compute the activation gradient double activation = neuron.Compute(value); for (int i = 0; i < gradient.Length; i++) gradient[i] = neuron.Weights[i] * neuron.ActivationFunction.Derivative2(activation); // Walk against the gradient for (int i = 0; i < value.Length; i++) value[i] -= gradient[i]; value = value.Divide(value.Sum()); } return value; } } }
/* * Copyright 2014 Technische Universität Darmstadt * * 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. */ using System.Linq; using KaVE.Commons.Model.Naming; using KaVE.Commons.Model.SSTs.Declarations; using KaVE.Commons.Model.SSTs.Impl.Declarations; using KaVE.Commons.Model.SSTs.Impl.Statements; using NUnit.Framework; using Fix = KaVE.RS.Commons.Tests_Integration.Analysis.SSTAnalysisTestSuite.SSTAnalysisFixture; namespace KaVE.RS.Commons.Tests_Integration.Analysis.SSTAnalysisTestSuite.Declarations { internal class IndexerDeclarationAnalysisTest : BaseSSTAnalysisTest { [Test] public void Indexer_HappyPath() { CompleteInClass(@" public int this[int i] { get { return -1; } set { var x = value; } } $ "); var expected = new PropertyDeclaration { Name = Names.Property("set get [p:int] [N.C, TestProject].Item([p:int] i)"), Get = { new ReturnStatement { Expression = Const("-1") } }, Set = { VarDecl("x", Fix.Int), Assign("x", RefExpr(VarRef("value"))) } }; var actual = AssertSingleProperty(); Assert.AreEqual(expected, actual); } [Test] public void Indexer_TwoParameters() { CompleteInClass(@" public int this[int i, int j] { get { return -1; } set { } } $ "); var expected = new PropertyDeclaration { Name = Names.Property("set get [p:int] [N.C, TestProject].Item([p:int] i, [p:int] j)"), Get = { new ReturnStatement { Expression = Const("-1") } } }; var actual = AssertSingleProperty(); Assert.AreEqual(expected, actual); } [Test] public void Indexer_OnlyGet() { CompleteInClass(@" public int this[int i] { get { return -1; } } $ "); var expected = new PropertyDeclaration { Name = Names.Property("get [p:int] [N.C, TestProject].Item([p:int] i)"), Get = { new ReturnStatement { Expression = Const("-1") } } }; var actual = AssertSingleProperty(); Assert.AreEqual(expected, actual); } [Test] public void Indexer_OnlySet() { CompleteInClass(@" public int this[int i] { set { var x = value; } } $ "); var expected = new PropertyDeclaration { Name = Names.Property("set [p:int] [N.C, TestProject].Item([p:int] i)"), Set = { VarDecl("x", Fix.Int), Assign("x", RefExpr(VarRef("value"))) } }; var actual = AssertSingleProperty(); Assert.AreEqual(expected, actual); } private IPropertyDeclaration AssertSingleProperty() { Assert.AreEqual(1, ResultSST.Properties.Count); return ResultSST.Properties.First(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyMover : MonoBehaviour { [SerializeField] private float moveSpeed = 10f; private Pathfinder pathfinder; private Transform pointA, pointB; private Vector3 movementVector; private float distanceToMove; private int pathProgress = 0; private List<Waypoint> path; private PlayerHealth adjacentBase; private bool enemyReachedGoal = false; void Awake() { pathfinder = FindObjectOfType<Pathfinder>(); } // Use this for initialization void Start() { path = pathfinder.GetPath(); SetWaypoints(); } private void SetWaypoints() { if (pathProgress == path.Count - 1) { if (!enemyReachedGoal) { enemyReachedGoal = true; SelfDestruct(); } return; } pointA = path[pathProgress].transform; pointB = path[++pathProgress].transform; movementVector = (pointB.position - pointA.position).normalized; distanceToMove = Vector3.Distance(pointA.position, pointB.position); } private IEnumerator FollowPath() { foreach (Waypoint waypoint in path) { transform.position = waypoint.transform.position; yield return new WaitForSeconds(1f); } } // Update is called once per frame void FixedUpdate() { HandleMovement(); } private void HandleMovement() { if (distanceToMove <= 0) { SetWaypoints(); } MoveEnemy(); } private void MoveEnemy() { float distanceThisFrame = moveSpeed * Time.deltaTime; distanceThisFrame = Mathf.Clamp(distanceThisFrame, 0f, distanceToMove); transform.Translate(movementVector * distanceThisFrame); distanceToMove -= distanceThisFrame; } private void SelfDestruct() { adjacentBase.HitBase(); GetComponent<EnemyHealthController>().Explode(); } private void OnTriggerEnter(Collider other) { if (other.gameObject.GetComponent<PlayerHealth>()) { adjacentBase = other.gameObject.GetComponent<PlayerHealth>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hahn.ApplicatonProcess.December2020.Domain.Services.Applicant { public class UpdateApplicantDto : AddApplicantDto { public bool Hired { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Tuna.Models { public class TrashDistribution { public float FoodWaste { get; set; } public float PlasticWaste { get; set; } public float ResidualWaste { get; set; } } }
using DivineApp.Models; using Microsoft.AspNet.Identity.EntityFramework; using System.Data.Entity; namespace DivineApp.Contexts { public class MyContext:IdentityDbContext<CompanyUser> { public MyContext() : base("DefaultConnection") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } public static MyContext Create() { return new MyContext(); } } }
namespace BlazorUtils.Interfaces { public interface ICoordinate { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VendingMachine.Models; namespace VendingMachine.Events { public class PaymentTakenWithChangeEvent : DomainEvent { public Change Change { get; private set; } public int ProductId { get; private set; } public PaymentTakenWithChangeEvent(Change change, int productId) { this.Change = change; this.ProductId = productId; } } }
using System; using System.Collections.Generic; using System.Linq; using MenuSample.Inputs; using MenuSample.Scenes; using MenuSample.Scenes.Core; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Xspace { public class Xspace : Microsoft.Xna.Framework.Game { public static int window_width = 1180; public static int window_height = 750; public Xspace() { GraphicsDeviceManager graphics = new GraphicsDeviceManager(this) { PreferredBackBufferWidth = window_width, PreferredBackBufferHeight = window_height, }; var sceneMgr = new SceneManager(this); Components.Add(new InputState(this)); Components.Add(sceneMgr); new BackgroundScene(sceneMgr).Add(); new MainMenuScene(sceneMgr, graphics).Add(); Content.RootDirectory = "Content"; IsFixedTimeStep = false; } public static void Main() { using (var game = new Xspace()) game.Run(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace NetCode.Synchronisers.References { public class SyncReferenceFactory : SynchroniserFactory { private readonly Type ReferenceType; private readonly bool Linked; public SyncReferenceFactory(Type refType, SyncFlags flags) { Linked = (flags & SyncFlags.Linked) != 0; ReferenceType = refType; } public sealed override Synchroniser Construct() { if (Linked) { return new SyncLinkedReference(ReferenceType); } return new SyncReference(ReferenceType); } } }
using System.Collections.Generic; using FakeItEasy; using FatCat.Nes.OpCodes.Arithmetic; using FluentAssertions; using JetBrains.Annotations; using Xunit; namespace FatCat.Nes.Tests.OpCodes.Arithmetic { public class DecrementYRegisterTests : OpCodeTest { private const int YRegister = 0x12; public static IEnumerable<object[]> NegativeData { [UsedImplicitly] get { yield return new object[] { 0b_1000_1111 // y register }; yield return new object[] { 0b_1100_0000 // y register }; yield return new object[] { 0b_0000_0000 // y register }; yield return new object[] { 0b_1111_1111 // y register }; } } public static IEnumerable<object[]> NonNegativeData { [UsedImplicitly] get { yield return new object[] { 0b_0000_1111 // y register }; yield return new object[] { 0b_0100_0000 // y register }; yield return new object[] { 0b_0111_0000 // y register }; } } public static IEnumerable<object[]> NonZeroData { [UsedImplicitly] get { yield return new object[] { 0x02 // y register }; yield return new object[] { 0xff // y register }; yield return new object[] { 0x00 // y register }; } } public static IEnumerable<object[]> ZeroData { [UsedImplicitly] get { yield return new object[] { 0x01 // y register }; } } protected override string ExpectedName => "DEY"; public DecrementYRegisterTests() { opCode = new DecrementYRegister(cpu, addressMode); cpu.YRegister = YRegister; } [Fact] public void WillDecreaseYRegisterValue() { opCode.Execute(); cpu.YRegister.Should().Be(YRegister - 1); } [Theory] [MemberData(nameof(NegativeData), MemberType = typeof(DecrementValueAtMemoryTests))] public void WillSetTheNegativeFlag(byte yRegister) => RunFlagSetTest(yRegister, CpuFlag.Negative); [Theory] [MemberData(nameof(ZeroData), MemberType = typeof(DecrementValueAtMemoryTests))] public void WillSetTheZeroFlag(byte yRegister) => RunFlagSetTest(yRegister, CpuFlag.Zero); [Fact] public void WillTakeNoCycles() { var cycles = opCode.Execute(); cycles.Should().Be(0); } [Theory] [MemberData(nameof(NonNegativeData), MemberType = typeof(DecrementValueAtMemoryTests))] public void WillUnsetTheNegativeFlag(byte yRegister) => RunRemoveFlagTest(yRegister, CpuFlag.Negative); [Theory] [MemberData(nameof(NonZeroData), MemberType = typeof(DecrementValueAtMemoryTests))] public void WillUnsetTheZeroFlag(byte yRegister) => RunRemoveFlagTest(yRegister, CpuFlag.Zero); private void RunFlagSetTest(byte yRegister, CpuFlag flag) { cpu.YRegister = yRegister; opCode.Execute(); A.CallTo(() => cpu.SetFlag(flag)).MustHaveHappened(); A.CallTo(() => cpu.RemoveFlag(flag)).MustNotHaveHappened(); } private void RunRemoveFlagTest(byte yRegister, CpuFlag flag) { cpu.YRegister = yRegister; opCode.Execute(); A.CallTo(() => cpu.RemoveFlag(flag)).MustHaveHappened(); A.CallTo(() => cpu.SetFlag(flag)).MustNotHaveHappened(); } } }
namespace SmartAssembly.Attributes { using System; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Struct | AttributeTargets.Class, Inherited=true)] public sealed class DoNotCaptureAttribute : Attribute { } }
// Copyright (c) Microsoft. All rights reserved. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.IoT.Connections.Azure { public enum SendResult { Success, Failure } }
// Project Prolog // Name: Spencer Carter // CS 1400 Section 003 // Project: Lab_02 // Date: 1/13/2015 // // I declare that the following code was written by me, provided // by the instructor, or provided in the textbook for this project. // I also declair understand that copying source // code from any other source constitutes cheating, and that I will receive // a zero on this project if I am found in violation of this policy. // // Image resources obtained for this file include: // Ryoku Tensigan (c) Spencer Carter (aka Theos-Kengen) all rights reserved. // The image was provided by the copyright owner (aka me) for educational purposes. // The image is not to be distributed to third parties, // and may not be shared other than for its intended purpose (this particular assignment). // --------------------------------------------------------------------------- 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 Lab_02 { //--------------------- pseudo-code ----------------------- //place LblInfo "Programming in C# can be fun" Font Blackadder ITC Size 18 //PBoxImage to display the image selected //BtnClose to close the program public partial class FrmMain : Form { /// <summary> /// Purpose: Creates the FrmMain and initializes all of the controls /// </summary> public FrmMain() { InitializeComponent(); } /// <summary> /// Purpose: On event BtnClose, it will close the program and exit /// </summary> /// <param name="sender">BtnClose event</param> /// <param name="e">Not used</param> private void BtnClose_Click(object sender, EventArgs e) { Close(); } // this closes the program when the button is clicked } // end of FrmMain } // end of namespace
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LambdaMethodOpExp002 { public delegate void MyDelegate(); class Program { static void Main(string[] args) { MyDelegate mydelegate; mydelegate = delegate { Console.WriteLine("Hello1"); }; mydelegate += () => { Console.WriteLine("Hello2"); }; mydelegate += () => Console.WriteLine("Hello3"); mydelegate(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Numerics; namespace HackerRank_HomeCode { public class ExtraLongFactorial { public void DisplayFact() { int n = Convert.ToInt32(Console.ReadLine()); var bigFact = BigInteger.One; for(int i = 1;i <=n;i++) { bigFact = bigFact * i; } Console.WriteLine(bigFact); } } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Compiler.Common.Exceptions; using Mosa.Compiler.Framework.Linker; using Mosa.Compiler.Framework.Trace; using Mosa.Compiler.MosaTypeSystem; using System; using System.Collections.Generic; using System.Diagnostics; namespace Mosa.Compiler.Framework { /// <summary> /// Basic base class for method compiler pipeline stages /// </summary> public abstract class BaseMethodCompilerStage { public delegate TraceLog CreateTraceHandler(string name, int tracelevel); #region Data Members private List<TraceLog> traceLogs; #endregion Data Members #region Stage Properties /// <summary> /// Retrieves the name of the compilation stage. /// </summary> /// <value>The name of the compilation stage.</value> public virtual string Name { get { return GetType().Name; } } /// <summary> /// Gets or sets the name of the formatted stage. /// </summary> public string FormattedStageName { get; private set; } #endregion Stage Properties #region Instructions Properties protected BaseInstruction LoadInstruction { get; private set; } protected BaseInstruction StoreInstruction { get; private set; } protected BaseInstruction MoveInstruction { get; private set; } protected BaseInstruction SubInstruction { get; private set; } protected BaseInstruction AddInstruction { get; private set; } protected BaseInstruction BranchInstruction { get; private set; } #endregion Instructions Properties #region Compiler Properties /// <summary> /// The architecture of the compilation process /// </summary> protected BaseArchitecture Architecture { get; private set; } /// <summary> /// List of basic blocks found during decoding /// </summary> protected BasicBlocks BasicBlocks { get; private set; } /// <summary> /// Holds the type system /// </summary> protected TypeSystem TypeSystem { get; private set; } /// <summary> /// Holds the type layout interface /// </summary> protected MosaTypeLayout TypeLayout { get; private set; } /// <summary> /// Gets the compiler options. /// </summary> protected CompilerSettings CompilerSettings { get; private set; } /// <summary> /// Holds the native pointer size /// </summary> protected int NativePointerSize { get; private set; } /// <summary> /// Holds the native alignment /// </summary> protected int NativeAlignment { get; private set; } /// <summary> /// Gets the size of the native instruction. /// </summary> /// <value> /// The size of the native instruction. /// </value> protected InstructionSize NativeInstructionSize { get; private set; } /// <summary> /// Gets a value indicating whether [is32 bit platform]. /// </summary> /// <value> /// <c>true</c> if [is32 bit platform]; otherwise, <c>false</c>. /// </value> protected bool Is32BitPlatform { get; private set; } /// <summary> /// Gets a value indicating whether [is64 bit platform]. /// </summary> /// <value> /// <c>true</c> if [is64 bit platform]; otherwise, <c>false</c>. /// </value> protected bool Is64BitPlatform { get; private set; } #endregion Compiler Properties #region Method Properties /// <summary> /// Hold the method compiler /// </summary> protected MethodCompiler MethodCompiler { get; private set; } /// <summary> /// Hold the method compiler /// </summary> protected MethodScanner MethodScanner { get; private set; } /// <summary> /// Retrieves the compilation scheduler. /// </summary> /// <value>The compilation scheduler.</value> public MethodScheduler MethodScheduler { get; private set; } /// <summary> /// Gets the method data. /// </summary> protected MethodData MethodData { get { return MethodCompiler.MethodData; } } /// <summary> /// Gets the linker. /// </summary> protected MosaLinker Linker { get { return MethodCompiler.Linker; } } /// <summary> /// Gets the type of the platform internal runtime. /// </summary> public MosaType PlatformInternalRuntimeType { get { return MethodCompiler.Compiler.PlatformInternalRuntimeType; } } /// <summary> /// Gets the type of the internal runtime. /// </summary> public MosaType InternalRuntimeType { get { return MethodCompiler.Compiler.InternalRuntimeType; } } /// <summary> /// Gets the method. /// </summary> protected MosaMethod Method { get { return MethodCompiler.Method; } } /// <summary> /// Gets the constant zero. /// </summary> protected Operand ConstantZero { get { return MethodCompiler.ConstantZero; } } /// <summary> /// Gets the 32-bit constant zero. /// </summary> protected Operand ConstantZero32 { get { return MethodCompiler.ConstantZero; } } /// <summary> /// Gets the 64-bit constant zero. /// </summary> protected Operand ConstantZero64 { get { return MethodCompiler.ConstantZero; } } /// <summary> /// Gets the stack frame. /// </summary> protected Operand StackFrame { get { return MethodCompiler.Compiler.StackFrame; } } /// <summary> /// Gets the stack pointer. /// </summary> protected Operand StackPointer { get { return MethodCompiler.Compiler.StackPointer; } } /// <summary> /// Gets the link register. /// </summary> protected Operand LinkRegister { get { return MethodCompiler.Compiler.LinkRegister; } } /// <summary> /// Gets the program counter /// </summary> protected Operand ProgramCounter { get { return MethodCompiler.Compiler.ProgramCounter; } } /// <summary> /// Gets the exception register. /// </summary> protected Operand ExceptionRegister { get { return MethodCompiler.Compiler.ExceptionRegister; } } /// <summary> /// Gets the leave target register. /// </summary> protected Operand LeaveTargetRegister { get { return MethodCompiler.Compiler.LeaveTargetRegister; } } /// <summary> /// Gets a value indicating whether this instance has protected regions. /// </summary> protected bool HasProtectedRegions { get { return MethodCompiler.HasProtectedRegions; } } /// <summary> /// Gets a value indicating whether this instance has code. /// </summary> protected bool HasCode { get { return BasicBlocks.HeadBlocks.Count != 0; } } /// <summary> /// The counters /// </summary> private readonly List<Counter> Counters = new List<Counter>(); #endregion Method Properties #region Methods /// <summary> /// Setups the specified compiler. /// </summary> /// <param name="compiler">The base compiler.</param> public void Initialize(Compiler compiler) { Architecture = compiler.Architecture; TypeSystem = compiler.TypeSystem; TypeLayout = compiler.TypeLayout; MethodScheduler = compiler.MethodScheduler; CompilerSettings = compiler.CompilerSettings; MethodScanner = compiler.MethodScanner; NativePointerSize = Architecture.NativePointerSize; NativeAlignment = Architecture.NativeAlignment; NativeInstructionSize = Architecture.NativeInstructionSize; Is32BitPlatform = Architecture.Is32BitPlatform; Is64BitPlatform = Architecture.Is64BitPlatform; if (Is32BitPlatform) { LoadInstruction = IRInstruction.Load32; StoreInstruction = IRInstruction.Store32; MoveInstruction = IRInstruction.Move32; AddInstruction = IRInstruction.Add32; SubInstruction = IRInstruction.Sub32; BranchInstruction = IRInstruction.Branch32; } else { LoadInstruction = IRInstruction.Load64; StoreInstruction = IRInstruction.Store64; MoveInstruction = IRInstruction.Move64; AddInstruction = IRInstruction.Add64; SubInstruction = IRInstruction.Sub64; BranchInstruction = IRInstruction.Branch64; } Initialize(); } /// <summary> /// Setups the specified compiler. /// </summary> /// <param name="methodCompiler">The compiler.</param> /// <param name="position">The position.</param> public void Setup(MethodCompiler methodCompiler, int position) { MethodCompiler = methodCompiler; BasicBlocks = methodCompiler.BasicBlocks; traceLogs = new List<TraceLog>(); FormattedStageName = $"[{position:00}] {Name}"; Setup(); } protected void Register(Counter counter) { Counters.Add(counter); } public void Execute() { foreach (var counter in Counters) { counter.Reset(); } try { Run(); } catch (Exception ex) { MethodCompiler.Stop(); PostEvent(CompilerEvent.Exception, $"Method: {Method} -> {ex}"); MethodCompiler.Compiler.Stop(); } PostTraceLogs(traceLogs); Finish(); foreach (var counter in Counters) { UpdateCounter(counter); } MethodCompiler = null; traceLogs = null; } protected Operand AllocateVirtualRegister(MosaType type) { return MethodCompiler.VirtualRegisters.Allocate(type); } protected Operand AllocateVirtualRegister(Operand operand) { return MethodCompiler.VirtualRegisters.Allocate(operand.Type); } protected Operand AllocateVirtualRegisterI32() { return MethodCompiler.VirtualRegisters.Allocate(TypeSystem.BuiltIn.I4); } protected Operand AllocateVirtualRegisterI64() { return MethodCompiler.VirtualRegisters.Allocate(TypeSystem.BuiltIn.I8); } protected Operand AllocateVirtualRegisterR4() { return MethodCompiler.VirtualRegisters.Allocate(TypeSystem.BuiltIn.R4); } protected Operand AllocateVirtualRegisterR8() { return MethodCompiler.VirtualRegisters.Allocate(TypeSystem.BuiltIn.R8); } protected Operand AllocateVirtualRegisterObject() { return MethodCompiler.VirtualRegisters.Allocate(TypeSystem.BuiltIn.Object); } protected Operand AllocateVirtualRegisterManagedPointer() { return AllocateVirtualRegisterI(); // temp } protected Operand AllocateVirtualRegisterI() { return Is32BitPlatform ? MethodCompiler.VirtualRegisters.Allocate(TypeSystem.BuiltIn.I4) : MethodCompiler.VirtualRegisters.Allocate(TypeSystem.BuiltIn.I8); } /// <summary> /// Allocates the virtual register or stack slot. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public Operand AllocateVirtualRegisterOrStackSlot(MosaType type) { return MethodCompiler.AllocateVirtualRegisterOrStackSlot(type); } #endregion Methods #region Overrides protected virtual void Initialize() { } protected virtual bool CheckToRun() { return true; } protected virtual void Setup() { } protected virtual void Run() { } protected virtual void Finish() { } #endregion Overrides #region Block Operations /// <summary> /// Create an empty block. /// </summary> /// <returns></returns> protected BasicBlock CreateNewBlock() { return BasicBlocks.CreateBlock(); } /// <summary> /// Create an empty block. /// </summary> /// <param name="blockLabel">The label.</param> /// <returns></returns> protected BasicBlock CreateNewBlock(int blockLabel) { return BasicBlocks.CreateBlock(blockLabel); } /// <summary> /// Creates the new block. /// </summary> /// <param name="blockLabel">The label.</param> /// <param name="instructionLabel">The instruction label.</param> /// <returns></returns> protected BasicBlock CreateNewBlock(int blockLabel, int instructionLabel) { return BasicBlocks.CreateBlock(blockLabel, instructionLabel); } /// <summary> /// Create an empty block. /// </summary> /// <param name="blockLabel">The label.</param> /// <param name="instructionLabel">The instruction label.</param> /// <returns></returns> protected Context CreateNewBlockContext(int blockLabel, int instructionLabel) { return new Context(CreateNewBlock(blockLabel, instructionLabel)); } /// <summary> /// Creates empty blocks. /// </summary> /// <param name="blocks">The Blocks.</param> /// <param name="instructionLabel">The instruction label.</param> /// <returns></returns> protected BasicBlock[] CreateNewBlocks(int blocks, int instructionLabel) { // Allocate the block array var result = new BasicBlock[blocks]; for (int index = 0; index < blocks; index++) { result[index] = CreateNewBlock(-1, instructionLabel); } return result; } /// <summary> /// Create an empty block. /// </summary> /// <param name="instructionLabel">The instruction label.</param> /// <returns></returns> protected Context CreateNewBlockContext(int instructionLabel) { return new Context(CreateNewBlock(-1, instructionLabel)); } /// <summary> /// Creates empty blocks. /// </summary> /// <param name="blocks">The Blocks.</param> /// <param name="instructionLabel">The instruction label.</param> /// <returns></returns> protected Context[] CreateNewBlockContexts(int blocks, int instructionLabel) { // Allocate the context array var result = new Context[blocks]; for (int index = 0; index < blocks; index++) { result[index] = CreateNewBlockContext(instructionLabel); } return result; } /// <summary> /// Splits the block. /// </summary> /// <param name="node">The node.</param> /// <returns></returns> protected BasicBlock Split(InstructionNode node) { var newblock = CreateNewBlock(-1, node.Label); node.Split(newblock); return newblock; } /// <summary> /// Splits the block. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> protected Context Split(Context context) { return new Context(Split(context.Node)); } /// <summary> /// Determines whether [is empty block with single jump] [the specified block]. /// </summary> /// <param name="block">The block.</param> /// <returns> /// <c>true</c> if [is empty block with single jump] [the specified block]; otherwise, <c>false</c>. /// </returns> protected bool IsEmptyBlockWithSingleJump(BasicBlock block) { if (block.NextBlocks.Count != 1) return false; for (var node = block.AfterFirst; !node.IsBlockEndInstruction; node = node.Next) { if (node.IsEmptyOrNop) continue; if (node.Instruction.FlowControl != FlowControl.UnconditionalBranch) return false; } return true; } /// <summary> /// Empties the block of all instructions. /// </summary> /// <param name="block">The block.</param> protected static bool EmptyBlockOfAllInstructions(BasicBlock block, bool useNop = false) { if (block.IsKnownEmpty) return true; bool found = false; for (var node = block.AfterFirst; !node.IsBlockEndInstruction; node = node.Next) { if (node.IsEmpty) continue; if (node.IsNop) { if (!useNop) node.Empty(); continue; } node.SetInstruction(IRInstruction.Nop); found = true; } block.IsKnownEmpty = found; return found; } /// <summary> /// Replaces the branch targets. /// </summary> /// <param name="target">The current from block.</param> /// <param name="oldTarget">The current destination block.</param> /// <param name="newTarget">The new target block.</param> protected void ReplaceBranchTargets(BasicBlock target, BasicBlock oldTarget, BasicBlock newTarget) { for (var node = target.BeforeLast; !node.IsBlockStartInstruction; node = node.Previous) { if (node.IsEmptyOrNop) continue; if (node.BranchTargetsCount == 0) continue; // TODO: When non branch instruction encountered, return (fast out) var targets = node.BranchTargets; for (int index = 0; index < targets.Count; index++) { if (targets[index] == oldTarget) { node.UpdateBranchTarget(index, newTarget); } } } } protected void RemoveEmptyBlockWithSingleJump(BasicBlock block, bool useNop = false) { Debug.Assert(block.NextBlocks.Count == 1); var target = block.NextBlocks[0]; foreach (var previous in block.PreviousBlocks.ToArray()) { ReplaceBranchTargets(previous, block, target); } EmptyBlockOfAllInstructions(block, useNop); Debug.Assert(block.PreviousBlocks.Count == 0); } public static void RemoveBlockFromPHIInstructions(BasicBlock removedBlock, BasicBlock next) { for (var node = next.AfterFirst; !node.IsBlockEndInstruction; node = node.Next) { if (node.IsEmptyOrNop) continue; if (!IsPhiInstruction(node.Instruction)) break; var sourceBlocks = node.PhiBlocks; int index = sourceBlocks.IndexOf(removedBlock); if (index < 0) continue; sourceBlocks.RemoveAt(index); for (int i = index; index < node.OperandCount - 1; index++) { node.SetOperand(i, node.GetOperand(i + 1)); } node.SetOperand(node.OperandCount - 1, null); node.OperandCount--; } } public static void RemoveBlocksFromPHIInstructions(BasicBlock removedBlock, BasicBlock[] nextBlocks) { foreach (var next in nextBlocks) { RemoveBlockFromPHIInstructions(removedBlock, next); } //Debug.Assert(removedBlock.NextBlocks.Count == 0); } public static void UpdatePHIInstructionTargets(List<BasicBlock> targets, BasicBlock source, BasicBlock newSource) { foreach (var target in targets) { UpdatePHIInstructionTarget(target, source, newSource); } } public static void UpdatePHIInstructionTarget(BasicBlock target, BasicBlock source, BasicBlock newSource) { Debug.Assert(target.PreviousBlocks.Count > 0); for (var node = target.AfterFirst; !node.IsBlockEndInstruction; node = node.Next) { if (node.IsEmptyOrNop) continue; if (!IsPhiInstruction(node.Instruction)) break; int index = node.PhiBlocks.IndexOf(source); //Debug.Assert(index >= 0); node.PhiBlocks[index] = newSource; } } #endregion Block Operations #region Protected Region Methods protected MosaExceptionHandler FindImmediateExceptionContext(int label) { foreach (var handler in Method.ExceptionHandlers) { if (handler.IsLabelWithinTry(label) || handler.IsLabelWithinHandler(label)) { return handler; } } return null; } protected MosaExceptionHandler FindNextEnclosingFinallyContext(MosaExceptionHandler exceptionContext) { int index = Method.ExceptionHandlers.IndexOf(exceptionContext); for (int i = index + 1; i < Method.ExceptionHandlers.Count; i++) { var entry = Method.ExceptionHandlers[i]; if (!entry.IsLabelWithinTry(exceptionContext.TryStart)) return null; if (entry.ExceptionHandlerType != ExceptionHandlerType.Finally) continue; return entry; } return null; } protected MosaExceptionHandler _NOT_USED_FindFinallyExceptionContext(InstructionNode node) { int label = node.Block.Label; foreach (var handler in Method.ExceptionHandlers) { if (handler.IsLabelWithinHandler(label)) { return handler; } } return null; } protected bool IsSourceAndTargetWithinSameTryOrException(InstructionNode node) { int leaveLabel = TraverseBackToNonCompilerBlock(node.Block).Label; int targetLabel = TraverseBackToNonCompilerBlock(node.BranchTargets[0]).Label; foreach (var handler in Method.ExceptionHandlers) { bool one = handler.IsLabelWithinTry(leaveLabel); bool two = handler.IsLabelWithinTry(targetLabel); if (one && !two) return false; if (!one && two) return false; if (one && two) return true; one = handler.IsLabelWithinHandler(leaveLabel); two = handler.IsLabelWithinHandler(targetLabel); if (one && !two) return false; if (!one && two) return false; if (one && two) return true; } // very odd return true; } protected BasicBlock TraverseBackToNonCompilerBlock(BasicBlock block) { var start = block; while (start.IsCompilerBlock) { if (!start.HasPreviousBlocks) return null; start = start.PreviousBlocks[0]; // any one } return start; } #endregion Protected Region Methods #region Trace Helper Methods public bool IsTraceable(int traceLevel) { return MethodCompiler.IsTraceable(traceLevel); } protected TraceLog CreateTraceLog(int traceLevel = 0) { if (!IsTraceable(traceLevel)) return null; var traceLog = new TraceLog(TraceType.MethodDebug, MethodCompiler.Method, FormattedStageName, MethodData.Version); traceLogs.Add(traceLog); return traceLog; } public TraceLog CreateTraceLog(string section) { return CreateTraceLog(section, -1); } public TraceLog CreateTraceLog(string section, int traceLevel) { if (traceLevel >= 0 && !IsTraceable(traceLevel)) return null; var traceLog = new TraceLog(TraceType.MethodDebug, MethodCompiler.Method, FormattedStageName, section, MethodData.Version); traceLogs.Add(traceLog); return traceLog; } private void PostTraceLog(TraceLog traceLog) { MethodCompiler.Compiler.PostTraceLog(traceLog); } private void PostTraceLogs(List<TraceLog> traceLogs) { if (traceLogs == null) return; foreach (var traceLog in traceLogs) { if (traceLog != null) { PostTraceLog(traceLog); } } } protected void PostEvent(CompilerEvent compileEvent, string message) { MethodCompiler.Compiler.PostEvent(compileEvent, message, MethodCompiler.ThreadID); } #endregion Trace Helper Methods #region Helper Methods public static bool IsMoveInstruction(BaseInstruction instruction) { return instruction == IRInstruction.Move32 || instruction == IRInstruction.Move64 || instruction == IRInstruction.MoveObject || instruction == IRInstruction.MoveR8 || instruction == IRInstruction.MoveR4; } public static bool IsCompareInstruction(BaseInstruction instruction) { return instruction == IRInstruction.Compare32x32 || instruction == IRInstruction.Compare32x64 || instruction == IRInstruction.Compare64x32 || instruction == IRInstruction.Compare64x64 || instruction == IRInstruction.CompareObject || instruction == IRInstruction.CompareR4 || instruction == IRInstruction.CompareR8; } public static bool IsPhiInstruction(BaseInstruction instruction) { return instruction == IRInstruction.Phi32 || instruction == IRInstruction.Phi64 || instruction == IRInstruction.PhiObject || instruction == IRInstruction.PhiR4 || instruction == IRInstruction.PhiR8; } public static bool IsSSAForm(Operand operand) { return operand.Definitions.Count == 1; } /// <summary> /// Updates the counter. /// </summary> /// <param name="counter">The counter.</param> public void UpdateCounter(Counter counter) { MethodData.Counters.UpdateSkipLock(counter.Name, counter.Count); } /// <summary> /// Gets the size of the type. /// </summary> /// <param name="type">The type.</param> /// <param name="align">if set to <c>true</c> [align].</param> /// <returns></returns> public int GetTypeSize(MosaType type, bool align) { return MethodCompiler.GetReferenceOrTypeSize(type, align); } public List<BasicBlock> AddMissingBlocksIfRequired(List<BasicBlock> blocks) { // make a copy var list = new List<BasicBlock>(blocks.Count); foreach (var block in blocks) { if (block != null) { list.Add(block); } } foreach (var block in BasicBlocks) { if (!blocks.Contains(block)) { // FUTURE: //if (HasProtectedRegions && block.IsCompilerBlock) // continue; list.Add(block); } } return list; } protected BaseInstruction GetLoadInstruction(MosaType type) { if (type.IsReferenceType) return IRInstruction.LoadObject; else if (type.IsPointer) return Select(IRInstruction.Load32, IRInstruction.Load64); if (type.IsPointer) return Select(IRInstruction.Load32, IRInstruction.Load64); else if (type.IsI1) return Select(IRInstruction.LoadSignExtend8x32, IRInstruction.LoadSignExtend8x64); else if (type.IsI2) return Select(IRInstruction.LoadSignExtend16x32, IRInstruction.LoadSignExtend16x64); else if (type.IsI4) return Select(IRInstruction.Load32, IRInstruction.LoadSignExtend32x64); else if (type.IsI8) return IRInstruction.Load64; else if (type.IsU1 || type.IsBoolean) return Select(IRInstruction.LoadZeroExtend8x32, IRInstruction.LoadZeroExtend8x64); else if (type.IsU2 || type.IsChar) return Select(IRInstruction.LoadZeroExtend16x32, IRInstruction.LoadZeroExtend16x64); else if (type.IsU4) return Select(IRInstruction.Load32, IRInstruction.LoadZeroExtend32x64); else if (type.IsU8) return IRInstruction.Load64; else if (type.IsR4) return IRInstruction.LoadR4; else if (type.IsR8) return IRInstruction.LoadR8; else if (Is32BitPlatform) // review return IRInstruction.Load32; else if (Is64BitPlatform) return IRInstruction.Load64; throw new InvalidOperationException(); } public BaseInstruction GetMoveInstruction(MosaType type) { if (type.IsReferenceType) return IRInstruction.MoveObject; if (type.IsPointer) return Select(IRInstruction.Move32, IRInstruction.Move64); else if (type.IsI1) return Select(IRInstruction.SignExtend8x32, IRInstruction.SignExtend8x64); else if (type.IsI2) return Select(IRInstruction.SignExtend16x32, IRInstruction.SignExtend16x64); else if (type.IsI4) return Select(IRInstruction.Move32, IRInstruction.Move32); else if (type.IsI8) return IRInstruction.Move64; else if (type.IsU1 || type.IsBoolean) return Select(IRInstruction.ZeroExtend8x32, IRInstruction.ZeroExtend8x64); else if (type.IsU2 || type.IsChar) return Select(IRInstruction.ZeroExtend16x32, IRInstruction.ZeroExtend16x64); else if (type.IsU4) return Select(IRInstruction.Move32, IRInstruction.ZeroExtend32x64); else if (type.IsU8) return IRInstruction.Move64; else if (type.IsR4) return IRInstruction.MoveR4; else if (type.IsR8) return IRInstruction.MoveR8; else if (Is32BitPlatform) // review return IRInstruction.Move32; else if (Is64BitPlatform) return IRInstruction.Move64; throw new InvalidOperationException(); } protected BaseIRInstruction GetStoreParameterInstruction(MosaType type) { return GetStoreParameterInstruction(type, Is32BitPlatform); } public BaseIRInstruction GetLoadParameterInstruction(MosaType type) { return GetLoadParameterInstruction(type, Is32BitPlatform); } public static BaseIRInstruction GetStoreParameterInstruction(MosaType type, bool is32bitPlatform) { if (type.IsReferenceType) return IRInstruction.StoreParamObject; else if (type.IsR4) return IRInstruction.StoreParamR4; else if (type.IsR8) return IRInstruction.StoreParamR8; else if (type.IsUI1 || type.IsBoolean) return IRInstruction.StoreParam8; else if (type.IsUI2 || type.IsChar) return IRInstruction.StoreParam16; else if (type.IsUI4) return IRInstruction.StoreParam32; else if (type.IsUI8) return IRInstruction.StoreParam64; else if (is32bitPlatform) return IRInstruction.StoreParam32; else //if (!is32bitPlatform) return IRInstruction.StoreParam64; throw new NotSupportedException(); } public static BaseIRInstruction GetLoadParameterInstruction(MosaType type, bool is32bitPlatform) { if (type.IsReferenceType) return IRInstruction.LoadParamObject; else if (type.IsR4) return IRInstruction.LoadParamR4; else if (type.IsR8) return IRInstruction.LoadParamR8; else if (type.IsU1 || type.IsBoolean) return IRInstruction.LoadParamZeroExtend8x32; else if (type.IsI1) return IRInstruction.LoadParamSignExtend8x32; else if (type.IsU2 || type.IsChar) return IRInstruction.LoadParamZeroExtend16x32; else if (type.IsI2) return IRInstruction.LoadParamSignExtend16x32; else if (type.IsUI4) return IRInstruction.LoadParam32; else if (type.IsUI8) return IRInstruction.LoadParam64; else if (type.IsEnum && type.ElementType.IsI4) return IRInstruction.LoadParam32; else if (type.IsEnum && type.ElementType.IsU4) return IRInstruction.LoadParam32; else if (type.IsEnum && type.ElementType.IsUI8) return IRInstruction.LoadParam64; else if (is32bitPlatform) return IRInstruction.LoadParam32; else return IRInstruction.LoadParam64; } public static BaseIRInstruction GetSetReturnInstruction(MosaType type, bool is32bitPlatform) { if (type == null) return null; if (type.IsReferenceType) return IRInstruction.SetReturnObject; else if (type.IsR4) return IRInstruction.SetReturnR4; else if (type.IsR8) return IRInstruction.SetReturnR8; else if (!is32bitPlatform) return IRInstruction.SetReturn64; else if (type.IsUI8 || (type.IsEnum && type.ElementType.IsUI8)) return IRInstruction.SetReturn64; else if (!MosaTypeLayout.CanFitInRegister(type)) return IRInstruction.SetReturnCompound; return IRInstruction.SetReturn32; } public BaseIRInstruction GetStoreInstruction(MosaType type) { if (type.IsReferenceType) return IRInstruction.StoreObject; else if (type.IsR4) return IRInstruction.StoreR4; else if (type.IsR8) return IRInstruction.StoreR8; else if (type.IsUI1 || type.IsBoolean) return IRInstruction.Store8; else if (type.IsUI2 || type.IsChar) return IRInstruction.Store16; else if (type.IsUI4) return IRInstruction.Store32; else if (type.IsUI8) return IRInstruction.Store64; else if (Is32BitPlatform) return IRInstruction.Store32; else if (Is64BitPlatform) return IRInstruction.Store64; throw new NotSupportedException(); } private BaseInstruction Select(BaseInstruction instruction32, BaseInstruction instruction64) { return Is32BitPlatform ? instruction32 : instruction64; } public static void ReplaceOperand(Operand target, Operand replacement) { foreach (var node in target.Uses.ToArray()) { for (int i = 0; i < node.OperandCount; i++) { var operand = node.GetOperand(i); if (target == operand) { node.SetOperand(i, replacement); } } } } protected MosaMethod GetMethod(string namespaceName, string typeName, string methodName) { var type = TypeSystem.GetTypeByName(namespaceName, typeName); if (type == null) return null; var method = type.FindMethodByName(methodName); return method; } protected void ReplaceWithCall(Context context, string namespaceName, string typeName, string methodName) { var method = GetMethod(namespaceName, typeName, methodName); Debug.Assert(method != null, $"Cannot find method: {methodName}"); // FUTURE: throw compiler exception var symbol = Operand.CreateSymbolFromMethod(method, TypeSystem); if (context.OperandCount == 1) { context.SetInstruction(IRInstruction.CallStatic, context.Result, symbol, context.Operand1); } else if (context.OperandCount == 2) { context.SetInstruction(IRInstruction.CallStatic, context.Result, symbol, context.Operand1, context.Operand2); } else { // FUTURE: throw compiler exception } MethodScanner.MethodInvoked(method, Method); } #endregion Helper Methods #region Constant Helper Methods protected Operand CreateConstant32(int value) { return Operand.CreateConstant(TypeSystem.BuiltIn.I4, value); } protected Operand CreateConstant32(uint value) { return Operand.CreateConstant(TypeSystem.BuiltIn.I4, value); } protected Operand CreateConstant32(long value) { return Operand.CreateConstant(TypeSystem.BuiltIn.I8, value); } protected Operand CreateConstant64(long value) { return Operand.CreateConstant(TypeSystem.BuiltIn.I8, value); } protected Operand CreateConstant64(ulong value) { return Operand.CreateConstant(TypeSystem.BuiltIn.I8, value); } protected Operand CreateConstantR4(float value) { return Operand.CreateConstant(TypeSystem.BuiltIn.R4, value); } protected Operand CreateConstantR8(double value) { return Operand.CreateConstant(TypeSystem.BuiltIn.R8, value); } protected static Operand CreateConstant(MosaType type, ulong value) { return Operand.CreateConstant(type, value); } #endregion Constant Helper Methods public void AllStopWithException(string exception) { MethodCompiler.Stop(); MethodCompiler.Compiler.Stop(); throw new CompilerException(exception); } protected bool CheckAllPhiInstructions() { foreach (var block in BasicBlocks) { for (var node = block.AfterFirst; !node.IsBlockEndInstruction; node = node.Next) { if (node.IsEmptyOrNop) continue; if (!IsPhiInstruction(node.Instruction)) break; foreach (var phiblock in node.PhiBlocks) { if (!block.PreviousBlocks.Contains(phiblock)) { throw new CompilerException("CheckAllPhiInstructions() failed in block: {block} at {node}!"); } } } } return true; } } }
namespace AquaServiceSPA.Models { public class Kh2po4: MixtureData { public double Kh2po4g { get; set; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace WaitingListBot.Data { public class Invite { [Key] public int Id { get; set; } public DateTime InviteTime { get; set; } public int NumberOfInvitedUsers { get; set; } public GuildData Guild { get; set; } public ICollection<InvitedUser> InvitedUsers { get; set; } [NotMapped] public string[]? FormatData { get { return JsonConvert.DeserializeObject<string[]>(string.IsNullOrEmpty(FormatDataJson) ? "{}" : FormatDataJson); } set { FormatDataJson = JsonConvert.SerializeObject(value); } } public string FormatDataJson { get; set; } public ulong InviteMessageId { get; set; } public ulong InviteMessageChannelId { get; set; } public ulong? InviteRole { get; set; } public bool? IsInviteRolePositive { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AgendaAPI.Dominio.Entidades; using AgendaAPI.Dominio.Servicos; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AgendaAPI.Controllers { [Route("api/[controller]")] [ApiController] public class TelefonesController : ControllerBase { private readonly ITelefoneServico servico; public TelefonesController(ITelefoneServico servico) { this.servico = servico; } [HttpPost] public ActionResult Post([FromBody] Telefone telefone) { var erros = servico.Criar(telefone); if (erros.Count > 0) { return BadRequest(erros); } return CreatedAtAction("Get", new { id = telefone.Id }, telefone); } [HttpGet("{id}")] public ActionResult Get(int id) { var contato = servico.Obter(id); if (contato == null) return NotFound(); return Ok(contato); } } }
using System; namespace ICOMSProvisioningService { public class LoadBalancerMembers { private string _LBIPAddress; private string _LBIPPort; public string listenerAddress { get { return this._LBIPAddress; } set { this._LBIPAddress = value; } } public string listenerPort { get { return this._LBIPPort; } set { this._LBIPPort = value; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TargetSphereController : MonoBehaviour { /* * This was supposed to be the wizard AOE attack * But things got complicated with that * So now everything is handled by the target script * this can be marked as obsolete */ // Start is called before the first frame update public List<Collider> TriggerList = new List<Collider>(); Collider closestEnemy; void Start() { } private void OnTriggerEnter(Collider other) { if (!TriggerList.Contains(other)) { TriggerList.Add(other); } } private void OnTriggerExit(Collider other) { if (TriggerList.Contains(other)) { TriggerList.Remove(other); } } Transform GetClosestEnemy(List<Transform> enemies, Transform fromThis) { Transform bestTarget = null; float closestDistanceSqr = Mathf.Infinity; Vector3 currentPosition = fromThis.position; foreach (Transform potentialTarget in enemies) { Vector3 directionToTarget = potentialTarget.position - currentPosition; float dSqrToTarget = directionToTarget.sqrMagnitude; if (dSqrToTarget < closestDistanceSqr) { closestDistanceSqr = dSqrToTarget; bestTarget = potentialTarget; } } return bestTarget; } // Update is called once per frame void Update() { // closestEnemy = GetClosestEnemy(TriggerList, this.transform); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using XPowerAPI.Controllers; using XPowerAPI.Models; namespace XPowerAPI.Services.Security { public interface IAuthenticationService : IDisposable { /// <summary> /// Authenticates a user and grants a new session key, should their login be correct /// </summary> /// <param name="request">the request parameters</param> /// <returns>the fresh session key</returns> Task<SessionKey> AuthenticateUser(CustomerSignin request); Task<SessionKey> IsSignedInAsync(string key, bool refresh = false); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Xml; using InvoiceClient.Helper; using InvoiceClient.Properties; using Model.Schema.EIVO; using Model.Schema.TXN; using Utility; namespace InvoiceClient.Agent.POSHelper { public class POSAllowanceWatcher : AllowanceWatcher { public POSAllowanceWatcher(String fullPath) : base(fullPath) { } protected override XmlDocument prepareInvoiceDocument(string invoiceFile) { var docInv = base.prepareInvoiceDocument(invoiceFile); String url = $"{POSReady._Settings.ServiceHost}{POSReady._Settings.VerifyAllowance}"; using (WebClientEx client = new WebClientEx()) { client.Timeout = 43200000; client.Headers[HttpRequestHeader.ContentType] = "application/xml"; client.Encoding = Encoding.UTF8; using (Stream stream = client.OpenWrite(url)) { docInv.Save(stream); docInv.Load(client.Response.GetResponseStream()); } //String result = client.UploadString(url, // docInv.OuterXml); //docInv.LoadXml(result); } return docInv; } protected override Root processUpload(WS_Invoice.eInvoiceService invSvc, XmlDocument docInv) { var result = invSvc.UploadAllowanceV2(docInv).ConvertTo<Root>(); if (result.Result.value == 1) { docInv.TrimAll().ConvertTo<AllowanceRoot>() .ConvertToXml().SaveDocumentWithEncoding(Path.Combine(POSReady._Settings.PreparedAllowance, $"{Guid.NewGuid()}.xml")); } return result; } protected override bool processError(IEnumerable<RootResponseInvoiceNo> rootInvoiceNo, XmlDocument docInv, string fileName) { if (rootInvoiceNo != null && rootInvoiceNo.Count() > 0) { IEnumerable<String> message = rootInvoiceNo.Select(i => String.Format("Allowance No:{0}=>{1}", i.Value, i.Description)); Logger.Warn(String.Format("Transferring fault while uploading allowance file:[{0}], cause:\r\n{1}", fileName, String.Join("\r\n", message.ToArray()))); AllowanceRoot invoice = docInv.TrimAll().ConvertTo<AllowanceRoot>(); AllowanceRoot stored = new AllowanceRoot(); var failedItems = rootInvoiceNo.Where(i => i.ItemIndexSpecified).Select(i => invoice.Allowance[i.ItemIndex]); stored.Allowance = failedItems.ToArray(); stored.ConvertToXml().SaveDocumentWithEncoding(Path.Combine(_failedTxnPath, String.Format("{0}-{1:yyyyMMddHHmmssfff}.xml", Path.GetFileNameWithoutExtension(fileName), DateTime.Now))); if (invoice.Allowance.Length > failedItems.Count()) { stored = new AllowanceRoot { Allowance = invoice.Allowance.Except(failedItems).ToArray() }; stored.ConvertToXml().SaveDocumentWithEncoding(Path.Combine(POSReady._Settings.PreparedAllowance, $"{Guid.NewGuid()}.xml")); } } return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ByteSizeLib; using Serilog; namespace CpanelDdnsProvider { public class Logging { public static readonly ILogger Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.File( "log.txt", rollOnFileSizeLimit: true, fileSizeLimitBytes: (long)ByteSize.FromMegaBytes(5).Bytes, retainedFileCountLimit: 10, rollingInterval: RollingInterval.Infinite ) .WriteTo.Trace() .CreateLogger(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace abstAndInter { abstract class AbstractHandler { abstract protected void Open(); abstract public void Create(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Erwine.Leonard.T.ExtensionMethods.AttributeTypes { public static class EnumExtensions { public static TAttribute[] GetEnumAttributes<TEnum, TAttribute>(this TEnum value) where TEnum : struct, IComparable, IFormattable, IConvertible where TAttribute : Attribute { Type t = value.GetType(); if (!t.IsEnum) throw new ArgumentException(String.Format("{0} is not an enumerated type.", t.FullName), "value"); return t.GetField(Enum.GetName(t, value)).GetAttributesOfType<TAttribute>(false); } } }
using System; namespace ExercicioElevador.Classes { public abstract class Elevador { protected int andarAtual; protected int totalAndares; protected int capacidade; protected int quantiaPessoas; public void Inicializar(int capacidadeD, int totalAndaresD){ //inicia o elevado dando o total de andares, capacidade, andar terreo e 0 pessoas andarAtual = 0; quantiaPessoas = 0; capacidade = capacidadeD; totalAndares = totalAndaresD; } public virtual string Mostrar(){ return $"O elevador está no {andarAtual} andar, tem {capacidade} de capacidade e tem {quantiaPessoas} pessoas"; } public virtual int Entrar(){ if (quantiaPessoas < capacidade) { Console.WriteLine($"Tinham {quantiaPessoas} no elevador, entrou 1 pessoa, agora temos {quantiaPessoas + 1} pessoas"); quantiaPessoas = quantiaPessoas + 1; } else { Console.WriteLine($"O elevador está cheio, a capacidade de {capacidade} foi atingida"); } return quantiaPessoas; } public int Sair(){ if (quantiaPessoas > 0) { Console.WriteLine($"Tinham {quantiaPessoas} no elevador, saiu 1, agora temos {quantiaPessoas - 1} pessoas"); quantiaPessoas = quantiaPessoas - 1; } else{ Console.WriteLine("O elevador está vazio"); } return quantiaPessoas; } public int Subir(){ Console.WriteLine("Para qual andar você quer ir?"); int andarIr = int.Parse(Console.ReadLine()); if(andarIr < andarAtual){ Console.WriteLine("Não dá para subir para baixo!"); } else if (andarIr <= totalAndares) { Console.WriteLine($"Estavamos no {andarAtual} andar, subimos e agora estamos no {andarIr} andar"); andarAtual = andarIr; } else{ Console.WriteLine("Não é possível ir para esse andar!"); } return andarAtual; } public int Descer(){ Console.WriteLine("Para qual andar você quer ir?"); int andarIr = int.Parse(Console.ReadLine()); if(andarIr > andarAtual){ Console.WriteLine("Não dá para descer para cima!"); } else if (andarIr <= totalAndares && andarIr >= 0) { Console.WriteLine($"Estavamos no {andarAtual} andar, descemos e agora estamos no {andarIr} andar"); andarAtual = andarIr; } else { Console.WriteLine("Não é possível ir para esse andar!"); } return andarAtual; } } }
using ImpostoDeRenda.Domain; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ImpostoDeRenda.Repository { public class ReportRepository { private static ReportRepository reportRepository; private ReportRepository() { } public static ReportRepository GetInstance() { if (reportRepository == null) { reportRepository = new ReportRepository(); } return reportRepository; } public void WriteReport(IList<ImpostoDeRendaReport> impostoDeRendaReports, string file) { using (StreamWriter fileWriter = GetStreamWriter(file)) { foreach (var impostoReport in impostoDeRendaReports) { fileWriter.WriteLine(string.Format("{0} com CPF - {1} e renda total R$ {2:0.00} tem retido um total de R$ {3:0.00} devido ao imposto de renda sobre uma renda taxável de R$ {4:0.00}", impostoReport.Pessoa.Nome, impostoReport.Pessoa.CPF, impostoReport.RendaTotal, impostoReport.ImpostoRetido, impostoReport.RendaTaxavel)); } } } private StreamWriter GetStreamWriter(string file) { return string.IsNullOrEmpty(file) ? new StreamWriter(Console.OpenStandardOutput()) : new StreamWriter(file); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CIS420Redux.Models.ViewModels.POS { public class PotentialClassIndexViewModel { public int Id { get; set; } public CIS420Redux.Models.POS CourseList { get; set; } public CIS420Redux.Models.Student posImage { get; set; } } }
// Accord Imaging Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Imaging.Filters { using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; /// <summary> /// Concatenation filter. /// </summary> /// /// <remarks> /// Concatenates two images side by side in a single image. /// </remarks> /// public class Concatenate : BaseTransformationFilter { private Bitmap overlayImage; private Dictionary<PixelFormat, PixelFormat> formatTranslations = new Dictionary<PixelFormat, PixelFormat>(); /// <summary> /// Format translations dictionary. /// </summary> public override Dictionary<PixelFormat, PixelFormat> FormatTranslations { get { return formatTranslations; } } /// <summary> /// Creates a new concatenation filter. /// </summary> /// <param name="overlayImage">The first image to concatenate.</param> public Concatenate(Bitmap overlayImage) { this.overlayImage = overlayImage; formatTranslations[PixelFormat.Format8bppIndexed] = PixelFormat.Format8bppIndexed; formatTranslations[PixelFormat.Format24bppRgb] = PixelFormat.Format24bppRgb; formatTranslations[PixelFormat.Format32bppRgb] = PixelFormat.Format32bppRgb; formatTranslations[PixelFormat.Format32bppArgb] = PixelFormat.Format32bppArgb; formatTranslations[PixelFormat.Format16bppGrayScale] = PixelFormat.Format16bppGrayScale; formatTranslations[PixelFormat.Format48bppRgb] = PixelFormat.Format48bppRgb; formatTranslations[PixelFormat.Format64bppArgb] = PixelFormat.Format64bppArgb; } /// <summary> /// Calculates new image size. /// </summary> protected override Size CalculateNewImageSize(UnmanagedImage sourceData) { int finalWidth = overlayImage.Width + sourceData.Width; int finalHeight = System.Math.Max(overlayImage.Height, sourceData.Height); return new Size(finalWidth, finalHeight); } /// <summary> /// Process the filter on the specified image. /// </summary> /// /// <param name="sourceData">Source image data.</param> /// <param name="destinationData">Destination image data.</param> /// protected override void ProcessFilter(UnmanagedImage sourceData, UnmanagedImage destinationData) { // Lock the overlay image (left image) BitmapData overlayData = overlayImage.LockBits( new Rectangle(0, 0, overlayImage.Width, overlayImage.Height), ImageLockMode.ReadOnly, overlayImage.PixelFormat); int dstHeight = destinationData.Height; int src1Height = overlayData.Height; int src2Height = sourceData.Height; int src1Stride = overlayData.Stride; int src2Stride = sourceData.Stride; int dstStride = destinationData.Stride; int pixelSize = System.Drawing.Image.GetPixelFormatSize(sourceData.PixelFormat) / 8; int copySize1 = overlayData.Width * pixelSize; int copySize2 = sourceData.Width * pixelSize; // do the job unsafe { byte* src1 = (byte*)overlayData.Scan0.ToPointer(); byte* src2 = (byte*)sourceData.ImageData.ToPointer(); byte* dst = (byte*)destinationData.ImageData.ToPointer(); // for each line for (int y = 0; y < dstHeight; y++) { if (y < src1Height) Accord.SystemTools.CopyUnmanagedMemory(dst, src1, copySize1); if (y < src2Height) Accord.SystemTools.CopyUnmanagedMemory(dst + copySize1, src2, copySize2); src1 += src1Stride; src2 += src2Stride; dst += dstStride; } } // Release overlayImage.UnlockBits(overlayData); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Sunny.Lib.DllHelper { public class SunnyDll { /* * EntryPoint: 指定要调用的 DLL 入口点。默认入口点名称是托管方法的名称 。 CharSet: 控制名称重整和封送 String 参数的方式 (默认是UNICODE) CallingConvention指示入口点的函数调用约定(默认WINAPI)(上次报告讲过的) SetLastError 指示被调用方在从属性化方法返回之前是否调用 SetLastError Win32 API 函数 (C#中默认false ) int 类型 */ [DllImport("SunnyDll.dll", EntryPoint = "GetSecurityString")] public static extern IntPtr GetSecurityString(SecurityStringType securityStringType); } public class SunnyDllHelper { public static string GetSecurityString(SecurityStringType securityStringType) { string securityStr = string.Empty; IntPtr intP = SunnyDll.GetSecurityString(securityStringType); securityStr = Marshal.PtrToStringAnsi(intP); return securityStr; } } public enum SecurityStringType { EncryptKey8 = 1, EncryptKey16 = 2, EncryptKey24 = 3, EncryptKey32 = 4, EncryptIv8 = 5, EncryptIv16 = 6, } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using MyFirstWebAPI.Models; namespace MyFirstWebAPI.Controllers { [Route("api/[controller]")] public class TodoController : Controller { // GET api/values [HttpGet] [Produces(typeof(Todo))] public IEnumerable<Todo> Get() { return new List<Todo>() { new Todo() { Id = 1, Caption = "Some todo title", Note = "do something" }, new Todo() { Id = 2, Caption = "Some todo title 2", Note = "do something" } }; } // GET api/values/5 [HttpGet("{id}")] [Produces("application/json", Type = typeof(Todo))] public Todo Get(int id) { return new Todo() { Id = id, Caption = $"Some todo title {id}", Note = "do something" }; } // POST api/values [HttpPost] [Consumes("application/json")] [Produces("application/json", Type = typeof(Todo))] public IActionResult Post([FromBody]Todo value) { if (!ModelState.IsValid) { return BadRequest(ModelState); } return CreatedAtAction("Get", new { id = value.Id }, value); } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
using SharpML.Recurrent.DataStructs; using SharpML.Recurrent.Loss; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Types; namespace RnnCenter { internal class CustomDataSet : DataSet { public CustomDataSet(Config config) { Training = CreateSequences(config.RnnTrainXFile, config.RnnTrainYFile); Validation = CreateSequences(config.RnnValidXFile, config.RnnValidYFile); Testing = CreateSequences(config.RnnTestXFile, config.RnnTestYFile); InputDimension = Training[0].Steps[0].Input.Rows; OutputDimension = Training[0].Steps[0].TargetOutput.Rows; LossTraining = new LossSumOfSquares(); LossReporting = new LossSumOfSquares(); } private List<DataSequence> CreateSequences(string xFilename, string yFilename) { double[][] x = LoadCsv(xFilename); double[][] y = LoadCsv(yFilename); // Create sequences List<DataSequence> sequences = new List<DataSequence>(); DataSequence ds = new DataSequence(); sequences.Add(ds); ds.Steps = new List<DataStep>(); for (int i = 0; i < x.Length; ++i) ds.Steps.Add(new DataStep(x[i], y[i])); return sequences; } private double[][] LoadCsv(string filename) { return File.ReadAllLines(filename).Select(x => x.Split(new char[] { ';' }).Select(y => double.Parse(y)).ToArray()).ToArray(); } } }
using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Vaccination.Models; using Microsoft.AspNetCore.Identity; namespace Vaccination.Data { public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole {Id = "99", Name = "admin", NormalizedName = "ADMIN".ToUpper() }); var hasher = new PasswordHasher<IdentityUser>(); modelBuilder.Entity<IdentityUser>().HasData( new IdentityUser { Id = "66", UserName = "admin@admin.com", NormalizedUserName = "ADMIN@ADMIN.COM", PasswordHash = hasher.HashPassword(null, "Gftadmin#2021"), EmailConfirmed = true, PhoneNumber = "66669995", PhoneNumberConfirmed = true, AccessFailedCount = 0, Email = "admin@admin.com", NormalizedEmail = "ADMIN@ADMIN.COM", LockoutEnabled = true, TwoFactorEnabled = false } ); modelBuilder.Entity<IdentityUserRole<string>>().HasData( new IdentityUserRole<string> { RoleId = "99", UserId = "66" } ); } public DbSet<Person> People { get; set; } public DbSet<Address> Addresses { get; set; } public DbSet<VaccinationRecord> VaccinationRecords { get; set; } public DbSet<VaccinationPoint> VaccinationPoints { get; set; } public DbSet<Vaccine> Vaccines { get; set; } public DbSet<VaccineBatch> VaccineBatches { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Asteroid : MonoBehaviour { public float speed = 4f; private Vector3 direction; public Rigidbody2D theRB; public int damageGive; public float scaler; public int health; public int value; public GameObject deathEffect; public GameObject bombEffect; // Start is called before the first frame update void Start() { transform.rotation = Quaternion.Euler(0, 0, Random.Range(0, 360)); speed = Random.Range(0f, 4f); scaler = Random.Range(0.5f, 2f); transform.localScale = new Vector3(scaler, scaler, 1); if(scaler<2f) { damageGive = 3; health = 1; value = 75; } if(scaler<1.5f) { damageGive = 2; health = 1; value = 50; } if(scaler<0.75f) { damageGive = 1; health = 1; value = 25; } } // Update is called once per frame void Update() { theRB.velocity = transform.up * speed; if(health<=0) { Instantiate(deathEffect, transform.position, transform.rotation); Destroy(gameObject); } if (PlayerControl.instance.bombTime > 0) { Instantiate(bombEffect, transform.position, transform.rotation); Destroy(gameObject); } } private void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Player") { other.GetComponent<PlayerControl>().DamagePlayer(1); Instantiate(bombEffect, transform.position, transform.rotation); Destroy(gameObject); } if (other.tag == "Enviroment") { health = 0; } if (other.tag == "Enemy") { other.GetComponent<EnemyControl>().DamageEnemy(damageGive); Instantiate(bombEffect, transform.position, transform.rotation); Destroy(gameObject); } if(other.tag == "Bullet") { health--; if(health<=0) { Instantiate(bombEffect, transform.position, transform.rotation); PlayerControl.instance.GainPoints(value); Destroy(gameObject); } } } }
/* Sodasaurus.cs * Author: Ben Hartman */ using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; namespace DinoDiner.Menu { /// <summary> /// Sodasaurus class, inherits from the Drink class. /// </summary> public class Sodasaurus : Drink, IMenuItem, IOrderItem { /// <summary> /// Gets a description of this order item. /// </summary> public override string Description { get { return this.ToString(); } } /// <summary> /// Gets any special instructions for this order item. /// </summary> public override string[] Special { get { List<string> special = new List<string>(); if (!Ice) special.Add("Hold Ice"); return special.ToArray(); } } /// <summary> /// Class constructor to set the price, calories, and ingredients. /// </summary> public Sodasaurus() { Price = 1.50; this.Calories = 112; Ice = true; Category = "Drink"; } /// <summary> /// backing variable for the flavor. /// </summary> private SodasaurusFlavor flavor; /// <summary> /// Property for the flavor. /// </summary> public SodasaurusFlavor Flavor { get { return flavor; } set { flavor = value; NotifyOfPropertyChange("Description"); } } /// <summary> /// Backing variable for the Size property. /// </summary> private Size size = Size.Small; /// <summary> /// Property to get or set the size. /// </summary> public override Size Size { get { return size; } set { size = value; switch(size) { case Size.Large: Price = 2.50; this.Calories = 208; break; case Size.Medium: Price = 2.00; this.Calories = 156; break; case Size.Small: Price = 1.50; this.Calories = 112; break; } NotifyOfPropertyChange("Description"); NotifyOfPropertyChange("Price"); } } /// <summary> /// Property to return a list of the Ingredients. /// </summary> public override List<string> Ingredients { get { return new List<string>() { "Water", "Natural Flavors", "Cane Sugar" }; } } /// <summary> /// Method to override ToString() to return name of item. /// </summary> /// <returns></returns> public override string ToString() { return $"{Flavor} Sodasaurus"; } } }
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using Karkas.Core.Utility.ReportingServicesHelper; public partial class Ornekler_RaporOrnekleri_RaporKopyalaveDataSourceSetleme : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void ButtonRaporAc_Click(object sender, EventArgs e) { string raporDizin = "/OrnekRaporlar/ReportMusteriBilgileri"; KarkasRapor rapor = new KarkasRapor(raporDizin); rapor.OnBeforeRaporAl += new BeforeRaporAl(KarkasRapor_OnBeforeRaporAl); rapor.RaporDosyaAd = "ReportMusteriBilgileri"; rapor.RaporFormat = RaporFormats.PDF; rapor.ParametreEkle("Adi", TextBoxAdi.Text); rapor.ParametreEkle("Soyadi", TextBoxSoyadi.Text); rapor.RaporAc(); } void KarkasRapor_OnBeforeRaporAl(KarkasRapor rapor) { RaporuKopyalaVeDataSourceunuAta(rapor); } public void RaporuKopyalaVeDataSourceunuAta(KarkasRapor rapor) { string[] splitted = rapor.RaporAd.Split('/'); string yeniRaporAd = splitted[splitted.Length - 1]; splitted[splitted.Length - 1] = String.Empty; string raporYolu = String.Join("/", splitted).TrimEnd('/'); if (!rapor.RaporVarMi(yeniRaporAd, raporYolu)) { rapor.RaporKopyalaVeDataSourceunuAta(yeniRaporAd, raporYolu, "OrnekRaporlar", raporYolu, "OrnekRaporlar"); } rapor.RaporAd = String.Format("{0}/{1}", raporYolu, yeniRaporAd); } }
using System.Data.Entity.ModelConfiguration; using RMAT3.Models; namespace RMAT3.Data.Mapping { public class PolicyLocationMap : EntityTypeConfiguration<PolicyLocation> { public PolicyLocationMap() { // Primary Key HasKey(t => t.PolicyLocationId); // Properties Property(t => t.AddedByUserId) .IsRequired() .HasMaxLength(20); Property(t => t.UpdatedByUserId) .IsRequired() .HasMaxLength(20); Property(t => t.PolicyLocationNbr) .HasMaxLength(50); Property(t => t.PolicyNbr) .IsRequired() .HasMaxLength(50); // Table & Column Mappings ToTable("PolicyLocation", "OLTP"); Property(t => t.PolicyLocationId).HasColumnName("PolicyLocationId"); Property(t => t.AddedByUserId).HasColumnName("AddedByUserId"); Property(t => t.AddTs).HasColumnName("AddTs"); Property(t => t.UpdatedByUserId).HasColumnName("UpdatedByUserId"); Property(t => t.UpdatedTs).HasColumnName("UpdatedTs"); Property(t => t.IsActiveInd).HasColumnName("IsActiveInd"); Property(t => t.PolicyLocationEffectiveDt).HasColumnName("PolicyLocationEffectiveDt"); Property(t => t.PolicyLocationExpirationDt).HasColumnName("PolicyLocationExpirationDt"); Property(t => t.PolicyLocationNbr).HasColumnName("PolicyLocationNbr"); Property(t => t.PolicyNbr).HasColumnName("PolicyNbr"); Property(t => t.LocationId).HasColumnName("LocationId"); // Relationships HasRequired(t => t.Location) .WithMany(t => t.PolicyLocations) .HasForeignKey(d => d.LocationId); HasRequired(t => t.Policy) .WithMany(t => t.PolicyLocations) .HasForeignKey(d => d.PolicyNbr); } } }
using AmWell.Resources.DTO.Response; using AmWell.Resources.DAL; using AmWell.Resources.DTO.Request; using AmWell.Resources.DTO.Response; using AmWellEntity = AmWell.Resources.Entities; using AmWell.Resources.Logging.CustomException; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web; using AmWell.Resources.Caching; using AmWell.Resources.Logging.Logger; namespace AmWell.Web.API.Controllers { public class ItemController : ApiController { private readonly IDalFactory _dalFactory = null; public ItemController() { if (_dalFactory == null) { _dalFactory = (IDalFactory)HttpContext.Current.Application["DalFactory"]; } } private ICacheProvider CacheProvider { get { return (ICacheProvider)HttpContext.Current.Application["CacheProvider"]; } } // GET: api/Product [HttpGet] public GetItemsResponseDto GetItemsBySubCatId(int productSubCatId) { var response = new GetItemsResponseDto(); var items = new List<AmWellEntity.Item>(); items = this.CacheProvider.GetCacheItem(CacheConstants.GetItemsBySubCatIdCacheKey + productSubCatId, CacheConstants.GetItemsBySubCatIdCacheKey) as List<AmWellEntity.Item>; //not in cache then pull records from db if (items == null || items.Count <= 0) { items = _dalFactory.GetItemsBySubCatId(productSubCatId); //adding records into cache this.CacheProvider.AddCacheItem(CacheConstants.GetItemsBySubCatIdCacheKey + productSubCatId, CacheConstants.GetItemsBySubCatIdCacheKey, items); } response.Items = items; return response; } [HttpGet] public GetItemDetailResponseDto GetItemByItemId(int itemId) { var response = new GetItemDetailResponseDto(); var item = new AmWellEntity.Item(); item = this.CacheProvider.GetCacheItem(CacheConstants.GetItemByItemIdCacheKey + itemId, CacheConstants.GetItemByItemIdCacheKey) as AmWellEntity.Item; //not in cache then pull records from db if (item == null) { item = _dalFactory.GetItemByItemId(itemId); //adding records into cache this.CacheProvider.AddCacheItem(CacheConstants.GetItemByItemIdCacheKey + itemId, CacheConstants.GetItemByItemIdCacheKey, item); } response.Item = item; return response; } // GET: api/Product [HttpGet] public GetItemsResponseDto GetItemsByCatId(int catId) { var response = new GetItemsResponseDto(); var items = new List<AmWellEntity.Item>(); items = this.CacheProvider.GetCacheItem(CacheConstants.GetItemsByCatIdCacheKey + catId, CacheConstants.GetItemsByCatIdCacheKey) as List<AmWellEntity.Item>; //not in cache then pull records from db if (items == null || items.Count <= 0) { items = _dalFactory.GetItemsByCatId(catId); //adding records into cache this.CacheProvider.AddCacheItem(CacheConstants.GetItemsByCatIdCacheKey + catId, CacheConstants.GetItemsByCatIdCacheKey, items); } response.Items = items; return response; } // GET: api/Product [HttpGet] public GetItemsResponseDto GetFeaturedItems() { var response = new GetItemsResponseDto(); var items = new List<AmWellEntity.Item>(); items = this.CacheProvider.GetCacheItem(CacheConstants.GetFeaturedItemsCacheKey , CacheConstants.GetFeaturedItemsCacheKey) as List<AmWellEntity.Item>; //not in cache then pull records from db if (items == null || items.Count <= 0) { items = _dalFactory.GetFeaturedItems(); //adding records into cache this.CacheProvider.AddCacheItem(CacheConstants.GetFeaturedItemsCacheKey , CacheConstants.GetFeaturedItemsCacheKey, items); } response.Items = items; return response; } [HttpPost] public AddItemResponseDto AddItem([FromBody]AddItemRequestDto request) { if (request == null || request.Item == null) throw new AmWellApiException("Request object is invalid"); var response = new AddItemResponseDto() { IsAdded = _dalFactory.AddItem(request.Item) }; if (response.IsAdded) { response.RowAffected = 1; response.StatusDescription = "Item Added Successfully"; } else { response.RowAffected = 0; response.StatusDescription = "Item Not Added"; } return response; } // GET: api/Item public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET: api/Item/5 public string Get(int id) { return "value"; } // POST: api/Item public void Post([FromBody]string value) { } // PUT: api/Item/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/Item/5 public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Text; namespace Turnamentor.Core.Loading { class BothTypeLoader : ITypeLoader { SourceCodeTypeLoader sourceCodeLoader = new SourceCodeTypeLoader(); AssemblyTypeLoader assemblyLoder = new AssemblyTypeLoader(); public IList<Type> LoadTypes<T>(IEnumerable<string> directories) { var res1 = sourceCodeLoader.LoadTypes<T>(directories); var res2 = assemblyLoder.LoadTypes<T>(directories); return res1.Concat(res2).ToList(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Factory { public class ConnectionFactory { public IDbConnection GetConnection() { IDbConnection conexao = new SqlConnection; conexao.ConnectionString = "String De Coneccao"; conexao.Open(); return conexao; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using CoinBot.Core; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace CoinBot.Clients.Kraken { public class KrakenClient : IMarketClient { /// <summary> /// The <see cref="CurrencyManager"/>. /// </summary> private readonly CurrencyManager _currencyManager; /// <summary> /// The Exchange name. /// </summary> public string Name => "Kraken"; /// <summary> /// The <see cref="Uri"/> of the CoinMarketCap endpoint. /// </summary> private readonly Uri _endpoint = new Uri("https://api.kraken.com/0/public/", UriKind.Absolute); /// <summary> /// The <see cref="HttpClient"/>. /// </summary> private readonly HttpClient _httpClient; /// <summary> /// The <see cref="ILogger"/>. /// </summary> private readonly ILogger _logger; /// <summary> /// The <see cref="JsonSerializerSettings"/>. /// </summary> private readonly JsonSerializerSettings _serializerSettings; public KrakenClient(ILogger logger, CurrencyManager currencyManager) { this._logger = logger ?? throw new ArgumentNullException(nameof(logger)); this._currencyManager = currencyManager ?? throw new ArgumentNullException(nameof(currencyManager)); this._httpClient = new HttpClient { BaseAddress = this._endpoint }; this._serializerSettings = new JsonSerializerSettings { Error = (sender, args) => { EventId eventId = new EventId(args.ErrorContext.Error.HResult); Exception ex = args.ErrorContext.Error.GetBaseException(); this._logger.LogError(eventId, ex, ex.Message); } }; } /// <inheritdoc/> public async Task<IReadOnlyCollection<MarketSummaryDto>> Get() { try { List<KrakenAsset> assets = await this.GetAssets(); List<KrakenPair> pairs = await this.GetPairs(); List<KrakenTicker> tickers = new List<KrakenTicker>(); foreach (KrakenPair pair in pairs) { // todo: can't get kraken details on these markets if (pair.PairId.EndsWith(".d")) continue; tickers.Add(await this.GetTicker(pair)); } return tickers.Select(m => { string baseCurrency = assets.Find(a => a.Id.Equals(m.BaseCurrency)).Altname; string quoteCurrency = assets.Find(a => a.Id.Equals(m.QuoteCurrency)).Altname; // Workaround for kraken if (baseCurrency.Equals("xbt", StringComparison.OrdinalIgnoreCase)) baseCurrency = "btc"; if (quoteCurrency.Equals("xbt", StringComparison.OrdinalIgnoreCase)) quoteCurrency = "btc"; return new MarketSummaryDto { BaseCurrrency = this._currencyManager.Get(baseCurrency), MarketCurrency = this._currencyManager.Get(quoteCurrency), Market = "Kraken", Volume = m.Volume[1], Last = m.Last[0] }; }).ToList(); } catch (Exception e) { this._logger.LogError(new EventId(e.HResult), e, e.Message); throw; } } /// <summary> /// Get the ticker. /// </summary> /// <returns></returns> private async Task<List<KrakenAsset>> GetAssets() { using (HttpResponseMessage response = await this._httpClient.GetAsync(new Uri("Assets", UriKind.Relative))) { string json = await response.Content.ReadAsStringAsync(); JObject jObject = JObject.Parse(json); List<KrakenAsset> assets = jObject.GetValue("result").Children().Cast<JProperty>().Select(property => { KrakenAsset asset = JsonConvert.DeserializeObject<KrakenAsset>(property.Value.ToString(), this._serializerSettings); asset.Id = property.Name; return asset; }).ToList(); return assets; } } /// <summary> /// Get the market summaries. /// </summary> /// <returns></returns> private async Task<List<KrakenPair>> GetPairs() { using (HttpResponseMessage response = await this._httpClient.GetAsync(new Uri("AssetPairs", UriKind.Relative))) { string json = await response.Content.ReadAsStringAsync(); JObject jResponse = JObject.Parse(json); List<KrakenPair> pairs = jResponse.GetValue("result").Children().Cast<JProperty>().Select(property => { KrakenPair pair = JsonConvert.DeserializeObject<KrakenPair>(property.Value.ToString()); pair.PairId = property.Name; return pair; }).ToList(); return pairs; } } /// <summary> /// Get the ticker. /// </summary> /// <returns></returns> private async Task<KrakenTicker> GetTicker(KrakenPair pair) { using (HttpResponseMessage response = await this._httpClient.GetAsync(new Uri($"Ticker?pair={pair.PairId}", UriKind.Relative))) { string json = await response.Content.ReadAsStringAsync(); JObject jObject = JObject.Parse(json); KrakenTicker ticker = JsonConvert.DeserializeObject<KrakenTicker>(jObject["result"][pair.PairId].ToString(), this._serializerSettings); ticker.BaseCurrency = pair.BaseCurrency; ticker.QuoteCurrency = pair.QuoteCurrency; return ticker; } } } }
using System; namespace API.DTOs { public class EventDto { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } public DateTime StartTime { get; set; } public DateTime FinishTime { get; set; } public string Theme { get; set; } public string Subtheme { get; set; } public string ExpectedTimeSpent { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using HardcoreHistoryBlog.Data; using HardcoreHistoryBlog.Models; using HardcoreHistoryBlog.Models.Blog_Models; using HardcoreHistoryBlog.Models.Comments; using HardcoreHistoryBlog.ViewModels; using Microsoft.EntityFrameworkCore; namespace HardcoreHistoryBlog.Core { public interface IRepository { Post GetPost(int id); List<Post> GetAllPosts(); List<Post> GetAllPosts(string Category); void AddPost(Post post); void UpdatePost(Post post); void RemovePost(int id); void AddSubComment(SubComment comment); void RemoveComment(int id); void GetUsers(); void AddUser(ApplicationUser user); List<ApplicationRole> AllRoles(); ApplicationRole GetRole(string id); void AddRole(ApplicationRole role); void UpdateRole(ApplicationRole role); ApplicationUser GetUser(string Id); Task<bool> SaveChangesAsync(); } }
using System.Web.Mvc; using WebAppSpotifyConsumer.Models; namespace WebAppSpotifyConsumer.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.AuthUri = GetAuthUri(); return View(); } public ActionResult AuthResponse(string access_token, string token_type, string expires_in, string state) { if (string.IsNullOrEmpty(access_token)) return View(); else { Session["token"] = access_token; return RedirectToAction("ShowPlaylists"); } return View(); } public ActionResult ShowPlaylists() { if (string.IsNullOrEmpty(Session["token"].ToString())) return View("Index"); var access_token = Session["token"].ToString(); SpotifyService spotifyService = new SpotifyService(); SpotifyUser spotifyUser = spotifyService.GetUserProfile(access_token); Playlists playlists = spotifyService.GetPlaylists(spotifyUser.UserId, access_token); ViewBag.Playlists = playlists; return View(); } private string GetAuthUri() { string clientId = "your-client-id"; string redirectUri = "http://localhost:17789/Home/AuthResponse"; Scope scope = Scope.PLAYLIST_MODIFY_PRIVATE; return "https://accounts.spotify.com/en/authorize?client_id=" + clientId + "&response_type=token&redirect_uri=" + redirectUri + "&state=&scope=" + scope.GetStringAttribute(" ") + "&show_dialog=true"; } } }
using System; namespace cn.bmob.io { /// <summary> /// Bmob自定义的序列化反序列化的对象,Hashtable仅支持简单类型和Hashtable。对象就是简单类型的组合! /// </summary> public interface IBmobWritable { /// <summary> /// 获取自定义对象的类型 /// </summary> string _type { get; } /// <summary> /// 把服务端返回的数据转化为本地对象值 /// </summary> /// <param name="input"></param> void readFields(BmobInput input); /// <summary> /// 把本地对象写入到output,后续序列化提交到服务器 /// </summary> /// <param name="output"></param> /// <param name="all">用于区分请求/打印输出序列化</param> void write(BmobOutput output, Boolean all); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Windows; namespace Panacea.Multilinguality { [DataContract] public abstract class Translatable :INotifyPropertyChanged { protected Dictionary<string, Dictionary<string, object>> _translations; protected Dictionary<string, object> _defaults; public event PropertyChangedEventHandler PropertyChanged; protected Dictionary<string, object> Defaults { get { return _defaults; } set { _defaults = value; } } public Translatable() { Defaults = new Dictionary<string, object>(); WeakEventManager<LanguageContext, EventArgs> .AddHandler(LanguageContext.Instance, nameof(LanguageContext.CultureChanged), OnLanguageChanged); } protected string GetTranslation([CallerMemberName] string prop = null) { var pi = GetType().GetProperty(prop); if (pi == null) return null; var jsonName = prop; var dm = pi.GetCustomAttribute<DataMemberAttribute>(); if (dm != null) jsonName = dm.Name; if (Translations != null && Translations.ContainsKey(jsonName) && Translations[jsonName].ContainsKey(LanguageContext.Instance.Culture.Name)) return Translations[jsonName][LanguageContext.Instance.Culture.Name].ToString(); if (Defaults.ContainsKey(prop)) return Defaults[prop].ToString(); return null; } protected void SetTranslation(string val, [CallerMemberName] string prop = null) { if (!Defaults.ContainsKey(prop)) Defaults[prop] = val; } protected TranslatableDictionary GetTranslations([CallerMemberName] string prop = null) { var pi = GetType().GetProperty(prop); if (pi == null) return null; var jsonName = prop; var dm = pi.GetCustomAttribute<DataMemberAttribute>(); if (dm != null) jsonName = dm.Name; var dict = Translations[jsonName]; if (!Defaults.ContainsKey(prop)) return null; foreach (var key in dict.Keys) { var trans = dict[key] as Dictionary<string, string>; if (trans.ContainsKey(LanguageContext.Instance.Culture.Name)) { (Defaults[prop] as TranslatableDictionary).SetString(key, trans[LanguageContext.Instance.Culture.Name].ToString()); } } return Defaults[prop] as TranslatableDictionary; } protected void SetTranslations(TranslatableDictionary val, [CallerMemberName] string prop = null) { if (!Defaults.ContainsKey(prop)) Defaults.Add(prop, val); } [DataMember(Name = "trans")] public Dictionary<string, Dictionary<string, object>> Translations { get { return _translations; } set { _translations = value; OnLanguageChanged(null, null); } } protected void OnLanguageChanged(object sender, EventArgs e) { Type t = GetType(); var plist = t.GetProperties().Where(p => p.GetCustomAttributes(typeof(IsTranslatableAttribute)).Any()); foreach ( PropertyInfo pi in plist) { OnPropertyChanged(pi.Name); } } protected virtual void OnPropertyChanged([CallerMemberName] string name = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } } }
using System; using Android.Webkit; namespace Xam.Plugin.WebView.Droid { public interface IWebViewChromeClientActivity { IValueCallback UploadMessage { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace dz4.dll { public class Chocolate { public double Number; public string Firm; public double Price; public string KindOfChocolate; public string Name; public string Addition; // public static List<Chocolate> chocolates = new List<Chocolate>(); // public static Chocolate chocolate = new Chocolate(); public static void Menu(List<Chocolate> chocolates) { int i; { Console.Write("Menu:\n1)Become \n2)Console \n3)Console with all information about one chocolate \n4)Delete \n\nYour solution: "); i = int.Parse(Console.ReadLine()); switch (i) { case 1: break; case 2: AllInformation(chocolates); break; case 3: OneInformation(chocolates); break; case 4: DeleteInformation(chocolates); break; default: Console.WriteLine("Not correct number, input new..."); break; } Console.Clear(); } } public static void OneInformation(List<Chocolate> chocolates) { Console.WriteLine("Input number: "); string numbChocolate = Console.ReadLine(); int numb; int.TryParse(numbChocolate, out numb); var chocolate = chocolates.FirstOrDefault(c => c.Number == numb); Console.WriteLine($"Number {chocolate.Number}, Firm {chocolate.Firm}, Price {chocolate.Price}, Kind of chocolate {chocolate.KindOfChocolate}, Name {chocolate.Name}, Addition{chocolate.Addition}"); Console.ReadLine(); } public static string DeleteInformation(List<Chocolate> chocolates) { chocolates.Clear(); return "All information about chocolate is delete"; } public static double SetValue()//validation { string vString = Console.ReadLine(); double valString; if (Double.TryParse(vString, out valString)) { return valString; } else { Console.WriteLine("Not correct value, please input number again: "); valString = SetValue(); } return valString; } public static void AllInformation(List<Chocolate> chocolates) { for (int i = 0; i < chocolates.Count; i++) { Console.WriteLine($"{chocolates[i]}"); } } } }
namespace W3ChampionsStatisticService.CommonValueObjects { public class PlayerId { public static PlayerId Create(string nameTag) { return new PlayerId { Name = nameTag.Split("#")[0], BattleTag = nameTag }; } public string Name { get; set; } public string BattleTag { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class EnemyAI : MonoBehaviour { [Header("References")] private NavMeshAgent Agent; public GameObject Target; public LayerMask GroundMask; public LayerMask PlayerMask; public LayerMask EnemyMask; public int obstacleMask; private MeshRenderer m_MeshRenderer; private Rigidbody rb; [Header("EnemyStats")] public float Speed; [Header("Ranges")] [Range(0,20)] public float DetectionRange; [Range(0, 20)] public float AttackRange; [Range(0,5)] public float CancelAttackRange; [Range(0,20)] public float RandomPosRange; [Header("WaitingState")] public float WaitingTime; [Header("AttackState")] public float ChargeAttacksSpeed; public float ChannelingTimeValue; public float ChannelingClock; public bool InChargeAttack; private bool InitCanalisationAttack; public bool PlayerInAttackRange; public bool inChargeAttackRange; [Header("ChargeAttackInfo")] public Vector3 dirChagre; public float distChagre; [Header("DebugInfo")] public bool PlayerInDetectionRange; private float WaitingClock; public Vector3? posAfterAttack; public Vector3? RandomTargetPos; private Vector3 distanceToTargetPos; public Material[] StatesMat; public Vector3 InitialPos; private bool Started = false; public bool DisableAI = false; private float attackRange; public bool horsState; private void Awake() { Agent = GetComponent<NavMeshAgent>(); m_MeshRenderer = GetComponent<MeshRenderer>(); rb = GetComponent<Rigidbody>(); horsState = false; } private void Start() { InitialPos = transform.position; Target = Character3D.m_instance.gameObject; Started = true; obstacleMask = LayerMask.GetMask("Grounded"); attackRange = AttackRange; } private void Update() { PlayerInDetectionRange = Physics.CheckSphere(transform.position, DetectionRange, PlayerMask); PlayerInAttackRange = Physics.CheckSphere(transform.position, attackRange, PlayerMask); if (!PlayerInDetectionRange && !PlayerInAttackRange && !horsState) { WaitingState(); } if (PlayerInDetectionRange && !PlayerInAttackRange && !horsState) { ChaseState(); } if (PlayerInDetectionRange && PlayerInAttackRange && !horsState) { AttackState(); } if (PlayerInAttackRange) { attackRange = AttackRange + CancelAttackRange; } else { attackRange = AttackRange; } if (horsState) { Agent.ResetPath(); PlayerInAttackRange = false; PlayerInDetectionRange = false; } } public void InitTurnBack() { Agent.isStopped = true; horsState = true; //Vector3 Dir = -(Target.transform.position - transform.position); //Agent.SetDestination(transform.position + 1f * Dir); } public void TurnBack() { } private void WaitingState() { Agent.speed = Speed; if (RandomTargetPos == null) { if(WaitingClock <= 0) { Agent.isStopped = false; SearchRandomPoint(); } else if(WaitingClock > 0) { WaitingClock -= Time.deltaTime; } } else { Agent.SetDestination(RandomTargetPos.Value); Debug.DrawRay(RandomTargetPos.Value, Vector3.up, Color.yellow, 3); distanceToTargetPos = RandomTargetPos.Value - transform.position; if (distanceToTargetPos.magnitude < 1f) { WaitForNewRandPos(); } } //StateColor m_MeshRenderer.material = StatesMat[0]; } private void SearchRandomPoint() { float randomX = Random.Range(-RandomPosRange, RandomPosRange); float randomZ = Random.Range(-RandomPosRange, RandomPosRange); Vector3 randPos = new Vector3(InitialPos.x + randomX, transform.position.y, InitialPos.z + randomZ); //NavMeshPosCheck NavMeshPath path = new NavMeshPath(); Agent.CalculatePath(randPos, path); if(path.status == NavMeshPathStatus.PathComplete) { RandomTargetPos = randPos; } else { RandomTargetPos = null; } } public void WaitForNewRandPos() { Agent.isStopped = true; RandomTargetPos = null; WaitingClock = WaitingTime; } private void ChaseState() { Agent.isStopped = false; Agent.speed = Speed; Agent.SetDestination(Target.transform.position); RandomTargetPos = null; InChargeAttack = false; posAfterAttack = null; //StateColor m_MeshRenderer.material = StatesMat[1]; } private void AttackState() { if (!InChargeAttack) { Agent.isStopped = true; transform.LookAt(new Vector3(Target.transform.position.x, transform.position.y, Target.transform.position.z)); } if (InitCanalisationAttack) { InitChargeAttack(); InitCanalisationAttack = false; } if(ChannelingClock <= 0) { if (posAfterAttack == null) { dirChagre = Target.transform.position - transform.position; distChagre = dirChagre.magnitude; dirChagre.Normalize(); float factor = 2; Vector3 tempPosAfterAttack; if (Physics.Raycast(transform.position, dirChagre, out RaycastHit hit, AttackRange * 2, obstacleMask)) { tempPosAfterAttack = transform.position + hit.distance * dirChagre; Debug.DrawRay(transform.position, dirChagre * hit.distance, Color.red, 3); } else { tempPosAfterAttack = transform.position + distChagre * factor * dirChagre; } posAfterAttack = tempPosAfterAttack; } } else { ChannelingClock -= Time.deltaTime; } if (posAfterAttack != null) { InChargeAttack = true; Agent.isStopped = false; Agent.speed = ChargeAttacksSpeed; Agent.SetDestination(posAfterAttack.Value); Debug.DrawRay(posAfterAttack.Value, Vector3.up, Color.cyan, 3); float distanceToPosAfterAttack = Vector3.Distance(posAfterAttack.Value, transform.position); if(distanceToPosAfterAttack < 0f) { Debug.Log("ChargeAttackEnd"); InChargeAttack = false; Agent.speed = Speed; posAfterAttack = null; Agent.isStopped = true; InitTurnBack(); //InitCanalisationAttack = true; } } //StateColor m_MeshRenderer.material = StatesMat[2]; } private void InitChargeAttack() { ChannelingClock = ChannelingTimeValue; } //Debug private void OnDrawGizmosSelected() { Gizmos.color = Color.blue; Gizmos.DrawWireSphere(transform.position, DetectionRange); Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, AttackRange); Gizmos.DrawWireSphere(transform.position, AttackRange + CancelAttackRange); Gizmos.color = Color.yellow; if (Started == false) { Gizmos.DrawWireSphere(transform.position, RandomPosRange); } else { Gizmos.DrawWireSphere(InitialPos, RandomPosRange); } } }
//Problem 16. Decimal to Hexadecimal Number //Using loops write a program that converts an integer number to its hexadecimal representation. //The input is entered as long. The output should be a variable of type string. //Do not use the built-in .NET functionality. using System; namespace Problem16DecimalToHexadecimalNumber { class DecimalToHexadecimalNumber { public static string Reverse(string s) { char[] charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } static void Main() { Console.Write("Enter decimal number: "); long num = long.Parse(Console.ReadLine()); string result = ""; string temp; while (num > 0) { temp = (num % 16).ToString(); switch (temp) { case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": result += temp; break; case "10": result += "A"; break; case "11": result += "B"; break; case "12": result += "C"; break; case "13": result += "D"; break; case "14": result += "E"; break; case "15": result += "F"; break; default: break; } num = num / 16; } // Reverse result result = Reverse(result); Console.WriteLine("Result: " + result); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using A2CourseWork.Classes; namespace A2CourseWork.Gui { public partial class Default : Form { public Default() { InitializeComponent(); this.panel2.BringToFront(); } //exit button private void btnexit_Click_1(object sender, EventArgs e) { MiscFunctions.exit(); } //minimize button private void minbtn_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } private void panel1_MouseUp(object sender, MouseEventArgs e) { } //Dragable panel System.Drawing.Point lastclick; private void panel1_MouseMove_1(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.Left += e.X - lastclick.X; this.Top += e.Y - lastclick.Y; } } private void panel1_MouseDown_1(object sender, MouseEventArgs e) { lastclick = e.Location; } private void panel2_MouseEnter(object sender, EventArgs e) { panel2.Size = new Size(312, 569); } private void panel2_MouseLeave(object sender, EventArgs e) { panel2.Size = new Size(91, 569); } private void pictureBox1_MouseEnter(object sender, EventArgs e) { panel2.Size = new Size(312, 569); } private void pictureBox3_MouseEnter(object sender, EventArgs e) { panel2.Size = new Size(312, 569); } private void pictureBox4_MouseEnter(object sender, EventArgs e) { panel2.Size = new Size(312, 569); } private void pictureBox1_MouseHover(object sender, EventArgs e) { booksidebtn.BackColor = Color.Gray; } private void booksidebtn_MouseLeave(object sender, EventArgs e) { booksidebtn.BackColor = Color.FromArgb(64, 64, 64); } private void viewsidebtn_MouseHover(object sender, EventArgs e) { viewsidebtn.BackColor = Color.Gray; } private void viewsidebtn_MouseLeave(object sender, EventArgs e) { viewsidebtn.BackColor = Color.FromArgb(64, 64, 64); } private void staffsidebtn_MouseHover(object sender, EventArgs e) { staffsidebtn.BackColor = Color.Gray; } private void staffsidebtn_MouseLeave(object sender, EventArgs e) { staffsidebtn.BackColor = Color.FromArgb(64, 64, 64); } private void booksidebtn_Click(object sender, EventArgs e) { BookingMenu menu = new BookingMenu(); this.Hide(); menu.Show(); } private void viewsidebtn_Click(object sender, EventArgs e) { ViewBooking.ViewMenu menu = new ViewBooking.ViewMenu(); this.Hide(); menu.Show(); } private void staffsidebtn_Click(object sender, EventArgs e) { AddEditStaff staffmenu = new AddEditStaff(); this.Hide(); staffmenu.Show(); } private void pictureBox2_Click(object sender, EventArgs e) { Gui.Menu menu = new Gui.Menu(); this.Hide(); menu.Show(); } private void pictureBox1_MouseHover_1(object sender, EventArgs e) { pricesbtn.BackColor = Color.Gray; } private void pricesbtn_MouseLeave(object sender, EventArgs e) { pricesbtn.BackColor = Color.FromArgb(64, 64, 64); panel2.Size = new Size(91, 569); } private void waitinglistbtn_MouseHover(object sender, EventArgs e) { waitinglistbtn.BackColor = Color.Gray; } private void waitinglistbtn_MouseLeave(object sender, EventArgs e) { waitinglistbtn.BackColor = Color.FromArgb(64, 64, 64); panel2.Size = new Size(91, 569); } private void pricesbtn_MouseEnter(object sender, EventArgs e) { panel2.Size = new Size(312, 569); } private void waitinglistbtn_MouseEnter(object sender, EventArgs e) { panel2.Size = new Size(312, 569); } private void honebtn_MouseHover(object sender, EventArgs e) { honebtn.BackColor = Color.Gray; } private void honebtn_MouseLeave(object sender, EventArgs e) { honebtn.BackColor = Color.FromArgb(64, 64, 64); } private void pricesbtn_Click(object sender, EventArgs e) { Prices p = new Prices(); this.Hide(); p.Show(); } //tell the user this is not implemented private void waitinglistbtn_Click(object sender, EventArgs e) { MessageBox.Show("This is not something i plan to add yet"); } //help button private void btnhelp_Click(object sender, EventArgs e) { try { System.Diagnostics.Process.Start("Userguide.docx"); } catch (Exception) { MessageBox.Show("Document is missing from solution folder"); } } } }
// GIMP# - A C# wrapper around the GIMP Library // Copyright (C) 2004-2011 Maurits Rijk // // Gradient.cs // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Gimp { public sealed class Gradient : DataObject { public Gradient(string name) : base(gimp_gradient_new(name)) { } internal Gradient(string name, bool unused) : base(name) { } public Gradient(Gradient gradient) : base(gimp_gradient_duplicate(gradient.Name)) { } public IEnumerator<GradientSegment> GetEnumerator() { for (int i = 0; i < NumberOfSegments; i++) { yield return new GradientSegment(this, i); } } public void ForEach(Action<GradientSegment> action) { foreach (var segment in this) { action(segment); } } public override bool Equals(object o) { if (o is Gradient) { return (o as Gradient).Name == Name; } return false; } public override int GetHashCode() { return Name.GetHashCode(); } protected override string TryRename(string newName) { return gimp_gradient_rename(Name, newName); } public void Delete() { if (!gimp_gradient_delete(Name)) { throw new GimpSharpException(); } } public bool Editable { get {return gimp_gradient_is_editable(Name);} } public int NumberOfSegments { get {return gimp_gradient_get_number_of_segments(Name);} } public RGB SegmentGetLeftColor(int segment, out double opacity) { var rgb = new GimpRGB(); if (!gimp_gradient_segment_get_left_color(Name, segment, out rgb, out opacity)) { throw new GimpSharpException(); } return new RGB(rgb); } public void SegmentSetLeftColor(int segment, RGB color, double opacity) { var rgb = color.GimpRGB; if (!gimp_gradient_segment_set_left_color(Name, segment, ref rgb, opacity)) { throw new GimpSharpException(); } } public RGB SegmentGetRightColor(int segment, out double opacity) { var rgb = new GimpRGB(); if (!gimp_gradient_segment_get_right_color(Name, segment, out rgb, out opacity)) { throw new GimpSharpException(); } return new RGB(rgb); } public void SegmentSetRightColor(int segment, RGB color, double opacity) { var rgb = color.GimpRGB; if (!gimp_gradient_segment_set_right_color(Name, segment, ref rgb, opacity)) { throw new GimpSharpException(); } } public double SegmentGetLeftPosition(int segment) { double position; if (!gimp_gradient_segment_get_left_pos(Name, segment, out position)) { throw new GimpSharpException(); } return position; } public double SegmentSetLeftPosition(int segment, double pos) { double finalPos; if (!gimp_gradient_segment_set_left_pos(Name, segment, pos, out finalPos)) { throw new GimpSharpException(); } return finalPos; } public double SegmentGetMiddlePosition(int segment) { double position; if (!gimp_gradient_segment_get_middle_pos(Name, segment, out position)) { throw new GimpSharpException(); } return position; } public double SegmentSetMiddlePosition(int segment, double pos) { double finalPos; if (!gimp_gradient_segment_set_middle_pos(Name, segment, pos, out finalPos)) { throw new GimpSharpException(); } return finalPos; } public double SegmentGetRightPosition(int segment) { double position; if (!gimp_gradient_segment_get_right_pos(Name, segment, out position)) { throw new GimpSharpException(); } return position; } public double SegmentSetRightPosition(int segment, double pos) { double finalPos; if (!gimp_gradient_segment_set_right_pos(Name, segment, pos, out finalPos)) { throw new GimpSharpException(); } return finalPos; } public GradientSegmentType SegmentGetBlendingFunction(int segment) { GradientSegmentType blendFunc; if (!gimp_gradient_segment_get_blending_function(Name, segment, out blendFunc)) { throw new GimpSharpException(); } return blendFunc; } public GradientSegmentColor SegmentGetBlendingColoringType(int segment) { GradientSegmentColor coloringType; if (!gimp_gradient_segment_get_coloring_type(Name, segment, out coloringType)) { throw new GimpSharpException(); } return coloringType; } public void SegmentRangeSetBlendingFunction(int startSegment, int endSegment, GradientSegmentType blendingFunction) { if (!gimp_gradient_segment_range_set_blending_function(Name, startSegment, endSegment, blendingFunction)) { throw new GimpSharpException(); } } public void SegmentRangeSetColoringType(int startSegment, int endSegment, GradientSegmentColor coloringType) { if (!gimp_gradient_segment_range_set_coloring_type(Name, startSegment, endSegment, coloringType)) { throw new GimpSharpException(); } } public void SegmentRangeFlip(int startSegment, int endSegment) { if (!gimp_gradient_segment_range_flip(Name, startSegment, endSegment)) { throw new GimpSharpException(); } } public void SegmentRangeReplicate(int startSegment, int endSegment, int replicateTimes) { if (!gimp_gradient_segment_range_replicate(Name, startSegment, endSegment, replicateTimes)) { throw new GimpSharpException(); } } public void SegmentRangeSplitMidpoint(int startSegment, int endSegment) { if (!gimp_gradient_segment_range_split_midpoint(Name, startSegment, endSegment)) { throw new GimpSharpException(); } } public void SegmentRangeSplitUniform(int startSegment, int endSegment, int splitParts) { if (!gimp_gradient_segment_range_split_uniform(Name, startSegment, endSegment, splitParts)) { throw new GimpSharpException(); } } public void SegmentRangeDelete(int startSegment, int endSegment) { if (!gimp_gradient_segment_range_delete(Name, startSegment, endSegment)) { throw new GimpSharpException(); } } public void SegmentRangeRedistributeHandles(int startSegment, int endSegment) { if (!gimp_gradient_segment_range_redistribute_handles(Name, startSegment, endSegment)) { throw new GimpSharpException(); } } public void SegmentRangeBlendColors(int startSegment, int endSegment) { if (!gimp_gradient_segment_range_blend_colors(Name, startSegment, endSegment)) { throw new GimpSharpException(); } } public void SegmentRangeBlendOpacity(int startSegment, int endSegment) { if (!gimp_gradient_segment_range_blend_opacity(Name, startSegment, endSegment)) { throw new GimpSharpException(); } } public double SegmentRangeMove(int startSegment, int endSegment, double delta, bool controlCompress) { return gimp_gradient_segment_range_move(Name, startSegment, endSegment, delta, controlCompress); } [DllImport("libgimp-2.0-0.dll")] extern static string gimp_gradient_new(string name); [DllImport("libgimp-2.0-0.dll")] extern static string gimp_gradient_duplicate(string name); [DllImport("libgimp-2.0-0.dll")] extern static string gimp_gradient_rename(string name, string new_name); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_delete(string name); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_is_editable(string name); [DllImport("libgimp-2.0-0.dll")] extern static int gimp_gradient_get_number_of_segments(string name); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_set_left_color(string name, int segment, ref GimpRGB color, double opacity); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_get_left_color(string name, int segment, out GimpRGB color, out double opacity); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_set_right_color(string name, int segment, ref GimpRGB color, double opacity); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_get_right_color(string name, int segment, out GimpRGB color, out double opacity); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_get_left_pos(string name, int segment, out double pos); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_set_left_pos(string name, int segment, double pos, out double final_pos); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_get_middle_pos(string name, int segment, out double pos); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_set_middle_pos(string name, int segment, double pos, out double final_pos); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_get_right_pos(string name, int segment, out double pos); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_set_right_pos(string name, int segment, double pos, out double final_pos); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_get_blending_function(string name, int segment, out GradientSegmentType blend_func); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_get_coloring_type(string name, int segment, out GradientSegmentColor coloring_type); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_range_set_blending_function (string name, int start_segment, int end_segment, GradientSegmentType blending_function); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_range_set_coloring_type (string name, int start_segment, int end_segment, GradientSegmentColor coloring_type); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_range_flip(string name, int start_segment, int end_segment); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_range_replicate(string name, int start_segment, int end_segment, int replicate_times); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_range_split_midpoint(string name, int start_segment, int end_segment); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_range_split_uniform(string name, int start_segment, int end_segment, int split_parts); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_range_delete(string name, int start_segment, int end_segment); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_range_redistribute_handles (string name, int start_segment, int end_segment); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_range_blend_colors (string name, int start_segment, int end_segment); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_gradient_segment_range_blend_opacity (string name, int start_segment, int end_segment); [DllImport("libgimp-2.0-0.dll")] extern static double gimp_gradient_segment_range_move(string name, int start_segment, int end_segment, double delta, bool control_compress); } }
using System; using UnityEngine; namespace RenderHeads.Media.AVProVideo { [AddComponentMenu("AVPro Video/Apply To Delegate")] public class ApplyToDelegate : MonoBehaviour { public Action<Texture, Vector2, Vector2> receiver; public MediaPlayer _media; public Texture2D _defaultTexture; private void Update() { bool flag = false; if (this._media != null && this._media.TextureProducer != null) { Texture texture = this._media.TextureProducer.GetTexture(0); if (texture != null) { this.ApplyMapping(texture, this._media.TextureProducer.RequiresVerticalFlip()); flag = true; } } if (!flag) { this.ApplyMapping(this._defaultTexture, false); } } private void ApplyMapping(Texture texture, bool requiresYFlip) { if (this.receiver != null) { Vector2 one = Vector2.get_one(); Vector2 vector = Vector2.get_zero(); if (requiresYFlip) { one = new Vector2(1f, -1f); vector = new Vector3(0f, 1f); } this.receiver.Invoke(texture, one, vector); } } private void OnEnable() { this.Update(); } private void OnDisable() { this.ApplyMapping(this._defaultTexture, false); } } }