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
9b17eb0a96b4404a61a5cbdc3ef99f4f0a152e51
C#
waverill/get_mah_versions
/get_mah_versions/Form1.cs
2.828125
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; using System.Net; using HtmlAgilityPack; using System.Text.RegularExpressions; namespace get_mah_versions { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { List<String> vers = new List<String>(); string URI = this.textBox1.Text; WebClient wc = new WebClient(); wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; string HtmlResult = wc.UploadString(URI,""); Regex file_regex = new Regex("(" + this.textBox2.Text + @")\<\/td\>\<td\>([0-9.]+)", RegexOptions.IgnoreCase); MatchCollection m = file_regex.Matches(HtmlResult); string printer = ""; int count = 1; foreach (Match ma in m) { string ver = ma.Groups[2].ToString(); if (!vers.Contains(ver)) { vers.Add(ver); printer += count +") " + ver + "\r\n\r\n"; count++; } } MessageBox.Show("Found " + vers.Count + " different versions for " + this.textBox2.Text + ".\r\n\r\n" + printer); } } }
21855d6c8918b33f544e20c0e5577ee451e24d69
C#
anitha-john/shrike-survey-tool
/server/SurveyAPI/RepositoryFactory/CreationRepository.cs
2.734375
3
 using Dapper; using Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Linq; namespace RepositoryFactory { public class CreationRepository : ICreationRepository { //Add questions public async Task<int> AddQuestions(Questions _questions) { int questionId = 0; using (UnitOfWork _unitOfWork = UnitOfWork.GenerateUnitOfWork()) { var sql = "insert into surveryengine.T_QUESTIONS_MASTER values (nextval('surveryengine.t_questions_master_question_id_seq'),@questionDesc, @questionType,@optionValuesJson) RETURNING question_id"; var data = await _unitOfWork.Connection.QueryAsync(sql, _questions, transaction: _unitOfWork.Transaction); questionId = Convert.ToInt32(((IDictionary<string, object>)data.FirstOrDefault())["question_id"]); _unitOfWork.Commit(); } return questionId; } public async Task<int> AddSurvey(Survey _survey) { int surveyId = 0; using (UnitOfWork _unitOfWork = UnitOfWork.GenerateUnitOfWork()) { try { var sql = "insert into surveryengine.t_survey values (nextval('surveryengine.t_survey_survey_id_seq'),@title, @createdOn,@createdBy,@isPublished) RETURNING survey_id"; var data = await _unitOfWork.Connection.QueryAsync(sql, _survey, transaction: _unitOfWork.Transaction); surveyId = Convert.ToInt32(((IDictionary<string, object>)data.FirstOrDefault())["survey_id"]); _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.RollBack(); } } return surveyId; } public async Task<bool> AddSurveyQuestions(List<Questions> questions, int surveyId) { using (UnitOfWork _unitOfWork = UnitOfWork.GenerateUnitOfWork()) { try { int order = 0; List<SurveyQuestions> _surveyQuestions = new List<SurveyQuestions>(); foreach (var question in questions) { //insert into question master table var query = "insert into surveryengine.T_QUESTIONS_MASTER values (nextval('surveryengine.t_questions_master_question_id_seq'),@questionDesc, @questionTypeStringyfy,CAST(@optionValuesJson as json)) RETURNING question_id"; var result = await _unitOfWork.Connection.QueryAsync(query, question, transaction: _unitOfWork.Transaction); SurveyQuestions _surveyQuestion = new SurveyQuestions(); _surveyQuestion.questionId = Convert.ToInt32(((IDictionary<string, object>)result.FirstOrDefault())["question_id"]); _surveyQuestion.surveyId = surveyId; _surveyQuestion.order = ++order; _surveyQuestions.Add(_surveyQuestion); } //inserting into the mapping table. Map between questions and survey var sql = "insert into surveryengine.t_survey_questions values (nextval('surveryengine.t_survey_questions_survey_question_id_seq'),@surveyId, @questionId,@order) RETURNING survey_question_id"; var rows = await _unitOfWork.Connection.ExecuteAsync(sql, _surveyQuestions); _unitOfWork.Commit(); return true; } catch (Exception ex) { //log error _unitOfWork.RollBack(); return false; } } } } }
4a93745c56874c9c32e41dc3649d808da21ce7ac
C#
leoskiline/ECommerce-LP4
/Trabalho/Models/Cliente.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Trabalho.Models { public class Cliente { int _id; string _nome; string _cpf; string _email; string _senha; Cidade _cidade; List<ClienteContato> _contatos; public Cliente() { _id = 0; _nome = ""; _cpf = ""; _email = ""; _senha = ""; _cidade = new Cidade(); _contatos = new List<ClienteContato>(); } public int Id { get => _id; set => _id = value; } public string Nome { get => _nome; set => _nome = value; } public string Cpf { get => _cpf; set => _cpf = value; } public string Email { get => _email; set => _email = value; } public string Senha { get => _senha; set => _senha = value; } public Cidade Cidade { get => _cidade; set => _cidade = value; } public List<ClienteContato> Contatos { get => _contatos; set => _contatos = value; } public string Validar() { string msg = ""; if(Email.Trim().Length > 45) { msg = "E-mail excede 45 caracteres."; } else if(Senha.Trim().Length > 45) { msg = "Senha excede os 45 caracteres."; } return msg; } } }
3b4a373c6b6fbf38ae4c49c8b8ce5508386a4fa8
C#
christianmadhan/EventMaker
/App1/App1/Model/Event.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Controls; using App1.Common; namespace App1.Model { class Event : NotifyChanged { private DateTimeOffset _datePicker; private TimeSpan _timePicker; private string _date; private DateTime _time; private int _id; private string _description; private string _name; private string _place; public Event(string date, DateTime time, int id, string description, string name, string place) { _date = date; _time = time; _id = id; _description = description; _name = name; _place = place; } public Event(DateTimeOffset datePicker, TimeSpan timePicker, int id, string description, string name, string place) { _datePicker = datePicker; _timePicker = timePicker; _id = id; _description = description; _name = name; _place = place; } // Empty constructer for the relay command public Event(){} // Get and set instance fields. public DateTimeOffset PickerDate { get => _datePicker; set { _datePicker = value; OnPropertyChanged(nameof(PickerDate)); } } public TimeSpan PickerTime { get => _timePicker; set { _timePicker = value; OnPropertyChanged(nameof(PickerTime)); } } public string Date { get => _date; set { _date = value; OnPropertyChanged(nameof(Date)); } } public DateTime Time { get => _time; set { _time = value; OnPropertyChanged(nameof(Time)); } } public int Id { get => _id; set { _id = value; OnPropertyChanged(nameof(Id)); } } public string Description { get => _description; set { _description = value; OnPropertyChanged(nameof(Description)); } } public string Name { get => _name; set { _name = value; OnPropertyChanged(nameof(Name)); } } public string Place { get => _place; set { _place = value; OnPropertyChanged(nameof(Place)); } } /* * Tostring method that returns all the information * about the Event. */ public override string ToString() { return "Date: " + _date + "\n" + "Time: " + _time + "\n" + "Id: " + _id + "\n" + "Name: " + _name + "\n" + "Place: " + _place + "\n" + "Description: " + Description; } } }
5ce93765d87ad531fb24b3adc960f2d987a93184
C#
alberot11/1-DAM
/PR/Tema 1 y 2/DiasMes.cs
3.640625
4
//Alberto Girón Serna using System; class DiasMes { static void Main() { Console.Write("Dime el mes (1-12): "); int mes= Convert.ToInt32(Console.ReadLine()); if (mes==2) Console.WriteLine(28); else if (mes==4 || mes==6 || mes==9 || mes==11) Console.WriteLine(30); else Console.WriteLine(31); // ------------------------------------------------------ switch(mes) { case 2: Console.WriteLine("28"); break; case 4: case 6: case 9: case 11: Console.WriteLine("30"); break; default: Console.WriteLine("31"); break; } } }
04b02d88fd0039d7e091548e82b23cda480fe006
C#
liuxx532/TspPsoDemo
/TspPsoDemo/RouteManager.cs
2.953125
3
using System; namespace TspPsoDemo { using Utilities; public class RouteManager { private readonly IRandomFactory randomFactory; private readonly IRouteUpdater routeUpdater; public RouteManager(IRandomFactory randomFactory, IRouteUpdater routeUpdater) { this.randomFactory = randomFactory; this.routeUpdater = routeUpdater; } public int[] AddSections(IRoute[] sections) { if (sections == null || sections.Length == 0) { throw new ArgumentException("Array cannot be null or empty", "sections"); } if (!routeUpdater.Isinitialised) { routeUpdater.Initialise(sections[0].DestinationIndex.Length); } foreach (var routeSection in sections) { routeUpdater.AddSection(this.randomFactory.NextRandom(0, routeSection.DestinationIndex.Length), routeSection, randomFactory.NextBool()); } return routeUpdater.FinalizeDestinationIndex(sections[0]); } //updates a particle's velocity. The shorter the total distance the greater the velocity public double UpdateVelocity(IRoute particleItinery, double weighting, double randomDouble) { return (1 / particleItinery.TourDistance) * randomDouble * weighting; } //Selects a section of the route with a length proportional to the particle's // relative velocity. public int GetSectionSize(IRoute particleItinery, double segmentVelocity, double totalVelocity) { int length = particleItinery.DestinationIndex.Length; return Convert.ToInt32(Math.Floor((segmentVelocity / totalVelocity) * length)); } } }
69ec81c4c822f69c073d3410fa67634dff688c18
C#
djvidov/Piler
/Piler/Controls/Crane.cs
3.3125
3
using System; using System.Threading; using System.Windows.Forms; namespace Piler.Controls { public class Crane : Button { public Crane() { this.Size = new System.Drawing.Size(10, 100); } public bool IsReady { get { return Top == 0; } } public void MoveAboveBlock(Block block) { var targetPosition = block.Left + Convert.ToInt32(block.Width / 2 - Width / 2); do { if (targetPosition > Left) { Left++; } else if (targetPosition < Left) { Left--; } Thread.Sleep(5); } while (targetPosition != Left); } public void GoUp() { do { if (0 > Top) { Top++; } else if (0 < Top) { Top--; } Thread.Sleep(5); } while (Top != 0); } public void GoDownAndTouchBlock(Block block) { do { Top++; Thread.Sleep(5); } while (!TouchBlock(block)); } public void GetUpBlock(Block block) { do { Top--; block.Top--; Thread.Sleep(5); } while (Top != 0); } private bool TouchBlock(Block block) { return Bounds.IntersectsWith(block.Bounds) ? true : false; } } }
d80896e997a42544ad08c038f5504d84271c2a35
C#
sinerger/HR_Application
/HR_Application_BLL/Models/Base/CommentModel.cs
3.078125
3
using System; using System.Collections.Generic; using System.Text; namespace HR_Application_BLL.Models.Base { public class CommentModel { public int ID { get; set; } public int EmployeeID { get; set; } public string Information { get; set; } public string Date { get; set; } public CommentModel Clone() { return new CommentModel() { ID = ID, EmployeeID = ID, Information = Information, Date = Date }; } public override string ToString() { return $"{Information} - {Date}"; } public override bool Equals(object obj) { bool result = false; if (obj is CommentModel) { CommentModel comment = (CommentModel)obj; if (comment.ID == ID && comment.EmployeeID== EmployeeID && comment.Information == Information && comment.Date == Date) { result = true; } } return result; } } }
d0793678d81ca7586b5fb93bd35b231fdddf8c70
C#
krishnamurthysvg/test
/TDD/Day03/Mock_Day3/GuessingGame/Utilities..cs
3.25
3
using System; using System.Text; using System.IO; using System.Security.Cryptography; using System.Linq; using System.Collections.Generic; namespace GuessingGameLib { class Utilities { public static string FILE_PATH = "./Redirect.txt"; public static string ENCRYPTION_KEY = "MAKV2SPBNI99212"; static Random random = new Random(); public static void startEncryptionGame() { Console.WriteLine("Welcome to the Encryption Game\n-------------------------------"); Console.WriteLine("You need Encryption/Decryption: E/D"); string option = Console.ReadLine(); string resultString; if (option.ToLower() == "e") { Console.WriteLine("Enter text to encrypt:"); string userInput = Console.ReadLine(); if (!string.IsNullOrEmpty(userInput)) { resultString = EncryptString(userInput); Console.WriteLine("Encryption is done "+ resultString); writeOutputToFile(resultString); } } else if (option.ToLower() == "d") { Console.WriteLine("Enter cypher text to decrypt:"); string userInput = Console.ReadLine(); if (!string.IsNullOrEmpty(userInput)) { resultString = EncryptString(userInput); Console.WriteLine("Decryption is done " + resultString); } } else { Console.WriteLine("Invalid input!!!"); } Console.ReadKey(); } private static void writeOutputToFile(string content) { FileStream ostrm; StreamWriter writer; TextWriter oldOut = Console.Out; try { ostrm = new FileStream(FILE_PATH, FileMode.OpenOrCreate, FileAccess.Write); writer = new StreamWriter(ostrm); Console.SetOut(writer); Console.WriteLine(content); Console.SetOut(oldOut); writer.Close(); ostrm.Close(); } catch (Exception e) { Console.WriteLine("Cannot open file for writing in specified path: " + FILE_PATH); Console.WriteLine(e.Message); return; } Console.WriteLine("Done"); } private static string EncryptString(string clearText) { byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(ENCRYPTION_KEY, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); } clearText = Convert.ToBase64String(ms.ToArray()); } } return clearText; } private static string DecryptString(string cipherText) { byte[] cipherBytes = Convert.FromBase64String(cipherText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(ENCRYPTION_KEY, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipherText = Encoding.Unicode.GetString(ms.ToArray()); } } return cipherText; } public static void randomNumberGame() { Console.WriteLine("Welcome to the Random Number Game\n-------------------------------"); Console.WriteLine("Enter how many random numbers you want?"); int count = int.Parse(Console.ReadLine()); Console.WriteLine("Enter MIN number?"); int from = int.Parse(Console.ReadLine()); Console.WriteLine("Enter MAX number?"); int to = int.Parse(Console.ReadLine()); List<int> vals = GenerateRandomNumber(count, from, to); Console.WriteLine("Result:\n" + vals.Count); vals.ForEach(Console.WriteLine); Console.ReadKey(); } //Password generator public static string passwordGenerator(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new Random(); return new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); } private static List<int> GenerateRandomNumber(int count, int min, int max) { // initialize set S to empty // for J := N-M + 1 to N do // T := RandInt(1, J) // if T is not in S then // insert T in S // else // insert J in S // // adapted for C# which does not have an inclusive Next(..) // and to make it from configurable range not just 1. if (max <= min || count < 0 || // max - min > 0 required to avoid overflow (count > max - min && max - min > 0)) { // need to use 64-bit to support big ranges (negative min, positive max) throw new ArgumentOutOfRangeException("Range " + min + " to " + max + " (" + ((Int64)max - (Int64)min) + " values), or count " + count + " is illegal"); } // generate count random values. HashSet<int> candidates = new HashSet<int>(); // start count values before max, and end at max for (int top = max - count; top < max; top++) { // May strike a duplicate. // Need to add +1 to make inclusive generator // +1 is safe even for MaxVal max value because top < max if (!candidates.Add(random.Next(min, top + 1))) { // collision, add inclusive max. // which could not possibly have been added before. candidates.Add(top); } } // load them in to a list, to sort List<int> result = candidates.ToList(); // shuffle the results because HashSet has messed // with the order, and the algorithm does not produce // random-ordered results (e.g. max-1 will never be the first value) for (int i = result.Count - 1; i > 0; i--) { int k = random.Next(i + 1); int tmp = result[k]; result[k] = result[i]; result[i] = tmp; } return result; } } }
c5c3213d7445eae5d363a4af3d5c60a3d4f33786
C#
BrianKilmer/TrainingC-
/Small Examples/Arrays/Arrays/Program.cs
3.28125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Arrays { class Program { static void Main(string[] args) { int[] numbers = { 4, 3, 8, 0, 5 }; Array.Sort(numbers); foreach (int i in numbers) Console.WriteLine(i); Console.WriteLine(); string[] str = { "d", "r", "a", "D", "c" }; Array.Sort(str); foreach (string i in str) Console.WriteLine(i); Console.ReadLine(); } } }
6c0e415f58ebdafb737e88ec08ab435b12bfa9a3
C#
Mossharbor/ActivityStreams
/Mossharbor.ActivityStreams/ActorTypes/PersonActor.cs
2.796875
3
using System; using System.Collections.Generic; using System.Text; #pragma warning disable CS1658 // Warning is overriding an error namespace Mossharbor.ActivityStreams { /// <summary> /// Represents a formal or informal collective of Actors. /// </summary> /// <example> ///{ /// "@context": "https://www.w3.org/ns/activitystreams", /// "type": "Person", /// "name": "Sally Smith" ///} /// </example> /// <see cref="https://www.w3.org/ns/activitystreams#Person"/> public class PersonActor : BaseActor { /// <summary> /// the type constant for this actor /// </summary> public const string PersonActorType = "Person"; /// <summary> /// Initializes a new instance of the <see cref="PersonActor"/> class. /// </summary> public PersonActor() : base(type: "Person") { } } }
911712b3d6d3f199c782cd7e48fd4ca61975e24d
C#
AndrioCelos/CBot
/CBot/IniReader.cs
2.953125
3
using System.Diagnostics.CodeAnalysis; namespace CBot; public class IniFile : Dictionary<string, Dictionary<string, string>> { public IniFile() : base() { } public IniFile(IEqualityComparer<string> comparer) : base(comparer) { } public IniFile(IDictionary<string, Dictionary<string, string>> source) : base(source) { } public IniFile(IDictionary<string, Dictionary<string, string>> source, IEqualityComparer<string> comparer) : base(source, comparer) { } public string this[string section, string key] { get => this[section][key]; set { if (!this.TryGetValue(section, out var dictionary)) { dictionary = new Dictionary<string, string>(this.Comparer); this[section] = dictionary; } dictionary[key] = value; } } public bool TryGetValue(string section, string key, [MaybeNullWhen(false)] out string value) { if (!this.TryGetValue(section, out var dictionary)) { value = null; return false; } return dictionary.TryGetValue(key, out value); } public static IniFile FromFile(string file) => FromFile(file, EqualityComparer<string>.Default); public static IniFile FromFile(string file, IEqualityComparer<string> comparer) { using var reader = new StreamReader(file); var result = new IniFile(comparer); Dictionary<string, string>? section = null; while (!reader.EndOfStream) { var line = reader.ReadLine()?.TrimStart(); if (line == null) break; if (line.StartsWith(";")) continue; // Comment. if (line.StartsWith("[")) { // Section header. int pos = line.IndexOf(']', 1); if (pos == -1) pos = line.Length; string sectionName = line[1..pos].Trim(); if (result.ContainsKey(sectionName)) // To emulate the Windows API, duplicate sections are ignored. section = null; else { section = new Dictionary<string, string>(comparer); result[sectionName] = section; } } else if (section != null) { int pos = line.IndexOf('='); if (pos == -1) continue; string key = line.Substring(0, pos).TrimEnd(); string value = line[(pos + 1)..].Trim(); // Duplicate keys are also ignored. if (!section.ContainsKey(key)) section[key] = value; } } return result; } }
8725985ec97e0f5e45e78674123d53f424c42055
C#
charul0827/Design-Project
/RobotSwarmServer/Control_Strategies/Strategies/Collision_Avoidance/CollisionFreeNavigation.cs
2.640625
3
/* * CollisionFreeNavigastion is a form of collision avoidance that lets the robots detect in advance if * they are on a collision course. It's theory can be read about in J. Snape, J. van den Berg, S. J. Guy, D. Manocha (2011). "The hybrid * reciprocal velocity obstacle". */ using AForge; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; namespace RobotSwarmServer.Control_Strategies.Strategies.Collision_Avoidance { class CollisionFreeNavigation : ControlStrategy { Vector robotPos, velocity, velocityPoint; List<Robot> neighborRobot; List<VelocityObstacle> obstacleList; List<Vector> permissibleVelocities; Vector zero = new Vector(0, 0); //Speedscaling temporarily increases the length of the velocityvector to make the //robots detect collision courses earlier. 5 is a good value. double velocityScaling = 5; //speedScaling scales the maximum speed of the robots to get a more stable behaviour. 0.5 is a good value. double speedScaling = 0.5; //radiusScaling scales the size of the collision radius to get more margin from collision. 1.3 is a good value double radiusScaling = 1.3; //vertexOffsetScaling is used to translate VO vertex from the robot position to an average of the 2 colliding robots //velocities. By setting it to 0 the translation is disabled. This is disabled because the behaviour were more stable //that way. In future development it may be prefered to use this. double vertexOffsetScaling = 0; public CollisionFreeNavigation() : base("CollisionAvoidance") { } public override void calculateNextMove(DoublePoint position, double speed, DoublePoint head, List<Robot> neighbors, out double refSpeed, out DoublePoint refHeading) { permissibleVelocities = new List<Vector>(); //Converts heading from DoublePoint to Vector since Vector is more usable. Vector heading = new Vector(head.X, head.Y); //Creates the velocityvector by combining the heading and speed of the robot. velocity = heading * speed * velocityScaling; robotPos = new Vector(position.X, position.Y); //velocityPoint contains the coordinates of the end of the velocityvector. velocityPoint = robotPos + velocity; neighborRobot = neighbors; //Step 1 is to calculate the forbidden area, the Velocity Obstacle VO. calculateVO(); //If the velocityvector is inside the VO it has to be changed. if (!pointOutsideVO(velocityPoint)) { //Step 2 is to calculate the permissible (allowed) velocities that is outside the VO. calculatePermissibleVelocities(); /* * If ther exists any permissible velocities, the one closest to the prefered velocity is chosen. */ if (permissibleVelocities.Count != 0) { Vector newVelocityPoint = permissibleVelocities[0]; //To calculate the normal length of a vector, a costly square root has to be performed. Therefore LengthSquared, which is faster, is used instead. double previousDist = (newVelocityPoint - velocityPoint).LengthSquared; foreach (Vector permissibleVelocityPoint in permissibleVelocities) { double thisDist = (permissibleVelocityPoint - velocityPoint).LengthSquared; if (thisDist < previousDist) { newVelocityPoint = permissibleVelocityPoint; } previousDist = thisDist; } velocity = newVelocityPoint - robotPos; } //If no permissible velocity exists, the velocity is set to zero. else { velocity = zero; } } refHeading = new DoublePoint(velocity.X, velocity.Y); refSpeed = Math.Min(Program.robotMaxSpeed * speedScaling, velocity.Length / velocityScaling); } /* * Calculates a forbidden area, the velocity obstacle VO. If the velocity vector is inside * this, the robot will collide with a neighbor robot. The VO is shaped like a cone with its vertex * at the robot position and the 2 edges tangent to the collision radius of the neighbor robot. * The cone is defined by 2 vectors representing the 2 edges and a vector point representing its vertex. */ private void calculateVO() { double collisionRadius = 2 * Program.robotRadius * radiusScaling; obstacleList = new List<VelocityObstacle>(); foreach (Robot neighbor in neighborRobot) { Vector neighborHeading = new Vector(neighbor.getHeading().X, neighbor.getHeading().Y); Vector neighborVelocity = neighborHeading * neighbor.getSpeed() * velocityScaling; Vector neighborVector = new Vector(neighbor.getPosition().X, neighbor.getPosition().Y); Vector vectorToNeighbor = neighborVector - robotPos; double radiusRelativeDist = collisionRadius / vectorToNeighbor.Length; //The VOangle is half of the angle of the cone that defines the VO. double VOangle; //Arcsinus is not defined for values larger than 1. Though if the robot drives inside the neighbor //robot's collision radius the radiusRelativeDist gets larger than 1. In that case the VOangle is set to 90 degrees. if (radiusRelativeDist <= 1) { VOangle = Math.Asin(radiusRelativeDist); } else { VOangle = Math.PI / 2; } double sinAngle = Math.Sin(VOangle); double cosAngle = Math.Cos(VOangle); Matrix rotationMatrixClockwise = new Matrix(cosAngle, sinAngle, -sinAngle, cosAngle, 0, 0); Matrix rotationMatrixCounterClockwise = new Matrix(cosAngle, -sinAngle, sinAngle, cosAngle, 0, 0); Vector rightEdge = vectorToNeighbor * rotationMatrixClockwise; Vector leftEdge = vectorToNeighbor * rotationMatrixCounterClockwise; Vector coneVertex = robotPos + vertexOffsetScaling * (neighborVelocity + velocity) / (2 * speedScaling); VelocityObstacle tempVO = new VelocityObstacle(rightEdge, leftEdge, vectorToNeighbor, coneVertex); /* * An additional method which is used to enlarge the VO additionally. If the velocity vector is inside VO and left * of the centerline, the VO is enlarged to the right and if the velocity vector is inside VO and right of the * centerline, the VO is enlarged to the left. This makes it easier for the robot to chose the correct side to * drive pass the neighbor. It is further explained in (J. Snape, J. van den Berg, S. J. Guy, D. Manocha (2011) "The hybrid * reciprocal velocity obstacle") where it is called "The hybrid reciprocal velocity obstacle". It is disabled here since * it didn't work according to plan but should work better with some adjustments. */ /* int test = pointRelativeCenterline(velocityPoint, temp); //test = -1 means that the velocity vector is inside VO and on the left side of the centerline if (test == -1) { tempVO.vertex = findLineIntersection(robotPos + neighborVelocity, temp.rightEdge, temp.vertex, temp.leftEdge); } //test = -1 means that the velocity vector is inside VO and on the right side of the centerline else if (test == 1) { tempVO.vertex = findLineIntersection(robotPos + neighborVelocity, temp.leftEdge, temp.vertex, temp.rightEdge); }*/ obstacleList.Add(tempVO); } } /* * Calculates the permissible velocities for the robot. Permissible velocities is outside the VO and should be as * close to the prefered velocity as possible. They consists partly of the intersections between the edges of VO, * and partly of the velocity vector projected on the edges of VO. */ private void calculatePermissibleVelocities() { //Calculates the permissible velocities in the intersections between the edges of VO for (int i = 0; i < obstacleList.Count - 1; i++) { VelocityObstacle VO1 = obstacleList[i]; for (int j = i + 1; j < obstacleList.Count; j++) { VelocityObstacle VO2 = obstacleList[j]; Vector possibleVelocity = findRayIntersection(VO1.vertex, VO1.leftEdge, VO2.vertex, VO2.leftEdge); if (possibleVelocity != zero) { if (pointOutsideVO(possibleVelocity)) { permissibleVelocities.Add(possibleVelocity); } } possibleVelocity = findRayIntersection(VO1.vertex, VO1.leftEdge, VO2.vertex, VO2.rightEdge); if (possibleVelocity != zero) { if (pointOutsideVO(possibleVelocity)) { permissibleVelocities.Add(possibleVelocity); } } possibleVelocity = findRayIntersection(VO1.vertex, VO1.rightEdge, VO2.vertex, VO2.leftEdge); if (possibleVelocity != zero) { if (pointOutsideVO(possibleVelocity)) { permissibleVelocities.Add(possibleVelocity); } } possibleVelocity = findRayIntersection(VO1.vertex, VO1.rightEdge, VO2.vertex, VO2.rightEdge); if (possibleVelocity != zero) { if (pointOutsideVO(possibleVelocity)) { permissibleVelocities.Add(possibleVelocity); } } } } //Calculates the permissible velocities that is the velocity vector projected on the edges of VO foreach (VelocityObstacle VO in obstacleList) { Vector pointOnEdge = projectPointOnRay(VO.vertex, VO.leftEdge, velocityPoint); if (pointOnEdge != zero) { if (pointOutsideVO(pointOnEdge)) { permissibleVelocities.Add(pointOnEdge); } } pointOnEdge = projectPointOnRay(VO.vertex, VO.rightEdge, velocityPoint); if (pointOnEdge != zero) { if (pointOutsideVO(pointOnEdge)) { permissibleVelocities.Add(pointOnEdge); } } } } /* * Calculates the intersection between two rays and returns the intersection point as a Vector type. * Ray 1 = start point: Vector p1, direction: Vector v1 * Ray 2 = start point: Vector p2, direction: Vector v2 * Returns a zero vector if the rays are parallel or if the intersection is behind the rays start point */ private Vector findRayIntersection(Vector p1, Vector v1, Vector p2, Vector v2) { double denominator = Vector.Determinant(v1, v2); double numerator = Vector.Determinant(v2, p1 - p2); //If the denominator is zero the rays are parallel if (denominator == 0) { return zero; } else { double scaling1 = numerator / denominator; double scaling2 = (p1.X - p2.X + scaling1 * v1.X) / v2.X; //If either of the scaling variables is negative the intersection is behind ray start point if (scaling1 < 0 || scaling2 < 0) { return zero; } //Intersection is valid else { return p1 + scaling1 * v1; } } } /* * Calculates the intersection between two lines and returns the intersection point as a Vector type. * Line 1 = point on line: Vector p1, direction: Vector v1 * Line 2 = point on line: Vector p2, direction: Vector v2 * Returns a zero vector if the lines are parallel */ private Vector findLineIntersection(Vector p1, Vector v1, Vector p2, Vector v2) { double denominator = Vector.Determinant(v1, v2); double numerator = Vector.Determinant(v2, p1 - p2); //Lines are parallel if (denominator == 0) { return zero; } else { return p1 + (numerator / denominator) * v1; } } /* * Determines if the point p is outside the VO. * Returns true if outside VO * Returns false if inside VO */ private bool pointOutsideVO(Vector p) { foreach (VelocityObstacle VO in obstacleList) { Vector pToVertex = p - VO.vertex; double uncertaintyAngleRange = 0.02; double pAngle = angleToXAxis(pToVertex); double lAngle = angleToXAxis(VO.leftEdge); double rAngle = angleToXAxis(VO.rightEdge); //Fix the angles so that they can be compared if (lAngle > rAngle) { if (pAngle < 0) { lAngle -= Math.PI * 2; } else { rAngle += Math.PI * 2; } } //If (lAngle < pAngle < rAngle) return false. An uncertaintyAngleRange is added since some permissible //velocities that is positioned exactly on the edge should be counted as outside the VO. if ((lAngle + uncertaintyAngleRange) < pAngle && pAngle < (rAngle - uncertaintyAngleRange)) { return false; } } return true; } /* * Detirmines if the velocity vector is on the left or right side of the VO if its inside the VO. * Returns -1 if the velocity vector is inside the VO and left of the centerline * Returns 1 if the velocity vector is inside the VO and right of the centerline * returns 0 if the velocity vector is outside the VO */ private int pointRelativeCenterline(Vector p, VelocityObstacle VO) { Vector pToVertex = p - VO.vertex; double pAngle = angleToXAxis(pToVertex); double lAngle = angleToXAxis(VO.leftEdge); double rAngle = angleToXAxis(VO.rightEdge); double centerlineAngle = angleToXAxis(VO.centerline); //Fix the angles so that they can be compared if (lAngle > rAngle) { if (pAngle < 0) { lAngle -= Math.PI * 2; } else { rAngle += Math.PI * 2; } if (centerlineAngle < lAngle) { centerlineAngle += Math.PI * 2; } else if (centerlineAngle > rAngle) { centerlineAngle -= Math.PI * 2; } } if (lAngle < pAngle && pAngle < rAngle) { if (pAngle < centerlineAngle) { return -1; } return 1; } return 0; } /* * Calculates the projection of a point on a ray * Returns the projection point if its valid * Returns a zero vector if the projected point is behind the ray start point */ private Vector projectPointOnRay(Vector rayPoint, Vector rayDirection, Vector point) { double scaling = ((point - rayPoint) * rayDirection); //Point is behind ray start point if (scaling < 0) { return zero; } else { return rayPoint + scaling * rayDirection / rayDirection.LengthSquared; } } private double angleToXAxis(Vector v) { return Math.Atan2(v.Y, v.X); } public override ControlStrategy cloneStrategy() { return new CollisionFreeNavigation(); } public override void paintStrategy(Graphics g, DoublePoint scaling) { try { //Paints Velocity Obstacles foreach (VelocityObstacle VO in obstacleList) { if (VO.rightEdge != null && VO.vertex != null && VO.leftEdge != null) { paintRay(VO.vertex, VO.rightEdge, Color.Red, g, scaling); paintRay(VO.vertex, VO.leftEdge, Color.Black, g, scaling); } } //Paints permissible velocities foreach (Vector v in permissibleVelocities) { if (robotPos != null) { drawPoint(v, Color.Green, g, scaling); } } //Paint robot velocity if (velocity != null && robotPos != null) { paintRay(robotPos, velocity, Color.Blue, g, scaling); if (!pointOutsideVO(robotPos + velocity)) { drawPoint(robotPos + velocity, Color.Red, g, scaling); } } } catch (Exception e) { Console.WriteLine("Caught Exception :" + e.Message); } } private void paintRay(Vector point, Vector directionVector, Color color, Graphics g, DoublePoint scale) { System.Drawing.Point startPoint = new System.Drawing.Point(Convert.ToInt32(point.X * scale.X), Convert.ToInt32(point.Y * scale.Y)); System.Drawing.Point directionPoint = new System.Drawing.Point(startPoint.X + Convert.ToInt32(directionVector.X * scale.X), startPoint.Y + Convert.ToInt32(directionVector.Y * scale.Y)); Pen pen = new Pen(color); g.DrawLine(pen, startPoint, directionPoint); } private void drawPoint(Vector point, Color color, Graphics g, DoublePoint scale) { Brush robotBrush = new SolidBrush(color); System.Drawing.Point p = new System.Drawing.Point(Convert.ToInt32((point.X) * scale.X), Convert.ToInt32((point.Y) * scale.Y)); g.FillEllipse(robotBrush, new Rectangle(p, new System.Drawing.Size(Convert.ToInt32(scale * 6), Convert.ToInt32(scale * 6)))); } public override void initializeStrategyPanel() { throw new NotImplementedException(); } } }
265efa6c365573e9ed790827daacbf24a6d28fdf
C#
janatdev/GiftAidCalculator
/GiftAidCalculator.Tests/TestCase_As_a_donor.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Moq; using NUnit.Framework; using GiftAidCalculator.TestConsole; using GiftAidCalculator.TestConsole.BuisnessLayer; using GiftAidCalculator.TestConsole.Interfaces; using GiftAidCalculator.TestConsole.EntityDataSource; namespace GiftAidCalculator.Tests { [TestFixture] class TestCase_As_a_donor { [Test] public void Giftaid_calculation_by_taxrate() { //Arrange const decimal taxRate = 20; const decimal donationAmount = 10; const decimal expectedResult = 2.0m; var mockConfigRepositry = new Mock<ITaxRateSetting>(); mockConfigRepositry.Setup(x => x.SetTaxRate).Returns(taxRate); ITaxRateCalculation taxRateSetting = new TaxRateCalculator(mockConfigRepositry.Object); //Act decimal actualResult = taxRateSetting.GiftAidCalculation(donationAmount); //Assert Assert.AreEqual(expectedResult, actualResult); Console.WriteLine("Gift aid at a tax rate of " + taxRate + " is: " + actualResult); } [Test] public void Round_to_two_decimal() { //Arrange const decimal expectedValue = 12m; const decimal taxRate = 20m; const decimal donationAmount = 10m; var mockConfigRepositry = new Mock<ITaxRateSetting>(); mockConfigRepositry.Setup(x => x.SetTaxRate).Returns(taxRate); ITaxRateCalculation taxRateSetting = new TaxRateCalculator(mockConfigRepositry.Object); decimal actual = taxRateSetting.GiftAidCalculation(donationAmount); //Act decimal actualValue = decimal.Round(donationAmount + actual, 2); //Assert Assert.AreEqual(actualValue, expectedValue); Console.WriteLine("Actual donation : [ " + donationAmount + " ] after adding gift aid and rounding to 2 decimal : " + actualValue); } } }
16c9069769e47e57a959b50b23255c60190ac502
C#
radtek/MedicalSystemDemo_anhuixiongke
/安徽省胸科医院/复苏/源代码/Client/MedicalSystem.Anes.Client.FrameWork/Helper/ModelHandler.cs
2.828125
3
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Reflection; using System.Text; namespace MedicalSystem.Anes.Client.FrameWork { /// <summary> /// 实体对象与DataTable互转 /// </summary> /// <typeparam name="T">实体类型</typeparam> public class ModelHandler<T> where T : new() { #region DataTable转换成实体类 /// <summary> /// 填充对象列表:用DataSet的第一个表填充实体类 /// </summary> /// <param name="ds">DataSet</param> /// <returns></returns> public List<T> FillModel(DataSet ds) { if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0) { return null; } else { return FillModel(ds.Tables[0]); } } /// <summary> /// 填充对象列表:用DataSet的第index个表填充实体类 /// </summary> public List<T> FillModel(DataSet ds, int index) { if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == 0) { return null; } else { return FillModel(ds.Tables[index]); } } /// <summary> /// 填充对象列表:用DataTable填充实体类 /// </summary> public List<T> FillModel(DataTable dt) { if (dt == null || dt.Rows.Count == 0) { return null; } List<T> modelList = new List<T>(); foreach (DataRow dr in dt.Rows) { if (dt.TableName.Equals("MED_PREOPERATIVE_EXPANSION") || dt.TableName.Equals("MED_POSTOPERATIVE_EXTENDED") || dt.TableName.Equals("MED_OPERATION_EXTENDED")) { if (dr.RowState == DataRowState.Unchanged) continue; } T model = FillModel(dr); modelList.Add(model); } return modelList; } /// <summary> /// 填充对象:用DataRow填充实体类 /// </summary> public T FillModel(DataRow dr) { if (dr == null) { return default(T); } //T model = (T)Activator.CreateInstance(typeof(T)); T model = new T(); foreach (PropertyInfo propertyInfo in GetProperties()) { propertyInfo.SetValue(model, dr[propertyInfo.Name] == DBNull.Value ? null : dr[propertyInfo.Name], null); } return model; } #endregion #region 实体类转换成DataTable /// <summary> /// 实体类转换成DataSet /// </summary> /// <param name="modelList">实体类列表</param> /// <returns></returns> public DataSet FillDataSet(List<T> modelList) { DataSet ds = new DataSet(); ds.Tables.Add(FillDataTable(modelList)); return ds; } /// <summary> /// 实体类转换成DataTable /// </summary> /// <param name="modelList">实体类列表</param> /// <returns></returns> public DataTable FillDataTable(List<T> modelList) { DataTable dt = CreateData(); if (modelList != null && modelList.Count > 0) { foreach (T model in modelList) { DataRow dataRow = dt.NewRow(); foreach (PropertyInfo propertyInfo in GetProperties()) { dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null) ?? DBNull.Value; } dt.Rows.Add(dataRow); } } dt.AcceptChanges(); return dt; } public DataTable ToDataTable(IEnumerable<T> list) { var dataTable = new DataTable(); foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(T))) { dataTable.Columns.Add(new DataColumn(pd.Name, Nullable.GetUnderlyingType(pd.PropertyType) ?? pd.PropertyType)); } foreach (T item in list) { var Row = dataTable.NewRow(); foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T))) { Row[dp.Name] = dp.GetValue(item) ?? DBNull.Value; } dataTable.Rows.Add(Row); } return dataTable; } public DataTable FillDataTable(T model) { DataTable dt = CreateData(); if (model != null) { DataRow dataRow = dt.NewRow(); foreach (PropertyInfo propertyInfo in GetProperties()) { dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null) ?? DBNull.Value; } dt.Rows.Add(dataRow); dt.AcceptChanges(); } return dt; } /// <summary> /// 根据实体类得到表结构 /// </summary> /// <param name="model">实体类</param> /// <returns></returns> private DataTable CreateData() { DataTable dataTable = new DataTable(typeof(T).Name); foreach (PropertyInfo propertyInfo in GetProperties()) { dataTable.Columns.Add(new DataColumn(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType)); } return dataTable; } #endregion #region Type PropertyInfo[] Cache private static Dictionary<Type, PropertyInfo[]> _cache = new Dictionary<Type, PropertyInfo[]>(); private PropertyInfo[] GetProperties() { PropertyInfo[] propInfos = null; if (!_cache.TryGetValue(typeof(T), out propInfos) || propInfos == null) { propInfos = typeof(T).GetProperties(); _cache[typeof(T)] = propInfos; } return propInfos; } #endregion } public class ModelHandler { #region 实体类转换成DataTable /// <summary> /// 实体类转换成DataTable /// </summary> /// <param name="modelList">实体类列表</param> /// <returns></returns> public DataTable FillDataTable(IList modelList) { if (modelList == null) return null; Type elemType = modelList.GetType().GetGenericArguments()[0]; DataTable dt = CreateData(elemType); if (modelList != null && modelList.Count > 0) { foreach (var model in modelList) { DataRow dataRow = dt.NewRow(); foreach (PropertyInfo propertyInfo in GetProperties(elemType)) { dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null) ?? DBNull.Value; } dt.Rows.Add(dataRow); } } dt.AcceptChanges(); return dt; } /// <summary> /// 根据实体类得到表结构 /// </summary> /// <param name="model">实体类</param> /// <returns></returns> private DataTable CreateData(Type type) { DataTable dataTable = new DataTable(type.Name); foreach (PropertyInfo propertyInfo in GetProperties(type)) { dataTable.Columns.Add(new DataColumn(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType)); } return dataTable; } #endregion #region Type PropertyInfo[] Cache private static Dictionary<Type, PropertyInfo[]> _cache = new Dictionary<Type, PropertyInfo[]>(); private PropertyInfo[] GetProperties(Type type) { PropertyInfo[] propInfos = null; if (!_cache.TryGetValue(type, out propInfos) || propInfos == null) { propInfos = type.GetProperties(); _cache[type] = propInfos; } return propInfos; } #endregion } }
181b4ea3bcc67ac4f9c25f884d5041284ae34da9
C#
Arctra234/SuperBloki
/SuperBloki.WebUI/Infrastructure/Binders/CartModelBinder.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using SuperBloki.Domain.Entities; using System.Web.Mvc; namespace SuperBloki.WebUI.Infrastructure.Binders { public class CartModelBinder : IModelBinder { private const string sessionKey = "Cart"; public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { // Pobierz obiekt koszyka z sesji Cart cart = null; if (controllerContext.HttpContext.Session != null) { cart = (Cart)controllerContext.HttpContext.Session[sessionKey]; } // Utwórz obiekt koszyka, jeśli nie zostanie znaleziony w sesji if (cart == null) { cart = new Cart(); if (controllerContext.HttpContext.Session != null) { controllerContext.HttpContext.Session[sessionKey] = cart; } } // Zwróć obiekt Cart return cart; } } }
7f6e1d2a7ee66484c19b4df89291e37e230f7b8a
C#
shendongnian/download4
/first_version_download2/214326-16644558-40885065-4.cs
2.71875
3
public class CustomerHandler { // in BL you may have to call several DAL methods to perform one Task // here i have added validation and insert // in case of validation fail method return false public bool InsertCustomer(Customer customer) { if (CustomerDataAccess.Validate(customer)) { CustomerDataAccess.insertCustomer(customer); return true; } return false; } }
b44f822ff4b6d112e814431408183327a0f462a0
C#
2011-nov02-net/lukef-project0
/StoreApplication/StoreApplication.DBClassLibrary/Repositories/StoreRepository.cs
3.015625
3
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; namespace StoreApplication.DBClassLibrary.Repositories { public class StoreRepository : IStoreRepository { private readonly DbContextOptions<Project0DBContext> _contextOptions; public StoreRepository(DbContextOptions<Project0DBContext> contextOptions) { _contextOptions = contextOptions; } /// <summary> /// Gets all Locations from the Location table in the database /// </summary> /// <returns></returns> public List<ClassLibrary.StoreApplication.Design.Location> GetLocations() { using var context = new Project0DBContext(_contextOptions); var dbLocations = context.Locations.ToList(); var appLocations = dbLocations.Select(l => new ClassLibrary.StoreApplication.Design.Location() { LocationId = l.LocationId, Name = l.Name }).ToList(); return appLocations; } /// <summary> /// Gets all Products from the Product table in the database /// </summary> /// <returns></returns> public List<ClassLibrary.StoreApplication.Design.Product> GetProducts() { using var context = new Project0DBContext(_contextOptions); var dbProducts = context.Products.ToList(); var appProducts = dbProducts.Select(p => new ClassLibrary.StoreApplication.Design.Product() { ProductId = p.ProductId, Title = p.Name, Price = p.Price }).ToList(); return appProducts; } /// <summary> /// Gets all Customers from the Customer table in the database /// </summary> /// <returns></returns> public List<ClassLibrary.StoreApplication.Design.Customer> GetCustomers() { using var context = new Project0DBContext(_contextOptions); var dbCustomers = context.Customers.ToList(); var appCustomers = dbCustomers.Select(c => new ClassLibrary.StoreApplication.Design.Customer() { CustomerId = c.CustomerId, FirstName = c.FirstName, LastName = c.LastName, Email = c.Email }).ToList(); return appCustomers; } /// <summary> /// Gets all Orders from the Order table in the database /// </summary> /// <returns></returns> public List<ClassLibrary.StoreApplication.Design.Order> GetOrders() { using var context = new Project0DBContext(_contextOptions); var dbOrders = context.Orders.ToList(); var appOrders = dbOrders.Select(o => new ClassLibrary.StoreApplication.Design.Order() { OrderId = o.OrderId, CustomerId = o.CustomerId, LocationId = o.LocationId, Quantity = o.Quantity } ).ToList(); return appOrders; } /// <summary> /// Gets all Customers that match a specific First name and Last name /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <returns></returns> public ClassLibrary.StoreApplication.Design.Customer GetCustomerByName(string firstName, string lastName) { using var context = new Project0DBContext(_contextOptions); var dbCustomers = context.Customers.ToList(); var appCustomers = dbCustomers.Select(c => new ClassLibrary.StoreApplication.Design.Customer() { CustomerId = c.CustomerId, FirstName = c.FirstName, LastName = c.LastName, Email = c.Email }).Where(c => c.FirstName == firstName && c.LastName == lastName).First(); return appCustomers; } /// <summary> /// Gets all Locations that match a specific Location name /// </summary> /// <param name="name"></param> /// <returns></returns> public ClassLibrary.StoreApplication.Design.Location GetLocationByName(string name) { using var context = new Project0DBContext(_contextOptions); var dbLocations = context.Locations.ToList(); var appLocations = dbLocations.Select(l => new ClassLibrary.StoreApplication.Design.Location() { LocationId = l.LocationId, Name = l.Name }).Where(l => l.Name == name).First(); return appLocations; } /// <summary> /// Gets all Products that match a specific Product name /// </summary> /// <param name="name"></param> /// <returns></returns> public ClassLibrary.StoreApplication.Design.Product GetProductByName(string name) { using var context = new Project0DBContext(_contextOptions); var dbProducts = context.Products.ToList(); var appProducts = dbProducts.Select(p => new ClassLibrary.StoreApplication.Design.Product() { ProductId = p.ProductId, Title = p.Name, Price = p.Price } ).Where(p => p.Title == name).First(); return appProducts; } /// <summary> /// Gets an Order based off of a specific OrderId /// </summary> /// <param name="id"></param> /// <returns></returns> public ClassLibrary.StoreApplication.Design.Order GetOrderById(int id) { using var context = new Project0DBContext(_contextOptions); var dbOrders = context.Orders .Include(o => o.Location) .Include(o => o.Customer) .Include(o => o.Product) .First(o => o.OrderId == id); var location = new ClassLibrary.StoreApplication.Design.Location(dbOrders.LocationId, dbOrders.Location.Name) { LocationId = dbOrders.LocationId, Name = dbOrders.Location.Name, }; var customer = new ClassLibrary.StoreApplication.Design.Customer() { CustomerId = dbOrders.CustomerId, FirstName = dbOrders.Customer.FirstName, LastName = dbOrders.Customer.LastName, Email = dbOrders.Customer.Email }; var product = new ClassLibrary.StoreApplication.Design.Product() { ProductId = dbOrders.ProductId, Title = dbOrders.Product.Name, Price = dbOrders.Product.Price, }; ClassLibrary.StoreApplication.Design.Order testorder = new ClassLibrary.StoreApplication.Design.Order() { OrderId = dbOrders.OrderId, CustomerId = customer.CustomerId, LocationId = location.LocationId, ProductId = product.ProductId, OrderTime = dbOrders.OrderTime, Quantity = dbOrders.Quantity }; return testorder; } /// <summary> /// Gets all orders that relate to a Customer /// </summary> /// <param name="customerId"></param> /// <returns></returns> public List<ClassLibrary.StoreApplication.Design.Order> GetCustomerOrders(int customerId) { using var context = new Project0DBContext(_contextOptions); var dbCustomerOrders = context.Orders.Where(o => o.CustomerId == customerId).ToList(); var appCustomerOrders = dbCustomerOrders.Select(o => new ClassLibrary.StoreApplication.Design.Order() { OrderId = o.OrderId, CustomerId = o.CustomerId, LocationId = o.LocationId, ProductId = o.ProductId, OrderTime = o.OrderTime, Quantity = o.Quantity } ).ToList(); return appCustomerOrders; } /// <summary> /// Gets all orders that relate to a Location /// </summary> /// <param name="locationId"></param> /// <returns></returns> public List<ClassLibrary.StoreApplication.Design.Order> GetLocationOrders(int locationId) { using var context = new Project0DBContext(_contextOptions); var dbCustomerOrders = context.Orders.Where(o => o.LocationId == locationId).ToList(); var appLocationOrders = dbCustomerOrders.Select(co => new ClassLibrary.StoreApplication.Design.Order() { OrderId = co.OrderId, CustomerId = co.CustomerId, LocationId = co.LocationId, ProductId = co.ProductId, OrderTime = co.OrderTime, Quantity = co.Quantity, } ).ToList(); return appLocationOrders; } /// <summary> /// Creates a new Customer record in the Customer database table /// </summary> /// <param name="customer"></param> public void InsertCustomer(ClassLibrary.StoreApplication.Design.Customer customer) { using var context = new Project0DBContext(_contextOptions); var dbCustomer = new Customer() { FirstName = customer.FirstName, LastName = customer.LastName, Email = customer.Email }; context.Customers.Add(dbCustomer); context.SaveChanges(); } /// <summary> /// Creates a new Order record in the Order database table /// </summary> /// <param name="order"></param> public void InsertOrder(ClassLibrary.StoreApplication.Design.Order order) { using var context = new Project0DBContext(_contextOptions); var dbOrder = new Order() { LocationId = order.LocationId, CustomerId = order.CustomerId, ProductId = order.ProductId, Quantity = order.Quantity }; context.Orders.Add(dbOrder); context.SaveChanges(); } public void UpdateLocationInventory(ClassLibrary.StoreApplication.Design.Location location, ClassLibrary.StoreApplication.Design.Product product) { throw new NotImplementedException(); } } }
e5f103395606c1bc07dd477cc23da3986c208b36
C#
shendongnian/download4
/code3/488302-11160241-25881305-2.cs
2.65625
3
var connection = new MySqlConnection(connStr); try { connection.Open(); var command = new MySqlCommand( "SELECT * FROM tblCountry WHERE Name = @Name", connection); command.Parameters.AddWithValue("@Name", name); ... } finally { connection.Close(); }
b80b0e87d71fb30408633d48bc3a8008dd757c0e
C#
pavani8/ShopBridgeApplication
/ShopBridge(BackendSolution)/Controllers/SubCategoryController.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ShopBridgeClassLibrary; namespace ShopBridge_BackendSolution_.Controllers { public class SubCategoryController : ApiController { SubCategoryOperations subCatOp = new SubCategoryOperations(); // GET: api/SubCategory [Route("api/SubCategory/GetAll")] public async Task<HttpResponseMessage> GetAll() { List<SubCategory> subcategories = await subCatOp.getAllSubCategories(); return Request.CreateResponse(HttpStatusCode.OK, subcategories); } // GET: api/SubCategory/5 [Route("api/SubCategory/GetSubCategoryById/{Id}")] public async Task<HttpResponseMessage> GetSubCategory(int Id) { try { SubCategory subCategory = await subCatOp.getSubCategoryById(Id); if (subCategory != null) return Request.CreateResponse(HttpStatusCode.OK, subCategory); else return Request.CreateErrorResponse(HttpStatusCode.NotFound, "SubCategory with Id = " + Id.ToString() + " not found"); } catch(Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message); } } // POST: api/SubCategory // [HttpPost] [Route("api/SubCategory/AddSubCategory")] public async Task<HttpResponseMessage> AddSubCategory([FromBody] SubCategory subCategory) { try { await subCatOp.AddSubCategory(subCategory); return Request.CreateResponse(HttpStatusCode.Created, subCategory); } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message); } } // PUT: api/SubCategory/5 [HttpPut] [Route("api/SubCategory/UpdateSubCategory/{Id}")] public async Task<HttpResponseMessage> UpdateSubCategory(int id, [FromBody] SubCategory subCategory) { try { SubCategory subcat = await subCatOp.getSubCategoryById(id); if (subcat == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "SubCategory with Id = " + id.ToString() + " not found to update"); } else { await subCatOp.UpdateSubCategory(id, subCategory); return Request.CreateResponse(HttpStatusCode.OK, subcat); } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message); } } // DELETE: api/SubCategory/5 [Route("api/SubCategory/DeleteSubCategory/{Id}")] public async Task<HttpResponseMessage> DeleteSubCategory(int id) { try { int response = await subCatOp.DeleteSubCategory(id); if (response == 0) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "SubCategory with Id = " + id.ToString() + " not found to delete"); } else { return Request.CreateResponse(HttpStatusCode.OK, "SubCategory with Id = " + id.ToString() + " is deleted"); } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message); } } } }
4083fe8722fd1a2572356315e68e879193a2b2be
C#
adyshkins/ClothesForHandsGroup2
/ClothesForHandsGroup2/Windows/EditminCountWindow.xaml.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using ClothesForHandsGroup2.ClassHelper; namespace ClothesForHandsGroup2.Windows { /// <summary> /// Логика взаимодействия для EditminCountWindow.xaml /// </summary> public partial class EditminCountWindow : Window { public EditminCountWindow() { InitializeComponent(); txtMinCount.Text = MinCountMaterial.EditMinCount.ToString(); } private void btnEnter_Click(object sender, RoutedEventArgs e) { var result = MessageBox.Show("Подтвердите изменение", "Изменение минимального кличества",MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { int val; if (int.TryParse(txtMinCount.Text, out val)) { MinCountMaterial.EditMinCount = val; Close(); } else { MessageBox.Show("Недопустимое значение"); } } } } }
ca9a26fcc76c24cff6d6cc6e65da643937a57bea
C#
smithkl42/AlantaMedia
/Alanta.Client.Media/RtpPacket.cs
2.765625
3
using System.Diagnostics; using Alanta.Client.Common.Logging; namespace Alanta.Client.Media { public enum RtpPacketType { Connect = 0, Stream = 1 } public enum RtpParseResult { Success, DataIncomplete, DataInvalid } public abstract class RtpPacket { #region Fields and Properties public RtpPacketType PacketType { get; protected set; } public const int RtpVersion = 2; public static readonly byte[] Preamble = { 0xFF, 0x00, 0xFF, 0x00 }; public static readonly byte[] Suffix = { 0xAA, 0xAA }; public byte[] PacketSuffix { get; protected set; } #endregion #region Constructors protected RtpPacket() { PacketSuffix = new byte[Suffix.Length]; } #endregion #region Methods public abstract RtpParseResult ParsePacket(ByteStream buffer); public abstract byte[] BuildPacket(); public abstract bool TryBuildPacket(ByteStream packetBuffer); public abstract int GetPacketSize(); public virtual bool IsValid() { bool isValid = true; for (int i = 0; i < Suffix.Length; i++) { if (PacketSuffix[i] != Suffix[i]) { isValid = false; break; } } if (!isValid) { ClientLogger.Debug("Packet suffix doesn't match."); } return isValid; } protected static bool FindNextPreamble(byte[] data, ref int offset) { // This brute-force algorithm is likely to be the fastest, since most of the time the preamble will be the first four bytes starting at position. for (; offset < data.Length - Preamble.Length; offset++) { if (IsPreamble(data, offset)) { offset += Preamble.Length; return true; } } return false; } protected static bool IsPreamble(byte[] data, int offset) { bool found = true; for (int j = 0; j < Preamble.Length; j++) { if (data[offset + j] != Preamble[j]) { found = false; break; } } return found; } #endregion Methods } }
e1022076e346bf8c4a6d5358ae198872ff9a1a65
C#
zyr365/ChatRoom
/WebApplication2/WebForm1.aspx.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication2 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Application.Lock(); //Application["Name"] = "小亮"; //Application.UnLock(); //Application["Age"] = 13; //Response.Write("Application[\"Name\"]的值为;"+Application["Name"].ToString()+"<br>"); //Response.Write("Application[\"Age\"]的值为;" + Application["Age"].ToString()); //Label1.Text = "您是该网站的第" + Application["count"].ToString()+ "个访问者"; } protected void Button1_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(TextBox1.Text)) { Session["nickname"] = TextBox1.Text; } Response.Redirect("ChatRoom.aspx"); } } }
86f03f7f83de96f15db3dc3b9ce0f5b3a49beea4
C#
Velantine/Testgroud
/Assets/Scripts/OptionsClass.cs
2.640625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Xml.Serialization; using System.IO; [XmlRoot("Options")] public class OptionsClass{ [Range(-80, 20)] [XmlElement("SoundVolume")] public float soundVolume; [Range(-80, 20)] [XmlElement("MusicVolume")] public float musicVolume; [XmlElement("Mute")] public bool mute; public void Save() { string Path = DataPool.optionPath(); var serializer = new XmlSerializer(typeof(OptionsClass)); var stream = new FileStream(Path, FileMode.Create); serializer.Serialize(stream, this); stream.Close(); } public static OptionsClass Load() { string Path = DataPool.optionPath(); OptionsClass container; var serializer = new XmlSerializer(typeof(OptionsClass)); if (File.Exists(Path)) { var stream = new FileStream(Path, FileMode.Open); container = serializer.Deserialize(stream) as OptionsClass; stream.Close(); container.Save(); } else { container = new OptionsClass(); container.Save(); } return container; } public OptionsClass(float sound, float music, bool mu) { this.soundVolume = sound; this.musicVolume = music; this.mute = mu; } public OptionsClass() { } }
6beed8ff1213cc490e0847ce8f667bb469c84297
C#
zeynepyalinizdagci/KodlamaIO
/Products/Program.cs
3
3
using System; namespace Products { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); Products hat = new Products(); hat.Name = "Hat"; hat.Description = "Hat"; hat.UnitInPrice = 5.9; hat.UnitInStock = 5; Products atkı = new Products(); atkı.Name = "atkı"; atkı.Description = "atkı"; atkı.UnitInPrice = 9; atkı.UnitInStock = 12; ProductManager productManager = new ProductManager(); //productManager.Add(atkı); for (int i = 0; i < 2; i++) { atkı.UnitInStock = productManager.Remove(atkı); } } } }
c235f0f09de13a0afcbe549f0647aae3294a4f77
C#
hjy1999/CsharpHomework
/Homework3/program1/Program.cs
3.578125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace program1 { public abstract class FatherShape { private string myID; public FatherShape(string i) { id = i; } public string id //获得图形 { get { return myID; } set { myID = value; } } public abstract double Area { get; } public string info { get { return id +"面积:"+ Area; } } } public class Square : FatherShape { private int myside; public Square(int side, string ID) : base(ID) { myside = side; } public override double Area { get { return myside * myside; } } } public class Circle : FatherShape { private int myradius; public Circle(int radius, string ID) : base(ID) { myradius = radius; } public override double Area { get { return myradius * myradius * System.Math.PI; } } } public class Rectangle : FatherShape { private int mywidth, myheight; public Rectangle(int width, int height, string ID) : base(ID) { myheight = height;mywidth = width; } public override double Area { get { return mywidth * myheight; } } } class Program { static void Main(string[] args) { FatherShape[] getID = { new Square(10,"正方形"), new Circle(5, "圆形"), new Rectangle(10, 5, "长方形") }; Console.WriteLine("输出:"); foreach (FatherShape s in getID) { Console.WriteLine(s.info); } } } }
f5bf3a7d5d364dccd1e9de5b9b4d096b10a0e126
C#
reignstudios/CS2X
/CS2X.CoreLib/Reflection/AssemblyInformationalVersionAttribute.cs
2.828125
3
namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyInformationalVersionAttribute : Attribute { private readonly string _informationalVersion; public AssemblyInformationalVersionAttribute(string informationalVersion) { _informationalVersion = informationalVersion; } public string InformationalVersion { get { return _informationalVersion; } } } }
78bed820dfaac1b6e9d6ca6c3fb6e0c489927a24
C#
ZhenyaBarsamov/CourseWorks_GOES
/SGVL — копия/Visualizers/SimpleGraphVisualizer/EdgesDrawing/IEdgeDrawer.cs
3.140625
3
using System.Drawing; using SGVL.Types.Graphs; namespace SGVL.Visualizers.SimpleGraphVisualizer.EdgesDrawing { /// <summary> /// Интерфейс объекта, занимающегося рисованием рёбер графа /// и проверкой принадлежности координат рёбрам /// </summary> public interface IEdgeDrawer { /// <summary> /// Нарисовать ребро графа /// </summary> /// <param name="g">Поверхность рисования</param> /// <param name="edge">Ребро, которое необходимо нарисовать</param> void DrawEdge(Graphics g, Edge edge); /// <summary> /// Нарисовать ребро, на которое была наведена мышь /// </summary> /// <param name="g">Поверхность рисования</param> /// <param name="edge">Ребро, которое необходимо нарисовать</param> void DrawSelectedEdge(Graphics g, Edge edge); /// <summary> /// Проверить координаты на принадлежность заданному ребру /// </summary> /// <param name="edge">Проверяемое ребро</param> /// <param name="coords">Проверяемые координаты</param> bool IsCoordinatesOnEdge(Edge edge, PointF coords); } }
137e158da871f87a33f43a1e32586b7e766f7fe9
C#
kayyer/sigstat
/SigStat.PreprocessingBenchmark/Monitor.cs
2.734375
3
using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.Queue; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SigStat.PreprocessingBenchmark { class Monitor { static CloudBlobContainer Container; static CloudQueue Queue; enum Action { Run, Refresh, Abort}; internal static async Task RunAsync() { Console.WriteLine("Initializing container: " + Program.Experiment); var blobClient = Program.Account.CreateCloudBlobClient(); Container = blobClient.GetContainerReference(Program.Experiment); if (!(await Container.ExistsAsync())) { Console.WriteLine("Container does not exist. Aborting..."); return; } Console.WriteLine("Initializing queue: " + Program.Experiment); var queueClient = Program.Account.CreateCloudQueueClient(); Queue = queueClient.GetQueueReference(Program.Experiment); if (!(await Queue.ExistsAsync())) { Console.WriteLine("Queue does not exist. Aborting..."); return; } Action action = Action.Run; DateTime lastRefresh = DateTime.Now.AddDays(-1); Console.WriteLine("Monitor is running. Press 'r' to force a refresh, press any other key to quit"); while(action!= Action.Abort) { if (Console.KeyAvailable) { switch (Console.ReadKey(true).Key) { case ConsoleKey.R: action = Action.Refresh; break; default: action = Action.Abort; break; } } if (((DateTime.Now- lastRefresh).TotalMinutes>1) || action == Action.Refresh) { await Queue.FetchAttributesAsync(); Console.WriteLine($"{DateTime.Now}: {Queue.ApproximateMessageCount} items are in the queue. (q-quit, r-refresh)"); lastRefresh = DateTime.Now; action = Action.Run; } else { Thread.Sleep(100); } } } } }
c2022debe31b9aaf67e806429b0f929a4dfb431e
C#
AnCh7/WealthLabDataConverter
/src/WealthLabDataConverter/Models/Fundamental/Split.cs
2.75
3
// ================================================= // File: // WealthLabDataConverter/WealthLabDataConverter.Library/Split.cs // // Last updated: // 2013-08-21 2:10 PM // ================================================= #region Usings using System.Globalization; using WealthLabDataConverter.Library.Models.Fundamental.Base; #endregion namespace WealthLabDataConverter.Library.Models.Fundamental { public class Split : FundamentalBase { public Split(string name) : base(name) {} public override string FormatValue() { var num = 1; var num2 = base.Value; var num3 = (1 * num2) - ((int)((1 * num2) + 0.5)); while ((num3 * num3) > 0.00025) { num++; num3 = (num * num2) - ((int)((num * num2) + 0.5)); if (num > 0x3e8) { break; } } var objArray = new object[] {((int)((num * num2) + 0.5)).ToString(CultureInfo.InvariantCulture), ':', num, " Stock Split"}; var result = string.Concat(objArray); return result; } } }
b408c2f28599feccd0208a9e45b419eccdbb353f
C#
ulitol97/HackingToTheGate
/Assets/Scripts/Game/UI/RemoteDesktopScreenUI.cs
2.578125
3
using Remote_Terminal; using UnityEngine; using UnityEngine.UI; using UnityObserver; namespace Game.UI { /// <summary> /// The RemoteDesktopScreenUI watches for changes in the VncManager. /// While the latter is active, updates the in-game object it is attached to with the remote desktop image, /// while the VncManager is not active, waits for new updates. /// As an observer object, it has a status <see cref="_statusOnline"/> which is notified by /// the observed VncManager if changed. /// </summary> // ReSharper disable once InconsistentNaming public class RemoteDesktopScreenUI : MonoBehaviour, IObserver { /// <summary> /// Default image that will be displayed when there is no remote desktop image available. /// </summary> public Sprite defaultSprite; // Sprite displayed by default /// <summary> /// Unity managed component that handles the sprites shown in game. /// </summary> private Image _imageRenderer; /// <summary> /// Represents the state of the RemoteDesktopScreenUI and whether it should request Image updates /// to the VncManager or not. /// </summary> private bool _statusOnline; /// <summary> /// Represents the state of the RemoteDesktopScreenUI in-game. If toggled, it should display it's /// assigned sprite. /// </summary> private bool _statusOnScreen; /// <summary> /// Function called when the RemoteDesktopUI is inserted into the game. /// Arranges the registration onto the observed subjects and sets up the ImageRenderer component in charge /// of displaying the desktop image. /// </summary> private void Awake() { // Initialize remote desktop sprite with sprite by default. SetUpImageRenderer(); } /// <summary> /// Function called on each frame the RemoteDesktopUI is present into the game. /// Polls the state of the object to determine if it should show remote desktop images or not. /// </summary> private void Update() { if (!_statusOnline || !_statusOnScreen) return; _imageRenderer.sprite = VncManager.GetInstance(true).remoteDesktopSprite; } /// <summary> /// Initializes the ImageRenderer in a disabled state /// before the remote desktop can be displayed. /// </summary> private void SetUpImageRenderer() { _imageRenderer = GetComponent<Image>(); _imageRenderer.enabled = false; _imageRenderer.overrideSprite = defaultSprite; } /// <summary> /// Updates the observing screen status with the current connection status of the VncManager observed. /// and sets the variables needed for the screen to behave properly in case of disconnection. /// </summary> public void UpdateObserver() { // Invert if it has to be shown on screen. _statusOnScreen = !_statusOnScreen; // Update status regarding the client status if (VncManager.GetInstance(true) != null) _statusOnline = VncManager.GetInstance(true).ConnectionStatus; // Put placeholder image in case of disconnection. if (!_statusOnline) { _imageRenderer.overrideSprite = defaultSprite; } else if (VncManager.GetInstance(true) != null) { _imageRenderer.overrideSprite = null; _imageRenderer.sprite = VncManager.GetInstance(true).remoteDesktopSprite; } // Deactivate game element if terminal mode is not toggled _imageRenderer.enabled = _statusOnScreen; } } }
89296cdb7ad10abc1fe7e1eb6d40c2261ea6e933
C#
jeffchiudev/CoffeeShop.Solutions-cs-practice
/CoffeeShop/Controllers/EmployeesController.cs
2.96875
3
using System.Collections.Generic; using System; using Microsoft.AspNetCore.Mvc; using CoffeeShop.Models; namespace CoffeeShop.Controllers { public class EmployeesController : Controller { [HttpGet("/employees")] //display all employees public ActionResult Index() { List<Employee> allEmployees = Employee.GetAll(); return View(allEmployees); } [HttpGet("/employees/new")] // user creates new employee with form public ActionResult New() { return View(); } [HttpPost("/employees")] //process form submission public ActionResult Create(string employeeName) //accepts argument because it is referring to the contents in the form { Employee newEmployee = new Employee(employeeName); //creates a new employee return RedirectToAction("Index"); //send the user back to the index route } [HttpGet("/employees/{id}")] public ActionResult Show(int id) { Dictionary<string, object> model = new Dictionary<string, object>(); Employee selectedEmployee = Employee.Find(id); List<Duty> employeeDutys = selectedEmployee.Dutys; model.Add("employee", selectedEmployee); //keys in dictionary employee and Dutys model.Add("dutys", employeeDutys); return View(model); } // creates new Dutys for an employee [HttpPost("/employees/{employeeId}/dutys")] public ActionResult Create(int employeeId, string dutyDescription) { Dictionary<string, object> model = new Dictionary<string, object>(); Employee foundEmployee = Employee.Find(employeeId); Duty newDuty = new Duty(dutyDescription); newDuty.Save(); foundEmployee.AddDuty(newDuty); List<Duty> employeeDutys = foundEmployee.Dutys; model.Add("dutys", employeeDutys); model.Add("employee", foundEmployee); return View("Show", model); } } }
2af898fb08bc6010c612d671ce86d6af87022230
C#
HachyCode/SnakesAndLadders-V1
/Player.cs
3.21875
3
using System; using System.Collections.Generic; using System.Text; namespace SnakesAndLadders_V1 { //Facade pattern subsystem class class Player { public static int PlayerPlace { get { return playerPlace; } set { playerPlace = value; } } private static int playerPlace; //adds dice number to existing player place. public static void PlayerGo(int amount) { playerPlace = playerPlace + amount; } //sets computer place to go to tile if its ot special tile. public static void PlayerJump(int amount) { playerPlace = amount; } } }
cd95517d2bfca029d88b11a84e20c7bf268d16be
C#
suvanl/Memo
/Memo/AttachedProperties/TextEntryWidthMatcherProperty.cs
2.96875
3
using System; using System.Windows; using System.Windows.Controls; namespace Memo { /// <summary> /// Matches the label width of all text entry controls within this panel /// </summary> public class TextEntryWidthMatcherProperty : BaseAttachedProperty<TextEntryWidthMatcherProperty, bool> { public override void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { // Get panel (typically a grid) var panel = (sender as Panel); // Call SetWidths (also allows the designer to work properly with this) SetWidths(panel); // Wait for panel to load RoutedEventHandler onLoaded = null; onLoaded = (s, ee) => { // Unhook panel.Loaded -= onLoaded; // Set widths SetWidths(panel); // Loop through each child foreach (var child in panel.Children) { // Ignore anything that isn't a TextEntryControl if (!(child is TextEntryControl control)) continue; // Set its width to the given value control.Label.SizeChanged += (ss, eee) => { // Update widths SetWidths(panel); }; } }; // Hook into the Loaded event panel.Loaded += onLoaded; } /// <summary> /// Updates all child TextEntryControl instances so their widths match the greatest width in the group /// </summary> /// <param name="panel">The panel containing the <see cref="TextEntryControl"/>s</param> private void SetWidths(Panel panel) { var maxSize = 0d; foreach (var child in panel.Children) { // Ignore anything that isn't a TextEntryControl if (!(child is TextEntryControl control)) continue; // Find out whether this value is larger than the others maxSize = Math.Max(maxSize, control.Label.RenderSize.Width + control.Label.Margin.Left + control.Label.Margin.Right); } var gridLength = (GridLength)new GridLengthConverter().ConvertFromString(maxSize.ToString()); foreach (var child in panel.Children) { // Ignore anything that isn't a TextEntryControl if (!(child is TextEntryControl control)) continue; // Set each control's LabelWidth value to the max size control.LabelWidth = gridLength; } } } }
068752c2bf70ae2de8fc8da437432aaa9bc08117
C#
FuchsFa/Robot-Puzzle
/Robot-Puzzle/Assets/Scripts/Model/GroundTile.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; #if UNITY_EDITOR using UnityEditor; #endif public class GroundTile : Tile { /// <summary> /// Die Sammlung der möglichen Terrain Types, die Tiles haben können. /// </summary> public enum TerrainType { solid, liquid }; /// <summary> /// Legt fest, welche Objekte auf dem Tile liegen können und welche Beine Roboter benötigen, um auf dem Tile zu stehen. /// </summary> public TerrainType terrainType; /// <summary> /// Tags, die Sensoren benutzen können, um das Tile zu identifizieren. /// </summary> public string[] tags; #if UNITY_EDITOR /// <summary> /// Erstellt ein neues GroundTile. /// </summary> [MenuItem("Assets/Create/GroundTile")] public static void CreateGroundTile() { string path = EditorUtility.SaveFilePanelInProject("Save Ground Tile", "New Ground Tile", "Asset", "Save Ground Tile", "Assets/Resources/Tiles"); if(path == "") { return; } AssetDatabase.CreateAsset(ScriptableObject.CreateInstance<GroundTile>(), path); } #endif }
380eb6ba9a4638b6858fe2c7ef05e6f07f323f66
C#
jhemphill1389/pairgame
/ConsoleGame/Weapons.cs
3.453125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Linq; namespace ConsoleGame { class Weapons { static public void Main() { // Creating a dictionary // using Dictionary<TKey,TValue> class Dictionary<int, string> My_dict = new Dictionary<int, string>(); // Adding key/value pairs in the // Dictionary Using Add() method My_dict.Add(1, "Fish"); My_dict.Add(2, "Frying pan"); My_dict.Add(3, "Brick"); My_dict.Add(4, "Crowbar"); My_dict.Add(5, "Knife"); My_dict.Add(6, "Sword"); My_dict.Add(7, "Pistol"); My_dict.Add(8, "Double-Barelled Shotgun"); My_dict.Add(9, "Bomb"); My_dict.Add(10, "Shield"); for (int i = 1; i < 10; ++i) { int index = random.Next(dictionary.Count); //string key = dictionary.Keys.ElementAt(index); KeyValuePair<string, int> pair = Dictionary.ElementAt(index); Console.WriteLine("key: " + pair.Key + ", value: " + pair.Value); } } } }
505ffaa810da3bb46f19704e200e3086c2ddebba
C#
uranium62/DynamicLib
/DynamicLib/Parser/DynamicTokenType.cs
3.03125
3
namespace DynamicLib.Parser { public enum DynamicTokenType { /// <summary> /// The unknown /// </summary> Unknown, /// <summary> /// The end /// </summary> End, /// <summary> /// The identifier /// </summary> Identifier, /// <summary> /// The string literal /// </summary> StringLiteral, /// <summary> /// The integer literal /// </summary> IntegerLiteral, /// <summary> /// The real literal /// </summary> RealLiteral, /// <summary> /// The exclamation /// </summary> Exclamation, /// <summary> /// The percent /// </summary> Percent, /// <summary> /// The amphersand /// </summary> Amphersand, /// <summary> /// The open paren /// </summary> OpenParen, /// <summary> /// The close paren /// </summary> CloseParen, /// <summary> /// The asterisk /// </summary> Asterisk, /// <summary> /// The plus /// </summary> Plus, /// <summary> /// The comma /// </summary> Comma, /// <summary> /// The minus /// </summary> Minus, /// <summary> /// The dot /// </summary> Dot, /// <summary> /// The slash /// </summary> Slash, /// <summary> /// The colon /// </summary> Colon, /// <summary> /// The less than /// </summary> LessThan, /// <summary> /// The equal /// </summary> Equal, /// <summary> /// The greater than /// </summary> GreaterThan, /// <summary> /// The question /// </summary> Question, /// <summary> /// The open bracket /// </summary> OpenBracket, /// <summary> /// The close bracket /// </summary> CloseBracket, /// <summary> /// The bar /// </summary> Bar, /// <summary> /// The exclamation equal /// </summary> ExclamationEqual, /// <summary> /// The double amphersand /// </summary> DoubleAmphersand, /// <summary> /// The less than equal /// </summary> LessThanEqual, /// <summary> /// The less greater /// </summary> LessGreater, /// <summary> /// The double equal /// </summary> DoubleEqual, /// <summary> /// The greater than equal /// </summary> GreaterThanEqual, /// <summary> /// The double bar /// </summary> DoubleBar } }
5df64eabd1b3d2d8226d6e6ef0280998e5de1823
C#
MiloszKrajewski/protoactor-dotnet
/src/Proto.Actor/Extensions/ActorSystemExtensions.cs
2.5625
3
// ----------------------------------------------------------------------- // <copyright file="ActorSystemExtensions.cs" company="Asynkron AB"> // Copyright (C) 2015-2020 Asynkron AB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; namespace Proto.Extensions { public class ActorSystemExtensions { private readonly ActorSystem _actorSystem; private readonly object _lockObject = new(); private IActorSystemExtension[] _extensions = new IActorSystemExtension[10]; public ActorSystemExtensions(ActorSystem actorSystem) { _actorSystem = actorSystem; } public T? Get<T>() where T : IActorSystemExtension { var id = IActorSystemExtension<T>.Id; return (T) _extensions[id]; } public void Register<T>(IActorSystemExtension<T> extension) where T : IActorSystemExtension { lock (_lockObject) { var id = IActorSystemExtension<T>.Id; if (id >= _extensions.Length) { var newSize = id * 2; //double size when growing Array.Resize(ref _extensions, newSize); } _extensions[id] = extension; } } } }
b5a44a09ad60c1c073f0e5f226f791e9437d2e3d
C#
boyjimeking/u3dArpgDemo
/script/AssetBundlesAssetBundleInfo.cs
2.640625
3
namespace InJoy.AssetBundles { using UnityEngine; using Internal; /// <summary> /// The description of downloaded asset bundle. /// Instances would be created automatically during downloading. /// So end user should not do anything. /// </summary> public class AssetBundleInfo { # region Interface /// <summary> /// Gets information about download. /// </summary> /// <value> /// The description. /// </value> public DownloadManager.Info downloadInfo { get { return m_downloadInfo; } } /// <summary> /// Gets the asset bundle itself. If you want to load asset from /// the asset bundle, it is recommended to use AssetBundles.Load. /// </summary> /// <value> /// The asset bundle. /// </value> public UnityEngine.AssetBundle assetBundle { get { return downloadInfo.assetBundle; } } /// <summary> /// Gets original filename w/o hash suffix of the asset bundle. /// </summary> /// <value> /// The filename. /// </value> public string Filename { get { return m_filename; } } /// <summary> /// Gets size of the asset bundle. /// </summary> /// <value> /// The size. /// </value> public long Size { get { return m_size; } } /// <summary> /// Gets type of the asset bundle. /// </summary> /// <value> /// The type. It could be "Asset" or "Scene". /// </value> public string Type { get { return m_type; } } /// <summary> /// Creates instance of description of the asset bundle. It would /// be invoked automatically from IndexInfo class with correct parameters. /// So end user should not do anything. /// </summary> public AssetBundleInfo(string filename, long size, string contentHash, string type, string[] urls, DownloadManager.OnDownloadCallbackType onDownloadCallback) { Debug.Log("Ctor - Started"); m_filename = filename; m_size = size; int version = RTUtils.HashToVersion(contentHash); m_type = type; m_downloadInfo = DownloadManager.LoadFromCacheOrDownloadAsync(urls, version, onDownloadCallback); Debug.Log("Ctor - Finished"); } #endregion #region Implementation private DownloadManager.Info m_downloadInfo; private string m_filename; private string m_internalName; private long m_size; private string m_type; #endregion } }
882769b36b9624e1ecaa4d4cc2a6c442e181389a
C#
stadnichenko-olga/ITScool
/CourseTasks/Matrixes/Matrix.cs
3.4375
3
using Ranges; using System; using System.Text; using Vectors; namespace Matrixes { public class Matrix { private Vector[] strings; public Matrix(int stringsNumber, int columnsNumber) { if (columnsNumber <= 0) { throw new ArgumentException(nameof(columnsNumber), "dimension is less than 1"); } if (stringsNumber <= 0) { throw new ArgumentException(nameof(stringsNumber), "dimension is less than 1"); } strings = new Vector[stringsNumber]; for (int i = 0; i < stringsNumber; i++) { strings[i] = new Vector(columnsNumber); } } public Matrix(double[,] array) { if (array.Length == 0) { throw new ArgumentException(nameof(array), "dimension is less than 1"); } int stringsNumber = array.GetLength(0); int columnsNumber = array.GetUpperBound(1) + 1; strings = new Vector[stringsNumber]; for (int i = 0; i < stringsNumber; i++) { double[] stringArray = new double[columnsNumber]; for (int j = 0; j < columnsNumber; j++) { stringArray[j] = array[i, j]; } strings[i] = new Vector(stringArray); } } public Matrix(Vector[] array) { if (array.Length == 0) { throw new ArgumentException(nameof(array), "dimension is less than 1"); } strings = new Vector[array.Length]; int i = 0; foreach (Vector vector in array) { strings[i] = new Vector(vector); i++; } } public Matrix(Matrix matrix) { strings = new Vector[matrix.GetStringsNumber()]; int i = 0; foreach (Vector line in matrix.strings) { strings[i] = new Vector(line); i++; } } public int GetStringsNumber() => strings.Length; public int GetColumnsNumber() => strings[0].GetSize(); private bool IsEmpty()=> strings.Length == 0; private double[][] ToArray() { double[][] result = new double[GetStringsNumber()][]; int stringsNumber = GetStringsNumber(); for (int i = 0; i < stringsNumber; i++) { result[i] = new double[GetColumnsNumber()]; Array.Copy(strings[i].ConvertToArray(), result[i], GetColumnsNumber()); } return result; } private void AddString(Vector newString) { Array.Resize(ref strings, GetStringsNumber() + 1); strings[GetStringsNumber() - 1] = new Vector(newString); } public Matrix MultiplyByScalar(double scalar) { Matrix result = new Matrix(GetStringsNumber(), GetColumnsNumber()); for (int i = 0; i < GetStringsNumber(); i++) { strings[i].MultiplyByScalar(scalar); } return this; } public Vector MultiplyByVector(Vector vectorToMultiplicate) { double[] result = new double[GetStringsNumber()]; for (int i = 0; i < GetStringsNumber(); i++) { result[i] = Vector.Multiply(strings[i], vectorToMultiplicate); } return new Vector(result); } public Matrix Append(Matrix matrix2) { int mMin = Math.Min(GetStringsNumber(), matrix2.GetStringsNumber()); for (int i = 0; i < mMin; i++) { strings[i].Add(matrix2.strings[i]); } for (int i = mMin; i < matrix2.GetStringsNumber(); i++) { AddString(matrix2.strings[i]); } return this; } public Matrix Deduct(Matrix matrix2) { int mMin = Math.Min(GetStringsNumber(), matrix2.GetStringsNumber()); for (int i = 0; i < mMin; i++) { strings[i].Subtract(matrix2.strings[i]); } for (int i = mMin; i < matrix2.GetStringsNumber(); i++) { AddString(matrix2.strings[i].MultiplyByScalar(-1)); } return this; } public Vector GetString(int i) { Range validIndexRange = new Range(0, GetStringsNumber()); if (!validIndexRange.IsInside(i)) { throw new ArgumentException(nameof(i) + "value is out of" + validIndexRange.ToString()); } return new Vector(strings[i]); } public Vector GetColumn(int i) { Range validIndexRange = new Range(0, GetColumnsNumber()); if (!validIndexRange.IsInside(i)) { throw new ArgumentException(nameof(i) + "value is out of" + validIndexRange.ToString()); } double[] column = new double[GetStringsNumber()]; int j = 0; foreach (Vector line in strings) { column[j] = line.GetCoordinate(i); j++; } return new Vector(column); } public void SetString(int i, Vector row) { Range validIndexRange = new Range(0, GetStringsNumber()); if (!validIndexRange.IsInside(i)) { throw new ArgumentException(nameof(i) + "value is out of" + validIndexRange.ToString()); } strings[i] = new Vector(new Vector(GetColumnsNumber(), row.ConvertToArray())); } public Matrix Transpose() { int stringsNumber = GetStringsNumber(); int columnsNumber = GetColumnsNumber(); double[][] matrixArray = ToArray(); Vector temp = new Vector(stringsNumber); Array.Resize(ref strings, columnsNumber); for (int i = 0; i < columnsNumber; i++) { for (int j = 0; j < stringsNumber; j++) { temp.SetCoordinate(j, matrixArray[j][i]); } strings[i] = new Vector(temp); } return this; } private Matrix GetMatrixStringDeleted(int index) { Range validIndexRange = new Range(0, GetStringsNumber()); if (!validIndexRange.IsInside(index)) { throw new ArgumentException(nameof(index) + "value is out of" + validIndexRange.ToString()); } Matrix result = new Matrix(GetStringsNumber() - 1, GetColumnsNumber()); for (int i = 0; i < index; i++) { result.strings[i] = new Vector(strings[i]); } for (int i = index; i < GetStringsNumber() - 1; i++) { result.strings[i] = new Vector(strings[i + 1]); } return result; } private Matrix GetMatrixColumnDeleted(int index) { Range validIndexRange = new Range(0, GetColumnsNumber()); if (!validIndexRange.IsInside(index)) { throw new ArgumentException(nameof(index) + "value is out of" + validIndexRange.ToString()); } Matrix result = new Matrix(Transpose().GetMatrixStringDeleted(index)); return result.Transpose(); } public override string ToString() { StringBuilder result = new StringBuilder(); result.Append("{ "); foreach (Vector row in strings) { result.Append(string.Join("; ", row)); } result.Append(" }"); return result.ToString(); } public override int GetHashCode() => GetStringsNumber().GetHashCode() ^ GetColumnsNumber().GetHashCode() ^ GetHashCode(strings); private static int GetHashCode(Vector[] array) { unchecked { int hash = 37; foreach (var item in array) { hash = 17 * hash + item.GetHashCode(); } return hash; } } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } if (obj == null || GetType() != obj.GetType()) { return false; } Matrix matrix2 = (Matrix)obj; return Equals(this, matrix2); } private static bool Equals(Matrix matrix1, Matrix matrix2) { if (matrix1.GetStringsNumber() != matrix2.GetStringsNumber()) { return false; } if (matrix1.GetColumnsNumber() != matrix2.GetColumnsNumber()) { return false; } int n = matrix1.GetStringsNumber(); for (int i = 0; i < n; i++) { if (!matrix1.strings[i].Equals(matrix2.strings[i])) { return false; } } return true; } public static Matrix Append(Matrix matrix1, Matrix matrix2) { Matrix tempMatrix = new Matrix(matrix1); return tempMatrix.Append(matrix2); } public static Matrix Deduct(Matrix matrix1, Matrix matrix2) { Matrix tempMatrix = new Matrix(matrix1); return tempMatrix.Deduct(matrix2); } public static Matrix GetMultiplication(Matrix matrix1, Matrix matrix2) { if (matrix1.IsEmpty()) { throw new ArgumentException(nameof(matrix1), " is empty"); } if (matrix2.IsEmpty()) { throw new ArgumentException(nameof(matrix2), " is empty"); } int stringsNumber = matrix1.GetStringsNumber(); int columnsNumber = matrix2.GetColumnsNumber(); double[,] result = new double[stringsNumber, columnsNumber]; for (int i = 0; i < stringsNumber; i++) { for (int j = 0; j < columnsNumber; j++) { result[i, j] = Vector.Multiply(matrix1.GetString(i), matrix2.GetColumn(j)); } } return new Matrix(result); } public double GetDeterminant() { if (IsEmpty()) { throw new ArgumentException("Matrix is empty"); } if (GetStringsNumber() != GetColumnsNumber()) { throw new ArgumentException(" Matrix is not squared"); } Matrix matrixD = new Matrix(this); int n = matrixD.GetStringsNumber(); if (n == 1) { return matrixD.strings[0].GetCoordinate(0); } if (n == 2) { return matrixD.strings[0].GetCoordinate(0) * matrixD.strings[1].GetCoordinate(1) - matrixD.strings[1].GetCoordinate(0) * matrixD.strings[0].GetCoordinate(1); } double result = 0; for (var j = 0; j < n; j++) { result += Math.Pow(-1, j + 1) * matrixD.strings[1].GetCoordinate(j) * matrixD.GetMatrixColumnDeleted(j).GetMatrixStringDeleted(1).GetDeterminant(); } return result; } } }
eb346b4a0cf3ec841fd1c74388776d7e289dcddf
C#
terry-u16/AtCoder
/Kujikatsu094/Kujikatsu094/Kujikatsu094.Test/AtCoderTester.cs
2.859375
3
using System; using Xunit; using Kujikatsu094.Questions; using System.Collections.Generic; using System.Linq; using Kujikatsu094.Collections; namespace Kujikatsu094.Test { public class AtCoderTester { [Theory] [InlineData(@"4 2 3 7 9", @"7")] [InlineData(@"8 3 1 4 1 5 9 2 6", @"8")] public void QuestionATest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionA(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } [Theory] [InlineData(@"90", @"4")] [InlineData(@"1", @"360")] public void QuestionBTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionB(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } [Theory] [InlineData(@"4 3 4 2 1", @"1")] [InlineData(@"3 1 1000 1", @"0")] [InlineData(@"7 218 786 704 233 645 728 389", @"23")] public void QuestionCTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionC(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } [Theory] [InlineData(@"2 4", @"5")] [InlineData(@"123 456", @"435")] [InlineData(@"123456789012 123456789012", @"123456789012")] public void QuestionDTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionD(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } [Theory] [InlineData(@"4 3 1 2 1 3 1 3 2 4 3 3", @"2 3 1")] [InlineData(@"10 10 2 5 6 5 2 1 7 9 7 2 5 5 2 4 6 7 2 2 7 8 7 9 1 8 6 9 8 10 6 8", @"1 2 2 1 2 2 6 3 3 3")] public void QuestionETest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionE(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } [Theory] [InlineData(@"5 3 10 14 19 34 33", @"202")] [InlineData(@"9 14 1 3 5 110 24 21 34 5 3", @"1837")] [InlineData(@"9 73 67597 52981 5828 66249 75177 64141 40773 79105 16076", @"8128170")] public void QuestionFTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionF(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } [Theory] [InlineData(@"3 1 2 300 3 3 600 1 4 800", @"2900 900 0 0")] [InlineData(@"5 3 5 400 5 3 700 5 5 1000 5 7 700 7 5 400", @"13800 1600 0 0 0 0")] [InlineData(@"6 2 5 1000 5 2 1100 5 5 1700 -2 -5 900 -5 -2 600 -5 -5 2200", @"26700 13900 3200 1200 0 0 0")] [InlineData(@"8 2 2 286017 3 1 262355 2 -2 213815 1 -3 224435 -2 -2 136860 -3 -1 239338 -2 2 217647 -1 3 141903", @"2576709 1569381 868031 605676 366338 141903 0 0 0")] public void QuestionGTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionG(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } void AssertNearlyEqual(IEnumerable<string> expected, IEnumerable<string> actual, double acceptableError = 1e-6) { Assert.Equal(expected.Count(), actual.Count()); foreach (var (exp, act) in (expected, actual).Zip().Select(p => (double.Parse(p.v1), double.Parse(p.v2)))) { var error = act - exp; Assert.InRange(Math.Abs(error), 0, acceptableError); } } IEnumerable<string> SplitByNewLine(string input) => input?.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None) ?? new string[0]; } }
ba03e6bb18fd6e4df7e7d08ec3db147399cdcfd2
C#
yonexbat/AdHocTestingEnvironments
/AdHocTestingEnvironments/Services/Implementations/EnvironmentService.cs
2.5625
3
using AdHocTestingEnvironments.Data; using AdHocTestingEnvironments.Model; using AdHocTestingEnvironments.Model.Entities; using AdHocTestingEnvironments.Model.Environment; using AdHocTestingEnvironments.Services.Interfaces; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AdHocTestingEnvironments.Services.Implementations { public class EnvironmentService: IEnvironmentService { private readonly ILogger _logger; private readonly AdHocTestingEnvironmentsContext _dbContext; public EnvironmentService( ILogger<EnvironmentService> logger, AdHocTestingEnvironmentsContext context) { _logger = logger; _dbContext = context; } public async Task<ApplicationInfo> GetApplication(string name) { ApplicationInfoEntity info = await _dbContext.InfoEntities.Where(x => x.Name == name) .SingleAsync(); var res = new ApplicationInfo() { Name = info.Name, ContainerImage = info.ContainerImage, HasDatabase = info.HasDatabase, InitSql = info.InitSql, }; return res; } public async Task<IList<Application>> ListEnvironmetns() { return await _dbContext.InfoEntities .OrderBy(x => x.Name) .Select(x => new Application { Name = x.Name }) .ToListAsync(); } } }
e53c974fcf047e1502b5ee46bc72f97877ddb065
C#
evak2979/CheckoutTest
/tests/Checkout.Tests.Acceptance/PaymentGatewayControllerTests.cs
2.53125
3
using System; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Checkout.Web.Models; using Newtonsoft.Json; using Shouldly; using Xunit; namespace Checkout.Tests.Acceptance { [Collection("Container collection")] public class PaymentGatewayControllerTests { private HttpClient _httpClient; public PaymentGatewayControllerTests() { HttpClientHandler clientHandler = new HttpClientHandler(); clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }; _httpClient = new HttpClient(clientHandler); } [Fact] public async Task GivenASubmitPaymentRequest_WhenValidPayment_ShouldReturn200SuccessCode() { // given var submitPaymentRequest = new SubmitPaymentRequest { CardDetails = new CardDetails { CVV = 123, Currency = "Pound", ExpiryDate = "01/2020", CardNumber = 1234567890123456 }, MerchantDetails = new MerchantDetails { MerchantId = Guid.NewGuid() }, Amount = 12345 }; var jsonRequest = JsonConvert.SerializeObject(submitPaymentRequest); // when var submitPaymentResponse = await _httpClient.PostAsync("https://localhost:9901/paymentgateway", new StringContent(jsonRequest, Encoding.UTF8, "application/json")); // then submitPaymentResponse.IsSuccessStatusCode.ShouldBeTrue(); var responseContent = await submitPaymentResponse.Content.ReadAsStringAsync(); var paymentInformation = JsonConvert.DeserializeObject<SubmitPaymentResponse>(responseContent); paymentInformation.PaymentId.ShouldBeOfType<Guid>(); paymentInformation.PaymentResponseStatus.ShouldBe("Successful"); } [Fact] public async Task GivenAPaymentRequest_WhenPaymentExists_ShouldReturn200SuccessCodeAndPaymentInformation() { // given var submitPaymentRequest = new SubmitPaymentRequest { CardDetails = new CardDetails { CVV = 123, Currency = "Pound", ExpiryDate = "01/2020", CardNumber = 1234567890123456 }, MerchantDetails = new MerchantDetails { MerchantId = Guid.NewGuid() }, Amount = 12345 }; var jsonRequest = JsonConvert.SerializeObject(submitPaymentRequest); var submitPaymentResponse = await _httpClient.PostAsync("https://localhost:9901/paymentgateway", new StringContent(jsonRequest, Encoding.UTF8, "application/json")); var responseContent = await submitPaymentResponse.Content.ReadAsStringAsync(); var paymentInformation = JsonConvert.DeserializeObject<SubmitPaymentResponse>(responseContent); // when var retrievePaymentResponse = await _httpClient.GetAsync($"https://localhost:9901/paymentgateway?paymentId={paymentInformation.PaymentId}&merchantId={submitPaymentRequest.MerchantDetails.MerchantId}"); // then retrievePaymentResponse.IsSuccessStatusCode.ShouldBeTrue(); var content = await retrievePaymentResponse.Content.ReadAsStringAsync(); var retrievedPayment = JsonConvert.DeserializeObject<RetrievePaymentResponse>(content); retrievedPayment.Amount.ShouldBe(submitPaymentRequest.Amount); retrievedPayment.CVV.ShouldBe("***"); retrievedPayment.CardNumber.ShouldBe("1234********3456"); retrievedPayment.ExpiryDate.ShouldBe(submitPaymentRequest.CardDetails.ExpiryDate); retrievedPayment.Currency.ShouldBe(submitPaymentRequest.CardDetails.Currency); retrievedPayment.PaymentResponseStatus.ShouldBe("Successful"); } [Fact] public async Task GivenAPaymentRequest_WhenPaymenDoesNotExist_ShouldReturn404() { // given + when var retrievePaymentResponse = await _httpClient.GetAsync($"https://localhost:9901/paymentgateway?paymentId={Guid.NewGuid()}&merchantId={Guid.NewGuid()}"); // then retrievePaymentResponse.StatusCode.ShouldBe(HttpStatusCode.NotFound); } [Fact] public async Task GivenASubmitPaymentRequest_WhenPaymentUnsuccessful_ShouldReturn400() { // given var submitPaymentRequest = new SubmitPaymentRequest { CardDetails = new CardDetails { CVV = 123, Currency = "Pound", ExpiryDate = "01/2020", CardNumber = 1234567890123456 }, MerchantDetails = new MerchantDetails { MerchantId = Guid.NewGuid() }, Amount = -1000 }; var jsonRequest = JsonConvert.SerializeObject(submitPaymentRequest); // when var submitPaymentResponse = await _httpClient.PostAsync("https://localhost:9901/paymentgateway", new StringContent(jsonRequest, Encoding.UTF8, "application/json")); // then submitPaymentResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); } } }
d0d19547625da6cef6b459a224b5016c0f4aabc7
C#
ridgew/BraneCloud
/Source/Projects/EC/App/CartPole/CartPole.cs
2.734375
3
using System; using BraneCloud.Evolution.EC.Configuration; using BraneCloud.Evolution.EC.NEAT; using BraneCloud.Evolution.EC.Simple; using BraneCloud.Evolution.EC.Util; namespace BraneCloud.Evolution.EC.App.CartPole { [ECConfiguration("ec.app.cartpole.CartPole")] public class CartPole : Problem, ISimpleProblem { int MAX_STEPS = 100000; double _x, /* cart position, meters */ _xDot, /* cart velocity */ _theta, /* pole angle, radians */ _thetaDot; /* pole angular velocity */ int _steps, _y; public double[] GetNetOutput(NEATNetwork net, double[][] input, IEvolutionState state) { double[] output; int netDepth = net.MaxDepth(); net.LoadSensors(input[0]); for (int relax = 0; relax < netDepth; relax++) { net.Activate(state); } output = net.GetOutputResults(); net.Flush(); return output; } public int RunCartPole(NEATNetwork net, IEvolutionState state) { // double in[] = new double[5]; //Input loading array double out1; double out2; double twelve_degrees = 0.2094384; _x = _xDot = _theta = _thetaDot = 0.0; _steps = 0; double[][] input = TensorFactory.Create<double>(1, 5); while (_steps++ < MAX_STEPS) { /*-- setup the input layer based on the four inputs and bias --*/ //setup_input(net,x,x_dot,theta,theta_dot); input[0][0] = 1.0; //Bias input[0][1] = (_x + 2.4) / 4.8; input[0][2] = (_xDot + .75) / 1.5; input[0][3] = (_theta + twelve_degrees) / .41; input[0][4] = (_thetaDot + 1.0) / 2.0; double[] output = GetNetOutput(net, input, state); /*-- decide which way to push via which output unit is greater --*/ if (output[0] > output[1]) _y = 0; else _y = 1; /*--- Apply action to the simulated cart-pole ---*/ cart_pole(_y); /*--- Check for failure. If so, return steps ---*/ if (_x < -2.4 || _x > 2.4 || _theta < -twelve_degrees || _theta > twelve_degrees) return _steps; } return _steps; } void cart_pole(int action) { double xacc, thetaacc, force, costheta, sintheta, temp; double GRAVITY = 9.8; double MASSCART = 1.0; double MASSPOLE = 0.1; double TOTAL_MASS = MASSPOLE + MASSCART; double LENGTH = 0.5; /* actually half the pole's length */ double POLEMASS_LENGTH = MASSPOLE * LENGTH; double FORCE_MAG = 10.0; double TAU = 0.02; /* seconds between state updates */ double FOURTHIRDS = 1.3333333333333; force = action > 0 ? FORCE_MAG : -FORCE_MAG; costheta = Math.Cos(_theta); sintheta = Math.Sin(_theta); temp = (force + POLEMASS_LENGTH * _thetaDot * _thetaDot * sintheta) / TOTAL_MASS; thetaacc = (GRAVITY * sintheta - costheta * temp) / (LENGTH * (FOURTHIRDS - MASSPOLE * costheta * costheta / TOTAL_MASS)); xacc = temp - POLEMASS_LENGTH * thetaacc * costheta / TOTAL_MASS; /*** Update the four state variables, using Euler's method. ***/ _x += TAU * _xDot; _xDot += TAU * xacc; _theta += TAU * _thetaDot; _thetaDot += TAU * thetaacc; } public void Evaluate(IEvolutionState state, Individual ind, int subpop, int threadnum) { if (ind.Evaluated) return; if (!(ind is NEATIndividual)) state.Output.Fatal("Whoa! It's not a NEATIndividual!!!", null); var neatInd = (NEATIndividual) ind; if (!(neatInd.Fitness is SimpleFitness)) state.Output.Fatal("Whoa! It's not a SimpleFitness!!!", null); NEATNetwork net = neatInd.CreateNetwork(); double fitness = RunCartPole(net, state); ((SimpleFitness) neatInd.Fitness).SetFitness(state, fitness, fitness >= MAX_STEPS); neatInd.Evaluated = true; } } }
d50f17ff8513c7807d7d3aa92252b3a82a3fba61
C#
reudismam/Refazer
/TreeElement/Spg.Isomorphic/IsomorphicManager.cs
2.890625
3
using System; using System.Collections.Generic; using RefazerFunctions.Substrings; using TreeElement.Spg.Mapping; using TreeElement.Spg.Node; namespace TreeEdit.Spg.Isomorphic { public class IsomorphicManager<T> { public static bool IsIsomorphic(TreeNode<T> t1, TreeNode<T> t2) { return AhuTreeIsomorphism(t1, t2); } public static TreeNode<T> FindIsomorphicSubTree(TreeNode<T> tree, TreeNode<T> subtree) { if (IsIsomorphic(tree, subtree)) return tree; foreach (var child in tree.Children) { var result = FindIsomorphicSubTree(child, subtree); if (result != null) return result; } return null; } public static bool AhuTreeIsomorphism(TreeNode<T> t1, TreeNode<T> t2) { var talg = new TreeAlignment<T>(); Dictionary<TreeNode<T>, string> dict1 = talg.Align(t1); Dictionary<TreeNode<T>, string> dict2 = talg.Align(t2); var ahuT1 = dict1[t1]; var ahuT2 = dict2[t2]; if (ahuT1.Equals(ahuT2)) { return true; } return false; } public static List<Tuple<TreeNode<T>, TreeNode<T>>> AllPairOfIsomorphic(TreeNode<T> t1, TreeNode<T> t2) { var pairs = new IsomorphicPairs<T>(); var ps = pairs.Pairs(t1, t2); return ps; } } }
976c16b81a6053f48aac477edf2c416109df0d6a
C#
GeorgiPetrovGH/TelerikAcademy
/12.Data-Structures-and-Algorithms/07. Recursion/Recursion/SubsetsOfStrings/Startup.cs
3.703125
4
namespace SubsetsOfStrings { using System; public class Startup { private static int k = 2; private static string[] words = { "test", "rock", "fun" }; private static string[] result = new string[k]; public static void Main() { GenerateVariatons(0, 0); } private static void GenerateVariatons(int index, int start) { if (index == k) { Console.WriteLine(string.Join(", ", result)); return; } for (int i = start; i < words.Length; i++) { result[index] = words[i]; GenerateVariatons(index + 1, i + 1); } } } }
7a3e8a20ca27561b84f005b69d322175a28dd636
C#
Novikevicius/BattleCity
/Assets/Scripts/Shooting.cs
2.75
3
using System; using BattleCity.Miscellaneous; using UnityEngine; namespace BattleCity { public class Shooting { public const float halfTankSize = 0.2f; private Direction bulletDirection; private GameObject bulletSpawn; private GameObject bulletPrefab; public Shooting (GameObject _bulletSpawn, GameObject _bulletPrefab) { bulletSpawn = _bulletSpawn; bulletPrefab = _bulletPrefab; bulletDirection = Direction.Up;; } public void Shoot (GameObject shooter, Movement movement, float speed) { if (bulletPrefab == null) throw new ArgumentNullException("BulletPrefab", "Bullet prefab is not set"); SetDirection(movement); SetBulletSpawnPosition(shooter.transform); SpawnBullet(shooter, speed); } private void SetBulletSpawnPosition (Transform transform) { Vector3 tankPosition = transform.position; switch (bulletDirection) { case Direction.Up: { bulletSpawn.transform.position = new Vector3(0f, halfTankSize, 0f) + tankPosition; break; } case Direction.Down: { bulletSpawn.transform.position = new Vector3(0f, -halfTankSize, 0f) + tankPosition; break; } case Direction.Left: { bulletSpawn.transform.position = new Vector3(-halfTankSize, 0f, 0f) + tankPosition; break; } case Direction.Right: { bulletSpawn.transform.position = new Vector3(halfTankSize, 0f, 0f) + tankPosition; break; } } } private void SetDirection (Movement movement) { bulletDirection = movement.Direction; } private void SpawnBullet (GameObject shooter, float speed) { if (bulletDirection == Direction.None) bulletDirection = Direction.Up; GameObject.Instantiate(bulletPrefab, bulletSpawn.transform.position, Quaternion.identity).GetComponent<Bullet>().InitializeBullet(bulletDirection, shooter, speed); } } }
9592ee4e1fc01f8de2a1264cca869f470ad987c1
C#
Alireza1044/DS97981
/A10/A10/RabinKarp.cs
2.765625
3
using System; using System.Collections.Generic; using TestCommon; namespace A10 { public class RabinKarp : Processor { public RabinKarp(string testDataName) : base(testDataName) { } public override string Process(string inStr) => TestTools.Process(inStr, (Func<string, string, long[]>)Solve); const long d = 256; const long q = 1000000007; static long patHash=0, txtHash=0, h = 1, M, N; public long[] Solve(string pattern, string text) { List<long> occurrences = new List<long>(); M = pattern.Length; N = text.Length; txtHash = 0; patHash = 0; h = 1; for (int i = 0; i < M - 1; i++) { h = (h * d) % q; } GetHash(pattern, text); for (int i = 0; i <= N - M; i++) { if (patHash == txtHash) { int j = new int(); for (j = 0; j < M; j++) { if (text[i + j] != pattern[j]) { break; } } if (j == M) occurrences.Add(i); } if (i < N - M) { txtHash = (d * (txtHash - text[i] * h) + text[i + (int)M]) % q; } if (txtHash < 0) txtHash += q; } return occurrences.ToArray(); } public static void GetHash(string pattern, string text) { for (int i = 0; i < M; i++) { patHash = (d * patHash + pattern[i]) % q; txtHash = (d * txtHash + text[i]) % q; } } public static long[] PreComputeHashes( string T, int P, long p, long x) { return null; } } }
8a5302c0ae93181247ec392d0bb5bccac98cf862
C#
MrBean355/KinderFinder
/Source Code/AdminPortal/AdminPortal/Controllers/WebAPI/Transmitters/FreeTransmitterController.cs
2.578125
3
using AdminPortal.Models; using System.Web.Http; namespace AdminPortal.Controllers.WebAPI.Transmitters { /** * Deregisters a transmitter from the system. */ public class FreeTransmitterController : ApiController { private KinderFinderEntities Db = new KinderFinderEntities(); [HttpPost] public IHttpActionResult FreeTransmitter(RequestDetails details) { int id = int.Parse(details.ID); var transmitter = Db.Transmitters.Find(id); if (transmitter == null) return BadRequest(); System.Diagnostics.Debug.WriteLine("[Info] Transmitter " + id + " removed from system."); Db.Transmitters.Remove(transmitter); Db.SaveChanges(); return Ok(); } public struct RequestDetails { public string ID; } } }
36a87e73961c292ca94de36e8945f2471e1ab163
C#
alaAlex/SapHotelReservations
/BookingApp/Program.cs
3.734375
4
using System; namespace BookingApp { class Program { static void Main(string[] args) { Console.WriteLine("Welcome"); Console.WriteLine("Please enter size of your hotel: "); int hotelSize; while (!int.TryParse(Console.ReadLine(), out hotelSize) || hotelSize > 1000) { Console.WriteLine("Bad data: size should be a number less than 10000"); Console.WriteLine("Please enter size of your hotel: "); } Hotel hotel = new Hotel(hotelSize); while (true) { Console.Write("Enter 'y' if you want to make a reservation, 'n' for termination: "); string makeReservation = Console.ReadLine(); if (makeReservation.ToLower().Equals("y")) { try { Console.Write("Enter start day: "); int startDay = int.Parse(Console.ReadLine()); Console.Write("Enter end day: "); int endDay = int.Parse(Console.ReadLine()); bool reservationAccepted = hotel.IsReservationAccepted(startDay, endDay); string acceptance = reservationAccepted ? "accepted" : "declined"; Console.WriteLine("Your reservation is {0}", acceptance); } catch (Exception) { Console.WriteLine("Bad data"); } } else if (makeReservation.ToLower().Equals("n")) { break; } } } } }
04de9abcc18c6adfcc877c4507afea6ac968f007
C#
x-danma/OOPTest
/OOP/OOPvsFunc/GUIs/TerminalGUI.cs
3.34375
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; namespace OOPvsFunc { public class TerminalGUI : IGUI { protected virtual string ShowPeoplePrefix { get; set; } = " - "; public void ShowPeople(ReadOnlyCollection<Person> people) { Console.WriteLine("Your current people in your register are:"); foreach (var person in people) { Console.WriteLine($"{ShowPeoplePrefix}{person.FirstName} {person.LastName} {person.Age} {person.Ssn}"); } } public virtual void ShowMenu() { Console.WriteLine(@"Hello welcome to the personprogram. Enter q to quit Enter p to print persons Enter a to add person Enter d to delete a person by ssn Enter f to read people from file Enter m to switch menu Enter s to search for people" ); } public virtual IAction GetAction() { string input = Console.ReadLine(); switch (input) { case "q": return new QuitAction(); case "p": return new PrintAction(); case "a": return new AddAction(new Person(GetStringInput("Enter firstname"), GetStringInput("Enter last name"), GetIntInput("Enter age"), new SocialNumber(GetStringInput("Enter Social security number")))); case "d": return new DeleteAction(new SocialNumber(GetStringInput("Enter social security number"))); case "m": return new SwitchMenuAction(new SwitchMenuGUI()); case "f": return new ReadFromFileAction(GetStringInput("Enter filename")); case "s": return new FindAction(GetStringInput("Please enter firstname")); default: Console.WriteLine("Please enter a correct input\n----------------------\n"); throw new FormatException(); } } private string GetStringInput(string v) { Console.WriteLine(v); return Console.ReadLine(); } private int GetIntInput(string v) { int output; while (true) { Console.WriteLine(v); if (Int32.TryParse(Console.ReadLine(), out output)) return output; Console.WriteLine("Please enter a number\n----------------------\n"); } } } }
e85989397edd4fd1990c03371e624ec3c35687e8
C#
Hlib7Dol/AnimalZooBinary
/Animal/AnimalZooBinary/AnimalZooBinary/Controller/FindBy.cs
3.390625
3
using AnimalZooBinary.Animals; using AnimalZooBinary.Scope; using System; using System.Linq; using System.Collections.Generic; using System.Text; namespace AnimalZooBinary.Controller { internal class FindBy { internal void GroupByType(List<BaseAnimal> animals) { var groupedAnimals = animals.GroupBy(x => x.GetAnimalType()).SelectMany(g => g).ToList(); foreach (var animal in groupedAnimals) { Console.WriteLine("The animal is " + (animal as BaseAnimal).GetAnimalType() + " his name is " + (animal as BaseAnimal).GetAnimalName()); } Console.WriteLine("Press / to refresh window"); } internal void FindByState(AnimalStateEnum state, List<BaseAnimal> animals) { var groupedAnimals = animals.Where(animal => animal.GetAnimalState() == state); foreach (var animal in groupedAnimals) { Console.WriteLine("The animal`s state is " + animal.GetAnimalState() + " his name is " + animal.GetAnimalName()); } Console.WriteLine("Press / to refresh window"); } internal List<BaseAnimal> FindSickTigers(List<BaseAnimal> animals) { animals = animals.FindAll(x => x.GetAnimalState() == AnimalStateEnum.Sick) .FindAll(x => x.GetAnimalType() == "Tiger") as List<BaseAnimal>; foreach (var animal in animals) { Console.WriteLine("The elephants " + animal.GetAnimalType() + "`s name is " + animal.GetAnimalName()); } Console.WriteLine("Press / to refresh window"); return animals; } internal List<BaseAnimal> FindElephantByName(string name, List<BaseAnimal> animals) { animals = animals.FindAll(x => x.GetAnimalType() == "Elephant") .FindAll(x => x.GetAnimalName() == name) as List<BaseAnimal>; Console.WriteLine("You have found the elephant " + animals[0].GetAnimalName()); Console.WriteLine("Press / to refresh window"); return animals; } internal List<BaseAnimal> FindAllWhichAreHungry(List<BaseAnimal> animals) { animals = animals.FindAll(x => x.GetAnimalState() == AnimalStateEnum.Hungry) .FindAll(x => x.GetAnimalType() == "Tiger") as List<BaseAnimal>; foreach (var animal in animals) { Console.WriteLine("The hungry " + animal.GetAnimalType() +"`s name is " + animal.GetAnimalName()); } Console.WriteLine("Press / to refresh window"); return animals; } internal List<BaseAnimal> FindAllDead(List<BaseAnimal> animals) { animals = animals.FindAll(x => x.GetAnimalState() == AnimalStateEnum.Dead) .GroupBy(x => x.GetAnimalType()) as List<BaseAnimal>; foreach (var animal in animals) { Console.WriteLine("The dead animal name is " + animal.GetAnimalName()); } Console.WriteLine("Press / to refresh window"); return animals; } internal List<BaseAnimal> FindWolfsAndBears(List<BaseAnimal> animals) { var wolfs = animals.FindAll(x => x.GetAnimalType() == "Wolf"); var bears = animals.FindAll(x => x.GetAnimalType() == "Bear"); wolfs.AddRange(bears); wolfs = wolfs.FindAll(x => x.GetAnimalHealth() > 3) as List<BaseAnimal>; foreach (var animal in wolfs) { Console.WriteLine("The " + animal.GetAnimalType() + " name is : " + animal.GetAnimalName()); } Console.WriteLine("Press / to refresh window"); return animals; } internal double FindAvarageHealthInZoo(List<BaseAnimal> animals) { Console.WriteLine("The avarage is : " + animals.Average(x => x.GetAnimalHealth())); Console.WriteLine("Press / to refresh window"); return animals.Average(x => x.GetAnimalHealth()); } internal void FindMinMaxHealth(List<BaseAnimal> animals) { var resList = new Tuple<int, int>(animals.Max(x => x.GetAnimalHealth()), animals.Min(x => x.GetAnimalHealth())); Console.WriteLine("Min:" + resList.Item2 + " Max:" + resList.Item2); Console.WriteLine("Press / to refresh window"); } internal List<BaseAnimal> MaxHealth(List<BaseAnimal> animals) { var res = (from a in animals group a by a.GetAnimalType() into gr select gr.OrderBy(a => a.GetAnimalHealth()).Last()) as List<BaseAnimal>; foreach (var animal in animals) { Console.WriteLine("The " + animal.GetAnimalType() + " name is : " + animal.GetAnimalName() + " his health is " + animal.GetAnimalHealth()); } Console.WriteLine("Press / to refresh window"); return res; } } }
a560fa713e9ac27c2948a92720488b94f62b2452
C#
Damnae/storybrew
/editor/UserInterface/Vector2Picker.cs
2.625
3
using BrewLib.UserInterface; using OpenTK; using System; using System.Globalization; namespace StorybrewEditor.UserInterface { public class Vector2Picker : Widget, Field { private readonly LinearLayout layout; private readonly Textbox xTextbox; private readonly Textbox yTextbox; public override Vector2 MinSize => layout.MinSize; public override Vector2 MaxSize => Vector2.Zero; public override Vector2 PreferredSize => layout.PreferredSize; private Vector2 value; public Vector2 Value { get { return value; } set { if (this.value == value) return; this.value = value; updateWidgets(); OnValueChanged?.Invoke(this, EventArgs.Empty); } } public object FieldValue { get { return Value; } set { Value = (Vector2)value; } } public event EventHandler OnValueChanged; public event EventHandler OnValueCommited; public Vector2Picker(WidgetManager manager) : base(manager) { Add(layout = new LinearLayout(manager) { FitChildren = true, Children = new Widget[] { new LinearLayout(manager) { Horizontal = true, FitChildren = true, Fill = true, Children = new Widget[] { new Label(Manager) { StyleName = "small", Text = "X", CanGrow = false, }, xTextbox = new Textbox(manager) { EnterCommits = true, }, }, }, new LinearLayout(manager) { Horizontal = true, FitChildren = true, Fill = true, Children = new Widget[] { new Label(Manager) { StyleName = "small", Text = "Y", CanGrow = false, }, yTextbox = new Textbox(manager) { EnterCommits = true, }, }, }, }, }); updateWidgets(); xTextbox.OnValueCommited += xTextbox_OnValueCommited; yTextbox.OnValueCommited += yTextbox_OnValueCommited; } private void xTextbox_OnValueCommited(object sender, EventArgs e) { var xCommit = xTextbox.Value; float x; try { x = float.Parse(xCommit, CultureInfo.InvariantCulture); } catch { updateWidgets(); return; } Value = new Vector2(x, value.Y); OnValueCommited?.Invoke(this, EventArgs.Empty); } private void yTextbox_OnValueCommited(object sender, EventArgs e) { var yCommit = yTextbox.Value; float y; try { y = float.Parse(yCommit, CultureInfo.InvariantCulture); } catch { updateWidgets(); return; } Value = new Vector2(value.X, y); OnValueCommited?.Invoke(this, EventArgs.Empty); } private void updateWidgets() { xTextbox.SetValueSilent(value.X.ToString(CultureInfo.InvariantCulture)); yTextbox.SetValueSilent(value.Y.ToString(CultureInfo.InvariantCulture)); } protected override void Layout() { base.Layout(); layout.Size = Size; } } }
39a5886cc9d40762a2ceddfeaee1ef1cb2f66dae
C#
aadjesus/Diversos
/Exemplos_Internet/WPF/126_Ink-A-Mator/ArtControls/Palette.cs
2.53125
3
/**************************************************************************** * * * Created By: Ernie Booth * * Contact: ebooth@microsoft.com - http://blogs.msdn.com/ebooth * * Last Modified: 6/23/2006 * * * * **************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; 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 ArtControls { /// <summary> /// ======================================== /// Palette Control: /// Allows user to pick a color from the gradient color palette. For this palette we do all of the color /// interpolation by hand so that we can do four color blends and a fun palette. /// ======================================== /// /// Follow steps 1a or 1b and then 2 to use this custom control in a XAML file. /// /// Step 1a) Using this custom control in a XAML file that exists in the current project. /// Add this XmlNamespace attribute to the root element of the markup file where it is /// to be used: /// /// xmlns:MyNamespace="clr-namespace:ArtControls" /// /// /// Step 1b) Using this custom control in a XAML file that exists in a different project. /// Add this XmlNamespace attribute to the root element of the markup file where it is /// to be used: /// /// xmlns:MyNamespace="clr-namespace:ArtControls;assembly=ArtControls" /// /// You will also need to add a project reference from the project where the XAML file lives /// to this project and Rebuild to avoid compilation errors: /// /// Right click on the target project in the Solution Explorer and /// "Add Reference"->"Projects"->[Browse to and select this project] /// /// /// Step 2) /// Go ahead and use your control in the XAML file. Note that Intellisense in the /// XML editor does not currently work on custom controls and its child elements. /// /// <MyNamespace:Palette/> /// /// </summary> public class Palette : Control { static Palette() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(Palette), new FrameworkPropertyMetadata(typeof(Palette))); } /// <summary> /// Create our Palette. /// </summary> public Palette() { // This is the setup for the colors that define the four corners of the four color blend. upperLeftColor = Brushes.Red; upperRightColor = Brushes.Blue; lowerLeftColor = Brushes.Yellow; lowerRightColor = Brushes.Green; // Create the BitmapSource and paint it for the palette. MainPalette = CreateMasterPalette(); FourColorPalette = CreateFourColorPalette(); // Create our Image controls. We need them here because we do mouse position look up on them. MainPaletteImage = new Image(); FourColorPaletteImage = new Image(); MainPaletteImage.MouseLeftButtonDown += new MouseButtonEventHandler(OnSelectedMainPalette); FourColorPaletteImage.MouseLeftButtonDown += new MouseButtonEventHandler(OnSelectedFourColorPalette); MainPaletteImage.Source = MainPalette; FourColorPaletteImage.Source = FourColorPalette; // We need to update what our source is. CornerControlClick = new RoutedCommand("RadioButtonClick", typeof(Palette)); CommandBinding radioButtionHandler = new CommandBinding(CornerControlClick); radioButtionHandler.CanExecute += new CanExecuteRoutedEventHandler(SetCanExecuteTrue); radioButtionHandler.Executed += new ExecutedRoutedEventHandler(OnFourColorCornerControlHit); this.CommandBindings.Add(radioButtionHandler); } /// <summary> /// We use Tags in our generic.xaml file to define which control is responsible for which corner of the four color palette. /// </summary> string ActiveColorCorner = "UpperLeft"; /// <summary> /// This handles figuring out which of the corner controls is active. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void OnFourColorCornerControlHit(object sender, ExecutedRoutedEventArgs e) { FrameworkElement fe = e.OriginalSource as FrameworkElement; if (fe == null) return; ActiveColorCorner = fe.Tag.ToString(); } /// <summary> /// Update the correct brush based on which is the active corner control. /// </summary> /// <param name="brush"></param> void UpdateColor(SolidColorBrush brush) { switch (ActiveColorCorner) { case "UpperRight": upperRightColor = brush; break; case "UpperLeft": upperLeftColor = brush; break; case "LowerRight": lowerRightColor = brush; break; case "LowerLeft": lowerLeftColor = brush; break; default: break; } // Recreate our palette and assign it to our image control. FourColorPalette = CreateFourColorPalette(); FourColorPaletteImage.Source = FourColorPalette; } /// <summary> /// Sets CanExecute = true; /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void SetCanExecuteTrue(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } /// <summary> /// Our pixels that we index into when a palette is clicked on. They are also used to create the Bitmap Source. /// </summary> Byte[] pixels, masterPixels; /// <summary> /// The size of our four color palette. We need to have a specific size because we index into the palette. /// Resizing would cause the lookup to work incorrectly so don't put the palettes in some control that is going to /// automatically size them. /// </summary> Size FourColorPaletteSize = new Size(203, 203); /// <summary> /// Our Master palette size is important. While it's width is arbitrary it's height must result in (Height Mod 7 == 0) or it will not /// draw correctly. For example 104 % 7 == 6 which means that we will have blank lines in our palette. /// </summary> Size MasterPaletteSize = new Size(25, 105); /// <summary> /// The number of Bytes Per Pixel we use. Since we use RGB24 bit color, thats 8 bits per color we have 3 bytes per pixel. /// </summary> int bytesPerPixel = 3; /// <summary> /// We need to alter the outside world when the color changes. /// </summary> public event RoutedEventHandler ColorChanged; protected void OnColorChanged(object sender, RoutedEventArgs e) { if (ColorChanged != null) { ColorChanged(sender, e); } } /// <summary> /// The property that tells the outside world what the current selected color is. /// </summary> public SolidColorBrush SelectedColor { get { return (SolidColorBrush)GetValue(SelectedColorProperty); } set { SetValue(SelectedColorProperty, value); OnColorChanged(MainPaletteImage, new RoutedEventArgs()); } } // Using a DependencyProperty as the backing store for PickedColor. This enables animation, styling, binding, etc... public static readonly DependencyProperty SelectedColorProperty = DependencyProperty.Register("SelectedColor", typeof(SolidColorBrush), typeof(Palette), new UIPropertyMetadata(new SolidColorBrush())); /// <summary> /// Figure out which color was selected in the four color palette. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void OnSelectedFourColorPalette(object sender, MouseButtonEventArgs e) { Point p = e.GetPosition(FourColorPaletteImage); int pixelIndex = (int)((int)(p.Y) * FourColorPaletteSize.Width * bytesPerPixel + (int)(p.X) * bytesPerPixel); byte r = pixels[pixelIndex]; byte g = pixels[pixelIndex + 1]; byte b = pixels[pixelIndex + 2]; SelectedColor = new SolidColorBrush(Color.FromRgb(r, g, b)); } /// <summary> /// Figure out which color was picked in our main palette. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void OnSelectedMainPalette(object sender, MouseButtonEventArgs e) { Point p = e.GetPosition(MainPaletteImage); int pixelIndex = (int)((int)(p.Y) * MasterPaletteSize.Width * bytesPerPixel + (int)(p.X) * bytesPerPixel); byte r = masterPixels[pixelIndex]; byte g = masterPixels[pixelIndex + 1]; byte b = masterPixels[pixelIndex + 2]; // We need to update our four color palette with this choice along with the corner controls. UpdateColor(new SolidColorBrush(Color.FromRgb(r, g, b))); } /// <summary> /// Command for when one of the corner controls is clicked. /// </summary> public RoutedCommand CornerControlClick { get { return (RoutedCommand)GetValue(CornerControlClickProperty); } set { SetValue(CornerControlClickProperty, value); } } // Using a DependencyProperty as the backing store for RadioButtonClick. This enables animation, styling, binding, etc... public static readonly DependencyProperty CornerControlClickProperty = DependencyProperty.Register("CornerControlClick", typeof(RoutedCommand), typeof(Palette), new UIPropertyMetadata(null)); /// <summary> /// Create Dependency Properties for the four corner control brushes. /// </summary> #region CornerColor Brushes public SolidColorBrush upperLeftColor { get { return (SolidColorBrush)GetValue(upperLeftColorProperty); } set { SetValue(upperLeftColorProperty, value); } } // Using a DependencyProperty as the backing store for upperLeftColor. This enables animation, styling, binding, etc... public static readonly DependencyProperty upperLeftColorProperty = DependencyProperty.Register("upperLeftColor", typeof(SolidColorBrush), typeof(Palette), new UIPropertyMetadata(null)); public SolidColorBrush upperRightColor { get { return (SolidColorBrush)GetValue(upperRightColorProperty); } set { SetValue(upperRightColorProperty, value); } } // Using a DependencyProperty as the backing store for upperRightColor. This enables animation, styling, binding, etc... public static readonly DependencyProperty upperRightColorProperty = DependencyProperty.Register("upperRightColor", typeof(SolidColorBrush), typeof(Palette), new UIPropertyMetadata(null)); public SolidColorBrush lowerLeftColor { get { return (SolidColorBrush)GetValue(lowerLeftColorProperty); } set { SetValue(lowerLeftColorProperty, value); } } // Using a DependencyProperty as the backing store for lowerLeftColor. This enables animation, styling, binding, etc... public static readonly DependencyProperty lowerLeftColorProperty = DependencyProperty.Register("lowerLeftColor", typeof(SolidColorBrush), typeof(Palette), new UIPropertyMetadata(null)); public SolidColorBrush lowerRightColor { get { return (SolidColorBrush)GetValue(lowerRightColorProperty); } set { SetValue(lowerRightColorProperty, value); } } // Using a DependencyProperty as the backing store for lowerRightColor. This enables animation, styling, binding, etc... public static readonly DependencyProperty lowerRightColorProperty = DependencyProperty.Register("lowerRightColor", typeof(SolidColorBrush), typeof(Palette), new UIPropertyMetadata(null)); #endregion BitmapSource mainPalette; public BitmapSource MainPalette { get { return mainPalette; } set { mainPalette = value; } } BitmapSource fourColorPalette; public BitmapSource FourColorPalette { get { return fourColorPalette; } set { fourColorPalette = value; } } public Image MainPaletteImage { get { return (Image)GetValue(MainPaletteImageProperty); } set { SetValue(MainPaletteImageProperty, value); } } // Using a DependencyProperty as the backing store for MainPaletteImage. This enables animation, styling, binding, etc... public static readonly DependencyProperty MainPaletteImageProperty = DependencyProperty.Register("MainPaletteImage", typeof(Image), typeof(Palette), new UIPropertyMetadata(null)); public Image FourColorPaletteImage { get { return (Image)GetValue(FourColorPaletteImageProperty); } set { SetValue(FourColorPaletteImageProperty, value); } } // Using a DependencyProperty as the backing store for FourColorPaletteImage. This enables animation, styling, binding, etc... public static readonly DependencyProperty FourColorPaletteImageProperty = DependencyProperty.Register("FourColorPaletteImage", typeof(Image), typeof(Palette), new UIPropertyMetadata(null)); /// <summary> /// Our structure for dealing with pixels /// </summary> struct Pixel { public Pixel(byte r, byte g, byte b) { this.r = r; this.g = g; this.b = b; } public byte r; public byte g; public byte b; } /// <summary> /// Our Structure for dealing with Pixels, but in double form. We use this when doing linear interpolation for gradient creation. /// </summary> struct PixelAsDoubles { public PixelAsDoubles(double r, double g, double b) { this.r = r; this.g = g; this.b = b; } public double r; public double g; public double b; } /* * Color Conversions * RGB - > CMYK white = red + green + blue white - green = blue + red = magenta white - red = blue + green = cyan white - blue = green + red = yellow CMYK - > RGB Magenta + cyan = blue yellow _ cyan = green magenta + yellow = red magentat + yellow + cyan = black * */ /// <summary> /// Create the four color palette by interpolating from the corners. /// Red -> Blue /// ^ ^ /// | | /// Green -> White /// </summary> /// <returns></returns> BitmapSource CreateFourColorPalette() { // Create a place to hold our pixel data. pixels = new Byte[(int)(FourColorPaletteSize.Width * FourColorPaletteSize.Height * bytesPerPixel)]; int i = 0; // Find Color Slopes Pixel upperLeft = new Pixel(upperLeftColor.Color.R, upperLeftColor.Color.G, upperLeftColor.Color.B); Pixel upperRight = new Pixel(upperRightColor.Color.R, upperRightColor.Color.G, upperRightColor.Color.B); Pixel lowerLeft = new Pixel(lowerLeftColor.Color.R, lowerLeftColor.Color.G, lowerLeftColor.Color.B); Pixel lowerRight = new Pixel(lowerRightColor.Color.R, lowerRightColor.Color.G, lowerRightColor.Color.B); // Get the change in color for the distance the color is traveling PixelAsDoubles LeftToRightTop = CalculatePixelSlope(upperLeft, upperRight, (int)FourColorPaletteSize.Width); PixelAsDoubles LeftToRightBottom = CalculatePixelSlope(lowerLeft, lowerRight, (int)FourColorPaletteSize.Width); // We interpolate from left to right and then top to bottom. for (int y = 0; y < FourColorPaletteSize.Height; y++) { for (int x = 0; x < FourColorPaletteSize.Width; x++) { Pixel p1, p2; p1 = CalculatePixelGradient(upperLeft, x, LeftToRightTop); p2 = CalculatePixelGradient(lowerLeft, x, LeftToRightBottom); PixelAsDoubles topToBottom = CalculatePixelSlope(p1, p2, (int)FourColorPaletteSize.Height); Pixel p = CalculatePixelGradient(p1, y, topToBottom); pixels[i++] = p.r; pixels[i++] = p.g; pixels[i++] = p.b; } } // Figure out the stride. int stride = (int)FourColorPaletteSize.Width * bytesPerPixel; return BitmapImage.Create((int)FourColorPaletteSize.Width, (int)FourColorPaletteSize.Height, 96, 96, PixelFormats.Rgb24, null, pixels, stride); } /// <summary> /// Create the Master Palette using the same color interpolation to create the gradients as the four color palette. /// </summary> /// <returns></returns> BitmapSource CreateMasterPalette() { masterPixels = new Byte[(int)(MasterPaletteSize.Width * MasterPaletteSize.Height * bytesPerPixel)]; int i = 0; // Red -> Blue // ^ ^ // | | // Green -> White // We want to use 8 colors for this palette. Pixel g1 = new Pixel(255, 255, 0); // yellow Pixel g2 = new Pixel(0, 255, 0); // green Pixel g3 = new Pixel(0, 0, 255); // blue Pixel g4 = new Pixel(255, 0, 0); // red Pixel g5 = new Pixel(255, 0, 255); // magenta Pixel g6 = new Pixel(0, 255, 255); // cyan Pixel g7 = new Pixel(0, 0, 0); // black Pixel g8 = new Pixel(255, 255, 255);// white // Get the change in color for the distance the color is traveling. // mess with the g parameters here to change how the palette is layed out. PixelAsDoubles s1 = CalculatePixelSlope(g8, g1, (int)MasterPaletteSize.Width); PixelAsDoubles s2 = CalculatePixelSlope(g2, g1, (int)MasterPaletteSize.Width); PixelAsDoubles s3 = CalculatePixelSlope(g2, g3, (int)MasterPaletteSize.Width); PixelAsDoubles s4 = CalculatePixelSlope(g4, g3, (int)MasterPaletteSize.Width); PixelAsDoubles s5 = CalculatePixelSlope(g4, g5, (int)MasterPaletteSize.Width); PixelAsDoubles s6 = CalculatePixelSlope(g6, g5, (int)MasterPaletteSize.Width); PixelAsDoubles s7 = CalculatePixelSlope(g6, g7, (int)MasterPaletteSize.Width); PixelAsDoubles s8 = CalculatePixelSlope(g8, g7, (int)MasterPaletteSize.Width); int gradientHeight = (int)MasterPaletteSize.Height / 7; int yOffset = 0; // We again go left to right then top to bottom. But we // need to do a group of gradients at a time. for (int y = 0; y < MasterPaletteSize.Height; y++) { for (int x = 0; x < MasterPaletteSize.Width; x++) { Pixel p1, p2; if (y < gradientHeight) { p1 = CalculatePixelGradient(g1, x, s1); p2 = CalculatePixelGradient(g2, x, s2); } else if (y < gradientHeight * 2) { p1 = CalculatePixelGradient(g2, x, s2); p2 = CalculatePixelGradient(g3, x, s3); yOffset = gradientHeight; } else if (y < gradientHeight * 3) { p1 = CalculatePixelGradient(g3, x, s3); p2 = CalculatePixelGradient(g4, x, s4); yOffset = gradientHeight * 2; } else if (y < gradientHeight * 4) { p1 = CalculatePixelGradient(g4, x, s4); p2 = CalculatePixelGradient(g5, x, s5); yOffset = gradientHeight * 3; } else if (y < gradientHeight * 5) { p1 = CalculatePixelGradient(g5, x, s5); p2 = CalculatePixelGradient(g6, x, s6); yOffset = gradientHeight * 4; } else if (y < gradientHeight * 6) { p1 = CalculatePixelGradient(g6, x, s6); p2 = CalculatePixelGradient(g7, x, s7); yOffset = gradientHeight * 5; } else { p1 = CalculatePixelGradient(g7, x, s7); p2 = CalculatePixelGradient(g7, x, s8); yOffset = gradientHeight * 6; } PixelAsDoubles topToBottom = CalculatePixelSlope(p1, p2, (int)gradientHeight); // Calculate top to bottom gradients. Pixel p = CalculatePixelGradient(p1, y - yOffset, topToBottom); // RGB order is very important. masterPixels[i++] = p.r; masterPixels[i++] = p.g; masterPixels[i++] = p.b; } } // Calculate stride. int stride = (int)MasterPaletteSize.Width * bytesPerPixel; // Create the BitmapSource from the pixels. return BitmapImage.Create((int)MasterPaletteSize.Width, (int)MasterPaletteSize.Height, 96, 96, PixelFormats.Rgb24, null, masterPixels, stride); } /// <summary> /// Get the right color for how far we have moved (distance) to the right or down. /// </summary> /// <param name="startingPixel">What is the starting color</param> /// <param name="distance">How many pixels to the right or down this pixel is.</param> /// <param name="slope">The color step for this gradient.</param> /// <returns></returns> private static Pixel CalculatePixelGradient(Pixel startingPixel, int distance, PixelAsDoubles slope) { Pixel p = new Pixel(); // We don't want to start at zero so shift. distance++; p.r = (byte)(startingPixel.r + slope.r * distance); p.g = (byte)(startingPixel.g + slope.g * distance); p.b = (byte)(startingPixel.b + slope.b * distance); return p; } /// <summary> /// Calculated the change needed for each step in /// </summary> /// <param name="p1">Pixel 1</param> /// <param name="p2">Pixel 2</param> /// <param name="distance">The distance between the pixels</param> /// <returns></returns> PixelAsDoubles CalculatePixelSlope(Pixel p1, Pixel p2, int distance) { return new PixelAsDoubles((double)(p2.r - p1.r) / distance, (double)(p2.g - p1.g) / distance, (double)(p2.b - p1.b) / distance); } } }
c1e14e8e3f5c5b3efad45658d443a83dda712f4c
C#
Aghw/cs230
/tree/master/NewFinalProject/LearningCenter/ClassEnrollmentRepository.cs
2.96875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using LearningCenter.Models; using LearningCenter.DataAccessLayer; using System.Web.Caching; namespace LearningCenter { public interface IClassRepository { ClassModel[] Classes { get; } ClassModel Class(int classId); ClassModel[] ForUser(int userId); } public interface IUserRepository { UserModel[] Users { get; } UserModel User(int userId); UserModel[] ForClass(int classId); void AddClassToUser(int userId, int classId); } //public interface IUserClassRepository //{ // UserClassModel Add(int userId, int classId); // bool Remove(int userId, int classId); // UserClassModel[] GetAll(int UserId); //} //public class UserClassModel //{ // public int UserId { get; set; } // public int ClassId { get; set; } //} public class ClassModel { public int Id { get; set; } //[Required(ErrorMessage = "Please enter class name")] public string Name { get; set; } //[Required(ErrorMessage = "Please enter class description")] public string Description { get; set; } //[Required(ErrorMessage = "Please enter class price")] public decimal Price { get; set; } } public class UserRepository : IUserRepository { public UserModel[] Users { get { return DatabaseAccessor.Instance.Users .Select(a => new UserModel { Id = a.UserId, Name = a.UserEmail, }).ToArray(); } } public UserModel User(int userId) { return DatabaseAccessor.Instance .Users .Select(a => new UserModel { Id = a.UserId, Name = a.UserEmail, }) .Where(a => a.Id == userId).First(); } public UserModel[] ForClass(int classId) { return DatabaseAccessor.Instance .Classes.First(c => c.ClassId == classId) .Users.Select(a => new UserModel { Id = a.UserId, Name = a.UserEmail, }).ToArray(); } public void AddClassToUser(int userId, int classId) { // get user from DatabaseAccessor.Instance.Users var user = DatabaseAccessor.Instance.Users.First(a => a.UserId == userId); // get class from DatabaseAccessor.Instance.Classes var classToAdd = DatabaseAccessor.Instance.Classes .FirstOrDefault(t => t.ClassId == classId); // Add class to user.Classes user.Classes.Add(classToAdd); // Save changes to users-classes joining table DatabaseAccessor.Instance.SaveChanges(); } } public class ClassRepository : IClassRepository { public ClassModel[] ForUser(int userId) { return DatabaseAccessor.Instance .Users.First(u => u.UserId == userId) .Classes.Select(a => new ClassModel { Id = a.ClassId, Name = a.ClassName, Description = a.ClassDescription, Price = a.ClassPrice }).ToArray(); } public ClassModel[] Classes { get { return DatabaseAccessor.Instance.Classes .Select(a => new ClassModel { Id = a.ClassId, Name = a.ClassName, Description = a.ClassDescription, Price = a.ClassPrice }).ToArray(); } } public ClassModel Class(int classId) { var class_offered = DatabaseAccessor.Instance.Classes .Where(a => a.ClassId == classId) .Select(a => new ClassModel { Id = a.ClassId, Name = a.ClassName, Description = a.ClassDescription, Price = a.ClassPrice }).First(); return class_offered; } } }
496a2fe250ab684e5f305205b6dba07973609298
C#
koson/cpp
/c#/DevForge/Sec-Three/school/ConsoleDev/Program.cs
3.234375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleDev { class Program { static void Main(string[] args) { int year; int month; int day; year = Convert.ToInt32(Console.ReadLine()); month = Convert.ToInt32(Console.ReadLine()); day = Convert.ToInt32(Console.ReadLine()); DateTime d = new DateTime(year, month, day); DateTime L1, L2, L3, L4; L1 = new DateTime(2013, 8, 31); L2 = new DateTime(2012, 8, 31); L3 = new DateTime(2011, 8, 31); L4 = new DateTime(2010, 8, 31); if (d<=L1&& d>L2) Console.WriteLine("1"); if (d <= L2 && d > L3) Console.WriteLine("2"); if (d <= L3 && d > L4) Console.WriteLine("3"); if (d < L4 && d > L1) Console.WriteLine("error"); } } }
a68e46b97f449aa5a48caefc0912e5cf82bdbde0
C#
RamanBut-Husaim/MiSOI
/BSUIR.MiSOI.Lab01/ImageProcessing.Service/LinearFilterBase.cs
3
3
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace ImageProcessing.Service { internal abstract class LinearFilterBase : FilterBase { public override void Apply(Bitmap bitMap) { var rect = new Rectangle(0, 0, bitMap.Width, bitMap.Height); BitmapData bitmapData = bitMap.LockBits(rect, ImageLockMode.ReadWrite, bitMap.PixelFormat); IntPtr startPtr = bitmapData.Scan0; int imageSize = Math.Abs(bitmapData.Stride) * bitMap.Height; var rgbBytes = new byte[imageSize]; Marshal.Copy(startPtr, rgbBytes, 0, imageSize); this.ApplyInternal(rgbBytes, Math.Abs(bitmapData.Stride)); Marshal.Copy(rgbBytes, 0, startPtr, imageSize); bitMap.UnlockBits(bitmapData); } protected abstract void ApplyInternal(byte[] imageBytes, int rowWidth); } }
02d878eb109da1b46e4003dfa7c61465ef7973f1
C#
bibaoke/Less.Common
/Less.Common/Less.Text/EditExtensions.cs
3.453125
3
//bibaoke.com using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Less.Collection; namespace Less.Text { /// <summary> /// 编辑 /// </summary> public static class EditExtensions { /// <summary> /// 替换 /// </summary> /// <param name="s"></param> /// <param name="args"></param> /// <returns></returns> /// <exception cref="ArgumentNullException">字符串不能为 null,args 不能为 null</exception> /// <exception cref="FormatException">用于指示要格式化的参数的数字小于零,或者大于等于 args 数组的长度</exception> public static string FormatString(this string s, params object[] args) { return string.Format(s, args); } /// <summary> /// 省略文本 /// </summary> /// <param name="s"></param> /// <param name="keepUnicodeCharCount">要保留的 unicode 字符数</param> /// <returns></returns> public static string Ellipsis(this string s, int keepUnicodeCharCount) { string result = s.Trim(keepUnicodeCharCount); return result.Length == s.Length ? result : result + "…"; } /// <summary> /// 根据 Unicode 字符数截取字符串 /// </summary> /// <param name="s">要进行截取的字符串</param> /// <param name="keepUnicodeCharCount">要保留的 Unicode 字符数</param> /// <returns>截取结果</returns> public static string Trim(this string s, int keepUnicodeCharCount) { List<char> result = new List<char>(); decimal count = 0; int index = 0; while (count.Ceiling() < keepUnicodeCharCount && index < s.Length) { result.Add(s[index]); if (s[index].IsUnicode()) { count += 1M; } else { count += 0.5M; } index++; } return result.Join(); } /// <summary> /// 清除头部字符串 /// </summary> /// <param name="s"></param> /// <param name="startString"></param> /// <param name="stringComparison"></param> /// <returns></returns> public static string TrimStart(this string s, string startString, StringComparison stringComparison) { if (s.StartsWith(startString, stringComparison)) { return s.Substring(startString.Length); } return s; } /// <summary> /// 清除头部字符串 /// 大小写敏感 /// </summary> /// <param name="s"></param> /// <param name="startString"></param> /// <returns></returns> public static string TrimStart(this string s, string startString) { return s.TrimStart(startString, StringComparison.Ordinal); } /// <summary> /// 清除头部空白 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string TrimStart(this string s) { return s.TrimStart(null); } /// <summary> /// 清除尾部字符串 /// </summary> /// <param name="s"></param> /// <param name="endString"></param> /// <param name="stringComparison"></param> /// <returns></returns> public static string TrimEnd(this string s, string endString, StringComparison stringComparison) { if (s.EndsWith(endString, stringComparison)) { return s.Substring(0, s.Length - endString.Length); } return s; } /// <summary> /// 清除尾部字符串 /// 大小写敏感 /// </summary> /// <param name="s"></param> /// <param name="endString"></param> /// <returns></returns> public static string TrimEnd(this string s, string endString) { return s.TrimEnd(endString, StringComparison.Ordinal); } /// <summary> /// 清除尾部空白 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string TrimEnd(this string s) { return s.TrimEnd(null); } /// <summary> /// 清除指定的匹配 /// </summary> /// <param name="s"></param> /// <param name="regex"></param> /// <returns></returns> public static string Clear(this string s, Regex regex) { return regex.Replace(s, string.Empty); } /// <summary> /// 清除字符串中的指定字符串 /// 区分大小写 /// </summary> /// <param name="s">字符串</param> /// <param name="stringToClear">指定字符串</param> /// <returns></returns> public static string Clear(this string s, string stringToClear) { return s.Replace(stringToClear, string.Empty); } /// <summary> /// 清除字符串中的指定字符串 /// </summary> /// <param name="s">字符串</param> /// <param name="stringToClear">指定字符串</param> /// <param name="caseOption">大小写选项</param> /// <returns></returns> public static string Clear(this string s, string stringToClear, CaseOptions caseOption) { return s.Replace(stringToClear, string.Empty, caseOption); } /// <summary> /// 替换文本中的字符串 /// </summary> /// <param name="s">文本</param> /// <param name="oldValue">要替换的字符串</param> /// <param name="newValue">取而代之的字符串</param> /// <param name="caseOption">大小写选项</param> /// <returns>替换之后的文本</returns> public static string Replace(this string s, string oldValue, string newValue, CaseOptions caseOption) { //根据大小写选项决定字符串查找选项 StringComparison comparison = caseOption.ToStringComparison(); //查找起始索引 int startIndex = 0; //找到的旧值索引 int oldValueIndex = 0; //替换处理之后的结果 string result = ""; //在文本中查找要替换的字符串 while ((oldValueIndex = s.IndexOf(oldValue, startIndex, comparison)) >= 0) { //把旧值索引前的内容追加到结果中 (oldValueIndex - startIndex).Each(index => { result += s[startIndex + index]; }); //再追加新值 result += newValue; //更新起始索引 startIndex = oldValueIndex + oldValue.Length; } //把剩余的内容追加到结果中 (s.Length - startIndex).Each(index => { result += s[startIndex + index]; }); return result.ToString(); } } }
4300ecd448b2fb707e5d7807714588a44dc6ff0b
C#
comaid/Pidgin
/Pidgin/Parser.Chain.cs
2.6875
3
using System; namespace Pidgin { public partial class Parser<TToken, T> { internal Parser<TToken, U> ChainAtLeastOnce<U, TChainer>(Func<TChainer> factory) where TChainer : struct, IChainer<T, U> => new ChainAtLeastOnceLParser<TToken, T, U, TChainer>(this, factory); } internal interface IChainer<in T, out U> { void Apply(T value); U GetResult(); void OnError(); } internal class ChainAtLeastOnceLParser<TToken, T, U, TChainer> : Parser<TToken, U> where TChainer : struct, IChainer<T, U> { private readonly Parser<TToken, T> _parser; private readonly Func<TChainer> _factory; public ChainAtLeastOnceLParser(Parser<TToken, T> parser, Func<TChainer> factory) { _parser = parser; _factory = factory; } internal override InternalResult<U> Parse(ref ParseState<TToken> state) { var result1 = _parser.Parse(ref state); if (!result1.Success) { // state.Error set by _parser return InternalResult.Failure<U>(result1.ConsumedInput); } var chainer = _factory(); chainer.Apply(result1.Value); var consumedInput = result1.ConsumedInput; state.BeginExpectedTran(); var result = _parser.Parse(ref state); while (result.Success) { state.EndExpectedTran(false); if (!result.ConsumedInput) { chainer.OnError(); throw new InvalidOperationException("Many() used with a parser which consumed no input"); } consumedInput = true; chainer.Apply(result.Value); state.BeginExpectedTran(); result = _parser.Parse(ref state); } state.EndExpectedTran(result.ConsumedInput); if (result.ConsumedInput) // the most recent parser failed after consuming input { // state.Error set by _parser chainer.OnError(); return InternalResult.Failure<U>(true); } var z = chainer.GetResult(); return InternalResult.Success<U>(z, consumedInput); } } }
113b41310fa226ff8b0b46f7bb9fdfb1c2e53d65
C#
RohitKumarCG/InventoryProject
/Rohit/RawMatarialTest/GetRawMaterialBLTest.cs
2.625
3
using System; using System.Collections.Generic; using System.Threading.Tasks; using Capgemini.Inventory.BusinessLayer; using Capgemini.Inventory.Entities; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Capgemini.Inventory.UnitTests { //Developed By Rohit //Creation Date: 01-10-2019 //Last Modified Date: //Module Name: GetRawMaterialUnitTest //Project: Inventory [TestClass] public class GetRawMaterialBLTest { /// <summary> /// Get all RawMaterials in the Collection if it is valid. /// </summary> [TestMethod] public async Task GetAllValidRawMaterials() { //Arrange RawMaterialBL rawMaterialBL = new RawMaterialBL(); RawMaterial rawMaterial = new RawMaterial() { RawMaterialName = "Grape", RawMaterialCode = "GRP", RawMaterialPrice = 60 }; await rawMaterialBL.AddRawMaterialBL(rawMaterial); bool isDisplayed = false; string errorMessage = null; //Act try { List<RawMaterial> rawMaterialList = await rawMaterialBL.GetAllRawMaterialsBL(); if (rawMaterialList.Count > 0) { isDisplayed = true; } } catch (Exception ex) { isDisplayed = false; errorMessage = ex.Message; } finally { //Assert Assert.IsTrue(isDisplayed, errorMessage); } } /// <summary> /// Raw Material List cannot be Empty /// </summary> [TestMethod] public async Task RawMaterialListCanNotBeEmpty() { //Arrange bool isDisplayed = false; string errorMessage = null; //Act try { RawMaterialBL rawMaterialBL = new RawMaterialBL(); List<RawMaterial> rawMaterialList = await rawMaterialBL.GetAllRawMaterialsBL(); if (rawMaterialList.Count < 1) { isDisplayed = true; } } catch (Exception ex) { isDisplayed = false; errorMessage = ex.Message; } finally { //Assert Assert.IsFalse(isDisplayed, errorMessage); } } /// <summary> /// Get RawMaterial in the Collection if ID is valid. /// </summary> [TestMethod] public async Task GetValidRawMaterialByID() { //Arrange RawMaterialBL rawMaterialBL = new RawMaterialBL(); RawMaterial rawMaterial = new RawMaterial() { RawMaterialName = "Muskmelon", RawMaterialCode = "MML", RawMaterialPrice = 40 }; await rawMaterialBL.AddRawMaterialBL(rawMaterial); bool isDisplayed = false; string errorMessage = null; //Act try { RawMaterial rawMaterial1 = await rawMaterialBL.GetRawMaterialByRawMaterialIDBL(rawMaterial.RawMaterialID); if (rawMaterial.RawMaterialID == rawMaterial1.RawMaterialID) { isDisplayed = true; } } catch (Exception ex) { isDisplayed = false; errorMessage = ex.Message; } finally { //Assert Assert.IsTrue(isDisplayed, errorMessage); } } /// <summary> /// RawMaterialID should exist. /// </summary> [TestMethod] public async Task RawMaterialIDDoesNotExist() { //Arrange RawMaterialBL rawMaterialBL = new RawMaterialBL(); RawMaterial rawMaterial = new RawMaterial() { RawMaterialName = "WaterMelon", RawMaterialCode = "WTM", RawMaterialPrice = 20 }; await rawMaterialBL.AddRawMaterialBL(rawMaterial); bool isDisplayed = false; string errorMessage = null; //Act try { RawMaterial rawMaterial1 = await rawMaterialBL.GetRawMaterialByRawMaterialIDBL(default(Guid)); } catch (Exception ex) { isDisplayed = false; errorMessage = ex.Message; } finally { //Assert Assert.IsFalse(isDisplayed, errorMessage); } } /// <summary> /// Get RawMaterial in the Collection if Name is valid. /// </summary> [TestMethod] public async Task GetValidRawMaterialByName() { //Arrange RawMaterialBL rawMaterialBL = new RawMaterialBL(); RawMaterial rawMaterial = new RawMaterial() { RawMaterialName = "Orange", RawMaterialCode = "ORG", RawMaterialPrice = 20 }; await rawMaterialBL.AddRawMaterialBL(rawMaterial); bool isDisplayed = false; string errorMessage = null; //Act try { RawMaterial rawMaterial1 = await rawMaterialBL.GetRawMaterialByRawMaterialNameBL(rawMaterial.RawMaterialName); if (rawMaterial.RawMaterialName == rawMaterial1.RawMaterialName) { isDisplayed = true; } } catch (Exception ex) { isDisplayed = false; errorMessage = ex.Message; } finally { //Assert Assert.IsTrue(isDisplayed, errorMessage); } } /// <summary> /// RawMaterialName should exist. /// </summary> [TestMethod] public async Task RawMaterialNameDoesNotExist() { //Arrange RawMaterialBL rawMaterialBL = new RawMaterialBL(); RawMaterial rawMaterial = new RawMaterial() { RawMaterialName = "Lemon", RawMaterialCode = "LMN", RawMaterialPrice = 5 }; await rawMaterialBL.AddRawMaterialBL(rawMaterial); bool isDisplayed = false; string errorMessage = null; //Act try { RawMaterial rawMaterial1 = await rawMaterialBL.GetRawMaterialByRawMaterialNameBL("SomeName"); } catch (Exception ex) { isDisplayed = false; errorMessage = ex.Message; } finally { //Assert Assert.IsFalse(isDisplayed, errorMessage); } } /// <summary> /// Get RawMaterial in the Collection if Code is valid. /// </summary> [TestMethod] public async Task GetValidRawMaterialByCode() { //Arrange RawMaterialBL rawMaterialBL = new RawMaterialBL(); RawMaterial rawMaterial = new RawMaterial() { RawMaterialName = "Lime", RawMaterialCode = "LIM", RawMaterialPrice = 5 }; await rawMaterialBL.AddRawMaterialBL(rawMaterial); bool isDisplayed = false; string errorMessage = null; //Act try { RawMaterial rawMaterial1 = await rawMaterialBL.GetRawMaterialByRawMaterialCodeBL(rawMaterial.RawMaterialCode); if (rawMaterial.RawMaterialCode == rawMaterial1.RawMaterialCode) { isDisplayed = true; } } catch (Exception ex) { isDisplayed = false; errorMessage = ex.Message; } finally { //Assert Assert.IsTrue(isDisplayed, errorMessage); } } /// <summary> /// RawMaterialCode should exist. /// </summary> [TestMethod] public async Task RawMaterialCodeDoesNotExist() { //Arrange RawMaterialBL rawMaterialBL = new RawMaterialBL(); RawMaterial rawMaterial = new RawMaterial() { RawMaterialName = "Salt", RawMaterialCode = "SAL", RawMaterialPrice = 15 }; await rawMaterialBL.AddRawMaterialBL(rawMaterial); bool isDisplayed = false; string errorMessage = null; //Act try { RawMaterial rawMaterial1 = await rawMaterialBL.GetRawMaterialByRawMaterialCodeBL("SomeCode"); } catch (Exception ex) { isDisplayed = false; errorMessage = ex.Message; } finally { //Assert Assert.IsFalse(isDisplayed, errorMessage); } } } }
bf9593b99bd734d574afdfbfd4029e0d6b8d691f
C#
anegostudios/vsapi
/Client/API/IClientNetworkChannel.cs
2.921875
3
using System; namespace Vintagestory.API.Client { public interface INetworkChannel { /// <summary> /// The channel name this channel was registered with /// </summary> string ChannelName { get; } /// <summary> /// Registers a handler for when you send a packet with given messageId /// </summary> /// <param name="type"></param> INetworkChannel RegisterMessageType(Type type); /// <summary> /// Registers a handler for when you send a packet with given messageId /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> INetworkChannel RegisterMessageType<T>(); } /// <summary> /// Handler for processing a message /// </summary> /// <param name="packet"></param> public delegate void NetworkServerMessageHandler<T>(T packet); /// <summary> /// Represent a custom network channel for sending messages between client and server /// </summary> public interface IClientNetworkChannel : INetworkChannel { /// <summary> /// True if the server is listening on this channel /// </summary> bool Connected { get; } /// <summary> /// Registers a handler for when you send a packet with given messageId. Must be registered in the same order as on the server. /// </summary> /// <param name="type"></param> new IClientNetworkChannel RegisterMessageType(Type type); /// <summary> /// Registers a handler for when you send a packet with given messageId. Must be registered in the same order as on the server. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> new IClientNetworkChannel RegisterMessageType<T>(); /// <summary> /// Registers a handler for when you send a packet with given messageId /// </summary> /// <typeparam name="T"></typeparam> /// <param name="handler"></param> IClientNetworkChannel SetMessageHandler<T>(NetworkServerMessageHandler<T> handler); /// <summary> /// Sends a packet to the server /// </summary> /// <param name="message"></param> void SendPacket<T>(T message); } }
5a549a1bb21101f9684e05b08ea7abf10dfa0311
C#
TimCodesStuff/BitcoinLibCSharp
/BitcoinLib/BitcoinLib/Encoding.cs
3.0625
3
using System.Numerics; using System; using System.Linq; namespace BitcoinLib { public class Encoding { public static byte[] HexStringToByteArray(string hexString) { return Enumerable.Range(0, hexString.Length) // Generate an enumerable of ints from 1 to hexString length .Where(x => x % 2 == 0) // Filter out all odd numbers from enumerable .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16)) // Convert each set of 2 hex characters to byte .ToArray(); } public static string ByteArrayToHexString(byte[] input, bool includeDashes = false) { if (includeDashes) return BitConverter.ToString(input).ToLower(); else return BitConverter.ToString(input).Replace("-", "").ToLower(); } /// <summary> Takes a Wallet Import Format string and converts it to a Hexadecimal string. See https://en.bitcoin.it/wiki/Wallet_import_format. </summary> public static string WiftoHex(string wifKey) { // Base58 decode string hex = ByteArrayToHexString(Base58Decode(wifKey)); // Remove first byte (main network byte) and last 4 bytes (checksum) return hex.Substring(2, 64); } public static string HexToWif(string hex, NetworkType network, bool isCompressedPublicKey = true) { //TODO: Verify string is Hex and correct length. hex = (network == NetworkType.Main) ? "80" + hex : "EF" + hex; if (isCompressedPublicKey) { hex += "01"; } byte[] doubleSha = Crypto.Sha256(Crypto.Sha256(HexStringToByteArray(hex))); string checksum = ByteArrayToHexString(doubleSha).Substring(0, 8); hex += checksum; return Base58Encode(HexStringToByteArray(hex)); } public static (string, string, string) DecomposeWifAddress(string wifKey) { // Base58 decode string hex = Encoding.ByteArrayToHexString(Base58Decode(wifKey)); //TODO: Check if WIF was used for compressed public key. string network = hex.Substring(0, 2); string wif = hex.Substring(2, 64); string checksum = hex.Substring(68, 8); return (network, wif, checksum); } public static bool ValidateWifAddressChecksum(string wifKey) { (string network, string hex, string wifChecksum) = Encoding.DecomposeWifAddress(wifKey); byte[] doubleSha = Crypto.Sha256(Crypto.Sha256(HexStringToByteArray(network + hex + "01"))); string checksum = ByteArrayToHexString(doubleSha).Substring(0, 8); return checksum == wifChecksum; } // Base 58 contains no 0, O, l, or I. private static string Base58characterSet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; /// <param name="array">An array of bytes to be encoded as base58.</param> /// <returns>A string of base58 characters.</returns> public static string Base58Encode(byte[] array) { BigInteger arrayToInt = 0; for (int i = 0; i < array.Length; ++i) { arrayToInt = arrayToInt * 256 + array[i]; } string retString = string.Empty; while (arrayToInt > 0) { int rem = (int)(arrayToInt % 58); arrayToInt /= 58; retString = Base58characterSet[rem] + retString; } for (int i = 0; i < array.Length && array[i] == 0; ++i) retString = Base58characterSet[0] + retString; return retString; } // Taken from https://gist.github.com/CodesInChaos/3175971#file-base58encoding-cs public static byte[] Base58Decode(string b58string) { // Decode Base58 string to BigInteger BigInteger intData = 0; for (int i = 0; i < b58string.Length; i++) { int digit = Base58characterSet.IndexOf(b58string[i]); // TODO: Handle invalid character. intData = intData * 58 + digit; } // Encode BigInteger to byte[] // Leading zero bytes get encoded as leading `1` characters int leadingZeroCount = b58string.TakeWhile(c => c == '1').Count(); var leadingZeros = Enumerable.Repeat((byte)0, leadingZeroCount); var bytesWithoutLeadingZeros = intData.ToByteArray() .Reverse()// to big endian .SkipWhile(b => b == 0);//strip sign byte var result = leadingZeros.Concat(bytesWithoutLeadingZeros).ToArray(); return result; } } }
9a22345eb90dff2796241d9b2e77ec570d7ad2d7
C#
FUSEEProjectTeam/Fusee
/src/Engine/Core/Effects/UniformChangedEnum.cs
2.671875
3
namespace Fusee.Engine.Core.Effects { /// <summary> /// Enum for determining the action that needs to be taken for a uniform variable in the <see cref="EffectManager"/>. /// </summary> public enum UniformChangedEnum { /// <summary> /// The effect isn't needed anymore - the uniform will be disposed of. /// </summary> Dispose = 0, /// <summary> /// The uniform value has changed and will be updated. /// </summary> Update = 1, //Not needed at the moment, because a ShaderEffect must declare all it's parameter declarations at creation. //Add = 2, /// <summary> /// The uniform value is unchanged - no action needed. /// </summary> Unchanged = 3 } }
9aef1f2a89b969c16bbaac5728ce2420cea3d34b
C#
YuriAICruz/shmup-steam
/Packages/Splines/Assets/Scripts/Paths/Path.cs
2.515625
3
using System; using System.Collections; using Graphene.Utils; using UnityEngine; namespace Splines.Paths { [Serializable] public class Path : IPath { public Path(Path path) { StartPoint = path.StartPoint; EndPoint = path.EndPoint; XCurve = path.XCurve; YCurve = path.YCurve; Ease = path.Ease; } public Vector2 StartPoint, EndPoint; public AnimationCurve XCurve; public AnimationCurve YCurve; public Equations Ease; private Transform _transform; private Vector3 _iniPos; public event Action OnPathStart, OnPathEnd; private Action<float> _evaluate; private float _speed; private Coroutine _routine; private MonoBehaviour _mono; public bool _loop; public bool Loop { get { return _loop; } } public void MoveOnPath(float speed, Transform transform, MonoBehaviour mono) { _speed = speed; _transform = transform; _iniPos = _transform.position; if (OnPathStart != null) OnPathStart(); _mono = mono; _routine = _mono.StartCoroutine(Translate()); } private IEnumerator Translate() { var _startTime = Time.time; var tx = 0f; var ty = 0f; var dist = (EndPoint - StartPoint).magnitude; while ((Time.time - _startTime) / (dist / _speed) < 1) { tx = RobertPannerEasingLerp.Evaluate((Time.time - _startTime) / (dist / _speed), 1, 0, 1, Ease, XCurve); ty = RobertPannerEasingLerp.Evaluate((Time.time - _startTime) / (dist / _speed), 1, 0, 1, Ease, YCurve); var pos = new Vector2( StartPoint.x + (EndPoint.x - StartPoint.x) * tx, StartPoint.y + (EndPoint.y - StartPoint.y) * ty // Mathf.Lerp(StartPoint.x, EndPoint.x, tx), // Mathf.Lerp(StartPoint.y, EndPoint.y, ty) ); _transform.position = _iniPos + new Vector3(pos.x, pos.y); yield return null; } if (_loop) { MoveOnPath(_speed, _transform, _mono); } if (OnPathEnd != null) OnPathEnd(); } public void Stop() { _mono.StopCoroutine(_routine); } } }
eae602644e8510fa9a417d61f6ef541db7ba694a
C#
RonokBhowmik/BasisTranningOOP49
/Console Applications/IterationConsoleApp/IterationConsoleApp/Program.cs
3.9375
4
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IterationConsoleApp { class Program { static void Main(string[] args) { //Prints the sum of the numbers o to 9 using for loop Console.Write("Prints the sum of the numbers o to 9 using for loop: "); int sum = 0; for (int i = 0; i < 10; i++) { sum = sum + i; } Console.WriteLine(sum); //Prints the sum of the numbers o to 9 using while loop Console.Write("Prints the sum of the numbers o to 9 using while loop:"); int a = 0; int sum1 = 0; while (a <9) { a++; sum1 = sum1 + a; } Console.WriteLine(sum1); //Prints the sum of the numbers o to 9 using do while loop Console.Write("Prints the sum of the numbers o to 9 using do while loop:"); int b = 0; int sum2 = 0; do { b++; sum2 = sum2 + b; } while (b <9); Console.WriteLine(sum2); //Prints Computer Science Five times Console.WriteLine("Prints Computer Science Five times:"); string mytext = "Computer Science"; for (int i = 0; i < 5; i++) { Console.WriteLine(mytext); } Console.ReadKey(); } } }
57a6d9e849e76d08f8dff8d2073056defd816909
C#
shendongnian/download4
/latest_version_download2/225761-49654730-170522773-2.cs
2.859375
3
public class Employee { public string FirstName { get; set; } public string LastName { get; set; } public int WeeklySales { get; set; } public override string ToString() { return $"{FirstName} {LastName}"; } }
ce8328e0b1f77c28216e5a5268527e0b6cba2fa6
C#
LennartMolFontys/TSS
/stringSplitter/stringSplitter/StringSplitter.cs
3.203125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace stringSplitter { static class StringSplitter { public static string InitializeFormat { get; } = "ID:<value>UnitAmount:<value>Length:<value>TotalSeats:<value><value>Length:<value>TotalSeats:<value>..."; public static string SeatOccupationFormat { get; } = "SeatsTaken:<value>SeatsTaken:<value>..."; private static string[] splitStrings = new string[] { "Length:", "TotalSeats:", "SeatsTaken:" }; public static int GetTrainId(string initialiseString) { try { int id = getValueBetweenStrings(initialiseString, "ID:", "UnitAmount:"); return id; } catch(FormatException) { throw new FormatException("Expected: " + InitializeFormat + "\ngot: " + initialiseString); } } public static int GetUnitAmount(string initialiseString) { try { int unitAmount = getValueBetweenStrings(initialiseString, "UnitAmount:", "Length:"); return unitAmount; } catch (FormatException) { throw new FormatException("Expected: " + InitializeFormat + "\ngot: " + initialiseString); } } private static int getValueBetweenStrings(string someString, string header, string footer) { int startPoint = someString.IndexOf(header) + header.Length; int length = someString.IndexOf(footer) - startPoint; if(!someString.Contains(header) || !someString.Contains(footer)) { throw new FormatException(); } return Convert.ToInt32(someString.Substring(startPoint, length)); } public static int[] GetSeatsTaken(string someString) { try { return getValuesFromString(someString, splitStrings); } catch(FormatException) { throw new FormatException("Expected: " + SeatOccupationFormat + "\ngot: " + someString); } } public static int[,] GetUnitInfo(string someString) { someString = someString.Substring(someString.IndexOf("Length:")); int[] values; try { values = getValuesFromString(someString, splitStrings); } catch(FormatException) { throw new FormatException("Expected: " + InitializeFormat + "\ngot: " + someString); } int[,] unitInfo = new int[values.Count() / 2, 2]; for (int i = 0; i < values.Count()/2 ; i++) { for (int ii = 0; ii < 2; ii++) { unitInfo[i, ii] = values[2 * i + ii]; } } return unitInfo; } private static int[] getValuesFromString(string someString, string[] headerStrings) { try { string[] stringValues = someString.Split(headerStrings, StringSplitOptions.RemoveEmptyEntries); int[] intvalues = new int[stringValues.Count()]; for (int i = 0; i < stringValues.Count(); i++) { intvalues[i] = Convert.ToInt32(stringValues[i]); } return intvalues; } catch (ArgumentOutOfRangeException) { throw new FormatException(); } catch (OverflowException) { throw new FormatException(); } catch (FormatException e) { throw e; } } } }
c3ab433d8f705baadb6d0875b6ff9762dcba0301
C#
zubair1599/RP
/RPDailyScrape/Common.cs
3.078125
3
using System; using System.Text.RegularExpressions; using System.Threading; namespace RPDailyScrape { internal class Common { public static Random rand; public static void Wait() { var interval = (int) Math.Floor(1 + (rand.NextDouble()*2)); Thread.Sleep(interval*1000); } public static string ProcessName(string name) { name = name.Replace("&acute;", "'"); var regex_name = new Regex(@"([^(]+)\(([A-Z\s]+)\)"); Match match_name = regex_name.Match(name); if (match_name.Success) { name = match_name.Groups[1].ToString().Trim(); } return name; } public static string FlattenName(string str) { str = str.ToUpper(); var regex = new Regex(@"(.*?)\s+[IVX]+$"); Match match = regex.Match(str); if (match.Success) { str = match.Groups[1].ToString(); } regex = new Regex(@"[^A-Z0-9]"); str = regex.Replace(str, ""); return str; } } }
9bc3cb174b98d8ba7e37e7cbe31d40d611e516f0
C#
nicolas98-a/Unaj-Menu-Digital
/App de Backend/Tp2-Rest-Acuña_Nicolas/Tp.Restaurante.API/Tp.Restaurante.API/Controllers/ComandaController.cs
2.609375
3
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using Tp.Restaurante.Application.Services; using Tp.Restaurante.Domain.DTOs; namespace Tp.Restaurante.API.Controllers { [Route("api/[controller]")] [ApiController] public class ComandaController : ControllerBase { private readonly IComandaService _service; public ComandaController(IComandaService service) { _service = service; } /// <summary> /// Agrega una comanda /// </summary> /// <param name="comanda"></param> /// <returns>Retorna el id de la comanda y la entidad a la que pertenece</returns> [HttpPost] [ProducesResponseType(typeof(GenericCreatedResponseDto), StatusCodes.Status201Created)] public IActionResult Post(CreateComandaRequestDto comanda) { try { return new JsonResult(_service.CreateComanda(comanda)) { StatusCode = 201 }; } catch (Exception e) { return new JsonResult(BadRequest(e.Message)); } } /// <summary> /// Devuelve todas las comadas, permite filtrar por fecha /// </summary> /// <param name="fecha"></param> /// <returns>Retorna la informacion de las comandas</returns> [HttpGet] [ProducesResponseType(typeof(List<ResponseGetComandaById>), StatusCodes.Status200OK)] public IActionResult GetComandas([FromQuery] string fecha) { try { return new JsonResult(_service.GetComandas(fecha)) { StatusCode = 200 }; } catch (Exception e) { return BadRequest(e.Message); } } /// <summary> /// Devuelve la comada que corresponde al id ingresado /// </summary> /// <param name="Id"></param> /// <returns>Retorna la informacion de la comanda</returns> [HttpGet("{Id}")] [ProducesResponseType(typeof(ResponseGetComandaById), StatusCodes.Status200OK)] public IActionResult GetComandaById(string Id) { try { return new JsonResult(_service.GetById(Id)) { StatusCode = 200 }; } catch (Exception e) { return new JsonResult(BadRequest(e.Message)) { StatusCode = 400 }; } } } }
bb8fefb3b746a49ca8fa347b38fdc56bff221756
C#
et8111/Lab13
/Lab13/LimboPlayer.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab13 { class LimboPlayer: Player { public override string Name { get; set; } public override Roshambo Ro { get; set; } public override int wins { get; set; } public LimboPlayer() { Name = "LIMBO"; } public override Roshambo generateRoshambo() { Random r = new Random(); Ro = (Roshambo)r.Next(0, 3); return Ro; } } }
d7fb476fc61fd7bf3082d84687cd6e4e7c49761d
C#
dotMorten/AllJoynDeviceSimulator
/src/SimulatorApp/AllJoynNotificationReceIver.cs
2.609375
3
using DeviceProviders; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AllJoynSimulatorApp { //Listens for AllJoyn notifications on the bus and raises an event when one is received internal class AllJoynNotificationReceiver { public delegate void OnNotificationHandler(string message); public event OnNotificationHandler OnNotification; /// Reference: https://allseenalliance.org/developers/learn/base-services/notification/interface private readonly IReadOnlyList<string> NOTIFICATION_PATHS = new List<string> { @"/emergency", @"/warning", @"/info", }; private readonly string NOTIFICATION_INTERFACE = @"org.alljoyn.Notification"; /// Reference: https://git.allseenalliance.org/cgit/services/notification.git/tree/cpp/src/PayloadAdapter.cc#n337 private readonly int NOTIFICATION_TEXT_ARGUMENT_INDEX = 9; private ICollection<ISignal> subcribedSignals = new Collection<ISignal>(); public AllJoynNotificationReceiver(DeviceProviders.AllJoynProvider provider = null) { DeviceProviders.AllJoynProvider Config = provider ?? new AllJoynProvider(); Config.ServiceJoined += Config_ServiceJoined; Config.Start(); } private void Config_ServiceJoined(IProvider sender, ServiceJoinedEventArgs args) { ServiceJoined(args.Service); } private void ServiceJoined(IService service) { if (!service.ImplementsInterface(NOTIFICATION_INTERFACE)) return; foreach (string path in NOTIFICATION_PATHS) { IBusObject busObject; IInterface @interface; ISignal signal; try { busObject = service.Objects.First(x => x.Path == path); } catch (InvalidOperationException) { Debug.WriteLine("Couldn't find bus object: " + path); return; } try { @interface = busObject.Interfaces.First(x => x.Name == NOTIFICATION_INTERFACE); } catch (InvalidOperationException) { Debug.WriteLine("Couldn't find Interface: " + NOTIFICATION_INTERFACE); return; } try { signal = @interface.Signals.Single(x => x.Name.ToLower() == "notify"); signal.SignalRaised += AllJoynNotifier_SignalRaised; subcribedSignals.Add(signal); } catch (InvalidOperationException) { Debug.WriteLine("The Notification interface is not implemented correctly."); return; } Debug.WriteLine(string.Format("Subscribed to {0} notifications on {1}.", path, service.Name)); } } private void AllJoynNotifier_SignalRaised(ISignal sender, IList<object> args) { Debug.WriteLine("Received Notification signal from " + sender.Name); if (OnNotification == null) return; string message = null; try { var textStructs = ((IList<object>)args[NOTIFICATION_TEXT_ARGUMENT_INDEX]).Cast<AllJoynMessageArgStructure>(); /// textStructs has type a(ss), where the first element of the struct (i.e. x[0]) is the /// language as per RFC 5646, while the second element (x[1]) is the message text. var english = textStructs.First(x => ((string)x[0]).StartsWith("en")); message = (string)english[1]; } catch (Exception ex) { Debug.WriteLine("Exception in SignalRaised: " + ex.Message); return; } Debug.WriteLine("Notification text: " + message); OnNotification(message); } } }
1933b22030a9c95016ea15cee7c889298a0bda03
C#
yuva2achieve/TelerikAcademy
/HighQualityCode/05.ConditionalStatementsLoops/01.Chef/Chef.cs
3.703125
4
namespace _01.Chef { using System; using System.Linq; public class Chef { // Task 1 is in this file // Task 2 is in MainClass.cs public void Cook() { Bowl bowl = this.GetBowl(); Potato potato = this.GetPotato(); Potato peeledPotato = (Potato)this.Peel(potato); Potato cuttedPotato = (Potato)this.Cut(peeledPotato); bowl.Add(cuttedPotato); Carrot carrot = this.GetCarrot(); Carrot peeledCarrot = (Carrot)this.Peel(carrot); Carrot cuttedCarrot = (Carrot)this.Cut(peeledCarrot); bowl.Add(cuttedCarrot); } public void Cook(Vegetable vegetableToCook) { // Cooking vegetable.. } private Bowl GetBowl() { return new Bowl(); } private Potato GetPotato() { return new Potato(); } private Carrot GetCarrot() { return new Carrot(); } private Vegetable Peel(Vegetable vegetable) { Vegetable peeledVegetable; if (vegetable is Potato) { peeledVegetable = new Potato(); } else { peeledVegetable = new Carrot(); } return peeledVegetable; } private Vegetable Cut(Vegetable vegetable) { Vegetable cuttedVegetable; if (vegetable is Potato) { cuttedVegetable = new Potato(); } else { cuttedVegetable = new Carrot(); } return cuttedVegetable; } } }
a0bdc1a35ff560bf8a42a712fbbf56733f07f10e
C#
llenroc/Cwq-LeetCode
/CSharpImpl/N1483_KthAncestorOfATreeNode.cs
3.65625
4
using System; using System.Collections.Generic; namespace CSharpImpl { /// <summary> /// link: https://leetcode.com/problems/kth-ancestor-of-a-tree-node/ /// /// You are given a tree with n nodes numbered from 0 to n-1 in the form of a parent array where parent[i] is the parent of node i. The root of the tree is node 0. /// Implement the function getKthAncestor(int node, int k) to return the k-th ancestor of the given node. If there is no such ancestor, return -1. /// The k-th ancestor of a tree node is the k-th node in the path from that node to the root. /// /// Example: /// [<https://assets.leetcode.com/uploads/2019/08/28/1528_ex1.png>] /// Input: ["TreeAncestor","getKthAncestor","getKthAncestor","getKthAncestor"] [[7,[-1,0,0,1,1,2,2]],[3,1],[5,2],[6,3]] /// Output: [null,1,0,-1] /// Explanation: TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]); treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3 treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5 treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor /// /// /// Constraints: /// * 1 <= k <= n <= 5*10^4 /// * parent[0] == -1 indicating that 0 is the root node. /// * 0 <= parent[i] < n for all 0 < i < n /// * 0 <= node < n /// * There will be at most 5*10^4 queries. /// /// </summary> public class N1483_KthAncestorOfATreeNode { public class TreeAncestor { public TreeAncestor(int n, int[] parent) { throw new NotImplementedException(); } public int GetKthAncestor(int node, int k) { throw new NotImplementedException(); } } /** * Your TreeAncestor object will be instantiated and called as such: * TreeAncestor obj = new TreeAncestor(n, parent); * int param_1 = obj.GetKthAncestor(node,k); */ } }
4ebe2335e3895d66765a0f3a3c07dd266bd9f4a6
C#
pcarvalho75/patternlab
/cloudService/hmm_old/ServiceHMM.svc.cs
2.53125
3
using PatternTools.FastaParser; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace hmm3 { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together. // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging. public class HMM : IHMM { public string GetData(int value) { return string.Format("You entered: {0}", value); } public string Scans(List<FastaItem> theSequences) { return null; } public string Scan(string fastaSequence) { //Dump the fasta seqeuence to a file StreamWriter sw = new StreamWriter(@"C:\Users\pcarvalho\Desktop\pfamWorkDir\seq.txt"); sw.WriteLine(fastaSequence); sw.Close(); string applicationCall = @"hmmscan --domtblout theTable.txt --cpu 3 E:\ProteinDatabases\PFam\Pfam-A.hmm seq.txt"; return fastaSequence; } public CompositeType GetDataUsingDataContract(CompositeType composite) { if (composite == null) { throw new ArgumentNullException("composite"); } if (composite.BoolValue) { composite.StringValue += "Suffix"; } return composite; } } }
9061e60433acbcd9980150da88b28e2c473a73b6
C#
sans90/SS
/计算面积/重载/Program.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 重载 { class Program { //调用 static void Main() { ConsoleColor consoleColor = Console.BackgroundColor; Console.WriteLine("1-3", consoleColor); CalculatedArea(Console.ReadLine()); Console.ReadLine(); } //定义 //几何体 static void CalculatedArea(string TypeArea) { switch (TypeArea) { case "1": Console.WriteLine("输入边"); float X = float.Parse(Console.ReadLine()); float result1 = Computes(X); Console.WriteLine(result1); break; case "2": Console.WriteLine("输入长"); float L = float.Parse(Console.ReadLine()); Console.WriteLine("输入高"); float H = float.Parse(Console.ReadLine()); float result0 = Computes(L, H); Console.WriteLine(result0); break; case "3": Console.WriteLine("输入半径"); float r = float.Parse(Console.ReadLine()); float re = Computes(r, 0); Console.WriteLine(re); break; } } //正方形 static float Computes(float Long) { float re = Long * Long; return re; } //三角形 static float Computes(float Long, float Hight) { float result = Long * Hight / 2; return result; } //圆 static float Computes(float r, int a = 0) { float result = (float)Math.PI * r; return result; } } }
90a9f801477bfca6e2a990568ea453c832bc3232
C#
Pharsat/SIGED_3
/SIGED_3.CRM.Model/AccesoDeRecursos/OAD/OrdenesDeTrabajoOAD.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SIGED_3.CRM.Model.Negocio.Entidades; using SIGED_3.CRM.Model.Util.Enum; using SIGED_3.CRM.Model.Util.Session; namespace SIGED_3.CRM.Model.AccesoDeRecursos.OAD { internal class OrdenesDeTrabajoOAD { /// <summary> /// Selecciona todos los registros de la tabla Bodega /// </summary> /// <returns>Lista de registros tipo Bodega</returns> public List<OrdenesDeTrabajo> Seleccionar_All() { using (ModeloDataContext dc = new ModeloDataContext()) { return dc.OrdenesDeTrabajo.ToList(); } } /// <summary> /// Selecciona todos los registros de la tabla Bodega /// </summary> /// <param name=Id>Identificador de la Bodega</param> /// <returns>Objeto singular del tipo Bodega</returns> public OrdenesDeTrabajo Seleccionar_Id(long Id) { using (ModeloDataContext dc = new ModeloDataContext()) { return dc.OrdenesDeTrabajo.Single(p => p.Id == Id); } } /// <summary> /// /// </summary> /// <param name="estado"></param> /// <param name="id_Cliente"></param> /// <param name="consecutivo"></param> /// <param name="desde"></param> /// <param name="hasta"></param> /// <returns></returns> public List<LP_OrdenesDeTrabajoResult> Seleccionar_LP(long? estado, long? id_Cliente, long? consecutivo, DateTime? desde, DateTime? hasta) { using (ModeloDataContext dc = new ModeloDataContext()) { id_Cliente = id_Cliente == 0 ? null : id_Cliente; return dc.LP_OrdenesDeTrabajo(estado, id_Cliente, consecutivo, desde, hasta).ToList(); } } /// <summary> /// Guarda un objeto de tipo Bodega en la base de datos. /// </summary> /// <param name=objBodega>Objeto Bodega a guardar</param> public void Guardar(OrdenesDeTrabajo objOrdenesDeTrabajo) { using (ModeloDataContext dc = new ModeloDataContext()) { dc.OrdenesDeTrabajo.InsertOnSubmit(objOrdenesDeTrabajo); dc.SubmitChanges(); } } /// <summary> /// Guarda el objeto OrdenesDeTrabajo y obtiene su Id /// </summary> /// <param name="objPedido">Licnete a guardar</param> public long Guardar_2(OrdenesDeTrabajo objOrdenesDeTrabajo) { using (ModeloDataContext dc = new ModeloDataContext()) { dc.OrdenesDeTrabajo.InsertOnSubmit(objOrdenesDeTrabajo); dc.SubmitChanges(); return dc.OrdenesDeTrabajo.Max(p => p.Id); } } /// <summary> /// Elimina un objeto del tipo Bodega, se recibe su Id unicamente /// </summary> /// <param name=Id>Identificativo del(a) Bodega</param> public void Eliminar(OrdenesDeTrabajo objOrdenesDeTrabajo) { using (ModeloDataContext dc = new ModeloDataContext()) { OrdenesDeTrabajo _objOrdenesDeTrabajo = dc.OrdenesDeTrabajo.Single(p => p.Id == objOrdenesDeTrabajo.Id); dc.OrdenesDeTrabajo.DeleteOnSubmit(_objOrdenesDeTrabajo); dc.SubmitChanges(); } } /// <summary> /// Actualiza una Bodega, se basa en el identificador para actualizar el objeto. /// </summary> /// <param name=objBodega>Objeto del tipo Bodega</param> public void Actualizar(OrdenesDeTrabajo objOrdenesDeTrabajo) { using (ModeloDataContext dc = new ModeloDataContext()) { OrdenesDeTrabajo _objOrdenesDeTrabajo = dc.OrdenesDeTrabajo.Single(p => p.Id == objOrdenesDeTrabajo.Id); _objOrdenesDeTrabajo.Id = objOrdenesDeTrabajo.Id; _objOrdenesDeTrabajo.Id_Solicitante = objOrdenesDeTrabajo.Id_Solicitante; _objOrdenesDeTrabajo.Id_GrupoDeMiembros = objOrdenesDeTrabajo.Id_GrupoDeMiembros; _objOrdenesDeTrabajo.Id_Estado = objOrdenesDeTrabajo.Id_Estado; _objOrdenesDeTrabajo.Consecutivo = objOrdenesDeTrabajo.Consecutivo; _objOrdenesDeTrabajo.FechaGeneracion = objOrdenesDeTrabajo.FechaGeneracion; _objOrdenesDeTrabajo.FechaInicio = objOrdenesDeTrabajo.FechaInicio; _objOrdenesDeTrabajo.FechaFinalizacion = objOrdenesDeTrabajo.FechaFinalizacion; dc.SubmitChanges(); } } public List<OrdenesDeTrabajo> Seleccionar_All_NoRecibidos() { using (ModeloDataContext dc = new ModeloDataContext()) { return dc.OrdenesDeTrabajo.Where(p => p.Id_Estado != (long)EstadosDelProceso_Enum.OTTCO && p.Id_GrupoDeMiembros == SessionManager.Id_GrupoDeMiembros && dc.OrdenesDeTrabajo_Recursos.Where(pd => (pd.Cantidad - (dc.Recibidos_Recursos.Any(odtr => odtr.Id_OrdenesDeTrabajo_Recurso == pd.Id) ? (dc.Recibidos_Recursos.Where(odtr => odtr.Id_OrdenesDeTrabajo_Recurso == pd.Id).Sum(odtr => odtr.Cantidad)) : 0)) > 0).Select(pd => pd.Id_OrdenDeTrabajo).Distinct().Contains(p.Id)).ToList(); } } public List<R_OrdenesDeTrabajoResult> RelatorioDeOrdenesDeTrabajo(long? Consecutivo, long? id_GrupoDeMiembros) { using (ModeloDataContext dc = new ModeloDataContext()) { return dc.R_OrdenesDeTrabajo(Consecutivo, id_GrupoDeMiembros).ToList(); } } } }
f6228e17fed5baa4610bf003514fd4c73dfac816
C#
filipetoscano/Platinum
/src/Platinum.Mock/MockDataAttribute.cs
3.046875
3
using System; namespace Platinum.Mock { /// <summary> /// Markup, indicating that a property is subject to random /// data being generated /// </summary> [AttributeUsage( AttributeTargets.Class | AttributeTargets.Property )] public class MockDataAttribute : Attribute { /// <summary> /// Marks a property as having mock data from the given data set or /// function. /// </summary> /// <param name="name"> /// Name of mock data set or function name. /// </param> public MockDataAttribute( string name ) { #region Validations if ( name == null ) throw new ArgumentNullException( nameof( name ) ); #endregion this.Name = name; } /// <summary> /// Gets the name of the mock data set or function name. /// </summary> public string Name { get; private set; } /// <summary> /// Gets the likelihood, in percentage, that the attributed property will have /// a 'null' value. /// </summary> /// <remarks> /// The valid range is 0..100. Any other value will be ignored. /// </remarks> public int LikelihoodNull { get; set; } = 0; } }
351761c25a8925c9f8bcad90c6a6859553fe6f00
C#
Soeh0001/BackendLaborationGUI
/Models/LibraryModel.cs
2.65625
3
namespace LibraryAPI { using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; public partial class LibraryModel : DbContext { public LibraryModel() : base("name=LibraryModel") { } public virtual DbSet<Authors> Authors { get; set; } public virtual DbSet<Books> Books { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Authors>() .HasMany(e => e.Books) .WithMany(e => e.Authors) .Map(m => m.ToTable("BookAuthors").MapLeftKey("AuthorId").MapRightKey("BookId")); } } }
4da091e1c3419c7fa31a7442045756eec7c4e303
C#
kmich1/DSZI-2018
/Foods.cs
2.859375
3
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SFML.Graphics; using SFML.System; namespace DSZI_2018 { public struct Food { public string Path; public Sprite Sprite; public int Value; public int Predicted; public Food(string path, Sprite sprite, int value, int predicted) { Path = path; Sprite = sprite; Value = value; Predicted = predicted; } } public static class Foods { private static string[] Paths = Directory .GetFiles("./data/foods/") .Select(Path.GetFileName) .ToArray(); public static Food GetRandomFood() { string path = Paths[Utils.GetRandom(0, Paths.Length)]; string foodType = path.Split('_')[0]; Texture texture = new Texture("./data/foods/" + path); Sprite sprite = new Sprite(texture) { Scale = new Vector2f((float)Config.FIELD_SIZE / (float)texture.Size.X, (float)Config.FIELD_SIZE / (float)texture.Size.Y) }; int value = 0; switch (foodType) { case "battery": value = 40; break; case "powerbank": value = 20; break; case "accumulator": value = 60; break; case "socket": value = 80; break; } int predicted = Algorithms.FoodRecognition(path); return new Food(path, sprite, value, predicted); } } }
ecda40065ffe530f703830e76d21cd2f821fcf82
C#
hqw786/Test
/PicoVR/360/Assets/APP/Scripts/Framework/SubPool.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; public class SubPool { public SubPool() { } public SubPool(GameObject prefab) { prefabObj = prefab; } public GameObject prefabObj; List<GameObject> objs = new List<GameObject>(); //对子对象内的对象进行增删改查操作 GameObject AddObject() { //实例化预置体并返回 objs.Add(Pool.Instance.Instantiation(prefabObj)); return objs[objs.Count - 1]; } public void DelAllObject() { objs.Clear(); } public GameObject GetObject() { foreach(GameObject g in objs) { if(!g.activeInHierarchy) { return g; } } //运行到这一步,说明没有隐藏的对象,生成新对象 return AddObject(); } }
09a02c13b21019d78abff9fb620e73b2dd7bfb20
C#
sgprojectmanagement/sgemployeemanagement
/sgprojectmanagement/Repository/Repository.cs
2.765625
3
using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; namespace sgprojectmanagement.Repository { public class Repository<TEntity> { private IMongoDatabase _database; private string _tableName; private IMongoCollection<TEntity> _collection; public Repository(IMongoDatabase db, string tblName) { _database = db; _tableName = tblName; _collection = _database.GetCollection<TEntity>(tblName); } public async Task<TEntity> Get(FilterDefinition<TEntity> filter) { return await _collection.Find<TEntity>(filter).FirstOrDefaultAsync(); } public async Task<IEnumerable<TEntity>> GetAll() { var some= _collection.Find(_ => true).ToListAsync(); return await some; } public async void Add(TEntity entity) { await _collection.InsertOneAsync(entity); } public async void Delete(FilterDefinition<TEntity> filter) { await _collection.DeleteOneAsync(filter); } public async void Update(FilterDefinition<TEntity> filter, UpdateDefinition<TEntity> update) { await _collection.UpdateOneAsync(filter, update); } } }
9fa28cc9f850868f74e9d4ee8b4aa1effc9f4c93
C#
test-in-prod/ueravchatclient
/Crypton.AvChat.Gui/Power/OpWhitelist/Whitelist.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml.Serialization; using System.Diagnostics; namespace Crypton.AvChat.Gui.Power.OpWhitelist { [Serializable] public class Channel { public string ChannelName { get; set; } public List<User> Users { get; set; } public Channel() { this.Users = new List<User>(); } public override string ToString() { return this.ChannelName; } } [Serializable] public class User { public string Name { get; set; } public override string ToString() { return this.Name; } } /// <summary> /// Manages Ops Whitelist /// </summary> internal static class WhitelistManager { private static List<Channel> _cache = null; /// <summary> /// Gets the white list /// </summary> public static List<Channel> List { get { if (_cache == null) { _cache = Load(); } return _cache; } } /// <summary> /// Gets ops white list, returns new list on any errors /// </summary> /// <returns></returns> public static List<Channel> Load() { string fpath = Path.Combine(DirectoryService.UERFolder, "opswhitelist.xml"); if (File.Exists(fpath)) { using (StreamReader sr = new StreamReader(fpath)) { XmlSerializer xs = new XmlSerializer(typeof(List<Channel>)); try { List<Channel> list = (List<Channel>)xs.Deserialize(sr); return list ?? new List<Channel>(); } catch (Exception any) { Trace.TraceError(any.ToString()); } } } return new List<Channel>(); } /// <summary> /// Saves channel list /// </summary> /// <param name="list"></param> public static void Save(List<Channel> list) { list = list ?? new List<Channel>(); _cache = list; string fpath = Path.Combine(DirectoryService.UERFolder, "opswhitelist.xml"); if (File.Exists(fpath)) { File.Delete(fpath); } using (StreamWriter sw = new StreamWriter(fpath)) { XmlSerializer xs = new XmlSerializer(typeof(List<Channel>)); xs.Serialize(sw, list); } } public static IEnumerable<Channel> Channels { get { return Load(); } } } }
55df4ec5aa9bac600dd1a03e90b1e4889f3924cc
C#
Techbrunch/restore
/Restore.Tests/InMemoryCrudDataEndpoint.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using Restore.Channel.Configuration; namespace Restore.Tests { public class InMemoryCrudDataEndpoint<T, TId> : ICrudEndpoint<T, TId> where TId : IEquatable<TId> { [NotNull] private readonly TypeConfiguration<T, TId> _typeConfig; [NotNull] private readonly IDictionary<TId, T> _items = new Dictionary<TId, T>(); public InMemoryCrudDataEndpoint([NotNull] TypeConfiguration<T, TId> typeConfig, [NotNull] IDictionary<TId, T> items) : this(typeConfig) { if (items == null) throw new ArgumentNullException(nameof(items)); _items = items; } public InMemoryCrudDataEndpoint(TypeConfiguration<T, TId> typeConfig, IEnumerable<T> items) : this(typeConfig, items.ToDictionary(item => typeConfig.IdExtractor(item))) { } public InMemoryCrudDataEndpoint([NotNull] TypeConfiguration<T, TId> typeConfig) { if (typeConfig == null) throw new ArgumentNullException(nameof(typeConfig)); _typeConfig = typeConfig; } public T Create(T item) { if (_items.ContainsKey(_typeConfig.IdExtractor(item))) { throw new ArgumentException("Item already exists"); } _items.Add(_typeConfig.IdExtractor(item), item); return item; } public T Read(TId id) { T result; var succes = _items.TryGetValue(id, out result); return succes ? result : default(T); } /// <summary> /// For testing purposes, so far not part of general interface. /// </summary> /// <returns></returns> public IEnumerable<T> ReadAll() { return _items.Values; } public T Update(T item) { // Just replace the instance if it exists. var itemId = _typeConfig.IdExtractor(item); var inlist = Read(itemId); if (EqualityComparer<T>.Default.Equals(inlist, default(T))) { // found, no default value atleast. _items[itemId] = item; } else { throw new ArgumentException("Can not update unexisting item!"); } return inlist; } public T Delete(T item) { if (_items.Remove(_typeConfig.IdExtractor(item))) { return item; } return default(T); } } }
d9802ce1cd9121d8e22c09d9610ac4ec7913a4f3
C#
bartoszjaniak/MakeMyDayApi
/Poligon/Program.cs
2.890625
3
using MakeMyDayApi.Models; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Poligon { class Program { private static string connectionString = "data source=mssql4.webio.pl,2401;initial catalog=bjaniak_makemyday;persist security info=True;user id=bjaniak_makemyday;password=Qewasdzxc1!;multipleactiveresultsets=True;"; static void Main(string[] args) { Account account = GetAccountByAccesData(new AccesData() { Login = "Bjaniak", Password = "12345" }); Console.WriteLine($"{account.User.Id} {account.User.Name} {account.User.Lastname} {account.User.InviteKey}"); Console.ReadKey(); } public static Account GetAccountByAccesData(AccesData accesData) { using (SqlConnection sqlCon = new SqlConnection(connectionString)) { sqlCon.Open(); SqlCommand sqlCommand = new SqlCommand("SELECT acc.Login, acc.Password, acc.Guid, p.ID, p.Name, p.Lastname, p.InviteKey FROM Accounts acc JOIN Persons p on p.ID = acc.Person WHERE acc.Login = @login AND acc.Password = @password", sqlCon); sqlCommand.Parameters.AddWithValue("@Login", accesData.Login); sqlCommand.Parameters.AddWithValue("@Password", accesData.Password); var reader = sqlCommand.ExecuteReader(); while (reader.Read()) { return new Account() { Login = reader[0].ToString(), Password = reader[1].ToString(), Guid = reader[2].ToString(), User = new User() { Id = int.Parse(reader[3].ToString()), Name = reader[4].ToString(), Lastname = reader[5].ToString(), InviteKey = reader[6].ToString() } }; } } return null; } } }
48ccb129f5c89fdb5e8c875bd964f0ef02b48ce9
C#
wilsonsantosnet/sample-seed-core-20-coreui
/Seed.Data/Repository/Sample/SampleFilterBasicExtension.cs
2.515625
3
using Seed.Domain.Entitys; using Seed.Domain.Filter; using System.Linq; namespace Seed.Data.Repository { public static class SampleFilterBasicExtension { public static IQueryable<Sample> WithBasicFilters(this IQueryable<Sample> queryBase, SampleFilter filters) { var queryFilter = queryBase; if (filters.Ids.IsSent()) queryFilter = queryFilter.Where(_ => filters.GetIds().Contains(_.SampleId)); if (filters.SampleId.IsSent()) { queryFilter = queryFilter.Where(_=>_.SampleId == filters.SampleId); } if (filters.Name.IsSent()) { queryFilter = queryFilter.Where(_=>_.Name.Contains(filters.Name)); } if (filters.Descricao.IsSent()) { queryFilter = queryFilter.Where(_=>_.Descricao.Contains(filters.Descricao)); } if (filters.SampleTypeId.IsSent()) { queryFilter = queryFilter.Where(_=>_.SampleTypeId == filters.SampleTypeId); } if (filters.Ativo.IsSent()) { queryFilter = queryFilter.Where(_=>_.Ativo != null && _.Ativo.Value == filters.Ativo); } if (filters.Age.IsSent()) { queryFilter = queryFilter.Where(_=>_.Age != null && _.Age.Value == filters.Age); } if (filters.Category.IsSent()) { queryFilter = queryFilter.Where(_=>_.Category != null && _.Category.Value == filters.Category); } if (filters.Datetime.IsSent()) { queryFilter = queryFilter.Where(_=>_.Datetime != null && _.Datetime.Value >= filters.Datetime.Value); } if (filters.DatetimeStart.IsSent()) { queryFilter = queryFilter.Where(_=>_.Datetime != null && _.Datetime.Value >= filters.DatetimeStart.Value); } if (filters.DatetimeEnd.IsSent()) { filters.DatetimeEnd = filters.DatetimeEnd.Value.AddDays(1).AddMilliseconds(-1); queryFilter = queryFilter.Where(_=>_.Datetime != null && _.Datetime.Value <= filters.DatetimeEnd); } if (filters.Tags.IsSent()) { queryFilter = queryFilter.Where(_=>_.Tags.Contains(filters.Tags)); } if (filters.Valor.IsSent()) { queryFilter = queryFilter.Where(_=>_.Valor != null && _.Valor.Value == filters.Valor); } if (filters.UserCreateId.IsSent()) { queryFilter = queryFilter.Where(_=>_.UserCreateId == filters.UserCreateId); } if (filters.UserCreateDate.IsSent()) { queryFilter = queryFilter.Where(_=>_.UserCreateDate >= filters.UserCreateDate); } if (filters.UserCreateDateStart.IsSent()) { queryFilter = queryFilter.Where(_=>_.UserCreateDate >= filters.UserCreateDateStart ); } if (filters.UserCreateDateEnd.IsSent()) { filters.UserCreateDateEnd = filters.UserCreateDateEnd.AddDays(1).AddMilliseconds(-1); queryFilter = queryFilter.Where(_=>_.UserCreateDate <= filters.UserCreateDateEnd); } if (filters.UserAlterId.IsSent()) { queryFilter = queryFilter.Where(_=>_.UserAlterId != null && _.UserAlterId.Value == filters.UserAlterId); } if (filters.UserAlterDate.IsSent()) { queryFilter = queryFilter.Where(_=>_.UserAlterDate != null && _.UserAlterDate.Value >= filters.UserAlterDate.Value); } if (filters.UserAlterDateStart.IsSent()) { queryFilter = queryFilter.Where(_=>_.UserAlterDate != null && _.UserAlterDate.Value >= filters.UserAlterDateStart.Value); } if (filters.UserAlterDateEnd.IsSent()) { filters.UserAlterDateEnd = filters.UserAlterDateEnd.Value.AddDays(1).AddMilliseconds(-1); queryFilter = queryFilter.Where(_=>_.UserAlterDate != null && _.UserAlterDate.Value <= filters.UserAlterDateEnd); } return queryFilter; } } }
e4b07d8db17a5b1c365c3678a25334b6d3c83cda
C#
hungyiloo/photo-sorter
/PhotoSorter/Viewmodels/MainViewmodel.cs
2.671875
3
using PhotoSorter.Extensions; using PhotoSorter.Views; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Windows.Media; using System.Windows.Media.Imaging; namespace PhotoSorter.Viewmodels { public class MainViewmodel : INotifyPropertyChanged { private IMainView _view; public MainViewmodel(IMainView view) { _view = view; var settings = PhotoSorter.Properties.Settings.Default; if (!String.IsNullOrEmpty(settings.SourceDirectory)) SetPhotoSourceDir(new DirectoryInfo(settings.SourceDirectory)); if (!String.IsNullOrEmpty(settings.DestinationDirectory)) SetPhotoDestinationDir(new DirectoryInfo(settings.DestinationDirectory)); if (!String.IsNullOrEmpty(settings.Bookmark)) GoToPhoto(settings.Bookmark); } # region Public Properties (bound to view) public bool SortingMode { get { return _PhotoSourceDir != null && _PhotoDestinationDir != null; } } public bool SetupMode { get { return _PhotoSourceDir == null || _PhotoDestinationDir == null; } } public ImageSource Photo { get { if (_Photos == null || _Photos.Current == null) return null; var img = new BitmapImage(new Uri(String.Format(_Photos.Current.FullName), UriKind.Relative)); img.Freeze(); // -> to prevent error: "Must create DependencySource on same Thread as the DependencyObject" return img; } } public string CopyDetails { get { return String.Format( "{0} => {1}{2}", _Photos != null && _Photos.Current != null ? _Photos.Current.FullName : "[source]", _PhotoDestinationDir == null ? "[destination]" : _PhotoDestinationDir.FullName + "\\", _Photos != null && _Photos.Current != null ? _Photos.Current.Name : "" // TODO: transform name ); } } public string Progress { get { return _Photos != null ? String.Format("{0}/{1}", _Photos.Position + 1, _Photos.Count) : "?/?"; } } # endregion # region Private Properties private DirectoryInfo _PhotoSourceDir { get; set; } private DirectoryInfo _PhotoDestinationDir { get; set; } private IterableList<FileInfo> _Photos { get; set; } # endregion # region Public Methods (imperative actions) public void SetPhotoSourceDir(DirectoryInfo di) { _PhotoSourceDir = di; var photos = new IterableList<FileInfo>(); foreach (FileInfo f in _PhotoSourceDir.EnumerateFiles("*.*", SearchOption.AllDirectories)) { if (f.Extension.ToUpper() == ".JPG" || f.Extension.ToUpper() == ".JPEG" || f.Extension.ToUpper() == ".PNG") photos.Add(f); } if (photos.Count > 0) { _Photos = photos; _Photos.MoveNext(); } else { _view.Alert("No photos found"); _PhotoSourceDir = null; } OnPropertyChanged("SortingMode", "SetupMode", "Photo", "Progress", "CopyDetails"); } public void SetPhotoDestinationDir(DirectoryInfo di) { _PhotoDestinationDir = di; OnPropertyChanged("SortingMode", "SetupMode", "Progress", "CopyDetails"); } public void AcceptPhoto() { var photo = _Photos.Current; try { photo.CopyTo(String.Format("{0}\\{1}", _PhotoDestinationDir.FullName, photo.Name)); } catch (IOException e) { if (_view.Confirm("This file already exists in the destination. Do you want to overwrite?")) { photo.CopyTo(String.Format("{0}\\{1}", _PhotoDestinationDir.FullName, photo.Name), true); } else { return; } } NextPhoto(); } public void NextPhoto() { if (!_Photos.MoveNext()) { _Photos.Reset(); _Photos.MoveNext(); } OnPropertyChanged("Photo", "Progress", "CopyDetails"); } public void PreviousPhoto() { // Try to go back, but do nothing if already at the beginning of the list if (_Photos.MovePrevious()) { OnPropertyChanged("Photo", "Progress", "CopyDetails"); } } public void GoToPhoto(string path) { FileInfo match = null; foreach (var photo in _Photos) { if (photo.FullName.Equals(path)) match = photo; } if (match != null) { _Photos.Position = _Photos.IndexOf(match); OnPropertyChanged("Photo", "Progress", "CopyDetails"); } else { _view.Alert(String.Format("Photo '{0}' not found!", path)); } } public void SaveSettings() { var settings = PhotoSorter.Properties.Settings.Default; if (SortingMode) { settings.Bookmark = _Photos.Current.FullName; settings.SourceDirectory = _PhotoSourceDir.FullName; settings.DestinationDirectory = _PhotoDestinationDir.FullName; settings.Save(); } } # endregion # region Property Changed Notification Implementation public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } protected void OnPropertyChanged(params string[] names) { foreach (var name in names) { OnPropertyChanged(name); } } # endregion } }
a3efae1f7fadb132e31d1ae5e05a75c56be97126
C#
SharePointDiv/HRPortal
/SGCorpHR.DATA/EmployeeDirectoryRepository.cs
2.59375
3
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using Dapper; using SGCorpHR.Models; using SGCorpHR.Models.Interfaces; namespace SGCorpHR.DATA { public class EmployeeDirectoryRepository : IEmployeeDirectoryRepository { public List<Employee> ListAllEmployees() { var emps = new List<Employee>(); using (SqlConnection cn = new SqlConnection(Settings.ConnectionString)) { var cmd = new SqlCommand("select e.FirstName, e.LastName,e.HireDate, (m.FirstName + ' ' + m.LastName) as [ManagerName], Departments.DepartmentName, Departments.DepartmentID, l.[state], e.[Status],e.EmpID from Employee e inner join Departments on e.DepartmentID = Departments.DepartmentID inner join Employee m on m.EmpID = e.ManagerID inner join Location l on e.LocationID = l.LocationID order by e.LastName", cn); cn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { var temp = new Employee(); temp.Department = new Departments(); temp.FirstName = dr.GetString(0); temp.LastName = dr.GetString(1); temp.HireDate = dr["HireDate"] is DBNull ? DateTime.Now : dr.GetDateTime(2); temp.ManagerName = dr.GetString(3); temp.Department.DepartmentName = dr.GetString(4); temp.Department.DepartmentID = dr.GetInt32(5); temp.State = dr.GetString(6); temp.Status = dr["Status"] is DBNull ? String.Empty : dr.GetString(7); temp.EmpID = dr.GetInt32(8); emps.Add(temp); } } } return emps; } public List<Employee> GetEmpByDptID(int id) { var emps = new List<Employee>(); using (SqlConnection cn = new SqlConnection(Settings.ConnectionString)) { var cmd = new SqlCommand("select e.FirstName, e.LastName,e.HireDate, (m.FirstName + ' ' + m.LastName) as [ManagerName], Departments.DepartmentName, Departments.DepartmentID, l.[state], e.[Status] from Employee e inner join Departments on e.DepartmentID = Departments.DepartmentID inner join Employee m on m.EmpID = e.ManagerID inner join Location l on e.LocationID = l.LocationID WHERE e.DepartmentID = "+ id+" order by e.LastName", cn); cn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { var temp = new Employee(); temp.Department = new Departments(); temp.FirstName = dr.GetString(0); temp.LastName = dr.GetString(1); temp.HireDate = dr["HireDate"] is DBNull ? DateTime.Now : dr.GetDateTime(2); temp.ManagerName = dr.GetString(3); temp.Department.DepartmentName = dr.GetString(4); temp.Department.DepartmentID = dr.GetInt32(5); temp.State = dr.GetString(6); temp.Status = dr["Status"] is DBNull ? String.Empty : dr.GetString(7); emps.Add(temp); } } } return emps; } public void DeleteEmp(int id) { using (SqlConnection cn = new SqlConnection(Settings.ConnectionString)) { cn.Query("Delete Employee WHERE EmpID = @empId", new { empId = id }); } } public void UpdateEmp(Employee updatedEmployee) { using (SqlConnection cn = new SqlConnection(Settings.ConnectionString)) { var p = new DynamicParameters(); p.Add("@firstName", updatedEmployee.FirstName); p.Add("@lastName", updatedEmployee.LastName); p.Add("@locationId", updatedEmployee.LocationID); p.Add("@managerId", 11); p.Add("@status", updatedEmployee.Status); p.Add("@deptId", updatedEmployee.Department.DepartmentID); p.Add("@empId", updatedEmployee.EmpID); p.Add("@hireDate", updatedEmployee.HireDate); cn.Query("UpdateEmployee", p, commandType: CommandType.StoredProcedure); } } public Employee GetEmpById(int id) { using (SqlConnection cn = new SqlConnection(Settings.ConnectionString)) { var cmd = new SqlCommand("select e.FirstName, e.LastName,e.HireDate, (m.FirstName + ' ' + m.LastName) as [ManagerName], Departments.DepartmentName, Departments.DepartmentID, e.LocationID, e.[Status],e.EmpID from Employee e inner join Departments on e.DepartmentID = Departments.DepartmentID inner join Employee m on m.EmpID = e.ManagerID inner join Location l on e.LocationID = l.LocationID WHERE e.EmpID = @empId order by e.LastName", cn); SqlParameter param = new SqlParameter(); param.ParameterName = "@empId"; param.Value = id; cmd.Parameters.Add(param); cn.Open(); var temp = new Employee(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { temp.Department = new Departments(); temp.FirstName = dr.GetString(0); temp.LastName = dr.GetString(1); temp.HireDate = dr["HireDate"] is DBNull ? DateTime.Now : dr.GetDateTime(2); temp.ManagerName = dr.GetString(3); temp.Department.DepartmentName = dr.GetString(4); temp.Department.DepartmentID = dr.GetInt32(5); temp.LocationID = dr.GetInt32(6); temp.Status = dr["Status"] is DBNull ? String.Empty : dr.GetString(7); temp.EmpID = dr.GetInt32(8); } } return temp; } } } }
3241c406b6d95ddf1a55d8ee27fb6426505c2542
C#
Dominent/TelerikAcademy
/C# OOP/03.Defining Classes - Part 1/GSM.cs
3.171875
3
using System.Collections.Generic; using System.Linq; namespace Defining_Classes___Part_1 { class Gsm { private static int iPhone4S; public Gsm() : this(null) { } public Gsm(string model) : this(model, null) { } public Gsm(string model, string manufacturer) : this(model, manufacturer, null) { } public Gsm(string model, string manufacturer, decimal? price) : this(model, manufacturer, price, null) { } public Gsm(string model, string manufacturer, decimal? price, string owner) : this(model, manufacturer, price, owner, null) { } public Gsm(string model, string manufacturer, decimal? price, string owner, Battery battery) : this(model, manufacturer, price, owner, battery, null) { } public Gsm(string model, string manufacturer, decimal? price, string owner, Battery battery, Display display) { this.Model = model; this.Manufacturer = manufacturer; this.Price = price; this.Owner = owner; this.Battery = battery; this.Display = display; } public string Model { get; set; } public string Manufacturer { get; set; } public decimal? Price { get; set; } public string Owner { get; set; } public Battery Battery { get; set; } public Display Display { get; set; } public List<Call> CallHistory { get; set; } public static int IPhone4S { get { return iPhone4S; } set { iPhone4S = value; } } public void AddCall(Call call) => CallHistory.Add(call); public void RemoveCall(Call call) => CallHistory.Remove(call); public decimal TotalPriceOfCalls() => (decimal)CallHistory.Sum(call => call.Seconds) / (60m * Call.PriceForCall); public override string ToString() // check for null { return $"Model - {Model}" + $"\nManufacturer - {Manufacturer}" + $"\nPrice - {Price}" + $"\nOwner - {Owner}" + $"\nBattery Info : " + $"\nModel - {Battery.Model}" + $"\nBatteryType - {Battery.BatteryType}" + $"\nHoursIdle - {Battery.HoursIdle}" + $"\nHoursTalk - {Battery.HoursTalk}" + $"\nDisplay Info : " + $"\nSize - {Display.Size}" + $"\nNumberOfColours - {Display.NumberOfColors}"; } } }
d32caba5f4b64e17f437962af6d5de3e42eb0b78
C#
semihokur/pattern-matching-csharp
/Src/Test/Utilities/TestHelpers.cs
2.671875
3
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; namespace Roslyn.Test.Utilities { public static class TestHelpers { public static IEnumerable<Type> GetAllTypesImplementingGivenInterface(Assembly assembly, Type interfaceType) { if (assembly == null || interfaceType == null || !interfaceType.IsInterface) { throw new ArgumentException("interfaceType is not an interface.", "interfaceType"); } return assembly.GetTypes().Where((t) => { // simplest way to get types that implement mef type // we might need to actually check whether type export the interface type later if (t.IsAbstract) { return false; } var candidate = t.GetInterface(interfaceType.ToString()); return candidate != null && candidate.Equals(interfaceType); }).ToList(); } public static IEnumerable<Type> GetAllTypesSubclassingType(Assembly assembly, Type type) { if (assembly == null || type == null) { throw new ArgumentException("Invalid arguments"); } return (from t in assembly.GetTypes() where !t.IsAbstract where type.IsAssignableFrom(t) select t).ToList(); } public static IEnumerable<Type> GetAllTypesWithStaticFieldsImplementingType(Assembly assembly, Type type) { return assembly.GetTypes().Where(t => { return t.GetFields(BindingFlags.Public | BindingFlags.Static).Any(f => type.IsAssignableFrom(f.FieldType)); }).ToList(); } public static string GetCultureInvariantString(object value) { if (value == null) return null; var valueType = value.GetType(); if (valueType == typeof(string)) { return value as string; } if (valueType == typeof(DateTime)) { return ((DateTime)value).ToString("M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); } if (valueType == typeof(float)) { return ((float)value).ToString(CultureInfo.InvariantCulture); } if (valueType == typeof(double)) { return ((double)value).ToString(CultureInfo.InvariantCulture); } if (valueType == typeof(decimal)) { return ((decimal)value).ToString(CultureInfo.InvariantCulture); } return value.ToString(); } } }
40f1cec99325016dd311fe7ad49eb784f2a53757
C#
clangelov/TelerikAcademyHomework
/16_WebForms/IntroductionASP.NET-Homework/SumNumbers-WebForms/Summator.aspx.cs
3.0625
3
namespace SumNumbers_WebForms { using System; using System.Globalization; public partial class Summator : System.Web.UI.Page { protected void Sum_Numbers(object sender, EventArgs e) { try { var firstNum = int.Parse(this.firstNumber.Value); var secondNum = int.Parse(this.secondNumber.Value); var sum = firstNum + secondNum; this.SumResult.Text = "Result is " + sum.ToString(CultureInfo.InvariantCulture); this.SumResult.Visible = true; } catch (Exception) { this.SumResult.Text = "Invalid input"; this.SumResult.Visible = true; } } } }
bd1fa81569d580a2a71c88f407fbe1cc599c9aae
C#
AndreiValuika/EPAM_Training
/NET.W.2019.Valuika.10/Task_5/CompRowsSum.cs
3.578125
4
using System.Collections.Generic; namespace SortJaggedArray { public class CompRowsSum : IComparer<int[]> { public int Compare(int[] x, int[] y) { return SumRow(x) > SumRow(y) ? 1 : -1; } private static int SumRow(int[] row) { int sum = 0; foreach (var item in row) { sum += item; } return sum; } } }
907e4d32139181ab79f8c6a45cdfdf4d9c7c77de
C#
line-developer-community/line-messaging-api-csharp
/line-messaging-api-csharp/Messages/Sender.cs
3.125
3
using System; namespace LineDC.Messaging.Messages { /// <summary> /// When sending a message from the LINE Official Account, you can specify the sender in Message objects. /// </summary> public class Sender { /// <summary> /// Display name. Certain words such as LINE may not be used. (Max: 20 characters) /// </summary> public string Name { get; } /// <summary> /// URL of the image to display as an icon when sending a message. (Max: 1000 characters) /// HTTPS /// </summary> public string IconUrl { get; } /// <summary> /// Constructor /// </summary> /// <param name="name"> /// Display name. Certain words such as LINE may not be used. (Max: 20 characters) /// </param> /// <param name="iconUrl"> /// URL of the image to display as an icon when sending a message. (Max: 1000 characters) /// HTTPS /// </param> public Sender(string name, string iconUrl) { Name = name.Substring(0, Math.Min(name.Length, 20)); IconUrl = iconUrl; } } }
388e7bed40aaa1ddde59fa36ad82b0f3e488f90f
C#
l87freeman/SquareCalculator
/GCalculator/Servises/LogReaderService.cs
2.890625
3
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using Services.Interfaces; using Services.Models; using Services.Extentions; namespace Services { public class FileLogReaderService:ILogReader { private readonly string _fileLogPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["fileLogPath"]); private readonly string _logNameFormat = ConfigurationManager.AppSettings["logNameFormat"]; /// <summary> /// <exception cref="DirectoryNotFoundException"></exception> /// </summary> /// <returns></returns> public ICollection<MessageDto> ReadLog(string logName) { var list = Directory.GetFiles(_fileLogPath) .Select(x => new FileInfo(x)) .Where(x => x.Name == logName) .SelectMany(ReadFile).ToMessages("|"); return list; } /// <summary> /// <exception cref="DirectoryNotFoundException"></exception> /// </summary> /// <returns></returns> public ICollection<LogDescriptionDto> LogList() { var list = Directory.GetFiles(_fileLogPath); return list.Select(s => new FileInfo(s)) .Select(fi => new LogDescriptionDto {Date = fi.CreationTime, Name = fi.Name}).ToList(); } private IEnumerable<string> ReadFile(FileInfo fileInfo) { var list = new List<string>(); using (var stream = fileInfo.OpenRead()) using (var streamReader = new StreamReader(stream)) { string str; while ((str = streamReader.ReadLine()) != null) { list.Add(str); } } return list; } } }
24b0e81a32afed0cc1e45ff87bcfd7257d6a64e2
C#
palladiumkenya/IQCareKe
/IQCare.CCC/DataAccess.CCC/Repository/person/PatientPopulationRepository.cs
2.5625
3
using System.Collections.Generic; using System.Linq; using DataAccess.CCC.Interface.person; using DataAccess.Context; using Entities.PatientCore; namespace DataAccess.CCC.Repository.person { public class PatientPopulationRepository :BaseRepository<PatientPopulation>,IPatientPopulationRepository { private readonly PersonContext _context; public PatientPopulationRepository() : this(new PersonContext()) { } public PatientPopulationRepository(PersonContext context) : base(context) { _context = context; } public List<PatientPopulation> GetPatientPopulations(int patientId) { IPatientPopulationRepository patientPopulationRepository =new PatientPopulationRepository(); List<PatientPopulation> myList = new List<PatientPopulation> { patientPopulationRepository.FindBy(x => x.PersonId == patientId & x.DeleteFlag == true) .OrderBy(x => x.Id) .FirstOrDefault() }; return myList; } } }
a2ca19be3a14271f15a6cec2c28335510f808d7d
C#
SaintOswald/SaintOswald.Libraries.Extensions
/SaintOswald.Libraries.Extensions/SaintOswald.Libraries.Extensions/LongExtensions/LongExtensions.cs
3.46875
3
/*********************************************************************************** * * Saint Oswald: Libraries - Extensions * * Copyright (c) 2015 - 2016, Saint Oswald * *********************************************************************************** * * LICENSED UNDER THE MIT LICENSE * SEE LICENSE FILE IN THE PROJECT ROOT FOR LICENSE INFORMATION * ***********************************************************************************/ using System; namespace SaintOswald.Libraries.Extensions.LongExtensions { /// <summary> /// Adds Extension Methods to long to provide useful, reusable functionality /// </summary> public static class LongExtensions { /// <summary> /// Converts the specified byte value to human readable file size format /// </summary> /// <param name="bytes">The byte value to convert</param> /// <param name="decimals">The number of decimal places in the formatted value</param> /// <returns> /// The specified byte value formatted as a human readable file size string /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified decimals value is less than 1 or greater than 28 /// </exception> public static string ToFileSize(this long bytes, int decimals = 2) { if (decimals < 1 || decimals > 28) { throw new ArgumentOutOfRangeException(nameof(decimals), "Decimals must be at least 1 and no bigger than 28"); } if (bytes >= 1099511627776) { return Math.Round(((decimal)bytes / 1024 / 1024 / 1024 / 1024), decimals) + " TB"; } else if (bytes >= 1073741824) { return Math.Round(((decimal)bytes / 1024 / 1024 / 1024), decimals) + " GB"; } else if (bytes >= 1048576) { return Math.Round(((decimal)bytes / 1024 / 1024), decimals) + " MB"; } else if (bytes >= 1024) { return Math.Round(((decimal)bytes / 1024), decimals) + " KB"; } else { return bytes + (bytes == 1 ? " byte" : " bytes"); } } } }
e6dc99e0b5bafffbfb84f439371f0caa25bcc598
C#
MokretsovD/ATM
/ATM/HostProcessor/Mock/ATMOperation.cs
3.03125
3
using System; namespace ATM.HostProcessor.Mock { /// <summary> /// Represents ATM operation. In this case only a withdrawal operation :) /// </summary> public class AtmOperation { /// <summary> /// Operation identifier /// </summary> public Guid OperationId { get; } /// <summary> /// Number of card /// </summary> public string CardNumber { get; } /// <summary> /// Charged fee /// </summary> public decimal Fee { get; } /// <summary> /// Operation Date /// </summary> public DateTime OperationDate { get; private set; } /// <summary> /// Withdrawed amount /// </summary> public decimal Amount { get; } /// <summary> /// Indicates that operation has been completed succefully /// </summary> /// <remarks>This could be OperationStatus instead. But for the simplicity sake I made it like this</remarks> public bool OperationCompleted { get; private set; } public AtmOperation(string cardNumber, Guid operationId, decimal amount, decimal fee, DateTime operationDate) { OperationDate = operationDate; CardNumber = cardNumber; OperationId = operationId; Fee = fee; Amount = amount; OperationCompleted = false; } /// <summary> /// Completes the current operation /// </summary> /// <param name="CompletionDate">Date and time.</param> public void SetComplete(DateTime CompletionDate) { // We can see that current OperationDate will be rewritten by // CompletionDate. Why? The reason is the same - to avoid unnecessary // complexity in the test task where it is possible. // Good solution would be to have status history for the operation // with date and time for each status change OperationDate = CompletionDate; OperationCompleted = true; } } }
4ed7269f190dad7961c79acf962e8221ee1727fb
C#
hdriel/C-_ScheduleCollage
/WindowsFormsApplication1/Lessons/ClassRoom.cs
2.921875
3
namespace ProjectAandB { using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; public class ClassRoom { private string _building; [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] [Column(Order = 0)] public string building { get { return _building; } set { if (value != _building) { _building = value; } } } private int _number; [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] [Column(Order = 1)] public int number { get { return _number; } set { if (value != _number) { _number = value; } } } [Required] public int maxStudents { get; set; } [Required] public bool hasProjector { get; set; } public string getNameClass() { return "" + building + number.ToString(); } } }
11bb401fbf330d6b349e27146224772c07bd1a15
C#
Trio556/Programming
/Programming/DataStructures/IDictionary.cs
2.8125
3
using System; using System.Collections.Generic; using System.Text; namespace Programming.DataStructures { public interface IDictionary<tkey, tvalue> : IEnumerable<KeyValuePair<tkey, tvalue>> { int Count { get; } tvalue this[tkey key] { get;set; } void Add(tkey key, tvalue value); void Remove(tkey key); void Clear(); } }
805423afdeff7a1f194ff448875da9f5720bc1ed
C#
Alikvk/AyvanSaray-CSharp-Projects
/DERS KODLARI/Hafta 2/Hafta2Gun4Part2/Program.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hafta2Gun4Part2 { class Program { static void Main(string[] args) { //implicit conversion (type-safe'tir.veri kaybı olmaz) int sayi = 5000; long dahabuyuksayi = sayi; //expilicit conversion (veri kaybı vardır) double ondaliklisayi = 154.95; int tamsayi = (int)ondaliklisayi; //aşağıdaki cast işlemi hata verir string yazi = "24121"; int sonuc = (int)yazi; //aşağıdaki cast'ten byte'a değer olarak 192 gelir. 56000%256 int numara = 56000; byte kucukSayi = (byte)numara; } } }
1770f5aaad594655e3e7bcbe773d07c19a74b69c
C#
Shmuel930/Neural_Network
/Neural_Network/Program.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Neural_Network { class Program { static void Main(string[] args) { NeuralNetwork myFirstNeuralNetWork = new NeuralNetwork(2, 12, 22); float[] inputArr = { 1, 0 }; float[] outputArr = myFirstNeuralNetWork.FeedForward(inputArr); for (int i = 0; i < outputArr.Length; i++) { Console.WriteLine(outputArr[i]); } } } }