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
5ee303b851c7bacf5bc931466c8ca6830967ff2b
C#
iliadsh/Calc.NET
/Calc.NET/SimpleCalculator.cs
3.203125
3
using System; using System.Collections.Generic; using System.Text; namespace Calc.NET { public class SimpleCalculator { private Parser parser; private SyntaxTree runner; private readonly List<CalcOperator> operators = new List<CalcOperator> { new CalcOperator() { symbol = '+', code = "ADD", Operate = (curr, newval) => curr + newval }, new CalcOperator() { symbol = '-', code = "SUB", Operate = (curr, newval) => curr - newval }, new CalcOperator() { symbol = '*', code = "MUL", Operate = (curr, newval) => curr * newval, precedence = true }, new CalcOperator() { symbol = '/', code = "DIV", Operate = (curr, newval) => curr / newval, precedence = true }, new CalcOperator() { symbol = '^', code = "POW", Operate = (curr, newval) => (float)Math.Pow(curr, newval) }, new CalcOperator() { symbol = '%', code = "MOD", Operate = (curr, newval) => curr % newval }, }; private readonly List<CalcFunction> functions = new List<CalcFunction> { new CalcFunction() { name = "sin", code = "SIN", Operate = (curr) => (float)Math.Sin(curr) }, new CalcFunction() { name = "cos", code = "COS", Operate = (curr) => (float)Math.Cos(curr) }, new CalcFunction() { name = "tan", code = "TAN", Operate = (curr) => (float)Math.Tan(curr) }, new CalcFunction() { name = "asin", code = "ASN", Operate = (curr) => (float)Math.Asin(curr) }, new CalcFunction() { name = "acos", code = "ACS", Operate = (curr) => (float)Math.Acos(curr) }, new CalcFunction() { name = "atan", code = "ATN", Operate = (curr) => (float)Math.Atan(curr) }, new CalcFunction() { name = "csc", code = "CSC", Operate = (curr) => 1 / (float)Math.Sin(curr) }, new CalcFunction() { name = "sec", code = "SEC", Operate = (curr) => 1 / (float)Math.Cos(curr) }, new CalcFunction() { name = "cot", code = "COT", Operate = (curr) => 1 / (float)Math.Tan(curr) }, new CalcFunction() { name = "sqrt", code = "SQT", Operate = (curr) => (float)Math.Sqrt(curr) }, new CalcFunction() { name = "abs", code = "ABS", Operate = (curr) => Math.Abs(curr) }, new CalcFunction() { name = "log", code = "LOG", Operate = (curr) => (float)Math.Log10(curr) }, new CalcFunction() { name = "ln", code = "NLG", Operate = (curr) => (float)Math.Log(curr) }, new CalcFunction() { name = "min", code = "MIN", ListOperate = (list) => { float lowest = list[0]; foreach(float item in list) { if (item < lowest) { lowest = item; } } return lowest; } }, new CalcFunction() { name = "max", code = "MAX", ListOperate = (list) => { float highest = list[0]; foreach(float item in list) { if (item > highest) { highest = item; } } return highest; } }, new CalcFunction() { name = "gcd", code = "GCD", maxListArgs = 2, ListOperate = (list) => Gcd(list) }, new CalcFunction() { name = "lcm", code = "LCM", maxListArgs = 2, ListOperate = (list) => { float a = list[0]; float b = list[1]; return a * b / Gcd(new List<float> { a, b }); } }, }; private static float Gcd(List<float> list) { float a = list[0]; float b = list[1]; if (b == 0) { return a; } else { return Gcd(new List<float> { b, a % b }); } } public SimpleCalculator() { parser = new Parser(); runner = new SyntaxTree(); parser.SetOperators(operators); parser.SetFunctions(functions); runner.SetOperators(operators); runner.SetFunctions(functions); runner.SetVariable("pi", (float)Math.PI); runner.SetVariable("e", (float)Math.E); } public void Clear() { parser.Clear(); runner.Clear(); } public void SetString(string input) { parser.SetInputString(input); } public float Calculate() { try { parser.Parse(); } catch (Exception e) { Console.WriteLine("Error Parsing Input!: " + e.ToString()); } runner.SetCommandList(parser.GetCommandStack()); try { runner.Build(); } catch (Exception e) { Console.WriteLine("Error Compiling Input!: " + e.ToString()); } try { return runner.Run(); } catch (Exception e) { Console.WriteLine("Error Running!: " + e.ToString()); } return -1; } } }
3644d2094f29b5a1028d9018d6306f95214c5fbc
C#
askrinnik/MyHomeLib.NET
/SourceCode/LibRusEc.FileStorage/FileStorageRepository.cs
2.765625
3
using System; using System.IO; using System.IO.Compression; namespace LibRusEc.FileStorage { public class FileStorageRepository { private readonly string storageFolder; public FileStorageRepository(string storageFolder) { this.storageFolder = storageFolder; } public Stream GetFile(string archiveName, string fileName) { using var za = ZipFile.OpenRead(Path.Combine(storageFolder, archiveName)); foreach (var entry in za.Entries) { if (entry.Name != fileName) continue; using var stream = entry.Open(); var ms = new MemoryStream(); stream.CopyTo(ms); ms.Position = 0; // rewind return ms; } return null; } } }
69adca8fdb20a0399edc88a533c58d86733763f6
C#
Parasuatene/UnityGithubAPI
/Assets/Scripts/QueryParamManager.cs
2.65625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class QueryParamManager : MonoBehaviour { private int pageNumber; private string repoParam; private string sortParam; private string orderParam; // 与えられたパラメータからクエリを作成して返却 public string CreateQueryParam(string repoName, int pageNumber = 1, string sort = "", string order = "") { this.pageNumber = pageNumber; string pageParam = "page=" + pageNumber; this.repoParam = "&q=" + repoName; // sortとorderは指定がある場合, 先頭に&を付与する this.sortParam = (sort == "" ? "" : "&" + sort); this.orderParam = (order == "" ? "" : "&" + order); return pageParam + repoParam + sortParam + orderParam; } public void ReCreateQueryParam(int pageNumber){ print("paging開始"); this.pageNumber = pageNumber; string pageParam = "page=" + pageNumber; string reQueryParam = pageParam + repoParam + sortParam + orderParam; StartCoroutine(GameObject.Find("SearchRepository").GetComponent<SearchRepository>().StartConnection(reQueryParam)); } public int GetPageNumber() { return this.pageNumber; } }
7d207573aee4a9885e3806cfbe5cb3f6ecc0fd43
C#
PlasticwaterLabs/GemsOfEgypt
/Assets/GemsOfEgypt/Scripts/InfoProvider.cs
2.640625
3
using UnityEngine; using System.Collections; using UnityEngine.UI; public class InfoProvider : MonoBehaviour { const string leftVentricle="Ventricle is one of two large chambers that collect and expel blood received from an atrium towards the peripheral beds within the body and lungs.Ventricles have thicker walls than atria and generate higher blood pressures. The left ventricle has thicker walls than the right because it needs to pump blood to most of the body while the right ventricle fills only the lungs.(Systemic Circulation)"; const string rightVentricle="Ventricle is one of two large chambers that collect and expel blood received from an atrium towards the peripheral beds within the body and lungs.Ventricles have thicker walls than atria and generate higher blood pressures.The right ventricle has thinner walls compared to left since it has to pump blood only to the lungs.(Pulmonary Circulation)"; const string rightAtrium = "The atrium (plural: atria) is one of the two blood collection chambers of the heart.The atrium is a chamber in which blood enters the heart, as opposed to the ventricle, where it is pushed out of the organ. The right atrium receives and holds deoxygenated blood from the superior vena cava, inferior vena cava."; const string leftAtrium="The atrium is one of the two blood collection chambers of the heart.The atrium is a chamber in which blood enters the heart, as opposed to the ventricle, where it is pushed out of the organ.The left atrium receives the oxygenated blood from the left and right pulmonary veins."; const string aorta="The aorta is the main artery in the human body, originating from the left ventricle of the heart and extending down to the abdomen, where it splits into two smaller arteries (the common iliac arteries). The aorta distributes oxygenated blood to all parts of the body through the systemic circulation."; const string pulmonaryArtery="The pulmonary artery carries deoxygenated blood from the heart to the lungs. It is one of the only arteries (other than the umbilical arteries in the fetus) that carries deoxygenated blood."; const string pulmonaryVien="The pulmonary veins are large blood vessels that receive oxygenated blood from the lungs and drain into the left atrium of the heart. There are four pulmonary veins, two from each lung. The pulmonary veins are among the few veins that carry oxygenated blood."; const string superiorVenacava="The superior vena cava (SVC) is the superior of the two venae cavae, the great venous trunks that return deoxygenated blood from the systemic circulation to the right atrium of the heart. It is a large-diameter (24 mm), yet short, vein that receives venous return from the upper half of the body, above the diaphragm."; const string inferiorVenacava="The inferior vena cava (or IVC) (Latin: vena, vein, cavus, hollow), is the inferior of the two venae cavae, the large veins that carry deoxygenated blood from the body into the right atrium of the heart. The inferior vena cava carries blood from the lower half of the body whilst the superior vena cava carries blood from the upper half of the body."; [SerializeField] static Text partName; [SerializeField] static Text desc; static GameObject partNameObj; static GameObject descObj; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public static string returnDesc(string partName) { switch (partName) { case "LeftVentricle": return leftVentricle; case "RightVentricle": return rightVentricle; case "RightAtrium": return rightAtrium; case "LeftAtrium": return leftAtrium; case "PulmonaryArtery": return pulmonaryArtery; case "PulmonaryVein0": return pulmonaryVien; case "PulmonaryVein1": return pulmonaryVien; case "PulmonaryVein2": return pulmonaryVien; case "PulmonaryVein3": return pulmonaryVien; case "SupiriorVenacava": return superiorVenacava; case "InferiorVenacava": return inferiorVenacava; case "Aorta": return aorta; default: return "This text should not be shown"; } } public static int getHeartPartIndex(string partName) { switch (partName) { case "LeftVentricle": return 0; case "RightVentricle": return 1; case "RightAtrium": return 2; case "LeftAtrium": return 3; case "PulmonaryArtery": return 4; case "PulmonaryVein0": return 5; case "PulmonaryVein1": return 6; case "PulmonaryVein2": return 7; case "PulmonaryVein3": return 8; case "SupiriorVenacava": return 9; case "InferiorVenacava": return 10; case "Aorta": return 11; default: Debug.LogError ( partName+"Untagged part is bieng pointed at"); return -1; } } // public static void setSomething(string nameStr) // { // // // { // partName = GameObject.FindGameObjectWithTag ("partName").GetComponent<Text> (); // desc = GameObject.FindGameObjectWithTag ("desc").GetComponent<Text> (); // if (partName!=null && desc!=null) { // // // desc.text = returnDesc (nameStr); // partName.text = nameStr; // } // } // // } // public static void clearAll() // { // // // { // partName = GameObject.FindGameObjectWithTag ("partName").GetComponent<Text> (); // desc = GameObject.FindGameObjectWithTag ("desc").GetComponent<Text> (); // if (partName!=null && desc!=null) { // // // desc.text = ""; // partName.text = ""; // } // } // // } public static void setSomething(string nameStr) { } public static void clearAll() { { partNameObj = GameObject.FindGameObjectWithTag ("partName"); descObj = GameObject.FindGameObjectWithTag ("desc"); if (partNameObj!=null && descObj!=null) { descObj.GetComponent<Text> ().text = ""; partNameObj.GetComponent<Text> ().text = ""; } } } }
031deefcc9dc332b782960601187900f5562d6a3
C#
mediabuff/WebSocketDemo
/WebSocketDemo/Services/QueueProcessor.cs
2.703125
3
using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace WebSocketDemo.Services { public abstract class QueueProcessor<T> : IHostedService { readonly TimeSpan _pollDelay = TimeSpan.FromMilliseconds(100); Task _backgroundTask; readonly ILogger _log; readonly CancellationTokenSource _shutdown = new CancellationTokenSource(); readonly IProducerConsumerCollection<T> _workQueue; public QueueProcessor(IProducerConsumerCollection<T> workQueue, ILogger logger) { _log = logger; _workQueue = workQueue; } public Task StartAsync(CancellationToken cancellationToken) { _backgroundTask = Task.Run(ProcessQueue, cancellationToken); return Task.CompletedTask; } async Task ProcessQueue() { while (!_shutdown.IsCancellationRequested) { if (!_workQueue.TryTake(out var request)) { await Task.Delay(_pollDelay, _shutdown.Token); continue; } try { await HandleRequest(request, _shutdown.Token); } catch (OperationCanceledException) { } catch (Exception ex) { _log.LogError(ex, $"Error handling: {request}"); } } } protected abstract Task HandleRequest(T request, CancellationToken cancelToken); public Task StopAsync(CancellationToken cancellationToken) { _shutdown.Cancel(); return Task.WhenAny(_backgroundTask, Task.Delay(Timeout.Infinite, cancellationToken)); } } }
9408e662c47d8313b36be90d0568c48d774aeb4c
C#
YlliElshani/Student-Management-System
/Application/Detyrat/Details.cs
2.59375
3
using System; using System.Threading; using System.Threading.Tasks; using Domain; using MediatR; using Persistence; namespace Application.Detyrat { public class Details { public class Query : IRequest <Detyra> { public Guid DetyraId {get; set;} } public class Handler : IRequestHandler<Query, Detyra> { private readonly DataContext _context; public Handler(DataContext context) { _context = context; } public async Task<Detyra> Handle(Query request, CancellationToken cancellationToken) { var detyra = await _context.Detyrat.FindAsync(request.DetyraId); return detyra; } } } }
2695928b37bdb5d95664dc3ba7d63628eaf0a4bc
C#
AbrahamPena/BeSpokedBikes
/BeSpokedBikes/Entities/Salesperson.cs
2.90625
3
using System; using System.Collections.Generic; namespace BeSpokedBikes.Entities { public class Salesperson { private int _id { get; set; } private string _firstName { get; set; } private string _lastName { get; set; } private string _address { get; set; } private string _phone { get; set; } private DateTime _startDate { get; set; } private DateTime _terminationDate { get; set; } private string _manager { get; set; } public int ID { get { return _id; } set { _id = value; } } public string FirstName { get { return _firstName; } set { _firstName = value; } } public string LastName { get { return _lastName; } set { _lastName = value; } } public string Address { get { return _address; } set { _address = value; } } public string Phone { get { return _phone; } set { _phone = value; } } public DateTime StartDate { get { return _startDate; } set { _startDate = value; } } public DateTime TerminationDate { get { return _terminationDate; } set { _terminationDate = value; } } public string Manager { get { return _manager; } set { _manager = value; } } public static List<Salesperson> GetSalespeople() { List<Salesperson> list = new List<Salesperson>(); System.Data.DataSet ds = Utilities.DataAccess.GetDataSet("SELECT * from salesperson"); Salesperson sp = null; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { sp = new Salesperson(); sp.ID = (int)ds.Tables[0].Rows[i]["id"]; sp.FirstName = ds.Tables[0].Rows[i]["first_name"].ToString(); sp.LastName = ds.Tables[0].Rows[i]["last_name"].ToString(); sp.Address = ds.Tables[0].Rows[i]["address"].ToString(); sp.Phone = ds.Tables[0].Rows[i]["phone"].ToString(); sp.StartDate = (DateTime)ds.Tables[0].Rows[i]["start_date"]; sp.TerminationDate = ds.Tables[0].Rows[i]["termination_date"] != DBNull.Value ? Convert.ToDateTime(ds.Tables[0].Rows[i]["termination_date"]) : DateTime.MinValue; sp.Manager = ds.Tables[0].Rows[i]["manager"].ToString(); list.Add(sp); } return list; } public static Salesperson GetSalesperson(int id) { string query = string.Format("SELECT * FROM salesperson WHERE id = {0}", id); System.Data.DataSet ds = Utilities.DataAccess.GetDataSet(query); Salesperson sp = new Salesperson(); sp.ID = (int)ds.Tables[0].Rows[0]["id"]; sp.FirstName = ds.Tables[0].Rows[0]["first_name"].ToString(); sp.LastName = ds.Tables[0].Rows[0]["last_name"].ToString(); sp.Address = ds.Tables[0].Rows[0]["address"].ToString(); sp.Phone = ds.Tables[0].Rows[0]["phone"].ToString(); sp.StartDate = (DateTime)ds.Tables[0].Rows[0]["start_date"]; sp.TerminationDate = (DateTime)ds.Tables[0].Rows[0]["termination_date"]; sp.Manager = ds.Tables[0].Rows[0]["manager"].ToString(); return sp; } public void InsertSalesperson(Salesperson sp) { string query = string.Format("INSERT INTO salesperson VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')", sp.FirstName, sp.LastName, sp.Address, sp.Phone, sp.StartDate, sp.TerminationDate, sp.Manager); Utilities.DataAccess.ExecuteNonQuery(query); } public void UpdateSalesperson(Salesperson sp) { string query = string.Format("UPDATE salesperson SET first_name = '{0}', last_name = '{1}', address = '{2}', phone = '{3}', start_date = '{4}', termination_date = '{5}', manager = '{6}' WHERE id = {7}", sp.FirstName, sp.LastName, sp.Address, sp.Phone, sp.StartDate, sp.TerminationDate, sp.Manager, sp.ID); Utilities.DataAccess.ExecuteNonQuery(query); } } }
dd72862485e5a857074418e3705229125f3d64ae
C#
hazharaziz/AP
/A7/A7/Dabir.cs
3.4375
3
using System; namespace A7 { /// <summary> /// Dabir class containing dabir properties /// </summary> public class Dabir : ICitizen, ITeacher { public string Name { get; set; } public string NationalId { get; set; } public Degree TopDegree { get; set; } public string ImgUrl { get; set; } public int Under100StudentCount { get; set; } /// <summary> /// Dabir Class constructor /// </summary> /// <param name="nationalId"></param> /// <param name="name"></param> /// <param name="imgUrl"></param> /// <param name="topDegree"></param> /// <param name="under100StudentCount"></param> public Dabir(string nationalId, string name, string imgUrl,Degree topDegree, int under100StudentCount) { Name = name; NationalId = nationalId; TopDegree = topDegree; ImgUrl = imgUrl; Under100StudentCount = under100StudentCount; } /// <summary> /// Teach Method for describing dabir /// </summary> /// <returns></returns> public string Teach() => $"Dabir {Name} is teaching"; } }
cd6578ebb478c271841f8aa21db679fd44d525da
C#
duck-rabbit/bwoah-chat
/bwoah-shared/bwoah-shared/DataClasses/AData.cs
2.734375
3
using Newtonsoft.Json; using System; namespace bwoah_shared.DataClasses { public abstract class AData { public string ParseToJson() { String json = JsonConvert.SerializeObject(this); Console.WriteLine(json); return json; } public AData ParseFromJson(string json) { return (AData)(JsonConvert.DeserializeObject(json, this.GetType())); } } }
9c817e0be332038d307864754b4f8ac17270350f
C#
jamesryan83/Csharp-Library
/Common/CommonJson/JsonUtil.cs
3.265625
3
using Newtonsoft.Json; using System.IO; using System; namespace CommonJson { public class JsonUtil { // Convert Object to Json String public static string ConvertObjectToJsonString(object data) { return JsonConvert.SerializeObject(data, Formatting.Indented); } // Convert Json string to object public static T ConvertJsonStringToObject<T>(string json) { return JsonConvert.DeserializeObject<T>(json); } // Save data to json public static void SaveDataToJsonFile(object data, string filePath) { if (filePath == null || filePath.Length == 0) return; using (StreamWriter writer = new StreamWriter(filePath)) { string json = JsonConvert.SerializeObject(data, Formatting.Indented); writer.Write(json); } } // TODO : crash here when data isn't right // Load data from json public static T LoadDataFromJsonFile<T>(string filePath) where T : class { if (filePath == null || filePath.Length == 0 || File.Exists(filePath) == false) return null; using (StreamReader reader = new StreamReader(filePath)) { string json = reader.ReadToEnd(); return JsonConvert.DeserializeObject<T>(json); } } } }
5ae2ed65966fb1735489580a9fa73690b40fde46
C#
jiwonan/myrandomrealnumber
/myrandomrealnumber/Program.cs
3.734375
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace myrandomrealnumber { class Program { static void Main(string[] args) { Random rand = new Random(); double num; num = rand.NextDouble(); int pc_answer = (int)(Math.Round(num, 3) * 100); int answer = -1; Console.WriteLine(pc_answer); while (answer != pc_answer) { Console.Write("숫자를 입력해주세요: "); answer = int.Parse(Console.ReadLine()); if (pc_answer > answer) Console.WriteLine(answer + "보다는 큰 숫자입니다.\n"); else if (pc_answer < answer) Console.WriteLine(answer + "보다는 작은 숫자입니다.\n"); } Console.WriteLine("정답입니다!"); } } }
0aa4cb95e50e8e336b8cbe71fc4e01530672fe97
C#
jeffryang24/NUT-number-to-text
/src/Nut/TextConverters/IndonesianConverter.cs
2.640625
3
using System; using Nut.Models; namespace Nut.TextConverters { public sealed class IndonesianConverter : BaseConverter { private static readonly Lazy<IndonesianConverter> Lazy = new Lazy<IndonesianConverter>(() => new IndonesianConverter()); public static IndonesianConverter Instance => Lazy.Value; public override string CultureName => Culture.Indonesian; public IndonesianConverter() { Initialize(); } private void Initialize() { NumberTexts.Add(0, new[] { "nol" }); NumberTexts.Add(1, new[] { "satu" }); NumberTexts.Add(2, new[] { "dua" }); NumberTexts.Add(3, new[] { "tiga" }); NumberTexts.Add(4, new[] { "empat" }); NumberTexts.Add(5, new[] { "lima" }); NumberTexts.Add(6, new[] { "enam" }); NumberTexts.Add(7, new[] { "tujuh" }); NumberTexts.Add(8, new[] { "delapan" }); NumberTexts.Add(9, new[] { "sembilan" }); NumberTexts.Add(10, new[] { "sepuluh" }); NumberTexts.Add(11, new[] { "sebelas" }); NumberTexts.Add(12, new[] { "dua belas" }); NumberTexts.Add(13, new[] { "tiga belas" }); NumberTexts.Add(14, new[] { "empat belas" }); NumberTexts.Add(15, new[] { "lima belas" }); NumberTexts.Add(16, new[] { "enam belas" }); NumberTexts.Add(17, new[] { "tujuh belas" }); NumberTexts.Add(18, new[] { "delapan belas" }); NumberTexts.Add(19, new[] { "sembilan belas" }); NumberTexts.Add(20, new[] { "dua puluh" }); NumberTexts.Add(30, new[] { "tiga puluh" }); NumberTexts.Add(40, new[] { "empat puluh" }); NumberTexts.Add(50, new[] { "lima puluh" }); NumberTexts.Add(60, new[] { "enam puluh" }); NumberTexts.Add(70, new[] { "tujuh puluh" }); NumberTexts.Add(80, new[] { "delapan puluh" }); NumberTexts.Add(90, new[] { "sembilan puluh" }); NumberTexts.Add(100, new[] { "seratus" }); ScaleTexts.Add(1000000000, new[] { "miliar" }); ScaleTexts.Add(1000000, new[] { "juta" }); ScaleTexts.Add(1000, new[] { "ribu" }); } protected override CurrencyModel GetCurrencyModel(string currency) { switch (currency) { case Currency.EUR: return new CurrencyModel { Currency = currency, Names = new[] { "euro", "euros" }, SubUnitCurrency = new BaseCurrencyModel { Names = new[] { "eurocent", "eurocents" } } }; case Currency.USD: return new CurrencyModel { Currency = currency, Names = new[] { "dollar", "dollars" }, SubUnitCurrency = new BaseCurrencyModel { Names = new[] { "cent", "cents" } } }; case Currency.RUB: return new CurrencyModel { Currency = currency, Names = new[] { "ruble", "rubles" }, SubUnitCurrency = new BaseCurrencyModel { Names = new[] { "kopek", "kopeks" } } }; case Currency.TRY: return new CurrencyModel { Currency = currency, Names = new[] { "turkish lira", "turkish lira" }, SubUnitCurrency = new BaseCurrencyModel { Names = new[] { "kurus", "kurus" } } }; case Currency.UAH: return new CurrencyModel { Currency = currency, Names = new[] { "ukrainian hryvnia", "ukrainian hryvnia" }, SubUnitCurrency = new BaseCurrencyModel { Names = new[] { "kopiyka", "kopiyky", "kopiyok" } } }; case Currency.IDR: return new CurrencyModel { Currency = currency, Names = new[] { "rupiah", "rupiah" }, SubUnitCurrency = new BaseCurrencyModel { Names = new[] { "" }} // No cent (SubUnitCurrency) in Rupiah }; } return null; } } }
eb35fabfa9027a66a421692c2c311eb13a8456de
C#
shendongnian/download4
/first_version_download2/180361-13611794-32460744-2.cs
2.59375
3
class FilePath { public FilePath(string inPath) { Path = inPath; } public string Path { get; set; } }
bcbdebf58c01a5a4177022fbe311ccb4dc7ae20b
C#
Jordan-Ben/ExplorableAreas
/ExplorableAreas/MainWindow.xaml.cs
2.78125
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.Navigation; using System.Windows.Shapes; namespace ExplorableAreas { /// <summary> /// Interaction logic for MainWindow.xaml /// Jordan Benson's GUI Explorable Areas /// Janell Baxter's code assistance used /// </summary> public partial class MainWindow : Window { List<Location> locations = new List<Location>(); Location currentLocation = new Location(); public MainWindow() { InitializeComponent(); Start(); } private void Start() { SetUpLocation(); ShowLocationsMenu(); Travel(); } //set up locations private void SetUpLocation() { locations.Add(new Location("Flying Forest", "A forest with Opium in the air", "Images/Forest.bmp")); locations.Add(new Location("loc b", "des b", "Images/flower.png")); locations.Add(new Location("loc c", "des c")); locations.Add(new Location("loc d", "des d")); currentLocation = locations[0]; } private void ShowLocationsMenu() { string temp = ""; foreach(Location location in locations) { temp+= location.Name + "\n"; } LocationMenuTextBlock.Text = temp; } private void Travel() { LocationNameTextBlock.Text = currentLocation.Name; LocationDescriptionTextBlock.Text = currentLocation.Description; LocationImageBox.Source = currentLocation.ShowLocationImage(); } private void TravelButton_Click(object sender, RoutedEventArgs e) { string location = TravelLocationTextBox.Text; location = location.ToLower(); if(location != "") { foreach (Location l in locations) { if(l.Name.ToLower().Contains(location)) { currentLocation = l; Travel(); } } } } } }
df2c851dccf9fdc850a9189679524bb87c3c9678
C#
maestroAlfredo/HBAlgorithmMain
/WindowsFormsApplication3/nodeFeederForm (AlfredHome-PC's conflicted copy 2015-04-19).cs
2.53125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace VoltageDropCalculatorApplication { public partial class nodeFeederForm : Form { public static int newProjectClicked = 1; //tracks if the user has clicked the create new project button public string projectName; double p; Graphics drawArea; int x; int y; int k; ErrorProvider errorProvider1 = new ErrorProvider(); public static double lengthTol = 0.1; int[] loadCountInt; //int that tracks the number of loads added to each node int[] genCountInt; //int that tracks the number of generators added to each node int maxLoadsDgsInt = 5; int nodeCountInt = 1; int maxNodes = 100; int loadCount; int genCount; DataSet nodeDataSet = new DataSet(); DataSet tempNodeDataSet = new DataSet(); //Dataset that stores the tables that are only in the main feeder List<int> mfNodeList = new List<int>(); //intlist that stores the nodes in the main feeder Dictionary<int, string> mfNodeDictionary = new Dictionary<int, string>(); //Dictionarylist that stores the node number and name DataTable tempTable = new DataTable();//temporary table that stores the node data to put in the main feederdataset DataSet libraryDataSet = new DataSet(); BindingList<int> nodeNumList = new BindingList<int>(); BindingList<string> nodeNameList = new BindingList<string>(); List<string> loadString; List<string> genString; TreeNode rootNode = new TreeNode(); List<string> addList; public nodeFeederForm() { InitializeComponent(); libraryDataSet.ReadXml("Libraries.xml"); //read the library xml drawArea = drawingPanel.CreateGraphics(); p = 10; List<string> cableString = libraryDataSet.Tables["Conductor Table"].AsEnumerable().Select(x => x[0].ToString()).ToList(); cableSelectCombo.DataSource = cableString; mfNodeList.Add(1); //adds the first node to the main feeder node list mfNodeDictionary.Add(1, "node1"); loadCount = 0; genCount = 0; //DataSet libraryLoadDataSet = new DataSet(); //DataSet libraryGenDataSet = new DataSet(); //libraryLoadDataSet.ReadXml("Loads.xml"); //libraryGenDataSet.ReadXml("Generators.xml"); //loadString = libraryLoadDataSet.Tables[0].AsEnumerable().Select(x => x[0].ToString()).ToList(); //genString = libraryGenDataSet.Tables[0].AsEnumerable().Select(x => x[0].ToString()).ToList(); //loadString.AddRange(genString); //joins the list of generators to the list of loads //loadGenCombo.DataSource = loadString; //for (int i = 0; i < libraryLoadDataSet.Tables[0].Rows.Count; i++) //{ // if (Convert.ToString(libraryLoadDataSet.Tables[0].Rows[i][0]) == loadGenCombo.Text) // { // alphaLabel.Text = Convert.ToString(libraryLoadDataSet.Tables[0].Rows[i][1]); // betaLabel.Text = Convert.ToString(libraryLoadDataSet.Tables[0].Rows[i][2]); // cbLabel.Text = Convert.ToString(libraryLoadDataSet.Tables[0].Rows[i][3]); // } //} //for (int i = 0; i < libraryGenDataSet.Tables[0].Rows.Count; i++) //{ // if (Convert.ToString(libraryGenDataSet.Tables[0].Rows[i][0]) == loadGenCombo.Text) // { // alphaLabel.Text = Convert.ToString(libraryGenDataSet.Tables[0].Rows[i][1]); // betaLabel.Text = Convert.ToString(libraryGenDataSet.Tables[0].Rows[i][2]); // cbLabel.Text = Convert.ToString(libraryGenDataSet.Tables[0].Rows[i][3]); // } //} //hides the length, cable, Rp and Rn columns //initialise the temporary datatable which stores the node data; //List<string> headings = new List<string> { "Node", "Name", "Load/DG", "Red", "White", "Blue", "Alpha", "Beta", "Cb", "Length", "Cable", "Rp", "Rn", "Parent", "Children" }; //for (int i = 0; i < headings.Count; i++) //{ // tempTable.Columns.Add(headings[i]); //adds the headings to the nodeDataTable //} //for (int j = 0; j < 5; j++) //{ // tempTable.Rows.Add("0", "Load " + (j + 1).ToString(), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "0", 0.0, 0.0, 0, 0); //} //for (int j = 0; j < 5; j++) //{ // tempTable.Rows.Add("0", "Gen " + (j + 1).ToString(), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "0", 0.0, 0.0, 0, 0); //} } private void projectNameTextBox_TextChanged(object sender, EventArgs e) { if (projectNameTextBox.Text == "") createNewProjectButton.Enabled = false; else createNewProjectButton.Enabled = true; } private void createNewProjectButton_Click(object sender, EventArgs e) { newProjectClicked = 0; projectName = projectNameTextBox.Text + ".xml"; //creates a string in projectName that will contain the reference to the xml file createNewProjectButton.Enabled = false; projectNameTextBox.Enabled = false; continueButton.Enabled = true; } private void cancelButton_Click(object sender, EventArgs e) { this.Close(); } private void continueButton_Click(object sender, EventArgs e) { SolidBrush sb = new SolidBrush(Color.SteelBlue); nodeNameTextBox.Text = "node 1"; drawArea.FillEllipse(sb, 20, drawingPanel.Height / 2, 10, 10); //totalNodeNumberNumericUpDown.Enabled = false; continueButton.Enabled = false; nodeNumList.Add(1); nodeNameList.Add(nodeNameTextBox.Text); activeRadio.Enabled = false; passiveRadio.Enabled = false; nodeNumCombo.Enabled = true; nodeNumCombo.DataSource = nodeNumList; nodeNameCombo.DataSource = nodeNameList; selectEndNodeCombo.Enabled = true; selectEndNodeCombo.DataSource = nodeNumList; endNodeCombo.Enabled = true; endNodeCombo.DataSource = nodeNameList; addNodeButton.Enabled = true; if (activeRadio.Checked == true) p = 90; DataTable nodeDataTable = new DataTable(); List<string> headings = new List<string> { "Node", "Name", "Load/DG", "Red", "White", "Blue", "Alpha", "Beta", "Cb", "Length", "Cable", "Rp", "Rn", "Parent", "Children" }; for (int i = 0; i < headings.Count; i++) { nodeDataTable.Columns.Add(headings[i]); //adds the headings to the nodeDataTable } //querires the datatables for the loads and gens where the user has selected DataTable resultLoads = new DataTable(); var table = libraryDataSet.Tables["Load Types"].Select("Selected = true"); if (table.AsEnumerable().Any()) { resultLoads = table.CopyToDataTable(); loadCount = resultLoads.Rows.Count; } DataTable resultGens = new DataTable(); var table1 = libraryDataSet.Tables["Gen Types"].Select("Selected = true"); if (table1.AsEnumerable().Any()) { resultGens = table1.CopyToDataTable(); genCount = resultGens.Rows.Count; } //if (resultLoads.AsEnumerable().Any()) loadCount = resultLoads.Rows.Count; //DataTable resultGens = libraryDataSet.Tables["Gen Types"].Select("Selected = true").CopyToDataTable(); //if (resultGens.AsEnumerable().Any()) genCount = resultGens.Rows.Count; //adds the selected Gens to the selected loads table foreach (DataRow dr in resultGens.Rows) { if (table.AsEnumerable().Any()) resultLoads.Rows.Add(dr.ItemArray); else { resultLoads = resultGens.Copy(); break; } } for (int i = 0; i < resultLoads.Rows.Count; i++) { nodeDataTable.Rows.Add("1", nodeNameTextBox.Text, resultLoads.Rows[i][0], 0.0, 0.0, 0.0, resultLoads.Rows[i]["alpha"], resultLoads.Rows[i]["beta"], resultLoads.Rows[i]["circuit breaker"], calculateLengths(lengthNumericUpDown.Value, i), cableSelectCombo.Text, calculateRp(rpLabel.Text, lengthNumericUpDown.Value, calculateLengths(lengthNumericUpDown.Value, i), i), calculateRn(rnLabel.Text, lengthNumericUpDown.Value, calculateLengths(lengthNumericUpDown.Value, i), i), 0, 0); } nodeDataTable.TableName = "node1"; tempTable = nodeDataTable.Copy(); tempTable.Rows[0][0] = "0"; //makes the first entry zero . nodeDataSet.Tables.Add(nodeDataTable); loadCountInt = new int[maxNodes]; genCountInt = new int[maxNodes]; nodeDataSet.WriteXml(projectName); nodeDataGridView.DataSource = nodeDataSet.Tables[0]; //nodeDataGridView.Columns[8].Visible = false; //hides the last four columns of the datagridview //nodeDataGridView.Columns[9].Visible = false; //nodeDataGridView.Columns[10].Visible = false; //nodeDataGridView.Columns[11].Visible = false; closeTableEdits(); } private void nodeFeederForm_Load(object sender, EventArgs e) { this.DoubleBuffered = true; } //adds a load or generator to the respective node private void addLoadDgButton_Click(object sender, EventArgs e) { } //checks to see if the nodeNumComboBox Text has been changed and then updates the datagrid view to the selected table. private void nodeNumCombo_TextChanged(object sender, EventArgs e) { if (nodeDataSet.Tables.Contains("node" + nodeNumCombo.Text)) { nodeNameTextBox.Text = nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[0][1].ToString(); lengthNumericUpDown.Value = Convert.ToDecimal(Convert.ToDouble(nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[0][9]) + ((loadCount == 0) ? (genCount - 1.0) * lengthTol : (loadCount - 1.0) * lengthTol)); cableSelectCombo.Text = nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[0][10].ToString(); } ////DataSet nodeDataSet = new DataSet(); //DataSet libraryLoadDataSet = new DataSet(); //DataSet libraryGenDataSet = new DataSet(); ////nodeDataSet.ReadXml(projectName); //libraryLoadDataSet.ReadXml("Loads.xml"); //libraryGenDataSet.ReadXml("Generators.xml"); //loadString = libraryLoadDataSet.Tables[0].AsEnumerable().Select(x => x[0].ToString()).ToList(); //genString = libraryGenDataSet.Tables[0].AsEnumerable().Select(x => x[0].ToString()).ToList(); if (nodeNumCombo.Text == "1") { deleteNodeButton.Enabled = false; }//disable a user from deleting node 1. else deleteNodeButton.Enabled = true; //loadString.AddRange(genString); //joins the list of generators to the list of loads //loadGenCombo.DataSource = loadString; //redNumericUp.Value = 0; //blueNumericUp.Value = 0; //whiteNumericUp.Value = 0; for (int i = 0; i < nodeCountInt; i++) { if (((Convert.ToInt16(nodeNumCombo.Text) - 1) == i) && (nodeDataSet.Tables.Count > 0)) { nodeDataGridView.DataSource = nodeDataSet.Tables[i]; } } //if (nodeDataSet.Tables.Contains("node" + nodeNumCombo.Text) && (nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[0][8] != null)) //{ // lengthNumericUpDown.Value = Convert.ToDecimal(nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[0][8]); //} } private void proceedToVCalcButton_Click(object sender, EventArgs e) { bool finished = true; foreach (DataTable dtable in nodeDataSet.Tables) { if (Convert.ToString(dtable.Rows[0][0]) == "0") { finished = false; break; } } if (finished) { tempNodeDataSet.Tables.Clear(); DataTable[] nodeVecDataTables = createNodeVecDatatable(mfNodeList); for (int i = 0; i < nodeVecDataTables.GetLength(0); i++ ) { tempNodeDataSet.Tables.Add(nodeVecDataTables[i]); } DataTable[] voltageVectorDataTable = new DataTable[3]; DataRow voltageRow; for (int k = 0; k < 3; k++) { voltageVectorDataTable[k] = new DataTable(); for (int i = 0; i < 35; i++) { //creates column headings numbered 1 to 35 voltageVectorDataTable[k].Columns.Add(Convert.ToString(i + 1), typeof(Double)); } for (int i = 0; i < (loadCount + genCount) * mfNodeList.Count; i++) { voltageRow = voltageVectorDataTable[k].NewRow(); for (int j = 0; j < 35; j++) { voltageRow[j] = 0.0; } voltageVectorDataTable[k].Rows.Add(voltageRow); } tempNodeDataSet.Tables.Add(voltageVectorDataTable[k]); } //double[] voltageRowDouble = new double[35]; tempNodeDataSet.WriteXml(projectName); voltageCalculationForm frm = new voltageCalculationForm(projectName, p, loadCount, genCount); frm.ShowDialog(); } else { MessageBox.Show("Cannot Proceed without specifying Loads or DGs for each individual node! Please check that all nodes have at least one Load or Generator"); } } private void cableSelectCombo_TextChanged(object sender, EventArgs e) { if (nodeDataSet.Tables.Contains("node" + nodeNumCombo.Text)) { for (int i = 0; i < nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows.Count; i++) { nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[i][10] = cableSelectCombo.Text; } } //goes through the conductor library first column to see if the combobox text matches the library conductor column text for (int i = 0; i < libraryDataSet.Tables["Conductor Table"].Rows.Count; i++) { if (Convert.ToString(libraryDataSet.Tables["Conductor Table"].Rows[i][0]) == cableSelectCombo.Text) { double rT2 = Convert.ToDouble(libraryDataSet.Tables["Conductor Table"].Rows[i][1]) * (Convert.ToDouble(libraryDataSet.Tables["Conductor Table"].Rows[i][2]) + 40.0) / (Convert.ToDouble(libraryDataSet.Tables["Conductor Table"].Rows[i][2]) + 20.0); rpLabel.Text = Convert.ToString(rT2 * (Convert.ToDouble(lengthNumericUpDown.Value) / 1000)); rnLabel.Text = Convert.ToString(rT2 * Convert.ToDouble(libraryDataSet.Tables["Conductor Table"].Rows[i][3]) * (Convert.ToDouble(lengthNumericUpDown.Value) / 1000)); } } } private void lengthNumericUpDown_ValueChanged(object sender, EventArgs e) { if (nodeDataSet.Tables.Contains("node" + nodeNumCombo.Text)) { for (int i = 0; i < nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows.Count; i++) { nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[i][9] = calculateLengths(lengthNumericUpDown.Value, i); } } DataSet libraryConductorDataSet = new DataSet(); libraryConductorDataSet.ReadXml("Conductors.xml"); //goes through the conductor library first column to see if the combobox text matches the library conductor column text for (int i = 0; i < libraryConductorDataSet.Tables[0].Rows.Count; i++) { if (Convert.ToString(libraryConductorDataSet.Tables[0].Rows[i][0]) == cableSelectCombo.Text) { double rT2 = Convert.ToDouble(libraryConductorDataSet.Tables[0].Rows[i][1]) * (Convert.ToDouble(libraryConductorDataSet.Tables[0].Rows[i][2]) + 40.0) / (Convert.ToDouble(libraryConductorDataSet.Tables[0].Rows[i][2]) + 20.0); rpLabel.Text = Convert.ToString(rT2 * (Convert.ToDouble(lengthNumericUpDown.Value) / 1000)); rnLabel.Text = Convert.ToString(rT2 * Convert.ToDouble(libraryConductorDataSet.Tables[0].Rows[i][3]) * (Convert.ToDouble(lengthNumericUpDown.Value) / 1000)); } } mfNodeList.Clear();//Clears the main feeder node list mfNodeDictionary.Clear(); drawArea.Clear(Color.White); getMainFeederNodes(Convert.ToInt32(selectEndNodeCombo.Text), mfNodeList); drawPoints(mfNodeList); } private void passiveCheck_CheckedChanged(object sender, EventArgs e) { } private void activeCheck_CheckedChanged(object sender, EventArgs e) { } private void totalNodeNumberNumericUpDown_ValueChanged(object sender, EventArgs e) { } private void addNodeButton_Click(object sender, EventArgs e) { nodeNameTextBox.Focus(); editTable(); //totalNodeNumberNumericUpDown.Value = totalNodeNumberNumericUpDown.Value + 1; nodeCountInt++; TreeNode thisNode = new TreeNode(); //rootNode.; //drawArea.FillEllipse(sb, Cordinate(nodeCountInt).X, Cordinate(nodeCountInt).Y, 10, 10); DataTable nodeDataTable = new DataTable(); List<string> headings = new List<string> { "Node", "Name", "Load/DG", "Red", "White", "Blue", "Alpha", "Beta", "Cb", "Length", "Cable", "Rp", "Rn", "Parent", "Children" }; for (int i = 0; i < headings.Count; i++) { nodeDataTable.Columns.Add(headings[i]); //adds the headings to the nodeDataTable } //querires the datatables for the loads and gens where the user has selected DataTable resultLoads = new DataTable(); var table = libraryDataSet.Tables["Load Types"].Select("Selected = true"); if (table.AsEnumerable().Any()) { resultLoads = table.CopyToDataTable(); loadCount = resultLoads.Rows.Count; } DataTable resultGens = new DataTable(); var table1 = libraryDataSet.Tables["Gen Types"].Select("Selected = true"); if (table1.AsEnumerable().Any()) { resultGens = table1.CopyToDataTable(); genCount = resultGens.Rows.Count; } //adds the selected Gens to the selected loads table foreach (DataRow dr in resultGens.Rows) { if (table.AsEnumerable().Any()) resultLoads.Rows.Add(dr.ItemArray); else { resultLoads = resultGens.Copy(); break; } } //adds the loads and gens to the datatable for (int i = 0; i < resultLoads.Rows.Count; i++) { nodeDataTable.Rows.Add(autoGeneratedNodeName("node " + nodeCountInt.ToString()).Remove(0, 5), autoGeneratedNodeName("node " + nodeCountInt.ToString()), resultLoads.Rows[i][0], 0.0, 0.0, 0.0, resultLoads.Rows[i]["alpha"], resultLoads.Rows[i]["beta"], resultLoads.Rows[i]["circuit breaker"], calculateLengths(lengthNumericUpDown.Value, i), cableSelectCombo.Text, calculateRp(rpLabel.Text, lengthNumericUpDown.Value, calculateLengths(lengthNumericUpDown.Value, i), i), calculateRn(rnLabel.Text, lengthNumericUpDown.Value, calculateLengths(lengthNumericUpDown.Value, i), i), nodeNumCombo.Text, 0); } //names the table in the datatable and adds it to the dataset nodeDataTable.TableName = "node" + Convert.ToString(nodeCountInt); nodeDataSet.Tables.Add(nodeDataTable); if (Convert.ToString(nodeDataSet.Tables[Convert.ToInt16(nodeNumCombo.Text) - 1].Rows[0][14]) != "0") { nodeDataSet.Tables[Convert.ToInt16(nodeNumCombo.Text) - 1].Rows[0][14] = Convert.ToString(nodeDataSet.Tables[Convert.ToInt16(nodeNumCombo.Text) - 1].Rows[0][14]) + ";" + Convert.ToString(nodeCountInt); } else { nodeDataSet.Tables[Convert.ToInt16(nodeNumCombo.Text) - 1].Rows[0][14] = Convert.ToString(nodeCountInt); } //TreeNode<int> thisNode = myNode.Children.Add(; //myNode = thisNode; nodeCount.Text = Convert.ToString(nodeCountInt); nodeNumList.Add(Convert.ToInt16(nodeCountInt)); nodeNameList.Add(autoGeneratedNodeName("node " + nodeCountInt.ToString())); nodeNumCombo.DataSource = nodeNumList; nodeNameCombo.DataSource = nodeNameList; selectEndNodeCombo.DataSource = nodeNumList; endNodeCombo.DataSource = nodeNameList; //nodeNumCombo.Update(); nodeNumCombo.SelectedIndex = nodeNumCombo.Items.Count - 1; nodeNameCombo.SelectedIndex = nodeNameCombo.Items.Count - 1; nodeDataGridView.DataSource = nodeDataSet.Tables[nodeCountInt - 1];//changes the datagrid view to display the new node. closeTableEdits(); } //This function separates the items in the delimited string (parameter 1) at the delimiter (parameter 2), //creates a new generic string list, and then adds each item to the new list. Finally, it returns the filled list. public static List<string> ConvertStringsToStringList(string items, char separator) { List<string> list = new List<string>(); string[] listItmes = items.Split(separator); foreach (string item in listItmes) { list.Add(item); } return list; } private void deleteNodeButton_Click(object sender, EventArgs e) { editTable(); //removes the node from the children of the parent node by setting the children field to zero or null string parentNode = Convert.ToString(nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[0][13]); if (Convert.ToString(nodeDataSet.Tables["node" + parentNode].Rows[0][14]).Length == 1) { nodeDataSet.Tables["node" + parentNode].Rows[0][14] = "0"; //sets the children of the parent node to zero if there was only one child } else { string replacement = null; string originalString = Convert.ToString(nodeDataSet.Tables["node" + parentNode].Rows[0][14]); originalString = originalString.Replace(originalString.Contains(nodeNumCombo.Text + ";") ? nodeNumCombo.Text + ";" : nodeNumCombo.Text, replacement); //updates the children to null if there is more than one child nodeDataSet.Tables["node" + parentNode].Rows[0][14] = originalString; } deleteNode("node" + nodeNumCombo.Text); nodeCountInt = nodeDataSet.Tables.Count; for (int i = 0; i < nodeDataSet.Tables.Count; i++) { string originalName = nodeDataSet.Tables[i].TableName; //originalName = originalName.Remove(0, 4); renameNode(originalName, "node" + (i + 1).ToString()); //renames the remaining nodes } for (int i = 0; i < nodeDataSet.Tables.Count; i++) nodeDataSet.Tables[i].TableName = "node" + (i + 1).ToString(); //renames the tables. for (int i = nodeNumList.Count - 1; i >= nodeDataSet.Tables.Count; i--) { nodeNumList.RemoveAt(i); } nodeCountInt = nodeDataSet.Tables.Count; nodeCount.Text = Convert.ToString(nodeCountInt); nodeNumCombo.DataSource = nodeNumList; nodeNameCombo.DataSource = nodeNameList; nodeNameCombo.Update(); nodeNumCombo.Update(); nodeNumCombo.SelectedIndex = nodeNumCombo.Items.Count - 1; nodeNameCombo.SelectedIndex = nodeNameCombo.Items.Count - 1; nodeNameTextBox.Text = nodeNameCombo.Text; nodeDataGridView.DataSource = nodeDataSet.Tables[nodeDataSet.Tables.Count - 1]; drawArea.Clear(Color.White); drawPoints(mfNodeList); closeTableEdits(); } //recursive method that deletes a node as well as its children and their children etc private void deleteNode(string nodeNumber) { if ((nodeNumber != "node0") && (nodeNumber != "node")) { string childNodes = Convert.ToString(nodeDataSet.Tables[nodeNumber].Rows[0][14]); List<string> nodesToRemoveList = new List<string>(); nodesToRemoveList = ConvertStringsToStringList(childNodes, ';'); //if (nodesToRemoveList.Contains("0")) nodesToRemoveList.Remove("0"); if (nodesToRemoveList.Contains(null)) nodesToRemoveList.Remove(null); for (int i = 0; i < nodesToRemoveList.Count; i++) { deleteNode("node" + Convert.ToString(nodesToRemoveList[i])); } nodeNameList.RemoveAt(nodeNameList.IndexOf(nodeDataSet.Tables[nodeNumber].Rows[0][1].ToString())); nodeDataSet.Tables.Remove(nodeNumber); } } private void renameNode(string oldNodeName, string newNodeName) { string childNodes = Convert.ToString(nodeDataSet.Tables[oldNodeName].Rows[0][14]); string newNodeNum = Convert.ToString(newNodeName).Remove(0, 4); string oldNodeNum = Convert.ToString(oldNodeName).Remove(0, 4); List<string> nodesToChangeParent = new List<string>(); DataTable dt = new DataTable(); int[] array = new int[2]; //array[0] = 5; //array[1] = 6; //updates the children of the node nodesToChangeParent = ConvertStringsToStringList(childNodes, ';'); if (oldNodeNum == "8") { Console.Write(Convert.ToString(nodesToChangeParent[0])); } for (int i = 0; i < nodesToChangeParent.Count; i++) { if ((Convert.ToString(nodesToChangeParent[i]) != "0") && (Convert.ToString(nodesToChangeParent[i]) != "")) { nodeDataSet.Tables["node" + Convert.ToString(nodesToChangeParent[i])].Rows[0][13] = newNodeNum; } } //updates the parents of the node string parentNode = Convert.ToString(nodeDataSet.Tables[oldNodeName].Rows[0][13]); if (parentNode != "0") { dt = (nodeDataSet.Tables["node" + parentNode] != null) ? nodeDataSet.Tables["node" + parentNode] : nodeDataSet.Tables[Convert.ToInt16(parentNode) - 1]; if (Convert.ToString(dt.Rows[0][14]).Length == 1) { dt.Rows[0][14] = newNodeNum; //sets the children of the parent node to newName if there was only one child } else { string replacement = newNodeNum; string originalString = Convert.ToString(dt.Rows[0][14]); //originalString = originalString.Replace(originalString.Contains(oldNodeNum + ";") ? oldNodeNum + ";" :";"+ oldNodeNum, replacement); //updates the children to newName originalString = originalString.Replace(oldNodeNum, replacement); dt.Rows[0][14] = originalString; } } } private void drawingPanel_Paint(object sender, PaintEventArgs e) { } //method gets the nodes in a main feeder list and then calculates the positions of those nodes. private void drawPoints(List<int> mainfeederList) { SolidBrush sb = new SolidBrush(Color.SteelBlue); Pen myPen = new Pen(sb); double drawingSpace = (double)drawingPanel.Width - 30; double nodespacing = drawingSpace / mainfeederList.Count; int y = drawingPanel.Height / 2; for (int i = 0; i < mainfeederList.Count; i++) { string label = "node 1"; if (nodeDataSet.Tables.Contains("node" + mainfeederList[i].ToString())) { label = nodeDataSet.Tables["node" + mainfeederList[i].ToString()].Rows[0][1].ToString(); } System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 10); System.Drawing.Font drawFont1 = new System.Drawing.Font("Arial", 8); drawArea.FillEllipse(sb, 30 + (i * (int)nodespacing), y, 10, 10); //draws the circle if (i != mainfeederList.Count - 1) { drawArea.DrawLine(myPen, 30 + (i * (float)nodespacing), y + 5, 30 + ((i + 1) * (float)nodespacing), y + 5); //draws the lines drawArea.DrawString(Convert.ToInt16(Math.Round(Convert.ToDouble(nodeDataSet.Tables[mainfeederList[i]].Rows[0][9]))) + "m", drawFont1, sb, (30 + (i * (float)nodespacing) + 30 + ((i + 1) * (float)nodespacing)) / 2, (float)y - 20); //draws the label } drawArea.DrawString(label, drawFont, sb, 30 + (i * (float)nodespacing), (float)y - 20); //draws the label } } //recursive method gets the nodes in the main feeder based on what the user specifies as the last node. private void getMainFeederNodes(int lastNode, List<int> mfNodeList) { if (mfNodeList.Count == 0) { mfNodeList.Add(lastNode); //adds the end node to the list mfNodeDictionary.Add(lastNode, "node" + lastNode.ToString()); } if (lastNode != 1) { mfNodeList.Add(Convert.ToInt16(nodeDataSet.Tables["node" + lastNode.ToString()].Rows[0][13])); //adds the parent node to the list mfNodeDictionary.Add(Convert.ToInt16(nodeDataSet.Tables["node" + lastNode.ToString()].Rows[0][13]), "node" + lastNode.ToString()); getMainFeederNodes(Convert.ToInt16(nodeDataSet.Tables["node" + lastNode.ToString()].Rows[0][13]), mfNodeList); } mfNodeList.Sort(); } //recursive method that returns a datatable with summed up loads and dgs for nodes which are not on the main feeder. public void addtempNodeTable(int nodeNumber, List<int> mfNodeList) { if (nodeNumber != 0) { if ((string)tempTable.Rows[0][0] == "0") { tempTable.Rows[0][0] = nodeNumber.ToString(); for (int rows = 0; rows < tempTable.Rows.Count; rows++) { for (int rows1 = 0; rows1 < nodeDataSet.Tables["node" + nodeNumber.ToString()].Rows.Count; rows1++) { if ((string)tempTable.Rows[rows][2] == (string)nodeDataSet.Tables["node" + nodeNumber.ToString()].Rows[rows1][2]) { for (int cols = 0; cols < tempTable.Columns.Count; cols++) { if ((cols != 3) && (cols != 4) && (cols != 5)) tempTable.Rows[rows][cols] = nodeDataSet.Tables["node" + nodeNumber.ToString()].Rows[rows1][cols]; } tempTable.Rows[rows][3] = Convert.ToDouble(tempTable.Rows[rows][3]) + Convert.ToDouble(nodeDataSet.Tables["node" + nodeNumber.ToString()].Rows[rows1][3]); tempTable.Rows[rows][4] = Convert.ToDouble(tempTable.Rows[rows][4]) + Convert.ToDouble(nodeDataSet.Tables["node" + nodeNumber.ToString()].Rows[rows1][4]); tempTable.Rows[rows][5] = Convert.ToDouble(tempTable.Rows[rows][5]) + Convert.ToDouble(nodeDataSet.Tables["node" + nodeNumber.ToString()].Rows[rows1][5]); break; } } } } string childNodes = Convert.ToString(nodeDataSet.Tables["node" + nodeNumber.ToString()].Rows[0][14]); List<string> nodesToAddTemp = new List<string>(); List<string> nodesToAdd = new List<string>(); nodesToAddTemp = ConvertStringsToStringList(childNodes, ';'); List<string> mfeederList = mfNodeList.ConvertAll<string>(delegate(int k) { return k.ToString(); }); //converts the mainfeeder nodelist which is an int list to a stringlist for later comparison nodesToAdd = nodesToAddTemp.Except(mfeederList).ToList(); addList = nodesToAdd; for (int i = 0; i < nodesToAdd.Count; i++) { addtempNodeTable(Convert.ToInt16(nodesToAdd[i]),mfNodeList); } if (nodesToAdd.Contains("0")) nodesToAdd.Remove("0"); //removes a zero from the nodes to add list. if (nodesToAdd.Contains(null)) nodesToAdd.Remove(null); //removes a zero from the nodes to add list. //has to go through each of the rows of the datatable of the child and adds the customers where the loadname and number match for (int i = 0; i < nodesToAdd.Count; i++) { for (int rows = 0; rows < tempTable.Rows.Count; rows++) { for (int rows1 = 0; rows1 < nodeDataSet.Tables["node" + Convert.ToString(nodesToAdd[i])].Rows.Count; rows1++) { if ((string)tempTable.Rows[rows][2] == (string)nodeDataSet.Tables["node" + Convert.ToString(nodesToAdd[i])].Rows[rows1][2]) { tempTable.Rows[rows][3] = Convert.ToDouble(tempTable.Rows[rows][3]) + Convert.ToDouble(nodeDataSet.Tables["node" + Convert.ToString(nodesToAdd[i])].Rows[rows1][3]); tempTable.Rows[rows][4] = Convert.ToDouble(tempTable.Rows[rows][4]) + Convert.ToDouble(nodeDataSet.Tables["node" + Convert.ToString(nodesToAdd[i])].Rows[rows1][4]); tempTable.Rows[rows][5] = Convert.ToDouble(tempTable.Rows[rows][5]) + Convert.ToDouble(nodeDataSet.Tables["node" + Convert.ToString(nodesToAdd[i])].Rows[rows1][5]); break; } } } } } } private void clearTempTable() { for (int i = 0; i < tempTable.Rows.Count; i++) { for (int j = 0; j < tempTable.Columns.Count; j++) { if (j != 2) tempTable.Rows[i][j] = "0"; } } } private DataTable addTableToMainFeeder(int nodeNumber, List<int> mfNodeList) { DataTable dt = new DataTable(); addtempNodeTable(nodeNumber, mfNodeList); dt = tempTable.Copy(); clearTempTable(); return dt; } private void selectEndNodeCombo_SelectedIndexChanged(object sender, EventArgs e) { mfNodeList.Clear();//Clears the main feeder node list mfNodeDictionary.Clear(); drawArea.Clear(Color.White); getMainFeederNodes(Convert.ToInt32(selectEndNodeCombo.Text), mfNodeList); drawPoints(mfNodeList); } private void nodeDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void editTable() { for (int i = 0; i < nodeDataGridView.Columns.Count; i++) { nodeDataGridView.Columns[i].ReadOnly = false; } } private void closeTableEdits() { for (int i = 0; i < nodeDataGridView.Columns.Count; i++) { if ((i != 3) && (i != 4) && (i != 5)) { nodeDataGridView.Columns[i].ReadOnly = true; } } } //allows only digits to be entered in the customer section of the datagridview private void nodeDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress); if ((nodeDataGridView.CurrentCell.ColumnIndex > 2) || (nodeDataGridView.CurrentCell.ColumnIndex < 5))//Desired Columns { TextBox tb = e.Control as TextBox; if (tb != null) { tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress); } } } //method to check if the pressed value is a digit private void Column1_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } } private void nodeNumCombo_SelectedIndexChanged(object sender, EventArgs e) { } private void cableSelectCombo_SelectedIndexChanged(object sender, EventArgs e) { } private void label14_Click(object sender, EventArgs e) { } private void rpLabel_TextChanged(object sender, EventArgs e) { if (nodeDataSet.Tables.Contains("node" + nodeNumCombo.Text)) { for (int i = 0; i < nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows.Count; i++) { nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[i][11] = calculateRp(rpLabel.Text, lengthNumericUpDown.Value, calculateLengths(lengthNumericUpDown.Value, i), i); } } } private void rnLabel_TextChanged(object sender, EventArgs e) { if (nodeDataSet.Tables.Contains("node" + nodeNumCombo.Text)) { for (int i = 0; i < nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows.Count; i++) { nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[i][12] = calculateRn(rnLabel.Text, lengthNumericUpDown.Value, calculateLengths(lengthNumericUpDown.Value, i), i); ; } } } private void nodeNameTextBox_Validating(object sender, CancelEventArgs e) { if (nodeNameTextBox.Text == "") { e.Cancel = true; this.errorProvider1.SetError(nodeNameTextBox, "name cannot be null"); } for (int i = 0; i < nodeDataSet.Tables.Count; i++) { if ((nodeDataSet.Tables[i].Rows[0][1].ToString() == nodeNameTextBox.Text) && ((string)nodeDataGridView.Rows[0].Cells[1].Value) != nodeNameTextBox.Text) { e.Cancel = true; nodeNameTextBox.Select(0, nodeNameTextBox.Text.Length); this.errorProvider1.SetError(nodeNameTextBox, "name already exists please select another"); } } } private void nodeNameTextBox_Validated(object sender, EventArgs e) { errorProvider1.SetError(nodeNameTextBox, ""); nodeNameList[nodeNameList.IndexOf(nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[0][1].ToString())] = nodeNameTextBox.Text; if (nodeDataSet.Tables.Contains("node" + nodeNumCombo.Text)) { for (int i = 0; i < nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows.Count; i++) { nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[i][1] = nodeNameTextBox.Text; } } drawArea.Clear(Color.White); drawPoints(mfNodeList); } private void nodeNameTextBox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Space) e.Handled = true; ; if (e.KeyChar == (char)Keys.Enter) lengthNumericUpDown.Focus(); } private void lengthNumericUpDown_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter) addNodeButton.Focus(); } private void nodeNameCombo_TextChanged(object sender, EventArgs e) { nodeNumCombo.Text = Convert.ToString(nodeNameList.IndexOf(nodeNameCombo.Text) + 1); } private void nodeNameTextBox_Enter(object sender, EventArgs e) { } private void nodeNameTextBox_TextChanged(object sender, EventArgs e) { //if (nodeDataSet.Tables.Contains("node" + nodeNumCombo.Text)) //{ // nodeNameList[nodeNameList.IndexOf(nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[0][1].ToString())] = nodeNameTextBox.Text; //} //if (nodeDataSet.Tables.Contains("node" + nodeNumCombo.Text)) //{ // for (int i = 0; i < nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows.Count; i++) // { // nodeDataSet.Tables["node" + nodeNumCombo.Text].Rows[i][1] = nodeNameTextBox.Text; // } //} } //recursive method that reutrns the autogenerated node name. It also caters for a scenario where the node already exists and will simply increse the number. private string autoGeneratedNodeName(string nodeName) { int num; if (nodeNameList.Contains(nodeName)) { string _numString = nodeName.Remove(0, 5); num = Convert.ToInt16(_numString); num++; nodeName = "node " + num.ToString(); autoGeneratedNodeName(nodeName); } return nodeName; } private void nodeNumCombo_SelectedIndexChanged_1(object sender, EventArgs e) { } private void endNodeCombo_SelectedIndexChanged(object sender, EventArgs e) { selectEndNodeCombo.SelectedIndex = nodeNameList.IndexOf(endNodeCombo.Text); } //method calculates the length of the first row of the node datatable. private double calculateLengths(decimal lengthInput, int rowIndex) { double calculatedLength = lengthTol; if ((rowIndex == 0) && (loadCount != 0)) { calculatedLength = Convert.ToDouble(lengthInput) - (lengthTol * (Convert.ToDouble(loadCount) - 1.0)); return calculatedLength; } else if ((rowIndex == 0) && (genCount != 0)) { calculatedLength = Convert.ToDouble(lengthInput) - (lengthTol * (Convert.ToDouble(genCount) - 1.0)); return calculatedLength; } else { calculatedLength = lengthTol; } return calculatedLength; } private string calculateRp(string rpText, decimal originalLength, double calculatedLength, int rowIndex) { double _calculatedRp = (calculatedLength / Convert.ToDouble(originalLength)) * Convert.ToDouble(rpText); string calculatedRp = Convert.ToString(_calculatedRp); if (rowIndex == 0) { _calculatedRp = (calculatedLength / Convert.ToDouble(originalLength)) * Convert.ToDouble(rpText); calculatedRp = Convert.ToString(_calculatedRp); return calculatedRp; } else { _calculatedRp = Convert.ToDouble(rpText) * calculatedLength / (Convert.ToDouble(originalLength)); calculatedRp = Convert.ToString(_calculatedRp); return calculatedRp; } } private string calculateRn(string rnText, decimal originalLength, double calculatedLength, int rowIndex) { double _calculatedRn = (calculatedLength / Convert.ToDouble(originalLength)) * Convert.ToDouble(rnText); string calculatedRn = Convert.ToString(_calculatedRn); if (rowIndex == 0) { _calculatedRn = (calculatedLength / Convert.ToDouble(originalLength)) * Convert.ToDouble(rnText); calculatedRn = Convert.ToString(_calculatedRn); return calculatedRn; } else { _calculatedRn = Convert.ToDouble(rnText) * calculatedLength / (Convert.ToDouble(originalLength)); calculatedRn = Convert.ToString(_calculatedRn); return calculatedRn; } } //method that returns the nodeVector datatables for all mainFeederNodes private DataTable[] createNodeVecDatatable(List<int> mfNodeList) { List<int> mfList = new List<int>(mfNodeList); k = mfNodeList.Count; DataTable[] nodeVecDataTables = new DataTable[k]; for (int i = 0; i < k; i++) { nodeVecDataTables[i] = new DataTable(); } for (int j = 0; j < k; j++) { //code to create a nodeVectorTable which will be used to calculate the voltage vector; //DataSet nodeDataSet = new DataSet(); //nodeDataSet.ReadXml(projectName); DataTable[] dt = new DataTable[mfList.Count]; //code to add the main feeder datatables into the main feeder dataset for (int i = 0; i < mfList.Count; i++) { dt[i] = new DataTable(); dt[i] = addTableToMainFeeder(mfList[i],mfList); dt[i].TableName = "node" + mfList[i].ToString(); if (tempNodeDataSet.Tables.Contains("node" + mfList[i].ToString())) tempNodeDataSet.Tables.Remove("node" + mfList[i].ToString()); tempNodeDataSet.Tables.Add(dt[i]); } //Create the column headers. List<string> headings = new List<string> { "Node", "Red", "White", "Blue", "Alpha", "Beta", "Cb", "Length", "Cable", "Rp", "Rn" }; //adds the column headers to the table for (int i = 0; i < headings.Count; i++) nodeVecDataTables[j].Columns.Add(headings[i]); //adds headings to the nodeVecDataTable; int nodeCountInt = 0; //adds rows to the table for (int i = 0; i < (loadCount + genCount) * mfList.Count; i++) { if (i % (loadCount + genCount) == 0) nodeCountInt++; nodeVecDataTables[j].Rows.Add(Convert.ToString(nodeCountInt), 0.0, 0.0, 0.0, 999.0, 999.0, 0.0, 0.0, 0.0, 0.0, 0.0); //adds rows and sets all their values to zero except a and b } for (int i = 0; i < mfList.Count; i++) { string loadDgTypeString = "blank"; int loadStartInt = (loadCount + genCount) * i; //variable which shows where the loads start in the table int genStartInt = 0; if (loadCount != 0) { genStartInt = (loadCount + genCount) * i + genCount; }//variable which shows where the generators start in the table else { genStartInt = (loadCount + genCount) * i; } for (int rows = 0; rows < tempNodeDataSet.Tables[i].Rows.Count; rows++) { //if (rows % 10 == 0) nodeVecDataTable.Rows[rows][7] = (double)lengthNumericUpDown.Value; //Assigns the first length to the first load. for (int cols = 1; cols < tempNodeDataSet.Tables[i].Columns.Count - 2; cols++) { if ((cols == 2)) { loadDgTypeString = Convert.ToString(tempNodeDataSet.Tables[i].Rows[rows][cols]); //gets the text in the 2nd column of the node datatable if (loadDgTypeString[0] == 'L') loadStartInt++; if (loadDgTypeString[0] == 'G') genStartInt++; } if ((loadDgTypeString[0] == 'L')) { if (cols == 1) { nodeVecDataTables[j].Rows[loadStartInt - 1][cols-1] = Convert.ToString(tempNodeDataSet.Tables[i].Rows[rows][cols]); } if ((cols > 2) && (cols != 10)) { nodeVecDataTables[j].Rows[loadStartInt - 1][cols - 2] = Convert.ToDouble(tempNodeDataSet.Tables[i].Rows[rows][cols]); } } if (loadDgTypeString[0] == 'G') { nodeVecDataTables[j].Rows[genStartInt][0] = Convert.ToString(tempNodeDataSet.Tables[i].Rows[rows][1]); if ((cols > 2) && (cols != 10)) { nodeVecDataTables[j].Rows[genStartInt][cols - 2] = Convert.ToDouble(tempNodeDataSet.Tables[i].Rows[rows][cols]); } } } } } mfList.RemoveAt(k-1-j); tempNodeDataSet.Tables.Clear(); } return nodeVecDataTables; } } }
1268c1b7b86f3141765c649943d74cc6de1938b3
C#
BBarry29/RPSLS
/RPSLStest/RPSLS1.cs
3.265625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assignment { public class RPSLSGame { string playerInput; string name; public void PlayGame() { if (playerInput == name) { StartGame(); GetWinner(); } } public void GetWinner() { if (cpuInput == playerInput) { Console.WriteLine("Draw!"); Console.WriteLine("You scored: {0} point(s) this round."); Console.WriteLine("The Computer scored {0} point(s) this round."); } else if (cpuInput == "Rock" && playerInput == "Scissors" || ) } } public void StartGame() { string cpuInput; Random RandomNumber = new Random(); int i = RandomNumber.Next(0, 5); if (i == 0) { cpuInput = "Rock"; } else if (i == 1) { cpuInput = "Paper"; } else if (i == 2) { cpuInput = "Scissors"; } else if (i == 3) { cpuInput = "Lizard"; } else if (i == 4) { cpuInput = "Spock"; } Console.WriteLine("Please choose Rock, Paper, Scissors, Lizard, or Spock: "); playerInput = Console.ReadLine(); } } }
e8a81d7fb133fff79a96982f46097b8b1915e9a9
C#
courtenayparserr/BSheet
/Plaid.Net/Data/Models/Results/PlaidResult.cs
3.140625
3
namespace Plaid.Net.Models { using System; /// <summary> /// Generic result from Plaid which could possibly be an error. /// </summary> /// <typeparam name="T">The type of response value.</typeparam> public class PlaidResult<T> : PlaidResult { /// <summary> /// Initializes a new instance of the <see cref="PlaidResult{T}"/> class. /// </summary> public PlaidResult() { } /// <summary> /// Initializes a new instance of the <see cref="PlaidResult{T}"/> class. /// </summary> /// <param name="value">The return value.</param> public PlaidResult(T value) { this.Value = value; } /// <summary> /// Gets or sets the result value. /// </summary> public T Value { get; set; } } /// <summary> /// Generic result from Plaid which could possibly be an error. /// </summary> public abstract class PlaidResult { /// <summary> /// Gets exception information if a request was not successful. /// </summary> public PlaidException Exception { get; internal set; } /// <summary> /// Gets a value indicating whether the operation resulted in an error. /// </summary> public bool IsError => this.Exception != null; } }
3239d7e6da2490c83f8cfca1edace32ae877f417
C#
ipoddubnyi/mt-tacticwar
/src/MT.TacticWar.UI.Editor/Sources/Painters/PassabilityPainter.cs
2.90625
3
using System; using MT.TacticWar.Core; using MT.TacticWar.Core.Landscape; using MT.TacticWar.UI.Graphics; namespace MT.TacticWar.UI.Editor.Painters { class PassabilityPainter : IPainter { private readonly GameGraphics graphics; private readonly Map map; private readonly bool passable; private bool active; // непрерывное рисование private int x; private int y; public PassabilityPainter(GameGraphics graphics, Map map, bool passable) { Stop(); this.graphics = graphics; this.map = map; this.passable = passable; } public void Start(int x, int y) { this.x = x; this.y = y; active = true; } public void Stop() { active = false; x = -1; y = -1; } public bool IsActive() { return active; } public bool TryMove(int x, int y) { if (this.x != x || this.y != y) { this.x = x; this.y = y; return true; } return false; } public void Paint() { if (passable) { map[x, y].Passable = true; graphics.DrawCell(map[x, y]); } else { map[x, y].Passable = false; graphics.DrawCross(new Coordinates(x, y)); } } } }
3a63199d3397206c27814becdc791706f62f3be7
C#
tdmehmet/Seat2Gether_Backend
/Seat2Gether/Repositories/MasterDataMaterialRepository.cs
2.84375
3
using Seat2Gether.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace Seat2Gether.Repositories { public class MasterDataMaterialRepository { private Seat2GetherDBContext DBContext; public MasterDataMaterialRepository() { DBContext = new Seat2GetherDBContext(); } public List<MasterDataMaterial> MaterialList() { var materialQuery = from material in DBContext.Material select material; List<MasterDataMaterial> materialList = materialQuery.ToList(); return materialList; } public void AddMaterial(MasterDataMaterial material) { DBContext.Material.Add(material); DBContext.SaveChanges(); } public void UpdateMaterial(MasterDataMaterial material) { DBContext.Material.Attach(material); var entry = DBContext.Entry(material); entry.State = EntityState.Modified; DBContext.SaveChanges(); } public void DeleteMaterial(MasterDataMaterial material) { DBContext.Material.Attach(material); var entry = DBContext.Entry(material); entry.State = EntityState.Deleted; DBContext.SaveChanges(); } } }
c1b74ed74ff001bcd436a09e38d6c398950df386
C#
livetract/BlazorWasm
/Wasm/Services/WeatherService.cs
2.59375
3
using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Json; using System.Threading.Tasks; using Wasm.Dtos; namespace Wasm.Services { public class WeatherService : IWeatherService { private readonly HttpClient _httpClient; private const string BaseUri = "https://localhost:9011/api/"; public WeatherService(HttpClient httpClient) { _httpClient = httpClient; } public async Task<IEnumerable<WeatherForecast>> GetDataAsync() { var data =await _httpClient.GetFromJsonAsync<IEnumerable<WeatherForecast>>($"{BaseUri}weatherforecast"); return data; } } }
99814838af282173561b2478ace5b87e58efaf8a
C#
shendongnian/download4
/first_version_download2/313550-25932921-73850941-2.cs
2.625
3
for (int i = 0; i < 365; i++) { var tasks = db.Tasks.Where(x => x.Date.AddDays(-i).ToString("d") == DateTime.Now.AddDays(-i).ToString("d")).ToList(); if (tasks != null) { tempTask.AddRange(tasks); } else { break; } }
3b1e225b3b53cf2877f85faf7e4a936285ceedc3
C#
SethTales/FluentInject
/FluentInject/Extensions/TypeExtensions.cs
2.578125
3
using System; using FluentInject.Exceptions; using FluentInject.Models; namespace FluentInject.Extensions { internal static class TypeExtensions { internal static bool IsSupportedCtorParam(this Type self) { return self.IsInterface ? true : throw new UnsupportedConstructorParameterException( $"Type {self} is not supported as an injectable constructor parameter at this time. " + $"Currently supported constructor parameter types are: {SupportedConstructorParameters.GetSupportedConstructorParameterTypes()}"); } } }
a36b0d58c3019ca4555b2b4df23671896e48d30b
C#
pijix/CallCenter
/CallCenter.Application/IncidenceService.cs
2.828125
3
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using CallCenter.CORE.Domain; using CallCenter.CORE.Domain.Enums; using CallCenter.DAL; namespace CallCenter.Application { public class IncidenceService { private DBContext _dbContext; public IncidenceService(DBContext dbContext) { _dbContext = dbContext; } /// <summary> /// Método que retorna todas las incidencias /// </summary> /// <returns>Lista de incidencias</returns> public IQueryable<Incidence> GetAll() { return _dbContext.Incidences.Include(a => a.Equipment); } /// <summary> /// Método que retorna una incidencia /// </summary> /// <param name="incidenceId">identificador del usuario</param> /// <returns>Una incidencia</returns> public Incidence GetById(Guid incidenceId) { return _dbContext.Incidences.FirstOrDefault(i=>i.Id == incidenceId); } /// <summary> /// Método que retorna una lista de incidencias por usuario /// </summary> /// <param name="userId">identificador del usuario</param> /// <returns>Lista de incidencias</returns> public IQueryable<Incidence> GetByUserId(Guid userId) { return _dbContext.Incidences.Select(a=>a).Where(u=>u.UserId == userId); } /// <summary> /// Método que retorna una lista de incidencias por equipo /// </summary> /// <param name="equipmentId">identificador del equipo</param> /// <returns>Lista de incidencias</returns> public IQueryable<Incidence> GetByEquipment(Guid equipmentId) { return _dbContext.Incidences.Select(a => a).Where(e => e.Equipment.Id == equipmentId); } /// <summary> /// Permite añdir una Incidencia /// </summary> /// <param name="incidence">entidad incidence</param> /// <returns>La incidencia añadida</returns> public Incidence Add(Incidence incidence) { try { var newClient = _dbContext.Incidences.Add(incidence); _dbContext.SaveChanges(); return newClient; } catch (Exception ex) { throw new Exception("Error al añadir la Incidencia: " + ex.InnerException.Message); } } /// <summary> /// Permite editar una Incidencia /// </summary> /// <param name="incidence">entidad</param> /// <returns>La incidencia editada</returns> public Incidence Update(Incidence incidence) { try { var editIncidence = _dbContext.Incidences.FirstOrDefault(i => i.Id == incidence.Id); if(editIncidence == null) throw new Exception("Incidencia no encontrada"); editIncidence.IncidenceTitle = incidence.IncidenceTitle; editIncidence.Equipment = incidence.Equipment; editIncidence.Priority = incidence.Priority; editIncidence.Status = incidence.Status; editIncidence.UserId = incidence.UserId; editIncidence.UserName = incidence.UserName; _dbContext.SaveChanges(); return editIncidence; } catch (Exception ex) { throw new Exception("Error al Editar la Incidencia: " + ex.InnerException.Message); } } /// <summary> /// Permite eliminar una Incidencia /// </summary> /// <param name="incidenceId">identificador de la incidencia</param> /// <returns>true o false por si se elimino correctamente</returns> public bool Delete(Guid incidenceId) { try { var exists = _dbContext.Incidences.FirstOrDefault(i => i.Id == incidenceId); if(exists == null ) throw new Exception("La Incidencia a eliminar no Existe"); _dbContext.Incidences.Remove(exists); _dbContext.SaveChanges(); return true; } catch (Exception ex) { throw new Exception("Error al Eliminar la Incidencia: " + ex.InnerException.Message); } } /// <summary> /// Retorna incidencias agrupadas por usuario, mas de 2 /// </summary> /// <returns>Objeto con Usuario y Total Incidencias</returns> public Object TotalIncidencesByUser() { try { return _dbContext.Incidences.Where(a=>a.Status != EnumIncidenceStatus.Cerrada).GroupBy(a => a.UserId).Where(a => a.Count()>2).Select(a => new { a.FirstOrDefault().UserName, IncidencesCount = a.Count()}).ToList(); } catch (Exception ex) { throw new Exception("Error al calular incidencias: " + ex.Message); } } /// <summary> /// Retorna incidencias agrupadas por equipo, mas de 2 /// </summary> /// <returns>Objeto con Equipo y Total Incidencias</returns> public Object TotalIncidencesByEquipment() { try { return _dbContext.Incidences.Where(a=>a.Status != EnumIncidenceStatus.Cerrada).GroupBy(a=>a.Equipment.Id).Where(a => a.Count()>2).Select(a => new { EquipmentName = a.FirstOrDefault().Equipment.Name, IncidencesCount = a.Count() }).ToList(); } catch (Exception ex) { throw new Exception("Error al calular incidencias: " + ex.InnerException.Message); } } } }
e52d8c905d48b92b7b785556a0538d092869f9e6
C#
rold2007/kerglerec
/Tests/Kerglerec.Tests/BirthControlTests.cs
2.59375
3
// <copyright file="BirthControlTests.cs" company="David Rolland"> // Copyright (c) David Rolland. All rights reserved. // </copyright> namespace Kerglerec.Tests { using System; using Shouldly; using Xunit; /// <summary> /// Contains tests for the BirthControl class. /// </summary> public class BirthControlTests { /// <summary> /// Tests the BirthControl::PopulationChange method. /// </summary> [Fact] public void PopulationChangeTest() { Population startPopulation = new Population().Add(1000); BirthControl birthControl = new BirthControl(); Calendar calendar = new Calendar(); Province province = new Province(); province.Add(startPopulation); Population populationFlow = new Population(); for (int i = 0; i < 12; i++) { calendar.Add(1); populationFlow = populationFlow.Add(birthControl.PopulationFlow(calendar, province)); } populationFlow.Adults.ShouldBeGreaterThan(0); populationFlow.Adults.ShouldBeLessThan(startPopulation.Adults); } /// <summary> /// Tests the BirthControl::PopulationChange method with invalid parameters. /// </summary> [Fact] public void PopulationChangeParameterTest() { BirthControl birthControl = new BirthControl(); Should.Throw<ArgumentNullException>(() => { birthControl.PopulationFlow(null, null); }).Message.ShouldContain("calendar"); Should.Throw<ArgumentNullException>(() => { birthControl.PopulationFlow(new Calendar(), null); }).Message.ShouldContain("province"); } } }
47c4f4bd57c6bd52c980fafd8e090cca5ce7d6f1
C#
nikitrifonovprojects/Data-Structures-and-Algorithms
/DataStructuresAndAlgorithms/NT.DataStructures/Hash.cs
3.25
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace NT.DataStructures { public class Hash<T> : ICollection<T> { private const int DefaultInitialSize = 17; internal List<HashSlot<T>>[] buckets; private int count; private int lenght; public Hash() { Initialize(DefaultInitialSize); } public Hash(ICollection<T> collection) { if (collection == null) { throw new ArgumentNullException(); } int size = NextPrimeNumber(collection.Count * 2); Initialize(size); this.UnionWith(collection); } public int Count { get { return this.count; } } public bool IsReadOnly { get { return false; } } private void Initialize(int size) { this.buckets = new List<HashSlot<T>>[size]; this.count = 0; this.lenght = size; } public void UnionWith(IEnumerable<T> collection) { foreach (T value in collection) { AddIfNotPresent(value); } } private bool AddIfNotPresent(T value) { if (value == null) { throw new ArgumentNullException(); } if (this.count * 2 > this.buckets.Length) { IncreaseCapacity(); } int hashCode = ReHash(value.GetHashCode()) & 0x7FFFFFFF; int bucket = hashCode % this.buckets.Length; var currentBucket = this.buckets[bucket]; if (currentBucket == null) { currentBucket = new List<HashSlot<T>>(); } else { for (int i = 0; i < currentBucket.Count; i++) { var current = currentBucket[i]; if (current.HashCode == hashCode && current.Value.Equals(value)) { return false; } } } HashSlot<T> itemToAdd = new HashSlot<T>(); itemToAdd.HashCode = hashCode; itemToAdd.Value = value; currentBucket.Add(itemToAdd); this.buckets[bucket] = currentBucket; this.count++; return true; } private void IncreaseCapacity() { int newSize = NextPrimeNumber(this.buckets.Length * 2); List<HashSlot<T>>[] newBuckets = new List<HashSlot<T>>[newSize]; for (int i = 0; i < this.lenght; i++) { if (this.buckets[i] != null) { var newHashCode = this.buckets[i].First().HashCode; var newBucket = newHashCode % newBuckets.Length; newBuckets[newBucket] = this.buckets[i]; } } this.buckets = newBuckets; this.lenght = newBuckets.Length; } public void Add(T item) { AddIfNotPresent(item); } public void Clear() { Array.Clear(this.buckets, 0, this.lenght); this.lenght = 0; this.count = 0; } public bool Contains(T value) { return this.ContainsAction(value, (currentBucket, i) => { }); } public void CopyTo(T[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException(); } if (this.count < 0) { throw new ArgumentOutOfRangeException(); } if (arrayIndex > array.Length || this.count > array.Length - arrayIndex) { throw new ArgumentOutOfRangeException(); } int current = 0; int numCopied = 0; for (int i = 0; i < this.lenght && numCopied < this.count; i++) { if (this.buckets[i] != null) { var tempArray = this.buckets[i].ToArray(); for (int k = 0; k < tempArray.Length; k++) { array[current + arrayIndex] = tempArray[k].Value; current++; numCopied++; } } } } public IEnumerator<T> GetEnumerator() { return new HashEnumerator<T>(this); } public bool Remove(T value) { return ContainsAction(value, (currentBucket, i) => { currentBucket.Remove(currentBucket[i]); this.count--; }); } private bool ContainsAction(T value, Action<List<HashSlot<T>>, int> action) { if (value == null) { throw new ArgumentNullException(); } int hashCode = ReHash(value.GetHashCode()) & 0x7FFFFFFF; int bucket = hashCode % this.buckets.Length; var currentBucket = this.buckets[bucket]; if (currentBucket != null) { for (int i = 0; i < currentBucket.Count; i++) { var current = currentBucket[i]; if (current.HashCode == hashCode && current.Value.Equals(value)) { action(currentBucket, i); return true; } } } return false; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private int NextPrimeNumber(int number) { int[] primes = { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369}; if (number < primes.Last()) { for (int i = 0; i < primes.Length; i++) { if (primes[i] > number) { return primes[i]; } } } else { do { number++; } while (!isPrime(number)); } return number; } private bool isPrime(int number) { double sqRoot = Math.Sqrt(number); for (int i = number; i <= sqRoot; i++) { if (number % i == 0) { return false; } } return true; } private int ReHash(int source) { unchecked { ulong c = 0xDEADBEEFDEADBEEF + (ulong)source; ulong d = 0xE2ADBEEFDEADBEEF ^ c; ulong a = d += c = c << 15 | c >> -15; ulong b = a += d = d << 52 | d >> -52; c ^= b += a = a << 26 | a >> -26; d ^= c += b = b << 51 | b >> -51; a ^= d += c = c << 28 | c >> -28; b ^= a += d = d << 9 | d >> -9; c ^= b += a = a << 47 | a >> -47; d ^= c += b << 54 | b >> -54; a ^= d += c << 32 | c >> 32; a += d << 25 | d >> -25; return (int)(a >> 1); } } } }
a4d35309d899830f2258ec7206d6e7b73a0b26c5
C#
inthehand/32feet
/Legacy/InTheHand.Devices.Bluetooth/Devices/Enumeration/DeviceUnpairingResult.cs
2.765625
3
//----------------------------------------------------------------------- // <copyright file="DeviceUnpairingResult.cs" company="In The Hand Ltd"> // Copyright (c) 2017 In The Hand Ltd, All rights reserved. // This source code is licensed under the MIT License - see License.txt // </copyright> //----------------------------------------------------------------------- namespace InTheHand.Devices.Enumeration { /// <summary> /// Contains information about the result of attempting to unpair a device. /// </summary> public sealed class DeviceUnpairingResult { #if WINDOWS_UWP private Windows.Devices.Enumeration.DeviceUnpairingResult _result; private DeviceUnpairingResult(Windows.Devices.Enumeration.DeviceUnpairingResult result) { _result = result; } public static implicit operator Windows.Devices.Enumeration.DeviceUnpairingResult(DeviceUnpairingResult result) { return result._result; } public static implicit operator DeviceUnpairingResult(Windows.Devices.Enumeration.DeviceUnpairingResult result) { return new DeviceUnpairingResult(result); } #else private DeviceUnpairingResultStatus _status; internal DeviceUnpairingResult() { _status = DeviceUnpairingResultStatus.Failed; } #if WIN32 internal DeviceUnpairingResult(int error) { switch(error) { case 0: _status = DeviceUnpairingResultStatus.Unpaired; break; default: _status = DeviceUnpairingResultStatus.Failed; break; } } #endif #endif /// <summary> /// Gets the paired status of the device after the unpairing action completed. /// </summary> /// <value>The paired status of the device.</value> public DeviceUnpairingResultStatus Status { get { #if WINDOWS_UWP return (DeviceUnpairingResultStatus)((int)_result.Status); #else return _status; #endif } } } }
95b69b8f9ee33fafe92d44a65c13eef42eec7d7f
C#
Yordan432/Exams
/Programming Basics Online Exam 10-11 March 2018/Online Exam Basics/05.Mask/Program.cs
3.1875
3
using System; public class Program { public static void Main() { int n = int.Parse(Console.ReadLine()); int countSpace = n - 2; int countSpaceMid = 0; FirstPart(n, ref countSpace, ref countSpaceMid); Console.WriteLine(new string('-', n * 2 + 2)); Console.Write("|"); Console.Write(new string(' ', n / 3)); Console.Write("_"); Console.Write(new string(' ', n + 1)); Console.Write("_"); Console.Write(new string(' ', n / 3)); Console.WriteLine("|"); double midPart = Math.Ceiling(n / 2.0); int countSpaceMiddle = n / 3; Console.Write("|"); Console.Write(new string(' ', countSpaceMiddle)); Console.Write("@"); Console.Write(new string(' ', n + 1)); Console.Write("@"); Console.Write(new string(' ', countSpaceMiddle)); Console.WriteLine("|"); for (int i = 0; i < ((n + 1) / 2) - 1; i++) { Console.Write("|"); Console.Write(new string(' ' , n * 2)); Console.WriteLine("|"); } Console.Write("|"); Console.Write(new string(' ' ,n- 1)); Console.Write("OO"); Console.Write(new string(' ', n - 1)); Console.WriteLine("|"); Console.Write("|"); Console.Write(new string(' ', n - 2)); Console.Write("/"); Console.Write(new string(' ' , 2)); Console.Write("\\"); Console.Write(new string(' ', n - 2)); Console.WriteLine("|"); Console.Write("|"); Console.Write(new string(' ', n - 2)); Console.Write(new string('|' , 4)); Console.Write(new string(' ', n - 2)); Console.WriteLine("|"); int inclined = 1; int tilda = n * 2; for (int i = 0; i < n + 1; i++) { Console.Write(new string('\\' , inclined)); Console.Write(new string('`' , tilda)); Console.WriteLine(new string('/' , inclined)); inclined++; tilda -= 2; } } private static void FirstPart(int n, ref int countSpace, ref int countSpaceMid) { for (int i = 0; i < n - 1; i++) { Console.Write(new string(' ', countSpace)); Console.Write("/"); Console.Write(new string(' ', countSpaceMid)); Console.Write("|"); Console.Write(new string(' ', 2)); Console.Write("|"); Console.Write(new string(' ', countSpaceMid)); Console.Write("\\"); countSpaceMid++; countSpace--; Console.WriteLine(); } } }
0d1c9b2be67a55c9c7f4e76e8f0d683145898a70
C#
isurling/EasySharpFrame
/ES/Network/Websocket/RemoteConnection.cs
2.71875
3
using Fleck; using System; namespace ES.Network.Websocket { /// <summary> /// 远程连接对象 /// </summary> public class RemoteConnection { /// <summary> /// 连接对象 /// </summary> public IWebSocketConnection socket; /// <summary> /// 用户自定义标识 绑定对象 /// </summary> public object tag; /// <summary> /// 字符消息 /// </summary> public string message; /// <summary> /// 字节消息 /// </summary> public byte[] buffer; /// <summary> /// 连接对象是否有效 /// </summary> public bool IsAvailable { get { if (socket != null) return socket.IsAvailable; else return false; } } /// <summary> /// 发送消息 /// </summary> /// <param name="message">字符消息</param> public bool Send(string message) { if (socket != null && socket.IsAvailable) { socket.Send(message); return true; } else return false; } /// <summary> /// 发送消息 /// </summary> /// <param name="message">字节消息</param> public bool Send(byte[] message) { if (socket != null && socket.IsAvailable) { socket.Send(message); return true; } else return false; } /// <summary> /// 获取唯一标识ID 同一个socket连接id不变 /// </summary> /// <returns></returns> public Guid GetSocketGuid() { if (socket != null && socket.IsAvailable) { return socket.ConnectionInfo.Id; } else return default; } } }
82e42eabef7929c2393c53e3dc2402fc8241dfa8
C#
s-rusev/TelerikAcademy
/C# I/3HW_OperatorsAndExpressions/OperatorsExpressions/RectangleArea/RectangleArea.cs
3.578125
4
using System; class RectangleArea { static void Main() { double height = Double.Parse(Console.ReadLine()); double width = Double.Parse(Console.ReadLine()); Console.WriteLine("The area of the rectangle is "+ (height*width)); } }
72a975c4512783423364f37154e9bcc0cf1cd952
C#
Binhhp/picture-engineer
/PictureEngineer.OCR/ImageProcess/Method/DeskewText.cs
2.625
3
using Emgu.CV; using Emgu.CV.CvEnum; using Emgu.CV.Structure; using Emgu.CV.Util; using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace PictureEngineer.OCR.ImageProcess.Method { public class DeskewText { /// <summary> /// deskew text /// </summary> /// <param name="img">input image gray</param> public static Image<Gray, byte> Run(Image<Gray, byte> img) { var gray = img.ThresholdBinaryInv(new Gray(200), new Gray(255)).Dilate(5); VectorOfPoint points = new VectorOfPoint(); CvInvoke.FindNonZero(gray, points); var minareaRect = CvInvoke.MinAreaRect(points); var rotationMatrix = new Mat(new Size(2, 3), DepthType.Cv32F, 1); var rotatedImage = img.CopyBlank(); if(minareaRect.Angle < -45) { minareaRect.Angle = 90 + minareaRect.Angle; } CvInvoke.GetRotationMatrix2D(minareaRect.Center, minareaRect.Angle, 1.0, rotationMatrix); CvInvoke.WarpAffine(img, rotatedImage, rotationMatrix, img.Size, Inter.Cubic, borderMode: BorderType.Replicate); return rotatedImage; } } }
fea3e82b02956c9194ca8373d7069ab47aa7aa1f
C#
HemantKoti/Design-Patterns
/StrategyPattern/Business/Strategies/Comparer/OrderAmountComparer.cs
3.09375
3
using Strategy_Pattern_First_Look.Business.Models; using System.Collections.Generic; namespace StrategyPattern.Business.Strategies.Comparer { class OrderAmountComparer : IComparer<Order> { public int Compare(Order x, Order y) { var xTotal = x.TotalPrice; var yTotal = y.TotalPrice; if (xTotal == yTotal) { return 0; } else if (xTotal > yTotal) { return 1; } return -1; } } }
a8dedcb6ca1b95a0ee28a8110da985bfc4c25072
C#
bingoo0/SoftUni-TechModule
/Simple Arrays - Exercises/1. Largest Element in Array/LargestElement.cs
3.640625
4
using System; using System.Linq; namespace _1.Largest_Element_in_Array { class LargestElement { static void Main() { var numbers = int.Parse(Console.ReadLine()); var arrayOfNums = new int[numbers]; var largestNum = int.MinValue; for (int i = 0; i < arrayOfNums.Length; i++) { var currentNumber = int.Parse(Console.ReadLine()); arrayOfNums[i] = currentNumber; if (currentNumber > largestNum) { largestNum = currentNumber ; } } // end for Console.WriteLine(largestNum); } } }
623f2bc06c0cae684d985e5e43b124dd9b51f540
C#
didafpunk/training-csharp
/AsyncDelegate/AsyncDelegate/Program.cs
3.21875
3
using System; using System.Net; using System.Threading; namespace AsyncDelegate { class Program { static bool donwloading = true; static void Main(string[] args) { string filename = "bateau.jpg"; string url = "https://codeavecjonathan.com/res/bateau.jpg"; var webClient = new WebClient(); webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted; Console.Write("Downloading."); webClient.DownloadFileAsync(new Uri(url), filename); while (donwloading) { Thread.Sleep(500); if (donwloading) { Console.Write("."); } } } private static void WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { Console.WriteLine("Downloading finished"); donwloading = false; } } }
ea0cac6d40977d4d60f2ff450242fd7a62c868b4
C#
wyjtom/test
/Login/Login/Web/showdata.aspx.cs
2.515625
3
using Login.Common; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Login.Web { public partial class showdata : System.Web.UI.Page { //public HttpResponseMessage /// <summary> /// 获取字符串 /// </summary> /// <param name="dataSet"></param> /// <returns></returns> public string GetJson(DataSet dataSet) { string Json = JsonConvert.SerializeObject(dataSet); this.TextBox1.Text = Json; // SendJons(Json); return Json;//new HttpResponse(Json); } /// <summary> /// 发送Json /// </summary> public void SendJons(string strJson) { HttpUtils.Post("http://localhost:52918/Web/TestJson.aspx", strJson,""); Response.Redirect("TestJson.aspx"); } /// <summary> /// 获取数据库数据 /// </summary> protected void GetData() { DataSet ds = DbHelper.ExecuteGetDateSet("select*from book"); GetJson(ds); GridView1.DataSource = ds.Tables[0].DefaultView;//设置gridview控件的数据源为创建的数据集ds GridView1.DataBind(); //绑定数据库表中数据 } /// <summary> /// 页面加载初始化 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { GetData(); } /// <summary> /// 分页 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; this.GetData(); } /// <summary> /// 选中 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { GridViewRow row = GridView1.SelectedRow; this.txtBookId.Text = HttpUtility.HtmlDecode(row.Cells[0].Text); this.txtBookName.Text = HttpUtility.HtmlDecode(row.Cells[1].Text); this.txtBookAddress.Text = HttpUtility.HtmlDecode(row.Cells[2].Text); } /// <summary> /// 删除 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { string bookid = GridView1.DataKeys[e.RowIndex][0].ToString(); SqlConnection con = new SqlConnection(); con.ConnectionString = ConfigurationManager.ConnectionStrings["RemoteConn"].ConnectionString; string sql = "delete from book where bookid='" + bookid + "'"; con.Open(); SqlCommand sqlCommand = new SqlCommand(sql, con); // cmd.Parameters.AddWithValue("@bookid", bookid); sqlCommand.ExecuteNonQuery(); con.Close(); GridView1.EditIndex = -1; GetData(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.SelectedIndex = e.NewEditIndex;//实现编辑功能 GetData(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { string bookId = GridView1.DataKeys[e.RowIndex][0].ToString();//取出修改行的主键值 string bookName = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).ToString(); string bookAddress = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).ToString(); //将用户更新的数据修改数据库 SqlConnection con = new SqlConnection(); //定义数据库连接对象 con.ConnectionString = ConfigurationManager.ConnectionStrings["RemoteConn"].ConnectionString; //定义数据库连接字符串 string sql = "update book set bookname='"+bookName+"',bookaddress='"+bookAddress+"' where bookid='"+bookId+"'"; con.Open(); SqlCommand cmd = new SqlCommand(sql, con); cmd.ExecuteNonQuery(); con.Close(); GridView1.EditIndex = -1; GetData(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; GetData(); } protected void Button1_Click(object sender, EventArgs e) { if (this.txtBookAddress.Text == "" || this.txtBookId.Text == "" || this.txtBookName.Text == "") { this.Label4.Text = "图书信息不能为空"; return; } string InsertStr = string.Format("insert into book(bookid,bookname,bookaddress)values('" + this.txtBookId.Text + "','" + this.txtBookName.Text + "','" + this.txtBookAddress.Text + "')"); int value = DbHelper.ExecuteCommand(InsertStr); if (value > 0) { this.Label4.Text = "新增成功"; } } protected void Button2_Click(object sender, EventArgs e) { DataSet ds = DbHelper.ExecuteGetDateSet("select*from book"); GetJson(ds); } } }
68be0837dcd08434c81a28c0062966433c953762
C#
DracZhang/SortVisualize
/Sort/Base/SortBase.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sort { public class SortBase { public List<int> SortList { get; private set; } public int TotalCount { get; private set; } public event EventHandler<OnSwapEventArgs> OnSwap; public event EventHandler OnFinished; public SortBase(List<int> SortList) { this.SortList = SortList; TotalCount = SortList.Count; } public virtual void Run() { OnFinished?.Invoke(this, null); } protected void Swap(int ID1, int ID2, int Value1, int Value2) { SortList[ID1] = Value2; SortList[ID2] = Value1; OnSwapEventArgs OSEA = new OnSwapEventArgs(ID1, ID2, Value1, Value2); OnSwap?.Invoke(this, OSEA); } } }
2e8a2c2a72c890c8d8ffb2df9c7e785a6e5e5972
C#
darl2ng/LinqBenchmarks
/LinqBenchmarks/Array/Int32/ArrayInt32WhereCount.cs
2.734375
3
namespace LinqBenchmarks.Array.Int32; public class ArrayInt32WhereCount: ArrayInt32BenchmarkBase { Func<int> linqOptimizerQuery; protected override void Setup() { base.Setup(); linqOptimizerQuery = source .AsQueryExpr() .Where(item => item.IsEven()) .Count() .Compile(); } [Benchmark(Baseline = true)] public int ForLoop() { var count = 0; var array = source; for (var index = 0; index < array.Length; index++) { var item = array[index]; if (item.IsEven()) count++; } return count; } [Benchmark] public int ForeachLoop() { var count = 0; foreach (var item in source) { if (item.IsEven()) count++; } return count; } [Benchmark] public int Linq() => source.Count(item => item.IsEven()); [Benchmark] public int LinqFaster() => source.CountF(item => item.IsEven()); [Benchmark] public int LinqFasterer() => EnumerableF.CountF(source, item => item.IsEven()); [Benchmark] public int LinqAF() => global::LinqAF.ArrayExtensionMethods.Count(source, item => item.IsEven()); [Benchmark] public int LinqOptimizer() => linqOptimizerQuery.Invoke(); [Benchmark] public int SpanLinq() => source .AsSpan() .Where(item => item.IsEven()) .Count(); [Benchmark] public int Streams() => source .AsStream() .Where(item => item.IsEven()) .Count(); [Benchmark] public int StructLinq() => source .ToStructEnumerable() .Where(item => item.IsEven()) .Count(); [Benchmark] public int StructLinq_ValueDelegate() { var predicate = new Int32IsEven(); return source .ToStructEnumerable() .Where(ref predicate, x => x) .Count(x => x); } [Benchmark] public int Hyperlinq() => source.AsValueEnumerable() .Where(item => item.IsEven()) .Count(); [Benchmark] public int Hyperlinq_ValueDelegate() => source.AsValueEnumerable() .Where<Int32IsEven>() .Count(); [Benchmark] public int Faslinq() => FaslinqExtensions .Where(source, item => item.IsEven()) .Count(); }
be6b95f241e4de26184636f73f898633b1ae9d3c
C#
leonard-thieu/css-sprite-sheet-generator
/CssSpriteSheetGenerator.Gui/Controls/SelfAdorningFrameworkElement.cs
2.625
3
using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Documents; using CssSpriteSheetGenerator.Gui.Controls.Tools; namespace CssSpriteSheetGenerator.Gui.Controls { /// <summary> /// An element that can be initialized with an adorner. /// </summary> [ExcludeFromCodeCoverage] public class SelfAdorningFrameworkElement : FrameworkElement, IDisposable { [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static SelfAdorningFrameworkElement() { WidthProperty.OverrideMetadata( typeof(SelfAdorningFrameworkElement), new FrameworkPropertyMetadata { BindsTwoWayByDefault = true }); HeightProperty.OverrideMetadata( typeof(SelfAdorningFrameworkElement), new FrameworkPropertyMetadata { BindsTwoWayByDefault = true }); MarginProperty.OverrideMetadata( typeof(SelfAdorningFrameworkElement), new FrameworkPropertyMetadata { BindsTwoWayByDefault = true }); } private AdornerLayer adornerLayer; // The adorner layer for this element /// <summary> /// Identifies the <see cref="IsSelected" /> dependency property. /// </summary> public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register( "IsSelected", typeof(bool), typeof(SelfAdorningFrameworkElement), new FrameworkPropertyMetadata( new PropertyChangedCallback(OnIsSelectedChanged))); private static void OnIsSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var obj = (SelfAdorningFrameworkElement)d; obj.OnIsSelectedChanged((bool)e.OldValue, (bool)e.NewValue); } private void OnIsSelectedChanged(bool oldValue, bool newValue) { if (oldValue == newValue) return; if (newValue) Adorner = new SelectedAdorner(this); else Adorner = new SpriteAdorner(this); } /// <summary> /// <para>If true, sets <see cref="Adorner" /> to <see cref="SelectedAdorner" />.</para> /// <para>If false, sets <see cref="Adorner" /> to <see cref="SpriteAdorner" />.</para> /// </summary> [Description("If true, sets Adorner to SelectedAdorner. If false, sets Adorner to SpriteAdorner.")] [Category("Common")] public bool IsSelected { get { return (bool)GetValue(IsSelectedProperty); } set { SetValue(IsSelectedProperty, value); } } /// <summary> /// Identifies the <see cref="Adorner" /> dependency property. /// </summary> public static readonly DependencyProperty AdornerProperty = DependencyProperty.Register( "Adorner", typeof(Adorner), typeof(SelfAdorningFrameworkElement), new PropertyMetadata( new PropertyChangedCallback(OnAdornerChanged))); private static void OnAdornerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var obj = (SelfAdorningFrameworkElement)d; obj.OnAdornerChanged((Adorner)e.OldValue, (Adorner)e.NewValue); } private void OnAdornerChanged(Adorner oldValue, Adorner newValue) { if (oldValue == newValue) return; if (adornerLayer != null) { this.ClearAdorners(); adornerLayer.Add(newValue); } } /// <summary> /// The <see cref="Adorner" /> to adorn this <see cref="SelfAdorningFrameworkElement" /> with. /// </summary> [Description("The adorner to adorn this element with.")] [Category("Common")] public Adorner Adorner { get { return (Adorner)GetValue(AdornerProperty); } set { SetValue(AdornerProperty, value); } } /// <summary> /// Adorns this element with the adorner specified in <see cref="Adorner" />. /// </summary> /// <param name="e">The <see cref="EventArgs" /> that contains the event data.</param> protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); if (Adorner == null) Adorner = new SpriteAdorner(this); adornerLayer = AdornerLayer.GetAdornerLayer(this); try { adornerLayer.Add(Adorner); } catch (NullReferenceException ex) { ex.LogAndSendExceptionNotification(); } } /// <summary> /// Removes the adorner from the adorner layer. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Removes the adorner from the adorner layer. /// </summary> /// <param name="disposing"> /// If true, disposes of managed and unmanaged resources. If false, only disposes of /// unmanaged resources. /// </param> protected virtual void Dispose(bool disposing) { if (disposing) if (adornerLayer != null) adornerLayer.Remove(Adorner); } } }
df0538d1132a4e77a0d32b9232463611293e3b4d
C#
shendongnian/download4
/code4/678011-16252715-39799161-2.cs
2.84375
3
static private dynamic[] testSet = new dynamic[] { 5L, 4D, 3F, null, 2U, 1M, null, 0UL }; static void Main(string[] args) { Stopwatch st1 = new Stopwatch(); st1.Start(); for(int i = 0; i < 100000; i++) Test1(); st1.Stop(); Stopwatch st2 = new Stopwatch(); st2.Start(); for(int i = 0; i < 100000; i++) Test2(); st2.Stop(); } static public void Test1() { var result = testSet.OrderBy(x => x == null ? (decimal?)null : (decimal)x).ToArray(); } static public void Test2() { var result = testSet.OrderBy(x => (object)x, new HeterogeneousNumbersComparer()).ToArray(); } public class HeterogeneousNumbersComparer : IComparer<object> { public int Compare(object a, object b) { if (a == null) if (b == null) return 0; else return -1; else if (b == null) return +1; if (a.GetType() == b.GetType()) { switch(Type.GetTypeCode(a.GetType())) { case TypeCode.Byte: return ((Byte)a).CompareTo((Byte)b); case TypeCode.Decimal: return ((Decimal)a).CompareTo((Decimal)b); case TypeCode.Double: return ((Double)a).CompareTo((Double)b); case TypeCode.Int16: return ((Int16)a).CompareTo((Int16)b); case TypeCode.Int32: return ((Int32)a).CompareTo((Int32)b); case TypeCode.Int64: return ((Int64)a).CompareTo((Int64)b); case TypeCode.SByte: return ((SByte)a).CompareTo((SByte)b); case TypeCode.Single: return ((Single)a).CompareTo((Single)b); case TypeCode.UInt16: return ((UInt16)a).CompareTo((UInt16)b); case TypeCode.UInt32: return ((UInt32)a).CompareTo((UInt32)b); case TypeCode.UInt64: return ((UInt64)a).CompareTo((UInt64)b); } } return Convert.ToDecimal(a).CompareTo(Convert.ToDecimal(b)); } } }
872e48b9a7778c277494a28faef6f41de42817a5
C#
augomat/projectTracker
/ProjectTracker/Storage/WorktimeRecord.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LiteDB; namespace ProjectTracker { public class WorktimeRecord : IStorageClass { [BsonId] public int storageID { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public string ProjectName { get; set; } public string Comment { get; set; } public WorktimeRecord() { } //needed for LiteDB public WorktimeRecord(DateTime start, DateTime end, string projectName, string comment) { Start = start; End = end; ProjectName = projectName; Comment = comment; } public WorktimeRecord(WorktimeRecord wtr) : this(wtr.Start, wtr.End, wtr.ProjectName, wtr.Comment) { } public override string ToString() { return String.Format("Start: {0}, End: {1}, Project: {2}, Comment: {3}", Start.ToString(), End.ToString(), ProjectName, Comment); } public override bool Equals(object obj) { var cmp = (WorktimeRecord)obj; return (cmp.Start == this.Start && cmp.End == this.End && cmp.ProjectName == this.ProjectName && cmp.Comment == this.Comment); } public override int GetHashCode() { return Start.GetHashCode() ^ End.GetHashCode() ^ ProjectName.GetHashCode() ^ Comment.GetHashCode(); } } }
20c8baa6151eda53545381a3b49c2bddd7dda0fd
C#
djeebus/MusicHub
/MusicHub.ConsoleApp/BotCommands/MostLovedUsers.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MusicHub.ConsoleApp.BotCommands { public class MostLovedUsers : BaseCommand { public override string Command { get { return "most-loved-users"; } } private readonly IAffinityTracker _affinityTracker; public MostLovedUsers(IAffinityTracker affinityTracker) { _affinityTracker = affinityTracker; } public override void ExecuteCommand(IrcDotNet.IrcClient client, IrcDotNet.IIrcMessageSource source, IList<IrcDotNet.IIrcMessageTarget> targets, string command, IList<string> parameters) { var users = _affinityTracker.GetMostLovedUsers(); Action<string> say = msg => client.LocalUser.SendMessage(targets, msg); say(string.Format("The {0} most loved users are:", users.Length)); for (int x = 0; x < users.Length; x++) say(string.Format("{0}) {1}", x + 1, users[x])); } } }
5d99d07f075733b0f701a8971b26d6c74ab127b2
C#
fvalverd/High-Level-MANET-Protocol
/source/winx86/NetLayer/SystemHandler.cs
2.640625
3
using System; using System.Collections.Generic; using System.Net; using System.Runtime.InteropServices; using System.Management; using System.Net.NetworkInformation; using SystemInterop; using System.Threading; namespace NetLayer { /// <summary> /// Clase con mtodos de comunicacin con el sistema operativo /// </summary> public class SystemHandler { /// <summary> /// Cambia la IP del sistema operativo al estdo dinmico /// Si ocurre un error se arroja la excepcin /// </summary> internal static void setDinamicIP(NetworkAdapter networkAdapter) { if (networkAdapter == null) { throw new Exception("no hay un adaptador de red seleccionado"); } ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { try { if (((UInt32)objMO["Index"]) == networkAdapter.Index) { //metodo que pertenecen a Win32_NetworkAdapterConfiguration ManagementBaseObject enableDinamic = objMO.GetMethodParameters("EnableDHCP"); ManagementBaseObject result = objMO.InvokeMethod("EnableDHCP", enableDinamic, null); if (((UInt32)result["returnValue"]) != 0) { throw new Exception("EnableDHCP: " + getManagementMessage(((UInt32)result["returnValue"]))); } break; } } catch (ThreadAbortException e) { throw e; } catch (Exception e) { throw new Exception("error en el adaptador de red: " + objMO["Description"] + ": " + e.Message); } } } /// <summary> /// Cambia la Ip del sistema operativo a la configuracin de red adhoc /// Si ocurre un error se arroja la excepcin /// </summary> internal static void setStaticIP(NetworkAdapter networkAdapter, String ip, String subnetMask) { if (networkAdapter == null) { throw new Exception("no hay un adaptador de red seleccionado"); } //Invoca los metodos nativos de Windows ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if (((UInt32)objMO["Index"]) == networkAdapter.Index) { //metodo que pertenecen a Win32_NetworkAdapterConfiguration ManagementBaseObject enableStatic = objMO.GetMethodParameters("EnableStatic"); //parametros EnableStatic enableStatic["IPAddress"] = new string[] { ip }; enableStatic["SubnetMask"] = new string[] { subnetMask }; //ejecuta EnableStatic ManagementBaseObject result = objMO.InvokeMethod("EnableStatic", enableStatic, null); if (((UInt32)result["returnValue"]) != 0) { throw new Exception("EnableStatic: " + getManagementMessage(((UInt32)result["returnValue"]))); } break; } } } /// <summary> /// Cambia la Ip del sistema operativo a la configuracin de red adhoc, segundo metodo /// Si ocurre un error se arroja la excepcin /// </summary> internal static void setStaticIP2(NetworkAdapter networkAdapter, String ip, String subnetMask) { if (networkAdapter == null) { throw new Exception("no hay un adaptador de red seleccionado"); } //Invoca los metodos nativos de Windows ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if (((UInt32)objMO["Index"]) == networkAdapter.Index) { //metodo que pertenecen a Win32_NetworkAdapterConfiguration ManagementBaseObject enableStatic = objMO.GetMethodParameters("EnableStatic"); //parametros EnableStatic enableStatic["IPAddress"] = new string[] { ip }; enableStatic["SubnetMask"] = new string[] { subnetMask }; //ejecuta EnableStatic ManagementBaseObject result = objMO.InvokeMethod("EnableStatic", enableStatic, null); if (((UInt32)result["returnValue"]) != 0) { throw new Exception("EnableStatic: " + getManagementMessage(((UInt32)result["returnValue"]))); } break; } } } /// <summary> /// Cambia el estado del adaptador de red a encendido /// Si ocurre un error se arroja la excepcin /// </summary> internal static void enableIpAdapter(NetworkAdapter networkAdapter) { if (networkAdapter == null) { throw new Exception("no hay un adaptador de red seleccionado"); } ManagementClass objMC = new ManagementClass("Win32_NetworkAdapter"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { try { if (((UInt32)objMO["Index"]) == networkAdapter.Index) { //enable ManagementBaseObject enable = objMO.GetMethodParameters("Enable"); ManagementBaseObject resultEnable = objMO.InvokeMethod("Enable", enable, null); if (((UInt32)resultEnable["returnValue"]) != 0) { throw new Exception("EnableNetworkAdapter: " + (UInt32)resultEnable["returnValue"]); } break; } } catch (ThreadAbortException e) { throw e; } catch (Exception e) { throw new Exception("error en el adaptador de red: " + objMO["Description"] + ": " + e.Message); } } } /// <summary> /// Cambia el estado del adaptador de red a apagado /// Si ocurre un error se arroja la excepcin /// </summary> internal static void disableIpAdapter(NetworkAdapter networkAdapter) { if (networkAdapter == null) { throw new Exception("no hay un adaptador de red seleccionado"); } ManagementClass objMC = new ManagementClass("Win32_NetworkAdapter"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { try { if (((UInt32)objMO["Index"]) == networkAdapter.Index) { //disable ManagementBaseObject disable = objMO.GetMethodParameters("Disable"); ManagementBaseObject resultDisable = objMO.InvokeMethod("Disable", disable, null); if (((UInt32)resultDisable["returnValue"]) != 0) { throw new Exception("DisableNetworkAdapter: " + (UInt32)resultDisable["returnValue"]); } break; } } catch (ThreadAbortException e) { throw e; } catch (Exception e) { throw new Exception("error en el adaptador de red: " + objMO["Description"] + ": " + e.Message); } } } /// <summary> /// Obtiene el estado DAD de la Ip asignada a TCP /// </summary> /// <returns>un estado de la clase IpState</returns> internal static int getIpState(NetworkAdapter networkAdapter, IPAddress ipAdress) { int ipState = IpState.NOTFOUND; NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { if (adapter.Id.Equals(networkAdapter.Id)) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; foreach (UnicastIPAddressInformation uni in uniCast) { if (uni.Address.ToString().Equals(ipAdress.ToString())) { switch (uni.DuplicateAddressDetectionState) { case DuplicateAddressDetectionState.Deprecated: { ipState = IpState.INVALID; break; } case DuplicateAddressDetectionState.Duplicate: { ipState = IpState.DUPLICATE; break; } case DuplicateAddressDetectionState.Invalid: { ipState = IpState.INVALID; break; } case DuplicateAddressDetectionState.Preferred: { ipState = IpState.VALID; break; } case DuplicateAddressDetectionState.Tentative: { ipState = IpState.INVALID; break; } } break; } } break; } } return ipState; } /// <summary> /// Obtiene el numero de bytes enviados por el adaptador /// </summary> /// <param name="networkAdapter">el adaptador de red</param> /// <returns>el numero de bytes enviados</returns> internal static Int64 getAliveValue(NetworkAdapter networkAdapter) { Int64 n = 0; NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { if (adapter.Id.Equals(networkAdapter.Id)) { n = adapter.GetIPv4Statistics().NonUnicastPacketsReceived; break; } } return n; } /// <summary> /// Obtiene el numero de bytes enviados por el adaptador /// </summary> /// <param name="networkAdapter">el adaptador de red</param> /// <returns>el numero de bytes enviados</returns> internal static bool isOperative(NetworkAdapter networkAdapter) { bool b = false; NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { if (adapter.Id.Equals(networkAdapter.Id)) { b = (adapter.OperationalStatus == OperationalStatus.Up); break; } } return b; } /// <summary> /// Busca el adaptador de red WIFI /// </summary> /// <returns>El adaptador de red Wifi</returns> public static NetworkAdapter getWifiAdapter() { try { WlanClient wLanClient = new WlanClient(); foreach (WlanClient.WlanInterface wlanIface in wLanClient.Interfaces) { if (wlanIface.NetworkInterface != null) { NetworkAdapter adapter = new NetworkAdapter(); adapter.Id = wlanIface.NetworkInterface.Id; adapter.Description = wlanIface.InterfaceDescription; ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { String id = (String)objMO["SettingID"]; if(adapter.Id.Equals(id)) { adapter.Index = (UInt32)objMO["Index"]; return adapter; } } } } return null; } catch (ThreadAbortException e) { throw e; } catch (Exception e) { throw e; } } /// <summary> /// Retorna una lista de adaptadores de red disponibles en la mquina /// Si ocurre un error se arroja una Excepcin /// </summary> /// <returns></returns> public static List<NetworkAdapter> getNetworkAdapters() { try { List<NetworkAdapter> adapters = new List<NetworkAdapter>(); ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if(true) { NetworkAdapter adapter = new NetworkAdapter(); adapter.Id = (String)objMO["SettingID"]; adapter.Description = (String)objMO["Description"]; adapter.Index = (UInt32)objMO["Index"]; adapters.Add(adapter); } } return adapters; } catch (ThreadAbortException e) { throw e; } catch (Exception e) { throw e; } } /// <summary> /// Obtiene el texto de un error de sistema de windows a partir del cdigo de error /// Si ocurre un error se arroja una Excepcin /// </summary> /// <param name="index">el cdigo de error</param> /// <returns>El texto con la descripcin del error</returns> private static String getManagementMessage(UInt32 index) { try { switch (index) { case 0: { return "Successful completion, no reboot required."; } case 1: { return "Successful completion, reboot required."; } case 64: { return "Method not supported on this platform."; } case 65: { return "Unknown failure."; } case 66: { return "Invalid subnet mask."; } case 67: { return "An error occurred while processing an instance that was returned."; } case 68: { return "Invalid input parameter."; } case 69: { return "More than five gateways specified."; } case 70: { return "Invalid IP address."; } case 71: { return "Invalid gateway IP address."; } case 72: { return "An error occurred while accessing the registry for the requested information."; } case 73: { return "Invalid domain name."; } case 74: { return "Invalid host name."; } case 75: { return "No primary or secondary WINS server defined."; } case 76: { return "Invalid file."; } case 77: { return "Invalid system path."; } case 78: { return "File copy failed."; } case 79: { return "Invalid security parameter."; } case 80: { return "Unable to configure TCP/IP service."; } case 81: { return "Unable to configure DHCP service."; } case 82: { return "Unable to renew DHCP lease."; } case 83: { return "Unable to release DHCP lease."; } case 84: { return "IP not enabled on adapter."; } case 85: { return "IPX not enabled on adapter."; } case 86: { return "Frame or network number bounds error."; } case 87: { return "Invalid frame type."; } case 88: { return "Invalid network number."; } case 89: { return "Duplicate network number."; } case 90: { return "Parameter out of bounds."; } case 91: { return "Access denied."; } case 92: { return "Out of memory."; } case 93: { return "Already exists."; } case 94: { return "Path, file, or object not found"; } case 95: { return "Unable to notify service."; } case 96: { return "Unable to notify DNS service."; } case 97: { return "Interface not configurable."; } case 98: { return "Not all DHCP leases could be released or renewed."; } case 100: { return "DHCP not enabled on adapter."; } default: { return "Unknown error. Win32Code: " + index; } } } catch (ThreadAbortException e) { throw e; } catch (Exception e) { throw e; } } } }
4cab155dcc9ed25077f35c3f398728da6d727e71
C#
cffitzgi/cowboy-cafe
/DataTests/PropertyChangedTests/CowboyCoffeePropertyChangedTests.cs
2.71875
3
using System; using System.Collections.Generic; using System.Text; using Xunit; using CowboyCafe.Data; using CowboyCafe.Data.Entrees; using CowboyCafe.Data.Sides; using CowboyCafe.Data.Drinks; using System.ComponentModel; namespace CowboyCafe.DataTests.PropertyChangedTests { public class CowboyCoffeePropertyChangedTests { [Fact] public void CowboyCoffeeShouldImplementINotifyPropertyChanged() { var coffee = new CowboyCoffee(); Assert.IsAssignableFrom<INotifyPropertyChanged>(coffee); } [Fact] public void ChangingSizeShouldInvokePropertyChanged() { var coffee = new CowboyCoffee(); Assert.PropertyChanged(coffee, "Size", () => { coffee.Size = Size.Large; }); Assert.PropertyChanged(coffee, "Size", () => { coffee.Size = Size.Medium; }); Assert.PropertyChanged(coffee, "Size", () => { coffee.Size = Size.Small; }); } [Fact] public void ChangingSizeShouldInvokePropertyChangeForPriceAndCalories() { var coffee = new CowboyCoffee(); Assert.PropertyChanged(coffee, "Price", () => { coffee.Size = Size.Large; }); Assert.PropertyChanged(coffee, "Calories", () => { coffee.Size = Size.Medium; }); } [Theory] [InlineData("RoomForCream")] [InlineData("Decaf")] public void ChangingPropertyShouldInvokePropertyChanged(string propertyName) { var coffee = new CowboyCoffee(); Assert.PropertyChanged(coffee, propertyName, () => { switch (propertyName) { case "RoomForCream": coffee.RoomForCream = true; break; case "Decaf": coffee.Decaf = true; break; } }); } [Fact] public void ChangingPropertyShouldInvokePropertyChangeForSpecialInstructions() { var coffee = new CowboyCoffee(); Assert.PropertyChanged(coffee, "SpecialInstructions", () => { coffee.RoomForCream = true; }); Assert.PropertyChanged(coffee, "SpecialInstructions", () => { coffee.Ice = true; }); } } }
6c768c62615c4b434d2d00cf3b7662ecd7cd851e
C#
ihristova11/TelerikAcademyAlpha
/01. MODULE 1/C# OOP/Exams/CSharp-OOP-16Jan2017/Telerik Academy/Academy/Models/Trainer.cs
3.171875
3
using System; using System.Collections.Generic; using System.Linq; using System.Security; using Academy.Models.Contracts; using Academy.Models.Utilities; namespace Academy.Models { public class Trainer : ITrainer { private string username; private const string PatternToPrint = "* Trainer:\n - Username: {0}\n - Technologies: {1}"; public Trainer(string username, string technologies) { this.Username = username; this.Technologies = technologies.Split(',').Select(x => x.Trim()).ToList(); } public string Username { get { return this.username; } set { Validator.CorrectName(value, Constants.MinUserNameLength , Constants.MaxUserNameLength, Constants.InvalidUserName); this.username = value; } } public IList<string> Technologies { get; set; } public override string ToString() { var technologies = string.Join("; ", this.Technologies); return string.Format(PatternToPrint, this.Username, technologies); } } }
2c2ef7bf49d9a2c255ff5c40f670df7e6df643b7
C#
ZerlenZhang/QuickStartTools
/Assets/ReadyGamerOne/Algorithm/Graph/TriangleMgr.cs
2.90625
3
using System.Collections.Generic; using UnityEngine; namespace ReadyGamerOne.Algorithm.Graph { public static class TriangleMgr { private static Dictionary<int, Triangle> id2Trianges = new Dictionary<int, Triangle>(); public static Triangle GetTriangle(int id) { foreach (var VARIABLE in id2Trianges) { if (VARIABLE.Key == id) return VARIABLE.Value; } return null; } public static Triangle GetTriangle(int pointid1, int pointid2, int pointid3) { foreach (var VARIABLE in id2Trianges) { var ids = VARIABLE.Value.PointIds; if (ids.Contains(pointid1) && ids.Contains(pointid2) && ids.Contains(pointid3)) return VARIABLE.Value; } var nt = new Triangle(pointid1, pointid2, pointid3); id2Trianges.Add(nt.id, nt); return nt; } public static Triangle GetTriangle(Point p1, Point p2, Point p3) { return GetTriangle(p1.id, p2.id, p3.id); } public static Triangle GetTriangle(Vector2 pos1, Vector2 pos2, Vector2 pos3) { return GetTriangle( PointMgr.GetPoint(pos1), PointMgr.GetPoint(pos2), PointMgr.GetPoint(pos3)); } public static Triangle GetTriangle(Point p, Line line) { return GetTriangle(p.id, line.pointIds[0], line.pointIds[1]); } } }
8fbd1a8d97a0d47e94ddd35dc805d139c47b6fe6
C#
jeuxjeux20/DongBall
/Assets/Scripts/AnnouncerManager.cs
2.703125
3
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class AnnouncerManager : MonoBehaviour { // Use this for initialization void Start() { StartCoroutine(AnnouncementCoroutine()); } // Update is called once per frame void Update() { } IEnumerator AnnouncementCoroutine() { while (true) { if (annoucements.Count == 0) { yield return new WaitUntil(() => { return annoucements.Count != 0; }); } else { var announce = annoucements.ConsumeNextPriority(); AudioSource source = gameObject.GetComponent<AudioSource>(); if (announce is GenericAnnoucement || announce is MultiKillAnnouncement) // soon { GameObject obj = (GameObject)Instantiate(Resources.Load("Announcer/AnnouncerGeneric"), GameObject.Find("Canvas").transform); obj.GetComponent<Text>().text = announce.Text; PlaySound(announce, source); yield return new WaitForSeconds(2f); obj.GetComponent<Animator>().Play("Done"); if (annoucements.Count > 0) { yield return new WaitForSeconds(1f); } } } } } private static void PlaySound(Annoucement announce, AudioSource source) { if (source.clip.name == announce.Type.ToString()) { source.Play(); } else { try { var sound = Resources.Load("Announcer/Sounds/" + announce.Type.ToString()); if (sound == null) { throw new Exception("The sound couldn't be found sry m8 but you need to add it !!"); } var castedSound = sound as AudioClip; if (castedSound == null) { Debug.LogError("idk but i cannot cast this (" + announce.Type.ToString() + ") to an audio clip :( : it is a " + sound.GetType()); throw new Exception("Cannot cast :("); } source.clip = castedSound; source.Play(); } catch (Exception e) { Debug.LogError("Something bad has occured while loading the sound: " + e.Message); } } } public enum AnnouncementType { EnemySlain, ItselfSlain, DoubleKill, TripleKill, QuadraKill, PentaKill, HexaKill, Other } public abstract class Annoucement : IPriorityHolder { public string Text { get; set; } public AnnouncementType Type { get; set; } public int Priority { get; set; } /* * Priority 0 = u hav slein an enemi - othar * Priority 1 = u hav ben slain * Priority 2-6 = Double, Triple, Quadra, Penta, Hexakill */ public static GenericAnnoucement FromEnemySlain() { return new GenericAnnoucement("u hav slein an enemi !!", AnnouncementType.EnemySlain, 0); } public static GenericAnnoucement FromItselfSlain() { return new GenericAnnoucement("u hav ben slain", AnnouncementType.ItselfSlain, 1); } public Annoucement() { } } public class GenericAnnoucement : Annoucement { public GenericAnnoucement(string text, AnnouncementType type = AnnouncementType.Other, int priority = 0) : base() { Text = text; Type = type; Priority = priority; } public GenericAnnoucement() : base() { } } public class MultiKillAnnouncement : Annoucement { public int Kills { get; private set; } public MultiKillAnnouncement(int kills) { if (kills < 2) { throw new ArgumentException("It is not a correct multikill : " + kills, "kills"); } if (kills > 6) { kills = 6; } switch (kills) { case 2: Type = AnnouncementType.DoubleKill; Text = "DOBEL KIL !"; break; case 3: Type = AnnouncementType.TripleKill; Text = "TRIPEL KIL !"; break; case 4: Type = AnnouncementType.QuadraKill; Text = "QUADRA KIL !"; break; case 5: Type = AnnouncementType.PentaKill; Text = "PINTAKIL !"; break; case 6: Type = AnnouncementType.HexaKill; Text = "HEXAKIL !"; break; default: throw new Exception("Wat, HOW DID U GET IN DEFAULT"); } Priority = kills; } } private AnnouncerQueue annoucements = new AnnouncerQueue(); private DateTime lastKill = DateTime.MinValue; private int killCount = 0; public void ShowEnemySlain() { if (killCount == 0 || DateTime.Now > lastKill + TimeSpan.FromSeconds(10)) { killCount = 1; annoucements.Add(Annoucement.FromEnemySlain()); } else { killCount++; annoucements.Add(new MultiKillAnnouncement(killCount)); } lastKill = DateTime.Now; } public void ShowItselfSlain() { annoucements.Add(Annoucement.FromItselfSlain()); } }
0868e9581c3c5cf0b935b4ae36e9bc17a7686725
C#
grigoryan98/Practise
/Stacks/Stacks/StackDemo.cs
3.328125
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stacks { public class StackDemo { public static void StackPush(Stack st, int a) { st.Push(a); Console.WriteLine($"Push {a}"); Console.WriteLine("Stack "); foreach (int c in st) Console.Write(c + " "); Console.WriteLine(); } public void StackPop(Stack st) { Console.WriteLine("Stack Pop"); int a = (int)st.Pop(); Console.WriteLine(a); Console.WriteLine("Stack"); foreach (int c in st) Console.Write(c + " "); Console.WriteLine(); } } }
afaa8e822a5d771612c044dd6e43a5f2677ee9a5
C#
akshay-shettar/Factory
/FactoryComparor/Factories/CharTypeFactory.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactoryComparor { public class CharTypeFactory : ComparorFactory<char> { private char _first; private char _second; public CharTypeFactory(char first, char second) { _first = first; _second = second; } public override char FindGreater() { return new CharType(_first, _second).FindGreater(); } } }
f3c8b88f7570fd4c69477c7d5e99d300f5ff7705
C#
Matias035/Rol_PlayGame_Testing_Eq.8
/tests/items/Test7.cs
2.65625
3
using NUnit.Framework; using RoleplayGame.Characters; using RoleplayGame.Items; namespace RoleplayGame.Library.Test { public class Test7 { [Test] public void WhenAddingMagicToACharacterItsAttackPowerGoesUp() { Elf elfo = new Elf("Eduardo"); Magic magia = new Magic(); elfo.AddItem(magia); int expectedAttackPower = 80; Assert.AreEqual(elfo.AttackPower, expectedAttackPower); } } }
6cced2d47b6a1a9156651707f2b09ece2c7ef7cd
C#
denysivanov/MillenniumManagement
/PositionCalculator/mlp.interviews.boxing.problem.Implementation/BoxedPosition/BoxedPositionCalculator.cs
2.65625
3
using System.Collections.Generic; using System.Linq; using mlp.interviews.boxing.problem.Interface.Entity; using mlp.interviews.boxing.problem.Interface.Interfaces; namespace mlp.interviews.boxing.problem.Implementation.BoxedPosition { public class BoxedPositionCalculator : IBoxedPositionCalculator { private readonly IOutputRecordConverter _outputRecordConverter; private readonly IBoxedPositionDetector _boxedPositionDetector; private readonly IBoxedPositionOutput _boxedPositionOutput; public BoxedPositionCalculator(IOutputRecordConverter outputRecordConverter, IBoxedPositionDetector boxedPositionDetector, IBoxedPositionOutput boxedPositionOutput) { _outputRecordConverter = outputRecordConverter; _boxedPositionDetector = boxedPositionDetector; _boxedPositionOutput = boxedPositionOutput; } public List<OutputRecord> Calculate(List<TestRecord> testResords) { var boxedPositions = testResords.Where(x => _boxedPositionDetector.IsBoxedPosition(testResords, x)); var convertedRecords = boxedPositions.Select(_outputRecordConverter.Convert); var returnRecords = _boxedPositionOutput.Get(convertedRecords); return returnRecords; } } }
53a902e2b9e3e794a0e27d0bff16d7b6e14c6dc6
C#
MrSchlag/bloodbender
/Bloodbender/RadianAngle.cs
3.15625
3
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bloodbender { public class RadianAngle { public float value; public RadianAngle(float value) { this.value = value; } public static Vector2 rotate(Vector2 origin, Vector2 point, RadianAngle angle) { return new Vector2( (float)(origin.X + Math.Cos(angle) * (point.X - origin.X) - Math.Sin(angle) * (point.Y - origin.Y)), (float)(origin.Y + Math.Sin(angle) * (point.X - origin.X) + Math.Cos(angle) * (point.Y - origin.Y)) ); } public static implicit operator float(RadianAngle radianAngle) { return radianAngle.value; } public static implicit operator RadianAngle(float f) { return new RadianAngle(f); } public static RadianAngle operator+ (RadianAngle a, RadianAngle b) { RadianAngle result = new RadianAngle(0); result.value = (float)((a.value + b.value + Math.PI) % (2 * Math.PI) - Math.PI); return result; } public static RadianAngle operator- (RadianAngle a, RadianAngle b) { RadianAngle result = new RadianAngle(0); result.value = (float)((a.value - b.value - Math.PI) % (2 * Math.PI) + Math.PI); return result; } } }
5b37a5d8d1add4e67b6bbb696d5088a965a532bc
C#
karstengresch/HexGridUtilitiesForGames
/codeplex/Utilities/Utils.cs
2.546875
3
#region The MIT License - Copyright (C) 2012-2013 Pieter Geerkens ///////////////////////////////////////////////////////////////////////////////////////// // PG Software Solutions Inc. - Hex-Grid Utilities ///////////////////////////////////////////////////////////////////////////////////////// // The MIT License: // ---------------- // // Copyright (c) 2012-2013 Pieter Geerkens (email: pgeerkens@hotmail.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, // merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. ///////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace PG_Napoleonics.Utilities { public static class Utils{ #region Enum Parsing utilities public static IEnumerable<TEnum> EnumGetValues<TEnum>() { return (IEnumerable<TEnum>)(Enum.GetValues(typeof(TEnum))); } public static T ParseEnum<T>(string value, bool checkConstants = true) { T enumValue; if (!TryParseEnum<T>(value, out enumValue) && checkConstants) ThrowInvalidDataException(typeof(T), enumValue); return enumValue; } public static bool TryParseEnum<T>(string value, out T enumValue) { enumValue = (T)Enum.Parse(typeof(T),value); return (Enum.IsDefined(typeof(T),enumValue)); } public static T EnumParse<T>(char c, string lookup) { var index = lookup.IndexOf(c); if (index == -1) ThrowInvalidDataException(typeof(T), c); return (T) Enum.ToObject(typeof(T), index); } #endregion #region ErrorThrowers public static void ThrowInvalidDataException(Type type, object data) { throw new InvalidDataException(string.Format("{0}: Invalid: '{1}'", type.Name, data)); } public static void ThrowInvalidDataException(string parseType, int lineNo, object section, string error, Exception ex, object data) { throw new InvalidDataException( string.Format("{0}: {3}\n for section {2} on line # {1}:\n {4}", parseType, lineNo, section, error, data), ex); } #endregion } }
400594dc2f1a4f783d6572d626c4d31b7efedfa7
C#
darvell/Coremero
/Coremero/Coremero/Storage/JsonCredentialStorage.cs
2.734375
3
using System.Diagnostics; using System.IO; using Coremero.Utilities; using Newtonsoft.Json.Linq; namespace Coremero.Storage { public class JsonCredentialStorage : ICredentialStorage { private readonly string _secretsPath = Path.Combine(PathExtensions.AppDir, "secrets.json"); public string GetKey(string keyName, string defaultKey = null) { if (!File.Exists(_secretsPath)) { Debug.Fail("No secrets file found!"); return defaultKey; } JObject config = JObject.Parse(File.ReadAllText(_secretsPath)); return config.Value<string>(keyName) ?? defaultKey; } } }
25755e1f777d40cf2b0363263b30daa2b44bca8d
C#
SimCitee/ProjetBD2
/ProjetBD/Collections/PlayerCollection.cs
3.03125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Oracle.DataAccess.Client; using ProjetBD.Models; namespace ProjetBD.Collections { class PlayerCollection { private static PlayerCollection _instance; private List<Player> _playerList; private PlayerCollection() { } public static PlayerCollection Instance() { if (_instance == null) _instance = new PlayerCollection(); return _instance; } public List<Player> Players { get { if (_playerList == null) { _playerList = new List<Player>(); } return _playerList; } } public void LoadPlayersFromDatabase(OracleConnection connection) { try { OracleCommand command = connection.CreateCommand(); command.CommandText = "SELECT Players.Id, Players.Firstname, Players.Lastname FROM Players"; connection.Open(); OracleDataReader reader = command.ExecuteReader(); while (reader.Read()) { Player player = new Player(reader["Firstname"].ToString(), reader["Lastname"].ToString(), Int32.Parse(reader["Id"].ToString())); Players.Add(player); } } catch (OracleException e) { throw e; } catch (Exception e) { throw e; } finally { if (connection != null) { connection.Close(); } } } } }
4806b36117b7db3c5c31fa1994e3ddd4a5b879dc
C#
VitaliiAndreev/WarThunder_PresetRandomizer
/Core.Json.Tests/Extensions/JArrayExtensionsTests.cs
2.765625
3
using Core.Json.Extensions; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; using System.Linq; namespace Core.Json.Tests.Extensions { /// <summary> See <see cref="JArrayExtensions"/>. </summary> [TestClass] public class JArrayExtensionsTests { #region Tests: AddIndividually() [TestMethod] public void AddNonIndividually() { // arrange var targetJsonArray = new JArray(1, 2, 3); var sourceJsonArray = new JArray(4, 5, 6); var initialCount = sourceJsonArray.Count(); // act targetJsonArray.Add(sourceJsonArray); // assert targetJsonArray.Count().Should().Be(initialCount + 1); targetJsonArray.Last().Should().BeEquivalentTo(sourceJsonArray); } [TestMethod] public void AddIndividually() { // arrange var targetJsonArray = new JArray(1, 2, 3); var sourceJsonArray = new JArray(4, 5, 6); // act targetJsonArray.AddIndividually(sourceJsonArray); // assert targetJsonArray.Should().BeEquivalentTo(new JArray(1, 2, 3, 4, 5, 6)); } #endregion Tests: AddIndividually() } }
da149bd055e1dc547d090199605ab0df3c1f8564
C#
axelma199/Proyecto.NET
/Servidor_AlejandroVenegas/ConexionBD/CajeroBD.cs
2.75
3
using Entidades_AlejandroVenegas.Objetos; using Servidor_AlejandroVenegas.Objetos; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace Tarea2_AlejandroVenegas.ConexionBD { class CajeroBD : Conexion { public bool insertar(Cajero c) { try { using (SqlConnection conn = new SqlConnection(conexion)) { conn.Open(); String query = "Insert BuenPrecio.dbo.Cajero(identificacion, nombre, primerapellido, segundoapellido, cajaasignada,estado) values(@identificacion, @nombre, @primerapellido, @segundoapellido, @cajaasignada,@estado)"; SqlCommand newCmd = new SqlCommand(query, conn); newCmd.CommandType = CommandType.Text; newCmd.Parameters.AddWithValue("@identificacion", c.getIdentificacion()); newCmd.Parameters.AddWithValue("@nombre", c.getNombre()); newCmd.Parameters.AddWithValue("@primerapellido", c.getPrimerApellido()); newCmd.Parameters.AddWithValue("@segundoapellido", c.getSegundoApellido()); newCmd.Parameters.AddWithValue("@cajaasignada", c.cajaAsignada); newCmd.Parameters.AddWithValue("@estado", c.activo); newCmd.ExecuteNonQuery(); conn.Close(); } } catch (SqlException s) { Console.WriteLine(s); return false; } return true; } public bool validarCajasAsignadas(int caja) { List<int> listaCajas = new List<int>(); bool existeCaja = false; try { using (SqlConnection connection = new SqlConnection(conexion)) { connection.Open(); string queryString = "Select CajaAsignada from BuenPrecio.dbo.Cajero where CajaAsignada=" + caja + ";"; SqlCommand command = new SqlCommand(queryString, connection); SqlDataReader oReader = command.ExecuteReader(); while (oReader.Read()) { listaCajas.Add(int.Parse(oReader["CajaAsignada"].ToString())); } connection.Close(); if (listaCajas.Count != 0) existeCaja = true; } } catch (SqlException s) { Console.WriteLine(s); return false; } return existeCaja; } public List<Cajero> listarCajeros() { List<Cajero> listaCajeros = new List<Cajero>(); try { using (SqlConnection connection = new SqlConnection(conexion)) { connection.Open(); string queryString = "Select * from BuenPrecio.dbo.Cajero where estado=1;"; SqlCommand command = new SqlCommand(queryString, connection); SqlDataReader oReader = command.ExecuteReader(); while (oReader.Read()) //Lee registros en base de datos hasta que se termine. { Cajero c = null; if (oReader["estado"].ToString() == "True") { c = new Cajero(oReader["Identificacion"].ToString(), oReader["Nombre"].ToString(), oReader["PrimerApellido"].ToString(), oReader["SegundoApellido"].ToString(), int.Parse(oReader["CajaAsignada"].ToString()), true); } else { c = new Cajero(oReader["Identificacion"].ToString(), oReader["Nombre"].ToString(), oReader["PrimerApellido"].ToString(), oReader["SegundoApellido"].ToString(), int.Parse(oReader["CajaAsignada"].ToString()), false); } listaCajeros.Add(c); } connection.Close(); } } catch (SqlException s) { Console.WriteLine(s); return null; } return listaCajeros; } public List<Cajero> listarCajerosNoAprobados() //Extrae de la base de datos solamente a los cajeros no aprobados todavía. { List<Cajero> listaCajeros = new List<Cajero>(); try { using (SqlConnection connection = new SqlConnection(conexion)) { connection.Open(); string queryString = "Select * from BuenPrecio.dbo.Cajero where estado=0;"; SqlCommand command = new SqlCommand(queryString, connection); SqlDataReader oReader = command.ExecuteReader(); while (oReader.Read()) //Lee registros en base de datos hasta que se termine. { bool estado = false; if (oReader["estado"].ToString() == "True") estado = true; Cajero c = new Cajero(oReader["Identificacion"].ToString(), oReader["Nombre"].ToString(), oReader["PrimerApellido"].ToString(), oReader["SegundoApellido"].ToString(), int.Parse(oReader["CajaAsignada"].ToString()), estado); listaCajeros.Add(c); } connection.Close(); } } catch (SqlException s) { Console.WriteLine(s); return null; } return listaCajeros; } internal bool aprobarCajero(string id, int cajaAsig) { if (validarExistenciaCajero(id)) { try { if (!validarCajasAsignadas(cajaAsig)) { using (SqlConnection conn = new SqlConnection(conexion)) { conn.Open(); String query = "Update BuenPrecio.dbo.Cajero set estado=1,CajaAsignada=" + cajaAsig + "where identificacion='" + id + "' and estado=0;"; //Aprueba sólo cajeros con estado en cero. SqlCommand newCmd = new SqlCommand(query, conn); newCmd.CommandType = CommandType.Text; newCmd.ExecuteNonQuery(); conn.Close(); string message = "Aprobación de cajero exitosa."; string title = "Mensaje"; MessageBox.Show(message, title); } } else { string message2 = "Error, caja ya esta siendo asignada por otro cliente."; string title2 = "Mensaje"; MessageBox.Show(message2, title2); } } catch (SqlException s) { Console.WriteLine(s); return false; } } return true; } public bool validarExistenciaCajero(String id) { string estado = "False"; try { using (SqlConnection connection = new SqlConnection(conexion)) { connection.Open(); string queryString = "Select identificacion from BuenPrecio.dbo.cajero where identificacion='" + id + "';"; SqlCommand command = new SqlCommand(queryString, connection); SqlDataReader oReader = command.ExecuteReader(); while (oReader.Read()) //Lee registros en base de datos hasta que se termine. { estado = oReader["identificacion"].ToString(); } connection.Close(); if (estado == "False") { string message = "Error, cajero no existe."; string title = "Mensaje"; MessageBox.Show(message, title); return false; } else { return true; } } } catch (SqlException s) { Console.WriteLine(s); return false; } } } }
58a82e19903cce044bcff41477f8c9d464ddbab5
C#
agaddampalli/Algorithms
/Chapter 2 - Arrays/LexicographicOrder.linq
3.46875
3
<Query Kind="Program" /> void Main() { var input = "271435"; var length = factorial(input.Length); LexicographicOrder(input); } public int factorial(int n) { if(n == 0 || n == 1) { return 1; } return n * factorial(n-1); } public void LexicographicOrder(string input) { bool finished = false; var s = new StringBuilder(input); while(!finished) { s.ToString().Dump(); int x = -1; int y = -1; //step1 for (int i = 0; i < s.Length - 1; i++) { if (s[i] < s[i + 1]) { x = i; } } if(x == -1) { finished = true; } else { //step 2 for (int i = 0; i < s.Length; i++) { if (s[x] < s[i]) { y = i; } } Swap(s, x, y); Reverse(s, x + 1, s.Length - 1); } } } public void Swap(StringBuilder builder, int i, int j) { var temp = builder[j]; builder[j] = builder[i]; builder[i] = temp; } public void Reverse(StringBuilder s, int start, int end) { while(start < end) { Swap(s, start++, end--); } }
43950b7e997f8d5a3f30b3408aa383ddb78088d7
C#
h0l0tn1k/Minesweeper
/WindowsFormsApplication1/Classes/ILogExporter.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Minesweeper { /// <summary> /// Interface for Exporting logs /// </summary> /// <typeparam name="T">Type of input objects</typeparam> public interface ILogExporter<T> where T : class, new() { /// <summary> /// Exports List of T objects into file in json format /// </summary> /// <param name="data">list of objects T</param> void Export(List<T> data); } }
3b9e42a327b80c66a034c2941f2f506c5af02553
C#
shanecelis/PshSharp
/src/TestCase/FloatRegTestCases2.cs
2.765625
3
using System; using Psh; namespace Psh.TestCase { public class FloatRegTestCases2 : TestCaseGenerator { private static int _testCaseCount = 200; private float[] _testCasesX = null; private float[] _testCasesY = null; private static float _firstSample = -3; private static float _lastSample = 3; public override int TestCaseCount() { return _testCaseCount; } public override ObjectPair TestCase(int inIndex) { if (_testCasesX == null) { _testCasesX = new float[_testCaseCount]; _testCasesY = new float[_testCaseCount]; for (int i = 0; i < _testCaseCount; i++) { _testCasesX[i] = XValue(i); _testCasesY[i] = TestCaseFunction(_testCasesX[i]); } } return new ObjectPair(_testCasesX[inIndex], _testCasesY[inIndex]); } private float XValue(float i) { return (float)_firstSample + (((_lastSample - _firstSample) / (_testCaseCount - 1)) * i); } private float TestCaseFunction(float x) { return (float)(Math.Exp(Math.Abs(x)) * Math.Sin(2.0 * Math.PI * x)); } } }
ef8b30f35728e782581f4e691de4b6fd36031516
C#
ibanknatoPrad/Voyager-Golden-Record-Decoder
/VoyagerImageDecoder/VoyagerReader3.cs
2.546875
3
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace VoyagerImageDecoder { public class VoyagerReader3 { private PictureBox pictureBox1; private PictureBox pictureBox2; private int x, y, d; public VoyagerReader3(PictureBox pictureBox1, PictureBox pictureBox2) { this.pictureBox1 = pictureBox1; this.pictureBox2 = pictureBox2; List<Segment> startLocations = new List<Segment>() { new Segment() { Channel = Channel.Left, Header = 88, CurrentPosition = 0, StartSample = 6000208, LengthSample = 1928181, WindowLengthSample = 3400 }, new Segment() { Channel = Channel.Right, Header = 88, CurrentPosition = 0, StartSample = 6503334, LengthSample = 1841946, WindowLengthSample = 3400 }, new Segment() { Channel = Channel.Left, Header = 88, CurrentPosition = 0, StartSample = 8312903, LengthSample = 1946880, WindowLengthSample = 3400 }, new Segment() { Channel = Channel.Right, Header = 88, CurrentPosition = 0, StartSample = 8657173, LengthSample = 1908929, WindowLengthSample = 3400 }, new Segment() { Channel = Channel.Left, Header = 88, CurrentPosition = 0, StartSample = 21715098, LengthSample = 1787198, WindowLengthSample = 3400 }, new Segment() { Channel = Channel.Left, Header = 88, CurrentPosition = 0, StartSample = 28675794, LengthSample = 1821805, WindowLengthSample = 3400 }, new Segment() { Channel = Channel.Right, Header = 88, CurrentPosition = 0, StartSample = 30786540, LengthSample = 1834844, WindowLengthSample = 3400 } }; foreach (Segment s in startLocations) { s.Start = (s.StartSample * 8) + s.Header; s.Length = s.LengthSample * 8; s.WindowLength = s.WindowLengthSample * 8; ReadWav(s); } } private void ReadWav(Segment s) { FileStream fr = new FileStream(@"C:\384kHzStereo.wav", FileMode.Open); WindowReader wr = null; Bitmap leftImage = null; Bitmap rightImage = null; if (s.Channel == Channel.Left) leftImage = new Bitmap(512, 384, PixelFormat.Format32bppArgb); else rightImage = new Bitmap(512, 384, PixelFormat.Format32bppArgb); x = 0; y = 0; for (int i = 0; i < 512; i++) { if (wr == null) { wr = new WindowReader(); wr.Segment = s; wr.PeakStart = 0; wr.Segment.CurrentPosition = wr.Segment.Start; fr.Seek(wr.Segment.Start, System.IO.SeekOrigin.Begin); } else { wr.Segment.CurrentPosition += wr.PeakEnd * 8; fr.Seek(wr.Segment.CurrentPosition, System.IO.SeekOrigin.Begin); } if (wr.Segment.CurrentPosition + wr.Segment.WindowLength >= wr.Segment.Start + wr.Segment.Length) { continue; } wr.Samples = new byte[wr.Segment.WindowLength]; fr.Read(wr.Samples, 0, wr.Samples.Length); Tuple<byte[], byte[]> data = SplitChannels(wr.Samples); if (wr.Segment.Channel == Channel.Left) { wr = ProcessData(data.Item1, wr); GenerateImage(wr.DataSum, ref leftImage); } else { wr = ProcessData(data.Item2, wr); GenerateImage(wr.DataSum, ref rightImage); } } fr.Close(); if (leftImage != null) { pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage; pictureBox1.Image = leftImage; pictureBox1.Invalidate(); pictureBox1.Update(); pictureBox1.Refresh(); //MakeGrayscale3(leftImage).Save(@"C:\2.png", ImageFormat.Png); } if (rightImage != null) { pictureBox2.SizeMode = PictureBoxSizeMode.CenterImage; pictureBox2.Image = rightImage; pictureBox2.Invalidate(); pictureBox2.Update(); pictureBox2.Refresh(); } } public static Bitmap MakeGrayscale3(Bitmap original) { //create a blank bitmap the same size as original Bitmap newBitmap = new Bitmap(original.Width, original.Height); //get a graphics object from the new image Graphics g = Graphics.FromImage(newBitmap); //create the grayscale ColorMatrix ColorMatrix colorMatrix = new ColorMatrix( new float[][] { new float[] {.3f, .3f, .3f, 0, 0}, new float[] {.59f, .59f, .59f, 0, 0}, new float[] {.11f, .11f, .11f, 0, 0}, new float[] {0, 0, 0, 1, 0}, new float[] {0, 0, 0, 0, 1} }); //create some image attributes ImageAttributes attributes = new ImageAttributes(); //set the color matrix attribute attributes.SetColorMatrix(colorMatrix); //draw the original image on the new image //using the grayscale color matrix g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); //dispose the Graphics object g.Dispose(); return newBitmap; } private void GenerateImage(float[] data, ref Bitmap img) { OffsetColor(data); for (int i = 0; i < data.Length; i++) { Color c; if (data[i] >= 0) c = GreyscaleMapper(data[i]); else c = Color.White; if (y > img.Height - 1) { y = 0; x++; } if (x > img.Width - 1) x = 0; img.SetPixel(x, y++, c); } } public Color GreyscaleMapper(float data) { int i = 0; //1.0f = black return Color.FromArgb((int)(200 - (255 * (data / d))), 0, 0, 0); } public float[] OffsetColor(float[] data) { float b = data.Min(); for (int i = 0; i < data.Length; i++) data[i] += Math.Abs(b); return data; } private Tuple<byte[], byte[]> SplitChannels(byte[] bytes) { byte[] left = new byte[bytes.Length / 2]; byte[] right = new byte[bytes.Length / 2]; int index = 0; for (int i = 0; i < left.Length; i += 4) { left[i] = bytes[index++]; left[i + 1] = bytes[index++]; left[i + 2] = bytes[index++]; left[i + 3] = bytes[index++]; right[i] = bytes[index++]; right[i + 1] = bytes[index++]; right[i + 2] = bytes[index++]; right[i + 3] = bytes[index++]; } return new Tuple<byte[], byte[]>(left, right); } private WindowReader ProcessData(byte[] data, WindowReader wr) { float[] dataInt = ConvertFromByteArrayToFloatArray(data); dataInt = Invert(dataInt); wr.PeakStart = FindPeak(dataInt); wr.PeakEnd = FindPeakLow(dataInt); float[] newData = new float[wr.PeakEnd - wr.PeakStart]; Array.Copy(dataInt, wr.PeakStart, newData, 0, newData.Length); d = (wr.PeakEnd - wr.PeakStart) / 384; wr.DataSum = PixelPack(newData, d); return wr; } private float[] Invert(float[] data) { for (int i = 0; i < data.Length; i++) data[i] = -data[i]; return data; } private float[] PixelPack(float[] data, int align) { float[] dataSum = new float[384]; int index = 0; for (int j = 0; j < dataSum.Length; j++) { for (int i = 0; i < align; i++) { dataSum[j] += data[index++]; } } return dataSum; } private int FindPeak(float[] data) { float b = float.MinValue; int index = 0; for (int i = 0; i < data.Length / 2; i++) { if (data[i] > b) { b = data[i]; index = i; } } return index; } private int FindPeakLow(float[] data) { float b = float.MaxValue; int index = 1000; for (int i = 1000; i < data.Length; i++) { if (data[i] < b) { b = data[i]; index = i; } } return index; } private float[] ConvertFromByteArrayToFloatArray(byte[] data) { float[] dataInt = new float[data.Length / 4]; int index = 0; for (int i = 0; i < data.Length; i += 4) { dataInt[index++] = System.BitConverter.ToSingle(data, i); } return dataInt; } } }
306dc19904bd0404b072749cad32247939da1a46
C#
shendongnian/download4
/code9/1577965-44086126-145835447-2.cs
2.796875
3
engine.Evaluate("x<-c(1:10)"); string[] text = engine.Evaluate("x").AsCharacter().ToArray(); StringBuilder builder = new StringBuilder(); foreach (string value in text) { builder.Append(value); } richTextBox1.Text = builder.ToString();
fdc7c72fcef5fad0c3c5f3ae90828bf6eb63d629
C#
Aidan63/smnclauncher
/smnclauncher/Utils/Patcher.cs
2.703125
3
using Newtonsoft.Json; using smnclauncher.Models; using System; using System.IO; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Security.Cryptography; namespace smnclauncher.Utils { static class Patcher { public static IObservable<double> Patch(string patchDirectory, string gameDirectory) { var update = JsonConvert.DeserializeObject<PatchFile>(File.ReadAllText(Path.Combine(patchDirectory, "patch.json"))); var changes = update.Add.Count + update.Delete.Count + update.Patch.Count; var obsAdd = update .Add .ToObservable() .Do(entry => { var src = patchDirectory + entry.Key; var dst = gameDirectory + entry.Value; if (File.Exists(dst)) { File.Delete(dst); } File.Copy(src, dst); }) .Select(_ => Unit.Default); var obsDelete = update .Delete .ToObservable() .Do(entry => { var dst = gameDirectory + entry; if (File.Exists(dst)) { File.Delete(dst); } }) .Select(_ => Unit.Default); var obsPatch = update .Patch .ToObservable() .Do(entry => { var src = patchDirectory + entry.Key; var dst = gameDirectory + entry.Value; switch (HashFile(dst)) { case string s when s == entry.NewHash: return; case string s when s != entry.OldHash: throw new Exception($"{src} hash does not match the expected value"); case string: var tempPatch = dst + ".tmp"; using (var baseFile = File.OpenRead(dst)) using (var deltaFile = File.OpenRead(src)) using (var tempFile = File.OpenWrite(tempPatch)) { OvermindRsync.RsyncInterface.PatchFile(baseFile, deltaFile, tempFile); } if (File.Exists(dst)) { File.Delete(dst); } if (HashFile(tempPatch) != entry.NewHash) { throw new Exception("Patched files hash does not match the expected hash"); } File.Move(tempPatch, dst); break; } }) .Select(_ => Unit.Default); return Observable .Merge(obsAdd, obsDelete, obsPatch) .Scan(0d, (acc, _) => acc + 1) .Select(acc => acc / changes); } public static string HashFile(string path) { using var provider = new SHA1CryptoServiceProvider(); using var stream = File.OpenRead(path); return BitConverter.ToString(provider.ComputeHash(stream)).Replace("-", string.Empty); } } }
f85bf0e8da2dff34a6c0f8e2efb71ddf3c03bd5e
C#
icebeam7/FutbolApp
/FutbolApp/FutbolApp.Android/Helpers/FileHelper.cs
2.546875
3
 using System; using System.IO; namespace FutbolApp.Droid.Helpers { public class FileHelper { public static string ObtenerRutaLocal(string archivo) { string ruta = Environment.GetFolderPath(Environment.SpecialFolder.Personal); return Path.Combine(ruta, archivo); } } }
37c7f0694b076d37c6f447cd9e4f79724a0f69a9
C#
jazziiilove/BookShelfWebApplication
/BookShelf.BusinessLogic/BookShelfUserManagerBLL.cs
2.71875
3
/* * Company: * Motto: Talk more to loved ones! * Assignment: A book shelf application * Deadline: 2012-01-02 * Programmer: Baran Topal * Solution name: .BookShelfWeb * Folder name: .BusinessLogic * Project name: .BookShelfWeb.BLL * File name: BookShelfUserManagerBLL.cs * Status: Finished */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using BookShelfWeb.BookShelfModel; using BookShelf.IBLL; using BookShelfWeb.DAL; using BookShelfWeb.Factory; using BookShelfWeb.IDAL; namespace BookShelf.BusinessLogic { /// <summary> /// BookShelfUser business layer manipulations /// </summary> public class BookShelfUserManagerBLL : IBookShelfUserManagerBLL { #region Add /// <summary> /// Add a user /// </summary> /// <param name="userEntity">user</param> /// <returns>true if success, false otherwise</returns> public bool AddUser(BookShelfUser userEntity) { try { return DALFactory.GetUserInterface<BookShelfUserDAL>().AddUser(userEntity) > 0; } catch (Exception) { return false; } } /// <summary> /// Add BookMembership for a user /// </summary> /// <param name="userID">user id</param> /// <param name="bookEntity">book</param> /// <returns>true if success, false otherwise</returns> public bool AddBookMembership(int userID, BookShelfBook bookEntity) { try { IBookShelfUserDAL objUser = DALFactory.GetUserInterface<BookShelfUserDAL>(); BookShelfUser objUserEntity = objUser.GetUserbyID(userID); if (null != objUserEntity) { objUserEntity.Books.Add(bookEntity); return objUser.UpdateUser(objUserEntity) > 0; } return false; } catch (Exception) { return false; } } #endregion Add #region Update /// <summary> /// Update user /// </summary> /// <param name="userEntity">user</param> /// <returns>true if success, false otherwise</returns> public bool UpdateUser(BookShelfUser userEntity) { try { return DALFactory.GetUserInterface<BookShelfUserDAL>().UpdateUser(userEntity) > 0; } catch (Exception ex) { return false; } } /// <summary> /// Update BookMembership by user id /// </summary> /// <param name="userID">user id</param> /// <param name="bookEntity">book</param> /// <param name="action">action</param> /// <returns>true if success, false otherwise</returns> public bool UpdateBookMembership(int userID, BookShelfBook bookEntity, string action) { try { if (DALFactory.GetUserInterface<BookShelfUserDAL>(userID).UpdateBookMembership(userID, bookEntity, action) > 0) return true; } catch (Exception ex) { return false; } return false; } #endregion Update #region Delete /// <summary> /// Delete a user /// </summary> /// <param name="userID">user id</param> /// <returns>true if success, false otherwise</returns> public bool DeleteUser(int userID) { try { IBookShelfUserDAL objUser = DALFactory.GetUserInterface<BookShelfUserDAL>(); return objUser.DeleteUser(userID) > 0; } catch (Exception) { return false; } } /// <summary> /// Delete Book for specific user/Return the book for the given user /// </summary> /// <param name="userID">user id</param> /// <param name="bookEntity">book</param> /// <returns>true if success, false otherwise</returns> public bool DeleteBookMembership(int userID, BookShelfBook bookEntity) { try { IBookShelfUserDAL objUser = DALFactory.GetUserInterface<BookShelfUserDAL>(); BookShelfUser objUserEntity = objUser.GetUserbyID(userID); if (null != objUserEntity) return objUserEntity.Books.Remove(bookEntity); else return false; } catch (Exception) { return false; } } #endregion Delete #region Get /// <summary> /// Get user by user id /// </summary> /// <param name="userId">user id</param> /// <returns>List of users, null if not found</returns> public BookShelfUser GetUserbyID(int userID) { return DALFactory.GetUserInterface<BookShelfUserDAL>(userID).GetUserbyID(userID); } /// <summary> /// Get user by user name /// </summary> /// <param name="fullName">full name</param> /// <returns>BookShelfUser, null if not found</returns> public BookShelfUser GetUserbyName(string fullName) { return DALFactory.GetUserInterface<BookShelfUserDAL>().GetUserbyName(fullName); } /// <summary> /// Get all user list /// </summary> /// <returns>list of users, empty list if not found</returns> public IList<BookShelfUser> GetUsers() { return (DALFactory.GetUserInterface<BookShelfUserDAL>().GetUsers()); } /// <summary> /// Get BookMembership by user id /// </summary> /// <param name="bookEntity">book entity</param> /// <returns>true if success, false otherwise</returns> public bool GetBookMembership(int userID, BookShelfBook bookEntity) { try { if (DALFactory.GetUserInterface<BookShelfUserDAL>().GetBookMembership(userID, bookEntity) > 0) return true; } catch (Exception) { return false; } return false; } #endregion Get } }
7036065ad0c8fd85aac4b902c3807febfc59756f
C#
mGrondzi/ARSearchLEGO
/Assets/CustomScripts/SwitchDatasets.cs
2.703125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SwitchDatasets: MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } /* public void SwitchTargetByName(string activateThisDataset) { TrackerManager trackerManager = (TrackerManager)TrackerManager.Instance; ObjectTracker objectTracker = TrackerManager.Instance.GetTracker<ObjectTracker>(); IEnumerable<DataSet> datasets = objectTracker.GetDataSets(); IEnumerable<DataSet> activeDataSets = objectTracker.GetActiveDataSets(); List<DataSet> activeDataSetsToBeRemoved = activeDataSets.ToList(); //Loop through all the active datasets and deactivate them. foreach (DataSet ads in activeDataSetsToBeRemoved) { objectTracker.DeactivateDataSet(ads); } //Swapping of the datasets should not be done while the ObjectTracker is working at the same time. //So, Stop the tracker first. objectTracker.Stop(); //Then, look up the new dataset and if one exists, activate it. foreach (DataSet ds in datasets) { if (ds.Path.Contains(activateThisDataset)) { objectTracker.ActivateDataSet(ds); } } //Finally, start the object tracker. objectTracker.Start(); }*/ }
b2785ae67a88250e6e76f6a323005a1bb4a9052e
C#
SKKbySSK/NotesGenerator
/NotesPlayer/Extensions/ElementExtension.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Animation; namespace NotesPlayer.Extensions { public static class ElementExtension { public static void AnimateOpacity(this UIElement Element, double Opacity, double Duration = 300, Action<UIElement> Completed = null) { DoubleAnimation da = new DoubleAnimation(Opacity, new Duration(TimeSpan.FromMilliseconds(Duration))); da.FillBehavior = FillBehavior.Stop; EventHandler ev = null; ev = new EventHandler((_, _2) => { Element.Opacity = Opacity; Completed?.Invoke(Element); da.Completed -= ev; }); da.Completed += ev; Element.BeginAnimation(UIElement.OpacityProperty, da); } } }
682444ab7a4e1f21cda6dc84f4e88b2d26c9e8a6
C#
PavelGem-13g/ne_spisivay
/9 класс/Фоновая 5_2/Фоновая 5_2/Program.cs
3.140625
3
using System; namespace Фоновая_5_2 { class CargoVehicles { protected string name; protected int mass; protected int powerReserve; protected int carryCap; protected int cargoMass; protected string Name { get { return name; } } protected CargoVehicles(string name, int mass, int powerReserve, int carryCap, int cargoMass) { this.name = name; this.mass = mass; this.powerReserve = powerReserve; this.carryCap = carryCap; this.cargoMass = cargoMass; } virtual public void output() { Console.WriteLine("Название ТС {0}, масса ТС {1}, запас хода {2}, грузопдъёмность {3}, масса груза {4}", name, mass, powerReserve, carryCap, mass); } protected CargoVehicles() { name = "Грузовая машина"; mass = 5; powerReserve = 500; carryCap = 1000; cargoMass = 500; } virtual public void Description() { Console.WriteLine("Это Description класса - одителя"); } virtual public int fullMass { get { return mass + cargoMass; } } public int CarryCap { get { return carryCap; } } virtual public int CargoMass { get { return cargoMass; } set { cargoMass = value; } } virtual public void fuelS(int benzMass) { double kpd = double.Parse(Console.ReadLine()); Console.WriteLine((43600d * benzMass * kpd) / (fullMass * 10 * 0.87d)); } } enum Transmission { задний = 1, передний, полный }; class RollingVehicles : CargoVehicles { protected int wheel; protected Transmission transmission; override public void output() { base.output(); Console.WriteLine(", кол-во колес {0}", wheel); } public override int fullMass { get { return mass + cargoMass; } } protected RollingVehicles() : base() { wheel = 4; } protected RollingVehicles(string name, int mass, int powerReserve, int carryCap, int cargoMass, int wheel) : base(name, mass, powerReserve, carryCap, cargoMass) { this.wheel = wheel; } public override void fuelS(int benzMass) { double koef; koef = Convert.ToDouble(Console.ReadLine()); double kpd = double.Parse(Console.ReadLine()); Console.WriteLine((kpd * 43600d * benzMass * kpd) / (fullMass * 10 * 0.87d)); } } class Train : RollingVehicles { int wagonsNumber; override public void output() { base.output(); Console.Write(", кол-во вагонов {0} \n", wagonsNumber); Console.WriteLine("_________________________________________________________________________________________________________"); } public Train() : base() { wagonsNumber = 0; } public Train(string name, int mass, int powerReserve, int carryCap, int cargoMass, int wheel, int wagonsNumber) : base(name, mass, powerReserve, carryCap, cargoMass, wheel) { this.wagonsNumber = wagonsNumber; } override public int fullMass { get { return mass + cargoMass + 70 + 600 * wheel + wagonsNumber * 23000; } } override public void Description() { Console.WriteLine("Грузовой поезд — группа грузовых вагонов во главе с локомотивом. Поезд предназначен для перевозки грузов. Устаревшее название — товарный поезд, в просторечии товарняк."); } public override int CargoMass { get { return cargoMass; } } public override void fuelS(int benzMass) { double ro, lamdda; lamdda = Convert.ToDouble(Console.ReadLine()); double kpd = double.Parse(Console.ReadLine()); Console.WriteLine((lamdda * benzMass * kpd) / (fullMass * 10 * 0.87d)); } } class Truck : RollingVehicles { protected int drivers; override public void output() { base.output(); Console.WriteLine(", кол-во водителей {0}", drivers); } public Truck() : base() { drivers = 1; } public Truck(string name, int mass, int powerReserve, int carryCap, int cargoMass, int wheel, int drivers) : base(name, mass, powerReserve, carryCap, cargoMass, wheel) { this.drivers = drivers; } override public void Description() { Console.WriteLine("Грузовой автомобиль — автомобиль, предназначенный для перевозки грузов в кузове или на грузовой платформе. "); } override public int fullMass { get { return mass + cargoMass + 5 * wheel + 70 * drivers; } } public override void fuelS(int benzMass) { double ro = 0, lamdda = 0; double kpd = 0; double koefTreniya = 0; double g = 0; do { try { //этот код был написан ьез использования мыши Console.Write("Введите удельную теплоту сгорания "); lamdda = Convert.ToDouble(Console.ReadLine()); if (lamdda < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Введите КПД двигателя "); kpd = double.Parse(Console.ReadLine()); if (kpd < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Введите коэф трения "); koefTreniya = double.Parse(Console.ReadLine()); if (lamdda < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Введите g "); g = double.Parse(Console.ReadLine()); if (lamdda < 0) throw new Exception("Это значение не может быть отрицательным"); } catch (Exception error) { Console.WriteLine(error.Message); } } while (!(lamdda > 0d && kpd > 0 && koefTreniya > 0 && g > 0)); Console.WriteLine("Запас хода рвен {0:F2}", (lamdda * benzMass * kpd) / (fullMass * g * koefTreniya)); } } class PickUp : Truck { bool isPass; public PickUp() : base() { isPass = true; } public PickUp(string name, int mass, int powerReserve, int carryCap, int cargoMass, int wheel, int drivers, bool isPass) : base(name, mass, powerReserve, carryCap, cargoMass, wheel, drivers) { this.isPass = isPass; } override public void output() { base.output(); if (isPass) Console.WriteLine(", пассажиры есть"); else Console.WriteLine(", пассажиров нет"); Console.WriteLine("_________________________________________________________________________________________________________"); } override public int fullMass { get { if (isPass) return mass + 5 * wheel + cargoMass + 280 + 70 * drivers; else return mass + cargoMass; } } override public void fuelS(int benzMass) { double ro = 0, lamdda = 0; double kpd = 0; double koefTreniya = 0; double g = 0; do { try { //этот код был написан ьез использования мыши Console.Write("Введите удельную теплоту сгорания "); lamdda = Convert.ToDouble(Console.ReadLine()); if (lamdda < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Введите КПД двигателя "); kpd = double.Parse(Console.ReadLine()); if (kpd < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Введите коэф трения "); koefTreniya = double.Parse(Console.ReadLine()); if (lamdda < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Введите g "); g = double.Parse(Console.ReadLine()); if (lamdda < 0) throw new Exception("Это значение не может быть отрицательным"); } catch (Exception error) { Console.WriteLine(error.Message); } } while (!(lamdda > 0d && kpd > 0 && koefTreniya > 0 && g > 0)); Console.WriteLine("Запас хода рвен {0:F2}", (lamdda * benzMass * kpd) / (fullMass * g * koefTreniya)); } override public void Description() { base.Description(); Console.WriteLine("Пикап — легкий грузовик с закрытой кабиной и открытой грузовой площадкой с невысокими сторонами и задней дверью"); } } class ExtraTruck : Truck { int tanksNum; public ExtraTruck() : base() { tanksNum = 1; } public ExtraTruck(string name, int mass, int powerReserve, int carryCap, int cargoMass, int wheel, int drivers, int tanksNum) : base(name, mass, powerReserve, carryCap, cargoMass, wheel, drivers) { this.tanksNum = tanksNum; } override public void output() { base.output(); Console.WriteLine(", кол-во вагончиков {0}", tanksNum); Console.WriteLine("_________________________________________________________________________________________________________"); } override public void Description() { base.Description(); Console.WriteLine("Большегруз — транспортное средство для перевозки тяжёлых грузов."); } override public int fullMass { get { return mass + cargoMass + 280 + 5 * wheel + 70 * drivers + tanksNum * 400; } } override public void fuelS(int benzMass) { double ro = 0, lamdda = 0; double kpd = 0; double koefTreniya = 0; double g = 0; do { try { //этот код был написан ьез использования мыши Console.Write("Введите удельную теплоту сгорания "); lamdda = Convert.ToDouble(Console.ReadLine()); if (lamdda < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Введите КПД двигателя "); kpd = double.Parse(Console.ReadLine()); if (kpd < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Введите коэф трения "); koefTreniya = double.Parse(Console.ReadLine()); if (lamdda < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Введите g "); g = double.Parse(Console.ReadLine()); if (lamdda < 0) throw new Exception("Это значение не может быть отрицательным"); } catch (Exception error) { Console.WriteLine(error.Message); } } while (!(lamdda > 0d && kpd > 0 && koefTreniya > 0 && g > 0)); Console.WriteLine("Запас хода рвен {0:F2}", (lamdda * benzMass * kpd) / (fullMass * g * koefTreniya)); } } class Program { public static ExtraTruck CreatingExtraTruck() { int choose = 0; do { try { Console.Write("Конструктор по умолчанию - 1, своё ТС - 2 "); choose = int.Parse(Console.ReadLine()); if (!(0 < choose && choose < 3)) throw new Exception("Введите чило в дапазоне 1-2"); } catch (Exception error) { Console.WriteLine(error.Message); } } while (!(0 < choose && choose < 3)); if (choose == 2) { string name = ""; int mass = 0; int powerReserve = 0; int carryCap = 0; int cargoMass = 0; int wheel = 0; int drivers = 0; int tanksNum = 0; do { try { Console.Write("Название "); name = Console.ReadLine(); if (name.Length == 0) throw new Exception("Введите название"); Console.Write("Масса "); mass = int.Parse(Console.ReadLine()); if (mass < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Запас хода "); powerReserve = int.Parse(Console.ReadLine()); if (powerReserve < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Грузоподъемность "); carryCap = int.Parse(Console.ReadLine()); if (carryCap < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Масса груза "); cargoMass = int.Parse(Console.ReadLine()); if (cargoMass < 0 || carryCap <= cargoMass) throw new Exception("Это значение не может быть отрицательным или больше грузоподъемности"); Console.Write("Кол-во колесов "); wheel = int.Parse(Console.ReadLine()); if (wheel < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Кол-во водителей "); drivers = int.Parse(Console.ReadLine()); if (drivers < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Кол-во вагончиков "); tanksNum = int.Parse(Console.ReadLine()); if (tanksNum < 0) throw new Exception("Это значение не может быть отрицательным"); } catch (Exception error) { Console.WriteLine(error.Message); } } while (!(name.Length > 0 && mass > 0 && powerReserve > 0 && carryCap > 0 && cargoMass > 0 && wheel > 0 && drivers > 0 && tanksNum > 0)); return new ExtraTruck(name, mass, powerReserve, carryCap, cargoMass, wheel, drivers, tanksNum); } else { return new ExtraTruck(); } } public static PickUp CreatingPickUp() { int choose = 0; do { try { Console.Write("Конструктор по умолчанию - 1, своё ТС - 2 "); choose = int.Parse(Console.ReadLine()); if (!(0 < choose && choose < 3)) throw new Exception("Введите чило в дапазоне 1-2"); } catch (Exception error) { Console.WriteLine(error.Message); } } while (!(0 < choose && choose < 3)); if (choose == 2) { string name = ""; int mass = 0; int powerReserve = 0; int carryCap = 0; int cargoMass = 0; int wheel = 0; int drivers = 0; bool isPass = true; int isPassInt; do { try { Console.Write("Название "); name = Console.ReadLine(); if (name.Length < 0) throw new Exception("Введите название"); Console.Write("Масса "); mass = int.Parse(Console.ReadLine()); if (mass < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Запас хода "); powerReserve = int.Parse(Console.ReadLine()); if (powerReserve < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Грузоподъемность "); carryCap = int.Parse(Console.ReadLine()); if (carryCap < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Масса груза "); cargoMass = int.Parse(Console.ReadLine()); if (cargoMass < 0 || carryCap >= cargoMass) throw new Exception("Это значение не может быть отрицательным или больше грузоподъемности"); Console.Write("Кол-во колесов "); wheel = int.Parse(Console.ReadLine()); if (wheel < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Кол-во водителей "); drivers = int.Parse(Console.ReadLine()); if (drivers < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Есть поссажиры? да - 1, нет - другое число "); isPassInt = int.Parse(Console.ReadLine()); if (isPassInt == 1) isPass = true; else isPass = false; } catch (Exception error) { Console.WriteLine(error.Message); } } while (name.Length > 0 && mass > 0 && powerReserve > 0 && carryCap > 0 && cargoMass > 0 && wheel > 0 && drivers > 0); return new PickUp(name, mass, powerReserve, carryCap, cargoMass, wheel, drivers, isPass); } else { return new PickUp(); } } public static Train CreatingTrain() { int choose = 0; do { try { Console.Write("Конструктор по умолчанию - 1, своё ТС - 2 "); choose = int.Parse(Console.ReadLine()); if (!(0 < choose && choose < 3)) throw new Exception("Введите чило в дапазоне 1-2"); } catch (Exception error) { Console.WriteLine(error.Message); } } while (!(0 < choose && choose < 3)); if (choose == 2) { string name = ""; int mass = 0; int powerReserve = 0; int carryCap = 0; int cargoMass = 0; int wheel = 0; int wagonsNumber = 0; do { try { Console.Write("Название "); name = Console.ReadLine(); if (name.Length < 0) throw new Exception("Введите название"); Console.Write("Масса "); mass = int.Parse(Console.ReadLine()); if (mass < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Запас хода "); powerReserve = int.Parse(Console.ReadLine()); if (powerReserve < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Грузоподъемность "); carryCap = int.Parse(Console.ReadLine()); if (carryCap < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Масса груза "); cargoMass = int.Parse(Console.ReadLine()); if (cargoMass < 0 || carryCap >= cargoMass) throw new Exception("Это значение не может быть отрицательным или больше грузоподъемности"); Console.Write("Кол-во колесов "); wheel = int.Parse(Console.ReadLine()); if (wheel < 0) throw new Exception("Это значение не может быть отрицательным"); Console.Write("Кол-во вагонов "); wagonsNumber = int.Parse(Console.ReadLine()); if (wagonsNumber < 0) throw new Exception("Это значение не может быть отрицательным"); } catch (Exception error) { Console.WriteLine(error.Message); } } while (name.Length > 0 && mass > 0 && powerReserve > 0 && carryCap > 0 && cargoMass > 0 && wheel > 0 && wagonsNumber > 0); return new Train(name, mass, powerReserve, carryCap, cargoMass, wheel, wagonsNumber); } else { return new Train(); } } static void Main(string[] args) { Console.Write("Введите длину массива: "); int n; int.TryParse(Console.ReadLine(), out n); CargoVehicles[] arr = new CargoVehicles[n]; Console.WriteLine("Заполнение массива"); Console.WriteLine("_________________________________________________________________________________________________________"); for (int i = 0; i < arr.Length; i++) { int temp = 0; Console.Write("Пикап - 1, большегруз - 2, поезд - 3: "); do { try { temp = int.Parse(Console.ReadLine()); if (!(0 < temp && temp < 4)) throw new Exception("Введите чило в дапазоне 1-3"); } catch (Exception error) { Console.WriteLine(error.Message); } } while (!(0 < temp && temp < 4)); if (temp == 1) arr[i] = CreatingPickUp(); if (temp == 2) arr[i] = CreatingExtraTruck(); if (temp == 3) arr[i] = CreatingTrain(); } //Console.Clear(); Console.WriteLine("Значения массива"); Console.WriteLine("_________________________________________________________________________________________________________"); foreach (CargoVehicles i in arr) { i.output(); i.Description(); Console.Write("Измените массу груза"); int tempCargoMass = 0; do { try { tempCargoMass = int.Parse(Console.ReadLine()); if (tempCargoMass > i.CarryCap) throw new Exception("Масса груза не может быть больше грузоподъемности"); if (tempCargoMass < 0) throw new Exception("Это значение не может быть отрицательным"); } catch (Exception error) { Console.WriteLine(error.Message); } } while (tempCargoMass > i.CarryCap || tempCargoMass < 0); i.CargoMass = tempCargoMass; Console.WriteLine("Новая масса груза ТС {0:F2}", i.CargoMass); Console.WriteLine("Полная масса ТС {0:F2}", i.fullMass); int fuelMass = 0; Console.Write("Введите значение массы бензина "); do { try { fuelMass = int.Parse(Console.ReadLine()); if (fuelMass + i.CargoMass > i.CarryCap) throw new Exception("Сумма массы бензина и массы груза не должна превышать грузоподъёмность"); if (fuelMass < 0) throw new Exception("Это значение не может быть отрицательным"); } catch (Exception error) { Console.WriteLine(error.Message); } } while (!(fuelMass + i.CargoMass < i.CarryCap && fuelMass >= 0)); i.fuelS(fuelMass); } /*Console.WriteLine("\n\n Значения отдельного объекта(класса ExtraTruck)"); Console.WriteLine("_________________________________________________________________________________________________________");*//* Truck truck = CreatingExtraTruck();*//* truck.Description(); truck.output();*/ Console.ReadKey(); } } }
11ac6b2fab931a69a88b432a9b52e651d0f68b1a
C#
Codinablack/Tibia
/src/Tibia.Network.Game/AddingFriendEventArgs.cs
2.71875
3
using System.ComponentModel; using Tibia.Data; using Tibia.Spawns; namespace Tibia.Network.Game { public class AddingFriendEventArgs : CancelEventArgs { /// <inheritdoc /> /// <summary> /// Initializes a new instance of the <see cref="T:Tibia.Network.Game.AddingFriendEventArgs" /> class. /// </summary> /// <param name="characterSpawn">The character spawn.</param> /// <param name="friendName">Name of the friend.</param> public AddingFriendEventArgs(CharacterSpawn characterSpawn, string friendName) { CharacterSpawn = characterSpawn; FriendName = friendName; } /// <summary> /// Gets the character spawn. /// </summary> /// <value> /// The character spawn. /// </value> public CharacterSpawn CharacterSpawn { get; } /// <summary> /// Gets the name of the friend. /// </summary> /// <value> /// The name of the friend. /// </value> public string FriendName { get; } /// <summary> /// Gets or sets the character. /// </summary> /// <value> /// The character. /// </value> public ICharacter Character { get; set; } } }
b107c5b535fe814f5c284bec2a59038b4555265a
C#
Bolillo-Kremer/DriverDB
/DriverDB.Core/Exceptions/DriverDoesntExist.cs
3.171875
3
using System; namespace DriverDB.Core.Exceptions { class DriverDoesntExist : Exception { #region Properties public string DriverName = string.Empty; #endregion Properties #region Constructors /// <summary> /// Creates new <see cref="DriverDoesntExist"/> /// </summary> /// <param name="aDriverName">The path to the driver that gave an error</param> public DriverDoesntExist(string aDriverName) : base($"Couldn't find {aDriverName} in the root direcotry") { this.DriverName = aDriverName; } /// <summary> /// Creates new <see cref="DriverDoesntExist"/> /// </summary> /// <param name="aDriverPath">The path to the driver that gave an error</param> /// <param name="Message">Error message</param> public DriverDoesntExist(string aDriverName, string Message) : base(Message) { this.DriverName = aDriverName; } #endregion Constructors } }
d3f5bb47ec071e25073acf60c9c870bd6fedcfae
C#
vectorized-runner/node-editor
/Core/Extensions/StringExtensions.cs
2.953125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Text.RegularExpressions; public static class StringExtensions { public static string ToInspector(this string str) { return str.SplitCamelCase().UppercaseFirst(); } static string SplitCamelCase(this string str) { return Regex.Replace( Regex.Replace( str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2" ), @"(\p{Ll})(\P{Ll})", "$1 $2" ); } static string UppercaseFirst(this string str) { // Check for empty string. if(string.IsNullOrEmpty(str)) { return string.Empty; } // Return char and concat substring. return char.ToUpper(str[0]) + str.Substring(1); } }
d670187bf557327bc00cccd04e23c1d2b2bd4de5
C#
Caster123/CS3247Project
/LastPiece/Assets/Source/DrawActivityOnResult.cs
3.078125
3
/** * DrawActivityOnResult must be implemented by any class wishing to use DrawActivity class. * The calling class is used as a parameter in DrawActivity.getInstance(DrawActivityOnResult) call. * Method onDrawActivityResult is called by a DrawActivity method onDrawActivityResultListener, which is a callback method from Java, * called when DrawActivity is closed. Created image is passed in parameter. * */ public interface DrawActivityOnResult { /** * Method onDrawActivityResult is called when uses quits the DrawActivity, with the created imaged passed in parameter. * * @param result Created image as byte array. */ void onDrawActivityResult(byte[] result); /** * Method onDrawActivityCanceled is called when uses quits the DrawActivity without saving the image, as in by using the back arrow. */ void onDrawActivityCanceled(); }
386af421bf51c5bc562c82840d32576ad90c0f06
C#
Horton-D/Lab18
/Lab18/Lab18/List.cs
3.578125
4
using System; using System.Collections.Generic; namespace Lab18 { public class List { private int _count = 0; private readonly string[] _array; private Object p; public List(int maxLength) { _array = new string[maxLength]; } public int Count() { return _count; } public bool IsEmpty() { return _count == 0; } public void Reverse() { Array.Reverse(_array); foreach (var item in _array) { Console.WriteLine(item); } } public bool IsFull() { return _count == _array.Length; } public bool Insert(string value) { if (IsFull()) { return false; } _array[_count] = value; _count++; return true; } public bool RemoveAt(int index) { for (int i = index; i < _count; i++) { _array[i] = _array[i + 1]; } _count--; if (index > _count) { return false; } return true; } public bool InsertAt(int index, Object o) { for (int i = index; i < _count; i++) { _array[i] = _array[i + 1]; } if (index > _count) { return false; } else { _array[_count] = (string)o; _count++; return true; } } public void Print() { foreach (var item in _array) { Console.WriteLine(item); } } } }
191e0e1c4a27b5054efcd8c9bbf0cafd4306919e
C#
ukillkenny/IPJ.Test
/Juego RPG/Juego RPG/Tower.cs
3.359375
3
using System; using System.Collections.Generic; using System.IO; using System.Text; class Tower { enum Options {Enter, Fight, Leave, GoToNextFloor, Error }; enum OnEnterOption { Leave, Fight, Error } enum OnFinishFightOption { Leave, GoToNextFloor, Error } private List<Floor> floors; private int lastVisitedFloor; private Options currentOption; public Tower(int floorsAmount) { floors = new List<Floor>(); for (int i = 0; i < floorsAmount; i++) { floors.Add(new Floor(4)); } lastVisitedFloor = 0; currentOption = Options.Enter; } public BinaryWriter Save(BinaryWriter bw) { bw.Write(floors.Count); for (int i = 0; i < floors.Count; i++) { bw = floors[i].Save(bw); } bw.Write(lastVisitedFloor); bw.Write((int)currentOption); return bw; } public Player StayInside(Player player) { switch (currentOption) { case Options.Enter: Enter(); break; case Options.Fight: player = Fight(player); break; case Options.Leave: player = Leave(player); break; case Options.GoToNextFloor: GoToNextFloor(); break; default: break; } return player; } public void Enter() { Console.WriteLine("Welcome to the Tower"); OnEnterOption onEnterOption; Console.WriteLine("Leave = 0 - Fight = 1"); int input = Convert.ToInt32(Console.ReadLine()); if (input >= 0 && input < (int)OnEnterOption.Error) { onEnterOption = (OnEnterOption)input; } else { onEnterOption = OnEnterOption.Error; } switch (onEnterOption) { case OnEnterOption.Leave: currentOption = Options.Leave; break; case OnEnterOption.Fight: currentOption = Options.Fight; break; } } public Player Fight(Player player) { player = floors[lastVisitedFloor].Fight(player); if (floors[lastVisitedFloor].enemies.Count == 0) { lastVisitedFloor++; OnFinishFightOption onFinishFightOption; Console.WriteLine("Leave = 0 - Go To Next Floor = 1"); int input = Convert.ToInt32(Console.ReadLine()); if (input >= 0 && input < (int)OnFinishFightOption.Error) { onFinishFightOption = (OnFinishFightOption)input; } else { onFinishFightOption = OnFinishFightOption.Error; } switch (onFinishFightOption) { case OnFinishFightOption.Leave: currentOption = Options.Leave; break; case OnFinishFightOption.GoToNextFloor: currentOption = Options.GoToNextFloor; break; } } return player; } public Player Leave(Player player) { player.GoToInn(); return player; } public void GoToNextFloor() { } }
3ba5f977c7e30383cbd7490bcf8bb32783fff151
C#
maplemike/NRF_MerchandisingCalendar
/NRF_MerchandisingCalendar/MerchandisingDate.cs
3.328125
3
using System; namespace MerchandisingCalendar { public class MerchandisingDate { #region FIELDS protected DateTime date; protected Int32 dayOfYear; protected Int32 period; protected Int32 quarter; protected Int32 week; protected Int32 year; #endregion #region PROPERTIES public virtual DateTime Date { get { return date; } protected set { date = value; } } public virtual Int32 DayOfYear { get { return dayOfYear; } protected set { dayOfYear = value; } } public virtual Int32 Period { get { return period; } protected set { period = value; } } public virtual String PeriodName { get { return DateFunctions.GetPeriodName(Period); } } public virtual Int32 Quarter { get { return quarter; } protected set { quarter = value; } } public virtual String QuarterName { get { return DateFunctions.GetQuarterName(Quarter); } } public virtual Int32 Week { get { return week; } protected set { week = value; } } public virtual Int32 Year { get { return year; } protected set { year = value; } } #endregion #region CONSTRUCTORS public MerchandisingDate(DateTime Date) { this.Date = Date; DayOfYear = DateFunctions.GetDayOfYear(Date); Period = DateFunctions.GetPeriod(Date); Quarter = DateFunctions.GetQuarter(Date); Week = DateFunctions.GetWeek(Date); Year = DateFunctions.GetYear(Date); } public MerchandisingDate(DateTime Date, Int32 Year, Int32 Quarter, Int32 Period, Int32 Week, Int32 DayOfYear) { if (DateFunctions.GetWeeksInYear(Year) == 52) { if ((DayOfYear < 1) || (DayOfYear > 364)) { throw new Exception("DayOfYear cannot be less than 1 or greater than 364."); } } else { if ((DayOfYear < 1) || (DayOfYear > 371)) //CHANGE THIS TO BE AWARE OF WEEK 52 and 53 { throw new Exception("DayOfYear cannot be less than 1 or greater than 371."); } } DateFunctions.ValidatePeriod(Period); DateFunctions.ValidateQuarter(Quarter); DateFunctions.ValidateWeek(Week, Year); if ((Year < 1) || (Year > 9999)) { throw new Exception("Year cannot be less than 1 or greater than 9999."); } this.Date = Date; this.DayOfYear = DayOfYear; this.Period = Period; this.Quarter = Quarter; this.Week = Week; this.Year = Year; } #endregion } }
d8473eeeaac902362332613e2ecc6d791a9da520
C#
atanashivachev/IT-kariera
/Year 1/Programming/Bonus 17 and 18, 10(10,15,17).02.2019/ProductsForPizza/ProductsForPizzaProgram.cs
3.828125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProductsForPizza { class ProductsForPizzaProgram { static void Main(string[] args) { List<string> products = Console.ReadLine().Split(' ').ToList(); int prodLength = int.Parse(Console.ReadLine()); var usedProds = new List<string>(); foreach (var prod in products) { if (prod.Length == prodLength) { Console.WriteLine($"Adding {prod}"); usedProds.Add(prod); } } Console.WriteLine($"Made pizza with total of {usedProds.Count} ingredients. The ingredients are: {string.Join(" ", usedProds)}."); } } }
2fbeec888014dfa14738ac0f2dba5bf555d8bc55
C#
mkbiltek2019/pdf_transform
/Utils/Utils.cs
3.46875
3
using System; using System.Linq; using System.Text.RegularExpressions; using PDFTransformation.Enums; namespace PDFTransformation { public static class CommonUtils { /// <summary> /// Generates the file names by using Random Generator for uploaded files. /// </summary> /// <returns>The file names.</returns> /// <param name="type">Type/extention of the file.</param> public static string GenerateFileNames(string type) { Random random = new Random(DateTime.Now.Second); const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return (new string(Enumerable.Repeat(chars, 10) .Select(s => s[random.Next(s.Length)]).ToArray()) + type); } /// <summary> /// Matchs the regex on the given string and return the matching string. /// </summary> /// <returns>The string matching the regex pattern.</returns> /// <param name="input">String on which regex matching is to be run.</param> /// <param name="pattern">The regex pattern to be matched.</param> public static String MatchRegex(String input, String pattern) { Match match = Regex.Match(input, pattern, RegexOptions.Singleline); while (match.Success) { return match.Value; } return ""; } } }
cddb4c5dd494cb399e1f025dbc4e3d22bbd19e79
C#
HRashedy/SMSSender
/SMSAPI.Data/Repositories/GenericRepository.cs
3.046875
3
using Microsoft.EntityFrameworkCore; using SMSAPI.Data.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SMSAPI.Data.Repositories { public abstract class GenericRepository<T> : IGenericRepository<T> where T : BaseEntity { protected DbContext _entities; protected readonly DbSet<T> _dbset; public GenericRepository(DbContext context) { _entities = context; _dbset = context.Set<T>(); } public virtual IEnumerable<T> Get() { return this._dbset; } public virtual T Get(string id) { return this._dbset.Find(id); } public virtual void Create(T data) { this._dbset.Add(data); this._entities.SaveChanges(); } public virtual void Update(T data) { this._entities.Entry(data).State = EntityState.Modified; this._entities.SaveChanges(); } public virtual void Delete(string id) { T entity = this._dbset.Find(id); this._entities.Entry(entity).State = EntityState.Deleted; this._entities.SaveChanges(); } public bool Exists(string id) { return this._dbset.Any(x => x.Id == id); } } }
2cd70fabd691454dca12b49f1bea64627728d932
C#
keichi/isurf
/IsosurfaceGenerator/Exporter/OBJExporter.cs
2.78125
3
/* * This file is part of "IsosurfaceGenerator" * * Copyright (C) 2013 Keichi TAKAHASHI. All Rights Reserved. * Please contact Keichi Takahashi <keichi.t@me.com> for further informations. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ using System; using System.IO; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using IsosurfaceGenerator.Utils; namespace IsosurfaceGenerator.Exporter { /// <summary> /// メッシュデータをOBJファイルとしてエクスポートするクラス /// </summary> public class OBJExporter : IMeshExporter { /// <summary> /// 出力ファイルのStreamWriter /// </summary> private StreamWriter _writer; /// <summary> /// 現在最大の頂点インデックス /// </summary> private int _verticesCount = 1; /// <summary> /// 現在最大の頂点法線ベクトルインデックス /// </summary> private int _normalVecsCount = 1; private OBJExporter() { } public OBJExporter (string filename) { _writer = new StreamWriter(filename); } /// <summary> /// メッシュをファイルへエクスポートする /// </summary> /// <param name="triangles">メッシュデータ</param> /// <param name="isoValue">等値曲面の値</param> public void Export(List<Triangle> triangles, float isoValue) { // 頂点と頂点インデックスの辞書 var dict = new Dictionary<Vec3, int>(); _writer.WriteLine("g " + isoValue.ToString()); // 全てのポリゴンの3つの頂点を書き出す foreach(var triangle in triangles) { var vertex1 = triangle.Vertex1; if (!dict.ContainsKey(vertex1)) { // 以下_writer.WriteLineを使用していないのは、パフォーマンス上の理由 dict.Add(vertex1, _verticesCount++); _writer.Write("v "); _writer.Write(vertex1.X); _writer.Write(' '); _writer.Write(vertex1.Y); _writer.Write(' '); _writer.Write(vertex1.Z); _writer.WriteLine(); } var vertex2 = triangle.Vertex2; if (!dict.ContainsKey(vertex2)) { dict.Add(vertex2, _verticesCount++); _writer.Write("v "); _writer.Write(vertex2.X); _writer.Write(' '); _writer.Write(vertex2.Y); _writer.Write(' '); _writer.Write(vertex2.Z); _writer.WriteLine(); } var vertex3 = triangle.Vertex3; if (!dict.ContainsKey(vertex3)) { dict.Add(vertex3, _verticesCount++); _writer.Write("v "); _writer.Write(vertex3.X); _writer.Write(' '); _writer.Write(vertex3.Y); _writer.Write(' '); _writer.Write(vertex3.Z); _writer.WriteLine(); } } // 全てのポリゴンの法線ベクトルを書き出す foreach(var triangle in triangles) { _normalVecsCount++; var normal = (triangle.Vertex3 - triangle.Vertex1).Cross (triangle.Vertex2 - triangle.Vertex1).Normalize (); _writer.Write("vn "); _writer.Write(normal.X); _writer.Write(' '); _writer.Write(normal.Y); _writer.Write(' '); _writer.Write(normal.Z); _writer.WriteLine(); } // ポリゴンの定義を行う for (var i = 0; i < triangles.Count; i++) { var i1 = dict[triangles[i].Vertex1]; var i2 = dict[triangles[i].Vertex2]; var i3 = dict[triangles[i].Vertex3]; if (i1 == i2 || i1 == i3 || i2 == i3) { continue; } _writer.Write("f "); _writer.Write(i1); _writer.Write("//"); _writer.Write(i + 1); _writer.Write(' '); _writer.Write(i2); _writer.Write("//"); _writer.Write(i + 1); _writer.Write(' '); _writer.Write(i3); _writer.Write("//"); _writer.Write(i + 1); _writer.WriteLine(); } } public void Dispose() { _writer.Dispose(); } } }
985175dfdace4bfda34f3c1e984a5505841203ee
C#
mpodonyi/Twilight
/Twilight.Test/TestBase.cs
3.109375
3
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using FluentAssertions; namespace Twilight.Test { public class TestBase { private static double ConvertDegreeAngleToDouble(string point) { //Example: 17.21.18S //Degrees Lat Long 51.5000000°, -000.1300000° //Degrees Minutes 51°30.00000', 000°07.80000' //Degrees Minutes Seconds 51°30'00.0000", 000°07'48.0000" var multiplier = (point.Contains("S") || point.Contains("W")) ? -1 : 1; //handle south and west point = Regex.Replace(point, "[^0-9.]", "."); //remove the characters var pointArray = point.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); //split the string. //Decimal degrees = // whole number of degrees, // plus minutes divided by 60, // plus seconds divided by 3600 var degrees = Double.Parse(pointArray[0]); var minutes = Double.Parse(pointArray[1]) / 60; //var seconds = Double.Parse(pointArray[2]) / 3600; return (degrees + minutes /*+ seconds*/) * multiplier; } protected void SunTest(string dateTime, string lat, string lng, string rise, string set, SunPeriodTypes sunPeriodType, Func<DateTimeOffset, double, double, SunPeriod> fun) { //const string pattern = "yyyy-MM-dd'T'HH:mm:ss.FFFK"; const string pattern = "yyyy-MM-dd'T'HH:mm:ssK"; DateTimeOffset inputOffset = DateTimeOffset.ParseExact(dateTime, pattern, CultureInfo.InvariantCulture); DateTimeOffset? riseOffset = rise == null ? (DateTimeOffset?)null : DateTimeOffset.ParseExact(rise, pattern, CultureInfo.InvariantCulture); DateTimeOffset? setOffset = set == null ? (DateTimeOffset?)null : DateTimeOffset.ParseExact(set, pattern, CultureInfo.InvariantCulture); double dLat = ConvertDegreeAngleToDouble(lat); double dLng = ConvertDegreeAngleToDouble(lng); SunPeriod sp = fun(inputOffset, dLat, dLng); sp.Rise.Should().Be(riseOffset, "Rise"); sp.Set.Should().Be(setOffset, "Set"); sp.SunPeriodType.Should().Be(sunPeriodType); } protected void MoonTest(string dateTime, string lat, string lng, string rise, string set, MoonPeriodTypes moonPeriodType, Func<DateTimeOffset, double, double, MoonPeriod> fun) { //const string pattern = "yyyy-MM-dd'T'HH:mm:ss.FFFK"; const string pattern = "yyyy-MM-dd'T'HH:mm:ssK"; DateTimeOffset inputOffset = DateTimeOffset.ParseExact(dateTime, pattern, CultureInfo.InvariantCulture); DateTimeOffset? riseOffset = rise == null ? (DateTimeOffset?)null : DateTimeOffset.ParseExact(rise, pattern, CultureInfo.InvariantCulture); DateTimeOffset? setOffset = set == null ? (DateTimeOffset?)null : DateTimeOffset.ParseExact(set, pattern, CultureInfo.InvariantCulture); double dLat = ConvertDegreeAngleToDouble(lat); double dLng = ConvertDegreeAngleToDouble(lng); MoonPeriod sp = fun(inputOffset, dLat, dLng); sp.Rise.Should().Be(riseOffset, "Rise"); sp.Set.Should().Be(setOffset, "Set"); sp.MoonPeriodType.Should().Be(moonPeriodType); } } }
b849e8a909632dfe42ba0c7b13f5bbbbeda43df5
C#
alanx0401/ASP-Project-2019
/ITP213/DAL/AcademicResultDAO.cs
2.78125
3
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Web; namespace MyFunctions.DAL { public class AcademicResultDAO { string DBConnect = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString; public AcademicResult getStudentByAdminNo(string adminNo) { //Get connection string from web.config SqlDataAdapter da; DataSet ds = new DataSet(); StringBuilder sqlCommand = new StringBuilder(); sqlCommand.AppendLine("Select * from academicResult where"); sqlCommand.AppendLine("adminNo = @paraAdminNo"); AcademicResult obj = new AcademicResult(); SqlConnection myConn = new SqlConnection(DBConnect); da = new SqlDataAdapter(sqlCommand.ToString(), myConn); da.SelectCommand.Parameters.AddWithValue("paraAdminNo", adminNo); // fill dataset da.Fill(ds, "studentTable"); int rec_cnt = ds.Tables["studentTable"].Rows.Count; if (rec_cnt > 0) { DataRow row = ds.Tables["studentTable"].Rows[0]; // Sql command returns only one record obj.academicResultID = row["academicResultID"].ToString(); obj.adminNo = row["adminNo"].ToString(); obj.cumulativeGPA = row["cumulativeGPA"].ToString(); obj.sem1Year1GPA = row["sem1Year1GPA"].ToString(); obj.sem2Year1GPA = row["sem2Year1GPA"].ToString(); obj.sem1Year2GPA = row["sem1Year2GPA"].ToString(); obj.sem2Year2GPA = row["sem2Year2GPA"].ToString(); obj.sem1Year3GPA = row["sem1Year3GPA"].ToString(); obj.sem2Year3GPA = row["sem2Year3GPA"].ToString(); } else { obj = null; } return obj; } public List<AcademicResult> getTDbyAdminNo() { // Step 2 : declare a list to hold collection of customer's timeDeposit // DataSet instance and dataTable instance List<AcademicResult> tdList = new List<AcademicResult>(); DataSet ds = new DataSet(); DataTable tdData = new DataTable(); // // Step 3 :Create SQLcommand to select all columns from TDMaster by parameterised customer id // where TD is not matured yet StringBuilder sqlStr = new StringBuilder(); sqlStr.AppendLine("SELECT * From academicResult"); // Step 4 :Instantiate SqlConnection instance and SqlDataAdapter instance SqlConnection myConn = new SqlConnection(DBConnect); SqlDataAdapter da = new SqlDataAdapter(sqlStr.ToString(), myConn); // Step 6: fill dataset da.Fill(ds, "TableTD"); // Step 7: Iterate the rows from TableTD above to create a collection of TD // for this particular customer int rec_cnt = ds.Tables["TableTD"].Rows.Count; if (rec_cnt > 0) { foreach (DataRow row in ds.Tables["TableTD"].Rows) { AcademicResult myTD = new AcademicResult(); // Step 8 Set attribute of timeDeposit instance for each row of record in TableTD myTD.academicResultID = row["academicResultID"].ToString(); myTD.adminNo = row["adminNo"].ToString(); myTD.cumulativeGPA = row["cumulativeGPA"].ToString(); // Step 9: Add each timeDeposit instance to array list tdList.Add(myTD); } } else { tdList = null; } return tdList; } } }
6247d1d7d227d6997e10c457e356d91c72143217
C#
voducdan/PTTKBanHang
/PTTKBanHang/Models/InfoCustomer.cs
2.65625
3
using System; using System.Collections.Generic; using System.Text; namespace PTTKBanHang.Models { public class InfoCustomer { private string _name; private string _email; private string _phonenumber; private string _address; public string name { get { return _name; } set { _name = value; } } public string email { get { return _email; } set { _email = value; } } public string phonenumber { get { return _phonenumber; } set { _phonenumber = value; } } public string address { get { return _address; } set { _address = value; } } public InfoCustomer() { } public InfoCustomer(string name, string email, string phonenumber, string address) { this._name = name; this._email = email; this._phonenumber = phonenumber; this._address = address; } } }
79a505dce8c886b570430f3f54999baa493370a3
C#
qkmaxware/NautilusUnits
/Units/src/Qkmaxware/Units/Frequency/ZettaHertz.cs
2.921875
3
namespace Qkmaxware.Units.Frequency { /// <summary> /// Unit of measurement for ZettaHertz (ZHz) /// </summary> public struct ZettaHertz : IFrequency { public static string Name => "ZettaHertz"; public static string Symbol => "ZHz"; } /// <summary> /// Extension method factory for generating ZettaHertz (ZHz) /// </summary> public static class ZettaHertzFactory { /// <summary> /// Create a quantity measured in ZettaHertzs /// </summary> /// <param name="value">measured value</param> /// <typeparam name="T">type of measured value</typeparam> /// <returns>quantity with value and units</returns> public static Quantity<T, ZettaHertz> ZHz<T>(this T value) { return new Quantity<T, ZettaHertz> (value); } } }
7cac39d089a5b987b9daaca849e611a0ee90d103
C#
sunny-lan/GenshinbotCsharp
/GenshinBotWindows/yui/windows/Line.cs
2.671875
3
using OpenCvSharp; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace genshinbot.yui.windows { class Line : Drawable, yui.Line { private Viewport parent; public Line(Viewport parent) { this.parent = parent; } OpenCvSharp.Point a, b; public OpenCvSharp.Point A { get => a; set { //parent.Invalidate(new Region(Util.RectAround(a, b).Sys())); a = value; parent.Invalidate(); } } public OpenCvSharp.Point B { get => b; set { // parent.Invalidate(new Region(Util.RectAround(a, b).Sys())); b = value; parent.Invalidate(); } } private Pen p = Pens.Red; private Scalar color = Scalar.Red; public Scalar Color { get => color; set { p = new Pen(value.SysBgr255(), 1); color = value; parent.Invalidate(); } } public void OnPaint(PaintEventArgs e) { e.Graphics.DrawLine(p, a.Sys(), b.Sys()); } int perpborder = 3, endBorder=3; public event Action<MouseEvent>? MouseEvent; public bool Parent_MouseEvent(MouseEvent e) { //optimize //if (!Util.RectAround(a, b).Pad(perpborder).Contains(e.Location)) // return false; if (a.DistanceTo(b)>endBorder*2) { var v = e.Location - a; Point2d lnV = (b - a); var para = v.ProjectOnto(lnV); if(para.Length() >=endBorder && para.Length()<= lnV.Length()) { var perp = v - para; if (perp.Length() <= perpborder) { MouseEvent?.Invoke(e); return true; } } } return false; } } }
81b7df7fb2805b934d3ecf4ceb6e8c931932b755
C#
DiazMichael/CodingExercises
/CountOnesInBinaryRepresentation/Program.cs
3.140625
3
using System; using System.Linq; namespace CountOnesInBinaryRepresentation { class Program { static void Main(string[] args) { var i = 999; Console.WriteLine(CountOnes(i)); } public static int CountOnes(int i) { return (Convert.ToString(i,2)).Where(x => x == '1').Count(); } } }
0d4675dd6ce5abe87827a609b820a798d74039cb
C#
raghavendra3790/algosAllinOne
/Graphs.Tests/DfsTests.cs
3.109375
3
using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Graphs; namespace Graphs.Tests { [TestClass] public class DfsTests { [TestMethod] public void TestDFSHasPathSuccess() { UndirectedGraph g = BuildGraph(); DFS dfs = new DFS(g, 1); Assert.IsTrue(dfs.HasPath(2)); Assert.IsTrue(dfs.HasPath(4)); Assert.IsTrue(dfs.HasPath(5)); Assert.IsFalse(dfs.HasPath(3)); Assert.IsFalse(dfs.HasPath(6)); Assert.IsFalse(dfs.HasPath(7)); } [TestMethod] public void TestDFSPathSuccess() { UndirectedGraph g = BuildGraph(); DFS dfs = new DFS(g, 1); List<int> pathTo5 = dfs.Path(5); Assert.IsTrue(pathTo5.Contains(2)); Assert.IsTrue(pathTo5.Contains(1)); Assert.IsFalse(pathTo5.Contains(4)); } /// Build a graph which looks like /// 1 /// / /// 2 3 /// /\ /\ /// 4 5 6 7 private UndirectedGraph BuildGraph() { Graphs.UndirectedGraph ug = new UndirectedGraph(7); ug.AddEdge(1, 2); ug.AddEdge(2, 4); ug.AddEdge(2, 5); ug.AddEdge(3, 6); ug.AddEdge(3, 7); return ug; } } }
534702bfaa95eb8182650c90cdca7af1d7ec7178
C#
ZuhayrProxi/BudgetRepo
/Budgeting.Infrastructure/UserRepository.cs
3
3
using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Serialization; using Budgeting.Core.Interfaces; using Budgeting.Core.Model; namespace Budgeting.Infrastructure { public class UserRepository : IUserRepository { public User Register(string username, string password) { User user = new User(username, password); SerializeXml(@"C:\Users.txt", user); return user; } public static void SerializeXml(string filepath, object obj) { var writer = new StreamWriter(filepath); var serializer = new XmlSerializer(obj.GetType(), new XmlRootAttribute("ListOfUsers")); serializer.Serialize(writer, obj); writer.Flush(); writer.Close(); } public static User DeserializeXml(string filepath) { var serializer = new XmlSerializer(typeof(List<User>)); FileStream myFileStream = new FileStream(filepath, FileMode.Open); XmlReader reader = XmlReader.Create(myFileStream); var user = (User)serializer.Deserialize(reader); myFileStream.Close(); return user; } public User Login(string user, string password) { throw new NotImplementedException(); } } }
090a2d362270777360688c73b4ecf889e463b878
C#
hack4change/hambasafe
/Server/Hambasafe.Services/Services/AttendanceService.cs
2.84375
3
using System; using System.Linq; using System.Threading.Tasks; using Hambasafe.DataLayer; using Hambasafe.DataLayer.Entities; using Hambasafe.Services.Exceptions; using Microsoft.EntityFrameworkCore; namespace Hambasafe.Services.Services { public interface IAttendanceService { Task<bool> Join(Attendance attendance); Task<bool> Withdraw(Attendance attendance); } public class AttendanceService : IAttendanceService { private readonly IRepository<Attendance> _attendanceRepository; private readonly IRepository<Event> _eventRepository; private readonly IRepository<User> _userRepository; public AttendanceService(IRepository<Attendance> attendanceRepository, IRepository<Event> eventRepository, IRepository<User> userRepository) { _attendanceRepository = attendanceRepository; _eventRepository = eventRepository; _userRepository = userRepository; } public async Task<bool> Join(Attendance attendance) { try { // Check if the event and user exists await ValidateAttendanceDetails(attendance); // Check if this attendance already exists if (await _attendanceRepository.FindAll(a => a.EventId == attendance.EventId && a.UserId == attendance.UserId) .AnyAsync()) { return false; } attendance.HasAttended = false; attendance.DateCreated = DateTime.UtcNow; var result = await _attendanceRepository.Add(attendance); if (result != 1) { throw new DataException($"Expected to add 1 attendance, but instead added {result}"); } return true; } catch (DbUpdateException ex) { throw new DataException("Error occured while adding an attendance", ex.InnerException); } } public async Task<bool> Withdraw(Attendance attendance) { try { // There may be more than one attendance var attendances = await _attendanceRepository.FindAll(a => a.EventId == attendance.EventId && a.UserId == attendance.UserId) .ToArrayAsync(); // Cannot delete an attendance once you have attended the event if (attendances.Any(a => a.HasAttended.HasValue && a.HasAttended.Value)) { throw new DataException("Cannot withdraw from an event that has already been attended"); } var result = await _attendanceRepository.DeleteRange(attendances); if (result != attendances.Length) { throw new DataException($"Expected to delete {attendances.Length} attendance, but instead deleted {result}"); } return true; } catch (DbUpdateException ex) { throw new DataException("Error occured while removing an attendance", ex.InnerException); } } private async Task ValidateAttendanceDetails(Attendance attendance) { if (!await _eventRepository.FindAll(e => e.Id == attendance.EventId).AnyAsync()) { throw new DataException($"Event does not exist for Id:{attendance.EventId}"); } if (!await _userRepository.FindAll(u => u.Id == attendance.UserId).AnyAsync()) { throw new DataException($"User does not exist for Id:{attendance.UserId}"); } } } }
2a66d70add928640eeea887cdf5941259e7433fd
C#
shendongnian/download4
/code2/269433-5471421-11726048-2.cs
2.859375
3
protected void Button1_Click(object sender, EventArgs e) { FileInfo imageInfo = new FileInfo(File1.Value.Trim()); if (!imageInfo.Exists) //Show msg for "please select one image file." else { switch (imageInfo.Extension.ToUpper()) { case ".JPG": this.UpLoadImageFile(imageInfo); break; case ".GIF": this.UpLoadImageFile(imageInfo); break; case ".BMP": this.UpLoadImageFile(imageInfo); break; default: //Show msg "file type error."; break; } } } private void UpLoadImageFile(FileInfo info) { SqlConnection objConn = null; SqlCommand objCom = null; try { byte[] content = new byte[info.Length]; FileStream imagestream = info.OpenRead(); imagestream.Read(content, 0, content.Length); imagestream.Close(); objConn = new SqlConnection(strConnectionString); objCom = new SqlCommand("insert into TableName(FieldName,Picture)values(@FieldName,@Picture)", objConn); SqlParameter FieldNameParameter = new SqlParameter("@FieldName", SqlDbType.NVarChar); if (this.txtFileName.Text.Trim().Equals("")) FieldNameParameter.Value = "Default"; else FieldNameParameter.Value = this.txtFileName.Text.Trim(); objCom.Parameters.Add(FieldNameParameter); SqlParameter pictureParameter = new SqlParameter("@Picture", SqlDbType.Image); pictureParameter.Value = content; objCom.Parameters.Add(pictureParameter); objConn.Open(); objCom.ExecuteNonQuery(); objConn.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { objConn.Close(); } }
e73de25ffe9a805f1f44e822b1cf8ae42b8e4dd4
C#
khadbui94/KoalaTea_POS_System
/KoalaTea_Project_Root/FormCalculator.cs
2.640625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace KoalaTea_Project_Root { public partial class FormCalculator : Form { public FormCalculator(TextBox otherBox) { InitializeComponent(); whichBox = otherBox; } public FormCalculator(TextBox otherBox, Button otherButton) { InitializeComponent(); whichBox = otherBox; whichButton = otherButton; buttonNext = true; } private TextBox whichBox; private Button whichButton; bool buttonNext = false; private void addItem_Button_Item_Next_Click(object sender, EventArgs e) { whichBox.Text = txbPreview.Text; if (buttonNext) whichButton.PerformClick(); this.Close(); } private void btnClear_Click(object sender, EventArgs e) { txbPreview.Clear(); } private void btnNum1_Click(object sender, EventArgs e) { txbPreview.Text += "1"; } private void btnNum2_Click(object sender, EventArgs e) { txbPreview.Text += "2"; } private void btnNum3_Click(object sender, EventArgs e) { txbPreview.Text += "3"; } private void btnNum4_Click(object sender, EventArgs e) { txbPreview.Text += "4"; } private void btnNum5_Click(object sender, EventArgs e) { txbPreview.Text += "5"; } private void btnNum6_Click(object sender, EventArgs e) { txbPreview.Text += "6"; } private void btnNum7_Click(object sender, EventArgs e) { txbPreview.Text += "7"; } private void btnNum8_Click(object sender, EventArgs e) { txbPreview.Text += "8"; } private void btnNum9_Click(object sender, EventArgs e) { txbPreview.Text += "9"; } private void btnNum0_Click(object sender, EventArgs e) { txbPreview.Text += "0"; } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void FormCalculator_Load(object sender, EventArgs e) { txbPreview.Select(); // center the calculator int x = (Screen.PrimaryScreen.WorkingArea.Width / 2) - (this.Width / 2); int y = (Screen.PrimaryScreen.WorkingArea.Height/2) - (this.Height / 2); this.Location = new Point(x, y); } private void btnDot_FormCalculator_Click(object sender, EventArgs e) { txbPreview.Text += "."; } } }
a63417f8c8312886b85e8baabad04bba5b691d27
C#
matheus-maeda/PatoTelecom
/PatoTelecom/Plano.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PatoTelecom { class Plano { private string _id; private string _nome; private string _franquia; private string _caracteristicas; private string _mensalidade; private string _ci; public string Id { get => _id; set => _id = value; } public string Nome { get => _nome; set => _nome = value; } public string Franquia { get => _franquia; set => _franquia = value; } public string Caracteristicas { get => _caracteristicas; set => _caracteristicas = value; } public string Mensalidade { get => _mensalidade; set => _mensalidade = value; } public string Ci { get => _ci; set => _ci = value; } public Plano(string nome, string franquia, string caracteristica, string ci, string mensalidade) { Nome = nome; Franquia = franquia; Caracteristicas = caracteristica; Ci = ci; Mensalidade = mensalidade; } } }
0868697c413577f9fa333a760a92b9a35ccb2888
C#
IsaoOhnuki/PlainWpf
/PlainUtility/Behaviors/InkCanvasBehavior.cs
2.71875
3
using System; using System.Linq; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Ink; using System.Windows.Media.Imaging; using System.Windows.Media; namespace Behaviors { public class InkCanvasBehavior { private InkCanvas InkCanvas; public static ICollection<Stroke> GetStrokes(DependencyObject target) { return (ICollection<Stroke>)target.GetValue(StrokesProperty); } public static void SetStrokes(DependencyObject target, ICollection<Stroke> value) { target.SetValue(StrokesProperty, value); } private static readonly DependencyProperty StrokesProperty = DependencyProperty.RegisterAttached( "Strokes", typeof(ICollection<Stroke>), typeof(InkCanvasBehavior), new PropertyMetadata(null, OnStrokesChanged)); private static void OnStrokesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is InkCanvas inkCanvas) { var behavior = GetBehavior(inkCanvas); if (behavior != null) { if (e.OldValue is INotifyCollectionChanged oldStrokes) { oldStrokes.CollectionChanged -= behavior.strokes_CollectionChanged; } inkCanvas.Strokes.Clear(); } behavior = new InkCanvasBehavior(); SetBehavior(inkCanvas, behavior); if (e.NewValue is INotifyCollectionChanged newStrokes) { newStrokes.CollectionChanged += behavior.strokes_CollectionChanged; foreach (var val in e.NewValue as ICollection<Stroke>) { inkCanvas.Strokes.Add(val); } } } } private void strokes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: if (!canvasDraw) { foreach (var val in e.NewItems) { InkCanvas.Strokes.Add(val as Stroke); } } break; case NotifyCollectionChangedAction.Remove: foreach (var val in e.OldItems) { InkCanvas.Strokes.Remove(val as Stroke); } break; case NotifyCollectionChangedAction.Reset: InkCanvas.Strokes.Clear(); break; } } private static InkCanvasBehavior GetBehavior(DependencyObject target) { return (InkCanvasBehavior)target.GetValue(BehaviorProperty); } private static void SetBehavior(DependencyObject target, InkCanvasBehavior value) { target.SetValue(BehaviorProperty, value); } private static readonly DependencyProperty BehaviorProperty = DependencyProperty.RegisterAttached( "Behavior", typeof(InkCanvasBehavior), typeof(InkCanvasBehavior), new PropertyMetadata(null, OnBehaviorChanged)); private static void OnBehaviorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is InkCanvas inkCanvas) { if (e.OldValue is InkCanvasBehavior oldBehavior) { oldBehavior.InkCanvas.StrokeCollected -= InkCanvas_StrokeCollected; oldBehavior.InkCanvas.SizeChanged -= InkCanvas_SizeChanged; oldBehavior.InkCanvas = null; } if (e.NewValue is InkCanvasBehavior newBehavior) { newBehavior.InkCanvas = inkCanvas; newBehavior.InkCanvas.StrokeCollected += InkCanvas_StrokeCollected; newBehavior.InkCanvas .SizeChanged += InkCanvas_SizeChanged; } } } private bool canvasDraw; private static void InkCanvas_StrokeCollected(object sender, InkCanvasStrokeCollectedEventArgs e) { var behavior = GetBehavior(sender as DependencyObject); behavior.canvasDraw = true; GetStrokes(sender as DependencyObject)?.Add(e.Stroke); behavior.canvasDraw = false; } private static void InkCanvas_SizeChanged(object sender, SizeChangedEventArgs e) { InkCanvas inkCanvas = sender as InkCanvas; var sizeChanged = GetActualSizeChanged(inkCanvas); sizeChanged?.Invoke(e.NewSize); } public static Action<Size> GetActualSizeChanged(DependencyObject target) { return (Action<Size>)target.GetValue(ActualSizeChangedProperty); } public static void SetActualSizeChanged(DependencyObject target, Action<Size> value) { target.SetValue(ActualSizeChangedProperty, value); } private static readonly DependencyProperty ActualSizeChangedProperty = DependencyProperty.RegisterAttached( "ActualSizeChanged", typeof(Action<Size>), typeof(InkCanvasBehavior), new PropertyMetadata(null)); public static BitmapSource DrawStrokes(BitmapSource imageSource, ICollection<Stroke> strokes, Size strokeCanvasSize) { if (imageSource != null && strokes != null && strokeCanvasSize.Width > 0 && strokeCanvasSize.Height > 0) { DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext drawingContext = drawingVisual.RenderOpen()) { double imageSourceWidth = imageSource.PixelWidth * 96.0 / imageSource.DpiX; double imageSourceHeight = imageSource.PixelHeight * 96.0 / imageSource.DpiY; drawingContext.DrawImage(imageSource, new Rect(new Size(imageSourceWidth, imageSourceHeight))); var matrix = new Matrix(imageSourceWidth / strokeCanvasSize.Width, 0, 0, imageSourceHeight / strokeCanvasSize.Height, 0, 0); foreach (var stroke in strokes) { var val = stroke.Clone(); val.Transform(matrix, true); val.Draw(drawingContext); } } RenderTargetBitmap bitmap = new RenderTargetBitmap(imageSource.PixelWidth, imageSource.PixelHeight, imageSource.DpiX, imageSource.DpiY, PixelFormats.Pbgra32); bitmap?.Render(drawingVisual); return bitmap as BitmapSource; } else return imageSource; } } }
bc45a1766c1ebdbd1a2c9b98a66491faae09c616
C#
dktrotti/SaltyBid
/ShanghaiBloodSports/Assets/Scripts/Input/AutoAttackInputBuffer.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace Assets.Scripts.Input { public class AutoAttackInputBuffer : MonoBehaviour, IInputBuffer { public InputDevice Device { get; } = new DummyDevice(); private DateTime lastAttackTime = DateTime.MinValue; public int secondsBetweenAttacks; public bool Match(InputSequence sequence) { var now = DateTime.Now; if (now > lastAttackTime.AddSeconds(secondsBetweenAttacks)) { lastAttackTime = now; return true; } return false; } public bool Peek(InputSequence sequence) { return false; } } public class DummyDevice : InputDevice { public InputState GetInputState() { return new InputState(JoystickPosition.NEUTRAL); } } }
51871a88cfdc7188bc5efb6aecc03b0b9e2ac1fb
C#
Glassification/Concierge
/Concierge.Tools/DiceRoller/ShuntingYard.cs
3.359375
3
// <copyright file="ShuntingYard.cs" company="Thomas Beckett"> // Copyright (c) Thomas Beckett. All rights reserved. // </copyright> namespace Concierge.Tools.DiceRoller { using System.Collections.Generic; using System.Linq; /// <summary> /// Provides methods for converting infix expressions to postfix expressions using the Shunting Yard algorithm. /// </summary> public static class ShuntingYard { private static readonly IDictionary<string, Operator> operators = new[] { new Operator("^", 4, true), new Operator("*", 3, false), new Operator("/", 3, false), new Operator("+", 2, false), new Operator("-", 2, false), }.ToDictionary(x => x.Symbol); /// <summary> /// Converts a list of tokens in infix notation to a postfix notation using the Shunting Yard algorithm. /// </summary> /// <param name="list">The list of tokens in infix notation.</param> /// <returns>A stack representing the list of tokens in postfix notation.</returns> public static Stack<object> ToPostfix(List<object> list) { var stack = new Stack<object>(); var output = new List<object>(); foreach (object token in list) { if (token is int obsoleteInt) { output.Add(obsoleteInt); } else if (token is DiceRoll diceRoll) { output.Add(diceRoll); } else if (token is string str && operators.TryGetValue(str, out Operator? op1)) { while (stack.Count > 0 && stack.Peek() is string str2 && operators.TryGetValue(str2, out Operator? op2)) { int c = op1?.Precedence.CompareTo(op2?.Precedence) ?? 0; if (c < 0 || (!(op1?.RightAssociative ?? false) && c <= 0)) { output.Add(stack.Pop()); } else { break; } } stack.Push(token); } } while (stack.Count > 0) { var top = stack.Pop(); output.Add(top); } output.Reverse(); return new Stack<object>(output); } } }
66a7701224c1247274e64c7157bb8d4c42218dde
C#
jkendev/Distributed-Brute-Force-Password-Recovery
/RecoveryManagerLibrary/PWBatch.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RecoveryManagerLibrary { /// <summary> /// A Struct to be passed across a network to a service. Smaller size than the PWBatch object! /// </summary> public struct Batch { public long startPermNumber; //Starting permutation number public long endPermNumber; //Ending permutation number public String jobID; public String encryptedPW; public char[] charSet; //Char set the password was constructed from. public int pwLength; //Length of plain texst password. /// <summary> /// Constructor for the above Struct. /// </summary> public Batch(long startPermNumber, long endPermNumber, String jobID, String encryptedPW, char[] charSet, int pwLength) : this() { this.startPermNumber = startPermNumber; this.endPermNumber = endPermNumber; this.jobID = jobID; this.encryptedPW = encryptedPW; this.charSet = new char[charSet.Length]; Array.Copy(charSet, this.charSet, charSet.Length); //Source, Destination, legnth. this.pwLength = pwLength; } } /// <summary> /// NAME: PWBatch /// PURPOSE: To wrap the Batch struct and hold other housekeeping data /// REMARKS: The services don't need to know about the housekeeping data. Thats why they are given a struct, not an object. /// Also, the PWBatch object allows a convenient way to implement the IEquitable interface, making it usable /// in several container classes (List and Queue). /// </summary> internal class PWBatch : System.IEquatable<PWBatch> { private Batch batch; //Struct of batch info private DateTime timeAssigned; //Time the batch was assigned. (well, created, but they are assigned very quickly after being created) private IRecoveryManagerServiceCallback assignedService; //The service this batch was assigned to. /// <summary> /// Constructor /// </summary> /// <param name="startPermNumber"> starting permutation number of the batch. </param> /// <param name="endPermNumber"> ending permutation of the batch - inclusive. </param> /// <param name="jobID"> ID of job the batch belongs to. </param> /// <param name="encryptedPW"> Encrypted form of password. </param> /// <param name="charSet"> char set the pw was formed from. </param> /// <param name="pwLength"> Length of plain text password. </param> public PWBatch(long startPermNumber, long endPermNumber, String jobID, String encryptedPW, char[] charSet, int pwLength) { batch = new Batch(startPermNumber, endPermNumber, jobID, encryptedPW, charSet, pwLength); timeAssigned = DateTime.Now; } public void setAssignedService(IRecoveryManagerServiceCallback service) { this.assignedService = service; } public IRecoveryManagerServiceCallback getAssignedService() { return this.assignedService; } /// <summary> /// An almost copy constructor. Takes the struct part of the batch and creates a new one. /// </summary> /// <param name="inBatch"></param> public PWBatch(Batch inBatch) { this.timeAssigned = DateTime.Now; this.batch = inBatch; } /// <summary> /// Restarts the age of the batch (by setting time assigned to now). /// </summary> public void restartAge() { this.timeAssigned = DateTime.Now; } /// <summary> /// Gets the age in milliseconds. /// </summary> /// <returns></returns> public long ageInMilliseconds() { DateTime current = DateTime.Now; TimeSpan ts = current - this.timeAssigned; return (long)ts.TotalMilliseconds; } /// <summary> /// Gets the starting permutation number /// </summary> /// <returns></returns> public double getStartPermNumber() { return batch.startPermNumber; } /// <summary> /// Gets the ending permutation number. /// </summary> /// <returns></returns> public double getEndPermNumber() { return batch.endPermNumber; } /// <summary> /// Gets the inner Struct that wraps the batch data. /// </summary> /// <returns></returns> public Batch getBatch() { return batch; } //Needed for aList.Contains(someBatch) method in a list of password batches. /// <summary> /// Implementation of Equals method from IEquitable interface. /// </summary> /// <param name="other"></param> /// <returns></returns> /// <remarks> Needed so that this class can be used in List and Queue. /// Matches on jobID, startPermNum and endPermNum /// All else is irrelevant for the container class usage that I've implemented /// </remarks> public Boolean Equals(PWBatch other) { Batch otherBatch = other.getBatch(); return batch.jobID.Equals(otherBatch.jobID) && batch.startPermNumber == otherBatch.startPermNumber && batch.endPermNumber == otherBatch.endPermNumber; } } }
c913f1813aba949adc1a5f23ccc8f0835e928aca
C#
GBarrera817/SW1_ISO9126_FUZZY
/SW1_ISO9126_FUZZY/Logica Difusa/ImplicacionDifusa.cs
2.890625
3
namespace SW1_ISO9126_FUZZY.Logica_Difusa { /// <summary> /// Clase para la implicación de la lógica difusa. /// </summary> public static class ImplicacionDifusa { /// <summary> /// Realiza la implicación, recibe el valor resultante de aplicar el operador /// a la regla evaluada. /// </summary> /// <param name="resultadoOperadorDifuso"></param> /// <param name="valorLinguistico"></param> /// <returns></returns> public static ValorLinguistico EjecutarImplicacion( double resultadoOperadorDifuso, ValorLinguistico valorLinguistico) { ValorLinguistico resultado = new ValorLinguistico(valorLinguistico.Nombre, valorLinguistico.FuncionMembresia); // Obtenemos el grado de pertenencia y cortamos la función de pertenencia en ese grado. //VOLVER A COMENTAR ESTA LÍNEA resultado.FuncionMembresia.CortarFuncion(resultadoOperadorDifuso); valorLinguistico.FuncionMembresia.CortarFuncion(resultadoOperadorDifuso); resultado.ValorMembresia = resultado.FuncionMembresia.ValorCorte; return resultado; } } }
3ea0282ebb1f917a17f9bde2d09609a6f74d76ad
C#
iosdevzone/excel-mapper
/src/Mappers/DictionaryMapper.cs
3.34375
3
using System; using System.Collections.Generic; using ExcelMapper.Abstractions; namespace ExcelMapper.Mappers { /// <summary> /// Tries to map the value of a cell to an object using a mapping dictionary. /// </summary> public class DictionaryMapper<T> : ICellValueMapper { /// <summary> /// Gets the dictionary used to map the value of a cell to an object. /// </summary> public IReadOnlyDictionary<string, T> MappingDictionary { get; } /// <summary> /// Constructs a mapper that tries to map the value of a cell to an object using a mapping dictionary. /// </summary> /// <param name="mappingDictionary">The dictionary used to map the value of a cell to an object.</param> /// <param name="comparer">The equality comparer used to the value of a cell to an object.</param> public DictionaryMapper(IDictionary<string, T> mappingDictionary, IEqualityComparer<string> comparer) { if (mappingDictionary == null) { throw new ArgumentNullException(nameof(mappingDictionary)); } MappingDictionary = new Dictionary<string, T>(mappingDictionary, comparer); } public CellValueMapperResult MapCellValue(ReadCellValueResult readResult) { // If we didn't find anything, keep going. This is not necessarily a fatal error. if (!MappingDictionary.TryGetValue(readResult.StringValue, out T result)) { return CellValueMapperResult.Ignore(); } return CellValueMapperResult.Success(result); } } }
9db830f3268320bc925ccff4941f3c79abdaa54d
C#
lc8882972/RateLimiters
/sample/Hello/State.cs
3.15625
3
using System; namespace Hello.State { // 状态模式 class Context { State state; public Context(State state) { this.state = state; } public State State { get; set; } public void Request() { state.Handle(this); } } abstract class State { public abstract void Handle(Context context); } class ConcreteStateA : State { public override void Handle(Context context) { context.State = new ConcreteStateB(); } } class ConcreteStateB : State { public override void Handle(Context context) { context.State = new ConcreteStateA(); } } }
3c092315813035af7b469d5aa78798e4aa52c7c9
C#
hlimbo/MathNinja
/Assets/Scripts/NumberText.cs
2.890625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; //use this class as a workaround for text values not updating sometimes [RequireComponent(typeof(TextMeshPro))] public class NumberText : MonoBehaviour { private TextMeshPro tmp; //use this variable to compare against integer values as opposed to its text property value public int value; public string text { get { return tmp.text; } set { tmp.text = value; } } private void Awake() { tmp = GetComponent<TextMeshPro>(); Debug.Assert(tmp != null); } public Vector2 GetPreferredValues() { return tmp.GetPreferredValues(); } public Vector2 GetPreferredValues(float width,float height) { return tmp.GetPreferredValues(width, height); } public Vector2 GetPreferredValues(string text) { return tmp.GetPreferredValues(text); } public Vector2 GetPreferredValues(string text,float width,float height) { return tmp.GetPreferredValues(text, width, height); } }
5241c2a1518cfa911d6fcbdb93d45e9f0651f259
C#
gentringer/Webservices
/webservices/Library-Webservice/RemotingPartage/Livre.cs
2.703125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RemotingPartage2 { public class Livre : MarshalByRefObject, RemotingInterfaces.ILivre { private String auteur; private String titre; private String isbn; private String editeur; private String nombreExamplaire; private List<string> commentaires; // Constructeur public Livre(String auteur, String titre, String isbn, String editeur, String nombreex) { this.auteur = auteur; this.titre = titre; this.isbn = isbn; this.editeur = editeur; this.nombreExamplaire = nombreex; this.commentaires = new List<String>(); } //Getter / setters pour Auteur etc. public String Auteur { get { return this.auteur; } } public String Titre { get { return this.titre; } } public String Isbn { get { return this.isbn; } } public String Editeur { get { return this.editeur; } } public String NombreExamplaire { get { return this.nombreExamplaire; } set { this.nombreExamplaire = value; } } public List<string> Commentaires { get { return this.commentaires; } } public String Affiche() { String affiche = ""; affiche += "Nom Livre :\t" + this.Titre + "\n"; affiche += "Auteur :\t" + this.Auteur + "\n"; affiche += "Editeur :\t" + this.Editeur + "\n"; affiche += "ISBN13 :\t" + this.Isbn + "\n"; affiche += "Examplaire :\t" + this.NombreExamplaire + "\n"; return affiche; } } }
f8efa0152ed5a1ca8cd44d6c44da92838bf9e6f6
C#
swcarrier/SteamCompletionTime
/SteamCompletionTime/Form1.cs
2.703125
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; using System.Xml; using RestSharp; namespace SteamCompletionTime { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void GetListButton_Click(object sender, EventArgs e) { var steamId = steamIdTextBox.Text; if (string.IsNullOrEmpty(steamId)) { resultsTextBox.Text = "Enter a steam id"; return; } var client = new RestClient("http://steamcommunity.com"); var response = client.Get(new RestRequest(string.Format("/id/{0}/games/?tab=all&xml=1",steamId))); if (response.StatusCode != HttpStatusCode.OK) { resultsTextBox.Text = response.Content; return; } var games = new Dictionary<string, GameInfo>(); using (XmlReader reader = XmlReader.Create(new StringReader(response.Content))) { while (reader.ReadToFollowing("name")) { reader.Read(); if (reader.NodeType == XmlNodeType.CDATA) { var gameName = reader.Value; gameName = Regex.Replace(gameName, @" - ", " ");//replace - with space gameName = Regex.Replace(gameName, @"[^a-zA-Z0-9 ,.-]", string.Empty); //strip non-ascii gameName = Regex.Replace(gameName, "Enhanced Edition", "", RegexOptions.IgnoreCase); gameName = Regex.Replace(gameName, "Game of the Year.*", "", RegexOptions.IgnoreCase); gameName = Regex.Replace(gameName, "GOTY.*", "", RegexOptions.IgnoreCase); if (!games.ContainsKey(gameName)) games.Add(gameName, new GameInfo{Name = gameName}); } } } resultsTextBox.Text = string.Format("Loading {0} games", games.Keys.Count); resultsTextBox.Refresh(); client = new RestClient("http://www.howlongtobeat.com"); foreach (var name in games.Keys.ToList()) { var request = new RestRequest("/search_main.php?t=games&page=1&sorthead=&sortd=Normal&plat=&detail=0"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("queryString", name, ParameterType.GetOrPost); client.PostAsync(request, (asyncResponse, handle) => HandleResponse(games, name, asyncResponse)); Thread.Sleep(100); } while (games.Values.Any(g => !g.Retrieved)) { Thread.Sleep(500); } var sortedList = games.Values.ToList().OrderByDescending(t => t.Hours).Select(t => t.Name + " - " + t.Hours); resultsTextBox.Text = string.Join("\r\n", sortedList.ToArray()); } private void HandleResponse(Dictionary<string, GameInfo> games, string name, IRestResponse response) { games[name].Retrieved = true; var doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(response.Content); var node = doc.DocumentNode.SelectSingleNode("//div[contains(@class, 'gamelist_tidbit time_')]"); if (node == null) return; var hours = node.InnerText; hours = Regex.Replace(hours, " Hours", ""); hours = Regex.Replace(hours, "&#189;", ".5"); var hoursFloat = 0.0f; float.TryParse(hours, out hoursFloat); games[name].Hours = hoursFloat; } } internal class GameInfo { public string Name { get; set; } public float Hours { get; set; } public bool Retrieved { get; set; } } }
0e6f7f64179a77e73a64b793dcba7215419fab91
C#
shendongnian/download4
/latest_version_download2/209185-44740183-150138252-4.cs
2.5625
3
public sealed class WebSaveActivity : NativeActivity { public InArgument<MyBigObject> ObjectToSave { get; set; } protected override bool CanInduceIdle { get { // This notifies the WF engine that the activity can be unloaded / persisted to an instance store. return true; } } protected override void Execute(NativeActivityContext context) { var currentBigObject = this.ObjectToSave.Get(context); currentBigObject.WorkflowInstanceId = context.WorkflowInstanceId; StartSaveOperationAsync(this.ObjectToSave.Get(context)); // This method should offload the actual save process to a thread or even a web method, then return immediately. // This tells the WF engine that the workflow instance can be suspended and persisted to the instance store. context.CreateBookmark("MySaveOperation", AfterSaveCompletesCallback); } private void AfterSaveCompletesCallback(NativeActivityContext context, Bookmark bookmark, object value) { // Do more things after the save completes. var saved = (bool) value; if (saved) { // yay! } else { // boo!!! } } }