Datasets:

blob_id
large_stringlengths
40
40
language
large_stringclasses
1 value
repo_name
large_stringlengths
5
119
path
large_stringlengths
4
271
score
float64
2.52
4.84
int_score
int64
3
5
text
stringlengths
26
4.09M
a878ad63b895ec4fb91526b1425ded55a68fe541
C#
Someone999/InfoReader
/InfoReader/NewExpressionParser/Nodes/OperatorExpressionNode.cs
3.296875
3
using System; using System.ComponentModel; using System.Linq; namespace InfoReaderPlugin.NewExpressionParser.Nodes { public class OperatorExpressionNode : ExpressionNode { void CheckValueNode(params ValueExpressionNode[] nodes) { if (nodes.Any(node => node is null || node.Value is null)) throw new ArgumentNullException(); } public static int GetPriority(string op) { switch (op) { case "(": case ")": return 5; case "!": return 4; case "*": case "/": return 3; case "+": case "-": return 2; case "==": case ">=": case "<=": case ">": case "<": case "!=": return 1; case "&&": case "||": return 0; default: throw new ArgumentException($"Invalid operator {(string.IsNullOrEmpty(op) ? "(null or empty)" : op)}.");//Incorrect Operator. } } public OperatorExpressionNode(object objNode) : base(objNode) { Value = objNode; } public override ExpressionNodeType NodeType => ExpressionNodeType.Operator; int _priority = -1; public int Priority => _priority == -1 ? _priority = GetPriority(Value as string ?? throw new InvalidCastException()) : _priority; public ValueExpressionNode Calculate(ValueExpressionNode left, ValueExpressionNode right) { if (Value is string s) { switch (s) { case "+": return Add((NumberExpressionNode)left, (NumberExpressionNode)right); case "-": return Sub((NumberExpressionNode)left, (NumberExpressionNode)right); case "*": return Mul((NumberExpressionNode)left, (NumberExpressionNode)right); case "/": return Div((NumberExpressionNode)left, (NumberExpressionNode)right); case ">=": return GreaterOrEquals((NumberExpressionNode)left, (NumberExpressionNode)right); case "<=": return LessOrEquals((NumberExpressionNode)left, (NumberExpressionNode)right); case ">": return Greater((NumberExpressionNode)left, (NumberExpressionNode)right); case "<": return Less((NumberExpressionNode)left, (NumberExpressionNode)right); case "==": return Equals(left, right); case "!=": return NotEquals(left, right); case "&&": return BoolAnd((BoolExpressionNode)left, (BoolExpressionNode)right); case "||": return BoolOr((BoolExpressionNode)left, (BoolExpressionNode)right); case "!": return Not((BoolExpressionNode)right); default: throw new InvalidOperationException(); } } throw new InvalidOperationException(); } NumberExpressionNode Add(NumberExpressionNode a, NumberExpressionNode b) { CheckValueNode(a, b); return new NumberExpressionNode((double)a.Value + (double)b.Value); } NumberExpressionNode Sub(NumberExpressionNode a, NumberExpressionNode b) { CheckValueNode(a, b); return new NumberExpressionNode(-(double)a.Value + (double)b.Value); } NumberExpressionNode Mul(NumberExpressionNode a, NumberExpressionNode b) { CheckValueNode(a, b); return new NumberExpressionNode((double)a.Value * (double)b.Value); } NumberExpressionNode Div(NumberExpressionNode a, NumberExpressionNode b) { CheckValueNode(a, b); return new NumberExpressionNode((double)a.Value / (double)b.Value); } BoolExpressionNode Equals(ValueExpressionNode a, ValueExpressionNode b) { return new BoolExpressionNode(a.Equals(b)); } BoolExpressionNode NotEquals(ValueExpressionNode a, ValueExpressionNode b) { return new BoolExpressionNode(!a.Equals(b)); } BoolExpressionNode BoolAnd(BoolExpressionNode a, BoolExpressionNode b) { CheckValueNode(a, b); return new BoolExpressionNode((bool)a.Value && (bool)b.Value); } BoolExpressionNode BoolOr(BoolExpressionNode a, BoolExpressionNode b) { CheckValueNode(a, b); return new BoolExpressionNode((bool)a.Value || (bool)b.Value); } BoolExpressionNode Greater(NumberExpressionNode a, NumberExpressionNode b) { CheckValueNode(a, b); return new BoolExpressionNode((double)a.Value > (double)b.Value); } BoolExpressionNode Less(NumberExpressionNode a, NumberExpressionNode b) { CheckValueNode(a, b); return new BoolExpressionNode((double)a.Value < (double)b.Value); } BoolExpressionNode GreaterOrEquals(NumberExpressionNode a, NumberExpressionNode b) { CheckValueNode(a, b); return new BoolExpressionNode((double)a.Value >= (double)b.Value); } BoolExpressionNode LessOrEquals(NumberExpressionNode a, NumberExpressionNode b) { CheckValueNode(a, b); return new BoolExpressionNode((double)a.Value <= (double)b.Value); } BoolExpressionNode Not(BoolExpressionNode right) { CheckValueNode(right); return new BoolExpressionNode(!(bool)right.Value); } } }
025334fe849074b2a49cfe337e55f60c3e849dcf
C#
catSirup/TheLantern
/Assets/Scripts/Object/Switch.cs
2.609375
3
using UnityEngine; using System.Collections; public class Switch : MonoBehaviour { public Sprite s_SwitchOff; public Sprite s_SwitchOn; private bool curState; private SpriteRenderer spriteRenderer; public void Init() { curState = false; spriteRenderer = gameObject.GetComponent<SpriteRenderer>(); } public void ActiveSwitch() { switch (curState) { case true: spriteRenderer.sprite = s_SwitchOn; break; case false: spriteRenderer.sprite = s_SwitchOff; break; } } public bool switchState { get { return this.curState; } set { this.curState = value; } } void OnTriggerEnter2D(Collider2D col) { if (col.name == "Box") { if(gameObject.CompareTag("Ground")) { this.curState = true; } } } void OnTriggerExit2D(Collider2D col) { if (col.name == "Box") { if (gameObject.CompareTag("Ground")) { this.curState = false; } } } void OnTriggerStay2D(Collider2D col) { // 스위치 if (col.CompareTag("Player")) { if (Input.GetKeyDown(KeyCode.E)) { this.curState = !this.curState; } } } }
cbf6891a4ed372bcc505f447b1637d5b3e1b97c0
C#
PengChen01/CodeAnalyseProject
/ColorProcess.cs
3.296875
3
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace Product { class ColorProcess { /// <summary> /// 返回指定深浅的一种随机颜色 /// </summary> /// <param name="index">颜色的中心值</param> /// <param name="radius">变化的幅度</param> /// <returns></returns> public static Color getRandColor(byte index,byte radius) { Random rand = new Random(); int[] rgb = new int[3]; int maxrgbindex =rand.Next(3); rgb[maxrgbindex]=255; int secrgbindex =rand.Next(2); int boolindex = getroundnumber(3,maxrgbindex,secrgbindex+1); rgb[boolindex]=rand.Next(2)*255; int minrgbindex = getroundnumber(3,maxrgbindex,getroundnumber(2,secrgbindex,1)+1); rgb[minrgbindex]=0; //调用参数信息 radius = (byte)Math.Abs(radius); if (radius>index) { radius = index; } rgb[minrgbindex] = (byte)(index + rand.Next(-1 * radius, radius)); if (rgb[boolindex]==0) { rgb[boolindex] = (byte)(index + rand.Next(-1 * radius, radius)); } Color color = Color.FromArgb(rgb[0], rgb[1], rgb[2]); return color; } /// <summary> /// 将数N回归到0~N-1之间 /// </summary> /// <param name="N"></param> /// <param name="index"></param> /// <param name="offset"></param> /// <returns></returns> private static int getroundnumber(int N,int index,int offset) { return (index + offset) % N; } } }
facdd350e745ed06072959cbf601619193f6ca17
C#
lucasgmagalhaes/Windows-Forms
/PUC/3º período/Leitor_Base_TI/Leitor_Base_TI/Form1.cs
2.53125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace Leitor_Base_TI { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Lista Processes; private void Form1_Load(object sender, EventArgs e) { listallprocess.MultiSelect = false; listallprocess.FullRowSelect = true; listallprocess.Columns.Add("colPID", "PID", 70); listallprocess.Columns.Add("colname", "Nome", 160); listallprocess.Columns.Add("colprio", "Prioridade", 100); listallprocess.Columns.Add("coltempo", "Tempo de execução", 100); listallprocess.Columns.Add("colstatus", "Status", 90); listallprocess.Columns.Add("colprog", "Progresso", 120); listfinished.MultiSelect = false; listfinished.FullRowSelect = true; listfinished.Columns.Add("colPID", "PID", 70); listfinished.Columns.Add("colname", "Nome", 160); listfinished.Columns.Add("colprio", "Prioridade", 100); listfinished.Columns.Add("coltempo", "Tempo de execução", 100); listfinished.Columns.Add("colstatus", "Status", 90); listfinished.Columns.Add("colprog", "Progresso", 120); } private void btncarregar_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Multiselect = false; if (open.ShowDialog() == DialogResult.OK) { if (open.FileName.EndsWith("txt")) { using (StreamReader read = new StreamReader(open.FileName)) { string line; while ((line = read.ReadLine()) != null) { string[] splt = line.Split(';'); Processo toadd = new Processo(int.Parse(splt[0]), splt[1], int.Parse(splt[2]), int.Parse(splt[3])); Processes.Inserir(toadd); ListViewItem item = new ListViewItem(); item.Text = toadd.Pid.ToString(); item.SubItems.Add(toadd.Name); item.SubItems.Add(toadd.Prio.ToString()); item.SubItems.Add(toadd.Tempo_execucao.ToString()); item.SubItems.Add("Parado"); item.SubItems.Add("0"); listallprocess.Items.Add(item); } read.Close(); } } } } } }
224c834c303e58a027614b0864985f42efa8710a
C#
xexuxjy/xexuxjy-xna-games
/GladiusUnity2021/ModelImporter/Assets/Editor/BlockEncoder.cs
2.546875
3
// https://github.com/Nominom/BCnEncoder.NET/blob/master/BCnEnc.Net/Encoder/Bc1BlockEncoder.cs using BCnEncoder.Encoder; using BCnEncoder.Shared; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace GCTextureTools { public static class BlockEncoder { public static class Bc1BlockEncoderSlow { public const int MaxTries = 9999; public const float ErrorThreshold = 0.01f; public static Vector4 CalculateMean(Vector4[] colors) { float r = 0; float g = 0; float b = 0; float a = 0; for (var i = 0; i < colors.Length; i++) { r += colors[i].X; g += colors[i].Y; b += colors[i].Z; a += colors[i].W; } return new Vector4( r / colors.Length, g / colors.Length, b / colors.Length, a / colors.Length ); } static Matrix4x4 CalculateCovariance(Vector4[] values, out Vector4 mean) { mean = CalculateMean(values); for (var i = 0; i < values.Length; i++) { values[i] -= mean; } //4x4 matrix var mat = new Matrix4x4(); for (var i = 0; i < values.Length; i++) { mat.M11 += values[i].X * values[i].X; mat.M12 += values[i].X * values[i].Y; mat.M13 += values[i].X * values[i].Z; mat.M14 += values[i].X * values[i].W; mat.M22 += values[i].Y * values[i].Y; mat.M23 += values[i].Y * values[i].Z; mat.M24 += values[i].Y * values[i].W; mat.M33 += values[i].Z * values[i].Z; mat.M34 += values[i].Z * values[i].W; mat.M44 += values[i].W * values[i].W; } mat = Matrix4x4.Multiply(mat, 1f / (values.Length - 1)); mat.M21 = mat.M12; mat.M31 = mat.M13; mat.M32 = mat.M23; mat.M41 = mat.M14; mat.M42 = mat.M24; mat.M43 = mat.M34; return mat; } internal static Vector4 CalculatePrincipalAxis(Matrix4x4 covarianceMatrix) { var lastDa = Vector4.UnitY; for (var i = 0; i < 30; i++) { var dA = Vector4.Transform(lastDa, covarianceMatrix); if (dA.LengthSquared() == 0) { break; } dA = Vector4.Normalize(dA); if (Vector4.Dot(lastDa, dA) > 0.999999) { lastDa = dA; break; } else { lastDa = dA; } } return lastDa; } public static void ConvertToVector4(Color[] colors,Vector4[] vectors) { for(int i=0;i<colors.Length;++i) { vectors[i].X += colors[i].R / 255f; vectors[i].Y += colors[i].G / 255f; vectors[i].Z += colors[i].B / 255f; vectors[i].W += colors[i].A / 255f; } } public static void CreateVectors(Color[] colors, out Vector3 mean, out Vector3 principalAxis) { Vector4[] vectors = new Vector4[colors.Length]; ConvertToVector4(colors, vectors); var cov = CalculateCovariance(vectors, out var v4Mean); mean = new Vector3(v4Mean.X, v4Mean.Y, v4Mean.Z); var pa = CalculatePrincipalAxis(cov); principalAxis = new Vector3(pa.X, pa.Y, pa.Z); if (principalAxis.LengthSquared() == 0) { principalAxis = Vector3.UnitY; } else { principalAxis = Vector3.Normalize(principalAxis); } } public static void GetMinMaxColor565(Color[] colors, Vector3 mean, Vector3 principalAxis,out ColorRgb565 min, out ColorRgb565 max) { float minD = 0; float maxD = 0; for (var i = 0; i < colors.Length; i++) { var colorVec = new Vector3(colors[i].R / 255f, colors[i].G / 255f, colors[i].B / 255f); var v = colorVec - mean; var d = Vector3.Dot(v, principalAxis); if (d < minD) minD = d; if (d > maxD) maxD = d; } //Inset minD *= 15 / 16f; maxD *= 15 / 16f; var minVec = mean + principalAxis * minD; var maxVec = mean + principalAxis * maxD; var minR = (int)(minVec.X * 255); var minG = (int)(minVec.Y * 255); var minB = (int)(minVec.Z * 255); var maxR = (int)(maxVec.X * 255); var maxG = (int)(maxVec.Y * 255); var maxB = (int)(maxVec.Z * 255); minR = minR >= 0 ? minR : 0; minG = minG >= 0 ? minG : 0; minB = minB >= 0 ? minB : 0; maxR = maxR <= 255 ? maxR : 255; maxG = maxG <= 255 ? maxG : 255; maxB = maxB <= 255 ? maxB : 255; // Optimal round minR = (minR & ColorRgb565.C565_5Mask) | (minR >> 5); minG = (minG & ColorRgb565.C565_6Mask) | (minG >> 6); minB = (minB & ColorRgb565.C565_5Mask) | (minB >> 5); maxR = (maxR & ColorRgb565.C565_5Mask) | (maxR >> 5); maxG = (maxG & ColorRgb565.C565_6Mask) | (maxG >> 6); maxB = (maxB & ColorRgb565.C565_5Mask) | (maxB >> 5); min = new ColorRgb565((byte)minR, (byte)minG, (byte)minB); max = new ColorRgb565((byte)maxR, (byte)maxG, (byte)maxB); } public static DXTBlock EncodeBlock(DXTBlock rawBlock) { CreateVectors(rawBlock.SourceColours, out var mean, out var pa); GetMinMaxColor565(rawBlock.SourceColours, mean, pa, out var min, out var max); var c0 = max; var c1 = min; if (c0.data < c1.data) { var c = c0; c0 = c1; c1 = c; } DXTBlock best = TryColors(rawBlock, c0, c1, out var bestError); var lastChanged = 0; for (var i = 0; i < MaxTries; i++) { var (newC0, newC1) = ColorVariationGenerator.Variate565(c0, c1, i); if (newC0.data < newC1.data) { var c = newC0; newC0 = newC1; newC1 = c; } DXTBlock block = TryColors(rawBlock, newC0, newC1, out var error); lastChanged++; if (error < bestError) { best = block; bestError = error; c0 = newC0; c1 = newC1; lastChanged = 0; } if (bestError < ErrorThreshold || lastChanged > ColorVariationGenerator.VarPatternCount) { break; } } return best; } } public static DXTBlock TryColors(DXTBlock rawBlock, ColorRgb565 color0, ColorRgb565 color1, out float error, float rWeight = 0.3f, float gWeight = 0.6f, float bWeight = 0.1f) { DXTBlock resultBlock = new DXTBlock(); var pixels = rawBlock.SourceColours; resultBlock.CalculatedColor0 = color0; resultBlock.CalculatedColor1 = color1; var c0 = color0.ToColor(); var c1 = color1.ToColor(); Color[] colors = resultBlock.HasAlphaOrBlack ?new Color[] {c0,c1,c0.InterpolateHalf(c1),Color.FromArgb(255,0, 0, 0)} : new Color[] {c0,c1,c0.InterpolateThird(c1, 1),c0.InterpolateThird(c1, 2)}; error = 0; for (var i = 0; i < 16; i++) { var color = pixels[i]; resultBlock[i] = ChooseClosestColor4(colors, color, rWeight, gWeight, bWeight, out var e); error += e; } return resultBlock; } public static Color InterpolateHalf(this Color c0, Color c1) => InterpolateColor(c0, c1, 1, 2); /// <summary> /// Interpolates two colors by third. /// </summary> /// <param name="c0">The first color endpoint.</param> /// <param name="c1">The second color endpoint.</param> /// <param name="num">The dividend in the third.</param> /// <returns>The interpolated color.</returns> public static Color InterpolateThird(this Color c0, Color c1, int num) => InterpolateColor(c0, c1, num, 3); public static Color InterpolateColor(Color c0, Color c1, int num, int den) => Color.FromArgb(255, (byte)Interpolate(c0.R, c1.R, num, den), (byte)Interpolate(c0.G, c1.G, num, den), (byte)Interpolate(c0.B, c1.B, num, den)); public static int Interpolate(int a, int b, int num, int den, int correction = 0) => (int)(((den - num) * a + num * b + correction) / (float)den); public static int ChooseClosestColor4(Color[] colors, Color color, float rWeight, float gWeight, float bWeight, out float error) { float[] d = new float[4] { Math.Abs(colors[0].R - color.R) * rWeight + Math.Abs(colors[0].G - color.G) * gWeight + Math.Abs(colors[0].B - color.B) * bWeight, Math.Abs(colors[1].R - color.R) * rWeight + Math.Abs(colors[1].G - color.G) * gWeight + Math.Abs(colors[1].B - color.B) * bWeight, Math.Abs(colors[2].R - color.R) * rWeight + Math.Abs(colors[2].G - color.G) * gWeight + Math.Abs(colors[2].B - color.B) * bWeight, Math.Abs(colors[3].R - color.R) * rWeight + Math.Abs(colors[3].G - color.G) * gWeight + Math.Abs(colors[3].B - color.B) * bWeight, }; var b0 = d[0] > d[3] ? 1 : 0; var b1 = d[1] > d[2] ? 1 : 0; var b2 = d[0] > d[2] ? 1 : 0; var b3 = d[1] > d[3] ? 1 : 0; var b4 = d[2] > d[3] ? 1 : 0; var x0 = b1 & b2; var x1 = b0 & b3; var x2 = b0 & b4; var idx = x2 | ((x0 | x1) << 1); error = d[idx]; return idx; } public static int ChooseClosestColor4AlphaCutOff(Color[] colors, Color color, float rWeight, float gWeight, float bWeight, int alphaCutOff, bool hasAlpha, out float error) { if (hasAlpha && color.A < alphaCutOff) { error = 0; return 3; } float[] d = new float[4] { Math.Abs(colors[0].R - color.R) * rWeight + Math.Abs(colors[0].G - color.G) * gWeight + Math.Abs(colors[0].B - color.B) * bWeight, Math.Abs(colors[1].R - color.R) * rWeight + Math.Abs(colors[1].G - color.G) * gWeight + Math.Abs(colors[1].B - color.B) * bWeight, Math.Abs(colors[2].R - color.R) * rWeight + Math.Abs(colors[2].G - color.G) * gWeight + Math.Abs(colors[2].B - color.B) * bWeight, hasAlpha ? 999 : Math.Abs(colors[3].R - color.R) * rWeight + Math.Abs(colors[3].G - color.G) * gWeight + Math.Abs(colors[3].B - color.B) * bWeight, }; var b0 = d[0] > d[2] ? 1 : 0; var b1 = d[1] > d[3] ? 1 : 0; var b2 = d[0] > d[3] ? 1 : 0; var b3 = d[1] > d[2] ? 1 : 0; var nb3 = d[1] > d[2] ? 0 : 1; var b4 = d[0] > d[1] ? 1 : 0; var b5 = d[2] > d[3] ? 1 : 0; var idx = (nb3 & b4) | (b2 & b5) | (((b0 & b3) | (b1 & b2)) << 1); error = d[idx]; return idx; } } public struct ColorRgb565 : IEquatable<ColorRgb565> { public const int C565_5Mask = 0xF8; public const int C565_6Mask = 0xFC; public bool Equals(ColorRgb565 other) { return data == other.data; } public override bool Equals(object obj) { return obj is ColorRgb565 other && Equals(other); } public override int GetHashCode() { return data.GetHashCode(); } public static bool operator ==(ColorRgb565 left, ColorRgb565 right) { return left.Equals(right); } public static bool operator !=(ColorRgb565 left, ColorRgb565 right) { return !left.Equals(right); } public const ushort RedMask = 0b11111_000000_00000; public const int RedShift = 11; public const ushort GreenMask = 0b00000_111111_00000; public const int GreenShift = 5; public const ushort BlueMask = 0b00000_000000_11111; public ushort data; public byte R { get { var r5 = (data & RedMask) >> RedShift; return (byte)((r5 << 3) | (r5 >> 2)); } set { var r5 = value >> 3; data = (ushort)(data & ~RedMask); data = (ushort)(data | (r5 << RedShift)); } } public byte G { get { var g6 = (data & GreenMask) >> GreenShift; return (byte)((g6 << 2) | (g6 >> 4)); } set { var g6 = value >> 2; data = (ushort)(data & ~GreenMask); data = (ushort)(data | (g6 << GreenShift)); } } public byte B { get { var b5 = data & BlueMask; return (byte)((b5 << 3) | (b5 >> 2)); } set { var b5 = value >> 3; data = (ushort)(data & ~BlueMask); data = (ushort)(data | b5); } } public int RawR { get { return (data & RedMask) >> RedShift; } set { if (value > 31) value = 31; if (value < 0) value = 0; data = (ushort)(data & ~RedMask); data = (ushort)(data | (value << RedShift)); } } public int RawG { get { return (data & GreenMask) >> GreenShift; } set { if (value > 63) value = 63; if (value < 0) value = 0; data = (ushort)(data & ~GreenMask); data = (ushort)(data | (value << GreenShift)); } } public int RawB { get { return data & BlueMask; } set { if (value > 31) value = 31; if (value < 0) value = 0; data = (ushort)(data & ~BlueMask); data = (ushort)(data | value); } } public ColorRgb565(byte r, byte g, byte b) { data = 0; R = r; G = g; B = b; } public ColorRgb565(Vector3 colorVector) { data = 0; R = ByteHelper.ClampToByte(colorVector.X * 255); G = ByteHelper.ClampToByte(colorVector.Y * 255); B = ByteHelper.ClampToByte(colorVector.Z * 255); } public Color ToColor() { return Color.FromArgb(255,R, G, B); } public override string ToString() { return $"r : {R} g : {G} b : {B}"; } } }
5f5c8293792c17d84289b0853f360ada2a22815d
C#
KimHuiEun/E-BookSystem
/EBook.Data/Entities/Rent.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBook.Data { public partial class Rent { public override string ToString() { return $"{RentId} / {RentDate} / {CustomerId} / {BookId} / {ReturnedDate}"; } public int Decade { get { return (DateTime.Now.Year - BirthYear) / 10 * 10; } } public int BirthYear { get; set; } public string Genre { get; set; } public string Gender { get; set; } public string Title { get; set; } } }
ee98303409de32f8e00a3ce26ec91dfb825b27d5
C#
ktj007/simpleRPG
/SimpleRPG/Assets/_SimpleRPG/Scripts/Characters/Special Abilities/Magic Missile/MagicMissileBehaviour.cs
2.546875
3
using UnityEngine; using RPG.Weapons; namespace RPG.Characters { public class MagicMissileBehaviour : AbilityBehaviour { const float MISSILE_SPEED = 10f; public override void Use(GameObject target, bool useTargetPosition) { base.Use(target, useTargetPosition); CastMissile(target); } private void CastMissile(GameObject target) { gameObject.transform.LookAt(target.transform); Vector3 positionToHit = target.transform.position; Vector3 unitVectorToTarget = (positionToHit - gameObject.transform.position).normalized; Vector3 positionToSpawnFrom = gameObject.transform.position; positionToSpawnFrom.y += 1f; // do not spawn from feet ;-) positionToSpawnFrom.z += unitVectorToTarget.z; // move missile away from player in the direction player is facing x positionToSpawnFrom.x += unitVectorToTarget.x; // move missile away from player in the direction player is facing z GameObject newProjectile = Instantiate(((MagicMissileConfig)config).GetMissile(), positionToSpawnFrom, Quaternion.identity); newProjectile.name = "Magic Missile"; newProjectile.transform.LookAt(target.transform); Projectile projectile = newProjectile.GetComponent<Projectile>(); projectile.SetProjectileTarget(target); projectile.SetDamageCaused( ((MagicMissileConfig)config).GetMissileDamage()); newProjectile.GetComponent<Rigidbody>().velocity = unitVectorToTarget * MISSILE_SPEED; } } }
35a4b4d8dee8aa14af33e9f314680cef940c4714
C#
SofiaMalmsten/ComputationalFloorplans
/PlotPlanning/PlotPlanning/Components/Evaluate/NumberOfHouses.cs
2.828125
3
using System; using System.Collections.Generic; using Grasshopper.Kernel; // In order to load the result of this wizard, you will also need to // add the output bin/ folder of this project to the list of loaded // folder in Grasshopper. // You can use the _GrasshopperDeveloperSettings Rhino command for that. namespace PlotPlanning.Components { public class NumberOfHouses : GH_Component { #region Register node /// <summary> /// Each implementation of GH_Component must provide a public /// constructor without any arguments. /// Category represents the Tab in which the component will appear, /// Subcategory the panel. If you use non-existing tab or panel names, /// new tabs/panels will automatically be created. /// </summary> public NumberOfHouses() : base("NumberOfHouses", "NrH", "Calculates the amount of SFH on a site", "PlotPlanningTool", "Evaluate") { } /// <summary> /// Provides an Icon for every component that will be visible in the User Interface. /// Icons need to be 24x24 pixels. /// </summary> protected override System.Drawing.Bitmap Icon { get { return Properties.Resources.NumberOfHouses; } } /// <summary> /// Each component must have a unique Guid to identify it. /// It is vital this Guid doesn't change otherwise old ghx files /// that use the old ID will partially fail during loading. /// </summary> public override Guid ComponentGuid { get { return new Guid("a088001a-e2ea-406f-adc0-7d31fe6430de"); } } #endregion #region Input/Output /// <summary> /// Registers all the input parameters for this component. /// </summary> protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) { pManager.AddGenericParameter("SFH", "S", "SFH", GH_ParamAccess.list); } /// <summary> /// Registers all the output parameters for this component. /// </summary> protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) { pManager.AddIntegerParameter("NumberOfHOuses", "N", "NumberOfHouses", GH_ParamAccess.item); } #endregion #region Solution /// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object can be used to retrieve data from input parameters and /// to store data in output parameters.</param> protected override void SolveInstance(IGH_DataAccess DA) { //Create class instances List<ObjectModel.SingleFamily> SFH = new List<ObjectModel.SingleFamily>(); //Get Data if (!DA.GetDataList(0, SFH)) return; //Calculate int numerOfHouses = SFH.Count; //Set data DA.SetData(0, numerOfHouses); } #endregion } }
ad4248340edc1c93626054f714bd2d3ca7937d3b
C#
Azure/azure-functions-host
/test/WebJobs.Script.Tests.Integration/TestScripts/CSharp/MobileTableOut/run.csx
2.96875
3
public static async Task<Item> Run(string input, TraceWriter log) { var item = new Item { Id = input, Text = "Hello from C#!" }; log.Info($"Inserting item {item.Id}"); // artificially making this function async to test // async return values await Task.Delay(500); return item; } public class Item { public string Id { get; set; } public string Text { get; set; } public bool IsProcessed { get; set; } public DateTimeOffset ProcessedAt { get; set; } // Mobile table properties public DateTimeOffset CreatedAt { get; set; } }
9529672935779265ff67fc13471e54074e399840
C#
gulyash/cs-dotnet
/dotnetlab1/dotnetlab1/Factories/PuffBaker.cs
3.765625
4
using dotnetlab1.Baking; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace dotnetlab1 { /// <summary> /// This class describes a bakery worker that is a professional with puff pastry /// </summary> class PuffBaker : IBaker { private string pastry; private Bakery workplace; /// <summary> /// When you hire a baker /// </summary> /// <param name="bakery">Baker's workplace</param> public PuffBaker(Bakery bakery) { workplace = bakery; pastry = "puff"; Console.WriteLine("You just hired {0} baker.", pastry); } /// <summary> /// This guy makes you a puff bun with a filling you want /// </summary> /// <param name="filling">Filling parameter</param> /// <returns></returns> public Bun bakeBun(string filling) { if (workplace.fridge.hasFilling(filling)) return new Bun(pastry, filling); else { Console.WriteLine("There's no {1} filling in the fridge", filling); return null; } } /// <summary> /// Baker gives you a pie with a filling you ordered /// </summary> /// <param name="filling">fill pie with it</param> /// <returns></returns> public Pie bakePie(string filling) { if (workplace.fridge.hasFilling(filling)) return new Pie(pastry, filling); else { Console.WriteLine("There's no {1} filling in the fridge", filling); return null; } } } }
697f1db0904ef7979898125c19907d78727d41be
C#
x-stars/DotNetExtensions
/XNetEx.ObjectModel/ObservableDataObject.cs
2.8125
3
using System; using System.Collections.Concurrent; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace XNetEx.ComponentModel; /// <summary> /// 提供属性更改通知类型 <see cref="INotifyPropertyChanged"/> 的抽象基类。 /// </summary> [Serializable] public abstract class ObservableDataObject : INotifyPropertyChanged { /// <summary> /// 表示索引属性的默认名称。 /// </summary> protected const string IndexerName = "Item[]"; /// <summary> /// 表示所有属性的数据存储。 /// </summary> private readonly ConcurrentDictionary<string, object?> PropertyData; /// <summary> /// 表示所有属性的关联属性的名称。 /// </summary> private readonly ConcurrentDictionary<string, string[]> RelatedProperties; /// <summary> /// 初始化 <see cref="ObservableDataObject"/> 类的新实例。 /// </summary> protected ObservableDataObject() { this.PropertyData = new ConcurrentDictionary<string, object?>(); this.RelatedProperties = new ConcurrentDictionary<string, string[]>(); this.InitializeRelatedProperties(); } /// <summary> /// 在属性值更改时发生。 /// </summary> [field: NonSerialized] public event PropertyChangedEventHandler? PropertyChanged; /// <summary> /// 在派生类中重写时,初始化所有属性的关联属性的名称。 /// </summary> protected virtual void InitializeRelatedProperties() { } /// <summary> /// 确定指定的属性名称是否表示当前数据实体。 /// </summary> /// <param name="propertyName">要确认是否表示数据实体的属性名称。</param> /// <returns>若 <paramref name="propertyName"/> 为 <see langword="null"/> 或空字符串, /// 则为 <see langword="true"/>;否则为 <see langword="false"/>。</returns> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] protected bool IsEntityName([NotNullWhen(false)] string? propertyName) { return string.IsNullOrEmpty(propertyName); } /// <summary> /// 获取指定属性或当前实体的值。 /// </summary> /// <typeparam name="T">属性的类型。</typeparam> /// <param name="propertyName">要获取值的属性的名称; /// 如果要获取当前实体的值,则为 <see langword="null"/> 或空字符串。</param> /// <returns>名为 <paramref name="propertyName"/> 的属性或当前实体的值。</returns> /// <exception cref="InvalidCastException"> /// 指定属性或实体的值无法转换为 <typeparamref name="T"/> 类型。</exception> [return: MaybeNull] protected T GetProperty<T>([CallerMemberName] string? propertyName = null) { if (this.IsEntityName(propertyName)) { return (T)(object)this; } return this.GetPropertyCore<T>(propertyName); } /// <summary> /// 设置指定属性的值。 /// </summary> /// <typeparam name="T">属性的类型。</typeparam> /// <param name="value">属性的新值。</param> /// <param name="propertyName">要设置值的属性的名称。</param> /// <exception cref="InvalidCastException"> /// <paramref name="value"/> 无法转换为指定属性的类型。</exception> /// <exception cref="InvalidOperationException"> /// <paramref name="propertyName"/> 为 <see langword="null"/> 或空字符串。</exception> protected virtual void SetProperty<T>( [AllowNull] T value, [CallerMemberName] string? propertyName = null) { if (this.IsEntityName(propertyName)) { throw new InvalidOperationException(); } var property = this.ExchangeProperty<T>(propertyName, value); var propertyChanged = !RuntimeHelpers.Equals(property, value); if (propertyChanged) { this.RelatedNotifyPropertyChanged(propertyName); } } /// <summary> /// 获取指定属性的值。 /// </summary> /// <typeparam name="T">属性的类型。</typeparam> /// <param name="propertyName">要获取值的属性的名称。</param> /// <returns>名为 <paramref name="propertyName"/> 的属性的值。</returns> [return: MaybeNull] protected virtual T GetPropertyCore<T>(string propertyName) { var hasValue = this.PropertyData.TryGetValue(propertyName, out var value); return hasValue ? (T?)value : default(T); } /// <summary> /// 设置指定属性的值,并返回其原值。 /// </summary> /// <typeparam name="T">属性的类型。</typeparam> /// <param name="value">属性的新值。</param> /// <param name="propertyName">要设置值的属性的名称。</param> /// <returns>名为 <paramref name="propertyName"/> 的属性的原值。</returns> /// <exception cref="InvalidCastException"> /// <paramref name="value"/> 无法转换为指定属性的类型。</exception> [return: MaybeNull] protected virtual T ExchangeProperty<T>(string propertyName, [AllowNull] T value) { var hasValue = this.PropertyData.ExchangeOrAdd(propertyName, value, out var oldValue); return hasValue ? (T?)oldValue : default(T); } /// <summary> /// 获取指定属性的关联属性的名称。 /// </summary> /// <param name="propertyName">要获取关联属性的属性的名称。</param> /// <returns>名为 <paramref name="propertyName"/> 的属性的关联属性的名称。</returns> protected string[] GetRelatedProperties([CallerMemberName] string? propertyName = null) { if (this.IsEntityName(propertyName)) { return Array.Empty<string>(); } this.RelatedProperties.TryGetValue(propertyName, out var relatedProperties); return relatedProperties ?? Array.Empty<string>(); } /// <summary> /// 设置指定属性的关联属性的名称。 /// </summary> /// <param name="propertyName">要设置关联属性的属性的名称。</param> /// <param name="relatedProperties">指定属性的关联属性的名称的数组。</param> /// <exception cref="InvalidOperationException"> /// <paramref name="propertyName"/> 为 <see langword="null"/> 或空字符串。</exception> protected void SetRelatedProperties(string propertyName, params string[] relatedProperties) { if (this.IsEntityName(propertyName)) { throw new InvalidOperationException(); } var hasRelated = (relatedProperties is not null) && (relatedProperties.Length != 0); if (hasRelated) { this.RelatedProperties[propertyName] = relatedProperties!; } else { this.RelatedProperties.TryRemove(propertyName, out relatedProperties!); } } /// <summary> /// 通知指定属性的值已更改,并通知其关联属性的值已更改。 /// </summary> /// <param name="propertyName">已更改属性的名称。</param> protected void RelatedNotifyPropertyChanged([CallerMemberName] string? propertyName = null) { this.NotifyPropertyChanged(propertyName); if (this.IsEntityName(propertyName)) { return; } var relatedProperties = this.GetRelatedProperties(propertyName); if (relatedProperties.Length == 0) { return; } Array.ForEach(relatedProperties, this.NotifyPropertyChanged); } /// <summary> /// 通知指定属性的值已更改。 /// </summary> /// <param name="propertyName">已更改属性的名称。</param> protected void NotifyPropertyChanged([CallerMemberName] string? propertyName = null) { this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } /// <summary> /// 使用指定的事件数据引发 <see cref="ObservableDataObject.PropertyChanged"/> 事件。 /// </summary> /// <param name="e">包含事件数据的 <see cref="PropertyChangedEventArgs"/>。</param> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { this.PropertyChanged?.Invoke(this, e); } }
6d0ce2feadc3deccec9af774aacfc105b6f125ab
C#
danielflower/MusicCollectionCompleter
/MusicCollectionCompleterTests/Services/AlbumIgonoranceDbTest.cs
2.703125
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using MusicCollectionCompleter.Desktop.Services; using NUnit.Framework; namespace MusicCollectionCompleter.MusicCollectionCompleterTests.Services { public class AlbumIgonoranceDbTest { AlbumIgonoranceDb db = new AlbumIgonoranceDb(new DirectoryInfo(Path.Combine(Path.GetTempPath(), "TestData", Guid.NewGuid().ToString()))); [Test] public void ReturnsAnEmptyListForAnUnknownAlbum() { CollectionAssert.IsEmpty(db.GetIgnoredAlbums("iamnotarealartist")); } [Test] public void AlbumsIgnorationCanBeStored() { var one = new Album("Album one"); var two = new Album("Album two"); var three = new Album("Album three"); db.IgnoreAlbum("theartist", one); db.IgnoreAlbum("theartist", two); db.IgnoreAlbum("anotherartist", three); CollectionAssert.AreEquivalent(new[] { one, two }, db.GetIgnoredAlbums("theartist")); } [Test] public void ItCanHandleCrazyCharacters() { var crazy = "crazy: artist/\\!"; CollectionAssert.IsEmpty(db.GetIgnoredAlbums(crazy)); var one = new Album("The One"); db.IgnoreAlbum(crazy, one); CollectionAssert.AreEquivalent(new[] { one }, db.GetIgnoredAlbums(crazy)); } } }
3bd253f7bd541490a96b63e3d4de851fb0909f2f
C#
1994wjdwodbs/StudyCSharp21
/chap10/Chap10App/ArrayListApp/Program.cs
3.34375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace ArrayListApp { class Program { static void Main(string[] args) { System.Collections.ArrayList array = new ArrayList(); array.Add(80); array.Add(74); array.Add(81); array.Add(90); array.Add(34); int x = array.IndexOf(81); array.Insert(x, 50); Console.WriteLine("81위치에 50 추가"); // Console.WriteLine($"{array.IndexOf(81)}"); foreach (var item in array) Console.WriteLine($"{item}"); array.Remove(90); Console.WriteLine("90 삭제"); foreach (var item in array) Console.WriteLine($"{item}"); array.Sort(); Console.WriteLine("정렬"); foreach (var item in array) Console.WriteLine($"{item}"); } } }
a4b776259c13e23a8d31b98876b93c2d6af0f6dd
C#
ermirbeqiraj/oop-encapsulation-abstraction
/OOP.EA/Bank.Logic/Implementations/ConvertionRates.cs
2.734375
3
using Bank.Logic.Interfaces; namespace Bank.Logic.Implementations { public class ConvertionRates : IConvertionRates { public decimal Convert(decimal amountToConvert, Currency amountToConvertCurrency, Currency baseCurrency) { var rates = 1.12m; // suppose we got this from some remote storage return amountToConvert * rates; } } }
1e33ed8d7be850cf0f087a5344367f1de34f5c36
C#
newhand2017/CS280-Lecture6-Examples
/PokemonLibrary/Gym.cs
3.53125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PokemonLibrary { public class Gym { public Pokemon[] pokemons; private Random random; //Build Gym with initial value public Gym(string[] names) { pokemons = new Pokemon[names.Length]; this.random = new Random(); for (int index = 0; index < pokemons.Length; index++) { pokemons[index] = PokemonFactory.Creat(names[index]); } } //Fight public void Fight() { int a = this.RandomGenerator(0, this.pokemons.Length); int b = this.RandomGenerator(0, this.pokemons.Length); pokemons[a].Attack(pokemons[b]); } //------------------------------------------------- // Other Function //------------------------------------------------- //Random Function private int RandomGenerator(int from, int to) { double result = (to - from) * this.random.NextDouble() + from; return (int)result; } //------------------------------------------------- // //------------------------------------------------- // public Pokemon pokemon1; // public Pokemon pokemon2; // public Gym(string name1, string name2) // { // this.pokemon1 = PokemonFactory.Creat(name1); // this.pokemon2 = PokemonFactory.Creat(name2); // } // public void fight(string name1, string name2) // { // pokemon1.Attack(pokemon2); // } //------------------------------------------------- } }
57f08cd7c51bfe3246a28c91a7ff12847f8600b7
C#
darakeon/dk-lib
/Source/Util/Exceptions/ComposedResult.cs
2.59375
3
namespace Keon.Util.Exceptions { /// <summary> /// Class to return an object composed by the return error and the success return /// </summary> /// <typeparam name="S">Success return Type</typeparam> /// <typeparam name="E">Error return Type</typeparam> public class ComposedResult<S, E> where S : new() where E : new() { /// <inheritdoc /> /// <summary> /// Class to return an object composed by the return error and the success return /// </summary> public ComposedResult() : this(new S(), new E()) { } /// <inheritdoc /> /// <summary> /// Class to return an object composed by the return error and the success return /// </summary> public ComposedResult(S success) : this(success, new E()) { } /// <inheritdoc /> /// <summary> /// Class to return an object composed by the return error and the success return /// </summary> public ComposedResult(E error) : this(new S(), error) { } /// <summary> /// Class to return an object composed by the return error and the success return /// </summary> public ComposedResult(S success, E error) { Success = success; Error = error; } ///<summary> ///</summary> public S Success; ///<summary> ///</summary> public E Error; } }
ae75d65038dcf34fc79f2ac2ad742f00e5a07c9e
C#
sprz/Advent-Of-Code
/2017/day16/Program.cs
3.34375
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace day16 { class Program { static void Main(string[] args) { var orders = File.ReadAllText("data.txt").Split(',').Select(x=> Dance.CreateNew(x)).ToList(); var startOrder = "abcdefghijklmnop"; var part1 = Part1(orders,startOrder); Console.WriteLine("Part 1: " + part1); var count = 1000000000; var initialOrder = Part2(orders,startOrder,count); Console.WriteLine("Part 2: "+initialOrder); } //wrong ecodajpgkfihlbnm public static string Part1(IEnumerable<IDance> input,String order) { StringBuilder output = new StringBuilder(order); foreach(var move in input) { move.Mutate(output); } return output.ToString(); } public static string Part2(IEnumerable<IDance> input,String order,int count) { StringBuilder output = new StringBuilder(order); var repeatCount = 1; for(;repeatCount<count;repeatCount++) { foreach(var move in input) { move.Mutate(output); } if(output.ToString() == order) break; } for(int i=0;i<count % repeatCount;i++) { foreach(var move in input) { move.Mutate(output); } } return output.ToString(); } } }
3a50a65cce5df38f5a57bb93b27c85dd2345e50c
C#
shendongnian/download4
/code3/449280-10128061-23213005-8.cs
3
3
class B { protected int x; } class D : B { void M() { { x = 123; // meaning this.x inherited from B } if (whatever) { int x = 10;
3422b7ae9f28722e2ba1647a67041e20cfc47b14
C#
TheDamTeam/Homefit
/Homefit/Homefit/Services/Constants.cs
2.59375
3
using SQLite; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Homefit.Services { public static class Constants { public const string DataBaseFilename = "Homefit.db3"; public const SQLiteOpenFlags Flags = SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache; public static string DatabasePath { get { var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); return Path.Combine(basePath,DataBaseFilename); } } } }
72795a7d501c1ed70a93914c601474c0b392d515
C#
mkbiltek/TelerikAcademy-4
/WebServices/WS-3-ArhitectureWebApi-Homework/TicTacToe.Tests/GameResultValidatorTests.cs
2.515625
3
namespace TicTacToe.Tests { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using TicTacToe.GameLogic; [TestClass] public class GameResultValidatorTests { private static GameResultValidator validator; [TestInitialize] public void InitializeObjects() { validator = new GameResultValidator(); } [TestMethod] public void FirstLineWith3XShouldBeWonByX() { var result = validator.GetResult("XXX--O-O-"); Assert.AreEqual(GameResult.WonByX, result); } [TestMethod] public void FirstLineWith3OShouldBeWonByO() { var result = validator.GetResult("OOOXXOXX-"); Assert.AreEqual(GameResult.WonByO, result); } [TestMethod] public void SecondLineWith3XShouldBeWonByX() { var result = validator.GetResult("OO-XXX---"); Assert.AreEqual(GameResult.WonByX, result); } [TestMethod] public void SecondLineWith3OShouldBeWonByO() { var result = validator.GetResult("XX-OOO-XX"); Assert.AreEqual(GameResult.WonByO, result); } [TestMethod] public void ThirdLineWith3XShouldBeWonByX() { var result = validator.GetResult("OO----XXX"); Assert.AreEqual(GameResult.WonByX, result); } [TestMethod] public void ThirdLineWith3OShouldBeWonByO() { var result = validator.GetResult("XX--XXOOO"); Assert.AreEqual(GameResult.WonByO, result); } [TestMethod] public void FirstVerticalWith3XShouldBeWonByX() { var result = validator.GetResult("XO-XO-X--"); Assert.AreEqual(GameResult.WonByX, result); } [TestMethod] public void FirstVerticalWith3OShouldBeWonByO() { var result = validator.GetResult("OX-OXXO--"); Assert.AreEqual(GameResult.WonByO, result); } [TestMethod] public void SecondVerticalWith3XShouldBeWonByX() { var result = validator.GetResult("OXO-X--X-"); Assert.AreEqual(GameResult.WonByX, result); } [TestMethod] public void SecondVerticalWith3OShouldBeWonByO() { var result = validator.GetResult("XOX-O-XO-"); Assert.AreEqual(GameResult.WonByO, result); } [TestMethod] public void ThirdVerticalWith3XShouldBeWonByX() { var result = validator.GetResult("-OX-OX--X"); Assert.AreEqual(GameResult.WonByX, result); } [TestMethod] public void ThirdVerticalWith3OShouldBeWonByO() { var result = validator.GetResult("XXOXXO--O"); Assert.AreEqual(GameResult.WonByO, result); } [TestMethod] public void FirstDiagonalWhenWonByXShouldBeWonByX() { var result = validator.GetResult("XO--XO--X"); Assert.AreEqual(GameResult.WonByX, result); } [TestMethod] public void FirstDiagonalWhenWonByOShouldBeWonByO() { var result = validator.GetResult("OXXXO---O"); Assert.AreEqual(GameResult.WonByO, result); } [TestMethod] public void SecondDiagonalWhenWonByXShouldBeWonByX() { var result = validator.GetResult("--X-XOXO-"); Assert.AreEqual(GameResult.WonByX, result); } [TestMethod] public void SecondDiagonalWhenWonByOShouldBeWonByO() { var result = validator.GetResult("XXOXO-O--"); Assert.AreEqual(GameResult.WonByO, result); } [TestMethod] public void GameWhenNotFinishedShouldBeUnfinished2() { var result = validator.GetResult("---------"); Assert.AreEqual(GameResult.NotFinished, result); } [TestMethod] public void GameWhenNotFinishedShouldBeUnfinished3() { var result = validator.GetResult("XOXOXOOX-"); Assert.AreEqual(GameResult.NotFinished, result); } [TestMethod] public void GameWhenDRAWShouldBeDraw() { var result = validator.GetResult("XOXOXOOXO"); Assert.AreEqual(GameResult.Draw, result); } } }
fdcaa49a9536caf1f13fb0837a6a126fecd1f462
C#
ondryaso/GrillBot
/Grillbot/Modules/WebAdminModule.cs
2.5625
3
using Discord.Commands; using Discord.WebSocket; using Grillbot.Attributes; using Grillbot.Extensions.Discord; using Grillbot.Services.Permissions.Preconditions; using Grillbot.Services.UserManagement; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; namespace Grillbot.Modules { [Group("webadmin")] [RequirePermissions] [ModuleID("WebAdminModule")] [Name("Správa webové administrace")] public class WebAdminModule : BotModuleBase { private UserService UserService { get; } public WebAdminModule(UserService userService) { UserService = userService; } [Command("add")] [Summary("Udělení přístupu uživatele do webové administrace.")] [Remarks("AllowType znamená typ povolení (Allow=0, Deny=1)\nHeslo je volitelné. Pokud nebude zadáno, tak bude vygenerováno náhodné.")] [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "<Pending>")] // Data is from mention. public async Task AddUser(string userMention, string password = null) { try { var user = GetUserFromMention(); if (user == null) { await ReplyAsync("Nebyl tagnut žádný uživatel."); return; } password = UserService.AddUserToWebAdmin(Context.Guild, user, password); await user?.SendPrivateMessageAsync( $"Byl ti udělen přístup do webové administrace. Uživatelské jméno je tvůj globální discord nick.\nHeslo máš zde: `{password}`. Uchovej si ho."); await ReplyAsync("Přístup umožněn."); } catch (InvalidOperationException ex) { await ReplyAsync(ex.Message); } } [Command("remove")] [Summary("Odebrání uživatele z webové administrace.")] [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "<Pending>")] // Data is from mention. public async Task RemoveUser(string userMention) { try { var user = GetUserFromMention(); if (user == null) { await ReplyAsync("Nebyl tagnut žádný uživatel."); return; } UserService.RemoveUserFromWebAdmin(Context.Guild, user); await ReplyAsync("Přístup byl odebrán."); } catch (ArgumentException ex) { await ReplyAsync(ex.Message); } } private SocketGuildUser GetUserFromMention() { return Context.Message.MentionedUsers.OfType<SocketGuildUser>().FirstOrDefault(); } } }
c6ae3f71939f972d0a4d913ef83e61ca3fb16307
C#
Something226/Slutprojekt
/Slutprojekt/Program.cs
3.90625
4
using System; using System.Collections.Generic; namespace Slutprojekt { class Program { static void Main(string[] args) { //Variables and lists/arrays List<string> shopItemstrings = new List<string>() { "dagger", "potion", "sword", "armor" }; // List<int> shopItemcost = new List<int>() { 5, 3, 10, 5 }; List<string> playerItems = new List<string>(); //inital message System.Console.WriteLine("Welcome to the shop\nWe have these items:"); //for-loop that prints available items Printitems(shopItemstrings); //requests player input System.Console.WriteLine("What would you like to buy?"); //method for buying items BuyItem(shopItemstrings, playerItems); Printitems(shopItemstrings); //list that shows player items System.Console.WriteLine("Player has these items"); Printitems(playerItems); Console.ReadLine(); } //Buyitem method, used to remove and add items purchased by user static void BuyItem(List<string> shopItemstrings, List<string> playerItems) { //player input prompt System.Console.WriteLine("(Enter name of the item you want)"); string item = Console.ReadLine(); item = item.ToLower(); //for-loop, checks for item name for (int i = 0; i < shopItemstrings.Count; i++) { if (item == shopItemstrings[i]) { System.Console.WriteLine("Are you sure you want that?(Y/n)"); string answer = ""; while (answer != "y" && answer != "n") { answer = Console.ReadLine().ToLower(); if (answer != "y" && answer != "n") { System.Console.WriteLine("Enter a valid answer"); } } if (answer == "y") { shopItemstrings.Remove(item); playerItems.Add(item); } if (answer == "n") { System.Console.WriteLine("cool"); } } } } //For-loop method, prints lists static void Printitems(List<string> list) { for (int i = 0; i < list.Count; i++) { System.Console.WriteLine(list[i]); } } } }
b5e6f03baf0371d659131180a0c4a40520164435
C#
Opiumtm/Imageboard10
/Imageboard10/Imageboard10.Core.Models/Serialization/ObjectSerializationService.cs
2.625
3
using System; using System.Collections.Generic; using Imageboard10.Core.ModelInterface; using Imageboard10.Core.Modules; namespace Imageboard10.Core.Models.Serialization { /// <summary> /// Сервис сериализации (общая реализация). /// </summary> public sealed class ObjectSerializationService : ModuleBase<IObjectSerializationService>, IObjectSerializationService { private readonly Dictionary<Type, IObjectSerializer> _typeCache = new Dictionary<Type, IObjectSerializer>(); private readonly Dictionary<string, IObjectSerializer> _idCache = new Dictionary<string, IObjectSerializer>(); private IObjectSerializer GetSerializer(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); lock (_typeCache) { if (!_typeCache.ContainsKey(type)) { _typeCache[type] = ModuleProvider.QueryModule<IObjectSerializer, Type>(type) ?? throw new ModuleNotFoundException($"Не найдена логика сериализации типа {type.FullName}"); } return _typeCache[type]; } } private IObjectSerializer GetSerializer(string typeId) { if (typeId == null) throw new ArgumentNullException(nameof(typeId)); lock (_idCache) { if (!_idCache.ContainsKey(typeId)) { _idCache[typeId] = ModuleProvider.QueryModule<IObjectSerializer, string>(typeId) ?? throw new ModuleNotFoundException($"Не найдена логика сериализации типа TypeId=\"{typeId}\""); } return _idCache[typeId]; } } /// <summary> /// Сериализовать. /// </summary> /// <param name="obj">Объект.</param> /// <returns>Сериализованный объект.</returns> public string SerializeToString(ISerializableObject obj) { if (obj == null) { return null; } var serializer = GetSerializer(obj.GetTypeForSerializer()); return SerializationImplHelper.WithTypeId(serializer.SerializeToString(obj), serializer.TypeId); } /// <summary> /// Сериализовать. /// </summary> /// <param name="obj">Объект.</param> /// <returns>Сериализованное медиа.</returns> public byte[] SerializeToBytes(ISerializableObject obj) { if (obj == null) { return null; } var serializer = GetSerializer(obj.GetTypeForSerializer()); return SerializationImplHelper.WithTypeId(serializer.SerializeToBytes(obj), serializer.TypeId); } /// <summary> /// Десериализовать. /// </summary> /// <param name="data">Данные.</param> /// <returns>Объект.</returns> public ISerializableObject Deserialize(string data) { if (data == null) { return null; } (var sdata, var typeId) = SerializationImplHelper.ExtractTypeId(data); var serializer = GetSerializer(typeId); return serializer.Deserialize(sdata); } /// <summary> /// Десериализовать. /// </summary> /// <param name="data">Данные.</param> /// <returns>Объект.</returns> public ISerializableObject Deserialize(byte[] data) { if (data == null) { return null; } (var sdata, var typeId) = SerializationImplHelper.ExtractTypeId(data); var serializer = GetSerializer(typeId); return serializer.Deserialize(sdata); } /// <summary> /// Найти сериализатор. /// </summary> /// <param name="type">Тип.</param> /// <returns>Сериализатор.</returns> public IObjectSerializer FindSerializer(Type type) => GetSerializer(type); /// <summary> /// Найти сериализатор. /// </summary> /// <param name="typeId">Идентификатор типа.</param> /// <returns>Сериализатор.</returns> public IObjectSerializer FindSerializer(string typeId) => GetSerializer(typeId); } }
7a426d972b9eb38c7df413c37d1ea4c6a76c75d7
C#
Leonov-Artem/InformationTheoryCoursework
/Algorithms/CRC/CyclicalRedundancyCheck.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms.CRC { public class CyclicalRedundancyCheck { string _bitString; public string BinaryText { get; private set; } public int GeneratingPolynomDegree { get; private set; } public string GeneratingPolynom { get; private set; } public CyclicalRedundancyCheck() { } public CyclicalRedundancyCheck(string text, string polynom) { GeneratingPolynom = StringConverter.GeneratingPolynomToBinary(polynom); GeneratingPolynomDegree = GeneratingPolynom.Length - 1; BinaryText = StringConverter.HexToBinary(text); _bitString = AddZerosToEnd(BinaryText, GeneratingPolynomDegree); } public string CheckMessageIntegrity(string textWithCRC, string polynom) { _bitString = BinaryText = textWithCRC; GeneratingPolynom = polynom; GeneratingPolynomDegree = GeneratingPolynom.Length - 1; return Compute(); } public string Compute() { while (_bitString.Length > GeneratingPolynomDegree) { BitStringXORgenPoly(); RemoveExtraZerosFromBitStringStart(); } return _bitString; } private void BitStringXORgenPoly() { string strToReplace = _bitString.Substring(0, GeneratingPolynom.Length); var xorResult = new StringBuilder(); for (int i = 0; i < GeneratingPolynom.Length; i++) { if (_bitString[i] == GeneratingPolynom[i]) xorResult.Append('0'); else xorResult.Append('1'); } _bitString = _bitString.Replace(strToReplace, xorResult.ToString()); } private void RemoveExtraZerosFromBitStringStart() { while (_bitString.StartsWith("0")) { if (_bitString.Length > GeneratingPolynomDegree) _bitString = _bitString.Remove(0, 1); else return; } } private string AddZerosToEnd(string sourceMessage, int count) { var newBitStr = new StringBuilder(sourceMessage); for (int i = 0; i < count; i++) newBitStr.Append("0"); return newBitStr.ToString(); } } }
45a732a669afb53826dfdf3a6efca6d50e4074c2
C#
SergeyRazin/Tasks-EPAM-
/Task9/MyClassLibraryCAPTCHA/Test_MyClassLibrary/Test_Accessors/Test_Accessor_XML.cs
2.84375
3
using System.Collections.Generic; using MyClassLibrary.Accessors; using MyClassLibrary.Interfaces; using NUnit.Framework; using MyClassLibrary.DataClasses; namespace Test_MyClassLibrary.Test_Accessors { //ПОДДЕЛКА для XPath public class FakeXPath:MyXPath { //получить месторождение со скважинами public override Oilfield getOil(string oilName0) { return new Test_Accessor_XML().CreateOilfieldAlacaevka(); } //получить все месторождения со скважинами public override List<Oilfield> getAllOil() { //создать лист месторождений со скважинами List<Oilfield> oilList = new List<Oilfield>(); //создать месторождения алакаевку и каменку var alak = new Test_Accessor_XML().CreateOilfieldAlacaevka(); var kamen = new Test_Accessor_XML().CreateOilfieldKamenka(); //добавить в этот лист алакаевку и каменку oilList.Add(alak); oilList.Add(kamen); //вернуть этот лист return oilList; } } //ПОДДЕЛКА для DAL public class FakeDalxml:IDAL { public List<Oilfield> OilLIst; public void SerializtionWithExchengeFile(string path, List<Oilfield> oilfields0) { //создать лист с месторождениями(в него будем сохранять результат работы кода) OilLIst = new List<Oilfield>(); //сохранить результат работы кода OilLIst = oilfields0; } public List<Oilfield> Desirializ(string path) { //создать лист месторождений со скважинами List<Oilfield> oilList = new List<Oilfield>(); //добавить в этот лист алакаевку и каменку oilList.Add(new Test_Accessor_XML().CreateOilfieldAlacaevka()); oilList.Add(new Test_Accessor_XML().CreateOilfieldKamenka()); //вернуть этот лист return oilList; } } [TestFixture] class Test_Accessor_XML { private Well well = new Well() {Number = 10,Debit = 10,Pump = "REDA"}; #region вспомогательные методы-------↓----------------------- //создать лист скважин public List<Well> CreateListWells() { Well well1 = new Well() { Number = 1, Debit = 100, Pump = "ШГН" }; Well well2 = new Well() { Number = 2, Debit = 200, Pump = "ЭЦН-30-1500" }; Well well3 = new Well() { Number = 3, Debit = 300, Pump = "REDA-500" }; List<Well> listWell = new List<Well>(); listWell.Add(well1); listWell.Add(well2); listWell.Add(well3); return listWell; } //создать месторождение алакаевка public Oilfield CreateOilfieldAlacaevka() { Oilfield alak = new Oilfield(); alak.Name = "Алакаевка"; alak.OilReserves = 1111; alak.Wells = CreateListWells(); return alak; } //создание месторождения каменка public Oilfield CreateOilfieldKamenka() { Oilfield kamen = new Oilfield(); kamen.Name = "Каменка"; kamen.OilReserves = 2222; kamen.Wells = CreateListWells(); return kamen; } //создание месторождения зольное public Oilfield CreatOilfieldZolnoe() { Oilfield zolnoe = new Oilfield(); zolnoe.Name = "Зольное"; zolnoe.OilReserves = 3333; zolnoe.Wells = CreateListWells(); return zolnoe; } #endregion вспомогательные методы----↑---------------------- [Test] public void Test_AccessorXML_AddOilfield_if_oilfield_with_this_name_olredy_exists() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalBinary(); accessor.xpath = new FakeXPath(); var alak = CreateOilfieldAlacaevka(); //act //assert Assert.Catch(() => accessor.AddOilfield(alak)); } [Test] public void Test_AccessorXML_AddOilfield_Normal() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); var zol = CreatOilfieldZolnoe(); FakeDalxml fakeDal = (FakeDalxml) accessor.Dal; //act accessor.AddOilfield(zol); //assert Assert.AreEqual(3,fakeDal.OilLIst.Count); } [Test] public void Test_AccessorXML_RemoveOilfield_if_index_not_found() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); //act //assert Assert.Catch(() => accessor.RemoveOilfield(100)); } [Test] public void Test_AccessorXML_RemoveOilfield_Normal() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); FakeDalxml fakeDal = (FakeDalxml) accessor.Dal; //act accessor.RemoveOilfield(0); //assert Assert.AreEqual(1, fakeDal.OilLIst.Count); } [Test] public void Test_AccessorXML_AddWell_if_Oilfield_not_found() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); //act //assert var ex = Assert.Catch(() => accessor.AddWell(well, "юююю")); StringAssert.Contains("Месторождения с таким именем нет", ex.Message); } [Test] public void Test_AccessorXML_AddWell_Normal() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); FakeDalxml fakeDalxml = (FakeDalxml) accessor.Dal; //act accessor.AddWell(well, "Алакаевка"); //assert Assert.AreEqual(4,fakeDalxml.OilLIst[0].Wells.Count); } [Test] public void Test_RemoveWell_if_Oilfield_not_found() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); FakeDalxml fakeDalxml = (FakeDalxml)accessor.Dal; //act //assert var ex = Assert.Catch(() => accessor.RemoveWell(1, ".....")); StringAssert.Contains("Месторождения с таким именем нет.", ex.Message); } [Test] public void Test_RemoveWell_if_number_well_not_found() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); FakeDalxml fakeDalxml = (FakeDalxml)accessor.Dal; //act //assert var ex = Assert.Catch(() => accessor.RemoveWell(1000, "Алакаевка")); StringAssert.Contains("Скважины с таким номером нет.", ex.Message); } [Test] public void Test_RemoveWell_if_Oilfield_Normal() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); FakeDalxml fakeDalxml = (FakeDalxml)accessor.Dal; //act accessor.RemoveWell(1,"Алакаевка"); //assert Assert.AreEqual(2,fakeDalxml.OilLIst[0].Wells.Count); } [Test] public void Test_Update_Oilfield_if_newName_alredy_exists() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); var zol = CreatOilfieldZolnoe(); zol.Name = "Каменка"; //act //assert Assert.Catch(()=>accessor.UpdateOilfield(0,zol)); } [Test] public void Test_Update_Oilfield_if_indexOilfield_not_found() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); var zol = CreatOilfieldZolnoe(); //act,assert var ex = Assert.Catch(() => accessor.UpdateOilfield(100, zol)); StringAssert.Contains("месторождения с таким индексом нет", ex.Message); } [Test] public void Test_Update_Oilfield_Normal() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); var zol = CreatOilfieldZolnoe(); FakeDalxml fakeDalxml = (FakeDalxml) accessor.Dal; //act accessor.UpdateOilfield(0,zol); //assert Assert.AreEqual(2, fakeDalxml.OilLIst.Count); Assert.AreEqual("Зольное", fakeDalxml.OilLIst[0].Name); } [Test] public void Test_GetAllOilfield() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); //act var rez = accessor.GetAllOilfield(); //accert Assert.AreEqual(2, rez.Count); Assert.AreEqual("Алакаевка", rez[0].Name); Assert.AreEqual(0, rez[0].Index); Assert.AreEqual("Каменка", rez[1].Name); Assert.AreEqual(1, rez[1].Index); } [Test] public void Test_GetOilfieldByIndex_if_index_notFound() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); //act //assert var ex = Assert.Catch(() => accessor.GetOilfieldByIndex(100)); StringAssert.Contains("месторождения с таким индексом нет", ex.Message); } [Test] public void Test_GetOilfieldByIndex_Normal() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); //act var rez = accessor.GetOilfieldByIndex(0); //assert Assert.AreEqual("Алакаевка", rez.Name); } [Test] public void Test_CountOilfield() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); //act var rez = accessor.CountOilfield(); //assert Assert.AreEqual(2,rez); } [Test] public void Test_CountWells() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); //act var rez = accessor.CountWells(); //assert Assert.AreEqual(6, rez); } [Test] public void Test_CountWellsInOilfields_if_index_notFound() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); //act,assert Assert.Catch(() => accessor.CountWellsInOilfield(100)); } [Test] public void Test_CountWellsInOilfields() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); //act var rez = accessor.CountWellsInOilfield(0); //assert Assert.AreEqual(3,rez); } [Test] public void Test_GetNameByIndex_if_index_notFound() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); //act,assert Assert.Catch(() => accessor.GetNameByIndex(100)); } [Test] public void Test_GetNameByIndex_Normal() { //arrange var accessor = new AccessorXML(); accessor.Dal = new FakeDalxml(); accessor.xpath = new FakeXPath(); //act var rez = accessor.GetNameByIndex(1); //assert Assert.AreEqual("Каменка", rez); } } }
e5ab11e62b7a8a3d11ac23c5570a118ce1f0b475
C#
Dream-Scaper/AABBRaylib
/ConsoleApp1/MyShape.cs
2.90625
3
using System.Collections.Generic; using Raylib; using Collision; namespace ConsoleApp1 { class MyShape { public Vector2 position = new Vector2(); public List<Vector2> MyPoints = new List<Vector2>(); public Color color = Color.BLACK; public AABB collisionBox = new AABB(); public float Swooce = 1f; public void Draw() { Vector2 Last = new Vector2(); for (int idx = 0; idx < MyPoints.Count; idx++) { if (idx > 0) Raylib.Raylib.DrawLineEx(position + Last, position + MyPoints[idx], 2, color); Last = MyPoints[idx]; } } public void Update() { List<Vector2> temp = new List<Vector2>(); for (int idx = 0; idx < MyPoints.Count; idx++) { temp.Add(MyPoints[idx] + position); } collisionBox.Fit(temp); } } }
9285e0f055926ed658237a267484b6ceed6b4e5f
C#
vijayprasad23/SupportClass2_Area
/SupportClass2_Area/Program.cs
3.96875
4
using System; namespace SupportClass2_Area { class Program { static void Main(string[] args) { //Variable Declarations double length, width, radius, height, base1, area; const double PI = 3.1415962; Console.WriteLine("This program will calculate the area of a rectangle, circle and triangle"); //User inputs for the rectangle Console.Write("\n\nArea of a Rectangle/Square...\n"); Console.Write("Please enter the length of the rectangle "); length = Convert.ToDouble(Console.ReadLine()); Console.Write("Please enter the width of the rectangle "); width = Convert.ToDouble(Console.ReadLine()); area = length * width; Console.Write("\nThe area of the rectangle is " + area); //User inputs for the circle Console.Write("\n\nArea of a Circle...\n"); Console.Write("Please enter the radius "); radius = Convert.ToDouble(Console.ReadLine()); area = PI * radius * radius; Console.Write("\nThe area of the circle is " + area); //User inputs for the triangle Console.Write("\n\nArea of a Triangle...\n"); Console.Write("Please enter the base "); base1 = Convert.ToDouble(Console.ReadLine()); Console.Write("Please enter the height "); height = Convert.ToDouble(Console.ReadLine()); area = 0.5 * base1 * height; Console.Write("\nThe area of the triangle is " + area); //Pausing the screen Console.Write("\n\n\nPress any key to exit... "); Console.ReadKey(); } } }
0cb0d5189cb7d83e3feeea267707cce057289d55
C#
dozray/deep
/deep.tool/Logger.cs
2.890625
3
using log4net; using System; using System.IO; using System.Text; public class Logger { private static readonly string LOG_DIR = (AppDomain.CurrentDomain.BaseDirectory + "logs"); private static readonly string FILE_PATH = (LOG_DIR + @"\" + DateTime.Now.ToString("yy-M-d") + ".log"); private static ILog lg = LogManager.GetLogger("AppInfo"); private static StringBuilder sb = new StringBuilder(); public static void Info(object message) { lg.Info(message); } public static void Info(object message, Exception exception) { lg.Info(message, exception); } public static void log(object obj) { try { if (File.Exists(FILE_PATH)) { sb.Length = 0; sb.AppendLine("=============================================================================="); sb.AppendFormat("Date:\t{0} Time:\t{1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()); sb.AppendLine(); sb.AppendLine(obj.ToString()); StreamWriter writer = File.AppendText(FILE_PATH); writer.WriteLine(sb.ToString()); writer.Flush(); writer.Close(); } else { if (!Directory.Exists(LOG_DIR)) { Directory.CreateDirectory(LOG_DIR); } File.Create(FILE_PATH).Close(); } } catch (Exception exception) { Console.WriteLine(exception.ToString()); } } }
6aebdcab592ac4ced8acc887ce6e2cdadc68e5e1
C#
graphql-dotnet/parser
/src/GraphQLParser/Visitors/ASTVisitor.cs
2.59375
3
using GraphQLParser.AST; namespace GraphQLParser.Visitors; /// <summary> /// Visitor which methods are called when traversing AST. /// <typeparam name="TContext">Type of the context object passed into all VisitXXX methods.</typeparam> /// </summary> public class ASTVisitor<TContext> where TContext : IASTVisitorContext { /// <summary> /// Visits <see cref="GraphQLDocument"/> node. /// </summary> protected virtual async ValueTask VisitDocumentAsync(GraphQLDocument document, TContext context) { await VisitAsync(document.Comments, context).ConfigureAwait(false); // Comments always null await VisitAsync(document.Definitions, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLArgument"/> node. /// </summary> protected virtual async ValueTask VisitArgumentAsync(GraphQLArgument argument, TContext context) { await VisitAsync(argument.Comments, context).ConfigureAwait(false); await VisitAsync(argument.Name, context).ConfigureAwait(false); await VisitAsync(argument.Value, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLArgumentsDefinition"/> node. /// </summary> protected virtual async ValueTask VisitArgumentsDefinitionAsync(GraphQLArgumentsDefinition argumentsDefinition, TContext context) { await VisitAsync(argumentsDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(argumentsDefinition.Items, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLArguments"/> node. /// </summary> protected virtual async ValueTask VisitArgumentsAsync(GraphQLArguments arguments, TContext context) { await VisitAsync(arguments.Comments, context).ConfigureAwait(false); await VisitAsync(arguments.Items, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLComment"/> node. /// </summary> protected virtual ValueTask VisitCommentAsync(GraphQLComment comment, TContext context) { return default; } /// <summary> /// Visits <see cref="GraphQLDescription"/> node. /// </summary> protected virtual ValueTask VisitDescriptionAsync(GraphQLDescription description, TContext context) { return default; } /// <summary> /// Visits <see cref="GraphQLOperationDefinition"/> node. /// </summary> protected virtual async ValueTask VisitOperationDefinitionAsync(GraphQLOperationDefinition operationDefinition, TContext context) { await VisitAsync(operationDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(operationDefinition.Name, context).ConfigureAwait(false); await VisitAsync(operationDefinition.Variables, context).ConfigureAwait(false); await VisitAsync(operationDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(operationDefinition.SelectionSet, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLName"/> node. /// </summary> protected virtual async ValueTask VisitNameAsync(GraphQLName name, TContext context) { await VisitAsync(name.Comments, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLVariableDefinition"/> node. /// </summary> protected virtual async ValueTask VisitVariableDefinitionAsync(GraphQLVariableDefinition variableDefinition, TContext context) { await VisitAsync(variableDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(variableDefinition.Variable, context).ConfigureAwait(false); await VisitAsync(variableDefinition.Type, context).ConfigureAwait(false); await VisitAsync(variableDefinition.DefaultValue, context).ConfigureAwait(false); await VisitAsync(variableDefinition.Directives, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLVariablesDefinition"/> node. /// </summary> protected virtual async ValueTask VisitVariablesDefinitionAsync(GraphQLVariablesDefinition variablesDefinition, TContext context) { await VisitAsync(variablesDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(variablesDefinition.Items, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLVariable"/> node. /// </summary> protected virtual async ValueTask VisitVariableAsync(GraphQLVariable variable, TContext context) { await VisitAsync(variable.Comments, context).ConfigureAwait(false); await VisitAsync(variable.Name, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLSelectionSet"/> node. /// </summary> protected virtual async ValueTask VisitSelectionSetAsync(GraphQLSelectionSet selectionSet, TContext context) { await VisitAsync(selectionSet.Comments, context).ConfigureAwait(false); await VisitAsync(selectionSet.Selections, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLAlias"/> node. /// </summary> #pragma warning disable CA1716 // Identifiers should not match keywords (alias) protected virtual async ValueTask VisitAliasAsync(GraphQLAlias alias, TContext context) #pragma warning restore CA1716 { await VisitAsync(alias.Comments, context).ConfigureAwait(false); await VisitAsync(alias.Name, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLField"/> node. /// </summary> protected virtual async ValueTask VisitFieldAsync(GraphQLField field, TContext context) { await VisitAsync(field.Comments, context).ConfigureAwait(false); await VisitAsync(field.Alias, context).ConfigureAwait(false); await VisitAsync(field.Name, context).ConfigureAwait(false); await VisitAsync(field.Arguments, context).ConfigureAwait(false); await VisitAsync(field.Directives, context).ConfigureAwait(false); await VisitAsync(field.SelectionSet, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLFragmentName"/> node. /// </summary> protected virtual async ValueTask VisitFragmentNameAsync(GraphQLFragmentName fragmentName, TContext context) { await VisitAsync(fragmentName.Comments, context).ConfigureAwait(false); await VisitAsync(fragmentName.Name, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLFragmentSpread"/> node. /// </summary> protected virtual async ValueTask VisitFragmentSpreadAsync(GraphQLFragmentSpread fragmentSpread, TContext context) { await VisitAsync(fragmentSpread.Comments, context).ConfigureAwait(false); await VisitAsync(fragmentSpread.FragmentName, context).ConfigureAwait(false); await VisitAsync(fragmentSpread.Directives, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLInlineFragment"/> node. /// </summary> protected virtual async ValueTask VisitInlineFragmentAsync(GraphQLInlineFragment inlineFragment, TContext context) { await VisitAsync(inlineFragment.Comments, context).ConfigureAwait(false); await VisitAsync(inlineFragment.TypeCondition, context).ConfigureAwait(false); await VisitAsync(inlineFragment.Directives, context).ConfigureAwait(false); await VisitAsync(inlineFragment.SelectionSet, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLTypeCondition"/> node. /// </summary> protected virtual async ValueTask VisitTypeConditionAsync(GraphQLTypeCondition typeCondition, TContext context) { await VisitAsync(typeCondition.Comments, context).ConfigureAwait(false); await VisitAsync(typeCondition.Type, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLImplementsInterfaces"/> node. /// </summary> protected virtual async ValueTask VisitImplementsInterfacesAsync(GraphQLImplementsInterfaces implementsInterfaces, TContext context) { await VisitAsync(implementsInterfaces.Comments, context).ConfigureAwait(false); await VisitAsync(implementsInterfaces.Items, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLFragmentDefinition"/> node. /// </summary> protected virtual async ValueTask VisitFragmentDefinitionAsync(GraphQLFragmentDefinition fragmentDefinition, TContext context) { await VisitAsync(fragmentDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(fragmentDefinition.FragmentName, context).ConfigureAwait(false); await VisitAsync(fragmentDefinition.TypeCondition, context).ConfigureAwait(false); await VisitAsync(fragmentDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(fragmentDefinition.SelectionSet, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLIntValue"/> node. /// </summary> protected virtual async ValueTask VisitIntValueAsync(GraphQLIntValue intValue, TContext context) { await VisitAsync(intValue.Comments, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLFloatValue"/> node. /// </summary> protected virtual async ValueTask VisitFloatValueAsync(GraphQLFloatValue floatValue, TContext context) { await VisitAsync(floatValue.Comments, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLStringValue"/> node. /// </summary> protected virtual async ValueTask VisitStringValueAsync(GraphQLStringValue stringValue, TContext context) { await VisitAsync(stringValue.Comments, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLBooleanValue"/> node. /// </summary> protected virtual async ValueTask VisitBooleanValueAsync(GraphQLBooleanValue booleanValue, TContext context) { await VisitAsync(booleanValue.Comments, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLEnumValue"/> node. /// </summary> protected virtual async ValueTask VisitEnumValueAsync(GraphQLEnumValue enumValue, TContext context) { await VisitAsync(enumValue.Comments, context).ConfigureAwait(false); await VisitAsync(enumValue.Name, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLListValue"/> node. /// </summary> protected virtual async ValueTask VisitListValueAsync(GraphQLListValue listValue, TContext context) { await VisitAsync(listValue.Comments, context).ConfigureAwait(false); await VisitAsync(listValue.Values, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLObjectValue"/> node. /// </summary> protected virtual async ValueTask VisitObjectValueAsync(GraphQLObjectValue objectValue, TContext context) { await VisitAsync(objectValue.Comments, context).ConfigureAwait(false); await VisitAsync(objectValue.Fields, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLObjectField"/> node. /// </summary> protected virtual async ValueTask VisitObjectFieldAsync(GraphQLObjectField objectField, TContext context) { await VisitAsync(objectField.Comments, context).ConfigureAwait(false); await VisitAsync(objectField.Name, context).ConfigureAwait(false); await VisitAsync(objectField.Value, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLDirective"/> node. /// </summary> protected virtual async ValueTask VisitDirectiveAsync(GraphQLDirective directive, TContext context) { await VisitAsync(directive.Comments, context).ConfigureAwait(false); await VisitAsync(directive.Name, context).ConfigureAwait(false); await VisitAsync(directive.Arguments, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLDirectives"/> node. /// </summary> protected virtual async ValueTask VisitDirectivesAsync(GraphQLDirectives directives, TContext context) { await VisitAsync(directives.Comments, context).ConfigureAwait(false); // Comment always null - see ParserContext.ParseDirectives await VisitAsync(directives.Items, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLNamedType"/> node. /// </summary> protected virtual async ValueTask VisitNamedTypeAsync(GraphQLNamedType namedType, TContext context) { await VisitAsync(namedType.Comments, context).ConfigureAwait(false); await VisitAsync(namedType.Name, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLListType"/> node. /// </summary> protected virtual async ValueTask VisitListTypeAsync(GraphQLListType listType, TContext context) { await VisitAsync(listType.Comments, context).ConfigureAwait(false); await VisitAsync(listType.Type, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLNonNullType"/> node. /// </summary> protected virtual async ValueTask VisitNonNullTypeAsync(GraphQLNonNullType nonNullType, TContext context) { await VisitAsync(nonNullType.Comments, context).ConfigureAwait(false); await VisitAsync(nonNullType.Type, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLNullValue"/> node. /// </summary> protected virtual async ValueTask VisitNullValueAsync(GraphQLNullValue nullValue, TContext context) { await VisitAsync(nullValue.Comments, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLSchemaDefinition"/> node. /// </summary> protected virtual async ValueTask VisitSchemaDefinitionAsync(GraphQLSchemaDefinition schemaDefinition, TContext context) { await VisitAsync(schemaDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(schemaDefinition.Description, context).ConfigureAwait(false); await VisitAsync(schemaDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(schemaDefinition.OperationTypes, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLRootOperationTypeDefinition"/> node. /// </summary> protected virtual async ValueTask VisitRootOperationTypeDefinitionAsync(GraphQLRootOperationTypeDefinition rootOperationTypeDefinition, TContext context) { await VisitAsync(rootOperationTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(rootOperationTypeDefinition.Type, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLScalarTypeDefinition"/> node. /// </summary> protected virtual async ValueTask VisitScalarTypeDefinitionAsync(GraphQLScalarTypeDefinition scalarTypeDefinition, TContext context) { await VisitAsync(scalarTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(scalarTypeDefinition.Description, context).ConfigureAwait(false); await VisitAsync(scalarTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(scalarTypeDefinition.Directives, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLObjectTypeDefinition"/> node. /// </summary> protected virtual async ValueTask VisitObjectTypeDefinitionAsync(GraphQLObjectTypeDefinition objectTypeDefinition, TContext context) { await VisitAsync(objectTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(objectTypeDefinition.Description, context).ConfigureAwait(false); await VisitAsync(objectTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(objectTypeDefinition.Interfaces, context).ConfigureAwait(false); await VisitAsync(objectTypeDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(objectTypeDefinition.Fields, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLFieldDefinition"/> node. /// </summary> protected virtual async ValueTask VisitFieldDefinitionAsync(GraphQLFieldDefinition fieldDefinition, TContext context) { await VisitAsync(fieldDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(fieldDefinition.Description, context).ConfigureAwait(false); await VisitAsync(fieldDefinition.Name, context).ConfigureAwait(false); await VisitAsync(fieldDefinition.Arguments, context).ConfigureAwait(false); await VisitAsync(fieldDefinition.Type, context).ConfigureAwait(false); await VisitAsync(fieldDefinition.Directives, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLFieldsDefinition"/> node. /// </summary> protected virtual async ValueTask VisitFieldsDefinitionAsync(GraphQLFieldsDefinition fieldsDefinition, TContext context) { await VisitAsync(fieldsDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(fieldsDefinition.Items, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLInputValueDefinition"/> node. /// </summary> protected virtual async ValueTask VisitInputValueDefinitionAsync(GraphQLInputValueDefinition inputValueDefinition, TContext context) { await VisitAsync(inputValueDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(inputValueDefinition.Description, context).ConfigureAwait(false); await VisitAsync(inputValueDefinition.Name, context).ConfigureAwait(false); await VisitAsync(inputValueDefinition.Type, context).ConfigureAwait(false); await VisitAsync(inputValueDefinition.DefaultValue, context).ConfigureAwait(false); await VisitAsync(inputValueDefinition.Directives, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLInputFieldsDefinition"/> node. /// </summary> protected virtual async ValueTask VisitInputFieldsDefinitionAsync(GraphQLInputFieldsDefinition inputFieldsDefinition, TContext context) { await VisitAsync(inputFieldsDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(inputFieldsDefinition.Items, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLInterfaceTypeDefinition"/> node. /// </summary> protected virtual async ValueTask VisitInterfaceTypeDefinitionAsync(GraphQLInterfaceTypeDefinition interfaceTypeDefinition, TContext context) { await VisitAsync(interfaceTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(interfaceTypeDefinition.Description, context).ConfigureAwait(false); await VisitAsync(interfaceTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(interfaceTypeDefinition.Interfaces, context).ConfigureAwait(false); await VisitAsync(interfaceTypeDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(interfaceTypeDefinition.Fields, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLUnionTypeDefinition"/> node. /// </summary> protected virtual async ValueTask VisitUnionTypeDefinitionAsync(GraphQLUnionTypeDefinition unionTypeDefinition, TContext context) { await VisitAsync(unionTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(unionTypeDefinition.Description, context).ConfigureAwait(false); await VisitAsync(unionTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(unionTypeDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(unionTypeDefinition.Types, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLUnionMemberTypes"/> node. /// </summary> protected virtual async ValueTask VisitUnionMemberTypesAsync(GraphQLUnionMemberTypes unionMemberTypes, TContext context) { await VisitAsync(unionMemberTypes.Comments, context).ConfigureAwait(false); await VisitAsync(unionMemberTypes.Items, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLEnumTypeDefinition"/> node. /// </summary> protected virtual async ValueTask VisitEnumTypeDefinitionAsync(GraphQLEnumTypeDefinition enumTypeDefinition, TContext context) { await VisitAsync(enumTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(enumTypeDefinition.Description, context).ConfigureAwait(false); await VisitAsync(enumTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(enumTypeDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(enumTypeDefinition.Values, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLEnumValueDefinition"/> node. /// </summary> protected virtual async ValueTask VisitEnumValueDefinitionAsync(GraphQLEnumValueDefinition enumValueDefinition, TContext context) { await VisitAsync(enumValueDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(enumValueDefinition.Description, context).ConfigureAwait(false); await VisitAsync(enumValueDefinition.EnumValue, context).ConfigureAwait(false); await VisitAsync(enumValueDefinition.Directives, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLEnumValuesDefinition"/> node. /// </summary> protected virtual async ValueTask VisitEnumValuesDefinitionAsync(GraphQLEnumValuesDefinition enumValuesDefinition, TContext context) { await VisitAsync(enumValuesDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(enumValuesDefinition.Items, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLInputObjectTypeDefinition"/> node. /// </summary> protected virtual async ValueTask VisitInputObjectTypeDefinitionAsync(GraphQLInputObjectTypeDefinition inputObjectTypeDefinition, TContext context) { await VisitAsync(inputObjectTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeDefinition.Description, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeDefinition.Fields, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLDirectiveDefinition"/> node. /// </summary> protected virtual async ValueTask VisitDirectiveDefinitionAsync(GraphQLDirectiveDefinition directiveDefinition, TContext context) { await VisitAsync(directiveDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(directiveDefinition.Description, context).ConfigureAwait(false); await VisitAsync(directiveDefinition.Name, context).ConfigureAwait(false); await VisitAsync(directiveDefinition.Arguments, context).ConfigureAwait(false); await VisitAsync(directiveDefinition.Locations, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLDirectiveLocations"/> node. /// </summary> protected virtual async ValueTask VisitDirectiveLocationsAsync(GraphQLDirectiveLocations directiveLocations, TContext context) { await VisitAsync(directiveLocations.Comments, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLSchemaExtension"/> node. /// </summary> protected virtual async ValueTask VisitSchemaExtensionAsync(GraphQLSchemaExtension schemaExtension, TContext context) { await VisitAsync(schemaExtension.Comments, context).ConfigureAwait(false); await VisitAsync(schemaExtension.Directives, context).ConfigureAwait(false); await VisitAsync(schemaExtension.OperationTypes, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLScalarTypeExtension"/> node. /// </summary> protected virtual async ValueTask VisitScalarTypeExtensionAsync(GraphQLScalarTypeExtension scalarTypeExtension, TContext context) { await VisitAsync(scalarTypeExtension.Comments, context).ConfigureAwait(false); await VisitAsync(scalarTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(scalarTypeExtension.Directives, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLObjectTypeExtension"/> node. /// </summary> protected virtual async ValueTask VisitObjectTypeExtensionAsync(GraphQLObjectTypeExtension objectTypeExtension, TContext context) { await VisitAsync(objectTypeExtension.Comments, context).ConfigureAwait(false); await VisitAsync(objectTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(objectTypeExtension.Interfaces, context).ConfigureAwait(false); await VisitAsync(objectTypeExtension.Directives, context).ConfigureAwait(false); await VisitAsync(objectTypeExtension.Fields, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLInterfaceTypeExtension"/> node. /// </summary> protected virtual async ValueTask VisitInterfaceTypeExtensionAsync(GraphQLInterfaceTypeExtension interfaceTypeExtension, TContext context) { await VisitAsync(interfaceTypeExtension.Comments, context).ConfigureAwait(false); await VisitAsync(interfaceTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(interfaceTypeExtension.Interfaces, context).ConfigureAwait(false); await VisitAsync(interfaceTypeExtension.Directives, context).ConfigureAwait(false); await VisitAsync(interfaceTypeExtension.Fields, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLUnionTypeExtension"/> node. /// </summary> protected virtual async ValueTask VisitUnionTypeExtensionAsync(GraphQLUnionTypeExtension unionTypeExtension, TContext context) { await VisitAsync(unionTypeExtension.Comments, context).ConfigureAwait(false); await VisitAsync(unionTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(unionTypeExtension.Directives, context).ConfigureAwait(false); await VisitAsync(unionTypeExtension.Types, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLEnumTypeExtension"/> node. /// </summary> protected virtual async ValueTask VisitEnumTypeExtensionAsync(GraphQLEnumTypeExtension enumTypeExtension, TContext context) { await VisitAsync(enumTypeExtension.Comments, context).ConfigureAwait(false); await VisitAsync(enumTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(enumTypeExtension.Directives, context).ConfigureAwait(false); await VisitAsync(enumTypeExtension.Values, context).ConfigureAwait(false); } /// <summary> /// Visits <see cref="GraphQLInputObjectTypeExtension"/> node. /// </summary> protected virtual async ValueTask VisitInputObjectTypeExtensionAsync(GraphQLInputObjectTypeExtension inputObjectTypeExtension, TContext context) { await VisitAsync(inputObjectTypeExtension.Comments, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeExtension.Directives, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeExtension.Fields, context).ConfigureAwait(false); } /// <summary> /// Dispatches node to the appropriate VisitXXX method. /// </summary> /// <param name="node">AST node to dispatch.</param> /// <param name="context">Context passed into all INodeVisitor.VisitXXX methods.</param> public virtual ValueTask VisitAsync(ASTNode? node, TContext context) { return node == null ? default : node switch { GraphQLArgument argument => VisitArgumentAsync(argument, context), GraphQLComment comment => VisitCommentAsync(comment, context), GraphQLDescription description => VisitDescriptionAsync(description, context), GraphQLDirective directive => VisitDirectiveAsync(directive, context), GraphQLDirectiveDefinition directiveDefinition => VisitDirectiveDefinitionAsync(directiveDefinition, context), GraphQLDirectiveLocations directiveLocations => VisitDirectiveLocationsAsync(directiveLocations, context), GraphQLDocument document => VisitDocumentAsync(document, context), GraphQLEnumTypeDefinition enumTypeDefinition => VisitEnumTypeDefinitionAsync(enumTypeDefinition, context), GraphQLEnumValueDefinition enumValueDefinition => VisitEnumValueDefinitionAsync(enumValueDefinition, context), GraphQLAlias alias => VisitAliasAsync(alias, context), GraphQLField field => VisitFieldAsync(field, context), GraphQLFieldDefinition fieldDefinition => VisitFieldDefinitionAsync(fieldDefinition, context), GraphQLFragmentDefinition fragmentDefinition => VisitFragmentDefinitionAsync(fragmentDefinition, context), // inherits from GraphQLInlineFragment so should be above GraphQLFragmentSpread fragmentSpread => VisitFragmentSpreadAsync(fragmentSpread, context), GraphQLInlineFragment inlineFragment => VisitInlineFragmentAsync(inlineFragment, context), GraphQLFragmentName fragmentName => VisitFragmentNameAsync(fragmentName, context), GraphQLTypeCondition typeCondition => VisitTypeConditionAsync(typeCondition, context), GraphQLInputObjectTypeDefinition inputObjectTypeDefinition => VisitInputObjectTypeDefinitionAsync(inputObjectTypeDefinition, context), GraphQLInputValueDefinition inputValueDefinition => VisitInputValueDefinitionAsync(inputValueDefinition, context), GraphQLInterfaceTypeDefinition interfaceTypeDefinition => VisitInterfaceTypeDefinitionAsync(interfaceTypeDefinition, context), GraphQLListType listType => VisitListTypeAsync(listType, context), GraphQLListValue listValue => VisitListValueAsync(listValue, context), GraphQLName name => VisitNameAsync(name, context), GraphQLNamedType namedType => VisitNamedTypeAsync(namedType, context), GraphQLNonNullType nonNullType => VisitNonNullTypeAsync(nonNullType, context), GraphQLObjectField objectField => VisitObjectFieldAsync(objectField, context), GraphQLObjectTypeDefinition objectTypeDefinition => VisitObjectTypeDefinitionAsync(objectTypeDefinition, context), GraphQLObjectValue objectValue => VisitObjectValueAsync(objectValue, context), GraphQLOperationDefinition operationDefinition => VisitOperationDefinitionAsync(operationDefinition, context), GraphQLRootOperationTypeDefinition rootOperationTypeDefinition => VisitRootOperationTypeDefinitionAsync(rootOperationTypeDefinition, context), GraphQLScalarTypeDefinition scalarTypeDefinition => VisitScalarTypeDefinitionAsync(scalarTypeDefinition, context), GraphQLBooleanValue boolValue => VisitBooleanValueAsync(boolValue, context), GraphQLEnumValue enumValue => VisitEnumValueAsync(enumValue, context), GraphQLFloatValue floatValue => VisitFloatValueAsync(floatValue, context), GraphQLIntValue intValue => VisitIntValueAsync(intValue, context), GraphQLNullValue nullValue => VisitNullValueAsync(nullValue, context), GraphQLStringValue stringValue => VisitStringValueAsync(stringValue, context), GraphQLSchemaDefinition schemaDefinition => VisitSchemaDefinitionAsync(schemaDefinition, context), GraphQLSelectionSet selectionSet => VisitSelectionSetAsync(selectionSet, context), GraphQLSchemaExtension schemaEx => VisitSchemaExtensionAsync(schemaEx, context), GraphQLScalarTypeExtension scalarEx => VisitScalarTypeExtensionAsync(scalarEx, context), GraphQLObjectTypeExtension objectEx => VisitObjectTypeExtensionAsync(objectEx, context), GraphQLInterfaceTypeExtension ifaceEx => VisitInterfaceTypeExtensionAsync(ifaceEx, context), GraphQLUnionTypeExtension unionEx => VisitUnionTypeExtensionAsync(unionEx, context), GraphQLEnumTypeExtension enumEx => VisitEnumTypeExtensionAsync(enumEx, context), GraphQLInputObjectTypeExtension inputEx => VisitInputObjectTypeExtensionAsync(inputEx, context), GraphQLUnionTypeDefinition unionTypeDefinition => VisitUnionTypeDefinitionAsync(unionTypeDefinition, context), GraphQLUnionMemberTypes unionMembers => VisitUnionMemberTypesAsync(unionMembers, context), GraphQLVariable variable => VisitVariableAsync(variable, context), GraphQLVariableDefinition variableDefinition => VisitVariableDefinitionAsync(variableDefinition, context), GraphQLArgumentsDefinition argsDef => VisitArgumentsDefinitionAsync(argsDef, context), GraphQLArguments args => VisitArgumentsAsync(args, context), GraphQLInputFieldsDefinition inputFieldsDef => VisitInputFieldsDefinitionAsync(inputFieldsDef, context), GraphQLDirectives directives => VisitDirectivesAsync(directives, context), GraphQLVariablesDefinition varsDef => VisitVariablesDefinitionAsync(varsDef, context), GraphQLEnumValuesDefinition enumValuesDef => VisitEnumValuesDefinitionAsync(enumValuesDef, context), GraphQLFieldsDefinition fieldsDef => VisitFieldsDefinitionAsync(fieldsDef, context), GraphQLImplementsInterfaces implements => VisitImplementsInterfacesAsync(implements, context), _ => throw new NotSupportedException($"Unknown node '{node.GetType().Name}'."), }; } /// <summary> /// Visits all nodes from the provided list. As a rule, these are nested /// sibling nodes of some parent node, for example, argument nodes for /// parent field node or value nodes for parent list node. /// </summary> protected virtual async ValueTask VisitAsync<T>(List<T>? nodes, TContext context) where T : ASTNode { if (nodes != null) { // Visitor may change AST while being traversed so foreach yields // System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.' for (int i = 0; i < nodes.Count; ++i) await VisitAsync(nodes[i], context).ConfigureAwait(false); } } }
e3272ecbf81dcf903c3ecb02bd11b663cff8d6b7
C#
mehradae/cs204
/MaxFreeTcbs.cs
2.625
3
using System; using Microsoft.Win32; namespace CS204 { public class MaxFreeTcbs { String path = "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"; public void Add() { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path, true)) { //range between 16,000 - 65,536 key?.SetValue("MaxFreeTcbs", "65536", RegistryValueKind.DWord); key?.Close(); } } public void Remove() { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path, true)) { if (key?.GetValue("MaxFreeTcbs") == null) return; key.DeleteValue("MaxFreeTcbs"); key.Close(); } } } }
162d94bfc8175a18798a3744705e4b6616c4f48a
C#
LawrenceHan/Hearthstone-decompile
/IlSpyDecompile/Assembly-CSharp-firstpass/PegasusShared/RewardChestDbRecord.cs
2.734375
3
using System.Collections.Generic; using System.IO; namespace PegasusShared { public class RewardChestDbRecord : IProtoBuf { public bool HasShowToReturningPlayer; private bool _ShowToReturningPlayer; private List<LocalizedString> _Strings = new List<LocalizedString>(); public int Id { get; set; } public bool ShowToReturningPlayer { get { return _ShowToReturningPlayer; } set { _ShowToReturningPlayer = value; HasShowToReturningPlayer = true; } } public List<LocalizedString> Strings { get { return _Strings; } set { _Strings = value; } } public override int GetHashCode() { int hashCode = GetType().GetHashCode(); hashCode ^= Id.GetHashCode(); if (HasShowToReturningPlayer) { hashCode ^= ShowToReturningPlayer.GetHashCode(); } foreach (LocalizedString @string in Strings) { hashCode ^= @string.GetHashCode(); } return hashCode; } public override bool Equals(object obj) { RewardChestDbRecord rewardChestDbRecord = obj as RewardChestDbRecord; if (rewardChestDbRecord == null) { return false; } if (!Id.Equals(rewardChestDbRecord.Id)) { return false; } if (HasShowToReturningPlayer != rewardChestDbRecord.HasShowToReturningPlayer || (HasShowToReturningPlayer && !ShowToReturningPlayer.Equals(rewardChestDbRecord.ShowToReturningPlayer))) { return false; } if (Strings.Count != rewardChestDbRecord.Strings.Count) { return false; } for (int i = 0; i < Strings.Count; i++) { if (!Strings[i].Equals(rewardChestDbRecord.Strings[i])) { return false; } } return true; } public void Deserialize(Stream stream) { Deserialize(stream, this); } public static RewardChestDbRecord Deserialize(Stream stream, RewardChestDbRecord instance) { return Deserialize(stream, instance, -1L); } public static RewardChestDbRecord DeserializeLengthDelimited(Stream stream) { RewardChestDbRecord rewardChestDbRecord = new RewardChestDbRecord(); DeserializeLengthDelimited(stream, rewardChestDbRecord); return rewardChestDbRecord; } public static RewardChestDbRecord DeserializeLengthDelimited(Stream stream, RewardChestDbRecord instance) { long num = ProtocolParser.ReadUInt32(stream); num += stream.Position; return Deserialize(stream, instance, num); } public static RewardChestDbRecord Deserialize(Stream stream, RewardChestDbRecord instance, long limit) { if (instance.Strings == null) { instance.Strings = new List<LocalizedString>(); } while (true) { if (limit >= 0 && stream.Position >= limit) { if (stream.Position == limit) { break; } throw new ProtocolBufferException("Read past max limit"); } int num = stream.ReadByte(); switch (num) { case -1: break; case 8: instance.Id = (int)ProtocolParser.ReadUInt64(stream); continue; case 16: instance.ShowToReturningPlayer = ProtocolParser.ReadBool(stream); continue; default: { Key key = ProtocolParser.ReadKey((byte)num, stream); switch (key.Field) { case 0u: throw new ProtocolBufferException("Invalid field id: 0, something went wrong in the stream"); case 100u: if (key.WireType == Wire.LengthDelimited) { instance.Strings.Add(LocalizedString.DeserializeLengthDelimited(stream)); } break; default: ProtocolParser.SkipKey(stream, key); break; } continue; } } if (limit < 0) { break; } throw new EndOfStreamException(); } return instance; } public void Serialize(Stream stream) { Serialize(stream, this); } public static void Serialize(Stream stream, RewardChestDbRecord instance) { stream.WriteByte(8); ProtocolParser.WriteUInt64(stream, (ulong)instance.Id); if (instance.HasShowToReturningPlayer) { stream.WriteByte(16); ProtocolParser.WriteBool(stream, instance.ShowToReturningPlayer); } if (instance.Strings.Count <= 0) { return; } foreach (LocalizedString @string in instance.Strings) { stream.WriteByte(162); stream.WriteByte(6); ProtocolParser.WriteUInt32(stream, @string.GetSerializedSize()); LocalizedString.Serialize(stream, @string); } } public uint GetSerializedSize() { uint num = 0u; num += ProtocolParser.SizeOfUInt64((ulong)Id); if (HasShowToReturningPlayer) { num++; num++; } if (Strings.Count > 0) { foreach (LocalizedString @string in Strings) { num += 2; uint serializedSize = @string.GetSerializedSize(); num += serializedSize + ProtocolParser.SizeOfUInt32(serializedSize); } } return num + 1; } } }
9cb4bc9ae1a486bf08abad605eaf5a9f9d1d5040
C#
LKempton/ConversionProgram
/Program.cs
3.890625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace SOFT153AlgorithmCoursework { // SOFT153 Assignment for algorithms! // Lee Kempton // Note: There is a filename variable in the ReadValues method, this has to be changed to the filepath of where convert.txt is stored on your machine for the program to run. static class Program { static void Main(string[] args) { // Used to call to the other class once the program has started. Algorithm myProgram = new Algorithm(); myProgram.StartProgram(); } } class Node { // Class to store the 3 seperate variables and the pointer to the next node in the list. public string firstUnit; public string secondUnit; public double convertFactor; public Node next; } class List { // Class to store the list. public Node firstNode; } class Algorithm { public void StartProgram() { string userInput; string userDecision; string[] splitValues; // Cut the string at comma ',' and spaces ' '. char[] delimiter = { ',', ' ' }; // Variables to store the three inputs easily. double amount; string firstUnit; string secondUnit; string output; bool isValid = false; List list = new List(); Node node = new Node(); // Method used to read in values from the file so it can be split and stored in the list. ReadValues(list, node); // Place this entire piece of code in a do-while, this is so the program will keep prompting the user for input until a valid input is entered. do { // Text telling the user what to input and providing an exmaple. Console.WriteLine("Please enter an amount and two units, all seperated by a single comma ','..."); Console.WriteLine("Example of valid entry: 5, ounce, gram..."); Console.WriteLine("\nEnter a negative number or 0 to exit the program!"); // Make the userInput variable equal to what the user puts in the console. userInput = Console.ReadLine(); // Used to exit the program and stop crashing if the first character is not a double. try { // Exits the program if the amount is a negative amount or 0, as per assignment. if (Convert.ToDouble(userInput) <= 0) { // Break out of the while loop. break; } } catch (FormatException ex) { } // Split at the delimiter and remove any values that are empty. splitValues = userInput.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); // Make sure there are 3 values, as there are 2 units and a conversion factor, this stops empty lines being put into the list. if (splitValues.Length == 3) { // Try-catch to stop format exceptions on the amount variable. try { amount = Convert.ToDouble(splitValues[0]); // Exits the program if the amount is a negative amount or 0, as per assignment. if (amount <= 0) { break; } // Use the CheckFormat to make sure the two units only contain a-z or A-Z; if (CheckFormat(splitValues[1]) == true && CheckFormat(splitValues[2]) == true) { // Assuming the values only contain letters, convert them to lower case using the same method used earlier. firstUnit = ConvertToLowerCase(splitValues[1]); secondUnit = ConvertToLowerCase(splitValues[2]); // Make the output string equal to the result from the SearchList Method. output = SearchList(list, firstUnit, secondUnit, amount); // Check the output value isn't null or empty, which is the two cases in which a valid input was not entered. if (output != "null" && output != "") { // Display the output and ask the user if they want to convert another unit. Console.WriteLine(output); Console.WriteLine("\nWould you like to convert another unit? Y/N"); // Take the user input for the decision on whether to resart the loop. userDecision = Console.ReadLine(); // Takes either y or n and sets isValid to either true or false, making the loop around all the code start again. if (userDecision == "Y" || userDecision == "y") { isValid = false; } else if (userDecision == "N" || userDecision == "n") { isValid = true; } // If a valid y/n is not entered then assume yes. else { isValid = false; Console.WriteLine("No valid decision made, assuming yes!\n"); } } } } // Exception used to stop the wrong type being entered for the amount, displaying an error message and restarting the loop. catch (FormatException ex) { Console.WriteLine("Please make sure your inputs are of the correct type.\n"); isValid = false; } } } while (isValid == false); Console.WriteLine("Conversion program complete/exited, press any key to exit!"); // To stop the program from automatically closing. Console.ReadKey(); } void ReadValues(List list, Node node) { string filename; StreamReader reader; // Variables used to split the string that is read from the file. string lineFromFile; string[] splitValues; // Cut the string at comma ',' and spaces ' '. char[] delimiter = { ',', ' ' }; // Set the filepath of where convert.txt is located. // Change this value to you're own filepath in order to run the program. Alternatively place convert.txt in the Debug folder within the bin folder in your project. filename = @"convert.txt"; // Used a StreamReader on the filename variable to search through the file. reader = new StreamReader(filename); // Keep looping until the end of the file is reached. while (!reader.EndOfStream) { // For each line assign it to a variable so it can be easily split. lineFromFile = reader.ReadLine(); // Split at the delimiter and remove any values that are empty. splitValues = lineFromFile.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); // Make sure there are 3 values, as there are 2 units and a conversion factor, this stops empty lines being put into the list. if (splitValues.Length == 3) { // Convert the two string values to lower case before continuing. splitValues[0] = ConvertToLowerCase(splitValues[0]); splitValues[1] = ConvertToLowerCase(splitValues[1]); // Create a new node each time and assign the first, second and conversion units to the 3 values stored in splitValues[]. node = new Node(); node.firstUnit = splitValues[0]; node.secondUnit = splitValues[1]; // Make sure the convertFactor is converted to double. node.convertFactor = Convert.ToDouble(splitValues[2]); // Make the next node equal to the firstNode position. node.next = list.firstNode; list.firstNode = node; } } } private string ConvertToLowerCase(string input) { // Temp value used to store the string as it is changed character by character. string temp = ""; // Loops for each character in the string. for (int i = 0; i < input.Length; i++) { // Checks to see if the ascii value of the character falls between 65 and 90, which means it's a capital letter. // Casting the individual character as a char returns it's ascii value. if ((char)input[i] >= 65 && (char)input[i] <= 90) { // Increase the ascii value by 32, making it the lower case version of the letter. int x = (char)input[i]; x += 32; char c = (char)x; // Make the temp string contain the new lower'd character. temp += c; } else { // If the character is already lower case then just add the unaltered version to the temp string. temp += input[i]; } } // Return the completed temp string. return temp; } private bool CheckFormat(string input) { // Similar to the ConvertToLower method in it's checks but instead returns a true of false depending on the ascii value of each character in the string. // Bool used to store whether the input is valid and is returned at the end. bool isValid = false; // Iterate through each character in the input string. for (int i = 0; i < input.Length; i++) { // Check to see if the ascii value falls between 65-90 or 97-122, which represents A-Z or a-z respectively. if ((char)input[i] >= 65 && (char)input[i] <= 90 || ((char)input[i] >= 97 && (char)input[i] <= 122)) { // If this is the case set the isValid bool to true. isValid = true; } else { // Else set it to false. isValid = false; // Break the loop so it can't override the fact it is not valid on the next character. break; } } // Return the value to the calling method. return isValid; } private string SearchList(List list, string first, string second, double amount) { bool isFound = false; double newValue; string output = ""; Node node = list.firstNode; // Keep going through the nodes until an empty one is found, indicating the end of the linked list. while (node != null) { // Check the user inputs equal both the first and second unit, making sure there is a valid case for that combination of units. if (first == node.firstUnit && second == node.secondUnit) { // Calculate the value of the conversion and store it in a new value. newValue = amount * node.convertFactor; // Construct the output message so it can be returned and displayed. output = amount + " " + first + "(s)" + " is equal to " + newValue + " " + second + "(s)"; // Set isFound to true so the value of output isn't changed to the base case. isFound = true; } // Iterate through the nodes on each pass of the loop. node = node.next; } // If no valid conversion is found set output to null and display and error message. if (isFound == false) { Console.WriteLine("A valid conversion could not be found.\n"); output = "null"; } // Return the output to the calling method. return output; } } }
4089aee366f849f1125f657790ac8b13e100ea2e
C#
GreedyCoding/CodingChallenges.Net
/CodingChallenges/SortingAlgorithms/SelectionSort.cs
3.984375
4
using System; using System.Collections.Generic; using System.Text; using CodingChallenges.Utilities; namespace CodingChallenges.SortingAlgorithms { class SelectionSort { public static int[] SortArray(int[] toSort, bool ascending) { int[] _result = toSort; //Determines the sorting order bool _ascending = ascending; //Logging the array contents to the console Console.WriteLine("This number sequence is going to be sorted:"); Log.ArrayContents(toSort); int _iterationCount = 0; //Keeps track of the iterations taken int lowestIndex; //Keeps track of the lowerst inddex //Iterating over the the array for every element except the last for (int i = 0; i < _result.Length - 1; i++) { //Set first item to be the lowest initially lowestIndex = i; //Iterate over all numbers to find the lowest number for (int index = i + 1; index < _result.Length; index++) { if (ascending) { //Check if current item is lower then the item at the lowest index if (_result[index] < _result[lowestIndex]) { lowestIndex = index; } } else { //Check if current item is higher then the item at lowers index if (_result[index] > _result[lowestIndex]) { lowestIndex = index; } } } _iterationCount++; //Set the lowest index element to the front so we can start iterating at the next element Sorting.SwapElements(_result, i, lowestIndex); } //Log the result if (ascending) { Console.WriteLine("Here is the Array sorted in ascending order:"); } else { Console.WriteLine("Here is the Array sorted in descending order:"); } Log.ArrayContents(_result); //Log how many iterations were needed to fully sort the array Console.WriteLine($"The iterations needed to SelectionSort this array were '{_iterationCount}'"); Log.Line(ConsoleColor.Yellow); return _result; } public static List<int> SortList(List<int> toSort, bool ascending) { List<int> _result = toSort; //Determines the sorting order bool _ascending = ascending; //Logging the array contents to the console Console.WriteLine("This number sequence is going to be sorted:"); Log.ListContents(toSort); int _iterationCount = 0; //Keeps track of the iterations taken int lowestIndex; //Keeps track of the lowerst inddex //Iterating over the the array for every element except the last for (int i = 0; i < _result.Count - 1; i++) { //Set first item to be the lowest initially lowestIndex = i; //Iterate over all numbers to find the lowest number for (int index = i + 1; index < _result.Count; index++) { if (ascending) { //Check if current item is lower then the item at the lowest index if (_result[index] < _result[lowestIndex]) { lowestIndex = index; } } else { //Check if current item is higher then the item at lowers index if (_result[index] > _result[lowestIndex]) { lowestIndex = index; } } } _iterationCount++; //Set the lowest index element to the front so we can start iterating at the next element Sorting.SwapElements(_result, i, lowestIndex); } //Log the result if (ascending) { Console.WriteLine("Here is the Array sorted in ascending order:"); } else { Console.WriteLine("Here is the Array sorted in descending order:"); } Log.ListContents(_result); //Log how many iterations were needed to fully sort the array Console.WriteLine($"The iterations needed to SelectionSort this list were '{_iterationCount}'"); return _result; } } }
5728f0b5d1356ce57aca416a5576fedd073b2d7c
C#
floasu/csharp3
/TemaHotel/TemaHotel/ViewModel/UserUtils.cs
2.546875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using TemaHotel.DataAccess; using TemaHotel.Model; namespace TemaHotel.ViewModel { public class UserUtils : INotifyPropertyChanged { User loggedUser; public event PropertyChangedEventHandler PropertyChanged; private string username; private string name; private string email; private String password; private string confirmPassword; public UserUtils(MenuCommands com) { loggedUser = com.LoggedUser; } public UserUtils() { } public string Username { get { return username; } set { username = value; OnPropertyChanged("Username"); } } public string Name { get { return name; } set { name = value; OnPropertyChanged("Name"); } } public string Email { get { return email; } set { email = value; OnPropertyChanged("Email"); } } public string Password { get { return password; } set { password = value; OnPropertyChanged("Password"); } } public string ConfirmPassword { get { return confirmPassword; } set { confirmPassword = value; OnPropertyChanged("ConfirmPassword"); } } public void NewUser(object param) { SignUp currentSign = new SignUp(); currentSign.Show(); } public void ManageUsers(object param) { ManageUsers users = new ManageUsers(); users.Show(); } private void OnPropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } } }
605552f55446de6d859467755537e4a3b4dd4962
C#
Taktloss/AGS_TranslationEditor
/TranslationApi/GoogleTranslate.cs
2.84375
3
using System; using System.Linq; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace TranslationApi { public class GoogleTranslator : ITranslateAPI { public string Translate(string text, string from, string to) { var originalText = WebUtility.UrlEncode(text); var url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={from}&tl={to}&dt=t&q={originalText}"; using (WebClient webClient = new WebClient { Encoding = System.Text.Encoding.UTF8 }) { try { string result = webClient.DownloadString(url); JArray array = JArray.Parse(result); var translationParts = array[0].Select(item => new { Translation = item[0].Value<string>() }); result = string.Join(" ", translationParts.Select(item => item.Translation)); return result; } catch (WebException ex) { return ex.Message; } } } } }
bf6f9ca5b6e0f52a2eccd863117cc4dc858a9d20
C#
YJammak/YUI
/YUI/YProperties/YCheckProperties.cs
2.640625
3
using System.Windows; using System.Windows.Media; namespace YUI.WPF.YProperties { public static partial class YAttachProperty { #region YCheckedForegroundProperty 被选中前景色 /// <summary> /// 鼠标悬浮前景色附加属性 /// </summary> public static readonly DependencyProperty YCheckedForegroundProperty = DependencyProperty.RegisterAttached( "YCheckedForeground", typeof(Brush), typeof(YAttachProperty), new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits)); /// <summary> /// 设置被选中前景色 /// </summary> /// <param name="element"></param> /// <param name="value"></param> public static void SetYCheckedForeground(DependencyObject element, Brush value) { element.SetValue(YCheckedForegroundProperty, value); } /// <summary> /// 获取被选中前景色 /// </summary> /// <param name="element"></param> /// <returns></returns> public static Brush GetYCheckedForeground(DependencyObject element) { return (Brush)element.GetValue(YCheckedForegroundProperty); } #endregion #region YCheckedBackgroundProperty 被选中背景色 /// <summary> /// 鼠标悬浮前景色附加属性 /// </summary> public static readonly DependencyProperty YCheckedBackgroundProperty = DependencyProperty.RegisterAttached( "YCheckedBackground", typeof(Brush), typeof(YAttachProperty), new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits)); /// <summary> /// 设置被选中背景色 /// </summary> /// <param name="element"></param> /// <param name="value"></param> public static void SetYCheckedBackground(DependencyObject element, Brush value) { element.SetValue(YCheckedBackgroundProperty, value); } /// <summary> /// 获取被选中背景色 /// </summary> /// <param name="element"></param> /// <returns></returns> public static Brush GetYCheckedBackground(DependencyObject element) { return (Brush)element.GetValue(YCheckedBackgroundProperty); } #endregion } }
e630eddf9b99b5a43708e0ddebaf55e98809fd34
C#
hikerclimb/Udemy-Intermediate-Course
/Course Material/Lecture11/4-ComboListBoxes/2-Switch Example/Backup/Switch Example/Form1.cs
2.9375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Switch_Example { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnShowLegs_Click(object sender, EventArgs e) { switch (cboAnimals.Text) { case "Bird": MessageBox.Show("The animal has 2 legs."); break; case "Dog": // Notice there is no code here to execute. case "Cat": MessageBox.Show("The animal has 4 legs."); break; case "Snake": MessageBox.Show("The animal has no legs."); break; case "Centipede": MessageBox.Show("The animal has 100 legs."); break; default: MessageBox.Show("You did not select from the list!"); break; } } } }
c5ce8711a100d9340838838a06cfcde41501ea49
C#
generateui/YouTown
/YouTown/IChit.cs
3.296875
3
namespace YouTown { /// <summary> /// A number on a hexagon tile /// </summary> /// Represented as simple type exposing some convenience getters. Has a /// <see cref="RandomChit"/> implementation to represent a chit to be /// replaced at board setup. public interface IChit : IGameItem { int Number { get; } int Chance { get; } bool IsRed { get; } } public abstract class ChitBase : IChit { protected ChitBase(int id) { Id = id; } /// <inheritdoc/> public int Id { get; } public virtual int Number { get; } public virtual int Chance { get; } public virtual bool IsRed { get; } protected bool Equals(ChitBase other) { return Id == other.Id && Number == other.Number; } /// <inheritdoc/> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((ChitBase) obj); } /// <inheritdoc/> public override int GetHashCode() { unchecked { return (Id*397) ^ Number; } } public override string ToString() => $"Number: {Number}"; } /// <summary> /// To be replaced with a real chit when the board is setup /// </summary> public class RandomChit : ChitBase { public RandomChit(int id) : base(id) { } } public class Chit2 : ChitBase { public Chit2(int id = Identifier.DontCare) : base(id) { } public override int Number => 2; public override int Chance => 1; } public class Chit3 : ChitBase { public Chit3(int id = Identifier.DontCare) : base(id) { } public override int Number => 3; public override int Chance => 2; } public class Chit4 : ChitBase { public Chit4(int id = Identifier.DontCare) : base(id) { } public override int Number => 4; public override int Chance => 3; } public class Chit5 : ChitBase { public Chit5(int id = Identifier.DontCare) : base(id) { } public override int Number => 5; public override int Chance => 4; } public class Chit6 : ChitBase { public Chit6(int id = Identifier.DontCare) : base(id) { } public override int Number => 6; public override int Chance => 5; public override bool IsRed => true; } public class Chit8 : ChitBase { public Chit8(int id = Identifier.DontCare) : base(id) { } public override int Number => 8; public override int Chance => 5; public override bool IsRed => true; } public class Chit9 : ChitBase { public Chit9(int id = Identifier.DontCare) : base(id) { } public override int Number => 9; public override int Chance => 4; } public class Chit10 : ChitBase { public Chit10(int id = Identifier.DontCare) : base(id) { } public override int Number => 10; public override int Chance => 3; } public class Chit11 : ChitBase { public Chit11(int id = Identifier.DontCare) : base(id) { } public override int Number => 11; public override int Chance => 2; } public class Chit12 : ChitBase { public Chit12(int id = Identifier.DontCare) : base(id) { } public override int Number => 12; public override int Chance => 1; } }
820158f1e6e0f56ea945461a39bf2889a5f7537b
C#
Mellodica/Udemy1
/Servicos/DepartamentoServico.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Udemy1.Models; using Microsoft.EntityFrameworkCore; namespace Udemy1.Servicos { public class DepartamentoServico { private readonly TudoContext _context; public DepartamentoServico(TudoContext context) { _context = context; } public async Task<List<Departamento>> FindAllAsync() { // Trocar o ToList para o ToListAsync (EntityFrameWork) return await _context.Departamento.OrderBy(x => x.Nome).ToListAsync(); } /* * public List<Departamento> FindAll() { return _context.Departamento.OrderBy(x => x.Nome).ToList(); } */ } }
c5e0c1729e8610b19a89ccc63c0e8e2bf4ec4dae
C#
slagusev/Rhovlyn
/Rhovlyn.Engine/Managers/TextureManager.cs
2.828125
3
using System; using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; using System.IO; using Rhovlyn.Engine.Graphics; using Microsoft.Xna.Framework; using Rhovlyn.Engine.Util; namespace Rhovlyn.Engine.Managers { public class TextureManager { private static GraphicsDevice Graphics; private Dictionary< string , SpriteMap > textures; public TextureManager(GraphicsDevice graphics) { Graphics = graphics; textures = new Dictionary<string, SpriteMap>(); if (!Parser.Exists<SpriteMap>()) Parser.Add<SpriteMap>(ParseTexture); } #region Management public SpriteMap this [string index] { get { return textures[index]; } set { textures[index] = value; } } public bool Add(SpriteMap spritemap) { if (String.IsNullOrEmpty(spritemap.Texture.Name)) throw new Exception("Cannot add a Texture with a empty name"); if (!Exists(spritemap.Texture.Name)) { this.textures.Add(spritemap.Texture.Name, spritemap); return true; } return false; } public bool Add(string name, SpriteMap spritemap) { if (!Exists(name)) { spritemap.Texture.Name = name; this.textures.Add(name, spritemap); return true; } return false; } public bool Add(string name, Stream stream, List<Rectangle> frames) { if (!Exists(name)) { this.textures.Add(name, new SpriteMap(Texture2D.FromStream(Graphics, stream), name, frames)); return true; } return false; } public bool Add(string name, Stream stream) { if (!Exists(name)) { this.textures.Add(name, new SpriteMap(Texture2D.FromStream(Graphics, stream), name)); return true; } return false; } public bool Add(string name, string path) { return this.Add(name, new FileStream(path, FileMode.Open)); } public bool Exists(string name) { return this.textures.ContainsKey(name); } /// <summary> /// Load a local file. /// </summary> /// <param name="path">Path</param> public bool Load(string path) { using (var fs = new FileStream(path, FileMode.Open)) { return Load(fs); } } /// <summary> /// Load the specified stream. /// </summary> /// <param name="stream">Input Stream</param> public bool Load(Stream stream) { using (var reader = new StreamReader(stream)) { try { while (!reader.EndOfStream) { var line = reader.ReadLine(); if (line.IndexOf("#") != -1) line = line.Substring(0, line.IndexOf("#")); line.Trim(); if (string.IsNullOrEmpty(line)) continue; //Process commands if (line.StartsWith("@")) { line = line.Substring(1); if (line.StartsWith("include:")) { var obj = line.Substring(line.IndexOf("include:")); this.Load(Engine.IO.Path.ResolvePath(obj)); } } else { this.Add(Parser.Parse<SpriteMap>(line)); } } } catch (Exception ex) { Console.WriteLine(ex); return false; } } return true; } /// <summary> /// Remove the SpriteMap with the specified name safely. /// </summary> /// <param name="name">Name of the sprite</param> public bool Remove(string name) { if (Exists(name)) { textures[name].Texture.Dispose(); textures.Remove(name); } return false; } public static object ParseTexture(string text) { //Loads Local file var args = text.Split(','); var tname = args[0]; var tpath = args[1]; var tex = Texture2D.FromStream(Graphics, Engine.IO.Path.ResolvePath(tpath)); if (args.Length > 2) { if (args[2].Contains("@")) { var rects = new List<Rectangle>(); // Explict Rectangle Declearations // x:y:w:h@.... // 0:0:64:64@0:0:128:32 foreach (var rect in args[2].Split( '@')) { var parms = rect.Split(':'); if (parms.Length != 4) continue; int x = 0, y = 0, w = 0, h = 0; x = int.Parse(parms[0]); y = int.Parse(parms[1]); w = int.Parse(parms[2]); h = int.Parse(parms[3]); rects.Add(new Rectangle(x, y, w, h)); } return new SpriteMap(tex, tname, rects); } // Semi-Implicit Bounds // rows*colms // Divides up the texture into a set number of columns and rows // 2*2 else if (args[2].Contains("*")) { var parms = args[2].Split('*'); if (parms.Length != 2) throw new InvalidDataException(String.Format("Sprite map semi-implicit bounds format error {0}", text)); int row = int.Parse(parms[0]); int col = int.Parse(parms[1]); return new SpriteMap(tex, tname, row, col); } } return new SpriteMap(tex, tname); } #endregion } }
bd68f7ecb9daa1da9d9fe7d946c814969ea1f6b8
C#
vyagi/ProgrammingTechniques
/DesignPatterns/Pizzeria/Pizzeria/ItalianCapriciosa.cs
3
3
namespace Pizzeria { public class ItalianCapriciosa : Pizza { public ItalianCapriciosa() { Name = "Italian Style Capriciosa"; Dough = "Thin Crust Dough"; Sauce = "Tomato Sauce"; Toppings.Add("Shredded Mozzarella Cheese"); Toppings.Add("Baked Ham"); Toppings.Add("Mushroom"); Toppings.Add("Aubergine"); Toppings.Add("Tomatoes"); } public override string Bake() => "Baking for 12 minutes in 230 Celsius degrees"; public override string Cut() => "Cutting in 8 triangular slices"; public override string Box() => "Boxing into fancy green, white and red box with Capriciosa"; } }
f9ff1436af949d8e8d9fff7197f9ef59762f6b90
C#
wermajew/DesignPatterns
/01Singleton/Students/2017/MajewskaWeronika/ConsoleApp1/SingletonThreads/SingletonThreadingSafe.cs
3.171875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SingletonThreadSafe { class SingletonThreadingSafe { private static SingletonThreadingSafe _instance = null; private static object syncObject = new object(); public static int InstanceCounter { get; private set; } private SingletonThreadingSafe() { InstanceCounter++; Console.WriteLine("Instance number = {0}", InstanceCounter); } public static SingletonThreadingSafe GetInstance() { lock (syncObject) { if (_instance == null) { _instance = new SingletonThreadingSafe(); } } return _instance; } } }
9319b079e5d691b827c5c285977d699fb722403e
C#
shendongnian/download4
/first_version_download2/69690-4382522-9242311-2.cs
2.859375
3
private DelegateCommand UpdateData1Command { get; set; } public MyViewModel() { this.UpdateData1Command = new DelegateCommand(_ => this.GetData1(), _ => this.IsGraph1Visible); } private bool isGraph1Visible; public bool IsGraph1Visible { get { return isGraph1Visible; } set { isGraph1Visible = value; OnPropertyChanged("IsGraph1Visible"); if(UpdateData1Command.CanExecute(null)) UpdateData1Command.Execute(null); } } private void RunQueries() { if (UpdateData1Command.CanExecute(null)) UpdateData1Command.Execute(null); } private void GetData1() { // call wcf service to get the data }
92fc515bc354f0e3db79f55598aa78aa3732b7fa
C#
shendongnian/download4
/code1/167043-23393827-64103995-2.cs
3.140625
3
public static K CopyMost<T, K>(this IEnumerable<T> records, Func<T, K> propertySelector, Func<K, bool> tieBreaker) { var grouped = records.GroupBy(x => propertySelector(x)).Select(x => new { Group = x, Count = x.Count() }); var maxCount = grouped.Max(x => x.Count); var subGroup = grouped.Where(x => x.Count == maxCount); if (subGroup.Count() == 1) return subGroup.Single().Group.Key; else return subGroup.Where(x => tieBreaker(x.Group.Key)).Single().Group.Key; }
28b61500fba8aa7ff5750e64248d5017f9301b9d
C#
K-Viera/Lenguajes-y-Compiladores
/AnalizadorLexico/AnalizadorLexico/TablaSimbolos.cs
2.90625
3
using System; using System.Collections.Generic; using System.Net.NetworkInformation; using System.Runtime.CompilerServices; using System.Text; namespace AnalizadorLexico { static class TablaSimbolos { public static List<string> simbolos=new List<string>(); public static List<List<string>> tipos = new List<List<string>>(); public static List<char> excepcionesInicioIdentificadores = new List<char>(); public static void CarcarModuloPorDefecto() { AgregarSimbolo("\f", "separador"); AgregarSimbolo("\n", "separador"); } #region Simbolos public static void AgregarSimbolo(string simbolo) { if (!simbolos.Contains(simbolo)) { simbolos.Add(simbolo); List<string> tipoTemporal = new List<string>(); tipos.Add(tipoTemporal); } } public static void AgregarSimbolo(string simbolo,string tipo) { if (!simbolos.Contains(simbolo)) { simbolos.Add(simbolo); List<string> tipoTemporal = new List<string>(); tipoTemporal.Add(tipo); tipos.Add(tipoTemporal); } } public static void AgregarTipoASimbolo(string simbolo, string tipo) { int index = simbolos.IndexOf(simbolo); if (!tipos[index].Contains(tipo)) { tipos[index].Add(tipo); } } public static void EliminarSimbolo(string simbolo) { int index = simbolos.IndexOf(simbolo); simbolos.RemoveAt(index); tipos.RemoveAt(index); } #endregion } }
02f6ba511f54e39e98baecbd630d6cb05bc8a81f
C#
delokman/DevInd_1
/twschart-1-/archive/TWSLibrary/UserControls/uctlAlertCreator.cs
2.640625
3
///////REVISION HISTORY///////////////////////////////////////////////////////////////////////////////////////////////////// //DATE INITIALS DESCRIPTION //02/01/2012 VP 1.Added naming conventions comment to properties and methods //02/02/2012 VP 1.Commenting of the code /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Windows.Forms; using CommonLibrary.Cls; namespace CommonLibrary.UserControls { public partial class UctlAlertCreator : UctlBase { #region " MEMBERS " private string _title = "Alert Creator"; #endregion " MEMBERS " #region " PROPERTY " /// <summary> /// Sets and gets the title of the AlertDialog control /// </summary> public override string Title { get { return _title; } set { _title = value; } } public bool IsAlertEnabled { get { return ui_nchkEnable.Checked; } set { ui_nchkEnable.Checked = value; } } /// <summary> /// This property indicates the sound enablility. This property is both settable and gettable. /// </summary> public string Action { get { return ui_ncmbAction.SelectedItem.ToString(); } set { ui_ncmbAction.SelectedItem = value; } } /// <summary> /// This property specifies the symbol to which alert is applied. This property is both settable and gettable. /// </summary> public string Symbol { get { return ui_ncmbSymbol.SelectedItem.ToString(); } set { ui_ncmbSymbol.SelectedItem = value; } } /// <summary> /// This property specifies the source sound. This property is both settable and gettable. /// </summary> public string Source { get { return ui_ncmbSource.SelectedItem.ToString(); } set { ui_ncmbSource.SelectedItem = value; } } /// <summary> /// This property indicates the duration for alert. This property is both settable and gettable. /// </summary> public string TimeOut { get { return ui_ncmbTimeout.SelectedItem.ToString(); } set { ui_ncmbTimeout.SelectedItem = value; } } /// <summary> /// This property specifies condition. This property is both settable and gettable. /// </summary> public string Condition { get { return ui_ncmbCondition.SelectedItem.ToString(); } set { ui_ncmbCondition.SelectedItem = value; } } /// <summary> /// This property specifies the price used with condition. This property is both settable and gettable. /// </summary> public string Price { get { return ui_ntxtPrice.Text; } set { ui_ntxtPrice.Text = value; } } /// <summary> /// This property indicates no of times the alert is occurs. This property is both settable and gettable. /// </summary> public string MaximunIteration { get { return ui_ncmbMaximumIteration.SelectedItem.ToString(); } set { ui_ncmbMaximumIteration.SelectedItem = value; } } #endregion " PROPERTY " #region " CONSTRUCTOR " /// <summary> /// Constructor for initilizing the components of the uctlAlertDialog /// </summary> public UctlAlertCreator() { InitializeComponent(); } /// <summary> /// Constructor for initilizing the components of the uctlAlertDialog with customised settings /// </summary> /// <param name="customizeSettings"></param> public UctlAlertCreator(object customizeSettings) { } #endregion " CONSTRUCTOR " #region " METHODS " /// <summary> /// Sets the text of the controls corresponding the localize value /// </summary> public override void SetLocalization() { Title = ClsLocalizationHandler.Alert + " " + ClsLocalizationHandler.Create; ui_lblAction.Text = ClsLocalizationHandler.Action + " :"; ui_lblSymbol.Text = ClsLocalizationHandler.Symbol + " :"; ui_lblSource.Text = ClsLocalizationHandler.Source + " :"; ui_lblTimeOut.Text = ClsLocalizationHandler.Timeout + " :"; ui_lblCondition.Text = ClsLocalizationHandler.Condition + " :"; ui_lblPrice.Text = ClsLocalizationHandler.Price + " :"; ui_lblMaximumIteration.Text = ClsLocalizationHandler.Maximum + " " + ClsLocalizationHandler.Iteration + " :"; ui_nbtnOk.Text = ClsLocalizationHandler.Ok; ui_nbtnCancel.Text = ClsLocalizationHandler.Cancel; ui_nbtnTest.Text = ClsLocalizationHandler.Test; } #endregion " METHODS " public event Action<object, EventArgs> OnOkClick; public event Action<object, EventArgs> OnCancelClick; public event Action<object, EventArgs> OnTestClick; /// <summary> /// Invokes OnOkClick click event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ui_nbtnOk_Click(object sender, EventArgs e) { OnOkClick(sender, e); } /// <summary> /// Invokes OnCancelClick click event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ui_nbtnCancel_Click(object sender, EventArgs e) { OnCancelClick(sender, e); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ui_npnlAlertDialogContainer_Click(object sender, EventArgs e) { } /// <summary> /// Invokes OnTestClick click event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ui_nbtnTest_Click(object sender, EventArgs e) { OnTestClick(sender, e); } private void ui_ntxtPrice_KeyPress(object sender, KeyPressEventArgs e) { ClsGlobal.KeyPressHandler(ui_ntxtPrice.Text, e, TextType.Real, 50, 1); } } }
98a0b4db3f21a293a34d512c481a1bfba8b06202
C#
manuelarriolag/MockDbConnections
/MockDbConnections/Program.cs
3.1875
3
using MockDbConnections.Mocks; using NSubstitute; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Text.RegularExpressions; using System.Linq; /// <summary> /// Example program demonstrating use of NSubstitute with abstract classes to mock /// a database. /// </summary> namespace MockDbConnections { class Program { static void Main(string[] args) { // The example is of accounts and portfolios. A portfolio contains zero or // many accounts. An account belongs to one portfolio. // Maps a portfolio name to an id for the test Dictionary<string, int> portfolioIds = new Dictionary<string, int>() { {"One", 1 }, {"Two", 2 }, {"Three", 3 } }; // A set of test accounts List<object[]> testCase = new List<object[]>(); testCase.Add(new object[] { 1, 1, 2, "ABC123", 100.00m }); testCase.Add(new object[] { 2, 2, 3, "DEF456", 200.00m }); testCase.Add(new object[] { 3, 3, 2, "GHI789", 300.00m }); testCase.Add(new object[] { 4, 2, 3, "JKL012", 400.00m }); testCase.Add(new object[] { 5, 1, 3, "MNO345", 500.00m }); // Mock the logger List<string> loggerStatements = new List<string>(); var logImpl = Substitute.For<ILog>(); logImpl .When(x => x.Log(Arg.Any<string>())) .Do(x => loggerStatements.Add((string)x[0])); Logger.LoggerImpl = logImpl; // Mock a connection factory var provider = Substitute.For<IDbConnectionFactory>(); provider.CreateConnection(Arg.Any<string>()).Returns( x => { var retval = Substitute.For<ADbConnection>(); retval.ConnectionString = (string)x[0]; return retval; }); provider.CreateCommand(Arg.Any<string>(), Arg.Any<IDbConnection>()).Returns( x => { var retval = Substitute.For<ADbCommand>(); retval.CommandText = (string)x[0]; retval.Connection = (IDbConnection)x[1]; // condition the command based on the SQL statement // Is it asking for a portfolio id? var regexGetPort = new Regex(@"select id from portfolio where port_name = '(\w+)';"); if ( regexGetPort.IsMatch(retval.CommandText) ) { var mtGetPort = regexGetPort.Match(retval.CommandText); string portName = mtGetPort.Groups[1].Value; if (portfolioIds.ContainsKey(portName)) retval.ScalarResult = portfolioIds[mtGetPort.Groups[1].Value]; else retval.ScalarResult = null; } // Or is it asking for a list of accounts? var regexGetAcct = new Regex(@"select id, portfolio_id, owner_id, account_number, balance from account where portfolio_id = (\d+);"); if ( regexGetAcct.IsMatch(retval.CommandText)) { var mtGetAcct = regexGetAcct.Match(retval.CommandText); var readerResult = Substitute.For<ADataReader>(); readerResult.RowSet = testCase.Where(y => ((int)y[1]) == int.Parse(mtGetAcct.Groups[1].Value)).ToList(); retval.ReaderResult = readerResult; } return retval; }); // Create the object under test GetAccounts getAccounts = new GetAccounts(provider, "ConnectionString"); // Do a bunch of positive test cases var accts = getAccounts.GetAccountsForPortfolio("One"); Debug.Assert(accts.Count == 2); accts.ForEach(x => Debug.Assert(x.PortfolioId == 1)); accts = getAccounts.GetAccountsForPortfolio("Two"); Debug.Assert(accts.Count == 2); accts.ForEach(x => Debug.Assert(x.PortfolioId == 2)); accts = getAccounts.GetAccountsForPortfolio("Three"); Debug.Assert(accts.Count == 1); accts.ForEach(x => Debug.Assert(x.PortfolioId == 3)); // Nothing should have been logged Debug.Assert(loggerStatements.Count == 0); // Do a negative test case accts = getAccounts.GetAccountsForPortfolio("Four"); Debug.Assert(accts.Count == 0); Debug.Assert(loggerStatements.Count == 1); Debug.Assert(loggerStatements[0] == @"Could not find portfolio id for 'Four'"); loggerStatements.Clear(); // Do an exception case - should skip the bad record and return the others testCase.Insert(0, new object[] { 6, 1, 3, "PQR678", "BadValue" }); accts = getAccounts.GetAccountsForPortfolio("One"); Debug.Assert(accts.Count == 2); Debug.Assert(loggerStatements.Count == 1); Debug.Assert(loggerStatements[0].StartsWith("Caught parse exception:")); } } }
400fafcdb50512284123fbb2910ed540a3e8f39d
C#
farjadhabib/SendEmail
/SendEmail/EmailUtiity.cs
2.875
3
using System; using System.Net; using System.Net.Mail; namespace SendEmail { public class EmailUtiity { SmtpClient smtp; public EmailUtiity(string mailServer, int? port, string username, string password) { smtp = (port != null && port > 0) ? new SmtpClient(mailServer, port.Value) : new SmtpClient(mailServer); smtp.Credentials = new NetworkCredential(username, password); } public void SendEmailNotification(string to, string from, string subject, string body) { try { MailMessage mail = new MailMessage(); mail.To.Add(to); mail.Subject = subject; mail.Body = body; mail.IsBodyHtml = true; mail.From = new MailAddress(from); smtp.Send(mail); } catch (Exception ex) { throw ex; } } } }
b17c08ce6f8ac6f69c122e46b1f417a25c06bfde
C#
BenjaminGroseclose/Banking-Application
/Bank Application/Bank/Bank/Database/DataConnection.cs
2.8125
3
using System; using System.Data.SqlClient; using System.Windows; namespace Bank.Database { public class DataConnection { public SqlConnectionStringBuilder SqlConnection() { try { SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder(); connectionString.DataSource = "groseclose.database.windows.net"; connectionString.UserID = "BGroseclose"; connectionString.Password = "Hward777"; connectionString.InitialCatalog = "Bank"; return connectionString; } catch (SqlException e) { MessageBox.Show("Unable to connect to the Database." + e.Errors, "Database Connection"); Application.Current.Shutdown(); } return null; } } }
3813b4f0cb3b851e26c728126a2f95db860a5e0c
C#
adenial/TemplateCore
/src/TemplateCore/Services/AuthMessageSender.cs
2.734375
3
//----------------------------------------------------------------------- // <copyright file="AuthMessageSender.cs" company="Without name"> // Company copyright tag. // </copyright> //----------------------------------------------------------------------- namespace TemplateCore.Services { using System.Threading.Tasks; // This class is used by the application to send Email and SMS // when you turn on two-factor authentication in ASP.NET Identity. // For more details see this link http://go.microsoft.com/fwlink/?LinkID=532713 /// <summary> /// Class AuthMessageSender. /// </summary> public class AuthMessageSender : IEmailSender, ISmsSender { /// <summary> /// Sends the email asynchronous. /// </summary> /// <param name="email">The email.</param> /// <param name="subject">The subject.</param> /// <param name="message">The message.</param> /// <returns>Task.</returns> public Task SendEmailAsync(string email, string subject, string message) { // Plug in your email service here to send an email. return Task.FromResult(0); } /// <summary> /// Sends the SMS asynchronous. /// </summary> /// <param name="number">The number.</param> /// <param name="message">The message.</param> /// <returns>Task.</returns> public Task SendSmsAsync(string number, string message) { // Plug in your SMS service here to send a text message. return Task.FromResult(0); } } }
e0891a10cd6f748825496c380941d823b4d39906
C#
t4rn/ParallelWsTester
/ParallelWsTester/Program.cs
2.578125
3
using Newtonsoft.Json; using ParallelWsTester.SoapFruitLoops; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.ServiceModel; using System.Threading.Tasks; namespace ParallelWsTester { class Program { private static Dictionary<int, string> addresses = new Dictionary<int, string> { {1, "http://localhost/FruitLoops.asmx" }, {2, "http://10.0.0.10/FruitLoops.asmx" }, {3, "http://10.4.4.5/FruitLoops.asmx" }, {4, "http://10.9.100.200/FruitLoops.asmx" }, }; static void Main(string[] args) { string htmlBase64 = longHtml2; AllInParallel(htmlBase64); //PickOneServer(htmlBase64); Console.WriteLine("\nPress any key to exit..."); Console.Read(); } private static void AllInParallel(string htmlBase64) { Task.Run(async () => { var taskList = new List<Task>(); foreach (var addr in addresses) { Task t = new Task(() => { ConvertHtmlToPdf(htmlBase64, addr.Value); }); taskList.Add(t); t.Start(); } await Task.WhenAll(taskList); }).GetAwaiter().GetResult(); } private static void PickOneServer(string htmlBase64) { Console.WriteLine($"Which server: {JsonConvert.SerializeObject(addresses, Formatting.Indented)}"); string wsAddress = null; string input = Console.ReadLine(); bool isOk = addresses.TryGetValue(Convert.ToInt32(input), out wsAddress); if (!isOk) { Console.WriteLine($"Bad input = '{input}'"); Console.Read(); return; } ConvertHtmlToPdf(htmlBase64, wsAddress); } private static void ConvertHtmlToPdf(string html, string addr) { using (var client = new FruitLoopsSoapClient()) { client.Endpoint.Address = new EndpointAddress(addr); Console.WriteLine($"{DateTime.Now} -> Start for '{addr}'"); Stopwatch stopwatch = Stopwatch.StartNew(); var result = client.ConvertHTML(html); if (result.isOK) { byte[] fileInBytes = Convert.FromBase64String(result.PdfContent); File.WriteAllBytes($"{client.Endpoint.Address.Uri.Host}.pdf", fileInBytes); } result.PdfContent = $"ContentLength: {result.PdfContent?.Length}"; string resultJson = JsonConvert.SerializeObject(result); Console.WriteLine($"{DateTime.Now} -> End for '{addr}': {resultJson} in '{stopwatch.Elapsed:hh\\:mm\\:ss}'"); } } private const string longHtml1 = "77u/yj4WST1ejgwJreTzAUw2yj4WST1ejgwJreTzAUw2yj4WST1ejgwJreTzAUw2yj4WST1ejgwJreTzAUw2"; private const string longHtml2 = "77u/gc89p564IHrMRvQZivtlgc89p564IHrMRvQZivtlgc89p564IHrMRvQZivtlgc89p564IHrMRvQZivtl"; } }
8ab9cb9eca02feee8d427e3781505d503c536f2d
C#
zebenman/DECO3801-Synergistics
/Synergystics/Assets/Scripts/Utilities.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using TMPro; using UnityEngine; using UnityEngine.UI; public static class Utilities { // A nice dark grey colour public static readonly Color DarkGrey = new Color(66f / 255f, 66f / 255f, 66f / 255f); // Some map sources public static readonly string[] MapSources = { "FARM", "TOWN_MARKET", "MONASTERY", "TAVERN", "BARRACKS", "DUNGEON" }; // Recursively set UI widget colours, ignoring certain objects public static void SetWidgetColorRecursive(GameObject root, Color color, params GameObject[] ignore) { if (ignore.Contains(root)) { return; } SetWidgetColor(root, color); // Set all child widget colours for (int i = 0; i < root.transform.childCount; i++) { SetWidgetColorRecursive(root.transform.GetChild(i).gameObject, color, ignore); } } // Set a widgets colour public static void SetWidgetColor(GameObject root, Color color) { // Check images and text Image rootImage = root.GetComponent<Image>(); TextMeshProUGUI rootText = root.GetComponent<TextMeshProUGUI>(); if (rootImage != null) { rootImage.color = color; } if (rootText != null) { rootText.color = color; } } // An indexed for-each enumerator public static IEnumerable<(int index, T value)> IndexedForeach<T>(this IEnumerable<T> self) { for(int i = 0; i < self.Count(); i++) { yield return (i, self.ElementAt(i)); } } // I actually have no idea what this does anymore public static IEnumerable<T> SelectRandom<T>(this IEnumerable<T> self, int count) { if (count <= 0) return null; List<int> indices = new List<int>(); count = Mathf.Min(count, self.Count()); for(int i = 0; i < count; i++) { int nextValue; do { nextValue = UnityEngine.Random.Range(0, self.Count()); } while (indices.Contains(nextValue)); indices.Add(nextValue); } return indices.Select(x => self.ElementAt(x)); } // Get the traits for each advisor type public static (AdvisorTrait a, AdvisorTrait b) GetTraitByType(this AdvisorType type) { switch(type) { case AdvisorType.MILITARY: return (AdvisorTrait.DIPLOMATIC, AdvisorTrait.WAR_MONGERING); case AdvisorType.SCHOLAR: return (AdvisorTrait.PRESTIGIOUS, AdvisorTrait.CONNIVING); case AdvisorType.AGRICULTURAL: return (AdvisorTrait.GREEDY, AdvisorTrait.DOWN_TO_EARTH); case AdvisorType.ECONOMICS: return (AdvisorTrait.PERCEPTIVE, AdvisorTrait.SENSIBLE); case AdvisorType.INTELLIGENCE: return (AdvisorTrait.CONSCIENTIOUS, AdvisorTrait.GULLIBLE); case AdvisorType.FOREIGN: return (AdvisorTrait.SUBTLE, AdvisorTrait.UPFRONT); } throw new ArgumentException("Illegal advisor type"); } }
4151369a236dcaea58080fa3ae6f1853512577c1
C#
razuk-78/DotNetExamples
/MVC/UnitTest/TestEntity.cs
2.640625
3
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System.Web.Mvc; using System.Reflection; using MVC.Models; using System.Data.Entity; using System.Linq; using System.Collections.Generic; using TestingDemo; namespace MVC.UnitTest { // https://docs.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking [TestClass] public class TestEntity { Mock<DbSet<Blog>> MockBlogs; Mock<BloggingContext> mockContext ; [TestInitialize] public void SetUp() { mockContext = new Mock<BloggingContext>(); MockBlogs = new Mock<DbSet<Blog>>(); } [TestMethod] public void test() { var data = new List<Blog> { new Blog { Name = "BBB" }, new Blog { Name = "ZZZ" }, new Blog { Name = "AAA" }, }.AsQueryable(); MockBlogs.As<IQueryable<Blog>>().Setup(e => e.Provider).Returns(data.Provider); MockBlogs.As<IQueryable<Blog>>().Setup(e => e.Expression).Returns(data.Expression); MockBlogs.As<IQueryable<Blog>>().Setup(e => e.ElementType).Returns(data.ElementType); MockBlogs.As<IQueryable<Blog>>().Setup(e => e.GetEnumerator()).Returns(data.GetEnumerator()); } [TestMethod] public void testBlogRepo() { var data = new List<Blog> { new Blog { Name = "ABBB" }, new Blog { Name = "ZZZ" }, new Blog { Name = "AAA" }, }.AsQueryable(); var post = new List<MVC.Models.Post> { new Post{} }.AsQueryable(); MockBlogs.As<IQueryable<Blog>>().Setup(e => e.Provider).Returns(data.Provider); MockBlogs.As<IQueryable<Blog>>().Setup(e => e.Expression).Returns(data.Expression); MockBlogs.As<IQueryable<Blog>>().Setup(e => e.ElementType).Returns(data.ElementType); MockBlogs.As<IQueryable<Blog>>().Setup(e => e.GetEnumerator()).Returns(data.GetEnumerator()); mockContext.Setup(e => e.Blogs).Returns(MockBlogs.Object); BlogRepo blog = new BlogRepo(mockContext.Object); Assert.AreEqual(blog.GetBlogsByName(e=>e.Name.StartsWith("A")).Count,2); } [TestMethod] public void CreateBlog_saves_a_blog_via_context() { var mockSet = new Mock<DbSet<Blog>>(); var mockContext = new Mock<BloggingContext>(); mockContext.Setup(m => m.Blogs).Returns(mockSet.Object); var service = new BlogRepo(mockContext.Object); service.AddBlog("ADO.NET Blog", "http://blogs.msdn.com/adonet"); mockSet.Verify(m => m.Add(It.IsAny<Blog>()), Times.Once()); mockContext.Verify(m => m.SaveChanges(), Times.Once()); } [TestMethod] public void CreateDb() { BloggingContext bloggingContext = new BloggingContext(); } } }
d61127709d647c012766ca81426d0ac80d33396f
C#
noahmpauls/advent-of-code-2020
/days/Day16.cs
2.890625
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace days { public class Day16 { //###################################################################### // Part 1 + 2 Solutions //###################################################################### public static int Part1() { const string path = Helpers.inputPath + @"\day16\input.txt"; string input = ProcessInputFile(path); IList<TicketValidator.Rule> rules = ParseRules(input); TicketValidator validator = new TicketValidator(); validator.AddRules(rules); IList<IList<int>> tickets = ParseNearbyTickets(input); int errorRate = 0; foreach (var ticket in tickets) { foreach (int val in ticket) { if (!validator.ValidateValue(val)) { errorRate += val; } } } return errorRate; } public static long Part2() { const string path = Helpers.inputPath + @"\day16\input.txt"; string input = ProcessInputFile(path); IList<TicketValidator.Rule> rules = ParseRules(input); TicketValidator validator = new TicketValidator(); validator.AddRules(rules); IList<int> myTicket = ParseYourTicket(input); IList<IList<int>> nearbyTickets = ParseNearbyTickets(input); IList<string> fieldOrder = FindFieldOrder(validator, nearbyTickets); long result = 1; for (int i = 0; i < myTicket.Count; i++) { if (fieldOrder[i].StartsWith("departure")) result *= (long)myTicket[i]; } return result; } //###################################################################### // Methods //###################################################################### public static string ProcessInputFile(string path) { return Helpers.GetFileAsString(path); } public static IList<TicketValidator.Rule> ParseRules(string text) { var result = new List<TicketValidator.Rule>(); // assumes a single name and exactly two bounds Regex rx = new Regex("(?<rule>[a-z ]+): (?<bound1>(?<min1>[0-9]+)-(?<max1>[0-9]+)) or (?<bound2>(?<min2>[0-9]+)-(?<max2>[0-9]+))"); foreach (Match m in rx.Matches(text)) { string name = m.Groups["rule"].Value; int min1 = int.Parse(m.Groups["min1"].Value); int max1 = int.Parse(m.Groups["max1"].Value); int min2 = int.Parse(m.Groups["min2"].Value); int max2 = int.Parse(m.Groups["max2"].Value); var rule = new TicketValidator.Rule { Name = name }; rule.AddBound(min1, max1); rule.AddBound(min2, max2); result.Add(rule); } return result; } public static IList<IList<int>> ParseNearbyTickets(string text) { var result = new List<IList<int>>(); Regex rxTicketBlock = new Regex(@"nearby tickets:\s+(?<tickets>([0-9]+[,\s]+)+)"); string ticketBlock = rxTicketBlock.Match(text).Value; Regex rxTicket = new Regex(@"(([0-9]+),?)+"); foreach(Match ticket in rxTicket.Matches(ticketBlock)) { IList<int> ticketVals = ticket.Value.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(v => int.Parse(v)).ToList(); result.Add(ticketVals); } return result; } public static IList<int> ParseYourTicket(string text) { Regex rxTicketBlock = new Regex(@"your ticket:\s+(?<ticket>([0-9]+,?)+)"); string ticket = rxTicketBlock.Match(text).Groups["ticket"].Value; return ticket.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(v => int.Parse(v)).ToList(); } public static IList<string> FindFieldOrder(TicketValidator validator, IList<IList<int>> tickets) { IList<IList<int>> validTickets = tickets.Where(t => validator.ValidateValues(t)).ToList(); int fieldCount = tickets[0].Count; var fieldIndices = new Dictionary<string, ISet<int>>(); foreach (string field in validator.Rules) { var indices = new HashSet<int>(Enumerable.Range(0, fieldCount)); fieldIndices.Add(field, indices); } IList<string> result = new List<string>(); foreach (int i in Enumerable.Range(0, fieldCount)) result.Add("NONE"); // find which indices the field cannot be due to values breaking rules foreach (var ticket in validTickets) { for (int i = 0; i < fieldCount; i++) { int val = ticket[i]; IList<string> invalidFields = validator.RulesBroken(val); foreach (string field in invalidFields) { fieldIndices[field].Remove(i); } } } // deduce index assignments from remaining possible values var assignedIndices = new HashSet<int>(); bool unassignedExists = false; do { unassignedExists = false; foreach (var field in fieldIndices) { // unassigned; ExceptWith removes any indices already assigned if (field.Value.Count > 1) { unassignedExists = true; field.Value.ExceptWith(assignedIndices); } // otherwise assign index else { assignedIndices.Add(field.Value.First()); result[field.Value.First()] = field.Key; } } } while (unassignedExists); return result; } } //########################################################################## // Helper Classes //########################################################################## // public class Day/* day */Result : DayResult<void, void> { } public class TicketValidator { private IDictionary<string, Rule> rules = new Dictionary<string, Rule>(); public IList<string> Rules { get { return rules.Values.Select(r => r.Name).ToList(); } } public void AddRule(string name) { if (!rules.ContainsKey(name)) rules.Add(name, new Rule { Name = name }); } public void AddRule(string name, int min, int max) { if (!rules.ContainsKey(name)) rules.Add(name, new Rule { Name = name }); rules[name].AddBound(min, max); } public void AddRule(string name, IEnumerable<Tuple<int, int>> bounds) { if (!rules.ContainsKey(name)) rules.Add(name, new Rule { Name = name }); foreach (var b in bounds) { rules[name].AddBound(b.Item1, b.Item2); } } public void AddRule(Rule rule) { if (!rules.ContainsKey(rule.Name)) rules.Add(rule.Name, rule); else rules[rule.Name] = rule; } public void AddRules(IEnumerable<Rule> newRules) { foreach(var rule in newRules) { AddRule(rule); } } public bool ValidateValue(int value) { foreach (var rule in rules.Values) { if (rule.Inbounds(value)) return true; } return false; } public bool ValidateValues(IEnumerable<int> values) { foreach (var value in values) { if (!ValidateValue(value)) return false; } return true; } public IList<string> RulesBroken(int value) { IList<string> result = new List<string>(); foreach (var rule in rules.Values) { if (!rule.Inbounds(value)) result.Add(rule.Name); } return result; } public class Rule { private IList<Tuple<int, int>> bounds = new List<Tuple<int, int>>(); public string Name { get; set; } public void AddBound(int min, int max) { bounds.Add(new Tuple<int, int>(min, max)); } public bool Inbounds(int value) { foreach(var b in bounds) { if (b.Item1 <= value && value <= b.Item2) return true; } return false; } } } }
be0ecb5964ec2a87f669705575225b0643ea75eb
C#
erbelair/HashtagSearch
/TwitterClientLibrary/Services/SearchService.cs
3.15625
3
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TwitterClientLibrary.Services { /// <summary> /// Service to search tweets. /// </summary> public class SearchService : BaseTwitterService, ISearchService { /// <summary> /// Initializes a new <see cref="SearchService"/>. /// </summary> /// <param name="client">Client to send our requests.</param> public SearchService(TwitterClient client) : base(client) { } /// <summary> /// Search for tweets containing a hashtag. /// </summary> /// <param name="hashtag">Hashtag to search for.</param> /// <param name="count">Number of tweets to return.</param> /// <param name="maxId">Tweet ID to end at.</param> /// <returns>List of matching tweets.</returns> public async Task<SearchResponse> GetByHashtagAsync(string hashtag, int count, long? maxId) { if (string.IsNullOrWhiteSpace(hashtag)) { return null; } if (hashtag.Substring(0, 1) != "#") { hashtag = "#" + hashtag; } var request = new SearchRequest(hashtag, count, maxId); var response = await Client.GetResponseAsync(Endpoints.Search, request.ToDictionary()); if (response.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<SearchResponse>(await response.Content.ReadAsStringAsync()); } else { return null; } } } }
0ca478b5e1d220313cdf67d1ef6b736cec4d7c3d
C#
ddmryrk/DesignPatternPractices
/02-FactoryMethod/Factorymethod.cs
3.53125
4
using _02_FactoryMethod.Interfaces; using System; namespace _02_FactoryMethod { class Factorymethod { /// Bu pattern ile loglamayı yönetecek fabrikalar yaratıyoruz. /// Sınıflar çıplak olmamalıdır. Interfacelerden türetilip soyutlanması gerekir. /// Fabrikaları da interfaceler ile soyutlayarak daha esnek bir yapı kuruyoruz. /// new ile oluşturulan her nesneye bağımlıyız. Bu yüzden soyutlamamız gerekir. static void Main(string[] args) { CustomerManager customerManager = new CustomerManager(new LoggerFactory2()); customerManager.Save(); Console.ReadLine(); } } public class CustomerManager { private ILoggerFactory _loggerFactory; public CustomerManager(ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; } public void Save() { Console.WriteLine("Saved!"); ILogger logger = _loggerFactory.CreateLogger(); logger.Log(); } } public class LoggerFactory : ILoggerFactory { public ILogger CreateLogger() { //Business to decide factory return new EdLogger(); } } public class LoggerFactory2 : ILoggerFactory { public ILogger CreateLogger() { //Business to decide factory return new Log4NetLogger(); } } public class EdLogger : ILogger { public void Log() { Console.WriteLine("Logged with EdLogger"); } } public class Log4NetLogger : ILogger { public void Log() { Console.WriteLine("Logged with Log4NetLogger"); } } }
f5b860b3d8bca6de5218d9cc1ee9ed6a6c8899ce
C#
GreysonWright/Date-Checker
/Date Check Tool/Date Check Tool/DataBaseTools.cs
3.03125
3
//Very wow such great efficiency using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Data; using System.Data.OleDb; using System.Windows; namespace Date_Check_Tool { public delegate void ProgressUpdated(object sender, DBToolsProgressUpdatedEventArgs e); //Somehow this lets us callback to the mainwindow when progress changes public delegate void FatalError(object sender, DBToolsFatalErrorEventArgs e); //Somehow this lets us callback to the mainwindow when we get a bad error class DataBaseTools { bool shouldAbort = false; //This flag is checked in case we catch a bad error public event ProgressUpdated progressUpdated; //progressUpdated event definition public event FatalError didReceiveFatalError; //didReceiveFatalError definition const int Link_Table = 0; //Link table index const int STN_Date_Table = 1; //STN table index const int WISLR_Date_Table = 2; //WISLR table index //Reads in all fields from each of the tables the user has selected public DataTable[] getDataTables(string[] filePaths, string[] tables) { List<DataTable> dataTables = new List<DataTable>(); progressUpdated(this, new DBToolsProgressUpdatedEventArgs(0, "Reading Tables")); //Report initial progress so the textblock text is set for (int i = 0; i < filePaths.Length; i++) //iterate the filepaths list { dataTables.Add(getDataTable(filePaths[i], tables[i])); //Gets the datatable from the table name at the filepath progressUpdated(this, new DBToolsProgressUpdatedEventArgs(Convert.ToInt32(i / Convert.ToDouble(filePaths.Length - 1) * 100), "Reading Tables")); //Fire the progressUpdated event } return dataTables.ToArray(); //Return the datatables list as an array } //Returns a datatable from the filepath with the table name public DataTable getDataTable(string filePath, string table) { List<string> dbConnectionStrings = new List<string>(); List<string> selectionQueries = new List<string>(); DataTable dataTable = new DataTable(); using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath)) using (OleDbCommand selectTablesCommand = new OleDbCommand("Select *FROM [" + table + "]", connection)) //When we use the "using" like this OleDBConnection and OleDBCommand will be released once we are done with it and our connection is closed { connection.Open(); //Open a connection to the database file containing the selected table OleDbDataReader reader = selectTablesCommand.ExecuteReader(); //Create a dbreader from the dbcommand dataTable.Load(reader); //Read in the opened datatable and store it as a datatable object } return dataTable; //Return the datatable } //Returns a link array with start and end valid dates public Link[] getLinksWithDates(string[] filePaths, string[] tables) { List<Link> links = new List<Link>(); DataTable[] dataTables = getDataTables(filePaths, tables); //get the table the user has selected List<DataRow> stnRows = dataTables[STN_Date_Table].Rows.Cast<DataRow>().ToList(); List<DataRow> wislrRows = dataTables[WISLR_Date_Table].Rows.Cast<DataRow>().ToList(); double progress = 0.0; Parallel.For(0, dataTables[0].Rows.Count, (i, loopState) => //Parallel for loops are awesome because they do stuff asynchronously { switch (shouldAbort) //Check if we should abort before every iteration (switches are faster so im using it instead of an if) { case false: //Shouldn't abort try //This may fail if the user didn't select the tables in the correct sequence { //Get the stn and wislr id from the link_link (first) table string stnId = dataTables[Link_Table].Rows[i].ItemArray[0].ToString(); string wislrId = dataTables[Link_Table].Rows[i].ItemArray[3].ToString(); Link link = new Link(dataTables, i);//Create a link from the tables and current row links.Add(link); //Add the newly created link to the links list //!!!! try to make the lists shorter as we go progressUpdated(this, new DBToolsProgressUpdatedEventArgs(Convert.ToInt32(++progress / Convert.ToDouble(dataTables[0].Rows.Count) * 100), "Comparing Dates")); //Fire the progress updated event } catch (Exception e) //Oh no... this shouldn't happen { Console.WriteLine(e); shouldAbort = true; //We have to stop this madness! didReceiveFatalError(this, new DBToolsFatalErrorEventArgs("This exception is usually thrown when the link, WISLR, and STN tables are not opened in the correct order, or an STN or WISLR date cannot be found in the STN or WISLR date table. Crashed on row " + (i + 1) + ".")); //Fire the fatal error event and prepare for death } break; default: //Noooooooooooo we have failed loopState.Break(); // basically this is the same as saying break; in a normal forloop break; } }); return links.ToArray(); //We're doing great so far return the completed links array containing links with start and end valid dates } //The moment we've all been waiting for! Writes dates to the first table in the tables array (remember thats the array in mainwindow.cs that gets passed into every method above this) public void writeDatesToTable(Link[] links, string filePath, string table) { string[] columns = { "Start_Valid", "End_Valid" }; //Define our start and end valid column names try { //Something may break here but we hope not using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath)) //Create a connection! { connection.Open(); foreach (string column in columns) //Iterate over the column array these next several is absolutely hideous but it must be done or we crash =/ { using (OleDbCommand insertCommand = new OleDbCommand("UPDATE " + table + " SET " + column + " = @date WHERE STNid = @stnId AND WISLRid = @wislrId", connection)) //When we use the "using" like this OleDBConnection should be discarded once it's done { OleDbDataAdapter dataAdapter = new OleDbDataAdapter(insertCommand); //Add parameters to write values in tables the date is written while the stn and wislr ids are used to lookup rows insertCommand.Parameters.AddWithValue("@date", ""); insertCommand.Parameters.AddWithValue("@stnId", ""); insertCommand.Parameters.AddWithValue("@wislrId", ""); for (int i = 0; i < links.Length; i++) //Begin iteration over links { Link link = links[i]; switch (column == columns[0]) //This kinda looks bad probably could've been done better { case true: //If is start valid //Set values of sql parameters (this all probably should be in a method) insertCommand.Parameters["@date"].Value = link.usedStartDate; insertCommand.Parameters["@stnId"].Value = link.stnId; insertCommand.Parameters["@wislrId"].Value = link.wislrId; insertCommand.ExecuteNonQuery(); //Executes the query built from the insertCommand and these params break; default: //end valid switch (string.IsNullOrEmpty(link.usedEndDate)) //Check if we have a date { case false: //Write the date if we have one //Set values of sql parameters (this all probably should be in a method) insertCommand.Parameters["@date"].Value = link.usedEndDate; insertCommand.Parameters["@stnId"].Value = link.stnId; insertCommand.Parameters["@wislrId"].Value = link.wislrId; insertCommand.ExecuteNonQuery(); //Executes the query built from the insertCommand and these params break; default: //If both dates were null do nothing (if we try to write a blank date here it crashes because its not in date format... break; } break; } progressUpdated(this, new DBToolsProgressUpdatedEventArgs(Convert.ToInt32(i / Convert.ToDouble(links.Length - 1) * 100), "Writing to " + column)); //Fire the progressUpdated event } } } } } catch(Exception ex) //Maybe this won't happen so late in the process { Console.WriteLine(ex); shouldAbort = true; //Let us not continue for we have failed didReceiveFatalError(this, new DBToolsFatalErrorEventArgs("An error occurred during the write process. Please make sure the Microsoft Access file being modified was not moved or deleted during the process.")); //Heres our pretty general error message } } public void writeToTable(DataTable table, string filePath) { using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath)) using (OleDbCommand createCommand = new OleDbCommand("CREATE TABLE [Date_Errors]([STNID] number, [WISLRID] number, [START_VALID] text, [END_VALID] text)", connection)) using (OleDbCommand deleteCommand = new OleDbCommand("DROP TABLE [Date_Errors]", connection)) using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter("Select *FROM [Date_Errors]", "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath)) using (OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dataAdapter)) { Console.WriteLine("rows" + table.Rows.Count); connection.Open(); try { createCommand.ExecuteNonQuery(); } catch(Exception ex) { deleteCommand.ExecuteNonQuery(); createCommand.ExecuteNonQuery(); Console.WriteLine(ex); } dataAdapter.AcceptChangesDuringFill = true; dataAdapter.Fill(table); dataAdapter.Update(table); } } //Returns an array containing table names for each of the tables in the hopefully existing access file (usually called to populate comboboxes) public string[] getTableNames(string filePath) { //I don't think this method needs to be asynchronous but I don't know List<string> tableNames = new List<string>(); try { using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath)) //When we use the "using" like this OleDBConnection will not be disposed once its done we hope { string[] restrictions = new string[4]; //I'm not really sure what this does or how this works but if we don't put restrictions it doesn't return our table names correctly restrictions[3] = "Table"; //Again I have no idea what's going on here or why we'r setting the last index to table connection.Open(); DataTable tables = connection.GetSchema("Tables", restrictions); //Somehow returns a datatable containing rows containing table names connection.Close(); foreach (DataRow row in tables.Rows) //Iterate over the rows in the table we got from the access file { tableNames.Add(row.ItemArray[2].ToString()); //In this case (and hopefully every case) the table names where in the third column so this adds them to the tablename list } } } catch(Exception ex) //This won't happen normally unless the users attempts to open that annoying temporary file access puts on the desktop when a file is open otherwise this shouldn't be possible { Console.WriteLine(ex); MessageBox.Show("Make sure that the file you are attempting to open is a Microsoft Access file.", "The file could not be opened.", MessageBoxButton.OK, MessageBoxImage.Error); //This isn't fatal! display the messagebox } return tableNames.ToArray(); //Everything worked lets return our tableNames } //Writes the start and end valid dates to the first table in the first file public void populateDates(string[] filePaths, string[] tables) { Link[] links = getLinksWithDates(filePaths, tables); //Creates a link array with links that have start and end valid dates if (!shouldAbort) //Check if we should continue { writeDatesToTable(links, filePaths[0], tables[0]); //Write the dates to the first table in the first file specified by the user } } } //These EventArgs subclasses allow us to pass things to the event public class DBToolsProgressUpdatedEventArgs: EventArgs { public int progress { get; } //Define our progress readonly property (displayed via progress bar) public string currentProcess { get; } //Define our process readonly property (displayed via label above progress bar) public DBToolsProgressUpdatedEventArgs(int progress, string process) { this.progress = progress; currentProcess = process; } } public class DBToolsFatalErrorEventArgs : EventArgs { public string error { get; } //Deine our error readonly property (displayed in body of messagebox) public DBToolsFatalErrorEventArgs(string errorText) { error = errorText; } } }
6b5fa3e9d9b012ea07924cfe4659d5e79525fe59
C#
krasiIvanov/SoftUni
/Projects/OOPDefiningClasses/CompanyRoster/Program.cs
3.53125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CompanyRoster { class Employee { public string name; public decimal salary; public string position; public string department; public string email; public int age; public Employee(string name,decimal salary,string position,string department,string email,int age) { this.name = name; this.salary = salary; this.position = position; this.department = department; this.email = email; this.age = age; } public Employee(string name, decimal salary, string position, string department):this(name,salary,position,department, @"n/a", -1) { } } class Program { static void Main(string[] args) { int numberOfEmployees = int.Parse(Console.ReadLine()); List<Employee> listWithEmployees = new List<Employee>(); for (int i = 0; i < numberOfEmployees; i++) { string[] employees = Console.ReadLine().Split(); string name = employees[0]; decimal salary = decimal.Parse(employees[1]); string position = employees[2]; string department = employees[3]; string email; int age; var newEmployee = new Employee(name, salary, position, department); if (employees.Length>4) { if (employees[4].Contains("@")) { email = employees[4]; newEmployee.email = email; } else { age = int.Parse(employees[4]); newEmployee.age = age; } } if (employees.Length>5) { age = int.Parse(employees[5]); newEmployee.age = age; } listWithEmployees.Add(newEmployee); } var result = listWithEmployees.GroupBy(e => e.department) .Select(e => new { Department = e.Key, AvaregeSalary = e.Average(emp => emp.salary), Employees = e.OrderByDescending(emp => emp.salary) }).FirstOrDefault(); Console.WriteLine($"Highest Average Salary: {result.Department}"); foreach (var emp in result.Employees) { Console.WriteLine($"{emp.name} {emp.salary:f2} {emp.email} {emp.age}"); } } } }
a07882ae705ee77729642a546d4b6743fdda0e81
C#
Mikegrann/DragonTD
/DragonTD/Sprite.cs
3.03125
3
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; namespace DragonTD { class Sprite { public Texture2D Texture; public Color Color; public Sprite(Texture2D texture, Color color) { Texture = texture; Color = color; } //making this virtual allows the subclass's overridden draw method to be called even if it gets referenced as the superclass. //https://msdn.microsoft.com/en-us/library/aa645767(v=vs.71).aspx public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch, Vector2 position, Vector2 origin, float rotation = 0f, float scale = 0f, SpriteEffects effects = SpriteEffects.None, float layerDepth = 0f) { spriteBatch.Draw(Texture, position, null, Color, rotation, origin, scale, effects, layerDepth); } } }
8a0fbffb76d0a8691a27d5d30144cf9778128632
C#
Uncle-Uee/jellyfish-lite
/Assets/JellyFish-Lite/Scripts/Runtime/Internal/Monitoring/ScreenSize/ScreenSizeMonitor.cs
2.6875
3
/** * Created By: Ubaidullah Effendi-Emjedi * LinkedIn : https://www.linkedin.com/in/ubaidullah-effendi-emjedi-202494183/ */ using System; using System.Collections; using JellyFish.Internal.Utilities; using UnityEngine; // ReSharper disable once CheckNamespace namespace JellyFish.Monitor.ScreenSize { public class ScreenSizeMonitor : MonoBehaviour { #region VARIABLES /// <summary> /// Monitor Screen Resolutions /// </summary> [Header("Status")] public bool MonitorResolution = false; /// <summary> /// Only Calculate World Size Flag. /// </summary> [Header("Settings")] public bool OnlyCalculateWorldSize = false; /// <summary> /// Only Calculate Screen Size Flag. /// </summary> public bool OnlyCalculateScreenSize = false; /// <summary> /// Game Camera Reference /// </summary> [Header("Game Camera Reference")] public CameraReference GameCamera; /// <summary> /// Resolution State. /// </summary> [Header("Resolution State")] public ResolutionState ResolutionState; /// <summary> /// Current Screen Size /// </summary> private Vector2Int _currentScreenSize; /// <summary> /// Previous Screen Size. /// </summary> private Vector2Int _previousScreenSize; /// <summary> /// Current World Size /// </summary> private Vector2 _currentWorldSize; /// <summary> /// Previous World Size. /// </summary> private Vector2 _previousWorldSize; /// <summary> /// On Start Monitoring Event /// </summary> private static event Action OnStartMonitoring; /// <summary> /// On Stop Monitoring Event. /// </summary> private static event Action OnStopMonitoring; #endregion #region UNITY METHODS private void OnEnable() { StartMonitoring(); OnStartMonitoring += StartMonitoring; OnStopMonitoring += StopMonitoring; } private void OnDisable() { StopMonitoring(); OnStartMonitoring -= StartMonitoring; OnStopMonitoring -= StopMonitoring; } #endregion #region SCREEN SIZE MONITOR METHODS /// <summary> /// Calculate the World and Screen Size. /// </summary> /// <param name="cameraPixelRect"></param> /// <param name="orthographicSize"></param> /// <param name="aspect"></param> /// <returns></returns> private IEnumerator ScreenSizeAndWorldBounds() { while (MonitorResolution) { CalculateScreenSizeAndWorldBounds(GameCamera.Camera.pixelRect, GameCamera.Camera.orthographicSize, GameCamera.Camera.aspect); yield return null; } } /// <summary> /// Calculate the World and Screen Size. /// </summary> private void CalculateScreenSizeAndWorldBounds(Rect cameraPixelRect, float orthographicSize, float aspect) { if (OnlyCalculateWorldSize) { CalculateWorldSize(orthographicSize, aspect); } if (OnlyCalculateScreenSize) { CalculateScreenResolution(cameraPixelRect); } } /// <summary> /// Calculate the World Size. /// </summary> /// <param name="orthographicSize"></param> /// <param name="aspect"></param> private void CalculateWorldSize(float orthographicSize, float aspect) { _currentWorldSize.y = orthographicSize; _currentWorldSize.x = _currentWorldSize.y * aspect; if (Mathf.Approximately(_currentWorldSize.x, _previousWorldSize.x) && Mathf.Approximately(_currentWorldSize.y, _previousWorldSize.y)) return; _previousWorldSize.y = _currentWorldSize.y; _previousWorldSize.x = _currentWorldSize.x; ResolutionState.CurrentWorldScreenSize = _previousWorldSize; print("World Size Changed!"); } /// <summary> /// Calculate the Screen Resolution. /// </summary> /// <param name="cameraPixelRect"></param> private void CalculateScreenResolution(Rect cameraPixelRect) { _currentScreenSize.x = (int) cameraPixelRect.width; _currentScreenSize.y = (int) cameraPixelRect.height; if (_currentScreenSize.x == _previousScreenSize.x || _currentScreenSize.y == _previousScreenSize.y) return; _previousScreenSize.x = _currentScreenSize.x; _previousScreenSize.y = _currentScreenSize.y; ResolutionState.CurrentScreenResolution = _previousScreenSize; print("Screen Resolution Changed!"); } /// <summary> /// Bound a Transform within the World. /// </summary> /// <param name="localPosition"></param> /// <returns></returns> public void BoundWithinScreen(ref Vector3 localPosition) { float worldWidth = ResolutionState.CurrentWorldScreenSize.x; float worldHeight = ResolutionState.CurrentWorldScreenSize.y; localPosition.y = Mathf.Clamp(localPosition.y, -worldHeight, worldHeight); localPosition.x = Mathf.Clamp(localPosition.x, -worldWidth, worldWidth); } private void StartMonitoring() { MonitorResolution = true; StopCoroutine(ScreenSizeAndWorldBounds()); StartCoroutine(ScreenSizeAndWorldBounds()); } private void StopMonitoring() { MonitorResolution = false; StopCoroutine(ScreenSizeAndWorldBounds()); } /// <summary> /// Call Start Monitoring Coroutine /// </summary> public static void CallStartMonitoring() { OnStartMonitoring?.Invoke(); } /// <summary> /// Call Stop Monitoring Coroutine /// </summary> public static void CallStopMonitoring() { OnStopMonitoring?.Invoke(); } #endregion } }
430091752fc925fcff7c4ae9a2911c411ac6dae7
C#
yifan86226/HRManageSystem
/CO_IA.Data.Portable/WorkLog/WorkLogQueryCondition.cs
2.53125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace CO_IA.Data { public class WorkLogQueryCondition : INotifyPropertyChanged { public WorkLogQueryCondition() { int date = DateTime.Today.Day; WorkDateFrom = DateTime.Today.Date.AddDays(1 - date); WorkDateTo = WorkDateFrom.AddMonths(1).AddMinutes(-1); } public string ActivityGuid { get; set; } private string title; public string Title { get { return this.title; } set { this.title = value; this.NotifyPropertyChanged("Title"); } } private DateTime workdateFrom; public DateTime WorkDateFrom { get { return this.workdateFrom; } set { this.workdateFrom = value; this.NotifyPropertyChanged("WorkDateFrom"); } } private DateTime workdateTo; public DateTime WorkDateTo { get { return this.workdateTo; } set { this.workdateTo = value; this.NotifyPropertyChanged("WorkDateTo"); } } private string worker; public string Worker { get { return this.worker; } set { this.worker = value; this.NotifyPropertyChanged("Worker"); } } private string description; public string Description { get { return this.description; } set { this.description = value; this.NotifyPropertyChanged("Description"); } } public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string propertyname) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyname)); } } } }
83c791768a6392c7e3076317b8315a34f6a8841c
C#
samuilll/Softuni_ProgrammingFundamentals
/PrgrammingFundametnalsFast/03_DataTypesAndVariables/Task19TheaThePhotographer/Task19TheaThePhotographer.cs
3.1875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task19TheThePhotographer { class Task19TheThePhotographer { static void Main(string[] args) { long numberOfPictures = long.Parse(Console.ReadLine()); long filterTime = long.Parse(Console.ReadLine()); long filterFactor = long.Parse(Console.ReadLine()); long uploadTimeForPicture = long.Parse(Console.ReadLine()); long usefulPictures = (long)Math.Ceiling((double)filterFactor / 100 * numberOfPictures); long allUploadTime = uploadTimeForPicture * usefulPictures; long allTime = allUploadTime + filterTime * numberOfPictures; //Console.WriteLine(usefulPictures); // Console.WriteLine(allUploadTime); // Console.WriteLine(allTime); long days = allTime / 60 / 60 / 24; long hours = (allTime / 60 / 60) % 24; long minutes = (allTime / 60) % 60; long seconds = allTime % 60; Console.WriteLine($"{days}:{hours:D2}:{minutes:d2}:{seconds:d2}"); } } }
904c63effd3cf79176d9f236824db03f302f4ed8
C#
yassine68/FirstProjectWith.NET5
/MyMusic.Services/Services/MusicService.cs
2.703125
3
using MyMusic.Core; using MyMusic.Core.Models; using MyMusic.Core.Services; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace MyMusic.Services.Services { public class MusicService : IMusicService { private readonly IUnitOfWork _unitOfWork; // Inject UnitOfWork public MusicService(IUnitOfWork unitOfWork) // UnitOfWork { this._unitOfWork = unitOfWork; } public async Task<Music> CreateMusicAsync(Music music) { var result = await _unitOfWork.Musics.AddAsync(music); await _unitOfWork.CommitAsync(); return result; } public async void DeleteMusic(Music music) { _unitOfWork.Musics.Remove(music); await _unitOfWork.CommitAsync(); } public async Task<IEnumerable<Music>> GetAllMusicsAsync() { return await this._unitOfWork.Musics.GetAllAsync(); } public async Task<IEnumerable<Music>> GetAllMusicsWithArtistAsync() { return await this._unitOfWork.Musics.GetAllWthArtisAsync(); } public async Task<Music> GetMusicByArtistIdAsync(int artistId) { return await this._unitOfWork.Musics.GetMusicByArtistIdAsync(artistId); } public async Task<Music> GetMusicById(int id) { return await _unitOfWork.Musics.GetByIdAsync(id); } public async Task UpdateMusicAsync(Music musicToBeUpdated, Music music) { musicToBeUpdated.Name = music.Name; musicToBeUpdated.ArtistId = music.ArtistId; await _unitOfWork.CommitAsync(); } } }
d24dad4bd65e70b02ded5a2271982c472a4a8e6f
C#
MarioBankov/SoftUni-Homeworks-
/C# Advanced/Exercises Multidimensional Arrays/2. 2x2 Squares in Matrix/Program.cs
3.765625
4
using System; using System.Collections.Generic; using System.Linq; namespace _2._2x2_Squares_in_Matrix { class Program { static void Main(string[] args) { int[] size = Console.ReadLine().Split(" ",StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); char[,] matrix = new char[size.First(), size.Last()]; int count = 0; for (int i = 0; i < matrix.GetLength(0) ; i++) { string[] data = Console.ReadLine().Split(" ",StringSplitOptions.RemoveEmptyEntries); for (int j = 0; j < matrix.GetLength(1); j++) { matrix[i, j] = char.Parse(data[j]); } } for (int row = 0; row < matrix.GetLength(0)-1; row++) { for (int col = 0; col < matrix.GetLength(1)-1; col++) { char a = matrix[row, col]; if (matrix[row,col+1]==a&&matrix[row+1,col]==a&&matrix[row+1,col+1]==a) { count++; } } } Console.WriteLine(count); } } }
5d3be21fb2b227feba97eba80538fdd23c986014
C#
FinnMcLaughlin/Untitled-RogueLike
/Assets/Scripts/Player Scripts/spawnCharacter.cs
2.609375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class spawnCharacter : MonoBehaviour { private bool bossSpawned; private bool playerSpawned; private bool playerRespawned = false; private GameObject spawnPoint; public GameObject player; // Find the spawnPoint within the game void Start(){ spawnPoint = GameObject.FindGameObjectWithTag ("Respawn"); HasPlayerSpawned (); } void Update(){ if (!playerRespawned) { bossSpawned = GameObject.FindGameObjectWithTag ("AllRooms").GetComponent<RoomTemplate> ().bossSpawned; if (bossSpawned) { Vector3 respawnPos = spawnPoint.transform.position; Destroy(spawnPoint); if (playerSpawned) { RepositionPlayer (respawnPos); } else { // If the player has not been spawned and the boss has // Get position of spawn point, destroy it, and // instatiate the player Instantiate (player, respawnPos, Quaternion.identity); playerSpawned = true; } playerRespawned = true; } } } public void ActivePlayer(){ GameObject.FindGameObjectWithTag ("Player").SetActive(true); } public void NonActivePlayer(){ GameObject.FindGameObjectWithTag ("Player").SetActive(false); } public void RepositionPlayer(Vector3 pos){ GameObject.FindGameObjectWithTag ("Player").transform.position = pos; } public void HasPlayerSpawned(){ if (GameObject.FindGameObjectWithTag ("Player") == null) { playerSpawned = false; } else { playerSpawned = true; } } }
5c2b42c9054bf7438acdda5ee06becc2d82e4c5c
C#
goldennoodles/AOERemake
/Assets/Scripts/Managers/GuiManager/GuiSections/GuiSection.cs
2.609375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GuiSection :MonoBehaviour { #region Variables [SerializeField] private string _guiName; [SerializeField] private bool _isEnabled; #endregion #region Getters and Setters public string GuiName { get { return _guiName; } set { _guiName = value; } } public bool IsEnabled { get { return _isEnabled; } } #endregion #region Main Functionalities public void Enable () { _isEnabled = true; this.gameObject.SetActive( true ); } public void Disable () { _isEnabled = false; this.gameObject.SetActive( false ); } #endregion #region Auxiliar Functionalities #endregion }
eaf3597319c5a0b7912a43c674895f1b8ff8c2e0
C#
eyalkapah/YahooFinanceApp
/AutoTrader.Models/Models/SectorProfit.cs
2.625
3
using System.Collections.Generic; namespace AutoTrader.Models.Models { public class SectorProfit { public double TotalProfit { get; set; } public double AverageProfit => TotalProfit / Symbols.Count; public List<string> Symbols { get; set; } public string Sector { get; set; } public SectorProfit(string sector) { Symbols = new List<string>(); Sector = sector; } } }
156be4157f336cf6b48fa7aa51e478a0d9354823
C#
yyoda/tail
/Tail/Command.cs
3
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace Tail { public class Command { private const int Interval = 100; private static readonly string[] TailOpts = new[] { "-f", "-n" }; public string[] Args { get; private set; } public int LineNumberOfFirst { get; private set; } public bool HasFileOnlyOne { get; private set; } public int HasFileNum { get; private set; } public Command(string[] args) { Args = args; LineNumberOfFirst = 10; HasFileOnlyOne = true; HasFileNum = 0; } public void DoTail() { const int endless = 0; DoTail(endless); } public void DoTail(int durationAsMilliSecond) { if (Args == null || Args.Length == 0) throw new ArgumentException("引数が存在しません."); var filePaths = new List<string>(); if (Args.Any(x => TailOpts.Contains(x))) { var opt = new GetOpt(Args, TailOpts).Parse(); //-f option List<string> fOpt; if (opt.TryGetValue("-f", out fOpt)) filePaths = fOpt; //-n option List<string> nOpt; if (opt.TryGetValue("-n", out nOpt)) { int nOptValue; if (Int32.TryParse(nOpt.First(), out nOptValue)) LineNumberOfFirst = nOptValue; else throw new ArgumentException("-n オプションの指定値が不正です.整数値を指定してください."); } } else filePaths = Args.ToList(); var searchedfilePaths = SearchFileHelper<List<string>>.GetFileListByFilename(filePaths); HasFileNum = searchedfilePaths.Count; HasFileOnlyOne = (searchedfilePaths.Count == 1); Parallel.ForEach(searchedfilePaths, filePath => { var seekedPosition = TailFast(filePath); TailFollowing(filePath, seekedPosition, durationAsMilliSecond); }); } private long TailFast(string filePath) { return FileStreamReaderMethod(filePath, (fs, sr) => { var rb = new RingBuffer<string>(LineNumberOfFirst / HasFileNum); string line; while ((line = sr.ReadLine()) != null) rb.Add(line); foreach (var s in rb) Output(filePath, s); return fs.Position; }); } private void TailFollowing(string filePath, long seekPosition, int durationAsMilliSecond) { DateTime initDate, currentDate; initDate = currentDate = DateTime.Now; var duration = TimeSpan.FromMilliseconds(durationAsMilliSecond); while ((durationAsMilliSecond == 0) || (currentDate - initDate).TotalMilliseconds < duration.TotalMilliseconds) { currentDate = DateTime.Now; //現在時刻更新 FileStreamReaderMethod(filePath, (fs, sr) => { fs.Seek(seekPosition, SeekOrigin.Begin); var line = ""; while ((line = sr.ReadLine()) != null) Output(filePath, line); seekPosition = fs.Position; return true; }); Thread.Sleep(Interval); } } private static T FileStreamReaderMethod<T>(string filePath, Func<FileStream, StreamReader, T> fileStreamReaderMethod) { using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sr = new StreamReader(fs, Encoding.UTF8)) { return fileStreamReaderMethod(fs, sr); } } private void Output(string filePath, string line) { var buf = HasFileOnlyOne ? line : "[" + filePath + "] " + line; Console.WriteLine(buf); } } }
10c1d4832ac97bb242b8be87f46f9790b9d8fc76
C#
Miroko/UnityRoguelike
/Assets/Scripts/Core/Direction.cs
2.90625
3
using UnityEngine; using System.Collections; public class Direction { public static Vector2 Up = new Vector2 (0, 1); public static Vector2 Down = new Vector2 (0, -1); public static Vector2 Left = new Vector2 (-1, 0); public static Vector2 Right = new Vector2 (1, 0); public static Vector2[] Directions = new Vector2[]{Up, Down, Left, Right}; public static Vector2 Random{ get{ float direction = UnityEngine.Random.value; if(direction < 0.25f) return Direction.Up; else if(direction < 0.50f) return Direction.Down; else if(direction < 0.75f) return Direction.Left; else return Direction.Right; } } public static Vector2 RandomWeighted(Vector2 direction, float weight){ Vector2 returnDirection = direction; if (!RandomHelper.Chance (weight)) { while(returnDirection == direction){ returnDirection = Random; } } return returnDirection; } }
789c4fe644e680ceca6da96af3d9b315686b8762
C#
Dpineda89/Clase-de-Animales
/Loro.cs
2.984375
3
using System; public class Loro: Aves // <- Herencia { public bool EsDomestico { get; set; } public string Plumaje { get; set; } public Loro() // <- Polimorfismo { EsDomestico = true; } public Loro(bool esDomestico) // <- Polimorfismo { EsDomestico = esDomestico; } public void Hablar() // <- Abstraccion { Console.WriteLine("Hablar"); } public void Tamano() { DescribirTamano(); OtroMetodo(); } private void DescribirTamano() // <- Encapsulamiento { Console.WriteLine("Un Ave Mediana"); } private void OtroMetodo() // <- Encapsulamiento { Console.WriteLine("Velocidad normal"); } public override void Volar() { Console.WriteLine("El Loro vuela mas Bajo"); } public override void Comer() { Console.WriteLine("El Loro come granos y semillas"); } }
6f308e4b3f8091f53295c4fcf5dad89bd483e7e3
C#
shendongnian/download4
/first_version_download2/457582-40757747-132213070-2.cs
2.90625
3
foreach (GridViewRow gvRow in gvProxyEntry.Rows) { List<object> emptyControls = new List<object>(); foreach (TableCell cell in gvRow.Cells) { foreach(Control c in cell.Controls)//newly added foreach loop { Type controlType = c.GetType(); if (controlType == typeof(CheckBox)) { CheckBox chkBox = (CheckBox)c; if (chkBox.Checked == false) { emptyControls.Add(chkBox); } } ... } ... } ... }
e071715acccce4378b028c8e461d60a51daaae5f
C#
soerenraeuchle/HiWiBoerse
/Login/Models/DBManager.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.Data.SqlClient; namespace Login.Models { public class DBManager { private DBManager() { } private static DBManager instance = null; //private static string ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\dev\\asp\\sopra\\Login\\Login\\App_Data\\Sopra.mdf;Integrated Security=True;User Instance=True"; private static string ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|Sopra.mdf;Integrated Security=True;User Instance=True"; private SqlConnection con = new SqlConnection(ConnectionString); public static DBManager getInstance() { if (instance == null) { instance = new DBManager(); instance.connect(); } return instance; } /** * Verbindung zur Datenbank aufbauen */ private void connect() { con.Open(); } public SqlDataReader auslesen(string query) { SqlCommand cmd = new SqlCommand(query, con); return cmd.ExecuteReader(); } public int aendern(string query) { SqlCommand cmd = new SqlCommand(query, con); return cmd.ExecuteNonQuery(); } } }
d43a235290154f45e832e94bf1ddcb70e181e1a1
C#
rdumont/changey
/Changey/LabelExtensions.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using Octokit; namespace Changey { public static class LabelExtensions { public static bool MatchesAny(this Label @this, IEnumerable<string> labels) { return labels.Any(label => string.Equals(@this.Name, label, StringComparison.InvariantCultureIgnoreCase)); } } }
ab10eb0c2171cb76bf6da82c42018e834ecadbfe
C#
flitbit/fbcore
/FlitBit.Core/WeakReferenceExtensions.cs
3.171875
3
#region COPYRIGHT© 2009-2014 Phillip Clark. All rights reserved. // For licensing information see License.txt (MIT style licensing). #endregion using System; namespace FlitBit.Core { /// <summary> /// Extends the weak reference type. /// </summary> public static class WeakReferenceExtensions { /// <summary> /// Tries to get the target of the reference. /// </summary> /// <typeparam name="T">type T of the referenced object</typeparam> /// <param name="weakRef">the target reference</param> /// <param name="target">reference to a variable that will recieve the target if successful</param> /// <returns> /// <em>true</em> if the reference is alive and has a valid value of type T; otherwise <em>false</em> /// </returns> /// <exception cref="InvalidCastException">thrown if the target of the reference cannot be cast to type T</exception> public static bool TryGetStrongTarget<T>(this WeakReference weakRef, out T target) { if (weakRef.IsAlive) { target = (T)weakRef.Target; return true; } target = default(T); return false; } } }
e8f06b5761f6b32e0b0321950ba713fdb08018ac
C#
Sckorn/vercanoid
/Assets/Standard Assets/Scripts/back/GridCell.cs
2.734375
3
using UnityEngine; using System.Collections; using System; public class GridCell { private bool hasBrick = false; private GameObject realObjRef; private GridCellCoords cellCoords; public bool HasBrick { get { return this.hasBrick; } set { this.hasBrick = value; } } public GameObject ObjectReference { get { return this.realObjRef; } } public GridCell(int _x, int _y, bool _hasBrick, char brickTypeChar = '\0') { this.cellCoords.x = _x; this.cellCoords.y = _y; this.hasBrick = _hasBrick; Morpher morph = GameObject.Find("Morpher").GetComponent<Morpher>(); try { if (this.hasBrick) this.realObjRef = morph.MorphBrick(this.cellCoords.x, this.cellCoords.y, brickTypeChar); } catch (UnityException e) { this.cellCoords.x = -1; this.cellCoords.y = -1; #if UNITY_EDITOR Debug.LogError("Can't instantiate Brick in Cell"); Debug.LogError(e.Message); return; #else //do later: handle exceptions to the main menu with a popup informing of the exception Application.Quit(); #endif } finally { if (this.realObjRef != null) { this.realObjRef.GetComponent<BrickObjectHandler>().SetCoordinates(this.cellCoords); } } } }
f4f8a2cd4e4fac7f8cc738ab68a83ef1f9f7b870
C#
shendongnian/download4
/code2/276770-5662111-12170497-2.cs
3.15625
3
using System; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; class Person { public int Id { get; set; } public FullName FullName { get; set; } } class FullName { public string FirstName { get; set; } public string LastName { get; set; } } class Program { static void Main(string[] args) { Person model = new Person { Id = 123, FullName = new FullName { FirstName = "Duncan", LastName = "Smart", } }; var nameBinder = CompileDataBinder<Person, string>("model.FullName.FirstName"); string fname = nameBinder(model); Debug.Assert(fname == "Duncan"); // Note how here we pretend we don't know TProp type var idBinder = CompileDataBinder<Person, object>("model.Id"); object id = idBinder(model); Debug.Assert(id.Equals(123)); } static Func<TModel, TProp> CompileDataBinder<TModel, TProp>(string expression) { var propNames = expression.Split('.'); var model = Expression.Parameter(typeof(TModel), "model"); Expression body = model; foreach (string propName in propNames.Skip(1)) body = Expression.Property(body, propName); //Debug.WriteLine(prop); if (body.Type != typeof(TProp)) body = Expression.Convert(body, typeof(TProp)); Func<TModel, TProp> func = Expression.Lambda<Func<TModel, TProp>>(body, model).Compile(); //TODO: cache funcs return func; } }
25dcd7fe34616b8f16a2eaecd2385f6cbae2c831
C#
h2n0/HashCode
/Drone.cs
2.984375
3
using System; using hashCode; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace hashCode { struct Drone { public static int[] ItemWeights { get; set; } Pos Location { get; set; } int TurnsTillTarget { get; set; } int MaxWeight { get; } List<Product> HeldItems { get; set; } int CurrentWeight { get; set; } public Drone(int maxWeight){ Location = Warehouses[0].Location; TurnsTillTarget = -1; MaxWeight = maxWeight; HeldItems = new List<Product>(); CurrentWeight = 0; } public int TimeToPosition(Pos target) { return (int) Math.Ceiling(Math.Sqrt(Math.Pow(Location.X - target.X, 2) + Math.Pow(Location.Y - target.Y, 2))); } public bool Load(Pos warehouseLocation, List<Product> itemsToLoad) { int newWeight = CurrentWeight; for (int i = 0; i < itemsToLoad.Count; i++) { newWeight += ItemWeights[i] * itemsToLoad[i].ProductQuantity; } if (newWeight > MaxWeight) { return false; } else { bool found; for (int i = 0; i < itemsToLoad.Count; i++) { found = false; int left = 0, right = HeldItems.Count - 1, mid = 0; while (left <= right) { mid = left + ((right - left) / 2); if (HeldItems[mid].ProductNumb > itemsToLoad[i].ProductNumb) { right = mid - 1; } else if (HeldItems[mid].ProductNumb < itemsToLoad[i].ProductNumb) { left = mid + 1; } else { HeldItems[mid].ProductQuantity += itemsToLoad[i].ProductQuantity; found = true; break; } } //------------------------------------------------------------------- if (found == false) { HeldItems.Insert(mid, itemsToLoad[i]); } } return true; } } public bool Deliver(Pos destination, int productNumb, int productQuantity, ref Order orderToDeliver) { //----------------------------finding index on drone---------------------------- int left = 0, right = HeldItems.Count - 1, mid = 0; while (left <= right) { mid = left + ((right - left) / 2); if (HeldItems[mid].ProductNumb > productNumb) { right = mid - 1; } else if (HeldItems[mid].ProductNumb < productNumb) { left = mid + 1; } else { if (HeldItems[mid].ProductQuantity < productQuantity) { Console.WriteLine("Not enough of item '" + productNumb + "' to deliver"); return false; } } } //----------------------------finding index in order---------------------------- left = 0; right = orderToDeliver.ItemsToDeliver.Count - 1; int midSecond = 0; while (left <= right) { midSecond = left + ((right - left) / 2); if (orderToDeliver.ItemsToDeliver[midSecond].ProductNumb > productNumb) { right = midSecond - 1; } else if (orderToDeliver.ItemsToDeliver[mid].ProductNumb < productNumb) { left = midSecond + 1; } else { orderToDeliver.ItemsToDeliver[midSecond].ProductQuantity = 0; HeldItems[mid].ProductQuantity -= orderToDeliver.ItemsToDeliver[midSecond].ProductQuantity; orderToDeliver.Completed = true; return true; } } TurnsTillTarget = TimeToPosition(orderToDeliver.Location); return true; } } }
9d4db3f82dc9ce1b65f70a28913d32279c61e9b5
C#
stefaanvermassen/service-fabric-cosmos-db-reverse-proxy
/AuditingService/Core/Guard.cs
3.28125
3
using CommonBase.CustomExceptions; using CommonBase.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AuditingService.Core { /// <summary> /// A static helper class that includes various parameter checking routines. /// </summary> public static class Guard { /// <summary> /// Throws <see cref="ArgumentNullException"/> if the given argument is null. /// </summary> /// <exception cref="ArgumentNullException"> if tested value if null.</exception> /// <param name="argValue">Argument value to test.</param> /// <param name="argName">Name of the argument being tested.</param> public static void ArgumentNotNull(string argName, object argValue) { if (argValue == null) { throw new ArgumentNullException(argName); } } /// <summary> /// Throws an exception if the tested string argument is null or the empty string. /// </summary> /// <exception cref="ArgumentNullException">Thrown if string value is null or empty.</exception> /// <param name="argValue">Argument value to check.</param> /// <param name="argName">Name of argument being checked.</param> public static void ArgumentNotNullOrEmpty(string argName, string argValue) { if (string.IsNullOrEmpty(argValue)) { throw new ArgumentWithErrorCodeException(ErrorCodes.ArgumentNullOrEmpty, argValue); } } /// <summary> /// Throws an exception if the tested IEnumerable argument is null or empty. /// </summary> /// <exception cref="ArgumentNullException">Thrown if IEnumerable value is null.</exception> /// <exception cref="ArgumentException">Thrown if IEnumerable value is empty.</exception> /// <param name="argValue">Argument value to check.</param> /// <param name="argName">Name of argument being checked.</param> public static void ArgumentNotNullOrEmpty(string argName, IEnumerable argValue) { //No null check for argValue required as long as the overload with string argValue exists. Because //when called with argValue is null, the overload with string argValue will always be called. if (!argValue.GetEnumerator().MoveNext()) { throw new ArgumentWithErrorCodeException(ErrorCodes.ArgumentNullOrEmpty, argValue); } } /// <summary> /// Throws an exception if the tested object is not of type T. /// </summary> /// <exception cref="ArgumentException">Thrown if object is not of type T.</exception> /// <param name="argValue">Argument value to check.</param> /// <param name="argName">Name of argument being checked.</param> public static void ArgumentOfType<T>(string argName, object argValue) { ArgumentNotNull(argName, argValue); Type typeParameterType = typeof(T); if (typeParameterType != argValue.GetType()) { throw new ArgumentWithErrorCodeException(ErrorCodes.ArgumentWrongType, argName, typeParameterType.Name, argValue.GetType().Name); } } } }
2802bebdba45461dd7bd37ab154076d852c0faaf
C#
MichaelDessureault/Battle-System-2.0
/Assets/Scripts/MonoBehaviours/00 General/IndexData.cs
2.78125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; // This script is used to have easy access with updating indexs by being able to search it's reference within a scene // It contains information on which index of a selection window was clicked, the information is reterived when it's passed // Best explain is while the abilities are selected this script will contain a value for that index // This script could be removed and the same hardcoded value could be inputed into the onclick event public class IndexData : MonoBehaviour { [SerializeField] private int indexValue = -1; public int IndexValue { get { return indexValue; } } // Use this for initialization void Start () { // -1 index is used for health potion, therefore less than -1 if (indexValue < -1) { print ("index value is not set correctly for: " + gameObject.name); } } }
ccc1a5218f2d70271402ddf92a7603885578f469
C#
SulfuricSulfur/UGWCodeProj
/Enemy.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.GamerServices; namespace UGWProjCode { class Enemy : Character { //attributes private int movingDirection; //this is what direction the enemy is moving //and what the opposite direction will be if they collide with something or reach the edge of something //0 is down(south, S) 1 is left(west, A) 2 is up(north, W) and 3 is right(east, D) private int enemyMoveSpd; //the moving speed of the enemy will change depending on what is up in //some enemies will be faster than others //lets the enemy speed up and charge correctly private Vector2 velocity; private Vector2 enemyPos; private bool canCharge; //determines if it is the enemy that can charge private bool chargingState; //for the 1 charging enemy, it will determin if it is currently charging so //there can be different animations depending on if the enemy is walking or running private bool closeToBlock; //determins if there is a block within a certain range so the enemy can't charge // properties public int MovingDirection { get { return movingDirection; } set { movingDirection = value; } } public int EnemyMoveSpeed { get { return enemyMoveSpd; } set { enemyMoveSpd = value; } } public Vector2 EnemyPosition { get { return enemyPos; } set { enemyPos = value; } } public bool CanCharge { get { return canCharge; } } public bool ChargingState { get { return chargingState; } set { chargingState = value; } } public bool CloseToBlock { get { return closeToBlock; } set { closeToBlock = value; } } //constructor public Enemy(Boolean deadstatus, Rectangle enemyrect, Texture2D enemytext, int moveDir, int enemySpd, bool chargeable) : base(deadstatus, enemyrect, enemytext) { movingDirection = moveDir; enemyMoveSpd = enemySpd; enemyPos = new Vector2(ObjRect.X, ObjRect.Y); canCharge = chargeable; closeToBlock = false; } //kill method /// <summary> /// The method for switching the player between worlds depending on what world they are /// currently in. /// </summary> /// <param name="player1"> the player object passed in</param> public void Kill(Player player1) { if (player1.IsDead == false) { player1.IsDead = true; } else if (player1.IsDead == true) { player1.IsDead = false; } } /// <summary> /// this will be called for every enemy in the enemy arrays to see if they are colliding with the player while in the same state /// </summary> /// <param name="plyr"></param> public void KillingPlayer(Player plyr) { //if the player is dead and the enemy is dead if (isDead == true && plyr.IsDead == true) { if (objRect.Intersects(plyr.ObjRect)) { Kill(plyr); } } //if the player is alive and the enemy is alive else if (isDead == false && plyr.IsDead == false) { if (objRect.Intersects(plyr.ObjRect)) { Kill(plyr); } } } /// <summary> /// The enemy moves. If dead, the enemy will move up and down or side to side (depending on what direction first starts out with) /// if allive, the enemy can only move side to side /// ONE enemy can charge. It pauses for a short amount of time before it speeds up. /// //takes in the player character. /// The enemies only move if the player is in the same state as them /// we will NOT have enemies of different states on top of eachother /// </summary> /// <param name="plyr"></param> public void Move(Player plyr) { if (isDead == true && plyr.IsDead == true)//dead { ObjRect = new Rectangle((int)enemyPos.X, (int)enemyPos.Y, ObjRect.Width, ObjRect.Height); if (movingDirection == 0)//down { enemyPos.Y += enemyMoveSpd; } if (movingDirection == 1)//left { enemyPos.X -= enemyMoveSpd; } if (movingDirection == 2)//up { enemyPos.Y -= enemyMoveSpd; } if (movingDirection == 3)//right { enemyPos.X += enemyMoveSpd; } ObjRect = new Rectangle((int)enemyPos.X, (int)enemyPos.Y, ObjRect.Width, ObjRect.Height); } else if (isDead == false && plyr.IsDead == false)//alive { ObjRect = new Rectangle((int)enemyPos.X, (int)enemyPos.Y, ObjRect.Width, ObjRect.Height); if (movingDirection == 1) { //charging to the left if (canCharge == true && plyr.ObjRect.Right - ObjRect.Left >= -150 && plyr.ObjRect.Right - ObjRect.Left < 20 && ((plyr.ObjRect.Bottom) - (ObjRect.Top) <= 80 && (plyr.ObjRect.Bottom) - (ObjRect.Top) >= -80))//only 1 type of enemy can charge { if (velocity.X > -10) { velocity.X += -1; enemyPos += velocity; chargingState = true; } else if (velocity.X <= -10) { velocity.X = -10; enemyPos += velocity; chargingState = true; } } //moving normally else { enemyPos.X -= enemyMoveSpd; velocity = Vector2.Zero; chargingState = false; } } if (movingDirection == 3) { //charging to the right if (canCharge == true && ObjRect.Right - plyr.ObjRect.Left >= -150 && ObjRect.Right - plyr.ObjRect.Left < 20 && ((plyr.ObjRect.Bottom) - (ObjRect.Top) <= 80 && (plyr.ObjRect.Bottom) - (ObjRect.Top) >= -80)) //only 1 type of enemy can charge { if (velocity.X < 10) { velocity.X += 1; enemyPos += velocity; chargingState = true; } else if (velocity.X >= 10) { velocity.X = 10; enemyPos += velocity; chargingState = true; } } //moving normally else { enemyPos.X += enemyMoveSpd; velocity = Vector2.Zero; chargingState = false; } } ObjRect = new Rectangle((int)enemyPos.X, (int)enemyPos.Y, ObjRect.Width, ObjRect.Height); } } //test collision method /// <summary> /// takes in the rectangle of an object and if it is alive or dead /// </summary> /// <param name="otherRect">the rectangle of any object</param> /// <param name="isDeadObj">if the object(same one the rectangle is) is alive or dead</param> public void EnemyCollide(Rectangle otherRect, bool isDeadObj) { if (this.ObjRect.Intersects(otherRect)) { if (this.IsDead == true && isDeadObj == true) { //collision on for the enemy //in the spooky zone if ((otherRect.Top - this.ObjRect.Bottom) >= -10 && (otherRect.Top - this.ObjRect.Bottom) < 0 && movingDirection == 0)//enemy collides with top of block { movingDirection = 2; } else if ((otherRect.Left - this.ObjRect.Right) >= -10 && (otherRect.Left - this.ObjRect.Right) < 0 && movingDirection == 3)//left side of the block collision { movingDirection = 1; } else if ((this.ObjRect.Left - otherRect.Right) >= -10 && (this.ObjRect.Left - otherRect.Right) < 0 && movingDirection == 1)//right side of block { movingDirection = 3; } else if ((this.ObjRect.Top - otherRect.Bottom) >= -10 && (this.ObjRect.Top - otherRect.Bottom) < 0 && movingDirection == 2)//cloding with bottom of block { movingDirection = 0; } } else if (this.IsDead == false && isDeadObj == false) { //physical world only requires left and right moving if ((otherRect.Left - this.ObjRect.Right) >= -10 && (otherRect.Left - this.ObjRect.Right) < 0 && movingDirection == 3)//left side of the block collision { movingDirection = 1; if (chargingState == true) { movingDirection = 1; } } if ((this.ObjRect.Left - otherRect.Right) >= -10 && (this.ObjRect.Left - otherRect.Right) < 0 && movingDirection == 1)//right side of block { movingDirection = 3; if (chargingState == true) { movingDirection = 3; } } } } } } }
332786ad48205372dc20eeb68337bcf18c45f827
C#
armaniR812/FileTrim
/MainForm.cs
2.609375
3
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 FileTrim { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void letterBtn_CheckedChanged(object sender, EventArgs e) { } private void mainConfBtn_Click(object sender, EventArgs e) { //Open the form according to what was checked on the main form. if (letterBtn.Checked == true) { RmvLettersForm lettersForm = new RmvLettersForm(); lettersForm.Show(); } else if (numberBtn.Checked == true) { RmvNumbersForm numbersForm = new RmvNumbersForm(); numbersForm.Show(); } else { MessageBox.Show("Please select a method."); } } } }
90e8bf1568c9df4b31b92a6b9c5b5a2f94a56bf2
C#
LilDavtyan/Myprojects
/Controllers/StudentController.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Les8.Models; namespace Les8.Controllers { public class StudentController : Controller { public ActionResult StudentList() { StudentContext studentlist = new StudentContext(); List<Student> student = studentlist.Student.ToList(); return View(student); } public ActionResult GetStudent(int id) { StudentContext stu = new StudentContext(); Student studentlist = stu.Student.Single(st=>st.ID==id) ; return View(studentlist); } [HttpGet] [ActionName("Create")] public ActionResult CreateGet() { return View(); } [HttpGet] [ActionName("Edit")] public ActionResult Edit_Get(int id) { StudentContext editstudent = new StudentContext(); Student editstud = editstudent.Student.Single(st => st.ID == id); return View(editstud); } [HttpPost] [ActionName("Edit")] public ActionResult Edit_Post([Bind(Include="ID, FirstName, LastName")] Student stud) { StudentMonipulation st = new StudentMonipulation(); stud.Keyword= st.Students.Single(sd => sd.ID == stud.ID).Keyword; if (ModelState.IsValid) { st.SaveStudent(stud); return RedirectToAction("StudentList"); } return View(stud); } //[HttpPost] //[ActionName("Edit")] //public ActionResult Edit_Post(int id) //{ // StudentContext st = new StudentContext(); // Student editedstudent = st.Student.Single(sd => sd.ID == id); // UpdateModel(editedstudent, new string[] { "FirstName", "LastName" }); // if (ModelState.IsValid) // { // StudentMonipulation savestudent = new StudentMonipulation(); // savestudent.SaveStudent(editedstudent); // return RedirectToAction("StudentList"); // } // return View(editedstudent); //} [HttpPost] [ActionName("Create")] //public ActionResult Create(FormCollection formcollection) //{ // /* foreach(String key in formcollection) // { // Response.Write("Key="+key+" "); // Response.Write(formcollection[key]); // Response.Write("</br>"); // } // return View(); // * */ // Student student = new Student(); // student.FirstName = formcollection["FirstName"]; // student.LastName = formcollection["LastName"]; // student.Keyword = formcollection["Keyword"]; // StudentMonipulation studentmonipulation = new StudentMonipulation(); // studentmonipulation.AddStudent(student); // return RedirectToAction("StudentList"); //} public ActionResult CreatePost() { if (ModelState.IsValid) { Student st = new Student(); UpdateModel(st); StudentMonipulation studentmonipulation = new StudentMonipulation(); studentmonipulation.AddStudent(st); return RedirectToAction("StudentList"); } return RedirectToAction("Create"); } public ActionResult Delete(int id) { StudentMonipulation st = new StudentMonipulation(); st.DeleteStudent(id); return RedirectToAction("StudentList"); } } }
5949a34c7fd96ec6b9cd7d56afac7dade719cfac
C#
AndrewSherstyuk/CsharpCourse
/Lesson3_Homework/Task8/Program.cs
3.71875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task8 { class Program { static void Main(string[] args) { Start: Console.WriteLine("\n\nPlease enter any integer within the following range: 0 - 100"); int number = Convert.ToInt32(Console.ReadLine()); char rangeID = 'Z'; if (number >= 0 && number <= 14) rangeID = 'A'; if (number >= 15 && number <= 35) rangeID = 'B'; if (number >= 36 && number <= 50) rangeID = 'C'; if (number >= 51 && number <= 100) rangeID = 'D'; switch(rangeID) { case ('A'): { Console.WriteLine($"The number belongs to group {rangeID}, which means that it's equal to or larger than 0 and equal to or less than 14"); break; } case ('B'): { Console.WriteLine($"The number belongs to group {rangeID}, which means that it's equal to or larger than 15 and equal to or less than 35"); break; } case ('C'): { Console.WriteLine($"The number belongs to group {rangeID}, which means that it's equal to or larger than 36 and equal to or less than 50"); break; } case ('D'): { Console.WriteLine($"The number belongs to group {rangeID}, which means that it's equal to or larger than 51 and equal to or less than 100"); break; } case ('Z'): { Console.WriteLine($"The number doesn't belongs to or the groups, which means that it's either less than zero or larger than 100"); break; } } goto Start; } } }
dad940a5c539a71742d1a6d21bf67ed0de242681
C#
tinaxiu/Leetcode
/ConsoleApp1/MinimumCosttoMergeStones.cs
3.390625
3
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp1 { class MinimumCosttoMergeStones { public int RunMergeStone() { int[] Stones = new int[4]; Stones[0] = 3; Stones[1] = 2; Stones[2] = 4; Stones[3] = 1; return MergeStones(Stones, 2); } public int MergeStones(int[] stones, int K) { int n = stones.Length; if ((n - 1) % (K - 1) != 0) return -1; int[] sums = new int[n + 1]; int[,] dp = new int[n, n]; sums[0] = 0; for (int i = 1; i < n + 1; ++i) { sums[i] = sums[i - 1] + stones[i - 1]; } for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) dp[i, j] = 0; for (int len = K; len <= n; ++len) { for (int i = 0; i + len <= n; ++i) { int j = i + len - 1; dp[i,j] = int.MaxValue; for (int t = i; t < j; t += K - 1) { dp[i,j] = Math.Min(dp[i,j], dp[i,t] + dp[t + 1,j]); } if ((j - i) % (K - 1) == 0) { dp[i,j] += sums[j + 1] - sums[i]; } } } return dp[0,n - 1]; } } }
4394f97361fed71f9919ee7d45c55937364a18fb
C#
KevinvdBurg/StartKicker
/Kickstarter_web/classes/DBLogin.cs
2.859375
3
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DBLogin.cs" company="StartKicker"> // // </copyright> // <summary> // All the DB connections that are needed to login someone in and to get all the relative infromation for a account // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.ComponentModel; namespace Kickstarter_web { using Oracle.DataAccess.Client; /// <summary> /// The Login methods that are needed to log someone in /// </summary> public class DBLogin : Database { /// <summary> /// It will logs someone in the system /// </summary> /// <param name="email"> /// An email /// </param> /// <param name="password"> /// An password /// </param> /// <returns> /// An Account Object if an account is found. Otherwise is wil return null /// </returns> public Account Login(string email, string password) { Account newAccount = null; int accountID; string rights; string sql; sql = "SELECT ACCOUNT_ID, RIGHTS FROM KICKSTARTER_ACCOUNT WHERE EMAIL = LOWER(:email) AND KICKPASSWORD = :password"; // sql = "SELECT * FROM KICKSTARTER_ACCOUNT;"; try { this.Connect(); OracleCommand cmd = new OracleCommand(sql, this.connection); cmd.Parameters.Add(new OracleParameter("email", email.ToLower())); cmd.Parameters.Add(new OracleParameter("password", password)); OracleDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { accountID = Convert.ToInt32(reader["ACCOUNT_ID"]); rights = Convert.ToString(reader["RIGHTS"]); if (rights == "user") { newAccount = new Account(accountID); } else if (rights == "admin") { newAccount = new Admin(accountID); } } } catch (OracleException e) { Console.WriteLine(e.Message); } finally { this.connection.Close(); } return newAccount; } /// <summary> /// Gets all the information from a given account ID /// </summary> /// <param name="account_id"> /// The account id that you want the details off /// </param> /// <param name="rights"> /// The rights from the Account /// </param> /// <returns> /// A Account or Admin Object from the givven account ID /// </returns> public Account GetAccount(int account_id, string rights) { Account newAccount = null; string sql; if (rights == "admin") { sql = "SELECT a.email, a.phone, a.kickname, a.picture, a.biography, a.kicklocation, a.timezone, a.vanity_url, a.rights, ad.kickadmin, ad.workemail, ad.salary, ad.DEPARTMENT FROM KICKSTARTER_ACCOUNT a INNER JOIN KICKSTARTER_ADMIN ad ON a.ACCOUNT_ID = ad.ADMIN_ID WHERE ACCOUNT_ID = :ACCOUNT_ID"; } else { sql = "SELECT email, phone, kickname, picture, biography, kicklocation, timezone, vanity_url, rights FROM KICKSTARTER_ACCOUNT WHERE ACCOUNT_ID = :ACCOUNT_ID"; } try { this.Connect(); OracleCommand cmd = new OracleCommand(sql, this.connection); cmd.Parameters.Add(new OracleParameter("ACCOUNT_ID", account_id)); OracleDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { if (rights == "user") { newAccount = new Account( account_id, Convert.ToString(reader["email"]), Convert.ToString(reader["phone"]), Convert.ToString(reader["kickname"]), Convert.ToString(reader["picture"]), Convert.ToString(reader["biography"]), Convert.ToString(reader["kicklocation"]), Convert.ToString(reader["timezone"]), Convert.ToString(reader["vanity_url"])); } else if (rights == "admin") { newAccount = new Admin( account_id, Convert.ToString(reader["email"]), Convert.ToString(reader["phone"]), Convert.ToString(reader["kickname"]), Convert.ToString(reader["picture"]), Convert.ToString(reader["biography"]), Convert.ToString(reader["kicklocation"]), Convert.ToString(reader["timezone"]), Convert.ToString(reader["vanity_url"]), Convert.ToString(reader["workemail"]), Convert.ToDouble(reader["salary"]), Convert.ToString(reader["DEPARTMENT"])); } } } catch (OracleException e) { Console.WriteLine(e.Message); } finally { this.connection.Close(); } return newAccount; } } }
72eff83203bc1c0f3a9be642baf99de7d85407ce
C#
samasder/unityProject_RogueTactics
/RogueTactics/Assets/Scripts/ViewModelComponent/Actor/Alliance.cs
2.5625
3
using UnityEngine; public class Alliance : MonoBehaviour { public Alliances type; public bool confused; public bool IsMatch(Alliance other, Targets targets) { bool isMatch = false; switch (targets) { case Targets.Self: isMatch = other == this; break; case Targets.Ally: isMatch = type == other.type; break; case Targets.Foe: isMatch = (type != other.type) && other.type != Alliances.Neutral; break; } return confused ? !isMatch : isMatch; } }
3b24717da701c5cc4097cfff4b1bad7ad19f2fb2
C#
fdeluna/.net-SeleniumTest
/VibboQA/PageObject/SearchResultGridPO.cs
2.875
3
using System; using OpenQA.Selenium; using System.Collections.Generic; namespace VibboQA.PageObject { /// <summary> /// Page Object To interact with search result grid /// </summary> public class SearchResultGridPO : BasePageObject { private IWebElement _searchResultGrid; private List<GridElementPO> _searchResultElements; private string _resultGridId = "list_ads_table_container"; private string _gridElementsClassName = "list_ads_row"; public SearchResultGridPO(IWebDriver driver) : base(driver) { _searchResultGrid = GetElementById(_resultGridId, defaultTimeOut); UpdateSearchGrid(); } /// <summary> /// Update list of WebElements existing in the grid /// </summary> public void UpdateSearchGrid() { _searchResultElements = new List<GridElementPO>(); List<IWebElement> gridItems = new List<IWebElement>(_searchResultGrid.FindElements(By.ClassName(_gridElementsClassName))); for (int i = 0; i < gridItems.Count; i++) { _searchResultElements.Add(new GridElementPO(driver, i)); } } /// <summary> /// Click any element of the grid by subject name /// </summary> /// <param name="subject"></param> /// <returns>Element detail PO</returns> public ElementDetailPO ClickElement(string subject) { ElementDetailPO elementDetailPO = null; foreach (GridElementPO element in _searchResultElements) { if (subject.Equals(element.GetElementSubjectName(), StringComparison.InvariantCultureIgnoreCase)) { elementDetailPO = element.ClickElementSubjectName(); break; } } return elementDetailPO; } /// <summary> /// Return any element of the grid by subject name /// </summary> /// <param name="subject"></param> /// <returns>Grid Elemet PO</returns> public GridElementPO ElementWithName(string subject) { GridElementPO gridElementPO = null; foreach (GridElementPO element in _searchResultElements) { if (subject.Equals(element.GetElementSubjectName(), StringComparison.InvariantCultureIgnoreCase)) { gridElementPO = element; break; } } return gridElementPO; } } }
716998efed8cfb09ace17f7add59314e54d69ab4
C#
Creysys/MinecraftClone3
/MinecraftClone3API/Util/AxisAlignedBoundingBox.cs
2.84375
3
using MinecraftClone3API.Blocks; using OpenTK; namespace MinecraftClone3API.Util { public class AxisAlignedBoundingBox { public Vector3 Min; public Vector3 Max; public Vector3 Translation => Min + (Max - Min) * 0.5f; public Vector3 Scale => Max - Min; public AxisAlignedBoundingBox(Vector3 min, Vector3 max) { Min = min; Max = max; } public bool Intersects(AxisAlignedBoundingBox bb, out BlockFace face, out float depth) { const float delta = 1e-7f; face = BlockFace.Back; depth = 0; var distances = new[] { bb.Max.X - Min.X, Max.X - bb.Min.X, bb.Max.Y - Min.Y, Max.Y - bb.Min.Y, bb.Max.Z - Min.Z, Max.Z - bb.Min.Z }; for (var i = 0; i < 6; i++) { if (distances[i] < delta) return false; if (i != 0 && !(distances[i] < depth)) continue; face = (BlockFace) i; depth = distances[i]; } return true; } public AxisAlignedBoundingBox Transform(Matrix4 transform) { var scale = transform.ExtractScale(); var translation = transform.ExtractTranslation(); return new AxisAlignedBoundingBox(Min * scale + translation, Max * scale + translation); } } }
d0f327cd08fcfbfd62aa14207909e3e02d3a51d6
C#
landorphan/service-location
/source/Landorphan.Ioc.ServiceLocation/ServiceLocation/Exceptions/LandorphanIocServiceExcepions/AbstractAssemblyRegistrarException.cs
2.609375
3
namespace Landorphan.Ioc.ServiceLocation.Exceptions { using System; using System.Globalization; using System.Runtime.Serialization; using System.Security; using Landorphan.Common; using Landorphan.Ioc.Resources; using Landorphan.Ioc.ServiceLocation.Interfaces; /// <summary> /// Exception thrown when service location finds an abstract implementation of <see cref="IAssemblySelfRegistration"/>. /// </summary> /// <seealso cref="LandorphanIocServiceLocationException"/> [Serializable] public sealed class AbstractAssemblyRegistrarException : LandorphanIocServiceLocationException { /// <summary> /// Initializes a new instance of the <see cref="AbstractAssemblyRegistrarException"/> class. /// </summary> public AbstractAssemblyRegistrarException() : this(null, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="AbstractAssemblyRegistrarException"/> class. /// </summary> /// <param name="message"> /// The message that describes the error. /// </param> public AbstractAssemblyRegistrarException(string message) : this(null, message, null) { } /// <summary> /// Initializes a new instance of the <see cref="AbstractAssemblyRegistrarException"/> class. /// </summary> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> /// <param name="innerException"> /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified. /// </param> public AbstractAssemblyRegistrarException(string message, Exception innerException) : this(null, message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="AbstractAssemblyRegistrarException"/> class. /// </summary> /// <param name="abstractType"> /// The abstract type that gave rise to this exception. /// </param> public AbstractAssemblyRegistrarException(Type abstractType) : this(abstractType, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="AbstractAssemblyRegistrarException"/> class. /// </summary> /// <param name="abstractType"> /// The abstract type that gave rise to this exception. /// </param> /// <param name="innerException"> /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified. /// </param> public AbstractAssemblyRegistrarException(Type abstractType, Exception innerException) : this(abstractType, null, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="AbstractAssemblyRegistrarException"/> class. /// </summary> /// <param name="abstractType"> /// The abstract type that gave rise to this exception. /// </param> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> /// <param name="innerException"> /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified. /// </param> public AbstractAssemblyRegistrarException(Type abstractType, string message, Exception innerException) : base(NullToDefaultMessage(abstractType, message), innerException) { AbstractType = abstractType; } /// <summary> /// Initializes a new instance of the <see cref="AbstractAssemblyRegistrarException"/> class. /// </summary> /// <param name="info"> /// The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown. /// </param> /// <param name="context"> /// The <see cref="StreamingContext"/> that contains contextual information about the source or destination. /// </param> private AbstractAssemblyRegistrarException(SerializationInfo info, StreamingContext context) : base(info, context) { AbstractType = (Type)info.GetValue("abstractType", typeof(Type)); } /// <inheritdoc/> [SecurityCritical] public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.ArgumentNotNull("info"); info.AddValue("abstractType", AbstractType); base.GetObjectData(info, context); } /// <summary> /// Gets the abstract type that gave rise to this exception. /// </summary> /// <value> /// The type of the abstract. /// </value> public Type AbstractType { get; } private static string NullToDefaultMessage(Type abstractType, string message) { var rv = message ?? string.Format( CultureInfo.InvariantCulture, StringResources.AbstractAssemblyRegistrarExceptionDefaultMessageFmt, abstractType.IsNull() ? StringResources.NullReplacementValue : abstractType.FullName); return rv; } } }
ba6ce12ce0f99347bb690abdcb78741c34bf69b4
C#
radoman1996/DSaturProject
/DSaturProject/DrawGraph.cs
2.703125
3
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 DSaturProject { public partial class DrawGraph : Form { #region PODACI public int numberVertices; public int chromaticNumber; public int[,] dataMatrix; public LinkedList<int>[] adjacentVertices; public Color[] palette; public Point[] vertexPoints; public int vertexDiag; public int vertexRad; #endregion public DrawGraph(int numberVertices, int chromaticNumber, int[,] dataMatrix, LinkedList<int>[] adjacentVertices) { InitializeComponent(); this.numberVertices = numberVertices; this.chromaticNumber = chromaticNumber; this.dataMatrix = dataMatrix; this.adjacentVertices = adjacentVertices; vertexDiag = 50; vertexRad = 25; Random rand = new Random(); palette = new Color[this.chromaticNumber]; if (this.chromaticNumber <= 4) { switch (this.chromaticNumber) { case 1: palette[0] = Color.Red; break; case 2: palette[0] = Color.Red; palette[1] = Color.Green; break; case 3: palette[0] = Color.Red; palette[1] = Color.Green; palette[2] = Color.Blue; break; case 4: palette[0] = Color.Red; palette[1] = Color.Green; palette[2] = Color.Blue; palette[3] = Color.Yellow; break; } } else { int k = 0; while (k < this.chromaticNumber) { Color color1 = Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256)); palette[k] = color1; int j = 0; while (j < k) { if (palette[j].Equals(color1)) { k--; break; } j++; } k++; } } int w = SystemInformation.PrimaryMonitorSize.Width; int h = SystemInformation.PrimaryMonitorSize.Height; int margin = 50; int xm = w - margin * 2; int ym = h - 50 - margin * 2; vertexPoints = new Point[this.numberVertices]; for (int i = 0; i < vertexPoints.Length; i++) { vertexPoints[i] = new Point(rand.Next(xm) + margin, rand.Next(ym) + margin); for (int j = 0; j < i; j++) { double a = vertexPoints[i].X - vertexPoints[j].X; double b = vertexPoints[i].Y - vertexPoints[j].Y; if (Math.Sqrt(a * a + b * b) < vertexDiag) { i--; break; } } } } private void DrawGraph_Load(object sender, EventArgs e) { Font font = new Font("Times New Roman", 12.0f, FontStyle.Bold); this.Font = font; int w = SystemInformation.PrimaryMonitorSize.Width; int h = SystemInformation.PrimaryMonitorSize.Height; this.Width = w; this.Height = h; this.StartPosition = FormStartPosition.CenterScreen; this.WindowState = FormWindowState.Maximized; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); using (Graphics g = e.Graphics) { g.Clear(Color.Black); using (Pen p = new Pen(Color.White, 1)) { for (int v = 0; v < this.numberVertices; v++) { foreach (int w in this.adjacentVertices[v]) { g.DrawLine(p, vertexPoints[v].X, vertexPoints[v].Y, vertexPoints[w].X, vertexPoints[w].Y); } } for (int v = 0; v < this.numberVertices; v++) { SolidBrush myBrush = new SolidBrush(palette[this.dataMatrix[1, v] - 1]); g.FillEllipse(myBrush, vertexPoints[v].X - vertexRad, vertexPoints[v].Y - vertexRad, vertexDiag, vertexDiag); myBrush = new SolidBrush(Color.White); String s = (v + 1).ToString(); g.DrawString(s, Font, myBrush, vertexPoints[v].X - 8, vertexPoints[v].Y - 10); } } } } } }
b9107cbfb8f231e3ad1f2b2f228c3bc52928c9b7
C#
HristoShabanakov/CSharp-ADVANCED-January2019
/C# Advanced/02.Stacks And Queues - Exercise/06.AutoRepairAndService/06.AutoRepairAndService.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { string[] cars = Console.ReadLine().Split(); string input; Queue<string> vehicles = new Queue<string>(cars); Stack<string> servedVehicles = new Stack<string>(); while ((input = Console.ReadLine()) != "End") { string[] commands = input.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries).ToArray(); if (commands[0] == "Service") { Console.WriteLine($"Vehicle {vehicles.Peek()} got served."); string car = vehicles.Peek(); vehicles.Dequeue(); servedVehicles.Push(car); } else if (commands[0] == "CarInfo") { string currentCar = commands[1]; if (!vehicles.Contains(currentCar)) { Console.WriteLine("Served."); } else { Console.WriteLine("Still waiting for service."); } } else if (commands[0] == "History") { Console.WriteLine(string.Join(", ", servedVehicles)); } } if (vehicles.Any()) { Console.WriteLine($"Vehicles for service: {string.Join(", ", vehicles)}"); } Console.WriteLine($"Served vehicles: {string.Join(", ", servedVehicles)}"); } }
b8a6423d95925fa9b4a7efa16f700a5218e47965
C#
erangeljr/DesignPatterns
/BridgePattern/Pharmacy.cs
3.15625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BridgePattern { public class Pharmacy : Referral { public int PharmacyReferralId { get; set; } public string Member { get; set; } public Dictionary<string, string> NationalDrugCode { get; set; } public Pharmacy(IFormatter formatter) : base(formatter) { NationalDrugCode = new Dictionary<string, string>(); } public override void Print() { Console.WriteLine(formatter.Format("Pharmacy Number", PharmacyReferralId.ToString())); Console.WriteLine(formatter.Format("Member", Member)); foreach (var drug in NationalDrugCode) { Console.WriteLine(formatter.Format("Code", drug.Key)); Console.WriteLine(formatter.Format("Name", drug.Value)); } Console.WriteLine(); } } }
17a0d96c1879907ca29a70bccbb002a23017339c
C#
lattic/VRSimulator
/Src/ProjectCars/MikeyTT-pcars-api-demo-5eb320b60b20/pCarsAPI-Demo/MainWindow.xaml.cs
2.5625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; namespace pCarsAPI_Demo { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public static int STRING_LENGTH_MAX = 64; public pCarsDataClass pcarsData = new pCarsDataClass(); private DispatcherTimer dispatchTimer = new DispatcherTimer(); public MainWindow() { InitializeComponent(); this.DataContext = pcarsData; dispatchTimer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(1) }; dispatchTimer.Tick += pCarsDataGetterLoop; dispatchTimer.Start(); } private void pCarsDataGetterLoop(object sender, EventArgs e) { var returnTuple = pCarsAPI_GetData.ReadSharedMemoryData(); //item1 is the true/false indicating a good read or not if (returnTuple.Item1) { //map the data that's read from the struct and map it to the class pcarsData = pcarsData.MapStructToClass(returnTuple.Item2, pcarsData); //Thread.Sleep(500); } else { //throw some kind of error or warning? } } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { dispatchTimer.Stop(); } } }
30623b1b973217959009405ba7820b389999c38c
C#
ggpo1/foodstorage_backend
/Services/RoomService/RoomService.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FoodStorage_Backend.Models; using FoodStorage_Backend.Models.DataBase; namespace FoodStorage_Backend.Services.RoomService { public class RoomService : IRoomService { public Task<Room> AddRoom(Room room) { MyDb.db.Rooms.Add(room); MyDb.db.SaveChanges(); return Task.Run(() => room); } public Task<Apartment> GetApartmentByRoomID(int roomID) { return Task.Run(() => MyDb.db.Rooms.FirstOrDefault(elem => elem.RoomID == roomID).Apartment); } public Task<List<Room>> GetApartmentRooms(int apartmentID) { return Task.Run(() => MyDb.db.Rooms.Where(elem => elem.ApartmentID == apartmentID).ToList()); } public Task<Room> GetRoomByID(int roomID) { return Task.Run(() => MyDb.db.Rooms.FirstOrDefault(elem => elem.RoomID == roomID)); } public Task<List<Room>> GetRooms() { return Task.Run(() => MyDb.db.Rooms.ToList()); } public Task<User> GetUserByRoomID(int roomID) { return Task.Run(() => MyDb.db.Rooms.FirstOrDefault(elem => elem.RoomID == roomID).Apartment.User); } } }
db41abaa084dd04a74ab74335e2e3bd0c213e4b6
C#
borko-rajkovic/LinqPractice
/013 Java (Read only)/007 Lambda/Lambda.linq
3.359375
3
<Query Kind="Program"> <Reference>&lt;RuntimeDirectory&gt;\System.Threading.dll</Reference> <Reference>&lt;RuntimeDirectory&gt;\System.Threading.Tasks.dll</Reference> </Query> class Program { public class Country { private String name; private int size; private String continent; public Country(String n, String c, int sz) { name = n; size = sz; continent = c; } public String GetName() { return name; } public String GetContinent() { return continent; } public int GetPopulation() { return size; } } public static int GetPopulation(List<Country> countries, String continent) { //var sublist = countries.Where(country => country.GetContinent().Equals(continent)); // Get list of populations //var populations = sublist.Select(c => c.GetPopulation()); // One way of getting sum // int population = populations.Aggregate(0, (x, y) => x + y); // Sum aggregate - the other way // int population = populations.Sum(); int population = countries.Select(c => c.GetContinent().Equals(continent) ? c.GetPopulation() : 0).Sum(); return population; } public static void Main(String[] args) { List<Country> countries = new List<Country>(); countries.Add(new Country("United States", "North America", 1)); countries.Add(new Country("Canada", "North America", 5)); countries.Add(new Country("India", "Asia", 9)); countries.Add(new Country("Japan", "Asia", 7)); Console.WriteLine(GetPopulation(countries, "Asia")); } }
6a18ce6a0e199f3e478923f4fa6d3cdada89c769
C#
VAllens/qMISPlat
/Library/Common/NVelocity/Runtime/Directive/VMProxyArg.cs
2.953125
3
// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace NVelocity.Runtime.Directive { using System; using System.IO; using Context; using NVelocity.Exception; using NVelocity.Runtime.Parser.Node; using Parser; /// <summary> /// The function of this class is to proxy for the calling parameter to the VM. /// * /// This class is designed to be used in conjunction with the VMContext class /// which knows how to get and set values via it, rather than a simple get() /// or put() from a hashtable-like object. /// * /// There is probably a lot of undocumented subtlety here, so step lightly. /// * /// We rely on the observation that an instance of this object has a constant /// state throughout its lifetime as it's bound to the use-instance of a VM. /// In other words, it's created by the VelocimacroProxy class, to represent /// one of the arguments to a VM in a specific template. Since the template /// is fixed (it's a file...), we don't have to worry that the args to the VM /// will change. Yes, the VM will be called in other templates, or in other /// places on the same template, bit those are different use-instances. /// * /// These arguments can be, in the lingo of /// the parser, one of : /// <ul> /// <li> Reference() : anything that starts with '$'</li> /// <li> StringLiteral() : something like "$foo" or "hello geir"</li> /// <li> NumberLiteral() : 1, 2 etc</li> /// <li> IntegerRange() : [ 1..2] or [$foo .. $bar]</li> /// <li> ObjectArray() : [ "a", "b", "c"]</li> /// <li> True() : true</li> /// <li> False() : false</li> /// <li>Word() : not likely - this is simply allowed by the parser so we can have /// syntactical sugar like #foreach($a in $b) where 'in' is the Word</li> /// </ul> /// Now, Reference(), StringLit, NumberLit, IntRange, ObjArr are all dynamic things, so /// their value is gotten with the use of a context. The others are constants. The trick /// we rely on is that the context rather than this class really represents the /// state of the argument. We are simply proxying for the thing, returning the proper value /// when asked, and storing the proper value in the appropriate context when asked. /// * /// So, the hope here, so an instance of this can be shared across threads, is to /// keep any dynamic stuff out of it, relying on trick of having the appropriate /// context handed to us, and when a constant argument, letting VMContext punch that /// into a local context. /// /// </summary> /// <author> <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: VMProxyArg.cs,v 1.4 2003/10/27 13:54:10 corts Exp $ /// /// </version> public class VMProxyArg { /// <summary>type of arg I will have /// </summary> private int type = 0; /// <summary>the AST if the type is such that it's dynamic (ex. JJTREFERENCE ) /// </summary> private SimpleNode nodeTree = null; /// <summary>reference for the object if we proxy for a static arg like an NumberLiteral /// </summary> private Object staticObject = null; /// <summary>not used in this impl : carries the appropriate user context /// </summary> private IInternalContextAdapter userContext = null; /// <summary>number of children in our tree if a reference /// </summary> private readonly int numTreeChildren = 0; /// <summary>our identity in the current context /// </summary> private readonly String contextReference = null; /// <summary>the reference we are proxying for /// </summary> private readonly String callerReference = null; /// <summary>the 'de-dollared' reference if we are a ref but don't have a method attached /// </summary> private readonly String singleLevelRef = null; /// <summary>by default, we are dynamic. safest /// </summary> private bool constant = false; /// <summary>in the event our type is switched - we don't care really what it is /// </summary> private const int GENERALSTATIC = - 1; private readonly IRuntimeServices runtimeServices = null; /// <summary> ctor for current impl /// * /// takes the reference literal we are proxying for, the literal /// the VM we are for is called with... /// * /// </summary> /// <param name="rs"> /// </param> /// <param name="contextRef">reference arg in the definition of the VM, used in the VM /// </param> /// <param name="callerRef"> reference used by the caller as an arg to the VM /// </param> /// <param name="t"> type of arg : JJTREFERENCE, JJTTRUE, etc /// /// </param> public VMProxyArg(IRuntimeServices rs, String contextRef, String callerRef, int t) { runtimeServices = rs; contextReference = contextRef; callerReference = callerRef; type = t; // make our AST if necessary setup(); // if we are multi-node tree, then save the size to // avoid fn call overhead if (nodeTree != null) { numTreeChildren = nodeTree.ChildrenCount; } // if we are a reference, and 'scalar' (i.e. $foo ) // then get the de-dollared ref so we can // hit our context directly, avoiding the AST if (type == ParserTreeConstants.REFERENCE) { if (numTreeChildren == 0) { // do this properly and use the Reference node singleLevelRef = ((ASTReference) nodeTree).RootString; } } } public String CallerReference { get { return callerReference; } } public String ContextReference { get { return contextReference; } } public SimpleNode NodeTree { get { return nodeTree; } } public Object StaticObject { get { return staticObject; } } public int Type { get { return type; } } /// <summary> tells if arg we are proxying for is /// dynamic or constant. /// * /// </summary> /// <returns>true of constant, false otherwise /// /// </returns> public bool isConstant() { return constant; } /// <summary> Invoked by VMContext when Context.put() is called for a proxied reference. /// * /// </summary> /// <param name="context">context to modify via direct placement, or AST.setValue() /// </param> /// <param name="o"> new value of reference /// </param> /// <returns>Object currently null /// /// </returns> public Object setObject(IInternalContextAdapter context, Object o) { /* * if we are a reference, we could be updating a property */ if (type == ParserTreeConstants.REFERENCE) { if (numTreeChildren > 0) { /* * we are a property, and being updated such as * #foo( $bar.BangStart) */ try { ((ASTReference) nodeTree).SetValue(context, o); } catch(MethodInvocationException methodInvocationException) { runtimeServices.Error( string.Format("VMProxyArg.getObject() : method invocation error setting value : {0}", methodInvocationException)); } } else { /* * we are a 'single level' reference like $foo, so we can set * out context directly */ context.Put(singleLevelRef, o); // alternate impl : userContext.put( singleLevelRef, o); } } else { /* * if we aren't a reference, then we simply switch type, * get a new value, and it doesn't go into the context * * in current impl, this shouldn't happen. */ type = GENERALSTATIC; staticObject = o; runtimeServices.Error( string.Format("VMProxyArg.setObject() : Programmer error : I am a constant! No setting! : {0} / {1}", contextReference, callerReference)); } return null; } /// <summary> returns the value of the reference. Generally, this is only /// called for dynamic proxies, as the static ones should have /// been stored in the VMContext's localContext store /// * /// </summary> /// <param name="context">Context to use for getting current value /// </param> /// <returns>Object value /// * /// /// </returns> public Object getObject(IInternalContextAdapter context) { try { /* * we need to output based on our type */ Object retObject = null; if (type == ParserTreeConstants.REFERENCE) { /* * two cases : scalar reference ($foo) or multi-level ($foo.bar....) */ if (numTreeChildren == 0) { /* * if I am a single-level reference, can I not get get it out of my context? */ retObject = context.Get(singleLevelRef); } else { /* * I need to let the AST produce it for me. */ retObject = nodeTree.Execute(null, context); } } else if (type == ParserTreeConstants.OBJECT_ARRAY) { retObject = nodeTree.Value(context); } else if (type == ParserTreeConstants.INTEGER_RANGE) { retObject = nodeTree.Value(context); } else if (type == ParserTreeConstants.TRUE) { retObject = staticObject; } else if (type == ParserTreeConstants.FALSE) { retObject = staticObject; } else if (type == ParserTreeConstants.STRING_LITERAL) { retObject = nodeTree.Value(context); } else if (type == ParserTreeConstants.NUMBER_LITERAL) { retObject = staticObject; } else if (type == ParserTreeConstants.TEXT) { /* * this really shouldn't happen. text is just a throwaway arg for #foreach() */ try { StringWriter writer = new StringWriter(); nodeTree.Render(context, writer); retObject = writer; } catch(Exception e) { runtimeServices.Error(string.Format("VMProxyArg.getObject() : error rendering reference : {0}", e)); } } else if (type == GENERALSTATIC) { retObject = staticObject; } else { runtimeServices.Error( string.Format("Unsupported VM arg type : VM arg = {0} type = {1}( VMProxyArg.getObject() )", callerReference, type)); } return retObject; } catch(MethodInvocationException mie) { /* * not ideal, but otherwise we propagate out to the * VMContext, and the Context interface's put/get * don't throw. So this is a the best compromise * I can think of */ runtimeServices.Error(string.Format("VMProxyArg.getObject() : method invocation error getting value : {0}", mie)); return null; } } /// <summary> does the housekeeping upon creating. If a dynamic type /// it needs to make an AST for further get()/set() operations /// Anything else is constant. /// </summary> private void setup() { switch(type) { case ParserTreeConstants.INTEGER_RANGE: case ParserTreeConstants.REFERENCE: case ParserTreeConstants.OBJECT_ARRAY: case ParserTreeConstants.STRING_LITERAL: case ParserTreeConstants.TEXT: { /* * dynamic types, just render */ constant = false; try { /* * fakie : wrap in directive to get the parser to treat our args as args * it doesn't matter that #include() can't take all these types, because we * just want the parser to consider our arg as a Directive/VM arg rather than * as if inline in schmoo */ String buff = string.Format("#include({0} ) ", callerReference); //ByteArrayInputStream inStream = new ByteArrayInputStream( buff.getBytes() ); //UPGRADE_ISSUE: The equivalent of constructor 'java.io.BufferedReader.BufferedReader' is incompatible with the expected type in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1109"' TextReader br = new StringReader(buff); nodeTree = runtimeServices.Parse(br, string.Format("VMProxyArg:{0}", callerReference), true); /* * now, our tree really is the first DirectiveArg(), and only one */ nodeTree = (SimpleNode) nodeTree.GetChild(0).GetChild(0); /* * sanity check */ if (nodeTree != null && nodeTree.Type != type) { runtimeServices.Error("VMProxyArg.setup() : programmer error : type doesn't match node type."); } /* * init. We can do this as they are only references */ nodeTree.Init(null, runtimeServices); } catch(Exception e) { runtimeServices.Error(string.Format("VMProxyArg.setup() : exception {0} : {1}", callerReference, e)); } break; } case ParserTreeConstants.TRUE: { constant = true; staticObject = true; break; } case ParserTreeConstants.FALSE: { constant = true; staticObject = false; break; } case ParserTreeConstants.NUMBER_LITERAL: { constant = true; staticObject = Int32.Parse(callerReference); break; } case ParserTreeConstants.WORD: { /* * this is technically an error... */ runtimeServices.Error( string.Format( "Unsupported arg type : {0} You most likely intended to call a VM with a string literal, so enclose with ' or \" characters. (VMProxyArg.setup())", callerReference)); constant = true; staticObject = new String(callerReference.ToCharArray()); break; } default: { runtimeServices.Error(string.Format(" VMProxyArg.setup() : unsupported type : {0}", callerReference)); } break; } } /* * CODE FOR ALTERNATE IMPL : please ignore. I will remove when comfortable with current. */ /// <summary> not used in current impl /// * /// Constructor for alternate impl where VelProxy class would make new /// VMProxyArg objects, and use this constructor to avoid re-parsing the /// reference args /// * /// that impl also had the VMProxyArg carry it's context /// </summary> public VMProxyArg(VMProxyArg model, IInternalContextAdapter c) { userContext = c; contextReference = model.ContextReference; callerReference = model.CallerReference; nodeTree = model.NodeTree; staticObject = model.StaticObject; type = model.Type; if (nodeTree != null) { numTreeChildren = nodeTree.ChildrenCount; } if (type == ParserTreeConstants.REFERENCE) { if (numTreeChildren == 0) { /* * use the reference node to do this... */ singleLevelRef = ((ASTReference) nodeTree).RootString; } } } } }
faf6611f03b77e11817d4ec427b43509fa89f801
C#
M1rceaDogaru/black-and-white-console
/MapLoader.cs
3.015625
3
using Push.Models; using System; using System.IO; namespace Push { public class MapLoader { private readonly TileManager _tileManager; private readonly BoxManager _boxManager; public MapLoader(TileManager tileManager, BoxManager boxManager) { _tileManager = tileManager; _boxManager = boxManager; } public bool LoadMapFrom(string filePath) { if (!File.Exists(filePath)) { return false; } var fileContent = File.ReadAllText(filePath); var fileLines = fileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); _tileManager.Clear(); _boxManager.Clear(); var positionY = 0; foreach (var line in fileLines) { if (line.StartsWith("-")) { _tileManager.AddLevelMessage(line); continue; } var positionX = 0; foreach (var character in line) { AddTile(character, positionX, positionY); positionX++; } positionY++; } return true; } private void AddTile(char character, int positionX, int positionY) { switch (character) { case 'B': AddTile(positionX, positionY, TileType.Black); break; case 'W': AddTile(positionX, positionY, TileType.White); break; case 'S': AddSwitch(positionX, positionY, TileType.White); break; case 'A': AddStart(positionX, positionY); break; case 'Y': AddEnd(positionX, positionY, TileType.White); break; case 'Z': AddEnd(positionX, positionY, TileType.Black); break; case '#': AddTileWithBox(positionX, positionY, BoxColor.Red, TileType.White); break; case '%': AddTileWithBox(positionX, positionY, BoxColor.Blue, TileType.Black); break; default: AddTile(positionX, positionY, TileType.Null); break; } } private void AddTileWithBox(int positionX, int positionY, BoxColor boxColor, TileType tileType) { var tile = new Tile { Id = Guid.NewGuid(), TileType = tileType, PositionX = positionX, PositionY = positionY }; _tileManager.AddTile(tile); _boxManager.AddBox(new Box { Id = Guid.NewGuid(), Color = boxColor, TileItsOn = tile }); } private void AddTile(int positionX, int positionY, TileType type) { _tileManager.AddTile(new Tile { Id = Guid.NewGuid(), TileType = type, PositionX = positionX, PositionY = positionY }); } private void AddSwitch(int positionX, int positionY, TileType type) { _tileManager.AddTile(new Switch { Id = Guid.NewGuid(), TileType = type, PositionX = positionX, PositionY = positionY }); } private void AddStart(int positionX, int positionY) { _tileManager.AddTile(new Start { Id = Guid.NewGuid(), PositionX = positionX, PositionY = positionY }); } private void AddEnd(int positionX, int positionY, TileType tileType) { _tileManager.AddTile(new End { Id = Guid.NewGuid(), TileType = tileType, PositionX = positionX, PositionY = positionY }); } } }
e3349ff73fd30311c793a71ee03f33b00d634c78
C#
bat-here/Unimoved
/HeapMedian.cs
3.546875
4
using System; using System.Collections.Generic; using System.IO; using System.Linq; class HeapMedian { /* Create two heaps, one min heap to hold numbers higher than the current median and one max heap to hold numbers lower than the current median. For each new number, if it is greater than the current median, add it to the min heap if it is smaller, add it to the max heap. Then balance the heaps to make sure that no heap is bigger than the other by more than 1. If the min/max heap has more than 2 elements over its corresponding heap. Move the top of the heap to the other one. Max/Min Heapify the heaps. To get the median, get the top element of the heap with the greater size, or the average of the top elements of the two heaps if their sizes are equal. */ static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); string[] a_temp = new string[n]; for(int i=0; i<n;i++){ a_temp[i] = Console.ReadLine(); } int[] a = Array.ConvertAll(a_temp,Int32.Parse); List<int> minHeap = new List<int> (); List<int> maxHeap = new List<int> (); decimal median = (decimal)a[0]; minHeap.Add(a[0]); Console.WriteLine(median.ToString("F1")); for(int i=1; i<a.Length;i++){ if(a[i] < median){ maxHeap.Add(a[i]); MaxHeapify(maxHeap,maxHeap.Count-1); } else{ minHeap.Add(a[i]); MinHeapify(minHeap,minHeap.Count-1); } if(maxHeap.Count > minHeap.Count + 1){ minHeap.Add(maxHeap[0]); MinHeapify(minHeap,minHeap.Count-1); Remove(maxHeap, true); } if(minHeap.Count > maxHeap.Count + 1){ maxHeap.Add(minHeap[0]); MaxHeapify(maxHeap,maxHeap.Count-1); Remove(minHeap,false); } MaxHeapifyDown(maxHeap,0); MinHeapifyDown(minHeap,0); if(minHeap.Count > maxHeap.Count){ median = (decimal)minHeap[0]; } else if(minHeap.Count < maxHeap.Count){ median = (decimal)maxHeap[0]; } else{ median = ((decimal)minHeap[0] + (decimal)maxHeap[0]) / 2; } Console.WriteLine(median.ToString("F1")); } } //Debugging function static void debug(List<int> maxHeap, List<int> minHeap,int idx){ if(idx > 190){ Console.WriteLine(idx+1 + ":"); Console.Write("Max Heap "); outputElements(maxHeap); Console.Write("Min Heap "); outputElements(minHeap); } } //Function for removing top element of heap, //Swap top and last element, use trickle down heapify //bool variable used so to differentiate between max and min heap static void Remove(List<int> heap, bool max){ SwapElements(heap,0,heap.Count-1); heap.RemoveAt(heap.Count-1); if(max){ MaxHeapifyDown(heap,0); } else{ MinHeapifyDown(heap,0); } } static void MaxHeapify(List<int> heap, int i){ if(i > 0){ int parent; if(i % 2 == 0){ parent = (i-1) /2; } else{ parent = i/2; } if(heap[i] > heap[parent]){ SwapElements(heap,i,parent); MaxHeapify(heap,parent); } } } static void MaxHeapifyDown(List<int> heap, int i){ int left = 2 * (i+1) - 1; int right = 2 * (i+1); int largest = i; if(left < heap.Count && heap[left] > heap[largest] ){ largest = left; } if(right < heap.Count && heap[right] > heap[largest]){ largest = right; } if(largest != i){ SwapElements(heap,largest,i); MaxHeapifyDown(heap,largest); } } static void MinHeapify(List<int> heap, int i){ if(i > 0){ int parent; if(i % 2 == 0){ parent = (i-1) /2; } else{ parent = i/2; } if(heap[i] < heap[parent]){ SwapElements(heap,i,parent); MinHeapify(heap,parent); } } } static void MinHeapifyDown(List<int> heap, int i){ int left = 2 * (i+1) - 1; int right = 2 * (i+1); int smallest = i; if(left < heap.Count && heap[left] < heap[smallest] ){ smallest = left; } if(right < heap.Count && heap[right] < heap[smallest]){ smallest = right; } if(smallest != i){ SwapElements(heap,smallest,i); MinHeapifyDown(heap,smallest); } } static void SwapElements(List<int> heap, int i, int j){ int temp = heap[i]; heap[i] = heap[j]; heap[j] = temp; } static void MaxHeapRemove(List<int> heap, int i){ } static void outputElements(List<int> heap){ foreach(int i in heap){ Console.Write(i + " "); } Console.WriteLine(); } }
314a3cdaf974b000c629c2c27aa3b2f0fd55b8de
C#
LeChatNoir666/renamerNG
/Renamer.cs
2.90625
3
using System; using System.Windows.Forms; namespace RenamerNG { /// <summary> /// Summary description for Renamer. /// </summary> public class Renamer { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { if (args.Length == 0) { Application.Run(new FrmMain("")); } else if (args.Length == 1) { Application.Run(new FrmMain(args[0])); } else { string msg = "Invalid number of parameters, found " + args.Length.ToString() + " expected 0 or 1.\nRefer to manual for parameter specification."; FrmMain.ErrorMessage(msg); } } } }
d6846f8ac7ea67418777379d633f5cd4fe7dd3a9
C#
ThePriestt/Chapter6
/03Task/Program.cs
3.765625
4
using System; // Напишете програма, която чете от конзолата поредица от цели числа и отпечатва най-малкото и най-голямото от тях. class Program { static void Main() { Console.WriteLine("Моля въведете броя на числата n"); int n = int.Parse(Console.ReadLine()); int currentNumber; int min = 0; int max = 0; for (int i = 0; i < n; i++) { Console.WriteLine("Моля въведете число"); currentNumber = int.Parse(Console.ReadLine()); if (i == 0) { min = currentNumber; max = currentNumber; } if (currentNumber < min) { min = currentNumber; } if (currentNumber > max) { max = currentNumber; } } Console.WriteLine("Най-малкото число е {0}", min); Console.WriteLine("Най-голямото число е {0}", max); } }