text
stringlengths
13
6.01M
using physics2; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Physics2 { internal static class PhysicsMath { private const double CLOSE = .01; internal static DoubleUpdatePositionVelocityEvent DoCollisionInfiniteMass( PhysicsObject physicsObject, IPhysicsObject physicsObjectInfiniteMass, double radius1, double time, Vector normal, Vector velocityVector, Vector velocityVectorInfiniteMass) { var normalVelocity1 = normal.Dot(velocityVector); var normalVelocity2 = normal.Dot(velocityVectorInfiniteMass); var finalV1 = velocityVector .NewAdded(normal.NewScaled(normalVelocity1).NewMinus()) .NewAdded(normal.NewScaled(normalVelocity1).NewMinus()) .NewAdded(normal.NewScaled(normalVelocity2)) .NewAdded(normal.NewScaled(normalVelocity2)); var force = physicsObject.Mass *((normalVelocity1 * 2) + (normalVelocity2 * 2)); return new DoubleUpdatePositionVelocityEvent( time, physicsObject, finalV1.x, finalV1.y, physicsObjectInfiniteMass, velocityVectorInfiniteMass.x, velocityVectorInfiniteMass.y, new MightBeCollision(new Collision( physicsObject.X + (time * physicsObject.Vx) + normal.NewScaled(-radius1).x, physicsObject.Y + (time * physicsObject.Vy) + normal.NewScaled(-radius1).y, normal.NewScaled(force).x, normal.NewScaled(force).y, false ))); } internal static DoubleUpdatePositionVelocityEvent DoCollision( PhysicsObject physicsObject1, IPhysicsObject physicsObject2, double radius1, double time, Vector normal, Vector velocityVector1, Vector velocityVector2 ) { // update the V of both // when a collision happen how does it go down? // the velocities we care about are normal to the line // we find the normal and take the dot product var v1 = normal.Dot(velocityVector1); var m1 = physicsObject1.Mass; var v2 = normal.Dot(velocityVector2); var m2 = physicsObject2.Mass; if (physicsObject1.Mobile == false) { var o2v = normal.NewScaled(-2 * v2).NewAdded(physicsObject2.Velocity); return new DoubleUpdatePositionVelocityEvent( time, physicsObject1, physicsObject1.Vx, physicsObject1.Vy, physicsObject2, o2v.x, o2v.y, new MightBeCollision( new Collision( physicsObject1.X + (time * physicsObject1.Vx) + normal.NewScaled(radius1).x, physicsObject1.Y + (time * physicsObject1.Vy) + normal.NewScaled(radius1).y, normal.NewScaled(-2 * v2 * m2).x, normal.NewScaled(-2 * v2 * m2).y, false ))); } else if (physicsObject2.Mobile == false) { var v1o = normal.NewScaled(-2 * v1).NewAdded(physicsObject1.Velocity); return new DoubleUpdatePositionVelocityEvent( time, physicsObject1, v1o.x, v1o.y, physicsObject2, physicsObject2.Vx, physicsObject2.Vy, new MightBeCollision( new Collision( physicsObject1.X + (time * physicsObject1.Vx) + normal.NewScaled(radius1).x, physicsObject1.Y + (time * physicsObject1.Vy) + normal.NewScaled(radius1).y, normal.NewScaled(-2 * v2 * m2).x, normal.NewScaled(-2 * v2 * m2).y, false))); } else { // we do the physics and we get a quadratic for vf2 var c1 = (v1 * m1) + (v2 * m2); var c2 = (v1 * v1 * m1) + (v2 * v2 * m2); var A = (m2 * m2) + (m2 * m1); var B = -2 * m2 * c1; var C = (c1 * c1) - (c2 * m1); double vf2; if (A != 0) { // b^2 - 4ac var D = (B * B) - (4 * A * C); if (D >= 0) { var vf2_plus = (-B + Math.Sqrt(D)) / (2 * A); var vf2_minus = (-B - Math.Sqrt(D)) / (2 * A); if (IsGood(vf2_minus, v2) && IsGood(vf2_plus, v2) && vf2_plus != vf2_minus) { if (Math.Abs(v2 - vf2_plus) > Math.Abs(v2 - vf2_minus)) { if (Math.Abs(v2 - vf2_minus) > CLOSE) { throw new Exception("we are getting physicsObject2 vf2s: " + vf2_plus + "," + vf2_minus + " for vi2: " + v2); } vf2 = vf2_plus; } else { if (Math.Abs(v2 - vf2_plus) > CLOSE) { throw new Exception("we are getting physicsObject2 vf2s: " + vf2_plus + "," + vf2_minus + " for vi2: " + v2); } vf2 = vf2_minus; } } else if (IsGood(vf2_minus, v2)) { vf2 = vf2_minus; } else if (IsGood(vf2_plus, v2)) { vf2 = vf2_plus; } else { throw new Exception("we are getting no vfs"); } } else { throw new Exception("should not be negative"); } } else { throw new Exception("A should not be 0! if A is zer something has 0 mass"); } { var o2v = normal.NewScaled(vf2).NewAdded(normal.NewScaled(-v2)).NewAdded(physicsObject2.Velocity); var f = (vf2 - v2) * m2; var vf1 = v1 - (f / m1); var o1v = normal.NewScaled(vf1).NewAdded(normal.NewScaled(-v1)).NewAdded(physicsObject1.Velocity); return new DoubleUpdatePositionVelocityEvent( time, physicsObject1, o1v.x, o1v.y, physicsObject2, o2v.x, o2v.y, new MightBeCollision(new Collision( physicsObject1.X + (time * physicsObject1.Vx) + normal.NewScaled(-radius1).x, physicsObject1.Y + (time * physicsObject1.Vy) + normal.NewScaled(-radius1).y, normal.NewScaled(f).x, normal.NewScaled(f).y, false ))); } } } private static Vector GetNormal(IPhysicsObject physicsObject1, double X, double Y, double Vx, double Vy, double time) { var dx = physicsObject1.X + (time * physicsObject1.Vx) - (X + (time * Vx)); var dy = physicsObject1.Y + (time * physicsObject1.Vy) - (Y + (time * Vy)); var normal = new Vector(dx, dy).NewUnitized(); return normal; } private static bool IsGood(double vf, double v) { return vf != v; } internal static bool TryCollisionBallInfiniteMass(PhysicsObject self, IPhysicsObject collider, double particalX, double particalY, double particalVx, double particalVy, Circle c1, Circle c2, double endTime, out DoubleUpdatePositionVelocityEvent evnt) { // how are they moving relitive to us double DVX = particalVx - self.Vx, DVY = particalVy - self.Vy; var thisX0 = self.X; var thisY0 = self.Y; var thatX0 = particalX; var thatY0 = particalY; // how far they are from us var DX = thatX0 - thisX0; var DY = thatY0 - thisY0; // if the objects are not moving towards each other dont bother var V = -new Vector(DVX, DVY).Dot(new Vector(DX, DY).NewUnitized()); if (V <= 0) { evnt = default; return false; } var R = c1.Radius + c2.Radius; var A = (DVX * DVX) + (DVY * DVY); var B = 2 * ((DX * DVX) + (DY * DVY)); var C = (DX * DX) + (DY * DY) - (R * R); if (TrySolveQuadratic(A, B, C, out var time) && time <= endTime) { evnt = DoCollisionInfiniteMass(self, collider, c1.Radius, time, GetNormal(self, particalX, particalY, particalVx, particalVy, time), self.Velocity, collider.Velocity); return true; } evnt = default; return false; } internal static bool TryPickUpBall(Ball ball, Player player, double particalX, double particalY, double particalVx, double particalVy, Circle c1, Circle c2, double endTime, out UpdateOwnerEvent evnt) { // how are they moving relitive to us double DVX = particalVx - ball.Vx, DVY = particalVy - ball.Vy; var thisX0 = ball.X; var thisY0 = ball.Y; var thatX0 = particalX; var thatY0 = particalY; // how far they are from us var DX = thatX0 - thisX0; var DY = thatY0 - thisY0; // if the objects are not moving towards each other dont bother var V = -new Vector(DVX, DVY).Dot(new Vector(DX, DY).NewUnitized()); if (V <= 0) { evnt = default; return false; } var R = c1.Radius + c2.Radius; var A = (DVX * DVX) + (DVY * DVY); var B = 2 * ((DX * DVX) + (DY * DVY)); var C = (DX * DX) + (DY * DY) - (R * R); if (TrySolveQuadratic(A, B, C, out var time) && time <= endTime) { evnt = new UpdateOwnerEvent(ball, time,player); return true; } evnt = default; return false; } internal static bool TryCollisionBall(PhysicsObject self, IPhysicsObject collider, double particalX, double particalY, double particalVx, double particalVy, Circle c1, Circle c2, double endTime, out DoubleUpdatePositionVelocityEvent evnt) { // how are they moving relitive to us double DVX = particalVx - self.Vx, DVY = particalVy - self.Vy; var thisX0 = self.X; var thisY0 = self.Y; var thatX0 = particalX; var thatY0 = particalY; // how far they are from us var DX = thatX0 - thisX0; var DY = thatY0 - thisY0; // if the objects are not moving towards each other dont bother var V = -new Vector(DVX, DVY).Dot(new Vector(DX, DY).NewUnitized()); if (V <= 0) { evnt = default; return false; } var R = c1.Radius + c2.Radius; var A = (DVX * DVX) + (DVY * DVY); var B = 2 * ((DX * DVX) + (DY * DVY)); var C = (DX * DX) + (DY * DY) - (R * R); if (TrySolveQuadratic(A, B, C, out var time) && time <= endTime) { evnt = DoCollision(self, collider, c1.Radius, time, GetNormal(self, particalX, particalY, particalVx, particalVy, time), self.Velocity, collider.Velocity); return true; } evnt = default; return false; } internal static bool TryCollisionPointCloudParticle( PhysicsObject self, PhysicsObject collider, double particalX, double particalY, double particalVx, double particalVy , Circle c1, Circle c2, double endTime, out IEvent evnt) { // how are they moving relitive to us double DVX = particalVx - self.Vx, DVY = particalVy - self.Vy; var thisX0 = self.X; var thisY0 = self.Y; // how far they are from us var DX = particalX - thisX0; var DY = particalY - thisY0; // if the objects are not moving towards each other dont bother var V = -new Vector(DVX, DVY).Dot(new Vector(DX, DY).NewUnitized()); if (V <= 0) { evnt = default; return false; } var R = c1.Radius + c2.Radius; var A = (DVX * DVX) + (DVY * DVY); var B = 2 * ((DX * DVX) + (DY * DVY)); var C = (DX * DX) + (DY * DY) - (R * R); if (TrySolveQuadratic(A, B, C, out var time) && time <= endTime) { evnt = DoCollision(self, collider, c1.Radius, time, new Vector(collider.Vx, collider.Vy).NewUnitized(), self.Velocity, collider.Velocity); return true; } evnt = default; return false; } public static bool TrySolveQuadratic(double a, double b, double c, out double res) { if (a == 0) { if (b == 0) { if (c == 0) { res = 0; return true; } res = default; return false; } res = -c / b; return true; } var sqrtpart = (b * b) - (4 * a * c); double x1, x2; if (sqrtpart > 0) { x1 = (-b + Math.Sqrt(sqrtpart)) / (2 * a); x2 = (-b - Math.Sqrt(sqrtpart)) / (2 * a); res = Math.Min(x1, x2); return true; } else if (sqrtpart < 0) { res = default; return false; } else { res = (-b + Math.Sqrt(sqrtpart)) / (2 * a); return true; } } public static IEnumerable<double> SolveQuadratic(double a, double b, double c) { if (a == 0) { if (b == 0) { if (c == 0) { return new double[] { 0 }; } return new double[] { }; } return new double[] { -c / b }; } var sqrtpart = (b * b) - (4 * a * c); if (sqrtpart > 0) { return new[] { (-b + Math.Sqrt(sqrtpart)) / (2 * a), (-b - Math.Sqrt(sqrtpart)) / (2 * a) }; } else if (sqrtpart < 0) { return new double[] { }; } else { return new double[] { (-b + Math.Sqrt(sqrtpart)) / (2 * a) }; } } internal static bool TryNextCollisionBallLine(PhysicsObject self, PhysicsObject line, Circle circle, Line lineShape, double endTime, out IEvent collision) { var normalDistance = new Vector(self.X, self.Y).Dot(lineShape.NormalUnit.NewUnitized());//myPhysicsObject.X var normalVelocity = new Vector(self.Vx - line.Vx, self.Vy - line.Vy).Dot(lineShape.NormalUnit.NewUnitized());//myPhysicsObject.Vx var lineNormalDistance = lineShape.NormalDistance;//line.X if (lineNormalDistance > normalDistance) { if (normalVelocity > 0) { var time = (lineNormalDistance - (normalDistance + circle.Radius)) / normalVelocity; var directionDistance = self.Position.NewAdded(self.Velocity.NewScaled(time)).Dot(lineShape.DirectionUnit) - line.Position.NewAdded(line.Velocity.NewScaled(time)).Dot(lineShape.DirectionUnit); if (time < endTime && Math.Abs(directionDistance) < lineShape.Length * .5) { collision = DoCollision(self, line, circle.Radius, time, lineShape.NormalUnit, self.Velocity, line.Velocity); return true; } else { collision = default; return false; } } else { collision = default; return false; } } else if (lineNormalDistance < normalDistance) { if (normalVelocity < 0) { var time = (lineNormalDistance - (normalDistance - circle.Radius)) / normalVelocity; var directionDistance = self.Position.NewAdded(self.Velocity.NewScaled(time)).Dot(lineShape.DirectionUnit) - line.Position.NewAdded(line.Velocity.NewScaled(time)).Dot(lineShape.DirectionUnit); if (time < endTime && Math.Abs(directionDistance) < lineShape.Length * .5) { collision = DoCollision(self, line, circle.Radius, time, lineShape.NormalUnit, self.Velocity, line.Velocity); return true; } else { collision = default; return false; } } else { collision = default; return false; } } else //if (lineNormalDistance == normalDistance) { if (normalVelocity < 0) { var time = (lineNormalDistance - (normalDistance - circle.Radius)) / normalVelocity; var directionDistance = self.Position.NewAdded(self.Velocity.NewScaled(time)).Dot(lineShape.DirectionUnit) - line.Position.NewAdded(line.Velocity.NewScaled(time)).Dot(lineShape.DirectionUnit); if (time < endTime && Math.Abs(directionDistance) < lineShape.Length * .5) { collision = DoCollision(self, line, circle.Radius, time, lineShape.NormalUnit, self.Velocity, line.Velocity); return true; } else { collision = default; return false; } } else if (normalVelocity > 0) { var time = (lineNormalDistance - (normalDistance + circle.Radius)) / normalVelocity; var directionDistance = self.Position.NewAdded(self.Velocity.NewScaled(time)).Dot(lineShape.DirectionUnit) - line.Position.NewAdded(line.Velocity.NewScaled(time)).Dot(lineShape.DirectionUnit); if (time < endTime && Math.Abs(directionDistance) < lineShape.Length * .5) { collision = DoCollision(self, line, circle.Radius, time, lineShape.NormalUnit, self.Velocity, line.Velocity); return true; } else { collision = default; return false; } } else //normalVelocity == 0 { // how?? :( collision = default; return false; } } } //internal static bool TryCollisionBallLine3( // PhysicsObject ball, // PhysicsObject line, // ) { //} internal static bool TryCollisionBallLine2( PhysicsObject ball, PhysicsObject line, Circle circle, double length, double endTime, Vector lineParallelStart, Vector DlineParallel, out IEvent collision) { //DlineParallel.NewScaled(1/ lineParallelStart.Length) var DDX = ball.Vx - (line.Vx); var DDY = ball.Vy - (line.Vy); //var unitLineParallel = lineParallelStart.NewUnitized().NewScaled(circle.Radius); var DX = ball.X - (line.X); var DY = ball.Y - (line.Y); //if (new Vector(DX, DY).Dot(new Vector(DDX, DDY)) > 0) //{ // collision = default; // return false; //} var PX = lineParallelStart.x; var PY = lineParallelStart.y; var DPX = DlineParallel.x; var DPY = DlineParallel.y; var A = (DDX * DPY) - (DDY * DPX); var B = (DPY * DX) + (DDX * PY) - (DDY * PX) - (DPX * DY); var C = (DX * PY) - (DY * PX); var times = SolveQuadratic(A, B, C).ToArray(); //if (new Vector(DX, DY).Length < 500) //{ // var db = 0; //} times = times.Where(x => Math.Abs((x * x * A) + (x * B) + C) < .001).ToArray(); if (B != 0 && !times.Any()) { if (Math.Abs(((-C / B) * (-C / B) * A)) < .001) { var x = times.ToList(); x.Add(-C / B); times = x.ToArray(); } } //if (times.Any()) { // var temp = times.First(); // var answer = temp * temp * A + temp * B + C; // if (Math.Abs(answer) > 1) { // } //} //if (times.Skip(1).Any()) //{ // var temp2 = times.Skip(1).First(); // var answer2 = temp2 * temp2 * A + temp2 * B + C; // if (Math.Abs(answer2) > 1) // { // var db = 0; // } //} //if (times.Any(x => x < 0 && x > -.5 && AreCloseAtTime(x))) //{ // var db = 0; //} times = times.Where(x => x > 0 && x <= endTime && AreCloseAtTime(x) && AreMovingTogether(x)).ToArray(); if (!times.Any()) { collision = default; return false; } // the point we collided with is not moving at the speed { var collisionTime = times.OrderBy(x => x).First(); var D = new Vector(DX + (DDX * collisionTime), DY + (DDY * collisionTime)); var endpoint = new Vector(PX, PY).NewAdded(new Vector(DPX, DPY).NewScaled(collisionTime)); var index = endpoint.Length == 0 ? 0 : D.Length / endpoint.Length * Math.Sign(endpoint.Dot(D)); var lineNormal = new Vector(PY + (DPY * collisionTime), -(PX + (DPX * collisionTime))).NewUnitized(); var linePointVelocity = line.Velocity.NewAdded(new Vector(DPX, DPY).NewScaled(index)); collision = DoCollision(ball, line, 0, collisionTime, lineNormal, ball.Velocity, linePointVelocity); return true; } bool AreCloseAtTime(double time) { var DXtime = DX + (DDX * time); var DYtime = DY + (DDY * time); return length / 2.0 > new Vector(DXtime, DYtime).Length; } bool AreMovingTogether(double time) { var D = new Vector(DX + (DDX * time), DY + (DDY * time)); var endpoint = new Vector(PX, PY).NewAdded(new Vector(DPX, DPY).NewScaled(time)); var index = endpoint.Length == 0 ? 0 : D.Length / endpoint.Length * Math.Sign(endpoint.Dot(D)); var linePointVelocity = line.Velocity.NewAdded(new Vector(DPX, DPY).NewScaled(index)); var dv = ball.Velocity.NewAdded(linePointVelocity.NewMinus()); var d = ball.Position.NewAdded(line.Position.NewAdded(new Vector(PX, PY).NewScaled(index)).NewMinus()); return dv.Dot(d) < 0; } } //internal static bool TryNextCollisionBallLineSweep(PhysicsObject self, Line startSweep, Line endSweep, Circle circle, double endTime, out IEvent collision) //{ // var normalDistance = new Vector(self.X, self.Y).Dot(startSweep.NormalUnit.NewUnitized());//myPhysicsObject.X // var normalVelocity = new Vector(self.Vx - line.Vx, self.Vy - line.Vy).Dot(startSweep.NormalUnit.NewUnitized());//myPhysicsObject.Vx // var lineNormalDistance = startSweep.NormalDistance;//line.X // if (lineNormalDistance > normalDistance) // { // if (normalVelocity > 0) // { // var time = (lineNormalDistance - (normalDistance + circle.Radius)) / normalVelocity; // var directionDistance = self.Position.NewAdded(self.Velocity.NewScaled(time)).Dot(startSweep.DirectionUnit) - // line.Position.NewAdded(line.Velocity.NewScaled(time)).Dot(startSweep.DirectionUnit); // if (time < endTime && Math.Abs(directionDistance) < startSweep.Length * .5) // { // collision = DoCollision(self, line, circle.Radius, 0, time, startSweep.NormalUnit); // return true; // } // else // { // collision = default; // return false; // } // } // else // { // collision = default; // return false; // } // } // else if (lineNormalDistance < normalDistance) // { // if (normalVelocity < 0) // { // var time = (lineNormalDistance - (normalDistance - circle.Radius)) / normalVelocity; // var directionDistance = self.Position.NewAdded(self.Velocity.NewScaled(time)).Dot(startSweep.DirectionUnit) - // line.Position.NewAdded(line.Velocity.NewScaled(time)).Dot(startSweep.DirectionUnit); // if (time < endTime && Math.Abs(directionDistance) < startSweep.Length * .5) // { // collision = DoCollision(self, line, circle.Radius, 0, time, startSweep.NormalUnit); // return true; // } // else // { // collision = default; // return false; // } // } // else // { // collision = default; // return false; // } // } // else //if (lineNormalDistance == normalDistance) // { // if (normalVelocity < 0) // { // var time = (lineNormalDistance - (normalDistance - circle.Radius)) / normalVelocity; // var directionDistance = self.Position.NewAdded(self.Velocity.NewScaled(time)).Dot(startSweep.DirectionUnit) - // line.Position.NewAdded(line.Velocity.NewScaled(time)).Dot(startSweep.DirectionUnit); // if (time < endTime && Math.Abs(directionDistance) < lineShape.Length * .5) // { // collision = DoCollision(self, line, circle.Radius, 0, time, startSweep.NormalUnit); // return true; // } // else // { // collision = default; // return false; // } // } // else if (normalVelocity > 0) // { // var time = (lineNormalDistance - (normalDistance + circle.Radius)) / normalVelocity; // var directionDistance = self.Position.NewAdded(self.Velocity.NewScaled(time)).Dot(startSweep.DirectionUnit) - // line.Position.NewAdded(line.Velocity.NewScaled(time)).Dot(lineShape.DirectionUnit); // if (time < endTime && Math.Abs(directionDistance) < lineShape.Length * .5) // { // collision = DoCollision(self, line, circle.Radius, 0, time, lineShape.NormalUnit); // return true; // } // else // { // collision = default; // return false; // } // } // else //normalVelocity == 0 // { // // how?? :( // collision = default; // return false; // } // } //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Robots_vs.Dinosaurs { public class DinoAttack { string bite; string clawSwipe; string taiWhip; //constructor public DinoAttack() { DinoAttack bite = new DinoAttack(); DinoAttack clawSwipe = new DinoAttack(); DinoAttack tailWhip = new DinoAttack(); List<DinoAttack> dinoAttacks = new List<DinoAttack>(); dinoAttacks.Add(bite); dinoAttacks.Add(clawSwipe); dinoAttacks.Add(tailWhip); } //member methods } }
using System; using System.Threading; using System.Threading.Tasks; using MediatR; using VehicleManagement.Application.Common.Interfaces; using VehicleManagement.Domain.Entities; namespace VehicleManagement.Application.Commands.Brands { public static class CreateBrand { public record Command(string Name) : IRequest<int>; public class Handler : IRequestHandler<Command, int> { private readonly IBrandRepository _repository; public Handler(IBrandRepository repository) { _repository = repository; } public async Task<int> Handle(Command request, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(request.Name)) return 0; return await _repository.Add(new Brand(request.Name)); } } } }
using System; using System.IO; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.ComponentModel; namespace FreeUI.Controls.Button { /// <summary> /// Controle baseado em uma PictureBox /// </summary> [DefaultEvent( "Click" ), ProvideProperty( "FreeUI.Controls.Button", typeof( System.Windows.Forms.Control ) ), DebuggerStepThrough] public class FreeUIPictureButton : PictureBox { private int zoom = 8; private Image imagemOriginal; public int Zoom { get => zoom; set => zoom = value; } public Image ImageActive { get => imagemOriginal; set => imagemOriginal = value; } public FreeUIPictureButton() { InitializeComponent(); } protected override void OnMouseEnter(EventArgs e) { Anima.Zoom.In( this, zoom ); base.OnMouseEnter( e ); } protected override void OnMouseLeave(EventArgs e) { Anima.Zoom.Out( this ); base.OnMouseLeave( e ); } protected override void OnClick(EventArgs e) { Anima.Zoom.Out( this ); base.OnClick( e ); } protected override void Dispose(bool disposing) { base.Dispose( disposing ); } /// <summary> /// Cria a imagem de a partir da base64 string /// </summary> /// <returns>Imagem genérica</returns> private Image ImagemBotaoBase64() { byte[] bytes = Convert.FromBase64String( "iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAMAAADDpiTIAAAAA3NCSVQICAjb4U/gAAAACXBIWXMAABjGAAAYxgH2cLukAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAtxQTFRF////PbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOePbOej3QdDAAAAPN0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISMkJSYnKCkrLC0uLzAxMjM0NTc4OTo7PD0+P0BBQkNERUZHSElLTE1OT1BRUlNUVVZXWFlbXF1eX2BhYmNkZWZoaWprb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KMcZE9DyRDkzbo6VrGsNqnB0Ezxyja1c6Y1L6ryIBmAd/CU4w5pxb6oFnFc8+WbxlDvt1yjweapVLv3xpiTAhtvT8Vmg3SH9rRQpdr2fFQOjTbZE7dGaZrhXdOzYRms2tKtjfRhZq2l1wDTQnv6CWBCF0kElgy2gtNpf4llQ10hYbKkv7QHOApWHyog47qOLS4wAPNOVkTnnonREeE3nlqQhY053lHztpWR6Xqts0a6YXmIoOLX/ysjQq0ffZi8WBobpQybNozu0/TNqd3PzNtWAo0d7t27MyXDodoqdDhl2aOvRZazPDkjZm+aOO+P3bQlI4/7tu4aPqYPA+02JQ8+K7S8s17j37ZTAHNXx7du7m89K7BydDiRapv2LjJj85fuXHbrrfeO/Dx58FTZxpD7e2hxjOngp9/fOC9t3Zt27hy/qOTxw3zpSJh/H+EmjpH9MQQJgAAAABJRU5ErkJggg==" ); Image image; using (MemoryStream ms = new MemoryStream( bytes )) image = Image.FromStream( ms ); return image; } private void InitializeComponent() { ( ( ISupportInitialize )this ).BeginInit(); SuspendLayout(); BackColor = Color.Transparent; Image = ( ImagemBotaoBase64() ); BackgroundImageLayout = ImageLayout.Stretch; Cursor = Cursors.Hand; Size = new Size( 50, 50 ); SizeMode = PictureBoxSizeMode.Zoom; ( ( ISupportInitialize )this ).EndInit(); ResumeLayout( false ); } } }
using System.Collections.Generic; using UnityEngine; namespace NeuralNetwork { public class NeuralNet : MonoBehaviour { public NetLayer InputLayer; public List<NetLayer> HiddenLayers = new List<NetLayer>(); public NetLayer OutputLayer; public int NeuralNetConnections; public NetData _NetData; private void Start() { } public void InitializeNeuralNetwork() { int IDIndex = 0; int LayerIndex = 0; // Input Layer to first Hidden foreach (var neuron in InputLayer.NeuronsInLayer) { for (int i = 0; i < HiddenLayers[0].NeuronsInLayer.Count; i++) { neuron.ConnectedNeurons.Add(HiddenLayers[0].NeuronsInLayer[i]); } neuron.NeuronID = "Input Neuron " + IDIndex.ToString(); IDIndex++; } IDIndex = 0; //BetweenHiddens for (int i = 0; i < HiddenLayers.Count-1; i++) { for (int j = 0; j < HiddenLayers[i].NeuronsInLayer.Count; j++) { HiddenLayers[i].NeuronsInLayer[j].ConnectedNeurons = HiddenLayers[i+1].NeuronsInLayer; } foreach (var neuron in HiddenLayers[i].NeuronsInLayer) { neuron.NeuronID = "Hidden " + LayerIndex + "Neuron " + IDIndex; IDIndex++; } IDIndex = 0; LayerIndex++; } //To Output IDIndex = 0; foreach (var neuron in HiddenLayers[HiddenLayers.Count-1].NeuronsInLayer) { neuron.NeuronID = "Hidden " + LayerIndex + "Neuron " + IDIndex; IDIndex++; } IDIndex = 0; for (int j = 0; j < HiddenLayers[HiddenLayers.Count-1].NeuronsInLayer.Count; j++) { HiddenLayers[HiddenLayers.Count-1].NeuronsInLayer[j].ConnectedNeurons = OutputLayer.NeuronsInLayer; foreach (var neuron in HiddenLayers[HiddenLayers.Count-1].NeuronsInLayer[j].ConnectedNeurons) { neuron.NeuronID = "Output Neuron " + IDIndex; IDIndex++; } } NeuralNetConnections = ComputeNumberOfWeights(); } int ComputeNumberOfWeights() { int nbr = 0; nbr += (InputLayer.NeuronsInLayer.Count + 1) * HiddenLayers[0].NeuronsInLayer.Count; for (int i = 0; i < HiddenLayers.Count-1; i++) { if (i == HiddenLayers.Count - 2) { nbr += (HiddenLayers[i].NeuronsInLayer.Count + 1) * OutputLayer.NeuronsInLayer.Count; } else { nbr += (HiddenLayers[i].NeuronsInLayer.Count + 1) * HiddenLayers[i + 1].NeuronsInLayer.Count; } } return nbr; } void SetRandomWeightsAndBias(int WeightsCount) //On Network first Initialisation { List<double> randomWeight = new List<double>(); for (int i = 0; i < WeightsCount; i++) { } } void SetDataWeightsAndBias(int WeighsCount) { } public List<double> GetWeightAndBias(NeuralNet instanceNetwork) { List<double> weights = new List<double>(); foreach (var neuron in instanceNetwork.InputLayer.NeuronsInLayer) { foreach (var weight in neuron.Weights) { weights.Add(weight); } } foreach (var hidden in instanceNetwork.HiddenLayers) { foreach (var neuron in hidden.NeuronsInLayer) { foreach (var weight in neuron.Weights) { weights.Add(weight); } } } foreach (var neuron in instanceNetwork.OutputLayer.NeuronsInLayer) { foreach (var weight in neuron.Weights) { weights.Add(weight); } } return weights; } public void TrainingNetwork() { } public void ExecutingNetwork() { } public void EvaluateNeuralNetEfficiency() { } public void GetData(NetData data) { _NetData = data; } } }
using System; using System.Collections.Generic; namespace ServerLib.Transactions { internal class ParticipantProxy { public string Endpoint; public bool ReadyToCommit = false; public ParticipantProxy(string endpoint) { Endpoint = endpoint; } public IPartitipantProxy GetProxy() { return ParticipantProxyCache.GetParticipant(Endpoint); } private static class ParticipantProxyCache { private static readonly Dictionary<string, IPartitipantProxy> Participants = new Dictionary<string, IPartitipantProxy>(); public static IPartitipantProxy GetParticipant(string endpoint) { IPartitipantProxy participant; if (!Participants.TryGetValue(endpoint, out participant)) { participant = (IPartitipantProxy) Activator.GetObject(typeof (IPartitipantProxy), endpoint); } return participant; } } } }
using System.Collections.Generic; public interface IFactoryElement<T> { bool CreateElement(out T elem); } public interface IFactoryByKey<T1,T2> { bool TryCreate(T1 id, out T2 elem); T2 Create(T1 id); T1[] GetKeys(); }
using FluentValidation; namespace Application.Articles.Commands.CreateArticleCommands { public class CreateArticleCommandValidator : AbstractValidator<CreateArticleCommand> { public CreateArticleCommandValidator () { RuleFor (e => e.Article.ArticleAuthor) .NotEmpty ().WithMessage ("Article Author is Required") .NotNull ().WithMessage ("Article Author is Required"); RuleFor (e => e.Article.ArticleBody) .NotEmpty ().WithMessage ("Article Body is Required") .NotNull ().WithMessage ("Article Body is Required"); RuleFor (e => e.Article.ArticleDate) .NotEmpty ().WithMessage ("Article Date is Required") .NotNull ().WithMessage ("Article Date is Required"); RuleFor (e => e.Article.ArticleTitle) .NotEmpty ().WithMessage ("Article Title is Required") .NotNull ().WithMessage ("Article Title is Required"); RuleFor (e => e.ArticleBanner) .NotEmpty ().WithMessage ("Article Banner is Required") .NotNull ().WithMessage ("Article Banner is Required"); } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Cogito.Threading; namespace Cogito.Kademlia { /// <summary> /// Represents a set of items within a <see cref="KTable{TKNodeId, TKBucketItem}"/>. /// </summary> /// <typeparam name="TKNodeId"></typeparam> /// <typeparam name="TKNodeData"></typeparam> class KBucket<TKNodeId, TKNodeData> where TKNodeId : struct, IKNodeId<TKNodeId> { readonly int k; readonly ReaderWriterLockSlim rw = new ReaderWriterLockSlim(); readonly LinkedList<KBucketItem<TKNodeId, TKNodeData>> l; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="k"></param> public KBucket(int k) { this.k = k; l = new LinkedList<KBucketItem<TKNodeId, TKNodeData>>(); } /// <summary> /// Updates the position of the node in the bucket. /// </summary> /// <typeparam name="TKNetwork"></typeparam> /// <param name="nodeId"></param> /// <param name="nodeData"></param> /// <param name="nodeEvents"></param> /// <param name="protocol"></param> /// <param name="cancellationToken"></param> internal async ValueTask TouchAsync(TKNodeId nodeId, TKNodeData nodeData, IKNodeEvents nodeEvents, IKNodeProtocol<TKNodeId, TKNodeData> protocol, CancellationToken cancellationToken) { var lk = rw.BeginUpgradableReadLock(); try { var i = GetNode(nodeId); if (i != null) { using (rw.BeginWriteLock()) { // item already exists, move to tail l.Remove(i); l.AddLast(i.Value); } } else if (l.Count < k) { using (rw.BeginWriteLock()) { // item does not exist, but bucket has room, insert at tail l.AddLast(new KBucketItem<TKNodeId, TKNodeData>(nodeId, nodeData, nodeEvents)); } } else { // item does not exist, but bucket does not have room, ping first entry var n = l.First; // start ping, check for async completion KNodePingResponse r; var t = protocol.PingAsync(n.Value.Id, n.Value.Data, cancellationToken); // completed synchronously (or immediately) if (t.IsCompleted) r = t.Result; else { // temporarily release lock and wait for completion lk.Dispose(); r = await t; lk = rw.BeginUpgradableReadLock(); } // was able to successfully ping the node if (r.Status == KNodeResponseStatus.OK) { // entry had response, move to tail, discard new entry if (l.Count > 1) { using (rw.BeginWriteLock()) { // remove from list if not already done (async operation could have overlapped) if (n.List != null) l.Remove(n); // node goes to end l.AddLast(n.Value); } } } else { using (rw.BeginWriteLock()) { // first entry had no response, remove, insert new at tail l.Remove(n); l.AddLast(new KBucketItem<TKNodeId, TKNodeData>(nodeId, nodeData, nodeEvents)); } } } } finally { lk.Dispose(); } } /// <summary> /// Finds the current index of the specified node ID within the bucket. /// </summary> /// <param name="nodeId"></param> /// <returns></returns> LinkedListNode<KBucketItem<TKNodeId, TKNodeData>> GetNode(TKNodeId nodeId) { for (var i = l.First; i != null; i = i.Next) if (nodeId.Equals(i.Value.Id)) return i; return null; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace izsu { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Abone _abone = new Abone(); _abone.AboneNo = textBox1.Text; _abone.AdSoyad = textBox2.Text; _abone.OncekiSayac = int.Parse(textBox3.Text); _abone.SonSayac = int.Parse(textBox4.Text); string aboneTuru = radioButton1.Checked == true ? "Ev" : "Kurum"; aboneTuru = radioButton2.Checked == true ? "Kurum" : "Ev"; _abone.AboneTuru = aboneTuru; listBox1.Items.Add(_abone); } private void listBox1_DoubleClick(object sender, EventArgs e) { Abone _abone = (Abone)listBox1.SelectedItem; double odeme = _abone.OdemeHesapla(_abone.OncekiSayac, _abone.SonSayac, _abone.AboneTuru); DialogResult result = MessageBox.Show("Ödeme Tutarı: " + odeme + "\nÖdeme Yapmak İstiyor Musunuz?", "Ödeme Ekranı", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { listBox2.Items.Add(_abone); listBox1.Items.Remove(_abone); } } private void listBox2_DoubleClick(object sender, EventArgs e) { Abone _abone = (Abone)listBox2.SelectedItem; Form2 frm = new Form2(_abone); frm.Show(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RemoteServices { public interface IServer { List<IClient> getClients(); void RegisterClient(string NewClientIP, string NewClientPort); void sendMove(string ip, string port, string move); void readyClient(); void gameOver(string identificador); void getProcessToCrash(); void freeze(); void unfreeze(); string getStatus(); } public interface IClient { void setPort(string port); string getPort(); void setIP(string ip); string getIP(); void startGame(string gameRate, string numPlayers); string getGameRate(); string getNumPlayers(); void updateGameState(Dictionary<string, int[]> pacmans, Dictionary<int, int[]> ghosts, Dictionary<int, int[]> coins); void initGame(Dictionary<string, int[]> pacmans); void fail(string s); void MsgToClient(string message, int[] vector); void SendMsg(string message, int[] vector); void BroadcastMessage(int[] vector); void requestMessage(int[] vector); void BroadcastVector(int[] vector); void vectorToClient(int[] vector); List<string> getMessages(); void getProcessToCrash(); void freeze(); void unfreeze(); string getStatus(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SEGU_ENTI.Entidades { public class clsAUDITORIA { public string CO_USUA_CREA { get; set; } public DateTime? FE_USUA_CREA { get; set; } public string CO_USUA_MODI { get; set; } public DateTime? FE_MODI { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace bt.Admin { public partial class Suacthdn : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { getData(); getsp(); } } public void getData() { int id_ctdhn = Convert.ToInt32(Request.QueryString["id_cthdn"]); banhang2Entities db = new banhang2Entities(); cthdnhap obj = db.cthdnhap.FirstOrDefault(x => x.id_cthdnhap == id_ctdhn); if (obj == null) { Response.Redirect("Chitiethdn.aspx?id_hdnhap=" + obj.id_hdnhap); } else { txtma.Text = obj.id_hdnhap.ToString(); cmbsp.SelectedValue = obj.masp.ToString(); txtsl.Text = obj.soluong.ToString(); txtdg.Text = obj.dongia.ToString(); txtma.ReadOnly = true; } } public void getsp() { banhang2Entities db = new banhang2Entities(); List<sanpham> obj = db.sanpham.ToList(); cmbsp.DataSource = obj; cmbsp.DataValueField = "masp"; cmbsp.DataTextField = "tensp"; cmbsp.DataBind(); } protected void tbnSua_Click(object sender, EventArgs e) { int id_ctdhn = Convert.ToInt32(Request.QueryString["id_cthdn"]); banhang2Entities db = new banhang2Entities(); cthdnhap obj = db.cthdnhap.FirstOrDefault(x => x.id_cthdnhap == id_ctdhn); obj.id_hdnhap = Convert.ToInt32(txtma.Text); obj.masp = Convert.ToInt32(cmbsp.SelectedValue); obj.soluong = Convert.ToInt32(txtsl.Text); obj.dongia = Convert.ToSingle(txtdg.Text); db.SaveChanges(); Response.Redirect("Chitiethdn.aspx?id_hdnhap="+ obj.id_hdnhap); } } }
using Client.UIControllers; using Domen; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Client.Forms { public partial class FrmProizvodjacLekova : Form { ProizvodjacLekova izabraniProizvodjac; SearchProizvodjacController searchProizvodjacController; public FrmProizvodjacLekova(ProizvodjacLekova izabraniProizvodjac, SearchProizvodjacController searchProizvodjacController) { InitializeComponent(); this.izabraniProizvodjac = izabraniProizvodjac; if (izabraniProizvodjac != null) { this.searchProizvodjacController = searchProizvodjacController; lblProizvodjacLekova.Text = izabraniProizvodjac.NazivProizvodjaca; searchProizvodjacController.GetLekoviProizvodjaca(izabraniProizvodjac, dgvLekovi); } else { throw new Exception(); } } private void btnBack_Click(object sender, EventArgs e) { this.Dispose(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Tree : PickableObject { public override PickableObject Pick(Transform hands) { rigidbody.isKinematic = false; return null; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; /** * * name : Training.cs * author : Aleksy Ruszala * date : 29/04/2019 * * */ namespace Application.Data.Models { /// <summary> /// This class representing model for training /// </summary> public class Training { //Primary public int Id { get; set; } //Properties public DateTime Date { get; set; } public DateTime Time { get; set; } public string Location { get; set; } public string CoachSRU { get; set; } //Relations public virtual Member Coach { get; set; } public virtual List<Activities> Activities { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.IO.Ports; namespace Raiwan.pages { /// <summary> /// Interaction logic for admin_panel.xaml /// </summary> public partial class admin_panel : Window { public admin_panel(string UserType) { InitializeComponent(); set_language(); if(UserType == "user") { changePass.IsEnabled = false; addUserBtn.IsEnabled = false; usersListBtn.IsEnabled = false; usersLogsBtn.IsEnabled = false; } } private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DragMove(); } private void submitBtn_Click(object sender, RoutedEventArgs e) { this.Close(); } private void quitBtn_Click(object sender, RoutedEventArgs e) { this.Close(); } private void Button_Click(object sender, RoutedEventArgs e) { panel.formatPage format = new panel.formatPage(); App.Current.MainWindow = format; this.Close(); format.ShowDialog(); } private void changePass_Click(object sender, RoutedEventArgs e) { panel.changePassword pass = new panel.changePassword(); App.Current.MainWindow = pass; this.Close(); pass.ShowDialog(); } private void addUserBtn_Click(object sender, RoutedEventArgs e) { panel.addUser user = new panel.addUser(); App.Current.MainWindow = user; this.Close(); user.ShowDialog(); } private void addAdminBtn_Click(object sender, RoutedEventArgs e) { panel.addAdmin admin = new panel.addAdmin(); App.Current.MainWindow = admin; this.Close(); admin.ShowDialog(); } private void deleteAdmin_Click(object sender, RoutedEventArgs e) { panel.deleteUser delAdmin = new panel.deleteUser(); App.Current.MainWindow = delAdmin; this.Close(); delAdmin.ShowDialog(); } private void set_language() { if((string)Application.Current.Properties["lang"] == "en" && (string)headerLable.Content == "پنل مدیریت") { headerLable.Content = "Admin Panel"; changePass.Content = "Change Encryption Key"; addUserBtn.Content = "Add User"; formatBtn.Content = "Format Device"; usersLogsBtn.Content = "Users Logs"; usersListBtn.Content = "Users List"; quitBtn.Content = "Cancel"; calenderBtn.Content = "Calender"; changeUP.Content = "Change User And Password"; } } private void serialPortStart() { SerialPort comPort = new SerialPort(); } private void calenderBtn_Click(object sender, RoutedEventArgs e) { MainWindow mainWindow = null; foreach (Window window in Application.Current.Windows) { Type type = typeof(MainWindow); if (window != null && window.DependencyObjectType.Name == type.Name) { mainWindow = (MainWindow)window; if (mainWindow != null) { break; } } } this.Close(); mainWindow.GetCalenders(); } private void usersLogsBtn_Click(object sender, RoutedEventArgs e) { MainWindow mainWindow = null; foreach (Window window in Application.Current.Windows) { Type type = typeof(MainWindow); if (window != null && window.DependencyObjectType.Name == type.Name) { mainWindow = (MainWindow)window; if (mainWindow != null) { break; } } } this.Close(); mainWindow.GetLogs(); } private void usersListBtn_Click(object sender, RoutedEventArgs e) { MainWindow mainWindow = null; foreach (Window window in Application.Current.Windows) { Type type = typeof(MainWindow); if (window != null && window.DependencyObjectType.Name == type.Name) { mainWindow = (MainWindow)window; if (mainWindow != null) { break; } } } this.Close(); mainWindow.GetUsersList(); } private void changeUP_Click(object sender, RoutedEventArgs e) { MainWindow mainWindow = null; foreach (Window window in Application.Current.Windows) { Type type = typeof(MainWindow); if (window != null && window.DependencyObjectType.Name == type.Name) { mainWindow = (MainWindow)window; if (mainWindow != null) { break; } } } panel.ChangeUP UP = new panel.ChangeUP(mainWindow.UserName,mainWindow.Password); App.Current.MainWindow = UP; this.Close(); UP.ShowDialog(); } private void memoryRecovery_Click(object sender, RoutedEventArgs e) { panel.memoryRecovery mRecovery = new panel.memoryRecovery(); App.Current.MainWindow = mRecovery; this.Close(); mRecovery.ShowDialog(); } } }
using MediatR; using System; using System.Collections.Generic; using System.Text; namespace CQSR.Abstraction { public interface IQuery<TResponse> : IRequest<TResponse> where TResponse: class { } }
using NetworkToolkit.Http.Primitives; using System; namespace NetworkToolkit { internal sealed class NullHttpHeaderSink : IHttpHeadersSink { public static readonly NullHttpHeaderSink Instance = new NullHttpHeaderSink(); public void OnHeader(object? state, ReadOnlySpan<byte> headerName, ReadOnlySpan<byte> headerValue) { } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Book_Manage_Sys { public partial class Form2 : Form { Form1 f1 = new Form1(); public Form2() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { } private void button4_Click(object sender, EventArgs e) { this.Hide(); Form3 f3 = new Form3(); f3.Show(); } private void Form2_Load(object sender, EventArgs e) { panel1.Visible = true; f1.sqlConnection1.Open(); SqlCommand cmd1 = new SqlCommand("select Tittle from Books ", f1.sqlConnection1); SqlDataReader dr1 = cmd1.ExecuteReader(); while (dr1.Read()) { comboBox1.Items.Add(dr1["Tittle"]).ToString(); // comboBox2.Items.Add(dr1["Category"]).ToString(); } f1.sqlConnection1.Close(); } private void button1_Click(object sender, EventArgs e) { panel1.Visible = true; f1.sqlConnection1.Open(); SqlDataAdapter sd = new SqlDataAdapter("Select *from Books ", f1.sqlConnection1); DataTable dt = new DataTable(); sd.Fill(dt); dataGridView1.DataSource = dt; f1.sqlConnection1.Close(); } private void button11_Click(object sender, EventArgs e) { f1.sqlConnection1.Open(); SqlDataAdapter sd = new SqlDataAdapter("Select *from Books where Tittle = '"+comboBox1.Text+"' ", f1.sqlConnection1); DataTable dt = new DataTable(); sd.Fill(dt); dataGridView1.DataSource = dt; f1.sqlConnection1.Close(); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { f1.sqlConnection1.Open(); SqlCommand cmd1 = new SqlCommand("select Category from Books where Tittle = '" + comboBox1.Text + "'", f1.sqlConnection1); SqlDataReader dr1 = cmd1.ExecuteReader(); while (dr1.Read()) { // comboBox1.Items.Add(dr1["Tittle"]).ToString(); comboBox2.Items.Add(dr1["Category"]).ToString(); } f1.sqlConnection1.Close(); } private void button5_Click(object sender, EventArgs e) { this.Hide(); Book_Portal bk = new Book_Portal(); bk.Show(); } private void button3_Click(object sender, EventArgs e) { this.Hide(); Bills bl = new Bills(); bl.Show(); } private void Cust_Click(object sender, EventArgs e) { this.Hide(); Customer cs = new Customer(); cs.Show(); } } }
using CMS_Database.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CMS_ShopOnline.Areas.Administration.Models { public class CTKhuyenMaiViewModel { public int? Id { get; set; } public int? IdKhuyenMai { get; set; } public bool? IsPhanTram { get; set; } public bool? IsTienMat { get; set; } public int? IdThanhPham { get; set; } public string Ten { get; set; } public int? SLToithieu { get; set; } public int? IdLoaiSP { get; set; } public double? TienGiam { get; set; } public string Loaithanhtoan { get; set; } public string Loaikhuyenmai { get; set; } public bool? IsDelete { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace radl_pps.domain { public class Auftrag { private int menge; private Artikel artikel; private int modus; private int periode; public int Menge { get { return menge; } set { menge = value; } } public Artikel Artikel { get { return artikel; } set { artikel = value; } } public int Modus { get { return modus; } set { modus = value; } } public int Periode { get { return periode; } set { periode = value; } } public Auftrag(int Menge, Artikel Artikel, int Modus) { this.Menge = Menge; this.Artikel = Artikel; this.Modus = Modus; } public Auftrag() { } } }
using System; using System.Collections; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ObserverAndMvvm.CollectionChanged { public class ItemsControl { private IEnumerable _itemsSource; public IEnumerable ItemsSource { get { return _itemsSource; } set { if (_itemsSource is not null && _itemsSource is INotifyCollectionChanged oldItemsSource) oldItemsSource.CollectionChanged -= OnCollectionChanged; _itemsSource = value; if (_itemsSource is not null && _itemsSource is INotifyCollectionChanged newItemsSource) newItemsSource.CollectionChanged += OnCollectionChanged; } } private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: Console.WriteLine($"Un élément a été ajouté à l'index {e.NewStartingIndex} : {e.NewItems[0]}"); break; case NotifyCollectionChangedAction.Remove: Console.WriteLine($"l'élément à l'index {e.OldStartingIndex} a été rétiré"); break; case NotifyCollectionChangedAction.Replace: Console.WriteLine($"l'élément à l'index {e.NewStartingIndex} ({e.OldItems[0]}) a été remplacé par : {e.NewItems[0]}"); break; case NotifyCollectionChangedAction.Move: break; case NotifyCollectionChangedAction.Reset: Console.WriteLine("La collection a été réinitialisée..."); break; } } } }
using System; using System.Collections; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using CommonTypes; namespace MainServer { internal class Program { private static void Main(string[] args) { IDictionary properties = new Hashtable(); properties["port"] = Config.RemoteMainserverPort; properties["timeout"] = Config.InvocationTimeout; var channelServ = new TcpChannel(properties, null, null); ChannelServices.RegisterChannel(channelServ, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof (MainServer), Config.RemoteMainserverObjName, WellKnownObjectMode.Singleton); Console.WriteLine("Press <enter> to exit"); Console.ReadLine(); } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Windows.Data; namespace Kit.WPF.Converters { /// <summary> /// Returns the value of the DescriptionAttribute applied to an enum value, or an empty string /// if the enum value is not decorated with the attribute. /// </summary> [ValueConversion(typeof(Enum), typeof(string))] public class EnumToDescriptionConverter : IValueConverter { object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { Debug.Assert(value is Enum, "value should be an Enum"); Debug.Assert(targetType.IsAssignableFrom(typeof(string)), "targetType should assignable from a String"); FieldInfo field = value.GetType().GetField(value.ToString()); object[] attrs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attrs.Length > 0) { DescriptionAttribute attr = attrs[0] as DescriptionAttribute; return attr.Description; } return ""; } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException("ConvertBack not supported."); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShimDemoDataAccessLayer { public class DataContext { public DataContext() { UserName = "jim"; } public string UserName { get; private set; } } }
using System; namespace WeaponGame { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); Weapons swaord = new Weapons("bow", 20, 10, 20, 100, 1); Console.WriteLine("cirtDamage: " + swaord.CritiDamage); Console.WriteLine(swaord.t()); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using GuardarImagenBaseDatos; namespace GuardarImagenBaseDatos.GuardarImagen { public partial class Download : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int id = Convert.ToInt32(Request.QueryString["id"]); Imagenes imagen = ImagenesDAL.GetImagenById(id); Response.Clear(); Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", imagen.Nombre)); switch (Path.GetExtension(imagen.Nombre).ToLower()) { case ".jpg": Response.ContentType = "image/jpg"; break; case ".gif": Response.ContentType = "image/gif"; break; case ".png": Response.ContentType = "image/png"; break; } Response.BinaryWrite(imagen.Imagen); Response.End(); } } }
using DemirbasTakipWpfUI.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemirbasTakipWpfUI.DataAccess { public class ProductDal:RepositoryBase<Product,DemirbasTakipDataContext> { //CRUD(Create,Read,Update,Delete) islemleri haricinde farkli veritabani islemleri yapacaksaniz buraya yaziniz. } }
using System; using System.Collections.Generic; using System.Text; namespace ExplicacionInterface { public interface IPieza { decimal Area(); decimal Perimetro(); } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace NMoSql { public static class Utils { private static readonly Regex _dereferenceOperators = new Regex(@"[-#=]+>+"); private static readonly Regex _endsInCast = new Regex(@"::\w+$"); public static bool IsObject(this JToken token) { return token != null && (token.Type == JTokenType.Object || token.Type == JTokenType.Array); } public static object ToObject(this JToken token) { if (token.Type == JTokenType.String) return (string)token; if (token.Type == JTokenType.Integer) return (int)token; if (token.Type == JTokenType.Boolean) return (bool)token; if (token.Type == JTokenType.Float) return (double)token; return token; } public static bool Truthy(this JToken token) { return !Falsy(token); } public static bool Falsy(this JToken token) { return string.IsNullOrEmpty(token?.ToString()) || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined || (token.Type == JTokenType.Boolean && !(bool)token); } public static bool IsNull(this JToken token) { return token == null || token.Type == JTokenType.Null; } public static bool IsNullOrUndefined(this JToken token) { return token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined; } public static bool IsUndefined(this JToken token) { return token == null || token.Type == JTokenType.Undefined; } public static string Parameterize(JToken value, IList<object> values, ISet<string> tableAliases) { if (value.Type == JTokenType.Boolean) return value.ToString().ToLower(); if (value.Type == JTokenType.Integer) { values.Add((int)value); return "@" + (values.Count - 1); } if (value.Type == JTokenType.Float) { values.Add((double)value); return "@" + (values.Count - 1); } var str = (string)value; if (str.StartsWith("$") && str.EndsWith("$")) { return QuoteObject(str.Substring(1, str.Length - 2), values, tableAliases); } else { values.Add(str); return "@" + (values.Count - 1); } } public static string QuoteIdentifier(JToken identifier) => QuoteIdentifier((string)identifier); public static string QuoteIdentifier(string identifier) { return "\"" + identifier?.Replace("\"", "\"\"") + "\""; } public static string QuoteColumn(JToken field, IList<object> values, ISet<string> tableAliases, params JToken[] collection) => QuoteObject(field, values, tableAliases, collection); public static string QuoteColumn(string field, IList<object> values, ISet<string> tableAliases, params string[] collection) => QuoteObject(field, values, tableAliases, collection); public static string QuoteObject(JToken field, IList<object> values, ISet<string> tableAliases, params JToken[] collection) => QuoteObject((string)field, values, tableAliases, collection?.Select(t => (string)t)?.ToArray()); public static string QuoteObject(string field, IList<object> values, ISet<string> tableAliases, params string[] collection) { var rest = collection.ToList(); // Split up database and/or schema definition for (var i = 0; i < rest.Count; i++) { if (rest[i].IndexOf('.') > 0) { var split = rest[i].Split('.'); rest.RemoveAt(i); foreach (var part in split) rest.Insert(i, part); } } // Casting var endsInCast = _endsInCast.Matches(field); if (endsInCast.Count > 0) { return QuoteObject(_endsInCast.Replace(field, string.Empty), values, tableAliases, rest.ToArray()) + endsInCast[0].Value; } // Using JSON/Hstore operators var dereferenceOperators = _dereferenceOperators.Matches(field); if (dereferenceOperators.Count > 0) { var operators = new List<string>(); foreach (Match dereferenceOperator in dereferenceOperators) operators.Add(dereferenceOperator.Value); var fields = _dereferenceOperators // Split on operators .Split(field) // Properly quote each part .Select((part, i) => { if (i == 0) return QuoteObject(part, values, tableAliases, rest.ToArray()); if (part.Length > 1 && part[0] == '\'' && part[part.Length - 1] == '\'') return Parameterize(part.Substring(1, part.Length - 2), values, tableAliases); int index; if (int.TryParse(part, out index)) return Parameterize(index, values, tableAliases); return Parameterize(part, values, tableAliases); }).ToArray(); // Re-join fields and operators var result = new StringBuilder(fields[0]); for (int i = 1, length = fields.Length; i < length; i++) { result.Append(operators[i - 1]); result.Append(fields[i]); } return result.ToString(); } // Just using *, no collection if (field.IndexOf('*') == 0 && collection != null) return string.Join(".", rest.Reverse<string>().Select(identifier => QuoteIdentifier(identifier))) + ".*"; // Using *, specified collection, used quotes if (field.IndexOf("\".*") > -1) return field; // Using *, specified collection, didn't use quotes if (field.IndexOf(".*") > -1) return "\"" + field.Split('.')[0] + ".*"; // No periods specified in field, use explicit 'table[, schema[, database] ] if (field.IndexOf('.') < 0 && tableAliases?.Contains(field) != true) return string.Join(".", rest.Reverse<string>().Concat(new[] { field }).Select(identifier => QuoteIdentifier(identifier))); // Otherwise, a '.' was in there, just quote whatever was specified return string.Join(".", field.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Select(identifier => QuoteIdentifier(identifier))); } public static string QuoteValue(JToken value) { if (value.Type == JTokenType.Integer) return Convert.ToString((int)value); if (value.Type == JTokenType.Float) return Convert.ToString((double)value); return "$$" + (string)value + "$$"; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace BPiaoBao.Common.Enums { /// <summary> /// 保单状态 /// </summary> public enum EnumInsuranceStatus { [Description("手动出单")] Manual = 5, [Description("未出单")] NoInsurance = 6, [Description("已出单")] GotInsurance = 7, [Description("已撤销")] Canceled = 8, } }
using System.Data.Entity.ModelConfiguration; using RMAT3.Models; namespace RMAT3.Data.Mapping { public class StateLookupMap : EntityTypeConfiguration<StateLookup> { public StateLookupMap() { // Primary Key HasKey(t => t.StateLookupId); // Properties Property(t => t.StateCd) .IsRequired() .HasMaxLength(50); Property(t => t.StateTxt) .HasMaxLength(200); // Table & Column Mappings ToTable("StateLookup", "OLTP"); Property(t => t.StateLookupId).HasColumnName("StateLookupId"); Property(t => t.StateCd).HasColumnName("StateCd"); Property(t => t.StateTxt).HasColumnName("StateTxt"); Property(t => t.CountryLookupId).HasColumnName("CountryLookupId"); // Relationships HasOptional(t => t.CountryLookup) .WithMany(t => t.StateLookups) .HasForeignKey(d => d.CountryLookupId); } } }
namespace GoopTest { using Goop.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; [TestClass] public class EnumerableExTest { [DataTestMethod] [DataRow('b', 'a', 'r')] [DataRow('b', 'y', 'r')] [DataRow('b', 'y', 'a')] [DataRow('b', 'y', 'z')] public void BinarySearch(char first, char last, char findThis) { char[] alphabet = _Alphabet().ToArray(); int expectedIndex = Array.BinarySearch(alphabet, findThis); int actualIndex = alphabet.BinarySearch(findThis); Assert.AreEqual(expectedIndex, actualIndex); IEnumerable<char> _Alphabet() { for (char c = first; c <= last; ++c) { yield return c; } } } } }
namespace AppBuilder.Shared { public static class CodeSnippets { public const string ConsoleInput = "using System;\n\nclass Program\n{\n\tpublic static void Main()\n\t{\n\t\tstring input = Console.ReadLine();\n\t\tstring additional = \" was your input\";\n\t\tConsole.WriteLine(input);\n\t\tstring newOutput = input + additional;\n\t\tConsole.WriteLine(newOutput);\n\t}\n}"; public const string ConsoleMutlitpeWrites = "using System;\n\nclass Program\n{\n\tpublic static void Main()\n\t{\n\t\tstring input = \"Foo\";\n\t\tstring additional = \" was not your input\";\n\t\tConsole.WriteLine(input);\n\t\tstring newOutput = input + additional;\n\t\tConsole.WriteLine(newOutput);\n\t}\n}"; public const string RazorSnippet = @"<h1>Hello World</h1> <h3>@testString</h3> @code { string testString = ""I Am Here!""; }"; public const string RazorChild = @"<h1>Hello World</h1> <h3>@testString</h3> @code { string testString = ""I Am Child!""; }"; public const string RazorParent = @"<h1>Hello World</h1> <h3>@testString</h3> <RazorChild></RazorChild> @code { string testString = ""I Am Parent!""; }"; public const string RazorActive = @"<h1 class=""@cssClass1"">Hello World</h1> <h3 class=""@cssClass2"">@testString</h3> <style> .redBlue { color:#d50000; background-color:#4fc3f7; } .blueRed { color:#4fc3f7; background-color:#d50000; } .big { } .small { } </style > <button @onclick = ""GetRandom"" > Click </button > <button @onclick = ""ChangeColor"" > @labelText </button > @if(randomVal > 50) { <p > Value @randomVal is greater than 50 </p > } @if(randomVal <= 50) { <p > Value @randomVal is less than 50 </p > } @code { string blueRed = ""blueRed""; string redBlue = ""redBlue""; string cssClass1 = "" ""; string cssClass2 = """"; string testString = ""I Am here!""; Random random = new Random(); int randomVal = 0; string labelText = ""START COLOR""; public void GetRandom() { randomVal = random.Next(1, 111); StateHasChanged(); } public void ChangeColor() { labelText = ""Change Color""; cssClass1 = cssClass1 == redBlue ? blueRed : redBlue; cssClass2 = cssClass2 == blueRed ? redBlue : blueRed; } }"; } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using BestFriendFinder2.Models; using System.IO; using Microsoft.AspNet.Identity; namespace BestFriendFinder2.Controllers { public class AnimalsController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); // GET: Animals public ActionResult Index() { List<Animal> animals = new List<Animal>(); if (User.IsInRole("Humane Society")) { string userID = User.Identity.GetUserId(); var user = db.Users.Where(u => u.Id == userID).FirstOrDefault(); //get user var hs = db.HumaneSocieties.Where(s => s.UserID == user.Id).FirstOrDefault(); animals = db.Animals.Where(a => a.HumaneSocietyID == hs.Id).ToList(); } else { animals = db.Animals.Include(a => a.HumaneSociety).ToList(); } return View(animals.ToList()); } // GET: Animals/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Animal animal = db.Animals.Find(id); if (animal == null) { return HttpNotFound(); } return View(animal); } // GET: Animals/Create public ActionResult Create() { ViewBag.HumaneSocietyID = new SelectList(db.HumaneSocieties, "Id", "Name"); return View(); } // POST: Animals/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Id,Name,Breed,Neutered,Age,HumaneSocietyID")] Animal animal) { if (ModelState.IsValid) { db.Animals.Add(animal); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.HumaneSocietyID = new SelectList(db.HumaneSocieties, "Id", "Name", animal.HumaneSocietyID); return View(animal); } [HttpPost] public ActionResult CreateFromCSV([Bind(Include = "Id,Name,Breed,Neutered,Age,HumaneSocietyID")]HttpPostedFileBase postedFile) { List<Animal> animals = new List<Animal>(); string filePath = string.Empty; if (postedFile != null) { string path = Server.MapPath("~/Uploads/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } filePath = path + Path.GetFileName(postedFile.FileName); string extension = Path.GetExtension(postedFile.FileName); postedFile.SaveAs(filePath); //Read the contents of CSV file. string csvData = System.IO.File.ReadAllText(filePath); //Execute a loop over the rows. string userID = User.Identity.GetUserId(); //get current userID var user = db.Users.Where(u => u.Id == userID).FirstOrDefault(); //get user var hs = db.HumaneSocieties.Where(h => h.UserID == user.Id).FirstOrDefault(); foreach (string row in csvData.Split('\n')) { if (!string.IsNullOrEmpty(row)) { db.Animals.Add(new Animal { Name = row.Split(',')[1], Breed = row.Split(',')[2], Neutered = Convert.ToBoolean(row.Split(',')[3]), Age = Convert.ToInt32(row.Split(',')[4]), HumaneSocietyID = hs.Id }); db.SaveChanges(); } } } return RedirectToAction("Index","Animals"); } // GET: Animals/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Animal animal = db.Animals.Find(id); if (animal == null) { return HttpNotFound(); } ViewBag.HumaneSocietyID = new SelectList(db.HumaneSocieties, "Id", "Name", animal.HumaneSocietyID); return View(animal); } // POST: Animals/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Name,Breed,Neutered,Age,HumaneSocietyID")] Animal animal) { if (ModelState.IsValid) { db.Entry(animal).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.HumaneSocietyID = new SelectList(db.HumaneSocieties, "Id", "Name", animal.HumaneSocietyID); return View(animal); } // GET: Animals/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Animal animal = db.Animals.Find(id); if (animal == null) { return HttpNotFound(); } return View(animal); } // POST: Animals/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Animal animal = db.Animals.Find(id); db.Animals.Remove(animal); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using UnityEngine; using Object = UnityEngine.Object; namespace Architecture.Presenting { [Serializable] public class PresentContextScriptableObject<TView, TKey> : IPresentContext<TView, TKey> where TView : Object { [SerializeField] private TView _prefab; private Dictionary<TKey, TView> _dictionary = new Dictionary<TKey, TView>(); public TView Get(TKey key) { if (!_dictionary.TryGetValue(key, out var pref)) { pref = Object.Instantiate(_prefab); _dictionary.Add(key, pref); } else { if (!pref) { pref = Object.Instantiate(_prefab); _dictionary[key] = pref; } } return pref; } public void Destroy(TKey key) { var pref = _dictionary[key]; Object.Destroy(pref); _dictionary.Remove(key); } } }
using System; using CTCT.Components.Contacts; using CTCT.Util; using CTCT.Components; using CTCT.Exceptions; namespace CTCT.Services { /// <summary> /// Performs all actions pertaining to the Contacts Collection. /// </summary> public class ContactService : BaseService, IContactService { /// <summary> /// Get an array of contacts. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="email">Match the exact email address.</param> /// <param name="limit">Limit the number of returned values.</param> /// <param name="modifiedSince">limit contacts retrieved to contacts modified since the supplied date</param> /// <param name="status">Filter results by contact status</param> /// <returns>Returns a list of contacts.</returns> public ResultSet<Contact> GetContacts(string accessToken, string apiKey, string email, int? limit, DateTime? modifiedSince, ContactStatus? status) { return GetContacts(accessToken, apiKey, email, limit, modifiedSince, status, null); } /// <summary> /// Get an array of contacts. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="modifiedSince">limit contact to contacts modified since the supplied date</param> /// <param name="pag">Pagination object.</param> /// <returns>Returns a list of contacts.</returns> public ResultSet<Contact> GetContacts(string accessToken, string apiKey, DateTime? modifiedSince, Pagination pag) { return GetContacts(accessToken, apiKey, null, null, modifiedSince, null, pag); } /// <summary> /// Get an array of contacts. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="limit">The Record Limit</param> /// <param name="modifiedSince">limit contact to contacts modified since the supplied date</param> /// <param name="pag">Pagination object.</param> /// <returns>Returns a list of contacts.</returns> public ResultSet<Contact> GetContacts(string accessToken, string apiKey, DateTime? modifiedSince, int? limit, Pagination pag) { return GetContacts(accessToken, apiKey, null, limit, modifiedSince, null, pag); } /// <summary> /// Get an array of contacts. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="email">Match the exact email address.</param> /// <param name="limit">Limit the number of returned values.</param> /// <param name="modifiedSince">limit contact to contacts modified since the supplied date</param> /// <param name="status">Match the exact contact status.</param> /// <param name="pag">Pagination object.</param> /// <returns>Returns a list of contacts.</returns> private ResultSet<Contact> GetContacts(string accessToken, string apiKey, string email, int? limit, DateTime? modifiedSince, ContactStatus? status, Pagination pag) { ResultSet<Contact> results = null; // Construct access URL string url = (pag == null) ? Config.ConstructUrl(Config.Endpoints.Contacts, null, new object[] { "email", email, "limit", limit, "modified_since", Extensions.ToISO8601String(modifiedSince), "status", status }) : pag.GetNextUrl(); // Get REST response CUrlResponse response = RestClient.Get(url, accessToken, apiKey); if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } if (response.HasData) { // Convert from JSON results = response.Get<ResultSet<Contact>>(); } return results; } /// <summary> /// Get contact details for a specific contact. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="contactId">Unique contact id.</param> /// <returns>Returns a contact.</returns> public Contact GetContact(string accessToken, string apiKey, string contactId) { Contact contact = null; string url = String.Concat(Config.Endpoints.BaseUrl, String.Format(Config.Endpoints.Contact, contactId)); CUrlResponse response = RestClient.Get(url, accessToken, apiKey); if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } if (response.HasData) { contact = Component.FromJSON<Contact>(response.Body); } return contact; } /// <summary> /// Add a new contact to the Constant Contact account /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="contact">Contact to add.</param> /// <param name="actionByVisitor">Set to true if action by visitor.</param> /// <returns>Returns the newly created contact.</returns> public Contact AddContact(string accessToken, string apiKey, Contact contact, bool actionByVisitor) { Contact newContact = null; string url = String.Concat(Config.Endpoints.BaseUrl, Config.Endpoints.Contacts, actionByVisitor ? String.Format("?action_by={0}", ActionBy.ActionByVisitor) : null); string json = contact.ToJSON(); CUrlResponse response = RestClient.Post(url, accessToken, apiKey, json); if (response.HasData) { newContact = Component.FromJSON<Contact>(response.Body); } else if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } return newContact; } /// <summary> /// Unsubscribe a specific contact. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="contactId">Unique contact id.</param> /// <returns>Returns true if operation succeeded.</returns> public bool DeleteContact(string accessToken, string apiKey, string contactId) { string url = String.Concat(Config.Endpoints.BaseUrl, String.Format(Config.Endpoints.Contact, contactId)); CUrlResponse response = RestClient.Delete(url, accessToken, apiKey); if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } return (!response.IsError && response.StatusCode == System.Net.HttpStatusCode.NoContent); } /// <summary> /// Delete a contact from all contact lists. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="contactId">Contact id to be removed from lists.</param> /// <returns>Returns true if operation succeeded.</returns> public bool DeleteContactFromLists(string accessToken, string apiKey, string contactId) { string url = String.Concat(Config.Endpoints.BaseUrl, String.Format(Config.Endpoints.ContactLists, contactId)); CUrlResponse response = RestClient.Delete(url, accessToken, apiKey); if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } return (!response.IsError && response.StatusCode == System.Net.HttpStatusCode.NoContent); } /// <summary> /// Delete a contact from a specific contact list. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token</param> /// <param name="apiKey">The API key for the application</param> /// <param name="contactId">Contact id to be removed</param> /// <param name="listId">ContactList to remove the contact from</param> /// <returns>Returns true if operation succeeded.</returns> public bool DeleteContactFromList(string accessToken, string apiKey, string contactId, string listId) { string url = String.Concat(Config.Endpoints.BaseUrl, String.Format(Config.Endpoints.ContactList, contactId, listId)); CUrlResponse response = RestClient.Delete(url, accessToken, apiKey); if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } return (!response.IsError && response.StatusCode == System.Net.HttpStatusCode.NoContent); } /// <summary> /// Update contact details for a specific contact. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="contact">Contact to be updated.</param> /// <param name="actionByVisitor">Set to true if action by visitor.</param> /// <returns>Returns the updated contact.</returns> public Contact UpdateContact(string accessToken, string apiKey, Contact contact, bool actionByVisitor) { Contact updateContact = null; if (contact.Id == null) { throw new CtctException(Config.Errors.UpdateId); } string url = String.Concat(Config.Endpoints.BaseUrl, String.Format(Config.Endpoints.Contact, contact.Id), actionByVisitor ? String.Format("?action_by={0}", ActionBy.ActionByVisitor) : null); string json = contact.ToJSON(); CUrlResponse response = RestClient.Put(url, accessToken, apiKey, json); if (response.HasData) { updateContact = Component.FromJSON<Contact>(response.Body); } else if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } return updateContact; } } }
using System; using System.Collections.Generic; using System.Linq; using Common; using OpenTK; namespace LSystemsPlants.Core.L_Systems { public class TurtleInterpreter { private TurtleState State { get; set; } private Stack<TurtleState> StateStack { get; set; } private List<Vector3> Vertices { get; set; } private List<Vector3> Colors { get; set; } public TurtleInterpreter(TurtleState initialState) { State = initialState; StateStack = new Stack<TurtleState>(); } public SimpleModel GetModel(IEnumerable<SymbolState> symbols) { var model = new SimpleModel(); Vertices = new List<Vector3>(symbols.Count()); Colors = new List<Vector3>(symbols.Count()); foreach (SymbolState symbol in symbols) { Execute(symbol); } model.Vertices = Vertices.ToArray(); model.Colors = Colors.ToArray(); model.Normals = new Vector3[] { new Vector3() }; Vertices = null; Colors = null; return model; } private void Execute(SymbolState symbol) { switch (symbol.Symbol) { case Symbol.L: case Symbol.R: case Symbol.FORWARD_DRAW: Vertices.Add(new Vector3(State.Coordinates[0], State.Coordinates[1], State.Coordinates[2])); State = Forward(State, symbol); Vertices.Add(new Vector3(State.Coordinates[0], State.Coordinates[1], State.Coordinates[2])); Colors.Add(symbol.Color); Colors.Add(symbol.Color); break; case Symbol.TURN_LEFT: State = UpdateAngle(symbol.Delta); break; case Symbol.TURN_RIGHT: State = UpdateAngle(-symbol.Delta); break; case Symbol.FORWARD_NO_DRAW: State = Forward(State, symbol); break; case Symbol.PUSH_STATE: StateStack.Push(State); break; case Symbol.POP_STATE: State = StateStack.Pop(); break; default: break; } } private TurtleState Forward(TurtleState state, SymbolState symbol) { Vector3 before = new Vector3(state.Coordinates[0], state.Coordinates[1], state.Coordinates[2]); var scaleMat = Matrix4.CreateScale(symbol.Step); var transformed = Vector3.Transform(Vector3.Transform(Vector3.UnitY, scaleMat), state.RotationMatrix) + before; return new TurtleState() { Coordinates = new[] { transformed.X, transformed.Y, transformed.Z }, Angle = state.Angle, RotationMatrix = state.RotationMatrix }; } private TurtleState UpdateAngle(float delta) { var updatedState = new TurtleState() { Coordinates = State.Coordinates.ToArray(), Angle = State.Angle + delta, }; // prevent accuracy loss if (Math.Abs(updatedState.Angle) > 10) { updatedState.Angle %= MathHelper.TwoPi; } updatedState.RotationMatrix = Matrix4.CreateRotationZ(updatedState.Angle); return updatedState; } } }
using System; using System.IO; using System.Xml.Serialization; namespace OzzUtils.Savables { [Serializable()] public abstract class SavableObject { protected static SavableObject GetInstanceFromFile(string fileName, Type type) { if (!typeof(SavableObject).IsAssignableFrom(type)) { throw new Exception("The type must be inherited from BaseSavable"); } StreamReader reader = new StreamReader(fileName); XmlSerializer x = new XmlSerializer(type); SavableObject instance = x.Deserialize(reader) as SavableObject; reader.Close(); instance.SavedFileName = fileName; return instance; } [XmlIgnore] public string SavedFileName { get; set; } public virtual void SaveToFile() { var folder = Path.GetDirectoryName(SavedFileName); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } StreamWriter writer = new StreamWriter(SavedFileName); XmlSerializer x = new XmlSerializer(this.GetType()); x.Serialize(writer, this); writer.Close(); } public virtual void SaveToFile(string fileName) { SavedFileName = fileName; SaveToFile(); } } }
using Domain.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Infrastructure.Persistence.Configurations { public class ModelConfiguration : IEntityTypeConfiguration<Model> { public void Configure(EntityTypeBuilder<Model> builder) { builder.Property(t => t.Name) .HasMaxLength(200) .IsRequired(); builder.Property(t => t.CreatedBy) .HasMaxLength(450); builder.Property(t => t.LastModifiedBy) .HasMaxLength(450); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InfirmerieBO { public class Medicament { private int id; private string libelle; private bool archive; private bool possedeVisite; // Constructeur qui instancie un objet public Medicament(int id, string libelle, bool archive, bool possedeVisite) { this.id = id; this.libelle = libelle; this.archive = archive; this.possedeVisite = possedeVisite; } public Medicament(int id, bool archive, bool possedeVisite) { this.id = id; this.archive = archive; this.possedeVisite = possedeVisite; } public Medicament(int id) { this.id = id; } public Medicament(string libelle) { this.libelle = libelle; } public int Id { get { return id; } set { id = value; } } public string Libelle { get { return libelle; } set { libelle = value; } } public bool Archive { get { return archive; } set { archive = value; } } public bool PossedeVisite { get { return possedeVisite; } set { possedeVisite = value; } } } }
using System; using Newtonsoft.Json; using OmniSharp.Extensions.JsonRpc.Client; namespace OmniSharp.Extensions.JsonRpc.Serialization.Converters { public class ClientNotificationConverter : JsonConverter<OutgoingNotification> { public override bool CanRead => false; public override OutgoingNotification ReadJson( JsonReader reader, Type objectType, OutgoingNotification existingValue, bool hasExistingValue, JsonSerializer serializer ) => throw new NotImplementedException(); public override void WriteJson(JsonWriter writer, OutgoingNotification value, JsonSerializer serializer) { writer.WriteStartObject(); writer.WritePropertyName("jsonrpc"); writer.WriteValue("2.0"); writer.WritePropertyName("method"); writer.WriteValue(value.Method); if (value.Params != null) { writer.WritePropertyName("params"); serializer.Serialize(writer, value.Params); } if (value.TraceParent != null) { writer.WritePropertyName("traceparent"); writer.WriteValue(value.TraceParent); if (!string.IsNullOrWhiteSpace(value.TraceState)) { writer.WritePropertyName("tracestate"); writer.WriteValue(value.TraceState); } } writer.WriteEndObject(); } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using SGDE.Domain.Entities; namespace SGDE.DataEFCoreSQL.Configurations { public class UserProfessionConfiguration { public UserProfessionConfiguration(EntityTypeBuilder<UserProfession> entity) { entity.ToTable("UserProfession"); entity.HasKey(x => x.Id); entity.Property(x => x.Id).ValueGeneratedOnAdd(); entity.HasIndex(x => x.UserId).HasName("IFK_User_UserProfession"); entity.HasOne(u => u.User).WithMany(a => a.UserProfessions).HasForeignKey(a => a.UserId).HasConstraintName("FK__UserProfession__UserId"); entity.HasIndex(x => x.ProfessionId).HasName("IFK_Profession_UserProfession"); entity.HasOne(u => u.Profession).WithMany(a => a.UserProfessions).HasForeignKey(a => a.ProfessionId).HasConstraintName("FK__UserProfession__ProfessionId"); } } }
using System; using System.Threading; using Caliburn.Micro; using Frontend.Core.Commands; using Frontend.Core.Logging; namespace Frontend.Core.Converting { public class CancelConvertingCommand : CommandBase { private readonly Func<CancellationTokenSource> tokenSourceFunc; public CancelConvertingCommand(IEventAggregator eventAggregator, Func<CancellationTokenSource> tokenSourceFunc) : base(eventAggregator) { this.tokenSourceFunc = tokenSourceFunc; } protected override bool OnCanExecute(object parameter) { return !tokenSourceFunc().IsCancellationRequested; } protected override void OnExecute(object parameter) { EventAggregator.PublishOnUIThread( new LogEntry("Process canceled - will stop working once the current step is complete.", LogEntrySeverity.Warning, LogEntrySource.UI)); tokenSourceFunc().Cancel(); } } }
// Copyright 2021 Google LLC. 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. using NtApiDotNet.Win32; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Runtime.InteropServices; using System.Text; namespace NtApiDotNet.Net.Firewall { /// <summary> /// Static class for firewall utility functions. /// </summary> public static class FirewallUtils { #region Public Members /// <summary> /// Name for fake NT type. /// </summary> public const string FIREWALL_NT_TYPE_NAME = "Firewall"; /// <summary> /// Name for fake filter NT type. /// </summary> public const string FIREWALL_FILTER_NT_TYPE_NAME = "FirewallFilter"; /// <summary> /// Get the NT type for the firewall. /// </summary> public static NtType FirewallType => NtType.GetTypeByName(FIREWALL_NT_TYPE_NAME); /// <summary> /// Get the NT type for the firewall. /// </summary> public static NtType FirewallFilterType => NtType.GetTypeByName(FIREWALL_FILTER_NT_TYPE_NAME); /// <summary> /// Get the generic mapping for a firewall object. /// </summary> /// <returns>The firewall object generic mapping.</returns> public static GenericMapping GetGenericMapping() { return new GenericMapping() { GenericRead = FirewallAccessRights.ReadControl | FirewallAccessRights.BeginReadTxn | FirewallAccessRights.Classify | FirewallAccessRights.Open | FirewallAccessRights.Read | FirewallAccessRights.ReadStats, GenericExecute = FirewallAccessRights.ReadControl | FirewallAccessRights.Enum | FirewallAccessRights.Subscribe, GenericWrite = FirewallAccessRights.ReadControl | FirewallAccessRights.Add | FirewallAccessRights.AddLink | FirewallAccessRights.BeginWriteTxn | FirewallAccessRights.Write, GenericAll = FirewallAccessRights.Delete | FirewallAccessRights.WriteDac | FirewallAccessRights.WriteOwner | FirewallAccessRights.ReadControl | FirewallAccessRights.BeginReadTxn | FirewallAccessRights.Classify | FirewallAccessRights.Open | FirewallAccessRights.Read | FirewallAccessRights.ReadStats | FirewallAccessRights.Enum | FirewallAccessRights.Subscribe | FirewallAccessRights.Add | FirewallAccessRights.AddLink | FirewallAccessRights.BeginWriteTxn | FirewallAccessRights.Write }; } /// <summary> /// Get the generic mapping for a firewall filter object. /// </summary> /// <returns>The firewall filter object generic mapping.</returns> public static GenericMapping GetFilterGenericMapping() { return new GenericMapping() { GenericRead = FirewallFilterAccessRights.ReadControl, GenericExecute = FirewallFilterAccessRights.ReadControl | FirewallFilterAccessRights.Match, GenericWrite = FirewallFilterAccessRights.ReadControl, GenericAll = FirewallFilterAccessRights.ReadControl | FirewallFilterAccessRights.Match }; } /// <summary> /// Get App ID from a filename. /// </summary> /// <param name="filename">The filename to convert.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The App ID.</returns> public static NtResult<string> GetAppIdFromFileName(string filename, bool throw_on_error) { return FirewallNativeMethods.FwpmGetAppIdFromFileName0(filename, out SafeFwpmMemoryBuffer appid).CreateWin32Result( throw_on_error, () => { using (appid) { appid.Initialize<FWP_BYTE_BLOB>(1); var blob = appid.Read<FWP_BYTE_BLOB>(0); return Encoding.Unicode.GetString(blob.ToArray()).TrimEnd('\0'); } }); } /// <summary> /// Get App ID from a filename. /// </summary> /// <param name="filename">The filename to convert.</param> /// <returns>The App ID.</returns> public static string GetAppIdFromFileName(string filename) { return GetAppIdFromFileName(filename, true).Result; } /// <summary> /// Get a list of known layer names. /// </summary> /// <returns>The list of known layer names.</returns> public static IEnumerable<string> GetKnownLayerNames() { return NamedGuidDictionary.LayerGuids.Value.Values; } /// <summary> /// Get a list of known layer guids. /// </summary> /// <returns>The list of known layer guids.</returns> public static IEnumerable<Guid> GetKnownLayerGuids() { return NamedGuidDictionary.LayerGuids.Value.Keys; } /// <summary> /// Get a known layer GUID from its name. /// </summary> /// <param name="name">The name of the layer.</param> /// <returns>The known layer GUID.</returns> public static Guid GetKnownLayerGuid(string name) { return NamedGuidDictionary.LayerGuids.Value.GuidFromName(name); } /// <summary> /// Get a known callout GUID from its name. /// </summary> /// <param name="name">The name of the callout.</param> /// <returns>The known callout GUID.</returns> public static Guid GetKnownCalloutGuid(string name) { return NamedGuidDictionary.CalloutGuids.Value.GuidFromName(name); } /// <summary> /// Get a list of known sub-layer names. /// </summary> /// <returns>The list of known sub-layer names.</returns> public static IEnumerable<string> GetKnownSubLayerNames() { return NamedGuidDictionary.SubLayerGuids.Value.Values; } /// <summary> /// Get a list of known callout names. /// </summary> /// <returns>The list of known callout names.</returns> public static IEnumerable<string> GetKnownCalloutNames() { return NamedGuidDictionary.CalloutGuids.Value.Values; } /// <summary> /// Get a list of known sub-layer guids. /// </summary> /// <returns>The list of known sub-layer guids.</returns> public static IEnumerable<Guid> GetKnownSubLayerGuids() { return NamedGuidDictionary.SubLayerGuids.Value.Keys; } /// <summary> /// Get a known sub-layer GUID from its name. /// </summary> /// <param name="name">The name of the sub-layer.</param> /// <returns>The known sub-layer GUID.</returns> public static Guid GetKnownSubLayerGuid(string name) { return NamedGuidDictionary.SubLayerGuids.Value.GuidFromName(name); } /// <summary> /// Get a layer GUID for an ALE layer enumeration. /// </summary> /// <param name="ale_layer">The ALE layer enumeration.</param> /// <returns>The ALE layer GUID.</returns> public static Guid GetLayerGuidForAleLayer(FirewallAleLayer ale_layer) { switch (ale_layer) { case FirewallAleLayer.ConnectV4: return FirewallLayerGuids.FWPM_LAYER_ALE_AUTH_CONNECT_V4; case FirewallAleLayer.ConnectV6: return FirewallLayerGuids.FWPM_LAYER_ALE_AUTH_CONNECT_V6; case FirewallAleLayer.ListenV4: return FirewallLayerGuids.FWPM_LAYER_ALE_AUTH_LISTEN_V4; case FirewallAleLayer.ListenV6: return FirewallLayerGuids.FWPM_LAYER_ALE_AUTH_LISTEN_V6; case FirewallAleLayer.RecvAcceptV4: return FirewallLayerGuids.FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4; case FirewallAleLayer.RecvAcceptV6: return FirewallLayerGuids.FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6; default: throw new ArgumentException("Unknown ALE layer", nameof(ale_layer)); } } #endregion #region Internal Methods internal static T CloneValue<T>(this T value) { if (value is ICloneable clone) return (T)clone.Clone(); return value; } internal static IPAddress GetAddress(FirewallIpVersion ip_version, byte[] addr_bytes) { switch (ip_version) { case FirewallIpVersion.V4: return new IPAddress(BitConverter.ToUInt32(addr_bytes.Take(4).Reverse().ToArray(), 0)); case FirewallIpVersion.V6: return new IPAddress(addr_bytes); } return IPAddress.None; } internal static IPAddress GetAddress(FirewallIpVersion ip_version, uint ip_address, byte[] remaining_bytes) { byte[] full_bytes = new byte[16]; Array.Copy(BitConverter.GetBytes(ip_address), full_bytes, 4); Array.Copy(remaining_bytes, 0, full_bytes, 4, 12); return GetAddress(ip_version, full_bytes); } internal static IPEndPoint GetEndpoint(FirewallIpVersion ip_version, uint ip_address, byte[] remaining_bytes, int port) { return new IPEndPoint(GetAddress(ip_version, ip_address, remaining_bytes), port); } internal static IPEndPoint GetEndpoint(FirewallIpVersion ip_version, byte[] addr_bytes, int port) { return new IPEndPoint(GetAddress(ip_version, addr_bytes), port); } #endregion } }
namespace Core.Interfaces { public interface Cuttable { } }
using System; using System.Collections.Generic; using System.Drawing; namespace Tanki { /// <summary> /// Интерфейс описующий информацию об игре (IGameRoom). /// Является частью интерфейса IGameRoom. /// Предназначен для обмена между клиентом/серверером /// Реализующий клас обязан иметь атрибут [Serializable] /// </summary> public interface IRoomStat { string Id { get; set; } int Players_count { get; set; } string Creator_Id { get; set; } } /// <summary> /// Интерфейс описующий информацию об игровом поле. /// Предназначен для обмена между клиентом/серверером /// Реализующий клас обязан иметь атрибут [Serializable] /// </summary> public interface IMap { IEnumerable<ITank> Tanks { get; set; } IEnumerable<IBullet> Bullets { get; set; } IEnumerable<IBlock> Blocks { get; set; } } /// <summary> /// Интерфейс описующий информацию об объекте. /// Является родителем для ITank, IBullet, IBlock. /// Предназначен для обмена между клиентом/серверером /// Реализующий клас обязан иметь атрибут [Serializable] /// </summary> public interface IEntity { Point Position { get; set; } Direction Direction { get; set; } bool Can_Shoot { get; set; } bool Is_Alive { get; set; } bool Can_Be_Destroyed { get; set; } int Speed { get; set; } } /// <summary> /// Интерфейс описующий информацию о Танке(Игроке). /// Является наследником IEntity. /// Является частью IPlayer(подругому IGamer). /// Используется в интерфейсах IServerEngine и IClientEngine. /// Реализующий клас обязан иметь атрибут [Serializable] /// </summary> public interface ITank : IEntity { int Lives { get; set; } Team Team { get; set; } } /// <summary> /// Интерфейс описующий информацию о Пуле. /// Является наследником IEntity. /// Используется в интерфейсах IServerEngine и IClientEngine. /// Реализующий клас обязан иметь атрибут [Serializable] /// </summary> public interface IBullet : IEntity { string Parent_Id { get; set; } } /// <summary> /// Интерфейс описующий информацию о Преградах (Пеньках). /// Является наследником IEntity. /// Используется в интерфейсах IServerEngine и IClientEngine. /// Реализующий клас обязан иметь атрибут [Serializable] /// </summary> public interface IBlock : IEntity { } /// <summary> Интерфейс описывает сущность Отправляющюю сообщения клиенту/серверу</summary> public interface ISender { } /// <summary> Интерфейс описывает сущность Принимающюю сообщения от клиента/сервера </summary> public interface IReceiver { } #region MessageQueue Interfaces /// <summary> Интерфейс описывает очередь сообщений клиента/сервера </summary> public interface IMessageQueue : IDisposable { void Enqueue(IPackage msg); void RUN(); } public enum MsgQueueType { mqOneByOneProcc, mqByTimerProcc } public interface IMessageQueueFabric { IMessageQueue CreateMessageQueue(MsgQueueType queueType, IEngine withEngine); } #endregion MessageQueue Interfaces #region IEngine /// <summary> Общий Интерфейс для движков (серверного и клиентского /// должен передаватся как dependency MessageQueue (поэтому определяется сдесь для исключения циклических ссылок библиотек) /// реализации будут в разных библиотеках, т.к. это разные реализации для разных приложений public delegate void ProcessMessageHandler(IPackage message); public delegate void ProcessMessagesHandler(IEnumerable<IPackage> messages); public interface IEngine { ProcessMessageHandler ProcessMessage { get; } ProcessMessagesHandler ProcessMessages { get; } } #endregion /// <summary> Пакет данных - играет роль сообщения между клинтом/сервером. /// Используется в IMesegeQueue, ISender, IReceiver</summary> /// Реализующий клас обязан иметь атрибут [Serializable] public interface IPackage { string Sender_id { get; set; } object Data { get; set; } } /// <summary> Сереализатор. Используется в ISender, IReceiver. </summary> public interface ISerializator { byte[] Serialize(object obj); IPackage Deserialize(byte[] bytes); } }
namespace WindowsFormsApp1 { partial class OrdersDBDataSet { partial class CustomerDataTable { } } } namespace WindowsFormsApp1.OrdersDBDataSetTableAdapters { partial class OrderTableAdapter { } public partial class CustomerTableAdapter { } }
namespace Detectors { public interface ISwitchable { void switchOn(); // включить датчик void switchOff(); // выключить датчик void checkUp(); // проверить состояние } }
using FastSQL.Core; using FastSQL.Sync.Core.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FastSQL.Sync.Core.Settings { public abstract class BaseSettingProvider : ISettingProvider { public abstract string Id { get; } public abstract string Name { get; } public abstract string Description { get; } public abstract bool Optional { get; } public string Message { get; set; } public virtual IEnumerable<OptionItem> Options => OptionManager?.Options ?? new List<OptionItem>(); public abstract IEnumerable<string> Commands { get; } public abstract Task<bool> Validate(); protected readonly IOptionManager OptionManager; public ResolverFactory ResolverFactory { get; set; } public BaseSettingProvider(IOptionManager optionManager) { OptionManager = optionManager; } public virtual ISettingProvider SetOptions(IEnumerable<OptionItem> options) { OptionManager.SetOptions(options); return this; } public abstract ISettingProvider LoadOptions(); public abstract ISettingProvider Save(); public abstract Task<bool> InvokeChildCommand(string command); public virtual async Task<bool> Invoke(string commandName) { if (commandName.ToLower() == "save") { Save(); Message = "Settings have been saved."; return true; } else if (commandName.ToLower() == "validate") { var result = await Validate(); return result; } return await InvokeChildCommand(commandName); } public virtual void Dispose() { } } }
using System; namespace Im.Access.GraphPortal.Repositories { public class ChaosPolicyEntity { public Guid Id { get; set; } public string PolicyKey { get; set; } public string Service { get; set; } public bool Enabled { get; set; } public bool FaultEnabled { get; set; } public double FaultInjectionRate { get; set; } public bool LatencyEnabled { get; set; } public double LatencyInjectionRate { get; set; } public DateTimeOffset LastUpdated { get; set; } } }
namespace Components.Core.DataAccess.Base.Interfaces { using Components.Core.DataAccess.Base.Poco; using System.Threading.Tasks; public interface IAsyncUnitOfWork<TEntity> where TEntity : Entity { Task<int> CommitAsync(); } }
using System; using System.Collections.Generic; using TestGame.Utils; namespace TestGame.Characters { /// <summary> /// Abstract character class. /// </summary> public abstract class Character { private const int MAX_HEALTH = 100; private int health = MAX_HEALTH; private String name; private Randomizer random = new Randomizer(); protected List<Actions.Action> actions; public String Name { get { return name; } protected set { name = value; } } public int Health { get { return health; } protected set { health = value; } } public int MaxHealth { get { return MAX_HEALTH; } } public Character(String name) { this.name = name; } /// <summary> /// Check character is alive or not. /// </summary> /// <returns>Character is alive or not</returns> public bool isAlive() { return (health > 0); } /// <summary> /// To damage the character. /// </summary> /// <param name="damage">Damage value</param> public void applyDamage(int damage) { health -= damage; if (health < 0) health = 0; } /// <summary> /// To heal the character. /// </summary> /// <param name="heal">Heal value</param> public void applyHeal(int heal) { health += heal; if (health > MAX_HEALTH) health = MAX_HEALTH; } /// <summary> /// Get random character action. /// </summary> /// <returns>Random action</returns> public Actions.Action getAction() { return actions[random.getRandomIndex(actions)]; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Shooter { class Menu { List<IOption> _options; string _header; int _maxLength; int _currentOption; int _x; int _y; public Menu() { MakeTight = false; _options = new List<IOption>(); } public Menu(string header, params string[] options) : this() { _header = header; for (int i = 0; i < options.Length; i++) { _options.Add(new Option(options[i], i)); } } public Menu(params IOption[] options) : this() { _options.AddRange(options); } public Menu(string header, params IOption[] options) : this(options) { _header = header; } public void Clear() { int add = 2; if (!string.IsNullOrEmpty(_header)) { if (MakeTight) _y -= 2; else _y -= 3; add += 4; } for (int i = 0; i < _options.Count + add; i++) { Console.SetCursorPosition(_x, _y + i); Console.BackgroundColor = ConsoleColor.Black; DrawLine(" ", _maxLength + 4); } } public int Start(int x, int y) { return Start(x, y, true); } public int Start(int x, int y, bool stop) { _x = x; _y = y; _currentOption = -1; Console.CursorVisible = false; bool optionsAvailable = false; for (int i = 0; i < _options.Count; i++) { if (!_options[i].IsEmpty() && !optionsAvailable) { optionsAvailable = true; if (stop) _currentOption = i; } if (_options[i].MaxLengthNeeded > _maxLength) _maxLength = _options[i].MaxLengthNeeded; } if (!string.IsNullOrEmpty(_header)) if (_maxLength < _header.Length + 8) _maxLength = _header.Length + 8; if (_x == -1) _x = (80 - _maxLength - 4) / 2; //╔═╗║╚╝╡╞ ╞╡┌┐└┘─ Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; if (!string.IsNullOrEmpty(_header)) { int offset = 3; if (MakeTight) offset = 2; Console.SetCursorPosition(_x, _y - offset); DrawLine(" ", (_maxLength - _header.Length - 6) / 2 + 2 + (_maxLength - _header.Length - 6) % 2); Console.Write("╔"); DrawLine("═", _header.Length + 4); Console.Write("╗"); DrawLine(" ", (_maxLength - _header.Length - 6) / 2 + 2); Console.SetCursorPosition(_x, _y - offset + 1); Console.Write("╔"); DrawLine("═", (_maxLength - _header.Length - 6) / 2 + 1 + (_maxLength - _header.Length - 6) % 2); Console.Write("╣ "); Console.Write(_header); Console.Write(" ╠"); DrawLine("═", (_maxLength - _header.Length - 6) / 2 + 1); Console.Write("╗"); Console.SetCursorPosition(_x, _y - offset + 2); Console.Write("║"); DrawLine(" ", (_maxLength - _header.Length - 6) / 2 + 1 + (_maxLength - _header.Length - 6) % 2); Console.Write("╚"); DrawLine("═", _header.Length + 4); Console.Write("╝"); DrawLine(" ", (_maxLength - _header.Length - 6) / 2 + 1); Console.Write("║"); if (!MakeTight) { Console.SetCursorPosition(_x, _y); Console.Write("║"); DrawLine(" ", _maxLength + 2); Console.Write("║"); } } else { Console.SetCursorPosition(_x, _y); Console.Write("╔"); DrawLine("═", _maxLength + 2); Console.Write("╗"); } for (int i = 0; i < _options.Count; i++) { _options[i].Menu = this; _options[i].Draw(); } Console.SetCursorPosition(_x, _y + _options.Count + 1); if (!string.IsNullOrEmpty(_header) && !MakeTight) { Console.Write("║"); DrawLine(" ", _maxLength + 2); Console.Write("║"); Console.SetCursorPosition(_x, _y + _options.Count + 2); } Console.Write("╚"); DrawLine("═", _maxLength + 2); Console.Write("╝"); if (!stop) return 0; if (!optionsAvailable) { Console.ReadKey(true); return 0; } if (_currentOption < 0) _currentOption = 0; _options[_currentOption].Draw(); ConsoleKeyInfo key; do { key = Console.ReadKey(true); if (_currentOption < 0) _currentOption = 0; if (!_options[_currentOption].Update(ref key)) { int index = _currentOption; do { if (key.Key == ConsoleKey.DownArrow && _currentOption < _options.Count - 1) index++; else if (key.Key == ConsoleKey.UpArrow && _currentOption > 0) index--; } while (_options[index].IsEmpty() && index != _options.Count - 1 && index != 0); if ((index == _options.Count - 1 || index == 0) && _options[index].IsEmpty()) index = _currentOption; if (index != _currentOption) { int temp = _currentOption; _currentOption = index; _options[temp].Draw(); _options[_currentOption].Draw(); } } else key = new ConsoleKeyInfo(); } while (key.Key != ConsoleKey.Enter); Console.CursorVisible = true; return _options[_currentOption].Value; } public void ReDraw() { this.Start(_x, _y, false); } public static void DrawLine(string text, int repeat) { for (int i = 0; i < repeat; i++) Console.Write(text); } public bool MakeTight { get; set; } public List<IOption> Options { get { return _options; } } public int MaxLength { get { return _maxLength; } set { _maxLength = value; } } public int CurrentOption { get { return _currentOption; } } public int X { get { return _x; } } public int Y { get { return _y; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LogUrFace.Domain.Events { public class Bus { private static readonly IList<IHandler<IDomainEvent>> Handlers = new List<IHandler<IDomainEvent>>(); public static void Register(IHandler<IDomainEvent> handler) { if (handler != null) Handlers.Add(handler); } public static void Raise<T>(T eventData) where T : IDomainEvent { foreach (var handler in Handlers) { if (handler.CanHandle(eventData)) handler.Handle(eventData); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.ServiceModel.Web; using System.Web; using TicketSellingServer; namespace FlightSearchServerCA { /// <summary> /// Defines the API between Client and Search server /// </summary> [ServiceContract] public interface IClientQueryService { /// <summary> /// See concrete class for details /// </summary> /// <param name="src"></param> /// <param name="dst"></param> /// <param name="date"></param> /// <returns></returns> [WebGet(UriTemplate = "flight?src={src}&dst={dst}&date={date}")] [OperationContract] QueryResultFlights GetFlights(string src, string dst, string date); /// <summary> /// See concrete class for details /// </summary> /// <param name="seller"></param> /// <param name="request"></param> /// <returns></returns> [WebInvoke(Method = "POST", UriTemplate = "seller/{seller}")] [OperationContract] int MakeReservation(string seller, ReservationRequest request); /// <summary> /// See concrete class for details /// </summary> /// <param name="seller"></param> /// <param name="request"></param> /// <returns></returns> [WebInvoke(Method = "DELETE", UriTemplate = "seller/{seller}/{reservationID}")] [OperationContract] void CancelReservation(string seller, string reservationID); } }
using Job.Customer.ExecuteCustomer.ExternalServices.Contents; using Job.Customer.ExecuteCustomer.ExternalServices.HttpRequest; using Job.Customer.ExecuteCustomer.Interfaces; using Job.Customer.ExecuteCustomer.Models.Response; using System.Threading.Tasks; namespace Job.Customer.ExecuteCustomer.Http { public class CustomerAPI : ICustomerAPI { private readonly ICustomerAPISettings _customerAPISettings; private int timeOut = 360; public CustomerAPI(ICustomerAPISettings customerAPISettings) { _customerAPISettings = customerAPISettings; } public async ValueTask<CustomersResponse> GetCustomers() { var result = await HttpRequestFactory.Get(string.Concat(_customerAPISettings.ApiBasePath, _customerAPISettings.ApiPath), timeOut, string.Empty); return result.ContentAsType<CustomersResponse>(); } } }
using System; using System.Collections; using System.Collections.Generic; using ObjectPooling; using UnityEngine; using UnityEngine.PlayerLoop; public class CarLateralMovement : MonoBehaviour { [Header("Scriptables")] [SerializeField] private SOGameObjectRef _RoadChunksRef; [SerializeField] private SOStearingInputs _StearingInputsRef; [SerializeField] private SOTimer _TimerRef; [SerializeField] private SOSwitchState _SwitchStateRef; [SerializeField] private Transform _Pivot; [SerializeField] private float _SpeedStateReducer = 0.25f; [SerializeField] private Vector3 _MoveAmount; private float _CurrentPosition; private float _SpeedMultiplier = 1f; private void OnEnable() { _StearingInputsRef.Instance.Value.StearingEvent += ChangeMovementDirection; _SwitchStateRef.Instance.Value.SwitchStatesEvent += StatesSwitched; _Pivot.rotation = Quaternion.Euler(0f, 0f, -10); } private void StatesSwitched() { if (_SwitchStateRef.Instance.Value.IsInDriveState % 2 == 0) { _SpeedMultiplier = _SpeedStateReducer; } else { _SpeedMultiplier = 1; } } private void OnDisable() { _StearingInputsRef.Instance.Value.StearingEvent -= ChangeMovementDirection; _SwitchStateRef.Instance.Value.SwitchStatesEvent -= StatesSwitched; } private void ChangeMovementDirection(int direction) { if ((_MoveAmount.x < 0 && direction < 0) || (_MoveAmount.x > 0 && direction > 0)) { _MoveAmount.x *= -1f; if (_Pivot.rotation.z < 0) { _Pivot.rotation = Quaternion.Euler(0f, 0f, 10); } else { _Pivot.rotation = Quaternion.Euler(0f, 0f, -10); } } } private void Update() { _CurrentPosition += (_MoveAmount.x * _SpeedMultiplier); var yPos = _RoadChunksRef.Instance.Value.transform.position.y; var zPos = _RoadChunksRef.Instance.Value.transform.position.z; _RoadChunksRef.Instance.Value.transform.position = new Vector3(-_CurrentPosition, yPos, zPos); if (_MoveAmount.x > 0f || -_CurrentPosition < 0) return; ResetCarPosition(); } public void ResetCarPosition() { _TimerRef.TryStartTimer(); } }
// *** WARNING: this file was generated by pulumigen. *** // *** 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.Kubernetes.Types.Inputs.Core.V1 { /// <summary> /// ContainerStatus contains details for the current status of this container. /// </summary> public class ContainerStatusArgs : Pulumi.ResourceArgs { /// <summary> /// Container's ID in the format 'docker://&lt;container_id&gt;'. /// </summary> [Input("containerID")] public Input<string>? ContainerID { get; set; } /// <summary> /// The image the container is running. More info: https://kubernetes.io/docs/concepts/containers/images /// </summary> [Input("image", required: true)] public Input<string> Image { get; set; } = null!; /// <summary> /// ImageID of the container's image. /// </summary> [Input("imageID", required: true)] public Input<string> ImageID { get; set; } = null!; /// <summary> /// Details about the container's last termination condition. /// </summary> [Input("lastState")] public Input<Pulumi.Kubernetes.Types.Inputs.Core.V1.ContainerStateArgs>? LastState { get; set; } /// <summary> /// This must be a DNS_LABEL. Each container in a pod must have a unique name. Cannot be updated. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// Specifies whether the container has passed its readiness probe. /// </summary> [Input("ready", required: true)] public Input<bool> Ready { get; set; } = null!; /// <summary> /// The number of times the container has been restarted, currently based on the number of dead containers that have not yet been removed. Note that this is calculated from dead containers. But those containers are subject to garbage collection. This value will get capped at 5 by GC. /// </summary> [Input("restartCount", required: true)] public Input<int> RestartCount { get; set; } = null!; /// <summary> /// Specifies whether the container has passed its startup probe. Initialized as false, becomes true after startupProbe is considered successful. Resets to false when the container is restarted, or if kubelet loses state temporarily. Is always true when no startupProbe is defined. /// </summary> [Input("started")] public Input<bool>? Started { get; set; } /// <summary> /// Details about the container's current condition. /// </summary> [Input("state")] public Input<Pulumi.Kubernetes.Types.Inputs.Core.V1.ContainerStateArgs>? State { get; set; } public ContainerStatusArgs() { } } }
using System.Collections.Generic; using System.Security.Claims; using JPProject.Domain.Core.Events; namespace JPProject.Sso.Domain.Events.User { public class ClaimsSyncronizedEvent : Event { public IEnumerable<Claim> Claims { get; } public ClaimsSyncronizedEvent(string username, IEnumerable<Claim> claims) : base(EventTypes.Success) { Claims = claims; AggregateId = username; } } }
using Android.Graphics; using System; using System.Collections.Generic; using System.Net; using System.Text; namespace BoardGamedia { /// <summary> /// Contains various utility methods. /// </summary> public class Utilities { /// <summary> /// Gets a <see cref="Bitmap"/> from a <paramref name="url"/>. /// </summary> /// <param name="url">Url to get the bitmap from.</param> /// <returns>Returns a <see cref="Bitmap"/> containing the image retrieved from the URL.</returns> public static Bitmap GetImageBitmapFromUrl(string url) { Bitmap imageBitmap = null; using (var webClient = new WebClient()) { var imageBytes = webClient.DownloadData(url); if (imageBytes != null && imageBytes.Length > 0) { imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length); } } return imageBitmap; } } }
using System.Net; using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.AspNetCore.Mvc; using Reception.Contracts.Reception; using Reception.Handlers.Order.Queries; namespace Reception.Api.Controllers { /// <summary> /// Контроллер для работы с заказом. /// </summary> [Route("api/[controller]")] [ApiController] public class OrderController : ControllerBase { private readonly IMediator _mediator; /// <summary> /// Инициализирует экземпляр <see cref="OrderController"/>. /// </summary> /// <param name="mediator">Медатор.</param> public OrderController(IMediator mediator) { _mediator = mediator; } /// <summary> /// Вовзаращет модель заказа по его идентификатору. /// </summary> /// <param name="orderId">Идентификатор заказа.</param> /// <param name="cancellation">Отмена задачи.</param> /// <returns>Задача, представляющая асинзронную операцию получение модели заказа по его идентификатору.</returns> [ProducesResponseType(typeof(OrderRegistryItem), (int)HttpStatusCode.OK)] [HttpGet("{orderId}")] public async Task<IActionResult> Get(int orderId, CancellationToken cancellation) { var order = await _mediator.Send(new GetOrderByIdQuery(orderId), cancellation); return Ok(order); } } }
namespace EcobitStage.DataTransfer { public class DTO { } }
namespace AtmDb.Data.Migrations { using System; using System.Data.Entity.Migrations; using System.Linq; using System.Text; internal sealed class Configuration : DbMigrationsConfiguration<AtmDbContext> { private const int CardNumberLength = 10; private const int CardPinLength = 4; private static Random randomGenerator = new Random(); public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; } protected override void Seed(AtmDbContext context) { if (context.CardAccount.Count() <= 0) { StringBuilder queryBuilder = new StringBuilder(); for (int j = 0; j < 50; j++) { queryBuilder.AppendLine("INSERT INTO CardAccounts (CardNumber, CardPin, CardCash) VALUES "); string cardNumber = GetRandomNumber(CardNumberLength); string cardPin = GetRandomNumber(CardPinLength); decimal balance = randomGenerator.Next(0, 1000000); queryBuilder.AppendLine(string.Format("('{0}', '{1}', {2}), ", cardNumber, cardPin, balance)); queryBuilder.Remove(queryBuilder.Length - 4, 2); queryBuilder.Append(';'); context.Database.ExecuteSqlCommand(queryBuilder.ToString()); queryBuilder.Clear(); } } } private string GetRandomNumber(int numberLength) { StringBuilder cardString = new StringBuilder(); for (int i = 0; i < numberLength; i++) { int randomDigit = randomGenerator.Next(0, 10); cardString.Append(randomDigit); } return cardString.ToString(); } } }
using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public static class Container { [return: NotNullIfNotNull("items")] public static Container<T>? From<T>(IEnumerable<T>? items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static Container<T>? From<T>(params T[] items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static Container<T>? From<T>(List<T>? items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static Container<T>? From<T>(in ImmutableArray<T>? items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static Container<T>? From<T>(ImmutableList<T>? items) => items switch { not null => new Container<T>(items), _ => null }; } public class Container<T> : ContainerBase<T> { public Container() : this(Enumerable.Empty<T>()) { } public Container(IEnumerable<T> items) : base(items) { } public Container(params T[] items) : base(items) { } [return: NotNullIfNotNull("items")] public static Container<T>? From(IEnumerable<T>? items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static implicit operator Container<T>?(T[] items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static Container<T>? From(params T[] items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static implicit operator Container<T>?(Collection<T>? items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static Container<T>? From(Collection<T>? items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static implicit operator Container<T>?(List<T>? items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static Container<T>? From(List<T>? items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static implicit operator Container<T>?(in ImmutableArray<T>? items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static Container<T>? From(in ImmutableArray<T>? items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static implicit operator Container<T>?(ImmutableList<T>? items) => items switch { not null => new Container<T>(items), _ => null }; [return: NotNullIfNotNull("items")] public static Container<T>? From(ImmutableList<T>? items) => items switch { not null => new Container<T>(items), _ => null }; } }
using UnityEngine; using System.Collections; using UnityEngine.UI; // a script to manage the value of the slider and to disable animation if the slider is set to the lowest value public class sliderValue : MonoBehaviour { public static int frames; public static bool interactable; public static bool animated; // Use this for initialization void Start () { frames = (int) GetComponent<Slider>().value; if(frames == 14) animated = false; else animated = true; interactable = true; } void Update() { if(!(bool)GetComponent<Slider>().IsInteractable()) interactable = false; else interactable = true; } public void onChanged() { if((bool)GetComponent<Slider>().IsInteractable()) { frames = (int)GetComponent<Slider>().value; interactable = true; if(frames == 14) animated = false; else animated = true; } else { interactable = false; } } }
using LearningEnglishMobile.Core.Models.User; using LearningEnglishMobile.Core.Services.Identity; using LearningEnglishMobile.Core.Services.OpenUrl; using LearningEnglishMobile.Core.Services.RequestProvider; using LearningEnglishMobile.Core.ViewModels; using LearningEnglishMobile.Core.ViewModels.Base; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace LearningEnglishMobile.Core.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class LoginView : ContentPage { public LoginView() { InitializeComponent(); } } }
using UnityEngine; namespace Game.Graphics.UI.Screen.Window { public class Window : MonoBehaviour { public bool IsActive; public CanvasGroup CanvasGroup; } }
using System; using OpenCookly.Common.Modules; using System.Collections.Generic; using System.ComponentModel.Composition; using Hegoburu.Presentation.Desktop.Core; namespace OpenCookly.Modules.Core { [Export(typeof(IModule))] public class Module : IModule { private List<IActivity> _activities; public Module() { _activities = new List<IActivity>(); } #region IModule implementation public void Initialize(StructureMap.IContainer container) { container.BuildUp(this); } public string Name { get { return "Core"; } } public string Description { get { return "Core system functionality"; } } public List<IActivity> Activities { get { return _activities; } } public IViewManager ViewManager{ get; set; } public IModelManager ModelManager{ get; set; } #endregion } }
using System.Net.Http; using System.Threading.Tasks; namespace DiscordBot.Bot.Common { public class HttpClientWrapper { private static readonly HttpClient Client = new HttpClient(); public Task<HttpResponseMessage> GetAsync(string url) { return Client.GetAsync(url); } } }
using System.IO; using Android.Content.Res; using GameLib; using GameLib.Audio; using GameLib.Input; using JumpAndRun.Actors; using JumpAndRun.ClientBase; using JumpAndRun.Content.BlockDefinitions; using JumpAndRun.Content.TerrainGeneration.Bioms; using ManagedBass; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace JumpAndRun.Client.Android { /// <summary> /// This is the main type for your game. /// </summary> public class JumpAndRunAndroidGame : Game { private readonly BaseGame _baseGame; private readonly GraphicsDeviceManager _manager; public JumpAndRunAndroidGame(AssetManager assets) { _manager = new GraphicsDeviceManager(this); _baseGame = new BaseGame(this); Content.RootDirectory = "Content"; _manager.IsFullScreen = true; _manager.PreferredBackBufferWidth = 800; _manager.PreferredBackBufferHeight = 480; _manager.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight; GameContext.Instance.Set(Platform.Android, assets); //_server = new Server(); //System.Threading.Thread.Sleep(1000); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { Bass.Init(); ContentManager.Instance.LoadContent(); ContentManager.Instance.Effect = Content.Load<Effect>("LightsBump"); //ContentManager.Instance.Effect = new AlphaTestEffect(GraphicsDevice); ContentManager.Instance.Font = Content.Load<SpriteFont>("Font"); //ContentManager.Instance.Effects.Add("JumpAndRun.DrunkEffect", Content.Load<Effect>("DrunkEffect")); ContentManager.Instance.PlayerEffects.Add(new Content.PlayerEffects.DrunkEffect().Name, new Content.PlayerEffects.DrunkEffect()); ContentManager.Instance.PlayerEffects.Add(new PlayerEffect().Name, new PlayerEffect()); ContentManager.Instance.BlockDefinitions.Add(new DirtBlockDefinition()); ContentManager.Instance.BlockDefinitions.Add(new LeaveBlockDefinition()); ContentManager.Instance.BlockDefinitions.Add(new GrassBlockDefinition()); ContentManager.Instance.BlockDefinitions.Add(new LogBlockDefinition()); ContentManager.Instance.BlockDefinitions.Add(new SandBlockDefinition()); ContentManager.Instance.Biomes.Add(new TestBiom()); ContentManager.Instance.Biomes.Add(new TestBiom2()); ContentManager.Instance.Animations.Add(new Content.Animations.SwordBeat().Name, new Content.Animations.SwordBeat()); ContentManager.Instance.Animations.Add(new Content.Animations.SwordIdle().Name, new Content.Animations.SwordIdle()); ContentManager.Instance.Items.Add(new Content.TestItem().Name, new Content.TestItem()); ContentManager.Instance.WorldComponents.Add(new Content.WorldComponent.Sun().Name, new Content.WorldComponent.Sun()); ContentManager.Instance.Actors.Add(new Content.NPCs.TestNpc()); ContentManager.Instance.Actors.Add(new Player()); ContentManager.Instance.Actors.Add(new MultiplayerPlayer()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.AddActorPackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.BlockChangePackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.ChunkPackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.ChunkRequestPackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.LogOffPackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.LogOnPackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.MovePackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.PingPackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.PlayerInfoPackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.RemoveActorPackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.SetActorDataPackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.TimeFactorPackage()); ContentManager.Instance.NetworkingPackages.Add(new Networking.Packages.TimeUpdatePackage()); _baseGame.Initialize(_manager); ContentManager.Instance.RegisterContent(); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. // TODO: use this.Content to load your game content here } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// game-specific content. /// </summary> protected override void UnloadContent() { _baseGame.UnloadContent(); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="realGameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime realGameTime) { _baseGame.Update(realGameTime); base.Update(realGameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="realGameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime realGameTime) { _baseGame.Draw(realGameTime); base.Draw(realGameTime); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using System.Linq; using System.Web; namespace treatment.Models { public class CommunityDBContext : DbContext { public CommunityDBContext(): base("CommunityMedicineDBContext") { Configuration.ProxyCreationEnabled = false; } public System.Data.Entity.DbSet<treatment.Models.District> Districts { get; set; } public System.Data.Entity.DbSet<treatment.Models.Thana> Thanas { get; set; } public System.Data.Entity.DbSet<treatment.Models.CommunityClinic> CommunityClinics { get; set; } public System.Data.Entity.DbSet<treatment.Models.Medicine> Medicines { get; set; } public System.Data.Entity.DbSet<treatment.Models.MedicineClinic> MedicineClinics { get; set; } public System.Data.Entity.DbSet<treatment.Models.Treatment> Treatments { get; set; } public System.Data.Entity.DbSet<treatment.Models.Doctor> Doctors { get; set; } public System.Data.Entity.DbSet<treatment.Models.Voter> Voters { get; set; } public System.Data.Entity.DbSet<treatment.Models.MedicineDose> MedicineDoses { get; set; } public System.Data.Entity.DbSet<treatment.Models.Desease> Deseases { get; set; } public System.Data.Entity.DbSet<treatment.Models.Account> Accounts { get; set; } public System.Data.Entity.DbSet<treatment.Models.TreatmentMedicine> TreatmentMedicines { get; set; } public System.Data.Entity.DbSet<treatment.Models.ViewModel.MedicineStockViewModel> MedicineStockViewModels { get; set; } public System.Data.Entity.DbSet<treatment.Models.DoctorClinic> DoctorClinics { get; set; } } }
using Microsoft.EntityFrameworkCore; using Realeyes.Domain.Models; namespace Realeyes.Infrastructure.Data { public class RealeyeDbContext:DbContext { public DbSet<Survey> Surveys { get; private set; } public DbSet<Session> Sessions { get; private set; } public RealeyeDbContext(DbContextOptions<RealeyeDbContext> options) : base(options) { } } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using System; using UnityEngine; namespace EnhancedEditor { /// <summary> /// Utility class used to dynamically increase and decrease the game global choronos, according to predefined steps. /// </summary> public static class ChronosStepper { #region Behaviour /// <summary> /// Delegate used to set the game global chronos factor. /// <br/> Override this callback to implement a different behaviour. /// </summary> public static Action<float> OnSetChronos = (c) => Time.timeScale = c; /// <summary> /// All values used as steps when increasing/decreasing the game chronos. /// </summary> public static float[] StepChronos = new float[] { .1f, .2f, .25f, .5f, .75f, 1f, 2f, 4f, 8f, 16f, 32f }; // ------------------------------------------- // Steps // ------------------------------------------- /// <summary> /// Increases the game time scale. /// </summary> public static void Increase() { int _index = Mathf.Min(GetChronosValueIndex() + 1, StepChronos.Length - 1); SetChronos(StepChronos[_index]); } /// <summary> /// Resets the game time scale to 1. /// </summary> public static void Reset() { SetChronos(1f); } /// <summary> /// Decreases the game time scale. /// </summary> public static void Decrease() { int _index = Mathf.Max(GetChronosValueIndex() - 1, 0); SetChronos(StepChronos[_index]); } // ------------------------------------------- // Utility // ------------------------------------------- private static void SetChronos(float _chronos) { OnSetChronos?.Invoke(_chronos); } private static int GetChronosValueIndex() { float _scale = Time.timeScale; float _nearest = Mathf.Abs(_scale - StepChronos[0]); for (int _i = 1; _i < StepChronos.Length; _i++) { float _value = StepChronos[_i]; float _difference = Mathf.Abs(_scale - _value); if (_difference > _nearest) return _i - 1; _nearest = _difference; } return StepChronos.Length - 1; } #endregion } }
using System.Collections.Generic; using Asset.Core.Repository.Library.Repositorys.HrModels; using Asset.Models.Library.EntityModels.HrModels; using Core.Repository.Library.Infrastucture; using System.Data.Entity; using System.Linq; using AssetSqlDatabase.Library.DatabaseContext; namespace Asset.Infrastucture.Library.Repositorys.Hrs { public class EmployeeRepository : Repository<Employee>, IEmployeeRepository { public EmployeeRepository(DbContext context) : base(context) { } public AssetDbContext AssetDbContext { get { return Context as AssetDbContext; } } public Employee GetEmployeeByFirstName(string firstName) { var employee = AssetDbContext.Employees.SingleOrDefault(e => e.FirstName == firstName); return employee; } public Employee GetEmployeeByLastName(string lastName) { var employee = AssetDbContext.Employees.SingleOrDefault(e => e.LastName == lastName); return employee; } public Employee GetEmployeeByEmail(string email) { var employee = AssetDbContext.Employees.SingleOrDefault(e => e.Email == email); return employee; } public Employee GetEmployeeByEmployeeCode(string code) { var employee = AssetDbContext.Employees.SingleOrDefault(e => e.Code == code); return employee; } public IEnumerable<Employee> EmployeesWithOrganizationBrnachDepartmentAndDdesignation() { var employee = AssetDbContext.Employees.Include(o => o.Organization).Include(b => b.Branch) .Include(d => d.Department).Include(ds => ds.Designation); return employee; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AuditInfoPropertyMap.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using CGI.Reflex.Core.Entities; using FluentNHibernate.Mapping; namespace CGI.Reflex.Core.Mappings { public class AuditInfoPropertyMap : BaseEntityMap<AuditInfoProperty> { public AuditInfoPropertyMap() { Map(x => x.PropertyName); Map(x => x.PropertyType); Map(x => x.OldValue); Map(x => x.NewValue); References(x => x.AuditInfo); } } }
using System; using MongoDB.Driver; namespace Braspag.Domain.Interfaces.Context { public interface IDataContext :IDisposable { MongoDatabase Context { get; } void RequestDone(); void RequestStart(); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SettingController : MonoBehaviour { public static SettingController settingController; public Sprite spriteButtonSelected, spriteButtonUnselected; [System.Serializable] public class Quality { public GameObject lowerQuality, higherQuality; public Text textQuality; public string[] stringQuality; public int indexQuality; } public Quality quality = new Quality(); [System.Serializable] public class TextureQuality { public GameObject lowQuality, mediumQuality, highQuality; } public TextureQuality textureQuality = new TextureQuality(); [System.Serializable] public class AntiAliasing { public GameObject offAntiAliasing, x2AntiAliasing, x4AntiAliasing, x8AntiAliasing; } public AntiAliasing antiAliasing = new AntiAliasing(); [System.Serializable] public class ShadowMode { public GameObject disableShadow, hardShadow, allShadow; } public ShadowMode shadowMode = new ShadowMode(); [System.Serializable] public class ShadowScale { public GameObject lowResolution, mediumResolution, highResolution, veryHighResolution; } public ShadowScale shadowScale = new ShadowScale(); [System.Serializable] public class CameraSensitivity { public Text textCameraSensitivity; public Slider cameraSensitivity; } public CameraSensitivity cameraSensitivity = new CameraSensitivity(); [System.Serializable] public class AudioVolume { public Text textSoundVolume, textMusicVolume; public Slider soundVolume, musicVolume; } public AudioVolume audioVolume = new AudioVolume(); public bool isMainMenu, isMain; private void Awake() { if (settingController == null) { settingController = this; } else if (settingController != this) { Destroy(gameObject); } } void Start() { } void Update() { QualityFunction(); TextureQualityFunction(); AntiAliasingFunction(); ShadowQualityFunction(); ShadowResolutionFunction(); cameraSensitivity.textCameraSensitivity.text = "" + Convert.ToInt32(cameraSensitivity.cameraSensitivity.value); audioVolume.textSoundVolume.text = "" + Convert.ToInt32(audioVolume.soundVolume.value); audioVolume.textMusicVolume.text = "" + Convert.ToInt32(audioVolume.musicVolume.value); } public void QualityFunction() { quality.textQuality.text = quality.stringQuality[quality.indexQuality]; if (quality.indexQuality <= 0) { quality.lowerQuality.SetActive(false); } else { quality.lowerQuality.SetActive(true); } if (quality.indexQuality >= 4) { quality.higherQuality.SetActive(false); } else { quality.higherQuality.SetActive(true); } } public void TextureQualityFunction() { if (QualitySettings.masterTextureLimit == 2) { ButtonSelectedFunction(textureQuality.lowQuality); ButtonUnselectedFunction(textureQuality.mediumQuality); ButtonUnselectedFunction(textureQuality.highQuality); } else if (QualitySettings.masterTextureLimit == 1) { ButtonUnselectedFunction(textureQuality.lowQuality); ButtonSelectedFunction(textureQuality.mediumQuality); ButtonUnselectedFunction(textureQuality.highQuality); } else if (QualitySettings.masterTextureLimit == 0) { ButtonUnselectedFunction(textureQuality.lowQuality); ButtonUnselectedFunction(textureQuality.mediumQuality); ButtonSelectedFunction(textureQuality.highQuality); } } public void AntiAliasingFunction() { if (QualitySettings.antiAliasing == 0) { ButtonSelectedFunction(antiAliasing.offAntiAliasing); ButtonUnselectedFunction(antiAliasing.x2AntiAliasing); ButtonUnselectedFunction(antiAliasing.x4AntiAliasing); ButtonUnselectedFunction(antiAliasing.x8AntiAliasing); } else if (QualitySettings.antiAliasing == 2) { ButtonUnselectedFunction(antiAliasing.offAntiAliasing); ButtonSelectedFunction(antiAliasing.x2AntiAliasing); ButtonUnselectedFunction(antiAliasing.x4AntiAliasing); ButtonUnselectedFunction(antiAliasing.x8AntiAliasing); } else if (QualitySettings.antiAliasing == 4) { ButtonUnselectedFunction(antiAliasing.offAntiAliasing); ButtonUnselectedFunction(antiAliasing.x2AntiAliasing); ButtonSelectedFunction(antiAliasing.x4AntiAliasing); ButtonUnselectedFunction(antiAliasing.x8AntiAliasing); } else if (QualitySettings.antiAliasing == 8) { ButtonUnselectedFunction(antiAliasing.offAntiAliasing); ButtonUnselectedFunction(antiAliasing.x2AntiAliasing); ButtonUnselectedFunction(antiAliasing.x4AntiAliasing); ButtonSelectedFunction(antiAliasing.x8AntiAliasing); } } public void ShadowQualityFunction() { if (QualitySettings.shadows == ShadowQuality.Disable) { ButtonSelectedFunction(shadowMode.disableShadow); ButtonUnselectedFunction(shadowMode.hardShadow); ButtonUnselectedFunction(shadowMode.allShadow); } else if (QualitySettings.shadows == ShadowQuality.HardOnly) { ButtonUnselectedFunction(shadowMode.disableShadow); ButtonSelectedFunction(shadowMode.hardShadow); ButtonUnselectedFunction(shadowMode.allShadow); } else if (QualitySettings.shadows == ShadowQuality.All) { ButtonUnselectedFunction(shadowMode.disableShadow); ButtonUnselectedFunction(shadowMode.hardShadow); ButtonSelectedFunction(shadowMode.allShadow); } } public void ShadowResolutionFunction() { if (QualitySettings.shadowResolution == ShadowResolution.Low) { ButtonSelectedFunction(shadowScale.lowResolution); ButtonUnselectedFunction(shadowScale.mediumResolution); ButtonUnselectedFunction(shadowScale.highResolution); ButtonUnselectedFunction(shadowScale.veryHighResolution); } else if (QualitySettings.shadowResolution == ShadowResolution.Medium) { ButtonUnselectedFunction(shadowScale.lowResolution); ButtonSelectedFunction(shadowScale.mediumResolution); ButtonUnselectedFunction(shadowScale.highResolution); ButtonUnselectedFunction(shadowScale.veryHighResolution); } else if (QualitySettings.shadowResolution == ShadowResolution.High) { ButtonUnselectedFunction(shadowScale.lowResolution); ButtonUnselectedFunction(shadowScale.mediumResolution); ButtonSelectedFunction(shadowScale.highResolution); ButtonUnselectedFunction(shadowScale.veryHighResolution); } else if (QualitySettings.shadowResolution == ShadowResolution.VeryHigh) { ButtonUnselectedFunction(shadowScale.lowResolution); ButtonUnselectedFunction(shadowScale.mediumResolution); ButtonUnselectedFunction(shadowScale.highResolution); ButtonSelectedFunction(shadowScale.veryHighResolution); } } public void TextureQualityLowFunction() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonSelectedFunction(textureQuality.lowQuality); ButtonUnselectedFunction(textureQuality.mediumQuality); ButtonUnselectedFunction(textureQuality.highQuality); quality.indexQuality = 5; QualitySettings.masterTextureLimit = 2; } public void TextureQualityMediumFunction() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonUnselectedFunction(textureQuality.lowQuality); ButtonSelectedFunction(textureQuality.mediumQuality); ButtonUnselectedFunction(textureQuality.highQuality); quality.indexQuality = 5; QualitySettings.masterTextureLimit = 1; } public void TextureQualityHighFunction() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonUnselectedFunction(textureQuality.lowQuality); ButtonUnselectedFunction(textureQuality.mediumQuality); ButtonSelectedFunction(textureQuality.highQuality); quality.indexQuality = 5; QualitySettings.masterTextureLimit = 0; } public void AntiAliasingOffFunction() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonSelectedFunction(antiAliasing.offAntiAliasing); ButtonUnselectedFunction(antiAliasing.x2AntiAliasing); ButtonUnselectedFunction(antiAliasing.x4AntiAliasing); ButtonUnselectedFunction(antiAliasing.x8AntiAliasing); quality.indexQuality = 5; QualitySettings.antiAliasing = 0; } public void AntiAliasingX2Function() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonUnselectedFunction(antiAliasing.offAntiAliasing); ButtonSelectedFunction(antiAliasing.x2AntiAliasing); ButtonUnselectedFunction(antiAliasing.x4AntiAliasing); ButtonUnselectedFunction(antiAliasing.x8AntiAliasing); quality.indexQuality = 5; QualitySettings.antiAliasing = 2; } public void AntiAliasingX4Function() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonUnselectedFunction(antiAliasing.offAntiAliasing); ButtonUnselectedFunction(antiAliasing.x2AntiAliasing); ButtonSelectedFunction(antiAliasing.x4AntiAliasing); ButtonUnselectedFunction(antiAliasing.x8AntiAliasing); quality.indexQuality = 5; QualitySettings.antiAliasing = 4; } public void AntiAliasingX8Function() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonUnselectedFunction(antiAliasing.offAntiAliasing); ButtonUnselectedFunction(antiAliasing.x2AntiAliasing); ButtonUnselectedFunction(antiAliasing.x4AntiAliasing); ButtonSelectedFunction(antiAliasing.x8AntiAliasing); quality.indexQuality = 5; QualitySettings.antiAliasing = 8; } public void ShadowQualityDisabledFunction() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonSelectedFunction(shadowMode.disableShadow); ButtonUnselectedFunction(shadowMode.hardShadow); ButtonUnselectedFunction(shadowMode.allShadow); quality.indexQuality = 5; QualitySettings.shadows = ShadowQuality.Disable; } public void ShadowQualityHardFunction() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonUnselectedFunction(shadowMode.disableShadow); ButtonSelectedFunction(shadowMode.hardShadow); ButtonUnselectedFunction(shadowMode.allShadow); quality.indexQuality = 5; QualitySettings.shadows = ShadowQuality.HardOnly; } public void ShadowQualityAllFunction() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonUnselectedFunction(shadowMode.disableShadow); ButtonUnselectedFunction(shadowMode.hardShadow); ButtonSelectedFunction(shadowMode.allShadow); quality.indexQuality = 5; QualitySettings.shadows = ShadowQuality.All; } public void ShadowResolutionLowFunction() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonSelectedFunction(shadowScale.lowResolution); ButtonUnselectedFunction(shadowScale.mediumResolution); ButtonUnselectedFunction(shadowScale.highResolution); ButtonUnselectedFunction(shadowScale.veryHighResolution); quality.indexQuality = 5; QualitySettings.shadowResolution = ShadowResolution.Low; } public void ShadowResolutionMediumFunction() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonUnselectedFunction(shadowScale.lowResolution); ButtonSelectedFunction(shadowScale.mediumResolution); ButtonUnselectedFunction(shadowScale.highResolution); ButtonUnselectedFunction(shadowScale.veryHighResolution); quality.indexQuality = 5; QualitySettings.shadowResolution = ShadowResolution.Medium; } public void ShadowResolutionHighFunction() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonUnselectedFunction(shadowScale.lowResolution); ButtonUnselectedFunction(shadowScale.mediumResolution); ButtonSelectedFunction(shadowScale.highResolution); ButtonUnselectedFunction(shadowScale.veryHighResolution); quality.indexQuality = 5; QualitySettings.shadowResolution = ShadowResolution.High; } public void ShadowResolutionVeryHighFunction() { if (isMainMenu == true) { ButtonSelectedAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonSelect); } ButtonUnselectedFunction(shadowScale.lowResolution); ButtonUnselectedFunction(shadowScale.mediumResolution); ButtonUnselectedFunction(shadowScale.highResolution); ButtonSelectedFunction(shadowScale.veryHighResolution); quality.indexQuality = 5; QualitySettings.shadowResolution = ShadowResolution.VeryHigh; } public void ButtonLowerQualityFunction() { if (isMainMenu == true) { ButtonClickAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonClick); } quality.indexQuality--; if (quality.indexQuality < 0) { quality.indexQuality = quality.stringQuality.Length - 1; } if (quality.indexQuality <= 4) { QualitySettings.SetQualityLevel(quality.indexQuality, true); } PlayerPrefs.SetInt("IndexQuality", quality.indexQuality); } public void ButtonHigherQualityFunction() { if (isMainMenu == true) { ButtonClickAudioFunction(); } else if (isMain == true) { GameController.gameController.AudioButtonFunction(GameController.gameController.audio.audioButtonClick); } quality.indexQuality++; if (quality.indexQuality == quality.stringQuality.Length - 1) { quality.indexQuality = 0; } if (quality.indexQuality <= 4) { QualitySettings.SetQualityLevel(quality.indexQuality, true); } PlayerPrefs.SetInt("IndexQuality", quality.indexQuality); } public void ButtonSelectedFunction(GameObject gameObject) { gameObject.GetComponent<Image>().sprite = spriteButtonSelected; gameObject.GetComponent<Image>().color = new Color32(255, 255, 255, 255); } public void ButtonSelectedAudioFunction() { MainMenuController.mainMenuController.mainMenu.audioButton.Stop(); MainMenuController.mainMenuController.mainMenu.audioButton.clip = MainMenuController.mainMenuController.mainMenu.audioButtonSelect; MainMenuController.mainMenuController.mainMenu.audioButton.Play(); } public void ButtonClickAudioFunction() { MainMenuController.mainMenuController.mainMenu.audioButton.Stop(); MainMenuController.mainMenuController.mainMenu.audioButton.clip = MainMenuController.mainMenuController.mainMenu.audioButtonClick; MainMenuController.mainMenuController.mainMenu.audioButton.Play(); } public void ButtonUnselectedFunction(GameObject gameObject) { gameObject.GetComponent<Image>().sprite = spriteButtonUnselected; gameObject.GetComponent<Image>().color = new Color32(200, 100, 50, 255); } }
 using System; using System.Linq; using BillingAPI.Models; using Microsoft.EntityFrameworkCore; namespace BillingAPI.DL.Data { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } public DbSet<Set> Sets { get; set; } public DbSet<ProductSet> ProductSets { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<ProductSet>().HasKey(a => new { a.ProductId, a.SetId }); foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys())) { relationship.DeleteBehavior = DeleteBehavior.Restrict; } base.OnModelCreating(modelBuilder); } } }
using System; using System.Collections.Generic; using System.Text; namespace CSharp.DesignPatterns.Singleton { public class XhellThread { private static XhellThread _instance; private string _name; private static object _lock = new object(); public XhellThread() { _name = $"{nameof(XhellThread)} Instance"; } public static XhellThread Instance { get { if(_instance == null) { lock (_lock) { if (_instance == null) _instance = new XhellThread(); } } return _instance; } } public string GetName() { return _name; } } }
/* * Copyright 2014 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Windows; using KaVE.VS.FeedbackGenerator.Utils; using NUnit.Framework; namespace KaVE.VS.FeedbackGenerator.Tests.Utils { [TestFixture] internal class ObjectToVisibilityConverterTest { [Test] public void ShouldConvertNullToHidden() { AssertConverts(null, Visibility.Collapsed); } [Test] public void ShouldConvertObjectToVisible() { AssertConverts(new object(), Visibility.Visible); } [Test] public void ShouldConvertNullableNullToHidden() { // ReSharper disable once RedundantCast AssertConverts((int?) null, Visibility.Collapsed); } [Test] public void ShouldConvertNullableValueToVisible() { AssertConverts((int?) 1, Visibility.Visible); } private static void AssertConverts(object value, Visibility exptectedResult) { var converter = new ObjectToVisibilityConverter(); var result = converter.Convert(value, null, null, null); Assert.AreEqual(exptectedResult, result); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FIUChat.Enums { public enum AuthenticateResult { Success = 10, Failure = 20, Unknown = 0 } }
using System; using System.Windows; using System.Windows.Controls; namespace DomaciRozpocet { /// <summary> /// Interaction logic for FilterWindow.xaml /// </summary> public partial class FilterWindow : Window { public FilterWindow() { InitializeComponent(); } /// <summary> /// Returns a predicate according to the chosen and entered values /// The predicate is used to filter records in ICollectionView /// </summary> public Predicate<object> FilterPredicate { get { switch (cbFilterSelection.SelectedIndex) { case 0: return item => ((Record)item).Amount > 0; case 1: return item => ((Record)item).Amount < 0; case 2: return item => ((Record)item).Person.ToLower() == this.Value.ToLower(); case 3: return item => ((Record)item).Reason.ToLower() == this.Value.ToLower(); case 4: if (DateFrom == null) return item => ((Record)item).Date <= DateTo; else if (DateTo == null) return item => ((Record)item).Date >= DateFrom; else return item => ((Record)item).Date >= DateFrom && ((Record)item).Date <= DateTo; case 5: return item => ((Record)item).Amount >= this.Amount || ((Record)item).Amount <= (-1 * this.Amount); case 6: return item => ((Record)item).Amount <= this.Amount && ((Record)item).Amount >= (-1 * this.Amount); } return item => true; } } /// <summary> /// Returns date from the 'from' DatePicker /// </summary> private Nullable<DateTime> DateFrom { get { return dpFrom.SelectedDate; } } /// <summary> /// Returns date from the 'to' DatePicker /// </summary> private Nullable<DateTime> DateTo { get { return dpTo.SelectedDate; } } /// <summary> /// Returns a decimal amount from the tbValue textbox /// </summary> private Nullable<decimal> Amount { get { try { return Decimal.Parse(tbValue.Text); } catch { return null; } } } /// <summary> /// Returns a string from the tbValue textbox /// </summary> private string Value { get { return (tbValue.Text).Trim(); } } /// <summary> /// Displays different UI elements based on the filter selection /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cbFilterSelection_SelectionChanged(object sender, SelectionChangedEventArgs e) { var selectedIndex = cbFilterSelection.SelectedIndex; if (selectedIndex == 2 || selectedIndex == 3 || selectedIndex == 5 || selectedIndex == 6) { tbValue.Visibility = Visibility.Visible; lblFrom.Visibility = Visibility.Hidden; lblTo.Visibility = Visibility.Hidden; dpFrom.Visibility = Visibility.Hidden; dpTo.Visibility = Visibility.Hidden; btnFilter.IsEnabled = true; } else if (selectedIndex == 4) { tbValue.Visibility = Visibility.Hidden; lblFrom.Visibility = Visibility.Visible; lblTo.Visibility = Visibility.Visible; dpFrom.Visibility = Visibility.Visible; dpTo.Visibility = Visibility.Visible; btnFilter.IsEnabled = true; } else { tbValue.Visibility = Visibility.Hidden; lblFrom.Visibility = Visibility.Hidden; lblTo.Visibility = Visibility.Hidden; dpFrom.Visibility = Visibility.Hidden; dpTo.Visibility = Visibility.Hidden; btnFilter.IsEnabled = true; } } /// <summary> /// Checks if the fields aren't empty, if not, closes the window /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnFilter_Click(object sender, RoutedEventArgs e) { bool success = false; if (cbFilterSelection.SelectedIndex == 2 || cbFilterSelection.SelectedIndex == 3) { if (Value == "") MessageBox.Show(this, "Prosím vyplňte pole"); else success = true; } else if (cbFilterSelection.SelectedIndex == 5 || cbFilterSelection.SelectedIndex == 6) { if (Amount == null) MessageBox.Show(this, "Prosím vyplňte pole"); else success = true; } else if (cbFilterSelection.SelectedIndex == 4) { if (DateFrom == null && DateTo == null) MessageBox.Show(this, "Prosím zadejte alespoň jedno datum"); else success = true; } else success = true; if (success) { this.DialogResult = true; this.Close(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StarRating : MonoBehaviour { private float _timePerStar = 0.3f; [SerializeField] private List<RectTransform> _stars; [SerializeField] private RectTransform _flare; void Start() { Setup(); } void Setup() { foreach (var star in _stars) { star.localScale = Vector3.zero; } _flare.localScale = Vector3.zero; } // Update is called once per frame public void ShowStarRating(int rating) { Setup(); StartCoroutine(ShowStars(rating)); } private IEnumerator ShowStars(int number) { yield return new WaitForSeconds(0.5f); for (var i = 0; i < number; i++) { var time = 0f; if (i == 2) { StartCoroutine(ShowFlare()); } while (time <= _timePerStar) { _stars[i].localScale = Vector3.Slerp(Vector3.zero, Vector3.one, time/_timePerStar); time += Time.deltaTime; yield return null; } _stars[i].localScale = Vector3.one; } } private IEnumerator ShowFlare() { yield return new WaitForSeconds(0.1f); var time = 0f; var timeToShow = _timePerStar * .6f; while (time <= timeToShow) { _flare.localScale = Vector3.Slerp(Vector3.zero, Vector3.one, time / timeToShow); time += Time.deltaTime; yield return null; } _flare.localScale = Vector3.one; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LiongStudio.ComputerVision.Tdd; using MathWorks.MATLAB.NET.Arrays; namespace LiongStudio.ComputerVision.Tdd { public class MatlabDelegate : IDisposable { private bool _IsDisposed = false; private Tdd _Tdd = new Tdd(); public MatlabDelegate() { } public void ExtractFisherVector(string pcaPath1, string pcaPath2, string gmmPath1, string gmmPath2, string inputDir, string inputFileNameNoEx1, string inputFileNameNoEx2, string outputDir) { _Tdd.ExtractFisherVector(pcaPath1, pcaPath2, gmmPath1, gmmPath2, inputDir, inputFileNameNoEx1, inputFileNameNoEx2, outputDir); } public void ExtractTddFeature(string envPath, string inputDir, string inputFileNameNoEx, string outputDir, int scale, int gpuId) { _Tdd.ExtractTddFeature(envPath, inputDir, inputFileNameNoEx, outputDir, scale, gpuId); } public void GeneratePcaGmm(List<string> inputFilePaths, string outputFileName, string pcaOutputFileDir, string gmmOutputFileDir) { var count = inputFilePaths.Count; MWCellArray carray = new MWCellArray(count, 1); for (int i = 0; i < count; ++i) carray[i + 1] = inputFilePaths[i]; _Tdd.GeneratePca(carray, outputFileName, pcaOutputFileDir); _Tdd.GenerateGmm(carray, pcaOutputFileDir + outputFileName + ".mat", outputFileName, gmmOutputFileDir); } public int GetVideoFrameCount(string vidPath) { return (_Tdd.GetVideoFrameCount(vidPath) as MathWorks.MATLAB.NET.Arrays.MWNumericArray).ToScalarInteger(); } public void Dispose() { if (!_IsDisposed) _Tdd.Dispose(); } } }
using UnityEngine; using System.Collections; public class PageController : MonoBehaviour { public GameObject FirstPage; public AudioClip OnChageMusic; private AudioSource asource; void Awake(){ if (FirstPage && FirstPage != gameObject) { gameObject.SetActive (false); } asource = GameObject.FindGameObjectWithTag ("GameScript").GetComponent<AudioSource>(); } void OnEnable(){ if (OnChageMusic) { if(asource.clip != OnChageMusic){ asource.clip = OnChageMusic; asource.Play(); } } } void OnDisable(){ } } public class pageChanger{ public static void ChangePage(GameObject currentPage, GameObject nextPage){ currentPage.SetActive(false); nextPage.SetActive(true); } }
using System; using Dapper.FluentMap.Mapping; using Domain.Entities; namespace Common.Mappings { public class WeatherMap : EntityMap<Weather> { public WeatherMap() { Map(u => u.MinimumTemperature).ToColumn("minimum_temperature"); Map(u => u.MaximumTemperature).ToColumn("maximum_temperature"); Map(u => u.ConditionCode).ToColumn("condition_code"); Map(u => u.IconURL).ToColumn("icon_url"); } } }
using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using PlayGen.Unity.Utilities.Localization; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; public class FloatingPlatform : MovingObject { [SyncVar] public bool CanPickUp = true; [SyncVar] public bool OnWater; [SyncVar] public string PickupValue; private List<string> _operations = new List<string>(); public WaterBehaviour Water; private Player _playerOnPlatform; private MeshRenderer _mesh; private LevelManager _levelManager; private Text _pickupText; public Vector3 StartPositionOnline; public Vector3 StartPositionOffline; public override void Start() { base.Start(); MovementSpeed = 0f; CanFloat = true; PlayerCanInteract = false; PlayerCanHit = true; CanRespawn = true; CanMove = true; _mesh = transform.GetChild(0).GetComponent<MeshRenderer>(); if (!SP_Manager.Instance.IsSinglePlayer()) { // Set the respawn position to be further along the path so that the paddlers must help RespawnLocation.Add(StartPositionOnline); RespawnLocation.Add(new Vector3(StartPositionOnline.x * -1, StartPositionOnline.y, StartPositionOnline.z)); } else { // Set the respawn position to be closer to the middle to ensure it can be seen in portrait mode RespawnLocation.Add(StartPositionOffline); RespawnLocation.Add(new Vector3(StartPositionOffline.x * -1, StartPositionOffline.y, StartPositionOffline.z)); } _pickupText = GetComponentInChildren<Text>(); PickupValue = ""; _operations = new List<string>(); } public override void ResetObject(Vector3 newPosition) { base.ResetObject(newPosition); CanFloat = true; MovementSpeed = 0f; PickupValue = ""; _operations = new List<string>(); } public override void Respawn() { base.Respawn(); _playerOnPlatform = null; CanMove = true; OnWater = false; if (isServer) { #if PSL_ENABLED PSL_LRSManager.Instance.NewAttempt(); #endif } } public override void Respawned() { base.Respawned(); CanPickUp = true; } public void PlaceOnWater(Player player, Vector3 pos) { _playerOnPlatform = player; transform.position = pos; OnWater = true; } void FixedUpdate() { if (_levelManager == null) { _levelManager = GameObject.Find("LevelManager").GetComponent<LevelManager>(); } if (_playerOnPlatform != null && (isServer || SP_Manager.Instance.IsSinglePlayer()) && CanMove) { // On Water GetComponent<BoxCollider>().enabled = true; _playerOnPlatform.GetComponent<Rigidbody>().useGravity = false; _playerOnPlatform.transform.position = new Vector3(transform.position.x, _playerOnPlatform.transform.position.y, transform.position.z); var player = _playerOnPlatform.GetComponent<Player>(); player.SyncForceMove( new Vector3(transform.position.x, _playerOnPlatform.transform.position.y, transform.position.z), _playerOnPlatform.transform.eulerAngles); Water.TouchedWater(this); } else { // Not on water GetComponent<BoxCollider>().enabled = false; } var players = GameObject.FindGameObjectsWithTag("Player"); CanPickUp = !players.Any(p => p.GetComponent<Player>().HoldingPlatform); _mesh.enabled = CanPickUp; if (_levelManager != null) { _levelManager.Current = PickupValue; } if (isServer && transform.position.z > 18f) { // out of bounds ResetPositions(); } } void OnTriggerEnter(Collider other) { // VICTORY CONDITION if (_playerOnPlatform == null) { return; } if (other.gameObject.tag == "Obstacle") { ResetPositions(); } else if (other.gameObject.tag == "Treasure") { #if PSL_ENABLED PSL_LRSManager.Instance.ChestReached(); #endif _playerOnPlatform.GetComponent<Player>().ReachedChest(); CanMove = false; StartCoroutine(GoalReached(other.gameObject)); } else if (other.gameObject.tag == "Collectible") { other.GetComponent<BoxCollider>().enabled = false; _playerOnPlatform.GetComponent<Player>().GotCollectible(); var operation = other.gameObject.GetComponent<MathsCollectible>().Operation; if (_operations.Count == 0) { if (operation.Contains("+")) { operation = operation.Substring(1, operation.Length - 1); PickupValue = operation; } else if (operation.Contains("/") || operation.Contains("x")) { operation = "0"; PickupValue = operation; } else { PickupValue = operation; } } else { PickupValue = _levelManager.Evaluate(PickupValue + operation).ToString(); } _operations.Add(operation); if (isServer || SP_Manager.Instance.IsSinglePlayer()) { GameObject.Find("AudioManager").GetComponent<NetworkAudioManager>().Play("Pickup"); if (isServer) { other.GetComponent<MathsCollectible>().RpcPlayCollectedAnimation(); } else if (SP_Manager.Instance.IsSinglePlayer()) { other.GetComponent<MathsCollectible>().ClientPlayCollectedAnimation(); } } } } public IEnumerator GoalReached(GameObject other) { var levelManager = GameObject.Find("LevelManager").GetComponent<LevelManager>(); if (levelManager.MathsVersion) { if (isServer) { RpcShowTotal(PickupValue == levelManager.Target); } else if (SP_Manager.Instance.IsSinglePlayer()) { ClientShowTotal(PickupValue == levelManager.Target); } yield return new WaitForSeconds(levelManager.TotalUI.AnimLength()); } var player = _playerOnPlatform.GetComponent<Player>(); player.ReachedChest(PickupValue == levelManager.Target); if (PickupValue == levelManager.Target || !levelManager.MathsVersion) { if (isServer || SP_Manager.Instance.IsSinglePlayer()) { player.SetGoalReached(false); player.ControlledByServer = true; player.SyncForceMove(other.transform.Find("VictoryLocation").position, Vector3.zero); } // Get the name of the player who reached the chest var playerName = _playerOnPlatform.SyncNickName; _playerOnPlatform = null; // Notify the players that a reward has been reached if (isServer) { player.RpcGoalReached(playerName); } else if (SP_Manager.Instance.IsSinglePlayer()) { player.ClientGoalReached(playerName); } CanFloat = false; Water.TouchedWater(this); MovePaddlersToStart(); } else { ResetPositions(); } if (isServer && levelManager.MathsVersion && !SP_Manager.Instance.IsSinglePlayer()) { RpcDisableTotal(); } else if (SP_Manager.Instance.IsSinglePlayer() && levelManager.MathsVersion) { ClientDisableTotal(); } } [ServerAccess] private void ResetPositions() { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } // Behave as if hit object var player = _playerOnPlatform.GetComponent<Player>(); _playerOnPlatform = null; player.GetComponent<BoxCollider>().enabled = false; player.FellInWater(); player.Respawn(); player.OnPlatform = false; CanFloat = false; CanMove = false; player.GetComponent<Rigidbody>().useGravity = true; Water.TouchedWater(this); if (SP_Manager.Instance.IsSinglePlayer()) { MovePaddlersToStart(); } if (isServer || SP_Manager.Instance.IsSinglePlayer()) { GameObject.Find("SpawnedObjects").GetComponent<CollectibleGeneration>().ResetColliders(); } } [ServerAccess] private void MovePaddlersToStart() { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } var players = GameObject.FindGameObjectsWithTag("Player") .Where(p => p.GetComponent<Player>().PlayerRole == Player.Role.Paddler); foreach (var player in players) { var p = player.GetComponent<Player>(); p.MoveTo(p.RespawnLocation[0]); } } [ClientRpc] private void RpcShowTotal (bool victory) { ClientShowTotal(victory); } [ClientAccess] private void ClientShowTotal(bool victory) { var method = MethodBase.GetCurrentMethod(); var attr = (ClientAccess)method.GetCustomAttributes(typeof(ClientAccess), true)[0]; if (!attr.HasAccess) { return; } var levelManager = GameObject.Find("LevelManager").GetComponent<LevelManager>(); levelManager.TotalUI.GetComponent<RectTransform>().localScale = Vector3.zero; levelManager.TotalUI.gameObject.SetActive(true); levelManager.TotalUI.Show(Localization.Get("UI_GAME_TOTAL"), PickupValue, victory); if (victory) { AudioManager.Instance.Play("Victory"); } else { AudioManager.Instance.Play("Failure"); } } [ClientRpc] private void RpcDisableTotal() { ClientDisableTotal(); } [ClientAccess] private void ClientDisableTotal() { var method = MethodBase.GetCurrentMethod(); var attr = (ClientAccess)method.GetCustomAttributes(typeof(ClientAccess), true)[0]; if (!attr.HasAccess) { return; } var levelManager = GameObject.Find("LevelManager").GetComponent<LevelManager>(); levelManager.TotalUI.gameObject.SetActive(false); } public bool InRange(GameObject other) { if (_playerOnPlatform != null) { // Player cannot interact return false; } var distance = Vector3.Distance(other.transform.position, transform.position); return distance < 1.5f; } public bool CanBePlacedInWater() { // Get Start Point var start = GameObject.Find("PlatformStartPoint"); return Vector3.Distance(start.transform.position, transform.position) < 1.0f; } public bool CanBePlacedOnLand() { var leftPlacement = GameObject.FindWithTag("PlatformPlaceLeft"); var rightPlacement = GameObject.FindWithTag("PlatformPlaceRight"); return Vector3.Distance(leftPlacement.transform.position, transform.position) < 1f || Vector3.Distance(rightPlacement.transform.position, transform.position) < 1f; } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Tookan.NET.Core; using Tookan.NET.Http; namespace Tookan.NET.Clients { internal class TeamsClient : ApiClient, ITeamsClient { public async Task<IEnumerable<Team>> GetTeamsAsync() { var uri = new Uri("/view_team", UriKind.Relative); var request = new {Connection.AccessToken}; const string type = "application/json"; var team = await Connection.Post<List<Team>>(uri, request, type, type); return team.Body; } public TeamsClient(IApiConnection apiConnection) : base(apiConnection) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class FirePickup : MonoBehaviour { public GameObject itemImage; public GameObject fire; private FireInventory inventory; // Start is called before the first frame update //void Start() //{ // inventory = GameObject.FindGameObjectWithTag("Player").GetComponent<FireInventory>(); //} private void Awake() { inventory = GameObject.FindGameObjectWithTag("Player").GetComponent<FireInventory>(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { for (int i = 0; i < inventory.slots.Length; i++) { if (!inventory.isFull[i]) { inventory.isFull[i] = true; inventory.fires[i] = fire; //the fire object is now connected to the icon inventory.essenceTexts[i].GetComponent<Text>().text = fire.GetComponent<FireFlyResources>().xpPerSecond.ToString(); LevelManager.essenceText[i] = inventory.essenceTexts[i].GetComponent<Text>().text; LevelManager.fires[i] = fire; LevelManager.fireIcons[i] = itemImage; Instantiate(itemImage, inventory.slots[i].transform, false); FindObjectOfType<AudioManager>().PickupFireSound(); Destroy(this.gameObject); break; } } } } }
using System; using System.Collections.Generic; using System.Text; namespace JsonParseLib.Attributes { public class JsonRenameFieldAttribute : Attribute { public string Field { get; set; } public JsonRenameFieldAttribute(string name) { Field = name; } } }
using CheckMySymptoms.Flow.ScreenSettings.Views; using CheckMySymptoms.Forms.View; namespace CheckMySymptoms.Flow.Requests { //[JsonConverter(typeof(RequestConverter))] abstract public class RequestBase { public CommandButtonRequest CommandButtonRequest { get; set; } abstract public ViewType ViewType { get; set; } abstract public ViewBase View { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using PayRoll.BLL; namespace PayRoll.UnitTest.BLL { [TestFixture] public class ChangeUnaffiliationTransactionTest: SetUpInmemoryDb { [Test] public void ExecuteTest() { int empId = 33; int memberId = 98; double dues = 98.9; database.DeleteEmployee(empId); database.RemoveUnionMember(memberId); AddSalariedEmployee addSalEmp = new AddSalariedEmployee(empId, "Masa", "Faav Street", 5000, database); addSalEmp.Execute(); ChangeAffiliationTransaction changeMemberTrans = new ChangeMemberTransaction(empId, memberId, dues, database); changeMemberTrans.Execute(); Employee empAff = database.GetEmployee(empId); Assert.IsNotNull(empAff); Assert.IsTrue(empAff.Affiliation is UnionAffiliation); ChangeAffiliationTransaction changeAffTrans = new ChangeUnaffiliatedTransaction(empId, database); changeAffTrans.Execute(); Employee empNoAff = database.GetEmployee(empId); Assert.IsNotNull(empNoAff); Assert.IsTrue(empNoAff.Affiliation is NoAffiliation); NoAffiliation ua = empNoAff.Affiliation as NoAffiliation; Assert.IsNotNull(ua); Employee member = database.GetUnionMember(memberId); Assert.IsNull(member); } } }
using System; namespace JimBobBennett.JimLib { [AttributeUsage(AttributeTargets.All, Inherited = true)] public class PreserveAttribute : Attribute { public bool Conditional { get; set; } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("FriendlyDisplay")] public class FriendlyDisplay : MonoBehaviour { public FriendlyDisplay(IntPtr address) : this(address, "FriendlyDisplay") { } public FriendlyDisplay(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public void DisableOtherModeStuff() { base.method_8("DisableOtherModeStuff", Array.Empty<object>()); } public static FriendlyDisplay Get() { return MonoClass.smethod_15<FriendlyDisplay>(TritonHs.MainAssemblyPath, "", "FriendlyDisplay", "Get", Array.Empty<object>()); } public void OnDestroy() { base.method_8("OnDestroy", Array.Empty<object>()); } public void OnNetCacheReady() { base.method_8("OnNetCacheReady", Array.Empty<object>()); } public void Unload() { base.method_8("Unload", Array.Empty<object>()); } public DeckPickerTrayDisplay m_deckPickerTray { get { return base.method_3<DeckPickerTrayDisplay>("m_deckPickerTray"); } } public GameObject m_deckPickerTrayContainer { get { return base.method_3<GameObject>("m_deckPickerTrayContainer"); } } } }
using System; using System.Data; using System.Collections.Generic; using System.Text; using Npgsql; using NpgsqlTypes; using QTHT.DataAccess; namespace QTHT.BusinesLogic { /// <summary> /// Mô tả thông tin cho bảng PhongBan /// Cung cấp các hàm xử lý, thao tác với bảng PhongBan /// Người tạo (C): /// Ngày khởi tạo: 14/10/2014 /// </summary> public class phongbanBL { private phongban objphongbanDA = new phongban(); public phongbanBL() { objphongbanDA = new phongban(); } #region Public Method /// <summary> /// Lấy toàn bộ dữ liệu từ bảng PhongBan /// </summary> /// <returns>DataTable</returns> public DataTable GetAll() { return objphongbanDA.GetAll(); } public DataTable GetAllPhongBanvsDonVi() { return objphongbanDA.GetAllPhongBanvsDonVi(); } /// <summary> /// Hàm lấy PhongBan theo mã /// </summary> /// <returns>Trả về objPhongBan </returns> public phongban GetByID(string strIDPhongBan) { return objphongbanDA.GetByID(strIDPhongBan); } /// <summary> /// Thêm mới dữ liệu vào bảng: PhongBan /// </summary> /// <param name="obj">objPhongBan</param> /// <returns>Trả về trắng: Thêm mới thành công; Trả về khác trắng: Thêm mới không thành công</returns> public string Insert(phongban objPhongBan) { return objphongbanDA.Insert(objPhongBan); } /// <summary> /// Cập nhật dữ liệu vào bảng: PhongBan /// </summary> /// <param name="obj">objPhongBan</param> /// <returns>Trả về trắng: Cập nhật thành công; Trả về khác trắng: Cập nhật không thành công</returns> public string Update(phongban objPhongBan) { return objphongbanDA.Update(objPhongBan); } /// <summary> /// Xóa dữ liệu từ bảng PhongBan /// </summary> /// <returns>Trả về trắng: xóa thành công; Trả về khác trắng: xóa không thành công</returns> public string Delete(string strIDPhongBan) { return objphongbanDA.Delete(strIDPhongBan); } /// <summary> /// Hàm kiểm tra trùng tên phòng ban /// </summary> /// <param name="sid">Mã phòng ban</param> /// <param name="sten">Tên phòng ban</param> /// <returns>bool: False-Không tồn tại;True-Có tồn tại</returns> public bool CheckExit(string sidphongban, string stenphongban) { return objphongbanDA.CheckExit(sidphongban, stenphongban); } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace Liddup.Services { internal interface IDeezerApi { } }
using System.Collections; using System.Collections.Generic; using Es.InkPainter; using Es.InkPainter.Sample; using UnityEngine; using UnityEngine.UI; public class BrushSizeSetter : MonoBehaviour { [SerializeField] private MousePainter painter; [SerializeField] private Slider brushScaleSlider; [SerializeField] private float defaultScale = 0.1f; private Brush playerBrush; private void Start() { playerBrush = painter.brush; playerBrush.Scale = defaultScale; } public void OnDrop() { playerBrush.Scale = brushScaleSlider.value; } }
// <copyright file="CryptoConnection.cs" company="David Eiwen"> // Copyright (c) David Eiwen. All rights reserved. // </copyright> namespace IndiePortable.Communication.Core.Devices.Connections.Decorators { using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using IndiePortable.Communication.Core.Devices; public class CryptoConnection<TAddress> : ConnectionBase<byte[], TAddress> { private readonly ConnectionBase<byte[], TAddress> decoratedConnection; private readonly Crypter crypter; public CryptoConnection(ConnectionBase<byte[], TAddress> decoratedConnection, Crypter crypter) { this.decoratedConnection = decoratedConnection ?? throw new ArgumentNullException(nameof(decoratedConnection)); this.crypter = crypter ?? throw new ArgumentNullException(nameof(crypter)); this.decoratedConnection.MessageReceived += (s, e) => { using (var str = new MemoryStream(e.ReceivedMessage)) { // type var type = (CryptoMessageType)str.ReadByte(); // aes key length // decrypt message var decrypted = this.crypter.Decrypt(e.ReceivedMessage); this.OnMessageReceived(decrypted); } }; } /// <summary> /// Finalizes an instance of the <see cref="CryptoConnection{TAddress}"/> class. /// </summary> ~CryptoConnection() { this.Dispose(false); } public override TAddress RemoteAddress => throw new NotImplementedException(); protected byte[] Encrypt(byte[] message) { // TODO: encrypt message throw new NotImplementedException(); } protected override void ActivateOverride() { if (this.IsActivated) { throw new InvalidOperationException(); } this.decoratedConnection.Activate(); // TODO: establish encryption } protected override void SendOverride(byte[] message) { if (!this.IsActivated) { throw new InvalidOperationException(); } this.decoratedConnection.Send( this.Encrypt(message ?? throw new ArgumentNullException(nameof(message)))); } protected override async Task SendAsyncOverride(byte[] message) { if (!this.IsActivated) { throw new InvalidOperationException(); } await this.decoratedConnection.SendAsync( this.Encrypt(message ?? throw new ArgumentNullException(nameof(message)))); } protected override void DisconnectOverride() { if (!this.IsActivated) { throw new InvalidOperationException(); } this.decoratedConnection.Disconnect(); } protected override async Task DisconnectAsyncOverride() { if (!this.IsActivated) { throw new InvalidOperationException(); } await this.decoratedConnection.DisconnectAsync(); } protected override void DisposeUnmanaged() { this.decoratedConnection.Dispose(); base.DisposeUnmanaged(); } private enum CryptoMessageType : byte { StartSession = 0b00_00_00_01, Message = 0b00_00_00_10 } } }