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
4308d460a48c48c3b5e9c23c4b1d6c636c922c60
C#
shendongnian/download4
/first_version_download2/374669-32256687-98377146-2.cs
2.734375
3
class BackgroundWorkerExample { private BackgroundWorker _backgroundWorker; public Program() { _backgroundWorker = new BackgroundWorker(); _backgroundWorker.DoWork += BackgroundWorker_DoWork; _backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted; } private void button1_Click(object sender, EventArgs e) { _backgroundWorker.RunWorkerAsync(); } private static void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { //some selenium code to tests something } private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //Whatever you want to do when the tests complete } }
c32fa2f2a75a9c41a6bd8042331dcea110a745bf
C#
StPeteFrank/numberpicker2practice
/Program.cs
3.78125
4
using System; namespace numberpicker2practice { class Program { static void Main(string[] args) { var minimum = 0; var maximum = 100; var guess = maximum / 2; var guessing = true; Console.WriteLine(guess); while (guessing) { Console.WriteLine("Is your number higher or lower?"); var userResponse = Console.ReadLine(); if (userResponse == "higher") { minimum = guess + 1; guess = (maximum + minimum) / 2; Console.WriteLine($"Is your number {guess} ?"); } if (userResponse == "lower") { maximum = guess - 1; guess = (maximum + minimum) / 2; Console.WriteLine($"Is your number {guess} ?"); } if (userResponse == "That's it!") { guessing = false; System.Console.WriteLine($"Your number is {guess} have a nice one!"); } } } } }
3584dbac4e55f79702c8c6051ce899a9fdb0566b
C#
w2Mac/CHashTest
/pitest.cs
3.796875
4
using System; namespace UserInput { public class SeptaClass { public static void Main(string[] args) { string userInput1; string userInput2; int a; int b; Console.Write("Please give a number as 1st variable: "); userInput1 = Console.ReadLine(); /* Converts to integer type */ a = Convert.ToInt32(userInput1); Console.Write("Please give a number as 2nd variable: "); userInput2 = Console.ReadLine(); /* Converts to double type */ b = Convert.ToInt32(userInput2); Console.WriteLine("The value of the 1st variable: {0}",b); Console.WriteLine("The value of the 2nd variable: {0}",a); } } }
cb73bb4b935573d5840b6f1fcea75c1fb0ebe953
C#
walidulhasan/TestService
/TestService/CustomValidation/uparCase.cs
3.078125
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text.RegularExpressions; using System.Web; namespace TestService.CustomValidation { public class UpperCaseAttribute : ValidationAttribute { //UpperCase protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { string suppliedValue = (string)value; var hasUpperChar = new Regex(@"[A-Z]+"); var match = hasUpperChar.IsMatch(suppliedValue); if (match == false) { return new ValidationResult("Input Should Have Uppercase "); } } return ValidationResult.Success; } } }
78fcd5fe3ac29747b135c103ab8e1b9a70f907bf
C#
Wumpus-Team-Chi/Wumpus-Code
/HuntTheWumpus/HighScore.cs
3.453125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HuntTheWumpus { class HighScore { private int playerScore; public HighScore(int score) { playerScore = score; } public int setStartingScore(int score) { playerScore = score; return playerScore; // allows gameControl to determine the player's score at the start. } public int getScoreAfterTurn(bool turn) { if(turn == true) { playerScore = playerScore - 100; } return playerScore; // this method returns the score after a turn was made in the game. // Parameter is from game control. Will determine if a turn was made. } public int getFinalScore(bool winOrLoss, int coins, int arrows) { if(winOrLoss == true) { playerScore = playerScore + (1000 * arrows) + (100 * coins) + 2500; } else { playerScore = 0; } return playerScore; // returns final score using boolean paramter to determine if a win or a loss. } public String toString() { String str = "Score: "; str += playerScore; return str; // displays current score } public String showHighScores() { String str = "High Scores: " + playerScore; return str; } } }
f9e9f036ff85c05643d523008d0ea53950190cc2
C#
PNNL-Comp-Mass-Spec/Informed-Proteomics
/InformedProteomics.TopDown/Scoring/FlipScoringGraphEdge.cs
2.6875
3
using System; using InformedProteomics.Backend.Data.Sequence; using InformedProteomics.Backend.Data.Spectrometry; using InformedProteomics.Scoring.GeneratingFunction; using InformedProteomics.TopDown.Scoring.FlipScoring; namespace InformedProteomics.TopDown.Scoring { /// <summary> /// Scoring graph edge for a scoring graph that using the FLIP scoring model. /// </summary> public class FlipScoringGraphEdge : IScoringGraphEdge { /// <summary> /// The FLIP scoring model. /// </summary> private readonly FlipScorer<DeconvolutedSpectrum> scorer; /// <summary> /// Initializes a new instance of the <see cref="FlipScoringGraphEdge" /> /// with initialized data. /// </summary> /// <param name="prevNodeIndex">The source node index.</param> /// <param name="sinkNodeIndex">The sink node index.</param> /// <param name="weight">The edge weight.</param> /// <param name="label">The amino acid that the edge corresponds to.</param> /// <param name="scorer">The FLIP scoring model.</param> public FlipScoringGraphEdge( int prevNodeIndex, int sinkNodeIndex, double weight, AminoAcid label, FlipScorer<DeconvolutedSpectrum> scorer) { PrevNodeIndex = prevNodeIndex; SinkNodeIndex = sinkNodeIndex; Weight = weight; Label = label; this.scorer = scorer; } /// <summary> /// Initializes a new instance of the <see cref="FlipScoringGraphEdge" /> /// with uninitialized data. /// </summary> /// <param name="scorer">The FLIP scoring model.</param> public FlipScoringGraphEdge(FlipScorer<DeconvolutedSpectrum> scorer) : this(0, 0, 0, null, scorer) { } /// <summary> /// Gets or sets the source node index. /// </summary> public int PrevNodeIndex { get; set; } /// <summary> /// Gets or sets the sink node index. /// </summary> public int SinkNodeIndex { get; set; } /// <summary> /// Gets or sets the weight of the node. /// </summary> public double Weight { get; set; } /// <summary> /// Gets or sets the amino acid that the edge corresponds to. /// </summary> public AminoAcid Label { get; set; } /// <summary> /// Gets of the score of the edge. /// </summary> /// <returns>The score of the edge.</returns> public double GetScore() { var massError = Math.Abs(SinkNodeIndex - (PrevNodeIndex + Label.Mass)) / SinkNodeIndex * 1e6; var errorScore = scorer.GetErrorScore(massError); return errorScore + Weight; } } }
22fc4be5843c569217ceebb8c3b46464a9305f12
C#
steveavl46/AdvantageLaser
/AdvantageLaserData/Data/BusObjects/DataAccess/CouponDataAccess.cs
2.625
3
using AdvLaser.AdvLaserObjects; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace AdvLaser.AdvLaserDataAccess { public static class CouponDataAccess { public static Coupon GetOne(int aCouponKey) { SqlCommand sqlCmd = new SqlCommand(); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, aCouponKey); BaseDataAccess.SetCommandType(sqlCmd, CommandType.StoredProcedure, "Coupon_GetOne"); BaseDataAccess.GenerateObjectFromReader sqlData = new BaseDataAccess.GenerateObjectFromReader(CreateCoupon); Coupon aCoupon = (Coupon)BaseDataAccess.ExecuteObjectReader(sqlCmd, sqlData); return aCoupon; } public static Coupon GetOneByCode(string aCode) { SqlCommand sqlCmd = new SqlCommand(); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@CouponCode", SqlDbType.VarChar, 8, ParameterDirection.Input, aCode); BaseDataAccess.SetCommandType(sqlCmd, CommandType.StoredProcedure, "GetCouponByCode"); BaseDataAccess.GenerateObjectFromReader sqlData = new BaseDataAccess.GenerateObjectFromReader(CreateCoupon); Coupon aCoupon = (Coupon)BaseDataAccess.ExecuteObjectReader(sqlCmd, sqlData); return aCoupon; } public static Object CreateCoupon(SqlDataReader returnData) { Coupon aCoupon = null; while (returnData.Read()) { aCoupon = new Coupon(); aCoupon.CouponKey = (int)returnData["CouponKey"]; aCoupon.CouponCode = (string)returnData["CouponCode"]; aCoupon.Description = (string)returnData["Description"]; aCoupon.StartDate = (DateTime)returnData["StartDate"]; aCoupon.EndDate = (DateTime)returnData["EndDate"]; aCoupon.CouponTypeKey = (int)returnData["CouponTypeKey"]; aCoupon.CouponCategoryKey = (int)returnData["CouponCategoryKey"]; aCoupon.DollarValue = (decimal)returnData["DollarValue"]; aCoupon.PercentValue = (decimal)returnData["PercentValue"]; aCoupon.MinimumOrder = (decimal)returnData["MinimumOrder"]; } return aCoupon; } public static int SaveCoupon(Coupon aCoupon) { if (aCoupon.CouponKey == 0) { return createNewCoupon(aCoupon); } else { return updateCoupon(aCoupon); } } public static SqlCommand SaveCouponCommand(Coupon aCoupon) { if (aCoupon.CouponKey == 0) { return createNewCouponCommand(aCoupon); } else { return createUpdateCouponCommand(aCoupon); } } private static int createNewCoupon(Coupon aCoupon) { SqlCommand sqlCmd = createNewCouponCommand(aCoupon); BaseDataAccess.ExecuteScalarCmd(sqlCmd); return ((int)sqlCmd.Parameters["@retval"].Value); } private static SqlCommand createNewCouponCommand(Coupon aCoupon) { SqlCommand sqlCmd = new SqlCommand(); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@CouponCode", SqlDbType.VarChar, 8, ParameterDirection.Input, aCoupon.CouponCode); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@Description", SqlDbType.VarChar, 25, ParameterDirection.Input, aCoupon.Description); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@StartDate", SqlDbType.DateTime, 8, ParameterDirection.Input, aCoupon.StartDate); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@EndDate", SqlDbType.DateTime, 8, ParameterDirection.Input, aCoupon.EndDate); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@CouponTypeKey", SqlDbType.Int, 0, ParameterDirection.Input, aCoupon.CouponTypeKey); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@CouponCategoryKey", SqlDbType.Int, 0, ParameterDirection.Input, aCoupon.CouponCategoryKey); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@DollarValue", SqlDbType.Float, 18, ParameterDirection.Input, aCoupon.DollarValue); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@PercentValue", SqlDbType.Float, 18, ParameterDirection.Input, aCoupon.PercentValue); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@MinimumOrder", SqlDbType.Float, 18, ParameterDirection.Input, aCoupon.MinimumOrder); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@retval", SqlDbType.Int, 0, ParameterDirection.Output, null); BaseDataAccess.SetCommandType(sqlCmd, CommandType.StoredProcedure, "Coupon_Create"); return sqlCmd; } private static SqlCommand createUpdateCouponCommand(Coupon aCoupon) { SqlCommand sqlCmd = new SqlCommand(); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@ID", SqlDbType.Int, 0, ParameterDirection.Input, aCoupon.CouponKey); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@CouponCode", SqlDbType.VarChar, 8, ParameterDirection.Input, aCoupon.CouponCode); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@Description", SqlDbType.VarChar, 25, ParameterDirection.Input, aCoupon.Description); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@StartDate", SqlDbType.DateTime, 8, ParameterDirection.Input, aCoupon.StartDate); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@EndDate", SqlDbType.DateTime, 8, ParameterDirection.Input, aCoupon.EndDate); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@CouponTypeKey", SqlDbType.Int, 0, ParameterDirection.Input, aCoupon.CouponTypeKey); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@CouponCategoryKey", SqlDbType.Int, 0, ParameterDirection.Input, aCoupon.CouponCategoryKey); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@DollarValue", SqlDbType.Float, 18, ParameterDirection.Input, aCoupon.DollarValue); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@PercentValue", SqlDbType.Float, 18, ParameterDirection.Input, aCoupon.PercentValue); BaseDataAccess.AddParamToSQLCmd(sqlCmd, "@MinimumOrder", SqlDbType.Float, 18, ParameterDirection.Input, aCoupon.MinimumOrder); BaseDataAccess.SetCommandType(sqlCmd, CommandType.StoredProcedure, "Coupon_Update"); return sqlCmd; } private static int updateCoupon(Coupon aCoupon) { SqlCommand sqlCmd = createUpdateCouponCommand(aCoupon); BaseDataAccess.ExecuteScalarCmd(sqlCmd); return aCoupon.CouponKey; } } }
810620e20e95457882ecf765e37e40473620ad62
C#
protokopf/-CS-Sheduler
/OrganizerCore/Model/ModelCore.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrganizerCore.Model { public class ModelCore : IDisposable { public interface IModelBaseCommunicator { void PushPackagesList(List<Package> pList); List<Package> PullPackagesList(); void PushOnePackage(Package package); Package PullOnePackage(Package package = null); void OpenBase(); void CloseBase(); } private IModelBaseCommunicator mCoreStorage; private List<MyTask> mTaskList; private StringBuilder mMessagesBuilder; private AbstractConvertor mStorageConvertor; private IEqualityComparer<Package> mPackageEquater; public ModelCore(IModelBaseCommunicator storageRef, IEqualityComparer<Package> packageEquater) { mPackageEquater = packageEquater; mCoreStorage = storageRef; mTaskList = new List<MyTask>(); mStorageConvertor = new Convertor(); mMessagesBuilder = new StringBuilder(); mCoreStorage.OpenBase(); LoadAllTasks(); } public void SaveAllTasks() { var pList = new List<Package>(); foreach (var task in mTaskList) pList.Add(mStorageConvertor.FromMyTaskToPackage(task)); mCoreStorage.PushPackagesList(pList); } public void LoadAllTasks() { var pList = mCoreStorage.PullPackagesList(); foreach (var package in pList) { MyTask task = mStorageConvertor.FromPackageToMyTask(package); task.SetPackageView(package); mTaskList.Add(task); } } public MyTask CheckIfTaskExists(Package package) { foreach (var task in mTaskList) if (mPackageEquater.Equals(package, task.GetPackageView())) return task; return null; } public Dictionary<int,string> GetTaskList() { Dictionary<int, string> tasks = new Dictionary<int, string>(); foreach (var task in mTaskList) tasks.Add(task.ID,task.ToString()); return tasks; } public string CheckEventAdvent() { mMessagesBuilder.Clear(); foreach(var ev in mTaskList) { if(ev.IsTime()) { mMessagesBuilder.Append(ev.Name).Append(" - ").Append(ev.Description); mTaskList.Remove(ev); return mMessagesBuilder.ToString(); } } return null; } public void AddTask(Package package) { if (CheckIfTaskExists(package) == null) { MyTask newtask = null; newtask = mStorageConvertor.FromPackageToMyTask(package); newtask.SetPackageView(package); mTaskList.Add(newtask); } } public void DeleteTask(Package package) { MyTask deletedTask = CheckIfTaskExists(package); if(deletedTask != null) mTaskList.Remove(deletedTask); } public void DeleteTask(int index) { mTaskList.RemoveRange(index, 1); } public Package GetTask(Package package) // в случае отсутствия пакета, возвращает null { return (CheckIfTaskExists(package)).GetPackageView(); } public void Dispose() { SaveAllTasks(); } } }
f34f16ea2713a405463ef8a23f49de1902f4c8a8
C#
BrianZell/TaskActions
/Src/IDT.TaskActions/BackoffInterval.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IDT.TaskActions { /// <summary> /// TimeSpan = smaller of (resetInterval * (count ^ scalingFactor)) or maxInterval /// </summary> public class BackoffInterval : IInterval { private readonly TimeSpan _resetInterval; private readonly TimeSpan _maxInterval; private readonly int _scalingFactor; public BackoffInterval(TimeSpan resetInterval, TimeSpan maxInterval, int scalingFactor) { _resetInterval = resetInterval; _maxInterval = maxInterval; _scalingFactor = scalingFactor; } public TimeSpan Calculate(int count) { var currentReset = new TimeSpan(_resetInterval.Ticks * Convert.ToInt64(Math.Pow(_scalingFactor, count))); return currentReset < _maxInterval ? currentReset : _maxInterval; } public static BackoffInterval Default { get { return new BackoffInterval(TimeSpan.FromSeconds(30), TimeSpan.FromHours(1), 2); } } } }
44cfab5b183c000a4e14fa5a938d8631bd5fd1f7
C#
gildasiocardoso/the-best-on-linq
/MakingLinqEasyTheBestOnLinq/FormMain.cs
3.1875
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 MakingLinqEasyTheBestOnLinq { /// <summary> /// LINQ Demonstration - feel free to use these material /// Created by Gildasio Cardoso - gildasiocardoso@gmail.com /// </summary> public partial class FormMain : Form { public FormMain() { InitializeComponent(); } string[] myArrayOfString = { "Honda", "Nissan", "Acura", "BMW", "Volvo", "Mazda", "Audi", "Volksvagem", "Dodge", "Ford" }; int[] myArrayOfNumber = { 2, 0, 1, 3, 4, 5, 6, 7, 9, 10, 8 }; private Boolean ShowResults(Decimal Param) { Decimal[] a = { Param }; string[] strArray = a.Select(s => s.ToString()).ToArray(); return ShowResults(strArray); } private Boolean ShowResults(Array Params) { Boolean result = false; txtResult.Clear(); for (int i = 0; (i < Params.Length); i++) { var str = Params.GetValue(i).ToString(); if (txtResult.Text == string.Empty) txtResult.Text = string.Concat("{", str); else txtResult.Text += string.Concat(", ", str); } result = (txtResult.Text != string.Empty); if (result) txtResult.Text += string.Concat("}"); return result; } private void btnArrayOfNumberSum_Click(object sender, EventArgs e) { var total = myArrayOfNumber.Sum(); txtResult.Clear(); // this way txtResult.Text = string.Format("{0:n}", total); // or you can do directly txtResult.Text = string.Format("{0:n}", myArrayOfNumber.Sum()); } private void btnArrayOfNumberOrderby_Click(object sender, EventArgs e) { var myResult = myArrayOfNumber.OrderBy(o => o); ShowResults(myResult.ToArray()); } private void btnArrayOfNumberDescendingOrder_Click(object sender, EventArgs e) { var result = myArrayOfNumber.OrderByDescending(d => d); ShowResults(result.ToArray()); } private void btnArrayOfNumberConcat_Click(object sender, EventArgs e) { int[] myArrayOfNumber2 = { 2, 0, 1, 3, 70, 90, 100, 80 }; var result = myArrayOfNumber.Concat(myArrayOfNumber2).Distinct(); ShowResults(result.ToArray()); } private void btnArrayOfNumberWhere_Click(object sender, EventArgs e) { var result = myArrayOfNumber.Where(w => (w >= 6)); ShowResults(result.ToArray()); } private void btnArrayOfStringContain_Click(object sender, EventArgs e) { var result = myArrayOfString.Where(w => w.Contains( "a")); ShowResults(result.ToArray()); } private void FormMain_Load(object sender, EventArgs e) { //tcScenario.SelectedTab = tpArrayOfString; tcScenario.SelectedTab = tpArrayOfNumber; carBrandBindingSource.DataSource = new CarBrand().GetAll().OrderBy(c => c.HostCountry ); //carBrandDataGridView.DataSource = } private void btnArrayOfStringContainCaseInSentitive_Click(object sender, EventArgs e) { var result = myArrayOfString.Where(w => w.ToUpper().Contains("A")); ShowResults(result.ToArray()); } private void btnArrayOfStringWhereOrderBy_Click(object sender, EventArgs e) { var result = myArrayOfString.Where(w => w.ToUpper().Contains("A")).OrderBy(ob => ob); ShowResults(result.ToArray()); } private void btnClassObjCountry_Click(object sender, EventArgs e) { // First way // or change everything for one single command ShowResults((new CarBrand().GetAll()) .Select(s => s.HostCountry) .Distinct() .OrderBy(o=>o).ToArray()); // Second way // or change to use the method I implemented into the class //ShowResults((new CarBrand()).GetCountries().ToArray()); /* // Third way // doing step by step // 1 returning a list of CarBrand var car_brand = new CarBrand().GetAll(); // 2 returning the column Country var country = car_brand.Select(s => s.HostCountry); // 3 removing duplicate values var result_country = country.Distinct(); // 4 ordening var result = result_country.OrderBy(o => o); ShowResults(result.ToArray()); */ } private void btnArrayOfStringStarstsWithEndsWith_Click(object sender, EventArgs e) { var result = myArrayOfString.Where(w => w.ToUpper().StartsWith("A") && w.ToUpper().EndsWith("A") ); ShowResults(result.ToArray()); } } }
c88eb7075636a3d3ba9a4b3625553b8e74d0f5d5
C#
iknowDavenMC/SuperFlash
/COMP476Proj/COMP476Proj/IntelligenceComponent/Pathfinding/AStar.cs
3.15625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace COMP476Proj { /// <summary> /// Static class to run the A* algorithm /// </summary> public static class AStar { /// <summary> /// Helper class for A* noeds /// </summary> private class AStarNode : IComparable<AStarNode> { public Node node; // Represented path node public AStarNode cameFrom; // A* node that leads to this one public float totalCost; public float costSoFar; public AStarNode(Node n) { node = n; cameFrom = null; totalCost = 0; costSoFar = 0; } // Used for comparing two nodes by the MinHeap public int CompareTo(AStarNode obj) { return Math.Sign(totalCost - obj.totalCost); } public static bool operator ==(AStarNode l, AStarNode r) { if ((object)l == null && (object)r == null) return true; if ((object)l == null || (object)r == null) return false; return l.node == r.node; } public static bool operator !=(AStarNode l, AStarNode r) { if ((object)l == null && (object)r == null) return false; if ((object)l == null || (object)r == null) return true; return l.node != r.node; } } /// <summary> /// Get a path from a start point to an end point using a set list of nodes /// </summary> /// <param name="start">Position to start at</param> /// <param name="end">Position to end at</param> /// <param name="graph">List of nodes to use</param> /// <param name="ignoreWeight">If true, extra weights will no be considered in the calculation or added to the edges</param> /// <returns>A list of nodes representing the path to take</returns> public static List<Node> GetPath(Vector2 start, Vector2 end, List<Node> graph, QuadTree grid, bool checkWalls = true, bool ignoreWeight = true) { List<Node> path = new List<Node>(); AStarNode startNode = new AStarNode(FindClosestNode(start, ref graph, ref grid, checkWalls)); AStarNode endNode = new AStarNode(FindClosestNode(end, ref graph, ref grid, checkWalls)); // If either the start or the end is null for some reason, return an empty list if (startNode.node == null || endNode.node == null) return new List<Node>(); List<AStarNode> closedList = new List<AStarNode>(); MinHeap<AStarNode> openList = new MinHeap<AStarNode>(); startNode.totalCost = getHeuristic(startNode, endNode); openList.Enqueue(startNode); while (!openList.IsEmpty()) { AStarNode current = openList.Top; // When the node being considered is the end node, stop if (current == endNode) if (ignoreWeight) return constructPath(current, 0, 0); else return constructPath(current, 3, 0.2f); openList.Dequeue(); closedList.Add(current); int edgeC = current.node.Edges.Count; for(int i=0; i!= edgeC; ++i) { Edge e = current.node.Edges[i]; AStarNode neighbour = closedList.Find(n => n.node == e.end); float costSoFar = current.costSoFar + e.Cost - (ignoreWeight ? 0 : e.Weight); if (neighbour != null) { // If the neighbouring node is already in the closed list and its // cost is less than this one, skip it if (costSoFar >= neighbour.costSoFar) continue; } else neighbour = new AStarNode(e.end); // If the node is already in the open list, find it and replace it if the new cost is lower if (openList.data.Contains(neighbour)) { List<AStarNode> openData = openList.data; neighbour = openData.Find(n => n == neighbour); if (costSoFar < neighbour.costSoFar) { neighbour.cameFrom = current; neighbour.costSoFar = costSoFar; neighbour.totalCost = costSoFar + getHeuristic(neighbour, endNode); // If the node is replaced, the heap has to be rebuilt openList.Clear(); int nodeC = openData.Count; for(int j=0; j!=nodeC; ++j) { openList.Enqueue(openData[j]); } } } else { neighbour.cameFrom = current; neighbour.costSoFar = costSoFar; neighbour.totalCost = costSoFar + getHeuristic(neighbour, endNode); openList.Enqueue(neighbour); } } } throw new Exception("AStar is returning in an impossible way"); } /// <summary> /// Get the heuristic value between two nodes (ie: Euclidean distance) /// </summary> /// <param name="n1"></param> /// <param name="n2"></param> /// <returns></returns> private static float getHeuristic(AStarNode n1, AStarNode n2) { return (n1.node.Position - n2.node.Position).LengthSquared(); } /// <summary> /// Construct the path recursively starting with the last node /// </summary> /// <param name="n">Current node</param> /// <param name="weight">Current weight value</param> /// <param name="weightPer">Additional weight per node in the path</param> /// <param name="next">Next node in the path</param> /// <returns>The final path of nodes</returns> private static List<Node> constructPath(AStarNode n, float weight, float weightPer, AStarNode next = null) { List<Node> path; // If this node didn't come from anywhere, it's the start. if (n.cameFrom == null) { if (next != null) { n.node.Edges.Find(e => e.end == next.node).Weight += weight; next.node.Edges.Find(e => e.end == n.node).Weight += weight; } path = new List<Node>(); path.Add(n.node); return path; } // recursion path = constructPath(n.cameFrom, weight - weightPer, weightPer, n); if (next != null) { n.node.Edges.Find(e => e.end == next.node).Weight += weight; next.node.Edges.Find(e => e.end == n.node).Weight += weight; } path.Add(n.node); return path; } /// <summary> /// Find the closest node to a point /// </summary> /// <param name="searchPos"></param> /// <param name="nodes"></param> /// <returns></returns> private static Node FindClosestNode(Vector2 searchPos, ref List<Node> nodes, ref QuadTree grid, bool checkWalls) { float minDist = float.MaxValue; Node closest = null; int nodeC = nodes.Count; List<Wall> check = new List<Wall>(); for(int n=0; n!= nodeC; ++n) { Node node = nodes[n]; if (grid != null && checkWalls) { LineSegment line = new LineSegment(searchPos, node.Position); bool blocked = false; // Check Quadtree check.Clear(); grid.getEntities(searchPos, ref check); int checkC = check.Count; for (int i = 0; i != checkC; ++i) { if (check[i].IsSeeThrough) continue; if (line.IntersectsBox(check[i].BoundingRectangle)) { blocked = true; break; } } // Check every wall //int wallC = grid.Count; //for (int i = 0; i != wallC; ++i) //{ // if (line.IntersectsBox(grid[i].BoundingRectangle)) // { // blocked = true; // break; // } //} // Check the grid for walls //int minGX = (int)Math.Min(searchPos.X, node.Position.X) / 200; //int minGY = (int)Math.Min(searchPos.Y, node.Position.Y) / 200; //int maxGX = (int)Math.Max(searchPos.X, node.Position.X) / 200; //int maxGY = (int)Math.Max(searchPos.Y, node.Position.Y) / 200; //if (minGX > 0) // --minGX; //if (minGY > 0) // --minGY; //if (maxGX > grid.GetUpperBound(1)) // ++maxGX; //if (maxGY > grid.GetUpperBound(0)) // ++maxGY; //for (int i = minGX; i <= maxGX; ++i) //{ // for (int j = minGY; j <= maxGY; ++j) // { // List<Wall> walls = grid[j, i]; // int wallC = walls.Count; // for (int k = 0; k != wallC; ++k) // { // Wall wall = walls[k]; // if (wall.IsSeeThrough) // continue; // if (line.IntersectsBox(wall.BoundingRectangle)) // { // blocked = true; // break; // } // } // if (blocked) // break; // } // if (blocked) // break; //} if (blocked) continue; } float dist = (node.Position - searchPos).LengthSquared(); if (dist < minDist) { minDist = dist; closest = node; } } return closest; } } }
d23d521944959020f8ed850d309409824d512fe5
C#
YasakaShun/test_csharp
/dokushu/dokushu/Test6.cs
3.265625
3
using System; using System.Collections.Generic; namespace dokushu { class Test6 { public static void Exec2() { var dic = new Dictionary<string, string>() { ["lettuce"] = "レタス", ["spinach"] = "ほうれんそう", ["cucumber"] = "きゅうり", }; dic["cucumber"] = "胡瓜"; dic.Add("cabbage", "キャベツ"); dic.Remove("spinach"); foreach (var m in dic) { Console.WriteLine($"{m.Key}: {m.Value}"); } } public static void Exec3() { var list = new List<int>() { 1, 2, 3, 4 }; list[2] = 50; list.Insert(1, 5); list.Remove(60); foreach (int v in list) { Console.WriteLine(v); } } } }
f9bab12d02b932aaeb5923a3ca225e02405d14a9
C#
nureyev/Pixel-Sprite-Generator-CSharp
/Pixel-Sprite-Generator-CSharp/Window1.xaml.cs
2.59375
3
using Pixel_Sprite_Generator.SpriteGen; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Pixel_Sprite_Generator { public partial class Window1 : Window { Mask spaceship = new Mask(new int[]{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1,-1, 0, 0, 0, 1, 1,-1, 0, 0, 0, 1, 1,-1, 0, 0, 1, 1, 1,-1, 0, 1, 1, 1, 2, 2, 0, 1, 1, 1, 2, 2, 0, 1, 1, 1, 2, 2, 0, 1, 1, 1, 1,-1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 }, 6, 12, true, false); Sprite sprite; public Window1() { InitializeComponent(); newBitmap(); } public void newBitmap() { int width = 12; int height = 12; int stride = width * 4; this.sprite = new Sprite(12, 12, spaceship, true); int[] spritePixels = this.sprite.renderPixelData(); // Create a writeable bitmap (which is a valid WPF Image Source WriteableBitmap bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null); // Create an array of pixels to contain pixel color values uint[] pixels = new uint[width * height]; int red; int green; int blue; int alpha; for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { int i = width * y + x; int index = (width * y + x)*4; red = spritePixels[index]; green = spritePixels[index + 1]; blue = spritePixels[index + 2]; alpha = spritePixels[index + 3]; pixels[i] = (uint)((alpha << 24) + (red << 16) + (green << 8) + blue); } } // apply pixels to bitmap bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * 4, 0); // set image source to the new bitmap this.MainImage.Source = bitmap; } private void Button_Click(object sender, RoutedEventArgs e) { newBitmap(); } } }
b19a5fb4239a74601d708e354d976cddd45e9634
C#
Horusiath/UTorri
/UTorri/TorrentJobProperties.cs
2.578125
3
using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; namespace UTorri { /// <summary> /// Torrent task properties class. /// </summary> public class TorrentJobProperties : RequestResult { private IDictionary<string, string> _changedValues; /// <summary> /// Return dictionary with changes made on current task properties. /// </summary> public IDictionary<string,string> Changes { get { return _changedValues; } } /// <summary> /// Checksum identifier of associated torrent. /// </summary> public string Hash { get; private set; } private ICollection<string> _trackers; /// <summary> /// Gets or sets collection of tracker names. /// </summary> public ICollection<string> Trackers { get { return _trackers; } set { _trackers = value; ChangeValue("trackers", string.Join("\r\n", _trackers.ToArray())); } } private int _uploadLimit; /// <summary> /// Gets or sets maximum upload limit. /// </summary> public int UploadLimit { get { return _uploadLimit; } set { _uploadLimit = value; ChangeValue("ulrate", _uploadLimit.ToString()); } } private int _downloadLimit; /// <summary> /// Gets or sets maximum download limit. /// </summary> public int DownloadLimit { get { return _downloadLimit; } set { _downloadLimit = value; ChangeValue("dlrate", _downloadLimit.ToString()); } } private TaskPropertyState _initialSeeding; /// <summary> /// Gets or sets Super-Seeding/Initial seeding option. /// </summary> public TaskPropertyState InitialSeeding { get { return _initialSeeding; } set { _initialSeeding = value; ChangeValue("superseed", ((int)_initialSeeding).ToString()); } } private TaskPropertyState _dht; /// <summary> /// Gets or sets Distributed Hash Table usage option. /// </summary> public TaskPropertyState UseDht { get { return _dht; } set { _dht = value; ChangeValue("dht", ((int)_dht).ToString()); } } private TaskPropertyState _pex; /// <summary> /// Gets or sets Peer Exchange Protocol usage option. /// </summary> public TaskPropertyState UsePex { get { return _pex; } set { _pex = value; ChangeValue("pex", ((int)_pex).ToString()); } } private TaskPropertyState _seedOverride; /// <summary> /// Gets or sets seed override option. /// </summary> public TaskPropertyState OverrideQueueing { get { return _seedOverride; } set { _seedOverride = value; ChangeValue("seed_override", ((int)_seedOverride).ToString()); } } private TimeSpan _seedRatio; /// <summary> /// Gets or sets maximum seed ratio. /// </summary> public TimeSpan SeedRatio { get { return _seedRatio; } set { _seedRatio = value; ChangeValue("seed_ratio", _seedRatio.TotalMilliseconds.ToString()); } } private TimeSpan _seedTime; /// <summary> /// Gets or sets maximum seed time. /// </summary> public TimeSpan SeedingTime { get { return _seedTime; } set { _seedTime = value; ChangeValue("seed_time", _seedTime.TotalSeconds.ToString()); } } private int _uploadSlots; /// <summary> /// Gets or sets maximum number of upload slots. /// </summary> public int UploadSlots { get { return _uploadSlots; } set { _uploadSlots = value; ChangeValue("ulslots", _uploadSlots.ToString()); } } public TorrentJobProperties() { _changedValues = new Dictionary<string, string>(); } public TorrentJobProperties(string json) : this() { this.FromJson(json); } /// <summary> /// Notifies changes made on any of the torrent task property. /// </summary> /// <param name="key"></param> /// <param name="value"></param> protected void ChangeValue(string key, string value) { if (_changedValues.ContainsKey(key)) _changedValues[key] = value; _changedValues.Add(key,value); } public override void FromJson(string json) { var obj = JsonConvert.DeserializeObject<TorrentTaskRawJson>(json); this.Hash = obj.hash; this._trackers = obj.trackers.Split(new[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries); this._uploadLimit = obj.ulrate; this._downloadLimit = obj.dlrate; this._initialSeeding = (TaskPropertyState) obj.superseed; this._dht = (TaskPropertyState) obj.dht; this._pex = (TaskPropertyState) obj.pex; this._seedOverride = (TaskPropertyState) obj.seed_override; this._seedRatio = TimeSpan.FromMilliseconds(obj.seed_ratio); this._seedTime = TimeSpan.FromSeconds(obj.seed_time); this._uploadSlots = obj.ulslots; } /// <summary> /// Helper class used for JSON parsing purposes. /// </summary> internal class TorrentTaskRawJson { internal string hash; internal string trackers; internal int ulrate; internal int dlrate; internal int superseed; internal int dht; internal int pex; internal int seed_override; internal int seed_ratio; internal int seed_time; internal int ulslots; } } /// <summary> /// Torrent task property option. /// </summary> public enum TaskPropertyState { /// <summary> /// Option forbidden. /// </summary> Forbidden = -1, /// <summary> /// Option shutdown. /// </summary> Off = 0, /// <summary> /// Use option when available. /// </summary> On = 1 } }
1747bfa24a4edd02267dac29510e232cb7fbf787
C#
stoyanov7/SoftwareUniversity
/C#Development/C#OOPBasics/DefiningClasses-Lab/01.BankAccount/01.BankAccount/StartUp.cs
2.890625
3
namespace _01.BankAccount { using System; public class StartUp { public static void Main(string[] args) { var bankAccount = new BankAccount(); bankAccount.ID = 1; bankAccount.Balance = 15; Console.WriteLine($"Account {bankAccount.ID}, balance {bankAccount.Balance}"); } } }
10c10bfbd1a10d09839df500a3664035c9b357cc
C#
CloudNStoyan/homework
/ConsoleApp1/BinaryToDecimal/Program.cs
3.953125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BinaryToDecimal { class Program { static void Main(string[] args) { //Using loops write a program that converts a binary integer number to its decimal form. //The input is entered as string. The output should be a variable of type long. //Do not use the built-in .NET functionality. string input = Console.ReadLine(); // 4 8 16 32 //1000 0000 1000 0000 var chars = input.ToArray(); int result = 0; for (var i = 0; i < chars.Length; i++) { result *= 2; if (chars[i] == '1') { result += 1; } } Console.WriteLine(result); } } }
3f0db0e278316e99da527147c00e1604c4fa7d3d
C#
nick0000100/ScheduleNeo
/Models/RegisterUserModel.cs
2.640625
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace scheduleNEO.Models { public class RegisterUserModel : BaseEntity { [Required] [MinLength(2)] [RegularExpression(@"^[A-Za-z0-9]+$", ErrorMessage="No special characters.")] [Display(Name="First Name")] public string FirstName {get;set;} [Required] [MinLength(2)] [RegularExpression(@"^[A-Za-z0-9]+$", ErrorMessage="No special characters.")] [Display(Name="Last Name")] public string LastName {get;set;} [Required] [Display(Name="Username")] public string Username {get;set;} [Required] [MinLength(8)] [Display(Name="Password")] [DataType(DataType.Password)] public string Password {get;set;} [DataType(DataType.Password)] [Display(Name="Confirm Password")] [Compare("Password", ErrorMessage = "Passwords do not match")] public string PasswordConfirmation {get;set;} } }
3a5ba596f4659c5af3e77bc4c510d3b2e7daeb5e
C#
undejavue/SITbusiness
/NotifyServer/ServerCore.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Diagnostics; namespace NotifyServer { public class NotifyServerCore { private TcpListener listenerLocal; private Thread listenerThreadLocal; private int PortLocal; private string ServerLocal; private TcpListener listenerRemote; private Thread listenerThreadRemote; private int PortRemote; private string receivedMessage = "Нет данных!"; public NotifyServerCore() { this.PortLocal = Properties.Settings.Default.localNotifyPort; this.PortRemote = Properties.Settings.Default.remoteClientPort; this.ServerLocal = Properties.Settings.Default.serverAddress; } public void Start() { listenerThreadLocal = new Thread(ListenerThreadLocal); listenerThreadLocal.IsBackground = true; listenerThreadLocal.Name = "LocalNotifyListener"; listenerThreadLocal.Start(); listenerThreadRemote = new Thread(ListenerThreadRemote); listenerThreadRemote.IsBackground = true; listenerThreadRemote.Name = "RemoteNotifyListener"; listenerThreadRemote.Start(); } protected void ListenerThreadLocal() { try { IPAddress ipAddress = IPAddress.Parse(ServerLocal); listenerLocal = new TcpListener(ipAddress, PortLocal); listenerLocal.Start(); while (true) { Socket clientSocket = listenerLocal.AcceptSocket(); UnicodeEncoding encoder = new UnicodeEncoding(); byte[] buffer = new byte[1024]; clientSocket.Receive(buffer); this.receivedMessage = encoder.GetString(buffer); clientSocket.Close(); } } catch (SocketException ex) { Trace.TraceError(String.Format("NotifyServerCore says: {0}", ex.Message)); } } protected void ListenerThreadRemote() { try { IPAddress ipAddress = IPAddress.Parse(Properties.Settings.Default.serverAddress); listenerRemote = new TcpListener(ipAddress, PortRemote); listenerRemote.Start(); while (true) { Socket clientSocket = listenerRemote.AcceptSocket(); UnicodeEncoding encoder = new UnicodeEncoding(); byte[] buffer = encoder.GetBytes(receivedMessage); clientSocket.Send(buffer, buffer.Length, 0); clientSocket.Close(); } } catch (SocketException ex) { Trace.TraceError(String.Format("NotifyServerCore says for remote: {0}", ex.Message)); } } public void Stop() { //listenerLocal.Stop(); listenerRemote.Stop(); } public void Suspend() { //listenerLocal.Stop(); listenerRemote.Stop(); } public void Resume() { Start(); } } }
79a75be88cac805489f1301d935521b4a0967c59
C#
appsafeleads/iugu-net-standard
/iugu.net.standard/Response/ErrorResponseMessage.cs
2.703125
3
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace iugu.net.standard.Response { public class ErrorResponseMessage { public int StatusCode { get; private set; } public string ReasonPhase { get; private set; } public List<ErrorMessage> Errors { get; set; } private ErrorResponseMessage(int statusCode, string reasonPhase, List<ErrorMessage> errors) { StatusCode = statusCode; ReasonPhase = reasonPhase; Errors = errors; } private ErrorResponseMessage(int statusCode, string reasonPhase, string simpleErrorMessage) { StatusCode = statusCode; ReasonPhase = reasonPhase; Errors = new List<ErrorMessage> { new ErrorMessage("Error", new string[] { simpleErrorMessage }) }; } /// <summary> /// Método utilizado para serializar a resposta de erro da IUGU /// </summary> /// <param name="currentErrorMessage">mensagem atual retornada da requisição</param> /// <param name="erroMessages">Classe que representa os erros retornados de uma request</param> /// <returns></returns> [Obsolete("Não será mais necessário na versão 2.x, resolve a issue ref: https://github.com/iugu/iugu-net/issues/54")] public static async Task<ErrorResponseMessage> BuildAsync(string currentErrorMessage) { try { var jsonMessage = await Task.FromResult(JsonConvert.DeserializeObject<IuguCompleteComplexErrorResponse>(currentErrorMessage)) .ConfigureAwait(false); var errors = jsonMessage.Message.Errors.Select(e => new ErrorMessage(e.Key, e.Value.Values<string>().ToArray())).ToList(); return new ErrorResponseMessage(jsonMessage.StatusCode, jsonMessage.ReasonPhase, errors); } catch (Exception) { try { var jsonMessage = await Task.FromResult(JsonConvert.DeserializeObject<IuguCompleteSimpleErrorResponse>(currentErrorMessage)) .ConfigureAwait(false); return new ErrorResponseMessage(jsonMessage.StatusCode, jsonMessage.ReasonPhase, jsonMessage.Message); } catch (Exception) { return null; } } } } public class ErrorMessage { public string FieldName { get; private set; } public string[] Errors { get; private set; } public ErrorMessage(string fieldName, string[] errors) { FieldName = fieldName; Errors = errors; } } internal sealed class IuguCompleteComplexErrorResponse { public int StatusCode { get; set; } public string ReasonPhase { get; set; } public UnformattedErrorMessage Message { get; set; } } internal sealed class UnformattedErrorMessage { public Dictionary<string, JArray> Errors { get; set; } } internal sealed class IuguCompleteSimpleErrorResponse { public int StatusCode { get; set; } public string ReasonPhase { get; set; } public string Message { get; set; } } }
14f864296b30d384dff9ff2ef48b5c6914c2baa0
C#
alexandra26arkhipenko/Day-8
/NET.W.2017.Arkhipenko.8/ConsoleApp/Sort/SortByName.cs
3.109375
3
using System.Collections; using System.Collections.Generic; using Books; namespace ConsoleApp { public class SortByName : IComparer<Book> { public int Compare(Book lhs, Book rhs) { if (ReferenceEquals(lhs, null)) { return 1; } if (ReferenceEquals(lhs, rhs)) { return 0; } return lhs.CompareTo(rhs); } } }
5bd8911e03b89573ccb2093e6ff3b139171cb0df
C#
jecus/CasWeb
/BusinessLayer/Repositiry/AircraftRepository.cs
2.59375
3
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BusinessLayer.Repositiry.Interfaces; using BusinessLayer.Views; using Entity.Extentions; using Entity.Infrastructure; using Microsoft.EntityFrameworkCore; namespace BusinessLayer.Repositiry { public class AircraftRepository : IAircraftRepository { private readonly DatabaseContext _db; public AircraftRepository(DatabaseContext databaseContext) { _db = databaseContext; } public async Task<AircraftView> GetById(int id) { var aircraft = await _db.Aircrafts .OnlyActive() .Include(i => i.Model) .FirstOrDefaultAsync(i => i.Id == id); return aircraft.ToBlView(); } public async Task<List<AircraftView>> Get(IEnumerable<int> ids) { var aircraft = await _db.Aircrafts .AsNoTracking() .OnlyActive() .Where(i => ids.Contains(i.Id)) .ToListAsync(); return aircraft.ToBlView(); } public async Task<List<AircraftView>> GetAll() { var aircraft = await _db.Aircrafts .AsNoTracking() .OnlyActive() .Include(i => i.Model) .ToListAsync(); return aircraft.ToBlView(); } } }
1df6ad1afd6b3e1ff8c70f7cd59cb9e087dc28ab
C#
JorgeCarlosVicenteSuarez/Battleships
/BattleShips.Logic.Tests/ShipTests.cs
2.671875
3
namespace BattleShips.Logic.Tests { using NUnit.Framework; [TestFixture] public class ShipTests { [Test] public void ShipNotSunkWhenCreated() { var destroyer = new Destroyer(); var battleship = new Battleship(); Assert.IsFalse(destroyer.Sunk); Assert.IsFalse(battleship.Sunk); } [Test] public void ShipLocationInvalidWhenCreated() { var destroyer = new Destroyer(); var battleship = new Battleship(); Assert.AreEqual(-1, destroyer.PosX); Assert.AreEqual(-1, destroyer.PosY); Assert.AreEqual(-1, battleship.PosX); Assert.AreEqual(-1, battleship.PosY); } [Test] public void ShipSizeAssignedWhenCreated() { var destroyer = new Destroyer(); var battleship = new Battleship(); Assert.AreEqual(4, destroyer.Size); Assert.AreEqual(5, battleship.Size); } [Test] public void ShipLocationAssignedCorrectly() { var destroyer = new Destroyer(); destroyer.Locate(5, 2, true); Assert.AreEqual(5, destroyer.PosX); Assert.AreEqual(2, destroyer.PosY); } [Test] public void DestroyerSunkInFourShoots() { var destroyer = new Destroyer(); destroyer.Locate(0, 0, false); var touched1 = destroyer.Shoot(0, 0); var touched2 = destroyer.Shoot(1, 0); var touched3 = destroyer.Shoot(2, 0); var touched4 = destroyer.Shoot(3, 0); Assert.IsTrue(touched1); Assert.IsTrue(touched2); Assert.IsTrue(touched3); Assert.IsTrue(touched4); Assert.IsTrue(destroyer.Sunk); } [Test] public void BattleshipSunkInFiveShoots() { var battleship = new Battleship(); battleship.Locate(0, 0, true); var touched1 = battleship.Shoot(0, 0); var touched2 = battleship.Shoot(0, 1); var touched3 = battleship.Shoot(0, 2); var touched4 = battleship.Shoot(0, 3); var touched5 = battleship.Shoot(0, 4); Assert.IsTrue(touched1); Assert.IsTrue(touched2); Assert.IsTrue(touched3); Assert.IsTrue(touched4); Assert.IsTrue(touched5); Assert.IsTrue(battleship.Sunk); } [Test] public void BattleshipNotSunkFailingTwoShoots() { var battleship = new Battleship(); battleship.Locate(0, 0, true); var touched1 = battleship.Shoot(0, 0); var notTouched1 = battleship.Shoot(1, 1); var touched2 = battleship.Shoot(0, 2); var touched3 = battleship.Shoot(0, 3); var notTouched2 = battleship.Shoot(0, 5); Assert.IsTrue(touched1); Assert.IsTrue(touched2); Assert.IsTrue(touched3); Assert.IsFalse(notTouched1); Assert.IsFalse(notTouched2); Assert.IsFalse(battleship.Sunk); } } }
7a972ecdb31f8d2210b273c8c79ce1328a4baa46
C#
duyhuytdh/SendEmail
/SendMail/SendMail/Util/TempHtmlReader.cs
2.703125
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System; using System.IO; using System.Diagnostics; using System.Configuration; namespace SendMail.Util { public static class TempHtmlReader { public static string tempEmail(string userName, string title, string message, string path) { string body = string.Empty; //using streamreader for reading my htmltemplate using (StreamReader reader = new StreamReader(path)) { body = reader.ReadToEnd(); } body = body.Replace("{userName}", userName); //replacing the required things body = body.Replace("{title}", title); body = body.Replace("{message}", message); return body; } } }
40a13e6b79dd1b0eb2a54ebe0b5ffa764fa65dc7
C#
Miliverse/Chapter_11
/Chapter_11/Program.cs
2.984375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Media; using System.Threading; using System.IO; using System.Diagnostics; using System.Runtime.InteropServices; namespace Chapter_11 { public static class Game { //Establish typewriting effect public static void Typewrite(string message) { for (int i = 0; i < message.Length; i++) { Console.Write(message[i]); System.Threading.Thread.Sleep(30); } // End the message with \n Console.Write(Environment.NewLine); } //Start the game. Duh public static void StartGame() { OpeningLore(); } // Text that explains the backstory, starts at the beginning of the game. public static void OpeningLore() { Typewrite("Placeholder"); Console.ReadKey(); } // Profile creation system, probably public static void ProfileCreation() { } } class Program { //Starts the program up in full screen or something [DllImport("kernel32.dll", ExactSpelling = true)] private static extern IntPtr GetConsoleWindow(); private static IntPtr ThisConsole = GetConsoleWindow(); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); private const int HIDE = 0; private const int MAXIMIZE = 3; private const int MINIMIZE = 6; private const int RESTORE = 9; static void Main(string[] args) // program game running thingy. stick stuff you want the program to run at launch in here { //Relates to earlier code about starting the program in full screen Console.SetWindowSize(Console.LargestWindowWidth, Console.LargestWindowHeight); ShowWindow(ThisConsole, MAXIMIZE); Console.ForegroundColor = ConsoleColor.White; Console.Title = "Chapter 11"; Game.StartGame(); //Start the game ExternalData.Menu(); } } class ExternalData // External Data Reading { // public things relating to the file reading thing public static string DataFile = "data.txt"; public static string Content = "(Empty File)"; public static string Input = ""; public static bool Run = true; public static int Choice = 0; // Color... text? static void ColorText(string Message) { Console.ForegroundColor = ConsoleColor.Blue; Console.BackgroundColor = ConsoleColor.White; Console.WriteLine(Message); Console.ResetColor(); } // Placeholder thing static void Placeholder() { Console.Title = "Chapter 11 - Save Mode"; while (Run == true) { Menu(); } } // Menu where you select what you what to do relating to a file // will later to change to a save system public static void Menu() { string input = ""; int Choice = 0; // Print menu to the screen Console.WriteLine("\n\n\n\n\n------------------------------------------"); Console.WriteLine(" 1) Read Content 2) Update Content 3) Exit"); Console.WriteLine("------------------------------------------"); Input = Console.ReadLine(); Choice = Convert.ToInt32(Input); if (Choice == 1) { Console.Clear(); if (File.Exists(DataFile)) { ColorText("The File contents are: "); Content = File.ReadAllText(DataFile); } Console.WriteLine(Content); Console.ReadKey(); Menu(); } else if (Choice == 2) { Console.Clear(); ColorText("\n\nEnter new content and press enter to save it:"); Input = Console.ReadLine(); Content = Input; ColorText("\nConfirm that file contents will be replaced.\nType Y or N:"); Input = Console.ReadLine(); Input = Input.ToLower(); if (Input == "y") { File.WriteAllText(DataFile, Content); ColorText("File updated."); Menu(); } else { ColorText("File not updated."); Menu(); } } } } }
b51ec8f654fcbf62646ef54be7579148b2890813
C#
Michael-Libois/fnuc
/DAL/Repository/UserRepo.cs
2.953125
3
using Common.interfaces; using DAL.Context; using DAL.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL.Repository { public class UserRepo : Irepository<User> { private DatabaseContext dbContext; public UserRepo(DatabaseContext db) { dbContext = db; } public User Create(User obj) { dbContext.Users.Add(obj); return obj; } public void Delete(int id) { User user = Retrieve(id); dbContext.Users.Remove(user); } public void Delete(string id) { User user = Retrieve(id); dbContext.Users.Remove(user); } public void Dispose() { dbContext.Dispose(); } public User Retrieve(int id) { return dbContext.Users.FirstOrDefault(u => u.Id == id); } public User Retrieve(string id) { throw new NotImplementedException(); } public List<User> RetrieveAll() { return dbContext.Users.ToList(); } public void Update(User obj) { User user = Retrieve(obj.Id); user.Name = obj.Name; } } }
0a5e3909e67a8317d5a7aa7f193d08de6d070312
C#
fredatgithub/SpiceSharp
/SpiceSharp/Components/Distributed/VoltageDelays/VoltageDelay.cs
2.671875
3
using SpiceSharp.Attributes; using SpiceSharp.Components.VoltageDelays; using SpiceSharp.ParameterSets; using System; namespace SpiceSharp.Components { /// <summary> /// A component that will drive an output to a delayed input voltage. /// </summary> /// <seealso cref="Component" /> /// <seealso cref="IParameterized{P}"/> [Pin(0, "V+"), Pin(1, "V-"), Pin(2, "VC+"), Pin(3, "VC-"), AutoGeneratedBehaviors] [Connected(0, 1), VoltageDriver(0, 1)] public partial class VoltageDelay : Component<Parameters> { /// <summary> /// The voltage delay pin count /// </summary> [ParameterName("pincount"), ParameterInfo("Number of pins")] public const int PinCount = 4; /// <summary> /// Initializes a new instance of the <see cref="VoltageDelay"/> class. /// </summary> /// <param name="name">The name of the entity.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="name"/> is <c>null</c>.</exception> public VoltageDelay(string name) : base(name, PinCount) { } /// <summary> /// Initializes a new instance of the <see cref="VoltageDelay"/> class. /// </summary> /// <param name="name">The name of the voltage-controlled voltage source.</param> /// <param name="pos">The positive node.</param> /// <param name="neg">The negative node.</param> /// <param name="controlPos">The positive controlling node.</param> /// <param name="controlNeg">The negative controlling node.</param> /// <param name="delay">The delay.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="name"/> is <c>null</c>.</exception> public VoltageDelay(string name, string pos, string neg, string controlPos, string controlNeg, double delay) : this(name) { Parameters.Delay = delay; Connect(pos, neg, controlPos, controlNeg); } } }
60e3f97a57035b7980883fb4e3c8dbed66d7c936
C#
broplz/MyTD
/Assets/Scripts/Enemy.cs
2.5625
3
using System; using System.Collections; using TMPro; using UnityEngine; public class Enemy : MonoBehaviour { private int target = 0; private GameObject[] wayPoints; [SerializeField] private float navigation; [SerializeField] private int health; [SerializeField] private float speed = 0.1f; private Transform enemy; private float navigationTime = 0; private void Awake() { wayPoints = GameObject.FindGameObjectsWithTag("MovingPoint"); Debug.Log($"Waypoint length {wayPoints.Length}"); } // Start is called before the first frame update private void Start() { enemy = GetComponent<Transform>(); Manager.Instance.RegisterEnemy(this); } // Update is called once per frame private void Update() { if (wayPoints != null) { navigationTime += Time.deltaTime * speed; if (navigationTime > navigation) { enemy.position = Vector2.MoveTowards(enemy.position, wayPoints[target].transform.position, navigationTime); navigationTime = 0; } } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("MovingPoint")) { target += 1; } if (target == wayPoints.Length) { Manager.Instance.UnregisterEnemy(this); Debug.Log($"target {target}"); } else if (collision.CompareTag("Projectile")) { Projectile newP = collision.gameObject.GetComponent<Projectile>(); EnemyHit(newP.AttackDamage); Destroy(collision.gameObject); } } public void EnemyHit(int hitpoints) { if (health - hitpoints > 0) { //enemy hurts health -= hitpoints; } else { //enemy dies } } }
fba779ca874bd261f31b399b082547d2215adb3d
C#
lvyitian/BaristaCore
/src/BaristaLabs.BaristaCore.Extensions/Blob.cs
3.09375
3
namespace BaristaLabs.BaristaCore { using System; using System.Collections.Generic; using System.Text; /// <summary> /// Represents a file-like object of immutable, raw data. /// </summary> /// <see cref="https://developer.mozilla.org/en-US/docs/Web/API/Blob"/> public class Blob { //Replace this with Span<byte> private readonly byte[] m_blob; private string m_type = string.Empty; private string m_disposition = string.Empty; public Blob(object[] array, JsObject options = null) { //Replace this with Span<byte> var data = new List<byte>(); foreach (var arr in array) { switch (arr) { case byte[] bytes: data.AddRange(bytes); break; case Blob blob: data.AddRange(blob.m_blob); break; default: data.AddRange(Encoding.UTF8.GetBytes(arr.ToString())); break; } } m_blob = data.ToArray(); if (options != null) { if (options.HasProperty("type")) m_type = options["type"].ToString(); } } [BaristaIgnore] public Blob(byte[] data, string contentType = null) { m_blob = data ?? throw new ArgumentNullException(nameof(data)); m_type = contentType; } /// <summary> /// Gets size in bytes of the blob. /// </summary> public double Size { get { return m_blob.LongLength; } } /// <summary> /// Gets the the MIME type of the blob. It returns an empty string if the type couldn't determined. /// </summary> public string Type { get { return m_type; } } /// <summary> /// Gets or sets a value that indicates the blob's content disposition. /// </summary> /// <remarks> /// This is a non-standard property used by Barista services that will set the Content-Disposition response header of a brew request if the default exported object is a blob and this value is set. /// </remarks> public string Disposition { get { return m_disposition; } set { m_disposition = value; } } /// <summary> /// Gets the underlying blob data. /// </summary> [BaristaIgnore] public byte[] Data { get { return m_blob; } } /// <summary> /// Returns a new Blob object containing the data in the specified range of bytes of the source Blob. /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <param name="contentType"></param> /// <returns></returns> public Blob Slice(long? start = null, long? end = null, string contentType = "") { if (start.HasValue == false) start = 0; var indexFrom = start.Value; if (indexFrom < 0) indexFrom = m_blob.LongLength + start.Value; if (end.HasValue == false) end = m_blob.LongLength; if (indexFrom > end.Value) throw new ArgumentException($"Start index ({indexFrom}) cannot be after end ({end.Value})."); long length = end.Value - indexFrom; byte[] data = new byte[length]; Array.Copy(m_blob, indexFrom, data, 0, length); var targetContentType = m_type; if (!String.IsNullOrWhiteSpace(contentType)) targetContentType = contentType; return new Blob(data, targetContentType); } /// <summary> /// Decodes the blob into a UTF-8 string. /// </summary> /// <returns></returns> public string ToUtf8String() { return Encoding.UTF8.GetString(m_blob); } /// <summary> /// Converts the blob into a Base64 string encoding. /// </summary> /// <returns></returns> public string ToBase64EncodedByteArray() { return Convert.ToBase64String(m_blob); } public static Blob FromUtf8String(string data, string contentType = null) { return new Blob(Encoding.UTF8.GetBytes(data), contentType); } public static Blob FromBase64EncodedByteArray(string data, string contentType = null) { return new Blob(Convert.FromBase64String(data), contentType); } } }
5d3dc545dabd429dbc81503538fe2d4d9a4cd2e0
C#
abaula/DistanceBtwCities
/WebApi/DistanceBtwCities.WebApi/Caching/CacheManager.cs
2.78125
3
using System; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.Caching; namespace DistanceBtwCities.WebApi.Caching { internal class CacheManager : ICacheManager { private readonly ICacheSettingsManager _cacheSettingsManager; private static readonly object CacheLock = new object(); public CacheManager(ICacheSettingsManager cacheSettingsManager) { _cacheSettingsManager = cacheSettingsManager; } /// <summary> /// Ищет кэшированные данные для входящего запроса. /// </summary> /// <param name="request">Входящий запрос.</param> /// <returns>Объект кэширования или null.</returns> public CacheDataItem GetCacheDataForRequest(HttpRequestMessage request) { // пробуем получить данные из кэша. var key = _getCacheKeyFromRequest(request); return (CacheDataItem) MemoryCache.Default.Get(key); } /// <summary> /// Проверяет тэг IfNoneMatch с Etag кэшированных данных. /// </summary> /// <param name="request">Запрос</param> /// <param name="cacheData">Кэшированные данные</param> /// <returns>true, если значения IfNoneMatch и Etag совпадают</returns> public bool CheckIfCachedDataIsValidForClient(HttpRequestMessage request, CacheDataItem cacheData) { return request.Headers.IfNoneMatch.Any(tagHeader => string.Compare(tagHeader.Tag, cacheData.ETag, StringComparison.InvariantCulture) == 0); } /// <summary> /// Добавляет заголовки для кэширования на стороне клиента. /// </summary> /// <param name="response">Ответ</param> /// <param name="cachedData">Кэшированные данные</param> public void AddResponseHeadersForCachingOnClientSide(HttpResponseMessage response, CacheDataItem cachedData) { response.Headers.ETag = new EntityTagHeaderValue(cachedData.ETag); if (response.Content != null) response.Content.Headers.LastModified = cachedData.CreatedAt.ToUniversalTime(); response.Headers.CacheControl = new CacheControlHeaderValue { MaxAge = TimeSpan.FromMinutes(cachedData.Settings.MaxAgeMinutes), Public = true }; } /// <summary> /// Проверяет нужно ли кэшировать ответ для запроса. /// Если заданы настройки кэширования для запроса, то содержимое ответа сохраняется в кэше. /// </summary> /// <param name="response">Ответ</param> /// <returns>Если ответ был сохранён в кэше, то возвращаем объект кэшированных данных, иначе null</returns> public CacheDataItem SaveResponseInCache(HttpResponseMessage response) { var cachedDataItem = _createCacheItemForRequest(response.RequestMessage); // если отсутствуют настройки кэширования, то выходим if (cachedDataItem == null) return null; // создаём ключ для кэша var key = _getCacheKeyFromRequest(response.RequestMessage); var cache = MemoryCache.Default; var cachedData = (CacheDataItem)cache.Get(key); if (cachedData != null) return cachedData; lock (CacheLock) { cachedData = (CacheDataItem)cache.Get(key); if (cachedData != null) return cachedDataItem; // создаём ETag cachedDataItem.ETag = string.Format("\"{0}\"", Guid.NewGuid().ToString("N")); // устанавливаем дату создания кэшированного объекта cachedDataItem.CreatedAt = DateTime.Now; // устанавливаем содержимое ответа и его тип var content = (ObjectContent)response.Content; cachedDataItem.Data = content.Value; cachedDataItem.DataType = content.ObjectType; // создаём политику хранения данных var policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(cachedDataItem.Settings.MaxAgeMinutes); // сохраняем данные в кэше cache.Add(key, cachedDataItem, policy); return cachedDataItem; } } private CacheDataItem _createCacheItemForRequest(HttpRequestMessage request) { // пробуем получить настройки кэширования для запроса. var cacheSettings = _cacheSettingsManager.GetCacheSettingsForRequest(request.RequestUri); if (cacheSettings != null) { // настройки кэширования получены, создаём объект кэширования и возвращаем. var cacheData = new CacheDataItem {Settings = cacheSettings}; return cacheData; } return null; } private string _getCacheKeyFromRequest(HttpRequestMessage request) { return request.RequestUri.AbsolutePath; } } }
67f5dbb46deb2baa8b74f255237ff24eca514778
C#
markfrance/Recording-Monitor
/packages/MSharp.Framework.2.1.0.629/src/Data/Engine/Cache.cs
2.828125
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace MSharp.Framework.Data { enum CacheContainerStrategy { Universal, PerHttpRequest } /// <summary> /// Provides a cache of objects retrieved from the database. /// </summary> public class Cache { object SyncLock = new object(); static Cache UniversalCache = new Cache(); Dictionary<Type, Dictionary<string, IEntity>> Types = new Dictionary<Type, Dictionary<string, IEntity>>(); Dictionary<Type, Dictionary<string, IEnumerable>> Lists = new Dictionary<Type, Dictionary<string, IEnumerable>>(); #region IsEnabled property static bool _IsCachingEnabled; static CacheContainerStrategy Strategy = CacheContainerStrategy.Universal; static Cache() { _IsCachingEnabled = Config.Get<bool>("Database.Cache.Enabled", defaultValue: true); switch (Config.Get("Database.Cache.Strategy", "Universal")) { case "Universal": Strategy = CacheContainerStrategy.Universal; break; case "PerHttpRequest": Strategy = CacheContainerStrategy.PerHttpRequest; break; default: throw new Exception("Invalid Database.Cache.Strategy setting is configured."); } } public static bool CanCache(Type type) { return CacheObjectsAttribute.IsEnabled(type) ?? _IsCachingEnabled; } #endregion /// <summary> /// Gets the current cache. /// </summary> public static Cache Current { get { switch (Strategy) { case CacheContainerStrategy.Universal: return UniversalCache; case CacheContainerStrategy.PerHttpRequest: if (HttpContext.Current == null) { // A not-null Cache is relied upon in many places. So return an empty cache: return new Cache(); } else { // Create a new one if it doesn't exist, or just return the one from current Http context. return HttpContext.Current.Items["Current.Database.Cache"] as Cache ?? (Cache)(HttpContext.Current.Items["Current.Database.Cache"] = new Cache()); } default: throw new NotSupportedException(Strategy + " is not supported!"); } } } Dictionary<string, IEntity> GetEntities(Type type) { var result = Types.TryGet(type); if (result == null) { lock (SyncLock) { result = Types.TryGet(type); if (result == null) { result = new Dictionary<string, IEntity>(); Types.Add(type, result); } } } return result; } Dictionary<string, IEnumerable> GetLists(Type type, bool autoCreate = true) { var result = Lists.TryGet(type); if (result == null && autoCreate) { lock (SyncLock) { result = Lists.TryGet(type); if (result == null) { result = new Dictionary<string, IEnumerable>(); Lists.Add(type, result); } } } return result; } /// <summary> /// Gets an entity from cache. Returns null if not found. /// </summary> public IEntity Get(string id) { try { foreach (var type in Types.Keys.ToArray()) { var result = Get(type, id); if (result != null) return result; } } catch { } return null; } /// <summary> /// Gets an entity from cache. Returns null if not found. /// </summary> public IEntity Get(Type entityType, string id) { if (!CanCache(entityType)) return null; var entities = GetEntities(entityType); if (entities.ContainsKey(id)) { try { return entities[id]; } catch (KeyNotFoundException) { // A threading issue. return Get(entityType, id); } } else { foreach (var type in entityType.Assembly.GetSubTypes(entityType)) { var result = Get(type, id); if (result != null) return result; } return null; } } /// <summary> /// Adds a given entity to the cache. /// </summary> public void Add(IEntity entity) { if (!CanCache(entity.GetType())) return; var entities = GetEntities(entity.GetType()); lock (entities) { var id = entity.GetId().ToString(); if (entities.ContainsKey(id)) { entities.GetOrDefault(id).Perform(x => x.InvalidateCachedReferences()); entities.Remove(id); } entities.Add(id, entity); ExpireLists(entity.GetType()); } } /// <summary> /// Removes a given entity from the cache. /// </summary> public void Remove(IEntity entity) { entity.InvalidateCachedReferences(); SessionMemory.Remove(entity); if (!(entity is IApplicationEvent)) foreach (var type in CacheDependentAttribute.GetDependentTypes(entity.GetType())) Remove(type, invalidateCachedReferences: true); if (!CanCache(entity.GetType())) return; var entities = GetEntities(entity.GetType()); lock (entities) { var id = entity.GetId().ToString(); if (entities.ContainsKey(id)) { entities.Remove(id); } ExpireLists(entity.GetType()); } if (this != Current) Current.Remove(entity); } /// <summary> /// Removes all entities of a given types from the cache. /// </summary> public void Remove(Type type, bool invalidateCachedReferences = false) { if (!CanCache(type)) return; lock (SyncLock) { foreach (var inherited in Types.Keys.Where(t => t.BaseType == type).ToList()) { Remove(inherited, invalidateCachedReferences); } } if (Types.ContainsKey(type)) { lock (SyncLock) { if (Types.ContainsKey(type)) { var entities = Types[type]; lock (entities) { Types.Remove(type); ExpireLists(type); if (invalidateCachedReferences) entities.Do(e => e.Value.InvalidateCachedReferences()); } } } } if (this != Current) Current.Remove(type, invalidateCachedReferences); } public void ExpireLists(Type type) { if (!CanCache(type)) return; for (var parentType = type; parentType != typeof(Entity); parentType = parentType.BaseType) { var lists = GetLists(parentType, autoCreate: false); if (lists != null) lock (lists) { lists.Clear(); } } if (this != Current) Current.ExpireLists(type); } internal IEnumerable GetList(Type type, string key) { if (!CanCache(type)) return null; var lists = GetLists(type); lock (lists) { if (lists.ContainsKey(key)) return lists[key]; else return null; } } internal void AddList(Type type, string key, IEnumerable list) { if (!CanCache(type)) return; var lists = GetLists(type); lock (lists) { if (lists.ContainsKey(key)) { lists.Remove(key); } lists.Add(key, list); } } static internal string BuildQueryKey(Type type, IEnumerable<ICriterion> conditions, int? numberOfRecords) { var r = new StringBuilder(); r.Append(type.GetCachedAssemblyQualifiedName()); r.Append(':'); if (conditions != null) foreach (var c in conditions) { r.Append(c.ToString()); r.Append('|'); } if (numberOfRecords.HasValue) { r.Append("|N:"); r.Append(numberOfRecords); } return r.ToString(); } public void ClearAll() { lock (SyncLock) { Types.Clear(); Lists.Clear(); } } internal int CountAllObjects() { return Types.Sum(t => t.Value.Count); } } }
11a61e41e17b2255afd05ce2efefc549912aade9
C#
alfaproject/Supay.Irc
/Supay.Irc/Messages/Replies/IrcX/KnockReplyMessage.cs
2.84375
3
using System; using System.Collections.Generic; namespace Supay.Irc.Messages { /// <summary> /// A reply to a <see cref="KnockMessage" />. /// </summary> [Serializable] public class KnockReplyMessage : NumericMessage { /// <summary> /// Creates a new instance of the <see cref="KnockReplyMessage" />. /// </summary> public KnockReplyMessage() : base(711) { Channel = string.Empty; } /// <summary> /// Gets or sets the channel that was knocked on. /// </summary> public string Channel { get; set; } /// <summary> /// Overrides <see cref="IrcMessage.GetTokens"/>. /// </summary> protected override ICollection<string> GetTokens() { var parameters = base.GetTokens(); parameters.Add(this.Channel); parameters.Add("Your KNOCK has been delivered."); return parameters; } /// <summary> /// Parses the parameters portion of the message. /// </summary> protected override void ParseParameters(IList<string> parameters) { base.ParseParameters(parameters); this.Channel = parameters.Count > 1 ? parameters[1] : string.Empty; } /// <summary> /// Notifies the given <see cref="MessageConduit" /> by raising the appropriate event for the current <see cref="IrcMessage" /> subclass. /// </summary> public override void Notify(MessageConduit conduit) { conduit.OnKnockReply(new IrcMessageEventArgs<KnockReplyMessage>(this)); } } }
4e5ea02163948b397139d7e52bee2ec4ca939583
C#
kamila-ropela/DocSystem
/DocSystem/DatabaseFiles/Helper/DocumentationTable.cs
2.71875
3
using DocSystem.Models; using System; using System.Collections.Generic; namespace DocSystem.DatabaseFiles.Helper { public static class DocumentationTable { public static List<Documentation> GetDocByDisease(string disease,int pid) { return Properties.dbContext.GetDocumentationDb($@"SELECT Documentation.Id, Documentation.PatientId, Concat(Doctor.Name, ' ', Doctor.Surname) AS DoctorName, Documentation.Disease, Documentation.Date FROM Documentation INNER JOIN Doctor ON Documentation.DoctorId = Doctor.Id WHERE Documentation.Disease = '{disease}' AND Documentation.PatientId={pid}"); } public static List<Documentation> GetDataByPatientId(int id) { return Properties.dbContext.GetDocumentationDb($@"SELECT Documentation.Id, Documentation.PatientId, Concat(Doctor.Name, ' ', Doctor.Surname) AS DoctorName, Documentation.Disease, Documentation.Date FROM Documentation INNER JOIN Doctor ON Documentation.DoctorId = Doctor.Id WHERE Documentation.PatientId = {id}"); } public static List<Documentation> GetDataByDoctorId(int id,int pid) { return Properties.dbContext.GetDocumentationDb($@"SELECT Documentation.Id, Documentation.PatientId, Concat(Doctor.Name, ' ', Doctor.Surname) AS DoctorName, Documentation.Disease, Documentation.Date FROM Documentation INNER JOIN Doctor ON Documentation.DoctorId = Doctor.Id WHERE Documentation.DoctorId = {id} AND Documentation.PatientId = {pid}"); } public static List<Documentation> AddDescriptionView(int patientId, int doctorId, string disease, DateTime date) { return Properties.dbContext.GetDocumentationDb($@"INSERT INTO Documentation (PatientId, DoctorId, Disease, Date) VALUES (" + patientId + "," + doctorId + ",'" + disease + "','CURDATE()');"); } public static void InsertData(int doctorId, int patientId, Documentation documentation, string date) { Properties.dbContext.ExecuteQuery($@"INSERT INTO Documentation (PatientId, DoctorId, Disease, Date) VALUES (" + patientId +"," + doctorId + ",'" + documentation.Disease + "', '"+date+"')"); } } }
c88cf6e6f4425265a0756497cb94dfc7b6061b13
C#
shendongnian/download4
/code11/1963862-59756137-213011581-14.cs
2.796875
3
class MainWindowViewModel : IDialogViewModelProvider { public void ShowFileAlreadyExistsDialog() { // Create the IDialogViewModel for the File Exists dialog var dialogTitleBarIcon = new BitmapImage(new Uri("../../logo.ico", UriKind.Relative)); if (titleBarIcon.CanFreeze) { titleBarIcon.Freeze(); } var message = "File exists. Do you want to replace it?"; var dialogTitle = "File Exists"; // Set the continuation callback which will be invoked once the dialog closed var fileExistsdialogViewModel = new FileExistsDialogViewModel( message, dialogTitle, dialogTitleBarIcon, dialogViewModel => HandleFileExistsDialogResponseAsync(dialogViewModel, filePath, settingsData)); // Show the dialog by setting the DialogViewModel property to an instance of IDialogViewModel this.DialogViewModel = fileExistsdialogViewModel; } // Continuation callback. Will be invoked once the dialog closed. // The parameter is the previously created FileExistsDialogViewmodel containing data set from the dialog. private async Task HandleFileExistsDialogResponseAsync(IDialogViewModel dialogViewModel, string filePath, string settingsData) { if (dialogViewModel.DialogResult == DialogResult.Accepted) { await SaveFileAsync(filePath, settingsData); } } // IDialogViewModelProvider interface implementation private IDialogViewModel dialogViewModel; public IDialogViewModel DialogViewModel { get => this.dialogViewModel; private set => TrySetValue(value, ref this.dialogViewModel); } }
99489082f97a389755a21f34285ea108348cea9b
C#
MatthiasSchilder/DotSpatial
/Source/Core/DotSpatial.NTSExtension/Voronoi/VNode.cs
2.6875
3
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; namespace DotSpatial.NTSExtension.Voronoi { /// <summary> /// The VNode. /// </summary> internal abstract class VNode { #region Fields private VNode _left; private VNode _right; #endregion #region Properties private VNode Left { get { return _left; } set { _left = value; value.Parent = this; } } private VNode Parent { get; set; } private VNode Right { get { return _right; } set { _right = value; value.Parent = this; } } #endregion #region Methods /// <summary> /// Checks the VDataNode for circles. /// </summary> /// <param name="n">The VDataNode.</param> /// <param name="ys">The ys.</param> /// <returns>The resulting VCircleEvent.</returns> public static VCircleEvent CircleCheckDataNode(VDataNode n, double ys) { VDataNode l = LeftDataNode(n); VDataNode r = RightDataNode(n); if (l == null || r == null || l.DataPoint == r.DataPoint || l.DataPoint == n.DataPoint || n.DataPoint == r.DataPoint) return null; if (MathTools.Ccw(l.DataPoint.X, l.DataPoint.Y, n.DataPoint.X, n.DataPoint.Y, r.DataPoint.X, r.DataPoint.Y, false) <= 0) return null; Vector2 center = Fortune.CircumCircleCenter(l.DataPoint, n.DataPoint, r.DataPoint); VCircleEvent vc = new() { NodeN = n, NodeL = l, NodeR = r, Center = center, Valid = true }; return vc.Y >= ys ? vc : null; } /// <summary> /// Cleans the tree. /// </summary> /// <param name="root">The root node.</param> public static void CleanUpTree(VNode root) { if (root is VDataNode) return; if (root is VEdgeNode ve) { while (ve.Edge.VVertexB == Fortune.VVUnkown) { ve.Edge.AddVertex(Fortune.VVInfinite); } if (ve.Flipped) { Vector2 t = ve.Edge.LeftData; ve.Edge.LeftData = ve.Edge.RightData; ve.Edge.RightData = t; } ve.Edge.Done = true; } CleanUpTree(root.Left); CleanUpTree(root.Right); } /// <summary> /// Processes the VCircleEvent. /// </summary> /// <param name="e">The VCircleEvent.</param> /// <param name="root">The root node.</param> /// <param name="vg">The VoronoiGraph.</param> /// <param name="circleCheckList">The circle check list.</param> /// <returns>The resulting root.</returns> public static VNode ProcessCircleEvent(VCircleEvent e, VNode root, VoronoiGraph vg, out VDataNode[] circleCheckList) { VEdgeNode eo; VDataNode b = e.NodeN; VDataNode a = LeftDataNode(b); VDataNode c = RightDataNode(b); if (a == null || b.Parent == null || c == null || !a.DataPoint.Equals(e.NodeL.DataPoint) || !c.DataPoint.Equals(e.NodeR.DataPoint)) { circleCheckList = new VDataNode[] { }; return root; // abbort because graph changed } VEdgeNode eu = (VEdgeNode)b.Parent; circleCheckList = new[] { a, c }; // 1. Create the new Vertex Vector2 vNew = new(e.Center.X, e.Center.Y); vg.Vertices.Add(vNew); // 2. Find out if a or c are in a distand part of the tree (the other is then b's sibling) and assign the new vertex if (eu.Left == b) { // c is sibling eo = EdgeToRightDataNode(a); // replace eu by eu's Right eu.Parent.Replace(eu, eu.Right); } else { // a is sibling eo = EdgeToRightDataNode(b); // replace eu by eu's Left eu.Parent.Replace(eu, eu.Left); } eu.Edge.AddVertex(vNew); eo.Edge.AddVertex(vNew); // 2. Replace eo by new Edge VoronoiEdge ve = new() { LeftData = a.DataPoint, RightData = c.DataPoint }; ve.AddVertex(vNew); vg.Edges.Add(ve); VEdgeNode ven = new(ve, false) { Left = eo.Left, Right = eo.Right }; if (eo.Parent == null) return ven; eo.Parent.Replace(eo, ven); return root; } /// <summary> /// Will return the new root (unchanged except in start-up). /// </summary> /// <param name="e">The VDataEvent.</param> /// <param name="root">The root node.</param> /// <param name="vg">The VoronoiGraph.</param> /// <param name="ys">The ys.</param> /// <param name="circleCheckList">The circle check list.</param> /// <returns>The new root.</returns> public static VNode ProcessDataEvent(VDataEvent e, VNode root, VoronoiGraph vg, double ys, out VDataNode[] circleCheckList) { if (root == null) { root = new VDataNode(e.DataPoint); circleCheckList = new[] { (VDataNode)root }; return root; } // 1. Find the node to be replaced VNode c = FindDataNode(root, ys, e.DataPoint.X); // 2. Create the subtree (ONE Edge, but two VEdgeNodes) VoronoiEdge ve = new() { LeftData = ((VDataNode)c).DataPoint, RightData = e.DataPoint, VVertexA = Fortune.VVUnkown, VVertexB = Fortune.VVUnkown }; vg.Edges.Add(ve); VNode subRoot; if (Math.Abs(ve.LeftData.Y - ve.RightData.Y) < 1e-10) { if (ve.LeftData.X < ve.RightData.X) { subRoot = new VEdgeNode(ve, false) { Left = new VDataNode(ve.LeftData), Right = new VDataNode(ve.RightData) }; } else { subRoot = new VEdgeNode(ve, true) { Left = new VDataNode(ve.RightData), Right = new VDataNode(ve.LeftData) }; } circleCheckList = new[] { (VDataNode)subRoot.Left, (VDataNode)subRoot.Right }; } else { subRoot = new VEdgeNode(ve, false) { Left = new VDataNode(ve.LeftData), Right = new VEdgeNode(ve, true) { Left = new VDataNode(ve.RightData), Right = new VDataNode(ve.LeftData) } }; circleCheckList = new[] { (VDataNode)subRoot.Left, (VDataNode)subRoot.Right.Left, (VDataNode)subRoot.Right.Right }; } // 3. Apply subtree if (c.Parent == null) return subRoot; c.Parent.Replace(c, subRoot); return root; } private static VEdgeNode EdgeToRightDataNode(VNode current) { VNode c = current; // 1. Up do { if (c.Parent == null) throw new Exception("No Left Leaf found!"); if (c.Parent.Right == c) { c = c.Parent; continue; } c = c.Parent; break; } while (true); return (VEdgeNode)c; } private static VDataNode FindDataNode(VNode root, double ys, double x) { VNode c = root; do { if (c is VDataNode node) return node; c = ((VEdgeNode)c).Cut(ys, x) < 0 ? c.Left : c.Right; } while (true); } private static VDataNode LeftDataNode(VNode current) { VNode c = current; // 1. Up do { if (c.Parent == null) return null; if (c.Parent.Left == c) { c = c.Parent; continue; } c = c.Parent; break; } while (true); // 2. One Left c = c.Left; // 3. Down while (c.Right != null) c = c.Right; return (VDataNode)c; // Cast instead of 'as' to cause an exception } private static VDataNode RightDataNode(VNode current) { VNode c = current; // 1. Up do { if (c.Parent == null) return null; if (c.Parent.Right == c) { c = c.Parent; continue; } c = c.Parent; break; } while (true); // 2. One Right c = c.Right; // 3. Down while (c.Left != null) c = c.Left; return (VDataNode)c; // Cast instead of 'as' to cause an exception } private void Replace(VNode childOld, VNode childNew) { if (Left == childOld) Left = childNew; else if (Right == childOld) Right = childNew; else throw new Exception("Child not found!"); childOld.Parent = null; } #endregion } }
dc314c63f7ae4e32a8113445ab91e910db56cf46
C#
npolyak/NP.LinearAlgebra
/MainTest/DimensionsUtils.cs
3.171875
3
using NP.Utilities; using System; using System.Collections.Generic; using System.Linq; namespace MainTest { public static class DimensionsUtils { public static Func<int, bool> DimensionCondition = (i) => i > 0; public static string DimensionsToStr(this IEnumerable<int> dimensions) { return dimensions.ToStr(i => !DimensionCondition(i)); } public static int TotalSize(this IEnumerable<int> dimensions) => dimensions.Where(DimensionCondition).Prod(); public static void CheckShape(this IEnumerable<int> dimensions, int arrayLenth) { int minDimensionLen = dimensions.TotalSize(); if (arrayLenth % minDimensionLen != 0) { throw new Exception($"ERROR: dimensions {dimensions.DimensionsToStr()} do not match the length {arrayLenth} of the array"); } } } }
037c13ada852ccf7c2d9e54acd27c3e94bd95c15
C#
msruzy/digimon-linkz-client
/System.Xml/System/Xml/Serialization/XmlSchemas.cs
2.796875
3
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Xml.Schema; namespace System.Xml.Serialization { /// <summary>Represents the collection of XML schemas.</summary> public class XmlSchemas : CollectionBase, IEnumerable<XmlSchema>, IEnumerable { private static string msdataNS = "urn:schemas-microsoft-com:xml-msdata"; private Hashtable table = new Hashtable(); IEnumerator<XmlSchema> IEnumerable<XmlSchema>.GetEnumerator() { return new XmlSchemaEnumerator(this); } /// <summary>Gets or sets the <see cref="T:System.Xml.Schema.XmlSchema" /> object at the specified index. </summary> /// <returns>The specified <see cref="T:System.Xml.Schema.XmlSchema" />.</returns> /// <param name="index">The index of the item to retrieve.</param> public XmlSchema this[int index] { get { if (index < 0 || index > this.Count) { throw new ArgumentOutOfRangeException(); } return (XmlSchema)base.List[index]; } set { base.List[index] = value; } } /// <summary>Gets a specified <see cref="T:System.Xml.Schema.XmlSchema" /> object that represents the XML schema associated with the specified namespace.</summary> /// <returns>The specified <see cref="T:System.Xml.Schema.XmlSchema" /> object.</returns> /// <param name="ns">The namespace of the specified object.</param> public XmlSchema this[string ns] { get { return (XmlSchema)this.table[(ns == null) ? string.Empty : ns]; } } /// <summary>Gets a value that indicates whether the schemas have been compiled.</summary> /// <returns>true, if the schemas have been compiled; otherwise, false.</returns> [MonoTODO] public bool IsCompiled { get { throw new NotImplementedException(); } } /// <summary>Processes the element and attribute names in the XML schemas and, optionally, validates the XML schemas. </summary> /// <param name="handler">A <see cref="T:System.Xml.Schema.ValidationEventHandler" /> that specifies the callback method that handles errors and warnings during XML Schema validation, if the strict parameter is set to true.</param> /// <param name="fullCompile">true to validate the XML schemas in the collection using the <see cref="M:System.Xml.Serialization.XmlSchemas.Compile(System.Xml.Schema.ValidationEventHandler,System.Boolean)" /> method of the <see cref="T:System.Xml.Serialization.XmlSchemas" /> class; otherwise, false.</param> [MonoTODO] public void Compile(ValidationEventHandler handler, bool fullCompile) { foreach (object obj in this) { XmlSchema xmlSchema = (XmlSchema)obj; if (fullCompile || !xmlSchema.IsCompiled) { xmlSchema.Compile(handler); } } } /// <summary>Adds an object to the end of the collection.</summary> /// <returns>The index at which the <see cref="T:System.Xml.Schema.XmlSchema" /> is added.</returns> /// <param name="schema">The <see cref="T:System.Xml.Schema.XmlSchema" /> object to be added to the collection of objects. </param> public int Add(XmlSchema schema) { this.Insert(this.Count, schema); return this.Count - 1; } /// <summary>Adds an instance of the <see cref="T:System.Xml.Serialization.XmlSchemas" /> class to the end of the collection.</summary> /// <param name="schemas">The <see cref="T:System.Xml.Serialization.XmlSchemas" /> object to be added to the end of the collection. </param> public void Add(XmlSchemas schemas) { foreach (object obj in schemas) { XmlSchema schema = (XmlSchema)obj; this.Add(schema); } } /// <summary>Adds an <see cref="T:System.Xml.Schema.XmlSchema" /> object that represents an assembly reference to the collection.</summary> /// <returns>The index at which the <see cref="T:System.Xml.Schema.XmlSchema" /> is added.</returns> /// <param name="schema">The <see cref="T:System.Xml.Schema.XmlSchema" /> to add.</param> /// <param name="baseUri">The <see cref="T:System.Uri" /> of the schema object.</param> [MonoNotSupported("")] public int Add(XmlSchema schema, Uri baseUri) { throw new NotImplementedException(); } /// <summary>Adds an <see cref="T:System.Xml.Schema.XmlSchema" /> object that represents an assembly reference to the collection.</summary> /// <param name="schema">The <see cref="T:System.Xml.Schema.XmlSchema" /> to add.</param> [MonoNotSupported("")] public void AddReference(XmlSchema schema) { throw new NotImplementedException(); } /// <summary>Determines whether the <see cref="T:System.Xml.Serialization.XmlSchemas" /> contains a specific schema.</summary> /// <returns>true, if the collection contains the specified item; otherwise, false.</returns> /// <param name="schema">The <see cref="T:System.Xml.Schema.XmlSchema" /> object to locate. </param> public bool Contains(XmlSchema schema) { return base.List.Contains(schema); } /// <summary>Returns a value that indicates whether the collection contains an <see cref="T:System.Xml.Schema.XmlSchema" /> object that belongs to the specified namespace.</summary> /// <returns>true if the item is found; otherwise, false.</returns> /// <param name="targetNamespace">The namespace of the item to check for.</param> [MonoNotSupported("")] public bool Contains(string targetNamespace) { throw new NotImplementedException(); } /// <summary>Copies the entire <see cref="T:System.Xml.Serialization.XmlSchemas" /> to a compatible one-dimensional <see cref="T:System.Array" />, which starts at the specified index of the target array.</summary> /// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the schemas copied from <see cref="T:System.Xml.Serialization.XmlSchemas" />. The <see cref="T:System.Array" /> must have zero-based indexing. </param> /// <param name="index">A 32-bit integer that represents the index in the array where copying begins.</param> public void CopyTo(XmlSchema[] array, int index) { base.List.CopyTo(array, index); } /// <summary>Locates in one of the XML schemas an <see cref="T:System.Xml.Schema.XmlSchemaObject" /> of the specified name and type. </summary> /// <returns>An <see cref="T:System.Xml.Schema.XmlSchemaObject" /> instance, such as an <see cref="T:System.Xml.Schema.XmlSchemaElement" /> or <see cref="T:System.Xml.Schema.XmlSchemaAttribute" />.</returns> /// <param name="name">An <see cref="T:System.Xml.XmlQualifiedName" /> that specifies a fully qualified name with a namespace used to locate an <see cref="T:System.Xml.Schema.XmlSchema" /> object in the collection.</param> /// <param name="type">The <see cref="T:System.Type" /> of the object to find. Possible types include: <see cref="T:System.Xml.Schema.XmlSchemaGroup" />, <see cref="T:System.Xml.Schema.XmlSchemaAttributeGroup" />, <see cref="T:System.Xml.Schema.XmlSchemaElement" />, <see cref="T:System.Xml.Schema.XmlSchemaAttribute" />, and <see cref="T:System.Xml.Schema.XmlSchemaNotation" />.</param> public object Find(XmlQualifiedName name, Type type) { XmlSchema xmlSchema = this.table[name.Namespace] as XmlSchema; if (xmlSchema == null) { foreach (object obj in this) { XmlSchema schema = (XmlSchema)obj; object obj2 = this.Find(schema, name, type); if (obj2 != null) { return obj2; } } return null; } object obj3 = this.Find(xmlSchema, name, type); if (obj3 == null) { foreach (object obj4 in this) { XmlSchema schema2 = (XmlSchema)obj4; object obj5 = this.Find(schema2, name, type); if (obj5 != null) { return obj5; } } } return obj3; } private object Find(XmlSchema schema, XmlQualifiedName name, Type type) { if (!schema.IsCompiled) { schema.Compile(null); } XmlSchemaObjectTable xmlSchemaObjectTable = null; if (type == typeof(XmlSchemaSimpleType) || type == typeof(XmlSchemaComplexType)) { xmlSchemaObjectTable = schema.SchemaTypes; } else if (type == typeof(XmlSchemaAttribute)) { xmlSchemaObjectTable = schema.Attributes; } else if (type == typeof(XmlSchemaAttributeGroup)) { xmlSchemaObjectTable = schema.AttributeGroups; } else if (type == typeof(XmlSchemaElement)) { xmlSchemaObjectTable = schema.Elements; } else if (type == typeof(XmlSchemaGroup)) { xmlSchemaObjectTable = schema.Groups; } else if (type == typeof(XmlSchemaNotation)) { xmlSchemaObjectTable = schema.Notations; } object obj = (xmlSchemaObjectTable == null) ? null : xmlSchemaObjectTable[name]; if (obj != null && obj.GetType() != type) { return null; } return obj; } /// <summary>Gets a collection of schemas that belong to the same namespace.</summary> /// <returns>An <see cref="T:System.Collections.IList" /> implementation that contains the schemas.</returns> /// <param name="ns">The namespace of the schemas to retrieve.</param> [MonoNotSupported("")] public IList GetSchemas(string ns) { throw new NotImplementedException(); } /// <summary>Searches for the specified schema and returns the zero-based index of the first occurrence within the entire <see cref="T:System.Xml.Serialization.XmlSchemas" />.</summary> /// <returns>The zero-based index of the first occurrence of the value within the entire <see cref="T:System.Xml.Serialization.XmlSchemas" />, if found; otherwise, -1.</returns> /// <param name="schema">The <see cref="T:System.Xml.Schema.XmlSchema" /> to locate. </param> public int IndexOf(XmlSchema schema) { return base.List.IndexOf(schema); } /// <summary>Inserts a schema into the <see cref="T:System.Xml.Serialization.XmlSchemas" /> at the specified index.</summary> /// <param name="index">The zero-based index at which <paramref name="schema" /> should be inserted. </param> /// <param name="schema">The <see cref="T:System.Xml.Schema.XmlSchema" /> object to be inserted. </param> public void Insert(int index, XmlSchema schema) { base.List.Insert(index, schema); } /// <summary>Static method that determines whether the specified XML schema contains a custom IsDataSet attribute set to true, or its equivalent. </summary> /// <returns>true if the specified schema exists; otherwise, false.</returns> /// <param name="schema">The XML schema to check for an IsDataSet attribute with a true value.</param> public static bool IsDataSet(XmlSchema schema) { XmlSchemaElement xmlSchemaElement = (schema.Items.Count != 1) ? null : (schema.Items[0] as XmlSchemaElement); if (xmlSchemaElement != null && xmlSchemaElement.UnhandledAttributes != null && xmlSchemaElement.UnhandledAttributes.Length > 0) { for (int i = 0; i < xmlSchemaElement.UnhandledAttributes.Length; i++) { XmlAttribute xmlAttribute = xmlSchemaElement.UnhandledAttributes[i]; if (xmlAttribute.NamespaceURI == XmlSchemas.msdataNS && xmlAttribute.LocalName == "IsDataSet") { return xmlAttribute.Value.ToLower(CultureInfo.InvariantCulture) == "true"; } } } return false; } /// <summary>Performs additional custom processes when clearing the contents of the <see cref="T:System.Xml.Serialization.XmlSchemas" /> instance.</summary> protected override void OnClear() { this.table.Clear(); } /// <summary>Performs additional custom processes before inserting a new element into the <see cref="T:System.Xml.Serialization.XmlSchemas" /> instance.</summary> /// <param name="index">The zero-based index at which to insert <paramref name="value" />. </param> /// <param name="value">The new value of the element at <paramref name="index" />. </param> protected override void OnInsert(int index, object value) { string text = ((XmlSchema)value).TargetNamespace; if (text == null) { text = string.Empty; } this.table[text] = value; } /// <summary>Performs additional custom processes when removing an element from the <see cref="T:System.Xml.Serialization.XmlSchemas" /> instance.</summary> /// <param name="index">The zero-based index at which <paramref name="value" /> can be found. </param> /// <param name="value">The value of the element to remove at <paramref name="index" />. </param> protected override void OnRemove(int index, object value) { this.table.Remove(value); } /// <summary>Performs additional custom processes before setting a value in the <see cref="T:System.Xml.Serialization.XmlSchemas" /> instance.</summary> /// <param name="index">The zero-based index at which <paramref name="oldValue" /> can be found. </param> /// <param name="oldValue">The value to replace with <paramref name="newValue" />. </param> /// <param name="newValue">The new value of the element at <paramref name="index" />. </param> protected override void OnSet(int index, object oldValue, object newValue) { string text = ((XmlSchema)oldValue).TargetNamespace; if (text == null) { text = string.Empty; } this.table[text] = newValue; } /// <summary>Removes the first occurrence of a specific schema from the <see cref="T:System.Xml.Serialization.XmlSchemas" />.</summary> /// <param name="schema">The <see cref="T:System.Xml.Schema.XmlSchema" /> to remove. </param> public void Remove(XmlSchema schema) { base.List.Remove(schema); } } }
c0b3911eedaa16367098a39c9c3d2ccacfb84994
C#
Nick-Semenyk/BSU.ASP15.01.Day8.Semenyk
/Matrix/Matrix/Matrix.cs
3.15625
3
using System; using System.CodeDom; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CSharp.RuntimeBinder; using static System.Math; namespace Matrix { public abstract class Matrix<T> : IEnumerable<T> { public int Size { get; protected set; } public T this[int a, int b] { get { return GetValue(a, b); } set { SetValue(a, b, value); } } public abstract T GetValue(int a, int b); public abstract void SetValue(int a, int b, T value); public IEnumerator<T> GetEnumerator() { for (int i = 0; i<Size; i++) for (int j = 0; j<Size; j++) yield return GetValue(i, j); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class SquareMatrix<T> : Matrix<T>, IEquatable<SquareMatrix<T>> { private T[][] matrix; public event EventHandler<MatrixChangeArgs> MatrixChanged = delegate { }; public override T GetValue(int a, int b) { if (a < Size && b < Size && a >= 0 && b >= 0) return matrix[a][b]; throw new MatrixElementAccessException("There is no element in this matrix with such index"); } public override void SetValue(int a, int b, T value) { if (a < Size && b < Size && a >= 0 && b >= 0) { matrix[a][b] = value; EventHandler<MatrixChangeArgs> handler = MatrixChanged; handler(this, new MatrixChangeArgs(a, b)); } else throw new MatrixElementAccessException("There is no element in this matrix with such index"); } public SquareMatrix(T[][] array) { if (array == null) throw new ArgumentNullException(); if (!array.Any()) throw new ArgumentException(); matrix = new T[array.Count()][]; for (int i = 0; i<array.Count(); i++) { if (array[i] == null) throw new ArgumentNullException(); if (array[i].Count() != array.Count()) throw new NotSquareArrayException(); matrix[i] = new T[array.Count()]; for (int j = 0; j<array[i].Count(); j++) { matrix[i][j] = array[i][j]; } } Size = matrix.Count(); } public SquareMatrix(int x) { if (x <= 0) throw new ArgumentException("Matrix must have positive size"); Size = x; matrix = new T[x][]; for (int i = 0; i<x; i++) { matrix[i] = new T[x]; for (int j = 0; j < x; j++) { matrix[i][j] = default(T); } } } public static SquareMatrix<T> operator +(SquareMatrix<T> lhs, SquareMatrix<T> rhs) { //can use + dynamic a = default(T); T b = default(T); try { a = a + b; } catch (RuntimeBinderException) { throw new InvalidOperationException(); } if (lhs == null || rhs == null) throw new ArgumentNullException(); if (lhs.Size != rhs.Size) throw new InvalidOperationException(); SquareMatrix<T> result = new SquareMatrix<T>(lhs.Size); for (int i = 0; i<lhs.Size; i++) { for (int j = 0; j<lhs.Size; j++) { dynamic leftSummand = lhs[i, j]; dynamic rightSummand = rhs[i, j]; dynamic sum = leftSummand + rightSummand; result[i, j] = sum; } } return result; } public virtual void Transpose() { for (int i = 0; i<Size; i++) for (int j = i+1; j<Size; j++) { T swapValue = this[i,j]; this[i,j] = this[j,i]; this[j,i] = swapValue; } } public bool Equals(SquareMatrix<T> other) { for (int i = 0; i<matrix.Count(); i++) { for(int j = 0; j<matrix[i].Count(); j++) { if (other[i,j] == null && matrix[i][j] == null) { continue; } if (other[i,j]?.Equals(matrix[i][j]) == true) { } else { return false; } } } return true; } public override string ToString() { StringBuilder result = new StringBuilder(); for (int i = 0; i < Size; i++) { for (int j = 0; j < Size; j++) { result.Append(matrix[i][j].ToString()); result.Append(' '); } result.Append(Environment.NewLine); } return result.ToString(); } } public class SymmetricMatrix<T> : Matrix<T> { private T[] elements; public SymmetricMatrix(T[][] array) { if (array == null) throw new ArgumentNullException(); if (!array.Any()) throw new ArgumentException(); elements = new T[array.Count() * (array.Count() - 1) / 2]; Size = array.Count(); for (int i = 0; i<array.Count(); i++) { if (array[i] == null) throw new ArgumentNullException(); if (array[i].Count() != array.Count()) throw new NotSquareArrayException(); for (int j = i; j<array.Count(); j++) { if (array[j] == null) throw new ArgumentNullException(); if (array[i][j]?.Equals(array[j][i]) ?? (array[i][j] == null && array[j][i] == null)) { SetValue(i, j, array[i][j]); } else { throw new NotSymmetricArrayException(); } } } } public SymmetricMatrix(int x) { if (x <= 1) throw new ArgumentException(); elements = new T[x * (x + 1) / 2]; } public static SymmetricMatrix<T> operator +(SymmetricMatrix<T> lhs, SymmetricMatrix<T> rhs) { //can use + dynamic a = default(T); dynamic b = default(T); try { a = a + b; } catch (Exception) { throw new InvalidOperationException(); } if (lhs == null || rhs == null) throw new ArgumentNullException(); if (lhs.Size != rhs.Size) throw new InvalidOperationException(); SymmetricMatrix<T> result = new SymmetricMatrix<T>(lhs.Size); for (int i = 0; i < lhs.Size; i++) { for (int j = i; j < lhs.Size; j++) { dynamic leftSummand = lhs[i, j]; dynamic rightSummand = rhs[i, j]; dynamic sum = leftSummand + rightSummand; result[i, j] = sum; } } return result; } public override T GetValue(int a, int b) { if (a < Size && b < Size && a >= 0 && b >= 0) return elements[Max(a,b) * (Max(a,b) + 1) + Min(a,b)]; throw new MatrixElementAccessException("There is no element in this matrix with such index"); } public override void SetValue(int a, int b, T value) { if (a < Size && b < Size && a >= 0 && b >= 0) elements[Max(a, b)*(Max(a, b) + 1) + Min(a, b)] = value; throw new MatrixElementAccessException("There is no element in this matrix with such index"); } } public class DiagonalMatrix<T> : Matrix<T> { private T[] elements; public DiagonalMatrix(T[][] array) { if (array == null) throw new ArgumentNullException(); if (!array.Any()) throw new ArgumentException(); elements = new T[array.Count()]; Size = array.Count(); for (int i = 0; i < array.Count(); i++) { if (array[i] == null) throw new ArgumentNullException(); if (array[i].Count() != array.Count()) throw new NotSquareArrayException(); for (int j = 0; j < array.Count(); j++) { if (i == j) { SetValue(i, i, array[i][j]); continue; } if (!default(T).Equals(array[i][j])) throw new NotDiagonalMatrixExeption(); } } } public DiagonalMatrix(int size) { if (size <= 1) throw new ArgumentException(); elements = new T[size]; Size = size; } public static DiagonalMatrix<T> operator +(DiagonalMatrix<T> lhs, DiagonalMatrix<T> rhs) { //can use + dynamic a = default(T); dynamic b = default(T); try { a = a + b; } catch (Exception) { throw new InvalidOperationException(); } if (lhs == null || rhs == null) throw new ArgumentNullException(); if (lhs.Size != rhs.Size) throw new InvalidOperationException(); DiagonalMatrix<T> result = new DiagonalMatrix<T>(lhs.Size); for (int i = 0; i < lhs.Size; i++) { dynamic leftSummand = lhs[i, i]; dynamic rightSummand = rhs[i, i]; dynamic sum = leftSummand + rightSummand; result[i, i] = sum; } return result; } public override T GetValue(int a, int b) { if (a < Size && b < Size && a >= 0 && b >= 0) if (a == b) return elements[a]; else return default(T); throw new MatrixElementAccessException("There is no element in this matrix with such index"); } public override void SetValue(int a, int b, T value) { if (a < Size && b < Size && a >= 0 && b >= 0) if (a == b) elements[a] = value; throw new MatrixElementAccessException("There is no element in this matrix with such index"); } } }
51da4aae49441738b037a403fe410feec9d3bf81
C#
YoeriVD/ADCSBDEMOS
/ADCSBDEMOS/Chapter 5/TaskParallelLibraryDemos.cs
3.296875
3
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace ADCSBDEMOS.Chapter_5 { internal class TaskParallelLibraryDemos { public event EventHandler SomeEvent; public void Run() { //ParallelDemo(); Tasks(); Console.WriteLine("DONE!"); } private void ParallelDemo() { for (var i = 0; i < 10; i++) { // DoWork(i); } var range = new List<string> { "test", "tfgsdfgt", "tfgsdfgdsfgft", "testfgsdfgsdgdsfgd" }; Parallel.ForEach(range, (current, loopState) => { DoWork(current); }); } private void Tasks() { var listOfTasks = new List<Task>(); for (var i = 0; i < 100; i++) { var count = i; var source = new CancellationTokenSource(); var t = Task.Run(() => DoWork(count.ToString()), source.Token); t.ContinueWith(previousTask => { if (!previousTask.IsCanceled && previousTask.IsCompleted) { Console.WriteLine(previousTask.Result); } else { Console.WriteLine($"c: {previousTask.IsCanceled}, f: {previousTask.IsFaulted}"); } throw new Exception(); }, source.Token) .ContinueWith( task => Console.WriteLine("faulted: " + task.IsFaulted), source.Token); listOfTasks.Add(t); source.Cancel(); } try { Task.WaitAll(listOfTasks.ToArray()); } catch (AggregateException ae) { Console.WriteLine(ae.InnerException.Message); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); } } private string DoWork(string i) { Thread.Sleep(new Random().Next(200, 2000)); Console.WriteLine(i + " is ready"); return i + "from task 1"; } } }
21cd546c8676c49cec64c78c1bda967048acb857
C#
GwennyB/Lab04-TicTacToe
/Lab04_TicTacToe/Classes/Board.cs
3.765625
4
using System; using System.Collections.Generic; using System.Text; namespace Lab04_TicTacToe.Classes { public class Board { /// <summary> /// Tic Tac Toe Gameboard states /// </summary> public string[,] GameBoard = new string[,] { {"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}, }; /// <summary> /// Displays the game board in its current state of play /// </summary> public void DisplayBoard() { Console.WriteLine("\n Let's Play Tic-Tac-Toe!\n"); //TODO: Output the board to the console for (int i = 0; i < 3; i++) { Console.Write(" "); for (int k = 0; k < 3; k++) { Console.Write($" [ {GameBoard[i, k]} ] "); } Console.Write("\n"); } Console.WriteLine("\n\n"); } } }
a5bb5727b14689d55678279298f620fd01e91dda
C#
dkhodko/Att_1
/1_28_3/3_1_28.cs
3.671875
4
using System; namespace _3_1_28 { enum SimpleColor { Black, White, Gray, Red, Orange, Yellow, Green, Blue } class Program { static bool IsPointAboveParabolaY(double x, double y, double x0, double y0, double a) { return y > a * Math.Pow(x - x0, 2) + y0; } static bool IsPointInRect(double x, double y, double x0, double y0, double w, double h) { return (y <= y0 && y >= y0 - h && x >= x0 && x <= x0 + w); } static bool IsPointAboveParabola1(double x, double y) { return IsPointAboveParabolaY(x, y, 0, -6, 1); } static bool IsPointInRect1(double x, double y) { return IsPointInRect(x, y, -6, 5, 10, 9); } static bool IsPointInRect2(double x, double y) { return IsPointInRect(x, y, 1, 9, 7, 9); } static SimpleColor GetColor(double x, double y) { if ((IsPointAboveParabola1(x, y) && IsPointInRect1(x, y)) || (IsPointAboveParabola1(x, y) && IsPointInRect2(x, y))) { return SimpleColor.Gray; } if ((IsPointInRect1(x, y) && x < 0 && !IsPointAboveParabola1(x, y)) || (IsPointAboveParabola1(x, y) && y < 0 && !IsPointInRect1(x, y))) { return SimpleColor.Orange; } if ((IsPointAboveParabola1(x, y) && y > 0 && !IsPointInRect1(x, y) && !IsPointInRect2(x, y)) || (IsPointInRect1(x, y) && IsPointInRect2(x, y) && !IsPointAboveParabola1(x, y))) { return SimpleColor.White; } if (IsPointInRect1(x, y) && x > 0 && !IsPointAboveParabola1(x, y) && !IsPointInRect2(x, y)) { return SimpleColor.Yellow; } if (IsPointInRect2(x, y) && !IsPointInRect1(x, y) && !IsPointAboveParabola1(x, y)) { return SimpleColor.Blue; } else return SimpleColor.Gray; } static void PrintColorForPoint(double x, double y) { Console.WriteLine("({0}, {1}) -> {2}", x, y, GetColor(x, y)); } static void PrintTestPoints() { PrintColorForPoint(1, 1); PrintColorForPoint(0, -5); PrintColorForPoint(-3, 0); PrintColorForPoint(5, 5); PrintColorForPoint(3, 0); PrintColorForPoint(3, -3); PrintColorForPoint(0, 8); } static double ReadData(string varName) { while (true) { try { Console.WriteLine("Введите {0}: ", varName); double value = double.Parse(Console.ReadLine()); return value; } catch (FormatException) { Console.WriteLine("Переменная должна являться числом"); } } } static void ReadCoord(out double x, out double y) { x = ReadData("X"); y = ReadData("Y"); } static void Main(string[] args) { PrintTestPoints(); while (true) { double x, y; ReadCoord(out x, out y); if (x < 10 && x > -10 && y < 10 && y > -10) PrintColorForPoint(x, y); else Console.WriteLine("Не входит в промежуток"); } } } }
60a5ba44ed16add8e135ec2d59b80a11a5f583de
C#
Bhitt/Hash_Tables
/Unique_Morse_Code_Words/Solution1.cs
3.84375
4
/* Solution 1 1) Enter the morse code letter representations into a hashmap for quick lookup 2) Keep a hashset for the transformations built from each word 3) Use a stringbuilder when creating transformations for fast appends 4) Foreach word in words Map each character to its morse code representation. Append that string to the transformation. After mapping all characters, add the transformation string to the hashset. 5) Return the number of unique strings in the hashset (Count). */ /* Time Complexity: O(C), the total number of characters in all the input words Space Complexity: O(S), the unique number of transformation strings saved to the hashset */ public class Solution { public int UniqueMorseRepresentations(string[] words) { // HashMap for Morse Code representation string[] morse = new string[] {".-","-...","-.-.","-..",".","..-.", "--.","....","..",".---","-.-",".-..", "--","-.","---",".--.","--.-",".-.", "...","-","..-","...-",".--","-..-", "-.--","--.."}; // HashSet for transformations HashSet<string> hs = new HashSet<string>(); // StringBuilder for quick appends StringBuilder sb = new StringBuilder(); // For each word in words foreach(string s in words){ // Add the morse code representations of each character in the word foreach(char c in s){ sb.Append(morse[c - 'a']); } // Add the transformation to the hashset hs.Add(sb.ToString()); // Clear the contents of StringBuilder sb.Clear(); } // Return the count of unique transformations return hs.Count; } } /* LEET CODE RESULTS Runtime: 88 ms, faster than 91.84% of C# online submissions for Unique Morse Code Words. Memory Usage: 25.2 MB, less than 74.83% of C# online submissions for Unique Morse Code Words. */
4d6098bc17fad83d4937281e2eb008d6432d2917
C#
briang123/Vidly
/Vidly/App_Start/MappingProfile.cs
2.5625
3
using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Web; using Vidly.Dtos; using Vidly.Models; namespace Vidly { public class MappingProfile : Profile { //commented out block is for latest version of AutoMapper vs. v4.1 //public static void Run() //{ // Mapper.Initialize(a => // { // a.AddProfile<MappingProfile>(); // }); //} public MappingProfile() { //Mapper.CreateMap<Customer, CustomerDto>().ReverseMap(); //instead of 2 create maps model/dto Mapper.CreateMap<Customer, CustomerDto>(); Mapper.CreateMap<MembershipType, MembershipTypeDto>(); Mapper.CreateMap<Movie, MovieDto>(); Mapper.CreateMap<Genre, GenreDto>(); Mapper.CreateMap<CustomerDto, Customer>(); Mapper.CreateMap<MovieDto, Movie>(); // Dto to Domain //Mapper.CreateMap<CustomerDto, Customer>() // .ForMember(c => c.Id, opt => opt.Ignore()); //Mapper.CreateMap<MovieDto, Movie>() // .ForMember(c => c.Id, opt => opt.Ignore()); } } }
b88ef0fc9dc81afda3bdd736c9d01c65f87ddd5d
C#
RachanaReddy47/AspMVC
/AspMVC/Models/DBOperations.cs
2.65625
3
using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure; using System.Data.SqlClient; using System.Linq; using System.Web; namespace AspMVC.Models { public class DBOperations { static DemoEntities D = new DemoEntities(); public static string InsertEmp(EMPDATA A) { try { D.EMPDATAs.Add(A); D.SaveChanges(); } catch(DbUpdateException E) { SqlException ex = E.GetBaseException() as SqlException; if (ex.Message.Contains("EMP_PK")) return "Employee no already Exists"; else if (ex.Message.Contains("FK__EMPDATA_DEPTNO")) return "No such Deptno exists"; else return "Error Ocurred"; } return "1 row inserted"; } public static List<EMPDATA> GetDept(int Deptno) { var LE = from L in D.EMPDATAs where L.DEPTNO == Deptno select L; return LE.ToList(); } public static List<EMPDATA> ExtractEmp(EMPDATA E) { var LE = from L in D.EMPDATAs where L.EMPNO == E.EMPNO select L; return LE.ToList(); } public static List<DEPTDATA> getDepts() { var dept = from D1 in D.DEPTDATAs select D1; return dept.ToList(); } public static List<EMPDATA> getEmpno() { var Empno = from E in D.EMPDATAs select E; return Empno.ToList(); } public static string DelEmpno(int eno) { var Empno = from E in D.EMPDATAs where E.EMPNO == eno select E; EMPDATA Eno =Empno.First(); D.EMPDATAs.Remove(Eno); D.SaveChanges(); return "1 row deleted"; } public static EMPDATA GetEmp(int eno) { var LE = from L in D.EMPDATAs where L.EMPNO == eno select L; EMPDATA Empno= LE.First(); return Empno; } public static string UpdateEmp(EMPDATA A) { try { var LE = from L in D.EMPDATAs where L.EMPNO == A.EMPNO select L; EMPDATA a = LE.First(); a.ENAME = A.ENAME; a.JOB = A.JOB; a.MGR = A.MGR; a.SAL = A.SAL; D.SaveChanges(); } catch(DbUpdateException E) { SqlException ex = E.GetBaseException() as SqlException; } return "1 row updated"; } public static List<EMPDATA> ExtractDate(DateTime dt1, DateTime dt2) { var Emp = from L in D.EMPDATAs where L.HIREDATE >= dt1 && L.HIREDATE <= dt2 select L; return Emp.ToList(); } } }
78981015ee07c5d8f0fe293e6c2e891f06109a71
C#
Bikeman868/OwinFramework.Authorization
/OwinFramework.Authorization.Core/DataContracts/Permission.cs
2.71875
3
namespace OwinFramework.Authorization.Core.DataContracts { /// <summary> /// The database representation of a permission that is tested /// by the application software before allowing access to /// restricted features. /// </summary> public class Permission { /// <summary> /// Database primary key value /// </summary> public long Id { get; set; } /// <summary> /// An internal name for this permission that is referred to in the /// source code of the application and should not be changed in /// the database /// </summary> public string CodeName { get; set; } /// <summary> /// The name of this permission displayed in the UI /// </summary> public string DisplayName { get; set; } /// <summary> /// Optional restriction on the permission limiting it to only a /// subset of the protected resources. For example there might be a /// permission for cancelling an order, some users might be able to /// cancel any order whereas other users can only cancel orders that /// they placed on the system. /// </summary> public string Resource { get; set; } /// <summary> /// A description of what this permission gives access to. This is /// displayed in the UI to helf the person managing the system to /// decide whether to assign this permission to users /// </summary> public string Description { get; set; } } }
79abdfbfeb9c51639ee195ed6d6b4560969768f7
C#
ser910/uwp
/NetGames/Tank/GameObject/Tank.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TankGame.Map; namespace TankGame.GameObject { public class Tank : GameObject { public Tank(double X, double Y, double Speed = 1, double Health = 1, Direction Direction = Direction.Non, bool IsAI = false, bool IsPlayer = false, double Width = 1, double Height = 1, bool IsMove = true, bool IsVisible = true, bool IsTransparante = false, bool IsCanBeDestroyed = true) : base(X, Y, Width, Health, Health, Speed, IsVisible, IsTransparante, IsCanBeDestroyed, IsMove, IsAI, IsPlayer, Direction) { } public bool Shot(Map.Map Map) { Bullet Bullet = new Bullet(this.X, this.Y, this.Direction); Bullet.Move(this.Direction,Map); Map.AddObject(Bullet); return true; } } }
b5dda7727c8f0cd80ee43fe0d30d9583160b2957
C#
Krypton091/MG_SE256
/SE256_RazorFinal_MattG/Models/SongModel.cs
2.546875
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace SE256_RazorFinal_MattG.Models { public class SongModel { [Required] public int Song_ID { get; set; } //primary key [Required, StringLength(255)] public String Song_Title { get; set; } //Title of song [Required] public String Song_Artist { get; set; } //Artist of song [Required] [RegularExpression(@"^[0-9]+\:[0-5]+\d$", ErrorMessage = "Please enter a time in the MM:SS format e.g 5:00, 63:24, 3:59")] public String Song_PlayTime { get; set; } //Length of song [Required] [RegularExpression(@"^[1-5]\.[05]$", ErrorMessage = "Please a 1-5 rating, ending in '.0' or '.5' e.g 3.0, 4.5, 5.0")] public Decimal Song_Rating { get; set; } //Song rating [Required] [Display(Name = "Song Release Date")] [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)] [MyDate(ErrorMessage = "Future dates not allowed")] public DateTime Song_Date { get; set; } //Release date of song [Required] public Boolean Song_Owned { get; set; } //Whether the song is owned or not [Required] [EmailAddress] public String Artist_Email { get; set; } //Artist's email [Required] public String Artist_Website { get; set; } //Artist's website public String Feedback { get; set; } } }
7eaca46a1f68e8fbdc439796d73d53d6724cba35
C#
sakapon/AtCoder-Contests
/CSharp/Contests2022/ABC234/E.cs
3.40625
3
using System; using System.Collections.Generic; using System.Linq; class E { static void Main() => Console.WriteLine(Solve()); static object Solve() { var x = long.Parse(Console.ReadLine()); var nums = new List<long>(); for (int k = 1; k <= 18; k++) { var ks = Enumerable.Range(0, k).ToArray(); for (int d1 = 1; d1 <= 9; d1++) { for (int d = -9; d <= 9; d++) { var ds = ks.Select(v => d1 + v * d).ToArray(); if (ds.Any(v => v < 0 || v > 9)) continue; var s = string.Join("", ds); nums.Add(long.Parse(s)); } } } return nums.First(v => v >= x); } }
5801061bc12a175486e5e1e96bc99eca0fa31194
C#
lucypero/BehaviorTreeCS
/BehaviorTreeCS/Components/Actions/PopFromStack.cs
2.859375
3
using System; using System.Collections.Generic; namespace BehaviorTreeCS { public class PopFromStack : Action { string stackKey; string stackValKey; public PopFromStack(string stackKey, string stackValKey) { this.stackKey = stackKey; this.stackValKey = stackValKey; } protected override BehaviorReturnCode Update(object agent, Blackboard blackboard) { try { Stack<object> stack = blackboard.GetVariable(stackKey) as Stack<object>; blackboard.SetVariable(stackValKey, stack.Pop()); ReturnCode = BehaviorReturnCode.Success; return BehaviorReturnCode.Success; } catch(InvalidOperationException e) { ReturnCode = BehaviorReturnCode.Failure; return BehaviorReturnCode.Failure; } } } }
6d1bb8b9e67311eb97ce3ce6880c586a431783f7
C#
georgipyaramov/HighQualityProgrammingCode
/UnitTesting/TestSchoolSystem/SchoolTest.cs
3.078125
3
namespace TestSchoolSystem { using System; using System.Collections.Generic; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using SchoolSystem; [TestClass] public class SchoolTest { [TestMethod] public void AddNewStudent_AddOneStudent() { School theSchool = new School(); theSchool.AddNewStudent("Gosho"); School myObject = theSchool; Type myType = typeof(School); FieldInfo setOfStudents = myType.GetField("students", BindingFlags.NonPublic | BindingFlags.Instance); IList<Student> students = setOfStudents.GetValue(myObject) as IList<Student>; Assert.IsTrue(students.Count == 1); } [TestMethod] public void AddNewStudent_AddFewStudents() { School theSchool = new School(); int few = 5; for (int i = 0; i < few; i++) { theSchool.AddNewStudent("Gosho"); } School myObject = theSchool; Type myType = typeof(School); FieldInfo setOfStudents = myType.GetField("students", BindingFlags.NonPublic | BindingFlags.Instance); IList<Student> students = setOfStudents.GetValue(myObject) as IList<Student>; Assert.IsTrue(students.Count == few); } [TestMethod] [ExpectedExceptionAttribute(typeof(InvalidOperationException))] public void AddNewStudent_AddTooManyStudents() { School theSchool = new School(); Type myType = typeof(School); FieldInfo maxID = myType.GetField("maxID", BindingFlags.NonPublic | BindingFlags.Static); FieldInfo minID = myType.GetField("minID", BindingFlags.NonPublic | BindingFlags.Static); FieldInfo idGenerator = myType.GetField("studentIDGenerator", BindingFlags.NonPublic | BindingFlags.Instance); uint minimumIDValue = 10; uint maximumIDValue = 99; minID.SetValue(myType, minimumIDValue); maxID.SetValue(myType, maximumIDValue); idGenerator.SetValue(theSchool, minimumIDValue); for (uint count = minimumIDValue; count <= maximumIDValue + 1; count++) { theSchool.AddNewStudent("Gosho"); } } [TestMethod] public void AddNewCourse_AddOneCourse() { School theSchool = new School(); theSchool.AddNewCourse("CSharp"); School myObject = theSchool; Type myType = typeof(School); FieldInfo setOfCourses = myType.GetField("courses", BindingFlags.NonPublic | BindingFlags.Instance); IList<Course> courses = setOfCourses.GetValue(myObject) as IList<Course>; Assert.IsTrue(courses.Count == 1); } [TestMethod] public void AddNewCourse_AddFewCoursesWithDifferantNames() { School theSchool = new School(); int few = 5; for (int i = 0; i < few; i++) { theSchool.AddNewCourse("CSharp" + i); } School myObject = theSchool; Type myType = typeof(School); FieldInfo setOfCourses = myType.GetField("courses", BindingFlags.NonPublic | BindingFlags.Instance); IList<Course> courses = setOfCourses.GetValue(myObject) as IList<Course>; Assert.IsTrue(courses.Count == few); } [TestMethod] [ExpectedExceptionAttribute(typeof(InvalidOperationException))] public void AddNewCourse_AddCoursesWithEqualNames() { School theSchool = new School(); theSchool.AddNewCourse("CSharp"); theSchool.AddNewCourse("CSharp"); } [TestMethod] public void SignStudentForCourse_SighOneStudentForOneCourse() { School theSchool = new School(); Student newStudent = theSchool.AddNewStudent("Pesho"); Course newCourse = theSchool.AddNewCourse("CSharp"); theSchool.SignUpStudentForCourse(newStudent.Id, newCourse.Name); School myObject = theSchool; Type myType = typeof(School); FieldInfo setOfCourses = myType.GetField("courses", BindingFlags.NonPublic | BindingFlags.Instance); IList<Course> courses = setOfCourses.GetValue(myObject) as IList<Course>; Assert.IsTrue(courses[courses.IndexOf(newCourse)].IsAttendingTheCourse(newStudent)); } [TestMethod] [ExpectedExceptionAttribute(typeof(InvalidOperationException))] public void SignStudentForCourse_SighUnexistingStudentForCourse() { School theSchool = new School(); Course newCourse = theSchool.AddNewCourse("CSharp"); theSchool.SignUpStudentForCourse(10000, newCourse.Name); } [TestMethod] [ExpectedExceptionAttribute(typeof(InvalidOperationException))] public void SignStudentForCourse_SighStudentForUnexistingCourse() { School theSchool = new School(); Student newStudent = theSchool.AddNewStudent("Pesho"); theSchool.SignUpStudentForCourse(newStudent.Id, "CSharp"); } [TestMethod] public void SignOutStudentOfCourse_SighOutOneStudentOfOneCourse() { School theSchool = new School(); Student newStudent = theSchool.AddNewStudent("Pesho"); Course newCourse = theSchool.AddNewCourse("CSharp"); theSchool.SignUpStudentForCourse(newStudent.Id, newCourse.Name); School myObject = theSchool; Type myType = typeof(School); FieldInfo setOfCourses = myType.GetField("courses", BindingFlags.NonPublic | BindingFlags.Instance); IList<Course> courses = setOfCourses.GetValue(myObject) as IList<Course>; Assert.IsTrue(courses[courses.IndexOf(newCourse)].IsAttendingTheCourse(newStudent)); theSchool.SignOutStudentOfCourse(newStudent.Id, newCourse.Name); Assert.IsFalse(courses[courses.IndexOf(newCourse)].IsAttendingTheCourse(newStudent)); } [TestMethod] [ExpectedExceptionAttribute(typeof(InvalidOperationException))] public void SignOutStudentOfCourse_SighOutUnexistingStudentOfCourse() { School theSchool = new School(); Course newCourse = theSchool.AddNewCourse("CSharp"); theSchool.SignOutStudentOfCourse(10000, newCourse.Name); } [TestMethod] [ExpectedExceptionAttribute(typeof(InvalidOperationException))] public void SignOutStudentOfCourse_SighStudentOfUnexistingCourse() { School theSchool = new School(); Student newStudent = theSchool.AddNewStudent("Pesho"); theSchool.SignOutStudentOfCourse(newStudent.Id, "CSharp"); } } }
c04f91f1700761164f122d09682e52e2a3e78660
C#
DippingBird/MultilayerPerceptron
/MultilayerPerceptron/RememberingMultilayerPerceptron.cs
2.859375
3
using System.Collections.Generic; using System; namespace MultilayerPerceptron { /// <summary> /// Additionally saves the previous gradient /// </summary> internal abstract class RememberingMultilayerPerceptron : GeneralMultilayerPerceptron { protected Matrix[] previousWeightGradients; protected Matrix[] weightStepRange; protected Vector[] previousBiasGradients; protected Vector[] biasStepRange; public RememberingMultilayerPerceptron(int inputNeuronLayerDimension, ICollection<int> hiddenNeuronLayerDimensions, int outputNeuronLayerDimension, double lowerBound, double higherBound, double weightPunishmentFactor, double startingStepRange) : base(inputNeuronLayerDimension, hiddenNeuronLayerDimensions, outputNeuronLayerDimension, lowerBound, higherBound, weightPunishmentFactor) { Initialize(startingStepRange); } public RememberingMultilayerPerceptron(Vector[] startingBiases, Matrix[] startingWeights, double weightPunishmentFactor, double startingStepRange) : base(startingBiases, startingWeights, weightPunishmentFactor) { Initialize(startingStepRange); } /// <param name="startingStepRange">The starting value for all weight and bias step-ranges</param> private void Initialize(double startingStepRange) { // Check wether starting step range is positive if (startingStepRange <= 0) { throw new ArgumentException("Starting step range must be positive"); } Function setStartingStepRange = Input => startingStepRange; previousWeightGradients = new Matrix[weights.Length]; weightStepRange = new Matrix[weights.Length]; previousBiasGradients = new Vector[biases.Length]; biasStepRange = new Vector[biases.Length]; for (int i = 0; i < NeuronLayerCount - 1; i++) { // Initialize previous weight gradients and delta weights previousWeightGradients[i] = new Matrix(weights[i].Height, weights[i].Width); weightStepRange[i] = new Matrix(weights[i].Height, weights[i].Width); weightStepRange[i] = weightStepRange[i].ApplyFunctionOnAllComponents(setStartingStepRange); // Initialize previous bias gradients and delta biases previousBiasGradients[i] = new Vector(biases[i].Dimension); biasStepRange[i] = new Vector(biases[i].Dimension); biasStepRange[i] = biasStepRange[i].ApplyFunctionOnAllComponents(setStartingStepRange); } } protected override void AdaptWeightsAndBiases() { CalculateWeightAndBiasStepRanges(); ChangeWeightsAndBiases(); } protected abstract void CalculateWeightAndBiasStepRanges(); private void ChangeWeightsAndBiases() { for (int i = 0; i < NeuronLayerCount - 1; i++) { weights[i] += weightStepRange[i]; biases[i] += biasStepRange[i]; } } protected override void ResetWeightAndBiasGradients() { for (int i = 0; i < NeuronLayerCount - 1; i++) { previousWeightGradients[i] = currentWeightGradients[i]; previousBiasGradients[i] = currentBiasGradients[i]; // Set current gradients to zero currentWeightGradients[i] = new Matrix(currentWeightGradients[i].Height, currentWeightGradients[i].Width); currentBiasGradients[i] = new Vector(currentBiasGradients[i].Dimension); } } /// <summary> /// Changes the sign of the given bias or weight step-range to the gradient sign /// </summary> /// <param name="currentStepRange">The current step range</param> /// <param name="currentGradient">The current gradient</param> /// <returns>The signed step range</returns> protected double SetStepRangeSign(double currentStepRange, double currentGradient) { return -Math.Sign(currentGradient) * Math.Abs(currentStepRange); } } }
d0204327c453117c135ec53767fc2042b994d598
C#
MallikarjunaPavuluri/C-Events-DelegatesAndLambdas
/Delegates.cs
3.3125
3
using System; namespace Hotel { public delegate void MyAction<T>(T a,T b); public delegate int Price(int t); public class Room { public static int Cost(int days) { return days * 50; } public static int Discount(int days) { return days * 10; } public static void CheckIn(String s1,String s2) { Console.WriteLine($"Check in Name of Two Persons-{s1} And {s2}"); } public static void CheckOut(String s1,String s2) { Console.WriteLine($"Check Out Name of Two Persons-{s1} And {s2}"); } public static void Welcome(String s1, String s2) { Console.WriteLine($"Welcome {s1} And {s2} To AIR Hotels"); } public static void Great(String s1, String s2) { Console.WriteLine($"Great to have {s1} And {s2} In AIR Hotels"); } } public class Program { public static void Main(String []args) { Room r = new Room(); MyAction<String> A1 = Room.CheckIn; A1("Malli", "Ravi"); MyAction<String> A2 = Room.CheckOut; A2("Kiran", "RamNagesh"); MyAction<String> A3 = Room.Welcome; A3("Kumar", "Vamshi"); MyAction<String> A4 = Room.Great; A4("Manish", "Rizvi"); Console.WriteLine("-----------------------"); Console.WriteLine("A4 += A1 + A2 + A3\n"); A4 += A1 + A2 + A3; A4("Manish", "Rizvi"); Console.WriteLine("----"); A1 += A1;//don't get repeated print only four A4("Manish", "Rizvi"); Console.WriteLine("-----------------------"); Console.WriteLine("A4 -=A1\n"); A4 -= A1; A4("Manish", "Rizvi"); Console.WriteLine("-----------------------"); Price cost = Room.Cost; Price dis = Room.Discount; cost += dis; int originalprice = cost(20); Console.WriteLine($"Discount-{originalprice}"); cost -= dis; originalprice = cost(20); Console.WriteLine($"Original Cost-{originalprice}"); } } }
314769ce2ec63f82091354344cd95c3d20f2858c
C#
Vinicius-Brito-Costa/ShootaGun
/UI - Scene/UIBar.cs
2.59375
3
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [AddComponentMenu("UIEssentials/Bar")] public class UIBar : MonoBehaviour { public string name; Image bar; float originalValue, currentValue; void Awake() { bar = GetComponent<Image>(); } public float Get() { return currentValue; } public void Set(float value) { originalValue = value; currentValue = originalValue; bar.fillAmount = porcentageCount(value, 0); } public void Add(float addedValue) { if(bar == null) return; var hp = bar.fillAmount; currentValue += addedValue; if(currentValue > originalValue) bar.fillAmount = hp; else bar.fillAmount = porcentageCount(currentValue, originalValue); } public void Subtract(float subtractedValue) { if(bar == null) return; var hp = bar.fillAmount; currentValue -= subtractedValue; if(currentValue < 0) bar.fillAmount -= hp; else bar.fillAmount = porcentageCount(currentValue, originalValue); } float porcentageCount(float value, float value2) { return value * (100 / 100) / 100; } }
bb8afe7ce61b680e862ad715eac00fcf01367d7f
C#
salutdev/ProblemSolving
/ConsoleApplication/NumberTheory/SieveOfEratosthenes.cs
3.703125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1.NumberTheory { public class SieveOfEratosthenes { public void Find() { int n = 10000; bool[] nums = new bool[n + 1]; for (int i = 2; i <= n; i++) { nums[i] = true; } for (int i = 2; i*i <= n; i++) { if (nums[i]) { for (int j = 2 * i; j <= n; j += i) { nums[j] = false; } } } for (int i = 2; i <= n; i++) { if (nums[i]) { Console.Write($"{i} "); } } } } }
eef3347e0444edde17c2e97498d0d2aa11d82bd0
C#
alexandre1000a/HackaCity
/Cejen/Cejen.Client/ClientBase.cs
2.59375
3
using System.Net; using Newtonsoft.Json; namespace Cejen.Client { public class ClientBase { private readonly WebClient _client; private readonly string _value; public ClientBase() { const string url = "http://www.precodoscombustiveis.com.br/mapa/atualiza?swlat=-20.509836929816302&swlng=-54.67620849609375&nelat=-20.42942579865923&nelng=54.56411361694336&zoom=13"; _client = new WebClient(); _value = _client.DownloadString(url); } public dynamic GetAllPostos() { var res = _value; dynamic dyn = JsonConvert.DeserializeObject(res); return dyn; } } }
e2fc6bc75c603fa1e22674f28fc01e3f1882b643
C#
emiliobs/AppDivisasMVVM2
/AppDivisasMVVMApi/AppDivisasMVVMApi/ViewModels/MainViewModel.cs
2.625
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Dynamic; using System.Linq; using System.Net.Http; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using AppDivisasMVVMApi.Classes; using GalaSoft.MvvmLight.Command; using Newtonsoft.Json; namespace AppDivisasMVVMApi.ViewModels { public class MainViewModel : INotifyPropertyChanged { #region Attributes private ExchangeRates exchangeRates; private decimal amount; private double sourceRate; private double targetRate; private bool isEnable; private bool isRunning; private string message; #endregion #region Properties public ObservableCollection<Rate> Rates { get; set; } public decimal Amount { set { if (amount != value); { amount = value; PropertyChanged?.Invoke(this,new PropertyChangedEventArgs("Amount")); } } get { return amount; } } public double SourceRate { set { if (sourceRate != value); { sourceRate = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SourceRate")); } } get { return sourceRate; } } public double TargetRate { set { if (targetRate != value) ; { targetRate = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TargetRate")); } } get { return targetRate; } } public bool IsEnable { set { if (isEnable != value) ; { isEnable = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsEnable")); } } get { return isEnable; } } public bool IsRunning { set { if (isRunning != value) ; { isRunning= value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsRunning")); } } get { return isRunning; } } public string Message { set { if (message != value) ; { message = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Message")); } } get { return message; } } #endregion #region Commands public ICommand ConvertMoneyCommand { get { return new RelayCommand(ConvertMoney);} } private async void ConvertMoney() { //valido campos(propiedades) if (Amount <= 0) { await App.Current.MainPage.DisplayAlert("Error", "You must enter a`positive value in amount","Acept"); return; } if (sourceRate == 0) { await App.Current.MainPage.DisplayAlert("Error", "You must select a source rate", "Acept"); return; } if (TargetRate == 0) { await App.Current.MainPage.DisplayAlert("Error", "You must select a source target", "Acept"); return; } var converted = (Amount / (decimal)SourceRate) * (decimal)TargetRate; Message = $"{Amount:C2} {converted:C2}"; } #endregion #region Constructor public MainViewModel() { Rates = new ObservableCollection<Rate>(); Message = "Enter an amount, select a source currency, select a target and press Convert button."; LoadRates(); } #endregion #region Methods private async void LoadRates() { IsRunning = true; try { var client = new HttpClient(); client.BaseAddress = new Uri("https://openexchangerates.org"); var url = "/api/latest.json?app_id=7ce0119051774ef5a478eefc8f8070d1"; var response = await client.GetAsync(url); if (!response.IsSuccessStatusCode) { Message = response.StatusCode.ToString(); IsRunning = false; return; } var result = await response.Content.ReadAsStringAsync(); exchangeRates = JsonConvert.DeserializeObject<ExchangeRates>(result); } catch (Exception e) { Message = e.Message; IsRunning = false; return; } ConvertRates(); IsRunning = false; IsEnable = true; } private void ConvertRates() { Rates.Clear(); var type = typeof(Rates); var properties = type.GetRuntimeFields(); foreach (var property in properties) { var code = property.Name.Substring(1, 3); Rates.Add(new Rate() { Code = code, TaxRate = (double)property.GetValue(exchangeRates.Rates) }); } } #endregion #region Event public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
86e217dcee776d34c3937e76a8c5347811a0c1ab
C#
DarkDestry/Cauldron
/Cauldron/IPC/Command.cs
2.734375
3
using System; using System.Diagnostics.SymbolStore; using System.Security.Cryptography; using System.Text.Json; using System.Text.Json.Serialization; namespace Cauldron.IPC { public abstract class Command { [JsonPropertyName("command")] public CommandType IpcCommand { get; } [JsonConstructor] public Command(CommandType command) { IpcCommand = command; } public virtual byte[] toBytes() { return System.Text.Encoding.ASCII.GetBytes(toJsonString()); } public virtual string toJsonString() { return JsonSerializer.Serialize<object>(this); } } [JsonConverter(typeof(IncomingCommandJsonConverter))] public abstract class IncomingCommand { [JsonPropertyName("command")] public CommandType IpcCommand { get; } public abstract void ExecuteCommand(); } [JsonConverter(typeof(CommandTypeJsonConverter))] public enum CommandType { Initialize, Shutdown, Resize, LoadWorld, SaveWorld, Unknown } public class CommandTypeJsonConverter : JsonConverter<CommandType> { public override CommandType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { string command = reader.GetString(); switch(command) { case "initialize" : return CommandType.Initialize; case "shutdown" : return CommandType.Shutdown; case "resize" : return CommandType.Resize; case "loadworld" : return CommandType.LoadWorld; case "saveworld" : return CommandType.SaveWorld; default: return CommandType.Unknown; } } public override void Write(Utf8JsonWriter writer, CommandType value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString().ToLower()); } } public class IncomingCommandJsonConverter : JsonConverter<IncomingCommand> { public override bool CanConvert(Type type) { return typeof(IncomingCommand).IsAssignableFrom(type); } public override IncomingCommand Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (JsonDocument.TryParseValue(ref reader, out JsonDocument document)) { if (document.RootElement.TryGetProperty("command", out JsonElement commandType)) { CommandType incomingCommandType = JsonSerializer.Deserialize<CommandType>(commandType.GetRawText()); string rootElement = document.RootElement.GetRawText(); //TODO: Potentially change this to use reflection instead switch (incomingCommandType) { case CommandType.Initialize: return JsonSerializer.Deserialize<IncomingInitializeCommand>(rootElement); case CommandType.Shutdown: break; case CommandType.Resize: break; case CommandType.LoadWorld: break; case CommandType.SaveWorld: break; default: throw new JsonException("Unknown Command Type found in incoming command"); } } throw new JsonException("Failed to extract command type from incoming command. Might it be missing?"); } throw new JsonException("Incoming Command failed to Parse"); } public override void Write(Utf8JsonWriter writer, IncomingCommand value, JsonSerializerOptions options) { throw new NotImplementedException(); } } }
3f29fd8bbe04cda5b67841d9863366e1380c4153
C#
byronqiji/HeartMonitor
/HeartModel/StateMachine/RunningHeart.cs
2.71875
3
using System; using System.Runtime.CompilerServices; using System.Threading; using HeartModel.StateMachine.RunningMachine; [assembly: InternalsVisibleTo("HeartMVC.Tests")] // 添加友元,用于单元测试 namespace HeartModel.StateMachine { /// <summary> /// 心跳运行状态 /// </summary> [Serializable] public class RunningHeart : HeartStateBase { internal RunBase runState; internal ReadyState readyState; internal RunningState runningState; internal PauseState pauseState; /// <summary> /// 构造方法 /// </summary> /// <param name="hsInfo">心跳信息</param> public RunningHeart(HeartServerInfo hsInfo) : base(hsInfo) { readyState = new ReadyState(this); runningState = new RunningState(this); pauseState = new PauseState(this); runState = readyState; } /// <summary> /// 运行状态 /// </summary> public override HeartServerState State { get { return HeartServerState.Running; } } /// <summary> /// 停止 /// </summary> public override void Pause() { runState.Pause(); } internal void DoAction(object state) { // 根据时间区间判断是否需要执行本次操作 if (IsDo()) { try { runState.Run(); } catch (Exception ex) { heartInfo.heartState.ReceiveException(ex); } } } /// <summary> /// 判断时间 是否需要执行 /// 开始时间和结束时间相同,说明时间间隔为24小时,始终返回true /// 若当前时间,落在开始时间和结束时间区间段内,返回true /// </summary> /// <returns></returns> internal bool IsDo() { TimeSpan nTS = DateTime.Now.TimeOfDay; return (heartInfo.SpanInfo.StartTime == heartInfo.SpanInfo.EndTime) || (nTS > heartInfo.SpanInfo.StartTime && nTS < heartInfo.SpanInfo.EndTime); } } }
e1545360ebc7e55419da7540dbcf11943ebea64a
C#
rBaun/DesignPatternsCSharp
/DesignPatterns/1. SOLID Principles/InterfaceSegregation.cs
3.578125
4
using System; using System.Collections.Generic; using System.Text; namespace DesignPatterns.SOLID_Principles { /** * The idea is to keep the interfaces segregated. * This is done by making interfaces, where there is * only the functionality needed in each interface. * * So basically, dont put too much into an interface. * Instead you should split them into seperate interfaces. */ public class Document { } /** * This interface is fine for MultiFunctionPrinter as seen below, * because a multifunctionprinter can do it all. * * But what if it is an old fashioned printer? */ public interface IMachine { void Print(Document d); void Scan(Document d); void Fax(Document d); } public class MultiFunctionPrinter : IMachine { public void Fax(Document d) { // Fax logic ... } public void Print(Document d) { // Print logic } public void Scan(Document d) { // Scan logic } } public class OldFashionedPrinter : IMachine { public void Print(Document d) { // Print logic is fine, since it is a printer } public void Fax(Document d) { // We gotta throw exception or handle fax error, since // an old fashioned printer can't handle fax throw new NotImplementedException(); } public void Scan(Document d) { // Same as Fax throw new NotImplementedException(); } } /** * To achieve interface segregation we simple need to split out big IMachine * into smaller interfaces. This could be done as seen below */ public interface IPrinter { void Print(Document d); } public interface IScanner { void Scan(Document d); } public class Photocopier : IPrinter, IScanner { public void Print(Document d) { // Print logic } public void Scan(Document d) { // Scan logic } } /** * If you then decide you want a multifunction interface, * then this could be implemented with the smaller interfaces. * * Here is an example: */ public interface IMultiFunctionDevice : IScanner, IPrinter { } public class MultiFunctionMachine : IMultiFunctionDevice { private IPrinter printer; private IScanner scanner; public MultiFunctionMachine(IPrinter printer, IScanner scanner) { this.printer = printer ?? throw new ArgumentNullException(paramName: nameof(printer)); this.scanner = scanner ?? throw new ArgumentNullException(paramName: nameof(scanner)); } public void Print(Document d) { printer.Print(d); } public void Scan(Document d) { scanner.Scan(d); } } //public class InterfaceSegregation //{ // static void Main(string[] args) // { // } //} }
60d89b2a61f32086d7bc50c0e779cabc59ad8746
C#
tsvetelina-e-y/Unwe_DotNet
/2_exercise/7_task/Program.cs
3.25
3
using System; namespace _7_task { class Program { static void Main(string[] args) { Console.WriteLine("Radius"); int radius = int.Parse(Console.ReadLine()); Console.WriteLine($"P = {Math.Round(Math.PI * radius * 2, 2)}"); Console.WriteLine($"S = {Math.PI * Math.Pow(radius, 2)}"); } } }
a7ffa6838286761f4db38b14e1e415ef50b6be48
C#
salileo/WallpaperManager
/WallpaperManager/BackgroundSetter.cs
2.609375
3
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Forms; using System.Windows.Media; using System.Windows.Media.Imaging; namespace WallpaperManager { class BackgroundSetter { [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int SystemParametersInfo(uint uiAction, uint uiParam, string pvParam, uint fWinIni); private static uint SPI_SETDESKWALLPAPER = 20; private static uint SPIF_UPDATEINIFILE = 0x1; /// <summary> /// Sets the background image /// </summary> /// <param name="filename">the file to use for setting the background image</param> /// <param name="displaymode">the display mode</param> /// <param name="backgroundcolor">the background color</param> /// <exception cref="Exception">Can throw exception</exception> public static void SetBackgroundImage(string filename, DisplayModeType displaymode, System.Windows.Media.Color backgroundcolor) { //get the screen dimensions and calculate the width of the task bar Rectangle totalScreenSize = Screen.PrimaryScreen.Bounds; Rectangle workingScreenSize = Screen.PrimaryScreen.WorkingArea; int lowerBorder = totalScreenSize.Height - workingScreenSize.Height; Int32Rect desiredImageSize = new Int32Rect(0, 0, totalScreenSize.Width, workingScreenSize.Height); Int32Rect actualImageSize = new Int32Rect(0, 0, 0, 0); Int32Rect finalImageSize = new Int32Rect(0, 0, 0, 0); PixelFormat imgFormat; BitmapPalette imgPalette; int imgScaleFactor = 4; //get the size and details of the actual image { BitmapImage tmp_img = new BitmapImage(); tmp_img.BeginInit(); tmp_img.CreateOptions = BitmapCreateOptions.None; tmp_img.CacheOption = BitmapCacheOption.OnLoad; tmp_img.UriSource = new Uri(filename); tmp_img.EndInit(); actualImageSize.Width = tmp_img.PixelWidth; actualImageSize.Height = tmp_img.PixelHeight; imgFormat = tmp_img.Format; imgPalette = tmp_img.Palette; imgScaleFactor = imgFormat.BitsPerPixel / 8; } //create the final bitmap which we will write to the file WriteableBitmap bmp = new WriteableBitmap(totalScreenSize.Width, totalScreenSize.Height, 96, 96, imgFormat, imgPalette); //set the background of the final image { List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>(); colors.Add(backgroundcolor); BitmapPalette palette = new BitmapPalette(colors); // Creates a new empty image with the pre-defined palette byte[] pixels = new byte[totalScreenSize.Width * totalScreenSize.Height * imgScaleFactor]; BitmapSource source = BitmapSource.Create(totalScreenSize.Width, totalScreenSize.Height, 96, 96, PixelFormats.Indexed1, palette, pixels, totalScreenSize.Width * imgScaleFactor); FormatConvertedBitmap converted = new FormatConvertedBitmap(source, imgFormat, imgPalette, 0); converted.CopyPixels(pixels, totalScreenSize.Width * imgScaleFactor, 0); Int32Rect background_srcRect = new Int32Rect(0, 0, totalScreenSize.Width, totalScreenSize.Height); bmp.WritePixels(background_srcRect, pixels, totalScreenSize.Width * imgScaleFactor, 0); } //get the image in the corrected dimension space BitmapImage img = new BitmapImage(); img.BeginInit(); img.CreateOptions = BitmapCreateOptions.None; img.CacheOption = BitmapCacheOption.OnLoad; switch (displaymode) { case DisplayModeType.Stretch: if (desiredImageSize.Width > actualImageSize.Width) { if (desiredImageSize.Height >= actualImageSize.Height) { //image is smaller than the screen size if (((double)desiredImageSize.Height / (double)actualImageSize.Height) < ((double)desiredImageSize.Width / (double)actualImageSize.Width)) img.DecodePixelHeight = desiredImageSize.Height; else img.DecodePixelWidth = desiredImageSize.Width; } else { //need to shrink the height of the image img.DecodePixelHeight = desiredImageSize.Height; } } else { if (desiredImageSize.Height >= actualImageSize.Height) { //need to shrink the width of the image img.DecodePixelWidth = desiredImageSize.Width; } else { //image is totally larger than the screen size if (((double)actualImageSize.Height / (double)desiredImageSize.Height) > ((double)actualImageSize.Width / (double)desiredImageSize.Width)) img.DecodePixelHeight = desiredImageSize.Height; else img.DecodePixelWidth = desiredImageSize.Width; } } break; case DisplayModeType.Fill: img.DecodePixelWidth = desiredImageSize.Width; img.DecodePixelHeight = desiredImageSize.Height; break; case DisplayModeType.Tile: //tile would be the same as center as we just want the image to fit on the screen //rest of the calculations would be done later default: //center if (desiredImageSize.Width > actualImageSize.Width) { if (desiredImageSize.Height >= actualImageSize.Height) { //image is smaller than the screen size //we don't need to do anything here } else { //need to shrink the height of the image img.DecodePixelHeight = desiredImageSize.Height; } } else { if (desiredImageSize.Height >= actualImageSize.Height) { //need to shrink the width of the image img.DecodePixelWidth = desiredImageSize.Width; } else { //image is totally larger than the screen size if (((double)actualImageSize.Height / (double)desiredImageSize.Height) > ((double)actualImageSize.Width / (double)desiredImageSize.Width)) img.DecodePixelHeight = desiredImageSize.Height; else img.DecodePixelWidth = desiredImageSize.Width; } } break; } img.UriSource = new Uri(filename); img.EndInit(); //recalculate the image offsets on the final bitmap finalImageSize.Width = img.PixelWidth; finalImageSize.Height = img.PixelHeight; finalImageSize.X = (desiredImageSize.Width - finalImageSize.Width) / 2; finalImageSize.Y = (desiredImageSize.Height - finalImageSize.Height) / 2; //copy the image to the final output byte[] img_bytes = new byte[finalImageSize.Width * finalImageSize.Height * imgScaleFactor]; img.CopyPixels(img_bytes, finalImageSize.Width * imgScaleFactor, 0); if (displaymode == DisplayModeType.Tile) { int xoffset = 0; int yoffset = 0; Int32Rect srcRect = new Int32Rect(); while (yoffset < desiredImageSize.Height) { srcRect.Y = 0; srcRect.Height = Math.Min((desiredImageSize.Height - yoffset), finalImageSize.Height); while (xoffset < desiredImageSize.Width) { srcRect.X = 0; srcRect.Width = Math.Min((desiredImageSize.Width - xoffset), finalImageSize.Width); bmp.WritePixels(srcRect, img_bytes, finalImageSize.Width * imgScaleFactor, xoffset, yoffset); xoffset += srcRect.Width; } yoffset += srcRect.Height; xoffset = 0; } } else { Int32Rect srcRect = new Int32Rect(0, 0, finalImageSize.Width, finalImageSize.Height); bmp.WritePixels(srcRect, img_bytes, finalImageSize.Width * imgScaleFactor, finalImageSize.X, finalImageSize.Y); } //store the bitmap to a file string tempfilename = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\WallpaperManager\\wallpapermanager.bmp"; FileStream stream = new FileStream(tempfilename, FileMode.Create); BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); encoder.Save(stream); stream.Close(); SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, tempfilename, SPIF_UPDATEINIFILE); } } }
60a1aa1f0668f08849cf72baca2c3987ba991188
C#
monpl/com.monpl.ui
/Runtime/UIManager.cs
2.53125
3
using Cysharp.Threading.Tasks; using UnityEngine; namespace Monpl.UI { public class UIManager : MonoBehaviour { private static UIManager _instance; public static UIManager Instance { get { if (_instance != null) return _instance; _instance = CreateManager(); return _instance; } } public static ScreenContainer ScreenContainer { get; private set; } public static PopupContainer PopupContainer { get; private set; } /// <summary> /// Scene에서 UIManager를 초기화 해준다. /// </summary> public async UniTask InitOnScene(string initScreenName) { if (!FindContainers()) return; // ScreenSize를 정확히 찾기 위해선 한 프레임 쉬어야한다. await UniTask.Yield(); ScreenContainer.PreInit(); await PopupContainer.PreInit(); ScreenContainer.ChangeScreen(initScreenName); } private static UIManager CreateManager() { var newManager = new GameObject("UIManager").AddComponent<UIManager>(); DontDestroyOnLoad(newManager); return newManager; } private bool FindContainers() { ScreenContainer = FindObjectOfType<ScreenContainer>(); PopupContainer = FindObjectOfType<PopupContainer>(); if (ScreenContainer != null && PopupContainer != null) return true; Debug.LogError("UImanager Init fail.."); return false; } } }
a24e770c11a32aa4233732cd7e6491f4be96b661
C#
romanrakus/SLMM
/SLMM/Common/Logging/LazyLogger.cs
2.859375
3
using System; using SLMM.Common.Extensions; namespace SLMM.Common.Logging { internal class LazyLogger : ILogger { private readonly Lazy<ILogger> _logger; public LazyLogger(Func<ILogger> factory) { Ensure.NotNull(factory, nameof(factory)); _logger = new Lazy<ILogger>(factory); } public void Trace(string message, params object[] args) { _logger.Value.Trace(message, args); } public void Debug(string message, params object[] args) { _logger.Value.Debug(message, args); } public void Info(string message, params object[] args) { _logger.Value.Info(message, args); } public void Error(string message, params object[] args) { _logger.Value.Error(message, args); } public void Error(Exception ex, string message, params object[] args) { _logger.Value.Error(ex, message, args); } public void Fatal(string message, params object[] args) { _logger.Value.Fatal(message, args); } public void Flush(TimeSpan? maxTimeToWait = null) { _logger.Value.Flush(maxTimeToWait); } } }
306ebdfc3843f43ebbf55c39a8c87a4f8674e799
C#
YR1044/SyncTrayzor
/src/SyncTrayzor/Services/Ipc/IpcCommsClient.cs
2.875
3
using System; using System.IO.Pipes; using System.Text; namespace SyncTrayzor.Services.Ipc { public class UnknownIpcCommandException : Exception { public UnknownIpcCommandException(string message) : base(message) { } } public interface IIpcCommsClient { void Shutdown(); void ShowMainWindow(); void StartSyncthing(); void StopSyncthing(); } public class IpcCommsClient : IIpcCommsClient { private readonly int pid; private string PipeName => $"SyncTrayzor-{this.pid}"; public IpcCommsClient(int pid) { this.pid = pid; } public void Shutdown() { this.SendCommand("Shutdown"); } public void ShowMainWindow() { this.SendCommand("ShowMainWindow"); } public void StartSyncthing() { this.SendCommand("StartSyncthing"); } public void StopSyncthing() { this.SendCommand("StopSyncthing"); } private void SendCommand(string command) { var clientStream = new NamedPipeClientStream(".", this.PipeName, PipeDirection.InOut, PipeOptions.Asynchronous); clientStream.Connect(500); clientStream.ReadMode = PipeTransmissionMode.Message; var commandBytes = Encoding.ASCII.GetBytes(command); byte[] buffer = new byte[256]; var responseBuilder = new StringBuilder(); clientStream.Write(commandBytes, 0, commandBytes.Length); int read = clientStream.Read(buffer, 0, buffer.Length); responseBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read)); while (!clientStream.IsMessageComplete) { read = clientStream.Read(buffer, 0, buffer.Length); responseBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read)); } this.ProcessResponse(responseBuilder.ToString()); } private void ProcessResponse(string response) { if (response == "OK") return; throw new UnknownIpcCommandException($"Remote side replied with {response}"); } public override string ToString() { return $"<IpcCommsClient PID={this.pid}>"; } } }
fbd6e9120dd2bd18ef81e8c9aa3ba2f20481a76a
C#
am11/pcre-net
/src/PCRE.NET.Tests/PcreNet/ReplaceTests.cs
2.65625
3
using System.Globalization; using NUnit.Framework; namespace PCRE.Tests.PcreNet { [TestFixture] public class ReplaceTests { [Test] public void should_replace_matches_with_callback() { var re = new PcreRegex(@"a+", PcreOptions.IgnoreCase); var result = re.Replace("foo aaa bar aAAa baz", match => match.Length.ToString(CultureInfo.InvariantCulture)); Assert.That(result, Is.EqualTo("foo 3 b1r 4 b1z")); } [Test] public void should_replace_matches_with_pattern() { var re = new PcreRegex(@"a+(b+)", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "<$0><$1><$&>"); Assert.That(result, Is.EqualTo("foo <aabb><bb><aabb> bar <aaabb><bb><aaabb><ab><b><ab> baz")); } [Test] public void should_replace_indexed_groups_with_braces() { var re = new PcreRegex(@"a+(?<grp>b+)", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "<${1}>"); Assert.That(result, Is.EqualTo("foo <bb> bar <bb><b> baz")); } [Test] public void should_replace_indexed_groups_without_braces() { var re = new PcreRegex(@"a+(?<grp>b+)", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "<$1>"); Assert.That(result, Is.EqualTo("foo <bb> bar <bb><b> baz")); } [Test] public void should_replace_indexed_groups_with_braces_at_end_of_pattern() { var re = new PcreRegex(@"a+(?<grp>b+)", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "#${1}"); Assert.That(result, Is.EqualTo("foo #bb bar #bb#b baz")); } [Test] public void should_replace_indexed_groups_without_braces_at_end_of_pattern() { var re = new PcreRegex(@"a+(?<grp>b+)", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "#$1"); Assert.That(result, Is.EqualTo("foo #bb bar #bb#b baz")); } [Test] public void should_replace_named_groups() { var re = new PcreRegex(@"a+(?<grp>b+)", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "<${grp}>"); Assert.That(result, Is.EqualTo("foo <bb> bar <bb><b> baz")); } [Test] public void should_insert_dollar() { var re = new PcreRegex(@"a+(b+)", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "$$-$"); Assert.That(result, Is.EqualTo("foo $-$ bar $-$$-$ baz")); } [Test] public void should_insert_pre_match() { var re = new PcreRegex(@"a+(b+)", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "<$`>"); Assert.That(result, Is.EqualTo("foo <foo > bar <foo aabb bar ><foo aabb bar aaabb> baz")); } [Test] public void should_insert_post_match() { var re = new PcreRegex(@"a+(b+)", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "<$'>"); Assert.That(result, Is.EqualTo("foo < bar aaabbab baz> bar <ab baz>< baz> baz")); } [Test] public void should_insert_subject() { var re = new PcreRegex(@"a+(b+)", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "<$_>"); Assert.That(result, Is.EqualTo("foo <foo aabb bar aaabbab baz> bar <foo aabb bar aaabbab baz><foo aabb bar aaabbab baz> baz")); } [Test] public void should_insert_last_matched_group() { var re = new PcreRegex(@"a+(b+)(c+)?", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbabcc baz", "<$+>"); Assert.That(result, Is.EqualTo("foo <bb> bar <bb><cc> baz")); } [Test] public void should_insert_nothing_if_no_group_matched() { var re = new PcreRegex(@"a+(b+)?"); var result = re.Replace("foo aabb bar baz", "<$+>"); Assert.That(result, Is.EqualTo("foo <bb> b<>r b<>z")); } [Test] public void should_insert_nothing_if_there_are_no_groups() { var re = new PcreRegex(@"a+"); var result = re.Replace("foo bar", "<$+>"); Assert.That(result, Is.EqualTo("foo b<>r")); } [Test] [TestCase("<$2$$$1$>", ExpectedResult = "foo <$2$bb$> bar <$2$bb$><$2$b$> baz")] [TestCase("<>${2", ExpectedResult = "foo <>${2 bar <>${2<>${2 baz")] [TestCase("<$42>", ExpectedResult = "foo <$42> bar <$42><$42> baz")] [TestCase("<$99999999999999999999>", ExpectedResult = "foo <$99999999999999999999> bar <$99999999999999999999><$99999999999999999999> baz")] [TestCase("<${x}>", ExpectedResult = "foo <${x}> bar <${x}><${x}> baz")] [TestCase("$42", ExpectedResult = "foo $42 bar $42$42 baz")] [TestCase("${x}", ExpectedResult = "foo ${x} bar ${x}${x} baz")] [TestCase("${x", ExpectedResult = "foo ${x bar ${x${x baz")] [TestCase("$", ExpectedResult = "foo $ bar $$ baz")] public string should_not_throw_on_invalid_replacement_patterns(string replacement) { var re = new PcreRegex(@"a+(?<n>b+)", PcreOptions.IgnoreCase); return re.Replace("foo aabb bar aaabbab baz", replacement); } [Test] public void should_only_replace_given_count() { var re = new PcreRegex(@"a+", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "X", 2); Assert.That(result, Is.EqualTo("foo Xbb bXr aaabbab baz")); } [Test] public void should_not_replace_when_count_is_zero() { var re = new PcreRegex(@"a+", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "X", 0); Assert.That(result, Is.EqualTo("foo aabb bar aaabbab baz")); } [Test] public void should_start_at_given_index() { var re = new PcreRegex(@"a+", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "X", -1, 12); Assert.That(result, Is.EqualTo("foo aabb bar XbbXb bXz")); } [Test] public void should_start_at_given_index_and_replace_count() { var re = new PcreRegex(@"a+", PcreOptions.IgnoreCase); var result = re.Replace("foo aabb bar aaabbab baz", "X", 2, 8); Assert.That(result, Is.EqualTo("foo aabb bXr Xbbab baz")); } [Test] [TestCase("#", ExpectedResult = "aab#ab#")] [TestCase("$_", ExpectedResult = "aabaabababaabab")] [TestCase("$`", ExpectedResult = "aabaababaabab")] [TestCase("$'", ExpectedResult = "aabaabababab")] [TestCase("$+", ExpectedResult = "aabab")] [TestCase("$&", ExpectedResult = "aabab")] public string should_handle_backslash_k_in_lookahead(string replacement) { var re = new PcreRegex(@"(?=a+b\K)"); return re.Replace("aabab", replacement); } [Test] public void readme_replace_example() { var result = PcreRegex.Replace("hello, world!!!", @"\p{P}+", "<$&>"); Assert.That(result, Is.EqualTo("hello<,> world<!!!>")); } } }
5f8aef1771c7b571d33616f9ec0e3b7d583668ff
C#
Sakthipriya123/NewsTracker
/Auction Project/Auction Project/API/AuctionController.cs
2.640625
3
using Auction_Project.Models; using Auction_Project.Services; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace Auction_Project.API { public class AuctionController : ApiController { private IAuctionService _auctionService; public AuctionController(IAuctionService auctionService) { this._auctionService = auctionService; } // GET: api/Auction public IEnumerable<Auction> Get() { return _auctionService.ListAuction(); } // GET: api/Auction/5 public IHttpActionResult Get(int id) { var bid = _auctionService.GetItem(id); if(bid == null) { return NotFound(); } return Ok(bid); } // POST: api/Auction public IHttpActionResult Post(Auction item) { if(item == null) { return BadRequest("Missing BidAuction"); } if (item.Id == 0) { _auctionService.AddItem(item); return Created("/auction/" + item.Id, item); } else { _auctionService.EditItem(item); return Ok(item); } } // PUT: api/Auction/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/Auction/5 public void Delete(int id) { } } }
a46fb136c287c2d594aeebc4b2d793e351b527b5
C#
kibedy/CharGenWpf
/CharGenWpf/MyConverter.cs
2.6875
3
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace CharGenWpf { public class MyConverter:IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var rr = value.ToString(); return rr; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var rr = int.Parse(value.ToString()); return rr; } } }
c3470330ab71bbbb8c825da6b6418f4be6f648a0
C#
CesarHLR/POO
/Parametros/Program.cs
3.609375
4
using System; namespace Parametros { class Equipo { public string nombre; public Equipo() { nombre="Real Madrid"; } //Año de fundacion del equipo con parametrio in //Esta vacio porque el año de fundacion no cambia public void Año(in Int16 año) { } } class Abreviatura { //Abreviar nombre del equipo mediante pase de parametros Ref public static void CambiaSiglas(ref Equipo e) { e=new Equipo(); e.nombre="MAD"; } } class Titulos { //Calcular titulos totales del equipo mediante parametro Out //Titulos de liga y titulos de champions public static void suma(int TL, int TCh, out int T) { T=TL+TCh; } public static int suma(int TL,int TCh) { return TL+TCh; } } class program { static void Main(string[] args) { int TitulosL=33; int TitulosC=13; int TotalT; Int16 A=1902; Titulos.suma(TitulosL,TitulosC,out TotalT); Console.WriteLine("Titulos totales del club entre Liga y Champions: "+TotalT); Equipo Eq=new Equipo(); Console.WriteLine("Equipo: "+ Eq.nombre); Abreviatura.CambiaSiglas(ref Eq); Console.WriteLine("Abreviacion: "+ Eq.nombre); Eq.Año(in A); Console.WriteLine("Año de fundacion: "+ A); } } }
c03c35b53958472345f8a5b2e14e88832e659d62
C#
ProteoWizard/pwiz
/pwiz_tools/Bumbershoot/idpicker/Util/STL_Containers/RBTree.cs
2.765625
3
/*===================================================================== File: RBTree.cs Summary: Implementation of the RBTree class. Author: Joannes Vermorel (joannes@vermorel.com) Last Modified: 2002-07-13 Acknowledgement: Brian Berns (code improvements) Copyright 2003 Joannes Vermorel This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment (see the following) in the product documentation is required. Portions Copyright 2003 Joannes Vermorel 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. =====================================================================*/ // // $Id$ // namespace System.Collections.Generic { internal delegate void RBTreeModifiedHandler(); /// <summary> /// Allows using a Comparison&lt;T&gt; object as an object that implemented IComparer&lt;T&gt; /// </summary> public class ComparisonForwarder<T> : IComparer<T> { /// <summary> /// Constructs a ComparisonForwarder that forwards calls to Compare() to the given comparison predicate. /// </summary> public ComparisonForwarder (Comparison<T> comparison) { Comparison = comparison; } /// <summary> /// The comparison predicate used by this instance. /// </summary> public Comparison<T> Comparison { get; private set; } /// <summary> /// Compares two T values using the comparison predicate. /// </summary> public int Compare (T x, T y) { return Comparison(x, y); } } /// <summary> /// RBTree is implemented using black-red binary trees. The algorithms follows the indications given in the textbook /// "Introduction to Algorithms" Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest /// </summary> public class RBTree<T> : ICollection<T>, IEnumerable<T> { /// <summary> /// Store the number of elements in the RBTree. /// </summary> private int count; /// <summary> /// Store the root node of the RBTree. /// </summary> internal RBTreeNode<T> root; /// <summary> /// Store the IComparer that allows to compare the node keys. /// </summary> public IComparer<T> Comparer { get; protected set; } // <summary> // Store the lock for multiple-reader access and single-writer access. // </summary> //private ReaderWriterLock rwLock; /// <summary> /// Initializes a new instance of Collections.System.RBTree /// class that is empty. A default comparer will be used to /// compare the elements added to the RBTree. /// </summary> public RBTree() { Comparer = Comparer<T>.Default; Initialize(); } /// <summary> /// Initializes an empty RBTree instance. /// </summary> /// <param name="comp"> /// comp represents the IComparer elements which will be used to sort the elements in RBTree. /// </param> public RBTree(IComparer<T> comp) { Comparer = comp; Initialize(); } /// <summary> /// Initializes a RBTree by copying elements from another RBTree, using the given comparer. /// </summary> public RBTree (RBTree<T> otherTree, IComparer<T> comp) { Comparer = comp; Initialize(); Copy(otherTree); } /// <summary> /// Initializes an empty RBTree instance using the given comparison predicate. /// </summary> /// <param name="comp"></param> public RBTree (Comparison<T> comp) { Comparer = new ComparisonForwarder<T>(comp); Initialize(); } /// <summary> /// Initializes a RBTree by copying elements from another RBTree, using the given comparison predicate. /// </summary> public RBTree (RBTree<T> otherTree, Comparison<T> comp) : this(comp) { Copy(otherTree); } /// <summary> /// Initializes a RBTree by copying elements from another RBTree, using the same comparer. /// </summary> public RBTree( RBTree<T> otherTree ) : this() { Copy( otherTree ); } /// <summary> /// Perform the common initialization tasks to all the constructors. /// </summary> private void Initialize() { count = 0; root = null; //rwLock = new ReaderWriterLock(); } private void Copy( RBTree<T> otherTree ) { root = Copy( otherTree.root, root ); count = otherTree.count; } // copy entire subtree, recursively private RBTreeNode<T> Copy( RBTreeNode<T> oldRoot, RBTreeNode<T> newFather ) { RBTreeNode<T> newRoot = null; // copy a node, then any subtrees if( oldRoot != null ) { newRoot = new RBTreeNode<T>( oldRoot ); if( newFather != null ) newRoot.Father = newFather; newRoot.Left = Copy( oldRoot.Left, newRoot ); newRoot.Right = Copy( oldRoot.Right, newRoot ); } return newRoot; // return newly constructed tree } /// <summary> /// Gets the number of elements stored in RBTree. /// </summary> public int Count { get { return count; } } /// <summary> /// Gets a value indicating whether the access to RBTree is /// synchronized (thread-safe). /// </summary> public bool IsSynchronized { get { return true; } } /// <summary> /// Gets an object that can be used to synchronize access /// to RBTree /// </summary> public object SyncRoot { get { return this; } } /// <summary> /// Gets a value indicating whether the RBTree has /// a fixed size. /// </summary> public bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the RBTree is /// read-only. /// </summary> public bool IsReadOnly { get { return false; } } internal RBTreeNode<T> MaxNode() { if( root == null ) throw new InvalidOperationException( "Unable to return Max because the RBTree is empty." ); RBTreeNode<T> node = root; while( node.Right != null ) node = node.Right; return node; } internal RBTreeNode<T> MinNode() { if( root == null ) throw new InvalidOperationException( "Unable to return Min because the RBTree is empty." ); RBTreeNode<T> node = root; while( node.Left != null ) node = node.Left; return node; } /// <summary> /// Gets the highest element stored in the RBTree. The operation /// is performed in a guaranteed logarithmic time of the size of RBTree. /// </summary> public T Max { get { //rwLock.AcquireReaderLock(Timeout.Infinite); try { return MaxNode().Key; } finally { //rwLock.ReleaseReaderLock(); } } } /// <summary> /// Gets the lowest element stored in the RBTree. The operation /// is performed in a guaranteed logarithmic time of the size of RBTree. /// </summary> public T Min { get { //rwLock.AcquireReaderLock(Timeout.Infinite); try { return MinNode().Key; } finally { //rwLock.ReleaseReaderLock(); } } } /// <summary> /// A pair whose first element is a reference to either a newly inserted key-value pair or an existing one, and the second element is a boolean storing whether the insert actually happened. /// </summary> public class InsertResult { internal InsertResult( T element, bool wasInserted ) { m_Element = element; m_WasInserted = wasInserted; } /// <summary> /// Returns the element, either newly inserted or a previously existing element. /// </summary> public T Element { get { return m_Element; } } /// <summary> /// Returns true if the element was inserted (i.e. the key was not already in the tree). /// </summary> public bool WasInserted { get { return m_WasInserted; } } internal T m_Element; internal bool m_WasInserted; } /// <summary> /// Inserts an elements to the RBTree. The operation is performed /// in a guaranteed logarithmic time of the RBTree size. /// Returns a pair: first element is a reference to either the inserted key-value pair or the existing one, /// second element is a boolean storing whether the insert actually happened /// (if the keys must be unique and the key was already in the tree, the key is not actually inserted) /// </summary> public InsertResult Insert( T x ) { //rwLock.AcquireReaderLock( Timeout.Infinite ); InsertResult rv = null; try { //OnRBTreeModified(); //if(comparer == null) // throw new ArgumentException("RBTree : not able to compare the elements"); if( root == null ) { root = new RBTreeNode<T>( x, null ); rv = new InsertResult( root.Key, true ); } else { // First step : a naive insertion of the element RBTreeNode<T> node1 = root, node2 = null; int compare = 0; while( node1 != null ) { node2 = node1; compare = Comparer.Compare( x, node1.Key ); if( compare < 0 ) { node1 = node1.Left; } else if( compare > 0 ) { node1 = node1.Right; } else { rv = new InsertResult( node1.Key, false ); node1 = null; } } if( rv == null ) { node1 = new RBTreeNode<T>( x, node2 ); rv = new InsertResult( node1.Key, true ); if( compare < 0 ) node2.Left = node1; else node2.Right = node1; node1.Color = true; // Then : correct the structure of the tree while( node1 != root && node1.Father.Color ) { if( node1.Father == node1.Father.Father.Left ) { node2 = node1.Father.Father.Right; if( node2 != null && node2.Color ) { node1.Father.Color = false; node2.Color = false; node1.Father.Father.Color = true; node1 = node1.Father.Father; } else { if( node1 == node1.Father.Right ) { node1 = node1.Father; RotateLeft( node1 ); } node1.Father.Color = false; node1.Father.Father.Color = true; RotateRight( node1.Father.Father ); } } else { node2 = node1.Father.Father.Left; if( node2 != null && node2.Color ) { node1.Father.Color = false; node2.Color = false; node1.Father.Father.Color = true; node1 = node1.Father.Father; } else { if( node1 == node1.Father.Left ) { node1 = node1.Father; RotateRight( node1 ); } node1.Father.Color = false; node1.Father.Father.Color = true; RotateLeft( node1.Father.Father ); } } } } else if( rv.WasInserted ) rv = new InsertResult( x, true ); } if( rv.WasInserted ) { root.Color = false; count++; } } finally { //rwLock.ReleaseReaderLock(); } //if( Count != EnumeratedCount ) throw new InvalidOperationException( "EnumeratedCount does not match stored count" ); return rv; } /// <summary> /// Attempts to add an element in the tree, but does nothing if the element already exists. /// </summary> public void Add( T x ) { Insert( x ); } /// <summary> /// Removes of the elements from the RBTree. /// </summary> public void Clear() { //rwLock.AcquireWriterLock( Timeout.Infinite ); try { //OnRBTreeModified(); root = null; count = 0; } finally { //rwLock.ReleaseWriterLock(); } } /// <summary> /// Determines whether the RBTree contains a specific object. /// The RBTree could contain several identical object. The operation /// is performed in a guaranteed logarithmic time of the RBTree size. /// </summary> public bool Contains( T x ) { // null is always contained in a tree if( x == null ) return true; //rwLock.AcquireReaderLock( Timeout.Infinite ); try { return ( FindNode( x ) != null ); } finally { //rwLock.ReleaseReaderLock(); } } /// <summary> /// Copies the elements of RBTree to a one dimensional /// System.Array at the specified index. /// </summary> public void CopyTo( T[] array, int index ) { // Check the validity of the arguments if( array == null ) throw new ArgumentNullException(); if( index < 0 ) throw new ArgumentOutOfRangeException(); if( array.Rank > 1 || ( array.Length - index ) < count ) throw new ArgumentException(); //rwLock.AcquireReaderLock( Timeout.Infinite ); try { int i = 0; foreach (var itr in this) if (i >= array.Length) break; else if (i >= index) array[i++] = itr; else ++i; } finally { //rwLock.ReleaseReaderLock(); } } /// <remarks> /// RBTreeEnumerator could be instancied only through the /// RBTree.GetEnumerator method. If the RBTree is modified /// after the instanciation of RBTreeEnumerator, then /// RBTreeEnumerator become invalid. Any attempt to read or /// iterate will throw an exception. The elements contained /// in the RBTree are iterated following the order provided /// to the RBTree (ascending order). /// </remarks> public class Enumerator : IEnumerator<T>, ICloneable { /// <summary> /// The current node (or null if none) /// </summary> RBTreeNode<T> current; /// <summary> /// Reference to the RBTree which has instanciated the /// RBTreeEnumerator. /// </summary> RBTree<T> tree; /// <summary> /// Store the state of the RBTreeEnumerator. If /// <c>!started</c> then the current position is /// before the first element of the RBTree. /// </summary> bool started; /// <summary> /// Store the the state of the RBTreeEnumerator. If /// <c>!isValid</c>, any attempt to read or iterate /// will throw an exception. /// </summary> bool isValid; /// <summary> /// Initializes an new instance of Collections.System.RBTreeEnumerator /// class. The current position is before the first element. /// </summary> /// <param name="t">The RBTree which will be enumerate.</param> internal Enumerator( RBTree<T> t ) { tree = t; if( t.root == null && t.Count > 0 ) throw new InvalidOperationException( "The RBTree has null root but non-zero size" ); started = false; isValid = true; current = tree.root; if( current != null ) { while( current.Left != null ) current = current.Left; } } internal Enumerator( RBTree<T> t, RBTreeNode<T> cur ) { tree = t; started = ( cur == tree.root ? false : true ); isValid = true; current = cur; } internal Enumerator( RBTree<T> t, RBTreeNode<T> cur, bool forceStarted ) { tree = t; started = forceStarted; isValid = true; current = cur; } internal RBTreeNode<T> CurrentNode { get { if( current == null ) throw new InvalidOperationException( "After last element" ); if( !isValid ) throw new InvalidOperationException( "The RBTree was modified after the enumerator was created" ); if( !started ) throw new InvalidOperationException( "Before first element" ); return current; } } /// <summary> /// Gets the current element in the RBTree. /// </summary> public T Current { get { return CurrentNode.Key; } } object IEnumerator.Current { get { return (object) Current; } } /// <summary> /// Advances the RBTreeEnumerator to the next element of the RBTree. /// Returns whether the move was possible. /// </summary> public bool MoveNext() { if( !isValid ) throw new InvalidOperationException( "The RBTree was modified after the enumerator was created" ); if( !started ) { started = true; return current != null; } if( current == null ) return false; if( current.Right == null ) { RBTreeNode<T> prev; do { prev = current; current = current.Father; } while( ( current != null ) && ( current.Right == prev ) ); } else { current = current.Right; while( current.Left != null ) current = current.Left; } return current != null; } /// <summary> /// Advances the RBTreeEnumerator to the previous element of the RBTree. /// Returns whether the move was possible. /// </summary> public bool MovePrev() { if( !isValid ) throw new InvalidOperationException( "The RBTree was modified after the enumerator was created" ); if( !started ) return false; if( current == null ) { current = tree.MaxNode(); } else if( current.Left == null ) { RBTreeNode<T> prev; do { prev = current; current = current.Father; } while( ( current != null ) && ( current.Left == prev ) ); } else { current = current.Left; while( current.Right != null ) current = current.Right; } return current != null; } /// <summary> /// Sets the enumerator the its initial position which is before /// the first element of the RBTree. /// </summary> public void Reset() { if( !isValid ) throw new InvalidOperationException( "The RBTree was modified after the enumerator was created" ); started = false; current = tree.root; if( current != null ) { while( current.Left != null ) current = current.Left; } } /// <summary> /// Returns true iff the enumerator points at a valid element. If it is false, it may mean the enumerator has not been initialized, or it can be considered pointing at the "end" of the RBTree. /// </summary> public bool IsValid { get { if( current == null || !isValid || !started ) return false; return true; } } /// <summary> /// Does nothing. /// </summary> public void Dispose() { } /// <summary> /// Invalidates the RBTreeEnumerator. /// </summary> internal void Invalidate() { isValid = false; } /// <summary> /// Returns a copy of this enumerator which can be stored or enumerated separately. /// </summary> public object Clone() { return new Enumerator( this.tree, this.current ); } } /// <summary> /// Returns an System.Collection.IEnumerator that can iterate /// through the RBTree. /// </summary> /// public Enumerator GetEnumerator() { Enumerator tEnum; //rwLock.AcquireReaderLock( Timeout.Infinite ); try { tEnum = new Enumerator( this ); //RBTreeModified += new RBTreeModifiedHandler( tEnum.Invalidate ); } finally { //rwLock.ReleaseReaderLock(); } return tEnum; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return (IEnumerator<T>) GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) GetEnumerator(); } /// <summary> /// FOR TESTING: returns the number of times an RBTreeEnumerator can be advanced, which should be equal to the other Count property. /// </summary> public int EnumeratedCount { get { int count = 0; Enumerator itr = GetEnumerator(); while( itr.MoveNext() ) ++count; return count; } } /// <summary> /// Removes the first occurrence of the element in the RBTree. /// The operation is performed in a guaranteed logarithmic time /// of the RBTree size. /// </summary> public bool Remove( T x ) { //rwLock.AcquireWriterLock( Timeout.Infinite ); try { RBTreeNode<T> node = FindNode( x ); if( node != null ) { RemoveRBTreeNode( node ); //if( Count != EnumeratedCount ) throw new InvalidOperationException( "EnumeratedCount does not match stored count" ); return true; } else return false; } finally { //rwLock.ReleaseWriterLock(); } } /// <summary> /// Removes the element pointed to by the given enumerator; this allows not having to redo the element search. /// </summary> public void Remove( Enumerator x ) { if( !x.IsValid ) return; RemoveRBTreeNode( x.CurrentNode ); } /// <summary> /// Returns an enumerator to the first element greater than or equal to the given element /// (i.e. the first position where the element could be inserted without violating ordering). /// </summary> public Enumerator LowerBound( T x ) { //rwLock.AcquireReaderLock( Timeout.Infinite ); try { return new Enumerator( this, LowerBoundNode( x ), true ); } finally { //rwLock.ReleaseReaderLock(); } } /// <summary> /// Returns an enumerator to the first element greater than the given element, or an invalid enumerator if the element is greater than all others in the map /// (i.e. the last position where the element could be inserted without violating ordering). /// </summary> public Enumerator UpperBound( T x ) { //rwLock.AcquireReaderLock( Timeout.Infinite ); try { return new Enumerator( this, UpperBoundNode( x ), true ); } finally { //rwLock.ReleaseReaderLock(); } } private RBTreeNode<T> FindNode( T x ) { RBTreeNode<T> node = LowerBoundNode( x ); if( node == null || Comparer.Compare( x, node.Key ) < 0 ) node = null; return node; } /// <summary> /// Returns an enumerator for the given element if it is in the map, or an invalid enumerator if it's not. /// </summary> public Enumerator Find( T x ) { //rwLock.AcquireReaderLock( Timeout.Infinite ); try { return new Enumerator( this, FindNode( x ), true ); } finally { //rwLock.ReleaseReaderLock(); } } private RBTreeNode<T> LowerBoundNode( T x ) { RBTreeNode<T> node = root; RBTreeNode<T> lowerBoundNode = null; int compare; while( node != null ) { compare = Comparer.Compare( node.Key, x ); if( compare < 0 ) node = node.Right; // descend right subtree else { // node not less than x, remember it lowerBoundNode = node; node = node.Left; // descend left subtree } } return lowerBoundNode; // return best remembered candidate } private RBTreeNode<T> UpperBoundNode( T x ) { RBTreeNode<T> node = root; RBTreeNode<T> upperBoundNode = null; while( node != null ) { if( Comparer.Compare( x, node.Key ) < 0 ) { // node greater than x, remember it upperBoundNode = node; node = node.Left; // descend left subtree } else node = node.Right; // descend right subtree } return upperBoundNode; // return best remembered candidate } /// <summary> /// Invalidates the System.Collections.IEnumerator linked /// with the RBTree. /// </summary> private void OnRBTreeModified() { /*( RBTreeModified != null ) { RBTreeModified(); RBTreeModified = null; }*/ } /// <summary> /// Removes a specific node of the RBTree. /// </summary> /// <param name="node"> /// node must be contained by RBTree.</param> private void RemoveRBTreeNode( RBTreeNode<T> node ) { RBTreeNode<T> nodeX, nodeY, fatherX, fatherY; if(node.Left == null || node.Right == null) nodeY = node; else nodeY = Successor(node); if(nodeY.Left != null) nodeX = nodeY.Left; else nodeX = nodeY.Right; fatherY = nodeY.Father; fatherX = fatherY; if(nodeX != null) nodeX.Father = nodeY.Father; if(fatherY == null) root = nodeX; else { if(nodeY == fatherY.Left) fatherY.Left = nodeX; else fatherY.Right = nodeX; } if(nodeY != node) node.Key = nodeY.Key; // Remove Correction of the colors if(nodeY == null || !nodeY.Color) { while(nodeX != root && (nodeX == null || !nodeX.Color)) { if(nodeX == fatherX.Left /*&& nodeX != fatherX.Right*/) { fatherY = fatherX; nodeY = fatherX.Right; if(/*nodeY != null && */nodeY.Color) { nodeY.Color = false; fatherX.Color = true; RotateLeft(fatherX); nodeY = fatherX.Right; } if((nodeY.Left == null || !nodeY.Left.Color) && (nodeY.Right == null || !nodeY.Right.Color)) { nodeY.Color = true; nodeX = fatherX; fatherX = fatherX.Father; } else { if(nodeY.Right == null || !nodeY.Right.Color) { nodeY.Left.Color = false; nodeY.Color = true; RotateRight(nodeY); nodeY = fatherX.Right; } nodeY.Color = fatherX.Color; fatherX.Color = false; nodeY.Right.Color = false; RotateLeft(fatherX); nodeX = root; } } else { fatherY = fatherX; nodeY = fatherX.Left; if(/*nodeY != null &&*/ nodeY.Color) { nodeY.Color = false; fatherX.Color = true; RotateRight(fatherX); nodeY = fatherX.Left; } if((nodeY.Right == null || !nodeY.Right.Color) && (nodeY.Left == null || !nodeY.Left.Color)) { nodeY.Color = true; nodeX = fatherX; fatherX = fatherX.Father; } else { if(nodeY.Left == null || !nodeY.Left.Color) { nodeY.Right.Color = false; nodeY.Color = true; RotateLeft(nodeY); nodeY = fatherX.Left; } nodeY.Color = fatherX.Color; fatherX.Color = false; nodeY.Left.Color = false; RotateRight(fatherX); nodeX = root; } } } // End While if(nodeX != null) nodeX.Color = false; } // End Correction count--; } /// <summary> /// Returns the node that contains the successor of node.Key. /// If such node does not exist then null is returned. /// </summary> /// <param name="node"> /// node must be contained by RBTree.</param> private RBTreeNode<T> Successor( RBTreeNode<T> node ) { RBTreeNode<T> node1, node2; if( node.Right != null ) { // We find the Min node1 = node.Right; while( node1.Left != null ) node1 = node1.Left; return node1; } node1 = node; node2 = node.Father; while( node2 != null && node1 == node2.Right ) { node1 = node2; node2 = node2.Father; } return node2; } /// <summary> /// Performs a left tree rotation. /// </summary> /// <param name="node"> /// node is considered as the root of the tree.</param> private void RotateLeft( RBTreeNode<T> node ) { RBTreeNode<T> nodeX = node, nodeY = node.Right; nodeX.Right = nodeY.Left; if(nodeY.Left != null) nodeY.Left.Father = nodeX; nodeY.Father = nodeX.Father; if(nodeX.Father == null) root = nodeY; else { if(nodeX == nodeX.Father.Left) nodeX.Father.Left = nodeY; else nodeX.Father.Right = nodeY; } nodeY.Left = nodeX; nodeX.Father = nodeY; } /// <summary> /// Performs a right tree rotation. /// </summary> /// <param name="node"> /// node is considered as the root of the tree.</param> private void RotateRight( RBTreeNode<T> node ) { RBTreeNode<T> nodeX = node, nodeY = node.Left; nodeX.Left = nodeY.Right; if(nodeY.Right != null) nodeY.Right.Father = nodeX; nodeY.Father = nodeX.Father; if(nodeX.Father == null) root = nodeY; else { if(nodeX == nodeX.Father.Right) nodeX.Father.Right = nodeY; else nodeX.Father.Left = nodeY; } nodeY.Right = nodeX; nodeX.Father = nodeY; } /// <summary> /// Copies the element of the tree into a one dimensional /// System.Array starting at index. /// </summary> /// <param name="currentRBTreeNode">The root of the tree.</param> /// <param name="array">The System.Array where the elements will be copied.</param> /// <param name="index">The index where the copy will start.</param> /// <returns> /// The new index after the copy of the elements of the tree. /// </returns> private int RecCopyTo( RBTreeNode<T> currentRBTreeNode, T[] array, int index ) { if(currentRBTreeNode != null) { array.SetValue(currentRBTreeNode.Key, index); return RecCopyTo(currentRBTreeNode.Right, array, RecCopyTo(currentRBTreeNode.Left, array, index + 1)); } else return index; } /// <summary> /// Returns a node of the tree which contains the object /// as Key. If the tree does not contain such node, then /// null is returned. /// </summary> /// <param name="node">The root of the tree.</param> /// <param name="x">The researched object.</param> private RBTreeNode<T> RecContains( RBTreeNode<T> node, T x ) { if(node == null) return null; int c = Comparer.Compare(x, node.Key); if(c == 0) return node; if(c < 0) return RecContains(node.Left, x); else return RecContains(node.Right, x); } /// <summary> /// For debugging only. Checks whether the RBTree is conform /// to the definition of the a red-black tree. If not an /// exception is thrown. /// </summary> /// <param name="node">The root of the tree.</param> private int RecConform( RBTreeNode<T> node ) { if(node == null) return 1; if(node.Father == null) { if(node.Color) throw new ArgumentException("RBTree : the root is not black."); } else { if(node.Father.Color && node.Color) throw new ArgumentException("RBTree : father and son are red."); } if(node.Left != null && Comparer.Compare(node.Key, node.Left.Key) < 0) throw new ArgumentException("RBTree : order not respected in tree."); if(node.Right != null && Comparer.Compare(node.Key, node.Right.Key) > 0) throw new ArgumentException("RBTree : order not respected in tree."); int a = RecConform(node.Left), b = RecConform(node.Right); if(a < 0 || b < 0) return -1; if(a != b) throw new ArgumentException("RBTree : the paths do have not the same number of black nodes."); if(!node.Color) return (a+1); else return a; } } /// <remarks> /// RBTreeNode is simple colored binary tree node which /// contains a key. /// </remarks> internal class RBTreeNode<T> { /// <summary> /// References to the other elements of the RBTree. /// </summary> RBTreeNode<T> father, left, right; /// <summary> /// Reference to the object contained by the RBTreeNode. /// </summary> T key; /// <summary> /// The color of the node (red = true, black = false). /// </summary> bool color; /// <summary> /// Initializes an new instance of Collections.System.RBTreeNode /// class. All references are set to null. /// </summary> internal RBTreeNode() { key = default(T); father = null; left = null; right = null; color = true; } /// <summary> /// Initializes an new instance of Collections.System.RBTreeNode /// class and partially insert the RBTreeNode into a tree. /// </summary> /// <param name="k">Key of the RBTreeNode</param> /// <param name="fatherRBTreeNode">The father node of the instanciated RBTreeNode.</param> internal RBTreeNode(T k, RBTreeNode<T> fatherRBTreeNode) { key = k; father = fatherRBTreeNode; left = null; right = null; color = true; } internal RBTreeNode( RBTreeNode<T> otherNode ) { key = otherNode.key; father = otherNode.father; left = otherNode.left; right = otherNode.right; color = otherNode.color; } /// <summary> /// Gets or sets the key of the RBTreeNode. /// </summary> internal T Key { get { return key; } set { key = value; } } /// <summary> /// Gets or sets the father of the RBTreeNode. /// </summary> internal RBTreeNode<T> Father { get { return father; } set { father = value; } } /// <summary> /// Gets or sets the left children of the RBTreeNode. /// </summary> internal RBTreeNode<T> Left { get { return left; } set { left = value; } } /// <summary> /// Gets or sets the right children of the RBTreeNode. /// </summary> internal RBTreeNode<T> Right { get { return right; } set { right = value; } } /// <summary> /// Gets or sets the color of the RBTreeNode. /// </summary> internal bool Color { get { return color; } set { color = value; } } } }
78eb5179f06d236ec58210252f67e374d4454bd1
C#
BrentMon/NUnitTest
/UnitTestProject2/02_PageObjectsAndFeatures/02_Object Repository/PageObjects_Amazon.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using OpenQA.Selenium; //using OpenQA.Selenium.IE; using OpenQA.Selenium.Support.UI; namespace UnitTestProject2 { class AmazonObjects { public static IWebElement wSearchbar(IWebDriver driver) { By bCartButtonLocator = By.Id("twotabsearchtextbox"); IWebElement wSearchbar = driver.FindElement(bCartButtonLocator); return wSearchbar; } public static IWebElement wCartButton(IWebDriver driver) { By bCartButtonLocator = By.Id("nav-cart"); IWebElement wCartButton = driver.FindElement(bCartButtonLocator); return wCartButton; } public static void mAmazonHomePage(IWebDriver driver) { if (HomePage.sHomeTitle().Equals(driver.Title.ToString())) { System.Console.WriteLine("You are on the home page, lets begin"); } else { System.Console.WriteLine("You were not on the home page, going there now"); driver.Navigate().GoToUrl("http://www.amazon.com"); } } public static void mProductSearch(IWebDriver driver, string a) { AmazonObjects.wSearchbar(driver).SendKeys(a); AmazonObjects.wSearchbar(driver).Submit(); } public static void mURLSearch(IWebDriver driver, string a) { driver.Navigate().GoToUrl(a); } } class HomePage { public static string sHomeTitle() { string sHomeTitle = "Amazon.com: Online Shopping for Electronics, Apparel, Computers, Books, DVDs &amp; more"; return sHomeTitle; } } class ProductPage { public static IWebElement wProductTitle(IWebDriver driver) { By bProductLocator = By.Id("productTitle"); IWebElement wProductTitle = driver.FindElement(bProductLocator); return wProductTitle; } public static IWebElement wAddToCartButton(IWebDriver driver) { By bAddToCartButtonLocator = By.Id("add-to-cart-button"); IWebElement wAddToCartButton = driver.FindElement(bAddToCartButtonLocator); return wAddToCartButton; } public static void mAddToCartWithPopup(IWebDriver driver) { try { //System.Threading.Thread.Sleep(1000); ProductPage.wAddToCartButton(driver).Click(); // System.Threading.Thread.Sleep(1000); ProductPage.ProtectionPopup.wProtectionNoThanks(driver).Click(); //set the no thanks button to null for the next item //ProductPage.wProtectionNoThanks(driver).Equals(null); } catch (NoSuchElementException) { //ProductPage.wAddToCartButton(driver).Click(); string exception = "The Protection Plan popup did not display"; System.Console.WriteLine(exception + " for " + DataSheet.sProductArrayCurrent); // System.Console.WriteLine(ex.Message); } } public static void mMultipleItemsFindAndPurchase(IWebDriver driver, String[] URL) { int i = 0; foreach (string item in URL) { //navigate to the first item in items array AmazonObjects.mURLSearch(driver, item); //AmazonObjects.mProductSearch(driver, item); //find the product title web element and give the current index of product array the same value as the curent product title DataSheet.sProductArray[i] = ProductPage.wProductTitle(driver).Text; DataSheet.sProductArrayCurrent = DataSheet.sProductArray[i]; //call the mAddToCart method to add the item to our cart. ProductPage.mAddToCartWithPopup(driver); //increment the index of our loop by 1 i = i + 1; } } public static class ProtectionPopup { public static IWebElement wProtectionNoThanks(IWebDriver driver) { By bProtectionNoThanksLocator = By.Id("siNoCoverage-announce"); IWebElement wProtectionNoThanks = driver.FindElement(bProtectionNoThanksLocator); return wProtectionNoThanks; } } } class CartPage { public static string sCartPageURL = "http://www.amazon.com/gp/cart/view.html/ref=nav_cart"; public static IWebElement wProductTitle (IWebDriver driver) { By bProductLocator = By.Id("productTitle"); IWebElement wProductTitle = driver.FindElement(bProductLocator); return wProductTitle; } public static IWebElement wActiveCart (IWebDriver driver) { By bActiveCartLocator = By.Id("sc-active-cart"); IWebElement wActiveCart = driver.FindElement(bActiveCartLocator); return wActiveCart; } public static IWebElement wCartItem(IWebDriver driver, string a) { By bCartItemLocator = By.LinkText(a); IWebElement wCartItem = driver.FindElement(bCartItemLocator); return wCartItem; } public static string[] mGetCartItems(IWebDriver driver, string[] items) { int y = 0; string[] mGetCartItems = new string[items.Length]; foreach (string a in items) { mGetCartItems[y] = CartPage.wCartItem(driver, a).Text; //mGetCartItems[y] = a; y = y + 1; }; return mGetCartItems; } public static string sProductTitle (IWebDriver driver) { string sProductTitle = CartPage.wProductTitle(driver).Text; return sProductTitle; } public static IWebElement wCartDeleteButton(IWebDriver driver) { By bDelete = By.LinkText(""); By bDeleteButtonLocator = By.Name("submit.delete."); IWebElement wCartDeleteButton = driver.FindElement(bDeleteButtonLocator); return wCartDeleteButton; } public static void mRemoveFromCart(IWebDriver driver) { CartPage.wCartDeleteButton(driver).Click(); } public static IWebElement wCartPrice(IWebDriver driver) { By bCartPriceLocator = By.ClassName("sc-price-sign"); IWebElement wCartPrice = driver.FindElement(bCartPriceLocator); return wCartPrice; } public static string sCartPrice (IWebDriver driver) { string sCartPrice = CartPage.wCartPrice(driver).Text; sCartPrice = sCartPrice.TrimStart(DataSheet.cDollarSign()); return sCartPrice; } public static double dCartPrice(IWebDriver driver) { try { double dCartPrice = Convert.ToDouble(CartPage.sCartPrice(driver)); return dCartPrice; } catch (NoSuchElementException ex) { System.Console.WriteLine(ex.Message); driver.Navigate().GoToUrl(CartPage.sCartPageURL); double dCartPrice = Convert.ToDouble(CartPage.sCartPrice(driver)); return dCartPrice; } } } }
8df04af330133ee5f58cb2ceb3d6121d9f12f0ae
C#
foo4foo/hci_projekat
/hci/Models/Software.cs
2.859375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace hci.Models { public class Software { private string dbID; public string DbId { get { return dbID; } set { dbID = value; } } private bool deleted = false; public bool Deleted { get { return deleted; } set { deleted = value; } } public string Id { get { return id; } set { id = value; } } public string Name { get { return name; } set { name = value; } } public string Developer { get { return developer; } set { developer = value; } } public string Site { get { return site; } set { site = value; } } public string Description { get { return description; } set { description = value; } } public string Os { get { return os; } set { os = value; } } public int Year { get { return year; } set { year = value; } } public double Price { get { return price; } set { price = value; } } private string id; private string name; private string developer; private string site; private string description; private string os; private int year; private double price; public Software(string _id, string _name, string _developer, string _site, string _description, string _os, int _year, double _price, bool _deleted) { this.id = _id; this.name = _name; this.developer = _developer; this.site = _site; this.description = _description; this.os = _os; this.year = _year; this.price = _price; this.Deleted = _deleted; } public Software() { } public override string ToString() { return Id + " " + Name + " " + Description + " " + Developer + " " + Os + " " + Year + " " + Site + " " + Price; } } }
c9d6f28ae9aa2a3ffef2a1e26a37fe882b8c53f3
C#
LapkoMax/GameAchievements
/AngularWeb/MediatRComands/Genre/GetGenreCommand.cs
2.609375
3
using AutoMapper; using DataAccess.Repository; using Entities.DataTransferObjects; using MediatR; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace AngularWeb.MediatRComands.Genre { public class GetGenreCommand : IRequest<GenreDto> { public long genreId { get; set; } } public class GetGenreCommandHandler : IRequestHandler<GetGenreCommand, GenreDto> { private readonly IRepositoryManager _repository; private readonly IMapper _mapper; public GetGenreCommandHandler(IRepositoryManager repository, IMapper mapper) { _repository = repository; _mapper = mapper; } public async Task<GenreDto> Handle(GetGenreCommand command, CancellationToken token) { var genre = await _repository.Genre.GetGenreAsync(command.genreId); var genreDto = _mapper.Map<GenreDto>(genre); return (genreDto); } } }
5f2007046c4049d22dbb58b47c72124c7b180583
C#
rizidorio/CEP_Version1
/CEP/CEP/MainPage.xaml.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using CEP.Servico.Modelo; using CEP.Servico; namespace CEP { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); btnBuscarCep.Clicked += BuscarEndereco; } private void BuscarEndereco(object sender, EventArgs e) { string cep = txtCep.Text.Trim(); if (IsValid(cep)) { try { Endereco endereco = ViaCEPServico.BuscarEndereco(cep); if(endereco.cep != null) { lblCep.Text = "CEP: " + endereco.cep; lblLogradouro.Text = "Logradouro: " + endereco.logradouro; lblBairro.Text = "Bairro: " + endereco.bairro; lblCidade.Text = "Cidade: " + endereco.localidade; lblEstado.Text = "Estado: " + endereco.uf; txtCep.Text = ""; } else { DisplayAlert("ERRO", "O não foi encontrado endereço para o CEP: " + cep, "OK"); } } catch (Exception ex) { DisplayAlert("ERRO CRÍTICO", ex.Message, "OK"); } } } private bool IsValid(string cep) { bool valido = true; if(cep.Length != 8) { DisplayAlert("ERRO", "O CEP deve conter 8 caracteres", "OK"); valido = false; } if(!int.TryParse(cep, out int NovoCep)) { DisplayAlert("ERRO", "O CEP deve conter somente números", "OK"); valido = false; } return valido; } } }
75c8ace6d39259ce9a1f25853927213a5fce4b44
C#
LXShades/plantgenerator
/Assets/Scripts/Generators/GenPetal.cs
2.5625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class GenPetal : GenMesh { Vector3 start; Vector3 direction; float radius; AnimationCurve outline; int numLengthVertices = 0; public GenPetal(Vector3 start, Vector3 direction, float radius, AnimationCurve outline, int numLengthVertices) { this.start = start; this.direction = direction; this.radius = radius; this.outline = outline; this.numLengthVertices = (numLengthVertices + 1) / 2 * 2; // temp: numRadialVertices should be even for now } protected override void OnRegenerate() { // Create the directional vectors Vector3 forward = direction; Vector3 right = Vector3.Cross(Vector3.up, direction).normalized; // Create a mirrored semi-circle along the given curve vertices = new List<Vector3>(new Vector3[numLengthVertices]); colors = new List<Color32>(new Color32[numLengthVertices]); Color32 baseColor = new Color32(0, 255, 0, 255); Color32 extColor = new Color32(0, 255, 0, 255); float progress = 0.0f; for (int i = 0; i < numLengthVertices / 2; i++) { float width = outline.Evaluate((float)i / (numLengthVertices / 2)); vertices[i << 1] = start + right * width + forward * progress; vertices[(i << 1) + 1] = start - right * width + forward * progress; colors[i << 1] = baseColor; colors[(i << 1) + 1] = extColor; progress += 1.0f / ((float)numLengthVertices / 2 - 1); } // Join the sides of the semi-circle triangles = new List<int>(new int[(numLengthVertices / 2 - 1) * 6]); int numCreatedIndices = 0; for (int quad = 0; quad < numLengthVertices / 2 - 1; quad++) { int baseline = quad * 2; triangles[numCreatedIndices + 2] = (baseline + 1) % numLengthVertices; triangles[numCreatedIndices + 1] = (baseline + 0) % numLengthVertices; triangles[numCreatedIndices + 0] = (baseline + 2) % numLengthVertices; triangles[numCreatedIndices + 5] = (baseline + 1) % numLengthVertices; triangles[numCreatedIndices + 4] = (baseline + 2) % numLengthVertices; triangles[numCreatedIndices + 3] = (baseline + 3) % numLengthVertices; numCreatedIndices += 6; } } }
03048019c5d2723410124cb10190d3c09570643c
C#
esciranka/xklementm
/Game/Assets/Level1/Scripts/ChangeInstruction.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ChangeInstruction : MonoBehaviour { Text text; Text bigText; // List<string> instructionsBigText = new List<string>(); List<string> instructions = new List<string>(); int index; // Start is called before the first frame update void Start() { text = GetComponent<Text>(); //bigText = GetComponent<Text>(); index = 0; //Prvá inštrukcia instructions.Add("Pristál si na planéte Elektromagnetizmu, na ktorej upadli štátne železnice v zabudnutie. Tvojou úlohou je znovu naštartovať elektromotor opusteného vlaku a naladiť jeho parametre tak, aby bol schopný dopraviť ťa do druhej úrovne." + "\nPre ďalšie inštrukcie stlač tlačidlo 'Ďalej' v pravom dolnom rohu obrazovky..."); //Informácie na úvod instructions.Add("Vlak, ktorý sa nachádza za východom má v sebe indukčný trojfázový synchrónny elektromotor poháňaný striedavým prúdom o výkone 6000 kW. Jeho účinnosť je pri vhodných otáčkach (1000 RPM) až 80%, to znamená, že ďalších 20% sa premení na teplo. "); //Prvá úloha instructions.Add("Tvojou prvou úlohou je preniesť akumulátory nachádzajúce sa na druhej strane miestnosti do vlaku. Tie mu budú slúžiť ako zdroj energie. Akumulátory postupne vlož do všetkých štyroch miest (minimálne do dvoch), ktoré sa nachádzajú na zadnej strane vlaku (po východe z miestnosti vľavo)."); //drujá úloha instructions.Add("Tvojou druhou úlohou je naštartovať motor vlaku. To dosiahneš tak, že nastavíš otáčky motora tak, aby boli okolo 100 % otáčok motora (950 - 1050 RMP). Počet otáčok je 120 násobok frekvencie predelený počtom pólov, teda 120*f/p. Frekvencia by mala byť rovnaká ako je frekvencia siete."); //tretia úloha instructions.Add("Ak sa ti podarilo naštartovať motor, si už na polceste k úspešnému ukončeniu prvej úrovne. Tvojou úlohou je nastaviť počet pólov a frekvenciu tak, aby vlak dokázal dojsť ďalšej!"); instructions.Add("Či si správne nastavil vstupné hodnoty tak, aby mal vlak čo najvyšší dojazd a dorazil do stanice (ktorá je podľa dostupných údajov vzdialená " + "približne 1300 km) si môžeš overiť tlačidlom 'Vypočítaj', ktoré sa nachádza na obrazovke s vstupnými hodnotami. Pozor! Toto tlačidlo vydrží už len niekoľko stlačení!"); instructions.Add("Ak si správne naladil všetky údaje, odomkol sa ti v prednej časti vlaku teleport , ktorý ti umožní odísť. Gratulujem ! "); } public void nextInstruction() { if (index + 1 < instructions.Count) index++; text.text = instructions[index]; Debug.Log("index : " + index.ToString()); } public void previousInstruction() { if (index > 0) index--; text.text = instructions[index]; //bigText.text = instructionsBigText[index]; Debug.Log("index : " + index.ToString()); } }
01408a77400f74ef4c98206b49415b6e6f68611c
C#
FourHyphen/MyTrimmingNew
/MyTrimmingNew/AuxiliaryLine/AuxiliaryLineCommandList.cs
3.078125
3
using System.Collections.Generic; namespace MyTrimmingNew.AuxiliaryLine { class AuxiliaryLineCommandList { private List<AuxiliaryLineCommand> CommandList { get; set; } private int CommandListIndex { get; set; } public AuxiliaryLineCommandList() { CommandList = new List<AuxiliaryLineCommand>(); CommandListIndex = 0; } public AuxiliaryLineParameter Execute(AuxiliaryLineCommand command, object operation) { if (DoneUnExecuteBefore()) { // かつての操作内容を削除し、今の操作内容を最新の履歴とする if (CommandListIndex >= 0) { CommandList.RemoveRange(CommandListIndex, CommandList.Count - CommandListIndex); } } AuxiliaryLineParameter result = command.Execute(operation); CommandList.Add(command); CommandListIndex++; return result; } private bool DoneUnExecuteBefore() { return (CommandListIndex < CommandList.Count); } public AuxiliaryLineParameter UnExecute(AuxiliaryController ac) { if(CommandListIndex <= 0) { return ac.CloneParameter(); } CommandListIndex--; return CommandList[CommandListIndex].BeforeParameter; } public AuxiliaryLineParameter ReExecute(AuxiliaryController ac) { if (CommandListIndex >= CommandList.Count) { return ac.CloneParameter(); } AuxiliaryLineParameter redo = CommandList[CommandListIndex].AfterParameter; CommandListIndex++; return redo; } } }
f8c4e5759104c5c1573016def892c184870c3297
C#
georgethejournalist/dirigent
/src/Dirigent.Common/Tools.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Dirigent.Common; namespace Dirigent.Common { public class Tools { public static ILaunchPlan FindPlanByName(IEnumerable<ILaunchPlan> planRepo, string planName) { // find plan in the repository ILaunchPlan plan; try { plan = planRepo.First((i) => i.Name == planName); return plan; } catch { throw new UnknownPlanName(planName); } } public static string GetAppStateString(AppIdTuple t, AppState appState) { var sbFlags = new StringBuilder(); if (appState.Started) sbFlags.Append("S"); if (appState.StartFailed) sbFlags.Append("F"); if (appState.Running) sbFlags.Append("R"); if (appState.Killed) sbFlags.Append("K"); if (appState.Initialized) sbFlags.Append("I"); if (appState.PlanApplied) sbFlags.Append("P"); var now = DateTime.UtcNow; var stateStr = String.Format("APP:{0}:{1}:{2}:{3}:{4}:{5}:{6}", t.ToString(), sbFlags.ToString(), appState.ExitCode, (now - appState.LastChange).TotalSeconds, appState.CPU, appState.GPU, appState.Memory ); return stateStr; } public static string GetPlanStateString(string planName, PlanState planState) { var stateStr = String.Format("PLAN:{0}:{1}", planName, planState.OpStatus.ToString()); return stateStr; } // returs first line without CR/LF public static string JustFirstLine(string multiLineString) { var crPos = multiLineString.IndexOf('\r'); var lfPos = multiLineString.IndexOf('\n'); if (crPos >= 0 || lfPos >= 0) { return multiLineString.Substring(0, Math.Min(crPos, lfPos)); } return multiLineString; // no other line found } } }
647720b717fc351452992066ca3e790b9b4bed29
C#
nvntuan123/ManageAppleStore
/ManageAppleStore_DAO/EmployeeOfTypesDAO.cs
2.609375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using ManageAppleStore_DTO; namespace ManageAppleStore_DAO { public class EmployeeOfTypesDAO { public static BindingList<EmployeeOfTypesDTO> loadListDAO() { try { BindingList<EmployeeOfTypesDTO> LstEmpType = new BindingList<EmployeeOfTypesDTO>(); string strSelect = @"select * from dbo.tblEmployeeOfType where dbo.tblEmployeeOfType.Status = 1"; SqlConnection conn = DataProviderDAO.createConnect(); SqlDataReader sdr = DataProviderDAO.queryData(strSelect, conn); while (sdr.Read()) { EmployeeOfTypesDTO EmpType = new EmployeeOfTypesDTO(); if (!sdr.IsDBNull(0)) { EmpType.StrID = sdr["ID"].ToString(); } if (!sdr.IsDBNull(1)) { EmpType.StrName = sdr["Name"].ToString(); } if (!sdr.IsDBNull(2)) { EmpType.BStatus = Convert.ToBoolean(sdr["Status"]); } LstEmpType.Add(EmpType); } sdr.Close(); conn.Close(); return LstEmpType; } catch (Exception) { return null; } } public static List<string> loadIDListDAO() { try { List<string> LstID = new List<string>(); string StrSelect = @"select dbo.tblEmployeeOfType.ID from dbo.tblEmployeeOfType"; SqlConnection conn = DataProviderDAO.createConnect(); SqlDataReader sdr = DataProviderDAO.queryData(StrSelect, conn); while (sdr.Read()) { if (!sdr.IsDBNull(0)) { LstID.Add(sdr["ID"].ToString()); } } sdr.Close(); conn.Close(); return LstID; } catch { return null; } } public static bool updateDAO(EmployeeOfTypesDTO EmpTypeCurrent) { string strUpdate = @"UPDATE dbo.tblEmployeeOfType SET Name = @Name WHERE ID like '" + EmpTypeCurrent.StrID + "'"; List<SqlParameter> LstPar = new List<SqlParameter>(); LstPar.Add(new SqlParameter("@Name", EmpTypeCurrent.StrID)); foreach (var ParCheck in LstPar) { if (ParCheck.Value == null) { ParCheck.Value = DBNull.Value; } } try { SqlConnection conn = DataProviderDAO.createConnect(); bool BResult = DataProviderDAO.executeStatement(strUpdate, LstPar.ToArray(), conn); conn.Close(); return BResult; } catch { return false; } } public static bool addDAO(EmployeeOfTypesDTO EmpTypeCurrent) { string strInsert = @"INSERT INTO dbo.tblLoaiNhanVien(ID, Name, Status) VALUES (@ID, @Name, 1)"; List<SqlParameter> LstPar = new List<SqlParameter>(); LstPar.Add(new SqlParameter("@ID", EmpTypeCurrent.StrID)); LstPar.Add(new SqlParameter("@Name", EmpTypeCurrent.StrName)); if (LstPar[0].Value == null) return false; foreach (var ParCheck in LstPar) { if (ParCheck.Value == null) { ParCheck.Value = DBNull.Value; } } try { SqlConnection conn = DataProviderDAO.createConnect(); bool BResult = DataProviderDAO.executeStatement(strInsert, LstPar.ToArray(), conn); conn.Close(); return BResult; } catch { return false; } } public static bool updateStatusDAO(EmployeeOfTypesDTO EmpTypeCurrent) { try { string StrUpdate = @"UPDATE dbo.tblEmployeeOfType SET Status = 0 WHERE ID = '" + EmpTypeCurrent.StrID + "'"; SqlConnection conn = DataProviderDAO.createConnect(); bool BResult = DataProviderDAO.executeStatement(StrUpdate, conn); conn.Close(); return BResult; } catch { return false; } } public static bool checkIDDAO(EmployeeOfTypesDTO EmpTypeCurrent) { try { bool BCheck = false; string StrSelect = @"SELECT TOP 1 ID FROM dbo.tblEmployeeOfType WHERE dbo.tblEmployeeOfType.ID like '" + EmpTypeCurrent.StrID + "'"; SqlConnection conn = DataProviderDAO.createConnect(); SqlDataReader sdr = DataProviderDAO.queryData(StrSelect, conn); if (sdr.Read()) { if (!sdr.IsDBNull(0)) { BCheck = true; } } sdr.Close(); conn.Close(); return BCheck; } catch { return false; } } public static bool checkNameDAO(EmployeeOfTypesDTO EmpTypeCurrent) { try { bool BCheck = false; string StrSelect = @"SELECT TOP 1 ID FROM dbo.tblEmployeeOfType WHERE dbo.tblEmployeeOfType.Name like N'" + EmpTypeCurrent.StrName + "'"; SqlConnection conn = DataProviderDAO.createConnect(); SqlDataReader sdr = DataProviderDAO.queryData(StrSelect, conn); if (sdr.Read()) { if (!sdr.IsDBNull(0)) { BCheck = true; } } sdr.Close(); conn.Close(); return BCheck; } catch { return false; } } } }
b33ae794aced818d4f8885359e9866b9e19f187e
C#
tanujgyan/LeetCode
/LeetCode/AQs/SearchRotatedArray.cs
3.3125
3
using System; using System.Collections.Generic; using System.Text; namespace LeetCode.Amazon_Interview_Questions { class SearchRotatedArray { int pivot = -1; int answer = -1; Dictionary<string, int> cache = new Dictionary<string, int>(); public int Search(int[] nums, int target) { if (nums.Length == 1) { if (nums[0] == target) { answer = 0; } else answer = -1; } else { SearchHelper(nums, 0, nums.Length - 1); Console.WriteLine("Pivot " + pivot); if (pivot == -1) { SearchTarget(nums, target, 0, nums.Length - 1); } else { if (target == nums[pivot]) { answer = pivot; } else if (pivot == 0 && target > nums[pivot]) { answer = -1; } else if ((pivot == 0 && target < nums[pivot])) { int[] newarr = new int[nums.Length - 1]; Array.Copy(nums, 1, newarr, 0, newarr.Length); SearchTarget(newarr, target, 0, newarr.Length - 1); if(answer!=-1) { answer++; } } else if ((target > nums[pivot] && target <= nums[nums.Length - 1])) { int[] newarr = new int[nums.Length - pivot]; Array.Copy(nums, pivot, newarr, 0, newarr.Length); SearchTarget(newarr, target, 0, newarr.Length - 1); if (answer != -1) { answer += pivot; } } else if (target <= nums[pivot - 1] && target >= nums[0]) { int[] newarr = new int[pivot]; Array.Copy(nums, 0, newarr, 0, newarr.Length); SearchTarget(newarr, target, 0, newarr.Length - 1); } } } Console.WriteLine("Answer " + answer); return answer; } private void SearchTarget(int[] arr, int target, int low, int high) { if (low > high) { return; } if (answer != -1) { return; } int mid = (high + low) / 2; if (target == arr[mid]) { answer = mid; } else if (target > arr[mid]) { SearchTarget(arr, target, mid + 1, high); } else if (target < arr[mid]) { SearchTarget(arr, target, 0, mid - 1); } } private void SearchHelper(int[] nums, int low, int high) { if (pivot != -1) { return; } if(!cache.ContainsKey(low+"_"+high)) { cache.Add(low + "_" + high, 1); } else { return; } int mid = (high + low) / 2; if (low >= high || mid == 0 || mid == nums.Length - 1) { if (low == 0) { if (nums[0] > nums[1]) { pivot = 0; } } else if (low == nums.Length - 1) { if (nums[low] < nums[low - 1]) { pivot = low; } } return; } if (nums[mid - 1] > nums[mid]) { pivot = mid; return; } else { SearchHelper(nums, 0, mid); SearchHelper(nums, mid + 1, high); } } } }
a6504902e7453f2f30e8f21ab619785468e9313a
C#
FlayaN/B3Utils
/Server/Api/Controllers/AwardsController.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Api.Models.Database; using Api.Models.ViewModels; using Api.Infrastructure; namespace Api.Controllers { [Route("api/v1/[controller]")] public class AwardsController : Controller { private AppDbContext _context; public AwardsController(AppDbContext context) { _context = context; } //[HttpGet("forUser/{userId}")] //public IActionResult GetAwardsForUser(string userId) //{ // var awards = new List<AwardViewModel>(); // var startDate = new DateTime(2017, 05, 18); // var query = _context.Activities.GroupBy(x => new { x.Type, x.UserId }) // .Select(x => new { Group = x.Key, TotalAmount = x.Sum(y => y.Amount) }) // .OrderByDescending(x => x.TotalAmount) // .FirstOrDefault(); // return new ObjectResult(awards); //} [HttpGet("{fitnessType}/{filter}")] public IActionResult GetAwards(FitnessType fitnessType, FilterType filter) { var query = _context.Activities.Where(x => x.Type == fitnessType); var awards = new List<AwardViewModel>(); var startDate = new DateTime(2017, 05, 18); switch (filter) { case FilterType.Month: for (DateTime date = startDate; date.Month < DateTime.UtcNow.Month; date = date.AddMonths(1)) { var res = query .Where(x => x.Date.Month == date.Month) .GroupBy(x => x.UserId) .Select(x => new { UserId = x.Key, TotalAmount = x.Sum(y => y.Amount) }) .OrderByDescending(x => x.TotalAmount) .Take(3); if (res != null) { int placement = 1; foreach(var award in res) { awards.Add(new AwardViewModel { AwardId = Guid.NewGuid(), UserId = award.UserId, Description = fitnessType == FitnessType.Distance ? $"Sträcka månad: {date.Month}" : $"Steg månad: {date.Month}", Value = award.TotalAmount.ToString(), Date = date, Type = fitnessType == FitnessType.Distance ? AwardType.MonthDistance : AwardType.MonthSteps, Placement = placement++ }); } } } break; case FilterType.Week: for (DateTime date = startDate; DateHelper.GetIso8601WeekOfYear(date) < DateHelper.GetIso8601WeekOfYear(DateTime.UtcNow); date = date.AddDays(7)) { var week = DateHelper.GetIso8601WeekOfYear(date); var res = query .Where(x => DateHelper.GetIso8601WeekOfYear(x.Date.Date) == week) .GroupBy(x => x.UserId) .Select(x => new { UserId = x.Key, TotalAmount = x.Sum(y => y.Amount) }) .OrderByDescending(x => x.TotalAmount) .Take(3); if (res != null) { int placement = 1; foreach (var award in res) { awards.Add(new AwardViewModel { AwardId = Guid.NewGuid(), UserId = award.UserId, Description = fitnessType == FitnessType.Distance ? $"Sträcka vecka: {week}" : $"Steg vecka: {week}", Value = award.TotalAmount.ToString(), Date = date, Type = fitnessType == FitnessType.Distance ? AwardType.WeekDistance : AwardType.WeekSteps, Placement = placement++ }); } } } break; case FilterType.All: default: break; } return new ObjectResult(awards); } } }
ffb55f864fc12a2308b0adfc2e9a36a4bdee1f50
C#
ElhamAbdelMged/test
/TechnicalTaskInvoice/Models/SQLItem.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TechnicalTaskInvoice.Models { public class SQLItem : IItemRepository { private readonly AppDbContext context; public SQLItem(AppDbContext context) { this.context = context; } public IEnumerable<Item> GetAllItem() { return context.Item.ToList(); } public Item GetItem(int ID) { return context.Item.Find(ID); } } }
8cbe434a813306570656d8d29d93e4cbee2b8e21
C#
genceredon/CSharpMasters
/HomeworkOne/AddOperation.cs
4.09375
4
using System; namespace HomeworkOne { public partial class Program { /// <summary> /// Adds the two numbers. /// </summary> /// <returns></returns> public static void AddTwoNumbers() { Console.WriteLine("Inside AddTwoNumbers method"); Console.Write("Type a number, and then press Enter: "); int num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Type another number, and then press Enter: "); int num2 = Convert.ToInt32(Console.ReadLine()); var sum = num1 + num2; Console.WriteLine($"Your result: {num1} + {num2} = {sum}"); } } }
e3fb4eb2c9b0e76ecb9b2ae95020af0b91a6f545
C#
umbersar/ToyDB
/ToyDB/SQLBatch.cs
2.875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static ToyDB.AST_Helper; namespace ToyDB { public class SQLBatch : Node { List<Statement> _statements; public List<Statement> Statements { get => _statements; set => _statements = value; } public SQLBatch() { this.Statements = new List<Statement>(); } public override string TokenLiteral() { if (this.Statements.Count > 0) { return this.Statements[0].TokenLiteral(); } else { return ""; } } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); foreach (var stmt in this.Statements) { stringBuilder.Append(stmt.ToString()); } return stringBuilder.ToString(); } } }
d7010eb176a822ecabf1425d1ef333afd4526684
C#
EvgeniyaDubrovskaya/slenium-training
/LiteCardTests/LiteCardTests/pages/ProductPage.cs
2.734375
3
using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LiteCardTests.pages { class ProductPage: Page { public ProductPage(IWebDriver driver) : base(driver) { } internal ProductPage Open(int prNumber) { var wbCards = driver.FindElements(By.CssSelector("li.product")); //Go to Product page wbCards[prNumber].FindElement(By.CssSelector("a")).Click(); //Wait button Add product wait.Until(ExpectedConditions.ElementExists(By.CssSelector("button[name='add_cart_product']"))); return this; } internal void AddProductToBasket() { var wbCountPrOld = CountProductInBasket(); if (IsElementPresent(driver, By.CssSelector("select[name='options[Size]'"))) { SelectElement select = new SelectElement(driver.FindElement(By.CssSelector("select[name='options[Size]'"))); select.SelectByIndex(1); } driver.FindElement(By.CssSelector("button[name='add_cart_product']")).Click(); //wait.Until(ExpectedConditions.TextToBePresentInElementValue(driver.FindElement(By.CssSelector("div#cart a span.quantity")), (wbCountPrOld + 1).ToString())); wait.Until(d => CountProductInBasket() == (wbCountPrOld + 1)); } internal int CountProductInBasket() { return int.Parse(driver.FindElement(By.CssSelector("div#cart a span.quantity")).Text); } } }
2eae69afc6331c265d7a6f082eb57cb13c403b8c
C#
simonrozsival/racing-simulation
/src/Racing.CircuitGenerator/WaypointsGenerator.cs
3.0625
3
using Racing.Mathematics; using System; using System.Collections.Generic; using System.Linq; using static System.Math; namespace Racing.CircuitGenerator { internal sealed class WaypointsGenerator { private readonly int min; private readonly int max; private readonly Random random; private readonly double minimumDistance; public WaypointsGenerator(int min, int max, Random random, double minimumDistance) { this.min = min; this.max = max; this.random = random; this.minimumDistance = minimumDistance; } public IEnumerable<Vector> GenerateSimpleCircuit(double width, double height) { yield return new Vector(0.5 * width, minimumDistance); yield return new Vector(width - minimumDistance, minimumDistance); yield return new Vector(width - minimumDistance, 0.5 * height); yield return new Vector(width - minimumDistance, height - minimumDistance); yield return new Vector(0.5 * width, height - minimumDistance); yield return new Vector(minimumDistance, height - minimumDistance); yield return new Vector(minimumDistance, 0.5 * height); yield return new Vector(minimumDistance, minimumDistance); } public IEnumerable<Vector> Generate(double width, double height) { var numberOfPoints = random.Next(min, max); var randomPoints = generateRandomPoints(numberOfPoints, width, height); var dataSet = computeConvexHull(randomPoints); pushApart(dataSet, n: 5); dataSet = insertRandomMidpoints(dataSet); pushApart(dataSet, n: 5); trySelectPointOnTheLongestStraightAsStart(dataSet); return dataSet; } private List<Vector> generateRandomPoints(int numberOfPoints, double width, double height) => Enumerable.Range(0, numberOfPoints) .Select(_ => new Vector( x: 2 * minimumDistance + random.NextDouble() * (width - 4 * minimumDistance), y: 2 * minimumDistance + random.NextDouble() * (height - 4 * minimumDistance))) .ToList(); private static List<Vector> computeConvexHull(List<Vector> points) { points.Sort( (a, b) => a.X == b.X ? a.Y.CompareTo(b.Y) : -a.X.CompareTo(b.X)); var hull = new List<Vector>(); int L = 0, U = 0; for (int i = points.Count - 1; i >= 0; i--) { Vector p = points[i], p1; while (L >= 2 && ((p1 = hull.Last()) - hull[hull.Count - 2]).Cross(p - p1) >= 0) { hull.RemoveAt(hull.Count - 1); L--; } hull.Add(p); L++; while (U >= 2 && ((p1 = hull.First()) - hull[1]).Cross(p - p1) <= 0) { hull.RemoveAt(0); U--; } if (U != 0) { hull.Insert(0, p); } U++; } hull.RemoveAt(hull.Count - 1); hull.Reverse(); return hull.ToList(); } private void pushApart(IList<Vector> points, int n) { for (var i = 0; i < n; i++) { pushApart(points); } } private void pushApart(IList<Vector> points) { var dst2 = minimumDistance * minimumDistance; for (int i = 0; i < points.Count; ++i) { for (int j = i + 1; j < points.Count; ++j) { if (points[i].DistanceSq(points[j]) < dst2) { var direction = points[j] - points[i]; var distance = direction.CalculateLength(); var shiftDistance = minimumDistance - distance; var displacement = shiftDistance * direction.Normalize(); points[j] = points[j] + displacement; points[i] = points[i] - displacement; } } } } private List<Vector> insertRandomMidpoints(IList<Vector> dataSet) { var extendedDataSet = new List<Vector>(dataSet.Count * 2); var difficulty = random.NextDouble(); var maxDisp = minimumDistance / 2; for (int i = 0; i < dataSet.Count; ++i) { var displacementLength = (float)Math.Pow(random.NextDouble(), difficulty) * maxDisp; var displacement = new Vector(0, 1).Rotate(random.NextDouble() * 2 * Math.PI); var midpoint = 0.5 * (dataSet[i] + dataSet[(i + 1) % dataSet.Count]); extendedDataSet.Add(dataSet[i]); extendedDataSet.Add(midpoint + displacementLength * displacement); } return extendedDataSet; } private static void trySelectPointOnTheLongestStraightAsStart(List<Vector> dataSet) { var maxLength = -1.0; var maxIndex = -1; for (int i = 0; i < dataSet.Count; i++) { var prev = dataSet[(i - 1 + dataSet.Count) % dataSet.Count]; var next = dataSet[(i + 1) % dataSet.Count]; var curr = dataSet[i]; var a = curr - prev; var b = next - curr; var lengthA = a.CalculateLength(); var lengthB = b.CalculateLength(); var angle = Acos(a.Dot(b) / (lengthA * lengthB)); if (angle < Math.PI / 6 && maxLength < lengthA + lengthB) { maxLength = lengthA + lengthB; maxIndex = i; } } if (maxIndex > 0) { for (int i = 0; i < maxIndex; i++) { var usedToBeFirst = dataSet[0]; dataSet.RemoveAt(0); dataSet.Add(usedToBeFirst); } } } } }
8c221574565b92c7a888a18f26c697d9ac66b19a
C#
rodwestmoreland/1150
/SDLessonsB/06_InheritenceClasses/People/Customer.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _06_InheritenceClasses.People { public class Customer:User { public int CustId { get; set; } public Customer(string email):base(email) { CustId = 0; } } }
c7757be8e17c212bc561c6b5b8b1ae15adbe1aea
C#
ahsanGoheer/Chess-Consortium-Manager
/BusinessLogicLayer/Manager.cs
3
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Data; using System.Text; using System.Threading.Tasks; using DataLayer; namespace BusinessLogicLayer { public class Manager //Facade controller as Singleton. { //Attributes. private static readonly object padlock = new object(); private static Manager instance = null; ArrayList onGoingGames = new ArrayList(9); //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- //Constructor. private Manager() { } //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- //Returns the only instance of the facade controller. public static Manager Instance { get { lock(padlock) { if(instance==null) { instance = new Manager(); } return instance; } } } //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- //Methods for Managing Players. public bool registerNewPlayer(Player newPlayer) { bool alreadyRegistered = true; DatabaseHandler registrationHandler = new DatabaseHandler(); if (!playerRegistered(newPlayer.CNIC)) { string playerInsertQuery = $"Insert into Player(PlayerName,PlayerCnic) values('{newPlayer.PlayerName}','{newPlayer.CNIC}')"; int status=registrationHandler.InsertQuery(playerInsertQuery); //registeredPlayers.Add(newPlayer); if(status==1) { PlayerStats newPlayerStats = new PlayerStats(newPlayer.CNIC); string playerStatsInsertQuery = $"Insert into PlayerStats(PlayerID,GamesPlayed,GamesWon,GamesLost,GamesDrawn) values('{newPlayerStats.CNIC}','{newPlayerStats.TotalGamesPlayed}','{newPlayerStats.TotalGamesWon}','{newPlayerStats.TotalGamesLost}','{newPlayerStats.TotalGamesDrawn}')"; registrationHandler.InsertQuery(playerStatsInsertQuery); registrationHandler.CloseConnection(); } alreadyRegistered = false; } return alreadyRegistered; } //---------------------------------------------------------------------------------------------- public ArrayList RankPlayers() { ArrayList statsList = fetchStats(); ArrayList Ranks = new ArrayList(10); statsList.Sort(new StatsComparer()); int counter = 0; if(statsList.Count>10) { counter = 10; } else { counter = statsList.Count-1; } for(int i=counter;i>0;i--) { string[] rankList = new string[3]; rankList[0] =(statsList[i] as PlayerStats).CNIC; rankList[1] = $"RANK: {(counter+1)-i}"; rankList[2]= (statsList[i] as PlayerStats).TotalGamesWon.ToString(); Ranks.Add(rankList); } return Ranks; } public string fetchName(string Cnic) { DatabaseHandler playerSearchHandler = new DatabaseHandler(); string query = $"Select PlayerName from Player where PlayerCnic='{Cnic}'"; DataSet playerData = playerSearchHandler.ExceuteQuerySet(query); playerSearchHandler.CloseConnection(); return playerData.Tables[0].Rows[0][0].ToString(); } //---------------------------------------------------------------------------------------------- public bool playerRegistered(string playerCnic) { bool isRegistered = false; if(playerCnic!="") { DatabaseHandler registrationHandler = new DatabaseHandler(); string query = "Select COUNT(PlayerCnic) from Player where PlayerCnic= '" + playerCnic + "'"; object result = registrationHandler.SpecificQuery(query); int count = (int)result; if (count == 1) { isRegistered = true; } registrationHandler.CloseConnection(); } return isRegistered; } //---------------------------------------------------------------------------------------------- public ArrayList fetchStats() { ArrayList locatedStats=new ArrayList(); DatabaseHandler playerStatsHandler = new DatabaseHandler(); string query = $"Select * from PlayerStats"; DataSet statsData = playerStatsHandler.ExceuteQuerySet(query); playerStatsHandler.CloseConnection(); foreach (DataRow temp in statsData.Tables[0].Rows) { string cnic = temp[0].ToString(); string TotalGamesPlayed = temp[1].ToString(); string GamesWon = temp[2].ToString(); string GamesLost = temp[3].ToString(); string GamesDrawn = temp[4].ToString(); PlayerStats fetchedStats = new PlayerStats(cnic, int.Parse(TotalGamesPlayed), int.Parse(GamesWon), int.Parse(GamesLost), int.Parse(GamesDrawn)); locatedStats.Add(fetchedStats); } return locatedStats; } //---------------------------------------------------------------------------------------------- public string searchPlayer(string playerCnic) { string Info = null; Player locatedPlayer = null; DatabaseHandler playerSearchHandler = new DatabaseHandler(); string query = $"Select p.PlayerCnic,p.PlayerName,ps.GamesPlayed,ps.GamesWon,ps.GamesLost,ps.GamesDrawn from dbo.Player p JOIN dbo.PlayerStats ps ON p.PlayerCnic = ps.PlayerID where p.PlayerCnic='{playerCnic}'"; DataSet playerData = playerSearchHandler.ExceuteQuerySet(query); playerSearchHandler.CloseConnection(); if(playerData.Tables[0].Rows.Count!=0) { locatedPlayer = new Player(playerData.Tables[0].Rows[0][1].ToString(), playerData.Tables[0].Rows[0][0].ToString()); Info = locatedPlayer.getPlayerInfo(); PlayerStats locatedPlayerStats = new PlayerStats(playerData.Tables[0].Rows[0][0].ToString(),(int)playerData.Tables[0].Rows[0][2],(int)playerData.Tables[0].Rows[0][3],(int)playerData.Tables[0].Rows[0][4],(int)playerData.Tables[0].Rows[0][5]); Info += locatedPlayerStats.printStats(); } return Info; } //---------------------------------------------------------------------------------------------- public string searchPlayerByName(string playerName) { string Info = null; Player locatedPlayer = null; DatabaseHandler playerSearchHandler = new DatabaseHandler(); string query = $"Select p.PlayerCnic,p.PlayerName,ps.GamesPlayed,ps.GamesWon,ps.GamesLost,ps.GamesDrawn from dbo.Player p JOIN dbo.PlayerStats ps ON p.PlayerCnic = ps.PlayerID where p.PlayerName='{playerName}'"; DataSet playerData = playerSearchHandler.ExceuteQuerySet(query); playerSearchHandler.CloseConnection(); if (playerData.Tables[0].Rows.Count != 0) { Info = ""; foreach(DataRow temp in playerData.Tables[0].Rows) { locatedPlayer = new Player(temp[1].ToString(), temp[0].ToString()); Info += "*************************\n"; Info += locatedPlayer.getPlayerInfo(); PlayerStats locatedPlayerStats = new PlayerStats(temp[0].ToString(), (int)temp[2], (int)temp[3], (int)temp[4], (int)temp[5]); Info += locatedPlayerStats.printStats(); } } return Info; } //---------------------------------------------------------------------------------------------- public string viewAllRegisteredPlayer() { string playerInformation = null; DatabaseHandler registeredPlayerHandler = new DatabaseHandler(); string query = "Select p.PlayerCnic,p.PlayerName,ps.GamesPlayed,ps.GamesWon,ps.GamesLost,ps.GamesDrawn from dbo.Player p JOIN dbo.PlayerStats ps ON p.PlayerCnic = ps.PlayerID"; DataSet registeredPlayerData = registeredPlayerHandler.ExceuteQuerySet(query); registeredPlayerHandler.CloseConnection(); if(registeredPlayerData.Tables[0].Rows.Count!=0) { foreach(DataRow temp in registeredPlayerData.Tables[0].Rows) { Player fetchedPlayer = new Player(temp[1].ToString(), temp[0].ToString());//PLAYER NAME AND CNIC playerInformation += fetchedPlayer.getPlayerInfo(); PlayerStats fetchedPlayerStats = new PlayerStats(temp[0].ToString(),(int)temp[2],(int)temp[3],(int)temp[4],(int)temp[5]);//CNIC, GAMES PLAYED,GAMES WON,GAMES LOST,GAMES DRAWN playerInformation += fetchedPlayerStats.printStats(); playerInformation += "****************************************\n"; } } return playerInformation; } //---------------------------------------------------------------------------------------------- public ArrayList fetchRegisteredPlayers() { ArrayList PlayersList = new ArrayList(); DatabaseHandler registeredPlayerHandler = new DatabaseHandler(); string query = "Select p.PlayerCnic,p.PlayerName from dbo.Player p"; DataSet registeredPlayerData = registeredPlayerHandler.ExceuteQuerySet(query); registeredPlayerHandler.CloseConnection(); if (registeredPlayerData.Tables[0].Rows.Count != 0) { foreach (DataRow temp in registeredPlayerData.Tables[0].Rows) { Player fetchedPlayer = new Player(temp[1].ToString(), temp[0].ToString());//PLAYER NAME AND CNIC PlayersList.Add(fetchedPlayer); } } return PlayersList; } //---------------------------------------------------------------------------------------------- public List<string> tableIDs() { List<string> IDs = new List<string>(); foreach(Game temp in onGoingGames) { IDs.Add(temp.TableID); } return IDs; } //---------------------------------------------------------------------------------------------- public string getAllGames() { DatabaseHandler gamesRecordHandler = new DatabaseHandler(); string query = "Select * from Game"; DataSet gameData = gamesRecordHandler.ExceuteQuerySet(query); gamesRecordHandler.CloseConnection(); string info = null; if (gameData.Tables[0].Rows.Count != 0) { info = ""; foreach (DataRow temp in gameData.Tables[0].Rows) { Game fetchedPlayer = new Game();//PLAYER NAME AND CNIC fetchedPlayer.TableID = temp[0].ToString(); fetchedPlayer.DateTimeOfGame = (DateTime)temp[1]; fetchedPlayer.Outcome = byte.Parse(temp[2].ToString()); fetchedPlayer.PlayerOneCnic = temp[3].ToString(); fetchedPlayer.PlayerTwoCnic = temp[4].ToString(); info += fetchedPlayer.GetTableInfo(); info += "**************************************\n"; } } return info; } public string getGame(DateTime gameDate) { DatabaseHandler gamesRecordHandler = new DatabaseHandler(); string query = $"Select * from Game where DateTimeOfGame >'{gameDate}' and DateTimeOfGame<'{gameDate.AddDays(1)}'"; DataSet gameData = gamesRecordHandler.ExceuteQuerySet(query); gamesRecordHandler.CloseConnection(); string info = null; if (gameData.Tables[0].Rows.Count != 0) { info = ""; foreach (DataRow temp in gameData.Tables[0].Rows) { Game fetchedPlayer = new Game();//PLAYER NAME AND CNIC fetchedPlayer.TableID = temp[0].ToString(); fetchedPlayer.DateTimeOfGame = (DateTime)temp[1]; fetchedPlayer.Outcome = byte.Parse(temp[2].ToString()); fetchedPlayer.PlayerOneCnic = temp[3].ToString(); fetchedPlayer.PlayerTwoCnic = temp[4].ToString(); info += fetchedPlayer.GetTableInfo(); info += "**************************************\n"; } } return info; } //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- //Manager Control Methods. public void deleteAPlayer(string Cnic) { if(playerRegistered(Cnic)) { DatabaseHandler playerDeletionHandler = new DatabaseHandler(); string query = $"Delete from PlayerStats where PlayerID='{Cnic}'"; playerDeletionHandler.UpdateQuery(query); string playerDeleteQuery = $"Delete from Player where PlayerCnic='{Cnic}'"; playerDeletionHandler.UpdateQuery(playerDeleteQuery); } else { throw new NoDataToShowException("Player not registered!"); } } //---------------------------------------------------------------------------------------------- public void assignOutcome(string TableId,byte choice) { for (int index = 0; index < onGoingGames.Count; index++) { if (TableId == (onGoingGames[index] as Game).TableID) { Game temp = onGoingGames[index] as Game; temp.Outcome = choice; if (choice == 1) { updateStats(temp.PlayerOneCnic, 1); updateStats(temp.PlayerTwoCnic, 2); } else if (choice == 2) { updateStats(temp.PlayerOneCnic, 2); updateStats(temp.PlayerTwoCnic, 1); } else if (choice == 3) { updateStats(temp.PlayerOneCnic, 3); updateStats(temp.PlayerTwoCnic, 3); } if(InsertGame(temp)) { onGoingGames.Remove(temp); } break; } } } //---------------------------------------------------------------------------------------------- public bool InsertGame(Game newGame) { DatabaseHandler gameRecordHandler = new DatabaseHandler(); string query = $"Insert into Game(TableID,PlayerOneCnic,PlayerTwoCnic,DateTimeOfGame,Outcome) values('{newGame.TableID}','{newGame.PlayerOneCnic}','{newGame.PlayerTwoCnic}','{newGame.DateTimeOfGame}',{newGame.Outcome})"; int status =gameRecordHandler.InsertQuery(query); gameRecordHandler.CloseConnection(); if(status==1) { return true; } return false; } //---------------------------------------------------------------------------------------------- public void updateStats(string cnic, byte outcome) { DatabaseHandler statsOutcomeHandler = new DatabaseHandler(); string query = $"Select * from PlayerStats where PlayerId='{cnic}'"; DataSet fetchedStats = statsOutcomeHandler.ExceuteQuerySet(query); bool outcomeAssigned = false; if (fetchedStats.Tables[0].Rows.Count != 0) { DataRow statsDataRow = fetchedStats.Tables[0].Rows[0]; PlayerStats reqStats = new PlayerStats(statsDataRow[0].ToString(), (int)statsDataRow[1], (int)statsDataRow[2], (int)statsDataRow[3], (int)statsDataRow[4]); if (reqStats.CNIC.Trim() == cnic.Trim()) { if (outcome == 1) { reqStats.gameWon(); outcomeAssigned = true; } else if (outcome == 2) { reqStats.gameLost(); outcomeAssigned = true; } else if (outcome == 3) { reqStats.gameDrawn(); outcomeAssigned = true; } } if (outcomeAssigned) { string updateQuery = $"Update PlayerStats set GamesPlayed={reqStats.TotalGamesPlayed}, GamesWon={reqStats.TotalGamesWon},GamesLost={reqStats.TotalGamesLost},GamesDrawn={reqStats.TotalGamesDrawn} where PlayerID='{reqStats.CNIC}'"; statsOutcomeHandler.UpdateQuery(updateQuery); statsOutcomeHandler.CloseConnection(); } } } //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- //Methods for Managing Tables. public bool assignGame(Game assignedgame ) { Game newGame = assignedgame; bool gameAssigned = false; if (!isAlreadyPlaying(newGame.PlayerOneCnic) && !isAlreadyPlaying(newGame.PlayerTwoCnic)) { if (playerRegistered(newGame.PlayerOneCnic) && newGame.PlayerTwoCnic == null) { if (isPending()) { Game temp = null; Game temp2 = null; for (int index = 0; index < onGoingGames.Count; index++) { if ((onGoingGames[index] as Game).PlayerTwoCnic == null) { temp = onGoingGames[index] as Game; temp.PlayerTwoCnic = newGame.PlayerOneCnic; temp.DateTimeOfGame = DateTime.Now; temp2 = newGame; temp2.TableID = temp.TableID; gameAssigned = true; break; } } } else { if (isAvailable()) { newGame.setTableID(); onGoingGames.Add(newGame); gameAssigned = true; } else { gameAssigned = false ; } } } else if ((playerRegistered(newGame.PlayerOneCnic) && playerRegistered(newGame.PlayerTwoCnic)) && newGame.PlayerTwoCnic != null) { if (isPending()) { Game temp = null; for (int index = 0; index < onGoingGames.Count; index++) { if ((onGoingGames[index] as Game).PlayerTwoCnic == null) { temp = onGoingGames[index] as Game; temp.PlayerOneCnic = newGame.PlayerOneCnic; temp.PlayerTwoCnic = newGame.PlayerTwoCnic; temp.DateTimeOfGame = DateTime.Now; gameAssigned = true; break; } } } else { if (isAvailable()) { newGame.setTableID(); onGoingGames.Add(newGame); gameAssigned = true; } } } } else { gameAssigned = false; } return gameAssigned; } //---------------------------------------------------------------------------------------------- public bool isAlreadyPlaying(string playerCnic) { bool check = false; for (int index = 0; index < onGoingGames.Count; index++) { Game temp = onGoingGames[index] as Game; if (playerCnic == temp.PlayerOneCnic && temp.PlayerOneCnic != null) { check = true; break; } else if (playerCnic == temp.PlayerTwoCnic && temp.PlayerTwoCnic != null) { check = true; break; } } return check; } //---------------------------------------------------------------------------------------------- public bool isPending() { bool isPendingOpponent = false; for (int index = 0; index < onGoingGames.Count; index++) { if ((onGoingGames[index] as Game).PlayerTwoCnic == null) { isPendingOpponent = true; break; } } return isPendingOpponent; } //---------------------------------------------------------------------------------------------- public bool isAvailable() { bool hasTable = false; if (onGoingGames.Count < 9) { hasTable = true; } return hasTable; } //---------------------------------------------------------------------------------------------- public string showTableInfo() { string tablesInfo =""; for (int index = 0; index < onGoingGames.Count; index++) { Game onGoingGame = onGoingGames[index] as Game; tablesInfo += onGoingGame.GetTableInfo(); tablesInfo += "*************************************\n"; } return tablesInfo; } //---------------------------------------------------------------------------------------------- public string getTableData(string TableId) { string tableData = null; for(int index=0;index<onGoingGames.Count;index++) { Game onGoingGame = onGoingGames[index] as Game; if(onGoingGame.TableID==TableId) { tableData = onGoingGame.GetTableInfo(); break; } } return tableData; } //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- ////Check if table is occupied. public bool isOccupied(string TableID) { bool check = false; Game requiredGame = null; foreach(Game temp in onGoingGames) { if(TableID==temp.TableID) { requiredGame = temp; } } if(requiredGame.PlayerOneCnic!=null&&requiredGame.PlayerTwoCnic!=null) { check = true; } return check; } //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- }//End Class. }//End Namespace.
8c4032a7d795c5b08cf1456e2caa593b6c77b092
C#
aiyanhe/yanhe
/030-练习/Program.cs
3.890625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _030_练习 { class Program { static void Main(string[] args) { //1:编写一个程序,对输入的4个整数,求出其中的最大值和最小值,并显示出来; //Console.WriteLine("请输入4个整数"); //Console.WriteLine("请输入第一个整数"); //int num1 = int.Parse(Console.ReadLine()); //Console.WriteLine("请输入第二个整数"); //int num2 = int.Parse(Console.ReadLine()); //Console.WriteLine("请输入第三个整数"); //int num3 = int.Parse(Console.ReadLine()); //Console.WriteLine("请输入第四个整数"); //int num4 = int.Parse(Console.ReadLine()); //int max1 = num1 > num2 ? num1 : num2; //int max2 = num3 > num4 ? num3 : num4; //int max = max1 > max2 ? max1 : max2; //int min1 = num1 < num2 ? num1 : num2; //int min2 = num3 < num4 ? num3 : num4; //int min = min1 < min2 ? min1 : min2; //Console.WriteLine("最大数:" + max + "\n" + "最小数:" + min); //Console.ReadKey(); //2:让用户输入两个整数,然后再输入0~3之间的一个数,0代表加,1代表-,*代表乘法; //Console.WriteLine("请输入2个整数"); //Console.WriteLine("请输入第一个整数"); //int num1 = int.Parse(Console.ReadLine()); //Console.WriteLine("请输入第二个整数"); //int num2 = int.Parse(Console.ReadLine()); //Console.WriteLine("選擇0,1,*(0代表加,1代表-,*代表乘法)"); //string str = Console.ReadLine(); //int sum = 0; //if (str == "0") { // sum = num1 + num2; //} //if (str == "1") //{ // sum = num1 - num2; //} //if (str == "*") //{ // sum = num1 * num2; //} //Console.WriteLine(sum); //Console.ReadKey(); //3:求出1~1000之间的所有能被7整除的数,并计算和输出每5个的和; //int num = 0; //int n1 = 0, n2 = 0, n3 = 0, n4 = 0, sum = 0; //for (int i = 0; i <= 1000; i++) //{ // if (i % 7 == 0) // { // num++; // if (num == 1) // { // n1 = i; // } // if (num == 2) // { // n2 = i; // } // if (num == 3) // { // n3 = i; // } // if (num == 4) // { // n4 = i; // } // if (num == 5) // { // sum = n1 + n2 + n3 + n4 + i; // Console.WriteLine(sum); // num = 0; // } // } //} //Console.ReadKey(); //4:编写一个控制台程序,分别输出1~100之间的平方、平方根; //double a, b; //for (int i =0;i<=100;i++) { // a = i * i; // b =Math.Sqrt(i); // Console.WriteLine(i+"的平方:"+a); // Console.WriteLine(i + "的平方根:" + b); //} //Console.ReadKey(); //5:兔子繁殖问题,设有一对新生的兔子,从第三个月开始他们每个月都生一对兔子,新生的兔子从第三个月开始又每个月生一对兔子。按此规律, //并假定兔子没有死亡,20个月后共有多少个兔子?要求编写为控制台程序。 //b: // Console.WriteLine("请输入月数"); // string a = Console.ReadLine(); // int yueShu = Convert.ToInt32(a); // int yue = 1; // int duiSu = 1; // bool chengNian = false; // int chengShuo = 0; // int shengZhizhouqi = 1; // while (yue <= yueShu) // { // //在第三个月时 // if (yue >= 3) // { // if (shengZhizhouqi >= 3) // { // chengNian = true; // } // //计算成熟的兔子数; // if (chengNian) // { // chengNian = false; // chengShuo++; // shengZhizhouqi = 1; // } // duiSu = duiSu + chengShuo; // } // yue++; // shengZhizhouqi++; // } // Console.WriteLine(yueShu + "个月后共有" + duiSu * 2 + "个兔子"); // goto b; //6:编程输出1~100中能被3整除但不能被5整除的数,并统计有多少个这样的数。 //int sum = 0; //for (int i = 0;i<=100; i++) { // if (i % 3 == 0 && i % 5 != 0) { // sum++; // } //} //Console.WriteLine(sum); //Console.ReadKey(); // 7:编程输出1000以内的所有素数; // int s = 0; //for (int i = 1; i <1000; i++) //{ // s = 0; // for (int t = 2; t <= i; t++) // { // if (i % t == 0) // { // s += t; // } // } // if (s == i) // { // Console.WriteLine(i); // } //} //Console.ReadKey(); //8:编程输出九九乘法表; //int sum; //for (int a = 0; a <= 9; a++) //{ // for (int b = a; b <= 9; b++) // { // sum = a * b; // Console.Write(a + "乘" + b + "等于" + sum); // } //} //Console.ReadKey(); //9:编写一个投骰子100次的程序,并打印出各种点数的出现次数; //Random ran = new Random(); //int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; //for (int i = 0; i <= 100; i++) //{ // int RandKey = ran.Next(1, 7); // switch (RandKey) // { // case 1: // a++; // break; // case 2: // b++; // break; // case 3: // c++; // break; // case 4: // d++; // break; // case 5: // e++; // break; // case 6: // f++; // break; // default: // break; // } //} //Console.WriteLine("点数1出现的次数:" + a + "\n点数2出现的次数:" + b + "\n点数3出现的次数:" + c + "\n点数4出现的次数:" + d + "\n点数5出现的次数:" + e + "\n点数6出现的次数:" + f); //Console.ReadKey(); //10:一个控制台应用程序,输出1~5的平方值,要求:用for语句实现。用while语句实现。用do-while语句实现; //int sum; //for (int i=1;i<=5;i++) { // sum = i * i; // Console.WriteLine(i+"的平方值为"+sum); //} //int i = 1; //while (i <= 5) { // sum = i * i; // Console.WriteLine(i + "的平方值为" + sum); // i++; //} //do { // sum = i * i; // Console.WriteLine(i + "的平方值为" + sum); // i++; //} while (i <= 5); //Console.ReadKey(); ////11:一个控制台应用程序,要求用户输入5个大写字母,如果用户输入的信息不满足要求,提示帮助信息并要求重新输入。 // Console.WriteLine("请输入用户名(请输入大写字母)"); // string str = Console.ReadLine(); // int length = str.Length; // int num; // for (int i = 0; i <= length; i++) { // num = str[i]; //// if (num <= 'Z' || num >= 'A') { // if (num <= 65 || num >= 90) { // str = ""; // Console.WriteLine("请重新输入(大写字母)"); // str = Console.ReadLine(); // i = 0; // } //} // Console.WriteLine("用户名为:"+str); // Console.ReadKey(); //12:一个控制台应用程序,要求完成写列功能。 //1)接受一个整数n。 //2)如果接收的值n为正数,输出1~n见的全部整数。 //3)如果接收的值n为负值,用break或者return退出程序。 //4)如何n为0的话,转到1继续接收下一个整数。 //l: //Console.WriteLine("请输入一个正整数"); //int n = Convert.ToInt32(Console.ReadLine()); //if (n > 0) { // for (int i = 1; i <= n;i++ ) { // Console.WriteLine(i); // } // Console.ReadKey(); //} //if (n < 0) { // return; //} //if (n == 0) { // goto l; //} //13:一个控制台应用程序,求1000之间的所有"完数",所谓”完数“是指一个数恰好等于它的所以因子之和,例如6是完数,因为6=1+2+3; // int s = 0; // for (int i = 1; i < 1000; i++) { // s = 0; // for (int t = 1; t < i; t++) { // if (i % t == 0) { // s += t; // } // } // if (s == i) // { // Console.WriteLine(i); // } // } // Console.ReadKey(); } } }
fd2ae69dde183bd8025424cdb3c4822c997de6b4
C#
Brayconn/PixelModdingFramework
/PixelModdingFramework/Rendering.cs
2.828125
3
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace PixelModdingFramework { public static partial class Rendering { public const int TilesetWidth = 16; public const int TilesetHeight = 16; #region Byte public static Image RenderTiles<T>(IMap<Int16, T, Byte> tileSource, Bitmap tileset, int tileSize, CompositingMode mode = CompositingMode.SourceOver) where T : IList<Byte> { Image img = new Bitmap(tileSource.Width * tileSize, tileSource.Height * tileSize); RenderTiles(img, tileSource, tileset, tileSize, mode); return img; } public static void RenderTiles<T>(Image i, IMap<Int16, T, Byte> tileSource, Bitmap tileset, int tileSize, CompositingMode mode = CompositingMode.SourceOver) where T : IList<Byte> { using(Graphics g = Graphics.FromImage(i)) { g.CompositingMode = mode; RenderTiles(g, tileSource, tileset, tileSize); } } public static void RenderTiles<T>(Graphics g, IMap<Int16, T, Byte> tileSource, Bitmap tileset, int tileSize) where T : IList<Byte> { for (int i = 0; i < (tileSource.Width * tileSource.Height); i++) { DrawTile(g, tileSource, i, tileset, tileSize); } } public static void DrawTile<T>(Image img, IMap<Int16, T, Byte> tileSource, int i, Bitmap tileset, int tileSize, CompositingMode mode = CompositingMode.SourceOver) where T : IList<Byte> { using (Graphics g = Graphics.FromImage(img)) { g.CompositingMode = mode; DrawTile(g, tileSource, i, tileset, tileSize); } } public static void DrawTile<T>(Graphics g, IMap<Int16, T, Byte> tileSource, int i, Bitmap tileset, int tileSize) where T : IList<Byte> { var x = (i % tileSource.Width) * tileSize; var y = (i / tileSource.Width) * tileSize; g.DrawImage(GetTile((Byte)tileSource.Tiles[i], tileset, tileSize), x, y, tileSize, tileSize); } #endregion Byte #region Nullable<Byte> public static Image RenderTiles<T>(IMap<Int16, T, Nullable<Byte>> tileSource, Bitmap tileset, int tileSize, CompositingMode mode = CompositingMode.SourceOver) where T : IList<Nullable<Byte>> { Image img = new Bitmap(tileSource.Width * tileSize, tileSource.Height * tileSize); RenderTiles(img, tileSource, tileset, tileSize, mode); return img; } public static void RenderTiles<T>(Image i, IMap<Int16, T, Nullable<Byte>> tileSource, Bitmap tileset, int tileSize, CompositingMode mode = CompositingMode.SourceOver) where T : IList<Nullable<Byte>> { using(Graphics g = Graphics.FromImage(i)) { g.CompositingMode = mode; RenderTiles(g, tileSource, tileset, tileSize); } } public static void RenderTiles<T>(Graphics g, IMap<Int16, T, Nullable<Byte>> tileSource, Bitmap tileset, int tileSize) where T : IList<Nullable<Byte>> { for (int i = 0; i < (tileSource.Width * tileSource.Height); i++) { if(tileSource.Tiles[i] != null) DrawTile(g, tileSource, i, tileset, tileSize); } } public static void DrawTile<T>(Image img, IMap<Int16, T, Nullable<Byte>> tileSource, int i, Bitmap tileset, int tileSize, CompositingMode mode = CompositingMode.SourceOver) where T : IList<Nullable<Byte>> { using (Graphics g = Graphics.FromImage(img)) { g.CompositingMode = mode; DrawTile(g, tileSource, i, tileset, tileSize); } } public static void DrawTile<T>(Graphics g, IMap<Int16, T, Nullable<Byte>> tileSource, int i, Bitmap tileset, int tileSize) where T : IList<Nullable<Byte>> { var x = (i % tileSource.Width) * tileSize; var y = (i / tileSource.Width) * tileSize; g.DrawImage(GetTile((Byte)tileSource.Tiles[i], tileset, tileSize), x, y, tileSize, tileSize); } #endregion Nullable<Byte> /// <summary> /// Gets a single tile from a tileset /// </summary> /// <param name="tileSource"></param> /// <param name="i"></param> /// <param name="tileset"></param> /// <param name="tileSize"></param> /// <returns></returns> public static Image GetTile(Byte tileValue, Bitmap tileset, int tileSize) { //yes, this is intentional to not use TilesetHeight var tilesetX = (tileValue % TilesetWidth) * tileSize; var tilesetY = (tileValue / TilesetWidth) * tileSize; return tileset.Clone(new Rectangle(tilesetX, tilesetY, tileSize, tileSize), PixelFormat.DontCare); } } }
dee3ad3b48a852e3d2aa143b3ef015ef804d34f3
C#
ghstahl/ASPNET4_InMemoryIdentity
/src/P5.IdentityServer3.Common/ScopeComparer.cs
2.640625
3
using System; using System.Collections.Generic; using IdentityServer3.Core.Models; namespace P5.IdentityServer3.Common { public class ScopeComparer : IEqualityComparer<Scope> { private StringComparison StringComparisonType { get; set; } public static ScopeComparer OrdinalIgnoreCase { get { return new ScopeComparer(StringComparison.OrdinalIgnoreCase); } } public ScopeComparer(StringComparison stringComparison = StringComparison.OrdinalIgnoreCase) { StringComparisonType = stringComparison; } public bool Equals(Scope x, Scope y) { if (ReferenceEquals(x, y)) return true; if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) return false; var compared = string.Compare(x.Name, y.Name, StringComparisonType) == 0 && x.AllowUnrestrictedIntrospection == y.AllowUnrestrictedIntrospection && x.Emphasize == y.Emphasize && x.Enabled == y.Enabled && x.Required == y.Required && x.ShowInDiscoveryDocument == y.ShowInDiscoveryDocument && x.Type == y.Type && string.Compare(x.Description, y.Description, StringComparisonType) == 0 && string.Compare(x.DisplayName, y.DisplayName, StringComparisonType) == 0 && string.Compare(x.ClaimsRule, y.ClaimsRule, StringComparisonType) == 0; return compared; } public int GetHashCode(Scope obj) { if (ReferenceEquals(obj, null)) return 0; int hashName = obj.Name == null ? 0 : obj.Name.GetHashCode(); return hashName ; } } }
fbafca5dfbe0b42d82bbf9de713a5982757bd3e9
C#
PavelDobranov/TelerikAcademy
/02-CSharp-Part-Two/07-ExceptionHandling/02.EnterNumbers/EnterNumbers.cs
4.125
4
// Problem 2. Enter numbers // Write a method ReadNumber(int start, int end) that enters an integer number in a given range [start…end]. // If an invalid number or non-number text is entered, the method should throw an exception. // Using this method write a program that enters 10 numbers: a1, a2, … a10, such that 1 < a1 < … < a10 < 100 using System; using System.Collections.Generic; class EnterNumbers { static int start = 1; static int end = 100; static void Main() { int[] numbersCollector = new int[10]; try { for (int i = 0; i < numbersCollector.Length; i++) { int number = GetNumber(start, end); numbersCollector[i] = number; start = number; } Console.WriteLine("Entered Numbers:\n[start-1] < {0} < [100-end]", string.Join(" < ", numbersCollector), end); } catch (FormatException) { Console.Error.WriteLine("Invalid Number!"); } catch (OverflowException) { Console.WriteLine("The Number Exceeds The Maximum Value Of Int32!"); } catch (ArgumentOutOfRangeException) { Console.WriteLine("The Number Is Not In Range!"); } } static int GetNumber(int start, int end) { Console.Write("Enter a number: "); int number = int.Parse(Console.ReadLine()); if (number <= start || number >= end) { throw new System.ArgumentOutOfRangeException(); } return number; } }
6219bb9edfd13f5a06b8f2b2ca8bc542c34ea907
C#
StanislavIT044/SoftUniCSharp
/C#OOP/TasksDuringTheHolidays/ExamProblem(exercise)/Core/Controller.cs
3.125
3
using SpaceStation.Core.Contracts; using SpaceStation.Models.Astronauts; using SpaceStation.Models.Astronauts.Contracts; using SpaceStation.Models.Mission; using SpaceStation.Models.Planets; using SpaceStation.Repositories; using SpaceStation.Repositories.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SpaceStation.Core { public class Controller : IController { private IRepository<IAstronaut> astronauts; private IRepository<IPlanet> planets; private int explorePlanetes; public Controller() { this.astronauts = new AstronautRepository(); this.planets = new PlanetRepository(); explorePlanetes = 0; } public string AddAstronaut(string type, string astronautName) { IAstronaut astronaut; if (type == "Biologist") { astronaut = new Biologist(astronautName); } else if (type == "Geodesist") { astronaut = new Geodesist(astronautName); } else if (type == "Meteorologist") { astronaut = new Meteorologist(astronautName); } else { throw new InvalidOperationException("Astronaut type doesn't exists!"); } astronauts.Add(astronaut); return $"Successfully added {type}: {astronautName}!"; } public string AddPlanet(string planetName, params string[] items) { IPlanet planet = new Planet(planetName, items); planets.Add(planet); return $"Successfully added Planet: {planetName}!"; } public string ExplorePlanet(string planetName) { List<IAstronaut> astronautsForMission = new List<IAstronaut>(); IMission mission = new Mission(); IPlanet planetToExplore = planets.FindByName(planetName); foreach (var astronaut in astronauts.Models) { if (astronaut.Oxygen > 60) { astronautsForMission.Add(astronaut); } } if (!astronautsForMission.Any()) { throw new InvalidOperationException("You need at least one astronaut to explore the planet"); } int deadAstronauts = astronautsForMission.Count(x => !x.CanBreath); mission.Explore(planetToExplore, astronautsForMission); this.explorePlanetes++; return $"Planet: {planetName} was explored! Exploration finished with {deadAstronauts} dead astronauts!"; } public string Report() { StringBuilder sb = new StringBuilder(); sb.AppendLine($"{explorePlanetes} planets were explored!"); sb.AppendLine($"Astronauts info:"); foreach (var astronaut in astronauts.Models) { sb.AppendLine($"Name: {astronaut.Name}"); sb.AppendLine($"Oxygen: {astronaut.Oxygen}"); if (astronaut.Bag.Items.Count == 0) { sb.AppendLine($"Bag items: none"); } else { sb.AppendLine($"Bag items: {string.Join(", ", astronaut.Bag.Items)}"); } } return sb.ToString().TrimEnd(); } public string RetireAstronaut(string astronautName) { IAstronaut astronaut = astronauts.FindByName(astronautName); if (astronaut != null) { astronauts.Remove(astronaut); } else { throw new InvalidOperationException($"Astronaut {astronautName} doesn't exists!"); } return $"Astronaut {astronautName} was retired!"; } } }
c0cec04fc78e1332ebf82a441ceb92bd6804b1e2
C#
funtechhackday/xrtd
/Assets/02.Scripts/Debug/DebugPanel.cs
2.546875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DebugPanel : MonoBehaviour { #region Singleton public static DebugPanel inst; private void Awake() { if (inst == null) inst = this; } #endregion public Text debugText; } public static class DPanel { public static void Add(MonoBehaviour script, string text) { if (DebugPanel.inst.debugText != null && DebugPanel.inst.debugText.isActiveAndEnabled) { var s = string.Format(" <color=green>{0}</color> <color=blue>[{1}]</color> {2}\n", Time.time, script.name, text); DebugPanel.inst.debugText.text = s + DebugPanel.inst.debugText.text; Debug.Log(s); } } }
5177cdf97dd47db6556e6e3a0e517774bfc9a279
C#
AHIRU2/MapAction
/Assets/Scripts/TimingGaugeController.cs
2.6875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using DG.Tweening; public class TimingGaugeController : MonoBehaviour { [SerializeField] private Slider slider; [SerializeField] private float pointerDuration; private Tween tween; // Start is called before the first frame update void Start() { MoveGaugePointer(); } /// <summary> /// ポインターのループ移動を開始 /// </summary> public void MoveGaugePointer() { tween = slider.DOValue(1.0f, pointerDuration).SetEase(Ease.Linear).SetLoops(-1, LoopType.Yoyo); } /// <summary> /// ポインターのループ移動を停止 /// </summary> public void StopPointer() { tween.Kill(); } /// <summary> /// ポインターの移動を一時停止 /// </summary> /// <returns></returns> public IEnumerator PausePointer() { tween.Pause(); yield return new WaitForSeconds(0.25f); ResumePointer(); } /// <summary> /// ポインターの移動を再開 /// </summary> public void ResumePointer() { tween.Play(); } /// <summary> /// クリティカルの判定、クリティカルならtrue /// </summary> /// <returns></returns> public bool CheckCritical() { return slider.value >= 0.45f && slider.value < 0.55f ? true : false; } }
01322eef9b447105c42cedba34c51c23de86ba7d
C#
2881099/dotnetGen_demo
/src/cd.db/DAL/Build/Testtypeinfo.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Threading.Tasks; using MySql.Data.MySqlClient; using cd.Model; namespace cd.DAL { public partial class Testtypeinfo : IDAL { #region transact-sql define public string Table { get { return TSQL.Table; } } public string Field { get { return TSQL.Field; } } public string Sort { get { return TSQL.Sort; } } internal class TSQL { internal static readonly string Table = "`testtypeinfo`"; internal static readonly string Field = "a.`Guid`, a.`Name`, a.`ParentId`, a.`SelfGuid`"; internal static readonly string Sort = "a.`Guid`"; internal static readonly string Returning = ""; internal static readonly string Delete = "DELETE FROM `testtypeinfo` WHERE "; internal static readonly string InsertField = @"`Guid`, `Name`, `ParentId`, `SelfGuid`"; internal static readonly string InsertValues = @"?Guid, ?Name, ?ParentId, ?SelfGuid"; internal static readonly string InsertMultiFormat = @"INSERT INTO `testtypeinfo`(" + InsertField + ") VALUES{0}"; internal static readonly string Insert = string.Format(InsertMultiFormat, $"({InsertValues}){Returning}"); } #endregion #region common call protected static MySqlParameter GetParameter(string name, MySqlDbType type, int size, object value) { MySqlParameter parm = new MySqlParameter(name, type); if (size > 0) parm.Size = size; parm.Value = value; return parm; } protected static MySqlParameter[] GetParameters(TesttypeinfoInfo item) { return new MySqlParameter[] { GetParameter("?Guid", MySqlDbType.Int32, 11, item.Guid), GetParameter("?Name", MySqlDbType.VarChar, 255, item.Name), GetParameter("?ParentId", MySqlDbType.Int32, 11, item.ParentId), GetParameter("?SelfGuid", MySqlDbType.Int32, 11, item.SelfGuid)}; } public TesttypeinfoInfo GetItem(IDataReader dr) { int dataIndex = -1; return GetItem(dr, ref dataIndex) as TesttypeinfoInfo; } public object GetItem(IDataReader dr, ref int dataIndex) { TesttypeinfoInfo item = new TesttypeinfoInfo(); if (!dr.IsDBNull(++dataIndex)) item.Guid = (int?)dr.GetInt32(dataIndex); if (item.Guid == null) { dataIndex += 3; return null; } if (!dr.IsDBNull(++dataIndex)) item.Name = dr.GetString(dataIndex); if (!dr.IsDBNull(++dataIndex)) item.ParentId = (int?)dr.GetInt32(dataIndex); if (!dr.IsDBNull(++dataIndex)) item.SelfGuid = (int?)dr.GetInt32(dataIndex); return item; } private void CopyItemAllField(TesttypeinfoInfo item, TesttypeinfoInfo newitem) { item.Guid = newitem.Guid; item.Name = newitem.Name; item.ParentId = newitem.ParentId; item.SelfGuid = newitem.SelfGuid; } #endregion public int Delete(int Guid) { return SqlHelper.ExecuteNonQuery(string.Concat(TSQL.Delete, "`Guid` = ?Guid"), GetParameter("?Guid", MySqlDbType.Int32, 11, Guid)); } public SqlUpdateBuild Update(TesttypeinfoInfo item, string[] ignoreFields) { var sub = new SqlUpdateBuild(new List<TesttypeinfoInfo> { item }); var ignore = ignoreFields?.ToDictionary(a => a, StringComparer.CurrentCultureIgnoreCase) ?? new Dictionary<string, string>(); if (ignore.ContainsKey("Name") == false) sub.SetName(item.Name); if (ignore.ContainsKey("ParentId") == false) sub.SetParentId(item.ParentId); if (ignore.ContainsKey("SelfGuid") == false) sub.SetSelfGuid(item.SelfGuid); return sub; } #region class SqlUpdateBuild public partial class SqlUpdateBuild { protected List<TesttypeinfoInfo> _dataSource; protected Dictionary<string, TesttypeinfoInfo> _itemsDic; protected string _fields; protected string _where; protected List<MySqlParameter> _parameters = new List<MySqlParameter>(); public SqlUpdateBuild(List<TesttypeinfoInfo> dataSource) { _dataSource = dataSource; _itemsDic = _dataSource == null ? null : _dataSource.ToDictionary(a => $"{a.Guid}"); if (_dataSource != null && _dataSource.Any()) this.Where(@"`Guid` IN ({0})", _dataSource.Select(a => a.Guid).Distinct()); } public SqlUpdateBuild() { } public override string ToString() { if (string.IsNullOrEmpty(_fields)) return string.Empty; if (string.IsNullOrEmpty(_where)) throw new Exception("防止 cd.DAL.Testtypeinfo.SqlUpdateBuild 误修改,请必须设置 where 条件。"); return string.Concat("UPDATE ", TSQL.Table, " SET ", _fields.Substring(1), " WHERE ", _where); } public int ExecuteNonQuery() { string sql = this.ToString(); if (string.IsNullOrEmpty(sql)) return 0; var affrows = SqlHelper.ExecuteNonQuery(sql, _parameters.ToArray()); BLL.Testtypeinfo.RemoveCache(_dataSource); return affrows; } async public Task<int> ExecuteNonQueryAsync() { string sql = this.ToString(); if (string.IsNullOrEmpty(sql)) return 0; var affrows = await SqlHelper.ExecuteNonQueryAsync(sql, _parameters.ToArray()); await BLL.Testtypeinfo.RemoveCacheAsync(_dataSource); return affrows; } public SqlUpdateBuild Where(string filterFormat, params object[] values) { if (!string.IsNullOrEmpty(_where)) _where = string.Concat(_where, " AND "); _where = string.Concat(_where, "(", SqlHelper.Addslashes(filterFormat, values), ")"); return this; } public SqlUpdateBuild WhereExists<T>(SelectBuild<T> select) { return this.Where($"EXISTS({select.ToString("1")})"); } public SqlUpdateBuild WhereNotExists<T>(SelectBuild<T> select) { return this.Where($"NOT EXISTS({select.ToString("1")})"); } public SqlUpdateBuild Set(string field, string value, params MySqlParameter[] parms) { if (value.IndexOf('\'') != -1) throw new Exception("cd.DAL.Testtypeinfo.SqlUpdateBuild 可能存在注入漏洞,不允许传递 ' 给参数 value,若使用正常字符串,请使用参数化传递。"); _fields = string.Concat(_fields, ", ", field, " = ", value); if (parms != null && parms.Length > 0) _parameters.AddRange(parms); return this; } public SqlUpdateBuild SetName(string value) { if (_dataSource != null) foreach (var item in _dataSource) item.Name = value; return this.Set("`Name`", $"?Name_{_parameters.Count}", GetParameter($"?Name_{_parameters.Count}", MySqlDbType.VarChar, 255, value)); } public SqlUpdateBuild SetParentId(int? value) { if (_dataSource != null) foreach (var item in _dataSource) item.ParentId = value; return this.Set("`ParentId`", $"?ParentId_{_parameters.Count}", GetParameter($"?ParentId_{_parameters.Count}", MySqlDbType.Int32, 11, value)); } public SqlUpdateBuild SetParentIdIncrement(int value) { if (_dataSource != null) foreach (var item in _dataSource) item.ParentId += value; return this.Set("`ParentId`", $"ifnull(`ParentId`, 0) + ?ParentId_{_parameters.Count}", GetParameter($"?ParentId_{_parameters.Count}", MySqlDbType.Int32, 11, value)); } public SqlUpdateBuild SetSelfGuid(int? value) { if (_dataSource != null) foreach (var item in _dataSource) item.SelfGuid = value; return this.Set("`SelfGuid`", $"?SelfGuid_{_parameters.Count}", GetParameter($"?SelfGuid_{_parameters.Count}", MySqlDbType.Int32, 11, value)); } public SqlUpdateBuild SetSelfGuidIncrement(int value) { if (_dataSource != null) foreach (var item in _dataSource) item.SelfGuid += value; return this.Set("`SelfGuid`", $"ifnull(`SelfGuid`, 0) + ?SelfGuid_{_parameters.Count}", GetParameter($"?SelfGuid_{_parameters.Count}", MySqlDbType.Int32, 11, value)); } } #endregion public TesttypeinfoInfo Insert(TesttypeinfoInfo item) { SqlHelper.ExecuteNonQuery(TSQL.Insert, GetParameters(item)); return item; } public int Insert(IEnumerable<TesttypeinfoInfo> items) { var mp = InsertMakeParam(items); if (string.IsNullOrEmpty(mp.sql)) return 0; return SqlHelper.ExecuteNonQuery(mp.sql, mp.parms); } public (string sql, MySqlParameter[] parms) InsertMakeParam(IEnumerable<TesttypeinfoInfo> items) { var itemsArr = items?.Where(a => a != null).ToArray(); if (itemsArr == null || itemsArr.Any() == false) return (null, null); var values = ""; var parms = new MySqlParameter[itemsArr.Length * 4]; for (var a = 0; a < itemsArr.Length; a++) { var item = itemsArr[a]; values += $",({TSQL.InsertValues.Replace(", ", a + ", ")}{a})"; var tmparms = GetParameters(item); for (var b = 0; b < tmparms.Length; b++) { tmparms[b].ParameterName += a; parms[a * 4 + b] = tmparms[b]; } } return (string.Format(TSQL.InsertMultiFormat, values.Substring(1)), parms); } #region async async public Task<TesttypeinfoInfo> GetItemAsync(MySqlDataReader dr) { var read = await GetItemAsync(dr, -1); return read.result as TesttypeinfoInfo; } async public Task<(object result, int dataIndex)> GetItemAsync(MySqlDataReader dr, int dataIndex) { TesttypeinfoInfo item = new TesttypeinfoInfo(); if (!await dr.IsDBNullAsync(++dataIndex)) item.Guid = (int?)dr.GetInt32(dataIndex); if (item.Guid == null) { dataIndex += 3; return (null, dataIndex); } if (!await dr.IsDBNullAsync(++dataIndex)) item.Name = dr.GetString(dataIndex); if (!await dr.IsDBNullAsync(++dataIndex)) item.ParentId = (int?)dr.GetInt32(dataIndex); if (!await dr.IsDBNullAsync(++dataIndex)) item.SelfGuid = (int?)dr.GetInt32(dataIndex); return (item, dataIndex); } public Task<int> DeleteAsync(int Guid) { return SqlHelper.ExecuteNonQueryAsync(string.Concat(TSQL.Delete, "`Guid` = ?Guid"), GetParameter("?Guid", MySqlDbType.Int32, 11, Guid)); } async public Task<TesttypeinfoInfo> InsertAsync(TesttypeinfoInfo item) { await SqlHelper.ExecuteNonQueryAsync(TSQL.Insert, GetParameters(item)); return item; } async public Task<int> InsertAsync(IEnumerable<TesttypeinfoInfo> items) { var mp = InsertMakeParam(items); if (string.IsNullOrEmpty(mp.sql)) return 0; return await SqlHelper.ExecuteNonQueryAsync(mp.sql, mp.parms); } #endregion } }
9ca8f35a3676ef1bf20ee4ee3485b270900b2d75
C#
iliqnk/OOP_HOMEWORKS
/DefiningClasses/02.LaptopShop/LaptopShop.cs
3.09375
3
using System; namespace _02.LaptopShop { class LaptopShop { static void Main() { Laptop basicLaptopInfo = new Laptop("HP 250 G2", 699.00M); Laptop fullLaptopInfo = new Laptop("Lenovo Yoga 2 Pro", 2259.00M, "Lenovo", "Intel Core i5-4210U (2-core, 1.70 - 2.70 GHz, 3MB cache)", "8 GB", "Intel HD Graphics 4400", "128GB SSD", @"13.3"" (33.78 cm) – 3200 x 1800 (QHD+), IPS sensor display", new Battery("Li-Ion, 4-cells, 2550 mAh", 4.5)); Console.WriteLine(basicLaptopInfo); Console.WriteLine(); Console.WriteLine(fullLaptopInfo); } } }
8dc0a675c237141cb502b9b17999418d47c7e2c4
C#
Raksha2711/B2BAPI
/Core/ApiResponse/InfoMessage.cs
2.8125
3
using System; using System.Collections.Generic; using System.Text; namespace Core.ApiResponse { public class InfoMessage { public InfoMessage() : this(string.Empty, string.Empty) { } public InfoMessage(string message) : this("", message) { } public InfoMessage(string key, string message) { Title = key; MessageText = message; } public string Title { get; set; } public string MessageText { get; set; } public override string ToString() { return string.Format("{0}. Key: '{1}', Message: '{2}'", base.ToString(), Title, MessageText); } } }
5989fafdd490621cd93f54dce0c92018f8be2484
C#
bleissem/ReflectionMapper
/src/ReflectionMapper/MapConfig.cs
2.65625
3
using AutoMapper; using System; using System.Collections.Generic; using System.Text; namespace ReflectionMapper { /// <summary> /// Maps with configuration when Reading or Saving /// </summary> /// <typeparam name="MapTo"></typeparam> /// <typeparam name="MapFrom"></typeparam> public abstract class MapConfig<MapTo, MapFrom> : IMap<MapFrom> where MapTo : class where MapFrom : class { public virtual Action<IMappingExpression<MapFrom, MapTo>> AlterReadMapping() { return null; } public virtual Action<IMappingExpression<MapTo, MapFrom>> AlterSaveMapping() { return null; } } }
6db95fd8a7c09b450cf7154ba5913138099212cb
C#
MateuszSierpinski/Malform-Checker
/Test/Save.cs
2.953125
3
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Test { class Save:Form1 { public DataTable SaveFile(DataTable table,char delimiter) { using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "", ValidateNames = true }) { if (sfd.ShowDialog() == DialogResult.OK) { string path = sfd.FileName; TextWriter writer = new StreamWriter(path); for (int i = 0; i < table.Rows.Count; i++) { for (int j = 0; j < table.Columns.Count; j++) { writer.Write(table.Rows[i].ItemArray[j].ToString() + delimiter); } writer.Write("\n"); } writer.Close(); MessageBox.Show("Data Exported"); } return table; } } } }
5aa9ee3a1fb19234dfb228385f18deb2c6e539a2
C#
AbdulmajidAlnouri/Open-Projects
/C#/Kaggle Project/Neural Network API/Genetic Neural Network API/Genetic Neural Network API/Utilities/Extenstions.cs
3.65625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Genetic_Neural_Network_API.Utilities { public static class Extensions { public static T RandomElement<T>(this IEnumerable<T> iEnumerable) { T result; //Get a random index to pull from. uint randomElementIndex = (uint)Config.RANDOM.Next(iEnumerable.Count()); //Select the element at the X index and assign it to result. X:randomElementIndex. result = iEnumerable.ElementAt((int)randomElementIndex); return result; } public static T RandomElement<T>(this IEnumerable<T> enumerable, uint passedUpperRange) { //Store the size of the IEnumerable. int enumerableCount = enumerable.Count(); //If passedUpperRange is greater than the count of IEnumerable then throw an ArgumentOutOfRangeException. if (passedUpperRange > enumerableCount) { throw new ArgumentOutOfRangeException("passedUpperRange: " + passedUpperRange + " is greater than the count of the IEnumerable."); } //The result to return. T result; //Get a random index to pull from. uint randomElementIndex = (uint)Config.RANDOM.Next(enumerableCount); //Select the element at the X index and assign it to result. X:randomElementIndex. result = enumerable.ElementAt((int)randomElementIndex); //Return the result. return result; } } }
aa6bcc7880f2c4baaf675bc03264903b8ef251b8
C#
jwbnw/SmuTutoringApp
/smuTutoringDataApp/Classes/dataTables.cs
3.03125
3
using System; using System.Data; using System.Windows; namespace smuTutoringDataApp { public class dataTables { public static DataTable masterDataTable { get; set; } //************************************************* //Method Name: CreateTable //Description: This method creates the // data table that will be used to save // the final report. The reason we create // a separate datatable as opposed to editing // the main datatable is an extra safety measure. // That way we can check for data. //************************************************* public static void CreateTable() { // Create new Data Table DataTable UserDataTable = new DataTable(); // Assign columns with their names and data types UserDataTable.Columns.Add("Appointment", typeof(string)); UserDataTable.Columns.Add("StudentID", typeof(string)); UserDataTable.Columns.Add("Last name", typeof(string)); UserDataTable.Columns.Add("First name", typeof(string)); UserDataTable.Columns.Add("Semester", typeof(string)); UserDataTable.Columns.Add("Academic year", typeof(string)); UserDataTable.Columns.Add("Subject area", typeof(string)); UserDataTable.Columns.Add("Course Code", typeof(string)); UserDataTable.Columns.Add("Tutor Name", typeof(string)); UserDataTable.Columns.Add("Sign In Time", typeof(string)); UserDataTable.Columns.Add("Sign Out Time", typeof(string)); UserDataTable.Columns.Add("Total Time", typeof(string)); UserDataTable.Columns.Add("Activity", typeof(string)); UserDataTable.Columns.Add("Waiver", typeof(string)); // Check for data in the master data table, if null then assign columns if (masterDataTable == null) { masterDataTable = UserDataTable; } } //****************************************** //Method Name: WriteInData //Description: This method take in the //necessary data from a student signing //in and writes it to the master data table //This method does no editing of the data //it take as parameters, that must be done //elsewhere //******************************************* public static void WriteInData(string date, string studentId, string studentLastName, string studentFirstName, string semester, string academicYear, string subjectArea, string courseCode, string signInTime,string waiver) { masterDataTable.Rows.Add(date, studentId, studentLastName, studentFirstName, semester, academicYear, subjectArea, courseCode, "", signInTime ,"","","",waiver); } //****************************************************** //Method Name: CheckForOutEntery //Description: This method will check to see if //there is an entery within the sign out time column. //If there is no data there aka null, it will fill that //null space with an empty space. It then returns the //master table. //****************************************************** public static void checkForOutEntery() { //Check for null data DataRow[] result = masterDataTable.Select("[Sign Out Time] is null"); //Fill each entery in the data row array with the empty string for (int i = 0; i < result.Length; i++) { DataRow tempToOperate = result[i]; if (tempToOperate != null) { try { tempToOperate[10] = "N/A"; tempToOperate[8] = "N/A"; tempToOperate[11] = "N/A"; tempToOperate[12] = "N/A"; } catch { } if (i == result.Length - 1 && tempToOperate[12].ToString() == "N/A") { programSettings.saveReport(masterDataTable, programSettings.masterSaveLocationPath); } } } } //****************************************************** //Method Name: Waiver //Description: This method will check to see if //the student has signed the waiver to use the app yet //****************************************************** public static bool checkForWaiver(string userID) { DataRow[] rowArrayToMatch = masterDataTable.Select("studentID='" + userID + "'"); int latestEntry = rowArrayToMatch.Length; try { //Set data row to last entery, we subtract one do the the lenght property starting its count at 1 as opposed to 0 DataRow UserTest = rowArrayToMatch[latestEntry - 1]; } catch { //return value as fals return false; } try { // Set the data row to edit DataRow studentIdMatch = rowArrayToMatch[latestEntry - 1]; // set a check to see if the user signed in string Wcheck = studentIdMatch[13].ToString(); if (Wcheck == "Yes") { return true; } else { return false; } } catch { return false; } } //*************************************************************** //Method Name: WriteTheOutData //Description: This method takes in 4 arguments, the user ID, //the tutor name, the sign out time and the option for Peer //assisted learning. We take the user Id and user it to query //the master data table and pull a data row array of rows //related to the user ID. We then preform some checks described //below and add the final data to the master data table. //*************************************************************** public static void WriteOutData(string userID, string tutorName, string outTime) { // A check in the event that we want to abort writing the data bool NoSendAlert = false; // Create data row array DataRow[] rowArrayToMatch = masterDataTable.Select("studentID='" + userID + "'"); //Get length of data row array int latestEntry = rowArrayToMatch.Length; // Run a test to see if there is any data try { //Set data row to last entery, we subtract one do the the lenght property starting its count at 1 as opposed to 0 DataRow UserTest = rowArrayToMatch[latestEntry - 1]; } catch { //Set the no send alert NoSendAlert = true; } // In the event of the No sent alert being true we prompt the user with the most likly error. if (NoSendAlert == true) { MessageBox.Show("Error No Match Found? Did you sign in? Please try again or ask for assistence."); } // If the No send alert is false we continue on else { try { // Set the data row to edit DataRow studentIdMatch = rowArrayToMatch[latestEntry - 1]; // set a check to see if the user signed in string check = studentIdMatch[9].ToString(); string doubleCheck = studentIdMatch[10].ToString(); // Run check. if (check == "") { MessageBox.Show("Error Please sign in before trying to sign out!"); } // If check clears else { //Run check and doubleCheck to make sure we are not pulling the prior row that already has data if (check != "" && doubleCheck != "") { MessageBox.Show("Error Please sign in before trying to sign out!"); } else { string inTime = studentIdMatch[9].ToString(); //calculate total time TimeSpan duration = DateTime.Parse(outTime).Subtract(DateTime.Parse(inTime)); string totalTime = duration.ToString(); studentIdMatch[11] = totalTime; studentIdMatch[10] = outTime; studentIdMatch[8] = tutorName; if (studentIdMatch[7].ToString() == "Here To Study") { studentIdMatch[12] = "STUDY"; } else { studentIdMatch[12] = "STEM"; } } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } //**************************************************** //Method Name: SetMasterTable //Description: This program will set the master table //with a table that it reads in from a .csv file that //is provided via a parameter in the form of a string //***************************************************** public static void setMasterTable(string filePath) { //Run process in try-catch block try { //Check file path for data if (filePath != null) { //Build data table DataTable csvDt = new DataTable(); //Read .csv into string[] string[] csvRows = System.IO.File.ReadAllLines(filePath); string[] fields = null; //Take the header row and split it up string colHeaders = csvRows[0]; string[] headerFeilds = colHeaders.Split(','); //Check for column names and then Asign columns based on header names foreach (string column in headerFeilds) { DataColumn headers = new DataColumn(column); csvDt.Columns.Add(headers); } //Take each row of data, read it into data row then add to data table for (int i = 1; i < csvRows.Length; i++) { fields = csvRows[i].Split(','); DataRow dataRow = csvDt.NewRow(); dataRow.ItemArray = fields; csvDt.Rows.Add(dataRow); } //Set master data table masterDataTable = csvDt; } } //Catch error in event of exception.Most likly two addressed directly. catch { MessageBox.Show("Error, No master found please continue. An open .csv file will also cause this error. If you keep seeing this message please contact the front desk"); } } } }