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
5dfe70c870023040679644179332744d079987a2
C#
Anil1111/Programming-Fundamentals-2017
/07. OBJECTS AND CLASSES LAB AND EXCERCISE/06. Sales Report/6.Sales report.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Sale { public string Town { get; set; } public string Product { get; set; } public double Price { get; set; } public double Quantity { get; set; } public static Sale ReadSale() { var sale = Console.ReadLine().Split(' ').ToList(); Sale currentSale = new Sale() {Town = sale[0],Product = sale[1],Price = double.Parse(sale[2]), Quantity =double.Parse(sale[3]) }; return currentSale; } } class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); List<Sale> salesDataBase = new List<Sale>(); for (int i = 0; i < n; i++) { Sale currentSale = Sale.ReadSale(); salesDataBase.Add(currentSale); } var sortedByTown = salesDataBase.OrderBy(x => x.Town).ToList(); Dictionary<string,List<double>> finalresult = new Dictionary<string,List<double>>(); foreach (var cuurentSale in sortedByTown) { var priceQuantity = cuurentSale.Price * cuurentSale.Quantity; if (!finalresult.ContainsKey(cuurentSale.Town)) { finalresult[cuurentSale.Town] = new List<double>(); finalresult[cuurentSale.Town].Add(priceQuantity); } else { finalresult[cuurentSale.Town].Add(priceQuantity); } } foreach (var kvp in finalresult) { var totalSum = kvp.Value; Console.Write($"{kvp.Key} -> {kvp.Value}"); } } }
f86c6ddd83bab1dba25ea04852997fa0d4c69570
C#
vlado-b/rx-playground
/WPF-Application/WpfApplication1/MainWindow.xaml.cs
2.734375
3
using Newtonsoft.Json; using System; using System.Net.Http; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Controls; namespace WpfApplication1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow { public MainWindow() { InitializeComponent(); var amountStream = Observable.FromEventPattern<TextChangedEventArgs>(amount, "TextChanged") .Select(x => (x.Sender as TextBox).Text) .Where(x => int.TryParse(x, out var result)) .Select(int.Parse) .Where(x => x > 0) .Throttle(TimeSpan.FromMilliseconds(100)) .ObserveOn(SynchronizationContext.Current); var currencySelectionStream = Observable.FromEventPattern(radioUSD, "Checked") .Merge( Observable.FromEventPattern(radioGBP, "Checked") ) .Merge( Observable.FromEventPattern(radioEUR, "Checked") ) .Merge( Observable.FromEventPattern(radioDEN, "Checked") ) .Merge( Observable.FromEventPattern(radioBTC, "Checked") ) .Select(x => (x.Sender as RadioButton)?.Content.ToString()) .ObserveOn(SynchronizationContext.Current); amountStream.CombineLatest(currencySelectionStream, (amount, currency) => new {Amount = amount, Currency = currency}) .DistinctUntilChanged() .SubscribeOn(NewThreadScheduler.Default) .SelectMany(x => Observable.FromAsync(a => ConvertAmount(x.Currency, x.Amount))) .ObserveOn(SynchronizationContext.Current) .Subscribe(result => { PrependToLog($"Rx: result {result}"); convertedAmounth.Text = result.ToString(); }, error => PrependToLog($"error in stream {error.Message}"), () => PrependToLog("Stream completed") ); ; } private void PrependToLog( string text) { debugLog.Text = text + Environment.NewLine + debugLog.Text; } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { debugLog.Text = amount.Text + Environment.NewLine + debugLog.Text ; } private void Button_Click_Increment(object sender, System.Windows.RoutedEventArgs e) { var tbValue = amount.Text; if( int.TryParse( tbValue.Trim(), out int parsedValue )) { amount.Text = (++parsedValue).ToString(); } } private void Button_Click_Decrement(object sender, System.Windows.RoutedEventArgs e) { var tbValue = amount.Text; if (int.TryParse(tbValue.Trim(), out int parsedValue)) { amount.Text = (--parsedValue).ToString(); } } private void RadioButton_Checked(object sender, System.Windows.RoutedEventArgs e) { return; if( sender is RadioButton radioButton ) { var currency = radioButton.Content.ToString(); debugLog.Text = currency + Environment.NewLine + debugLog.Text; if (int.TryParse(amount.Text.Trim(), out int parsedAmount)) { Task.Run(async () => { var convertedAmount = await ConvertAmount(currency, parsedAmount); Dispatcher.Invoke(() => { debugLog.Text = "converted amount: " + convertedAmount + Environment.NewLine + debugLog.Text; convertedAmounth.Text = convertedAmount.ToString(); }); }); } } } private async Task<double> ConvertAmount(string targetCurrency, int amount ) { var result = 0d; using( var client = new HttpClient()) { var response = await client.GetStringAsync( $"http://localhost:3000/convert/usd/{targetCurrency}/{amount}" ); // sends GET request result = JsonConvert.DeserializeObject<ConvertedResult>(response).Result; } return result; } } internal class ConvertedResult { public string From { get; set; } public string To { get; set; } public double Amount { get; set; } public double Result { get; set; } } }
6298162e996cd7e7f314c81238976a6bcd8010d4
C#
SimonAi1801/csharp_samples_events_producerconsumer-template
/source/ProducerConsumer/ProducerConsumer.Wpf/MainWindow.xaml.cs
2.765625
3
using ProducerConsumer.Core; using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Windows; namespace ProducerConsumer.Wpf { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow { private Producer _producer; private Consumer _consumer; private Queue<Task> _queue; public MainWindow() { InitializeComponent(); } /// <summary> /// Producer, Consumer und Queue erzeugen. Observer anmelden und /// Simulation starten /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonStart_Click(object sender, RoutedEventArgs e) { TextBlockLog.Text = ""; _queue=new Queue<Task>(); int min = Convert.ToInt32(TextBoxProducerMinimum.Text); int max = Convert.ToInt32(TextBoxProducerMaximum.Text); //_producer = new Producer(min, max, LogTask, _queue); min = Convert.ToInt32(TextBoxConsumerMinimum.Text); max = Convert.ToInt32(TextBoxConsumerMaximum.Text); //_consumer = new Consumer(min, max, _queue); CheckBoxIsRunning.IsChecked = true; } /// <summary> /// Fügt eine Zeile zur Textbox hinzu. /// Da Timer in eigenem Thread läuft ist ein Threadwechsel mittels Invoke /// notwendig /// </summary> /// <param name="line"></param> void AddLineToTextBox(string line) { StringBuilder text = new StringBuilder(TextBlockLog.Text); text.Append(FastClock.Instance.Time.ToShortTimeString() + "\t"); text.Append(line + "\n"); TextBlockLog.Text = text.ToString(); } private void CheckBoxIsRunning_Click(object sender, RoutedEventArgs e) { FastClock.Instance.IsRunning = CheckBoxIsRunning.IsChecked == true; } } }
e5e14af0cd92f2038f894d73667db93f375fb614
C#
Suliac/TP-Jenkins
/Tests-Jenkins/CalculTest.cs
2.796875
3
using NUnit.Framework; using System; namespace TestsJenkins { /// <summary> /// Test class to test calcul function /// </summary> [TestFixture] public class CalculTest { /// <summary> /// Test method for Add function /// </summary> [Test] public void TestAdd() { Assert.AreEqual(TPJenkins.Program.Add(2, 3), 5); } /// <summary> /// Test method for division function /// </summary> [Test] public void TestDiv() { Assert.AreEqual(TPJenkins.Program.Div(6, 2), 3); } /// <summary> /// Test methode for division by zero /// </summary> [Test] public void TestDivByZero() { Assert.Throws<DivideByZeroException>(() => TPJenkins.Program.Div(6, 0)); } } }
92df337229bddbda9814e2b4bb242cd8d2fe73e5
C#
ianrkent/codesmellkata
/MessageChainsBonus/Customer.cs
2.65625
3
namespace MessageChainsBonus { public class Customer { public Customer(Address address) { this.Address = address; } public Address Address { get; private set; } } }
3e8a8924e3136c3fd548226d7dd617bbecde1c0a
C#
chaosifier/MultiGestureView
/Source/MultiGestureViewPlugin.Portable/MultiGestureView.cs
2.78125
3
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace MultiGestureViewPlugin { /// <summary> /// A ContentView with built-in gesture recognizers. /// </summary> public class MultiGestureView : ContentView { /// <summary> /// Enable vibration on long press. /// </summary> public bool VibrateOnLongPress { get; set; } /// <summary> /// Vibration duration in milliseconds on long press. The default value is 100ms. /// </summary> public int LongPressVibrationDuration { get; set; } = 100; /// <summary> /// Enable vibration on tap. /// </summary> public bool VibrateOnTap { get; set; } /// <summary> /// Vibration duration in milliseconds on tap. The default value is 100ms. /// </summary> public int TapVibrationDuration { get; set; } = 100; /// <summary> /// Long press event. /// If the Content or its children have gesture recognizers set, in order to prevent gesture conflicts, it is recommended to set their InputTransparent property to True. /// </summary> public event EventHandler LongPressed { add { LongPressedHandler += value; } remove { LongPressedHandler -= value; } } public EventHandler LongPressedHandler; /// <summary> /// Tap event. /// If the Content or its children have gesture recognizers set, in order to prevent gesture conflicts, it is recommended to set their InputTransparent property to True. /// </summary> public event EventHandler Tapped { add { TappedHandler += value; } remove { TappedHandler -= value; } } public EventHandler TappedHandler; /// <summary> /// Right click event. Only works on UWP. /// </summary> public event EventHandler RightClicked { add { RightClickedHandler += value; } remove { RightClickedHandler -= value; } } public EventHandler RightClickedHandler; } }
ef04c21322804b16903bd46583c5c8a995ba09aa
C#
medeirosgabriel/csharp_basic
/Variable_Scope/Variable_Scope.cs
3.046875
3
using System; class Variable_Scope { static int num3 = 3; // Static to use in the static method static void Main() { int num1 = 1; Console.WriteLine(num1); Console.WriteLine(num3); test(); } static void test() { int num2 = 2; // Console.WriteLine(num1); Error Console.WriteLine(num2); Console.WriteLine(num3); } }
1c3469a7e9efe7d163ea824d531036288855f409
C#
nicgalehouse/AODamageMeter
/AODamageMeter/FightEvents/Heal/MeGotHealth.cs
2.96875
3
using System; using System.Text.RegularExpressions; namespace AODamageMeter.FightEvents.Heal { // When someone heals you (via a nano, HoT, first aid, treatment kit, etc), a sourced event gets created with // the amount that you could've been healed for, if you were hurt enough, and an unsourced event gets created // with the amount you were actually healed for (if you weren't hurt at all, no events get created). When you // heal yourself (via a nano, heal delta, etc), there's a single unsourced event. I'm going to assume that the // events are always in order--that if there's a sourced event, the corresponding unsourced event immediately // follows it in the chain of MeGotHealth events. Seems to be the case, but not sure. public class MeGotHealth : HealEvent { public const string EventName = "Me got health"; public override string Name => EventName; protected static MeGotHealth _latestStartEvent; public static readonly Regex Sourced = CreateRegex($"You got healed by {SOURCE} for {AMOUNT} points of health."), Unsourced = CreateRegex($"You were healed for {AMOUNT} points."); public MeGotHealth(Fight fight, DateTime timestamp, string description) : base(fight, timestamp, description) { SetTargetToOwner(); if (TryMatch(Sourced, out Match match)) { SetSource(match, 1); HealType = HealType.PotentialHealth; SetAmount(match, 2); _latestStartEvent = this; } else if (TryMatch(Unsourced, out match)) { HealType = HealType.RealizedHealth; SetAmount(match, 1); if (_latestStartEvent != null && _latestStartEvent.Fight == fight) { Source = _latestStartEvent.Source; StartEvent = _latestStartEvent; _latestStartEvent.EndEvent = this; _latestStartEvent = null; } else { SetSourceToOwner(); } } else IsUnmatched = true; } } }
ddd9929c5cc96967f62f5d42762ee8629deb7b3a
C#
viniciusmzo/URI
/1042/1042/Program.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1042 { class Program { static void Main(string[] args) { string[] vet = Console.ReadLine().Split(' '); List<int> listaOrdenada = new List<int>(); for (int i = 0; i < 3; i++) { listaOrdenada.Add(int.Parse(vet[i])); } listaOrdenada.Sort(); foreach (int num in listaOrdenada) { Console.WriteLine(num); } Console.WriteLine(); for (int i = 0; i < 3; i++) { Console.WriteLine(vet[i]); } Console.ReadKey(); } } }
92dc3011e37e846ccdec6d67936e52bb51168fa3
C#
jogibear9988/nugget
/src/Nugget.Server/EventArguments/DataReceivedEventArgs.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nugget.Server { public class DataReceivedEventArgs : EventArgs { public IEnumerable<DataFragment> Fragments { get; set; } public DataReceivedEventArgs(IEnumerable<DataFragment> fragments) { Fragments = fragments; } [Obsolete("GetFragmentPayloadAsString is not just here for convenience while I get the server working for the new protocol", false)] public string GetFragmentPayloadAsString() { var sb = new StringBuilder(); foreach (var f in Fragments) { if (f.Masked) f.UnMaskPayload(); sb.Append(Encoding.UTF8.GetString(f.GetPayload())); } return sb.ToString(); } } }
1118d1ede835176d3310894fb9e8049d9036b417
C#
AndrMint/Builder
/Kursai/05-23PirmaPaskaita/05-23PirmaPaskaita/Modulis.cs
3.0625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _05_23PirmaPaskaita { class Modulis { public string Pavadinimas { get; private set; } public int KredituSkaicius { get; private set; } public string Kodas { get; private set; } public int StudentuSkaicius { get; private set; } public string KoordVardas { get; private set; } public string KoordPavarde { get; private set; } public Modulis () { Console.Write("Pavadinimas: "); Pavadinimas = Console.ReadLine(); Console.Write("Kreditu skaicius: "); KredituSkaicius = Convert.ToInt32(Console.ReadLine()); Console.Write("Kodas: "); Kodas = Console.ReadLine(); Console.WriteLine("Studentu skaicius: "); StudentuSkaicius = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Koordinatoriaus vardas: "); KoordVardas = Console.ReadLine(); Console.WriteLine("Koordinatoriaus pavarde: "); KoordPavarde = Console.ReadLine(); } public Modulis(string pavadinimas, int kreditai, string kodas, int studentai, string koordVardas, string koordPavarde) { Pavadinimas = pavadinimas; KredituSkaicius = kreditai; Kodas = kodas; StudentuSkaicius = studentai; KoordVardas = koordVardas; KoordPavarde = koordPavarde; } public void Isvedimas() { Console.WriteLine("Modulis: {0} (kodas: {1})", Pavadinimas, Kodas); Console.WriteLine("Kreditu skaicius: {0}", KredituSkaicius); Console.WriteLine("Studentu skaicius: {0}", StudentuSkaicius); Console.WriteLine("Koordinatoriaus vardas: {0}", KoordVardas); Console.WriteLine("Koordinatoriaus pavarde: {0}", KoordPavarde); } } }
91b19df072889d3e860a5fb057f58b0c1e7996b6
C#
colotu/xxShop
/Lib/CS/YSWL.Common/Mail/EmailConvert.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Net.Mail; using System.Globalization; namespace YSWL.Common.Mail { public static class EmailConvert { public static string ToDelimitedString(ICollection collection, string delimiter) { if (collection == null) { return string.Empty; } StringBuilder builder = new StringBuilder(); if (collection is Hashtable) { foreach (object obj2 in ((Hashtable)collection).Keys) { builder.Append(obj2.ToString() + delimiter); } } if (collection is ArrayList) { foreach (object obj3 in (ArrayList)collection) { builder.Append(obj3.ToString() + delimiter); } } if (collection is string[]) { foreach (string str in (string[])collection) { builder.Append(str + delimiter); } } if (collection is MailAddressCollection) { foreach (MailAddress address in (MailAddressCollection)collection) { builder.Append(address.Address + delimiter); } } return builder.ToString().TrimEnd(new char[] { Convert.ToChar(delimiter, CultureInfo.InvariantCulture) }); } } }
b5ff7037e197189166aa8be1487c86eae8e108d1
C#
jhartwell/FSystem
/src/FSystem.Common/JsonFormat.cs
3.328125
3
using System; using System.Collections.Generic; using FSystem.Common.Interfaces; using Newtonsoft.Json; namespace FSystem.Common { /// <summary> /// Concrete implementation of <see cref="IFormat"/> /// </summary> public class JsonFormat : IFormat { /// <summary> /// Formats the given value to Json /// </summary> /// <returns>A string that contains the serialized Json.</returns> /// <param name="value">The object that is going to be serialized /// into JSON</param> /// <typeparam name="T">The type of the object that is going to be /// formatted.</typeparam> public string Format<T>(T value) { return JsonConvert.SerializeObject(new { items = value }); } } }
cfbb9351fbc56061d486cf11912b187bec702477
C#
phil11971/OtherSorting
/CircleSort/Program.cs
3.6875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CircleSorting { class Program { static void Main(string[] args) { int[] mas = new int[] { 9, 6, 10, 8, 43, 2, 6, 24, 6 }; Console.WriteLine("Src mas"); PrintMas(mas); CircleSort(mas); Console.WriteLine("Res mas"); PrintMas(mas); Console.ReadKey(); } public static void CircleSort(int[] arr) { if (arr.Length > 0) while (CircleSortR(arr, 0, arr.Length - 1, 0) != 0); } private static int CircleSortR(int[] arr, int lo, int hi, int numSwaps) { if (lo == hi) return numSwaps; int high = hi; int low = lo; int mid = (hi - lo) / 2; while (lo < hi) { if (arr[lo] > arr[hi]) { Swap(arr, lo, hi); numSwaps++; } lo++; hi--; } if (lo == hi && arr[lo] > arr[hi + 1]) { Swap(arr, lo, hi + 1); numSwaps++; } numSwaps = CircleSortR(arr, low, low + mid, numSwaps); numSwaps = CircleSortR(arr, low + mid + 1, high, numSwaps); return numSwaps; } private static void Swap(int[] arr, int idx1, int idx2) { int tmp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = tmp; } static void PrintMas(int[] arr) { for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " "); Console.WriteLine(); } } }
e0033fb412cc603efdb84dcf4469b03068e37874
C#
FernandoMX13/POO-CSharp
/Serie/Ejercicio7/Program.cs
4.125
4
/* Creancion suma de dos numeros complejos mediante el uso de una clase de numero complejo. */ using System; namespace Ejercicio7 { class Program { //Esta funcion realiza la operacion de la suma de numeros complejos mediante sus atributos. static NumeroComplejo Sumar(NumeroComplejo nc1, NumeroComplejo nc2) { NumeroComplejo resultado = new NumeroComplejo(nc1.pr+nc2.pr, nc1.pi + nc2.pi); return resultado; } static void Main(string[] args) { //Creaciom de lo numeros complejos NumeroComplejo NC1 = new NumeroComplejo(1,-3); NumeroComplejo NC2 = new NumeroComplejo(0, 2); //Mostrando los numeros complejos Console.WriteLine("Primer numero complejo"); Console.WriteLine(NC1.Imprimir()+"\n"); Console.WriteLine("Segundo numero complejo"); Console.WriteLine(NC2.Imprimir() + "\n"); //Realizacion de la suma de numeros complejos. var res = Sumar(NC1, NC2); Console.WriteLine("\nEl resultado de la suma de {0} con {1} es: {2}\n", NC1.Imprimir(), NC2.Imprimir(), res.Imprimir()); Console.WriteLine("\nPresiona cualquier tecla para salir."); Console.ReadKey(); } } }
cf36a400129a3e4279ec773da359cd74bd6f9b62
C#
ilkera/InterviewHacker
/Array/MergeArrayIntoLarger.linq
3.125
3
<Query Kind="Program" /> void Main() { int[] small = {1, 4, 7}; int[] large = {2, 3, 8, 12, 14, 0, 0, 0, 0}; MergeArray(large, small, 4); large.Dump(); } public static void MergeArray(int[] large, int[] small, int largeEndIndex) { if (large.Length == largeEndIndex + 1 || small.Length + largeEndIndex > large.Length) { throw new Exception("No empty spot left"); } int currentEnd = largeEndIndex + small.Length; int currentLarge = largeEndIndex; int currentSmall = small.Length - 1; while (currentSmall >= 0 && currentLarge >= 0) { if (large[currentLarge] < small[currentSmall]) { large[currentEnd] = small[currentSmall--]; } else { large[currentEnd] = large[currentLarge--]; } currentEnd--; } while (currentSmall >= 0) { large[currentEnd--] = small[currentSmall--]; } } // Define other methods and classes here
db60616bb75f59f524971e92d8e621a3ca9355d3
C#
alexfrstnberg/CrashCourseAT
/Projects/Team1/Semeniuk/OpenCartSeleniumTests/SeleniumTests/DBWork.cs
2.703125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; namespace SeleniumTests { class DBWork { private static readonly string _connectionString = @"Data Source=127.0.0.1;port=3309;username=admin;password=admin;Initial Catalog=storedb;Integrated Security=True"; public static void ExecuteQuery(string queryString) { try { using (var databaseConnection = new MySqlConnection(_connectionString)) { databaseConnection.Open(); using (var command = new MySqlCommand(queryString, databaseConnection)) { command.ExecuteScalar(); } } } catch (Exception ex) { Console.WriteLine(ex.Message); //throw ex; } } public static void DeleteCustomer(string firstName, string lastName, string email, string telephone) { var queryString = $@"DELETE FROM `oc_customer` WHERE `firstname` = '{firstName}' AND `lastname` = '{lastName}' AND `email` = '{email}' AND `telephone` = '{telephone}'"; ExecuteQuery(queryString); } } }
00db93ffdbcc4a65520c10a68bea19e16ba492dc
C#
Hadea/IMO
/Serialisierung/Program.cs
3.421875
3
using System; using System.IO; using System.Xml.Serialization; namespace Serialisierung { class Program { static void Main() { // neuen leeren DataContainer erzeugen und RAM position merken. DataContainer data = new DataContainer(); // DataContainer stück für stück füllen data.NumberA = 50000; data.BitB = true; data.TextC = "Hallo Welt"; // Serializer im RAM erstellen und position merken. Der Serializer wird dabei direkt // auf eine Datenstruktur festgelegt, hier der DataContainer. XmlSerializer serializer = new XmlSerializer(typeof(DataContainer)); // Über den StreamWriter holen wir uns schreibzugriff auf die Datei data.xml // Das using sorgt dafür das der Dateizugriff auch wieder beendet wird. "Dispose" using (var writer = new StreamWriter("data.xml")) { // Der befehl Serialize schreibt in den StreamWriter den kompletten nach XML konvertierten // inhalt des DataContainer. serializer.Serialize(writer, data); } // auf der schliessenden klammer des using wird der Dateizugriff freigegeben. // Eine Variable die den demnächst gelesen DataContainer beinhalten soll DataContainer dataFromDisk; if (File.Exists("data.xml")) // Überprüfen ob die Datei existiert, denn nur dann können wir lesen ;) { // Mit dem StreamReader holen wir uns lesezugriff auf die data.xml // das using sorgt dafür das der lesezugriff auch wieder beendet wird. using (var reader = new StreamReader("data.xml")) { // Mit Deserialize lesen wir den gesamten inhalt aus dem StreamReader // das dadurch erzeugte objekt wird im RAM platziert und wir merken uns die Adresse // in dataFromDisk. Da Deserialize mit allen Objekten klar kommen soll gibt es das gelesene // Objekt als "object" zurück, weshalb wir es uminterpretieren müssen zu dem was es vorher war dataFromDisk = (DataContainer)serializer.Deserialize(reader); } // beendet den lesezugriff auf die Datei "dispose" // ausgeben des inhalts des frisch von der Festplatte gelesenen Objektes. Console.WriteLine(dataFromDisk.NumberA); Console.WriteLine(dataFromDisk.BitB); Console.WriteLine(dataFromDisk.TextC); } } } /// <summary> /// Der DataContainer repräsentiert die Datenstruktur welche auf die Festplatte geschrieben und auch gelesen werden sollen. /// </summary> public class DataContainer { public int NumberA; public bool BitB; public string TextC; } }
605eb11de026112e43efae1aa05ab9a698cf56a9
C#
Ameliorate/BuildStation-Client
/Buildstation_Client2/Buildstation_Client2/Class/NetworkSorters/FinishedHandler.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace Buildstation_Client2.Class.NetworkSorters { class FinishedHandler : NetworkSorter { public FinishedHandler() { NetworkThread.RegisterSorter("Finished", this); } private Dictionary<string, bool> Finished = new Dictionary<string, bool>(); public override void NewTrafic(string Data) { try { Finished.Add(Data, true); } catch (ArgumentException) { Finished[Data] = true; } } public void WaitUntill(string Condition) { try { Finished.Add(Condition, false); } catch (ArgumentException) {} while (true) { Thread.Sleep(100); if (Finished[Condition] == true) break; } Finished.Remove(Condition); } } }
6e11c93263ebec1954a82010192e90395223d322
C#
Justin-Shi/EXCoreDemo
/EXCoreDemo.Core/MicrosoftGraph/MicrosoftGraphBase.cs
2.59375
3
using System; using EXCoreDemo.Core.Helper; namespace EXCoreDemo.Core.MicrosoftGraph { public abstract class MicrosoftGraphBase : UrlBase { protected const string MICROSOFT_GRAPH_RESOURCE_URI = "https://graph.microsoft.com/v1.0"; #region Fields private string accessToken; #endregion #region Properties public string AccessToken { get { return accessToken; } set { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentNullException(nameof(accessToken)); } accessToken = value; } } #endregion #region Constructor public MicrosoftGraphBase(string _accessToken) { if (string.IsNullOrWhiteSpace(_accessToken)) { throw new ArgumentNullException(nameof(accessToken)); } accessToken = _accessToken; } #endregion } }
ea9bd2fde55ad5ee9d4b3e31db83d336763aff97
C#
houzhenhuang/DesignPattern
/SingletonPattern/SingletonSecond.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SingletonPattern { public class SingletonSecond { private static object singletonSecond_lock = new object(); long lResult = 0; private SingletonSecond() { Console.WriteLine("被实例化了一次"); for (int i = 0; i < 100000000; i++) { lResult += i; } } public long GetResult() { return lResult; } private static SingletonSecond _singletonSecond { get; set; } static SingletonSecond() { _singletonSecond = new SingletonSecond(); } public static SingletonSecond CreateInstance() { return _singletonSecond; } } }
f7c62a31d5e2eb053771e4ac32596c4a8976079f
C#
HerculesDC/TimeMech
/Assets/Scripts/ITimeMech.cs
2.890625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public interface ITimeMech { void CheckLevelState();//doesn't yet support default implementation void Slow(); void Stop(); void Restore(); } [System.Serializable] //necessary to be able to expose in the inspector public struct TimeVar : ITimeMech { public float originalSpeed; public float halfSpeed; public static float stopped = 0f; public float currentSpeed; public void CheckLevelState() { switch (LevelManager.levelTime) { case LevelTimeState.Normal: Restore(); break; case LevelTimeState.Slowed: Slow(); break; case LevelTimeState.Stopped: Stop(); break; default: break; } } public void Slow() { if (currentSpeed != this.halfSpeed) currentSpeed = this.halfSpeed; } public void Stop() { if (currentSpeed != TimeVar.stopped) currentSpeed = TimeVar.stopped; } public void Restore() { if (currentSpeed != this.originalSpeed) currentSpeed = this.originalSpeed; } }
6e06a76805485a1825d265f0fada2a12ad6e4999
C#
TestBatch-125354/Siles-LoayzaAndres-Project1
/StoreTest/DBRepoTest.cs
2.875
3
using Microsoft.EntityFrameworkCore; using StoreDB; using StoreDB.Models; using Xunit; using System.Linq; using System.Collections.Generic; namespace StoreTest { public class DBRepoTest { private DBRepo repo; private Product testProduct = new Product() { Id = 1, Name = "Apple", Description = "This is a test apple." }; private InvItem testInvItem = new InvItem() { ProductId = 1, LocationId = 1, Quantity = 20 }; [Fact] private void AddInvItemShouldAdd() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("AddInvItemShouldAdd").Options; using var testContext = new StoreContext(options); repo = new DBRepo(testContext); //Act repo.AddInvItem(testInvItem); //Assert using var assertContext = new StoreContext(options); Assert.NotNull(assertContext.InvItems.Single(x => x.ProductId==testInvItem.ProductId && x.LocationId==testInvItem.LocationId)); } [Fact] private void AddInvItemShouldAddProduct() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("AddInvItemShouldAddProduct").Options; using var testContext = new StoreContext(options); repo = new DBRepo(testContext); //Act testInvItem.Product = testProduct; repo.AddInvItem(testInvItem); //Assert using var assertContext = new StoreContext(options); Assert.NotNull(assertContext.Products.Single(x => x.Name==testProduct.Name)); } [Fact] private void AddCartItemShouldAdd() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("AddCartItemShouldAdd").Options; using var testContext = new StoreContext(options); repo = new DBRepo(testContext); CartItem testCartItem = new CartItem() { ProductId = testInvItem.ProductId, CartId = 1, Quantity = testInvItem.Quantity }; //Act repo.AddCartItem(testCartItem); //Assert using var assertContext = new StoreContext(options); Assert.NotNull(assertContext.CartItems.Single(x => x.ProductId==testCartItem.ProductId && x.CartId==testCartItem.CartId)); } [Fact] private void GetInventoryShouldGet() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("GetInventoryShouldGet").Options; using var testContext = new StoreContext(options); testInvItem.Product = testProduct; //GetInventory includes product List<InvItem> items = new List<InvItem>() { testInvItem, new InvItem() {ProductId=1, Product=testProduct, LocationId=2, Quantity=100}, //same product, diff loc new InvItem() {ProductId=1, Product=testProduct, LocationId=3, Quantity=100} //same product, diff loc }; testContext.InvItems.AddRange(items); testContext.SaveChanges(); //Act using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); var result = repo.GetInvItemsByLocation(1); //get from locationId=1 //Assert Assert.NotNull(result); Assert.NotEmpty(result); //only one item was added at locationId=1 } [Fact] private void GetLocationsShouldGet() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("GetLocationsShouldGet").Options; using var testContext = new StoreContext(options); List<Location> locations = new List<Location>() { new Location() {Id = 1, Name = "Metropolis"}, new Location() {Id = 2, Name = "Gotham"}, new Location() {Id = 3, Name = "Chincinnati"} }; testContext.Locations.AddRange(locations); testContext.SaveChanges(); //Act using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); List<Location> assertLocations = repo.GetLocations(); //Assert Assert.NotNull(assertLocations); Assert.Equal(3, assertLocations.Count); } [Fact] private void GetCartItemsShouldGet() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("GetLocationsShouldGet").Options; using var testContext = new StoreContext(options); List<CartItem> items = new List<CartItem>() { new CartItem() {ProductId=1, Product=new Product(), CartId=1, Quantity=10}, new CartItem() {ProductId=2, Product=new Product(), CartId=1, Quantity=10}, new CartItem() {ProductId=3, Product=new Product(), CartId=1, Quantity=10}, new CartItem() {ProductId=1, Product=new Product(), CartId=2, Quantity=10}, new CartItem() {ProductId=1, Product=new Product(), CartId=3, Quantity=10} }; testContext.CartItems.AddRange(items); testContext.SaveChanges(); //Act using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); var result = repo.GetCartItems(1); //get where cartId=1 //Assert Assert.NotNull(result); Assert.Equal(3, result.Count); //there should be 3 cartItems where cartId=1 } [Fact] private void EmptyCartShouldEmpty() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("EmptyCartShouldEmpty").Options; using var testContext = new StoreContext(options); testContext.Carts.Add(new Cart(){LocationId=1, CustomerId=1}); //cart must exist List<CartItem> items = new List<CartItem>() { new CartItem() {ProductId=1, CartId=1, Quantity=5}, new CartItem() {ProductId=2, CartId=1, Quantity=5}, new CartItem() {ProductId=3, CartId=1, Quantity=5}, new CartItem() {ProductId=1, CartId=2, Quantity=5}, new CartItem() {ProductId=2, CartId=3, Quantity=5}, }; testContext.CartItems.AddRange(items); testContext.SaveChanges(); //Act using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); repo.EmptyCart(1); //remove all CartItems where cartId=1 //Assert Assert.Empty(assertContext.CartItems.Where(x => x.CartId==1).ToList()); } [Fact] private void ReduceInventoryShouldReduce() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("ReduceInventoryShouldReduce").Options; using var testContext = new StoreContext(options); testContext.InvItems.Add(new InvItem(){Product=testProduct, ProductId=1, LocationId=1, Quantity=50}); testContext.SaveChanges(); //Act using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); repo.GetInvItem(1, 1).Quantity -= 20; //reduce by 20 //Assert Assert.Equal(30, assertContext.InvItems.First().Quantity); //50-20=30 } [Fact] private void AddToInvItemQuantityShouldAdd() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("AddToInvItemQuantityShouldAdd").Options; using var testContext = new StoreContext(options); testContext.InvItems.Add(new InvItem() { Product= testProduct, ProductId=1, LocationId=1, Price=5, Quantity=10 }); testContext.SaveChanges(); //Act using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); repo.AddToInvItemQuantity(1, 1, 10); //Assert Assert.Equal(20, assertContext.InvItems.First().Quantity); } [Fact] private void HasCustomerShouldWork() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("HasCustomerShouldWork").Options; using var testContext = new StoreContext(options); testContext.Customers.Add(new Customer(){ UserName = "milhouse", Password = "password" }); testContext.SaveChanges(); //Act and Assert using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); Assert.True(repo.HasCustomer("milhouse")); } [Fact] private void HasCartItemShouldWork() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("HasCartItemShouldWork").Options; using var testContext = new StoreContext(options); CartItem item = new CartItem(){ CartId=1, ProductId=1, Product=testProduct, Price =5, Quantity=3 }; testContext.CartItems.Add(item); testContext.SaveChanges(); //Act and Assert using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); Assert.True(repo.HasCartItem(item)); } [Fact] private void HasCartShouldWork() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("HasCartShouldWork").Options; using var testContext = new StoreContext(options); Cart cart = new Cart(){ CustomerId=1, LocationId=1 }; testContext.Carts.Add(cart); testContext.SaveChanges(); //Act and Assert using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); Assert.True(repo.HasCart(1, 1)); } [Fact] private void GetOrdersAscendGetsOrderAscend() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("GetOrdersAscGetsOrdersAsc").Options; using var testContext = new StoreContext(options); testContext.Orders.Add(new Order(){ LocationId=1, CustomerId=1, CreationTime= new System.DateTime(2020, 1, 1), //newest Cost=10 }); testContext.Orders.Add(new Order(){ LocationId=1, CustomerId=1, CreationTime= new System.DateTime(1997, 1, 1), //oldest Cost=10 }); testContext.Orders.Add(new Order(){ LocationId=1, CustomerId=1, CreationTime= new System.DateTime(2003, 1, 1), Cost=10 }); testContext.SaveChanges(); //Act using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); List<Order> orders = repo.GetOrdersAscend((x => x.CustomerId==1), (x => x.CreationTime)); //Assert Assert.Equal(new System.DateTime(1997, 1, 1), orders.First().CreationTime); } [Fact] private void GetOrdersDescendGetsOrderDescend() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("GetOrdersDescGetsOrdersDesc").Options; using var testContext = new StoreContext(options); testContext.Orders.Add(new Order(){ LocationId=1, CustomerId=1, CreationTime= new System.DateTime(1997, 1, 1), //oldest Cost=10 }); testContext.Orders.Add(new Order(){ LocationId=1, CustomerId=1, CreationTime= new System.DateTime(2020, 1, 1), //newest Cost=10 }); testContext.Orders.Add(new Order(){ LocationId=1, CustomerId=1, CreationTime= new System.DateTime(2003, 1, 1), Cost=10 }); testContext.SaveChanges(); //Act using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); List<Order> orders = repo.GetOrdersDescend((x => x.CustomerId==1), (x => x.CreationTime)); //Assert Assert.Equal(new System.DateTime(2020, 1, 1), orders.First().CreationTime); } [Fact] private void GetInvItemIncludesProduct() { //Arrange var options = new DbContextOptionsBuilder<StoreContext>().UseInMemoryDatabase("GetInvItemIncludesProduct").Options; using var testContext = new StoreContext(options); testContext.InvItems.Add(new InvItem(){ LocationId=1, ProductId=1, Product=testProduct, Price=5, Quantity=10 }); testContext.SaveChanges(); //Act using var assertContext = new StoreContext(options); repo = new DBRepo(assertContext); InvItem item = repo.GetInvItem(1, 1); //Assert Assert.NotNull(item.Product); } } }
75eef92c95f0ab477dd078fb6b1e0b796f54f683
C#
NoeCalmness/CoreFrame
/Scripts/UI/PVE/ColliderTriggerListener.cs
2.765625
3
using System; using UnityEngine; public class ColliderTriggerListener : MonoBehaviour { #region static functions static public ColliderTriggerListener Get(GameObject go) { if(!go) { Logger.LogError("cannot add ColliderTriggerListener Component,the gameObject is null"); return null; } ColliderTriggerListener listener = go.GetComponentDefault<ColliderTriggerListener>(); return listener; } public static void AddEnterListener(GameObject go, Action<Collider> callback) { ColliderTriggerListener c = Get(go); if(c) c.onTriggerEnter = callback; } public static void AddStayListener(GameObject go, Action<Collider> callback) { ColliderTriggerListener c = Get(go); if (c) c.onTriggerStay = callback; } public static void AddExitListener(GameObject go, Action<Collider> callback) { ColliderTriggerListener c = Get(go); if (c) c.onTriggerExit = callback; } #endregion public Action<Collider> onTriggerEnter; public Action<Collider> onTriggerStay; public Action<Collider> onTriggerExit; private void OnTriggerEnter(Collider other) { //Logger.LogInfo("OnTriggerEnter other is {0}", other.name); onTriggerEnter?.Invoke(other); } private void OnTriggerStay(Collider other) { //Logger.LogInfo("OnTriggerStay other is {0}", other.name); onTriggerStay?.Invoke(other); } private void OnTriggerExit(Collider other) { //Logger.LogInfo("OnTriggerExit other is {0}", other.name); onTriggerExit?.Invoke(other); } }
bafb01f9511c448bd5f2baef284db268e74fa838
C#
rzaniboni/BethenyPieShopMvcCore
/BethanyPieShop/Models/PieRepository.cs
2.890625
3
using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; namespace BethanyPieShop.Models { public class PieRepository : IPieRepository { private readonly AppDbContext _context; public PieRepository (AppDbContext dbContext) { this._context = dbContext; } public IEnumerable<Pie> AllPies { get { return _context.Pies.Include (c => c.Category); } } public IEnumerable<Pie> PiesOfTheWeek { get { return _context.Pies.Include(c => c.Category).Where(p => p.IsPieOfTheWeek); } } public Pie GetPieById (int pieId) { return _context.Pies.FirstOrDefault(p => p.PieId == pieId); } } }
717ff9d915dbb7be1d9aee43d977403d8d24a6dd
C#
hnjm/FFTriadBuddy
/sources/ImageHashDB.cs
2.546875
3
using Palit.TLSHSharp; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml; using CloudStorage; namespace FFTriadBuddy { public enum EImageHashType { None, Rule, Card, Cactpot, } public class HashCollection { public readonly TlshHash ComplexHash; public readonly ScanLineHash SimpleHash; public HashCollection(TlshHash complexHash, ScanLineHash simpleHash) { ComplexHash = complexHash; SimpleHash = simpleHash; } public HashCollection(string complexHashStr, string simpleHashStr) { ComplexHash = string.IsNullOrEmpty(complexHashStr) ? null : TlshHash.FromTlshStr(complexHashStr); SimpleHash = string.IsNullOrEmpty(simpleHashStr) ? null : ScanLineHash.FromString(simpleHashStr); } public bool IsMatching(HashCollection other, out int distance) { distance = FindDistance(other); int maxMatchDistance = (ComplexHash != null) ? 19 : 0; return distance <= maxMatchDistance; } public int FindDistance(HashCollection other) { if (ComplexHash != null && other.ComplexHash != null) { return ComplexHash.TotalDiff(other.ComplexHash, false); } if (SimpleHash != null && other.SimpleHash != null) { return SimpleHash.GetDistance(other.SimpleHash); } return int.MaxValue; } public override string ToString() { return (ComplexHash != null) ? ("C:" + ComplexHash) : ("S:" + SimpleHash); } } public class ImageHashData : IComparable { public readonly object Owner; public readonly EImageHashType Type; public readonly HashCollection Hash; public object GuideOb; public ImageHashData(object owner, HashCollection hash, EImageHashType type) { Owner = owner; Hash = hash; Type = type; } public ImageHashData(object owner, HashCollection hash, EImageHashType type, object guideOb) { Owner = owner; Hash = hash; Type = type; GuideOb = guideOb; } public int CompareTo(object obj) { ImageHashData otherOb = (ImageHashData)obj; return (otherOb == null) ? 1 : (Type != otherOb.Type) ? Type.CompareTo(otherOb.Type) : Hash.ToString().CompareTo(otherOb.Hash.ToString()); } public bool IsHashMatching(HashCollection testHash) { int dummyDistance = 0; return Hash.IsMatching(testHash, out dummyDistance); } public bool IsHashMatching(HashCollection testHash, out int distance) { return Hash.IsMatching(testHash, out distance); } public bool IsHashMatching(ImageHashData testHashData) { int dummyDistance = 0; return Hash.IsMatching(testHashData.Hash, out dummyDistance); } public bool IsHashMatching(ImageHashData testHashData, out int distance) { return Hash.IsMatching(testHashData.Hash, out distance); } public override string ToString() { return Type + ": " + Owner; } } public class ImageHashDB { public List<ImageHashData> hashes; public string DBPath; private static ImageHashDB instance = new ImageHashDB(); public List<TriadGameModifier> modObjects; public ImageHashDB() { DBPath = "data/hashes.xml"; hashes = new List<ImageHashData>(); modObjects = new List<TriadGameModifier>(); } public static ImageHashDB Get() { return instance; } public bool Load() { hashes.Clear(); CactpotGame.InititalizeHashDB(); modObjects.Clear(); foreach (Type type in Assembly.GetAssembly(typeof(TriadGameModifier)).GetTypes()) { if (type.IsSubclassOf(typeof(TriadGameModifier))) { modObjects.Add((TriadGameModifier)Activator.CreateInstance(type)); } } try { XmlDocument xdoc = new XmlDocument(); xdoc.Load(AssetManager.Get().GetAsset(DBPath)); foreach (XmlNode testNode in xdoc.DocumentElement.ChildNodes) { XmlElement testElem = (XmlElement)testNode; ImageHashData hashEntry = LoadHashEntry(testElem); if (hashEntry != null) { hashes.Add(hashEntry); } } } catch (Exception ex) { Logger.WriteLine("Loading failed! Exception:" + ex); } Logger.WriteLine("Loaded hashes: " + hashes.Count); return true; } public ImageHashData LoadHashEntry(XmlElement xmlElem) { ImageHashData result = null; if (xmlElem != null && xmlElem.Name == "hash" && xmlElem.HasAttribute("type") && (xmlElem.HasAttribute("value") || xmlElem.HasAttribute("valueS"))) { string typeName = xmlElem.GetAttribute("type"); string hashValueC = xmlElem.HasAttribute("value") ? xmlElem.GetAttribute("value") : null; string hashValueS = xmlElem.HasAttribute("valueS") ? xmlElem.GetAttribute("valueS") : null; HashCollection hashData = new HashCollection(hashValueC, hashValueS); if (typeName.Equals("rule", StringComparison.InvariantCultureIgnoreCase)) { string ruleName = xmlElem.GetAttribute("name"); TriadGameModifier ruleMod = ParseRule(ruleName); result = new ImageHashData(ruleMod, hashData, EImageHashType.Rule); } else if (typeName.Equals("card", StringComparison.InvariantCultureIgnoreCase)) { string cardIdName = xmlElem.GetAttribute("id"); int cardId = int.Parse(cardIdName); TriadCard cardOb = TriadCardDB.Get().cards[cardId]; result = new ImageHashData(cardOb, hashData, EImageHashType.Card); } else if (typeName.Equals("cactpot", StringComparison.InvariantCultureIgnoreCase)) { string numIdName = xmlElem.GetAttribute("id"); int numId = int.Parse(numIdName); if (numId >= 1 && numId <= 9) { result = new ImageHashData(CactpotGame.hashDB[numId - 1], hashData, EImageHashType.Cactpot); } } } return result; } public ImagePatternDigit LoadDigitEntry(XmlElement xmlElem) { ImagePatternDigit result = new ImagePatternDigit(-1, null); if (xmlElem != null && xmlElem.Name == "digit" && xmlElem.HasAttribute("type") && xmlElem.HasAttribute("value")) { string typeName = xmlElem.GetAttribute("type"); string hashValue = xmlElem.GetAttribute("value"); result = new ImagePatternDigit(int.Parse(typeName), ImageDataDigit.FromHexString(hashValue)); } return result; } public List<ImagePatternDigit> LoadDigitHashes(JsonParser.ArrayValue jsonArr) { List<ImagePatternDigit> list = new List<ImagePatternDigit>(); foreach (JsonParser.Value value in jsonArr.entries) { JsonParser.ObjectValue jsonOb = (JsonParser.ObjectValue)value; string hashValue = (JsonParser.StringValue)jsonOb["hash"]; ImagePatternDigit digitHash = new ImagePatternDigit((JsonParser.IntValue)jsonOb["id"], ImageDataDigit.FromHexString(hashValue)); list.Add(digitHash); } return list; } public List<ImageHashData> LoadImageHashes(JsonParser.ObjectValue jsonOb) { List<ImageHashData> list = new List<ImageHashData>(); string[] enumArr = Enum.GetNames(typeof(EImageHashType)); foreach (KeyValuePair<string, JsonParser.Value> kvp in jsonOb.entries) { EImageHashType groupType = (EImageHashType)Array.IndexOf(enumArr, kvp.Key); JsonParser.ArrayValue typeArr = (JsonParser.ArrayValue)kvp.Value; foreach (JsonParser.Value value in typeArr.entries) { JsonParser.ObjectValue jsonHashOb = (JsonParser.ObjectValue)value; string idStr = jsonHashOb["id"]; object hashOwner = null; switch (groupType) { case EImageHashType.Rule: hashOwner = ParseRule(idStr); break; case EImageHashType.Card: hashOwner = TriadCardDB.Get().cards[int.Parse(idStr)]; break; case EImageHashType.Cactpot: hashOwner = CactpotGame.hashDB[int.Parse(idStr) - 1]; break; default: break; } if (hashOwner != null) { HashCollection hashes = new HashCollection(jsonHashOb["hashC", JsonParser.StringValue.Empty], jsonHashOb["hashS", JsonParser.StringValue.Empty]); ImageHashData hashEntry = new ImageHashData(hashOwner, hashes, groupType); list.Add(hashEntry); } } } return list; } public void StoreDigitHashes(List<ImagePatternDigit> entries, JsonWriter jsonWriter) { entries.Sort(); foreach (ImagePatternDigit entry in entries) { jsonWriter.WriteObjectStart(); jsonWriter.WriteInt(entry.Value, "id"); jsonWriter.WriteString(entry.Hash, "hash"); jsonWriter.WriteObjectEnd(); } } public void StoreImageHashes(List<ImageHashData> entries, JsonWriter jsonWriter) { foreach (EImageHashType subType in Enum.GetValues(typeof(EImageHashType))) { if (subType != EImageHashType.None) { List<ImageHashData> sortedSubtypeList = entries.FindAll(x => x.Type == subType); sortedSubtypeList.Sort(); jsonWriter.WriteArrayStart(subType.ToString()); foreach (ImageHashData entry in sortedSubtypeList) { jsonWriter.WriteObjectStart(); switch (subType) { case EImageHashType.Card: jsonWriter.WriteString(((TriadCard)entry.Owner).Id.ToString(), "id"); break; default: jsonWriter.WriteString(entry.Owner.ToString(), "id"); break; } if (entry.Hash.ComplexHash != null) { jsonWriter.WriteString(entry.Hash.ComplexHash.ToString(), "hashC"); } if (entry.Hash.SimpleHash != null) { jsonWriter.WriteString(entry.Hash.SimpleHash.ToString(), "hashS"); } jsonWriter.WriteObjectEnd(); } jsonWriter.WriteArrayEnd(); } } } private TriadGameModifier ParseRule(string ruleName) { TriadGameModifier result = null; foreach (TriadGameModifier mod in modObjects) { if (ruleName.Equals(mod.GetName(), StringComparison.InvariantCultureIgnoreCase)) { result = (TriadGameModifier)Activator.CreateInstance(mod.GetType()); break; } } if (result == null) { Logger.WriteLine("Loading failed! Can't parse rule: " + ruleName); } return result; } } }
1a8c639e1e5e41fdebf42f32503f513315425249
C#
sivze/BAMApp
/BAMApp/BAMApp/ViewModels/BaseViewModel.cs
3.109375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BAMApp.ViewModels { public abstract class BaseViewModel : INotifyPropertyChanged { /// <summary> /// Raised when a property on this object has a new value. /// </summary> public event PropertyChangedEventHandler PropertyChanged; private bool isBusy = false; private string loadingMessage; public bool IsBusy { get { return isBusy; } set { if (isBusy != value) { isBusy = value; OnPropertyChanged("IsBusy"); } } } public string LoadingMessage { get { return loadingMessage; } set { if (loadingMessage != value) { loadingMessage = value; OnPropertyChanged("LoadingMessage"); } } } /// <summary> /// Raises this object's PropertyChanged event. /// </summary> /// <param name="propertyName">The property that has a new value.</param> protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } } }
48f01415bed64deb949da8d17aa8e57fde5c6cac
C#
PetrosSarantakos/Simple-Console-Chat-App
/IndividualProject_PetrosSarantakos/MessageManager.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IndividualProject_PetrosSarantakos.Models; namespace IndividualProject_PetrosSarantakos { public class MessageManager { public void SendMessage(string senderId) { using (var db = new AppContext()) { User sender = db.Users.Find(senderId); Console.WriteLine("Who do you want to contact? Enter receiver's username."); string receiverId = Console.ReadLine(); User receiver = db.Users.Find(receiverId); Console.WriteLine("Write your message"); string text = Console.ReadLine(); Message message = new Message { Time = DateTime.Now, Sender = sender, Receiver = receiver, Text = text }; db.Messages.Add(message); db.SaveChanges(); } Console.WriteLine("Message sent. Press any key to continue"); Console.ReadKey(); } public void ViewMessageFromUser(string sender, string receiver) { List<Message> messages = new List<Message>(); List<string> log = new List<string>(); string path = $"from {sender} to {receiver}.txt"; using (var db = new AppContext()) { messages = db.Messages.Where(m => ((m.Sender.Id == sender) && (m.Receiver.Id == receiver)) ||((m.Receiver.Id==sender)&&(m.Sender.Id==receiver))).ToList(); if (messages.Count == 0) { Console.WriteLine($"No messages between you and user {receiver}"); } foreach (var item in messages) { Console.WriteLine($"from:{item.Sender.Id} to:{item.Receiver.Id} text:{item.Text} \nsent:{item.Time}"); log.Add($"from:{item.Sender.Id} to:{item.Receiver.Id} text:{item.Text} \nsent:{item.Time}"); } System.IO.File.Create(path).Close(); } System.IO.File.AppendAllLines(path, log); Console.WriteLine("Press any key to continue."); Console.ReadKey(); } } }
1ec39dbee00367f3b1a342fa5b855f413c523fab
C#
joseph-turk/make-it-art-api-core
/Controllers/ArtworkController.cs
2.640625
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Hosting; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using MakeItArtApi.Models; using MakeItArtApi.Services; namespace MakeItArtApi.Controllers { [Route("api/[controller]")] public class ArtworkController : ControllerBase { private readonly ModelContext _context; private readonly IHostingEnvironment _hostingEnvironment; private readonly ImageService imageService; public ArtworkController(ModelContext context, IHostingEnvironment hostingEnvironment) { _context = context; _hostingEnvironment = hostingEnvironment; imageService = new ImageService(); } [HttpGet] public async Task<ActionResult> GetAll() { var artworks = await _context.Artworks.ToListAsync(); return Ok(artworks); } [HttpGet("{id}", Name = "GetArtwork")] public async Task<ActionResult> GetById(int id) { var artwork = await _context.Artworks.FindAsync(id); if (artwork == null) return NotFound(); return Ok(artwork); } [HttpPost] public async Task<ActionResult> Create() { if (!Request.HasFormContentType) return BadRequest(); Guid imageId = Guid.NewGuid(); IFormCollection form = Request.Form; // Form Fields string title = form["title"]; string description = form["description"]; decimal price = Convert.ToDecimal(form["price"]); // Form Upload IFormFile image = form.Files.FirstOrDefault(); string fileExtension = String.Empty; if (image == null) return BadRequest(); // Set upload directories string uploadsDir = Path.Combine(_hostingEnvironment.WebRootPath, "uploads"); string artworkDir = Path.Combine(uploadsDir, "artwork"); string imageDir = Path.Combine(artworkDir, imageId.ToString()); // Create directories if needed if (!Directory.Exists(uploadsDir)) Directory.CreateDirectory(uploadsDir); if (!Directory.Exists(artworkDir)) Directory.CreateDirectory(artworkDir); Directory.CreateDirectory(imageDir); // Get file extension fileExtension = Path.GetExtension(image.FileName); // Create resized images Image<Rgba32> thumbnailImage = imageService.ResizeImage(image, 400); Image<Rgba32> heroImage = imageService.ResizeImage(image, 1920, 1080); // Set paths for saving files string fullFileName = String.Concat("full", fileExtension); string thumbnailFileName = String.Concat("thumbnail", fileExtension); string heroFileName = String.Concat("hero", fileExtension); string fullPath = Path.Combine(imageDir, fullFileName); string thumbnailPath = Path.Combine(imageDir, thumbnailFileName); string heroPath = Path.Combine(imageDir, heroFileName); // Save full-size image using (FileStream fileStream = new FileStream(fullPath, FileMode.Create)) { image.CopyTo(fileStream); fileStream.Flush(); } // Save resized images thumbnailImage.Save(thumbnailPath); heroImage.Save(heroPath); // Create artwork and save to DB Artwork artwork = new Artwork { Title = title, Description = description, Price = price, ImageId = imageId, ImageExtension = fileExtension, CreatedAt = DateTime.Now, SoldOn = null, IsSold = false }; _context.Artworks.Add(artwork); await _context.SaveChangesAsync(); return CreatedAtRoute("GetArtwork", new Artwork { Id = artwork.Id }, artwork); } [HttpPut("{id}")] public async Task<ActionResult> Update(int id, [FromBody] Artwork artwork) { var existingArtwork = await _context.Artworks.FindAsync(id); if (existingArtwork == null) return NotFound(); existingArtwork.Title = artwork.Title; existingArtwork.Description = artwork.Description; existingArtwork.Price = artwork.Price; existingArtwork.IsSold = artwork.IsSold; if (existingArtwork.IsSold) existingArtwork.SoldOn = DateTime.Now; _context.Artworks.Update(existingArtwork); await _context.SaveChangesAsync(); return Ok(); } [HttpDelete("{id}")] public async Task<ActionResult> Delete(int id) { var existingArtwork = await _context.Artworks.FindAsync(id); if (existingArtwork == null) return NotFound(); string imagePath = Path.Combine( _hostingEnvironment.WebRootPath, "uploads", "artwork", existingArtwork.ImageId.ToString() ); _context.Artworks.Remove(existingArtwork); await _context.SaveChangesAsync(); Directory.Delete(imagePath, true); return Ok(); } } }
e1e3ead07ae0ed26294e482f77cb68ac1730de0f
C#
umutdogand/DevRobot
/src/ViewCreator/Components/HtmlComponent/HTMLComponent.cs
2.765625
3
namespace ViewCreator.Components { using System; public abstract class HtmlComponent : Attribute, IHtmlComponent { public HtmlFeatureCollection Features { get; set; } public string Class { get { return GetFeature<String>(HtmlFeaturesFactory.ClassKey); } set { SetFeature(HtmlFeaturesFactory.Class(value)); } } public string Style { get { return GetFeature<String>(HtmlFeaturesFactory.StyleKey); } set { SetFeature(HtmlFeaturesFactory.Style(value)); } } public string OnMouseDown { get { return GetFeature<String>(HtmlFeaturesFactory.OnMouseDownKey); } set { SetFeature(HtmlFeaturesFactory.OnMouseDown(value)); } } public string OnMouseMove { get { return GetFeature<String>(HtmlFeaturesFactory.OnMouseMoveKey); } set { SetFeature(HtmlFeaturesFactory.OnMouseMove(value)); } } public string OnmouseOut { get { return GetFeature<String>(HtmlFeaturesFactory.OnmouseOutKey); } set { SetFeature(HtmlFeaturesFactory.OnmouseOut(value)); } } public string OnMouseOver { get { return GetFeature<String>(HtmlFeaturesFactory.OnMouseOverKey); } set { SetFeature(HtmlFeaturesFactory.OnMouseOver(value)); } } public string OnMouseUp { get { return GetFeature<String>(HtmlFeaturesFactory.OnMouseUpKey); } set { SetFeature(HtmlFeaturesFactory.OnMouseUp(value)); } } public string OnMouseWheel { get { return GetFeature<String>(HtmlFeaturesFactory.OnMouseWheelKey); } set { SetFeature(HtmlFeaturesFactory.OnMouseWheel(value)); } } public HtmlComponent() { Features = new HtmlFeatureCollection(); } public void SetFeature(IHtmlFeature feature) { Features.Add(feature); } public object GetFeature(string name) { return Features.GetValue(name); } public T GetFeature<T>(string name) { return (T)GetFeature(name); } } }
47a6aae10777ba0df718d2d5fce3f149f4f92f68
C#
VolskyiI/C-sharp
/14/1-7/1-7/Program.cs
3.375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1_7 { class Program { static void Main(string[] args) { string str = "3+i*4"; ComplexNumber obj1 = new ComplexNumber(1,2); Console.WriteLine(obj1.ToString()); obj1 =(ComplexNumber)str; Console.WriteLine(obj1); ComplexNumber obj2 = new ComplexNumber(3, 2); ComplexNumber obj3 = new ComplexNumber(5, 3); Console.WriteLine(obj3 < obj2); Console.WriteLine(obj3 > obj2); Console.WriteLine(obj2 == obj3); Console.WriteLine(obj2 != obj3); ComplexSet<ComplexNumber> set = new ComplexSet<ComplexNumber>(); ComplexNumber obj4 = new ComplexNumber(3, 5); ComplexNumber obj5 = new ComplexNumber(1, 4); ComplexNumber obj6 = new ComplexNumber(2, 6); ComplexNumber obj8 = new ComplexNumber(7, 3); ComplexNumber obj9 = new ComplexNumber(4, 3); set[0] = obj4; set[1] = obj5; set[2] = obj6; set[3] = obj8; set[4] = obj9; foreach (var cp in set) { Console.WriteLine(cp); } string str2 = set[3]; set[4] = (ComplexNumber)"4+i*3"; Console.ReadLine(); } } }
21c3d2f7f5c5209edc0ee4627de64ca1e1a87c9b
C#
lachezarslavkovv/CSharp-OOP-Advanced
/03.Generics-Lab/03.GenericScale/StartUp.cs
2.84375
3
using System; public class StartUp { public static void Main() { Scale<int> scale = new Scale<int>(5, 6); Console.WriteLine(scale.GetHeavier()); Scale<string> stringScale = new Scale<string>("Str", "Str"); Console.WriteLine(stringScale.GetHeavier()); } }
d22d341c19f46d0ea6898050dfad013a57ba0b94
C#
shawnliang/Wammer-win-station
/Client/Libs/HTML2XHTML/SysUtil.cs
3.03125
3
#region using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; #endregion namespace Waveface.Util { public class SysUtil { // Convert a string from one charset to another charset public static String StringEncodingConvert(String strText, String strSrcEncoding, String strDestEncoding) { Encoding _srcEnc = Encoding.GetEncoding(strSrcEncoding); Encoding _destEnc = Encoding.GetEncoding(strDestEncoding); byte[] _bData = _srcEnc.GetBytes(strText); byte[] _bResult = Encoding.Convert(_srcEnc, _destEnc, _bData); return _destEnc.GetString(_bResult); } // convert a byte array to string using default encoding public static String BytesToString(byte[] bData) { return Encoding.GetEncoding(0).GetString(bData); } // get the byte array from a string using default encoding public static byte[] StringToBytes(String strData) { return Encoding.GetEncoding(0).GetBytes(strData); } // swap two elements in a array public static void SwapArrayElement(Object[] objArray, int i, int j) { Object _t = objArray[i]; objArray[i] = objArray[j]; objArray[j] = _t; } // write a byte array to a file public static int WriteFile(String strFilePath, byte[] bContent) { FileStream _fs = new FileStream(strFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); BinaryWriter _bw = new BinaryWriter(_fs); try { _bw.Write(bContent); } finally { _bw.Close(); _fs.Close(); } return 0; } // copy a object by content,not by reference public static T SerializeClone<T>(T srcObject) { BinaryFormatter _bfFormatter = new BinaryFormatter(); MemoryStream _msStream = new MemoryStream(); T _result = default(T); try { _bfFormatter.Serialize(_msStream, srcObject); _msStream.Seek(0, SeekOrigin.Begin); _result = (T)_bfFormatter.Deserialize(_msStream); } finally { if (_msStream != null) _msStream.Close(); } return _result; } // write a string to a file using default encoding public static int WriteFile(String strFilePath, String strContent) { Encoding _encDefault = Encoding.GetEncoding(0); FileStream _fs = new FileStream(strFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); BinaryWriter _bw = new BinaryWriter(_fs); try { _bw.Write(_encDefault.GetBytes(strContent)); } finally { _bw.Close(); _fs.Close(); } return 0; } // read all the content from a file as byte array public static byte[] ReadFileAsBytes(String strFilePath) { FileStream _fs = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BinaryReader _br = new BinaryReader(_fs); byte[] _baResult = null; try { _baResult = new byte[_fs.Length]; _br.Read(_baResult, 0, _baResult.Length); } finally { _br.Close(); _fs.Close(); } return _baResult; } // read all the content from a file as string in default encoding public static String ReadFile(String strFilePath) { Encoding _encDefault = Encoding.GetEncoding(0); FileStream _fs = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BinaryReader _br = new BinaryReader(_fs); String _strResult = null; try { byte[] _bData = new byte[_fs.Length]; _br.Read(_bData, 0, _bData.Length); _strResult = _encDefault.GetString(_bData); } finally { _br.Close(); _fs.Close(); } return _strResult; } public static void HashList2HashArray(Hashtable htList, Hashtable htArray) { IEnumerator _it = htList.Keys.GetEnumerator(); while (_it.MoveNext()) { Object _obj = _it.Current; ArrayList _alList = (ArrayList)htList[_obj]; if (_alList.Count > 0) { Object[] _objSize = new Object[1]; _objSize[0] = _alList.Count; Type[] _types = new Type[1]; _types[0] = typeof(int); Object[] _objArray = (Object[])_alList[0].GetType().MakeArrayType().GetConstructor(_types).Invoke(_objSize); for (int i = 0; i < _alList.Count; i++) { _objArray[i] = _alList[i]; } htArray[_obj] = _objArray; } else { htArray[_obj] = null; } } } // Convert a ArrayList object to a array public static Object[] List2Array(ArrayList alList) { if (alList.Count == 0) return null; Object[] _objSize = new Object[1]; _objSize[0] = alList.Count; Type[] _types = new Type[1]; _types[0] = typeof(int); Object[] _objArray = (Object[])alList[0].GetType().MakeArrayType().GetConstructor(_types).Invoke(_objSize); for (int i = 0; i < alList.Count; i++) { _objArray[i] = alList[i]; } return _objArray; } // Load elements into a generic list from an array public static void LoadListFromArray<T>(List<T> list, T[] array) { list.Clear(); for (int i = 0; i < array.Length; i++) { list.Add(array[i]); } } } }
b559b775d8e757b9ed0ce6416dd6f41ce9df9b3f
C#
mzweigert/Photon-In-Maze
/Assets/Common Scripts/Optional.cs
3.359375
3
using System; namespace PhotonInMaze.Common { public class Optional<T> { private static readonly Optional<T> EMPTY = new Optional<T>(); private T value; private Optional() { } private Optional(T arg) { if(arg == null) { throw new ArgumentNullException(); } value = arg; } public static Optional<T> Empty() { return EMPTY; } public static Optional<T> Of(T arg) { return new Optional<T>(arg); } public static Optional<T> OfNullable(T arg) { return arg != null ? Of(arg) : Empty(); } public static Optional<T> OfNullable(Func<T> outputArg) { return outputArg != null ? Of(outputArg()) : Empty(); } public bool HasValue { get { return value != null; } } public bool HasNotValue { get { return value == null; } } public void IfPresent(Action<T> action) { if(action != null && value != null) { action(value); } } public void IfAbsent(Action action) { if(action != null && value == null) { action.Invoke(); } } public void IfPresentOrElse(Action<T> actionIfpresent, Action actionElse) { if(actionIfpresent == null || actionElse == null) { throw new NullReferenceException(); } else if(value != null) { actionIfpresent(value); } else { actionElse.Invoke(); } } public T Get() { return value; } public T OrElse(T other) { return HasValue ? value : other; } public T OrElseGet(Func<T> getOther) { return HasValue ? value : getOther(); } public T InitIfAbsentAndGet(Func<T> getOther) { if(!HasValue) { value = getOther(); } return value; } public T OrElseThrow<E>(Func<E> exceptionSupplier) where E : Exception { if(HasValue){ return value; } else { E exception = exceptionSupplier.Invoke(); throw exception; } } public static explicit operator T(Optional<T> optional) { return OfNullable((T)optional).Get(); } public static implicit operator Optional<T>(T optional) { return OfNullable(optional); } public override bool Equals(object obj) { if(obj is Optional<T>) return true; if(!(obj is Optional<T>)) return false; return Equals(value, (obj as Optional<T>).value); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return HasValue ? $"Optional has <{value}>" : $"Optional has no any value: <{value}>"; } } }
ac1ce4a9bdab08b7f9e2555ba62f53aad3316b8d
C#
composer2/My-projects-and-homeworks-C-HTML-OOP-CSS
/OPP/OOP homeworks/Extension-Methods-Delegates-Lambda-LINQ-Homework/Extension-Methods-Delegates-Lambda-LINQ/DivisibleBy7And3/DivisibleBy7And3.cs
4.0625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DivisibleBy7And3 { class DivisibleBy7And3 { static void Main(string[] args) { //arr int var numbers = new int[100]; for (int i = 0; i < numbers.Length; i++) { numbers[i] = i; } //sorted with lambda var lambdaLocate = numbers.Where(x => x % 7 == 0 && x % 3 == 0).ToArray(); Console.WriteLine("Numbers that are are divisible by 7 and 3(using lambda and extention methods): "); Console.WriteLine(new string('*', 40)); foreach (var number in lambdaLocate) { Console.WriteLine(number); } //sorted with LINQ var linqLocate = from number in numbers where number % 7 == 0 && number % 3 == 0 select number; Console.WriteLine(); Console.WriteLine("Numbers that are are divisible by 7 and 3(using LINQ): "); Console.WriteLine(new string('*', 40)); foreach (var number in linqLocate) { Console.WriteLine(number); } } } }
5f3b93885a5a6784cf626e3c78abf2cf78389858
C#
GoldMineCloud/DI-sample
/WillSortForFood/Program.cs
3.0625
3
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Autofac; using Autofac.Core; using Autofac.Features; using Autofac.Util; using Autofac.Builder; using LinqLib.Sort; using WillSortForFood.Evaluators; using WillSortForFood.Sorters; namespace WillSortForFood { public class Something { public Something( MergeSorter sorterA, BubbleSorter sorterB, QuickSorter sorterC, SomeSorter sorterD) { Console.WriteLine(sorterA.AlgorithmName); Console.WriteLine(sorterB.AlgorithmName); Console.WriteLine(sorterC.AlgorithmName); Console.WriteLine(sorterD.AlgorithmName); } } public class SomeSorter : ISorter { private readonly BubbleSorter sorter; public SomeSorter(BubbleSorter sorter) { this.sorter = sorter; } public string AlgorithmName { get { return "custom " + sorter.AlgorithmName; } } public int[] Sort(IEnumerable<int> items) { return sorter.Sort(items); } } class Program { static void Main(string[] args) { var builder = new ContainerBuilder(); builder.RegisterType<DependencyInjectionSortingEvaluator>().As<ISortingEvaluator>(); builder.RegisterType<ShelSorter>().As<ISorter>(); builder.RegisterType<Something>(); //registers all types that end with "Sorter" var currentAssembly = Assembly.GetExecutingAssembly(); builder.RegisterAssemblyTypes(currentAssembly) .Where(t => t.Name.EndsWith("Sorter")); var container = builder.Build(); container.Resolve<Something>(); //for fun const int n = 10000; new[] { Evaluate(n, SortType.Bubble), Evaluate(n, SortType.Heap), Evaluate(n, SortType.Insert), Evaluate(n, SortType.Merge), Evaluate(n, SortType.Quick), Evaluate(n, SortType.Select), Evaluate(n, SortType.Shell) } .OrderBy(x => x.TimeInMs) .ToList() .ForEach(Print); } private static EvaluationResult Evaluate(int n, SortType sortType) { return new DependencyInjectionSortingEvaluator(new YouPickSorter(sortType)) .EvaluateOn(ArrayOfRandomIntegers(n)); } private static void Print(EvaluationResult result) { var initialColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("'{0}' ", result.SortingAlgorithmName); Console.ForegroundColor = initialColor; Console.Write("took"); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write(" {0}ms", result.TimeInMs); Console.ForegroundColor = initialColor; Console.Write(", first element is {0}, last is {1}", result.SortedItems.First(), result.SortedItems.Last()); Console.WriteLine(); } private static IEnumerable<int> ArrayOfRandomIntegers(int n) { var rnd = new Random((int) DateTime.Now.Ticks); return Enumerable.Range(0, n) .Select(x => rnd.Next(int.MaxValue)); } } }
d0db2d10da85a46f95add7a46c4aff6d54c18813
C#
shendongnian/download4
/code4/583821-13658454-32590314-6.cs
2.875
3
//your program class Program { static void Main(string[] args) { foreach (string s in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*PlugIn.dll"))//getting plugins in base directory ending with PlugIn.dll { Assembly aWrite = Assembly.LoadFrom(s); Type tWrite = aWrite.GetType("PlugInApp.plugInClass"); IWrite click = (IWrite)Activator.CreateInstance(tWrite); click.write(); } } }
daf5bdec1b3f1a88535f6e0655930c76ba91b9e1
C#
shendongnian/download4
/code8/1480693-40877333-132715133-2.cs
3.09375
3
public string CipheredString(string userMessage) { string[] columnEncrypted = userMessage.Split(' '); string[] columnDecrypted = new string[6]; string DecryptedString = string.Empty; string DirtyDecrypt = string.Empty; columnDecrypted[0] = columnEncrypted[5]; columnDecrypted[1] = columnEncrypted[2]; columnDecrypted[2] = columnEncrypted[4]; columnDecrypted[3] = columnEncrypted[3]; columnDecrypted[4] = columnEncrypted[0]; columnDecrypted[5] = columnEncrypted[1]; for (int c = 0; c < columnDecrypted[0].Length; c++) { for (int r = 0; r < 6; r++) { string row = columnDecrypted[r]; string column = row[c].ToString(); DirtyDecrypt += column; } } string CleanDecrypt = DirtyDecrypt.Replace("_", " ").Replace("*",""); return CleanDecrypt; }
a3b26189a8e48ee91f6d0e8f594b783933f8a49c
C#
water102/Ribo-Downloader
/Ribo Downloader/Program.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Ribo_Downloader { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { bool result; var mutex = new System.Threading.Mutex(true, "{7803901c-1e28-40d0-9f2e-884a3ab0e477}", out result); if (!result) { return; } if (!System.IO.Directory.Exists(VAR.LocalData)) { System.IO.Directory.CreateDirectory(VAR.LocalData); } string pts = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\"; if (!System.IO.File.Exists(VAR.LocalData+"save_path.txt")) { System.IO.TextWriter tw = new System.IO.StreamWriter(VAR.LocalData + "save_path.txt", true); tw.Write(pts); tw.Close(); } else { pts = System.IO.File.ReadAllText(VAR.LocalData + "save_path.txt"); pts = pts.Split(new string[] { "\r\n" }, StringSplitOptions.None)[0]; VAR.SavePath = pts; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Main()); GC.KeepAlive(mutex); } } }
68a391db31f8d380bff251d83976d1f262d995f8
C#
DerrickYeb/VAT_Calculator
/VatCalculatorApi.DAL/Helpers/TestingDisplayResults.cs
2.59375
3
using System; using System.Collections.Generic; using System.Text; using VatCalculatorApi.DAL.Models; namespace VatCalculatorApi.DAL.Helpers { public static class TestingDisplayResults { public static decimal StandardAndFlatRateVatPayable(UserInputsModel inputsModel) { decimal totalPrice = inputsModel.Amount * inputsModel.Quantity; //decimal vat = totalPrice * (RateExtensions.Getfund + Nhil(inputsModel.Amount)); decimal totalVat = RateExtensions.VatRate * (totalPrice + Getfund(inputsModel.Amount) + Nhil(inputsModel.Amount)) + OnlyFlatRateResult(inputsModel); inputsModel.TotalVat = Math.Round(totalVat); inputsModel.VAT = totalVat; StandardRateAndFlatRate(inputsModel); return inputsModel.TotalVat; } public static decimal OnlyStandardRateResult(UserInputsModel inputsModel) { decimal totalPrice = (inputsModel.Amount * inputsModel.Quantity); inputsModel.StandardRate = totalPrice * RateExtensions.StandardRate; inputsModel.TotalVat = RateExtensions.VatRate * (totalPrice + Nhil(inputsModel.Amount) + Getfund(inputsModel.Amount)); inputsModel.VAT = RateExtensions.VatRate * (totalPrice + Nhil(inputsModel.Amount) + Getfund(inputsModel.Amount)); return inputsModel.StandardRate; } public static decimal OnlyFlatRateResult(UserInputsModel inputsModel) { inputsModel.FlatRate = inputsModel.Amount * inputsModel.Quantity * RateExtensions.FlatRate; inputsModel.TotalVat = inputsModel.FlatRate; inputsModel.VAT = 0; return inputsModel.FlatRate; } public static decimal OnlyVatResult(UserInputsModel inputsModel) { decimal totalPrice = inputsModel.Amount * inputsModel.Quantity; return inputsModel.VAT = RateExtensions.VatRate * (totalPrice * Nhil(inputsModel.Amount) + Getfund(inputsModel.Amount)); } public static decimal StandardRateAndFlatRate(UserInputsModel inputsModel) { inputsModel.FlatRate = inputsModel.Amount * inputsModel.Quantity * RateExtensions.FlatRate; return inputsModel.StandardRate = RateExtensions.StandardRate * (inputsModel.Amount * inputsModel.Quantity) + Nhil(inputsModel.Amount) + Getfund(inputsModel.Amount); } public static decimal Nhil(decimal amount) { return RateExtensions.Nhil * amount; } public static decimal Getfund(decimal amount) { return RateExtensions.Getfund * amount; } } }
fd29933be059d565b7e8c3d7c4426032b3099a97
C#
scrum-groep-i8ao3-1/sprint2
/s1-be-mo5/s1-be-mo5/5.14/Program.cs
3.71875
4
using System; class program { public static void Main() { Console.Write("Geef een Decimal: "); int DecimalNumber = int.Parse(Console.ReadLine()); int remainder; string result = string.Empty; while (DecimalNumber > 0) { remainder = DecimalNumber % 2; DecimalNumber /= 2; result = remainder.ToString() + result; } Console.WriteLine("Binary: {0}", result); Console.ReadLine(); int decimalNumber, quotient; int i = 1, j, temp = 0; char[] hexadecimalNumber = new char[100]; char temp1; Console.WriteLine("Geef een decimaal:"); decimalNumber = int.Parse(Console.ReadLine()); quotient = decimalNumber; while (quotient != 0) { temp = quotient % 16; if (temp < 10) temp = temp + 48; else temp = temp + 55; temp1 = Convert.ToChar(temp); hexadecimalNumber[i++] = temp1; quotient = quotient / 16; } Console.Write("Equivalent HexaDecimal Number is "); for (j = i - 1; j > 0; j--) Console.Write(hexadecimalNumber[j]); Console.Read(); } }
e4be8380560a0535b8a2e5e5b3dc8f500f9c200f
C#
ironxing/CsharpCourse
/KT8/X/TestReadFile/TestReadFile/TestReadFile/Program.cs
2.90625
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestReadFile { class Program { static void Main(string[] args) { string filename = @"C:\Users\Xing\Google Drive\My Documents\ORU\Termin 3\Del2 Objektorienterad programmering med C#\KT8\X\aTextFile.txt"; using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { var sr = new StreamReader(fs); var filecontent = sr.ReadToEnd(); Console.Write(filecontent); sr.Close(); } Console.ReadKey(); } } }
ed48e46e7fe634f168a4fe54096aaef63adabea3
C#
danielhuggins/TyrSc2
/Tyr/StrategyAnalysis/CreeperLord.cs
2.59375
3
using SC2APIProtocol; using System.Collections.Generic; using SC2Sharp.Agents; namespace SC2Sharp.StrategyAnalysis { public class CreeperLord : Strategy { private static CreeperLord Singleton = new CreeperLord(); private Dictionary<ulong, int> LastExpansionHoverFrame = new Dictionary<ulong, int>(); public static Strategy Get() { return Singleton; } public override bool Detect() { HashSet<ulong> creeperLords = new HashSet<ulong>(); foreach (Unit enemy in Bot.Main.Enemies()) { if (enemy.UnitType != UnitTypes.OVERLORD) continue; foreach (Agent agent in Bot.Main.Units()) { if (!UnitTypes.ResourceCenters.Contains(agent.Unit.UnitType)) continue; if (agent.DistanceSq(enemy) <= 2 * 2) { creeperLords.Add(enemy.Tag); if (!LastExpansionHoverFrame.ContainsKey(enemy.Tag)) LastExpansionHoverFrame.Add(enemy.Tag, Bot.Main.Frame); else if (Bot.Main.Frame - LastExpansionHoverFrame[enemy.Tag] >= 22.4 * 10) return true; break; } } } List<ulong> removeTags = new List<ulong>(); foreach (ulong tag in LastExpansionHoverFrame.Keys) if (!creeperLords.Contains(tag)) removeTags.Add(tag); foreach (ulong removeTag in removeTags) LastExpansionHoverFrame.Remove(removeTag); return false; } public override string Name() { return "CreeperLord"; } } }
310fd8e86e9cfb3f2ee30c53f1b4f76ce6a0392e
C#
ananth039/Anantha-Kumar-.net-Practice-programs
/auto generrated id i textbox from database table/auto generrated id i textbox from database table/Employee Registration form.aspx.cs
2.65625
3
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace auto_generrated_id_i_textbox_from_database_table { public partial class Employee_Registration_form : System.Web.UI.Page { string eno = "eno_"; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Emp"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { if (IsPostBack == false) { AutoGeneratedId(); } } private void AutoGeneratedId() { con.Open(); SqlCommand cmd = new SqlCommand("select count(*) from emp", con); int i = Convert.ToInt32(cmd.ExecuteScalar()); con.Close(); i++; eno = eno + i; txtEmpno.Text = eno; } protected void btnRegister_Click(object sender, EventArgs e) { con.Open(); SqlCommand cmd = new SqlCommand("insert into emp values(@eno,@ename,@sal)",con); cmd.Parameters.AddWithValue("@eno", txtEmpno.Text); cmd.Parameters.AddWithValue("@ename", txtEname.Text); cmd.Parameters.AddWithValue("@sal", int.Parse(txtSalary.Text)); cmd.ExecuteNonQuery(); con.Close(); AutoGeneratedId(); txtEname.Text = ""; txtSalary.Text = ""; } } }
159ba722236efeb79f4b5a96e824fd9d31938595
C#
MattisVainikainen/ProgHomeWork
/Övningar/IfSatser/Ovning6.cs
3.28125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProgHomeWork.Övningar.IfSatser { class Ovning6 { int totalPrice; public int TotalPrice(int prisPerEnhet, int enheter) { totalPrice = prisPerEnhet * enheter; if(totalPrice > 1000) { totalPrice = (int)(totalPrice * 0.9); } return totalPrice; } public void Print() { Console.WriteLine("Ange Antal: "); int antal = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Ange Pris per Enhet: "); int enhetsPris = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Totalpriset med rabatt är : " + TotalPrice(antal, enhetsPris)); Console.ReadLine(); } } }
739bd9040baa3fd16cb4661ec7961bc51c060525
C#
Avi-Meshulam/MyStore
/MyStore/Converters/StringFormatConverter.cs
2.921875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Data; namespace MyStore.Converters { /// <summary> /// Formats a string using StringFormat property or "parameter" paramater /// </summary> /// <example> /// <Page.Resources> /// <local:StringFormatConverter x:Key="StringFormatConverter"/> /// <local:StringFormatConverter x:Key="DateStringFormatConverter" StringFormat="\{0:dd/MM/yyyy\}"/> /// </Page.Resources> /// <TextBlock Text="{x:Bind Date, Converter={StaticResource StringFormatConverter}}, ConverterParameter='\{0:dd/MM/yyyy\}'"/> /// <TextBlock Text="{x:Bind Date, Converter={StaticResource DateStringFormatConverter}}"/> /// </example> public sealed class StringFormatConverter : IValueConverter { public string StringFormat { get; set; } public object Convert(object value, Type targetType, object parameter, string language) { string format = (string.IsNullOrEmpty(StringFormat)) ? parameter as string : StringFormat; if (value == null || string.IsNullOrEmpty(format)) return value; return string.Format(format, value); } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } }
11dda9aef9b005414634745dfe03286f1245840a
C#
msgsmg/msggittest
/csharpfiles/ReverseCStyleStringInPlace/Program.cs
3.890625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReverseCStyleStringInPlace { class Program { static void Main(string[] args) { Console.WriteLine("Enter a string"); string str = Console.ReadLine(); Console.WriteLine("Reverse string is : " + RevString(str)); Console.ReadKey(); } private static string RevString(string str) { int end = str.Length - 1; int start = 0; char[] cArr = str.ToCharArray(); char tmp = '\0'; while (start < end) { tmp = cArr[start]; cArr[start] = cArr[end]; cArr[end] = tmp; start++; end--; } return new string(cArr); } } }
9672cf7743433bc9c6e5e87a88da15970dc44a4e
C#
ShreyTiwari/School-Manager
/SchoolManager/Members/Receptionist.cs
3.109375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolManager { public class Complaint : EventArgs { public DateTime ComplaintTime { get; set; } public string ComplaintRaised { get; set; } } public class Receptionist : SchoolMember, IPayroll { private int income; private int balance; public event EventHandler<Complaint> ComplaintRaised; public Receptionist(int income = 10000) { this.income = income; balance = 0; } public Receptionist(string name, string address, int phoneNum, int income = 10000) { Name = name; Address = address; Phone = phoneNum; this.income = income; balance = 0; } public void Display() { Console.WriteLine("Name: {0}, Address: {1}, Phone: {2}", Name, Address, Phone); } public void Pay() { Util.NetworkDelay.PayEntity("Receptionist", Name, ref balance, income); } public void HandleComplaint() { Complaint complaint = new Complaint(); complaint.ComplaintTime = DateTime.Now; complaint.ComplaintRaised = Util.Console.AskQuestion("Please enter your Complaint: "); ComplaintRaised?.Invoke(this, complaint); } } }
022a3599981d20f49847db85958b4b799f773563
C#
sakapon/AtCoder-Contests
/CSharp/Contests2020/ABC151/F.cs
3.109375
3
using System; using System.Linq; class F { static void Main() { var n = int.Parse(Console.ReadLine()); var p = new int[n].Select(_ => Console.ReadLine().Split().Select(int.Parse).ToArray()).Select(x => new V(x[0], x[1])).ToArray(); if (n == 2) { Console.WriteLine((p[1] - p[0]).Norm / 2); return; } var M = 0.0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) M = Math.Max(M, GetRadius(p[i], p[j], p[k])); Console.WriteLine(M); } static double GetRadius(V p0, V p1, V p2) { var v1 = p1 - p0; var v2 = p2 - p0; var v3 = p2 - p1; var a = v1.Norm; var b = v2.Norm; var c = v3.Norm; var s_4 = Math.Abs(v1.X * v2.Y - v2.X * v1.Y) * 2; if (s_4 == 0) return Math.Max(Math.Max(a, b), c) / 2; if (Cos(a, b, c) <= 0) return a / 2; if (Cos(b, c, a) <= 0) return b / 2; if (Cos(c, a, b) <= 0) return c / 2; return a * b * c / s_4; } static double Cos(double a, double b, double c) { return (b * b + c * c - a * a) / (2 * b * c); } } struct V { public static V Zero = new V(); public static V XBasis = new V(1, 0); public static V YBasis = new V(0, 1); public int X, Y; public V(int x, int y) { X = x; Y = y; } public double Norm => Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2)); public static V operator +(V v) => v; public static V operator -(V v) => new V(-v.X, -v.Y); public static V operator +(V v1, V v2) => new V(v1.X + v2.X, v1.Y + v2.Y); public static V operator -(V v1, V v2) => new V(v1.X - v2.X, v1.Y - v2.Y); public static bool operator ==(V v1, V v2) => v1.X == v2.X && v1.Y == v2.Y; public static bool operator !=(V v1, V v2) => !(v1 == v2); public override bool Equals(object obj) => obj is V && this == (V)obj; public override int GetHashCode() => X ^ Y; public override string ToString() => $"{X} {Y}"; }
5c676dceda9b03839162eb2e1454c3903597f8c9
C#
shendongnian/download4
/first_version_download2/170184-12730444-30043009-2.cs
3.34375
3
using System.Linq; using System.Text.RegularExpressions; static class Program { static void Main(string[] aargs) { string value = "I have a dog and a cat."; Regex regex = new Regex("dog|cat"); var matchesList = (from Match m in regex.Matches(value) select m.Value).ToList(); } }
75cf63137af4cfe9045c54ea1692f80e88ec2e62
C#
nuryanto2121/RumahUmat
/RumahUmat/Repository/OptionDBRepo.cs
2.625
3
using RumahUmat; using RumahUmat.Models; using Dapper; using Microsoft.Extensions.Configuration; using Npgsql; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; namespace RumahUmat.Repository { public class OptionDBRepo : IRepository<OptionDB,int> { private string connectionString; public OptionDBRepo(string Configuration) { connectionString = Configuration; } public OutPut Add(OptionDB item) { throw new NotImplementedException(); } internal IDbConnection Connection { get { return new NpgsqlConnection(connectionString); } } public bool Save(OptionDB domain) { throw new NotImplementedException(); } public bool Update(OptionDB domain) { throw new NotImplementedException(); } public bool Delete(int key) { throw new NotImplementedException(); } public List<OptionDB> GetList() { throw new NotImplementedException(); } public List<OptionDB> GetList(string Method, string ApiName) { List<OptionDB> op = new List<OptionDB>(); using (IDbConnection conn = Connection) { try { conn.Open(); op = conn.Query<OptionDB>("SELECT * FROM public.\"OptionDb\" where \"ApiName\" = @apiName AND \"Method\" = @method", new { apiName = ApiName, method = Method }).ToList(); } catch (Exception ex) { throw (ex); } finally { if (conn.State == ConnectionState.Open) conn.Close(); } } return op; } public List<OptionDB> GetList(int pageSize, int currentPage, string sortName, string sortOrder) { throw new NotImplementedException(); } public OptionDB GetById(int key) { OptionDB op = new OptionDB(); using (IDbConnection conn = Connection) { try { conn.Open(); op = conn.Query<OptionDB>("SELECT * FROM public.\"OptionDb\" where OptionDBId = @ID",new { ID = key}).FirstOrDefault(); } catch (Exception ex) { throw (ex); } finally { if (conn.State == ConnectionState.Open) conn.Close(); } } return op; } public OptionDB GetById(string Method,string ApiName) { OptionDB op = new OptionDB(); using (IDbConnection conn = Connection) { try { conn.Open(); op = conn.Query<OptionDB>("SELECT * FROM public.\"OptionDb\" where ApiName = @apiName AND Method = @method", new { apiName = ApiName, method = Method }).FirstOrDefault(); } catch (Exception ex) { throw (ex); } finally { if (conn.State == ConnectionState.Open) conn.Close(); } } return op; } } }
890faa47aee52bfe8dcb6d9a19b2ba439b6d92b9
C#
yaelschlotman/SodaMachine
/SodaMachine/SodaMachine/Coin.cs
2.921875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MySodaMachine { public class Coin { private string CoinName; private int Quantity; private int Value; public Coin(string coinName, int quantity, int value) { this.CoinName = coinName; this.Quantity = quantity; this.Value = value; } public string coinName { get { return CoinName; } set { CoinName = value; } } public int quantity { get { return Quantity; } set { Quantity = value; } } public int value { get { return Value; } set { Value = value; } } } }
6607d7b8f22674143ba2d14aed93a97503694849
C#
c-sharp-projects/Gideon-Personal-assistant
/Gideon/Weather.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Media.Imaging; using System.Xml; using System.Xml.Linq; namespace Gideon { class Weather { const String URL = "http://api.openweathermap.org/data/2.5/weather?q="; const String Key = "&mode=xml&appid=bdda109516ac7460899029cc0dc03963"; double TemperatureCelsius; double TemperatureCelsiusMax; double TemperatureCelsiusMin; double Kelvin = 273.15; public string Status { get; set; } public string Temperature { get; set; } public string MaxTemperature { get; set; } public string MinTemperature { get; set; } public string City { get; set; } public BitmapImage ImageData { get; set; } public Weather() { ParseXML("Pune"); UpdateInfo(); } public void ParseXML(string City) { try { using (WebClient client = new WebClient()) { string xml = GetXmlData(City, client); XDocument xmlDoc = XDocument.Parse(xml); this.City = xmlDoc.Descendants("city").Attributes("name").First().Value; Temperature = xmlDoc.Descendants("temperature").Attributes("value").First().Value; MaxTemperature = xmlDoc.Descendants("temperature").Attributes("max").First().Value; MinTemperature = xmlDoc.Descendants("temperature").Attributes("min").First().Value; Status = xmlDoc.Descendants("speed").Attributes("name").First().Value; Location.City = xmlDoc.Descendants("city").Attributes("name").First().Value; Location.Wind = xmlDoc.Descendants("speed").Attributes("value").First().Value; Location.Lastupdate = UtcToLocal(xmlDoc.Descendants("lastupdate").Attributes("value").First().Value); Location.Temperature = xmlDoc.Descendants("temperature").Attributes("value").First().Value; Location.Pressure = xmlDoc.Descendants("pressure").Attributes("value").First().Value; Location.TemperatureMax = xmlDoc.Descendants("temperature").Attributes("max").First().Value; Location.TemperatureMin = xmlDoc.Descendants("temperature").Attributes("min").First().Value; Location.Country = xmlDoc.Descendants("country").First().Value; Location.Sunrise = UtcToLocal(xmlDoc.Descendants("sun").Attributes("rise").First().Value); Location.Sunset = UtcToLocal(xmlDoc.Descendants("sun").Attributes("set").First().Value); Location.WindDir = xmlDoc.Descendants("direction").Attributes("name").First().Value; Location.WindDesc = xmlDoc.Descendants("speed").Attributes("name").First().Value; Location.Cloud = xmlDoc.Descendants("clouds").Attributes("name").First().Value; Location.Humidity = xmlDoc.Descendants("humidity").Attributes("value").First().Value; } } catch (XmlException e) { GideonBase.SynObj.SpeakAsync("Could not receive accurate data to " + e.Source); //SynObj.SpeakAsync("The program will now quit..."); System.Environment.Exit(1); } catch (Exception e) { //SynObj.SpeakAsync(e.Message); } } private string GetXmlData(string city, WebClient client) { return client.DownloadString(URL + city + Key); } public void UpdateInfo() { TemperatureCelsius = Convert.ToDouble(Temperature) - Kelvin; TemperatureCelsiusMax = Convert.ToDouble(MaxTemperature) - Kelvin; TemperatureCelsiusMin = Convert.ToDouble(MinTemperature) - Kelvin; Temperature = Math.Round(TemperatureCelsius, 0) + " ℃"; MaxTemperature = Math.Round(TemperatureCelsiusMax, 2) + " ℃"; MinTemperature = Math.Round(TemperatureCelsiusMin, 2) + " ℃"; if (isDay()) { ImageData = LoadImage(WeatherPath.Sunicon); } else { ImageData = LoadImage(WeatherPath.Moonicon); } } private DateTime UtcToLocal(string DateStr) { DateTime univDateTime; univDateTime = DateTime.Parse(DateStr); return univDateTime.ToLocalTime(); } public bool isDay() { bool isDay = true; int citySunriseTime = (Location.Sunrise.Hour * 60) + (Location.Sunrise.Minute); int currentSystemTime = (DateTime.Now.Hour * 60) + (DateTime.Now.Minute); int citySunsetTime = (Location.Sunset.Hour * 60) + (Location.Sunset.Minute); if (Location.Sunset.Day == DateTime.Now.Day) { if (citySunriseTime <= currentSystemTime && currentSystemTime < citySunsetTime) { isDay = true; } else { isDay = false; } } else { citySunsetTime += 24 * 60; if (citySunriseTime <= currentSystemTime && currentSystemTime < citySunsetTime) { isDay = true; } else { isDay = false; } } return isDay; } public BitmapImage LoadImage(string url) { BitmapImage bi = null; try { bi = new BitmapImage(); bi.BeginInit(); bi.UriSource = new Uri(url); bi.EndInit(); } catch (Exception e) { } return bi; } } class Location { private static string city; private static string country; private static DateTime sunrise; private static DateTime sunset; private static string cloud; private static string humidity; private static DateTime lastupdate; private static string wind; private static string temperature; private static string temperatureMin; private static string temperatureMax; private static string pressure; private static string windDesc; private static string windDir; public static string City { get { return city; } set { city = value; } } public static string Pressure { get { return pressure; } set { pressure = value; } } public static string WindDesc { get { return windDesc; } set { windDesc = value; } } public static string WindDir { get { return windDir; } set { windDir = value; } } public static string Country { get { return country; } set { country = value; } } public static string TemperatureMin { get { return temperatureMin; } set { temperatureMin = value; } } public static string TemperatureMax { get { return temperatureMax; } set { temperatureMax = value; } } public static DateTime Sunrise { get { return sunrise; } set { sunrise = value; } } public static DateTime Sunset { get { return sunset; } set { sunset = value; } } public static string Cloud { get { return cloud; } set { cloud = value; } } public static string Wind { get { return wind; } set { wind = value; } } public static string Temperature { get { return temperature; } set { temperature = value; } } public static string Humidity { get { return humidity; } set { humidity = value; } } public static DateTime Lastupdate { get { return lastupdate; } set { lastupdate = value; } } } }
351ad6a505ff12617969766a5476fe6a3e2b3413
C#
PowerShell/vscode-powershell
/test/mocks/BinaryModule/TestSampleCmdletCommand.cs
2.828125
3
using System.Management.Automation; namespace BinaryModule { [Cmdlet(VerbsDiagnostic.Test, "SampleCmdlet")] [OutputType(typeof(FavoriteStuff))] public class TestSampleCmdletCommand : PSCmdlet { [Parameter( Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public int FavoriteNumber { get; set; } = 42; [Parameter( Position = 1, ValueFromPipelineByPropertyName = true)] [ValidateSet("Cat", "Dog", "Horse")] public string FavoritePet { get; set; } = "Dog"; // This method gets called once for each cmdlet in the pipeline when the pipeline starts executing protected override void BeginProcessing() { WriteVerbose("Begin!"); } // This method will be called for each input received from the pipeline to this cmdlet; if no input is received, this method is not called protected override void ProcessRecord() { WriteObject(new FavoriteStuff { FavoriteNumber = FavoriteNumber, FavoritePet = FavoritePet }); } // This method will be called once at the end of pipeline execution; if no input is received, this method is not called protected override void EndProcessing() { WriteVerbose("End!"); } } public class FavoriteStuff { public int FavoriteNumber { get; set; } public string FavoritePet { get; set; } } }
0e59950a555acca7a6c3b8f4817a8bdc774c018e
C#
dmkovtun/SkyTrek
/SkyTrekVisual/GameItems/UserControls/NewAsteroid.xaml.cs
2.640625
3
using System; using System.Diagnostics; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using SkyTrekVisual.Controls; namespace SkyTrekVisual.GameItems { /// <summary> /// Interaction logic for Asteriod.xaml /// </summary> public partial class NewAsteroid : UserControl, IGameItem, IDestructibleItem, IDamagable { public static int MaxSize = 32; public static int MinSize = 5; public NewAsteroid() { InitializeComponent(); GenerateType(); GenerateSize(); } public NewAsteroid(int x, int y) : this() { CoordLeft = x; CoordBottom = y; SetValue(Panel.ZIndexProperty, 1000); Speed = ItemGrid.Height/4; HitDamage = (int)ItemGrid.Height*4 / HitDamage; } private double _CoordLeft; public double CoordLeft { get { return _CoordLeft; } set { SetValue(Canvas.LeftProperty, _CoordLeft = value); } } private double _CoordBottom; public double CoordBottom { get { return _CoordBottom; } set { SetValue(Canvas.BottomProperty, _CoordBottom = value); } } public ImageBrush LoadImage(int t) => new ImageBrush(new BitmapImage(new Uri(DirectoryHelper.CurrentDirectory + @"\Asteroids\Asteroid" + t.ToString() + ".png", UriKind.Relative))); public void GenerateType() { ItemGrid.Background = LoadImage(new Random().Next() % 4 + 1); } public void GenerateSize() { ItemGrid.Height = ItemGrid.Width = new Random().Next(MinSize, MaxSize); } #region IDestructibleItem public int ItemWidth { get { return (int)ActualWidth; } } public int ItemHeight { get { return (int)ActualHeight; } } public bool IsCollision(IDestructibleItem item) => CollisionDetector.IsCollision(this, item); #endregion public double Speed { get; set; } = 3; public void GoBackward() { CoordLeft -= Speed; } #region IDamagable public double HealthPoints { get; set; } = 20; public int HitDamage { get; set; } = 10; public bool IsAlive() => HealthPoints > 0; public void WasHit(double hitDamage) { HealthPoints -= hitDamage; } public bool IsInvincible { get; set; } = false; #endregion } }
c24060ab6cdb5b8c108cdb57ae4bca251118addb
C#
muchamad2/ElectroFisher
/Assets/Scripts/Level1/Fisher/SpawnFish.cs
2.796875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnFish : MonoBehaviour { public GameObject[] spownpoint; public GameObject[] riverFishObject; public GameObject[] seaFishObject; void Start() { Spawn(); } void Spawn() { foreach (var sp in spownpoint) { GameObject obj; if (GameUtility.environmentType == EnvironmentType.Forest) { int index = getRiverFish(); obj = Instantiate(riverFishObject[index], sp.transform.position, Quaternion.identity); } else if (GameUtility.environmentType == EnvironmentType.Sea) { int index = getSeaFish(); obj = Instantiate(seaFishObject[index], sp.transform.position, Quaternion.identity); } } } public int getRiverFish(){ int rand = UnityEngine.Random.Range(0,riverFishObject.Length-1); return rand; } int getSeaFish(){ int rand = UnityEngine.Random.Range(0,seaFishObject.Length-1); return rand; } }
577b6cabe01e7f80fed230121fffdf2dc46ddf78
C#
SmileyfoxUnderrain/NN0
/NN0/ActivationFunctions/SoftSignFunction.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NN0.ActivationFunctions { public class SoftSignFunction : ILayerIndependentFunction { public double Function(double x) { var ret = x / (1 + Math.Abs(x)); return ret; } public double Derivative(double x) { var ret = 1 / Math.Pow(1 + Math.Abs(x), 2); return ret; } } }
d8a7bbdec01aea764b6751f99d861880fd07ec6a
C#
aadjesus/Diversos
/Exemplos_Roger/System.Boolean/Methods/ToUInt16/ToUInt1600/Program.cs
3.15625
3
/// Author: Roger Villela /// Contact: Roger.Villela@live.com /// LinkedIn: http://br.linkedin.com/in/rogeralvesvillela /// Blog: http://rogervillelajournal.wordpress.com /// Products: Microsoft Visual Studio /Microsoft Visual C# /// Programming Language: C# /// /// UInt16 ToUInt16( IFormatProvider provider ) /// /// DESCRIÇÃO /// /// Converte, se possível, o valor da instância numa representação suportada pelo tipo UInt16. /// Ou seja, em um valor UInt16(ushort), um(true) ou zero(false). /// /// Este método é uma implementação explícita (explicit interface implementation) de /// IConvertible. Estes são os métodos de IConvertible implementados por Boolean: /// - IConvertible.ToBoolean /// - IConvertible.ToByte /// - IConvertible.ToChar /// - IConvertible.ToDateTime /// - IConvertible.ToDecimal /// - IConvertible.ToDouble /// - IConvertible.ToInt16 /// - IConvertible.ToInt32 /// - IConvertible.ToInt64 /// - IConvertible.ToSByte /// - IConvertible.ToSingle /// - IConvertible.ToType /// - IConvertible.ToUInt16 /// - IConvertible.ToUInt32 /// - IConvertible.ToUInt64 /// /// Nem todos estes métodos realizam a conversão. Alguns podem apenas lançar uma exception, como /// a InvalidCastException indicando que a conversão não é suportada. #region Namespaces using System; #endregion namespace ToUInt1600 { public class Program { #region Common Messages //public static readonly String PauseMessage = "Pressione <ENTER> para continuar..."; public static readonly String EndMessage = "Pressione <ENTER> para terminar..."; #endregion static void Main( String[] args ) { //Boolean value = true; Boolean value = false; /* * Como é uma explicit interface implementation é preciso realizar o casting. **/ // O propósito dos métodos de IConvertible, além da conversão é óbvio, // é poder gerar uma saída formatada de acordo com a cultura definida pelo programa // ou pelo sistema operacional. Console.WriteLine( "{0}", ( (IConvertible)value ).ToUInt16( null ).ToString() ); Console.WriteLine( "\n {0}", Program.EndMessage ); Console.ReadKey(); } } }
61131bfa64d5f41561ca6d16e15297e56656cd5c
C#
rokn/EatGame
/EatMe/EatMe/Components/SpriteRenderer.cs
2.546875
3
using System; using EatMe.UnifiedClasses; using ECS; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace EatMe.Components { public class SpriteRenderer : Component, IDrawableComponent { public int DrawLayer { get; set; } public Texture2D Texture { get; set; } public Vector2 Origin { get; set; } public Color Color { get; set; } public float Transperency { get; set; } private Transform _transform; public SpriteRenderer() { Texture = null; Color = Color.White; Transperency = 1.0f; } public int Width => Texture?.Width ?? 0; public int Height => Texture?.Height ?? 0; public override void Start() { _transform = Entity.GetComponent<Transform>(); } public SpriteRenderer(string filename) { Texture = Resources.GetTexture(filename); Origin = new Vector2(Texture.Width/2, Texture.Height/2); Color = Color.White; Transperency = 1.0f; } public bool Draw() { if (_transform == null) { _transform = Entity.GetComponent<Transform>(); } if (Texture == null || _transform == null || !IsInView()) return false; Main.SpriteBatch.Draw(Texture, _transform.Position, null, Color * Transperency, (float)_transform.Rotation, Origin, _transform.Scale, SpriteEffects.None, 0.1f); return true; } private bool IsInView() { var maxDimension = Math.Max(Width, Height); Vector2 pos = _transform.Position; //TODO: Make Camera check for point in view with transofrmations Rectangle container = new Rectangle((int)(pos.X - Origin.X), (int)(pos.Y - Origin.Y), maxDimension, maxDimension); return Main.MainCamera.IsInView(container); } } }
320dc7422d21f4645b48ffc1cff6388fe1a32f28
C#
mdsoftware/m3d
/m3d/Faces3D.cs
2.984375
3
/*************************************************************************** This code is written by Denis Mitrofanov This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ***************************************************************************/ using System; using System.Collections.Generic; using System.Text; namespace m3d { /// <summary> /// 3D face /// </summary> public class Face3D { protected Point3D[] points; private int tag; private int shadow; public Face3D(int size) { this.tag = 0; this.shadow = 0; this.points = new Point3D[size]; } public Face3D Copy() { Face3D f = new Face3D(this.points.Length); for (int i = 0; i < f.points.Length; i++) f.points[i] = this.points[i]; f.tag = this.tag; f.shadow = this.shadow; return f; } public Point3D[] Points { get { return this.points; } } public int Depth { get { if (this.points == null) return 0; int x = 0; for (int i = 0; i < this.points.Length; i++) x += this.points[i].Z; return (int)Math.Round((double)x / (double)this.points.Length, 0); } } public Face3D(List<Point3D> points) : this(points.Count) { for (int i = 0; i < this.points.Length; i++) this.points[i] = points[i]; } public Face3D(Point3D[] points) : this(points.Length) { this.points = new Point3D[points.Length]; for (int i = 0; i < this.points.Length; i++) this.points[i] = points[i]; } public void Project(RotateCoeffs rotate, Point3D camera) { if (this.points == null) return; for (int i = 0; i < this.points.Length; i++) this.points[i].Project(rotate, camera); } public void ApplyViewer(Point3D viewer) { if (this.points == null) return; for (int i = 0; i < this.points.Length; i++) this.points[i].ApplyViewer(viewer); } public int Tag { get { return this.tag; } set { this.tag = value; } } public int Shadow { get { return this.shadow; } set { this.shadow = value; } } public int Count { get { return this.points.Length; } } } /// <summary> /// 3D triangle /// </summary> public sealed class Triangle3D : Face3D { public Triangle3D(Point3D a, Point3D b, Point3D c) : base(3) { this.points[0] = a; this.points[1] = b; this.points[2] = c; } } /// <summary> /// 3D rectangle /// </summary> public sealed class Rectangle3D : Face3D { public Rectangle3D(Point3D a, Point3D b, Point3D c, Point3D d) : base(4) { this.points[0] = a; this.points[1] = b; this.points[2] = c; this.points[3] = d; } } /// <summary> /// 3D line /// </summary> public sealed class Line3D : Face3D { public Line3D(Point3D a, Point3D b) : base(2) { this.points[0] = a; this.points[1] = b; } } }
6abcf9a2114264913bc433debb18a140943852f8
C#
ARigitano/AugmentedGymnasium
/Assets/Scripts/SceneScripts/Core/HealingZone.cs
2.84375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// An area in which players can stay in to regain their life points over time. /// </summary> public class HealingZone : MonoBehaviour { /// <summary> /// The speed at which the players regain their life points. /// </summary> [SerializeField] private int _speed = 1; private void OnTriggerStay(Collider other) { if (other.tag == "PlayerArea" && other.GetComponent<TrackerCircle>().life < other.GetComponent<TrackerCircle>(). lifeMax) { other.GetComponent<TrackerCircle>().life += _speed; } } }
36d2acae92942af81e32c51c739b10c6cf2d449d
C#
FeiYanLeung/Laboratory
/Laboratory.Migrator/Models/DbInitializer/SQLDbinitializer.cs
2.78125
3
using Laboratory.Migrator.Models.Entities; using System.Collections.Generic; using System.Data.Entity; namespace Laboratory.Migrator.Models.DbInitializer { public sealed class SQLDbinitializer : DropCreateDatabaseAlways<DataContext> { protected override void Seed(DataContext context) { new List<ProductCategory>() { new ProductCategory(){ Name = "文具", Products = new List<Product>(){ new Product("铅笔",1.5M), new Product("墨水",2), new Product("钢笔",29.99M), new Product("笔记本",3.5M) } }, new ProductCategory(){ Name = "食品", SubCategories = new List<ProductCategory>(){ new ProductCategory("水果"){ Products = new List<Product>(){ new Product("火龙果",6), new Product("苹果",8), new Product("橘子",8), new Product("梨子",5), new Product("杏子",10) } }, new ProductCategory("蔬菜"){ Products = new List<Product>(){ new Product("大白菜",2.1M), new Product("小白菜",2.3M), new Product("菠菜",1.5M), new Product("豇豆",6), new Product("生姜",8), new Product("蒜苗",5) } }, new ProductCategory("初加工"){ Products = new List<Product>(){ new Product("腊肉",30), new Product("干黄花菜",20), new Product("活豆腐",2), new Product("生菜油",15) } }, new ProductCategory("熟食"){ Products = new List<Product>(){ new Product("烤五花肉",42), new Product("茶叶蛋",1.5M), new Product("炸丸子",20) } } } } } .ForEach(item => { context.ProductCategories.Add(item); }); context.SaveChanges(); } } }
dff229fc0c70afa33437645675fd8c22acec11a0
C#
Razonatair/ScrambleForTheStars
/Classes/ThreadManager.cs
3.015625
3
//=================================================== // Copyright 2018 Dyllin Edward Reid Black // //=================================================== using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Threading; //This class will handle the creation and assigning of threads. //It has not been implemented yet. namespace Scramble { public static class ThreadManager { private static Thread[] threadArray; //The array which will hold all threads used by the game. private static bool initialized; //Defines whether or not this class has been initialized yet. //Initializes the class and prepares it for use. public static void Initialize() { //If we're not initialized, run through initialization. if (!initialized) { threadArray = new Thread[Settings.threadNumber]; initialized = true; } else //Else, hassle the programmer for trying to initialize something they already did. { Debug.Log("Attempting to initialize already initialized ThreadManager."); } } } }
fedb79c5cdcac1e736f6b85499d430dab575bba3
C#
priyaaank/XamarinMapsPoc
/Mappy.Common/Models/Atm.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mappy { public class Atm : BankEntity { public string Brand { get; private set; } private const string SunCorpBrandName = "suncorp"; public Atm(long id, string brand, string name, long locationId, double latitude, double longitude, double distance, string locationType,string address) : base(id, name, locationId, latitude, longitude, distance, BankEntity.Type.Atm,locationType, address ) { this.Brand = brand; } public override bool IsBranch() { return false; } public override bool IsAtm() { return true; } public override bool IsOwnBrand () { if (Brand == null) return true; return string.Equals (SunCorpBrandName, Brand, StringComparison.OrdinalIgnoreCase); } #region implemented abstract members of BankEntity public override string BrandName () { return this.Brand; } #endregion } }
d587d507d6c4c528cbe66243a755447fca3be958
C#
BigEggStudy/Coursera-Princeton-Algorithm
/c#/BigEgg.Algorithm/BigEgg.Algorithm/Sorts/SortHelper.cs
3.6875
4
using System; using System.Collections.Generic; namespace BigEgg.Algorithm.Sorts { internal static class SortHelper { /// <summary> /// Is v < w ? /// </summary> /// <returns><c>True</c> if v < w, otherwise <c>false</c>.</returns> public static bool Less(IComparable v, IComparable w) { return v.CompareTo(w) < 0; } /// <summary> /// Is v < w ? /// </summary> /// <returns><c>True</c> if v < w, otherwise <c>false</c>.</returns> public static bool Less<Key>(IComparer<Key> c, Key v, Key w) where Key : class { return c.Compare(v, w) < 0; } /// <summary> /// Is v > w ? /// </summary> /// <returns><c>True</c> if v > w, otherwise <c>false</c>.</returns> public static bool Greater(IComparable v, IComparable w) { return v.CompareTo(w) > 0; } /// <summary> /// Is v > w ? /// </summary> /// <returns><c>True</c> if v > w, otherwise <c>false</c>.</returns> public static bool Greater<Key>(IComparer<Key> c, Key v, Key w) where Key : class { return c.Compare(v, w) > 0; } /// <summary> /// Exchange a[i] and a[j] (for indirect sort) /// </summary> /// <param name="a">The array</param> /// <param name="i">The index1.</param> /// <param name="j">The index2.</param> public static void Exchange<Key>(Key[] a, int i, int j) { Key swap = a[i]; a[i] = a[j]; a[j] = swap; } /// <summary> /// Check if array is sorted in ascending order, using the natural order. /// </summary> /// <param name="a">The array</param> /// <returns><c>True</c> if array is sorted, otherwise <c>false</c>.</returns> public static bool IsSorted(IComparable[] a) { return IsSorted(a, SortOrder.ASC); } /// <summary> /// Check if array is sorted in specific order, using the natural order. /// </summary> /// <param name="a">The array</param> /// <param name="order">The sort order</param> /// <returns><c>True</c> if array is sorted, otherwise <c>false</c>.</returns> public static bool IsSorted(IComparable[] a, SortOrder order) { return IsSorted(a, 0, a.Length, order); } /// <summary> /// Is the array sorted in specific order from a[lo] to a[hi], using the natural order. /// </summary> /// <param name="a">The array</param> /// <param name="lo">The low index</param> /// <param name="hi">The high index</param> /// <param name="order">The sort order</param> /// <returns><c>True</c> if array is sorted, otherwise <c>false</c>.</returns> public static bool IsSorted(IComparable[] a, int lo, int hi, SortOrder order) { if (order == SortOrder.ASC) { for (int i = lo + 1; i < hi; i++) if (Less(a[i], a[i - 1])) return false; } else { for (int i = lo + 1; i < hi; i++) if (Greater(a[i], a[i - 1])) return false; } return true; } /// <summary> /// Check if array is sorted in ascending order, using a comparer /// </summary> /// <param name="a">The array</param> /// <param name="c">The comparer.</param> /// <returns><c>True</c> if array is sorted, otherwise <c>false</c>.</returns> public static bool IsSorted<Key>(Key[] a, IComparer<Key> c) where Key : class { return IsSorted(a, c, SortOrder.ASC); } /// <summary> /// Check if array is sorted in specific order, using the natural order. /// </summary> /// <param name="a">The array</param> /// <param name="c">The comparer.</param> /// <param name="order">The sort order</param> /// <returns><c>True</c> if array is sorted, otherwise <c>false</c>.</returns> public static bool IsSorted<Key>(Key[] a, IComparer<Key> c, SortOrder order) where Key : class { return IsSorted(a, c, 0, a.Length, order); } /// <summary> /// Is the array sorted in specific order from a[lo] to a[hi], using the natural order. /// </summary> /// <param name="a">The array</param> /// <param name="c">The comparer.</param> /// <param name="lo">The low index</param> /// <param name="hi">The high index</param> /// <param name="order">The sort order</param> /// <returns><c>True</c> if array is sorted, otherwise <c>false</c>.</returns> public static bool IsSorted<Key>(Key[] a, IComparer<Key> c, int lo, int hi, SortOrder order) where Key : class { if (order == SortOrder.ASC) { for (int i = lo + 1; i < hi; i++) if (Less(c, a[i], a[i - 1])) return false; } else { for (int i = lo + 1; i < hi; i++) if (Greater(c, a[i], a[i - 1])) return false; } return true; } } }
f58eb0536d7417b7c3bcdd519811aea5d40ce9d5
C#
anshu777/etm-api
/ETM.Service/Services/StatusService.cs
2.5625
3
using ETM.Repository.Dto; using ETM.Repository.Models; using ETM.Service.Interfaces; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ETM.Service.Services { public class StatusService : IStatusService { public async Task<List<StatusDto>> GetAll() { List<StatusDto> status = null; try { using (var _context = new DatabaseContext()) { var svs = await _context.Status.Include(x => x.StatusType).ToListAsync<Status>(); status = (from s in svs select new StatusDto() { id = s.Id, name = s.Name, description = s.Description, statustypeId = s.StatusTypeId, statustype = s.StatusType.Type }).ToList(); } return status; } catch (Exception e) { throw; } } public async Task<List<StatusType>> GetAllTypes() { List<StatusType> Types = null; try { using(var _contaxt = new DatabaseContext()) { var stypes = await _contaxt.StatusType.ToListAsync<StatusType>(); Types = (from s in stypes select new StatusType() { Id = s.Id, Type = s.Type }).ToList(); } return Types; } catch(Exception e) { throw; } } public async Task<List<StatusDto>> GetByStatusId(int id) { List<StatusDto> status = null; try { using (var _context = new DatabaseContext()) { var statusValue = await _context.Status.Where(x => x.StatusTypeId == id).Include(x => x.StatusType).ToListAsync<Status>(); status = (from s in statusValue select new StatusDto() { id = s.Id, name = s.Name, description = s.Description, statustypeId = s.StatusTypeId }).ToList(); } return status; } catch (Exception e) { throw; } } public async Task<Status> AddStatus(Status status) { try { int sid; using (var _context = new DatabaseContext()) { _context.Status.Add(status); await _context.SaveChangesAsync(); } return status; } catch (Exception e) { throw; } } } }
fdb9202c3a95e36adb26131cc7d5def43bbaf588
C#
arman-tech/AlphaVantageLib
/AlphaVantage.Common/Common/AttributeHelper.cs
3.046875
3
using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace AlphaVantage.Common { public static class AttributeHelper { public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>( Expression<Func<T, TOut>> propertyExpression, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute { var expression = (MemberExpression)propertyExpression.Body; var propertyInfo = (PropertyInfo)expression.Member; var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute; return attr != null ? valueSelector(attr) : default(TValue); } public static TOut GetPropertyBasedOnAvPropertyName<T, TOut, TAttribute, TValue>( string attributeName, T obj, Func<TAttribute, TValue> valueSelector) where TAttribute : AvPropertyNameAttribute { // sanity check - if valueSelect is null then throw an exception if (valueSelector == null) throw new ArgumentNullException(nameof(valueSelector)); // get properties where it has the custom attribute we are looking for with the property name in question. // also ensure that the property type matches the TOut type mentioned. var propInfo = typeof(T).GetProperties() .FirstOrDefault(x => x.GetCustomAttribute<TAttribute>(true) != null && x.GetCustomAttribute<TAttribute>(true).ExtractPropertyName.Equals(attributeName) && x.PropertyType == typeof(TOut)); return propInfo != null ? (TOut)propInfo.GetValue(obj) : default(TOut); } public static void SetPropertyBasedOnAvPropertyName<T, TKind, TAttribute, TValue>( string attributeName, T obj, TKind val, Func<TAttribute, TValue> valueSelector) where TAttribute : AvPropertyNameAttribute where TValue : class { if (valueSelector == null) throw new ArgumentNullException(nameof(valueSelector)); var propInfo = typeof(T).GetProperties() .FirstOrDefault(x => x.GetCustomAttribute<TAttribute>(true) != null && x.GetCustomAttribute<TAttribute>(true).ExtractPropertyName.Equals(attributeName) && x.PropertyType == typeof(TKind)); if (null != propInfo) { propInfo.SetValue(obj, val); } } } }
3d586761891739dc4c9dfa369ec7634f55d21253
C#
TorreyGarland/Highway1.Universal
/Highway1.Universal.UI/Interactivity/PasswordBindingBehavior.cs
2.703125
3
namespace Highway1.Universal.UI.Interactivity { using System.Diagnostics; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; /// <summary>Password binding behavior class.</summary> /// <seealso cref="Highway1.Universal.UI.Interactivity.BehaviorBase{Windows.UI.Xaml.Controls.PasswordBox}" /> [DebuggerStepThrough] public sealed class PasswordBindingBehavior : BehaviorBase<PasswordBox> { #region Properties /// <summary> /// Gets or sets a value indicating whether [bind password]. /// </summary> /// <value><c>true</c> if [bind password]; otherwise, <c>false</c>.</value> public bool BindPassword { get { return (bool)GetValue(BindPasswordProperty); } set { SetValue(BindPasswordProperty, value); } } /// <summary>The bind password property</summary> public static DependencyProperty BindPasswordProperty { get; } = DependencyProperty.Register(nameof(BindPassword), typeof(bool), typeof(PasswordBindingBehavior), new PropertyMetadata(true, BindPasswordChanged)); /// <summary> /// Gets or sets a value indicating whether this instance is updating. /// </summary> /// <value> /// <c>true</c> if this instance is updating; otherwise, <c>false</c>. /// </value> public bool IsUpdating { get { return (bool)GetValue(IsUpdatingProperty); } set { SetValue(IsUpdatingProperty, value); } } /// <summary>The is updating property</summary> public static DependencyProperty IsUpdatingProperty { get; } = DependencyProperty.Register(nameof(IsUpdating), typeof(bool), typeof(PasswordBindingBehavior), new PropertyMetadata(false)); /// <summary>Gets or sets the password.</summary> /// <value>The password.</value> public string Password { get { return (string)GetValue(PasswordProperty); } set { SetValue(PasswordProperty, value); } } /// <summary>The password property</summary> public static DependencyProperty PasswordProperty { get; } = DependencyProperty.Register(nameof(Password), typeof(string), typeof(PasswordBindingBehavior), new PropertyMetadata(string.Empty, PasswordChanged)); #endregion #region Methods [DebuggerStepThrough] private static void BindPasswordChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) => (sender as PasswordBindingBehavior)?.BindPasswordChanged((bool)e.OldValue, (bool)e.NewValue); /// <summary>Binds the password changed.</summary> /// <param name="oldValue">if set to <c>true</c> [old value].</param> /// <param name="newValue">if set to <c>true</c> [new value].</param> private void BindPasswordChanged(bool oldValue, bool newValue) { if (AssociatedObject == null) return; if (oldValue) AssociatedObject.PasswordChanged -= PasswordBoxPasswordChanged; if (newValue) AssociatedObject.PasswordChanged += PasswordBoxPasswordChanged; } /// <summary>Called when [detached].</summary> protected override void OnDetached() { base.OnDetached(); if (AssociatedObject != null) AssociatedObject.PasswordChanged -= PasswordBoxPasswordChanged; } [DebuggerStepThrough] private void PasswordBoxPasswordChanged(object sender, RoutedEventArgs e) { if (AssociatedObject == null) return; IsUpdating = true; Password = AssociatedObject.Password; IsUpdating = false; } [DebuggerStepThrough] private static void PasswordChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) => (sender as PasswordBindingBehavior)?.PasswordChanged(); /// <summary>Passwords the changed.</summary> /// <param name="oldValue">The old value.</param> /// <param name="newValue">The new value.</param> [DebuggerStepThrough] private void PasswordChanged() { if (AssociatedObject == null) return; if (!BindPassword) return; AssociatedObject.PasswordChanged -= PasswordBoxPasswordChanged; if (!IsUpdating) AssociatedObject.Password = Password ?? string.Empty; AssociatedObject.PasswordChanged += PasswordBoxPasswordChanged; } #endregion } }
9bca78fde04d8a996d0c0873dc438b9bcc826b2e
C#
ALowski/hotelRMS
/src/rms/Hotels.Core/LoadPredictors/MovingAverageLoadPredictor.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using Hotels.Basic; namespace Hotels.Core.LoadPredictors { public sealed class MovingAverageLoadPredictor : ILoadPredictor { private double _priceTemp; private double[] _price; private int _priceDay=-1; private double[] _forecast; private DateTime _today; private Queue<PastDay> _pastDays; private bool[] _futureDays; private int _count = 0; public void Initialize(DateTime today, bool[] pastDays, bool[] futureDays,int planningHorizont) { _priceTemp = -1d; _today = today; //_forecast = new double[planningHorizont]; _pastDays = new Queue<PastDay>(); _futureDays = futureDays; var start = pastDays.Length - 1; while (start >= 0 && _count<30) { if (pastDays[start]) { ++_count; } --start; } for (++start; start < pastDays.Length; ++start) { _pastDays.Enqueue(new PastDay { Value = pastDays[start], Stats = 0 }); } } public void AddBooking(Booking booking) { var dayNumber = Math.Max(-1, (_today-booking.CheckIn).Days); if (dayNumber > -1 && dayNumber <= _pastDays.Count) { if(_priceDay<0) _priceDay = dayNumber; if (dayNumber <= _priceDay) { if (dayNumber < _priceDay||(dayNumber == _priceDay && _priceTemp < booking.PricePerNight)) { _priceTemp = booking.PricePerNight; } _priceDay = dayNumber; } var pastDay = _pastDays.Reverse().ElementAt(dayNumber-1); pastDay.Stats += booking.LengthOfStay; } } public double[] Calculate(double[] forecast, double[] price) { _price = price; double total=0.0; int length = 8; double percent=0.35; var values=_pastDays.Reverse().Where(c=>c.Value).ToList(); if (((double)values.Take(length).Count(c => c.Stats > 0) / length) < percent) { length=15; if(((double)values.Take(length).Count(c=>c.Stats>0)/length)<percent) length=30; } for(int i=0;i<length;i++) total+=values.ElementAt(i).Stats*(length-i); var value = 2 * total / (length * (length + 1)); //var total = _pastDays.Reverse()..Sum(ps => ps.Value ? ps.Stats : 0); //var value = (double)total / _count; //double dif = 0; for (var i = 0; i < _futureDays.Count() && i < 90; ++i) { if (_futureDays[i]) { forecast[i] = value; price[i] = _priceTemp; // + dif; // dif = forecast[i] - (int)forecast[i]; // forecast[i] = (int)forecast[i]; } } _forecast = forecast; _price = price; return _price; } public double[] GetForecast() { return _forecast; } public double[] GetPrice() { return _price; } } }
b4fb43ee6193a303f2f004ad5519e61ca870d5a0
C#
azturner/Rock
/Rock.Slingshot.Model/PhoneNumberImport.cs
2.765625
3
namespace Rock.Slingshot.Model { /// <summary> /// /// </summary> [System.Diagnostics.DebuggerDisplay( "{Number}" )] public class PhoneNumberImport { /// <summary> /// Gets or sets the phone number. The number is stored without any string formatting. (i.e. (502) 555-1212 will be stored as 5025551212). This property is required. /// </summary> /// <value> /// A <see cref="System.String"/> representing the phone number without string formatting. /// </value> public string Number { get; set; } /// <summary> /// Gets or sets the extension (if any) that would need to be dialed to contact the owner. /// </summary> /// <value> /// A <see cref="System.String"/> representing the extensions that would need to be dialed to contact the owner. If no extension is required, this property will be null. /// </value> public string Extension { get; set; } /// <summary> /// Gets the Phone Number's Number Type Id. /// </summary> /// <value> /// A <see cref="System.Int32"/> representing the Number Type Id. If unknown, this value will be null. /// </value> public int? NumberTypeValueId { get; set; } /// <summary> /// Gets or sets a flag indicating whether the number has been opted in for SMS /// </summary> /// <value> /// A <see cref="System.Boolean"/> value that is <c>true</c> if the phone number has opted in for SMS messaging; otherwise <c>false</c>. /// </value> public bool IsMessagingEnabled { get; set; } /// <summary> /// Gets or sets a flag indicating whether the PhoneNumber is unlisted or not. /// </summary> /// <value> /// A <see cref="System.Boolean"/> value that is <c>true</c> if the PhoneNumber is unlisted; otherwise <c>false</c>. /// </value> public bool IsUnlisted { get; set; } } }
c331bf5392d4bfe84a8b1a88fe0805e4a10626d5
C#
zackimball/BulletJournalApp
/BulletData/BulletRecords/Note.cs
2.578125
3
using System; namespace BulletRecords { public class Note : iNote { public string RecordId { get; set; } public NoteType NoteType { get; set; } public string NoteBody { get; set; } public DateTime? CompleteDate { get; set; } public DateTime? DueDate { get; set; } public Note(NoteType requestedType = NoteType.Default) { RecordId = new Guid().ToString(); NoteType = requestedType; NoteBody = ""; } } }
6e7435b0ce4668720fdcdf50004a68255347e348
C#
samhuang/Sparkline.Net
/SparkLib/Spark.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; using SparkNet.TickProviders; namespace SparkNet { public class Spark { private static ITickProvider _tickProvider; public static ITickProvider TickProvider { get { return _tickProvider ?? (_tickProvider = DefaultTickProvider); } set { if (value == null) throw new ArgumentNullException(); _tickProvider = value; } } internal static ITickProvider DefaultTickProvider { get { return new MsGothicTickProvider(); } } public static string Render(params double[] numbers) { return Render(data: numbers); } /// <summary> /// Convert numbers to spark chart strings. /// </summary> /// <param name="data">List or Array of numbers</param> /// <returns>empty string if <paramref name="data"/>is <code>null</code> or empty.</returns> public static string Render(IList<double> data) { var ticks = TickProvider.Ticks; if (data == null || data.Count == 0) return string.Empty; char[] res = new char[data.Count()]; double min = data.Min(); double max = data.Max(); double step = (max - min) / (ticks.Length - 1); if (step.Equals(0d)) step = 1; for (var i = 0; i < data.Count(); i++) { var val = data[i]; double d = (val - min)/step; // if it's 10^-10 close to its rounded, round; floor otherwise int tick = (int) ((Math.Abs(Math.Round(d) - d) < 1e-10) ? Math.Round(d) : Math.Floor((val - min) / step)); res[i] = ticks[tick]; } return TickProvider.Assemble(res); } } }
8cfbcb513ae6c4be6321d3ba6f5ebde9db9a53fe
C#
MrWT/WinoneCenter
/WinoneCenter/Controllers/EmployeeController.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using WinoneCenter.Services; using WinoneCenter.Models; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace WinoneCenter.Controllers { [Route("api/[controller]")] public class EmployeeController : Controller { private readonly EmployeeService _employeeService; public EmployeeController(EmployeeService employeeService) { _employeeService = employeeService; } /// <summary> /// Get All Employee Data /// </summary> /// <returns></returns> [HttpGet] public IActionResult GetAll() { return Ok(new { code = "0000", msg = "", obj = _employeeService.GetAll() }); } /// <summary> /// Get One Employee Data by Name /// </summary> /// <param name="name"></param> /// <returns></returns> [HttpGet("{name}")] public IActionResult GetOneByName(string name) { return Ok(new { code = "0000", msg = "", obj = _employeeService.GetOneByName(name) }); } /// <summary> /// Get One Employee Data by ObjectId /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet("{id}")] public IActionResult GetOneById(string id) { return Ok(new { code = "0000", msg = "", obj = _employeeService.GetOneById(id) }); } /// <summary> /// Post One Employee Data /// </summary> /// <param name="employee"></param> /// <returns></returns> [HttpPost] public IActionResult Post(Employee employee) { try { _employeeService.InsertOne(employee); return Ok(new { code = "0000", msg = "" }); } catch (Exception ex) { return BadRequest(new { code = ex.GetHashCode().ToString(), msg = ex.ToString() }); } } /// <summary> /// Put One Employee Data /// </summary> /// <param name="employee"></param> /// <returns></returns> [HttpPut] public IActionResult Put(Employee employee) { try { _employeeService.UpdateOne(employee); return Ok(new { code = "0000", msg = "" }); } catch (Exception ex) { return BadRequest(new { code = ex.GetHashCode().ToString(), msg = ex.ToString() }); } } } }
c88d3f4cfc8213ca0333bc5d0a18699ae359e480
C#
meshudn/Software-Service-Engineering
/metadataclient/6/Task1-Template/TcpRequest.cs
3.0625
3
using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace SSE { public class TcpRequest { private TcpRequest() {} public static async Task<string> Do(IPAddress ip, int port, string message) { var client = new TcpClient(ip.AddressFamily); await client.ConnectAsync(ip, port); using (var r = new StreamReader(client.GetStream(), Encoding.ASCII)) using (var w = new StreamWriter(client.GetStream(), Encoding.ASCII)) { await w.WriteAsync(message); w.Flush(); return await r.ReadToEndAsync(); } } } }
4eb733d259978c738ae744033838e6f2e02bf60f
C#
dallmeyer/lc
/ValidateBinarySearchTree/ValidateBinarySearchTree.cs
3.359375
3
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { private class Output { public int min; public int max; public bool isValidBst; } public bool IsValidBST(TreeNode root) { if (root == null) return true; Output x = Helper(root); return x.isValidBst; } private Output Helper(TreeNode root) { if (root == null || root.val == null) { return null; } Output node = new Output(); node.min = root.val; node.max = root.val; node.isValidBst = true; Output left = Helper(root.left); Output right = Helper(root.right); if (left != null) { node.isValidBst = node.isValidBst && left.isValidBst; if (left.max >= root.val) { node.isValidBst = false; } node.min = left.min; //if left.min >= root.val, isValidBst will already be false so no need to worry about min/max } if (right != null) { node.isValidBst = node.isValidBst && right.isValidBst; if (right.min <= root.val) { node.isValidBst = false; } node.max = right.max; //if right.max <= root.val, isValidBst will already be false so no need to worry about min/max } return node; } }
64ac46f487a69a592d418093a7b15e566863fce9
C#
mertbilgic/dotnetcore
/CourseApp/Controllers/CourseController.cs
2.78125
3
using System.Collections.Generic; using System.Linq; using CourseApp.Models; using CourseApp.ViewModels; using Microsoft.AspNetCore.Mvc; namespace CourseApp.Controllers { //localhost:5000/course public class CourseController:Controller { public ActionResult TestList(){ var list = new List<Listcs>() { new Listcs(){Name="Kategori 1"}, new Listcs(){Name="Kategori 2"}, new Listcs(){Name="Kategori 3"} }; var products = new List<Product>(){ new Product(){Name ="Product 1"}, new Product(){Name ="Product 2"}, new Product(){Name ="Product 3"} }; ProductsListViewModel model = new ProductsListViewModel(); model.Products=products; model.Lists=list; return View(model); } public ActionResult TestIndex(){ var kurs = new Course(){Id=1,Name="Komple Uygulamalı Web Geliştirme Kursu"}; var ogrenciler = new List<StudentData>(){ new StudentData(){name = "Ali"}, new StudentData(){name = "Termos"}, new StudentData(){name = "Ali"}, new StudentData(){name = "Termos"} }; var viewmodel = new CourseStudentsViewModel(); viewmodel.Course=kurs; viewmodel.Students=ogrenciler; return View(viewmodel); } public ActionResult ByReleased(int year,int month){ return Content("year : "+year+" month : "+month); } public ActionResult CourseList(int? pageindex ,string sortby){ if(!pageindex.HasValue) pageindex=1; if(string.IsNullOrWhiteSpace(sortby)) sortby ="name"; return Content("pageindex = "+pageindex+" sort by = "+sortby); } //localhost:5000/course/index public IActionResult Index(){ return View(); } [HttpGet] //localhost:5000/course/apply method: Get public IActionResult Apply() { return View(); } [HttpPost] //localhost:5000/course/apply methot: Post public IActionResult Apply(Student student) { if( ModelState.IsValid==true){ Repository.AddStudent(student); return View("Thanks",student); } else{ return View(student); } } public IActionResult testID(int id){ return Content("id="+id); } public IActionResult Details(){ var course = new Course(); course.Name =".NetCore"; course.description="C#"; course.isPublished= true; return View(course); } //localhost:5000/course/list public IActionResult List(){ var student =Repository.Students.Where(i=>i.Confirm==true); return View(student); } } }
b77869b2d266a7f117278b3e529641aae9d25c93
C#
doongjohn/Tower_Of_Ukani
/Assets/Devs/Yuchan/System/Random/ARandom.cs
2.9375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ARandom { public static int Dir => Random.Range(0,2) == 0 ? -1 : 1; public static Vector2 Dir2d => Random.insideUnitCircle; //0~100 %d의 확률로 True False를 반환. public static bool Get(int chance) => Random.Range(0, 100) <= chance ? true : false; public static bool Get(float chance) => Random.Range(0f, 100f) <= chance ? true : false; }
2287b7e1791a24188fb93f6f4ee6ff363bc9ed61
C#
hillaryneaves/Participations
/Classes3/Classes3/SecondWindow.xaml.cs
2.625
3
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Classes3 { /// <summary> /// Interaction logic for SecondWindow.xaml /// </summary> public partial class SecondWindow : Window { public SecondWindow() { InitializeComponent(); } public string FirstName { get; set; } public string LastName { get; set; } public Address Address { get; set; } public override string ToString() { return $"{FirstName} {LastName} " + $"\r{Address}"; } } }
c40eae24506edb8d2fbc16945c27f34f5176737b
C#
jkastner/JK_RecordSystemTest_4-18-2021
/RecordsLib/ClassLibrary1/RecordSet.cs
3.203125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RecordsLib { public interface IRecordSet { IEnumerable<IRecord> ByGender(); IEnumerable<IRecord> ByBirthDate(); IEnumerable<IRecord> ByLastName(); IReadOnlyList<IRecord> Data { get; } } public abstract class BaseRecordSet : IRecordSet { public List<IRecord> data = new List<IRecord>(); public IReadOnlyList<IRecord> Data => data; public abstract void InitializeRecords(); public IEnumerable<IRecord> ByGender() { return Data.OrderBy(x => x.Gender). ThenBy(x=>x.LastName); } public IEnumerable<IRecord> ByBirthDate() { return Data.OrderBy(x => x.DateOfBirth); } public IEnumerable<IRecord> ByLastName() { return Data.OrderByDescending(x => x.LastName); } public void AddRecords(IEnumerable<IRecord> records) { this.data.AddRange(records); } } }
3694991e9890265ab244d9056f6dc65ef310705b
C#
AndrewFakher/BookGeeks
/Book Store/Book Store/Details.cs
2.703125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Book_Store { public partial class Details : Form { string pname; string N; string A; string abc; public Details() { InitializeComponent(); } public Details(string sname) { pname = sname; InitializeComponent(); } public Details(string name, string auth, string price) { InitializeComponent(); N = name; A= auth; abc= price; label1.Text = N; label2.Text = A; label3.Text = abc; } private void pictureBox5_Click(object sender, EventArgs e) { this.Hide(); } private void pictureBox4_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } private void pictureBox1_Click(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { MessageBox.Show("Item added to your wishlist"); } private void button1_Click(object sender, EventArgs e) { if (MessageBox.Show("Item added to cart, Checkout now? ", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { checkout C = new checkout(abc); C.Show(); this.Hide(); } else { MessageBox.Show("your item was added to your cart"); } } private void label1_Click(object sender, EventArgs e) { } private void BookName_Click(object sender, EventArgs e) { } private void Author_Click(object sender, EventArgs e) { } private void Price_Click(object sender, EventArgs e) { } private void label1_Click_1(object sender, EventArgs e) { } private void Details_Load(object sender, EventArgs e) { } } }
31700e3b6ac4343741b79b641e261ffe019e263d
C#
zoujingjing/Homework
/homework2/Shape.cs
3.203125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; /*********************************一个类定义的时候**************************************/ //无或internal: 只能在当前项目中访问该类 //public:可以在任何地方访问该类 //private:不能在任何地方访问该类 //abstract或internal abstract:类只能在当前项目中访问,不能实例化,只能供继承之用 //public abstract: 类可以在任何地方访问,不能实例化,只能供继承之用 //sealed 或internal sealed:类只能在当前项目中访问,不能供继承之用,只能实例化 //public sealed 类可以在任何地方访问,不能供继承之用,只能实例化 /*********************************一个类定义的时候**************************************/ //该类是所有二维图形的基类,定义为抽象类,表明不能被实例化 public abstract class Shape:Object { public int color; //构造函数默认状态,这个函数默认就有,可以不用写出来 public Shape() { } //虚方法:这样做的好处是无论将派生类做何种类型隐式转换,都将调用派生类自己的方法。 //派生类可以通过override重写这个虚方法 public override string ToString(){ return null;}//重写了Object类的ToString()方法 public virtual double Area() { return 0; }//求面积 public virtual double Perimeter() { return 0; }//求周长 public virtual double Volume() { return 0; }//求体积 //求圆周长,注意,这里没有用到虚方法,是为了用另一种多态方式“覆盖”来实现 public double Diameter() { return 0; } ~Shape() { }//析构函数 }
7cf2803879520373c8e412eea824b44ba507bc24
C#
rafalrojek/BankProject
/Bank.Domain/Concrete/BankAccountIdentityDbContext.cs
2.53125
3
using System.Data.Entity; using Microsoft.AspNet.Identity.EntityFramework; using Bank.Domain.Entities; namespace Bank.Domain.Concrete { public class BankAccountIdentityDbContext: IdentityDbContext<BankAccount> { public BankAccountIdentityDbContext() : base("BankDb") { } static BankAccountIdentityDbContext() { Database.SetInitializer(new BankDbInit()); } public static BankAccountIdentityDbContext Create() { return new BankAccountIdentityDbContext(); } } public class BankDbInit : DropCreateDatabaseIfModelChanges<BankAccountIdentityDbContext> { protected override void Seed(BankAccountIdentityDbContext context) { PerformInitalSetup(context); base.Seed(context); } public void PerformInitalSetup(BankAccountIdentityDbContext context) { } } }
f689e20136cbfe0da30f08ba47b1e5d92e796bcf
C#
chrishanzlik/ZPLForge
/src/ZPLForge/Contracts/IQrCode.cs
2.609375
3
using ZPLForge.Common; namespace ZPLForge.Contracts { /// <summary> /// QR Code contract /// </summary> public interface IQrCode : ILabelContent { /// <summary> /// Gets or sets the qr code content. /// </summary> string Content { get; set; } /// <summary> /// QR Code Model 1 is the original specification, while QR Code Model 2 is an /// enhanced form of the symbology. Model 2 provides additional features and can /// be automatically differentiated from Model 1. /// </summary> QrModel QrModel { get; set; } /// <summary> /// Gets or sets the magnification factor which determines how big the QR Code /// is printed on your label. /// </summary> Magnification MagnificationFactor { get; set; } /// <summary> /// Gets or sets the reliability level of the QR Code /// </summary> ErrorCorrection ErrorCorrection { get; set; } /// <summary> /// Gets or sets the mask value. Allowed values are from 0 to 7. /// </summary> int MaskValue { get; set; } } }
11901aac53a2a606751928d6fcaebc6a988696bc
C#
SergioPonomarev/XT-2018Q4
/Epam.Task3/Epam.Task3.MyString/MyString.cs
3.703125
4
using System; using System.Text; namespace Epam.Task3.MyString { public class MyString : IEquatable<MyString>, IComparable<MyString>, IComparable { public static readonly string Empty = string.Empty; private char[] chars; public MyString(char[] value) { this.chars = value; this.Length = value.Length; } public MyString(char[] value, int startIndex, int length) { if (value == null) { throw new ArgumentNullException("Value collection is null."); } if (((startIndex + length) > value.Length) || (startIndex < 0) || (length < 0)) { throw new ArgumentOutOfRangeException("Index is out of range. Start index and length must be greater than or equal to zero. The sum of start index and length must be less than or equal to elements in value collection."); } this.chars = new char[length]; for (int i = 0; i < length; i++) { this.chars[i] = value[startIndex + i]; } this.Length = length; } public MyString(char ch, int count) { if (count < 0) { throw new ArgumentOutOfRangeException("Count must be greater than or equal to zero.", nameof(count)); } this.chars = new char[count]; for (int i = 0; i < count; i++) { this.chars[i] = ch; } this.Length = count; } private MyString() { this.chars = new char[0]; this.Length = 0; } private MyString(int length) { this.chars = new char[length]; this.Length = length; } private MyString(string str) { this.chars = str.ToCharArray(); this.Length = str.Length; } public int Length { get; } public char this[int index] { get { if (index >= this.Length || index < 0) { throw new IndexOutOfRangeException("Index is out of range. "); } return this.chars[index]; } } public static implicit operator string(MyString value) { return value.ToString(); } public static implicit operator StringBuilder(MyString value) { StringBuilder sb = new StringBuilder(value.ToString()); return sb; } public static implicit operator MyString(string str) { MyString myString = new MyString(str); return myString; } public static implicit operator MyString(StringBuilder sb) { MyString myString = new MyString(sb.ToString()); return myString; } public static bool operator ==(MyString lhs, MyString rhs) { if (object.ReferenceEquals(lhs, null)) { if (object.ReferenceEquals(rhs, null)) { return true; } return false; } return lhs.Equals(rhs); } public static bool operator !=(MyString lhs, MyString rhs) { return !(lhs == rhs); } public static MyString Concat(object o1) { MyString myString; if (o1 == null) { return myString = new MyString(); } string result = o1.ToString(); myString = new MyString(result); return myString; } public static MyString Concat(object o1, object o2) { MyString myString; if (o1 == null && o2 == null) { return myString = new MyString(); } if (o1 == null) { return myString = MyString.Concat(o2); } if (o2 == null) { return myString = MyString.Concat(o1); } string result = o1.ToString() + o2.ToString(); myString = new MyString(result); return myString; } public static MyString Concat(object o1, object o2, object o3) { MyString myString; if (o1 == null && o2 == null && o3 == null) { return myString = new MyString(); } if (o1 == null && o2 == null) { return myString = MyString.Concat(o3); } if (o1 == null && o3 == null) { return myString = MyString.Concat(o2); } if (o2 == null && o3 == null) { return myString = MyString.Concat(o1); } if (o1 == null) { return myString = MyString.Concat(o2, o3); } if (o2 == null) { return myString = MyString.Concat(o1, o3); } if (o3 == null) { return myString = MyString.Concat(o1, o2); } string result = o1.ToString() + o2.ToString() + o3.ToString(); myString = new MyString(result); return myString; } public static MyString Concat(params object[] args) { if (args == null) { throw new ArgumentNullException("Collection of elements is null."); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < args.Length; i++) { sb.Append(args[i].ToString()); } string result = sb.ToString(); MyString myString = new MyString(result); return myString; } public static MyString Concat(MyString ms1, MyString ms2) { MyString myString; if (ms1 == null && ms2 == null) { return myString = new MyString(); } if (ms1 == null) { return myString = ms2; } if (ms2 == null) { return myString = ms1; } string result = ms1.ToString() + ms2.ToString(); myString = new MyString(result); return myString; } public static MyString Concat(MyString ms1, MyString ms2, MyString ms3) { MyString myString; if (ms1 == null && ms2 == null && ms3 == null) { return myString = new MyString(); } if (ms1 == null && ms2 == null) { return myString = ms3; } if (ms1 == null && ms3 == null) { return myString = ms2; } if (ms2 == null && ms3 == null) { return myString = ms1; } if (ms1 == null) { myString = MyString.Concat(ms2, ms3); } if (ms2 == null) { myString = MyString.Concat(ms1, ms3); } if (ms3 == null) { myString = MyString.Concat(ms1, ms2); } string result = ms1.ToString() + ms2.ToString() + ms3.ToString(); myString = new MyString(result); return myString; } public static MyString Concat(params MyString[] args) { if (args == null) { throw new ArgumentNullException("Collection of elements is null."); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < args.Length; i++) { sb.Append(args[i].ToString()); } string result = sb.ToString(); MyString myString = new MyString(result); return myString; } public static MyString Copy(MyString value) { if (value == null) { throw new ArgumentNullException("Value is null."); } string result = value.ToString(); return new MyString(result); } public bool Contains(MyString value) { if (value == null) { throw new ArgumentNullException("Value is null."); } bool check = false; for (int i = 0; i <= this.Length - value.Length; i++) { if (this[i] == value[0]) { int index = i; int j; for (j = 0; j < value.Length; j++) { if (this[index] != value[j]) { break; } index++; } if (j == value.Length) { check = true; break; } } } return check; } public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) { throw new ArgumentNullException("Destination array is null."); } if (sourceIndex < 0 || destinationIndex < 0 || count < 0 || sourceIndex > this.Length - 1 || destinationIndex > destination.Length - 1 || count + sourceIndex > this.Length || count + destinationIndex > destination.Length) { throw new ArgumentOutOfRangeException("Index is out of range."); } for (int i = 0; i < count; i++) { destination[destinationIndex + i] = this[sourceIndex + i]; } } public bool EndsWith(MyString value) { if (value == null) { throw new ArgumentNullException("Value is null."); } for (int i = this.Length - 1, j = value.Length - 1; j >= 0; i--, j--) { if (this[i] != value[j]) { return false; } } return true; } public int IndexOf(char ch) { return this.IndexOf(ch, 0); } public int IndexOf(char ch, int startIndex) { return this.IndexOf(ch, startIndex, this.Length - startIndex); } public int IndexOf(char ch, int startIndex, int count) { if (startIndex < 0 || count < 0 || startIndex >= this.Length || startIndex + count > this.Length) { throw new ArgumentOutOfRangeException("Index is out of range."); } for (int i = startIndex; i < count; i++) { if (this[i] == ch) { return i; } } return -1; } public int IndexOf(MyString value) { return this.IndexOf(value, 0); } public int IndexOf(MyString value, int startIndex) { return this.IndexOf(value, startIndex, this.Length - startIndex); } public int IndexOf(MyString value, int startIndex, int count) { if (value == null) { throw new ArgumentNullException("Value is null."); } if (startIndex < 0 || count < 0 || startIndex >= this.Length || startIndex + count > this.Length) { throw new ArgumentOutOfRangeException("Index is out of range."); } bool check = false; int i; int internalCount = count; for (i = startIndex; i <= this.Length - value.Length && internalCount >= 0; i++, internalCount--) { if (this[i] == value[0]) { int index = i; int j; for (j = 0; j < internalCount && j < value.Length; j++) { if (this[index] != value[j]) { break; } index++; } if (j == value.Length) { check = true; break; } } } if (check) { return i; } else { return -1; } } public int IndexOfAny(char[] anyOf) { return this.IndexOfAny(anyOf, 0); } public int IndexOfAny(char[] anyOf, int startIndex) { return this.IndexOfAny(anyOf, startIndex, this.Length - startIndex); } public int IndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) { throw new ArgumentNullException("Array is null."); } if (startIndex < 0 || count < 0 || startIndex >= this.Length || startIndex + count > this.Length) { throw new ArgumentOutOfRangeException("Index is out of range."); } int i; for (i = startIndex; i < count + startIndex; i++) { for (int j = 0; j < anyOf.Length; j++) { if (this[i] == anyOf[j]) { return i; } } } return -1; } public MyString Insert(int startIndex, MyString value) { if (value == null) { throw new ArgumentNullException("Value is null."); } if (startIndex < 0 || startIndex > this.Length) { throw new ArgumentOutOfRangeException("Index is out of range."); } MyString myString = new MyString(this.Length + value.Length); int i = 0; int j = 0; int k = 0; while (i < myString.Length) { if (i == startIndex) { while (j < value.Length) { myString.chars[i] = value[j]; i++; j++; } } if (i != startIndex) { while (k < this.Length) { myString.chars[i] = this[k]; i++; k++; if (i == startIndex) { break; } } } } return myString; } public int LastIndexOf(char ch) { return this.LastIndexOf(ch, this.Length - 1); } public int LastIndexOf(char ch, int startIndex) { return this.LastIndexOf(ch, startIndex, this.Length - startIndex); } public int LastIndexOf(char ch, int startIndex, int count) { if (startIndex < 0 || count < 0 || startIndex >= this.Length || startIndex - count + 1 < 0) { throw new ArgumentOutOfRangeException("Index is out of range."); } for (int i = startIndex; i > startIndex - count; i--) { if (this[i] == ch) { return i; } } return -1; } public int LastIndexOf(MyString value) { return this.LastIndexOf(value, this.Length - 1); } public int LastIndexOf(MyString value, int startIndex) { return this.LastIndexOf(value, startIndex, startIndex + 1); } public int LastIndexOf(MyString value, int startIndex, int count) { if (value == null) { throw new ArgumentNullException("Value is null."); } if (startIndex < 0 || count < 0 || startIndex >= this.Length || startIndex - count + 1 < 0) { throw new ArgumentOutOfRangeException("Index is out of range."); } int i; int internalCount = count; for (i = startIndex; internalCount >= 0 && i >= 0; i--, internalCount--) { if (this[i] == value[value.Length - 1]) { int index = i; int j; for (j = value.Length - 1; j >= 0 && value.Length <= internalCount; j--) { if (this[index] != value[j]) { break; } index--; } if (j == -1) { return index + 1; } } } return -1; } public int LastIndexOfAny(char[] anyOf) { return this.LastIndexOfAny(anyOf, this.Length - 1); } public int LastIndexOfAny(char[] anyOf, int startIndex) { return this.LastIndexOfAny(anyOf, startIndex, startIndex + 1); } public int LastIndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) { throw new ArgumentNullException("Array is null."); } if (startIndex < 0 || count < 0 || startIndex >= this.Length || startIndex - count + 1 < 0) { throw new ArgumentOutOfRangeException("Index is out of range."); } int i; for (i = startIndex; i >= 0; i--) { for (int j = 0; j < anyOf.Length; j++) { if (this[i] == anyOf[j]) { return i; } } } return -1; } public MyString Remove(int startIndex) { return this.Remove(startIndex, this.Length - startIndex); } public MyString Remove(int startIndex, int count) { if (startIndex < 0 || count < 0 || startIndex + count > this.Length) { throw new ArgumentOutOfRangeException("Index is out of range."); } MyString myString = new MyString(this.Length - count); for (int i = 0, j = 0; j < myString.Length; i++, j++) { if (i == startIndex) { i += count; } myString.chars[j] = this[i]; } return myString; } public MyString Replace(char oldChar, char newChar) { MyString myString = new MyString(this.Length); for (int i = 0; i < this.Length; i++) { if (this[i] == oldChar) { myString.chars[i] = newChar; } else { myString.chars[i] = this[i]; } } return myString; } public MyString Replace(MyString oldValue, MyString newValue) { if (newValue == null) { throw new ArgumentNullException("Value is null."); } if (oldValue == MyString.Empty) { throw new ArgumentException("The value to change mustn't have zero length."); } int indexOldValue = this.IndexOf(oldValue); if (indexOldValue == -1) { return this; } char[] temp = this.ToCharArray(); MyString myString = new MyString(temp); while (indexOldValue != -1) { myString = myString.Remove(indexOldValue, oldValue.Length); myString = myString.Insert(indexOldValue, newValue); indexOldValue = myString.IndexOf(oldValue); } return myString; } public bool StartsWith(MyString value) { if (value == null) { throw new ArgumentNullException("Value is null."); } for (int i = 0, j = 0; j < value.Length; i++, j++) { if (this[i] != value[j]) { return false; } } return true; } public MyString SubMyString(int startIndex) { return this.SubMyString(startIndex, this.Length - startIndex); } public MyString SubMyString(int startIndex, int length) { if (startIndex + length > this.Length || startIndex < 0 || length < 0) { throw new ArgumentOutOfRangeException("Index is out of range."); } MyString myString = new MyString(length); for (int i = startIndex, j = 0; j < myString.Length; i++, j++) { myString.chars[j] = this[i]; } return myString; } public string ToLower() { MyString myString = new MyString(this.Length); for (int i = 0; i < this.Length; i++) { myString.chars[i] = char.ToLower(this[i]); } return myString; } public string ToUpper() { MyString myString = new MyString(this.Length); for (int i = 0; i < this.Length; i++) { myString.chars[i] = char.ToUpper(this[i]); } return myString; } public char[] ToCharArray() { char[] temp = new char[this.Length]; for (int i = 0; i < temp.Length; i++) { temp[i] = this[i]; } return temp; } public override string ToString() { StringBuilder sb = new StringBuilder(this.Length); string result; for (int i = 0; i < this.Length; i++) { sb.Append(this[i]); } return result = sb.ToString(); } public override bool Equals(object value) { string temp = value as string; if (temp == null) { throw new ArgumentNullException("Value is null or not supported type."); } return this.Equals(temp); } public bool Equals(MyString value) { if (object.ReferenceEquals(value, null)) { return false; } if (object.ReferenceEquals(this, value)) { return true; } if (this.GetType() != value.GetType()) { return false; } if (this.Length != value.Length) { return false; } for (int i = 0; i < this.Length; i++) { if (this[i] != value[i]) { return false; } } return true; } public override int GetHashCode() { int num = 5381; int num2 = num; for (int i = 0; i < this.Length; i += 2) { num = ((num << 5) + num) ^ this[i]; if (i + 1 == this.Length) { break; } num2 = ((num2 << 5) + num2) ^ this[i + 1]; } return num + (num2 * 1566083941); } public int CompareTo(object value) { string temp = value as string; if (temp == null) { throw new ArgumentNullException("Value is null or not supported type."); } return this.CompareTo(temp); } public int CompareTo(MyString value) { int min = this.Length < value.Length ? this.Length : value.Length; for (int i = 0; i < min; i++) { if (char.ToUpper(this[i]) < char.ToUpper(value[i])) { return -1; } if (char.ToUpper(this[i]) > char.ToUpper(value[i])) { return 1; } } if (this.Length < value.Length) { return -1; } if (this.Length > value.Length) { return 1; } if (char.IsLower(this[0]) && char.IsLower(value[0])) { return 0; } if (char.IsLower(this[0])) { return -1; } if (char.IsLower(value[0])) { return 1; } return 0; } } }
e35ba146e69d244d200d627acfaf412d582a8ec6
C#
SytseOegema/MoodCap
/functions/MoodCap/ListImages.cs
2.5625
3
using Google.Cloud.Functions.Framework; using Google.Cloud.Storage.V1; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading.Tasks; namespace MoodCap { public class ListImages : IHttpFunction { private readonly ILogger _logger; private StorageClient _storage; public ListImages(ILogger<ListImages> logger) { _logger = logger; _storage = StorageClient.Create(); } public async Task HandleAsync(HttpContext context) { HttpResponse response = context.Response; HttpRequest request = context.Request; if (request.Method != "GET") { response.StatusCode = (int) HttpStatusCode.MethodNotAllowed; return; } var storageObjects = _storage.ListObjects("moodcap"); string output = ""; foreach(var storageObject in storageObjects) { output += storageObject.Name; } response.StatusCode = 200; await response.WriteAsync(output); return; } } }
2e0f3064c379b5fda5c61135783338405f7c7410
C#
kimduquan/xproject
/XCS/XOutput.cs
3.140625
3
using System.Collections.Generic; namespace XCS { public abstract class XOutput { public string XFirst { protected get; set; } protected Dictionary<string, string> XStrings { get; set; } public XOutput() { XFirst = ""; XStrings = new Dictionary<string, string>(); } public abstract bool XWriteStrings(List<string> strings); public virtual bool XWrite() { bool bRes = false; List<string> strings = new List<string>(); strings.Add(XFirst); foreach(KeyValuePair<string, string> pair in XStrings) { strings.Add(pair.Key); strings.Add(pair.Value); } bRes = XWriteStrings(strings); return bRes; } public void XWrite(string name, string value) { XStrings[name] = value; } public abstract bool XClose(); } }
b62d377bc3d52cd2dfe4e02437ca98a207b1f453
C#
DanWahlin/CSCourseCode
/Samples/CSProgramming/BaseClassLibrary/Threading/AsynchronousDelegates/UsingAThread.cs
2.578125
3
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Threading; namespace ThreadsAndDelegates { /// <summary> /// Summary description for Form1. /// </summary> public class UsingAThread : System.Windows.Forms.Form { private System.Windows.Forms.Button btnStart; private System.Windows.Forms.ProgressBar pbStatus; private System.Windows.Forms.Label lblOutput; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public UsingAThread() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pbStatus = new System.Windows.Forms.ProgressBar(); this.btnStart = new System.Windows.Forms.Button(); this.lblOutput = new System.Windows.Forms.Label(); this.SuspendLayout(); // // pbStatus // this.pbStatus.Location = new System.Drawing.Point(16, 128); this.pbStatus.Name = "pbStatus"; this.pbStatus.Size = new System.Drawing.Size(264, 23); this.pbStatus.TabIndex = 0; // // btnStart // this.btnStart.Location = new System.Drawing.Point(16, 48); this.btnStart.Name = "btnStart"; this.btnStart.TabIndex = 1; this.btnStart.Text = "Start"; this.btnStart.Click += new System.EventHandler(this.btnStart_Click); // // lblOutput // this.lblOutput.Location = new System.Drawing.Point(168, 48); this.lblOutput.Name = "lblOutput"; this.lblOutput.TabIndex = 2; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(296, 166); this.Controls.Add(this.lblOutput); this.Controls.Add(this.btnStart); this.Controls.Add(this.pbStatus); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new UsingAThread()); } int _max; private void btnStart_Click(object sender, System.EventArgs e) { _max = 100; Thread t = new Thread(new System.Threading.ThreadStart(StartProcess)); t.Start(); MessageBox.Show("Done with operation!!"); } delegate void StartProcessHandler(); private void StartProcess() { if (this.pbStatus.InvokeRequired) { StartProcessHandler sph = new StartProcessHandler(StartProcess); this.Invoke(sph); } else { this.Refresh(); this.pbStatus.Maximum = _max; for (int i = 0; i <= _max; i++) { Thread.Sleep(10); this.lblOutput.Text = i.ToString(); this.pbStatus.Value = i; } } } } }
a1652a6838a32746952e5034cb956139c2111521
C#
kennetms/Scripts
/ReviewPanelManager.cs
3.140625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /// <summary> /// Class that handles keeping track of and displaying the review panel. /// </summary> public class ReviewPanelManager : MonoBehaviour { /// <summary> /// our array of objects that makes up the review panel /// </summary> private List<GameObject> reviewPanel; //GameObject for our review panel canvas display public GameObject m_ReviewPanelCanvas; /// <summary> /// the textbox that will display our object's review information /// </summary> public Text m_reviewPanelText; //the position in the review panel array of the object we are currently displaying private int m_currentReviewPos; //the GameObject being displayed on the review panel currently. private GameObject m_currentlyDisplayed; /// <summary> /// Used for initialization /// </summary> void Start() { m_ReviewPanelCanvas.SetActive(false); reviewPanel = new List<GameObject>(); enabled = false; } /// <summary> /// Add a GameObject to the review panel /// </summary> /// <param name="obj">The object to add to the review panel</param> public void AddReviewPanelObject(GameObject obj) { reviewPanel.Add(obj); } /// <summary> /// Load the review panel /// </summary> public void LoadReviewPanel() { //initialize the review panel InitializeReviewPanel(); //set our review panel canvas to active m_ReviewPanelCanvas.SetActive(true); enabled = true; } /// <summary> /// Initializes the review panel by initalizing the displaying of objects and information, /// starting with the first object added to the review panel. /// </summary> private void InitializeReviewPanel() { //we need a check for the situation where we have no review panel objects if (reviewPanel.Count == 0) { m_reviewPanelText.text = "No Review Panel Objects!"; return; } //initialize the position in the review panel array of our first object to display m_currentReviewPos = 0; //display the first object DisplayReviewPanelObject(m_currentReviewPos); } /// <summary> /// Displays the review panel object in the review panel array at index index. /// </summary> /// <param name="index">the index of the object in the review panel to display</param> private void DisplayReviewPanelObject(int index) { //if we're already displaying something, move it out of camera view if(m_currentlyDisplayed != null) m_currentlyDisplayed.transform.position = new Vector3(0, 0, 0); //the GameObject we're displaying m_currentlyDisplayed = reviewPanel[index]; /** Collider objColl = m_currentlyDisplayed.GetComponent<Collider>(); if (objColl != null) objColl.enabled = false;*/ //we are getting the object's information from the review panel ReviewInformation reviewInfo = m_currentlyDisplayed.GetComponent<ReviewInformation>(); //if we have no review info, we default to display text that this is an innocuous item. if (reviewInfo == null) { m_reviewPanelText.text = m_currentlyDisplayed.name + " is an innocuous object; it is neither a hazard nor a safety."; return; } //displaying our review info for the object m_reviewPanelText.text = reviewInfo.ReviewInfo; } void Update() { if (m_currentlyDisplayed != null) //display our object's image/move it infront of the camera DisplayRotation.RotateView(m_currentlyDisplayed); } /// <summary> /// going to the next object in the review panel /// </summary> public void NextReviewObject() { //looping to first object if we're currently displaying the last if (m_currentReviewPos < reviewPanel.Count - 1) { //no need to loop DisplayReviewPanelObject(++m_currentReviewPos); } else { //loop to beginning of list m_currentReviewPos = 0; DisplayReviewPanelObject(m_currentReviewPos); } } /// <summary> /// backing up to the previous object displayed in the review panel /// </summary> public void PreviousReviewObject() { //loop to last object if we're currently displaying the first. if (m_currentReviewPos > 0) { //no need to loop DisplayReviewPanelObject(--m_currentReviewPos); } else { //loop to end of list m_currentReviewPos = reviewPanel.Count - 1; DisplayReviewPanelObject(m_currentReviewPos); } } }
3eb73f91071da4e9c00d237caf1f7a8c0647aa55
C#
Teorist/TeoLib
/Models/Item.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.Xml.Serialization; namespace TeoLib.Models { [Serializable, DataContract(Name = "item")] public class Item : BaseModel, IEquatable<Item> { [XmlAttribute(AttributeName = "id")] [DataMember(Name = "id")] public string Id { get; set; } [XmlAttribute(AttributeName = "type")] [DataMember(Name = "type")] public string Type { get; set; } [XmlElement(ElementName = "title")] [DataMember(Name = "title")] public string Title { get; set; } [XmlElement(ElementName = "note")] [DataMember(Name = "note")] public string Note { get; set; } [XmlElement(ElementName = "quality")] [DataMember(Name = "quality")] public int? Quality { get; set; } public Item() : base() { Id = DefaultString; Type = DefaultString; Title = DefaultString; Note = DefaultString; Quality = DefaultInt; } public Item(Item other) : base(other) { Id = other.Id; Type = other.Type; Title = other.Title; Note = other.Note; Quality = other.Quality; } #region IEquatable public bool Equals(Item other) { if (null == other) return false; return Id == other.Id; } public override bool Equals(object other) { if (null != other) return false; return Equals((Item)other); } public override int GetHashCode() { return null != Id ? Id.GetHashCode() : 0; } #endregion } }
61ec61bbaefbf54a6294ded55f0832314626c611
C#
Netopya/COMP-442-Assignment-3
/COMP442-Assignment3/SymbolTables/ClassEntry.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace COMP442_Assignment3.SymbolTables { // An entry in a symbol table representing a class public class ClassEntry : Entry { SymbolTable child; public ClassEntry(string name, SymbolTable parent) : base(parent, EntryKinds.classKind, name) { // Create a symbol table for the scope of this class child = new SymbolTable("Class Symbol Table: " + name, this); } // An unlinked (no parent) constructor if we need to create a hanging class (ex: a reference to an undefined class) public ClassEntry(string name) : base(null, EntryKinds.classKind, name) { child = null; } public override SymbolTable getChild() { return child; } public override string getType() { return string.Empty; } } }
93c6b36906ae27fba27c9614866d1122e7f1a3a7
C#
DzIvanova/OOP
/OOP-Homework-1/3. PC Catalog/Computer.cs
3.46875
3
using System; namespace _3.PC_Catalog { class Computer { private string name; private Component ram; private Component motherboard; private Component processor; //private decimal pcPrice; public string Name { get { return this.name; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentException("The name of the PC cannot be empty or null!"); this.name = value; } } public Component Motherboard { get { return this.motherboard; } set { this.motherboard = value; } } public Component RAM { get { return this.ram; } set { this.ram = value; } } public Component Processor { get { return this.processor; } set { this.processor = value; } } public decimal PcPrice { get { return this.Motherboard.Price + this.Processor.Price + this.RAM.Price; } } public Computer(string name, Component ram, Component motherboard, Component processor) { this.Name = name; this.RAM = ram; this.Motherboard = motherboard; this.Processor = processor; } public override string ToString() { System.Text.StringBuilder output = new System.Text.StringBuilder(); output.AppendLine("Name: " + this.Name); output.AppendLine("Motherboard: " + this.Motherboard.ToString()); output.AppendLine("Processor: " + this.Processor.ToString()); output.AppendLine("RAM: " + this.RAM.ToString()); output.AppendLine("Total Price: " + this.PcPrice + " lv"); return output.ToString(); } } }
51b96b93ea57c5fac8a675610742f31ec0388b22
C#
bzaar/CRFSharp
/CRFSharpConsole/DecoderConsole.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using CRFSharpWrapper; using CRFSharp; using System.Threading.Tasks; using System.Collections.Concurrent; using System.Diagnostics; using AdvUtils; namespace CRFSharpConsole { class DecoderConsole { public void Usage() { Console.WriteLine("CRFSharpConsole -decode <options>"); Console.WriteLine("-modelfile <string> : The model file used for decoding"); Console.WriteLine("-inputfile <string> : The input file to predict its content tags"); Console.WriteLine("-outputfile <string> : The output file to save raw tagged result"); Console.WriteLine("-outputsegfile <string> : The output file to save segmented tagged result"); Console.WriteLine("-nbest <int> : Output n-best result, default value is 1"); Console.WriteLine("-thread <int> : <int> threads used for decoding"); Console.WriteLine("-prob : output probability, default is not output"); Console.WriteLine(" 0 - not output probability"); Console.WriteLine(" 1 - only output the sequence label probability"); Console.WriteLine(" 2 - output both sequence label and individual entity probability"); Console.WriteLine("-maxword <int> : <int> max words per sentence, default value is 100"); Console.WriteLine("Example: "); Console.WriteLine(" CRFSharp_Console -decode -modelfile ner.model -inputfile ner_test.txt -outputfile ner_test_result.txt -outputsegfile ner_test_result_seg.txt -thread 4 -nbest 3 -prob 2 -maxword 500"); } public void Run(string[] args) { var options = new DecoderArgs(); for (var i = 0; i < args.Length; i++) { if (args[i][0] == '-') { var key = args[i].Substring(1).ToLower().Trim(); var value = ""; if (key == "decode") { continue; } else if (i < args.Length - 1) { i++; value = args[i]; switch (key) { case "outputfile": options.strOutputFileName = value; break; case "inputfile": options.strInputFileName = value; break; case "modelfile": options.strModelFileName = value; break; case "outputsegfile": options.strOutputSegFileName = value; break; case "thread": options.thread = int.Parse(value); break; case "nbest": options.nBest = int.Parse(value); break; case "prob": options.probLevel = int.Parse(value); break; case "maxword": options.maxword = int.Parse(value); break; default: var cc = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("No supported {0} parameter, exit", key); Console.ForegroundColor = cc; Usage(); return; } } else { var cc = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{0} is invalidated parameter.", key); Console.ForegroundColor = cc; Usage(); return; } } } if (options.strInputFileName == null || options.strModelFileName == null) { Usage(); return; } new CRFSharpWrapper.DecoderDriver().Decode(options); } } }
508cfabcfafe03912ff09bb73519adb8ebf08d2d
C#
marianard/Locadora
/Locadora/Controllers/GeneroController.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Locadora.Data; using Locadora.Models; namespace Locadora.Controllers { public class GeneroController : Controller { private readonly LocadoraContext _context; public GeneroController(LocadoraContext context) { _context = context; } /// <summary> /// Lista todos os generos /// </summary> /// <returns>Retorna uma view com todos os generos</returns> public async Task<IActionResult> Index() { return View(await _context.Genero.ToListAsync()); } /// <summary> /// Mostra os detalhes do genero /// </summary> /// <param name="id">Id do genero para ver os detalhes</param> /// <returns>Retorna uma view com o genero</returns> public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var genero = await _context.Genero .FirstOrDefaultAsync(m => m.GeneroId == id); if (genero == null) { return NotFound(); } return View(genero); } /// <summary> /// Retorna a pagina de criação do genero /// </summary> /// <returns>Retorna a view de criação do genero</returns> public IActionResult Create() { return View(); } /// <summary> /// Recebe o novo genero para ser persistido. /// </summary> /// <param name="genero">Detalhes do genero que vai ser criado </param> /// <returns>Retorna para a index</returns> [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("GeneroId,Nome,DataCriacao,Ativo")] Genero genero) { if (ModelState.IsValid) { _context.Add(genero); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(genero); } /// <summary> /// Retorna os dados para serem editados /// </summary> /// <param name="id">Id do genero para ser editado</param> /// <returns>Retorna uma view com o genero a ser editado</returns> public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var genero = await _context.Genero.FindAsync(id); if (genero == null) { return NotFound(); } return View(genero); } /// <summary> /// Edita o genero /// </summary> /// <param name="id">O id do genero que vai ser editado</param> /// <returns>Retorna para a index </returns> [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("GeneroId,Nome,DataCriacao,Ativo")] Genero genero) { if (id != genero.GeneroId) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(genero); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!GeneroExists(genero.GeneroId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(genero); } /// <summary> /// Retorna os dados para serem excluidos /// </summary> /// <param name="id">Id do genero para ser excluido</param> /// <returns>Retorna uma view com o genero a ser excluido</returns> public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var genero = await _context.Genero .FirstOrDefaultAsync(m => m.GeneroId == id); if (genero == null) { return NotFound(); } return View(genero); } /// <summary> /// Exclui o genero /// </summary> /// <param name="id">O id do genero que vai ser excluido</param> /// <returns>Retorna para a index </returns> [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var genero = await _context.Genero.FindAsync(id); _context.Genero.Remove(genero); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool GeneroExists(int id) { return _context.Genero.Any(e => e.GeneroId == id); } } }
a5992eb060b15222a97b3f6b0e030a49722e257d
C#
dimanngo/PoEAA
/C_Sharp/Framework.Tests/CustomerServices/GetCustomerByIdQuery.cs
2.796875
3
using System; using System.Collections.Generic; using Framework.Data_Manipulation; namespace Framework.Tests.CustomerServices { class GetCustomerByIdQuery : BaseQueryObject<Customer, GetCustomerByIdQuery.Criteria> { public class Criteria { public int CustomerId { get; set; } private Criteria() { } public static Criteria SearchById(int id) { return new Criteria {CustomerId = id}; } } public override IList<Customer> PerformSearchOperation(Criteria searchInput) { Dictionary<int, string> customerList = new Dictionary<int, string>(); customerList.Add(1, "Juan dela Cruz"); customerList.Add(2, "Jane Doe"); customerList.Add(3, "John Doe"); Tuple<string, string> searchResult = new Tuple<string, string>(searchInput.CustomerId.ToString(), customerList[searchInput.CustomerId]); IBaseMapper mapper = DataSynchronizationManager.GetInstance().GetMapper<Customer>(); Customer customer = new Customer(mapper); customer.Number = searchResult.Item1; customer.Name = searchResult.Item2; return new List<Customer>(new[] { customer }); } } }
9b13e0c61dbfaef376c9b476892d4b62f243b00d
C#
debop/NFramework
/src/NFramework.FusionCharts/Widgets/Attributes/WidgetFontAttribute.cs
3.109375
3
using System; using System.Drawing; using NSoft.NFramework.Tools; namespace NSoft.NFramework.FusionCharts.Widgets { /// <summary> /// Font Attributes. Widgets 에 있는 Chart중에는 IsBold, IsItalic, IsUnderline을 쓰는 것도 있지만, Is가 안 붙은 것도 있다. /// 그래서 구분을 위해 따로 정의하였다. /// </summary> /// <seealso cref="FontAttribute"/> [Serializable] public class WidgetFontAttribute : ChartAttributeBase { /// <summary> /// 생성자 /// </summary> public WidgetFontAttribute() : this(string.Empty) {} /// <summary> /// 생성자 /// </summary> /// <param name="prefix"></param> public WidgetFontAttribute(string prefix) { Prefix = (prefix ?? string.Empty).Trim(); } protected string Prefix { get; set; } public string Font { get; set; } public Color? FontColor { get; set; } public string FontSize { get; set; } public bool? Bold { get; set; } public bool? Italic { get; set; } public bool? Underline { get; set; } /// <summary> /// Chart 설정 또는 변량에 대해 XML 속성으로 생성합니다. /// </summary> /// <param name="writer">xml writer</param> public override void GenerateXmlAttributes(System.Xml.XmlWriter writer) { base.GenerateXmlAttributes(writer); if(Font.IsNotWhiteSpace()) writer.WriteAttributeString(Prefix + "Font", Font); if(FontColor.HasValue) writer.WriteAttributeString(Prefix + "FontColor", FontColor.Value.ToHexString()); if(FontSize.IsNotWhiteSpace()) writer.WriteAttributeString(Prefix + "FontSize", FontSize); if(Bold.HasValue) writer.WriteAttributeString(Prefix + "Bold", Bold.Value.GetHashCode().ToString()); if(Italic.HasValue) writer.WriteAttributeString(Prefix + "Italic", Italic.Value.GetHashCode().ToString()); if(Underline.HasValue) writer.WriteAttributeString(Prefix + "Underline", Underline.Value.GetHashCode().ToString()); } } }
14ca6f0643864e233b533bc2e145b3ec490ad1c8
C#
naps250/mal-api
/MalApi/Manga/MalMangaInfoFromUserLookup.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MalApi { public class MalMangaInfoFromUserLookup : IEquatable<MalMangaInfoFromUserLookup> { public int MangaId { get; private set; } public string Title { get; private set; } /// <summary> /// Could be something other than the enumerated values if MAL adds new types! /// </summary> public MalMangaType Type { get; private set; } public ICollection<string> Synonyms { get; private set; } public MalMangaSeriesStatus Status { get; private set; } public int NumChapters { get; private set; } public int NumVolumes { get; private set; } public UncertainDate StartDate { get; private set; } public UncertainDate EndDate { get; private set; } public string ImageUrl { get; private set; } public MalMangaInfoFromUserLookup(int mangaId, string title, MalMangaType type, ICollection<string> synonyms, MalMangaSeriesStatus status, int numChapters, int numVolumes, UncertainDate startDate, UncertainDate endDate, string imageUrl) { MangaId = mangaId; Title = title; Type = type; Synonyms = synonyms; Status = status; NumChapters = numChapters; NumVolumes = numVolumes; StartDate = startDate; EndDate = endDate; ImageUrl = imageUrl; } public override bool Equals(object obj) { return Equals(obj as MalMangaInfoFromUserLookup); } public bool Equals(MalMangaInfoFromUserLookup other) { if (other == null) return false; return this.MangaId == other.MangaId; } public override int GetHashCode() { return MangaId.GetHashCode(); } public override string ToString() { return Title; } } }
ae2e6dede2fb1b47e415a4bde60a7b6484d613d5
C#
MellyMellyMelly/Poker
/Backend/Testing/Objects/Duplicate.cs
2.90625
3
namespace Base.Objects { public class PropertyCopier<TParent, TChild> where TParent : class where TChild : class { public static void Copy(TParent parent, TChild child) { var parentProperties = parent.GetType().GetProperties(); var childProperties = child.GetType().GetProperties(); foreach (var parentProperty in parentProperties) { foreach (var childProperty in childProperties) { if (parentProperty.Name == childProperty.Name && parentProperty.PropertyType == childProperty.PropertyType) { childProperty.SetValue(child, parentProperty.GetValue(parent)); } } } } public static void UpdateRecord(TParent parent, TChild child) { var parentProperties = parent.GetType().GetProperties(); var childProperties = child.GetType().GetProperties(); foreach (var parentProperty in parentProperties) { foreach (var childProperty in childProperties) { if (parentProperty.Name == childProperty.Name && parentProperty.PropertyType == childProperty.PropertyType) { if(childProperty.PropertyType == typeof(int)) { if(childProperty.Name != "wins" && childProperty.Name != "games") { int newValue = (int) parentProperty.GetValue(parent) + (int) childProperty.GetValue(child); childProperty.SetValue(child, newValue); break; } } } } } } public static void UpdateHandTotal(TParent parent, TChild child) { var parentProperties = parent.GetType().GetProperties(); var childProperties = child.GetType().GetProperties(); foreach (var parentProperty in parentProperties) { foreach (var childProperty in childProperties) { if (parentProperty.Name == childProperty.Name && parentProperty.PropertyType == childProperty.PropertyType) { int newValue = (int) parentProperty.GetValue(parent) + (int) childProperty.GetValue(child); childProperty.SetValue(child, newValue); break; } } } } } }
a7af28f43f5115690935f9d3e1f2a3fa0922454f
C#
Wivor/Dyplom
/Untitled Strategy Game/Assets/Scripts/Game/Map/Grid.cs
2.671875
3
using System; using UnityEngine; public class Grid : MonoBehaviour { public Transform hexPrefab; private int _id = 0; private Vector3 _startPos; private float _hexWidth; private float _hexHeight; private float _offset; private int _gridWidth; private int _gridHeight; private const float Size = 1; private const float Gap = 0.1f; public int GridWidth { get => _gridWidth; private set => _gridWidth = value; } public int GridHeight { get => _gridHeight; private set => _gridHeight = value; } private Grid() { CalcHexSize(); } public void GenerateGrid(int width, int height) { _gridWidth = width; _gridHeight = height; ClearGrid(); CalcStartPos(); CreateGrid(); ConnectNeighbours(); } public void ClearGrid() { _id = 0; Storage.ClearStorage(); foreach (Transform child in transform) Destroy(child.gameObject); } private void AddGap() { _hexWidth += _hexWidth * Gap; _hexHeight += _hexHeight * Gap; } private void CalcHexSize() { _hexWidth = (float)Math.Sqrt(3) * Size; _hexHeight = Size * 2; _offset = _hexWidth / 2; AddGap(); } private void CalcStartPos() { float x = -_hexWidth * (_gridWidth / 2); float z = _hexHeight * (_gridHeight / 2); _startPos = new Vector3(x, 0, z); } private void CreateGrid() { for (int y = 0; y < _gridHeight; y++) { for (int x = 0; x < _gridWidth; x++) { Transform hex = Instantiate(hexPrefab, transform, true); Vector2 gridPos = new Vector2(x, y); hex.position = CalcWorldPos(gridPos); hex.name = "Hex " + x + "x" + y; hex.GetComponent<Hex>().id = _id; hex.GetComponent<Node>().position = new Node.Position(x, y); Storage.hexes.Add(hex.GetComponent<Hex>()); _id++; } } } Vector3 CalcWorldPos(Vector2 gridPos) { float x; if (gridPos.y % 2 != 0) x = _startPos.x + gridPos.x * _hexWidth + _offset; else x = _startPos.x + gridPos.x * _hexWidth ; float z = _startPos.z - gridPos.y * _hexHeight * 0.75f; return new Vector3(x, 0, z); } private void ConnectNeighbours() { foreach (Hex hex in Storage.hexes) { hex.GetComponent<Node>().ConnectNeighbours(); } } }
a9447043dae38003721b80c434e73215cabd6728
C#
MohammedAzmat/Shatranj
/ShatranjCore/PieceSet.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShatranjCore { public class PieceSet { private PieceColor color; public List<Piece> Pieces; public PieceColor PieceSetColor { get { return color; } } public PieceSet(PieceColor color) { this.color = color; this.Pieces = new List<Piece>(); } } }
54e8814b6d3e0b112292f2d49969549c74818533
C#
worldkk1/321ACTION
/321ACTION/Home.cs
2.546875
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 _321ACTION { public partial class Home : Form { public Home() { InitializeComponent(); } private void btn_start_Click(object sender, EventArgs e) { Mode md = new Mode(); md.Show(); this.Hide(); } private void btn_setting_Click(object sender, EventArgs e) { test tt = new test(); tt.Show(); this.Hide(); } private void btn_exit_Click(object sender, EventArgs e) { Application.Exit(); } private void Home_Load(object sender, EventArgs e) { int btn_width = this.Width/2; int btn_height = this.Height/2; btn_start.Location = new Point(btn_width-(btn_start.Width/2), btn_height); btn_setting.Location = new Point(btn_start.Left, btn_start.Height + btn_start.Top + 10); btn_exit.Location = new Point(btn_setting.Left, btn_setting.Height + btn_setting.Top+10); } } }