content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
/******************************************************* * Tic Tac Toe Pro * * Creator: Augusto Lange * * Last Change: 07/03/2012 * Version: 1.03 * * ****************************************************/ /***************************************************** * Version 1.01: * * Date: 15/04/2011 * * - Code the Idea; * - Form with the components for Win CE 6.0; * - Creation of the Logic of the Game; * - Creation of the Player's class; * - Using the Picture Box to Display an Image in Windows CE 6.0. * *****************************************************/ /***************************************************** * Version 1.02: * * Date: 18/04/2011 * * - Correction of Some Bugs: * - Bug Occurs by clicking on a rectangle already marked, then the program pass the turn; * - Bug Occured by still playing after clicking on the button to stop the game. * - Changing some colors letters; * - Adding the Program Name, Version, Copyright and Author strings. * *****************************************************/ /***************************************************** * Version 1.03: * * Date: 07/03/2012 * * - Added The Total Game Played. * *****************************************************/ using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.Diagnostics; using System.IO; namespace Tic_Tac_Toe { public partial class frmTTT : Form { public const int Grid = 3; private Graphics MyGraphics; private int Largura; private int Altura; private bool changes; private List<Rectangle> lstRectanges; private int[] Play; private Player Plr1; private Player Plr2; private int CountGames; private String strHistoryFileName; private delegate void UpdateStatusDelegate(); private Thread MyThread; public frmTTT() { InitializeComponent(); CountGames = 0; MyGraphics = this.pbxGame.CreateGraphics(); LoadImage(); lblAppVersion.Text = "Version 1.03"; changes = true; btnClose.Enabled = true; Play = new int[9]; //Start(); //MyThread = new Thread(new ThreadStart(this.threadEntry)); //MyThread.IsBackground = true; //MyThread.Priority = ThreadPriority.Highest; //MyThread.Start(); } private void threadEntry() { while (changes) { doUpdate(); Thread.Sleep(16); } } private void doUpdate() { if (this.InvokeRequired) { this.Invoke(new UpdateStatusDelegate(doUpdate), new object[] { }); return; } this.Start(); } private void btnClose_Click(object sender, EventArgs e) { if (btnClose.Enabled) { //MyThread.Abort(); this.Close(); } } private void btnStart_Click(object sender, EventArgs e) { if (btnClose.Enabled) { Plr1 = new Player(true, txtPlr1.Text != String.Empty ? txtPlr1.Text : "Player 1"); Plr2 = new Player(false, txtPlr2.Text != String.Empty ? txtPlr2.Text : "Player 2"); Plr1.Letter = "O"; Plr2.Letter = "X"; lblScr1.Text = Plr1.Score.ToString(); lblScr2.Text = Plr2.Score.ToString(); lblPlr1.Text = Plr1.Name + ":"; lblPlr2.Text = Plr2.Name + ":"; txtPlr1.Hide(); txtPlr2.Hide(); txtPlr1.Enabled = false; txtPlr2.Enabled = false; btnClose.Enabled = false; btnStart.Text = "Stop Game"; changes = true; CreateHistory(); Start(); Victory(); } else { Play = new int[9]; txtPlr1.Text = Plr1.Name; txtPlr2.Text = Plr2.Name; txtPlr1.Enabled = true; txtPlr2.Enabled = true; txtPlr1.Show(); txtPlr2.Show(); btnClose.Enabled = true; btnStart.Text = "New Game"; StringBuilder sbHeader = new StringBuilder(); sbHeader.AppendFormat("{0} e {1} Finalizaram o Jogo em {2}:\n\n", Plr1.Name, Plr2.Name, DateTime.Today.ToString("dd/MM/yyyy")); StreamWriter swHistory = new StreamWriter(strHistoryFileName, true); swHistory.WriteLine(sbHeader); swHistory.Close(); LoadImage(); } } private void CreateHistory() { int countFiles = 1; strHistoryFileName = "\\SDMMC\\History\\" + Plr1.Name + " VS " + Plr2.Name + " " + countFiles.ToString() + ".txt"; if (!Directory.Exists("\\SDMMC\\History")) Directory.CreateDirectory("\\SDMMC\\History"); while (File.Exists(strHistoryFileName)) { countFiles++; strHistoryFileName = "\\SDMMC\\History\\" + Plr1.Name + " VS " + Plr2.Name + " " + countFiles.ToString() + ".txt"; } StreamWriter swHistory = new StreamWriter(strHistoryFileName, false); swHistory.Close(); } private void LoadImage() { MyGraphics.Clear(Color.Black); if (File.Exists("\\SDMMC\\Images\\Pic.jpg")) { pbxGame.Image = new Bitmap("\\SDMMC\\Images\\Pic.jpg"); pbxGame.SizeMode = PictureBoxSizeMode.CenterImage; } } private void Start() { if (changes) { StringBuilder sbHeader = new StringBuilder(); Rectangle rect; lstRectanges = new List<Rectangle>(); StreamWriter swHistory = new StreamWriter(strHistoryFileName, true); Altura = this.pbxGame.Height / Grid; Largura = this.pbxGame.Width / Grid; Play = new int[9]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { rect = new Rectangle(Largura * j, Altura * i, (Largura * (j + 1)) - (Largura * j) , (Altura * (i + 1)) - (Altura * i)); lstRectanges.Add(rect); } } MyGraphics.Clear(Color.Black); MyGraphics.DrawLine(new Pen(Color.Cyan), Largura, 0, Largura, this.pbxGame.Height); MyGraphics.DrawLine(new Pen(Color.Cyan), Largura * 2, 0, Largura * 2, this.pbxGame.Height); MyGraphics.DrawLine(new Pen(Color.Cyan), 0, Altura, this.pbxGame.Width, Altura); MyGraphics.DrawLine(new Pen(Color.Cyan), 0, Altura * 2, this.pbxGame.Width, Altura * 2); changes = false; sbHeader.AppendFormat("{0} e {1} Iniciaram um Jogo em {2}:\n\n", Plr1.Name, Plr2.Name, DateTime.Today.ToString("dd/MM/yyyy")); swHistory.Write(sbHeader); swHistory.Close(); } } private void Victory() { int game = 0; if ((Play[0] == Play[1]) && (Play[0] == Play[2]) && (Play[1] == Play[2]) && (Play[0] != 0) && (Play[1] != 0) && (Play[2] != 0)) game = 1; else if ((Play[3] == Play[4]) && (Play[3] == Play[5]) && (Play[4] == Play[5]) && (Play[3] != 0) && (Play[4] != 0) && (Play[5] != 0)) game = 2; else if ((Play[6] == Play[7]) && (Play[6] == Play[8]) && (Play[7] == Play[8]) && (Play[6] != 0) && (Play[7] != 0) && (Play[8] != 0)) game = 3; else if ((Play[0] == Play[3]) && (Play[0] == Play[6]) && (Play[3] == Play[6]) && (Play[0] != 0) && (Play[3] != 0) && (Play[6] != 0)) game = 4; else if ((Play[1] == Play[4]) && (Play[1] == Play[7]) && (Play[4] == Play[7]) && (Play[1] != 0) && (Play[4] != 0) && (Play[7] != 0)) game = 5; else if ((Play[2] == Play[5]) && (Play[2] == Play[8]) && (Play[5] == Play[8]) && (Play[2] != 0) && (Play[5] != 0) && (Play[8] != 0)) game = 6; else if ((Play[0] == Play[4]) && (Play[0] == Play[8]) && (Play[4] == Play[8]) && (Play[0] != 0) && (Play[4] != 0) && (Play[8] != 0)) game = 7; else if ((Play[2] == Play[4]) && (Play[2] == Play[6]) && (Play[4] == Play[6]) && (Play[2] != 0) && (Play[4] != 0) && (Play[6] != 0)) game = 8; else if ((Play[0] != 0) && (Play[1] != 0) && (Play[2] != 0) && (Play[3] != 0) && (Play[4] != 0) && (Play[5] != 0) && (Play[6] != 0) && (Play[7] != 0) && (Play[8] != 0)) game = 9; if (game != 0) { GameFinished(game); } else { ChangeTurn(); } } private void GameFinished(int game) { StringBuilder sbHeader = new StringBuilder(); Pen pencil = new Pen(Color.WhiteSmoke, 15); Font fontScore = new Font("Tahoma", 10, FontStyle.Regular); Font fontScoreBold = new Font("Tahoma", 10, FontStyle.Bold); Point P1, P2; StreamWriter swHistory = new StreamWriter(strHistoryFileName, true); P1 = new Point(); P2 = new Point(); bool draw = false; switch (game) { case 1: P1 = Center(lstRectanges[0]); P2 = Center(lstRectanges[2]); break; case 2: P1 = Center(lstRectanges[3]); P2 = Center(lstRectanges[5]); break; case 3: P1 = Center(lstRectanges[6]); P2 = Center(lstRectanges[8]); break; case 4: P1 = Center(lstRectanges[0]); P2 = Center(lstRectanges[6]); break; case 5: P1 = Center(lstRectanges[1]); P2 = Center(lstRectanges[7]); break; case 6: P1 = Center(lstRectanges[2]); P2 = Center(lstRectanges[8]); break; case 7: P1 = Center(lstRectanges[0]); P2 = Center(lstRectanges[8]); break; case 8: P1 = Center(lstRectanges[2]); P2 = Center(lstRectanges[6]); break; default: case 9: draw = true; break; } changes = true; if (!draw) { MyGraphics.DrawLine(pencil, P1.X, P1.Y, P2.X, P2.Y); if (Plr1.Turn) { Plr1.UpdateScore(false); lblScr1.Text = Plr1.Score.ToString(); lblScr1.ForeColor = Color.Red; lblScr1.Font = fontScoreBold; sbHeader.AppendFormat("\n\t\t\t\t{0} Ganhou o Jogo!\n\n", Plr1.Name); } else if (Plr2.Turn) { Plr2.UpdateScore(false); lblScr2.Text = Plr2.Score.ToString(); lblScr2.ForeColor = Color.Red; lblScr2.Font = fontScoreBold; sbHeader.AppendFormat("\n\t\t\t\t{0} Ganhou o Jogo!\n\n", Plr2.Name); } Thread.Sleep(1000); lblScr1.ForeColor = Color.Black; lblScr1.Font = fontScore; lblScr2.ForeColor = Color.Black; lblScr2.Font = fontScore; ChangeTurn(); } else { Thread.Sleep(1000); sbHeader.AppendFormat("\n\t\t\t\tO Jogo Empatou!\n\n"); } Thread.Sleep(1000); lblTotalScr.Text = (CountGames++).ToString(); swHistory.WriteLine(sbHeader); swHistory.Close(); Start(); } private void ChangeTurn() { Font fontTurn = new Font("Tahoma", 10, FontStyle.Bold); Font fontNotTurn = new Font("Tahoma", 10, FontStyle.Regular); Plr1.Turn = !Plr1.Turn; Plr2.Turn = !Plr2.Turn; if (Plr1.Turn) { lblPlr1.ForeColor = Color.Blue; lblPlr1.Font = fontTurn; lblPlr2.ForeColor = Color.Black; lblPlr2.Font = fontNotTurn; } else if (Plr2.Turn) { lblPlr2.ForeColor = Color.Blue; lblPlr2.Font = fontTurn; lblPlr1.ForeColor = Color.Black; lblPlr1.Font = fontNotTurn; } } private void pbxGame_Click(object sender, EventArgs e) { if ((!btnClose.Enabled) && (!changes)) { Point mousePt = PointToClient(MousePosition); if (pbxGame.ClientRectangle.Contains(mousePt)) { for (int i = 0; i < 9; i++) { if (lstRectanges[i].Contains(mousePt)) { if (Play[i] == 0) { Font font = new Font("Tahoma", 60, FontStyle.Regular); StringFormat sf = new StringFormat(); sf.LineAlignment = StringAlignment.Center; sf.Alignment = StringAlignment.Center; if (Plr1.Turn) { MyGraphics.DrawString(Plr1.Letter, font, new SolidBrush(Color.Blue), lstRectanges[i], sf); Play[i] = 1; TurnLog(Plr1, i); } else if (Plr2.Turn) { MyGraphics.DrawString(Plr2.Letter, font, new SolidBrush(Color.Red), lstRectanges[i], sf); Play[i] = 2; TurnLog(Plr2, i); } Victory(); } } } } } } private void TurnLog(Player plr, int rect) { StringBuilder sbBody = new StringBuilder(); sbBody.AppendFormat("\t{0} Jogou No ", plr.Name); switch (rect) { case 0: sbBody.Append("Canto Superior Esquerdo"); break; case 1: sbBody.Append("Centro Superior"); break; case 2: sbBody.Append("Canto Superior Direito"); break; case 3: sbBody.Append("Centro Esquerdo"); break; case 4: sbBody.Append("Centro"); break; case 5: sbBody.Append("Centro Direito"); break; case 6: sbBody.Append("Canto Inferior Esquerdo"); break; case 7: sbBody.Append("Centro Inferior"); break; case 8: sbBody.Append("Canto Inferior Direito"); break; } StreamWriter swHistory = new StreamWriter(strHistoryFileName, true); swHistory.WriteLine(sbBody); swHistory.Close(); } public Point Center(Rectangle rect) { return new Point(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2); } } }
30.513514
180
0.451601
[ "Apache-2.0" ]
aslange/TIC_TAC_TOE_Win-CE
Form1.cs
15,808
C#
namespace ClearHl7.Codes.V260 { /// <summary> /// HL7 Version 2 Table 0544 - Container Condition. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0544</remarks> public enum CodeContainerCondition { /// <summary> /// ... - No suggested values. /// </summary> NoSuggestedValues } }
24.857143
59
0.563218
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7.Codes/V260/CodeContainerCondition.cs
350
C#
using TGC.Core.Camara; using TGC.Core.Input; using TGC.Core.Mathematica; namespace TGC.Examples.Camara { /// <summary> /// Camara que permite rotar y hacer zoom alrededor de un objeto central /// </summary> public class TgcRotationalCamera : TgcCamera { public static float DEFAULT_ZOOM_FACTOR = 0.15f; public static float DEFAULT_CAMERA_DISTANCE = 10f; public static float DEFAULT_ROTATION_SPEED = 100f; public static TGCVector3 DEFAULT_DOWN = new TGCVector3(0f, -1f, 0f); /// <summary> /// Crea camara con valores por defecto. /// </summary> public TgcRotationalCamera(TgcD3dInput input) { Input = input; CameraCenter = TGCVector3.Empty; NextPos = TGCVector3.Empty; CameraDistance = DEFAULT_CAMERA_DISTANCE; ZoomFactor = DEFAULT_ZOOM_FACTOR; RotationSpeed = DEFAULT_ROTATION_SPEED; DiffX = 0f; DiffY = 0f; DiffZ = 1f; PanSpeed = 0.01f; UpVector = new TGCVector3(0f, 1f, 0f); base.SetCamera(NextPos, LookAt, UpVector); } /// <summary> /// Crea una camara con una posicion inicial y un objetivo. /// </summary> /// <param name="position"></param> /// <param name="target"></param> public TgcRotationalCamera(TGCVector3 position, TGCVector3 target, TgcD3dInput input) : this(input) { NextPos = position; CameraCenter = target; base.SetCamera(NextPos, LookAt, UpVector); } /// <summary> /// Crea una camara con el centro de la camara, la distancia, la velocidad de zoom, Crea una camara con el centro de la /// camara, la distancia y la velocidad de rotacion. /// </summary> /// <param name="cameraCenter"></param> /// <param name="cameraDistance"></param> /// <param name="zoomFactor"></param> /// <param name="rotationSpeed"></param> public TgcRotationalCamera(TGCVector3 cameraCenter, float cameraDistance, float zoomFactor, float rotationSpeed, TgcD3dInput input) : this(input) { CameraCenter = cameraCenter; CameraDistance = cameraDistance; ZoomFactor = zoomFactor; RotationSpeed = rotationSpeed; } /// <summary> /// Crea una camara con el centro de la camara, la distancia y la velocidad de zoom /// </summary> /// <param name="cameraCenter"></param> /// <param name="cameraDistance"></param> /// <param name="zoomFactor"></param> public TgcRotationalCamera(TGCVector3 cameraCenter, float cameraDistance, float zoomFactor, TgcD3dInput input) : this(cameraCenter, cameraDistance, zoomFactor, DEFAULT_ROTATION_SPEED, input) { } /// <summary> /// Crea una camara con el centro de la camara, la distancia /// </summary> /// <param name="cameraCenter"></param> /// <param name="cameraDistance"></param> public TgcRotationalCamera(TGCVector3 cameraCenter, float cameraDistance, TgcD3dInput input) : this(cameraCenter, cameraDistance, DEFAULT_ZOOM_FACTOR, input) { } private TgcD3dInput Input { get; } /// <summary> /// Actualiza los valores de la camara. /// </summary> public override void UpdateCamera(float elapsedTime) { //Obtener variacion XY del mouse var mouseX = 0f; var mouseY = 0f; if (Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT)) { mouseX = Input.XposRelative; mouseY = Input.YposRelative; DiffX += mouseX * elapsedTime * RotationSpeed; DiffY += mouseY * elapsedTime * RotationSpeed; } else { DiffX += mouseX; DiffY += mouseY; } //Calcular rotacion a aplicar var rotX = -DiffY / FastMath.PI; var rotY = DiffX / FastMath.PI; //Truncar valores de rotacion fuera de rango if (rotX > FastMath.PI * 2 || rotX < -FastMath.PI * 2) { DiffY = 0; rotX = 0; } //Invertir Y de UpVector segun el angulo de rotacion if (rotX < -FastMath.PI / 2 && rotX > -FastMath.PI * 3 / 2) { UpVector = DEFAULT_DOWN; } else if (rotX > FastMath.PI / 2 && rotX < FastMath.PI * 3 / 2) { UpVector = DEFAULT_DOWN; } else { UpVector = DEFAULT_UP_VECTOR; } //Determinar distancia de la camara o zoom segun el Mouse Wheel if (Input.WheelPos != 0) { DiffZ += ZoomFactor * Input.WheelPos * -1; } var distance = -CameraDistance * DiffZ; //Limitar el zoom a 0 if (distance > 0) { distance = 0; } //Realizar Transformacion: primero alejarse en Z, despues rotar en X e Y y despues ir al centro de la cmara var m = TGCMatrix.Translation(0, 0, -distance) * TGCMatrix.RotationX(rotX) * TGCMatrix.RotationY(rotY) * TGCMatrix.Translation(CameraCenter); //Extraer la posicion final de la matriz de transformacion NextPos = new TGCVector3(m.M41, m.M42, m.M43); //Hacer efecto de Pan View if (Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_RIGHT)) { var dx = -Input.XposRelative; var dy = Input.YposRelative; var panSpeedZoom = PanSpeed * FastMath.Abs(distance); var d = CameraCenter - NextPos; d.Normalize(); var n = TGCVector3.Cross(d, UpVector); n.Normalize(); var up = TGCVector3.Cross(n, d); var desf = TGCVector3.Scale(up, dy * panSpeedZoom) - TGCVector3.Scale(n, dx * panSpeedZoom); NextPos = NextPos + desf; CameraCenter = CameraCenter + desf; } //asigna las posiciones de la camara. base.SetCamera(NextPos, CameraCenter, UpVector); } public override void SetCamera(TGCVector3 position, TGCVector3 target) { NextPos = position; CameraCenter = target; base.SetCamera(NextPos, CameraCenter, UpVector); } #region Getters y Setters /// <summary> /// Centro de la camara sobre la cual se rota /// </summary> public TGCVector3 CameraCenter { get; set; } /// <summary> /// Distance entre la camara y el centro /// </summary> public float CameraDistance { get; set; } /// <summary> /// Velocidad con la que se hace Zoom /// </summary> public float ZoomFactor { get; set; } /// <summary> /// Velocidad de rotacion de la camara /// </summary> public float RotationSpeed { get; set; } /// <summary> /// Velocidad de paneo /// </summary> public float PanSpeed { get; set; } public TGCVector3 NextPos { get; set; } public float DiffX { get; set; } public float DiffY { get; set; } public float DiffZ { get; set; } #endregion Getters y Setters } }
34.852018
131
0.537957
[ "MIT" ]
AVinitzca/tgc-viewer
TGC.Examples/Camara/TgcRotationalCamera.cs
7,772
C#
using System; using Couchbase.Core.Buckets; using Couchbase.Core.Transcoders; using Couchbase.IO.Converters; using Couchbase.IO.Operations; using Moq; using NUnit.Framework; namespace Couchbase.UnitTests.CouhbaseBucketTests { [TestFixture] public class DecrementTests { private readonly IByteConverter _converter = new DefaultConverter(); private readonly ITypeTranscoder _transcoder = new DefaultTranscoder(); [Test] public void Decrement_With_Key_ExecutesCorrectOperation() { // Arrange Decrement operation = null; var mockRequestExecuter = new Mock<IRequestExecuter>(); mockRequestExecuter .Setup(m => m.SendWithRetry(It.IsAny<Decrement>())) .Callback((IOperation<ulong> op) => operation = (Decrement)op); // Act using (var bucket = new CouchbaseBucket(mockRequestExecuter.Object, _converter, _transcoder)) { bucket.Name = "bucket"; bucket.Decrement("key"); } // Assert Assert.NotNull(operation); Assert.AreEqual(1, operation.Delta); Assert.AreEqual(1, operation.Initial); Assert.AreEqual("bucket", operation.BucketName); Assert.AreEqual(0, operation.Expires); Assert.AreEqual(2, operation.Timeout); } [Test] public void Decrement_With_Timeout_ExecutesCorrectOperation() { // Arrange Decrement operation = null; var mockRequestExecuter = new Mock<IRequestExecuter>(); mockRequestExecuter .Setup(m => m.SendWithRetry(It.IsAny<Decrement>())) .Callback((IOperation<ulong> op) => operation = (Decrement)op); // Act using (var bucket = new CouchbaseBucket(mockRequestExecuter.Object, _converter, _transcoder)) { bucket.Name = "bucket"; bucket.Decrement("key", TimeSpan.FromSeconds(10)); } // Assert Assert.NotNull(operation); Assert.AreEqual(1, operation.Delta); Assert.AreEqual(1, operation.Initial); Assert.AreEqual("bucket", operation.BucketName); Assert.AreEqual(0, operation.Expires); Assert.AreEqual(10, operation.Timeout); } [Test] public void Decrement_With_Delta_ExecutesCorrectOperation() { // Arrange Decrement operation = null; var mockRequestExecuter = new Mock<IRequestExecuter>(); mockRequestExecuter .Setup(m => m.SendWithRetry(It.IsAny<Decrement>())) .Callback((IOperation<ulong> op) => operation = (Decrement)op); // Act using (var bucket = new CouchbaseBucket(mockRequestExecuter.Object, _converter, _transcoder)) { bucket.Name = "bucket"; bucket.Decrement("key", 2); } // Assert Assert.NotNull(operation); Assert.AreEqual(2, operation.Delta); Assert.AreEqual(1, operation.Initial); Assert.AreEqual("bucket", operation.BucketName); Assert.AreEqual(0, operation.Expires); Assert.AreEqual(2, operation.Timeout); } [Test] public void Decrement_With_DeltaTimeout_ExecutesCorrectOperation() { // Arrange Decrement operation = null; var mockRequestExecuter = new Mock<IRequestExecuter>(); mockRequestExecuter .Setup(m => m.SendWithRetry(It.IsAny<Decrement>())) .Callback((IOperation<ulong> op) => operation = (Decrement)op); // Act using (var bucket = new CouchbaseBucket(mockRequestExecuter.Object, _converter, _transcoder)) { bucket.Name = "bucket"; bucket.Decrement("key", 2, TimeSpan.FromSeconds(10)); } // Assert Assert.NotNull(operation); Assert.AreEqual(2, operation.Delta); Assert.AreEqual(1, operation.Initial); Assert.AreEqual("bucket", operation.BucketName); Assert.AreEqual(0, operation.Expires); Assert.AreEqual(10, operation.Timeout); } [Test] public void Decrement_With_DeltaInitial_ExecutesCorrectOperation() { // Arrange Decrement operation = null; var mockRequestExecuter = new Mock<IRequestExecuter>(); mockRequestExecuter .Setup(m => m.SendWithRetry(It.IsAny<Decrement>())) .Callback((IOperation<ulong> op) => operation = (Decrement)op); // Act using (var bucket = new CouchbaseBucket(mockRequestExecuter.Object, _converter, _transcoder)) { bucket.Name = "bucket"; bucket.Decrement("key", 2, 4); } // Assert Assert.NotNull(operation); Assert.AreEqual(2, operation.Delta); Assert.AreEqual(4, operation.Initial); Assert.AreEqual("bucket", operation.BucketName); Assert.AreEqual(0, operation.Expires); Assert.AreEqual(2, operation.Timeout); } [Test] public void Decrement_With_DeltaInitialExpirationTime_ExecutesCorrectOperation() { // Arrange Decrement operation = null; var mockRequestExecuter = new Mock<IRequestExecuter>(); mockRequestExecuter .Setup(m => m.SendWithRetry(It.IsAny<Decrement>())) .Callback((IOperation<ulong> op) => operation = (Decrement)op); // Act using (var bucket = new CouchbaseBucket(mockRequestExecuter.Object, _converter, _transcoder)) { bucket.Name = "bucket"; bucket.Decrement("key", 2, 4, TimeSpan.FromSeconds(10)); } // Assert Assert.NotNull(operation); Assert.AreEqual(2, operation.Delta); Assert.AreEqual(4, operation.Initial); Assert.AreEqual("bucket", operation.BucketName); Assert.AreEqual(10, operation.Expires); Assert.AreEqual(2, operation.Timeout); } [Test] public void Decrement_With_DeltaInitialExpiration_ExecutesCorrectOperation() { // Arrange Decrement operation = null; var mockRequestExecuter = new Mock<IRequestExecuter>(); mockRequestExecuter .Setup(m => m.SendWithRetry(It.IsAny<Decrement>())) .Callback((IOperation<ulong> op) => operation = (Decrement)op); // Act using (var bucket = new CouchbaseBucket(mockRequestExecuter.Object, _converter, _transcoder)) { bucket.Name = "bucket"; bucket.Decrement("key", 2, 4, 10); } // Assert Assert.NotNull(operation); Assert.AreEqual(2, operation.Delta); Assert.AreEqual(4, operation.Initial); Assert.AreEqual("bucket", operation.BucketName); Assert.AreEqual(10, operation.Expires); Assert.AreEqual(2, operation.Timeout); } [Test] public void Decrement_With_DeltaInitialExpirationTimeTimeout_ExecutesCorrectOperation() { // Arrange Decrement operation = null; var mockRequestExecuter = new Mock<IRequestExecuter>(); mockRequestExecuter .Setup(m => m.SendWithRetry(It.IsAny<Decrement>())) .Callback((IOperation<ulong> op) => operation = (Decrement)op); // Act using (var bucket = new CouchbaseBucket(mockRequestExecuter.Object, _converter, _transcoder)) { bucket.Name = "bucket"; bucket.Decrement("key", 2, 4, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20)); } // Assert Assert.NotNull(operation); Assert.AreEqual(2, operation.Delta); Assert.AreEqual(4, operation.Initial); Assert.AreEqual("bucket", operation.BucketName); Assert.AreEqual(10, operation.Expires); Assert.AreEqual(20, operation.Timeout); } [Test] public void Decrement_With_DeltaInitialExpirationTimeout_ExecutesCorrectOperation() { // Arrange Decrement operation = null; var mockRequestExecuter = new Mock<IRequestExecuter>(); mockRequestExecuter .Setup(m => m.SendWithRetry(It.IsAny<Decrement>())) .Callback((IOperation<ulong> op) => operation = (Decrement)op); // Act using (var bucket = new CouchbaseBucket(mockRequestExecuter.Object, _converter, _transcoder)) { bucket.Name = "bucket"; bucket.Decrement("key", 2, 4, 10, TimeSpan.FromSeconds(20)); } // Assert Assert.NotNull(operation); Assert.AreEqual(2, operation.Delta); Assert.AreEqual(4, operation.Initial); Assert.AreEqual("bucket", operation.BucketName); Assert.AreEqual(10, operation.Expires); Assert.AreEqual(20, operation.Timeout); } } }
32.255892
105
0.567015
[ "Apache-2.0" ]
andrassebo/couchbase-net-client
Src/Couchbase.UnitTests/CouchbaseBucketTests/DecrementTests.cs
9,580
C#
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace MassTransit { using System; public interface ExceptionConsumerConsumeContext<T> : ConsumerConsumeContext<T> where T : class { /// <summary> /// The exception that was thrown /// </summary> Exception Exception { get; } /// <summary> /// The exception info, suitable for inclusion in a fault message /// </summary> ExceptionInfo ExceptionInfo { get; } } }
35.40625
83
0.651368
[ "Apache-2.0" ]
zengdl/MassTransit
src/MassTransit/ExceptionConsumerConsumeContext.cs
1,135
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace VkApi.Wrapper.Objects { public class AccountUserSettingsInterest { [JsonProperty("title")] public String Title { get; set; } [JsonProperty("value")] public String Value { get; set; } } }
22.285714
44
0.657051
[ "MIT" ]
FrediKats/VkLibrary
VkApi.Wrapper/Objects/Account/AccountUserSettingsInterest.cs
312
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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 Microsoft.Azure.Management.ManagedServices.Models; using Microsoft.Azure.PowerShell.Cmdlets.ManagedServices.Extensions; using Microsoft.Azure.PowerShell.Cmdlets.ManagedServices.Models; using Microsoft.WindowsAzure.Commands.Common.CustomAttributes; using Microsoft.WindowsAzure.Commands.Utilities.Common; using System; using System.Collections.Generic; using System.Management.Automation; using System.Text; namespace Microsoft.Azure.PowerShell.Cmdlets.ManagedServices.Commands { [GenericBreakingChange( message: "New mandatory parameter 'DisplayName' will be added to represent a user-friendly name for a registration definition", deprecateByVersion: ManagedServicesUtility.UpcomingVersion, changeInEfectByDate: ManagedServicesUtility.UpcomingVersionReleaseDate)] [GenericBreakingChange( message: "New mandatory parameter 'Authorization' will be added to represent a list containing principal IDs and role definition IDs.", deprecateByVersion: ManagedServicesUtility.UpcomingVersion, changeInEfectByDate: ManagedServicesUtility.UpcomingVersionReleaseDate)] [Cmdlet( VerbsCommon.New, Microsoft.Azure.Commands.ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "ManagedServicesDefinition", DefaultParameterSetName = DefaultParameterSet, SupportsShouldProcess = true), OutputType(typeof(PSRegistrationDefinition))] public class NewAzureRmManagedServicesDefinition : ManagedServicesCmdletBase { protected const string DefaultParameterSet = "Default"; protected const string ByPlanParameterSet = "ByPlan"; [Parameter(ParameterSetName = DefaultParameterSet, Mandatory = true, HelpMessage = "The name of the Registration Definition.")] [Parameter(ParameterSetName = ByPlanParameterSet, Mandatory = true, HelpMessage = "The name of the Registration Definition.")] public string Name { get; set; } [Parameter(ParameterSetName = DefaultParameterSet, Mandatory = true, HelpMessage = "The ManagedBy Tenant Identifier.")] [Parameter(ParameterSetName = ByPlanParameterSet, Mandatory = true, HelpMessage = "The ManagedBy Tenant Identifier.")] public string ManagedByTenantId { get; set; } [Parameter(ParameterSetName = DefaultParameterSet, Mandatory = true, HelpMessage = "The ManagedBy Principal Identifier.")] [Parameter(ParameterSetName = ByPlanParameterSet, Mandatory = true, HelpMessage = "The ManagedBy Principal Identifier.")] public string PrincipalId { get; set; } [Parameter(ParameterSetName = DefaultParameterSet, Mandatory = true, HelpMessage = "The Managed Service Provider's Role Identifier.")] [Parameter(ParameterSetName = ByPlanParameterSet, Mandatory = true, HelpMessage = "The Managed Service Provider's Role Identifier.")] public string RoleDefinitionId { get; set; } [Parameter(ParameterSetName = DefaultParameterSet, Mandatory = false, HelpMessage = "The description of the Registration Definition.")] [Parameter(ParameterSetName = ByPlanParameterSet, Mandatory = false, HelpMessage = "The description of the Registration Definition.")] public string Description { get; set; } [Parameter(ParameterSetName = ByPlanParameterSet, Mandatory = true, HelpMessage = "The name of the plan.")] [ValidateNotNullOrEmpty] public string PlanName { get; set; } [Parameter(ParameterSetName = ByPlanParameterSet, Mandatory = true, HelpMessage = "The name of the Publisher.")] [ValidateNotNullOrEmpty] public string PlanPublisher { get; set; } [Parameter(ParameterSetName = ByPlanParameterSet, Mandatory = true, HelpMessage = "The name of the Product.")] [ValidateNotNullOrEmpty] public string PlanProduct { get; set; } [Parameter(ParameterSetName = ByPlanParameterSet, Mandatory = true, HelpMessage = "The version number of the plan.")] [ValidateNotNullOrEmpty] public string PlanVersion { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } public Guid RegistrationDefinitionId { get; set; } = default(Guid); public override void ExecuteCmdlet() { var scope = this.GetDefaultScope(); if (!this.ManagedByTenantId.IsGuid()) { throw new ApplicationException("ManagedByTenantId must be a valid GUID."); } if (!this.PrincipalId.IsGuid()) { throw new ApplicationException("PrincipalId must be a valid GUID."); } if (!this.RoleDefinitionId.IsGuid()) { throw new ApplicationException("RoleDefinitionId must be a valid GUID."); } if (this.RegistrationDefinitionId == default(Guid)) { this.RegistrationDefinitionId = Guid.NewGuid(); } ConfirmAction(MyInvocation.InvocationName, $"{scope}/providers/Microsoft.ManagedServices/registrationDefinitions/{this.RegistrationDefinitionId}", () => { Plan plan = null; if (this.IsParameterBound(x => x.PlanName) && this.IsParameterBound(x => x.PlanPublisher) && this.IsParameterBound(x => x.PlanProduct) && this.IsParameterBound(x => x.PlanVersion)) { plan = new Plan { Name = this.PlanName, Product = this.PlanProduct, Publisher = this.PlanPublisher, Version = this.PlanVersion }; } var registrationDefinition = new RegistrationDefinition { Plan = plan, Properties = new RegistrationDefinitionProperties { Description = this.Description, RegistrationDefinitionName = this.Name, ManagedByTenantId = this.ManagedByTenantId, Authorizations = new List<Authorization> { new Authorization { PrincipalId =this.PrincipalId, RoleDefinitionId =this.RoleDefinitionId } } } }; var result = this.PSManagedServicesClient.CreateOrUpdateRegistrationDefinition( scope: scope, registrationDefinition: registrationDefinition, registratonDefinitionId: this.RegistrationDefinitionId); WriteObject(new PSRegistrationDefinition(result), true); }); } } }
51.765823
144
0.601663
[ "MIT" ]
DaeunYim/azure-powershell
src/ManagedServices/ManagedServices/Commands/NewAzureRmManagedServicesDefinition.cs
8,024
C#
namespace Patterns.Playground.AbstractFactory.Nutrition { public interface IHasCalories { double Calories { get; } } }
19.714286
55
0.688406
[ "MIT" ]
paulroho/Patterns.Playground
Patterns.Playground.AbstractFactory/Nutrition/IHasCalories.cs
138
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the worklink-2018-09-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.WorkLink.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.WorkLink.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DisassociateWebsiteCertificateAuthority operation /// </summary> public class DisassociateWebsiteCertificateAuthorityResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DisassociateWebsiteCertificateAuthorityResponse response = new DisassociateWebsiteCertificateAuthorityResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException")) { return InternalServerErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException")) { return InvalidRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException")) { return TooManyRequestsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedException")) { return UnauthorizedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonWorkLinkException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DisassociateWebsiteCertificateAuthorityResponseUnmarshaller _instance = new DisassociateWebsiteCertificateAuthorityResponseUnmarshaller(); internal static DisassociateWebsiteCertificateAuthorityResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DisassociateWebsiteCertificateAuthorityResponseUnmarshaller Instance { get { return _instance; } } } }
42.669565
192
0.654371
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/WorkLink/Generated/Model/Internal/MarshallTransformations/DisassociateWebsiteCertificateAuthorityResponseUnmarshaller.cs
4,907
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Cdn.V20190615.Outputs { /// <summary> /// Defines the IsDevice condition for the delivery rule. /// </summary> [OutputType] public sealed class DeliveryRuleIsDeviceConditionResponse { /// <summary> /// The name of the condition for the delivery rule. /// Expected value is 'IsDevice'. /// </summary> public readonly string Name; /// <summary> /// Defines the parameters for the condition. /// </summary> public readonly Outputs.IsDeviceMatchConditionParametersResponse Parameters; [OutputConstructor] private DeliveryRuleIsDeviceConditionResponse( string name, Outputs.IsDeviceMatchConditionParametersResponse parameters) { Name = name; Parameters = parameters; } } }
29.475
84
0.652248
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Cdn/V20190615/Outputs/DeliveryRuleIsDeviceConditionResponse.cs
1,179
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.CostManagement.V20190101.Outputs { [OutputType] public sealed class QueryDatasetResponse { /// <summary> /// Dictionary of aggregation expression to use in the query. The key of each item in the dictionary is the alias for the aggregated column. Query can have up to 2 aggregation clauses. /// </summary> public readonly ImmutableDictionary<string, Outputs.QueryAggregationResponse>? Aggregation; /// <summary> /// Has configuration information for the data in the export. The configuration will be ignored if aggregation and grouping are provided. /// </summary> public readonly Outputs.QueryDatasetConfigurationResponse? Configuration; /// <summary> /// Has filter expression to use in the query. /// </summary> public readonly Outputs.QueryFilterResponse? Filter; /// <summary> /// The granularity of rows in the query. /// </summary> public readonly string? Granularity; /// <summary> /// Array of group by expression to use in the query. Query can have up to 2 group by clauses. /// </summary> public readonly ImmutableArray<Outputs.QueryGroupingResponse> Grouping; /// <summary> /// Array of sorting by columns in query. /// </summary> public readonly ImmutableArray<Outputs.QuerySortingConfigurationResponse> Sorting; [OutputConstructor] private QueryDatasetResponse( ImmutableDictionary<string, Outputs.QueryAggregationResponse>? aggregation, Outputs.QueryDatasetConfigurationResponse? configuration, Outputs.QueryFilterResponse? filter, string? granularity, ImmutableArray<Outputs.QueryGroupingResponse> grouping, ImmutableArray<Outputs.QuerySortingConfigurationResponse> sorting) { Aggregation = aggregation; Configuration = configuration; Filter = filter; Granularity = granularity; Grouping = grouping; Sorting = sorting; } } }
38.421875
192
0.664498
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/CostManagement/V20190101/Outputs/QueryDatasetResponse.cs
2,459
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the servicecatalog-2015-12-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ServiceCatalog.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ServiceCatalog.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ProvisioningArtifact Object /// </summary> public class ProvisioningArtifactUnmarshaller : IUnmarshaller<ProvisioningArtifact, XmlUnmarshallerContext>, IUnmarshaller<ProvisioningArtifact, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ProvisioningArtifact IUnmarshaller<ProvisioningArtifact, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ProvisioningArtifact Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ProvisioningArtifact unmarshalledObject = new ProvisioningArtifact(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("CreatedTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.CreatedTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Description", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Description = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Id", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Id = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Name = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ProvisioningArtifactUnmarshaller _instance = new ProvisioningArtifactUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ProvisioningArtifactUnmarshaller Instance { get { return _instance; } } } }
36.609091
173
0.619568
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/ServiceCatalog/Generated/Model/Internal/MarshallTransformations/ProvisioningArtifactUnmarshaller.cs
4,027
C#
using System; using Build.DomainModel.MSBuild; namespace Build.TaskEngine.Tasks { internal sealed class PropertyGroupTask : ITaskRunner { private readonly ExpressionEngine.ExpressionEngine _expressionEngine; public PropertyGroupTask(ExpressionEngine.ExpressionEngine expressionEngine) { if (expressionEngine == null) throw new ArgumentNullException("expressionEngine"); _expressionEngine = expressionEngine; } public void Run(BuildEnvironment environment, Node task, IProjectDependencyGraph graph, ILogger logger) { var group = (PropertyGroup) task; _expressionEngine.Evaluate(group, environment); } } }
25.72
105
0.785381
[ "MIT" ]
Kittyfisto/.NETBuild
Build/TaskEngine/Tasks/PropertyGroupTask.cs
645
C#
namespace Toggl.Foundation.MvvmCross.Helper { public enum UpcomingEventsOption { Disabled, WhenEventStarts, FiveMinutes, TenMinutes, FifteenMinutes, ThirtyMinutes, OneHour } }
17.428571
43
0.602459
[ "BSD-3-Clause" ]
AzureMentor/mobileapp
Toggl.Foundation.MvvmCross/Helper/UpcomingEventsOption.cs
244
C#
using Nssol.Platypus.Infrastructure; using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Nssol.Platypus.Models.TenantModels { /// <summary> /// 前処理履歴用添付ファイル /// </summary> public class PreprocessHistoryAttachedFile : TenantModelBase { /// <summary> /// 前処理ID /// </summary> [Required] public long PreprocessHistoryId { get; set; } /// <summary> /// データID /// </summary> [Required] public long PreprocessDataId { get; set; } /// <summary> /// ファイルを識別するためのキー /// </summary> public string Key { get; set; } /// <summary> /// ファイル名 /// </summary> [Required] public string FileName { get; set; } /// <summary> /// 保存先パス /// </summary> [Required] public string StoredPath { get; set; } /// <summary> /// 学習履歴 /// </summary> [ForeignKey(nameof(PreprocessHistory))] public virtual PreprocessHistory PreprocessHistory { get; set; } /// <summary> /// 添付ファイル /// </summary> [NotMapped] public ResourceFileInfo AttachedFile { get { return new ResourceFileInfo(StoredPath, FileName, ResourceType.PreprocContainerAttachedFiles); } set { if (value.Type != ResourceType.PreprocContainerAttachedFiles) { throw new ArgumentException($"Unexpected resource type: expected = {ResourceType.PreprocContainerAttachedFiles}, actual = {value.Type}"); } this.StoredPath = value.StoredPath; this.FileName = value.FileName; } } } }
28.014925
157
0.533831
[ "Apache-2.0" ]
yonetatuu/kamonohashi
web-api/platypus/platypus/Models/TenantModels/PreprocessingHistoryAttachedFile.cs
1,983
C#
namespace FoodControl.Model { using System; public class NutrientAggregation { public decimal KiloCalories { get; set; } public decimal Fat { get; set; } public Nullable<decimal> Saturates { get; set; } public decimal Protein { get; set; } public decimal Carbohydrate { get; set; } public decimal Sugar { get; set; } public Nullable<decimal> Salt { get; set; } public DateTime Date { get; set; } } }
28.352941
56
0.603734
[ "MIT" ]
MatthiasHoldorf/FoodControl
FoodControl/Model/ViewModel/NutrientAggregation.cs
484
C#
/** * $File: JCS_2DSideScrollerPlayer.cs $ * $Date: $ * $Revision: $ * $Creator: Jen-Chieh Shen $ * $Notice: See LICENSE.txt for modification and distribution information * Copyright (c) 2016 by Shen, Jen-Chieh $ */ using System; using UnityEngine; namespace JCSUnity { /// <summary> /// Character controll of player /// </summary> [RequireComponent(typeof(JCS_2DSideScrollerPlayerAudioController))] [RequireComponent(typeof(JCS_2DAnimator))] [RequireComponent(typeof(JCS_OrderLayerObject))] public class JCS_2DSideScrollerPlayer : JCS_Player { /* Variables */ protected JCS_2DAnimator mJCS2DAnimator = null; protected JCS_OrderLayerObject mOrderLayerObject = null; //-- Action (Ladder, Rope) [Header("** Check Variables (JCS_2DSideScrollerPlayer) **")] //-- Facing [SerializeField] private JCS_2DFaceType mFace = JCS_2DFaceType.FACE_LEFT; //-- Climbing [Tooltip("See if there are ladder object so we can climb.")] [SerializeField] private bool mCanLadder = false; [Tooltip("See if there are rope object so we can climb.")] [SerializeField] private bool mCanRope = false; [Tooltip("Object that we can climb on.")] [SerializeField] private JCS_2DClimbableObject m2DClimbingObject = null; private bool mExitingClimbing = false; private bool mStartClimbing = false; [Tooltip("Count of the current jump.")] [SerializeField] private int mJumpCount = 0; [Tooltip("")] [SerializeField] private JCS_ClimbMoveType mClimbMoveType = JCS_ClimbMoveType.IDLE; [Header("** Runtime Variables (JCS_2DSideScrollerPlayer) **")] [Tooltip("Character's status.")] [SerializeField] private JCS_2DCharacterState mCharacterState = JCS_2DCharacterState.NORMAL; //-- Jumping [Header("** Jump Settings (JCS_2DSideScrollerPlayer) **")] [Tooltip("Type that this character can do.")] [SerializeField] private JCS_JumpeType mJumpType = JCS_JumpeType.BASIC_JUMP; private bool mDoubleJump = false; // trigger to check private bool mTripleJump = false; // trigger to check [Tooltip("Force apply when it jump. (Horizontal)")] [SerializeField] protected float[] mJumpYForces = null; [Tooltip("Force apply when it jump. (Vertical)")] [SerializeField] protected float[] mJumpXForces = null; [Tooltip("Maxinum speed of free fall object.")] [SerializeField] private float mTerminalSpeed = 20; [Tooltip("")] [SerializeField] private bool[] mForceXAfterJump = null; //-- Animator Control [Header("** Animation Settings (JCS_2DSideScrollerPlayer) **")] [Tooltip("Animation display when it jump event occurs.")] [SerializeField] private RuntimeAnimatorController[] mJumpAnim = null; [Tooltip("Animation sprite's offset for jump effect.")] [SerializeField] private Vector3[] mJumpAnimOffset = null; //-- Audio Control protected JCS_2DSideScrollerPlayerAudioController mAudioController = null; // once we call Physics.IgnoreCollision will call // OnTriggerEnter and OnTriggerExit once, // to prevent this happen trigger this for checking. private bool mResetingCollision = false; //-- GENERAL [Header("** Other Settings (JCS_2DSideScrollerPlayer) **")] [Tooltip("")] [SerializeField] private float mAirFriction = 0.5f; private bool mAttackedInAir = false; [Tooltip("Can the player down jump the platform.")] [SerializeField] private bool mCanDownJump = false; [Header("** Control Key Settings (JCS_2DSlideScrollerPlayer) **")] [Tooltip("Key press up.")] [SerializeField] private KeyCode mUpKey = KeyCode.UpArrow; [Tooltip("Key press down.")] [SerializeField] private KeyCode mDownKey = KeyCode.DownArrow; [Tooltip("Key press right.")] [SerializeField] private KeyCode mRightKey = KeyCode.RightArrow; [Tooltip("Key press left.")] [SerializeField] private KeyCode mLeftKey = KeyCode.LeftArrow; [Tooltip("Key press jump.")] [SerializeField] private KeyCode mJumpKey = KeyCode.LeftAlt; [Tooltip("Key press climb up.")] [SerializeField] private KeyCode mClimbUpKey = KeyCode.UpArrow; [Tooltip("Key press climb down.")] [SerializeField] private KeyCode mClimbDownKey = KeyCode.DownArrow; [Header("** Climb Settings (JCS_2DSideScrollerPlayer) **")] [SerializeField] private bool mAutoClimb = false; [SerializeField] private JCS_ClimbMoveType mAutoClimbDirection = JCS_ClimbMoveType.MOVE_UP; [Tooltip("Force when u exit the climbing state.")] [SerializeField] private float mExitClimbForceY = 10; [Header("** Hit Settings (JCS_2DSideScrollerPlayer) **")] [Tooltip("Trigger to enable hit effect.")] [SerializeField] private bool mHitEffect = true; [Tooltip("Velocity when get hit. (Horizontal) ")] [SerializeField] private float mHitVelX = 5; [Tooltip("Velocity when get hit. (Vertical) ")] [SerializeField] private float mHitVelY = 5; private bool mJustClimbOnTopOfBox = false; /* Setter & Getter */ public bool JustClimbOnTopOfBox { get { return this.mJustClimbOnTopOfBox; } set { this.mJustClimbOnTopOfBox = value; } } public bool AutoClimb { get { return this.mAutoClimb; } set { this.mAutoClimb = value; } } public JCS_ClimbMoveType AutoClimbDirection { get { return this.mAutoClimbDirection; } set { this.mAutoClimbDirection = value; } } public JCS_ClimbMoveType ClimbMoveType { get { return this.mClimbMoveType; } } public bool ResetingCollision { get { return this.mResetingCollision; } set { this.mResetingCollision = value; } } public bool ExitingClimbing { get { return this.mExitingClimbing; } set { this.mExitingClimbing = value; } } public JCS_2DCharacterState CharacterState { get { return this.mCharacterState; } set { this.mCharacterState = value; } } public bool CanLadder { get { return this.mCanLadder; } set { this.mCanLadder = value; } } public bool CanRope { get { return this.mCanRope; } set { this.mCanRope = value; } } public void SetJumpType(JCS_JumpeType type) { this.mJumpType = type; } public JCS_JumpeType GetJumpType() { return this.mJumpType; } public JCS_2DAnimator GetCharacterAnimator() { return this.mJCS2DAnimator; } public bool isGrounded() { return this.mCharacterController.isGrounded; } public JCS_2DSideScrollerPlayerAudioController GetAudioController() { return this.mAudioController; } public int JumpCount { get { return this.mJumpCount; } } public JCS_2DFaceType Face { get { return this.mFace; } } public JCS_OrderLayerObject OrderLayerObject { get { return this.mOrderLayerObject; } } public KeyCode UpKey { get { return this.mUpKey; } set { this.mUpKey = value; } } public KeyCode DownKey { get { return this.mDownKey; } set { this.mDownKey = value; } } public KeyCode RightKey { get { return this.mRightKey; } set { this.mRightKey = value; } } public KeyCode LeftKey { get { return this.mLeftKey; } set { this.mLeftKey = value; } } public KeyCode JumpKey { get { return this.mJumpKey; } set { this.mJumpKey = value; } } public KeyCode ClimbUpKey { get { return this.mClimbUpKey; } set { this.mClimbUpKey = value; } } public KeyCode ClimbDownKey { get { return this.mClimbDownKey; } set { this.mClimbDownKey = value; } } public JCS_2DClimbableObject ClimbableObject { get { return this.m2DClimbingObject; } set { this.m2DClimbingObject = value; } } /* Functions */ protected override void Awake() { base.Awake(); this.mAudioController = this.GetComponent<JCS_2DSideScrollerPlayerAudioController>(); this.mJCS2DAnimator = this.GetComponent<JCS_2DAnimator>(); this.mOrderLayerObject = this.GetComponent<JCS_OrderLayerObject>(); } protected override void Start() { base.Start(); } protected override void Update() { base.Update(); ProcessState(); } /// <summary> /// /// </summary> /// <param name="act"></param> public override void ControlEnable(bool act) { // enable all the component here if (act) { if (JCS_GameSettings.instance.CAMERA_TYPE != JCS_CameraType.MULTI_TARGET) { AudioListener al = this.mAudioController.GetAudioListener(); if (al != null) al.enabled = true; } mIsControllable = true; } // diable all the component here else { if (JCS_GameSettings.instance.CAMERA_TYPE != JCS_CameraType.MULTI_TARGET) { AudioListener al = this.mAudioController.GetAudioListener(); if (al != null) al.enabled = false; } mIsControllable = false; } } /// <summary> /// /// </summary> /// <param name="facing"></param> public void TurnFace(int facing) { TurnFace((JCS_2DFaceType)facing); } /// <summary> /// /// </summary> /// <param name="type"></param> public void TurnFace(JCS_2DFaceType type) { Vector3 originalScale = this.gameObject.transform.localScale; float absoluteOriginalScale = JCS_Mathf.AbsoluteValue(originalScale.x); this.gameObject.transform.localScale = new Vector3((int)type * absoluteOriginalScale, originalScale.y, originalScale.z); mFace = type; } /// <summary> /// /// </summary> /// <param name="type"></param> public void Jump(JCS_JumpeType type) { switch (type) { case JCS_JumpeType.BASIC_JUMP: BasicJump(mJumpYForces[0]); break; case JCS_JumpeType.DOUBLE_JUMP: DoubleJump(mJumpYForces[0], mJumpYForces[1]); break; case JCS_JumpeType.TRIPLE_JUMP: TripleJump(mJumpYForces[0], mJumpYForces[1], mJumpYForces[2]); break; case JCS_JumpeType.DOUBLE_JUMP_FORCE: break; case JCS_JumpeType.TRIPLE_JUMP_FORCE: break; } } /// <summary> /// /// </summary> /// <param name="force"></param> /// <returns></returns> public bool BasicJump(float force = 10) { if (CharacterState == JCS_2DCharacterState.CLIMBING) return false; if (mExitingClimbing) return false; if (!isGrounded()) return false; if (!mIsControllable) return false; if (isInAttackStage()) return false; this.VelY = force; if (mForceXAfterJump[0]) this.VelX = (mJumpXForces[0] * -(int)mFace); mDoubleJump = false; mTripleJump = false; mAudioController.BasicJumpSound(); DoJumpAnimEffect(0); ++mJumpCount; return true; } /// <summary> /// /// </summary> /// <param name="firstForce"></param> /// <param name="secodForce"></param> /// <returns></returns> public bool DoubleJump(float firstForce = 10, float secodForce = 10) { if (CharacterState == JCS_2DCharacterState.CLIMBING) return false; if (mExitingClimbing) return false; if (!mIsControllable) return false; if (mAttackedInAir) return false; if (isInAttackStage()) return false; // Jump the first jump bool firstJump = BasicJump(firstForce); if (mJumpCount == 0 && !isGrounded()) mDoubleJump = false; // check if do the second jump if (!firstJump && !mDoubleJump) { this.VelY = secodForce; mDoubleJump = true; mAudioController.DoubleJumpSound(); if (mForceXAfterJump[1]) this.VelX = (mJumpXForces[1] * -(int)mFace); DoJumpAnimEffect(1); ++mJumpCount; return true; } return false; } /// <summary> /// /// </summary> /// <param name="firstForce"></param> /// <param name="secodForce"></param> /// <param name="thirdForce"></param> /// <returns></returns> public bool TripleJump(float firstForce = 10, float secodForce = 10, float thirdForce = 10) { if (CharacterState == JCS_2DCharacterState.CLIMBING) return false; if (!mIsControllable) return false; if (mAttackedInAir) return false; if (isInAttackStage()) return false; // get current double jump succeed or not bool currentDoubleJump = DoubleJump(firstForce, secodForce); if (mJumpCount == 1 && !isGrounded()) mTripleJump = false; // if current double jump not succeed // if double jump succeed if (!currentDoubleJump && !mTripleJump && mDoubleJump) { this.VelY = thirdForce; mTripleJump = true; mAudioController.TripleJumpSound(); if (mForceXAfterJump[2]) this.VelX = (mJumpXForces[2] * -(int)mFace); DoJumpAnimEffect(2); ++mJumpCount; return true; } return false; } /// <summary> /// /// </summary> public void ToggleFace() { if (mFace == JCS_2DFaceType.FACE_LEFT) mFace = JCS_2DFaceType.FACE_RIGHT; else mFace = JCS_2DFaceType.FACE_LEFT; TurnFace((int)mFace); } /// <summary> /// Move right with defualt speed. /// </summary> public void MoveRight() { MoveRight(MoveSpeed); } /// <summary> /// move right with pass in speed. /// </summary> /// <param name="vel"> speed </param> public void MoveRight(float vel) { // cannot move during climbing if (CharacterState == JCS_2DCharacterState.CLIMBING) return; if (!mIsControllable) return; bool isAttacking = isInAttackStage(); if (isGrounded() || mExitingClimbing) { if (!isAttacking) this.mVelocity.x = vel; mExitingClimbing = false; } // in air else { this.mVelocity.x += (0 - this.mVelocity.x) * mAirFriction * Time.deltaTime; } if (isAttacking) return; TurnFace(JCS_2DFaceType.FACE_RIGHT); DoAnimation(JCS_LiveObjectState.WALK); } /// <summary> /// Move left with defualt speed. /// </summary> public void MoveLeft() { MoveLeft(MoveSpeed); } /// <summary> /// Move left with pass in speed. /// </summary> /// <param name="vel"> speed </param> public void MoveLeft(float vel) { // cannot move during climbing if (CharacterState == JCS_2DCharacterState.CLIMBING) return; if (!mIsControllable) return; bool isAttacking = isInAttackStage(); if (isGrounded() || mExitingClimbing) { if (!isAttacking) this.mVelocity.x = -vel; mExitingClimbing = false; } // in air else { this.mVelocity.x += (0 - this.mVelocity.x) * mAirFriction * Time.deltaTime; } if (isAttacking) return; TurnFace(JCS_2DFaceType.FACE_LEFT); DoAnimation(JCS_LiveObjectState.WALK); } /// <summary> /// /// </summary> public override void Stand() { if (mStartClimbing) return; if (isInAttackStage()) return; // In Air if (!isGrounded()) return; DoAnimation(JCS_LiveObjectState.STAND); this.mVelocity.x = 0; } /// <summary> /// /// </summary> public override void Attack() { // cannot attack during climbing if (CharacterState == JCS_2DCharacterState.CLIMBING) return; if (!mIsControllable || isInAttackStage()) return; if (isGrounded()) this.mVelocity.x = 0; else this.mAttackedInAir = true; DoAnimation(JCS_LiveObjectState.RAND_ATTACK); mAudioController.AttackSound(); } /// <summary> /// /// </summary> public override void Jump() { if (IsDownJump()) return; Jump(GetJumpType()); } /// <summary> /// /// </summary> public override void Alert() { } /// <summary> /// /// </summary> public override void Ladder() { DoAnimation(JCS_LiveObjectState.LADDER); this.mVelocity.x = 0; } /// <summary> /// /// </summary> public override void Rope() { DoAnimation(JCS_LiveObjectState.ROPE); this.mVelocity.x = 0; } /// <summary> /// /// </summary> public override void Die() { this.mVelocity = Vector3.zero; DoAnimation(JCS_LiveObjectState.DIE); } /// <summary> /// /// </summary> public override void Dance() { throw new NotImplementedException(); } /// <summary> /// /// </summary> public override void Swim() { DoAnimation(JCS_LiveObjectState.SWIM); } /// <summary> /// /// </summary> public override void Fly() { DoAnimation(JCS_LiveObjectState.FLY); } /// <summary> /// /// </summary> public override void Sit() { } /// <summary> /// When player get hit. /// </summary> public override void Hit() { if (!mHitEffect) { JCS_Debug.LogError( "You call the function without checking the hit effect?"); return; } ExitClimbing(0); int randDirection = JCS_Random.Range(0, 2); // 0 ~ 1 // if 0 push right, else if 1 push left float pushVel = (randDirection == 0) ? mHitVelX : -mHitVelX; // apply force as velocity this.mVelocity.x += pushVel; // hop a bit. (velcotiy y axis) this.mVelocity.y += mHitVelY; DoAnimation(JCS_LiveObjectState.STAND); } /// <summary> /// /// </summary> public override void Ghost() { } /// <summary> /// Climb and teleport are the same key. /// </summary> public virtual void ClimbOrTeleport() { if (isInAttackStage()) return; // check the direction correctly or not. // 這個讓原本就在梯子上面的玩家不再往上爬! if (!CheckClimbDirection()) return; // set mode to climbing. CharacterState = JCS_2DCharacterState.CLIMBING; } /// <summary> /// /// </summary> public override void Prone() { // cannot prone in the air. if (!isGrounded() && VelY != 0) return; /** * NOTE(jenchieh): i dont think these two return really effect * anything. */ //if (mStartClimbing) // return; //// cannot prone while climbing. //if (CharacterState == JCS_2DCharacterState.CLIMBING) // return; if (CanRope || CanLadder) { if (CheckClimbDirection()) { CharacterState = JCS_2DCharacterState.CLIMBING; return; } } DoAnimation(JCS_LiveObjectState.PRONE); this.mVelocity.x = 0; } /// <summary> /// Check if the player down jumping. /// </summary> /// <returns></returns> public bool IsDownJump() { if (!mCanDownJump) return false; if (JCS_Input.GetKey(JumpKey) && JCS_Input.GetKey(DownKey)) return true; return false; } /// <summary> /// Check if we are still in the attack stage. /// </summary> /// <returns> /// true: in attack stage. /// false: not in attack stage. /// </returns> protected bool isInAttackStage() { JCS_LiveObjectState lastState = (JCS_LiveObjectState)GetCharacterAnimator().CurrentAnimId; if (lastState == JCS_LiveObjectState.RAND_ATTACK && !GetCharacterAnimator().CurrentAnimation.IsDonePlaying) return true; return false; } /// <summary> /// Do the animation by passin the state. /// </summary> /// <param name="state"> state </param> /// <returns> /// true: play animation success. /// false: failed to play animation. /// </returns> protected bool DoAnimation(JCS_LiveObjectState state) { if (GetCharacterAnimator().CurrentAnimation != null) { if (GetCharacterAnimator().CurrentAnimId == (int)JCS_LiveObjectState.RAND_ATTACK) { if (!GetCharacterAnimator().CurrentAnimation.IsDonePlaying) return false; } } if (state != JCS_LiveObjectState.RAND_ATTACK) { if (CharacterState != JCS_2DCharacterState.CLIMBING) { JCS_LiveObjectState lastState = (JCS_LiveObjectState)GetCharacterAnimator().CurrentAnimId; if (lastState == JCS_LiveObjectState.JUMP && !isGrounded()) return false; } } if (state == JCS_LiveObjectState.RAND_ATTACK) GetCharacterAnimator().PlayOneShot((int)JCS_LiveObjectState.RAND_ATTACK); else GetCharacterAnimator().DoAnimation((int)state); DoSound(state); return true; } /// <summary> /// Do the sound base on the state we are in. /// </summary> /// <param name="state"> state we are in. </param> protected void DoSound(JCS_LiveObjectState state) { GetAudioController().PlaySoundByPlayerState(state); } /// <summary> /// Process State Pattern. /// </summary> private void ProcessState() { switch (mCharacterState) { case JCS_2DCharacterState.NORMAL: { CharacterNormal(); } break; case JCS_2DCharacterState.CLIMBING: { CharacterClimbing(); } break; case JCS_2DCharacterState.ATTACK: { } break; } } /// <summary> /// While Character is standing. /// </summary> private void CharacterNormal() { // if is in the AIR if (!isGrounded()) { // apply gravity mVelocity.y -= (JCS_GameConstant.GRAVITY * Time.deltaTime * JCS_GameSettings.instance.GRAVITY_PRODUCT); /* TODO!! */ if (!mJustClimbOnTopOfBox) DoAnimation(JCS_LiveObjectState.JUMP); // apply terminal speed if (mVelocity.y < -mTerminalSpeed) { mVelocity.y = -mTerminalSpeed; } } // if is on the ground else { mJustClimbOnTopOfBox = false; Stand(); mAttackedInAir = false; mJumpCount = 0; // if on the ground and is in attack stage, // dont move the character in x-axis. if (isInAttackStage()) mVelocity.x = 0; } mStartClimbing = false; } /// <summary> /// While character are climbing. /// </summary> private void CharacterClimbing() { mJumpCount = 0; if (!mStartClimbing) { if (!mAutoClimb) { if (!GetCharacterAnimator().IsInState((int)JCS_LiveObjectState.STAND) && !GetCharacterAnimator().IsInState((int)JCS_LiveObjectState.JUMP) && !GetCharacterAnimator().IsInState((int)JCS_LiveObjectState.WALK)) { ExitClimbing(0); return; } } if (m2DClimbingObject == null) { ExitClimbing(0); return; } mStartClimbing = true; } if (CanLadder) Ladder(); else if (CanRope) Rope(); else { ExitClimbing(0); return; } // while climbing zero jump count. mJumpCount = 0; mClimbMoveType = JCS_ClimbMoveType.IDLE; if (mAutoClimb) { mClimbMoveType = mAutoClimbDirection; } else { // process input if (JCS_Input.GetKey(this.ClimbUpKey)) mClimbMoveType = JCS_ClimbMoveType.MOVE_UP; else if (JCS_Input.GetKey(this.mClimbDownKey)) mClimbMoveType = JCS_ClimbMoveType.MOVE_DOWN; else { mClimbMoveType = JCS_ClimbMoveType.IDLE; GetCharacterAnimator().StopAnimationInFrame(); } } bool climbing = false; // process velocity switch (mClimbMoveType) { case JCS_ClimbMoveType.IDLE: this.mVelocity.y = 0; break; case JCS_ClimbMoveType.MOVE_UP: this.mVelocity.y = MoveSpeed; climbing = true; break; case JCS_ClimbMoveType.MOVE_DOWN: this.mVelocity.y = -MoveSpeed; climbing = true; break; } if (climbing) { if (m2DClimbingObject == null) { ExitClimbing(0); return; } // let x axis the same as ladder x axis. Vector3 newPos = this.transform.position; newPos.x = m2DClimbingObject.transform.position.x; this.transform.position = newPos; // start the animation agian GetCharacterAnimator().PlayAnimationInFrame(); } else { if (JCS_Input.GetKey(this.JumpKey) || JCS_Input.GetKey(this.JumpKey)) { if (JCS_Input.GetKey(this.LeftKey) || JCS_Input.GetKey(this.RightKey)) { ExitClimbing(); mExitingClimbing = true; } } } if (isGrounded()) ExitClimbing(0); } /// <summary> /// Spawn a animation for jumping effect. /// </summary> /// <param name="index"></param> private void DoJumpAnimEffect(int index) { if (mJumpAnim.Length < index) return; if (mJumpAnim.Length != mJumpAnimOffset.Length) return; if (mJumpAnim.Length == 0) return; if (mJumpAnim[index] == null) return; GameObject gameObject = JCS_Utility.SpawnAnimateObjectDeathEvent( mJumpAnim[index], mOrderLayerObject.sortingOrder - 1); Vector3 newPos = Vector3.zero; Vector3 tempOffset = mJumpAnimOffset[index]; // change the position depends on the scale. if (this.transform.localScale.x < 0) tempOffset.x = -tempOffset.x; // assign new position for the effect. newPos = this.transform.localPosition + tempOffset; // assign to effect's transform. gameObject.transform.localPosition = newPos; gameObject.transform.localScale = this.transform.localScale; } /// <summary> /// Call this when exit climbing status. /// </summary> private void ExitClimbing() { ExitClimbing(mExitClimbForceY); } /// <summary> /// Call this when exit climbing status. /// </summary> /// <param name="jumpForce"> force to exit the climbing object. </param> private void ExitClimbing(float jumpForce) { mCharacterState = JCS_2DCharacterState.NORMAL; if (jumpForce != 0) { // when exit give a litte jump /** * ATTENSION(jenchieh): this make Unity's CharacterController * component 'isGrounded' not accurate. Use this carefully. */ mVelocity.y = jumpForce; } // start the animation agian GetCharacterAnimator().PlayAnimationInFrame(); if (jumpForce != 0) { CanLadder = false; CanRope = false; } } /// <summary> /// /// </summary> /// <returns></returns> private bool CheckClimbDirection() { // no climbing object, no climbing! if (m2DClimbingObject == null) return false; if (m2DClimbingObject.IsOpTopOfLeanPlatform(this) && !JCS_Input.GetKey(mClimbDownKey)) return false; // when is in air, character can climb what ever if (!isGrounded()) return true; JCS_ClimbMoveType keyInput = JCS_ClimbMoveType.IDLE; // process input if (JCS_Input.GetKey(this.ClimbUpKey)) keyInput = JCS_ClimbMoveType.MOVE_UP; else if (JCS_Input.GetKey(this.mClimbDownKey)) keyInput = JCS_ClimbMoveType.MOVE_DOWN; switch (keyInput) { case JCS_ClimbMoveType.IDLE: return true; case JCS_ClimbMoveType.MOVE_UP: { if (this.transform.position.y < this.m2DClimbingObject.transform.position.y) return true; } break; case JCS_ClimbMoveType.MOVE_DOWN: { if (this.transform.position.y > this.m2DClimbingObject.transform.position.y) return true; } break; } return false; } } }
29.788782
138
0.502604
[ "MIT" ]
jcs090218/JCSUnity
Assets/JCSUnity/Scripts/GameObject/2D/2DPlayer/JCS_2DSideScrollerPlayer.cs
34,029
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. namespace Mosa.Test.Collection { public static class Int8Tests { public static int AddI1I1(sbyte first, sbyte second) { return (first + second); } public static int SubI1I1(sbyte first, sbyte second) { return (first - second); } public static int MulI1I1(sbyte first, sbyte second) { return (first * second); } public static int DivI1I1(sbyte first, sbyte second) { return (first / second); } public static int RemI1I1(sbyte first, sbyte second) { return (first % second); } public static sbyte RetI1(sbyte first) { return first; } public static int AndI1I1(sbyte first, sbyte second) { return (first & second); } public static int OrI1I1(sbyte first, sbyte second) { return (first | second); } public static int XorI1I1(sbyte first, sbyte second) { return (first ^ second); } public static int CompI1(sbyte first) { return (~first); } public static int ShiftLeftI1I1(sbyte first, byte second) { return (first << second); } public static int ShiftRightI1I1(sbyte first, byte second) { return (first >> second); } public static bool CeqI1I1(sbyte first, sbyte second) { return (first == second); } public static bool CltI1I1(sbyte first, sbyte second) { return (first < second); } public static bool CgtI1I1(sbyte first, sbyte second) { return (first > second); } public static bool CleI1I1(sbyte first, sbyte second) { return (first <= second); } public static bool CgeI1I1(sbyte first, sbyte second) { return (first >= second); } public static bool Newarr() { sbyte[] arr = new sbyte[0]; return arr != null; } public static bool Ldlen(int length) { sbyte[] arr = new sbyte[length]; return arr.Length == length; } public static sbyte Ldelem(int index, sbyte value) { sbyte[] arr = new sbyte[index + 1]; arr[index] = value; return arr[index]; } public static bool Stelem(int index, sbyte value) { sbyte[] arr = new sbyte[index + 1]; arr[index] = value; return true; } public static sbyte Ldelema(int index, sbyte value) { sbyte[] arr = new sbyte[index + 1]; SetValueInRefValue(ref arr[index], value); return arr[index]; } private static void SetValueInRefValue(ref sbyte destination, sbyte value) { destination = value; } } }
18.70229
76
0.65102
[ "BSD-3-Clause" ]
Kintaro/MOSA-Project
Source/Mosa.Test.Collection/Int8Tests.cs
2,452
C#
using CodeWars; using NUnit.Framework; namespace CodeWarsTests { [TestFixture] public class SimpleFun131LearnCharitableGameTests { [Test] public void BasicTests() { var kata = new SimpleFun131LearnCharitableGame(); Assert.AreEqual(false, kata.LearnCharitableGame(new int[] {100, 100, 100, 90, 1, 0, 0})); Assert.AreEqual(false, kata.LearnCharitableGame(new int[] {0, 0, 0, 0})); Assert.AreEqual(true, kata.LearnCharitableGame(new int[] {0, 56, 100})); Assert.AreEqual(false, kata.LearnCharitableGame(new int[] {33, 19, 38, 87, 93, 4})); Assert.AreEqual(true, kata.LearnCharitableGame(new int[] {11})); } } }
29.36
101
0.615804
[ "MIT" ]
a-kozhanov/codewars.com_csharp
CodeWarsTests/7kyu/SimpleFun131LearnCharitableGameTests.cs
736
C#
using System.Collections.Generic; using System.Linq; using Blockfrost.Api.Generate.Contexts; using Microsoft.OpenApi.Models; namespace Blockfrost.Api.Generate { public class OpenApiDocumentContext : OpenApiContext { public OpenApiDocumentContext(System.IO.DirectoryInfo outputDir, OpenApiDocument specs) : base(specs) { Models = new List<ModelContext>(); Services = new List<ServiceContext>(); HttpAttributes = new List<HttpAttributeContext>(); ServiceExtension = new BlockfrostServiceExtensionContext(outputDir, specs); Load(); } public List<ModelContext> Models { get; } public List<ServiceContext> Services { get; } public List<HttpAttributeContext> HttpAttributes { get; } public BlockfrostServiceExtensionContext ServiceExtension { get; } public List<ModelContext> LoadModels() { var models = new List<ModelContext>(); var successSchemas = Spec.SchemasWhere(r => r.IsSuccessStatusCode()); var distinctSchemas = successSchemas.Distinct().ToList(); foreach (var schema in distinctSchemas) { var model = new ModelContext(Spec, schema); models.Add(model); } return models; } public void Load() { Models.Clear(); Models.AddRange(LoadModels()); Services.Clear(); Services.AddRange(LoadServices()); HttpAttributes.Clear(); HttpAttributes.AddRange(LoadAttributes()); } private IEnumerable<HttpAttributeContext> LoadAttributes() { List<KeyValuePair<string, string>> parameters = new() { new("string", "route"), new("string", "version") }; return Spec.Paths.SelectMany(p => p.Value.Operations.Select(m => new HttpAttributeContext(Spec,m.Key,parameters))).ToList(); } private IEnumerable<ServiceContext> LoadServices() { return (from tag in Spec.Tags select new ServiceContext(Spec, tag)).ToList(); } } }
34.546875
136
0.598824
[ "Apache-2.0" ]
blockfrost/blockfrost-donet
tools/Blockfrost.Api.Generate/OpenApiDocumentContext.cs
2,213
C#
using FontStashSharp; using Microsoft.Xna.Framework; using OlympUI; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Olympus { public partial class HeaderBig : Label { public static readonly new Style DefaultStyle = new() { Assets.FontHeaderBig, }; public HeaderBig(string text) : base(text) { } } public partial class HeaderMedium : Label { public static readonly new Style DefaultStyle = new() { Assets.FontHeaderMedium, }; public HeaderMedium(string text) : base(text) { } } public partial class HeaderSmall : Label { public static readonly new Style DefaultStyle = new() { Assets.FontHeaderSmall, }; public HeaderSmall(string text) : base(text) { } } public partial class HeaderSmaller : Label { public static readonly new Style DefaultStyle = new() { Assets.FontHeaderSmaller, }; public HeaderSmaller(string text) : base(text) { } } public partial class LabelSmall : Label { public static readonly new Style DefaultStyle = new() { OlympUI.Assets.FontSmall, }; public LabelSmall(string text) : base(text) { } } public partial class DebugLabel : Label { public static readonly new Style DefaultStyle = new() { OlympUI.Assets.FontMono, }; public DebugLabel(string text) : base(text) { } } }
21.948718
63
0.584112
[ "MIT" ]
0x0ade/Olympus.FNA
Olympus.FNA/Elements/LabelStyles.cs
1,714
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.Verticals.AgriFood.Farming { /// <summary> The Farms service client. </summary> public partial class FarmsClient { private static readonly string[] AuthorizationScopes = new string[] { "https://farmbeats.azure.net/.default" }; private readonly TokenCredential _tokenCredential; private readonly HttpPipeline _pipeline; private readonly Uri _endpoint; private readonly string _apiVersion; /// <summary> The ClientDiagnostics is used to provide tracing support for the client library. </summary> internal ClientDiagnostics ClientDiagnostics { get; } /// <summary> The HTTP pipeline for sending and receiving REST requests and responses. </summary> public virtual HttpPipeline Pipeline => _pipeline; /// <summary> Initializes a new instance of FarmsClient for mocking. </summary> protected FarmsClient() { } /// <summary> Initializes a new instance of FarmsClient. </summary> /// <param name="endpoint"> The endpoint of your FarmBeats resource (protocol and hostname, for example: https://{resourceName}.farmbeats.azure.net). </param> /// <param name="credential"> A credential used to authenticate to an Azure Service. </param> /// <exception cref="ArgumentNullException"> <paramref name="endpoint"/> or <paramref name="credential"/> is null. </exception> public FarmsClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new FarmBeatsClientOptions()) { } /// <summary> Initializes a new instance of FarmsClient. </summary> /// <param name="endpoint"> The endpoint of your FarmBeats resource (protocol and hostname, for example: https://{resourceName}.farmbeats.azure.net). </param> /// <param name="credential"> A credential used to authenticate to an Azure Service. </param> /// <param name="options"> The options for configuring the client. </param> /// <exception cref="ArgumentNullException"> <paramref name="endpoint"/> or <paramref name="credential"/> is null. </exception> public FarmsClient(Uri endpoint, TokenCredential credential, FarmBeatsClientOptions options) { Argument.AssertNotNull(endpoint, nameof(endpoint)); Argument.AssertNotNull(credential, nameof(credential)); options ??= new FarmBeatsClientOptions(); ClientDiagnostics = new ClientDiagnostics(options, true); _tokenCredential = credential; _pipeline = HttpPipelineBuilder.Build(options, Array.Empty<HttpPipelinePolicy>(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); _endpoint = endpoint; _apiVersion = options.Version; } /// <summary> Gets a specified farm resource under a particular farmer. </summary> /// <param name="farmerId"> ID of the associated farmer resource. </param> /// <param name="farmId"> ID of the farm resource. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Response Body</c>: /// <code>{ /// farmerId: string, /// id: string, /// eTag: string, /// status: string, /// createdDateTime: string (ISO 8601 Format), /// modifiedDateTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual async Task<Response> GetFarmAsync(string farmerId, string farmId, RequestContext context = null) { Argument.AssertNotNullOrEmpty(farmerId, nameof(farmerId)); Argument.AssertNotNullOrEmpty(farmId, nameof(farmId)); using var scope = ClientDiagnostics.CreateScope("FarmsClient.GetFarm"); scope.Start(); try { using HttpMessage message = CreateGetFarmRequest(farmerId, farmId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets a specified farm resource under a particular farmer. </summary> /// <param name="farmerId"> ID of the associated farmer resource. </param> /// <param name="farmId"> ID of the farm resource. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Response Body</c>: /// <code>{ /// farmerId: string, /// id: string, /// eTag: string, /// status: string, /// createdDateTime: string (ISO 8601 Format), /// modifiedDateTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual Response GetFarm(string farmerId, string farmId, RequestContext context = null) { Argument.AssertNotNullOrEmpty(farmerId, nameof(farmerId)); Argument.AssertNotNullOrEmpty(farmId, nameof(farmId)); using var scope = ClientDiagnostics.CreateScope("FarmsClient.GetFarm"); scope.Start(); try { using HttpMessage message = CreateGetFarmRequest(farmerId, farmId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Creates or updates a farm resource under a particular farmer. </summary> /// <param name="farmerId"> ID of the associated farmer resource. </param> /// <param name="farmId"> ID of the farm resource. </param> /// <param name="content"> The content to send as the body of the request. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Request Body</c>: /// <code>{ /// farmerId: string, /// id: string, /// eTag: string, /// status: string, /// createdDateTime: string (ISO 8601 Format), /// modifiedDateTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// </code> /// Schema for <c>Response Body</c>: /// <code>{ /// farmerId: string, /// id: string, /// eTag: string, /// status: string, /// createdDateTime: string (ISO 8601 Format), /// modifiedDateTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual async Task<Response> CreateOrUpdateAsync(string farmerId, string farmId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(farmerId, nameof(farmerId)); Argument.AssertNotNullOrEmpty(farmId, nameof(farmId)); using var scope = ClientDiagnostics.CreateScope("FarmsClient.CreateOrUpdate"); scope.Start(); try { using HttpMessage message = CreateCreateOrUpdateRequest(farmerId, farmId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Creates or updates a farm resource under a particular farmer. </summary> /// <param name="farmerId"> ID of the associated farmer resource. </param> /// <param name="farmId"> ID of the farm resource. </param> /// <param name="content"> The content to send as the body of the request. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Request Body</c>: /// <code>{ /// farmerId: string, /// id: string, /// eTag: string, /// status: string, /// createdDateTime: string (ISO 8601 Format), /// modifiedDateTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// </code> /// Schema for <c>Response Body</c>: /// <code>{ /// farmerId: string, /// id: string, /// eTag: string, /// status: string, /// createdDateTime: string (ISO 8601 Format), /// modifiedDateTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual Response CreateOrUpdate(string farmerId, string farmId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(farmerId, nameof(farmerId)); Argument.AssertNotNullOrEmpty(farmId, nameof(farmId)); using var scope = ClientDiagnostics.CreateScope("FarmsClient.CreateOrUpdate"); scope.Start(); try { using HttpMessage message = CreateCreateOrUpdateRequest(farmerId, farmId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Deletes a specified farm resource under a particular farmer. </summary> /// <param name="farmerId"> ID of the farmer. </param> /// <param name="farmId"> ID of the farm. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual async Task<Response> DeleteAsync(string farmerId, string farmId, RequestContext context = null) { Argument.AssertNotNullOrEmpty(farmerId, nameof(farmerId)); Argument.AssertNotNullOrEmpty(farmId, nameof(farmId)); using var scope = ClientDiagnostics.CreateScope("FarmsClient.Delete"); scope.Start(); try { using HttpMessage message = CreateDeleteRequest(farmerId, farmId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Deletes a specified farm resource under a particular farmer. </summary> /// <param name="farmerId"> ID of the farmer. </param> /// <param name="farmId"> ID of the farm. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="farmerId"/> or <paramref name="farmId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual Response Delete(string farmerId, string farmId, RequestContext context = null) { Argument.AssertNotNullOrEmpty(farmerId, nameof(farmerId)); Argument.AssertNotNullOrEmpty(farmId, nameof(farmId)); using var scope = ClientDiagnostics.CreateScope("FarmsClient.Delete"); scope.Start(); try { using HttpMessage message = CreateDeleteRequest(farmerId, farmId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get a cascade delete job for specified farm. </summary> /// <param name="jobId"> ID of the job. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="jobId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="jobId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Response Body</c>: /// <code>{ /// farmerId: string, /// resourceId: string, /// resourceType: string, /// id: string, /// status: string, /// durationInSeconds: number, /// message: string, /// createdDateTime: string (ISO 8601 Format), /// lastActionDateTime: string (ISO 8601 Format), /// startTime: string (ISO 8601 Format), /// endTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual async Task<Response> GetCascadeDeleteJobDetailsAsync(string jobId, RequestContext context = null) { Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); using var scope = ClientDiagnostics.CreateScope("FarmsClient.GetCascadeDeleteJobDetails"); scope.Start(); try { using HttpMessage message = CreateGetCascadeDeleteJobDetailsRequest(jobId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get a cascade delete job for specified farm. </summary> /// <param name="jobId"> ID of the job. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="jobId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="jobId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Response Body</c>: /// <code>{ /// farmerId: string, /// resourceId: string, /// resourceType: string, /// id: string, /// status: string, /// durationInSeconds: number, /// message: string, /// createdDateTime: string (ISO 8601 Format), /// lastActionDateTime: string (ISO 8601 Format), /// startTime: string (ISO 8601 Format), /// endTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual Response GetCascadeDeleteJobDetails(string jobId, RequestContext context = null) { Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); using var scope = ClientDiagnostics.CreateScope("FarmsClient.GetCascadeDeleteJobDetails"); scope.Start(); try { using HttpMessage message = CreateGetCascadeDeleteJobDetailsRequest(jobId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Returns a paginated list of farm resources under a particular farmer. </summary> /// <param name="farmerId"> ID of the associated farmer. </param> /// <param name="ids"> Ids of the resource. </param> /// <param name="names"> Names of the resource. </param> /// <param name="propertyFilters"> /// Filters on key-value pairs within the Properties object. /// eg. &quot;{testKey} eq {testValue}&quot;. /// </param> /// <param name="statuses"> Statuses of the resource. </param> /// <param name="minCreatedDateTime"> Minimum creation date of resource (inclusive). </param> /// <param name="maxCreatedDateTime"> Maximum creation date of resource (inclusive). </param> /// <param name="minLastModifiedDateTime"> Minimum last modified date of resource (inclusive). </param> /// <param name="maxLastModifiedDateTime"> Maximum last modified date of resource (inclusive). </param> /// <param name="maxPageSize"> /// Maximum number of items needed (inclusive). /// Minimum = 10, Maximum = 1000, Default value = 50. /// </param> /// <param name="skipToken"> Skip token for getting next set of results. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="farmerId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="farmerId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Response Body</c>: /// <code>{ /// value: [ /// { /// farmerId: string, /// id: string, /// eTag: string, /// status: string, /// createdDateTime: string (ISO 8601 Format), /// modifiedDateTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// ], /// $skipToken: string, /// nextLink: string /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual AsyncPageable<BinaryData> GetFarmsByFarmerIdAsync(string farmerId, IEnumerable<string> ids = null, IEnumerable<string> names = null, IEnumerable<string> propertyFilters = null, IEnumerable<string> statuses = null, DateTimeOffset? minCreatedDateTime = null, DateTimeOffset? maxCreatedDateTime = null, DateTimeOffset? minLastModifiedDateTime = null, DateTimeOffset? maxLastModifiedDateTime = null, int? maxPageSize = null, string skipToken = null, RequestContext context = null) { Argument.AssertNotNullOrEmpty(farmerId, nameof(farmerId)); return GetFarmsByFarmerIdImplementationAsync("FarmsClient.GetFarmsByFarmerId", farmerId, ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context); } private AsyncPageable<BinaryData> GetFarmsByFarmerIdImplementationAsync(string diagnosticsScopeName, string farmerId, IEnumerable<string> ids, IEnumerable<string> names, IEnumerable<string> propertyFilters, IEnumerable<string> statuses, DateTimeOffset? minCreatedDateTime, DateTimeOffset? maxCreatedDateTime, DateTimeOffset? minLastModifiedDateTime, DateTimeOffset? maxLastModifiedDateTime, int? maxPageSize, string skipToken, RequestContext context) { return PageableHelpers.CreateAsyncPageable(CreateEnumerableAsync, ClientDiagnostics, diagnosticsScopeName); async IAsyncEnumerable<Page<BinaryData>> CreateEnumerableAsync(string nextLink, int? pageSizeHint, [EnumeratorCancellation] CancellationToken cancellationToken = default) { do { var message = string.IsNullOrEmpty(nextLink) ? CreateGetFarmsByFarmerIdRequest(farmerId, ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context) : CreateGetFarmsByFarmerIdNextPageRequest(nextLink, farmerId, ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context); var page = await LowLevelPageableHelpers.ProcessMessageAsync(_pipeline, message, context, "value", "nextLink", cancellationToken).ConfigureAwait(false); nextLink = page.ContinuationToken; yield return page; } while (!string.IsNullOrEmpty(nextLink)); } } /// <summary> Returns a paginated list of farm resources under a particular farmer. </summary> /// <param name="farmerId"> ID of the associated farmer. </param> /// <param name="ids"> Ids of the resource. </param> /// <param name="names"> Names of the resource. </param> /// <param name="propertyFilters"> /// Filters on key-value pairs within the Properties object. /// eg. &quot;{testKey} eq {testValue}&quot;. /// </param> /// <param name="statuses"> Statuses of the resource. </param> /// <param name="minCreatedDateTime"> Minimum creation date of resource (inclusive). </param> /// <param name="maxCreatedDateTime"> Maximum creation date of resource (inclusive). </param> /// <param name="minLastModifiedDateTime"> Minimum last modified date of resource (inclusive). </param> /// <param name="maxLastModifiedDateTime"> Maximum last modified date of resource (inclusive). </param> /// <param name="maxPageSize"> /// Maximum number of items needed (inclusive). /// Minimum = 10, Maximum = 1000, Default value = 50. /// </param> /// <param name="skipToken"> Skip token for getting next set of results. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="farmerId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="farmerId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Response Body</c>: /// <code>{ /// value: [ /// { /// farmerId: string, /// id: string, /// eTag: string, /// status: string, /// createdDateTime: string (ISO 8601 Format), /// modifiedDateTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// ], /// $skipToken: string, /// nextLink: string /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual Pageable<BinaryData> GetFarmsByFarmerId(string farmerId, IEnumerable<string> ids = null, IEnumerable<string> names = null, IEnumerable<string> propertyFilters = null, IEnumerable<string> statuses = null, DateTimeOffset? minCreatedDateTime = null, DateTimeOffset? maxCreatedDateTime = null, DateTimeOffset? minLastModifiedDateTime = null, DateTimeOffset? maxLastModifiedDateTime = null, int? maxPageSize = null, string skipToken = null, RequestContext context = null) { Argument.AssertNotNullOrEmpty(farmerId, nameof(farmerId)); return GetFarmsByFarmerIdImplementation("FarmsClient.GetFarmsByFarmerId", farmerId, ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context); } private Pageable<BinaryData> GetFarmsByFarmerIdImplementation(string diagnosticsScopeName, string farmerId, IEnumerable<string> ids, IEnumerable<string> names, IEnumerable<string> propertyFilters, IEnumerable<string> statuses, DateTimeOffset? minCreatedDateTime, DateTimeOffset? maxCreatedDateTime, DateTimeOffset? minLastModifiedDateTime, DateTimeOffset? maxLastModifiedDateTime, int? maxPageSize, string skipToken, RequestContext context) { return PageableHelpers.CreatePageable(CreateEnumerable, ClientDiagnostics, diagnosticsScopeName); IEnumerable<Page<BinaryData>> CreateEnumerable(string nextLink, int? pageSizeHint) { do { var message = string.IsNullOrEmpty(nextLink) ? CreateGetFarmsByFarmerIdRequest(farmerId, ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context) : CreateGetFarmsByFarmerIdNextPageRequest(nextLink, farmerId, ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context); var page = LowLevelPageableHelpers.ProcessMessage(_pipeline, message, context, "value", "nextLink"); nextLink = page.ContinuationToken; yield return page; } while (!string.IsNullOrEmpty(nextLink)); } } /// <summary> Returns a paginated list of farm resources across all farmers. </summary> /// <param name="ids"> Ids of the resource. </param> /// <param name="names"> Names of the resource. </param> /// <param name="propertyFilters"> /// Filters on key-value pairs within the Properties object. /// eg. &quot;{testKey} eq {testValue}&quot;. /// </param> /// <param name="statuses"> Statuses of the resource. </param> /// <param name="minCreatedDateTime"> Minimum creation date of resource (inclusive). </param> /// <param name="maxCreatedDateTime"> Maximum creation date of resource (inclusive). </param> /// <param name="minLastModifiedDateTime"> Minimum last modified date of resource (inclusive). </param> /// <param name="maxLastModifiedDateTime"> Maximum last modified date of resource (inclusive). </param> /// <param name="maxPageSize"> /// Maximum number of items needed (inclusive). /// Minimum = 10, Maximum = 1000, Default value = 50. /// </param> /// <param name="skipToken"> Skip token for getting next set of results. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <remarks> /// Schema for <c>Response Body</c>: /// <code>{ /// value: [ /// { /// farmerId: string, /// id: string, /// eTag: string, /// status: string, /// createdDateTime: string (ISO 8601 Format), /// modifiedDateTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// ], /// $skipToken: string, /// nextLink: string /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual AsyncPageable<BinaryData> GetFarmsAsync(IEnumerable<string> ids = null, IEnumerable<string> names = null, IEnumerable<string> propertyFilters = null, IEnumerable<string> statuses = null, DateTimeOffset? minCreatedDateTime = null, DateTimeOffset? maxCreatedDateTime = null, DateTimeOffset? minLastModifiedDateTime = null, DateTimeOffset? maxLastModifiedDateTime = null, int? maxPageSize = null, string skipToken = null, RequestContext context = null) { return GetFarmsImplementationAsync("FarmsClient.GetFarms", ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context); } private AsyncPageable<BinaryData> GetFarmsImplementationAsync(string diagnosticsScopeName, IEnumerable<string> ids, IEnumerable<string> names, IEnumerable<string> propertyFilters, IEnumerable<string> statuses, DateTimeOffset? minCreatedDateTime, DateTimeOffset? maxCreatedDateTime, DateTimeOffset? minLastModifiedDateTime, DateTimeOffset? maxLastModifiedDateTime, int? maxPageSize, string skipToken, RequestContext context) { return PageableHelpers.CreateAsyncPageable(CreateEnumerableAsync, ClientDiagnostics, diagnosticsScopeName); async IAsyncEnumerable<Page<BinaryData>> CreateEnumerableAsync(string nextLink, int? pageSizeHint, [EnumeratorCancellation] CancellationToken cancellationToken = default) { do { var message = string.IsNullOrEmpty(nextLink) ? CreateGetFarmsRequest(ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context) : CreateGetFarmsNextPageRequest(nextLink, ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context); var page = await LowLevelPageableHelpers.ProcessMessageAsync(_pipeline, message, context, "value", "nextLink", cancellationToken).ConfigureAwait(false); nextLink = page.ContinuationToken; yield return page; } while (!string.IsNullOrEmpty(nextLink)); } } /// <summary> Returns a paginated list of farm resources across all farmers. </summary> /// <param name="ids"> Ids of the resource. </param> /// <param name="names"> Names of the resource. </param> /// <param name="propertyFilters"> /// Filters on key-value pairs within the Properties object. /// eg. &quot;{testKey} eq {testValue}&quot;. /// </param> /// <param name="statuses"> Statuses of the resource. </param> /// <param name="minCreatedDateTime"> Minimum creation date of resource (inclusive). </param> /// <param name="maxCreatedDateTime"> Maximum creation date of resource (inclusive). </param> /// <param name="minLastModifiedDateTime"> Minimum last modified date of resource (inclusive). </param> /// <param name="maxLastModifiedDateTime"> Maximum last modified date of resource (inclusive). </param> /// <param name="maxPageSize"> /// Maximum number of items needed (inclusive). /// Minimum = 10, Maximum = 1000, Default value = 50. /// </param> /// <param name="skipToken"> Skip token for getting next set of results. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <remarks> /// Schema for <c>Response Body</c>: /// <code>{ /// value: [ /// { /// farmerId: string, /// id: string, /// eTag: string, /// status: string, /// createdDateTime: string (ISO 8601 Format), /// modifiedDateTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// ], /// $skipToken: string, /// nextLink: string /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual Pageable<BinaryData> GetFarms(IEnumerable<string> ids = null, IEnumerable<string> names = null, IEnumerable<string> propertyFilters = null, IEnumerable<string> statuses = null, DateTimeOffset? minCreatedDateTime = null, DateTimeOffset? maxCreatedDateTime = null, DateTimeOffset? minLastModifiedDateTime = null, DateTimeOffset? maxLastModifiedDateTime = null, int? maxPageSize = null, string skipToken = null, RequestContext context = null) { return GetFarmsImplementation("FarmsClient.GetFarms", ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context); } private Pageable<BinaryData> GetFarmsImplementation(string diagnosticsScopeName, IEnumerable<string> ids, IEnumerable<string> names, IEnumerable<string> propertyFilters, IEnumerable<string> statuses, DateTimeOffset? minCreatedDateTime, DateTimeOffset? maxCreatedDateTime, DateTimeOffset? minLastModifiedDateTime, DateTimeOffset? maxLastModifiedDateTime, int? maxPageSize, string skipToken, RequestContext context) { return PageableHelpers.CreatePageable(CreateEnumerable, ClientDiagnostics, diagnosticsScopeName); IEnumerable<Page<BinaryData>> CreateEnumerable(string nextLink, int? pageSizeHint) { do { var message = string.IsNullOrEmpty(nextLink) ? CreateGetFarmsRequest(ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context) : CreateGetFarmsNextPageRequest(nextLink, ids, names, propertyFilters, statuses, minCreatedDateTime, maxCreatedDateTime, minLastModifiedDateTime, maxLastModifiedDateTime, maxPageSize, skipToken, context); var page = LowLevelPageableHelpers.ProcessMessage(_pipeline, message, context, "value", "nextLink"); nextLink = page.ContinuationToken; yield return page; } while (!string.IsNullOrEmpty(nextLink)); } } /// <summary> Create a cascade delete job for specified farm. </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="jobId"> Job ID supplied by end user. </param> /// <param name="farmerId"> ID of the associated farmer. </param> /// <param name="farmId"> ID of the farm to be deleted. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="jobId"/>, <paramref name="farmerId"/> or <paramref name="farmId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="jobId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Response Body</c>: /// <code>{ /// farmerId: string, /// resourceId: string, /// resourceType: string, /// id: string, /// status: string, /// durationInSeconds: number, /// message: string, /// createdDateTime: string (ISO 8601 Format), /// lastActionDateTime: string (ISO 8601 Format), /// startTime: string (ISO 8601 Format), /// endTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual async Task<Operation<BinaryData>> CreateCascadeDeleteJobAsync(WaitUntil waitUntil, string jobId, string farmerId, string farmId, RequestContext context = null) { Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); Argument.AssertNotNull(farmerId, nameof(farmerId)); Argument.AssertNotNull(farmId, nameof(farmId)); using var scope = ClientDiagnostics.CreateScope("FarmsClient.CreateCascadeDeleteJob"); scope.Start(); try { using HttpMessage message = CreateCreateCascadeDeleteJobRequest(jobId, farmerId, farmId, context); return await LowLevelOperationHelpers.ProcessMessageAsync(_pipeline, message, ClientDiagnostics, "FarmsClient.CreateCascadeDeleteJob", OperationFinalStateVia.Location, context, waitUntil).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Create a cascade delete job for specified farm. </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="jobId"> Job ID supplied by end user. </param> /// <param name="farmerId"> ID of the associated farmer. </param> /// <param name="farmId"> ID of the farm to be deleted. </param> /// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="jobId"/>, <paramref name="farmerId"/> or <paramref name="farmId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="jobId"/> is an empty string, and was expected to be non-empty. </exception> /// <remarks> /// Schema for <c>Response Body</c>: /// <code>{ /// farmerId: string, /// resourceId: string, /// resourceType: string, /// id: string, /// status: string, /// durationInSeconds: number, /// message: string, /// createdDateTime: string (ISO 8601 Format), /// lastActionDateTime: string (ISO 8601 Format), /// startTime: string (ISO 8601 Format), /// endTime: string (ISO 8601 Format), /// name: string, /// description: string, /// properties: Dictionary&lt;string, AnyObject&gt; /// } /// </code> /// Schema for <c>Response Error</c>: /// <code>{ /// error: { /// code: string, /// message: string, /// target: string, /// details: [Error], /// innererror: { /// code: string, /// innererror: InnerError /// } /// }, /// traceId: string /// } /// </code> /// /// </remarks> public virtual Operation<BinaryData> CreateCascadeDeleteJob(WaitUntil waitUntil, string jobId, string farmerId, string farmId, RequestContext context = null) { Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); Argument.AssertNotNull(farmerId, nameof(farmerId)); Argument.AssertNotNull(farmId, nameof(farmId)); using var scope = ClientDiagnostics.CreateScope("FarmsClient.CreateCascadeDeleteJob"); scope.Start(); try { using HttpMessage message = CreateCreateCascadeDeleteJobRequest(jobId, farmerId, farmId, context); return LowLevelOperationHelpers.ProcessMessage(_pipeline, message, ClientDiagnostics, "FarmsClient.CreateCascadeDeleteJob", OperationFinalStateVia.Location, context, waitUntil); } catch (Exception e) { scope.Failed(e); throw; } } internal HttpMessage CreateGetFarmsByFarmerIdRequest(string farmerId, IEnumerable<string> ids, IEnumerable<string> names, IEnumerable<string> propertyFilters, IEnumerable<string> statuses, DateTimeOffset? minCreatedDateTime, DateTimeOffset? maxCreatedDateTime, DateTimeOffset? minLastModifiedDateTime, DateTimeOffset? maxLastModifiedDateTime, int? maxPageSize, string skipToken, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/farmers/", false); uri.AppendPath(farmerId, true); uri.AppendPath("/farms", false); if (ids != null) { foreach (var param in ids) { uri.AppendQuery("ids", param, true); } } if (names != null) { foreach (var param in names) { uri.AppendQuery("names", param, true); } } if (propertyFilters != null) { foreach (var param in propertyFilters) { uri.AppendQuery("propertyFilters", param, true); } } if (statuses != null) { foreach (var param in statuses) { uri.AppendQuery("statuses", param, true); } } if (minCreatedDateTime != null) { uri.AppendQuery("minCreatedDateTime", minCreatedDateTime.Value, "O", true); } if (maxCreatedDateTime != null) { uri.AppendQuery("maxCreatedDateTime", maxCreatedDateTime.Value, "O", true); } if (minLastModifiedDateTime != null) { uri.AppendQuery("minLastModifiedDateTime", minLastModifiedDateTime.Value, "O", true); } if (maxLastModifiedDateTime != null) { uri.AppendQuery("maxLastModifiedDateTime", maxLastModifiedDateTime.Value, "O", true); } if (maxPageSize != null) { uri.AppendQuery("$maxPageSize", maxPageSize.Value, true); } if (skipToken != null) { uri.AppendQuery("$skipToken", skipToken, true); } uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } internal HttpMessage CreateGetFarmsRequest(IEnumerable<string> ids, IEnumerable<string> names, IEnumerable<string> propertyFilters, IEnumerable<string> statuses, DateTimeOffset? minCreatedDateTime, DateTimeOffset? maxCreatedDateTime, DateTimeOffset? minLastModifiedDateTime, DateTimeOffset? maxLastModifiedDateTime, int? maxPageSize, string skipToken, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/farms", false); if (ids != null) { foreach (var param in ids) { uri.AppendQuery("ids", param, true); } } if (names != null) { foreach (var param in names) { uri.AppendQuery("names", param, true); } } if (propertyFilters != null) { foreach (var param in propertyFilters) { uri.AppendQuery("propertyFilters", param, true); } } if (statuses != null) { foreach (var param in statuses) { uri.AppendQuery("statuses", param, true); } } if (minCreatedDateTime != null) { uri.AppendQuery("minCreatedDateTime", minCreatedDateTime.Value, "O", true); } if (maxCreatedDateTime != null) { uri.AppendQuery("maxCreatedDateTime", maxCreatedDateTime.Value, "O", true); } if (minLastModifiedDateTime != null) { uri.AppendQuery("minLastModifiedDateTime", minLastModifiedDateTime.Value, "O", true); } if (maxLastModifiedDateTime != null) { uri.AppendQuery("maxLastModifiedDateTime", maxLastModifiedDateTime.Value, "O", true); } if (maxPageSize != null) { uri.AppendQuery("$maxPageSize", maxPageSize.Value, true); } if (skipToken != null) { uri.AppendQuery("$skipToken", skipToken, true); } uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } internal HttpMessage CreateGetFarmRequest(string farmerId, string farmId, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/farmers/", false); uri.AppendPath(farmerId, true); uri.AppendPath("/farms/", false); uri.AppendPath(farmId, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } internal HttpMessage CreateCreateOrUpdateRequest(string farmerId, string farmId, RequestContent content, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200201); var request = message.Request; request.Method = RequestMethod.Patch; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/farmers/", false); uri.AppendPath(farmerId, true); uri.AppendPath("/farms/", false); uri.AppendPath(farmId, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/merge-patch+json"); request.Content = content; return message; } internal HttpMessage CreateDeleteRequest(string farmerId, string farmId, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier204); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/farmers/", false); uri.AppendPath(farmerId, true); uri.AppendPath("/farms/", false); uri.AppendPath(farmId, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } internal HttpMessage CreateGetCascadeDeleteJobDetailsRequest(string jobId, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/farms/cascade-delete/", false); uri.AppendPath(jobId, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } internal HttpMessage CreateCreateCascadeDeleteJobRequest(string jobId, string farmerId, string farmId, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier202); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/farms/cascade-delete/", false); uri.AppendPath(jobId, true); uri.AppendQuery("farmerId", farmerId, true); uri.AppendQuery("farmId", farmId, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } internal HttpMessage CreateGetFarmsByFarmerIdNextPageRequest(string nextLink, string farmerId, IEnumerable<string> ids, IEnumerable<string> names, IEnumerable<string> propertyFilters, IEnumerable<string> statuses, DateTimeOffset? minCreatedDateTime, DateTimeOffset? maxCreatedDateTime, DateTimeOffset? minLastModifiedDateTime, DateTimeOffset? maxLastModifiedDateTime, int? maxPageSize, string skipToken, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } internal HttpMessage CreateGetFarmsNextPageRequest(string nextLink, IEnumerable<string> ids, IEnumerable<string> names, IEnumerable<string> propertyFilters, IEnumerable<string> statuses, DateTimeOffset? minCreatedDateTime, DateTimeOffset? maxCreatedDateTime, DateTimeOffset? minLastModifiedDateTime, DateTimeOffset? maxLastModifiedDateTime, int? maxPageSize, string skipToken, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } private static ResponseClassifier _responseClassifier200; private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); private static ResponseClassifier _responseClassifier200201; private static ResponseClassifier ResponseClassifier200201 => _responseClassifier200201 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 201 }); private static ResponseClassifier _responseClassifier204; private static ResponseClassifier ResponseClassifier204 => _responseClassifier204 ??= new StatusCodeClassifier(stackalloc ushort[] { 204 }); private static ResponseClassifier _responseClassifier202; private static ResponseClassifier ResponseClassifier202 => _responseClassifier202 ??= new StatusCodeClassifier(stackalloc ushort[] { 202 }); } }
49.737316
499
0.586058
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/agrifood/Azure.Verticals.AgriFood.Farming/src/Generated/FarmsClient.cs
60,779
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\IMethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IWorkbookFunctionsIsLogicalRequest. /// </summary> public partial interface IWorkbookFunctionsIsLogicalRequest : IBaseRequest { /// <summary> /// Gets the request body. /// </summary> WorkbookFunctionsIsLogicalRequestBody RequestBody { get; } /// <summary> /// Issues the POST request. /// </summary> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(); /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IWorkbookFunctionsIsLogicalRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IWorkbookFunctionsIsLogicalRequest Select(string value); } }
33.677419
153
0.58908
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsIsLogicalRequest.cs
2,088
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace kubernetes_hello_world_demo { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
27.222222
71
0.629932
[ "MIT" ]
cloudblockandbeyond/kubernetes-hello-world-demo
kubernetes-hello-world-demo/Program.cs
735
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace HashMapImplementation { /* * Reviewing what a hashmap actually is, I use it all the time, * but don't actually understand what it is or how it works. * https://youtu.be/s8YcbwVl-HI * */ class Program { static Hashtable userInfoHash; static List<UserInfo> userInfoList; static Stopwatch SW; const int maxSizeofHashTable = 5000000 ; static void Main(string[] args) { userInfoHash = new Hashtable(); userInfoList = new List<UserInfo>(); SW = new Stopwatch(); int deepestQuarterSizeofHashTable = (int)(maxSizeofHashTable * 0.75); // Add to hashtable and list for (int i = 0; i < maxSizeofHashTable; i++) { // add useri value with key i userInfoHash.Add(i, "user" + i); // add to list as well userInfoList.Add(new UserInfo(i, "user" + i)); } Console.WriteLine("Testing List<UserInfo> with full lookup range using brute force"); var averageLookupTimeinMS = AverageLookupTimeRoughEstimate(1, maxSizeofHashTable, GetUserFromList_BruteForceSearch, 404); Console.WriteLine("AVG time taken to retrieve FROM LIST full range brute force " + string.Format("{0:0.##}", averageLookupTimeinMS.ToString()) + " ms\n\n"); Console.WriteLine("Testing List<UserInfo> with skewed deep lookup range using brute force"); averageLookupTimeinMS = AverageLookupTimeRoughEstimate(deepestQuarterSizeofHashTable, maxSizeofHashTable, GetUserFromList_BruteForceSearch, 404); Console.WriteLine("AVG time taken to retrieve FROM LIST deepest 75% range brute force " + string.Format("{0:0.##}", averageLookupTimeinMS.ToString()) + " ms\n\n"); Console.WriteLine("Testing List<UserInfo> with full lookup range using List.Find()"); averageLookupTimeinMS = AverageLookupTimeRoughEstimate(1, maxSizeofHashTable, GetUserFromList_Find, 404); Console.WriteLine("AVG time taken to retrieve FROM LIST full range with Find() " + string.Format("{0:0.##}", averageLookupTimeinMS.ToString()) + " ms\n\n"); Console.WriteLine("Testing List<UserInfo> with skewed deep lookup range using List.Find()"); averageLookupTimeinMS = AverageLookupTimeRoughEstimate(deepestQuarterSizeofHashTable, maxSizeofHashTable, GetUserFromList_Find, 404); Console.WriteLine("AVG time taken to retrieve FROM LIST deepest 75% range with Find() " + string.Format("{0:0.##}", averageLookupTimeinMS.ToString()) + " ms\n\n"); Console.WriteLine("Testing Hashtable<UserInfo> with full lookup range"); averageLookupTimeinMS = AverageLookupTimeRoughEstimate(1, maxSizeofHashTable, GetUserFromHashTable, 404); Console.WriteLine("AVG time taken to retrieve FROM HASHTABLE full range " + string.Format("{0:0.##}", averageLookupTimeinMS.ToString()) + " ms\n\n"); Console.WriteLine("Testing Hashtable<UserInfo> with skewed deep lookup range"); averageLookupTimeinMS = AverageLookupTimeRoughEstimate(deepestQuarterSizeofHashTable, maxSizeofHashTable, GetUserFromHashTable, 404); Console.WriteLine("AVG time taken to retrieve FROM HASHTABLE deepest 75% range " + string.Format("{0:0.##}", averageLookupTimeinMS.ToString()) + " ms\n\n"); // how to use built-in c# hashmap, what is hashmap. // Build own hashmap // make own hashing function // Test performance of all three. } /* Hashtable is a collection of key value pairs (associative array) Key is an indexer Value is accessed by key; Value = Hashtable[key]; Hashtables are best collection for lookup times, every value has unique key, O(1) constant time to lookup Default Hashtable in C# uses Dictionary, can foreach DictionaryEntry in Hashtable{} Hash function maps a key to a unique index where a value is held; the same key will map to the same value index every time If the hash function maps to an occupied value index, that is a 'collision', can resolve with chain links on that index or larger table Usually key is stored with value in memory like a 'header' */ // brute force list search public static string GetUserFromList_BruteForceSearch(int userId) { for (int i = 0; i < userInfoList.Count; i++) { if (userInfoList[i].userId == userId) { return userInfoList[i].userName; } } return string.Empty; } // List.Find() search public static string GetUserFromList_Find(int userId) { return userInfoList.Find(x => x.userId == userId).userName; } public static string GetUserFromHashTable(int userId) { return (string)userInfoHash[userId]; } public delegate string GetUserInfoUserName(int userId); public static float AverageLookupTimeRoughEstimate(int minRandomVal, int maxRandomVal, GetUserInfoUserName lookupFunction, int cycles = 5) { // access Random randomUserGen = new Random(); int randomUser = -1; SW.Start(); float startTime = 0f; float endTime = 0f; float deltaTime = 0f; float averageTime = 0f; int cycle = 0; string userName = string.Empty; // compare list to hashtable with full range of random users while (cycle < cycles) { // same random user for both randomUser = randomUserGen.Next(minRandomVal, maxRandomVal); // set a starting timestamp startTime = SW.ElapsedMilliseconds; // perform time sensitive operation userName = lookupFunction(randomUser); // ACTUALLY WORKING WOW!!! // set an ending timestamp endTime = SW.ElapsedMilliseconds; // print out the change in time deltaTime = endTime - startTime; averageTime += deltaTime; //Console.WriteLine("Time taken to retrieve " + userName + " FROM LIST " // + string.Format("{0:0.##}", deltaTime) + "ms"); //Console.WriteLine("Time taken to retrieve " + userName + " FROM H@$HTABLE " // + string.Format("{0:0.##}", deltaTime) + "ms"); cycle++; } return averageTime / cycles; } } // type for list to demonstrate hashtable speed struct UserInfo { public int userId; public string userName; public UserInfo(int id, string name) { userId = id; userName = name; } } }
37.994819
157
0.602891
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
JayGarxP/InterviewPrep
CtCI/1_Arrays_Strings/HashMapandTableComparisons-C#-VS/HashMapImplementation/Program.cs
7,335
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace BSMatchMaker { static class Program { /// <summary> /// アプリケーションのメイン エントリ ポイントです。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } } }
24
65
0.611842
[ "Apache-2.0" ]
hhosaka/BSMatchMaker
Program.cs
504
C#
using System; using System.Collections.Generic; using System.Windows.Input; using Xamarin.Essentials; using Xamarin.Forms; using UpcomingMoviesMob.Core; using UpcomingMoviesMob.Models; using System.Collections.ObjectModel; using UpcomingMoviesMob.Views; namespace UpcomingMoviesMob.ViewModels { public class AboutViewModel : BaseViewModel { public string Greeting { get; set; } = "Hello!"; TmdbAPI tmdb = new TmdbAPI(); public ObservableCollection<TrendingItem> TrendingTodayCollection { get; set; } public ObservableCollection<TrendingItem> TrendingWeekCollection { get; set; } public Command<TrendingItem> ItemTapped { get; } public AboutViewModel() { Title = "Home"; CreateGreeting(); TrendingTodayCollection = tmdb.GetTrendingToday(); TrendingWeekCollection = tmdb.GetTrendingWeek(); ItemTapped = new Command<TrendingItem>(OnItemSelected); } async void OnItemSelected(TrendingItem trendingItem) { if (trendingItem == null) return; // This will push the ItemDetailPage onto the navigation stack if (trendingItem.media_type == "movie") { await Shell.Current.GoToAsync($"{nameof(MovieDetailPage)}?{nameof(MovieDetailViewModel.MovieId)}={trendingItem.id}"); } else if (trendingItem.media_type == "tv") { await Shell.Current.GoToAsync($"{nameof(SeriesDetailPage)}?{nameof(SeriesDetailViewModel.SeriesId)}={trendingItem.id}"); } } private void CreateGreeting() { if ((DateTime.Now.Hour >= 21) && (DateTime.Now.Hour < 5)) { Greeting = "Good night!"; } if ((DateTime.Now.Hour >= 5) && (DateTime.Now.Hour < 12)) { Greeting = "Good morning!"; } if ((DateTime.Now.Hour >= 12) && (DateTime.Now.Hour < 17)) { Greeting = "Good afternoon!"; } if ((DateTime.Now.Hour >= 17) && (DateTime.Now.Hour < 21)) { Greeting = "Good evening!"; } } public ICommand OpenTmdbWebsite { get { return new Command(OpenTmdbWebsiteAsync); } } private async void OpenTmdbWebsiteAsync() { try { string url = "https://www.themoviedb.org/"; await Browser.OpenAsync(url, BrowserLaunchMode.SystemPreferred); } catch { // An unexpected error occured. No browser may be installed on the device. } } } }
33.223529
136
0.551346
[ "MIT" ]
catsbyy/movies-are-coming-android
UpcomingMoviesMob/ViewModels/AboutViewModel.cs
2,826
C#
/* * MundiAPI.Standard * * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). */ using System; using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using MundiAPI.Standard; using MundiAPI.Standard.Utilities; using MundiAPI.Standard.Http.Request; using MundiAPI.Standard.Http.Response; using MundiAPI.Standard.Http.Client; namespace MundiAPI.Standard.Controllers { public partial interface ITransactionsController { /// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="transactionId">Required parameter: Example: </param> /// <return>Returns the Models.GetTransactionResponse response from the API call</return> Models.GetTransactionResponse GetTransaction(string transactionId); /// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="transactionId">Required parameter: Example: </param> /// <return>Returns the Models.GetTransactionResponse response from the API call</return> Task<Models.GetTransactionResponse> GetTransactionAsync(string transactionId); } }
34.078947
98
0.693436
[ "MIT" ]
mundipagg/MundiAPI-NetStandard
MundiAPI.Standard/Controllers/ITransactionsController.cs
1,295
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using SamuraiApp.Data; namespace SamuraiApp.Data.Migrations { [DbContext(typeof(SamuraiContext))] [Migration("20210211201748_battledates")] partial class battledates { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.3") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("SamuraiApp.Domain.Battle", b => { b.Property<int>("BattleId") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("EndDate") .HasColumnType("datetime2"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("StartDate") .HasColumnType("datetime2"); b.HasKey("BattleId"); b.ToTable("Battles"); }); modelBuilder.Entity("SamuraiApp.Domain.BattleSamurai", b => { b.Property<int>("BattleId") .HasColumnType("int"); b.Property<int>("SamuraiId") .HasColumnType("int"); b.Property<DateTime>("DateJoined") .ValueGeneratedOnAdd() .HasColumnType("datetime2") .HasDefaultValueSql("getDate()"); b.HasKey("BattleId", "SamuraiId"); b.HasIndex("SamuraiId"); b.ToTable("BattleSamurai"); }); modelBuilder.Entity("SamuraiApp.Domain.Horse", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int>("SamuraiId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("SamuraiId") .IsUnique(); b.ToTable("Horse"); }); modelBuilder.Entity("SamuraiApp.Domain.Quote", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("SamuraiId") .HasColumnType("int"); b.Property<string>("Text") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("SamuraiId"); b.ToTable("Quotes"); }); modelBuilder.Entity("SamuraiApp.Domain.Samurai", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Samurais"); }); modelBuilder.Entity("SamuraiApp.Domain.BattleSamurai", b => { b.HasOne("SamuraiApp.Domain.Battle", null) .WithMany() .HasForeignKey("BattleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("SamuraiApp.Domain.Samurai", null) .WithMany() .HasForeignKey("SamuraiId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("SamuraiApp.Domain.Horse", b => { b.HasOne("SamuraiApp.Domain.Samurai", null) .WithOne("Horse") .HasForeignKey("SamuraiApp.Domain.Horse", "SamuraiId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("SamuraiApp.Domain.Quote", b => { b.HasOne("SamuraiApp.Domain.Samurai", "Samurai") .WithMany("Quotes") .HasForeignKey("SamuraiId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Samurai"); }); modelBuilder.Entity("SamuraiApp.Domain.Samurai", b => { b.Navigation("Horse"); b.Navigation("Quotes"); }); #pragma warning restore 612, 618 } } }
35.638554
125
0.478026
[ "MIT" ]
DiracSpace/EF-Core
SamuraiApp.Data/Migrations/20210211201748_battledates.Designer.cs
5,918
C#
using System; using System.Linq; using Android.Content; using Toggl.Foundation.Services; using Toggl.PrimeRadiant.Settings; namespace Toggl.Giskard.Services { public sealed class SharedPreferencesStorageAndroid : KeyValueStorage { private readonly ISharedPreferences sharedPreferences; public SharedPreferencesStorageAndroid(ISharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } public override bool GetBool(string key) => sharedPreferences.GetBoolean(key, false); public override string GetString(string key) => sharedPreferences.GetString(key, null); public override void SetBool(string key, bool value) { var editor = sharedPreferences.Edit(); editor.PutBoolean(key, value); editor.Commit(); } public override void SetString(string key, string value) { var editor = sharedPreferences.Edit(); editor.PutString(key, value); editor.Commit(); } public override void SetInt(string key, int value) { var editor = sharedPreferences.Edit(); editor.PutInt(key, value); editor.Commit(); } public override void SetLong(string key, long value) { var editor = sharedPreferences.Edit(); editor.PutLong(key, value); editor.Commit(); } public override int GetInt(string key, int defaultValue) => sharedPreferences.GetInt(key, defaultValue); public override long GetLong(string key, long defaultValue) => sharedPreferences.GetLong(key, defaultValue); public override void Remove(string key) { var editor = sharedPreferences.Edit(); editor.Remove(key); editor.Commit(); } public override void RemoveAllWithPrefix(string prefix) { var keys = sharedPreferences.All.Keys .Where(key => key.StartsWith(prefix, StringComparison.Ordinal)); var editor = sharedPreferences.Edit(); foreach (var key in keys) { editor.Remove(key); } editor.Commit(); } } }
28.91358
84
0.595645
[ "BSD-3-Clause" ]
AzureMentor/mobileapp
Toggl.Giskard/Services/SharedPreferencesStorageAndroid.cs
2,344
C#
namespace Piranha.Jawbone.Sqlite { // https://www.sqlite.org/lang_conflict.html public enum ConflictResolution { Default = 0, Replace = 1, Rollback = 2, Abort = 3, Fail = 4, Ignore = 5 } }
18.071429
48
0.529644
[ "Unlicense" ]
ObviousPiranha/Jawbone
Piranha.Jawbone/Sqlite/ConflictResolution.cs
253
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Cdn.V20171012.Outputs { [OutputType] public sealed class CacheExpirationActionParametersResponse { /// <summary> /// Caching behavior for the requests that include query strings. /// </summary> public readonly string CacheBehavior; /// <summary> /// The duration for which the content needs to be cached. Allowed format is [d.]hh:mm:ss /// </summary> public readonly string? CacheDuration; /// <summary> /// The level at which the content needs to be cached. /// </summary> public readonly string CacheType; public readonly string OdataType; [OutputConstructor] private CacheExpirationActionParametersResponse( string cacheBehavior, string? cacheDuration, string cacheType, string odataType) { CacheBehavior = cacheBehavior; CacheDuration = cacheDuration; CacheType = cacheType; OdataType = odataType; } } }
29.574468
97
0.633094
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Cdn/V20171012/Outputs/CacheExpirationActionParametersResponse.cs
1,390
C#
using System.Collections.Generic; using System.Reflection; using System.Runtime.Serialization; using System.Diagnostics; using System.Globalization; using Macross.Json.Extensions; namespace System.Text.Json.Serialization { #pragma warning disable CA1812 // Remove class never instantiated internal class JsonStringEnumMemberConverter<T> : JsonConverter<T> #pragma warning restore CA1812 // Remove class never instantiated { private const BindingFlags EnumBindings = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; #if NETSTANDARD2_0 private static readonly string[] s_Split = new string[] { ", " }; #endif private class EnumInfo { #pragma warning disable SA1401 // Fields should be private public string Name; public Enum EnumValue; public ulong RawValue; #pragma warning restore SA1401 // Fields should be private public EnumInfo(string name, Enum enumValue, ulong rawValue) { Name = name; EnumValue = enumValue; RawValue = rawValue; } } private readonly bool _AllowIntegerValues; private readonly Type? _UnderlyingType; private readonly Type _EnumType; private readonly TypeCode _EnumTypeCode; private readonly bool _IsFlags; private readonly Dictionary<ulong, EnumInfo> _RawToTransformed; private readonly Dictionary<string, EnumInfo> _TransformedToRaw; public JsonStringEnumMemberConverter(JsonNamingPolicy? namingPolicy, bool allowIntegerValues, Type? underlyingType) { Debug.Assert( (typeof(T).IsEnum && underlyingType == null) || (Nullable.GetUnderlyingType(typeof(T)) == underlyingType), "Generic type is invalid."); _AllowIntegerValues = allowIntegerValues; _UnderlyingType = underlyingType; _EnumType = _UnderlyingType ?? typeof(T); _EnumTypeCode = Type.GetTypeCode(_EnumType); _IsFlags = _EnumType.IsDefined(typeof(FlagsAttribute), true); string[] builtInNames = _EnumType.GetEnumNames(); Array builtInValues = _EnumType.GetEnumValues(); _RawToTransformed = new Dictionary<ulong, EnumInfo>(); _TransformedToRaw = new Dictionary<string, EnumInfo>(); for (int i = 0; i < builtInNames.Length; i++) { Enum? enumValue = (Enum?)builtInValues.GetValue(i); if (enumValue == null) continue; ulong rawValue = GetEnumValue(enumValue); string name = builtInNames[i]; FieldInfo field = _EnumType.GetField(name, EnumBindings)!; EnumMemberAttribute? enumMemberAttribute = field.GetCustomAttribute<EnumMemberAttribute>(true); string transformedName = enumMemberAttribute?.Value ?? namingPolicy?.ConvertName(name) ?? name; _RawToTransformed[rawValue] = new EnumInfo(transformedName, enumValue, rawValue); _TransformedToRaw[transformedName] = new EnumInfo(name, enumValue, rawValue); } } public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { JsonTokenType token = reader.TokenType; if (token == JsonTokenType.String) { string enumString = reader.GetString()!; // Case sensitive search attempted first. if (_TransformedToRaw.TryGetValue(enumString, out EnumInfo? enumInfo)) return (T)Enum.ToObject(_EnumType, enumInfo.RawValue); if (_IsFlags) { ulong calculatedValue = 0; #if NETSTANDARD2_0 string[] flagValues = enumString.Split(s_Split, StringSplitOptions.None); #else string[] flagValues = enumString.Split(", "); #endif foreach (string flagValue in flagValues) { // Case sensitive search attempted first. if (_TransformedToRaw.TryGetValue(flagValue, out enumInfo)) { calculatedValue |= enumInfo.RawValue; } else { // Case insensitive search attempted second. bool matched = false; foreach (KeyValuePair<string, EnumInfo> enumItem in _TransformedToRaw) { if (string.Equals(enumItem.Key, flagValue, StringComparison.OrdinalIgnoreCase)) { calculatedValue |= enumItem.Value.RawValue; matched = true; break; } } if (!matched) throw ThrowHelper.GenerateJsonException_DeserializeUnableToConvertValue(_EnumType, flagValue); } } return (T)Enum.ToObject(_EnumType, calculatedValue); } // Case insensitive search attempted second. foreach (KeyValuePair<string, EnumInfo> enumItem in _TransformedToRaw) { if (string.Equals(enumItem.Key, enumString, StringComparison.OrdinalIgnoreCase)) { return (T)Enum.ToObject(_EnumType, enumItem.Value.RawValue); } } throw ThrowHelper.GenerateJsonException_DeserializeUnableToConvertValue(_EnumType, enumString); } if (token != JsonTokenType.Number || !_AllowIntegerValues) throw ThrowHelper.GenerateJsonException_DeserializeUnableToConvertValue(_EnumType); switch (_EnumTypeCode) { case TypeCode.Int32: if (reader.TryGetInt32(out int int32)) { return (T)Enum.ToObject(_EnumType, int32); } break; case TypeCode.Int64: if (reader.TryGetInt64(out long int64)) { return (T)Enum.ToObject(_EnumType, int64); } break; case TypeCode.Int16: if (reader.TryGetInt16(out short int16)) { return (T)Enum.ToObject(_EnumType, int16); } break; case TypeCode.Byte: if (reader.TryGetByte(out byte ubyte8)) { return (T)Enum.ToObject(_EnumType, ubyte8); } break; case TypeCode.UInt32: if (reader.TryGetUInt32(out uint uint32)) { return (T)Enum.ToObject(_EnumType, uint32); } break; case TypeCode.UInt64: if (reader.TryGetUInt64(out ulong uint64)) { return (T)Enum.ToObject(_EnumType, uint64); } break; case TypeCode.UInt16: if (reader.TryGetUInt16(out ushort uint16)) { return (T)Enum.ToObject(_EnumType, uint16); } break; case TypeCode.SByte: if (reader.TryGetSByte(out sbyte byte8)) { return (T)Enum.ToObject(_EnumType, byte8); } break; } throw ThrowHelper.GenerateJsonException_DeserializeUnableToConvertValue(_EnumType); } public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { // Note: There is no check for value == null because Json serializer won't call the converter in that case. ulong rawValue = GetEnumValue(value!); if (_RawToTransformed.TryGetValue(rawValue, out EnumInfo? enumInfo)) { writer.WriteStringValue(enumInfo.Name); return; } if (_IsFlags) { ulong calculatedValue = 0; StringBuilder Builder = new StringBuilder(); foreach (KeyValuePair<ulong, EnumInfo> enumItem in _RawToTransformed) { enumInfo = enumItem.Value; if (!(value as Enum)!.HasFlag(enumInfo.EnumValue) || enumInfo.RawValue == 0) // Definitions with 'None' should hit the cache case. { continue; } // Track the value to make sure all bits are represented. calculatedValue |= enumInfo.RawValue; if (Builder.Length > 0) Builder.Append(", "); Builder.Append(enumInfo.Name); } if (calculatedValue == rawValue) { writer.WriteStringValue(Builder.ToString()); return; } } if (!_AllowIntegerValues) throw new JsonException($"Enum type {_EnumType} does not have a mapping for integer value '{rawValue.ToString(CultureInfo.CurrentCulture)}'."); switch (_EnumTypeCode) { case TypeCode.Int32: writer.WriteNumberValue((int)rawValue); break; case TypeCode.Int64: writer.WriteNumberValue((long)rawValue); break; case TypeCode.Int16: writer.WriteNumberValue((short)rawValue); break; case TypeCode.Byte: writer.WriteNumberValue((byte)rawValue); break; case TypeCode.UInt32: writer.WriteNumberValue((uint)rawValue); break; case TypeCode.UInt64: writer.WriteNumberValue(rawValue); break; case TypeCode.UInt16: writer.WriteNumberValue((ushort)rawValue); break; case TypeCode.SByte: writer.WriteNumberValue((sbyte)rawValue); break; default: throw new JsonException(); // GetEnumValue should have already thrown. } } private ulong GetEnumValue(object value) { return _EnumTypeCode switch { TypeCode.Int32 => (ulong)(int)value, TypeCode.Int64 => (ulong)(long)value, TypeCode.Int16 => (ulong)(short)value, TypeCode.Byte => (byte)value, TypeCode.UInt32 => (uint)value, TypeCode.UInt64 => (ulong)value, TypeCode.UInt16 => (ushort)value, TypeCode.SByte => (ulong)(sbyte)value, _ => throw new NotSupportedException($"Enum '{value}' of {_EnumTypeCode} type is not supported."), }; } } }
29.883162
147
0.693307
[ "MIT" ]
tsvx/core
ClassLibraries/Macross.Json.Extensions/Code/System.Text.Json.Serialization/JsonStringEnumMemberConverter{T}.cs
8,698
C#
using System; namespace Elreg.GhostCarService.Replay { public interface IPlayer { void Start(); void Stop(); void Finish(); void Pause(); void Restart(); int LapCount { get; } DateTime? TimeStampOfLastLap { get; } event EventHandler LapAdded; bool IsRecordedLapPlayerActiv { get; } bool ForceSuppressRecordedLap { get; set; } uint? ForcedSpeed { set; } } }
25
52
0.56
[ "MIT" ]
Heinzman/DigiRcMan
VisualStudio/Sources/GhostCarService/Replay/IPlayer.cs
475
C#
/* ######### ############ ############# ## ########### ### ###### ##### ### ####### #### ### ########## #### #### ########### #### #### ########### ##### ##### ### ######## ##### ##### ### ######## ###### ###### ### ########### ###### ###### #### ############## ###### ####### ##################### ###### ####### ###################### ###### ####### ###### ################# ###### ####### ###### ###### ######### ###### ####### ## ###### ###### ###### ####### ###### ##### ##### ###### ##### ##### #### ##### #### ##### ### ##### ### ### # ### ### ### ## ### ### __________#_______####_______####______________ 我们的未来没有BUG * ============================================================================== * Filename: List.cs * Created: 2018/7/13 14:29:22 * Author: エル・プサイ・コングリィ * Purpose: * ============================================================================== */ #if UNITY_EDITOR || USE_LUA_PROFILER using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MikuLuaProfiler { public class MList<T> { private const int DefaultCapacity = 4; private T[] _items; private int _size; private int _version; public MList(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity"); } this._items = new T[capacity]; } public int Capacity { get { return this._items.Length; } set { if (value < this._size) { throw new ArgumentOutOfRangeException(); } Array.Resize<T>(ref this._items, value); } } public int Count { get { return this._size; } } public T this[int index] { get { return this._items[index]; } set { this._items[index] = value; } } public void Clear() { this._size = 0; this._version++; } public void Add(T item) { if (this._size == this._items.Length) { this.GrowIfNeeded(1); } this._items[this._size++] = item; this._version++; } private void GrowIfNeeded(int newCount) { int num = this._size + newCount; if (num > this._items.Length) { this.Capacity = Math.Max(Math.Max(this.Capacity * 2, 4), num); } } public void RemoveAt(int index) { if (index < 0 || index >= this._size) { throw new ArgumentOutOfRangeException("index"); } this.Shift(index, -1); Array.Clear(this._items, this._size, 1); this._version++; } private void Shift(int start, int delta) { if (delta < 0) { start -= delta; } if (start < this._size) { Array.Copy(this._items, start, this._items, start + delta, this._size - start); } this._size += delta; if (delta < 0) { Array.Clear(this._items, this._size, -delta); } } } } #endif
27.893333
95
0.294216
[ "Apache-2.0" ]
13751742405/Miku-LuaProfiler
LuaProfiler/Tools/InjectAPKTool/InjectToLua/DLL/Core/Driver/List.cs
4,224
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Entities.Concrete { public class UserOperationClaim : IEntity { [Key] public int Id { get; set; } public int UserId { get; set; } public int OperationClaimId { get; set; } } }
22.166667
49
0.681704
[ "MIT" ]
tuncerrstm/ReCapProject
Core/Entities/Concrete/UserOperationClaim.cs
401
C#
using System.Collections.Generic; using System.Linq; using MapzenGo.Helpers; using MapzenGo.Models.Factories; using MapzenGo.Models.Settings; using UnityEngine; using UnityEngine.UI; namespace MapzenGo.Models { public class PoiFactory : Factory { [SerializeField] private GameObject _labelPrefab; [SerializeField] private GameObject _container; public override string XmlTag { get { return "pois"; } } [SerializeField] protected PoiFactorySettings FactorySettings; public override void Start() { base.Start(); Query = (geo) => geo["geometry"]["type"].str == "Point" && geo["properties"].HasField("name"); } public override void Create(Tile tile) { if (!(tile.Data.HasField(XmlTag) && tile.Data[XmlTag].HasField("features"))) return; foreach (var entity in tile.Data[XmlTag]["features"].list.Where(x => Query(x)).SelectMany(geo => Create(tile, geo))) { if (entity != null) { entity.transform.SetParent(_container.transform, true); //entity.transform.localScale = Vector3.one * 3/tile.transform.lossyScale.x; } } } protected override IEnumerable<MonoBehaviour> Create(Tile tile, JSONObject geo) { var kind = geo["properties"]["kind"].str.ConvertToPoiType(); if (!FactorySettings.HasSettingsFor(kind)) yield break; var typeSettings = FactorySettings.GetSettingsFor<PoiSettings>(kind); var go = Instantiate(_labelPrefab); var poi = go.AddComponent<Poi>(); poi.transform.SetParent(_container.transform, true); poi.GetComponentInChildren<Image>().sprite = typeSettings.Sprite; //if (geo["properties"].HasField("name")) // go.GetComponentInChildren<TextMesh>().text = geo["properties"]["name"].str; var c = geo["geometry"]["coordinates"]; var dotMerc = GM.LatLonToMeters(c[1].f, c[0].f); var localMercPos = dotMerc - tile.Rect.Center; go.transform.position = new Vector3((float) localMercPos.x, (float) localMercPos.y); var target = new GameObject("poiTarget"); target.transform.position = localMercPos.ToVector3(); target.transform.SetParent(tile.transform, false); poi.Stick(target.transform); SetProperties(geo, poi, typeSettings); yield return poi; } private static void SetProperties(JSONObject geo, Poi poi, PoiSettings typeSettings) { poi.Id = geo["properties"]["id"].ToString(); if (geo["properties"].HasField("name")) poi.Name = geo["properties"]["name"].str; poi.Type = geo["type"].str; poi.Kind = geo["properties"]["kind"].str; poi.name = "poi"; } } }
38.063291
128
0.586299
[ "MIT" ]
Galahaddruid/MapzenGo
Assets/MapzenGo/Models/Factories/PoiFactory.cs
3,009
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.AspNetCore.Http.Features { /// <summary> /// Provides information regarding TLS token binding parameters. /// </summary> /// <remarks> /// TLS token bindings help mitigate the risk of impersonation by an attacker in the /// event an authenticated client's bearer tokens are somehow exfiltrated from the /// client's machine. See https://datatracker.ietf.org/doc/draft-popov-token-binding/ /// for more information. /// </remarks> public interface ITlsTokenBindingFeature { /// <summary> /// Gets the 'provided' token binding identifier associated with the request. /// </summary> /// <returns>The token binding identifier, or null if the client did not /// supply a 'provided' token binding or valid proof of possession of the /// associated private key. The caller should treat this identifier as an /// opaque blob and should not try to parse it.</returns> byte[] GetProvidedTokenBindingId(); /// <summary> /// Gets the 'referred' token binding identifier associated with the request. /// </summary> /// <returns>The token binding identifier, or null if the client did not /// supply a 'referred' token binding or valid proof of possession of the /// associated private key. The caller should treat this identifier as an /// opaque blob and should not try to parse it.</returns> byte[] GetReferredTokenBindingId(); } }
46
89
0.669686
[ "MIT" ]
48355746/AspNetCore
src/Http/Http.Features/src/ITlsTokenBindingFeature.cs
1,656
C#
using GaiaProject.Engine.Enums; using MongoDB.Bson.Serialization.Attributes; namespace GaiaProject.Engine.Model.Actions { [BsonDiscriminator(nameof(RescoreFederationTokenAction))] public class RescoreFederationTokenAction : PlayerAction { public override ActionType Type => ActionType.RescoreFederationToken; public FederationTokenType Token { get; set; } public override string ToString() { return $"rescores federation token {Token.ToDescription()}"; } } }
28.117647
71
0.788703
[ "MIT" ]
Etchelon/gaiaproject
Backend/Libraries/Engine/Model/Actions/RescoreFederationTokenAction.cs
480
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Nest { [MapsApi("graph.explore.json")] public partial interface IGraphExploreRequest : IHop { [DataMember(Name ="controls")] IGraphExploreControls Controls { get; set; } } // ReSharper disable once UnusedTypeParameter public partial interface IGraphExploreRequest<TDocument> where TDocument : class { } public partial class GraphExploreRequest { public IHop Connections { get; set; } public IGraphExploreControls Controls { get; set; } public QueryContainer Query { get; set; } public IEnumerable<IGraphVertexDefinition> Vertices { get; set; } } // ReSharper disable once UnusedTypeParameter public partial class GraphExploreRequest<TDocument> where TDocument : class { } public partial class GraphExploreDescriptor<TDocument> where TDocument : class { IHop IHop.Connections { get; set; } IGraphExploreControls IGraphExploreRequest.Controls { get; set; } QueryContainer IHop.Query { get; set; } IEnumerable<IGraphVertexDefinition> IHop.Vertices { get; set; } public GraphExploreDescriptor<TDocument> Query(Func<QueryContainerDescriptor<TDocument>, QueryContainer> querySelector) => Assign(querySelector, (a, v) => a.Query = v?.Invoke(new QueryContainerDescriptor<TDocument>())); public GraphExploreDescriptor<TDocument> Vertices(Func<GraphVerticesDescriptor<TDocument>, IPromise<IList<IGraphVertexDefinition>>> selector) => Assign(selector, (a, v) => a.Vertices = v?.Invoke(new GraphVerticesDescriptor<TDocument>())?.Value); public GraphExploreDescriptor<TDocument> Connections(Func<HopDescriptor<TDocument>, IHop> selector) => Assign(selector, (a, v) => a.Connections = v?.Invoke(new HopDescriptor<TDocument>())); public GraphExploreDescriptor<TDocument> Controls(Func<GraphExploreControlsDescriptor<TDocument>, IGraphExploreControls> selector) => Assign(selector, (a, v) => a.Controls = v?.Invoke(new GraphExploreControlsDescriptor<TDocument>())); } }
42.634615
146
0.77041
[ "Apache-2.0" ]
Atharvpatel21/elasticsearch-net
src/Nest/XPack/Graph/Explore/GraphExploreRequest.cs
2,217
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace UserTestsModels { public class User { public User() { } public string Auth0Id { get; set; } public int Revapoints { get; set; } } }
20.411765
44
0.674352
[ "MIT" ]
210503-Reston-KwikKoder/Back-End-Tests
UTBE/UserTestsModels/User.cs
347
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System.Collections.Concurrent; using System.Linq; using System.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { // Tests that should take a long time, perhaps even exceeding // test timeout, without shortcuts in overload resolution. public class OverloadResolutionPerfTests : CSharpTestBase { [WorkItem(13685, "https://github.com/dotnet/roslyn/issues/13685")] [ConditionalFactAttribute(typeof(IsRelease), typeof(NoIOperationValidation))] public void Overloads() { const int n = 3000; var builder = new StringBuilder(); builder.AppendLine("class C"); builder.AppendLine("{"); builder.AppendLine($" static void F() {{ F(null); }}"); // matches n overloads: F(C0), F(C1), ... for (int i = 0; i < n; i++) { builder.AppendLine($" static void F(C{i} c) {{ }}"); } builder.AppendLine("}"); for (int i = 0; i < n; i++) { builder.AppendLine($"class C{i} {{ }}"); } var source = builder.ToString(); var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (3,23): error CS0121: The call is ambiguous between the following methods or properties: 'C.F(C0)' and 'C.F(C1)' // static void F() { F(null); } Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("C.F(C0)", "C.F(C1)").WithLocation(3, 23)); } [WorkItem(13685, "https://github.com/dotnet/roslyn/issues/13685")] [ConditionalFactAttribute(typeof(IsRelease), typeof(NoIOperationValidation))] public void BinaryOperatorOverloads() { const int n = 3000; var builder = new StringBuilder(); builder.AppendLine("class C"); builder.AppendLine("{"); builder.AppendLine($" static object F(C x) => x + null;"); // matches n overloads: +(C, C0), +(C, C1), ... for (int i = 0; i < n; i++) { builder.AppendLine($" public static object operator+(C x, C{i} y) => null;"); } builder.AppendLine("}"); for (int i = 0; i < n; i++) { builder.AppendLine($"class C{i} {{ }}"); } var source = builder.ToString(); var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (3,29): error CS0034: Operator '+' is ambiguous on operands of type 'C' and '<null>' // static object F(C x) => x + null; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + null").WithArguments("+", "C", "<null>").WithLocation(3, 29)); } [ConditionalFact(typeof(IsRelease))] public void StaticMethodsWithLambda() { const int n = 100; var builder = new StringBuilder(); builder.AppendLine("using System;"); for (int i = 0; i < n; i++) { builder.AppendLine($"class C{i} {{ }}"); } builder.AppendLine("static class S"); builder.AppendLine("{"); for (int i = 0; i < n; i++) { builder.AppendLine($" internal static void F(C{i} x, Action<C{i}> a) {{ F(x, y => F(y, z => F(z, w => {{ }}))); }}"); } builder.AppendLine("}"); var source = builder.ToString(); var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(IsRelease))] public void ConstructorsWithLambdaAndParams() { const int n = 100; var builder = new StringBuilder(); builder.AppendLine("using System;"); for (int i = 0; i < n; i++) { builder.AppendLine($"class C{i} {{ }}"); } builder.AppendLine("class C"); builder.AppendLine("{"); for (int i = 0; i < n; i++) { builder.AppendLine($" internal static C F(C{i} x, params object[] args) => new C(x, y => F(y, args[1]), args[0]);"); builder.AppendLine($" internal C(C{i} x, Func<C{i}, C> f, params object[] args) {{ }}"); } builder.AppendLine("}"); var source = builder.ToString(); var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(IsRelease))] public void ExtensionMethodsWithLambda() { const int n = 100; var builder = new StringBuilder(); builder.AppendLine("using System;"); for (int i = 0; i < n; i++) { builder.AppendLine($"class C{i} {{ }}"); } builder.AppendLine("static class S"); builder.AppendLine("{"); for (int i = 0; i < n; i++) { builder.AppendLine($" internal static void F(this C{i} x, Action<C{i}> a) {{ x.F(y => y.F(z => z.F(w => {{ }}))); }}"); } builder.AppendLine("}"); var source = builder.ToString(); var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(IsRelease))] public void ExtensionMethodsWithLambdaAndParams() { const int n = 100; var builder = new StringBuilder(); builder.AppendLine("using System;"); for (int i = 0; i < n; i++) { builder.AppendLine($"class C{i} {{ }}"); } builder.AppendLine("static class S"); builder.AppendLine("{"); for (int i = 0; i < n; i++) { builder.AppendLine($" internal static void F(this C{i} x, Action<C{i}> a, params object[] args) {{ x.F(y => y.F(z => z.F(w => {{ }}), args[1]), args[0]); }}"); } builder.AppendLine("}"); var source = builder.ToString(); var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [ConditionalFactAttribute(typeof(IsRelease), typeof(NoIOperationValidation))] public void ExtensionMethodsWithLambdaAndErrors() { const int n = 200; var builder = new StringBuilder(); builder.AppendLine("using System;"); for (int i = 0; i < n; i++) { builder.AppendLine($"class C{i} {{ }}"); } builder.AppendLine("static class S"); builder.AppendLine("{"); for (int i = 0; i < n; i++) { if (i % 2 == 0) { builder.AppendLine($" internal static void F(this C{i} x) {{ x.G(y => y.G(z => z.F())); }}"); // No match for x.G(...). } else { builder.AppendLine($" internal static void G(this C{i} x, Action<C{i}> a) {{ }}"); } } builder.AppendLine("}"); var source = builder.ToString(); var comp = CreateCompilationWithMscorlib40AndSystemCore(source); // error CS1929: 'Ci' does not contain a definition for 'G' and the best extension method overload 'S.G(C1, Action<C1>)' requires a receiver of type 'C1' var diagnostics = Enumerable.Range(0, n / 2). Select(i => Diagnostic(ErrorCode.ERR_BadInstanceArgType, "x").WithArguments($"C{i * 2}", "G", "S.G(C1, System.Action<C1>)", "C1")). ToArray(); comp.VerifyDiagnostics(diagnostics); } [Fact, WorkItem(29360, "https://github.com/dotnet/roslyn/pull/29360")] public void RaceConditionOnImproperlyCapturedAnalyzedArguments() { const int n = 6; var builder = new StringBuilder(); builder.AppendLine("using System;"); for (int i = 0; i < n; i++) { builder.AppendLine($"public class C{i}"); builder.AppendLine("{"); for (int j = 0; j < n; j++) { builder.AppendLine($" public string M{j}()"); builder.AppendLine(" {"); for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) { builder.AppendLine($" Class.Method((C{k} x{k}) => x{k}.M{l});"); } } builder.AppendLine(" return null;"); builder.AppendLine(" }"); } builder.AppendLine("}"); } builder.AppendLine(@" public static class Class { public static void Method<TClass>(Func<TClass, Func<string>> method) { } public static void Method<TClass>(Func<TClass, Func<string, string>> method) { } } "); var source = builder.ToString(); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [WorkItem(35949, "https://github.com/dotnet/roslyn/issues/35949")] [ConditionalFact(typeof(IsRelease))] public void NotNull_Complexity() { var source = @" #nullable enable using System; using System.Diagnostics.CodeAnalysis; class C { C f = null!; void M(C c) { c.f = c; c.NotNull( x => x.f.NotNull( y => y.f.NotNull( z => z.f.NotNull( q => q.f.NotNull( w => w.f.NotNull( e => e.f.NotNull( r => r.f.NotNull( _ => { """".NotNull(s => s); """".NotNull(s => s); """".NotNull(s => s); """".NotNull(s => s); """".NotNull(s => s); """".NotNull(s => s); """".NotNull(s => s); """".NotNull(s => s); """".NotNull(s => s); """".NotNull(s => s); """".NotNull(s => s); """".NotNull(s => s); return """"; })))))))); } } static class Ext { public static V NotNull<T, V>([NotNull] this T t, Func<T, V> f) => throw null!; } "; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [ConditionalFactAttribute(typeof(IsRelease))] [WorkItem(40495, "https://github.com/dotnet/roslyn/issues/40495")] public void NestedLambdas_01() { var source = @"#nullable enable using System.Linq; class Program { static void Main() { Enumerable.Range(0, 1).Sum(a => Enumerable.Range(0, 1).Sum(b => Enumerable.Range(0, 1).Sum(c => Enumerable.Range(0, 1).Sum(d => Enumerable.Range(0, 1).Sum(e => Enumerable.Range(0, 1).Sum(f => Enumerable.Range(0, 1).Count(g => true))))))); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } // Test should complete in several seconds if UnboundLambda.ReallyBind // uses results from _returnInferenceCache. [ConditionalFactAttribute(typeof(IsRelease))] [WorkItem(1083969, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1083969")] public void NestedLambdas_02() { var source = @"using System.Collections.Generic; using System.Linq; class Program { static void F(IEnumerable<int[]> x) { x.GroupBy(y => y[1]).SelectMany(x => x.GroupBy(y => y[2]).SelectMany(x => x.GroupBy(y => y[3]).SelectMany(x => x.GroupBy(y => y[4]).SelectMany(x => x.GroupBy(y => y[5]).SelectMany(x => x.GroupBy(y => y[6]).SelectMany(x => x.GroupBy(y => y[7]).SelectMany(x => x.GroupBy(y => y[8]).SelectMany(x => x.GroupBy(y => y[9]).SelectMany(x => x.GroupBy(y => y[0]).SelectMany(x => x.GroupBy(y => y[1]).SelectMany(x => x.GroupBy(y => y[2]).SelectMany(x => x.GroupBy(y => y[3]).SelectMany(x => x.GroupBy(y => y[4]).SelectMany(x => x.GroupBy(y => y[5]).SelectMany(x => x.GroupBy(y => y[6]).SelectMany(x => x.GroupBy(y => y[7]).SelectMany(x => x.GroupBy(y => y[8]).SelectMany(x => x.GroupBy(y => y[9]).SelectMany(x => x.GroupBy(y => y[0]).Select(x => x.Average(z => z[0]))))))))))))))))))))); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(48886, "https://github.com/dotnet/roslyn/issues/48886")] public void ArrayInitializationAnonymousTypes() { const int nTypes = 250; const int nItemsPerType = 1000; var builder = new StringBuilder(); for (int i = 0; i < nTypes; i++) { builder.AppendLine($"class C{i}"); builder.AppendLine("{"); builder.AppendLine(" static object[] F = new[]"); builder.AppendLine(" {"); for (int j = 0; j < nItemsPerType; j++) { builder.AppendLine($" new {{ Id = {j} }},"); } builder.AppendLine(" };"); builder.AppendLine("}"); } var source = builder.ToString(); var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly() { const int nMethods = 10000; var builder = new StringBuilder(); builder.AppendLine("static class Program"); builder.AppendLine("{"); for (int i = 0; i < nMethods; i++) { builder.AppendLine(i % 2 == 0 ? "#nullable enable" : "#nullable disable"); builder.AppendLine($" static object F{i}(object arg{i}) => arg{i};"); } builder.AppendLine("}"); var source = builder.ToString(); var comp = CreateCompilation(source); comp.NullableAnalysisData = new ConcurrentDictionary<object, NullableWalker.Data>(); comp.VerifyDiagnostics(); int analyzed = comp.NullableAnalysisData.Where(pair => pair.Value.RequiredAnalysis).Count(); Assert.Equal(nMethods / 2, analyzed); } [Fact] [WorkItem(49745, "https://github.com/dotnet/roslyn/issues/49745")] public void NullableStateLambdas() { const int nFunctions = 10000; var builder = new StringBuilder(); builder.AppendLine("#nullable enable"); builder.AppendLine("class Program"); builder.AppendLine("{"); builder.AppendLine(" static void F1(System.Func<object, object> f) { }"); builder.AppendLine(" static void F2(object arg)"); builder.AppendLine(" {"); for (int i = 0; i < nFunctions; i++) { builder.AppendLine($" F1(arg{i} => arg{i});"); } builder.AppendLine(" }"); builder.AppendLine("}"); var source = builder.ToString(); var comp = CreateCompilation(source); comp.NullableAnalysisData = new ConcurrentDictionary<object, NullableWalker.Data>(); comp.VerifyDiagnostics(); CheckIsSimpleMethod(comp, "F2", true); var method = comp.GetMember("Program.F2"); Assert.Equal(1, comp.NullableAnalysisData[method].TrackedEntries); } [Theory] [InlineData("class Program { static object F() => null; }", "F", true)] [InlineData("class Program { static void F() { } }", "F", true)] [InlineData("class Program { static void F() { { } { } { } } }", "F", true)] [InlineData("class Program { static void F() { ;;; } }", "F", false)] [InlineData("class Program { static void F2(System.Action a) { } static void F() { F2(() => { }); } }", "F", true)] [InlineData("class Program { static void F() { void Local() { } } }", "F", false)] [InlineData("class Program { static void F() { System.Action a = () => { }; } }", "F", false)] [InlineData("class Program { static void F() { if (true) { } } }", "F", false)] [InlineData("class Program { static void F() { while (true) { } } }", "F", false)] [InlineData("class Program { static void F() { try { } finally { } } }", "F", false)] [InlineData("class Program { static void F() { label: F(); } }", "F", false)] [WorkItem(49745, "https://github.com/dotnet/roslyn/issues/49745")] public void NullableState_IsSimpleMethod(string source, string methodName, bool expectedResult) { var comp = CreateCompilation(source); var diagnostics = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error); diagnostics.Verify(); CheckIsSimpleMethod(comp, methodName, expectedResult); } private static void CheckIsSimpleMethod(CSharpCompilation comp, string methodName, bool expectedResult) { var tree = comp.SyntaxTrees[0]; var model = (CSharpSemanticModel)comp.GetSemanticModel(tree); var methodDeclaration = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(m => m.Identifier.ToString() == methodName); var methodBody = methodDeclaration.Body; BoundBlock block; if (methodBody is { }) { var binder = model.GetEnclosingBinder(methodBody.SpanStart); block = binder.BindEmbeddedBlock(methodBody, new DiagnosticBag()); } else { var expressionBody = methodDeclaration.ExpressionBody; var binder = model.GetEnclosingBinder(expressionBody.SpanStart); block = binder.BindExpressionBodyAsBlock(expressionBody, new DiagnosticBag()); } var actualResult = NullableWalker.IsSimpleMethodVisitor.IsSimpleMethod(block); Assert.Equal(expectedResult, actualResult); } } }
41.160083
178
0.499697
[ "MIT" ]
JS-SiL/roslyn
src/Compilers/CSharp/Test/Semantic/Semantics/OverloadResolutionPerfTests.cs
19,800
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder v3.0.10.102 // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Web; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web; using Umbraco.ModelsBuilder; using Umbraco.ModelsBuilder.Umbraco; namespace JNCC.PublicWebsite.Core.Models { /// <summary>Science Details Individual Section Slider schema</summary> [PublishedContentModel("scienceDetailsIndividualSectionSliderSchema")] public partial class ScienceDetailsIndividualSectionSliderSchema : ScienceDetailsSectionBaseSchema { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "scienceDetailsIndividualSectionSliderSchema"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public ScienceDetailsIndividualSectionSliderSchema(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<ScienceDetailsIndividualSectionSliderSchema, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public IHtmlString Content { get { return this.GetPropertyValue<IHtmlString>("content"); } } ///<summary> /// Show Grey Background: By setting this to "True" all slider items will have a grey background applied. By default no background will be applied. ///</summary> [ImplementPropertyType("showGreyBackground")] public bool ShowGreyBackground { get { return this.GetPropertyValue<bool>("showGreyBackground"); } } ///<summary> /// Show Timeline Arrows: By setting this to "True" a timeline arrow will be added between the slider items. By default no timeline arrows will be applied. ///</summary> [ImplementPropertyType("showTimelineArrows")] public bool ShowTimelineArrows { get { return this.GetPropertyValue<bool>("showTimelineArrows"); } } ///<summary> /// Slider Items: Section to create the slider items displayed, the order of these items will determine the order the items are displayed in the slider. ///</summary> [ImplementPropertyType("sliderItems")] public IEnumerable<IPublishedContent> SliderItems { get { return this.GetPropertyValue<IEnumerable<IPublishedContent>>("sliderItems"); } } ///<summary> /// Sub Sections: Optional sub sections which will be rendered below the content of this section. ///</summary> [ImplementPropertyType("subSections")] public IEnumerable<IPublishedContent> SubSections { get { return this.GetPropertyValue<IEnumerable<IPublishedContent>>("subSections"); } } } }
35.085106
157
0.728017
[ "MIT" ]
jncc/jncc-website
src/JNCC.PublicWebsite.Core/Models/ScienceDetailsIndividualSectionSliderSchema.generated.cs
3,298
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.RedShift { public partial class SnapshotScheduleAssociation : Pulumi.CustomResource { /// <summary> /// The cluster identifier. /// </summary> [Output("clusterIdentifier")] public Output<string> ClusterIdentifier { get; private set; } = null!; /// <summary> /// The snapshot schedule identifier. /// </summary> [Output("scheduleIdentifier")] public Output<string> ScheduleIdentifier { get; private set; } = null!; /// <summary> /// Create a SnapshotScheduleAssociation resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public SnapshotScheduleAssociation(string name, SnapshotScheduleAssociationArgs args, CustomResourceOptions? options = null) : base("aws:redshift/snapshotScheduleAssociation:SnapshotScheduleAssociation", name, args ?? new SnapshotScheduleAssociationArgs(), MakeResourceOptions(options, "")) { } private SnapshotScheduleAssociation(string name, Input<string> id, SnapshotScheduleAssociationState? state = null, CustomResourceOptions? options = null) : base("aws:redshift/snapshotScheduleAssociation:SnapshotScheduleAssociation", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing SnapshotScheduleAssociation resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static SnapshotScheduleAssociation Get(string name, Input<string> id, SnapshotScheduleAssociationState? state = null, CustomResourceOptions? options = null) { return new SnapshotScheduleAssociation(name, id, state, options); } } public sealed class SnapshotScheduleAssociationArgs : Pulumi.ResourceArgs { /// <summary> /// The cluster identifier. /// </summary> [Input("clusterIdentifier", required: true)] public Input<string> ClusterIdentifier { get; set; } = null!; /// <summary> /// The snapshot schedule identifier. /// </summary> [Input("scheduleIdentifier", required: true)] public Input<string> ScheduleIdentifier { get; set; } = null!; public SnapshotScheduleAssociationArgs() { } } public sealed class SnapshotScheduleAssociationState : Pulumi.ResourceArgs { /// <summary> /// The cluster identifier. /// </summary> [Input("clusterIdentifier")] public Input<string>? ClusterIdentifier { get; set; } /// <summary> /// The snapshot schedule identifier. /// </summary> [Input("scheduleIdentifier")] public Input<string>? ScheduleIdentifier { get; set; } public SnapshotScheduleAssociationState() { } } }
40.805556
177
0.641026
[ "ECL-2.0", "Apache-2.0" ]
johnktims/pulumi-aws
sdk/dotnet/RedShift/SnapshotScheduleAssociation.cs
4,407
C#
/**************************************************************************** * GenBankFeaturesBvtTestCases.cs * * This file contains the GenBank Features Bvt test cases. * ***************************************************************************/ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using Bio.IO; using Bio.IO.GenBank; using Bio.TestAutomation.Util; using Bio.Util.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; #if (SILVERLIGHT == false) namespace Bio.TestAutomation.IO.GenBank #else namespace Bio.Silverlight.TestAutomation.IO.GenBank #endif { /// <summary> /// GenBank Features Bvt test case implementation. /// </summary> [TestClass] public class GenBankFeaturesBvtTestCases { #region Enums /// <summary> /// GenBank location operator used for different testcases. /// </summary> private enum LocationOperatorParameter { Join, Complement, Order, Default }; #endregion Enums #region Global Variables private readonly Utility utilityObj = new Utility(@"TestUtils\GenBankFeaturesTestConfig.xml"); #endregion Global Variables #region Constructor /// <summary> /// Static constructor to open log and make other settings needed for test /// </summary> static GenBankFeaturesBvtTestCases() { Trace.Set(Trace.SeqWarnings); if (!ApplicationLog.Ready) { ApplicationLog.Open("bio.automation.log"); } } #endregion Constructor #region Genbank Features Bvt test cases /// <summary> /// Format a valid DNA sequence to GenBank file /// and validate GenBank features. /// Input : DNA Sequence /// Output : Validate GenBank features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateGenBankFeaturesForDNASequence() { ValidateGenBankFeatures(Constants.SimpleGenBankDnaNodeName, "DNA"); } /// <summary> /// Format a valid Protein sequence to GenBank file /// and validate GenBank features. /// Input : Protein Sequence /// Output : Validate GenBank features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateGenBankFeaturesForPROTEINSequence() { ValidateGenBankFeatures(Constants.SimpleGenBankProNodeName, "Protein"); } /// <summary> /// Format a valid RNA sequence to GenBank file /// and validate GenBank features. /// Input : RNA Sequence /// Output : Validate GenBank features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateGenBankFeaturesForRNASequence() { ValidateGenBankFeatures(Constants.SimpleGenBankRnaNodeName, "RNA"); } /// <summary> /// Format a valid DNA sequence to GenBank file, /// add new features and validate GenBank features. /// Input : DNA Sequence /// Output : Validate addition of new GenBank features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateAdditionOfGenBankFeaturesForDNASequence() { ValidateAdditionGenBankFeatures(Constants.SimpleGenBankDnaNodeName); } /// <summary> /// Format a valid Protein sequence to GenBank file, /// add new features and validate GenBank features. /// Input : Protein Sequence /// Output : Validate addition of new GenBank features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateAdditionOfGenBankFeaturesForPROTEINSequence() { ValidateAdditionGenBankFeatures(Constants.SimpleGenBankProNodeName); } /// <summary> /// Format a valid RNA sequence to GenBank file /// add new features and validate GenBank features. /// Input : RNA Sequence /// Output : Validate addition of new GenBank features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateAdditionOfGenBankFeaturesForRNASequence() { ValidateAdditionGenBankFeatures(Constants.RNAGenBankFeaturesNode); } /// <summary> /// Format a valid DNA sequence to GenBank file /// and validate GenBank DNA sequence standard features. /// Input : Valid DNA sequence. /// Output : Validation /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateDNASeqStandardFeaturesKey() { ValidateStandardFeaturesKey(Constants.DNAStandardFeaturesKeyNode, "DNA"); } /// <summary> /// Format a valid Protein sequence to GenBank file /// and validate GenBank Protein seq standard features. /// Input : Valid Protein sequence. /// Output : Validation /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidatePROTEINSeqStandardFeaturesKey() { ValidateStandardFeaturesKey(Constants.SimpleGenBankProNodeName, "Protein"); } /// <summary> /// Format a valid sequence to /// GenBank file using GenBankFormatter(File-Path) constructor and /// validate GenBank Features. /// Input : MultiSequence GenBank DNA file. /// Validation : Validate GenBank Features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateGenBankFeaturesForMultipleDNASequence() { ValidateGenBankFeatures(Constants.MultiSequenceGenBankDNANode, "DNA"); } /// <summary> /// Format a valid sequence to /// GenBank file using GenBankFormatter(File-Path) constructor and /// validate GenBank Features. /// Input : MultiSequence GenBank Protein file. /// Validation : Validate GenBank Features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateGenBankFeaturesForMultiplePROTEINSequence() { ValidateGenBankFeatures(Constants.MultiSeqGenBankProteinNode, "Protein"); } /// <summary> /// Parse a Valid DNA Sequence and Validate Features /// within specified range. /// Input : Valid DNA Sequence and specified range. /// Ouput : Validation of features count within specified range. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateFeaturesWithinRangeForDNASequence() { ValidateGetFeatures(Constants.DNAStandardFeaturesKeyNode, null); } /// <summary> /// Parse a Valid RNA Sequence and Validate Features /// within specified range. /// Input : Valid RNA Sequence and specified range. /// Ouput : Validation of features count within specified range. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateFeaturesWithinRangeForRNASequence() { ValidateGetFeatures(Constants.RNAGenBankFeaturesNode, null); } /// <summary> /// Parse a Valid Protein Seq and Validate features /// within specified range. /// Input : Valid Protein Sequence and specified range. /// Ouput : Validation of features count within specified range. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateFeaturesWithinRangeForPROTEINSequence() { ValidateGetFeatures(Constants.SimpleGenBankProNodeName, null); } /// <summary> /// Parse a Valid DNA Sequence and Validate CDS Qualifiers. /// Input : Valid DNA Sequence. /// Ouput : Validation of all CDS Qualifiers.. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateDNASequenceCDSQualifiers() { ValidateCDSQualifiers(Constants.DNAStandardFeaturesKeyNode, "DNA"); } /// <summary> /// Parse a Valid Protein Sequence and Validate CDS Qualifiers. /// Input : Valid Protein Sequence. /// Ouput : Validation of all CDS Qualifiers.. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidatePROTEINSequenceCDSQualifiers() { ValidateCDSQualifiers(Constants.SimpleGenBankProNodeName, "Protein"); } /// <summary> /// Parse a Valid RNA Sequence and Validate CDS Qualifiers. /// Input : Valid RNA Sequence. /// Ouput : Validation of all CDS Qualifiers.. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRNASequenceCDSQualifiers() { ValidateCDSQualifiers(Constants.RNAGenBankFeaturesNode, "RNA"); } /// <summary> /// Parse a Valid DNA Sequence and Validate CDS Qualifiers. /// Input : Valid DNA Sequence and accession number. /// Ouput : Validation of all CDS Qualifiers.. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateFeaturesUsingAccessionForDNASequence() { ValidateGetFeatures(Constants.DNAStandardFeaturesKeyNode, "Accession"); } /// <summary> /// Parse a Valid RNA Sequence and Validate CDS Qualifiers. /// Input : Valid RNA Sequence and accession number. /// Ouput : Validation of all CDS Qualifiers.. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateFeaturesUsingAccessionForRNASequence() { ValidateGetFeatures(Constants.RNAGenBankFeaturesNode, "Accession"); } /// <summary> /// Parse a Valid Protein Sequence and Validate CDS Qualifiers. /// Input : Valid Protein Sequence and accession number. /// Ouput : Validation of all CDS Qualifiers.. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateFeaturesUsingAccessionForPROTEINSequence() { ValidateGetFeatures(Constants.SimpleGenBankProNodeName, "Accession"); } /// <summary> /// Parse a Valid DNA Sequence and validate citation referenced /// present in GenBank metadata. /// Input : Valid DNA Sequence and specified range. /// Ouput : Validation of citation referneced. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateCitationReferencedForDNASequence() { ValidateCitationReferenced(Constants.DNAStandardFeaturesKeyNode); } /// <summary> /// Parse a Valid RNA Sequence and validate citation referenced /// present in GenBank metadata. /// Input : Valid RNA Sequence and specified range. /// Ouput : Validation of citation referneced. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateCitationReferencedForRNASequence() { ValidateCitationReferenced(Constants.RNAGenBankFeaturesNode); } /// <summary> /// Parse a Valid Protein Sequence and validate citation referenced /// present in GenBank metadata. /// Input : Valid Protein Sequence and specified range. /// Ouput : Validation of citation referneced. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateCitationReferencedForPROTEINSequence() { ValidateCitationReferenced(Constants.SimpleGenBankProNodeName); } /// <summary> /// Parse a Valid DNA Sequence and validate citation referenced /// present in GenBank metadata by passing featureItem. /// Input : Valid DNA Sequence and specified range. /// Ouput : Validation of citation referneced. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateCitationReferencedForDNASequenceUsingFeatureItem() { ValidateCitationReferencedUsingFeatureItem( Constants.DNAStandardFeaturesKeyNode); } /// <summary> /// Parse a Valid RNA Sequence and validate citation referenced /// present in GenBank metadata by passing featureItem. /// Input : Valid RNA Sequence and specified range. /// Ouput : Validation of citation referneced. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateCitationReferencedForRNASequenceUsingFeatureItem() { ValidateCitationReferencedUsingFeatureItem(Constants.RNAGenBankFeaturesNode); } /// <summary> /// Parse a Valid Protein Sequence and validate citation referenced /// present in GenBank metadata by passing featureItem. /// Input : Valid Protein Sequence and specified range. /// Ouput : Validation of citation referneced. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateCitationReferencedForPROTEINSequenceUsingFeatureItem() { ValidateCitationReferencedUsingFeatureItem(Constants.SimpleGenBankProNodeName); } /// <summary> /// Vaslidate Genbank Properties. /// Input : Genbank sequence. /// Output : validation of GenBank features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateGenBankFeatureProperties() { // Get Values from XML node. string filePath = utilityObj.xmlUtil.GetTextValue( Constants.DNAStandardFeaturesKeyNode, Constants.FilePathNode); string mRNAFeatureCount = utilityObj.xmlUtil.GetTextValue( Constants.DNAStandardFeaturesKeyNode, Constants.mRNACount); string exonFeatureCount = utilityObj.xmlUtil.GetTextValue( Constants.DNAStandardFeaturesKeyNode, Constants.ExonCount); string intronFeatureCount = utilityObj.xmlUtil.GetTextValue( Constants.DNAStandardFeaturesKeyNode, Constants.IntronCount); string cdsFeatureCount = utilityObj.xmlUtil.GetTextValue( Constants.DNAStandardFeaturesKeyNode, Constants.CDSCount); string allFeaturesCount = utilityObj.xmlUtil.GetTextValue( Constants.DNAStandardFeaturesKeyNode, Constants.GenBankFeaturesCount); string GenesCount = utilityObj.xmlUtil.GetTextValue( Constants.DNAStandardFeaturesKeyNode, Constants.GeneCount); string miscFeaturesCount = utilityObj.xmlUtil.GetTextValue( Constants.DNAStandardFeaturesKeyNode, Constants.MiscFeatureCount); string rRNACount = utilityObj.xmlUtil.GetTextValue( Constants.DNAStandardFeaturesKeyNode, Constants.rRNACount); string tRNACount = utilityObj.xmlUtil.GetTextValue( Constants.DNAStandardFeaturesKeyNode, Constants.tRNACount); string zeroValue = utilityObj.xmlUtil.GetTextValue( Constants.DNAStandardFeaturesKeyNode, Constants.emptyCount); ISequenceParser parserObj = new GenBankParser(filePath); IEnumerable<ISequence> seq = parserObj.Parse(); // Get all metada features. Hitting all the properties in the metadata feature. var metadata = (GenBankMetadata) seq.ElementAt(0).Metadata[Constants.GenBank]; List<FeatureItem> allFeatures = metadata.Features.All; List<Minus10Signal> minus10Signal = metadata.Features.Minus10Signals; List<Minus35Signal> minus35Signal = metadata.Features.Minus35Signals; List<ThreePrimeUtr> threePrimeUTR = metadata.Features.ThreePrimeUTRs; List<FivePrimeUtr> fivePrimeUTR = metadata.Features.FivePrimeUTRs; List<Attenuator> attenuator = metadata.Features.Attenuators; List<CaatSignal> caatSignal = metadata.Features.CAATSignals; List<CodingSequence> CDS = metadata.Features.CodingSequences; List<DisplacementLoop> displacementLoop = metadata.Features.DisplacementLoops; List<Enhancer> enhancer = metadata.Features.Enhancers; List<Exon> exonList = metadata.Features.Exons; List<GcSingal> gcsSignal = metadata.Features.GCSignals; List<Gene> genesList = metadata.Features.Genes; List<InterveningDna> interveningDNA = metadata.Features.InterveningDNAs; List<Intron> intronList = metadata.Features.Introns; List<LongTerminalRepeat> LTR = metadata.Features.LongTerminalRepeats; List<MaturePeptide> matPeptide = metadata.Features.MaturePeptides; List<MiscBinding> miscBinding = metadata.Features.MiscBindings; List<MiscDifference> miscDifference = metadata.Features.MiscDifferences; List<MiscFeature> miscFeatures = metadata.Features.MiscFeatures; List<MiscRecombination> miscRecobination = metadata.Features.MiscRecombinations; List<MiscRna> miscRNA = metadata.Features.MiscRNAs; List<MiscSignal> miscSignal = metadata.Features.MiscSignals; List<MiscStructure> miscStructure = metadata.Features.MiscStructures; List<ModifiedBase> modifierBase = metadata.Features.ModifiedBases; List<MessengerRna> mRNA = metadata.Features.MessengerRNAs; List<NonCodingRna> nonCodingRNA = metadata.Features.NonCodingRNAs; List<OperonRegion> operonRegion = metadata.Features.OperonRegions; List<PolyASignal> polySignal = metadata.Features.PolyASignals; List<PolyASite> polySites = metadata.Features.PolyASites; List<PrecursorRna> precursorRNA = metadata.Features.PrecursorRNAs; List<ProteinBindingSite> proteinBindingSites = metadata.Features.ProteinBindingSites; List<RibosomeBindingSite> rBindingSites = metadata.Features.RibosomeBindingSites; List<ReplicationOrigin> repliconOrigin = metadata.Features.ReplicationOrigins; List<RepeatRegion> repeatRegion = metadata.Features.RepeatRegions; List<RibosomalRna> rRNA = metadata.Features.RibosomalRNAs; List<SignalPeptide> signalPeptide = metadata.Features.SignalPeptides; List<StemLoop> stemLoop = metadata.Features.StemLoops; List<TataSignal> tataSignals = metadata.Features.TATASignals; List<Terminator> terminator = metadata.Features.Terminators; List<TransferMessengerRna> tmRNA = metadata.Features.TransferMessengerRNAs; List<TransitPeptide> transitPeptide = metadata.Features.TransitPeptides; List<TransferRna> tRNA = metadata.Features.TransferRNAs; List<UnsureSequenceRegion> unSecureRegion = metadata.Features.UnsureSequenceRegions; List<Variation> variations = metadata.Features.Variations; // Validate GenBank Features. Assert.AreEqual(minus10Signal.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(minus35Signal.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(threePrimeUTR.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(fivePrimeUTR.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(caatSignal.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(attenuator.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(displacementLoop.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(enhancer.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(gcsSignal.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(genesList.Count.ToString((IFormatProvider) null), GenesCount); Assert.AreEqual(interveningDNA.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(LTR.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(matPeptide.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(miscBinding.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(miscDifference.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(miscFeatures.Count.ToString((IFormatProvider) null), miscFeaturesCount); Assert.AreEqual(miscRecobination.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(miscSignal.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(modifierBase.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(miscRNA.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(miscStructure.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(mRNA.Count.ToString((IFormatProvider) null), mRNAFeatureCount); Assert.AreEqual(nonCodingRNA.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(operonRegion.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(polySignal.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(polySites.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(precursorRNA.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(proteinBindingSites.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(rBindingSites.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(repliconOrigin.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(rRNA.Count.ToString((IFormatProvider) null), rRNACount); Assert.AreEqual(signalPeptide.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(stemLoop.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(tataSignals.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(repeatRegion.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(terminator.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(tmRNA.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(variations.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(tRNA.Count.ToString((IFormatProvider) null), tRNACount); Assert.AreEqual(transitPeptide.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(unSecureRegion.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(stemLoop.Count, Convert.ToInt32(zeroValue, null)); Assert.AreEqual(allFeatures.Count, Convert.ToInt32(allFeaturesCount, null)); Assert.AreEqual(CDS.Count, Convert.ToInt32(cdsFeatureCount, null)); Assert.AreEqual(exonList.Count, Convert.ToInt32(exonFeatureCount, null)); Assert.AreEqual(intronList.Count, Convert.ToInt32(intronFeatureCount, null)); } /// <summary> /// Validate location builder with normal string. /// Input Data : Location string "345678910"; /// Output Data : Validation of Location start,end position,seperator /// and operators. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateNormalStringLocationBuilder() { ValidateLocationBuilder(Constants.NormalLocationBuilderNode, LocationOperatorParameter.Default, false); } /// <summary> /// Validate location builder with Single dot seperator string. /// Input Data : Location string "1098945.2098765"; /// Output Data : Validation of Location start,end position,seperator /// and operators. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateSingleDotSeperatorLocationBuilder() { ValidateLocationBuilder(Constants.SingleDotLocationBuilderNode, LocationOperatorParameter.Default, false); } /// <summary> /// Validate location builder with Join Opperator. /// Input Data : Location string "join(26300..26395)"; /// Output Data : Validation of Location start,end position,seperator /// and operators. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateJoinOperatorLocationBuilder() { ValidateLocationBuilder(Constants.JoinOperatorLocationBuilderNode, LocationOperatorParameter.Join, true); } /// <summary> /// Validate location builder with Join Opperator. /// Input Data : Location string "complement(45745..50256)"; /// Output Data : Validation of Location start,end position,seperator /// and operators. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateComplementOperatorLocationBuilder() { ValidateLocationBuilder(Constants.ComplementOperatorLocationBuilderNode, LocationOperatorParameter.Complement, true); } /// <summary> /// Validate location builder with Order Opperator. /// Input Data : Location string "order(9214567.50980256)"; /// Output Data : Validation of Location start,end position,seperator /// and operators. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateOrderOperatorLocationBuilder() { ValidateLocationBuilder(Constants.OrderOperatorLocationBuilderNode, LocationOperatorParameter.Order, true); } /// <summary> /// Validate CDS feature location builder by passing GenBank file. /// Input Data : Location string "join(136..202,AF032048.1:67..345, /// AF032048.1:1162..1175)"; /// Output Data : Validation of Location start,end position,seperator /// and operators. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateSubSequenceGenBankFile() { ValidateLocationBuilder(Constants.GenBankFileLocationBuilderNode, LocationOperatorParameter.Join, true); } /// <summary> /// Validate SubSequence start, end and range of sequence. /// Input Data : GenBank file; /// Output Data : Validation of Location start,end position,seperator /// and operators. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateSequenceFeatureForRna() { ValidateSequenceFeature(Constants.GenBankFileSubSequenceNode); } /// <summary> /// Validate SubSequence start, end and range of sequence. /// Input Data : Dna GenBank file; /// Output Data : Validation of Location start,end position,seperator /// and operators. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateSequenceFeatureForDna() { ValidateSequenceFeature(Constants.GenBankFileSubSequenceDnaNode); } /// <summary> /// Validate SubSequence start, end and range of sequence. /// Input Data :Protein GenBank file; /// Output Data : Validation of Location start,end position,seperator /// and operators. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateSequenceFeatureForProteinA() { ValidateSequenceFeature(Constants.GenBankFileSubSequenceProteinNode); } /// <summary> /// Validate SubSequence start, end and range of sequence. /// Input Data : GenBank file; /// Output Data : Validation of Location start,end position,seperator /// and operators. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateSequenceFeatureUsingReferencedSequence() { // Get Values from XML node. string filePath = utilityObj.xmlUtil.GetTextValue( Constants.GenBankFileSubSequenceNode, Constants.FilePathNode); string subSequence = utilityObj.xmlUtil.GetTextValue( Constants.GenBankFileSubSequenceNode, Constants.ExpectedSubSequence); string subSequenceStart = utilityObj.xmlUtil.GetTextValue( Constants.GenBankFileSubSequenceNode, Constants.SequenceStart); string subSequenceEnd = utilityObj.xmlUtil.GetTextValue( Constants.GenBankFileSubSequenceNode, Constants.SequenceEnd); string referenceSeq = utilityObj.xmlUtil.GetTextValue( Constants.GenBankFileSubSequenceNode, Constants.referenceSeq); ISequence sequence; ISequence firstFeatureSeq = null; // Parse a genBank file. var refSequence = new Sequence(Alphabets.RNA, referenceSeq); var parserObj = new GenBankParser(filePath); sequence = parserObj.Parse().FirstOrDefault(); var metadata = sequence.Metadata[Constants.GenBank] as GenBankMetadata; // Get Subsequence feature,start and end postions. var referenceSequences = new Dictionary<string, ISequence>(); referenceSequences.Add(Constants.Reference, refSequence); firstFeatureSeq = metadata.Features.All[0].GetSubSequence(sequence, referenceSequences); var sequenceString = new string(firstFeatureSeq.Select(a => (char) a).ToArray()); // Validate SubSequence. Assert.AreEqual(sequenceString, subSequence); Assert.AreEqual(metadata.Features.All[0].Location.LocationStart.ToString((IFormatProvider) null), subSequenceStart); Assert.AreEqual(metadata.Features.All[0].Location.LocationEnd.ToString((IFormatProvider) null), subSequenceEnd); Assert.IsNull(metadata.Features.All[0].Location.Accession); Assert.AreEqual(metadata.Features.All[0].Location.StartData, subSequenceStart); Assert.AreEqual(metadata.Features.All[0].Location.EndData, subSequenceEnd); // Log to VSTest GUI ApplicationLog.WriteLine(string.Format(null, "GenBank Features BVT: Successfully validated the Subsequence feature '{0}'", sequenceString)); ApplicationLog.WriteLine(string.Format(null, "GenBank Features BVT: Successfully validated the start of subsequence'{0}'", metadata.Features.All[0].Location.LocationStart.ToString( (IFormatProvider) null))); } /// <summary> /// Validate Sequence features for Exon,CDS,Intron.. /// Input Data : Sequence feature item and location. /// Output Data : Validation of created sequence features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateGenBankSubFeatures() { ValidateGenBankSubFeatures(Constants.GenBankSequenceFeaturesNode); } /// <summary> /// Validate Sequence features for features with Join operator. /// Input Data : Sequence feature item and location. /// Output Data : Validation of created sequence features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateGenBankSubFeatureswithOperator() { ValidateGenBankSubFeatures(Constants.GenBankSequenceFeaturesForMRNA); } /// <summary> /// Validate Sequence features for features with Empty sub-operator. /// Input Data : Sequence feature item and location. /// Output Data : Validation of created sequence features. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateGenBankSubFeatureswithEmptyOperator() { ValidateAdditionGenBankFeatures( Constants.OperatorGenBankFileNode); } #endregion Genbank Features Bvt test cases #region Supporting Methods /// <summary> /// Validate GenBank features. /// </summary> /// <param name="nodeName">xml node name.</param> /// <param name="methodName">Name of the method</param> private void ValidateGenBankFeatures(string nodeName, string methodName) { // Get Values from XML node. string filePath = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FilePathNode); string alphabetName = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.AlphabetNameNode); string expectedSequence = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.ExpectedSequenceNode); string mRNAFeatureCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.mRNACount); string exonFeatureCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.ExonCount); string intronFeatureCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.IntronCount); string cdsFeatureCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.CDSCount); string allFeaturesCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.GenBankFeaturesCount); string expectedCDSKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.CDSKey); string expectedIntronKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.IntronKey); string expectedExonKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.ExonKey); string mRNAKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.mRNAKey); string sourceKeyName = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SourceKey); string proteinKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.ProteinKeyName); string tempFileName = Path.GetTempFileName(); ISequenceParser parserObj = new GenBankParser(filePath); IEnumerable<ISequence> sequenceList = parserObj.Parse(); if (sequenceList.Count() == 1) { string expectedUpdatedSequence = expectedSequence.Replace("\r", "").Replace("\n", "").Replace(" ", ""); var orgSeq = new Sequence(Utility.GetAlphabet(alphabetName), expectedUpdatedSequence); orgSeq.ID = sequenceList.ElementAt(0).ID; orgSeq.Metadata.Add(Constants.GenBank, sequenceList.ElementAt(0).Metadata[Constants.GenBank]); using (ISequenceFormatter formatterObj = new GenBankFormatter(tempFileName)) { formatterObj.Write(orgSeq); formatterObj.Close(); } } else { string expectedUpdatedSequence = expectedSequence.Replace("\r", "").Replace("\n", "").Replace(" ", ""); var orgSeq = new Sequence(Utility.GetAlphabet(alphabetName), expectedUpdatedSequence); orgSeq.ID = sequenceList.ElementAt(1).ID; orgSeq.Metadata.Add(Constants.GenBank, sequenceList.ElementAt(1).Metadata[Constants.GenBank]); using (ISequenceFormatter formatterObj = new GenBankFormatter(tempFileName)) { formatterObj.Write(orgSeq); formatterObj.Close(); } } // parse a temporary file. using (var tempParserObj = new GenBankParser(tempFileName)) { IEnumerable<ISequence> tempFileSeqList = tempParserObj.Parse(); ISequence sequence = tempFileSeqList.ElementAt(0); var metadata = (GenBankMetadata) sequence.Metadata[Constants.GenBank]; // Validate formatted temporary file GenBank Features. Assert.AreEqual(metadata.Features.All.Count, Convert.ToInt32(allFeaturesCount, null)); Assert.AreEqual(metadata.Features.CodingSequences.Count, Convert.ToInt32(cdsFeatureCount, null)); Assert.AreEqual(metadata.Features.Exons.Count, Convert.ToInt32(exonFeatureCount, null)); Assert.AreEqual(metadata.Features.Introns.Count, Convert.ToInt32(intronFeatureCount, null)); Assert.AreEqual(metadata.Features.MessengerRNAs.Count, Convert.ToInt32(mRNAFeatureCount, null)); Assert.AreEqual(metadata.Features.Attenuators.Count, 0); Assert.AreEqual(metadata.Features.CAATSignals.Count, 0); Assert.AreEqual(metadata.Features.DisplacementLoops.Count, 0); Assert.AreEqual(metadata.Features.Enhancers.Count, 0); Assert.AreEqual(metadata.Features.Genes.Count, 0); if ((0 == string.Compare(methodName, "DNA", CultureInfo.CurrentCulture, CompareOptions.IgnoreCase)) || (0 == string.Compare(methodName, "RNA", CultureInfo.CurrentCulture, CompareOptions.IgnoreCase))) { IList<FeatureItem> featureList = metadata.Features.All; Assert.AreEqual(featureList[0].Key.ToString(null), sourceKeyName); Assert.AreEqual(featureList[1].Key.ToString(null), mRNAKey); Assert.AreEqual(featureList[3].Key.ToString(null), expectedCDSKey); Assert.AreEqual(featureList[5].Key.ToString(null), expectedExonKey); Assert.AreEqual(featureList[6].Key.ToString(null), expectedIntronKey); ApplicationLog.WriteLine( "GenBank Features BVT: Successfully validated the GenBank Features"); ApplicationLog.WriteLine(string.Format(null, "GenBank Features BVT: Successfully validated the CDS feature '{0}'", featureList[3].Key.ToString(null))); ApplicationLog.WriteLine(string.Format(null, "GenBank Features BVT: Successfully validated the Exon feature '{0}'", featureList[5].Key.ToString(null))); } else { IList<FeatureItem> proFeatureList = metadata.Features.All; Assert.AreEqual(proFeatureList[0].Key.ToString(null), sourceKeyName); Assert.AreEqual(proFeatureList[1].Key.ToString(null), proteinKey); Assert.AreEqual(proFeatureList[2].Key.ToString(null), expectedCDSKey); ApplicationLog.WriteLine( "GenBank Features BVT: Successfully validated the GenBank Features"); ApplicationLog.WriteLine(string.Format(null, "GenBank Features BVT: Successfully validated the CDS feature '{0}'", proFeatureList[2].Key.ToString(null))); ApplicationLog.WriteLine(string.Format(null, "GenBank Features BVT: Successfully validated the Source feature '{0}'", proFeatureList[0].Key.ToString(null))); } tempParserObj.Close(); } File.Delete(tempFileName); } /// <summary> /// Validate addition of GenBank features. /// </summary> /// <param name="nodeName">xml node name.</param> private void ValidateAdditionGenBankFeatures(string nodeName) { // Get Values from XML node. string filePath = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FilePathNode); string alphabetName = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.AlphabetNameNode); string expectedSequence = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.ExpectedSequenceNode); string addFirstKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FirstKey); string addSecondKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SecondKey); string addFirstLocation = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FirstLocation); string addSecondLocation = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SecondLocation); string addFirstQualifier = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FirstQualifier); string addSecondQualifier = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SecondQualifier); using (ISequenceParser parser1 = new GenBankParser(filePath)) { IEnumerable<ISequence> seqList1 = parser1.Parse(); var localBuilderObj = new LocationBuilder(); string tempFileName = Path.GetTempFileName(); string expectedUpdatedSequence = expectedSequence.Replace("\r", "").Replace("\n", "").Replace(" ", ""); var orgSeq = new Sequence(Utility.GetAlphabet(alphabetName), expectedUpdatedSequence); orgSeq.ID = seqList1.ElementAt(0).ID; orgSeq.Metadata.Add(Constants.GenBank, seqList1.ElementAt(0).Metadata[Constants.GenBank]); using (ISequenceFormatter formatterObj = new GenBankFormatter(tempFileName)) { formatterObj.Write(orgSeq); formatterObj.Close(); // parse GenBank file. using (var parserObj = new GenBankParser(tempFileName)) { IEnumerable<ISequence> seqList = parserObj.Parse(); ISequence seq = seqList.ElementAt(0); var metadata = (GenBankMetadata) seq.Metadata[Constants.GenBank]; // Add a new features to Genbank features list. metadata.Features = new SequenceFeatures(); var feature = new FeatureItem(addFirstKey, addFirstLocation); var qualifierValues = new List<string>(); qualifierValues.Add(addFirstQualifier); qualifierValues.Add(addFirstQualifier); feature.Qualifiers.Add(addFirstQualifier, qualifierValues); metadata.Features.All.Add(feature); feature = new FeatureItem(addSecondKey, addSecondLocation); qualifierValues = new List<string>(); qualifierValues.Add(addSecondQualifier); qualifierValues.Add(addSecondQualifier); feature.Qualifiers.Add(addSecondQualifier, qualifierValues); metadata.Features.All.Add(feature); // Validate added GenBank features. Assert.AreEqual(metadata.Features.All[0].Key.ToString(null), addFirstKey); Assert.AreEqual( localBuilderObj.GetLocationString(metadata.Features.All[0].Location), addFirstLocation); Assert.AreEqual(metadata.Features.All[1].Key.ToString(null), addSecondKey); Assert.AreEqual(localBuilderObj.GetLocationString(metadata.Features.All[1].Location), addSecondLocation); parserObj.Close(); } File.Delete(tempFileName); } } } /// <summary> /// Validate GenBank standard features key. /// </summary> /// <param name="nodeName">xml node name.</param> /// <param name="methodName">Name of the method</param> private void ValidateStandardFeaturesKey(string nodeName, string methodName) { // Get Values from XML node. string filePath = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FilePathNode); string expectedCondingSeqCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.CDSCount); string exonFeatureCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.ExonCount); string expectedtRNA = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.tRNACount); string expectedGeneCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.GeneCount); string miscFeatureCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.MiscFeatureCount); string expectedCDSKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.CDSKey); string expectedIntronKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.IntronKey); string mRNAKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.mRNAKey); string allFeaturesCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.StandardFeaturesCount); // Parse a file. ISequenceParser parserObj = new GenBankParser(filePath); IEnumerable<ISequence> seq = parserObj.Parse(); var metadata = seq.ElementAt(0).Metadata[Constants.GenBank] as GenBankMetadata; if ((0 == string.Compare(methodName, "DNA", CultureInfo.CurrentCulture, CompareOptions.IgnoreCase)) || (0 == string.Compare(methodName, "RNA", CultureInfo.CurrentCulture, CompareOptions.IgnoreCase))) { // Validate standard features keys. Assert.AreEqual(metadata.Features.CodingSequences.Count.ToString((IFormatProvider) null), expectedCondingSeqCount); Assert.AreEqual(metadata.Features.Exons.Count.ToString((IFormatProvider) null), exonFeatureCount); Assert.AreEqual(metadata.Features.TransferRNAs.Count.ToString((IFormatProvider) null), expectedtRNA); Assert.AreEqual(metadata.Features.Genes.Count.ToString((IFormatProvider) null), expectedGeneCount); Assert.AreEqual(metadata.Features.MiscFeatures.Count.ToString((IFormatProvider) null), miscFeatureCount); Assert.AreEqual(StandardFeatureKeys.CodingSequence.ToString(null), expectedCDSKey); Assert.AreEqual(StandardFeatureKeys.Intron.ToString(null), expectedIntronKey); Assert.AreEqual(StandardFeatureKeys.MessengerRna.ToString(null), mRNAKey); Assert.AreEqual(StandardFeatureKeys.All.Count.ToString((IFormatProvider) null), allFeaturesCount); } else { Assert.AreEqual(metadata.Features.CodingSequences.Count.ToString((IFormatProvider) null), expectedCondingSeqCount); Assert.AreEqual(StandardFeatureKeys.CodingSequence.ToString(null), expectedCDSKey); } } /// <summary> /// Validate GenBank Get features with specified range. /// </summary> /// <param name="nodeName">xml node name.</param> /// <param name="methodName">name of method</param> private void ValidateGetFeatures(string nodeName, string methodName) { // Get Values from XML node. string filePath = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FilePathNode); string expectedFirstRangeStartPoint = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FirstRangeStartPoint); string expectedSecondRangeStartPoint = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SecondRangeStartPoint); string expectedFirstRangeEndPoint = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FirstRangeEndPoint); string expectedSecondRangeEndPoint = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SecondRangeEndPoint); string expectedCountWithinSecondRange = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FeaturesWithinSecondRange); string expectedCountWithinFirstRange = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FeaturesWithinFirstRange); // Parse a GenBank file. using (ISequenceParser parserObj = new GenBankParser(filePath)) { IEnumerable<ISequence> seq = parserObj.Parse(); var metadata = seq.ElementAt(0).Metadata[Constants.GenBank] as GenBankMetadata; List<CodingSequence> cdsList = metadata.Features.CodingSequences; string accessionNumber = cdsList[0].Location.Accession; if ((0 == string.Compare(methodName, "Accession", CultureInfo.CurrentCulture, CompareOptions.IgnoreCase))) { // Validate GetFeature within specified range. Assert.AreEqual(metadata.GetFeatures(accessionNumber, Convert.ToInt32(expectedFirstRangeStartPoint, null), Convert.ToInt32(expectedFirstRangeEndPoint, null)) .Count.ToString((IFormatProvider) null), expectedCountWithinFirstRange); Assert.AreEqual(metadata.GetFeatures(accessionNumber, Convert.ToInt32(expectedSecondRangeStartPoint, null), Convert.ToInt32(expectedSecondRangeEndPoint, null)) .Count.ToString((IFormatProvider) null), expectedCountWithinSecondRange); } else { // Validate GetFeature within specified range. Assert.AreEqual(metadata.GetFeatures( Convert.ToInt32(expectedFirstRangeStartPoint, null), Convert.ToInt32(expectedFirstRangeEndPoint, null)).Count.ToString((IFormatProvider) null), expectedCountWithinFirstRange); Assert.AreEqual(metadata.GetFeatures( Convert.ToInt32(expectedSecondRangeStartPoint, null), Convert.ToInt32(expectedSecondRangeEndPoint, null)).Count.ToString((IFormatProvider) null), expectedCountWithinSecondRange); } } } /// <summary> /// Validate GenBank Citation referenced present in GenBank Metadata. /// </summary> /// <param name="nodeName">xml node name.</param> private void ValidateCitationReferenced(string nodeName) { // Get Values from XML node. string filePath = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FilePathNode); string expectedCitationReferenced = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.citationReferencedCount); // Parse a GenBank file. using (ISequenceParser parserObj = new GenBankParser(filePath)) { IEnumerable<ISequence> seq = parserObj.Parse(); var metadata = seq.ElementAt(0).Metadata[Constants.GenBank] as GenBankMetadata; // Get a list citationReferenced present in GenBank file. List<CitationReference> citationReferenceList = metadata.GetCitationsReferredInFeatures(); // Validate citation referenced present in GenBank features. Assert.AreEqual(citationReferenceList.Count.ToString((IFormatProvider) null), expectedCitationReferenced); } } /// <summary> /// Validate GenBank Citation referenced by passing featureItem present in GenBank Metadata. /// </summary> /// <param name="nodeName">xml node name.</param> private void ValidateCitationReferencedUsingFeatureItem(string nodeName) { // Get Values from XML node. string filePath = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FilePathNode); string expectedCitationReferenced = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.citationReferencedCount); // Parse a GenBank file. using (ISequenceParser parserObj = new GenBankParser(filePath)) { IEnumerable<ISequence> seq = parserObj.Parse(); var metadata = seq.ElementAt(0).Metadata[Constants.GenBank] as GenBankMetadata; IList<FeatureItem> featureList = metadata.Features.All; // Get a list citationReferenced present in GenBank file. List<CitationReference> citationReferenceList = metadata.GetCitationsReferredInFeature(featureList[0]); Assert.AreEqual(citationReferenceList.Count.ToString((IFormatProvider) null), expectedCitationReferenced); } } /// <summary> /// Validate All qualifiers in CDS feature. /// </summary> /// <param name="nodeName">xml node name.</param> private void ValidateCDSQualifiers(string nodeName, string methodName) { // Get Values from XML node. string filePath = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FilePathNode); string expectedCDSProduct = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.CDSProductQualifier); string expectedCDSException = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.CDSException); string expectedCDSCodonStart = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.CDSCodonStart); string expectedCDSLabel = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.CDSLabel); string expectedCDSDBReference = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.CDSDBReference); string expectedGeneSymbol = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.GeneSymbol); // Parse a GenBank file. using (ISequenceParser parserObj = new GenBankParser(filePath)) { IEnumerable<ISequence> seq = parserObj.Parse(); var metadata = seq.ElementAt(0).Metadata[Constants.GenBank] as GenBankMetadata; // Get CDS qaulifier.value. List<CodingSequence> cdsQualifiers = metadata.Features.CodingSequences; List<string> codonStartValue = cdsQualifiers[0].CodonStart; List<string> productValue = cdsQualifiers[0].Product; List<string> DBReferenceValue = cdsQualifiers[0].DatabaseCrossReference; // validate CDS qualifiers. if ((0 == string.Compare(methodName, "DNA", CultureInfo.CurrentCulture, CompareOptions.IgnoreCase)) || (0 == string.Compare(methodName, "RNA", CultureInfo.CurrentCulture, CompareOptions.IgnoreCase))) { Assert.AreEqual(cdsQualifiers[0].Label, expectedCDSLabel); Assert.AreEqual(cdsQualifiers[0].Exception.ToString(null), expectedCDSException); Assert.AreEqual(productValue[0], expectedCDSProduct); Assert.AreEqual(codonStartValue[0], expectedCDSCodonStart); Assert.IsTrue(string.IsNullOrEmpty(cdsQualifiers[0].Allele)); Assert.IsFalse(string.IsNullOrEmpty(cdsQualifiers[0].Citation.ToString())); Assert.AreEqual(DBReferenceValue[0], expectedCDSDBReference); Assert.AreEqual(cdsQualifiers[0].GeneSymbol, expectedGeneSymbol); } else { Assert.AreEqual(cdsQualifiers[0].Label, expectedCDSLabel); Assert.AreEqual(cdsQualifiers[0].Exception.ToString(null), expectedCDSException); Assert.IsTrue(string.IsNullOrEmpty(cdsQualifiers[0].Allele)); Assert.IsFalse(string.IsNullOrEmpty(cdsQualifiers[0].Citation.ToString())); Assert.AreEqual(DBReferenceValue[0], expectedCDSDBReference); Assert.AreEqual(cdsQualifiers[0].GeneSymbol, expectedGeneSymbol); } } } /// <summary> /// Validate general Location builder. /// </summary> /// <param name="operatorPam">Different operator parameter name</param> /// <param name="nodeName">Different location string node name</param> /// <param name="isOperator">True if operator else false.</param> private void ValidateLocationBuilder(string nodeName, LocationOperatorParameter operatorPam, bool isOperator) { // Get Values from XML node. string locationString = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.LocationStringValue); string locationStartPosition = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.LoocationStartNode); string locationEndPosition = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.LoocationEndNode); string locationSeperatorNode = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.LocationSeperatorNode); string expectedLocationString = string.Empty; string sublocationStartPosition = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SubLocationStart); string sublocationEndPosition = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SubLocationEnd); string sublocationSeperatorNode = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SubLocationSeperator); string subLocationsCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SubLocationCount); // Build a new location ILocationBuilder locationBuilderObj = new LocationBuilder(); ILocation location = locationBuilderObj.GetLocation(locationString); expectedLocationString = locationBuilderObj.GetLocationString(location); // Validate constructed location starts,end and location string. Assert.AreEqual(locationStartPosition, location.LocationStart.ToString((IFormatProvider) null)); Assert.AreEqual(locationString, expectedLocationString); Assert.AreEqual(locationEndPosition, location.LocationEnd.ToString((IFormatProvider) null)); switch (operatorPam) { case LocationOperatorParameter.Join: Assert.AreEqual(LocationOperator.Join, location.Operator); break; case LocationOperatorParameter.Complement: Assert.AreEqual(LocationOperator.Complement, location.Operator); break; case LocationOperatorParameter.Order: Assert.AreEqual(LocationOperator.Order, location.Operator); break; default: Assert.AreEqual(LocationOperator.None, location.Operator); Assert.AreEqual(locationSeperatorNode, location.Separator.ToString(null)); Assert.IsTrue(string.IsNullOrEmpty(location.Accession)); Assert.IsNotNull(location.SubLocations); break; } if (isOperator) { Assert.IsTrue(string.IsNullOrEmpty(location.Separator)); Assert.AreEqual(sublocationEndPosition, location.SubLocations[0].LocationEnd.ToString((IFormatProvider) null)); Assert.AreEqual(sublocationSeperatorNode, location.SubLocations[0].Separator.ToString(null)); Assert.AreEqual(Convert.ToInt32(subLocationsCount, null), location.SubLocations.Count); Assert.AreEqual(sublocationStartPosition, location.SubLocations[0].LocationStart.ToString((IFormatProvider) null)); Assert.AreEqual(LocationOperator.None, location.SubLocations[0].Operator); Assert.AreEqual(0, location.SubLocations[0].SubLocations.Count); } } /// <summary> /// Validate addition of GenBank features. /// </summary> /// <param name="nodeName">xml node name.</param> private void ValidateGenBankSubFeatures(string nodeName) { // Get Values from XML node. string firstKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FirstKey); string secondKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SecondKey); string thirdKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.ThirdFeatureKey); string fourthKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FourthKey); string fifthKey = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FifthKey); string firstLocation = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FirstLocation); string secondLocation = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SecondLocation); string thirdLocation = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.ThirdLocation); string fourthLocation = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FourthLocation); string fifthLocation = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FifthLocation); string featuresCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.MainFeaturesCount); string secondCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SecondCount); string thirdCount = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.ThirdCount); // Create a feature items var seqFeatures = new SequenceFeatures(); var firstItem = new FeatureItem(firstKey, firstLocation); var secondItem = new FeatureItem(secondKey, secondLocation); var thirdItem = new FeatureItem(thirdKey, thirdLocation); var fourthItem = new FeatureItem(fourthKey, fourthLocation); var fifthItem = new FeatureItem(fifthKey, fifthLocation); seqFeatures.All.Add(firstItem); seqFeatures.All.Add(secondItem); seqFeatures.All.Add(thirdItem); seqFeatures.All.Add(fourthItem); seqFeatures.All.Add(fifthItem); // Validate sub features . List<FeatureItem> subFeatures = firstItem.GetSubFeatures(seqFeatures); Assert.AreEqual(Convert.ToInt32(featuresCount, null), subFeatures.Count); subFeatures = secondItem.GetSubFeatures(seqFeatures); Assert.AreEqual(Convert.ToInt32(secondCount, null), subFeatures.Count); subFeatures = thirdItem.GetSubFeatures(seqFeatures); Assert.AreEqual(Convert.ToInt32(thirdCount, null), subFeatures.Count); } /// <summary> /// Validate Seqeunce feature of GenBank file. /// </summary> /// <param name="nodeName">xml node name. for different alphabet</param> private void ValidateSequenceFeature(string nodeName) { // Get Values from XML node. string filePath = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.FilePathNode); string subSequence = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.ExpectedSubSequence); string subSequenceStart = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SequenceStart); string subSequenceEnd = utilityObj.xmlUtil.GetTextValue( nodeName, Constants.SequenceEnd); ISequence firstFeatureSeq = null; // Parse a genBank file. using (ISequenceParser parserObj = new GenBankParser(filePath)) { IEnumerable<ISequence> seq = parserObj.Parse(); var metadata = seq.ElementAt(0).Metadata[Constants.GenBank] as GenBankMetadata; // Get Subsequence feature,start and end postions. firstFeatureSeq = metadata.Features.All[0].GetSubSequence(seq.ElementAt(0)); var sequenceString = new string(firstFeatureSeq.Select(a => (char) a).ToArray()); // Validate SubSequence. Assert.AreEqual(sequenceString, subSequence); Assert.AreEqual(metadata.Features.All[0].Location.LocationStart.ToString((IFormatProvider) null), subSequenceStart); Assert.AreEqual(metadata.Features.All[0].Location.LocationEnd.ToString((IFormatProvider) null), subSequenceEnd); Assert.IsNull(metadata.Features.All[0].Location.Accession); Assert.AreEqual(metadata.Features.All[0].Location.StartData, subSequenceStart); Assert.AreEqual(metadata.Features.All[0].Location.EndData, subSequenceEnd); } } #endregion Supporting Methods } }
48.226287
131
0.590894
[ "Apache-2.0" ]
jdm7dv/Microsoft-Biology-Foundation
Tests/Bio.TestAutomation/IO/GenBank/GenBankFeaturesBvtTestCases.cs
71,184
C#
// Cinema Suite using UnityEngine; namespace CinemaDirector { /// <summary> /// A helper class for Unity's AnimationCurve class. /// Made to account for tangent mode of keys when adding/changing/removing keys. /// </summary> public static class AnimationCurveHelper { /// <summary> /// Add a new key to an AnimationCurve. /// Ensures the integrity of other key's tangent modes. /// </summary> /// <param name="curve">The existing AnimationCurve.</param> /// <param name="keyframe">The new keyframe</param> /// <returns>The index of the newly added key.</returns> public static int AddKey(AnimationCurve curve, Keyframe keyframe) { if (curve.length == 0) { return curve.AddKey(keyframe); } else if (curve.length == 1) { // Save the existing keyframe data. (Unity changes the tangent info). Keyframe temp = curve[0]; int newIndex = curve.AddKey(keyframe); if(newIndex == -1) { return 0; } else if(newIndex == 0) { curve.MoveKey(1, temp); } else { curve.MoveKey(0, temp); } return newIndex; } else { Keyframe left = new Keyframe(); Keyframe right = new Keyframe(); for (int i = 0; i < curve.length - 1; i++) { Keyframe l = curve[i]; Keyframe r = curve[i + 1]; if (l.time < keyframe.time && keyframe.time < r.time) { left = l; right = r; } } int index = curve.AddKey(keyframe); // Handle left neighbour. if (index > 0) { // Restore the saved data. curve.MoveKey(index - 1, left); // Update tangent data based on tangent mode. int tangentMode = curve[index - 1].tangentMode; if (IsAuto(tangentMode)) { curve.SmoothTangents(index - 1, 0); } if (IsBroken(tangentMode)) { if (IsRightLinear(tangentMode)) { SetKeyRightLinear(curve, index - 1); } } } // Handle the Right neighbour. if (index < curve.length - 1) { // Restore the saved data. curve.MoveKey(index + 1, right); // Update tangent data based on tangent mode. int tangentMode = curve[index + 1].tangentMode; if (IsAuto(tangentMode)) { curve.SmoothTangents(index + 1, 0); } if (IsBroken(tangentMode)) { if (IsLeftLinear(tangentMode)) { SetKeyLeftLinear(curve, index + 1); } } } return index; } } /// <summary> /// Move/Change an existing key in an AnimationCurve. /// Maintains TangentMode and updates neighbours. /// </summary> /// <param name="curve">The existing AnimationCurve.</param> /// <param name="index">The index of the current Keyframe.</param> /// <param name="keyframe">The new Keyframe data.</param> /// <returns>The index of the Keyframe.</returns> public static int MoveKey(AnimationCurve curve, int index, Keyframe keyframe) { // Save the tangent mode. Keyframe old = curve[index]; keyframe.tangentMode = old.tangentMode; int newIndex = curve.MoveKey(index, keyframe); // Respect the tangentMode and update as necessary. if (IsAuto(keyframe.tangentMode)) { curve.SmoothTangents(newIndex, 0); } else if (IsBroken(keyframe.tangentMode)) { if (IsLeftLinear(keyframe.tangentMode)) { SetKeyLeftLinear(curve, newIndex); } if (IsRightLinear(keyframe.tangentMode)) { SetKeyRightLinear(curve, newIndex); } } // update the left neighbour if (newIndex > 0) { // Update tangent data based on tangent mode. int tangentMode = curve[newIndex - 1].tangentMode; if (IsAuto(tangentMode)) { curve.SmoothTangents(newIndex - 1, 0); } if (IsBroken(tangentMode)) { if (IsRightLinear(tangentMode)) { SetKeyRightLinear(curve, newIndex - 1); } } } // update the right neighbour if (newIndex < curve.length - 1) { // Update tangent data based on tangent mode. int tangentMode = curve[newIndex + 1].tangentMode; if (IsAuto(tangentMode)) { curve.SmoothTangents(newIndex + 1, 0); } if (IsBroken(tangentMode)) { if (IsLeftLinear(tangentMode)) { SetKeyLeftLinear(curve, newIndex + 1); } } } return newIndex; } /// <summary> /// Remove a key from an AnimationCurve. /// </summary> /// <param name="curve">The existing AnimationCurve.</param> /// <param name="index">The index of the Key to be removed.</param> public static void RemoveKey(AnimationCurve curve, int index) { curve.RemoveKey(index); // Update left neighbour. if (index > 0) { // Update tangent data based on tangent mode. int tangentMode = curve[index-1].tangentMode; if (IsAuto(tangentMode)) { curve.SmoothTangents(index - 1, 0); } if (IsBroken(tangentMode)) { if (IsRightLinear(tangentMode)) { SetKeyRightLinear(curve, index - 1); } } } // Update right neighbour. if (index < curve.length) { // Update tangent data based on tangent mode. int tangentMode = curve[index].tangentMode; if (IsAuto(tangentMode)) { curve.SmoothTangents(index, 0); } if (IsBroken(tangentMode)) { if (IsLeftLinear(tangentMode)) { SetKeyLeftLinear(curve, index); } } } } /// <summary> /// Set the indexed key of an AnimationCurve to RightLinear. /// </summary> /// <param name="curve">The curve to change.</param> /// <param name="index">The index of the key to set to RightLinear.</param> public static void SetKeyRightLinear(AnimationCurve curve, int index) { Keyframe kf = curve[index]; float tangentValue = kf.outTangent; if (index < curve.length - 1) { Keyframe next = curve[index + 1]; tangentValue = (next.value - kf.value) / (next.time - kf.time); } Keyframe newKeyframe = new Keyframe(kf.time, kf.value, kf.inTangent, tangentValue); // Get current tangent mode. int leftTangent = (IsAuto(kf.tangentMode) || kf.tangentMode == 0) ? 0 : (kf.tangentMode % 8) - 1; newKeyframe.tangentMode = leftTangent + 16 + 1; curve.MoveKey(index, newKeyframe); } /// <summary> /// Set the indexed key of an AnimationCurve to LeftLinear. /// </summary> /// <param name="curve">The curve to change.</param> /// <param name="index">The index of the key to set to LeftLinear.</param> public static void SetKeyLeftLinear(AnimationCurve curve, int index) { Keyframe kf = curve[index]; float tangentValue = kf.inTangent; if (index > 0) { Keyframe prev = curve[index - 1]; tangentValue = (kf.value - prev.value) / (kf.time - prev.time); } Keyframe newKeyframe = new Keyframe(kf.time, kf.value, tangentValue, kf.outTangent); int rightTangent = kf.tangentMode > 16 ? (kf.tangentMode / 8) * 8 : 0; newKeyframe.tangentMode = rightTangent + 1 + 4; curve.MoveKey(index, newKeyframe); } /// <summary> /// Is the TangentMode Auto. /// </summary> /// <param name="tangentMode">The tangentMode value.</param> /// <returns>True if set to auto.</returns> public static bool IsAuto(int tangentMode) { return tangentMode == 10; } /// <summary> /// Is the TangentMode Broken. /// </summary> /// <param name="index">The tangentMode value.</param> /// <returns>True if set to Broken.</returns> public static bool IsBroken(int tangentMode) { return (tangentMode % 2) == 1; } /// <summary> /// Is the TangentMode RightLinear. /// </summary> /// <param name="tangentMode">The tangentMode value.</param> /// <returns>True if the right tangent mode is set to linear.</returns> public static bool IsRightLinear(int tangentMode) { return (tangentMode / 8) == 2; } /// <summary> /// Is the TangentMode LeftLinear. /// </summary> /// <param name="tangentMode">The tangentMode value.</param> /// <returns>True if the left tangent mode is set to linear.</returns> public static bool IsLeftLinear(int tangentMode) { return IsBroken(tangentMode) && (tangentMode % 8) == 5; } } }
34.426332
109
0.460025
[ "MIT" ]
craftweak/ChaoHsiang_desktop
Assets/Cinema Suite/Cinema Director/System/Runtime/Helpers/AnimationCurveHelper.cs
10,984
C#
namespace EA.Weee.RequestHandlers.Tests.Unit.AatfReturn { using Core.AatfReturn; using Domain.AatfReturn; using EA.Weee.RequestHandlers.Security; using EA.Weee.Tests.Core; using FakeItEasy; using FluentAssertions; using Prsd.Core.Mapper; using RequestHandlers.AatfReturn; using RequestHandlers.AatfReturn.Specification; using Requests.AatfReturn; using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Threading.Tasks; using Xunit; public class GetAatfInfoByOrganisationRequestHandlerTests { private GetAatfInfoByOrganisationRequestHandler handler; private readonly IMap<Aatf, AatfData> mapper; private readonly IGenericDataAccess dataAccess; private readonly IWeeeAuthorization authorization; public GetAatfInfoByOrganisationRequestHandlerTests() { mapper = A.Fake<IMap<Aatf, AatfData>>(); dataAccess = A.Fake<IGenericDataAccess>(); authorization = A.Fake<IWeeeAuthorization>(); handler = new GetAatfInfoByOrganisationRequestHandler(mapper, dataAccess, authorization); } [Fact] public async void HandleAsync_NoOrganisationOrInternalAccess_ThrowsSecurityException() { var authorization = new AuthorizationBuilder().DenyInternalOrOrganisationAccess().Build(); handler = new GetAatfInfoByOrganisationRequestHandler(A.Fake<IMap<Aatf, AatfData>>(), A.Fake<IGenericDataAccess>(), authorization); Func<Task> action = async () => await handler.HandleAsync(A.Dummy<GetAatfByOrganisation>()); await action.Should().ThrowAsync<SecurityException>(); } [Fact] public async void HandleAsync_GivenRequest_DataAccessShouldBeCalled() { var id = Guid.NewGuid(); await handler.HandleAsync(new GetAatfByOrganisation(id)); A.CallTo(() => dataAccess.GetManyByExpression(A<AatfsByOrganisationSpecification>.That.Matches(c => c.OrganisationId == id))).MustHaveHappened(Repeated.Exactly.Once); } [Fact] public async void HandleAsync_GivenAatfData_AatfDataShouldBeMapped() { var aatfs = Aatfs(); A.CallTo(() => dataAccess.GetManyByExpression(A<AatfsByOrganisationSpecification>._)).Returns(aatfs); await handler.HandleAsync(A.Dummy<GetAatfByOrganisation>()); for (var i = 0; i < aatfs.Count; i++) { A.CallTo(() => mapper.Map(aatfs.ElementAt(i))).MustHaveHappened(Repeated.Exactly.Once); } } [Fact] public async void HandleAsync_GivenMappedAatfData_AatfDataShouldBeReturn() { var aatfDatas = new List<AatfData>() { A.Fake<AatfData>(), A.Fake<AatfData>() }.ToArray(); A.CallTo(() => dataAccess.GetManyByExpression(A<AatfsByOrganisationSpecification>._)).Returns(Aatfs()); A.CallTo(() => mapper.Map(A<Aatf>._)).ReturnsNextFromSequence(aatfDatas); var result = await handler.HandleAsync(A.Dummy<GetAatfByOrganisation>()); foreach (var aatfData in aatfDatas) { result.Should().Contain(aatfData); } result.Count().Should().Be(aatfDatas.Length); } private List<Aatf> Aatfs() { var aatfs = new List<Aatf>() { A.Fake<Aatf>(), A.Fake<Aatf>() }; return aatfs; } } }
34.761905
178
0.627671
[ "Unlicense" ]
DEFRA/prsd-weee
src/EA.Weee.RequestHandlers.Tests.Unit/AatfReturn/GetAatfInfoByOrganisationRequestHandlerTests.cs
3,652
C#
using UnityEngine; namespace Assets.Script { public class Jogador : MonoBehaviour { private Rigidbody2D _rigidbody2D; private Vector3 _posicaoInicial; private bool _deveImpulsionar; private Animator _animator; public Diretor Diretor; public float Forca; public void Awake() { _rigidbody2D = GetComponent<Rigidbody2D>(); _posicaoInicial = transform.position; _animator = GetComponent<Animator>(); } public void Update() { _animator.SetFloat("VelocidadeY", transform.position.y); if (Input.GetButtonDown("Fire1")) { _deveImpulsionar = true; } } public void FixedUpdate() { if (_deveImpulsionar) { Impulsionar(); } } public void OnCollisionEnter2D(Collision2D outro) { if (outro.gameObject.CompareTag("Obstaculo") || outro.gameObject.CompareTag("Chao")) { _rigidbody2D.simulated = false; Diretor.FinalizaJogo(); } } private void Impulsionar() { _rigidbody2D.velocity = Vector2.zero; _rigidbody2D.AddForce(Vector2.up * Forca * Time.deltaTime, ForceMode2D.Impulse); _deveImpulsionar = false; } public void Reiniciar() { transform.position = _posicaoInicial; _rigidbody2D.simulated = true; } } }
24.4
96
0.53657
[ "MIT" ]
flaviogf/Cursos
alura/curso_unity2d/Assets/Script/Jogador.cs
1,588
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using HelloRandom.Service; using Microsoft.AspNetCore.Mvc; namespace HelloRandom.Controllers { [Route("api/[controller]")] public class Random2Controller : Controller { // GET api/values [HttpGet] public string Get() { return RandomService.GenerateOutTradeNo2(); } } }
19.26087
55
0.65237
[ "Apache-2.0" ]
ElandGroup/HelloRandom
src/HelloRandom/Controllers/Random2Controller.cs
445
C#
using Mitigate.Utils; using System; using System.Collections.Generic; namespace Mitigate.Enumerations { class UnknownDLLs : Enumeration { public override string Name => "Prevent Execution of Unknown DLLs"; public override string MitigationType => MitigationTypes.ExecutionPrevention; public override string MitigationDescription => "Identify and block potentially malicious software by using application control tools like Windows Defender Application Control, AppLocker, or Software Restriction Policies [6 that are capable of auditing and/or blocking unknown DLLs."; public override string EnumerationDescription => "Checks if SRPs or Applocker is enabled for DLLs"; public override string[] Techniques => new string[] { "T1547.004", "T1546.009", "T1546.010", "T1574", "T1574.001", "T1574.006", "T1574.012", "T1129", "T1553.003", }; public override IEnumerable<EnumerationResults> Enumerate(Context context) { // Checking for restriction on unknown DLLs // 1. Check for AppLocker // 2. if not set then chech for Software Restriction Policies // 3. Check for ASR rules if (AppLockerUtils.IsAppLockerEnabled("DLL")) { if (!AppLockerUtils.IsAppLockerRunning()) { throw new Exception("AppLocker SVC is not running"); } yield return new BooleanConfig("App Locker DLL Rules", true); var Rules = AppLockerUtils.GetAppLockerRules("DLL"); foreach (var rule in Rules) { yield return new ConfigurationDetected(rule.Name, rule.Action); } } else if (SoftwareRestrictionUtils.DLLMonitoringEnabled()) { yield return new BooleanConfig("SRP DLL monitoring", true); } // WDAC } } }
38.142857
293
0.571629
[ "MIT" ]
moullos/Mitigate
Mitigate/Enumerations/ExecutionPrevention/UnknownDLLs.cs
2,138
C#
using System; using System.Linq; using System.Threading.Tasks; using AsyncOAuth; using Fitbit.Models; using RequestToken = Fitbit.Models.RequestToken; namespace Fitbit.OAuth1Migration { public class Authenticator { public string ConsumerKey { get; private set; } public string ConsumerSecret { get; private set; } public Authenticator(string consumerKey, string consumerSecret) { ConsumerKey = consumerKey; ConsumerSecret = consumerSecret; } public string GenerateAuthUrlFromRequestToken(RequestToken token, bool forceLogoutBeforeAuth) { var url = Constants.BaseApiUrl + (forceLogoutBeforeAuth ? Constants.LogoutAndAuthorizeUri : Constants.AuthorizeUri); return string.Format("{0}?oauth_token={1}", url, token.Token); } /// <summary> /// First step in the OAuth process is to ask Fitbit for a temporary request token. /// From this you should store the RequestToken returned for later processing the auth token. /// </summary> /// <returns></returns> public async Task<RequestToken> GetRequestTokenAsync() { // create authorizer var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret); // get request token var tokenResponse = await authorizer.GetRequestToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsRequestTokenUri); var requestToken = tokenResponse.Token; // return the request token return new RequestToken { Token = requestToken.Key, Secret = requestToken.Secret }; } /// <summary> /// For Desktop authentication. Your code should direct the user to the FitBit website to get /// Their pin, they can then enter it here. /// </summary> /// <param name="pin"></param> /// <param name="token"></param> /// <returns></returns> public async Task<AuthCredential> GetAuthCredentialFromPinAsync(string pin, RequestToken token) { var oauthRequestToken = new AsyncOAuth.RequestToken(token.Token, token.Secret); var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret); var accessTokenResponse = await authorizer.GetAccessToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsAccessTokenUri, oauthRequestToken, pin); // save access token. var accessToken = accessTokenResponse.Token; return new AuthCredential { AuthToken = accessToken.Key, AuthTokenSecret = accessToken.Secret }; } public async Task<AuthCredential> ProcessApprovedAuthCallbackAsync(RequestToken token) { if (token == null) throw new ArgumentNullException("token", "RequestToken cannot be null"); if (string.IsNullOrWhiteSpace(token.Token)) throw new ArgumentNullException("token", "RequestToken.Token must not be null"); var oauthRequestToken = new AsyncOAuth.RequestToken(token.Token, token.Secret); var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret); var accessToken = await authorizer.GetAccessToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsAccessTokenUri, oauthRequestToken, token.Verifier); var result = new AuthCredential { AuthToken = accessToken.Token.Key, AuthTokenSecret = accessToken.Token.Secret, UserId = accessToken.ExtraData["encoded_user_id"].FirstOrDefault() }; return result; } } }
41.593407
166
0.637781
[ "MIT" ]
NagendraSUVCE/Fitbit.NET
OAuth1Migration/Fitbit.OAuth1Migration/Authenticator.cs
3,787
C#
using System.Collections.Generic; namespace GTA.Plugins.Common { public sealed class PointTypeCheckpoint : BasePointType<PointTypeCheckpoint> { internal Dictionary<int, int> pointT; // --------------------------------------------------------------------------------------------------------------------------- public PointTypeCheckpoint() : base() { pointT = new Dictionary<int, int>(); } // --------------------------------------------------------------------------------------------------------------------------- public PointTypeCheckpoint add( double x, double y, double z, uint timeLimit ) { pointT.Add( PoolCount, ( int ) timeLimit ); add( x, y, z ); return this; } } }
34.695652
135
0.393484
[ "Apache-2.0" ]
wmysterio/gta-script-generator
GTA.SA/Plugins/Common/Races/Points/PointTypeCheckpoint.cs
800
C#
using netDxf; 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.Controls; using System.Windows.Forms; using System.Windows.Media; namespace NetDXFviwerWinform { public partial class Form1 : Form { public Form1() { InitializeComponent(); myDXF.GridHeight = 5000; myDXF.GridWidth = 5000; myDXF.ViewHeight = grid1.ActualHeight; myDXF.ViewWidth = grid1.ActualWidth; myDXF.WinHeight = this.Height; myDXF.WinWidth = this.Width; myDXF.border.Reset(myDXF.GridHeight, myDXF.GridWidth, true, this.Height, this.Width, this.Height, this.Width); DrawDXF(); } private void btOpenDxf_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == DialogResult.OK) { String fileDXF = openFileDialog.FileName; DrawDXF(fileDXF); } } public DXF2WPF myDXF = new DXF2WPF(); private void DrawDXF(string fileDXF) { TypeConverter.defaultThickness = 0.01; myDXF.DxfDoc = new DxfDocument(); /* netDxf.Blocks.Block myBlock = netDxf.Blocks.Block.Load("P4035PINM.dxf"); netDxf.Entities.Insert myInsert = new netDxf.Entities.Insert(myBlock); myInsert.Lineweight= Lineweight.W100; myInsert.LinetypeScale= 100; myInsert.Position = new Vector3(0,100,0); myInsert.Scale = new Vector3(-2,2,0); Vector3 pos0 = new Vector3(myInsert.Position.X,myInsert.Position.Y,0); myInsert.Position = pos0; myInsert.Rotation = 0; AciColor bgcolor = new AciColor(); myDXF.DxfDoc.AddEntity(myInsert); */ /*netDxf.Blocks.Block myBlock2 = netDxf.Blocks.Block.Load(fileDXF); netDxf.Entities.Insert myInsert2 = new netDxf.Entities.Insert(myBlock2); myInsert2.Position = new Vector3(30,40,0); myInsert2.Scale = new Vector3(1,1,0); myInsert2.Color = AciColor.Blue; myInsert2.Rotation = 0; myDXF.DxfDoc.AddEntity(myInsert2);*/ /* netDxf.Entities.Insert myInsert2 = new netDxf.Entities.Insert(myBlock); Vector3 scaleInsert = new Vector3(1,-1,1); myInsert2.Scale = scaleInsert; Vector3 pos= new Vector3(myInsert2.Position.X+5,myInsert2.Position.Y,0); myInsert2.Position = pos; myDXF.DxfDoc.AddEntity(myInsert2); */ if (fileDXF == "") fileDXF = @"test8.dxf"; if (fileDXF != "") { this.Content = myDXF.GetMainGrid(fileDXF, true, true); //DrawUtils.SaveAsPng(DrawUtils.GetImage(myDXF.mainCanvas)); } else { this.Content = myDXF.GetMainGrid(true, true); } //myDXF.border.ZoomAuto(5000,5000,((Grid)Application.Current.MainWindow.Content).ActualHeight,((Grid)Application.Current.MainWindow.Content).ActualWidth); myDXF.border.ZoomAuto(5000, 5000, mainWin.myDXF.WinHeight, mainWin.myDXF.WinWidth); // DrawUtils.DrawPoint(100,0,myDXF.mainCanvas,Colors.Red,25,1); //DrawUtils.DrawPoint(-225,0,myDXF.mainCanvas,Colors.Red,25,1); //DrawUtils.SaveAsPng(DrawUtils.GetImage(myDXF.mainCanvas)); } private void DrawDXFInsert(string fileDXF) { TypeConverter.defaultThickness = 0.01; DrawEntities.RazMaxDim(); /*netDxf.Entities.Line ligneTmp = new netDxf.Entities.Line(); ligneTmp.StartPoint = new Vector3(0,0,0); ligneTmp.EndPoint = new Vector3(100,100,0);*/ myDXF.DxfDoc = new DxfDocument(); //myDXF.DxfDoc.AddEntity(ligneTmp); if (fileDXF == "") fileDXF = "raptor.dxf"; netDxf.Blocks.Block myBlock = netDxf.Blocks.Block.Load(fileDXF); netDxf.Entities.Insert myInsert = new netDxf.Entities.Insert(myBlock); myDXF.DxfDoc.AddEntity(myInsert); netDxf.Entities.Insert myInsert2 = new netDxf.Entities.Insert(myBlock); //myInsert2.Rotation = 180; Vector3 scaleInsert = new Vector3(1, -1, 1); myInsert2.Scale = scaleInsert; Vector3 pos = new Vector3(myInsert2.Position.X + 5, myInsert2.Position.Y, 0); myInsert2.Position = pos; myDXF.DxfDoc.AddEntity(myInsert2); this.Content = myDXF.GetMainGrid(myDXF.DxfDoc, true, true); } private void DrawDXF() { DrawDXF(""); } private void DrawDXF2() { // canvas1.Children.Clear(); /*this.Content = DXF2WPF.GetMainGrid("sample2.dxf");*/ //this.Content = myDXF.GetMainGrid("sample2.dxf",true,false); netDxf.Entities.Line ligneTmp = new netDxf.Entities.Line(); ligneTmp.StartPoint = new Vector3(0, 0, 0); ligneTmp.EndPoint = new Vector3(100, 100, 0); /*ligneTmp.Thickness=20; ligneTmp.Lineweight = (Lineweight)15; ligneTmp.Color = new AciColor(8);*/ myDXF.DxfDoc = new DxfDocument(); myDXF.DxfDoc.AddEntity(ligneTmp); Grid mainGrid = new Grid(); Canvas newMainCanvas = new Canvas(); DXF2WPF.GetCanvas(myDXF.DxfDoc, myDXF.mainCanvas); myDXF.mainCanvas.Background = new SolidColorBrush(Colors.Blue); mainGrid.Children.Add(myDXF.mainCanvas); this.Content = mainGrid; //this.Content = myDXF.GetMainGrid("panther.dxf"); /*CanvasCreator.GetCanvas(DxfDoc,canvas1); DrawUtils.DrawOrigin(canvas1);*/ } } }
32.559783
167
0.599566
[ "Apache-2.0" ]
HuLiangGit/Media_AramToHandPro001
NetDXFviwerWinform/Form1.cs
5,993
C#
// This file is licensed to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.Serialization; namespace Spines.Hana.Blame.Services.ReplayManager { [DataContract] public class Agari { /// <summary> /// The player who won the hand. /// </summary> [DataMember(Name = "winner")] public int Winner { get; set; } /// <summary> /// The player dealt into the hand in case of ron, or the winner in case of tsumo. /// </summary> [DataMember(Name = "from")] public int From { get; set; } /// <summary> /// The fu of the hand. /// </summary> [DataMember(Name = "fu")] public int Fu { get; set; } /// <summary> /// The score change for each player after the win. /// </summary> [DataMember(Name = "scoreChanges")] public List<int> ScoreChanges { get; } = new List<int>(); /// <summary> /// The yaku in the hand. /// </summary> [DataMember(Name = "yaku")] public List<Yaku> Yaku { get; } = new List<Yaku>(); } }
26.380952
86
0.604693
[ "MIT" ]
spinesheath/HanaMahjong
Spines.Hana.Blame/Spines.Hana.Blame/Services/ReplayManager/Agari.cs
1,108
C#
namespace MoogleEngine; // This class contains all utility methods used in the proyect. internal static class Utils { /// <summary> /// Computes the TF of an entire document. /// </summary> /// <param name="rawDocument">The raw frequencies of each term in the document.</param> /// <returns>An array containing the TF of each term in a document.</returns> public static double[] GetDocumentTermFrequency(Vector<int> rawDocument) { double[] result = new double[rawDocument.Length]; int maxFreq = rawDocument.Max(); // if the max frequency in the document is 0, simply return 0 for the whole array. if (maxFreq == 0) return result; for (int i = 0; i < result.Length; i++) { if (rawDocument[i] == 0) { result[i] = 0; continue; } // Augmented Term Frequency formula result[i] = 0.5 + 0.5 * ((double)rawDocument[i] / maxFreq); } return result; } /// <summary> /// Returns the logarithmically scaled inverse fraction of the documents that contain /// the word (obtained by dividing the total number of documents by the number of documents /// containing the term, and then taking the logarithm of that quotient) /// </summary> /// <param name="termIndex">The index of the term in the corpus.</param> /// <param name="rawCorpus">The corpus matrix containing the raw count of each term in each document</param> /// <returns>Returns the IDF of a term in a corpus.</returns> /// <exception cref="IndexOutOfRangeException"></exception> public static double GetInverseDocumentFrequency(int termIndex, Matrix<int> rawCorpus) { if (termIndex < 0 || termIndex >= rawCorpus.Width) throw new IndexOutOfRangeException($"{nameof(termIndex)} must be greater than 0 and lower than {nameof(rawCorpus)}.ColumnLength."); int corpusLength = rawCorpus.Height; int documentsWithTerm = rawCorpus.GetColumn(termIndex).Count(v => v != 0); if (documentsWithTerm == 0) return 0; return Math.Log((double)corpusLength / documentsWithTerm); } /// <summary> /// Computes the IDF of every term in a corpus. /// </summary> /// <param name="rawCorpus">The corpus matrix containing the raw count of each term in each document</param> /// <returns>An array containing the IDF of each term.</returns> public static double[] GetCorpusIDF(Matrix<int> rawCorpus) { double[] idfs = new double[rawCorpus.Width]; for (int i = 0; i < idfs.Length; i++) idfs[i] = GetInverseDocumentFrequency(i, rawCorpus); return idfs; } /// <summary> /// Computes the TF-IDF of a single document in a corpus.<br> /// Note: `document` and `rawCorpus` can't be simultaneously null. /// </summary> /// <param name="document">The vector containing the raw frequencies of each term in a document</param> /// <param name="rawCorpus">The corpus matrix containing the raw count of each term in each document</param> /// <param name="idf">The IDF vector containing the IDFs of each term in the corpus.</param> /// <returns>An array containing the TF-IDF of each term in a document.</returns> /// <exception cref="ArgumentNullException"></exception> public static double[] GetDocumentTFIDF(Vector<int> document, Matrix<int>? rawCorpus = null, Vector<double>? idf = null) { if (idf == null && rawCorpus == null) throw new ArgumentNullException(nameof(idf), "rawCorpus and idf can't be simultaneously null."); double[] result = new double[document.Length]; double[] docTF = GetDocumentTermFrequency(document); if (rawCorpus != null) idf ??= new Vector<double>(GetCorpusIDF(rawCorpus)); if (idf != null) for (int i = 0; i < result.Length; i++) result[i] = docTF[i] * idf[i]; return result; } /// <summary> /// Computes the TF-IDF of every term in every document in a corpus. /// </summary> /// <param name="rawCorpus">The corpus matrix containing the raw count of each term in each document</param> /// <param name="idf">The IDF vector containing the IDFs of each term in the corpus.</param> /// <returns>A matrix with the TF-IDF of each term in each document in the corpus.</returns> public static Matrix<double> GetCorpusTFIDF(Matrix<int> rawCorpus, Vector<double>? idf = null) { Matrix<double> result = new(rawCorpus.Width, rawCorpus.Height); double[] idfs = idf?.ToArray() ?? GetCorpusIDF(rawCorpus); for (int i = 0; i < rawCorpus.Height; i++) { double[] docTFs = GetDocumentTermFrequency(rawCorpus.GetRow(i)); for (int e = 0; e < rawCorpus.Width; e++) result[e, i] = docTFs[e] * idfs[e]; } return result; } // Standard Filter applied to characters in Filtered reads internal static bool StandardCharFilter(char c) => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c); // Standard Map applied to characters (used for normalization (elimination of accents and such)) internal static char StandardCharMap(char c) => c.ToString().ToLower().Normalize(System.Text.NormalizationForm.FormD)[0]; // Make an action on each filtered paragraph in a file. public static void ForEachFilteredParagraphInFile(string filePath, Action<string> action) => SeparateTextInFile(filePath, c => c == '\n', action, StandardCharFilter, StandardCharMap); // Make an action on each unfiltered paragraph in a file. public static void ForEachRawParagraphInFile(string filePath, Action<string> action) => SeparateTextInFile(filePath, c => c == '\n', action, c => true, c => c); // Make an action on each filtered word in a file. public static void ForEachWordInFile(string filePath, Action<string> action) => SeparateTextInFile(filePath, char.IsWhiteSpace, action, StandardCharFilter, StandardCharMap); // Make an action on parts of a file, defined by an isSeparator function, applying // a filter and a map to each character. public static void SeparateTextInFile( string filePath, Func<char, bool> isSeparator, Action<string> action, Func<char, bool> filter, Func<char, char> map) { using StreamReader reader = new(filePath); string currentWord = ""; while (!reader.EndOfStream) { char input = (char)reader.Read(); char c = map(input); if (isSeparator(c)) { currentWord = currentWord.Trim(); if (currentWord != "") action(currentWord); currentWord = ""; } else if (filter(c)) currentWord += c; } currentWord = currentWord.Trim(); if (currentWord != "") action(currentWord); } // Same as SeparateTextInFile but in a string. public static void SeparateTextInString( string str, Func<char, bool> isSeparator, Action<string> action, Func<char, bool> filter, Func<char, char> map) { using StringReader reader = new(str); string currentWord = ""; while (reader.Peek() != -1) { currentWord = currentWord.Trim(); char input = (char)reader.Read(); char c = map(input); if (isSeparator(c)) { if (currentWord != "") action(currentWord); currentWord = ""; } else if (filter(c)) currentWord += c; } currentWord = currentWord.Trim(); if (currentWord != "") action(currentWord); } /// <summary> /// Computes the minimal distance between a series of terms in a file. /// </summary> /// <param name="documentPath">File path.</param> /// <returns>An Int32 that represents the minimal distance between the terms.</returns> public static int GetMinDistanceBetweenTerms(string documentPath, string[] terms) { int[][] positions = GetAllTermsPositionsInDocument(documentPath, terms); int foundTerms = positions.Count(p => p.Length != 0); // if less than two terms where found in a document, // finding the distance is useless and error-prone if (foundTerms < 2) return 0; return GetShortestPathInIndexArray(positions, 0, -1, -1); } private static int GetShortestPathInIndexArray(in int[][] indexArray, int depth, int max, int min) { // This recursive method computes every possible path in a positional array // and returns the shortest path length (obtained by finding the highest and lowest // positions in the array, and finding the distance between them) if (depth >= indexArray.Length) return max - min; if (indexArray[depth].Length == 0) return GetShortestPathInIndexArray(indexArray, depth + 1, max, min); int[] distances = new int[indexArray[depth].Length]; for (int i = 0; i < distances.Length; i++) // for each distance in the current depth, get the shortest path from that distance // to the next depths, passing as max index the max between the previous max or the // current position, and a similar process is used for passing the min parameter. distances[i] = GetShortestPathInIndexArray(indexArray, depth + 1, max >= 0 ? Math.Max(max, indexArray[depth][i]) : indexArray[depth][i], min >= 0 ? Math.Min(min, indexArray[depth][i]) : indexArray[depth][i]); return distances.Min(); } private static int[][] GetAllTermsPositionsInDocument(string documentPath, string[] terms) { // this method finds every position in a document of each term in an array. List<int>[] result = new List<int>[terms.Length]; for (int i = 0; i < result.Length; i++) result[i] = new(); int wordIndex = 0; ForEachWordInFile(documentPath, w => { for (int i = 0; i < terms.Length; i++) { if (terms[i] == w) { result[i] ??= new(); result[i].Add(wordIndex); break; } } wordIndex++; }); return result.Select(l => l.ToArray()).ToArray(); } public static string[] GetAllTermVariationsInVocabulary(string term, string[] vocabulary, int distance) { // This method finds every variation of a term in a vocabulary, up to a maximal Levenshtein distance List<string> variations = new(); foreach (string word in vocabulary) if (CalculateDLDistance(term, word) <= distance) variations.Add(word); return variations.ToArray(); } public static int[][] GetAllArrayCombinations(in int[] lengths) { // By using an array containing the lengths of other arrays, this method // returns each possible index combination of said arrays int totalLength = 1; foreach (int length in lengths) totalLength *= length; List<int[]> result = new(); GetAllArrayCombinations(lengths, new List<int>(), ref result); return result.ToArray(); } private static void GetAllArrayCombinations(in int[] lengths, List<int> previousTerms, ref List<int[]> result) { // This method recursively computes every index combination of several arrays, // which lengths are stored in the lengths array. int n = previousTerms.Count; // wrap things up if we are at the last term. if (n == lengths.Length - 1) { int[] value = new int[lengths.Length]; previousTerms.CopyTo(value); for (int i = 0; i < lengths[n]; i++) { value[n] = i; result.Add((int[])value.Clone()); } return; } // if we aren't at the last term, find all combinations for the next terms else { for (int i = 0; i < lengths[n]; i++) { List<int> nextTerms = new(previousTerms); nextTerms.Add(i); GetAllArrayCombinations(lengths, nextTerms, ref result); } } } public static int CalculateDLDistance(string a, string b) => CalculateDLDistance(a, b, a.Length - 1, b.Length - 1); // Method for calculating Damerau–Levenshtein distance between two strings (a & b) // i indicates the 0-indexed length of the current substring of a, and j of b. private static int CalculateDLDistance(string a, string b, int i, int j) { // if both substrings still have valid lengths if (i > -1 && j > -1) { // if there is a swap between this character and the next, it counts as a single operation in Damerau-Levenshtein. if (i > 0 && j > 0 && a[i] == b[j - 1] && a[i - 1] == b[j]) return CalculateDLDistance(a, b, i - 2, j - 2) + 1; // if there isn't a swap, and the current characters are different, then a substitution must be made. else return CalculateDLDistance(a, b, i - 1, j - 1) + (a[i] == b[j] ? 0 : 1); } // this happens if a is longer than b else if (i > -1) return CalculateDLDistance(a, b, i - 1, j) + 1; // this happens if b is longer than a else if (j > -1) return CalculateDLDistance(a, b, i, j - 1) + 1; // base case else return 0; } }
40.045845
143
0.596666
[ "MIT" ]
leoamaro01/moogle-2021
MoogleEngine/Utils.cs
13,978
C#
using Assets.Gamelogic.Core; using UnityEngine; using UnityEngine.UI; namespace Assets.Gamelogic.UI { public class SpellsPanelController : MonoBehaviour { private static Image lightningCircleIcon; private static Image rainCircleIcon; private static Image lightningSpellIcon; private static Image rainSpellIcon; private void Awake() { lightningCircleIcon = transform.FindChild("LightningIcon").FindChild("ActiveImage").GetComponent<Image>(); rainCircleIcon = transform.FindChild("RainIcon").FindChild("ActiveImage").GetComponent<Image>(); lightningSpellIcon = transform.FindChild("LightningIcon").FindChild("LightningImage").GetComponent<Image>(); rainSpellIcon = transform.FindChild("RainIcon").FindChild("RainImage").GetComponent<Image>(); } public static void SetLightningIconFill(float fill) { lightningCircleIcon.fillAmount = fill; lightningSpellIcon.color = fill < 1f ? SimulationSettings.TransparentWhite : Color.white; } public static void SetRainIconFill(float fill) { rainCircleIcon.fillAmount = fill; rainSpellIcon.color = fill < 1f ? SimulationSettings.TransparentWhite : Color.white; } } }
37.885714
120
0.674962
[ "MIT" ]
JoshuaSmith117/HelloWorldSOS
workers/unity/Assets/Gamelogic/UI/SpellsPanelController.cs
1,326
C#
// (c) Copyright Crainiate Software 2010 using System; using System.Drawing; namespace Crainiate.Diagramming { [Serializable] public class Controller { //Property variables private Views _views; private Model _model; private ClipboardCommand _command; private Clipboard _clipboard; private Factory _factory; private CommandFactory _commandFactory; private CommandStack _undoStack; private CommandStack _redoStack; private bool _cut; private bool _copy; private bool _paste; private bool _delete; private bool _undo; private bool _redo; private bool _roundPixels; private bool _checkBounds; //Constructors public Controller(Model model) { Model = model; Factory = new Factory(); CommandFactory = new CommandFactory(this); _views = new Views(); _clipboard = new Clipboard(); _checkBounds = true; _undoStack = new CommandStack(); _redoStack = new CommandStack(); AllowCut = true; AllowCopy = true; AllowPaste = true; AllowDelete = true; AllowUndo = true; AllowRedo = true; RoundPixels = true; } public virtual Views Views { get { return _views; } } public virtual Model Model { get { return _model; } set { if (value == null) throw new ArgumentNullException(); _model = value; //Loop through each view and set the model reference if (Views != null) { foreach (IView view in Views) { view.SetModel(value); } } } } public virtual CommandStack UndoStack { get { return _undoStack; } } public virtual CommandStack RedoStack { get { return _redoStack; } } public Clipboard Clipboard { get { return _clipboard; } } public virtual bool AllowCut { get { return _cut; } set { _cut = value; } } public virtual bool AllowCopy { get { return _copy; } set { _copy = value; } } public virtual bool AllowPaste { get { return _paste; } set { _paste = value; } } public virtual bool AllowDelete { get { return _delete; } set { _delete = value; } } public virtual bool AllowUndo { get { return _undo; } set { _undo = value; } } public virtual bool AllowRedo { get { return _redo; } set { _redo = value; } } public virtual bool RoundPixels { get { return _roundPixels; } set { _roundPixels = value; } } public virtual bool CheckBounds { get { return _checkBounds; } set { _checkBounds = value; } } //Used to create elements at runtime. Follows the Factory design pattern public virtual Factory Factory { get { return _factory; } set { if (value == null) throw new ArgumentNullException(); _factory = value; } } //Creates commands at runtime. Follows the Factory design pattern public virtual CommandFactory CommandFactory { get { return _commandFactory; } set { if (value == null) throw new ArgumentNullException(); _commandFactory = value; } } //Methods //Execute the comand and push it onto the top of the undo stack public virtual void ExecuteCommand(Command command) { if (command == null) return; command.Execute(); if (AllowUndo) UndoStack.Push(command); } //Pop the top command off the undo stack, execute it and push it onto the redo stack. public virtual void UndoCommand() { if (!AllowUndo || UndoStack.Count == 0) return; Command command = UndoStack.Pop(); command.Undo(); RedoStack.Push(command); } //Pop the command off the redo stack and process it back through ExecuteCommand public virtual void RedoCommand() { if (!AllowRedo || RedoStack.Count == 0) return; Command command = RedoStack.Pop(); command.Redo(); if (AllowUndo) UndoStack.Push(command); } public virtual Element CloneElement(Element element) { Element newElement = (Element) element.Clone(); newElement.ActionElement = element; newElement.SetKey(element.Key); newElement.SetModel(element.Model); //Set the action shapes for the complex shape children if (element is ComplexShape) { ComplexShape complex = (ComplexShape)element; ComplexShape newComplex = (ComplexShape)newElement; foreach (Solid solid in newComplex.Children.Values) { solid.ActionElement = complex.Children[solid.Key]; } } //Keep size of table if (element is Table) { Table table = (Table)element; Table newTable = (Table)newElement; newTable.Size = table.Size; } return newElement; } public virtual void Suspend() { foreach (IView view in Views) { view.Suspend(); } } public virtual void Resume() { foreach (IView view in Views) { view.Resume(); } } public virtual void Invalidate() { foreach (IView view in Views) { view.Invalidate(); } } public virtual void Refresh() { foreach (IView view in Views) { view.Refresh(); } } //Sets all elements selected to true/false public void SelectElements(bool selection) { Suspend(); foreach (Element element in Model.Elements) { if (element is ISelectable && element.Layer == Model.Layers.CurrentLayer) { ISelectable selectable = (ISelectable)element; selectable.Selected = selection; } } Resume(); Invalidate(); } //Selects elements from a rectangle public virtual void SelectElements(RectangleF diagramRectangle) { foreach (Element element in Model.Elements) { if (element is ISelectable) { ISelectable selectable = (ISelectable)element; selectable.Selected = (element.Intersects(diagramRectangle) && element.Layer == Model.Layers.CurrentLayer); } } } //Determine if an element can dock public virtual bool CanDock(InteractiveMode interactiveMode, MouseElements mouseElements) { if (interactiveMode == InteractiveMode.Normal) { //Check is shape or port if (mouseElements.MouseMoveElement is Shape || mouseElements.MouseMoveElement is Port) { //return false if permission not available to dock if (mouseElements.MouseStartOrigin != null) { Origin origin = mouseElements.MouseStartOrigin; Link line = (Link) mouseElements.MouseStartElement; if (mouseElements.MouseMoveElement is Shape) { Shape shape = (Shape) mouseElements.MouseMoveElement; if (shape.Direction == Direction.None) return false; if (origin == line.Start && shape.Direction== Direction.In) return false; if (origin == line.End && shape.Direction == Direction.Out) return false; } if (mouseElements.MouseMoveElement is Port) { Port port = (Port) mouseElements.MouseMoveElement; if (port.Direction == Direction.None) return false; if (origin == line.Start && port.Direction == Direction.In) return false; if (origin == line.End && port.Direction == Direction.Out) return false; } } return true; } } //Can dock for interactive elements else { if (mouseElements.InteractiveElement is Link) { Link line = (Link) mouseElements.InteractiveElement; //Determine if applies to start or end origin if (mouseElements.InteractiveOrigin == line.Start) { if (mouseElements.MouseMoveElement is Shape) { Shape shape = (Shape) mouseElements.MouseMoveElement; if (shape.Direction == Direction.None) return false; if (shape.Direction== Direction.In) return false; } if (mouseElements.MouseMoveElement is Port) { Port port = (Port) mouseElements.MouseMoveElement; if (port.Direction == Direction.None) return false; if (port.Direction == Direction.In) return false; } } else { if (mouseElements.MouseMoveElement is Shape) { Shape shape = (Shape) mouseElements.MouseMoveElement; if (shape.Direction == Direction.None) return false; if (shape.Direction == Direction.Out) return false; } if (mouseElements.MouseMoveElement is Port) { Port port = (Port) mouseElements.MouseMoveElement; if (port.Direction == Direction.None) return false; if (port.Direction == Direction.Out) return false; } } return true; } } return false; } //Determines if an element can be added interactively public virtual bool CanAdd(Element element) { return true; } public virtual bool CanDelete(Element element) { return true; } public virtual PointF SnapToLocation(PointF location, SizeF size, TransformCommand action) { Nullable<float> bestX = null; Nullable<float> bestY = null; Nullable<RectangleF> verticalVector = null; Nullable<RectangleF> horizontalVector = null; PointF bestLocation = new PointF(); foreach (Shape shape in Model.Shapes.Values) { if (shape.UpdateElement == null) { //Left float diff = Math.Abs(shape.X - location.X); if (diff <= 9) { if (!bestX.HasValue || diff < bestX.Value) { bestX = diff; bestLocation.X = shape.X; verticalVector = new RectangleF(shape.X, 0, 0, Model.Size.Height); } } //Right diff = Math.Abs(shape.Bounds.Right - location.X - size.Width); if (diff <= 9) { if (!bestX.HasValue || diff < bestX.Value) { bestX = diff; bestLocation.X = shape.Bounds.Right - size.Width; verticalVector = new RectangleF(shape.Bounds.Right, 0, 0, Model.Size.Height); } } //Top diff = Math.Abs(shape.Y - location.Y); if (diff <= 9) { if (!bestY.HasValue || diff < bestY.Value) { bestY = diff; bestLocation.Y = shape.Y; horizontalVector = new RectangleF(0, shape.Y, Model.Size.Width, 0); } } //Bottom diff = Math.Abs(shape.Bounds.Bottom - location.Y - size.Height); if (diff <= 9) { if (!bestY.HasValue || diff < bestY.Value) { bestY = diff; bestLocation.Y = shape.Bounds.Bottom - size.Height; horizontalVector = new RectangleF(0, shape.Bounds.Bottom, Model.Size.Width, 0); } } } } if (bestX.HasValue) location = new PointF(bestLocation.X, location.Y); if (bestY.HasValue) location = new PointF(location.X, bestLocation.Y); //Set the vectors if (verticalVector.HasValue) { if (horizontalVector.HasValue) { action.SetVectors(new RectangleF[] { verticalVector.Value, horizontalVector.Value }); } else { action.SetVectors(new RectangleF[] { verticalVector.Value }); } } else { if (horizontalVector.HasValue) action.SetVectors(new RectangleF[] {horizontalVector.Value }); } return location; } public virtual SizeF BoundsCheck(ElementList actions, SizeF delta) { //Return pass if the diagram does not have boundary checking if (!CheckBounds) return delta; foreach (Element element in actions) { delta = BoundsCheck(element, delta); if (delta.IsEmpty) return delta; } return delta; } //Bounds checking by element public virtual SizeF BoundsCheck(Element element, SizeF delta) { //Return pass if the controller does not have boundary checking or the delta is empty if (!CheckBounds) return delta; if (delta.IsEmpty) return delta; Element action = element.ActionElement; bool contains = false; //If the original (action) is contained in the container contains = (Model.Contains(new PointF(action.Bounds.X + delta.Width, action.Bounds.Y + delta.Height))); // && container.Contains(new PointF(action.Rectangle.Right + container.Offset.X + delta.Width, action.Rectangle.Bottom + container.Offset.Y + delta.Height), container.Margin)); contains = contains && (Model.Contains(new PointF(action.Bounds.Right + delta.Width, action.Bounds.Bottom + delta.Height))); if (contains) return delta; return SizeF.Empty; } //Bounds checking by point public virtual bool BoundsCheck(PointF action, float dx, float dy) { //Return pass if the diagram does not have boundary checking if (!CheckBounds) return true; //If the original (action) is contained in the container if (Model.Contains(new PointF(action.X, action.Y))) { //Check top left if (!Model.Contains(new PointF(action.X + dx, action.Y + dy))) return false; } return true; } } }
27.40378
293
0.510063
[ "BSD-3-Clause" ]
Mohllal/FlowchartConverter
Crainiate.Diagramming/Controller.cs
15,949
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("UnicodeCharacter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("UnicodeCharacter")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ab8f594e-c22e-4573-a643-34d1920786a5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.459459
84
0.749824
[ "MIT" ]
Maxtorque/Datatype-and-Variables2
UnicodeCharacter/UnicodeCharacter/Properties/AssemblyInfo.cs
1,426
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace IdentityServer.AuthIdentity.Quickstart.Consent { public class ConsentOptions { public static bool EnableOfflineAccess = true; public static string OfflineAccessDisplayName = "Offline Access"; public static string OfflineAccessDescription = "Access to your applications and resources, even when you are offline"; public static readonly string MustChooseOneErrorMessage = "You must pick at least one permission"; public static readonly string InvalidSelectionErrorMessage = "Invalid selection"; } }
43.470588
127
0.753721
[ "MIT" ]
Olek-HZQ/IdentityServerManagement
src/IdentityServer.AuthIdentity/Quickstart/Consent/ConsentOptions.cs
741
C#
using System; namespace OCP.Migration { /** * Repair step * @since 9.1.0 */ public interface IRepairStep { /** * Returns the step's name * * @return string * @since 9.1.0 */ string getName(); /** * Run repair step. * Must throw exception on error. * * @param IOutput output * @throws \Exception in case of failure * @since 9.1.0 */ void run(IOutput output); } }
16.8125
48
0.449814
[ "MIT" ]
mindfocus/nextcloud_net
publicApi/OCP/Migration/IRepairStep.cs
540
C#
#nullable enable using System.Threading; using System.Threading.Tasks; using BTCPayServer.Abstractions.Contracts; using BTCPayServer.Data; using BTCPayServer.Events; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using Newtonsoft.Json; namespace BTCPayServer.Services { public class SettingsRepository : ISettingsRepository { private readonly ApplicationDbContextFactory _ContextFactory; private readonly EventAggregator _EventAggregator; private readonly IMemoryCache _memoryCache; public SettingsRepository(ApplicationDbContextFactory contextFactory, EventAggregator eventAggregator, IMemoryCache memoryCache) { _ContextFactory = contextFactory; _EventAggregator = eventAggregator; _memoryCache = memoryCache; } public async Task<T?> GetSettingAsync<T>(string? name = null) where T : class { name ??= typeof(T).FullName ?? string.Empty; return await _memoryCache.GetOrCreateAsync(GetCacheKey(name), async entry => { await using var ctx = _ContextFactory.CreateContext(); var data = await ctx.Settings.Where(s => s.Id == name).FirstOrDefaultAsync(); return data == null ? default : Deserialize<T>(data.Value); }); } public async Task UpdateSetting<T>(T obj, string? name = null) where T : class { name ??= typeof(T).FullName ?? string.Empty; await using (var ctx = _ContextFactory.CreateContext()) { var settings = UpdateSettingInContext<T>(ctx, obj, name); try { await ctx.SaveChangesAsync(); } catch (DbUpdateException) { ctx.Entry(settings).State = EntityState.Added; await ctx.SaveChangesAsync(); } } _memoryCache.Set(GetCacheKey(name), obj); _EventAggregator.Publish(new SettingsChanged<T>() { Settings = obj }); } public SettingData UpdateSettingInContext<T>(ApplicationDbContext ctx, T obj, string? name = null) where T : class { name ??= obj.GetType().FullName ?? string.Empty; _memoryCache.Remove(GetCacheKey(name)); var settings = new SettingData { Id = name, Value = Serialize(obj) }; ctx.Attach(settings); ctx.Entry(settings).State = EntityState.Modified; return settings; } private T? Deserialize<T>(string value) where T : class { return JsonConvert.DeserializeObject<T>(value); } private string Serialize<T>(T obj) { return JsonConvert.SerializeObject(obj); } private string GetCacheKey(string name) { return $"{nameof(SettingsRepository)}_{name}"; } public async Task<T> WaitSettingsChanged<T>(CancellationToken cancellationToken = default) where T : class { return (await _EventAggregator.WaitNext<SettingsChanged<T>>(cancellationToken)).Settings; } } }
36.411111
136
0.600549
[ "MIT" ]
BTCparadigm/btcpayserver
BTCPayServer/Services/SettingsRepository.cs
3,277
C#
// // Copyright (c) 2012-2016 Krueger Systems, 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; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; #pragma warning disable 1591 // XML Doc Comments namespace SQLite { public partial class SQLiteAsyncConnection { SQLiteConnectionString _connectionString; SQLiteOpenFlags _openFlags; public SQLiteAsyncConnection(string databasePath, bool storeDateTimeAsTicks = true) : this(databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks) { } public SQLiteAsyncConnection(string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true) { _openFlags = openFlags; _connectionString = new SQLiteConnectionString(databasePath, storeDateTimeAsTicks); } public static void ResetPool() { SQLiteConnectionPool.Shared.Reset(); } SQLiteConnectionWithLock GetConnection () { return SQLiteConnectionPool.Shared.GetConnection (_connectionString, _openFlags); } public Task<CreateTablesResult> CreateTableAsync<T> (CreateFlags createFlags = CreateFlags.None) where T : new () { return CreateTablesAsync (createFlags, typeof(T)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2> (CreateFlags createFlags = CreateFlags.None) where T : new () where T2 : new () { return CreateTablesAsync (createFlags, typeof (T), typeof (T2)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3> (CreateFlags createFlags = CreateFlags.None) where T : new () where T2 : new () where T3 : new () { return CreateTablesAsync (createFlags, typeof (T), typeof (T2), typeof (T3)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4> (CreateFlags createFlags = CreateFlags.None) where T : new () where T2 : new () where T3 : new () where T4 : new () { return CreateTablesAsync (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4, T5> (CreateFlags createFlags = CreateFlags.None) where T : new () where T2 : new () where T3 : new () where T4 : new () where T5 : new () { return CreateTablesAsync (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5)); } public Task<CreateTablesResult> CreateTablesAsync (CreateFlags createFlags = CreateFlags.None, params Type[] types) { return Task.Factory.StartNew (() => { CreateTablesResult result = new CreateTablesResult (); var conn = GetConnection (); using (conn.Lock ()) { foreach (Type type in types) { int aResult = conn.CreateTable (type, createFlags); result.Results[type] = aResult; } } return result; }); } public Task<int> DropTableAsync<T> () where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.DropTable<T> (); } }); } public Task<int> InsertAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Insert (item); } }); } public Task<int> InsertOrReplaceAsync(object item) { return Task.Factory.StartNew(() => { var conn = GetConnection(); using (conn.Lock()) { return conn.InsertOrReplace(item); } }); } public Task<int> UpdateAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Update (item); } }); } public Task<int> DeleteAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Delete (item); } }); } public Task<T> GetAsync<T>(object pk) where T : new() { return Task.Factory.StartNew(() => { var conn = GetConnection(); using (conn.Lock()) { return conn.Get<T>(pk); } }); } public Task<T> FindAsync<T> (object pk) where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Find<T> (pk); } }); } public Task<T> GetAsync<T> (Expression<Func<T, bool>> predicate) where T : new() { return Task.Factory.StartNew(() => { var conn = GetConnection(); using (conn.Lock()) { return conn.Get<T> (predicate); } }); } public Task<T> FindAsync<T> (Expression<Func<T, bool>> predicate) where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Find<T> (predicate); } }); } public Task<int> ExecuteAsync (string query, params object[] args) { return Task<int>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Execute (query, args); } }); } public Task<int> InsertAllAsync (IEnumerable items) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.InsertAll (items); } }); } public Task<int> UpdateAllAsync (IEnumerable items) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.UpdateAll (items); } }); } [Obsolete("Will cause a deadlock if any call in action ends up in a different thread. Use RunInTransactionAsync(Action<SQLiteConnection>) instead.")] public Task RunInTransactionAsync (Action<SQLiteAsyncConnection> action) { return Task.Factory.StartNew (() => { var conn = this.GetConnection (); using (conn.Lock ()) { conn.BeginTransaction (); try { action (this); conn.Commit (); } catch (Exception) { conn.Rollback (); throw; } } }); } public Task RunInTransactionAsync(Action<SQLiteConnection> action) { return Task.Factory.StartNew(() => { var conn = this.GetConnection(); using (conn.Lock()) { conn.BeginTransaction(); try { action(conn); conn.Commit(); } catch (Exception) { conn.Rollback(); throw; } } }); } public AsyncTableQuery<T> Table<T> () where T : new () { // // This isn't async as the underlying connection doesn't go out to the database // until the query is performed. The Async methods are on the query iteself. // var conn = GetConnection (); return new AsyncTableQuery<T> (conn.Table<T> ()); } public Task<T> ExecuteScalarAsync<T> (string sql, params object[] args) { return Task<T>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { var command = conn.CreateCommand (sql, args); return command.ExecuteScalar<T> (); } }); } public Task<List<T>> QueryAsync<T> (string sql, params object[] args) where T : new () { return Task<List<T>>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Query<T> (sql, args); } }); } } // // TODO: Bind to AsyncConnection.GetConnection instead so that delayed // execution can still work after a Pool.Reset. // public class AsyncTableQuery<T> where T : new () { TableQuery<T> _innerQuery; public AsyncTableQuery (TableQuery<T> innerQuery) { _innerQuery = innerQuery; } public AsyncTableQuery<T> Where (Expression<Func<T, bool>> predExpr) { return new AsyncTableQuery<T> (_innerQuery.Where (predExpr)); } public AsyncTableQuery<T> Skip (int n) { return new AsyncTableQuery<T> (_innerQuery.Skip (n)); } public AsyncTableQuery<T> Take (int n) { return new AsyncTableQuery<T> (_innerQuery.Take (n)); } public AsyncTableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr) { return new AsyncTableQuery<T> (_innerQuery.OrderBy<U> (orderExpr)); } public AsyncTableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr) { return new AsyncTableQuery<T> (_innerQuery.OrderByDescending<U> (orderExpr)); } public Task<List<T>> ToListAsync () { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.ToList (); } }); } public Task<int> CountAsync () { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.Count (); } }); } public Task<T> ElementAtAsync (int index) { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.ElementAt (index); } }); } public Task<T> FirstAsync () { return Task<T>.Factory.StartNew(() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.First (); } }); } public Task<T> FirstOrDefaultAsync () { return Task<T>.Factory.StartNew(() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.FirstOrDefault (); } }); } } public class CreateTablesResult { public Dictionary<Type, int> Results { get; private set; } internal CreateTablesResult () { this.Results = new Dictionary<Type, int> (); } } class SQLiteConnectionPool { class Entry { public SQLiteConnectionString ConnectionString { get; private set; } public SQLiteConnectionWithLock Connection { get; private set; } public Entry (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags) { ConnectionString = connectionString; Connection = new SQLiteConnectionWithLock (connectionString, openFlags); } public void OnApplicationSuspended () { Connection.Dispose (); Connection = null; } } readonly Dictionary<string, Entry> _entries = new Dictionary<string, Entry> (); readonly object _entriesLock = new object (); static readonly SQLiteConnectionPool _shared = new SQLiteConnectionPool (); /// <summary> /// Gets the singleton instance of the connection tool. /// </summary> public static SQLiteConnectionPool Shared { get { return _shared; } } public SQLiteConnectionWithLock GetConnection (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags) { lock (_entriesLock) { Entry entry; string key = connectionString.ConnectionString; if (!_entries.TryGetValue (key, out entry)) { entry = new Entry (connectionString, openFlags); _entries[key] = entry; } return entry.Connection; } } /// <summary> /// Closes all connections managed by this pool. /// </summary> public void Reset () { lock (_entriesLock) { foreach (var entry in _entries.Values) { entry.OnApplicationSuspended (); } _entries.Clear (); } } /// <summary> /// Call this method when the application is suspended. /// </summary> /// <remarks>Behaviour here is to close any open connections.</remarks> public void ApplicationSuspended () { Reset (); } } class SQLiteConnectionWithLock : SQLiteConnection { readonly object _lockPoint = new object (); public SQLiteConnectionWithLock (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags) : base (connectionString.DatabasePath, openFlags, connectionString.StoreDateTimeAsTicks) { } public IDisposable Lock () { return new LockWrapper (_lockPoint); } private class LockWrapper : IDisposable { object _lockPoint; public LockWrapper (object lockPoint) { _lockPoint = lockPoint; Monitor.Enter (_lockPoint); } public void Dispose () { Monitor.Exit (_lockPoint); } } } }
24.929119
151
0.655037
[ "MIT" ]
jsdelivrbot/mpos-net-sdk
PagarMe.Mpos/Tms/SQLiteAsync.cs
13,013
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Azure.Core.Http; using Azure.Core.Pipeline; namespace Azure.Core.Testing { public class RecordMatcher { private readonly RecordedTestSanitizer _sanitizer; public RecordMatcher(RecordedTestSanitizer sanitizer) { _sanitizer = sanitizer; } public HashSet<string> ExcludeHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Date", "x-ms-date", "x-ms-client-request-id", "User-Agent", "Request-Id" }; // Headers that don't indicate meaningful changes between updated recordings public HashSet<string> VolatileHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Date", "x-ms-date", "x-ms-client-request-id", "User-Agent", "Request-Id", "If-Match", "If-None-Match", "If-Modified-Since", "If-Unmodified-Since" }; // Headers that don't indicate meaningful changes between updated recordings public HashSet<string> VolatileResponseHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Date", "ETag", "Last-Modified", "x-ms-request-id", "x-ms-correlation-request-id" }; public virtual RecordEntry FindMatch(Request request, IList<RecordEntry> entries) { SortedDictionary<string, string[]> headers = new SortedDictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); foreach (var header in request.Headers) { var gotHeader = request.Headers.TryGetValues(header.Name, out IEnumerable<string> values); Debug.Assert(gotHeader); headers[header.Name] = values.ToArray(); } _sanitizer.SanitizeHeaders(headers); string uri = _sanitizer.SanitizeUri(request.UriBuilder.ToString()); int bestScore = int.MaxValue; RecordEntry bestScoreEntry = null; foreach (RecordEntry entry in entries) { int score = 0; if (!AreUrisSame(entry.RequestUri, uri)) { score++; } if (entry.RequestMethod != request.Method) { score++; } score += CompareHeaderDictionaries(headers, entry.RequestHeaders, ExcludeHeaders); if (score == 0) { return entry; } if (score < bestScore) { bestScoreEntry = entry; bestScore = score; } } throw new InvalidOperationException(GenerateException(request.Method, uri, headers, bestScoreEntry)); } public virtual bool IsEquivalentRecord(RecordEntry entry, RecordEntry otherEntry) => IsEquivalentRequest(entry, otherEntry) && IsEquivalentResponse(entry, otherEntry); protected virtual bool IsEquivalentRequest(RecordEntry entry, RecordEntry otherEntry) => entry.RequestMethod == otherEntry.RequestMethod && IsEquivalentUri(entry.RequestUri, otherEntry.RequestUri) && CompareHeaderDictionaries(entry.RequestHeaders, otherEntry.RequestHeaders, VolatileHeaders) == 0; private static bool AreUrisSame(string entryUri, string otherEntryUri) => // Some versions of .NET behave differently when calling new Uri("...") // so we'll normalize the recordings (which may have been against // a different .NET version) to be safe new Uri(entryUri).ToString() == new Uri(otherEntryUri).ToString(); protected virtual bool IsEquivalentUri(string entryUri, string otherEntryUri) => AreUrisSame(entryUri, otherEntryUri); protected virtual bool IsEquivalentResponse(RecordEntry entry, RecordEntry otherEntry) { IEnumerable<KeyValuePair<string, string[]>> entryHeaders = entry.ResponseHeaders.Where(h => !VolatileResponseHeaders.Contains(h.Key)); IEnumerable<KeyValuePair<string, string[]>> otherEntryHeaders = otherEntry.ResponseHeaders.Where(h => !VolatileResponseHeaders.Contains(h.Key)); return entry.StatusCode == otherEntry.StatusCode && entryHeaders.SequenceEqual(otherEntryHeaders, new HeaderComparer()) && IsBodyEquivalent(entry, otherEntry); } protected virtual bool IsBodyEquivalent(RecordEntry record, RecordEntry otherRecord) { return (record.ResponseBody ?? Array.Empty<byte>()).AsSpan() .SequenceEqual((otherRecord.ResponseBody ?? Array.Empty<byte>())); } private string GenerateException(RequestMethod requestMethod, string uri, SortedDictionary<string, string[]> headers, RecordEntry bestScoreEntry) { StringBuilder builder = new StringBuilder(); builder.AppendLine($"Unable to find a record for the request {requestMethod} {uri}"); if (bestScoreEntry == null) { builder.AppendLine("No records to match."); return builder.ToString(); } if (requestMethod != bestScoreEntry.RequestMethod) { builder.AppendLine($"Method doesn't match, request <{requestMethod}> record <{bestScoreEntry.RequestMethod}>"); } if (!AreUrisSame(uri, bestScoreEntry.RequestUri)) { builder.AppendLine("Uri doesn't match:"); builder.AppendLine($" request <{uri}>"); builder.AppendLine($" record <{bestScoreEntry.RequestUri}>"); } builder.AppendLine("Header differences:"); CompareHeaderDictionaries(headers, bestScoreEntry.RequestHeaders, ExcludeHeaders, builder); return builder.ToString(); } private string JoinHeaderValues(string[] values) { return string.Join(",", values); } private int CompareHeaderDictionaries(SortedDictionary<string, string[]> headers, SortedDictionary<string, string[]> entryHeaders, HashSet<string> ignoredHeaders, StringBuilder descriptionBuilder = null) { int difference = 0; var remaining = new SortedDictionary<string, string[]>(entryHeaders, entryHeaders.Comparer); foreach (KeyValuePair<string, string[]> header in headers) { if (remaining.TryGetValue(header.Key, out string[] values)) { remaining.Remove(header.Key); if (!ignoredHeaders.Contains(header.Key) && !values.SequenceEqual(header.Value)) { difference++; descriptionBuilder?.AppendLine($" <{header.Key}> values differ, request <{JoinHeaderValues(header.Value)}>, record <{JoinHeaderValues(values)}>"); } } else if (!ignoredHeaders.Contains(header.Key)) { difference++; descriptionBuilder?.AppendLine($" <{header.Key}> is absent in record, value <{JoinHeaderValues(header.Value)}>"); } } foreach (KeyValuePair<string, string[]> header in remaining) { if (!ignoredHeaders.Contains(header.Key)) { difference++; descriptionBuilder?.AppendLine($" <{header.Key}> is absent in request, value <{JoinHeaderValues(header.Value)}>"); } } return difference; } private class HeaderComparer : IEqualityComparer<KeyValuePair<string, string[]>> { public bool Equals(KeyValuePair<string, string[]> x, KeyValuePair<string, string[]> y) { return x.Key.Equals(y.Key, StringComparison.OrdinalIgnoreCase) && x.Value.SequenceEqual(y.Value); } public int GetHashCode(KeyValuePair<string, string[]> obj) { return obj.GetHashCode(); } } } }
38.617778
211
0.577627
[ "MIT" ]
Only2125/azure-sdk-for-net
sdk/core/Azure.Core/tests/TestFramework/RecordMatcher.cs
8,691
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 16.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete2__objs.TimeOnly.String{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.TimeOnly; using T_DATA2 =System.String; using T_DATA1_U=System.TimeOnly; using T_DATA2_U=System.String; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__02__VN public static class TestSet_504__param__02__VN { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1233)).Add(new System.TimeSpan(900)); T_DATA2 vv2=null; var recs=db.testTable.Where(r => ((object)vv1) /*OP{*/ != /*}OP*/ ((object)vv2)); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1233)).Add(new System.TimeSpan(900)); T_DATA2 vv2=null; var recs=db.testTable.Where(r => !(((object)vv1) /*OP{*/ != /*}OP*/ ((object)vv2))); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 };//class TestSet_504__param__02__VN //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete2__objs.TimeOnly.String
27.421429
138
0.544152
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/NotEqual/Complete2__objs/TimeOnly/String/TestSet_504__param__02__VN.cs
3,841
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.Editors.PropertyPages; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestTools.MockObjects; using Microsoft.VisualStudio.Editors.UnitTests.Mocks; using Microsoft.VisualStudio.Editors.UnitTests.PropertyPages.Mocks; using System.Windows.Forms; using System.Reflection; using Microsoft.VisualStudio.Editors.ApplicationDesigner; namespace Microsoft.VisualStudio.Editors.UnitTests.PropertyPages { /// <summary> /// UNDONE /// This provides a base set of support for implementing complex unit test for property pages. /// Actually, they really support something more than traditional unit tests, it's more like /// running the full property page inside a faked VS environment, so that user interactions, /// property changes, SCC, errors, undo/redo, etc., can all be tested easily in the unit /// test environment. /// /// Your property page test should inherit from either BaseTestClassForPropertyPages_ConfigDependent /// or BaseTestClassForPropertyPages_NonConfigDependent. /// /// See ApplicationPropPageVBWPFTests for examples of how to put this together and how to /// modify the expectations and functionality of the supporting mocks/fakes. /// </summary> abstract class FakePropertyPageHosting_Base : IDisposable { #region Per-TestMethod fields public object[] Fake_objects; public VsHierarchyFake Fake_hierarchy; public PropertyPageSiteFake Fake_site; public DTEFake Fake_dte; public PropertyPageSiteOwnerFake Fake_propertyPageSiteOwner; public ComPropertyPageFake Fake_comPropertyPage; //of type ComPropertyPageFake - Can't define it as public because that would be exposing a friend interface via a public class, sigh. public ProjectPropertiesFake Fake_projectProperties { get { return Fake_hierarchy.Fake_projectProperties; } } #endregion abstract public void InitializePageForUnitTests(PropPageUserControlBase page); #region Support for fake user events public void Fake_FireControlEvent(Control control, string eventName, EventArgs eventArgs) { MethodInfo onEventMethod = control.GetType().GetMethod("On" + eventName, System.Reflection.BindingFlags.NonPublic | BindingFlags.Instance); if (onEventMethod == null) { MessageBox.Show("Couldn't find OnXXX method for event " + eventName); throw new InvalidOperationException(); } onEventMethod.Invoke(control, new object[] { eventArgs }); } /// <summary> /// Sets a control's text on the property page, making sure that the normal /// events get fired (or at least that the page thinks they get fired), to /// mimic a user's having typed in text and committed it. /// </summary> /// <param name="textbox"></param> /// <param name="value"></param> public void Fake_TypeTextIntoControl(TextBox textbox, string value) { Fake_TypeTextIntoControl(textbox, value, false); } /// <summary> /// Sets a control's text on the property page, making sure that the normal /// events get fired (or at least that the page thinks they get fired), to /// mimic a user's having typed in text and committed it. /// </summary> /// <param name="textbox"></param> /// <param name="value"></param> public void Fake_TypeTextIntoControl(TextBox textbox, string value, bool doNotCommit) { textbox.Text = value; // This will fire TextChanged if (!doNotCommit) { // To make the control commit, we need to fire LostFocus (we can't do this // directly because you can't set focus to non-visible controls. Fake_FireControlEvent(textbox, "LostFocus", EventArgs.Empty); } } public void Fake_SelectItemInComboBox(ComboBox combobox, string itemDisplayText) { foreach (object item in combobox.Items) { if (item.ToString().Equals(itemDisplayText, StringComparison.OrdinalIgnoreCase)) { combobox.SelectedItem = item; Fake_FireControlEvent(combobox, "SelectionChangeCommitted", EventArgs.Empty); return; } } throw new Exception("Couldn't find specified entry '" + itemDisplayText + "'in the combobox"); } public void Fake_DropDownCombobox(ComboBox combobox) { Fake_FireControlEvent(combobox, "DropDown", EventArgs.Empty); } public string[] Fake_GetDisplayTextOfItemsInCombobox(ComboBox combobox) { List<string> items = new List<string>(); foreach (object item in combobox.Items) { items.Add(item.ToString()); } return items.ToArray(); } /// <summary> /// Create an expectation that a messagebox is shown with the given exception type /// </summary> /// <param name="exceptionType"></param> /// <param name="helpLink"></param> public void Fake_ExpectMsgBox(Type exceptionType, string helpLink) { ((PropertyPageSiteOwnerFake)Fake_propertyPageSiteOwner).Fake_msgBoxes.ExpectMsgBox( exceptionType, helpLink); } #endregion #region IDisposable Members public void Dispose() { if (Fake_propertyPageSiteOwner != null && Fake_propertyPageSiteOwner is IDisposable) { ((IDisposable)Fake_propertyPageSiteOwner).Dispose(); } } #endregion #region Project flavor support protected string ProjectExtenderName = "MyFakeProjectExtender"; protected abstract void Fake_EnsureProjectExtenderAdded(); public void Fake_Flavor_SetAllPropertiesToHidden() { Fake_EnsureProjectExtenderAdded(); Fake_site.Fake_objectExtenders.Fake_RegisteredExtenders[ProjectExtenderName].PropertyFilterOptions.AllPropertiesAreHidden = true; } public void Fake_Flavor_SetPropertyToHidden(string propertyName) { Fake_EnsureProjectExtenderAdded(); Fake_site.Fake_objectExtenders.Fake_RegisteredExtenders[ProjectExtenderName] .PropertyFilterOptions.HiddenPropertyNames.Add(propertyName); } public void Fake_Flavor_SetAllPropertiesToReadOnly() { Fake_EnsureProjectExtenderAdded(); Fake_site.Fake_objectExtenders.Fake_RegisteredExtenders[ProjectExtenderName] .PropertyFilterOptions.AllPropertiesAreReadOnly = true; } public void Fake_Flavor_SetPropertyToReadOnly(string propertyName) { Fake_EnsureProjectExtenderAdded(); Fake_site.Fake_objectExtenders.Fake_RegisteredExtenders[ProjectExtenderName] .PropertyFilterOptions.ReadOnlyPropertyNames.Add(propertyName); } #endregion } }
39.520619
190
0.654754
[ "Apache-2.0" ]
jasonmalinowski/project-system
src/Microsoft.VisualStudio.Editor.UnitTests/PropertyPages/Mocks/FakePropertyPageHosting/FakePropertyPageHosting_Base.cs
7,667
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using JsonPatch.Paths; namespace JsonPatch { public class JsonPatchDocument<TEntity> : IJsonPatchDocument where TEntity : class, new() { private List<JsonPatchOperation> _operations = new List<JsonPatchOperation>(); public List<JsonPatchOperation> Operations { get { return _operations; } } public void Add(string path, object value) { _operations.Add(new JsonPatchOperation { Operation = JsonPatchOperationType.add, Path = path, ParsedPath = PathHelper.ParsePath(path, typeof(TEntity)), Value = value }); } public void Replace(string path, object value) { _operations.Add(new JsonPatchOperation { Operation = JsonPatchOperationType.replace, Path = path, ParsedPath = PathHelper.ParsePath(path, typeof(TEntity)), Value = value }); } public void Remove(string path) { _operations.Add(new JsonPatchOperation { Operation = JsonPatchOperationType.remove, Path = path, ParsedPath = PathHelper.ParsePath(path, typeof(TEntity)) }); } public void Move(string from, string path) { _operations.Add(new JsonPatchOperation { Operation = JsonPatchOperationType.move, FromPath = from, ParsedFromPath = PathHelper.ParsePath(from, typeof(TEntity)), Path = path, ParsedPath = PathHelper.ParsePath(path, typeof(TEntity)), }); } public void ApplyUpdatesTo(TEntity entity) { foreach (var operation in _operations) { switch (operation.Operation) { case JsonPatchOperationType.remove: PathHelper.SetValueFromPath(typeof(TEntity), operation.ParsedPath, entity, null, JsonPatchOperationType.remove); break; case JsonPatchOperationType.replace: PathHelper.SetValueFromPath(typeof(TEntity), operation.ParsedPath, entity, operation.Value, JsonPatchOperationType.replace); break; case JsonPatchOperationType.add: PathHelper.SetValueFromPath(typeof(TEntity), operation.ParsedPath, entity, operation.Value, JsonPatchOperationType.add); break; case JsonPatchOperationType.move: var value = PathHelper.GetValueFromPath(typeof(TEntity), operation.ParsedFromPath, entity); PathHelper.SetValueFromPath(typeof(TEntity), operation.ParsedFromPath, entity, null, JsonPatchOperationType.remove); PathHelper.SetValueFromPath(typeof(TEntity), operation.ParsedPath, entity, value, JsonPatchOperationType.add); break; default: throw new NotSupportedException("Operation not supported: " + operation.Operation); } } } } }
38.460674
148
0.569968
[ "MIT" ]
mindingdata/JsonPatch
src/JsonPatch/JsonPatchDocument.cs
3,425
C#
/* Copyright (C) 2019 Alex Watt (alexwatt@hotmail.com) This file is part of Highlander Project https://github.com/alexanderwatt/Hghlander.Net Highlander is free software: you can redistribute it and/or modify it under the terms of the Highlander license. You should have received a copy of the license along with this program; if not, license is available at <https://github.com/alexanderwatt/Hghlander.Net/blob/develop/LICENSE>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ using System; namespace FpML.V5r10.Reporting.Models.Futures { public interface IFuturesAssetParameters { /// <summary> /// Flag that sets whether the contract is deliverable. /// </summary> Boolean IsDeliverable{ get; set; } /// <summary> /// The starting npv. /// </summary> Decimal BaseNPV { get; set; } /// <summary> /// Gets or sets the quote. /// </summary> /// <value>The quote.</value> Decimal Quote { get; set; } /// <summary> /// Gets or sets the number. /// </summary> /// <value>The number.</value> int NumberOfContracts { get; set; } /// <summary> /// Gets or sets the trade price. /// </summary> /// <value>The trade price.</value> Decimal TradePrice { get; set; } /// <summary> /// Gets or sets the multiplier. /// </summary> /// <value>The multiplier.</value> Decimal Multiplier { get; set; } /// <summary> /// The accrual period as a decimal. /// </summary> Decimal AccrualPeriod { get; set; } /// <summary> /// Gets or sets the contract notional. /// </summary> /// <value>The contract notional.</value> Decimal ContractNotional { get; set; } /// <summary> /// Gets or sets the settlement discount factor. /// </summary> /// <value>The quote.</value> Decimal SettlementDiscountFactor { get; set; } } }
30.684932
87
0.591071
[ "BSD-3-Clause" ]
mmrath/Highlander.Net
Metadata/FpML.V5r10/FpML.V5r10.Reporting.Models/Futures/IFuturesAssetParameters.cs
2,242
C#
using System.Collections.Generic; namespace TestNinja.Fundamentals { public class Math { public int Add(int a, int b) { if (a == b) { return a; } return a + b; } public int Sub(int a, int b) { if (a == b) { return a - b; } if (a > b) { return a - b; } return b - a; } public int Multiply(int a, int b) { return a * b; } public int Divide(int a, int b) { if (b == 0) { b = 1; } return a / b; } public int Max(int a, int b) { return a >= b ? a : b; } public IEnumerable<int> GetOddNumbers(int limit) { for (var i = 0; i <= limit; i++) if (i % 2 != 0) yield return i; } public IEnumerable<int> GetEvenNumbers(int limit) { for (var i = 0; i <= limit; i++) if (i % 2 == 0) yield return i; } } }
18.863636
57
0.330924
[ "MIT" ]
mdaniyalkhann/SampleTests
TestNinjaCore/Fundamentals/Math.cs
1,245
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public const float JUMP_FORCE = 8f; private Rigidbody2D rigidBody; public LayerMask groundMask; //Creamos una variable LayerMask que referiense a la capa del suelo private Animator anim; private const string STATE_ALIVE = "isAlive"; private const string STATE_ON_THE_GROUND = "isOnTheGround"; public float runningSpeed = 2.0f; private SpriteRenderer spriteRender; Vector3 startPosition; [SerializeField] //A pesar de que sea una variable privado con esto la podemos ver en el editor de unity private int healthPoints, manaPoints; public const int INITIAL_HEALTH = 100, INITIAL_MANA = 15, MAX_HEALTH = 200, MAX_MANA = 30, MIN_HEALTH = 0, MIN_MANA = 0; public const int SUPERJUMP_COST = 15; public const float SUPERJUMP_FORCE = 1.5F; private void Awake() { rigidBody = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); spriteRender = GetComponent<SpriteRenderer>(); healthPoints = 50; } // Start is called before the first frame update void Start() { startPosition = this.transform.position; } // Update is called once per frame void Update() { Debug.DrawRay(this.transform.position, Vector2.down * 1.5f, Color.green); if (GameManager.sharedInstance.currentGameState == GameState.inGame) { if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0)) { Jump(false); } if (Input.GetKeyDown(KeyCode.E)) { Jump(true); } } anim.SetBool(STATE_ON_THE_GROUND, IsTouchingTheGround()); if (healthPoints <= 0) { Die(); } } void Jump(bool superJump) { float jumpForceFactor = JUMP_FORCE; if (superJump && manaPoints>=SUPERJUMP_COST) { manaPoints -= SUPERJUMP_COST; jumpForceFactor *= SUPERJUMP_FORCE; } if (IsTouchingTheGround()) { rigidBody.AddForce(Vector2.up * jumpForceFactor, ForceMode2D.Impulse); GetComponent<AudioSource>().Play(); } } private void FixedUpdate() { if (GameManager.sharedInstance.currentGameState == GameState.inGame) { if (rigidBody.velocity.x < runningSpeed) { if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) { rigidBody.velocity = new Vector2(runningSpeed, rigidBody.velocity.y); spriteRender.flipX = false; } if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) { rigidBody.velocity = new Vector2(-runningSpeed, rigidBody.velocity.y); spriteRender.flipX = true; } } } } //Nos devuelve un booleano para saber si el personaje esta tocando o no el suelo bool IsTouchingTheGround() { if (Physics2D.Raycast(this.transform.position, Vector2.down,1.5f, groundMask)) //origen direccion distancia maxima y layerMask { return true; } else { return false; } } public void Die() { this.anim.SetBool(STATE_ALIVE, false); GameManager.sharedInstance.GameOver(); } public void StartGame() { anim.SetBool(STATE_ALIVE, true); anim.SetBool(STATE_ON_THE_GROUND, true); Invoke("RestartPosition", 0.4f); healthPoints = INITIAL_HEALTH; manaPoints = INITIAL_MANA; } void RestartPosition() { this.transform.position = startPosition; rigidBody.velocity = Vector2.zero; GameObject mainCamera = GameObject.Find("Main Camera"); mainCamera.GetComponent<CameraFollow>().ResetCameraPosition(); } public void CollectHealth(int points) { this.healthPoints += points; if (healthPoints >= MAX_HEALTH) { healthPoints = MAX_HEALTH; } } public void CollectMana(int points) { this.manaPoints += points; if (manaPoints >= MAX_MANA) { manaPoints = MAX_MANA; } } public int GetHealth() { return healthPoints; } public int GetMana() { return manaPoints; } }
29.477707
134
0.583405
[ "MIT" ]
alexFiorenza/SpaceMan-Game
SpaceMan Platzi/Assets/Scripts/PlayerController.cs
4,630
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200301.Outputs { /// <summary> /// Describes the connection monitor endpoint. /// </summary> [OutputType] public sealed class ConnectionMonitorEndpointResponse { /// <summary> /// Address of the connection monitor endpoint (IP or domain name). /// </summary> public readonly string? Address; /// <summary> /// Filter for sub-items within the endpoint. /// </summary> public readonly Outputs.ConnectionMonitorEndpointFilterResponse? Filter; /// <summary> /// The name of the connection monitor endpoint. /// </summary> public readonly string Name; /// <summary> /// Resource ID of the connection monitor endpoint. /// </summary> public readonly string? ResourceId; [OutputConstructor] private ConnectionMonitorEndpointResponse( string? address, Outputs.ConnectionMonitorEndpointFilterResponse? filter, string name, string? resourceId) { Address = address; Filter = filter; Name = name; ResourceId = resourceId; } } }
29.132075
81
0.61658
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20200301/Outputs/ConnectionMonitorEndpointResponse.cs
1,544
C#
using System.Threading; using System.Threading.Tasks; using Mediator.Net.Context; using Mediator.Net.Contracts; using Mediator.Net.TestUtil.Messages; using Mediator.Net.TestUtil.TestUtils; namespace Mediator.Net.TestUtil.Handlers.EventHandlers { public class DerivedEventHandler : IEventHandler<DerivedEvent> { public Task Handle(IReceiveContext<DerivedEvent> context, CancellationToken cancellationToken) { RubishBox.Rublish.Add(nameof(DerivedEventHandler)); return Task.FromResult(1); } } }
29.210526
102
0.740541
[ "Apache-2.0" ]
JiaZhenLin/Mediator.Net
src/Mediator.Net.TestUtil/Handlers/EventHandlers/DerivedEventHandler.cs
557
C#
using Catalog.API.Entities; using Catalog.API.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Catalog.API.Controllers { [ApiController] [Route("api/v1/[controller]")] public class CatalogController : ControllerBase { private readonly IProductRepository _repository; private readonly ILogger<CatalogController> _logger; public CatalogController(IProductRepository repository, ILogger<CatalogController> logger) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } [HttpGet] [ProducesResponseType(typeof(IEnumerable<Product>), StatusCodes.Status200OK)] public async Task<ActionResult<IEnumerable<Product>>> GetProducts() { var products = await _repository.GetProducts(); return Ok(products); } [HttpGet("{id:length(24)}", Name = "GetProduct")] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(Product), StatusCodes.Status200OK)] public async Task<ActionResult<Product>> GetProductById(string id) { var product = await _repository.GetProduct(id); if (product is null) { _logger.LogError($"Product with id: {id}, not found."); return NotFound(); } return Ok(product); } [Route("[action]/{category}", Name = "GetProductByCategory")] [HttpGet] [ProducesResponseType(typeof(IEnumerable<Product>), StatusCodes.Status200OK)] public async Task<ActionResult<IEnumerable<Product>>> GetProductByCategory(string category) { var products = await _repository.GetProductByCategory(category); return Ok(products); } [HttpPost] [ProducesResponseType(typeof(Product), StatusCodes.Status200OK)] public async Task<ActionResult<Product>> CreateProduct([FromBody] Product product) { await _repository.CreateProduct(product); return CreatedAtRoute("GetProduct", new { id = product.Id }, product); } [HttpPut] [ProducesResponseType(typeof(Product), StatusCodes.Status200OK)] public async Task<IActionResult> Update(Product product) { return Ok(await _repository.UpdateProduct(product)); } [HttpDelete("{id:length(24)}", Name = "DeleteProduct")] [ProducesResponseType(typeof(Product), StatusCodes.Status200OK)] public async Task<IActionResult> DeleteProductById(string id) { return Ok(await _repository.DeleteProduct(id)); } } }
34.752941
100
0.652674
[ "MIT" ]
GC-Learning/netcore-microservices
src/Services/Catalog/Catalog.API/Controllers/CatalogController.cs
2,956
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Remutable.Tests { [TestClass] public class InheritedPropertiesTests { [TestMethod] public void TestBaseInheritedProperty1_Success() { var instance = new InheritedType4("prop1", "prop2", "prop3", "prop4"); var actual = Remute.Default.With(instance, x => x.Prop1, "update"); Assert.AreEqual("update", actual.Prop1); Assert.AreEqual(instance.Prop2, actual.Prop2); Assert.AreEqual(instance.Prop3, actual.Prop3); Assert.AreEqual(instance.Prop4, actual.Prop4); } [TestMethod] public void TestBaseInheritedProperty2_Success() { var instance = new InheritedType4("prop1", "prop2", "prop3", "prop4"); var actual = Remute.Default.With(instance, x => x.Prop4, "update"); Assert.AreEqual("update", actual.Prop4); Assert.AreEqual(instance.Prop1, actual.Prop1); Assert.AreEqual(instance.Prop2, actual.Prop2); Assert.AreEqual(instance.Prop3, actual.Prop3); } [TestMethod] public void TestConfig_Success() { var config = new ActivationConfiguration() .Configure<InheritedType4>(x => new InheritedType4(x.Prop1, x.Prop2, x.Prop3, x.Prop4)); var remute = new Remute(config); var instance = new InheritedType4("prop1", "prop2", "prop3", "prop4"); var actual = remute.With(instance, x => x.Prop1, "update"); Assert.AreEqual("update", actual.Prop1); Assert.AreEqual(instance.Prop2, actual.Prop2); Assert.AreEqual(instance.Prop3, actual.Prop3); Assert.AreEqual(instance.Prop4, actual.Prop4); } } }
41.090909
104
0.606195
[ "MIT" ]
ababik/Remute
Remute.Tests/InheritedPropertiesTests.cs
1,808
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.RecoveryServices.Outputs { /// <summary> /// InMageAzureV2 provider specific settings /// </summary> [OutputType] public sealed class InMageAzureV2ReplicationDetailsResponse { /// <summary> /// Agent expiry date. /// </summary> public readonly string? AgentExpiryDate; /// <summary> /// The agent version. /// </summary> public readonly string? AgentVersion; /// <summary> /// Azure VM Disk details. /// </summary> public readonly ImmutableArray<Outputs.AzureVmDiskDetailsResponse> AzureVMDiskDetails; /// <summary> /// The compressed data change rate in MB. /// </summary> public readonly double? CompressedDataRateInMB; /// <summary> /// The data stores of the on-premise machine. Value can be list of strings that contain data store names. /// </summary> public readonly ImmutableArray<string> Datastores; /// <summary> /// A value indicating the discovery type of the machine. Value can be vCenter or physical. /// </summary> public readonly string? DiscoveryType; /// <summary> /// A value indicating whether any disk is resized for this VM. /// </summary> public readonly string? DiskResized; /// <summary> /// The selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum. /// </summary> public readonly string? EnableRdpOnTargetOption; /// <summary> /// The infrastructure VM Id. /// </summary> public readonly string? InfrastructureVmId; /// <summary> /// Gets the Instance type. /// Expected value is 'InMageAzureV2'. /// </summary> public readonly string InstanceType; /// <summary> /// The source IP address. /// </summary> public readonly string? IpAddress; /// <summary> /// A value indicating whether installed agent needs to be updated. /// </summary> public readonly string? IsAgentUpdateRequired; /// <summary> /// A value indicating whether the source server requires a restart after update. /// </summary> public readonly string? IsRebootAfterUpdateRequired; /// <summary> /// The last heartbeat received from the source server. /// </summary> public readonly string? LastHeartbeat; /// <summary> /// The last RPO calculated time. /// </summary> public readonly string? LastRpoCalculatedTime; /// <summary> /// The last update time received from on-prem components. /// </summary> public readonly string? LastUpdateReceivedTime; /// <summary> /// License Type of the VM to be used. /// </summary> public readonly string? LicenseType; /// <summary> /// The master target Id. /// </summary> public readonly string? MasterTargetId; /// <summary> /// The multi vm group Id. /// </summary> public readonly string? MultiVmGroupId; /// <summary> /// The multi vm group name. /// </summary> public readonly string? MultiVmGroupName; /// <summary> /// A value indicating whether multi vm sync is enabled or disabled. /// </summary> public readonly string? MultiVmSyncStatus; /// <summary> /// The id of the disk containing the OS. /// </summary> public readonly string? OsDiskId; /// <summary> /// The type of the OS on the VM. /// </summary> public readonly string? OsType; /// <summary> /// The OS Version of the protected item. /// </summary> public readonly string? OsVersion; /// <summary> /// The process server Id. /// </summary> public readonly string? ProcessServerId; /// <summary> /// The process server name. /// </summary> public readonly string ProcessServerName; /// <summary> /// The list of protected disks. /// </summary> public readonly ImmutableArray<Outputs.InMageAzureV2ProtectedDiskDetailsResponse> ProtectedDisks; /// <summary> /// The list of protected managed disks. /// </summary> public readonly ImmutableArray<Outputs.InMageAzureV2ManagedDiskDetailsResponse> ProtectedManagedDisks; /// <summary> /// The protection stage. /// </summary> public readonly string? ProtectionStage; /// <summary> /// The recovery availability set Id. /// </summary> public readonly string? RecoveryAvailabilitySetId; /// <summary> /// The ARM id of the log storage account used for replication. This will be set to null if no log storage account was provided during enable protection. /// </summary> public readonly string? RecoveryAzureLogStorageAccountId; /// <summary> /// The target resource group Id. /// </summary> public readonly string? RecoveryAzureResourceGroupId; /// <summary> /// The recovery Azure storage account. /// </summary> public readonly string? RecoveryAzureStorageAccount; /// <summary> /// Recovery Azure given name. /// </summary> public readonly string? RecoveryAzureVMName; /// <summary> /// The Recovery Azure VM size. /// </summary> public readonly string? RecoveryAzureVMSize; /// <summary> /// The replica id of the protected item. /// </summary> public readonly string? ReplicaId; /// <summary> /// The resync progress percentage. /// </summary> public readonly int? ResyncProgressPercentage; /// <summary> /// The RPO in seconds. /// </summary> public readonly double? RpoInSeconds; /// <summary> /// The selected recovery azure network Id. /// </summary> public readonly string? SelectedRecoveryAzureNetworkId; /// <summary> /// The selected source nic Id which will be used as the primary nic during failover. /// </summary> public readonly string? SelectedSourceNicId; /// <summary> /// The test failover virtual network. /// </summary> public readonly string? SelectedTfoAzureNetworkId; /// <summary> /// The CPU count of the VM on the primary side. /// </summary> public readonly int? SourceVmCpuCount; /// <summary> /// The RAM size of the VM on the primary side. /// </summary> public readonly int? SourceVmRamSizeInMB; /// <summary> /// The target availability zone. /// </summary> public readonly string? TargetAvailabilityZone; /// <summary> /// The target proximity placement group Id. /// </summary> public readonly string? TargetProximityPlacementGroupId; /// <summary> /// The ARM Id of the target Azure VM. This value will be null until the VM is failed over. Only after failure it will be populated with the ARM Id of the Azure VM. /// </summary> public readonly string? TargetVmId; /// <summary> /// The uncompressed data change rate in MB. /// </summary> public readonly double? UncompressedDataRateInMB; /// <summary> /// A value indicating whether managed disks should be used during failover. /// </summary> public readonly string? UseManagedDisks; /// <summary> /// The vCenter infrastructure Id. /// </summary> public readonly string? VCenterInfrastructureId; /// <summary> /// The validation errors of the on-premise machine Value can be list of validation errors. /// </summary> public readonly ImmutableArray<Outputs.HealthErrorResponse> ValidationErrors; /// <summary> /// The OS disk VHD name. /// </summary> public readonly string? VhdName; /// <summary> /// The virtual machine Id. /// </summary> public readonly string? VmId; /// <summary> /// The PE Network details. /// </summary> public readonly ImmutableArray<Outputs.VMNicDetailsResponse> VmNics; /// <summary> /// The protection state for the vm. /// </summary> public readonly string? VmProtectionState; /// <summary> /// The protection state description for the vm. /// </summary> public readonly string? VmProtectionStateDescription; [OutputConstructor] private InMageAzureV2ReplicationDetailsResponse( string? agentExpiryDate, string? agentVersion, ImmutableArray<Outputs.AzureVmDiskDetailsResponse> azureVMDiskDetails, double? compressedDataRateInMB, ImmutableArray<string> datastores, string? discoveryType, string? diskResized, string? enableRdpOnTargetOption, string? infrastructureVmId, string instanceType, string? ipAddress, string? isAgentUpdateRequired, string? isRebootAfterUpdateRequired, string? lastHeartbeat, string? lastRpoCalculatedTime, string? lastUpdateReceivedTime, string? licenseType, string? masterTargetId, string? multiVmGroupId, string? multiVmGroupName, string? multiVmSyncStatus, string? osDiskId, string? osType, string? osVersion, string? processServerId, string processServerName, ImmutableArray<Outputs.InMageAzureV2ProtectedDiskDetailsResponse> protectedDisks, ImmutableArray<Outputs.InMageAzureV2ManagedDiskDetailsResponse> protectedManagedDisks, string? protectionStage, string? recoveryAvailabilitySetId, string? recoveryAzureLogStorageAccountId, string? recoveryAzureResourceGroupId, string? recoveryAzureStorageAccount, string? recoveryAzureVMName, string? recoveryAzureVMSize, string? replicaId, int? resyncProgressPercentage, double? rpoInSeconds, string? selectedRecoveryAzureNetworkId, string? selectedSourceNicId, string? selectedTfoAzureNetworkId, int? sourceVmCpuCount, int? sourceVmRamSizeInMB, string? targetAvailabilityZone, string? targetProximityPlacementGroupId, string? targetVmId, double? uncompressedDataRateInMB, string? useManagedDisks, string? vCenterInfrastructureId, ImmutableArray<Outputs.HealthErrorResponse> validationErrors, string? vhdName, string? vmId, ImmutableArray<Outputs.VMNicDetailsResponse> vmNics, string? vmProtectionState, string? vmProtectionStateDescription) { AgentExpiryDate = agentExpiryDate; AgentVersion = agentVersion; AzureVMDiskDetails = azureVMDiskDetails; CompressedDataRateInMB = compressedDataRateInMB; Datastores = datastores; DiscoveryType = discoveryType; DiskResized = diskResized; EnableRdpOnTargetOption = enableRdpOnTargetOption; InfrastructureVmId = infrastructureVmId; InstanceType = instanceType; IpAddress = ipAddress; IsAgentUpdateRequired = isAgentUpdateRequired; IsRebootAfterUpdateRequired = isRebootAfterUpdateRequired; LastHeartbeat = lastHeartbeat; LastRpoCalculatedTime = lastRpoCalculatedTime; LastUpdateReceivedTime = lastUpdateReceivedTime; LicenseType = licenseType; MasterTargetId = masterTargetId; MultiVmGroupId = multiVmGroupId; MultiVmGroupName = multiVmGroupName; MultiVmSyncStatus = multiVmSyncStatus; OsDiskId = osDiskId; OsType = osType; OsVersion = osVersion; ProcessServerId = processServerId; ProcessServerName = processServerName; ProtectedDisks = protectedDisks; ProtectedManagedDisks = protectedManagedDisks; ProtectionStage = protectionStage; RecoveryAvailabilitySetId = recoveryAvailabilitySetId; RecoveryAzureLogStorageAccountId = recoveryAzureLogStorageAccountId; RecoveryAzureResourceGroupId = recoveryAzureResourceGroupId; RecoveryAzureStorageAccount = recoveryAzureStorageAccount; RecoveryAzureVMName = recoveryAzureVMName; RecoveryAzureVMSize = recoveryAzureVMSize; ReplicaId = replicaId; ResyncProgressPercentage = resyncProgressPercentage; RpoInSeconds = rpoInSeconds; SelectedRecoveryAzureNetworkId = selectedRecoveryAzureNetworkId; SelectedSourceNicId = selectedSourceNicId; SelectedTfoAzureNetworkId = selectedTfoAzureNetworkId; SourceVmCpuCount = sourceVmCpuCount; SourceVmRamSizeInMB = sourceVmRamSizeInMB; TargetAvailabilityZone = targetAvailabilityZone; TargetProximityPlacementGroupId = targetProximityPlacementGroupId; TargetVmId = targetVmId; UncompressedDataRateInMB = uncompressedDataRateInMB; UseManagedDisks = useManagedDisks; VCenterInfrastructureId = vCenterInfrastructureId; ValidationErrors = validationErrors; VhdName = vhdName; VmId = vmId; VmNics = vmNics; VmProtectionState = vmProtectionState; VmProtectionStateDescription = vmProtectionStateDescription; } } }
35.683698
172
0.609573
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/RecoveryServices/Outputs/InMageAzureV2ReplicationDetailsResponse.cs
14,666
C#
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.IO; using Amazon.IonDotnet.Internals.Text; using Amazon.IonDotnet.Tests.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Amazon.IonDotnet.Tests.Internals { [TestClass] public class TextReaderTimestampTest { [TestMethod] public void Date_2000_11_20_8_20_15_Unknown() { var data = DirStructure.OwnTestFileAsBytes("text/ts_2000_11_20_8_20_15_unknown.ion"); IIonReader reader = new UserTextReader(new MemoryStream(data)); ReaderTimestampCommon.Date_2000_11_20_8_20_15_Unknown(reader); } /// <summary> /// Test the date string with >14 offset. /// </summary> /// <param name="dateString"></param> /// <param name="expectedDateString"></param> [DataRow("1857-05-30T19:24:59.1+23:59", "1857-05-29T19:25:59.1Z")] [TestMethod] public void Date_LargeOffset(string dateString, string expectedDateString) { var date = Timestamp.Parse(dateString); var expectedDate = Timestamp.Parse(expectedDateString); Assert.IsTrue(date.LocalOffset >= -14 * 60 && date.LocalOffset <= 14 * 60); Assert.IsTrue(date.Equals(expectedDate)); } /// <summary> /// Test local timezone offset /// </summary> /// <param name="dateString"></param> /// <param name="expectedLocalOffset"> Time zone offset in minutes</param> /// <param name="expectedTimeOffset"></param> [DataRow("2010-10-10T03:20+02:12", +(2 * 60 + 12), "3:20:00 AM +02:12")] [DataRow("2010-10-10T03:20-02:12", -(2 * 60 + 12), "3:20:00 AM -02:12")] [DataRow("2010-10-10T03:20+00:12", +(0 * 60 + 12), "3:20:00 AM +00:12")] [DataRow("2010-10-10T03:20+02:00", +(2 * 60 + 00), "3:20:00 AM +02:00")] [TestMethod] public void TimeZone_Hour_Minute(string dateString, int expectedLocalOffset, string expectedTimeOffset) { var date = Timestamp.Parse(dateString); var localOffset = date.LocalOffset; var LocalDateTime = ExtractTimeAndTimeZone(date.AsDateTimeOffset()); Assert.AreEqual(expectedLocalOffset, localOffset); Assert.AreEqual(expectedTimeOffset, LocalDateTime); } private string ExtractTimeAndTimeZone(System.DateTimeOffset localDateTime) { var value = localDateTime.ToString(); return value.Substring(value.Length - 17); } } }
40.506494
111
0.641552
[ "Apache-2.0" ]
costleya/ion-dotnet
Amazon.IonDotnet.Tests/Internals/TextReaderTimestampTest.cs
3,121
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Havit.Diagnostics.Contracts; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.JSInterop; namespace Havit.Blazor.Components.Web { /// <summary> /// Raw component extending <see cref="InputFile"/> with direct upload. /// </summary> public class HxInputFileCore : InputFile, IAsyncDisposable { /// <summary> /// URL of the server endpoint receiving the files. /// </summary> [Parameter] public string UploadUrl { get; set; } /// <summary> /// Raised during running file upload (the frequency depends on browser implementation). /// </summary> [Parameter] public EventCallback<UploadProgressEventArgs> OnProgress { get; set; } /// <summary> /// Raised after a file is uploaded (for every single file separately). /// </summary> [Parameter] public EventCallback<FileUploadedEventArgs> OnFileUploaded { get; set; } /// <summary> /// Raised when all files are uploaded (after all <see cref="OnFileUploaded"/> events). /// </summary> [Parameter] public EventCallback<UploadCompletedEventArgs> OnUploadCompleted { get; set; } /// <summary> /// Single <c>false</c> or multiple <c>true</c> files upload. /// </summary> [Parameter] public bool Multiple { get; set; } /// <summary> /// Takes as its value a comma-separated list of one or more file types, or unique file type specifiers, describing which file types to allow. /// <see href="https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept">MDN Web Docs - HTML attribute: accept</see>. /// </summary> [Parameter] public string Accept { get; set; } /// <summary> /// The maximum files size in bytes. /// When exceeded, the <see cref="OnFileUploaded"/> returns <c>413-RequestEntityTooLarge</c> as <see cref="FileUploadedEventArgs.ResponseStatus"/>. /// Default is <c>null</c> (unlimited). /// </summary> [Parameter] public long? MaxFileSize { get; set; } /// <summary> /// Input element id. /// </summary> [Parameter] public string Id { get; set; } = "hx" + Guid.NewGuid().ToString("N"); [Inject] protected IJSRuntime JSRuntime { get; set; } /// <summary> /// Last known count of associated files. /// </summary> public int FileCount { get; private set; } private DotNetObjectReference<HxInputFileCore> dotnetObjectReference; private IJSObjectReference jsModule; private TaskCompletionSource<UploadCompletedEventArgs> uploadCompletedTaskCompletionSource; private ConcurrentBag<FileUploadedEventArgs> filesUploaded; public HxInputFileCore() { dotnetObjectReference = DotNetObjectReference.Create(this); } protected override void OnParametersSet() { base.OnParametersSet(); // Temporary hack as base implementation of InputFile does not expose ElementReference (vNext: https://github.com/dotnet/aspnetcore/blob/main/src/Components/Web/src/Forms/InputFile.cs) AdditionalAttributes ??= new Dictionary<string, object>(); AdditionalAttributes["id"] = this.Id; AdditionalAttributes["multiple"] = this.Multiple; AdditionalAttributes["accept"] = this.Accept; } /// <summary> /// Initiates the upload (does not wait for upload completion). Use OnUploadCompleted event. /// </summary> /// <param name="accessToken">Authorization Bearer Token to be used for upload (i.e. use IAccessTokenProvider).</param> /// <remarks> /// We do not want to make the Havit.Blazor library dependant on WebAssembly libraries (IAccessTokenProvider and such). Therefor the accessToken here... /// </remarks> public async Task StartUploadAsync(string accessToken = null) { Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(UploadUrl), nameof(UploadUrl) + " has to be set."); await EnsureJsModuleAsync(); filesUploaded = new ConcurrentBag<FileUploadedEventArgs>(); await jsModule.InvokeVoidAsync("upload", Id, dotnetObjectReference, this.UploadUrl, accessToken, this.MaxFileSize); } /// <summary> /// Uploads the file(s). /// </summary> /// <param name="accessToken">Authorization Bearer Token to be used for upload (i.e. use IAccessTokenProvider).</param> public async Task<UploadCompletedEventArgs> UploadAsync(string accessToken = null) { uploadCompletedTaskCompletionSource = new TaskCompletionSource<UploadCompletedEventArgs>(); await StartUploadAsync(accessToken); return await uploadCompletedTaskCompletionSource.Task; } /// <summary> /// Gets list of files chosen. /// </summary> public async Task<FileInfo[]> GetFilesAsync() { await EnsureJsModuleAsync(); return await jsModule.InvokeAsync<FileInfo[]>("getFiles", Id); } private async Task EnsureJsModuleAsync() { jsModule ??= await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/Havit.Blazor.Components.Web/" + nameof(HxInputFileCore) + ".js"); } /// <summary> /// Clears associated input element and resets component to initial state. /// </summary> public async Task ResetAsync() { await EnsureJsModuleAsync(); await jsModule.InvokeVoidAsync("reset", Id); } /// <summary> /// Receive upload progress notification from underlying javascript. /// </summary> [JSInvokable("HxInputFileCore_HandleUploadProgress")] public async Task HandleUploadProgress(int fileIndex, string fileName, long loaded, long total) { var uploadProgress = new UploadProgressEventArgs() { FileIndex = fileIndex, OriginalFileName = fileName, UploadedBytes = loaded, UploadSize = total }; await OnProgress.InvokeAsync(uploadProgress); } /// <summary> /// Receive upload finished notification from underlying javascript. /// </summary> [JSInvokable("HxInputFileCore_HandleFileUploaded")] public async Task HandleFileUploaded(int fileIndex, string fileName, long fileSize, string fileType, long fileLastModified, int responseStatus, string responseText) { var fileUploaded = new FileUploadedEventArgs() { FileIndex = fileIndex, OriginalFileName = fileName, ContentType = fileType, Size = fileSize, LastModified = DateTimeOffset.FromUnixTimeMilliseconds(fileLastModified), ResponseStatus = (HttpStatusCode)responseStatus, ResponseText = responseText, }; filesUploaded.Add(fileUploaded); await OnFileUploaded.InvokeAsync(fileUploaded); } /// <summary> /// Receive upload finished notification from underlying javascript. /// </summary> [JSInvokable("HxInputFileCore_HandleUploadCompleted")] public async Task HandleUploadCompleted(int fileCount, long totalSize) { var uploadCompleted = new UploadCompletedEventArgs() { FilesUploaded = filesUploaded, FileCount = fileCount, TotalSize = totalSize }; filesUploaded = null; uploadCompletedTaskCompletionSource?.TrySetResult(uploadCompleted); await OnUploadCompleted.InvokeAsync(uploadCompleted); } public async ValueTask DisposeAsync() { ((IDisposable)this).Dispose(); if (jsModule != null) { await jsModule.InvokeVoidAsync("dispose", Id); await jsModule.DisposeAsync(); } dotnetObjectReference.Dispose(); } } }
34.632075
187
0.726369
[ "MIT" ]
robertmclaws/Havit.Blazor
Havit.Blazor.Components.Web/Files/HxInputFileCore.cs
7,344
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Rest.Azure; using Microsoft.Azure.Commands.Network.Models; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using AutoMapper; using CNM = Microsoft.Azure.Commands.Network.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; namespace Microsoft.Azure.Commands.Network { [Cmdlet(VerbsCommon.Get, "AzureRmRouteTable"), OutputType(typeof(PSRouteTable))] public partial class GetAzureRmRouteTable : NetworkBaseCmdlet { [Parameter( Mandatory = true, HelpMessage = "The resource group name of route table.", ParameterSetName = "Expand", ValueFromPipelineByPropertyName = true)] [Parameter( Mandatory = false, HelpMessage = "The resource group name of route table.", ParameterSetName = "NoExpand", ValueFromPipelineByPropertyName = true)] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Alias("ResourceName")] [Parameter( Mandatory = true, HelpMessage = "The name of route table.", ParameterSetName = "Expand", ValueFromPipelineByPropertyName = true)] [Parameter( Mandatory = false, HelpMessage = "The name of route table.", ParameterSetName = "NoExpand", ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter( Mandatory = true, ParameterSetName = "Expand", ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string ExpandResource { get; set; } public override void Execute() { base.Execute(); if (!string.IsNullOrEmpty(this.Name)) { var vRouteTable = this.NetworkClient.NetworkManagementClient.RouteTables.Get(ResourceGroupName, Name, ExpandResource); var vRouteTableModel = NetworkResourceManagerProfile.Mapper.Map<CNM.PSRouteTable>(vRouteTable); vRouteTableModel.ResourceGroupName = this.ResourceGroupName; vRouteTableModel.Tag = TagsConversionHelper.CreateTagHashtable(vRouteTable.Tags); WriteObject(vRouteTableModel, true); } else { IPage<RouteTable> vRouteTablePage; if (!string.IsNullOrEmpty(this.ResourceGroupName)) { vRouteTablePage = this.NetworkClient.NetworkManagementClient.RouteTables.List(this.ResourceGroupName); } else { vRouteTablePage = this.NetworkClient.NetworkManagementClient.RouteTables.ListAll(); } var vRouteTableList = ListNextLink<RouteTable>.GetAllResourcesByPollingNextLink(vRouteTablePage, this.NetworkClient.NetworkManagementClient.RouteTables.ListNext); List<PSRouteTable> psRouteTableList = new List<PSRouteTable>(); foreach (var vRouteTable in vRouteTableList) { var vRouteTableModel = NetworkResourceManagerProfile.Mapper.Map<CNM.PSRouteTable>(vRouteTable); vRouteTableModel.ResourceGroupName = NetworkBaseCmdlet.GetResourceGroup(vRouteTable.Id); vRouteTableModel.Tag = TagsConversionHelper.CreateTagHashtable(vRouteTable.Tags); psRouteTableList.Add(vRouteTableModel); } WriteObject(psRouteTableList); } } } }
42.026087
135
0.63832
[ "MIT" ]
AzureDataBox/azure-powershell
src/ResourceManager/Network/Commands.Network/RouteTable/GetAzureRMRouteTableCommand.cs
4,719
C#
using DiabloSharp.Attributes; namespace DiabloSharp.Models { public enum ItemEquipmentSlot { [LocalizationEnUs("Head")] Head, [LocalizationEnUs("Shoulders")] Shoulders, [LocalizationEnUs("Neck")] Neck, [LocalizationEnUs("Torso")] Torso, [LocalizationEnUs("Hands")] Hands, [LocalizationEnUs("Wrists")] Wrists, [LocalizationEnUs("Waist")] Waist, [LocalizationEnUs("Legs")] Legs, [LocalizationEnUs("Feet")] Feet, [LocalizationEnUs("Left-Finger")] LeftFinger, [LocalizationEnUs("Right-Finger")] RightFinger, [LocalizationEnUs("Mainhand")] Mainhand, [LocalizationEnUs("Offhand")] Offhand } }
23.735294
42
0.55886
[ "MIT" ]
leardev/DiabloSharp
src/DiabloSharp/Models/ItemEquipmentSlot.cs
807
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NodaTime; using PluralKit.Core; namespace PluralKit.API { public struct MessageReturn { [JsonProperty("timestamp")] public Instant Timestamp; [JsonProperty("id")] public string Id; [JsonProperty("original")] public string Original; [JsonProperty("sender")] public string Sender; [JsonProperty("channel")] public string Channel; [JsonProperty("system")] public JObject System; [JsonProperty("member")] public JObject Member; } [ApiController] [Route("v1/msg")] [Route("msg")] public class MessageController: ControllerBase { private IDataStore _data; private TokenAuthService _auth; public MessageController(IDataStore _data, TokenAuthService auth) { this._data = _data; _auth = auth; } [HttpGet("{mid}")] public async Task<ActionResult<MessageReturn>> GetMessage(ulong mid) { var msg = await _data.GetMessage(mid); if (msg == null) return NotFound("Message not found."); return new MessageReturn { Timestamp = Instant.FromUnixTimeMilliseconds((long) (msg.Message.Mid >> 22) + 1420070400000), Id = msg.Message.Mid.ToString(), Channel = msg.Message.Channel.ToString(), Sender = msg.Message.Sender.ToString(), Member = msg.Member.ToJson(_auth.ContextFor(msg.System)), System = msg.System.ToJson(_auth.ContextFor(msg.System)), Original = msg.Message.OriginalMid?.ToString() }; } } }
30.551724
109
0.606659
[ "Apache-2.0" ]
PrincessAmi/ModdedPluralKit
PluralKit.API/Controllers/MessageController.cs
1,772
C#
using System; namespace Tamir.SharpSsh.jsch { /* -*-mode:java; c-basic-offset:2; -*- */ /* Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class RequestWindowChange : Request { internal int width_columns=80; internal int height_rows=24; internal int width_pixels=640; internal int height_pixels=480; public void setSize(int row, int col, int wp, int hp) { this.width_columns=row; this.height_rows=col; this.width_pixels=wp; this.height_pixels=hp; } public void request(Session session, Channel channel) { Buffer buf=new Buffer(); Packet packet=new Packet(buf); //byte SSH_MSG_CHANNEL_REQUEST //uint32 recipient_channel //string "window-change" //boolean FALSE //uint32 terminal width, columns //uint32 terminal height, rows //uint32 terminal width, pixels //uint32 terminal height, pixels packet.reset(); buf.putByte((byte) Session.SSH_MSG_CHANNEL_REQUEST); buf.putInt(channel.getRecipient()); buf.putString(Util.getBytes("window-change")); buf.putByte((byte)(waitForReply() ? 1 : 0)); buf.putInt(width_columns); buf.putInt(height_rows); buf.putInt(width_pixels); buf.putInt(height_pixels); session.write(packet); } public bool waitForReply(){ return false; } } }
37.24
79
0.723237
[ "BSD-3-Clause" ]
3rdandUrban-dev/Nuxleus
linux-distro/package/nuxleus/Source/Vendor/sharpssh/SharpSSH/jsch/RequestWindowChange.cs
2,793
C#
using System.Collections.Generic; namespace Unleash.Communication { internal class UnleashApiClientRequestHeaders { public string AppName { get; set; } public string InstanceTag { get; set; } public Dictionary<string,string> CustomHttpHeaders { get; set; } } }
27.909091
75
0.67101
[ "Apache-2.0" ]
AndreasChristianson/unleash-client-core
src/Unleash/Communication/UnleashApiClientRequestHeaders.cs
309
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.DataBox.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Map of filter type and the details to transfer all data. This field is /// required only if the TransferConfigurationType is given as TransferAll /// </summary> public partial class TransferConfigurationTransferAllDetails { /// <summary> /// Initializes a new instance of the /// TransferConfigurationTransferAllDetails class. /// </summary> public TransferConfigurationTransferAllDetails() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// TransferConfigurationTransferAllDetails class. /// </summary> /// <param name="include">Details to transfer all data.</param> public TransferConfigurationTransferAllDetails(TransferAllDetails include = default(TransferAllDetails)) { Include = include; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets details to transfer all data. /// </summary> [JsonProperty(PropertyName = "include")] public TransferAllDetails Include { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Include != null) { Include.Validate(); } } } }
31.338235
112
0.607227
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/databox/Microsoft.Azure.Management.DataBox/src/Generated/Models/TransferConfigurationTransferAllDetails.cs
2,131
C#
using Movement; using Editions; using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public static class DirectionsMenu { private static readonly float WarningPanelHeight = 55f; public static bool IsVisible { get { return DirectionsWindow != null && DirectionsWindow.activeSelf; } } public static Action<string> Callback; private static GameObject DirectionsWindow; public static void Show(Action<string> callback, Func<string, bool> filter = null) { DeleteOldDirectionsMenu(); Callback = callback; GameObject prefab = (GameObject)Resources.Load("Prefabs/UI/DirectionsWindow", typeof(GameObject)); DirectionsWindow = MonoBehaviour.Instantiate(prefab, GameObject.Find("UI/DirectionsPanel").transform); GameObject.Find("UI").transform.Find("ContextMenuPanel").gameObject.SetActive(false); CustomizeDirectionsMenu(filter); CustomizeForStressed(); DirectionsWindow.transform.localPosition = FixMenuPosition( DirectionsWindow.transform.gameObject, Input.mousePosition ); Phases.CurrentSubPhase.IsReadyForCommands = true; } public static void ShowForAll(Action<string> callback, Func<string, bool> filter = null) { DeleteOldDirectionsMenu(); Callback = callback; GameObject prefab = (GameObject)Resources.Load("Prefabs/UI/DirectionsWindow", typeof(GameObject)); DirectionsWindow = MonoBehaviour.Instantiate(prefab, GameObject.Find("UI/DirectionsPanel").transform); GameObject.Find("UI").transform.Find("ContextMenuPanel").gameObject.SetActive(false); CustomizeDirectionsMenuAll(filter); DirectionsWindow.transform.localPosition = FixMenuPosition( DirectionsWindow.transform.gameObject, Input.mousePosition ); } private static void DeleteOldDirectionsMenu() { foreach (Transform transform in GameObject.Find("UI/DirectionsPanel").transform) { GameObject.Destroy(transform.gameObject); } } private static void CustomizeDirectionsMenu(Func<string, bool> filter = null) { List<char> linesExist = new List<char>(); foreach (KeyValuePair<string, MovementComplexity> maneuverData in Selection.ThisShip.GetManeuvers()) { string[] parameters = maneuverData.Key.Split('.'); char maneuverSpeed = parameters[0].ToCharArray()[0]; if (parameters[2] == "V") { switch (maneuverSpeed) { case '1': maneuverSpeed = '-'; break; case '2': maneuverSpeed = '='; break; default: break; } } GameObject button = DirectionsWindow.transform.Find("Directions").Find("Speed" + maneuverSpeed).Find(maneuverData.Key).gameObject; if (maneuverData.Value != MovementComplexity.None) { if (filter == null || filter(maneuverData.Key)) { if (!linesExist.Contains(maneuverSpeed)) linesExist.Add(maneuverSpeed); SetManeuverColor(button, maneuverData); button.SetActive(true); button.GetComponent<Button>().onClick.AddListener(UI.AssignManeuverButtonPressed); GameObject number = DirectionsWindow.transform.Find("Numbers").Find("Speed" + maneuverSpeed).Find("Number").gameObject; number.SetActive(true); } } } HideExtraElements(linesExist); } private static void CustomizeDirectionsMenuAll(Func<string, bool> filter = null) { List<char> linesExist = new List<char>(); foreach (string maneuverCode in GenericMovement.GetAllManeuvers()) { string[] parameters = maneuverCode.Split('.'); char maneuverSpeed = parameters[0].ToCharArray()[0]; if (parameters[2] == "V") { switch (maneuverSpeed) { case '1': maneuverSpeed = '-'; break; case '2': maneuverSpeed = '='; break; default: break; } } GameObject button = DirectionsWindow.transform.Find("Directions").Find("Speed" + maneuverSpeed).Find(maneuverCode).gameObject; if (filter == null || filter(maneuverCode)) { if (!linesExist.Contains(maneuverSpeed)) linesExist.Add(maneuverSpeed); SetManeuverColor(button, new KeyValuePair<string, MovementComplexity>(maneuverCode, MovementComplexity.Normal)); button.SetActive(true); button.GetComponent<Button>().onClick.AddListener(UI.AssignManeuverButtonPressed); GameObject number = DirectionsWindow.transform.Find("Numbers").Find("Speed" + maneuverSpeed).Find("Number").gameObject; number.SetActive(true); } } HideExtraElements(linesExist); } private static void HideExtraElements(List<char> linesExist) { float freeSpace = 40; // COLUMNS float totalWidth = 480f; List<string> columns = new List<string>() { ".L.E", ".L.R", ".F.R", ".R.R", ".R.E" }; GameObject directionsPanel = DirectionsWindow.transform.Find("Directions").gameObject; int columnCounter = 0; int missingColumnsCounter = 0; foreach (var column in columns) { bool columnExists = false; for (int i = 1; i < 6; i++) { Transform directionIcon = directionsPanel.transform.Find("Speed" + i).Find(i + column); if (directionIcon != null && directionIcon.gameObject.activeSelf) { columnExists = true; //break; } } if (columnExists) { for (int i = 1; i < 6; i++) { Transform directionIcon = directionsPanel.transform.Find("Speed" + i).Find(i + column); if (directionIcon != null && directionIcon.gameObject.activeSelf) { directionIcon.localPosition = new Vector2(205 + columnCounter * 40, directionIcon.localPosition.y); } } columnCounter++; } else { missingColumnsCounter++; totalWidth -= 40; } } // LINES float totalHeight = 320f; for (int i = -2; i < 6; i++) { char c = (i >= 0) ? i.ToString().ToCharArray()[0] : ((i == -1) ? '-' : '='); if (!linesExist.Contains(c)) { totalHeight -= 40; GameObject numbersLinePanel = DirectionsWindow.transform.Find("Numbers").gameObject; numbersLinePanel.transform.Find("Speed" + c).gameObject.SetActive(false); GameObject directionsLinePanel = DirectionsWindow.transform.Find("Directions").gameObject; directionsLinePanel.transform.Find("Speed" + c).gameObject.SetActive(false); } } DirectionsWindow.GetComponent<RectTransform>().sizeDelta = new Vector3(DirectionsWindow.GetComponent<RectTransform>().sizeDelta.x, linesExist.Count * 40); DirectionsWindow.transform.Find("Numbers").GetComponent<RectTransform>().sizeDelta = new Vector3(DirectionsWindow.transform.Find("Numbers").GetComponent<RectTransform>().sizeDelta.x, linesExist.Count * 40 + 10); DirectionsWindow.transform.Find("Directions").GetComponent<RectTransform>().sizeDelta = new Vector3(DirectionsWindow.transform.Find("Directions").GetComponent<RectTransform>().sizeDelta.x - missingColumnsCounter * freeSpace, linesExist.Count * 40 + 10); DirectionsWindow.GetComponent<RectTransform>().sizeDelta = new Vector2(DirectionsWindow.transform.Find("Directions").GetComponent<RectTransform>().sizeDelta.x + 70, DirectionsWindow.GetComponent<RectTransform>().sizeDelta.y); float offset = 5; foreach (Transform transform in DirectionsWindow.transform.Find("Numbers")) { if (transform.gameObject.activeSelf) { transform.localPosition = new Vector2(transform.localPosition.x, offset); offset -= freeSpace; } } offset = 0; foreach (Transform transform in DirectionsWindow.transform.Find("Directions")) { if (transform.gameObject.activeSelf) { transform.localPosition = new Vector2(transform.localPosition.x, offset); offset -= freeSpace; } } DirectionsWindow.GetComponent<RectTransform>().sizeDelta = new Vector2(totalWidth + 10, totalHeight + 10); } private static void SetManeuverColor(GameObject button, KeyValuePair<string, MovementComplexity> maneuverData) { Color maneuverColor = Color.yellow; if (maneuverData.Value == MovementComplexity.Easy) maneuverColor = Edition.Current.MovementEasyColor; if (maneuverData.Value == MovementComplexity.Normal) maneuverColor = Color.white; if (maneuverData.Value == MovementComplexity.Complex) { maneuverColor = Color.red; if (Selection.ThisShip != null && Selection.ThisShip.IsStressed) button.transform.Find("RedBackground").gameObject.SetActive(true); } button.GetComponentInChildren<Text>().color = maneuverColor; } private static Vector3 FixMenuPosition(GameObject menuPanel, Vector3 position) { float globalUiScale = GameObject.Find("UI").transform.localScale.x; Vector3 screenPosition = new Vector3(position.x, position.y); Vector3 newPosition = new Vector3(position.x / globalUiScale, position.y / globalUiScale - Screen.height / globalUiScale); RectTransform menuRect = menuPanel.GetComponent<RectTransform>(); float windowHeight = menuRect.sizeDelta.y; float windowWidth = menuRect.sizeDelta.x; if (newPosition.x + windowWidth > Screen.width / globalUiScale) { newPosition = new Vector3(Screen.width / globalUiScale - windowWidth - 5, newPosition.y, 0); } if (-newPosition.y + windowHeight > Screen.height / globalUiScale) { newPosition = new Vector3(newPosition.x, (position.y + windowHeight) / globalUiScale - Screen.height / globalUiScale + 5, 0); } if (Selection.ThisShip != null && Selection.ThisShip.IsStressed && -newPosition.y < WarningPanelHeight * menuRect.localScale.y - 5 ) { newPosition = new Vector3(newPosition.x, - WarningPanelHeight - 5, 0); } return newPosition; } public static void Hide() { GameObject.Destroy(DirectionsWindow); } private static void CustomizeForStressed() { if (Selection.ThisShip.IsStressed) { GameObject warningGO = DirectionsWindow.transform.Find("Warning").gameObject; warningGO.SetActive(true); } } }
38.598007
261
0.597005
[ "MIT" ]
nickell-andrew/FlyCasual
Assets/Scripts/View/UI/DirectionsMenu.cs
11,620
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxFactoryTests : CSharpTestBase { [Fact, WorkItem(33713, "https://github.com/dotnet/roslyn/issues/33713")] public void AlternateVerbatimString() { var token = SyntaxFactory.Token(SyntaxKind.InterpolatedVerbatimStringStartToken); Assert.Equal("$@\"", token.Text); Assert.Equal("$@\"", token.ValueText); } [Fact] public void SyntaxTree() { var text = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit(), encoding: null).GetText(); Assert.Null(text.Encoding); Assert.Equal(SourceHashAlgorithm.Sha1, text.ChecksumAlgorithm); } [Fact] public void SyntaxTreeFromNode() { var text = SyntaxFactory.CompilationUnit().SyntaxTree.GetText(); Assert.Null(text.Encoding); Assert.Equal(SourceHashAlgorithm.Sha1, text.ChecksumAlgorithm); } [Fact] public void TestConstructNamespaceWithNameOnly() { var n = SyntaxFactory.NamespaceDeclaration(name: SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("goo"))); Assert.NotNull(n); Assert.Equal(0, n.Errors().Length); Assert.Equal(0, n.Externs.Count); Assert.Equal(0, n.Usings.Count); Assert.False(n.NamespaceKeyword.IsMissing); Assert.Equal(9, n.NamespaceKeyword.Width); Assert.False(n.OpenBraceToken.IsMissing); Assert.Equal(SyntaxKind.OpenBraceToken, n.OpenBraceToken.Kind()); Assert.Equal(1, n.OpenBraceToken.Width); Assert.Equal(0, n.Members.Count); Assert.False(n.CloseBraceToken.IsMissing); Assert.Equal(SyntaxKind.CloseBraceToken, n.CloseBraceToken.Kind()); Assert.Equal(1, n.CloseBraceToken.Width); Assert.Equal(SyntaxKind.None, n.SemicolonToken.Kind()); } [Fact] public void TestConstructClassWithKindAndNameOnly() { var c = SyntaxFactory.ClassDeclaration(identifier: SyntaxFactory.Identifier("goo")); Assert.NotNull(c); Assert.Equal(0, c.AttributeLists.Count); Assert.Equal(0, c.Modifiers.Count); Assert.Equal(5, c.Keyword.Width); Assert.Equal(SyntaxKind.ClassKeyword, c.Keyword.Kind()); Assert.Equal(0, c.ConstraintClauses.Count); Assert.False(c.OpenBraceToken.IsMissing); Assert.Equal(SyntaxKind.OpenBraceToken, c.OpenBraceToken.Kind()); Assert.Equal(1, c.OpenBraceToken.Width); Assert.Equal(0, c.Members.Count); Assert.False(c.CloseBraceToken.IsMissing); Assert.Equal(SyntaxKind.CloseBraceToken, c.CloseBraceToken.Kind()); Assert.Equal(1, c.CloseBraceToken.Width); Assert.Equal(SyntaxKind.None, c.SemicolonToken.Kind()); } [WorkItem(528399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528399")] [Fact()] public void PassExpressionToSyntaxToken() { // Verify that the Token factory method does validation for cases when the argument is not a valid token. Assert.Throws<ArgumentException>(() => SyntaxFactory.Token(SyntaxKind.NumericLiteralExpression)); } [WorkItem(546101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546101")] [Fact] public void TestConstructPragmaChecksumDirective() { Func<string, SyntaxToken> makeStringLiteral = value => SyntaxFactory.ParseToken(string.Format("\"{0}\"", value)).WithLeadingTrivia(SyntaxFactory.ElasticMarker).WithTrailingTrivia(SyntaxFactory.ElasticMarker); var t = SyntaxFactory.PragmaChecksumDirectiveTrivia(makeStringLiteral("file"), makeStringLiteral("guid"), makeStringLiteral("bytes"), true); Assert.Equal(SyntaxKind.PragmaChecksumDirectiveTrivia, t.Kind()); Assert.Equal("#pragmachecksum\"file\"\"guid\"\"bytes\"", t.ToString()); Assert.Equal("#pragma checksum \"file\" \"guid\" \"bytes\"\r\n", t.NormalizeWhitespace().ToFullString()); } [Fact] public void TestFreeFormTokenFactory_NonTokenKind() { Type exceptionType; try { SyntaxFactory.Token(SyntaxKind.IdentifierName); AssertEx.Fail("Should have thrown - can't create an IdentifierName token"); return; } catch (Exception e) { exceptionType = e.GetType(); } // Should throw the same exception as the simpler API (which follows a different code path). Assert.Throws(exceptionType, () => SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.IdentifierName, "text", "valueText", default(SyntaxTriviaList))); } [Fact] public void TestFreeFormTokenFactory_SpecialTokenKinds() { // Factory method won't do the right thing for these SyntaxKinds - throws instead. Assert.Throws<ArgumentException>(() => SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.IdentifierToken, "text", "valueText", default(SyntaxTriviaList))); Assert.Throws<ArgumentException>(() => SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.CharacterLiteralToken, "text", "valueText", default(SyntaxTriviaList))); Assert.Throws<ArgumentException>(() => SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.NumericLiteralToken, "text", "valueText", default(SyntaxTriviaList))); // Ensure that when they throw, the appropriate message is used using (new EnsureEnglishUICulture()) { try { SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.IdentifierToken, "text", "valueText", default(SyntaxTriviaList)); AssertEx.Fail("Should have thrown"); return; } catch (ArgumentException e) { Assert.Equal($"Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier or Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier to create identifier tokens.{Environment.NewLine}Parameter name: kind", e.Message); Assert.Contains(typeof(SyntaxFactory).ToString(), e.Message); // Make sure the class/namespace aren't updated without also updating the exception message } try { SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.CharacterLiteralToken, "text", "valueText", default(SyntaxTriviaList)); AssertEx.Fail("Should have thrown"); return; } catch (ArgumentException e) { Assert.Equal($"Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal to create character literal tokens.{Environment.NewLine}Parameter name: kind", e.Message); Assert.Contains(typeof(SyntaxFactory).ToString(), e.Message); // Make sure the class/namespace aren't updated without also updating the exception message } try { SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.NumericLiteralToken, "text", "valueText", default(SyntaxTriviaList)); AssertEx.Fail("Should have thrown"); return; } catch (ArgumentException e) { Assert.Equal($"Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal to create numeric literal tokens.{Environment.NewLine}Parameter name: kind", e.Message); Assert.Contains(typeof(SyntaxFactory).ToString(), e.Message); // Make sure the class/namespace aren't updated without also updating the exception message } } // Make sure that the appropriate methods work as suggested in the exception messages, and don't throw SyntaxFactory.Identifier("text"); SyntaxFactory.Literal('c'); //character literal SyntaxFactory.Literal(123); //numeric literal } [Fact] public void TestFreeFormTokenFactory_DefaultText() { for (SyntaxKind kind = InternalSyntax.SyntaxToken.FirstTokenWithWellKnownText; kind <= InternalSyntax.SyntaxToken.LastTokenWithWellKnownText; kind++) { if (!SyntaxFacts.IsAnyToken(kind)) continue; var defaultText = SyntaxFacts.GetText(kind); var actualRed = SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), kind, defaultText, defaultText, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)); var actualGreen = actualRed.Node; var expectedGreen = InternalSyntax.SyntaxFactory.Token(InternalSyntax.SyntaxFactory.ElasticZeroSpace, kind, InternalSyntax.SyntaxFactory.ElasticZeroSpace); Assert.Same(expectedGreen, actualGreen); // Don't create a new token if we don't have to. } } [Fact] public void TestFreeFormTokenFactory_CustomText() { for (SyntaxKind kind = InternalSyntax.SyntaxToken.FirstTokenWithWellKnownText; kind <= InternalSyntax.SyntaxToken.LastTokenWithWellKnownText; kind++) { if (!SyntaxFacts.IsAnyToken(kind)) continue; var defaultText = SyntaxFacts.GetText(kind); var text = ToXmlEntities(defaultText); var valueText = defaultText; var token = SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), kind, text, valueText, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)); Assert.Equal(kind, token.Kind()); Assert.Equal(text, token.Text); Assert.Equal(valueText, token.ValueText); if (string.IsNullOrEmpty(valueText)) { Assert.IsType<InternalSyntax.SyntaxToken.SyntaxTokenWithTrivia>(token.Node); } else { Assert.IsType<InternalSyntax.SyntaxToken.SyntaxTokenWithValueAndTrivia<string>>(token.Node); } } } [Fact] public void TestSeparatedListFactory_DefaultSeparators() { var null1 = SyntaxFactory.SeparatedList((ParameterSyntax[])null); Assert.Equal(0, null1.Count); Assert.Equal(0, null1.SeparatorCount); Assert.Equal("", null1.ToString()); var null2 = SyntaxFactory.SeparatedList((System.Collections.Generic.IEnumerable<VariableDeclaratorSyntax>)null); Assert.Equal(0, null2.Count); Assert.Equal(0, null2.SeparatorCount); Assert.Equal("", null2.ToString()); var empty1 = SyntaxFactory.SeparatedList(new TypeArgumentListSyntax[] { }); Assert.Equal(0, empty1.Count); Assert.Equal(0, empty1.SeparatorCount); Assert.Equal("", empty1.ToString()); var empty2 = SyntaxFactory.SeparatedList(System.Linq.Enumerable.Empty<TypeParameterSyntax>()); Assert.Equal(0, empty2.Count); Assert.Equal(0, empty2.SeparatorCount); Assert.Equal("", empty2.ToString()); var singleton1 = SyntaxFactory.SeparatedList(new[] { SyntaxFactory.IdentifierName("a") }); Assert.Equal(1, singleton1.Count); Assert.Equal(0, singleton1.SeparatorCount); Assert.Equal("a", singleton1.ToString()); var singleton2 = SyntaxFactory.SeparatedList((System.Collections.Generic.IEnumerable<ExpressionSyntax>)new[] { SyntaxFactory.IdentifierName("x") }); Assert.Equal(1, singleton2.Count); Assert.Equal(0, singleton2.SeparatorCount); Assert.Equal("x", singleton2.ToString()); var list1 = SyntaxFactory.SeparatedList(new[] { SyntaxFactory.IdentifierName("a"), SyntaxFactory.IdentifierName("b"), SyntaxFactory.IdentifierName("c") }); Assert.Equal(3, list1.Count); Assert.Equal(2, list1.SeparatorCount); Assert.Equal("a,b,c", list1.ToString()); var builder = new System.Collections.Generic.List<ArgumentSyntax>(); builder.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName("x"))); builder.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName("y"))); builder.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName("z"))); var list2 = SyntaxFactory.SeparatedList<ArgumentSyntax>(builder); Assert.Equal(3, list2.Count); Assert.Equal(2, list2.SeparatorCount); Assert.Equal("x,y,z", list2.ToString()); } [WorkItem(720708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720708")] [Fact] public void TestLiteralDefaultStringValues() { // string CheckLiteralToString("A", @"""A"""); CheckLiteralToString("\r", @"""\r"""); CheckLiteralToString("\u0007", @"""\a"""); CheckLiteralToString("\u000c", @"""\f"""); CheckLiteralToString("\u001f", @"""\u001f"""); // char CheckLiteralToString('A', @"'A'"); CheckLiteralToString('\r', @"'\r'"); CheckLiteralToString('\u0007', @"'\a'"); CheckLiteralToString('\u000c', @"'\f'"); CheckLiteralToString('\u001f', @"'\u001f'"); // byte CheckLiteralToString(byte.MinValue, @"0"); CheckLiteralToString(byte.MaxValue, @"255"); // sbyte CheckLiteralToString((sbyte)0, @"0"); CheckLiteralToString(sbyte.MinValue, @"-128"); CheckLiteralToString(sbyte.MaxValue, @"127"); // ushort CheckLiteralToString(ushort.MinValue, @"0"); CheckLiteralToString(ushort.MaxValue, @"65535"); // short CheckLiteralToString((short)0, @"0"); CheckLiteralToString(short.MinValue, @"-32768"); CheckLiteralToString(short.MaxValue, @"32767"); // uint CheckLiteralToString(uint.MinValue, @"0U"); CheckLiteralToString(uint.MaxValue, @"4294967295U"); // int CheckLiteralToString((int)0, @"0"); CheckLiteralToString(int.MinValue, @"-2147483648"); CheckLiteralToString(int.MaxValue, @"2147483647"); // ulong CheckLiteralToString(ulong.MinValue, @"0UL"); CheckLiteralToString(ulong.MaxValue, @"18446744073709551615UL"); // long CheckLiteralToString((long)0, @"0L"); CheckLiteralToString(long.MinValue, @"-9223372036854775808L"); CheckLiteralToString(long.MaxValue, @"9223372036854775807L"); // float CheckLiteralToString(0F, @"0F"); CheckLiteralToString(0.012345F, @"0.012345F"); CheckLiteralToString(float.MaxValue, @"3.40282347E+38F"); // double CheckLiteralToString(0D, @"0"); CheckLiteralToString(0.012345D, @"0.012345"); CheckLiteralToString(double.MaxValue, @"1.7976931348623157E+308"); // decimal CheckLiteralToString(0M, @"0M"); CheckLiteralToString(0.012345M, @"0.012345M"); CheckLiteralToString(decimal.MaxValue, @"79228162514264337593543950335M"); } [WorkItem(849836, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849836")] [Fact] public void TestLiteralToStringDifferentCulture() { var culture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = new CultureInfo("de-DE", useUserOverride: false); // If we are using the current culture to format the string then // decimal values should render as , instead of . TestLiteralDefaultStringValues(); var literal = SyntaxFactory.Literal(3.14); Assert.Equal("3.14", literal.ValueText); CultureInfo.CurrentCulture = culture; } [WorkItem(9484, "https://github.com/dotnet/roslyn/issues/9484")] [Fact] public void TestEscapeLineSeparator() { var literal = SyntaxFactory.Literal("\u2028"); Assert.Equal("\"\\u2028\"", literal.Text); } [WorkItem(20693, "https://github.com/dotnet/roslyn/issues/20693")] [Fact] public void TestEscapeSurrogate() { var literal = SyntaxFactory.Literal('\uDBFF'); Assert.Equal("'\\udbff'", literal.Text); } private static void CheckLiteralToString(dynamic value, string expected) { var literal = SyntaxFactory.Literal(value); Assert.Equal(expected, literal.ToString()); } private static string ToXmlEntities(string str) { var builder = new StringBuilder(); foreach (char ch in str) { builder.AppendFormat("&#{0};", (int)ch); } return builder.ToString(); } [Fact] [WorkItem(17067, "https://github.com/dotnet/roslyn/issues/17067")] public void GetTokenDiagnosticsWithoutSyntaxTree_WithDiagnostics() { var tokens = SyntaxFactory.ParseTokens("1l").ToList(); Assert.Equal(2, tokens.Count); // { "1l", "EOF" } var literal = tokens.First(); Assert.Equal("1l", literal.Text); Assert.Equal(Location.None, literal.GetLocation()); literal.GetDiagnostics().Verify( // warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity Diagnostic(ErrorCode.WRN_LowercaseEllSuffix)); } [Fact] [WorkItem(17067, "https://github.com/dotnet/roslyn/issues/17067")] public void GetTokenDiagnosticsWithoutSyntaxTree_WithoutDiagnostics() { var tokens = SyntaxFactory.ParseTokens("1L").ToList(); Assert.Equal(2, tokens.Count); // { "1L", "EOF" } var literal = tokens.First(); Assert.Equal("1L", literal.Text); Assert.Equal(Location.None, literal.GetLocation()); literal.GetDiagnostics().Verify(); } [Fact] [WorkItem(17067, "https://github.com/dotnet/roslyn/issues/17067")] public void GetTokenDiagnosticsWithSyntaxTree_WithDiagnostics() { var expression = (LiteralExpressionSyntax)SyntaxFactory.ParseExpression("1l"); Assert.Equal("1l", expression.Token.Text); Assert.NotNull(expression.Token.SyntaxTree); var expectedLocation = Location.Create(expression.Token.SyntaxTree, TextSpan.FromBounds(0, 2)); Assert.Equal(expectedLocation, expression.Token.GetLocation()); expression.Token.GetDiagnostics().Verify( // (1,2): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // 1l Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 2)); } [Fact] [WorkItem(17067, "https://github.com/dotnet/roslyn/issues/17067")] public void GetTokenDiagnosticsWithSyntaxTree_WithoutDiagnostics() { var expression = (LiteralExpressionSyntax)SyntaxFactory.ParseExpression("1L"); Assert.Equal("1L", expression.Token.Text); Assert.NotNull(expression.Token.SyntaxTree); var expectedLocation = Location.Create(expression.Token.SyntaxTree, TextSpan.FromBounds(0, 2)); Assert.Equal(expectedLocation, expression.Token.GetLocation()); expression.Token.GetDiagnostics().Verify(); } [Fact] [WorkItem(17067, "https://github.com/dotnet/roslyn/issues/17067")] public void GetDiagnosticsFromNullToken() { var token = new SyntaxToken(null); Assert.Equal(Location.None, token.GetLocation()); token.GetDiagnostics().Verify(); } [Fact] [WorkItem(21231, "https://github.com/dotnet/roslyn/issues/21231")] public void TestSpacingOnNullableIntType() { var syntaxNode = SyntaxFactory.CompilationUnit() .WithMembers( SyntaxFactory.SingletonList<MemberDeclarationSyntax>( SyntaxFactory.ClassDeclaration("C") .WithMembers( SyntaxFactory.SingletonList<MemberDeclarationSyntax>( SyntaxFactory.PropertyDeclaration( SyntaxFactory.NullableType( SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.IntKeyword))), SyntaxFactory.Identifier("P")) .WithAccessorList( SyntaxFactory.AccessorList()))))) .NormalizeWhitespace(); // no space between int and ? Assert.Equal("class C\r\n{\r\n int? P\r\n {\r\n }\r\n}", syntaxNode.ToFullString()); } [Fact] [WorkItem(21231, "https://github.com/dotnet/roslyn/issues/21231")] public void TestSpacingOnNullableDatetimeType() { var syntaxNode = SyntaxFactory.CompilationUnit() .WithMembers( SyntaxFactory.SingletonList<MemberDeclarationSyntax>( SyntaxFactory.ClassDeclaration("C") .WithMembers( SyntaxFactory.SingletonList<MemberDeclarationSyntax>( SyntaxFactory.PropertyDeclaration( SyntaxFactory.NullableType( SyntaxFactory.ParseTypeName("DateTime")), SyntaxFactory.Identifier("P")) .WithAccessorList( SyntaxFactory.AccessorList()))))) .NormalizeWhitespace(); // no space between DateTime and ? Assert.Equal("class C\r\n{\r\n DateTime? P\r\n {\r\n }\r\n}", syntaxNode.ToFullString()); } [Fact] [WorkItem(21231, "https://github.com/dotnet/roslyn/issues/21231")] public void TestSpacingOnTernary() { var syntaxNode = SyntaxFactory.ParseExpression("x is int? y: z").NormalizeWhitespace(); // space between int and ? Assert.Equal("x is int ? y : z", syntaxNode.ToFullString()); var syntaxNode2 = SyntaxFactory.ParseExpression("x is DateTime? y: z").NormalizeWhitespace(); // space between DateTime and ? Assert.Equal("x is DateTime ? y : z", syntaxNode2.ToFullString()); } [Fact] [WorkItem(21231, "https://github.com/dotnet/roslyn/issues/21231")] public void TestSpacingOnCoalescing() { var syntaxNode = SyntaxFactory.ParseExpression("x is int??y").NormalizeWhitespace(); Assert.Equal("x is int ?? y", syntaxNode.ToFullString()); var syntaxNode2 = SyntaxFactory.ParseExpression("x is DateTime??y").NormalizeWhitespace(); Assert.Equal("x is DateTime ?? y", syntaxNode2.ToFullString()); var syntaxNode3 = SyntaxFactory.ParseExpression("x is object??y").NormalizeWhitespace(); Assert.Equal("x is object ?? y", syntaxNode3.ToFullString()); } } }
45.168807
243
0.601454
[ "Apache-2.0" ]
acesiddhu/roslyn
src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxFactoryTests.cs
24,619
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace lxssex.RPC { public class Channel : IDisposable { private static readonly MethodInfo[] PRIMITIVE_WRITE_METHODS; private static readonly MethodInfo[] PRIMITIVE_READ_METHODS; private static readonly MethodInfo GENERIC_WRITE_METHOD; private static readonly MethodInfo GENERIC_WRITE_ARRAY_METHOD; private static readonly MethodInfo GENERIC_READ_METHOD; private static readonly MethodInfo GENERIC_READ_ARRAY_METHOD; static Channel() { PRIMITIVE_WRITE_METHODS = typeof(UnmanagedMemoryAccessor).GetTypeInfo().DeclaredMethods.Where(x => x.IsPublic && !x.IsStatic && !x.ContainsGenericParameters && x.Name == "Write").ToArray(); PRIMITIVE_READ_METHODS = typeof(UnmanagedMemoryAccessor).GetTypeInfo().DeclaredMethods.Where(x => x.IsPublic && !x.IsStatic && !x.ContainsGenericParameters && x.Name.StartsWith("Read") && x.ReturnType.IsPrimitive).ToArray(); GENERIC_WRITE_METHOD = typeof(UnmanagedMemoryAccessor).GetTypeInfo().DeclaredMethods.First(x => x.IsPublic && !x.IsStatic && x.ContainsGenericParameters && x.Name == "Write"); GENERIC_WRITE_ARRAY_METHOD = typeof(UnmanagedMemoryAccessor).GetTypeInfo().DeclaredMethods.First(x => x.IsPublic && !x.IsStatic && x.ContainsGenericParameters && x.Name == "WriteArray"); GENERIC_READ_METHOD = typeof(UnmanagedMemoryAccessor).GetTypeInfo().DeclaredMethods.First(x => x.IsPublic && !x.IsStatic && x.ContainsGenericParameters && x.Name == "Read"); GENERIC_READ_ARRAY_METHOD = typeof(UnmanagedMemoryAccessor).GetTypeInfo().DeclaredMethods.First(x => x.IsPublic && !x.IsStatic && x.ContainsGenericParameters && x.Name == "ReadArray"); } private static MethodInfo GetWriter(Type dataType) { if (dataType.IsArray) { return GENERIC_WRITE_ARRAY_METHOD.MakeGenericMethod(dataType.GetElementType()); } else if (dataType.IsPrimitive) { return PRIMITIVE_WRITE_METHODS.First(x => x.GetParameters()[1].ParameterType == dataType); } else { return GENERIC_WRITE_METHOD.MakeGenericMethod(dataType); } } private static MethodInfo GetReader(Type dataType) { if (dataType.IsArray) { return GENERIC_READ_ARRAY_METHOD.MakeGenericMethod(dataType.GetElementType()); } else if (dataType.IsPrimitive) { return PRIMITIVE_READ_METHODS.First(x => x.ReturnType == dataType); } else { return GENERIC_READ_METHOD.MakeGenericMethod(dataType); } } private bool disposedValue; public TypeInfo ServicingType { get; } public object ServicingObject { get; } public SafeBuffer SharedMemory { get; } public WaitHandle SyncEvent { get; } public ChannelGetEventDelegate GetEvent { get; } public ChannelSetEventDelegate SetEvent { get; } public Channel(Type servicingType, SafeBuffer sharedMemory, WaitHandle syncEvent, ChannelGetEventDelegate getEvent, ChannelSetEventDelegate setEvent) { ServicingType = servicingType.GetTypeInfo(); SharedMemory = sharedMemory; SyncEvent = syncEvent; GetEvent = getEvent; SetEvent = setEvent; } public Channel(object servicingObject, SafeBuffer sharedMemory, WaitHandle syncEvent, ChannelGetEventDelegate getEvent, ChannelSetEventDelegate setEvent) : this(servicingObject.GetType(), sharedMemory, syncEvent, getEvent, setEvent) { ServicingObject = servicingObject; } private string ReadData(out object[] values, out object @return) { using UnmanagedMemoryAccessor accessor = new UnmanagedMemoryAccessor(SharedMemory, 0, (long)SharedMemory.ByteLength, FileAccess.ReadWrite); long pos = sizeof(long); int encodedCallerNameLength = accessor.ReadInt32(pos); pos += sizeof(int); byte[] encodedCallerName = new byte[encodedCallerNameLength]; accessor.ReadArray(pos, encodedCallerName, 0, encodedCallerNameLength); string callerName = Encoding.UTF8.GetString(encodedCallerName); MethodInfo caller = ServicingType.GetDeclaredMethod(callerName); if (caller is null) throw new MissingMemberException(ServicingType.FullName, callerName); ParameterInfo[] @params = caller.GetParameters(); values = new object[@params.Length]; return ReadData(@params, values, caller.ReturnParameter, out @return); } private string ReadData(ParameterInfo[] @params, object[] values, ParameterInfo returnParam, out object @return) { using UnmanagedMemoryAccessor accessor = new UnmanagedMemoryAccessor(SharedMemory, 0, (long)SharedMemory.ByteLength, FileAccess.ReadWrite); long resultBytes = accessor.ReadInt64(0); long pos = sizeof(long); int encodedCallerNameLength = accessor.ReadInt32(pos); pos += sizeof(int); byte[] encodedCallerName = new byte[encodedCallerNameLength]; accessor.ReadArray(pos, encodedCallerName, 0, encodedCallerNameLength); pos += encodedCallerNameLength; object Deserialize(ParameterInfo param) { if (param == null) { return null; } else if (param.ParameterType.IsArray) { Type elementType = param.ParameterType.GetElementType(); MethodInfo readMethod = GetReader(param.ParameterType); int arrayLength = accessor.ReadInt32(pos); Array array = Array.CreateInstance(elementType, arrayLength); pos += sizeof(int); readMethod.Invoke(accessor, new object[] { pos, array, 0, arrayLength }); pos += arrayLength * Marshal.SizeOf(elementType); return array; } else if (param.ParameterType == typeof(string)) { int encodedStringLength = accessor.ReadInt32(pos); pos += sizeof(int); byte[] encodedString = new byte[encodedStringLength]; accessor.ReadArray(pos, encodedString, 0, encodedStringLength); pos += encodedStringLength; return Encoding.UTF8.GetString(encodedString); } else if (param.ParameterType == typeof(IntPtr)) { long value = accessor.ReadInt64(pos); pos += sizeof(long); return new IntPtr(value); } else if (param.ParameterType == typeof(UIntPtr)) { ulong value = accessor.ReadUInt64(pos); pos += sizeof(ulong); return new UIntPtr(value); } else { Type valueType = param.ParameterType.IsByRef ? param.ParameterType.GetElementType() : param.ParameterType; MethodInfo readMethod = GetReader(valueType); object value = null; if (valueType.IsPrimitive) { value = readMethod.Invoke(accessor, new object[] { pos }); } else { object[] readParams = new object[] { pos, null }; readMethod.Invoke(accessor, readParams); value = readParams[1]; } Console.WriteLine("{0}: {1} readed", valueType.FullName, value); pos += Marshal.SizeOf(valueType); return value; } } for (int i0 = 0; i0 < @params.Length; i0++) { values[i0] = Deserialize(@params[i0]); } @return = Deserialize(returnParam); if (resultBytes != pos) throw new DataMisalignedException(); return Encoding.UTF8.GetString(encodedCallerName); } private void WriteData(string callerName, ParameterInfo[] @params, object[] values, ParameterInfo returnParam, object @return = null) { using (UnmanagedMemoryAccessor accessor = new UnmanagedMemoryAccessor(SharedMemory, 0, (long)SharedMemory.ByteLength, FileAccess.ReadWrite)) { long pos = sizeof(long); byte[] encodedName = Encoding.UTF8.GetBytes(callerName); accessor.Write(pos, encodedName.Length); pos += sizeof(int); accessor.WriteArray(pos, encodedName, 0, encodedName.Length); pos += encodedName.Length; void Serialize(ParameterInfo param, object value) { if (param == null) { //skip } else if (param.ParameterType.IsArray) { MethodInfo writeMethod = GetWriter(param.ParameterType); Array array = (Array)value; accessor.Write(pos, array.Length); pos += sizeof(int); writeMethod.Invoke(accessor, new object[] { pos, array, 0, array.Length }); pos += array.Length * Marshal.SizeOf(param.ParameterType.GetElementType()); } else if (param.ParameterType == typeof(string)) { byte[] encodedString = Encoding.UTF8.GetBytes((string)value); accessor.Write(pos, encodedString.Length); pos += sizeof(int); accessor.WriteArray(pos, encodedString, 0, encodedString.Length); pos += encodedString.Length; } else if (param.ParameterType == typeof(IntPtr)) { accessor.Write(pos, ((IntPtr)value).ToInt64()); pos += sizeof(long); } else if (param.ParameterType == typeof(UIntPtr)) { accessor.Write(pos, ((UIntPtr)value).ToUInt64()); pos += sizeof(ulong); } else { Type valueType = param.ParameterType.IsByRef ? param.ParameterType.GetElementType() : param.ParameterType; MethodInfo writeMethod = GetWriter(valueType); Console.WriteLine("{0}: {1} written", valueType.FullName, value); writeMethod.Invoke(accessor, new[] { pos, value }); pos += Marshal.SizeOf(valueType); } } for (int i0 = 0; i0 < @params.Length; i0++) { Serialize(@params[i0], values[i0]); } Serialize(returnParam, @return); accessor.Write(0, pos); } } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { SyncEvent.Dispose(); SharedMemory.Dispose(); } disposedValue = true; } } public object SendMessage(object[] args, [CallerMemberName] string callerName = null) { if (disposedValue) { throw new ObjectDisposedException(nameof(Channel)); } else { MethodInfo method = ServicingType.GetDeclaredMethod(callerName); ParameterInfo[] @params = method.GetParameters(); WriteData(callerName, @params, args, method.ReturnParameter); //Notify other side SetEvent(ChannelEventType.ChannelSync); //Wait while other side complete request SyncEvent.WaitOne(); //Check incoming event switch (GetEvent()) { case ChannelEventType.ChannelSync: case ChannelEventType.ChannelSync | ChannelEventType.LinuxSide: case ChannelEventType.ChannelSync | ChannelEventType.WindowsSide: case ChannelEventType.ChannelOpened: case ChannelEventType.ChannelOpened | ChannelEventType.LinuxSide: case ChannelEventType.ChannelOpened | ChannelEventType.WindowsSide: case ChannelEventType.ChannelOpened | ChannelEventType.LinuxSide | ChannelEventType.WindowsSide: break; case ChannelEventType.ChannelClosed: case ChannelEventType.ChannelClosed | ChannelEventType.LinuxSide: case ChannelEventType.ChannelClosed | ChannelEventType.WindowsSide: case ChannelEventType.ChannelClosed | ChannelEventType.LinuxSide | ChannelEventType.WindowsSide: Dispose(); throw new OperationCanceledException(); default: throw new NotSupportedException(); } List<ParameterInfo> byRef = @params.Where(x => x.IsOut && x.ParameterType.IsByRef).ToList(); object @return = null; if (byRef.Count > 0 || method.ReturnParameter != null) { if (ReadData(@params, args, method.ReturnParameter, out @return) != callerName) { throw new InvalidDataException(); } } return @return; } } public void ReceiveMessage() { if (disposedValue) { throw new ObjectDisposedException(nameof(Channel)); } else { //Wait while other side send request SyncEvent.WaitOne(); //Check incoming event switch (GetEvent()) { case ChannelEventType.ChannelSync: case ChannelEventType.ChannelSync | ChannelEventType.LinuxSide: case ChannelEventType.ChannelSync | ChannelEventType.WindowsSide: case ChannelEventType.ChannelOpened: case ChannelEventType.ChannelOpened | ChannelEventType.LinuxSide: case ChannelEventType.ChannelOpened | ChannelEventType.WindowsSide: case ChannelEventType.ChannelOpened | ChannelEventType.LinuxSide | ChannelEventType.WindowsSide: break; case ChannelEventType.ChannelClosed: case ChannelEventType.ChannelClosed | ChannelEventType.LinuxSide: case ChannelEventType.ChannelClosed | ChannelEventType.WindowsSide: case ChannelEventType.ChannelClosed | ChannelEventType.LinuxSide | ChannelEventType.WindowsSide: Dispose(); throw new OperationCanceledException(); default: throw new NotSupportedException(); } string callerName = ReadData(out object[] args, out _); MethodInfo method = ServicingType.GetDeclaredMethod(callerName); ParameterInfo[] @params = method.GetParameters(); object @return = method.Invoke(ServicingObject, args); List<ParameterInfo> byRef = @params.Where(x => x.IsOut && x.ParameterType.IsByRef).ToList(); if (byRef.Count > 0 || method.ReturnParameter != null) { WriteData(callerName, @params, args, method.ReturnParameter, @return); } //Notify other side SetEvent(ChannelEventType.ChannelSync); } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } }
46.102981
240
0.552375
[ "MIT" ]
DjArt/lxssex
src/Shared/lxssex.RPC/Channel.cs
17,014
C#
using System; using Ncqrs.Eventing.Sourcing; namespace Events { [Serializable] public class NoteTextChanged : SourcedEvent { public Guid NoteId { get; set; } public String NewText { get; set; } } }
15.285714
48
0.464174
[ "Apache-2.0" ]
SzymonPobiega/ncqrs
Samples/MyNotes/src/Events/NoteTextChanged.cs
323
C#
// Copyright (c) Amer Koleci and contributors. // Distributed under the MIT license. See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using SharpGen.Runtime; using Vortice.Direct2D1; namespace Vortice.DirectWrite { internal class IDWriteTextRendererShadow : IDWritePixelSnappingShadow { public static IntPtr ToIntPtr(IDWriteTextRenderer callback) { return ToCallbackPtr<IDWriteTextRenderer>(callback); } protected unsafe class IDWriteTextRendererVtbl : IDWritePixelSnappingVtbl { public IDWriteTextRendererVtbl(int nbMethods) : base(nbMethods + 4) { AddMethod(new DrawGlyphRunDelegate(DrawGlyphRunImpl)); AddMethod(new DrawUnderlineDelegate(DrawUnderlineImpl)); AddMethod(new DrawStrikethroughDelegate(DrawStrikethroughImpl)); AddMethod(new DrawInlineObjectDelegate(DrawInlineObjectImpl)); } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private unsafe delegate int DrawGlyphRunDelegate(IntPtr thisObject, IntPtr clientDrawingContext, float baselineOriginX, float baselineOriginY, MeasuringMode measuringMode, GlyphRun.__Native* glyphRunNative, GlyphRunDescription.__Native* glyphRunDescriptionNative, IntPtr clientDrawingEffect); private unsafe static int DrawGlyphRunImpl(IntPtr thisObject, IntPtr clientDrawingContextPtr, float baselineOriginX, float baselineOriginY, MeasuringMode measuringMode, GlyphRun.__Native* glyphRunNative, GlyphRunDescription.__Native* glyphRunDescriptionNative, IntPtr clientDrawingEffectPtr) { try { var shadow = ToShadow<IDWriteTextRendererShadow>(thisObject); var callback = (IDWriteTextRenderer)shadow.Callback; using (var glyphRun = new GlyphRun()) { glyphRun.__MarshalFrom(ref *glyphRunNative); var glyphRunDescription = new GlyphRunDescription(); glyphRunDescription.__MarshalFrom(ref *glyphRunDescriptionNative); callback.DrawGlyphRun(clientDrawingContextPtr, baselineOriginX, baselineOriginY, measuringMode, glyphRun, ref glyphRunDescription, clientDrawingEffectPtr == IntPtr.Zero ? null : (IUnknown)Marshal.GetObjectForIUnknown(clientDrawingEffectPtr)); } return Result.Ok.Code; } catch (Exception ex) { return Result.GetResultFromException(ex).Code; } } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private unsafe delegate int DrawUnderlineDelegate(IntPtr thisObject, IntPtr clientDrawingContext, float baselineOriginX, float baselineOriginY, Underline.__Native* underlineNative, IntPtr clientDrawingEffect); private unsafe static int DrawUnderlineImpl(IntPtr thisObject, IntPtr clientDrawingContextPtr, float baselineOriginX, float baselineOriginY, Underline.__Native* underlineNative, IntPtr clientDrawingEffectPtr) { try { var shadow = ToShadow<IDWriteTextRendererShadow>(thisObject); var callback = (IDWriteTextRenderer)shadow.Callback; var underline = new Underline(); underline.__MarshalFrom(ref *underlineNative); callback.DrawUnderline(clientDrawingContextPtr, baselineOriginX, baselineOriginY, ref underline, clientDrawingEffectPtr == IntPtr.Zero ? null : (IUnknown)Marshal.GetObjectForIUnknown(clientDrawingEffectPtr)); return Result.Ok.Code; } catch (Exception ex) { return Result.GetResultFromException(ex).Code; } } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private unsafe delegate int DrawStrikethroughDelegate(IntPtr thisObject, IntPtr clientDrawingContext, float baselineOriginX, float baselineOriginY, Strikethrough.__Native* strikethroughNative, IntPtr clientDrawingEffect); private unsafe static int DrawStrikethroughImpl(IntPtr thisObject, IntPtr clientDrawingContextPtr, float baselineOriginX, float baselineOriginY, Strikethrough.__Native* strikethroughNative, IntPtr clientDrawingEffectPtr) { try { var shadow = ToShadow<IDWriteTextRendererShadow>(thisObject); var callback = (IDWriteTextRenderer)shadow.Callback; var strikethrough = new Strikethrough(); strikethrough.__MarshalFrom(ref *strikethroughNative); callback.DrawStrikethrough(clientDrawingContextPtr, baselineOriginX, baselineOriginY, ref strikethrough, clientDrawingEffectPtr == IntPtr.Zero ? null : (IUnknown)Marshal.GetObjectForIUnknown(clientDrawingEffectPtr)); return Result.Ok.Code; } catch (Exception ex) { return Result.GetResultFromException(ex).Code; } } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DrawInlineObjectDelegate(IntPtr thisObject, IntPtr clientDrawingContext, float originX, float originY, IntPtr inlineObject, int isSideways, int isRightToLeft, IntPtr clientDrawingEffect); private static int DrawInlineObjectImpl(IntPtr thisObject, IntPtr clientDrawingContextPtr, float originX, float originY, IntPtr inlineObject, int isSideways, int isRightToLeft, IntPtr clientDrawingEffectPtr) { try { var shadow = ToShadow<IDWriteTextRendererShadow>(thisObject); var callback = (IDWriteTextRenderer)shadow.Callback; callback.DrawInlineObject(clientDrawingContextPtr, originX, originY, inlineObject == IntPtr.Zero ? null : new IDWriteInlineObjectNative(inlineObject), isSideways != 0, isRightToLeft != 0, clientDrawingEffectPtr == IntPtr.Zero ? null : (IUnknown)Marshal.GetObjectForIUnknown(clientDrawingEffectPtr)); return Result.Ok.Code; } catch (Exception ex) { return Result.GetResultFromException(ex).Code; } } } protected override CppObjectVtbl Vtbl { get; } = new IDWriteTextRendererVtbl(0); } }
56.791045
304
0.583837
[ "MIT" ]
Ethereal77/Vortice.Windows
src/Vortice.Direct2D1/DirectWrite/IDWriteTextRendererShadow.cs
7,612
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace gcl2 { public class GrammaticException : SintacticParserException { public Symbol Producer { get; private set; } public List<LinkedList<Symbol>> Productions { get; private set; } public GrammaticException(string message, Symbol producer) : this(message, producer, new LinkedList<Symbol>[] { }) { } public GrammaticException(string message, Symbol producer, IEnumerable<LinkedList<Symbol>> productions) : base(message) { Producer = producer; Productions = new List<LinkedList<Symbol>>(productions); } } }
27
111
0.643347
[ "MIT" ]
Isracg/GCL
gcl2/GrammaticException.cs
731
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("UI-elementsWPF")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UI-elementsWPF")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42.428571
98
0.709175
[ "MIT" ]
readerboy17/SE-4220_UI-elementsWPF
UI-elementsWPF/Properties/AssemblyInfo.cs
2,379
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AppNetDotNet.Model; using Newtonsoft.Json; namespace AppNetDotNet.ApiCalls { public class Broadcasts { // public Broadcast.Channel create_channel(string title, string description, List<string> editors, bool public = true, public static Tuple<Channel, ApiCallResponse> subscribe(string access_token, string id) { return Channels.Subscriptions.subscribe(access_token, id); } public static Tuple<Channel, ApiCallResponse> unsubscribe(string access_token, string id) { return Channels.Subscriptions.unsubscribe(access_token, id); } public static Tuple<List<Broadcast.Broadcast_Channel>, ApiCallResponse> getOfCurrentUser(string access_token) { Channels.channelParameters parameters = new Channels.channelParameters(); parameters.channel_types = "net.app.core.broadcast"; parameters.include_annotations = true; Tuple<List<Channel>, ApiCallResponse> channels = Channels.Subscriptions.getOfCurrentUser(access_token, parameters); if (channels.Item2.success) { List<Broadcast.Broadcast_Channel> broadcast_channels = new List<Broadcast.Broadcast_Channel>(); foreach (Channel channel in channels.Item1) { broadcast_channels.Add(new Broadcast.Broadcast_Channel(channel)); } return new Tuple<List<Broadcast.Broadcast_Channel>, ApiCallResponse>(broadcast_channels, channels.Item2); } else { return new Tuple<List<Broadcast.Broadcast_Channel>, ApiCallResponse>(null, channels.Item2); } } public static Tuple<Broadcast.Broadcast_Channel, ApiCallResponse> get(string access_token, string id) { Channels.channelParameters parameters = new Channels.channelParameters(); parameters.channel_types = "net.app.core.broadcast"; parameters.include_annotations = true; Tuple<Channel,ApiCallResponse> channel = Channels.get(access_token, id); if (channel.Item2.success) { return new Tuple<Broadcast.Broadcast_Channel, ApiCallResponse>(new Broadcast.Broadcast_Channel(channel.Item1), channel.Item2); } else { return new Tuple<Broadcast.Broadcast_Channel, ApiCallResponse>(null, channel.Item2); } } public static Tuple<List<Broadcast.Broadcast_Message>, ApiCallResponse> getMessagesInChannel(string accessToken, string channelId) { List<Broadcast.Broadcast_Message> broadcasts = new List<Broadcast.Broadcast_Message>(); Messages.messageParameters parameters = new Messages.messageParameters(); parameters.include_message_annotations = true; parameters.include_annotations = true; parameters.include_user_annotations = true; Tuple<List<Message>, ApiCallResponse> entries = AppNetDotNet.ApiCalls.Messages.getMessagesInChannel(accessToken, channelId, parameters); if (entries.Item2.success) { foreach (Message message in entries.Item1) { broadcasts.Add(new Broadcast.Broadcast_Message(message)); } } return new Tuple<List<Broadcast.Broadcast_Message>, ApiCallResponse>(broadcasts, entries.Item2); } public static Tuple<Message, ApiCallResponse> create_message( string access_token, string channel_id, string headline, string text = null, string read_more_link = null, List<File> toBeEmbeddedFiles = null) { Model.Annotations.Broadcast_Message_Metadata message_annotations = new Model.Annotations.Broadcast_Message_Metadata(); message_annotations.subject = headline; List<Annotation> annotations = new List<Annotation>(); Annotation annotation = new Annotation("net.app.core.broadcast.message.metadata", message_annotations); annotations.Add(annotation); if (!string.IsNullOrEmpty(read_more_link)) { Model.Annotations.Crosspost crosspost_annotation = new Model.Annotations.Crosspost(); crosspost_annotation.canonical_url = read_more_link; Annotation annotation_more_link = new Annotation("net.app.core.crosspost", crosspost_annotation); annotations.Add(annotation_more_link); } int machine_only = 1; if (!string.IsNullOrEmpty(text)) { machine_only = 0; } return Messages.create(access_token, text, channel_id, null, annotations: annotations, machineOnly: machine_only, parse_links: true, parse_markdown_links: true, toBeEmbeddedFiles: toBeEmbeddedFiles); } } }
45.301724
149
0.630067
[ "BSD-3-Clause" ]
liGhun/AppNet.NET
AppNetDotNet/ApiCalls/Broadcasts.cs
5,257
C#
/* BehaviourTreeDesigner Copyright (c) 2021 David McDonagh 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; using System.Collections.Generic; using UnityEngine; using NUnit.Framework; using UnityEngine.TestTools; public class BehaviourTreeStructureTests { [Test] public void NotEmpty_Test(){ BehaviourTreeStructure treeStructure = new BehaviourTreeStructure(); Dictionary<string, NodeStructure> emptyStructure = new Dictionary<string, NodeStructure>(); Assert.IsFalse(treeStructure.NotEmpty(emptyStructure)); } [Test] public void ContainsRootNode_Test(){ BehaviourTreeStructure treeStructure = new BehaviourTreeStructure(); Dictionary<string, NodeStructure> structure = new Dictionary<string, NodeStructure>(); Assert.IsFalse(treeStructure.ContainsRootNode(structure)); NodeStructure rootNode = new NodeStructure("Root", "PrioritySelector", new List<string>(), Vector2.zero); structure["Root"] = rootNode; Assert.IsTrue(treeStructure.ContainsRootNode(structure)); } [Test] public void AllChildrenExist_Test(){ BehaviourTreeStructure treeStructure = new BehaviourTreeStructure(); Dictionary<string, NodeStructure> structure = new Dictionary<string, NodeStructure>(); NodeStructure childNode1 = new NodeStructure("ChildNode1", "Action", new List<string>(), Vector2.zero); NodeStructure childNode2 = new NodeStructure("ChildNode2", "Action", new List<string>(), Vector2.zero); List<string> childNodes = new List<string>{"ChildNode1", "ChildNode2"}; NodeStructure rootNode = new NodeStructure("Root", "PrioritySelector", childNodes, Vector2.zero); structure["Root"] = rootNode; Assert.IsFalse(treeStructure.AllChildrenExist(structure)); structure["ChildNode1"] = childNode1; Assert.IsFalse(treeStructure.AllChildrenExist(structure)); structure["ChildNode2"] = childNode2; Assert.IsTrue(treeStructure.AllChildrenExist(structure)); } [Test] public void AllNodesConnected_Test(){ BehaviourTreeStructure treeStructure = new BehaviourTreeStructure(); Dictionary<string, NodeStructure> structure = new Dictionary<string, NodeStructure>(); NodeStructure childNode1 = new NodeStructure("ChildNode1", "Action", new List<string>(), Vector2.zero); NodeStructure childNode2 = new NodeStructure("ChildNode2", "Action", new List<string>(), Vector2.zero); List<string> childNodes = new List<string>{"ChildNode1", "ChildNode2"}; NodeStructure rootNode = new NodeStructure("Root", "PrioritySelector", childNodes, Vector2.zero); structure["Root"] = rootNode; structure["childNode1"] = childNode1; structure["childNode2"] = childNode2; Assert.IsTrue(treeStructure.AllNodesConnected(structure)); NodeStructure unconnectedNode = new NodeStructure("node", "Action", new List<string>(), Vector2.zero); structure["unconnectedNode"] = unconnectedNode; Assert.IsFalse(treeStructure.AllNodesConnected(structure)); } [Test] public void AllChildrenUnique_Test(){ BehaviourTreeStructure treeStructure = new BehaviourTreeStructure(); Dictionary<string, NodeStructure> structure = new Dictionary<string, NodeStructure>(); NodeStructure childNode1 = new NodeStructure("ChildNode1", "Action", new List<string>(), Vector2.zero); NodeStructure childNode2 = new NodeStructure("ChildNode2", "Action", new List<string>(), Vector2.zero); List<string> childNodes = new List<string>{"ChildNode1", "ChildNode2"}; NodeStructure rootNode = new NodeStructure("Root", "PrioritySelector", childNodes, Vector2.zero); structure["Root"] = rootNode; structure["childNode1"] = childNode1; structure["childNode2"] = childNode2; Assert.IsTrue(treeStructure.AllChildrenUnique(structure)); childNode2 = new NodeStructure("ChildNode2", "Action", new List<string>{"ChildNode1"}, Vector2.zero); structure["childNode2"] = childNode2; Assert.IsFalse(treeStructure.AllChildrenUnique(structure)); } [Test] public void GetParentName_Test(){ BehaviourTreeStructure treeStructure = new BehaviourTreeStructure(); Dictionary<string, NodeStructure> structure = new Dictionary<string, NodeStructure>(); NodeStructure childNode1 = new NodeStructure("ChildNode1", "Action", new List<string>(), Vector2.zero); List<string> childNodes = new List<string>{"ChildNode1"}; NodeStructure rootNode = new NodeStructure("Root", "PrioritySelector", childNodes, Vector2.zero); structure["Root"] = rootNode; structure["childNode1"] = childNode1; Assert.AreEqual("Root", treeStructure.GetParentName(structure, childNode1)); } [Test] public void GetAllNodeNames_Test(){ BehaviourTreeStructure treeStructure = new BehaviourTreeStructure(); Dictionary<string, NodeStructure> structure = new Dictionary<string, NodeStructure>(); NodeStructure childNode1 = new NodeStructure("ChildNode1", "Action", new List<string>(), Vector2.zero); List<string> childNodes = new List<string>{"ChildNode1"}; NodeStructure rootNode = new NodeStructure("Root", "PrioritySelector", childNodes, Vector2.zero); structure["Root"] = rootNode; structure["ChildNode1"] = childNode1; List<string> nodeNames = treeStructure.GetAllNodeNames(structure); Assert.IsTrue(nodeNames.Count == 2); Assert.IsTrue(nodeNames.Contains("Root")); Assert.IsTrue(nodeNames.Contains("ChildNode1")); } [Test] public void GetAllChildNodeNames_Test(){ BehaviourTreeStructure treeStructure = new BehaviourTreeStructure(); Dictionary<string, NodeStructure> structure = new Dictionary<string, NodeStructure>(); NodeStructure childNode1 = new NodeStructure("ChildNode1", "Action", new List<string>(), Vector2.zero); List<string> childNodes = new List<string>{"ChildNode1"}; NodeStructure rootNode = new NodeStructure("Root", "PrioritySelector", childNodes, Vector2.zero); structure["Root"] = rootNode; structure["ChildNode1"] = childNode1; List<string> nodeNames = treeStructure.GetAllChildNodeNames(structure); Assert.IsTrue(nodeNames.Count == 1); Assert.IsTrue(nodeNames.Contains("ChildNode1")); } [Test] public void GetNumNodesOfType_Test(){ BehaviourTreeStructure treeStructure = new BehaviourTreeStructure(); Dictionary<string, NodeStructure> structure = new Dictionary<string, NodeStructure>(); NodeStructure childNode1 = new NodeStructure("ChildNode1", "Action", new List<string>(), Vector2.zero); NodeStructure childNode2 = new NodeStructure("ChildNode2", "Action", new List<string>(), Vector2.zero); List<string> childNodes = new List<string>{"ChildNode1", "ChildNode2"}; NodeStructure rootNode = new NodeStructure("Root", "PrioritySelector", childNodes, Vector2.zero); structure["Root"] = rootNode; structure["childNode1"] = childNode1; structure["childNode2"] = childNode2; int expectedNum = 2; int actualNum = treeStructure.GetNumNodesOfType(structure, "Action"); Assert.AreEqual(expectedNum, actualNum); } }
43.331633
113
0.709172
[ "MIT" ]
toastisme/BehaviourTreeDesigner
Tests/Runtime/BehaviourTreeStructureTests.cs
8,493
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace System.Reflection.Emit { public partial class ILGenerator { internal ILGenerator() { // Prevent generating a default constructor } public virtual int ILOffset { get { return default; } } public virtual void BeginCatchBlock(Type? exceptionType) { } public virtual void BeginExceptFilterBlock() { } public virtual Label BeginExceptionBlock() { return default; } public virtual void BeginFaultBlock() { } public virtual void BeginFinallyBlock() { } public virtual void BeginScope() { } public virtual LocalBuilder DeclareLocal(Type localType) { return default; } public virtual LocalBuilder DeclareLocal(Type localType, bool pinned) { return default; } public virtual Label DefineLabel() { return default; } public virtual void Emit(OpCode opcode) { } public virtual void Emit(OpCode opcode, byte arg) { } public virtual void Emit(OpCode opcode, double arg) { } public virtual void Emit(OpCode opcode, short arg) { } public virtual void Emit(OpCode opcode, int arg) { } public virtual void Emit(OpCode opcode, long arg) { } public virtual void Emit(OpCode opcode, ConstructorInfo con) { } public virtual void Emit(OpCode opcode, Label label) { } public virtual void Emit(OpCode opcode, Label[] labels) { } public virtual void Emit(OpCode opcode, LocalBuilder local) { } public virtual void Emit(OpCode opcode, SignatureHelper signature) { } public virtual void Emit(OpCode opcode, FieldInfo field) { } public virtual void Emit(OpCode opcode, MethodInfo meth) { } [CLSCompliantAttribute(false)] public void Emit(OpCode opcode, sbyte arg) { } public virtual void Emit(OpCode opcode, float arg) { } public virtual void Emit(OpCode opcode, string str) { } public virtual void Emit(OpCode opcode, Type cls) { } public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) { } public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { } public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) { } public virtual void EmitWriteLine(LocalBuilder localBuilder) { } public virtual void EmitWriteLine(FieldInfo fld) { } public virtual void EmitWriteLine(string value) { } public virtual void EndExceptionBlock() { } public virtual void EndScope() { } public virtual void MarkLabel(Label loc) { } public virtual void ThrowException([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type excType) { } public virtual void UsingNamespace(string usingNamespace) { } } }
22.061798
161
0.564808
[ "MIT" ]
LoopedBard3/runtime
src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs
3,929
C#
// Copyright (c) 2020, UW Medicine Research IT, University of Washington // Developed by Nic Dobbins and Cliff Spital, CRIO Sean Mooney // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. using System; using System.Collections.Generic; using Model.Cohort; using Model.Compiler; namespace API.DTO.Cohort { public class DatasetDTO { public DatasetResultSchemaDTO Schema { get; set; } public Dictionary<string, IEnumerable<object>> Results { get; set; } public DatasetDTO() { } public DatasetDTO(Dataset dataset) { Schema = dataset.Schema.Shape == Shape.Dynamic ? new DynamicDatasetResultSchemaDTO(dataset.Schema) : new DatasetResultSchemaDTO(dataset.Schema); Results = dataset.Results; } public DatasetDTO(DatasetProvider.Result result) : this(result.Dataset) { } } }
29.944444
79
0.653061
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
BayesianGraph/leaf
src/server/API/DTO/Cohort/DatasetDTO.cs
1,080
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Internal { using System.Collections; using System.ComponentModel; using System.Data.Entity.Infrastructure; using System.Data.Entity.Resources; using System.Data.Entity.Utilities; // <summary> // Represents a raw SQL query against the context that may be for entities in an entity set // or for some other non-entity element type. // </summary> internal abstract class InternalSqlQuery : IEnumerable #if !NET40 , IDbAsyncEnumerable #endif { #region Constructors and fields private readonly string _sql; private readonly object[] _parameters; private readonly bool? _streaming; // <summary> // Initializes a new instance of the <see cref="InternalSqlQuery" /> class. // </summary> // <param name="sql"> The SQL. </param> // <param name="streaming"> Whether the query is streaming or buffering. </param> // <param name="parameters"> The parameters. </param> internal InternalSqlQuery(string sql, bool? streaming, object[] parameters) { DebugCheck.NotNull(sql); DebugCheck.NotNull(parameters); _sql = sql; _parameters = parameters; _streaming = streaming; } #endregion #region Access to the SQL string and parameters // <summary> // Gets the SQL query string, // </summary> // <value> The SQL query. </value> public string Sql { get { return _sql; } } // <summary> // Get the query streaming behavior. // </summary> // <value> // <c>true</c> if the query is streaming; // <c>false</c> if the query is buffering // </value> internal bool? Streaming { get { return _streaming; } } // <summary> // Gets the parameters. // </summary> // <value> The parameters. </value> public object[] Parameters { get { return _parameters; } } #endregion #region AsNoTracking // <summary> // If the query is tracking entities, then this method returns a new query that will // not track entities. // </summary> // <returns> A no-tracking query. </returns> public abstract InternalSqlQuery AsNoTracking(); #endregion #region AsStreaming // <summary> // If the query is buffering, then this method returns a new query that will stream // the results instead. // </summary> // <returns> A streaming query. </returns> public abstract InternalSqlQuery AsStreaming(); #endregion #region IEnumerable implementation // <summary> // Returns an <see cref="IEnumerator" /> which when enumerated will execute the given SQL query against the database. // </summary> // <returns> The query results. </returns> public abstract IEnumerator GetEnumerator(); #endregion #region IDbAsyncEnumerable implementation #if !NET40 // <summary> // Returns an <see cref="IDbAsyncEnumerator" /> which when enumerated will execute the given SQL query against the database. // </summary> // <returns> The query results. </returns> public abstract IDbAsyncEnumerator GetAsyncEnumerator(); #endif #endregion #region ToString // <summary> // Returns a <see cref="System.String" /> that contains the SQL string that was set // when the query was created. The parameters are not included. // </summary> // <returns> // A <see cref="System.String" /> that represents this instance. // </returns> public override string ToString() { return Sql; } #endregion } }
29.65
133
0.581547
[ "Apache-2.0" ]
CZEMacLeod/EntityFramework6
src/EntityFramework/Internal/InternalSqlQuery.cs
4,153
C#
namespace CityBreaks.Models { public class Property { } }
11.666667
28
0.628571
[ "MIT" ]
mikebrind/Razor-Pages-In-Action
Chapter07/DependencyInversionPrincipal/CityBreaks/Models/Property.cs
72
C#
using System.Collections.Generic; using UnityEngine; namespace Oxide.Plugins { [Info("Bye Fireballs", "Ryz0r", "1.0.2")] [Description("Removes fireballs from MiniCopter crashes.")] public class ByeFireballs : RustPlugin { private void OnEntitySpawned(BaseHelicopterVehicle m) { m.fireBall.guid = null; } } }
24.266667
63
0.648352
[ "MIT" ]
nackerr/uMod-Plugins
Plugins/ByeFireballs.cs
364
C#
namespace BabelBot.Receiver.Commands; public class NoDefaultCommandException : Exception { public NoDefaultCommandException() : base("No default command set up") { } }
24.714286
78
0.774566
[ "MIT" ]
RauchF/BabelBot
src/BabelBot.Receiver.Commands/Exceptions/NoDefaultCommandException.cs
173
C#
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Runtime.InteropServices; using System.Text; using Silk.NET.Core.Native; using Ultz.SuperInvoke; #pragma warning disable 1591 namespace Silk.NET.Vulkan { public unsafe struct PipelineCompilerControlCreateInfoAMD { public PipelineCompilerControlCreateInfoAMD ( StructureType sType = StructureType.PipelineCompilerControlCreateInfoAmd, void* pNext = default, PipelineCompilerControlFlagsAMD compilerControlFlags = default ) { SType = sType; PNext = pNext; CompilerControlFlags = compilerControlFlags; } /// <summary></summary> public StructureType SType; /// <summary></summary> public void* PNext; /// <summary></summary> public PipelineCompilerControlFlagsAMD CompilerControlFlags; } }
26.025641
85
0.681773
[ "MIT" ]
AzyIsCool/Silk.NET
src/Vulkan/Silk.NET.Vulkan/Structs/PipelineCompilerControlCreateInfoAMD.gen.cs
1,015
C#
// Copyright 2016 Esri // // 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. // System using System.Windows.Controls; using DistanceAndDirectionLibrary.Helpers; using DistanceAndDirectionLibrary.Views; using DistanceAndDirectionLibrary; using DistanceAndDirectionLibrary.ViewModels; using DistanceAndDirectionLibrary.Models; namespace ArcMapAddinDistanceAndDirection.ViewModels { public class MainViewModel : BaseViewModel { public MainViewModel() { // set some views and datacontext LinesView = new GRLinesView(); LinesView.DataContext = new LinesViewModel(); CircleView = new GRCircleView(); CircleView.DataContext = new CircleViewModel(); EllipseView = new GREllipseView(); EllipseView.DataContext = new EllipseViewModel(); RangeView = new GRRangeView(); RangeView.DataContext = new RangeViewModel(); // load the configuration file DistanceAndDirectionConfig.AddInConfig.LoadConfiguration(); } #region Properties object selectedTab = null; public object SelectedTab { get { return selectedTab; } set { // Don't raise event if same tab selected if (selectedTab == value) return; selectedTab = value; var tabItem = selectedTab as TabItem; if (tabItem == null) return; Mediator.NotifyColleagues(Constants.TAB_ITEM_SELECTED, ((tabItem.Content as UserControl).Content as UserControl).DataContext); } } #region Views public GRLinesView LinesView { get; set; } public GRCircleView CircleView { get; set; } public GREllipseView EllipseView { get; set; } public GRRangeView RangeView { get; set; } #endregion #endregion } }
31.024691
142
0.632312
[ "Apache-2.0" ]
ArcGIS/distance-direction-addin-dotnet
source/addins/ArcMapAddinDistanceAndDirection/ArcMapAddinDistanceAndDirection/ViewModels/MainViewModel.cs
2,515
C#
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using XiaoQi.EFCore; using XiaoQi.EFCore.Models; using XiaoQi.IService; using XiaoQi.Model; namespace XiaoQi.Controllers { [Route("api/[controller]/[action]")] [ApiController] [Authorize("MyPolicy")] public class XqArticleLookController : ControllerBase { private readonly IXqArticleLookService _xqArticleLookService; private MessageModel messageModel = new MessageModel(); public XqArticleLookController (IXqArticleLookService xqArticleLookService) { _xqArticleLookService = xqArticleLookService; } /// <summary> /// 获取 /// </summary> /// <returns></returns> [HttpGet] public IActionResult GetXqArticleLooks() { var res = _xqArticleLookService.Query(); messageModel.response = res; return new JsonResult(messageModel); } /// <summary> /// 添加 /// </summary> /// <param name="userinfo"></param> /// <returns></returns> [HttpPost] public async Task<IActionResult> AddXqArticleLook(XqArticleLook xqArticleLook) { var res = await _xqArticleLookService.Add(xqArticleLook); if (res) messageModel.response = true; else { messageModel.response = false; messageModel.msg = "添加失败"; } return new JsonResult(messageModel); } /// <summary> /// 更新 /// </summary> /// <param name="xqArticleLook"></param> /// <returns></returns> [HttpPut] public async Task<IActionResult> UpdateXqArticleLook(XqArticleLook xqArticleLook) { var res = await _xqArticleLookService.Update(xqArticleLook); if (res) messageModel.response = true; else { messageModel.response = false; messageModel.msg = "更新失败"; } return new JsonResult(messageModel); } /// <summary> /// 删除 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpDelete] public async Task<IActionResult> DeleteById(string id) { var res = await _xqArticleLookService.Delete(id); if (res) messageModel.response = true; else { messageModel.response = false; messageModel.msg = "删除失败"; } return new JsonResult(messageModel); } } }
31.707071
93
0.503345
[ "Apache-2.0" ]
xiaoqiyaozou1/XiaoQi
XiaoQi/Controllers/XqArticleLookController .cs
3,179
C#