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
830f4d6baeb8a97e4ee1b4b1bda1563c4d7b084a
C#
Novak-Oksana/AndroidCalc
/XamarinCalculator/XamarinCalculator.Android/MainActivity.cs
2.515625
3
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace XamarinCalculator.Droid { [Activity(Label = "XamarinCalculator.Android", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { private EditText txt_Result; private bool last_number = false; private Calculator calc; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); FindVeiws(); calc = new Calculator(); // Get our button from the layout resource, // and attach an event to it } private void FindVeiws() { txt_Result = FindViewById<EditText>(Resource.Id.txtResult); var btn_0 = FindViewById<Button>(Resource.Id.btn0); btn_0.Click += NumClick; var btn_1 = FindViewById<Button>(Resource.Id.btn1); btn_1.Click += NumClick; var btn_2 = FindViewById<Button>(Resource.Id.btn2); btn_2.Click += NumClick; var btn_3 = FindViewById<Button>(Resource.Id.btn3); btn_3.Click += NumClick; var btn_4 = FindViewById<Button>(Resource.Id.btn4); btn_4.Click += NumClick; var btn_5 = FindViewById<Button>(Resource.Id.btn5); btn_5.Click += NumClick; var btn_6 = FindViewById<Button>(Resource.Id.btn6); btn_6.Click += NumClick; var btn_7 = FindViewById<Button>(Resource.Id.btn7); btn_7.Click += NumClick; var btn_8 = FindViewById<Button>(Resource.Id.btn8); btn_8.Click += NumClick; var btn_9 = FindViewById<Button>(Resource.Id.btn9); btn_9.Click += NumClick; var btn_plus = FindViewById<Button>(Resource.Id.btnsum); btn_plus.Click += OpClick; var btn_minus = FindViewById<Button>(Resource.Id.btnminus); btn_minus.Click += OpClick; var btn_div = FindViewById<Button>(Resource.Id.btndiv); btn_div.Click += OpClick; var btn_mul = FindViewById<Button>(Resource.Id.btnmul); btn_mul.Click += OpClick; var btn_equal = FindViewById<Button>(Resource.Id.btnequal); btn_equal.Click += OnClickEq; var btn_c = FindViewById<Button>(Resource.Id.btnc); btn_c.Click += OnClickClear; } private void OnClickClear(object sender, EventArgs e) { txt_Result.Text = ""; calc.set_last_operator('*'); calc.calculate(0); calc.set_last_operator('+'); txt_Result.Text = "" + calc.get_result(); } private void OnClickEq(object sender, EventArgs e) { calc.calculate(Convert.ToInt32(txt_Result.Text)); txt_Result.Text = "" + calc.get_result(); last_number = false; } private void OpClick(object sender, EventArgs e) { Button button = (Button)sender; char op = System.Convert.ToChar(button.Text); calc.calculate(Convert.ToInt32(txt_Result.Text)); calc.set_last_operator(op); last_number = false; } private void NumClick(object sender, EventArgs e) { Button button = (Button)sender; if (last_number) txt_Result.Text = txt_Result.Text + button.Text; else txt_Result.Text = button.Text; last_number = true; } } }
474b0dc8ce59b2614db55011f9631a7926b5e09f
C#
P-Beshkov/PS-Teamwork
/Test/Writer.cs
2.671875
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test { public class Writer { public static void WriteToFile(string text, string path) { using (StreamWriter writer = new StreamWriter(path)) { writer.WriteLine(text); } } static void Main(string[] args) { } } }
424847d8bd9d591146858d5bbab9a2103d5e89cc
C#
shendongnian/download4
/first_version_download2/171198-12825291-30302959-2.cs
2.625
3
var type1 = new Type1(); var type2 = new Type2(); ... var propMap = new List<Tuple<Expression<Func<Type1, object>>, Expression<Func<TradeStaticAttributesItemModel, object>>>> { new Tuple<Expression<Func<Type1, object>>, Expression<Func<Type2, object>>>(x => x.Prop1, x => x.Prop1), new Tuple<Expression<Func<Type1, object>>, Expression<Func<Type2, object>>>(x => x.Prop2, x => x.Prop2) }; foreach (var prop in propMap) { if (prop.Item1.Compile()(type1) != prop.Item2.Compile()(type2)) { ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object)); var assign = Expression.Lambda<Action<Trade, object>>(Expression.Assign(prop.Item1.Body, Expression.Convert(valueParameterExpression, prop.Item1.Body.Type)), prop.Item1.Parameters.Single(), valueParameterExpression); Action<Type1, object> setter = assign.Compile(); setter(type1, prop.Item2.Compile()(type2)); } }
590abfb4044e87f8259913310fb228d7f50bcb6b
C#
Qorpent/comdiv.oldcore
/Comdiv.Core/Application/WidgetPosition.cs
2.625
3
namespace Comdiv.Application { /// <summary> /// Стандартные позиции виджетов /// </summary> public enum WidgetPosition { /// <summary> /// Позиция нестандартная /// </summary> None, /// <summary> /// Панель управления /// </summary> Toolbar , /// <summary> /// Заголовок HTML /// </summary> HtmlHeader , /// <summary> /// Верхний левый фрейм /// </summary> HeaderLeft, /// <summary> /// Верхний центральный фрейм /// </summary> HeaderCenter, /// <summary> /// Верхний правый фрейм /// </summary> HeaderRight, /// <summary> /// Левый фрейм основной части /// </summary> BodyLeft, /// <summary> /// Верхний фрейм фрейм основной части /// </summary> BodyHeader, /// <summary> /// НИжний фрейм основной части /// </summary> BodyFooter, /// <summary> /// Правый фрейм основной части /// </summary> BodyRight, /// <summary> /// Левый нижний фрейм /// </summary> FooterLeft, /// <summary> /// Центральный нижний фрейм /// </summary> FooterCenter, /// <summary> /// Правый нижний фрейм /// </summary> FooterRight, StatusBar, Title, } }
5eedbfa3be25f6ebf813aeeea8a23afbea38a3a1
C#
MauroAguirre/Estudio
/Taller de objetos/Obligatorio documentacion/Obligatorio taller objetos/Dominio/Nacional.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dominio { public class Nacional: Excursion { private int descuento; public int Descuento { get { return descuento;} set { descuento = value;} } public Nacional(string codigo, string descripcion, DateTime fechaComienzo, int diaTraslado, List<DestinoEstadia> destinoEstadias, int stock, int costoTraslado,int descuento) : base(codigo, descripcion, fechaComienzo, diaTraslado, destinoEstadias, stock, costoTraslado) { this.descuento = descuento; } public override int Costo() { int costo = 0; foreach (DestinoEstadia unD in DestinoEstadia) { costo += unD.DiasEstadia * unD.Destino.CostoDiario; } costo += CostoTraslado * DiaTraslado; costo *= Stock; costo -= (costo * descuento) / 100; return costo; } } }
8d1272749935f2f8d1188ee8193b59b59f42d720
C#
coolcooldeath/oop
/laba 7 exception/laba 7 exception/Program.cs
2.984375
3
using System; using System.IO; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using System.Runtime.CompilerServices; using System.Text; namespace laba_7_exception { public static class Logger { public static void FileLog(string message) { File.AppendAllText("log.txt", message); } public static void ConsoleLog(string message) { Console.WriteLine($"{message}"); } } public class Printer { public virtual void IAmPrinting(Transport obj) { obj.ToString(); } } public interface IPrintable { void Print(); } public interface IPrintableAnother { void Print(); } public abstract class Transport { public virtual void ToString() { } public abstract int Weight { get; set; } } public abstract class Aviation : Transport { public abstract int Fuel { get; set; } public abstract int Km { get; set; } public override void ToString() { } public class Cargo : Aviation { public override void ToString() { Console.WriteLine($"грузоподъемность грузового транспорта - {Weight},объем топливного отсека - {Fuel} , дальность полета - {Km}"); } public override int Weight { get; set; } public override int Fuel { get; set; } public override int Km { get; set; } public Cargo(int Km, int Weight, int Fuel) { this.Weight = Weight; this.Km = Km; this.Fuel = Fuel; } } public class Military : Aviation { public override void ToString() { Console.WriteLine($"грузоподъемность военного транспорта - {Weight},объем топливного отсека - {Fuel} , дальность полета - {Km}"); } public override int Weight { get; set; } public override int Fuel { get; set; } public override int Km { get; set; } public Military() { throw new Nothing("Нельзя создать самолет без параметров"); } public Military(int Km, int Weight, int Fuel) { this.Weight = Weight; this.Km = Km; this.Fuel = Fuel; } } public class Passenger : Aviation { public override void ToString() { Console.WriteLine($"грузоподъемность пассажирского транспорта - {Weight},объем топливного отсека - {Fuel} , дальность полета - {Km}, количество мест - {Seats}"); } public int Seats { get; set; } public override int Weight { get; set; } public override int Fuel { get; set; } public override int Km { get; set; } public Passenger(int Km, int Weight, int Fuel, int Seats) { this.Weight = Weight; this.Km = Km; this.Fuel = Fuel; this.Seats = Seats; } } public sealed class Tu134 : Military, IPrintable, IPrintableAnother { public override void ToString() { Console.WriteLine($"грузоподъемность военного транспорта - {Weight},объем топливного отсека - {Fuel} , дальность полета - {Km}"); } private int km; public int weight=3000 ; public override int Fuel { get; set; } public override int Km { get { return km; } set { if (km < 0) throw new NotNullException("Дальность не может быть меньше нуля", 211); else km = value; } } public override int Weight { get { return weight; } set { if (weight < 2000) throw new WeightException("Вес не может быть меньше допустимого значения", 2000); else weight = value; } } public Tu134(int Km, int Weight, int Fuel) : base(Km, Weight, Fuel) { this.Weight = Weight; this.Km = Km; this.Fuel = Fuel; } void IPrintable.Print() { Console.WriteLine("Это военный самолет ТУ - 134 модификация 2001 года"); } void IPrintableAnother.Print() { Console.WriteLine("Это военный самолет ТУ - 134 модификация 2009 года"); } } public sealed class Boeing : Passenger, IPrintable, IPrintableAnother { public override void ToString() { Console.WriteLine($"грузоподъемность пассажирского транспорта - {Weight},объем топливного отсека - {Fuel} , дальность полета - {Km}, количество мест - {Seats}"); } new public int Seats { get; set; } public override int Weight { get; set; } public override int Fuel { get; set; } public override int Km { get; set; } public Boeing(int Km, int Weight, int Fuel, int Seats) : base(Km, Weight, Fuel, Seats) { this.Weight = Weight; this.Km = Km; this.Fuel = Fuel; this.Seats = Seats; } void IPrintable.Print() { Console.WriteLine("Это пассажирский самолет Боинг модификации 2020 года "); } void IPrintableAnother.Print() { Console.WriteLine("Это пассажирский самолет Боинг модификации 2010 года"); } } } class NotNullException : Exception { public string message; public int num; public NotNullException(string message, int num) : base(message) { this.num = num; this.message = message; } } class Nothing: Exception { public string message; public Nothing(string message) : base(message) { this.message = message; } } class WeightException:Exception { public string message; public int MinWeight; public WeightException(string message,int MinWeight) : base(message) { this.message = message; this.MinWeight = MinWeight; } } class Program { static void Main(string[] args) { int x = 10, y = 0, z,Km,count; Console.WriteLine($"Введите дальность"); Km =Convert.ToInt32(Console.ReadLine()); Console.WriteLine($"Введите количество элементов массива для проверки от 1 до 4"); count = Convert.ToInt32(Console.ReadLine()); Aviation.Military.Tu134 tu134_1 = new Aviation.Tu134(900, 5000, 2000); Aviation.Military.Tu134 tu134_2 = new Aviation.Tu134(1000, 4000, 2000); Aviation.Military.Tu134 tu134_3 = new Aviation.Tu134(5000, 3000, 3000); Aviation.Military.Tu134 tu134_4 = new Aviation.Tu134(6000, 3000, 2000); Printer printer = new Printer(); Aviation[] aviations = new Aviation[4] { tu134_1, tu134_2, tu134_3, tu134_4 }; try { z = x / y; } catch (DivideByZeroException ex) { StringBuilder log = new StringBuilder(); log.Append(DateTime.Now+"\n"); log.Append(ex.StackTrace+"\n"); log.Append("Ошибка: Деление на ноль" + "\n" +"________________________________________________" +"\n"); Logger.FileLog(Convert.ToString(log)); } try { Aviation.Military.Tu134 tu134 = new Aviation.Tu134(Km, 3000, 2000); tu134.ToString(); } catch (NotNullException ex) { StringBuilder log = new StringBuilder(); log.Append(DateTime.Now + "\n"); log.Append(ex.StackTrace + "\n"); log.Append("Ошибка:" + ex.Message + "\n" + "________________________________________________" + "\n"); Logger.FileLog(Convert.ToString(log)); } try { Aviation.Military military= new Aviation.Military(); } catch (Nothing ex) { StringBuilder log = new StringBuilder(); log.Append(DateTime.Now + "\n"); log.Append(ex.StackTrace + "\n"); log.Append("Ошибка:" + ex.Message + "\n" + "________________________________________________" + "\n"); Logger.FileLog(Convert.ToString(log)); } try { for (int i = 0; i < 5; i++) { printer.IAmPrinting(aviations[i]); } } catch(IndexOutOfRangeException ex) { StringBuilder log = new StringBuilder(); log.Append(DateTime.Now + "\n"); log.Append(ex.StackTrace + "\n"); log.Append("Ошибка:" + ex.Message + "\n" + "________________________________________________" + "\n"); Logger.FileLog(Convert.ToString(log)); } try { Aviation.Military.Tu134 tu134_6 = new Aviation.Tu134(900, 1000, 2000); tu134_6.ToString(); } catch (WeightException ex) { StringBuilder log = new StringBuilder(); log.Append(DateTime.Now + "\n"); log.Append(ex.StackTrace + "\n"); log.Append("Ошибка:" + ex.Message + "\n" + "________________________________________________" + "\n"); Logger.ConsoleLog(Convert.ToString(log)); } finally { StringBuilder log = new StringBuilder(); log.Append(DateTime.Now + "\n"); log.Append("Блок finally отчистка ресурсов в отлове исключений"+"\n"); log.Append("\n" + "________________________________________________" + "\n"); Logger.ConsoleLog(Convert.ToString(log)); Logger.FileLog(Convert.ToString(log)); } static int Abs(int value) { if (value > 0) return value; return -value; } Debug.Assert(Abs(-5) == 5); Debug.Assert(Abs(100) == 100); } } }
16c6707fd072ccbf89e1da88e667e1fdc6e62b97
C#
yakubovych/StudentsAssessment
/test/enter.xaml.cs
2.6875
3
using System.Collections.ObjectModel; using System.Data.Entity; using System.Windows; namespace test { public partial class enter : Window { ObservableCollection<User> users; ApplicationContext db = new ApplicationContext(); public enter() { db.Users.Load(); db.Users.Local.ToBindingList(); Users = db.Users.Local; InitializeComponent(); } public ObservableCollection<User> Users { get { return users; } set { users = value; } } private void regist(object sender, RoutedEventArgs e) { this.Hide(); register register = new register(); if (register.ShowDialog() == false) { if(register.reguser == null) { } else { db.Users.Local.Add(register.reguser); db.SaveChanges(); } } this.Show(); } private void Button_Click(object sender, RoutedEventArgs e) { bool isConnected = false; foreach (var u in users) { if (u.Login == login.Text && u.Password == password.Password) { isConnected = true; } } if (isConnected) { MainWindow MainWindow = new MainWindow(); Close(); MainWindow.ShowDialog(); } else { MessageBox.Show("Логін або пароль введений неправильно!"); } } } }
512c43e097d49cff4b6ee50ab4094526f8f60b77
C#
C41-233/FFF
/Project/FCommon/FBase/Time/DateTimeExtension.cs
2.75
3
using System; namespace FFF.Base.Time { public static class DateTimeExtension { public static readonly DateTime UtcStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); public static long ToTimeStamp(this DateTime dt) { var span = dt.Subtract(UtcStart); return (long) span.TotalMilliseconds; } } }
56eee66739f8f7631592eddeb759ddb744b3d8dd
C#
tayduivn/SocialPayments
/SocialPayments.DomainServices/ValidationService.cs
2.90625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NLog; using System.Text.RegularExpressions; namespace SocialPayments.DomainServices { public class ValidationService { private DomainServices.FormattingServices formattingServices = new FormattingServices(); private Logger _logger; public ValidationService(Logger logger) { _logger = logger; } public bool AreMobileNumbersEqual(string mobileNumber, string mobileNumberToCompare) { try { return formattingServices.FormatMobileNumber(mobileNumber).Equals(formattingServices.FormatMobileNumber(mobileNumberToCompare), StringComparison.OrdinalIgnoreCase); } catch (Exception ex) { _logger.Log(LogLevel.Error, String.Format("Unhandled Exception Comparing Mobile Number {0}", ex.Message)); } return false; } public bool IsEmailAddress(string uri) { string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+" + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@" + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+" + @"[a-zA-Z]{2,}))$"; Regex reStrict = new Regex(patternStrict); bool isStrictMatch = reStrict.IsMatch(uri); return isStrictMatch; } public bool IsMECode(string uri) { return uri[0].Equals('$'); } public bool IsFacebookAccount(string uri) { if (uri.Length < 4) return false; if (uri.Substring(0, 3).Equals("fb_")) return true; return false; } } }
7a5996e9de366cbb800d7dc2d2f9d0485a4d3f13
C#
Rammun/Apollon
/Apollon/Ship.cs
3.265625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Apollon { /// <summary> /// Оисывает корабль /// </summary> public class Ship { float height = Setting.Height; float fuel = Setting.Fuel; float speed = Setting.Speed; bool power = false; public Ship() { } public float Height { get { return height; } } // Текущая высота корабля public float Fuel { get { return fuel; } } // Текущее кол-во топлива public float Speed { get { return speed; } } // Текущая скорость корабля public bool Power { get { return power; } } // Текущее состояние двигателя // Включить двигатель public void PowerOn() { if (fuel > 0) power = true; } // Выключить двигатель public void PowerOff() { power = false; } /// <summary> /// Вычисляет высоту корабля /// </summary> /// <param name="s">секунды</param> /// <returns>высота</returns> public void MoveShip(float s) { if(power) // Если двигатель включен { speed += s * Setting.Ship_g; fuel -= Setting.Speed_f * s; if(fuel < 0) { fuel = 0; power = false; } } else // Если двигатель выключен { speed += s * Setting.Moon_g; } height += s * speed; // Считаем высоту } } }
8c98e46ff11435713f349cf032844b3adc7a3bef
C#
shendongnian/download4
/code1/12658-59545576-212121075-4.cs
2.515625
3
private bool decimalSeparator = false; private void Control_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Decimal) decimalSeparator = true; } private void Control_KeyPress(object sender, KeyPressEventArgs e) { if (decimalSeparator) { e.KeyChar = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]; decimalSeparator = false; } }
6964cffe924a13d107c03393c59547a7a403abe5
C#
DmitriyGj/BasicProgramming2
/Documentation.csproj/Specifier.cs
3.125
3
using System; using System.Linq; using System.Reflection; namespace Documentation { public class Specifier<T> : ISpecifier { public string GetApiDescription() { return typeof(T).GetCustomAttributes()?.OfType<ApiDescriptionAttribute>().FirstOrDefault()?.Description; } public string[] GetApiMethodNames() { return typeof(T).GetMethods() .Where(method=>method.GetCustomAttributes().OfType<ApiMethodAttribute>().Any()) .Select(method=> method.Name).ToArray(); } public string GetApiMethodDescription(string methodName) { return typeof(T).GetMethod(methodName)? .GetCustomAttributes().OfType<ApiDescriptionAttribute>().FirstOrDefault()?.Description ; } public string[] GetApiMethodParamNames(string methodName) { return typeof(T).GetMethod(methodName)?.GetParameters().Select(param => param.Name).ToArray(); } public string GetApiMethodParamDescription(string methodName, string paramName) { return typeof(T).GetMethod(methodName)?.GetParameters() .Where(param=>param.Name.Equals(paramName)) .Select(param=>param).FirstOrDefault()? .GetCustomAttributes().OfType<ApiDescriptionAttribute>().FirstOrDefault()?.Description; } public ApiParamDescription GetApiMethodParamFullDescription(string methodName, string paramName) { var paramDescription = new ApiParamDescription(); var method = typeof(T).GetMethod(methodName); var attributes = method?.GetParameters() .Where(param => param.Name == paramName).FirstOrDefault()?.GetCustomAttributes(); if (method is null || attributes is null) { paramDescription.ParamDescription = new CommonDescription(paramName); return paramDescription; } paramDescription.ParamDescription = new CommonDescription(paramName, GetApiMethodParamDescription(methodName, paramName)); paramDescription.MinValue = attributes?.OfType<ApiIntValidationAttribute>().FirstOrDefault()?.MinValue; paramDescription.MaxValue = attributes?.OfType<ApiIntValidationAttribute>().FirstOrDefault()?.MaxValue; paramDescription.Required = attributes?.OfType<ApiRequiredAttribute>().FirstOrDefault()?.Required ?? false; return paramDescription; } public ApiMethodDescription GetApiMethodFullDescription(string methodName) { var method = typeof(T).GetMethod(methodName); if (method == null || method?.GetCustomAttributes().OfType<ApiMethodAttribute>().FirstOrDefault() == null) return null; var res = new ApiMethodDescription { MethodDescription = new CommonDescription { Name = methodName, Description = GetApiMethodDescription(methodName) }, ParamDescriptions = method.GetParameters()? .Select(param => GetApiMethodParamFullDescription(methodName, param.Name)).ToArray(), ReturnDescription = GetReturnDescription(method) }; return res; } private static ApiParamDescription GetReturnDescription(MethodInfo method) { var invalidAtr = method?.ReturnParameter?.GetCustomAttributes().OfType<ApiIntValidationAttribute>().FirstOrDefault(); var reqAtr = method?.ReturnParameter?.GetCustomAttributes().OfType<ApiRequiredAttribute>().FirstOrDefault(); if (reqAtr == null && invalidAtr == null) return null; var returnDescription = new ApiParamDescription { MaxValue = invalidAtr?.MaxValue, MinValue = invalidAtr?.MinValue, Required = reqAtr?.Required ?? false }; return returnDescription; } } }
260b74aa8debfa6d0f983a54fe47646629e1eabe
C#
arkados/Moon.Sender
/Moon.Cdo/ServerCdoFactory.cs
2.515625
3
using System.Web; namespace Moon.Cdo { /// <summary> /// Pro vytváření objektů pomocí Server.CreateObject /// </summary> public class ServerCdoFactory :ICdoFactory { public virtual T Create<T>() { return (T)HttpContext.Current.Server.CreateObject(typeof(T).FullName); } } }
cf57f021bab5edcc5fc3c332de0dba0e58260ebd
C#
jinibyun/CodingLearn
/ConsoleAdoNet/ConsoleAdoNet/_07StoredProcOutput.cs
2.90625
3
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; namespace ConsoleAdoNet { public class _07StoredProcOutput : BaseClass { public override void Test() { /* CREATE PROC uspSPwithOUTPUT @v_title_id varchar(10) , @v_output int OUTPUT AS UPDATE titles SET price = price * 2 WHERE title_id = @v_title_id SET @v_output = (SELECT @@ROWCOUNT) -- affected row count */ string titleId = "BU1032"; using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("uspSPwithOUTPUT", con)) { cmd.CommandType = CommandType.StoredProcedure; var param1 = new SqlParameter("@v_title_id", SqlDbType.VarChar, 6 ); param1.Direction = ParameterDirection.Input; param1.Value = titleId; cmd.Parameters.Add(param1); var param2 = new SqlParameter("@v_output", SqlDbType.Int); param2.Direction = ParameterDirection.Output; cmd.Parameters.Add(param2); con.Open(); cmd.ExecuteNonQuery(); var outputRecord = cmd.Parameters["@v_output"].Value != null ? int.Parse(cmd.Parameters["@v_output"].Value.ToString()) : -1; Console.WriteLine(outputRecord); } } } } }
49382fd050536e4b337a949dbc663535bfe790ac
C#
switch-stuff/AES-Sharp
/Program.cs
2.921875
3
using System; using System.IO; using System.Linq; namespace AES_Sharp { class Program { static void Main(string[] args) { byte[] h(string Hex) { return Enumerable.Range(0, Hex.Length).Where(x => x % 2 == 0).Select(x => Convert.ToByte(Hex.Substring(x, 2), 16)).ToArray(); } File.WriteAllBytes(args[2] + ".out", Aes.CTR(h(args[0]), h(args[1]), File.ReadAllBytes(args[2]))); } } }
c5ed68cdd0a3d152aa5c307dc701e6935582fd06
C#
Fasjeit/DiscoNet
/DiscoNet.Tests/SymmetricTests.cs
2.78125
3
namespace DiscoNet.Tests { using System; using System.Linq; using System.Text; using DiscoNet.Noise; using StrobeNet.Extensions; using Xunit; public class SymmetricTests { [Fact] public void TestHash() { var input = Encoding.ASCII.GetBytes("hi, how are you?"); if (!string.Equals( Symmetric.Hash(input, 32).ToHexString(), "eda8506c1fb0bbcc3f62626fef074bbf2d09a8c7c608f3fa1482c9a625d00f75", StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("Hash does not produce a correct output"); } } [Fact] public void TestSum() { var message1 = Encoding.ASCII.GetBytes("hello"); var message2 = Encoding.ASCII.GetBytes("how are you good sir?"); var message3 = Encoding.ASCII.GetBytes("sure thing"); var fullMessage = message1.Concat(message2).ToArray(); // Trying with NewHash with streaming and without streaming var h1 = new Hash(32); h1.Write(message1); h1.Write(message2); var out1 = h1.Sum(); var h2 = new Hash(32); h2.Write(fullMessage); var out2 = h2.Sum(); if (!out1.SequenceEqual(out2)) { throw new Exception("Sum function does not work"); } // Trying with Hash() var out3 = Symmetric.Hash(fullMessage, 32); if (!out1.SequenceEqual(out3)) { throw new Exception("Sum function does not work"); } // Trying the streaming even more h1.Write(message3); out1 = h1.Sum(); h2.Write(message3); out2 = h2.Sum(); if (!out1.SequenceEqual(out2)) { throw new Exception("Sum function does not work"); } // tring with Hash() out3 = Symmetric.Hash(fullMessage.Concat(message3).ToArray(), 32); if (!out1.SequenceEqual(out3)) { throw new Exception("Sum function does not work"); } } [Fact] public void TestDeriveKeys() { var input = Encoding.ASCII.GetBytes("hi, how are you?"); if (!string.Equals( Symmetric.DeriveKeys(input, 64).ToHexString(), "d6350bb9b83884774fb9b0881680fc656be1071fff75d3fa94519d50a10b92644e3cc1cae166a60167d7bf00137018345bb8057be4b09f937b0e12066d5dc3df", StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("DeriveKeys does not produce a correct output"); } } [Fact] public void TestProtectVerifyIntegrity() { var key = "eda8506c1fb0bbcc3f62626fef074bbf2d09a8c7c608f3fa1482c9a625d00f75".ToByteArray(); var message = Encoding.ASCII.GetBytes("hoy, how are you?"); var plaintextAndTag = Symmetric.ProtectIntegrity(key, message); var retrievedMessage = Symmetric.VerifyIntegrity(key, plaintextAndTag); if (!message.SequenceEqual(retrievedMessage)) { throw new Exception("Verify did not work"); } // Tamper plaintextAndTag[plaintextAndTag.Length - 1] ^= 1; bool tamperDetected; try { Symmetric.VerifyIntegrity(key, plaintextAndTag); tamperDetected = false; } catch (Exception) { tamperDetected = true; } if (!tamperDetected) { throw new Exception("Verify did not work"); } } [Fact] public void TestNonceSize() { var key = "eda8506c1fb0bbcc3f62626fef074bbf2d09a8c7c608f3fa1482c9a625d00f75".ToByteArray(); var plaitext = Encoding.ASCII.GetBytes("hello, how are you?"); var ciphertext = Symmetric.Encrypt(key, plaitext); if (ciphertext.Length != 19 + 16 + 24) { throw new Exception("Length of this ciphertext should be 19B(PT) + 16B(TAG) + 24B(NONCE)"); } } [Fact] public void TestEncryptDecrypt() { var key = "eda8506c1fb0bbcc3f62626fef074bbf2d09a8c7c608f3fa1482c9a625d00f75".ToByteArray(); var plaintexs = new[] { "", "a", "ab", "abc", "abcd", "short", "hello, how are you?", "this is very short", "this is very long though, like, very very long, should we test very very long things here?", "Domestic cats are similar in size to the other members of the genus Felis, typically weighing " + "between 4 and 5 kg (9 and 10 lb).[36] Some breeds, such as the Maine Coon, can occasionally " + "exceed 11 kg (24 lb). Conversely, very small cats, less than 2 kg (4 lb), have been reported.[59] " + "The world record for the largest cat is 21 kg(50 lb).[60][self - published source] " + "The smallest adult cat ever officially recorded weighed around 1 kg(2 lb).[60] " + "Feral cats tend to be lighter, as they have more limited access to food than house cats." + "The Boston Cat Hospital weighed trapped feral cats, and found the average feral adult " + "male to weigh 4 kg(9 lb), and average adult female 3 kg(7 lb).[61] Cats average about " + "23–25 cm(9–10 in) in height and 46 cm(18 in) in head / body length(males being larger than females), " + "with tails averaging 30 cm(12 in) in length;[62] feral cats may be smaller on average.ats have seven" + " cervical vertebrae, as do almost all mammals; 13 thoracic vertebrae(humans have 12); seven lumbar" + " vertebrae(humans have five); three sacral vertebrae like most mammals(humans have five);" + " and a variable number of caudal vertebrae in the tail(humans have only vestigial caudal" + " vertebrae, fused into an internal coccyx).[63]:11 The extra lumbar and thoracic vertebrae" + " account for the cat's spinal mobility and flexibility. Attached to the spine are 13 ribs," + " the shoulder, and the pelvis.[63] :16 Unlike human arms, cat forelimbs are attached to the" + " shoulder by free-floating clavicle bones which allow them to pass their body through any" + " space into which they can fit their head.[64]", }; foreach (var plaintextString in plaintexs) { var plaintex = Encoding.ASCII.GetBytes(plaintextString); var ciphertext = Symmetric.Encrypt(key, plaintex); var decrypted = Symmetric.Decrypt(key, ciphertext); if (!plaintex.SequenceEqual(decrypted)) { throw new Exception("Decrypt did not work"); } } } [Fact] public void TestHashOutputHashOutput() { var message1 = Encoding.ASCII.GetBytes("hello"); var message2 = Encoding.ASCII.GetBytes("how are you good sir?"); var message3 = Encoding.ASCII.GetBytes("sure thing"); var h1 = new Hash(32); h1.Write(message1); h1.Write(message2); // this should not affect the state h1.Sum(); h1.Write(message3); var out1 = h1.Sum(); var h2 = new Hash(32); h2.Write(message1); h2.Write(message2); h2.Write(message3); var out2 = h2.Sum(); if (!out1.SequenceEqual(out2)) { throw new Exception("Sum function affects the hash state"); } } [Fact] public void TestTupleHash() { var message1 = Encoding.ASCII.GetBytes("the plasma"); var message2 = Encoding.ASCII.GetBytes("screen is broken, we need to do something about it!"); var message3 = Encoding.ASCII.GetBytes( "\x00\x01\x02\x03\x04\x05\x00\x01\x02\x03\x04\x05\x00\x01\x02\x03" + "\x04\x05\x00\x01\x02\x03\x04\x05\x00\x01\x02\x03\x04\x05\x00\x01\x02\x03\x04\x05"); var message4 = Encoding.ASCII.GetBytes( "HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAH" + "AHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA" + "HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAH" + "AHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA" + "HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA" + "HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA" + "HAHAHAHAHAHAHAHAHAHAHAHAHA"); // trying with NewHash with streaming and without streaming var h1 = new Hash(32); h1.Write(message1); h1.Write(message2); h1.Write(message3); var out1 = h1.Sum(); var h2 = new Hash(32); h2.WriteTuple(message1); h2.WriteTuple(message2); h2.WriteTuple(message3); var out2 = h2.Sum(); if (out1.SequenceEqual(out2)) { throw new Exception("Tuple hashing should be different from stream hashing"); } // trying a hybrid with streaming var h3 = new Hash(32); h3.WriteTuple(message1); h3.Write(message2); h3.Write(message3); h3.WriteTuple(message4); var out3 = h3.Sum(); var h4 = new Hash(32); h4.WriteTuple(message1); h4.WriteTuple(message2.Concat(message3).ToArray()); h4.WriteTuple(message4); var out4 = h4.Sum(); if (!out3.SequenceEqual(out4)) { throw new Exception("Tuple hashing doesn't work properly with streaming"); } } [Fact] public void TestEncryptDecryptAndAuthenticate() { var key = "eda8506c1fb0bbcc3f62626fef074bbf2d09a8c7c608f3fa1482c9a625d00f75".ToByteArray(); var plaintexs = new[] { "", "a", "ab", "abc", "abcd", "short", "hello, how are you?", "this is very short", "this is very long though, like, very very long, should we test very very long things here?", "Domestic cats are similar in size to the other members of the genus Felis, typically weighing " + "between 4 and 5 kg (9 and 10 lb).[36] Some breeds, such as the Maine Coon, can occasionally " + "exceed 11 kg (24 lb). Conversely, very small cats, less than 2 kg (4 lb), have been reported.[59] " + "The world record for the largest cat is 21 kg(50 lb).[60][self - published source] " + "The smallest adult cat ever officially recorded weighed around 1 kg(2 lb).[60] " + "Feral cats tend to be lighter, as they have more limited access to food than house cats." + "The Boston Cat Hospital weighed trapped feral cats, and found the average feral adult " + "male to weigh 4 kg(9 lb), and average adult female 3 kg(7 lb).[61] Cats average about " + "23–25 cm(9–10 in) in height and 46 cm(18 in) in head / body length(males being larger than females), " + "with tails averaging 30 cm(12 in) in length;[62] feral cats may be smaller on average.ats have seven" + " cervical vertebrae, as do almost all mammals; 13 thoracic vertebrae(humans have 12); seven lumbar" + " vertebrae(humans have five); three sacral vertebrae like most mammals(humans have five);" + " and a variable number of caudal vertebrae in the tail(humans have only vestigial caudal" + " vertebrae, fused into an internal coccyx).[63]:11 The extra lumbar and thoracic vertebrae" + " account for the cat's spinal mobility and flexibility. Attached to the spine are 13 ribs," + " the shoulder, and the pelvis.[63] :16 Unlike human arms, cat forelimbs are attached to the" + " shoulder by free-floating clavicle bones which allow them to pass their body through any" + " space into which they can fit their head.[64]", }; var ads = new[] { "blou blou", "a", "haahahAHAHAHhahaHAHAHahah so funny", "you must be fun at parties", "this is insanely long oh lala voulait dire le boulanger. C'est a dire que. Je ne sais pas. Merci.", "do I really need to do this? This is not fun anymore. Help me please. I am stuck in a keyboard and nobody knows I am here. This is getting quite uncomfortable", "bunch of \x00 and stuff \x00 you know", "89032", "9032ir9032kf9032fk093fewk90 fkwe09fk 903i2r 0932ir 0932ir 3029ir 230rk we0rkwe 09rkwer9 w0ekrw e09rkwe 09rew", "", "4815162342" }; for (var plaintextIndex = 0; plaintextIndex < plaintexs.Length; plaintextIndex++) { var plaintex = Encoding.ASCII.GetBytes(plaintexs[plaintextIndex]); var ad = Encoding.ASCII.GetBytes(ads[plaintextIndex]); var ciphertext = Symmetric.EncryptAndAuthenticate(key, plaintex, ad); var decrypted = Symmetric.DecryptAndAuthenticate(key, ciphertext, ad); if (!plaintex.SequenceEqual(decrypted)) { throw new Exception("Decrypt did not work"); } } } } }
2f1b4a8fdc5a2454f7614d4f8c08d6afc4180c2a
C#
asafgunay/dotnet-core-kodluyoruz-2019-2
/console-uygulama-ornegi/ConsoleApp/Models/Bike.cs
2.734375
3
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp.Models { public class Bike : Vehicle { public Bike() { // bos constructor } public Bike(string brand, string modelName, double price, bool hasBasket) { Brand = brand; ModelName = modelName; Tires = 2; Price = price; HasBasket = hasBasket; } public bool HasBasket { get; set; } } }
7f0cd35bd101d0417683e30207be11e7d1f4d99a
C#
shendongnian/download4
/code8/1359158-36822228-116485491-2.cs
2.734375
3
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { int dataLength = _serialPort.BytesToRead; byte[] data = new byte[dataLength]; int nbrDataRead = _serialPort.Read(data, 0, dataLength); if (nbrDataRead == 0) return; // Send data to api string str = Encoding.ASCII.GetString(e.Data); if (!string.IsNullOrEmpty(str)) { var api = new HttpClient(); api.BaseUrl("http://somewhere.com"); api.PostAsJsonAsync("api/Something", str) } if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, // and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler<SerialDataEventArgs>( _spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } } // i think this can go completely ... void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e)
5b0d7a8667b212e6a0aef86e1f05a609c640a85c
C#
Mee7891/MyFirstCSWinApplication
/MathUtils.cs
3.65625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyFirstCSWinApplication { static class MathUtils { public static void SimpleFactors(int n, bool repets, IPrinterEnumerable<int> printer) { List<int> factors = new List<int>(); //Простой алгоритм //int i = 2; //while (i < n) //{ // while (n % i == 0) // { // if(repets || factors.Count==0 || factors.Last()!=i) // factors.Add(i); // n = n / i; // } // i++; //} //Усовершенствованный //Вначале разбираемся с четными множителями, простой из которых только 2 while (n % 2 == 0) { if (repets || factors.Count == 0) factors.Add(2); n /= 2; } int i = 3; int max_factor = (int)Math.Sqrt(n); //смысл считать есть только до корня включительно while (i <= max_factor) { while (n % i == 0) { if (repets || factors.Count == 0 || factors.Last() != i) factors.Add(i); n /= i; max_factor = (int)Math.Sqrt(n); } i += 2; } if (n > 1) factors.Add(n); printer.PrintEnumerable(factors); } public static void Swap<T>(ref T a, ref T b) { T temp = a; a = b; b = temp; } public static void Swap<T>(T a, T b) { T temp = a; a = b; b = temp; } } }
0e46e406238527f2fd1a18f57aebb62b902108aa
C#
razvansdira/C-Sharp-For-Loop
/Exercise52.cs
3.71875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace C_Sharp_For_Loop { class Exercise52 { public static void Main() { int x, y, z, n; double sum = 0, tn, gpn; Console.Write(" Input the first number of the GP series: "); x = Convert.ToInt32(Console.ReadLine()); Console.Write("Input the number or terms in the GP series: "); n = Convert.ToInt32(Console.ReadLine()); Console.Write(" Input the common ratio of GP series: "); y = Convert.ToInt32(Console.ReadLine()); Console.Write("The numbers for the GP series: "); Console.Write("1 "); for (z = 1; z <= n; z++) { gpn = Math.Pow(y, z); Console.Write("{0} ", gpn); } sum = (x * (1 - (Math.Pow(y, n + 1)))) / (1 - y); tn = x * (Math.Pow(y, n - 1)); Console.Write("\n The tn terms of GP: {0} ", tn); Console.Write("\nThe sum of the GP series: {0} ", sum); Console.ReadLine(); } } }
83e781aea6da2182b4e40eabefffea1db0cba3a2
C#
Luminisc/ConcurrentLogger
/AvaloniaMVVM/AvaloniaMVVM/Kernels/HistogramKernels.cs
2.828125
3
using ILGPU; namespace AvaloniaMVVM.Kernels { public class HistogramKernels { public static void StandardDeviation(Index index, ArrayView<double> result, ArrayView3D<short> input) { long sum = 0; var band = input.GetSliceView(index).AsLinearView(); for (int i = 0; i < band.Length; i++) { sum += band[i]; } double mean = sum / band.Length; double dividend = 0; for (int i = 0; i < band.Length; i++) { dividend += XMath.Pow(band[i] - mean, 2); } result[index] = XMath.Sqrt(dividend / band.Length); } public static void CalculateDeviationImage(Index index, ArrayView2D<short> result, ArrayView<double> input, double imageWidth, double imageHeight, int maxDeviation) { int x = (int)(imageWidth * (index.X / (double)input.Length)); int y = (int)(imageHeight * (input[index] / (double)maxDeviation)); for (int i = 0; i < result.Height; i++) { result[x, result.Height - i - 1] = i > y ? short.MaxValue : (short)0; } } public static void CalculateHistogram(Index3 index, ArrayView<int> result, ArrayView3D<short> input) { var val = input[index]; if (val < 0) val = 0; Atomic.Add(ref result[(int)val], 1); } public static void CalculateHistogramImage(Index index, ArrayView2D<short> result, ArrayView<int> input, double imageWidth, double imageHeight, int max) { if (index.X == 0) // because zeroes is too huge, and not interesting for histogram image return; imageHeight--; int x = (int)(imageWidth * (index.X / (double)input.Length)); int y = (int)(imageHeight * (input[index] / (double)max)); for (int i = 0; i < result.Height; i++) { result[x, result.Height - i - 1] = i > y ? short.MaxValue : (short)0; } } } }
bf1b4638fb35d4bd848362e0864121843f3fb608
C#
TotalerBob/honeybadger
/honeybadgersOCR/Program.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace honeybadgersOCR { class Program { static void Main(string[] args) { string imageFilePath = @"C:\Users\sabin\Desktop\honeybadger\coupon\1.PNG"; if (File.Exists(imageFilePath)) { // Call the REST API method. Console.WriteLine("\nWait a moment for the results to appear.\n"); Rest.MakeOCRRequest(imageFilePath).Wait(); } else { Console.WriteLine("\nInvalid file path"); } Console.WriteLine("\nPress Enter to exit..."); Console.ReadLine(); } } }
61d8720aa2dde3078abb3f6312e68d0e4b45fe86
C#
PauloTessarolliJr/Calc
/Zero Funcoes/WindowsFormsApplication1/NewtonMod.cs
2.890625
3
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using YAMP; namespace WindowsFormsApplication1 { class NewtonMod { private NumberStyles style; private CultureInfo culture; private Parser p; private string func; private double x1, erro, x, e, der; private bool testeEntrada = true; private double fx; private Value v; public NewtonMod(string func, string x, string erro) { style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; culture = CultureInfo.CreateSpecificCulture("en-GB"); this.func = func; if (!double.TryParse(x, style, culture, out this.x)) testeEntrada = false; if (!double.TryParse(erro, style, culture, out this.erro)) testeEntrada = false; if (!testeEntrada) System.Windows.Forms.MessageBox.Show("Entrada Invalida"); if (string.IsNullOrEmpty(func)) { System.Windows.Forms.MessageBox.Show("Entrada Invalida"); testeEntrada = false; } } private bool tryParse() { try { p = Parser.Parse(this.func); return true; } catch { return false; } } public string Calcula() { der = x; if (testeEntrada) { if (!this.tryParse()) { System.Windows.Forms.MessageBox.Show("Incompatível"); return null; } Parser.AddCustomConstant("x", x); v = p.Execute(); double.TryParse(v.ToString(), style, culture, out fx); do { Derivada d = new Derivada(func); x1 = x - fx / d.Calcula(der); e = Math.Abs((x1 - x) / (Math.Max(1, x1))); x = x1; } while (erro > e); return x.ToString(); } return null; } } }
1831599398fa799978514deffad95cd743ad9047
C#
OSUGameDev/Invaders
/GameCode/Invaders/Assets/Scripts/Spawner.cs
3.203125
3
using UnityEngine; public class Spawner : MonoBehaviour { [SerializeField] private GameObject[] enemies; // a list of types of enemies the spawner can spawn (e.g., astroid, alian1, alian2, etc.). [SerializeField] private int spawnRateMax; [SerializeField] private int spawnRateMin; [SerializeField] private float speed; //the speed at which the enemies move after getting spawned. private float timeTilNextSpawn; // Use this for initialization void Start () { resetTimeTilNextSpawn(); } // Update is called once per frame void Update () { timeTilNextSpawn -= Time.deltaTime; //this is a basic countdown timer that will make the timeTilNextSpawn variable // countdown in seconds. if(timeTilNextSpawn <= 0) //when the countdown timer gets to zero, spawn a new enemy. { System.Random rnd = new System.Random(); //creats a random number generator int index = rnd.Next(0,enemies.Length); //get a random integer between zero and the number of different types of enemies. //creates the enemy at this objects position and rotation, then applies force to the enemies rigidbody downwards. Instantiate(enemies[index], this.transform.position, this.transform.rotation).GetComponent<Rigidbody2D>().AddForce((-this.transform.up)* speed); resetTimeTilNextSpawn(); //resets the clock to a new random amount of time between the max and min. } } /// <summary> /// resets the time until next spawn to a random number between spawnRateMin and spawnRateMax. /// </summary> void resetTimeTilNextSpawn(){ timeTilNextSpawn = Random.value * spawnRateMax + spawnRateMin; } }
f2c17449a36c4af660d1eb8c342b52f6b960c30a
C#
CliffordSix/2.5Platformer
/Assets/Behaviours/Triggers/Trigger.cs
2.546875
3
using UnityEngine; using UnityEngine.Events; using System.Collections; public abstract class Trigger : MonoBehaviour { public bool oneShot = false; public bool inverted = false; [SerializeField] UnityEvent onActivated; [SerializeField] UnityEvent onDeactivated; bool lastResult = false; protected abstract bool CheckActive(); protected virtual void LateUpdate() { bool active = IsActive(); if (JustActivated()) onActivated.Invoke(); if (JustDeactivated()) onDeactivated.Invoke(); lastResult = active; } public bool IsActive() { bool result = CheckActive(); if(oneShot) { if (oneShot && lastResult) { result = true; } else if (oneShot && !lastResult) { result = CheckActive(); } } if (inverted) result = !result; return result; } public bool JustActivated() { bool active = IsActive(); return active && lastResult != active; } public bool JustDeactivated() { bool active = IsActive(); return !active && lastResult != active; } }
d892319d402767ec34c2305dc4d1f6e2b710cd88
C#
MinBek/SOS21GB
/Vecka1/InputOutput/Exercise02.cs
3.390625
3
using System; namespace Vecka1.InputOutput { static class Exercise02 { public static void Solution() { // Skriv ut Hej och ditt namn på separata rader. Console.WriteLine("2. Greeting - Separate lines"); Console.Write("Enter your name: "); string name = Console.ReadLine(); Console.WriteLine("Hej"); Console.WriteLine(name); } } }
10e381e353b679599abfaa81ff9ff83dcce5e00d
C#
Pbinh1101/.NetFramework-N1
/BasicWinForm/frmTimer.cs
2.734375
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 BasicWinForm { public partial class frmTimer : Form { public frmTimer() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { if (totalsecond == 0) { timer1.Stop(); } else { totalsecond--; lbltimer.Text = $"{totalsecond / 60 : #0}:{totalsecond % 60 :#0}"; } } int totalsecond = 0; private void btnbatdau_Click(object sender, EventArgs e) { var minute = (int)numTimer.Value; totalsecond = minute * 60; timer1.Start(); } } }
57acbc0b37e1ece0e905194c9005bb9f72f68ef7
C#
AramisIT/Lamps
/WMS client/db/Workers/dbArchitector.cs
2.734375
3
using System.Data.SqlServerCe; namespace WMS_client.db { /// <summary> </summary> public static class dbArchitector { /// <summary> Maps</summary> public static void CreateMapTable() { using (SqlCeCommand query = dbWorker.NewQuery(@"CREATE TABLE Maps( Id bigint not null, ParentId bigint not null, Description nchar(50) not null, RegisterFrom int not null, RegisterTo int not null)")) { query.ExecuteNonQuery(); } } /// <summary> </summary> public static void ClearAllDataFromTable<T>() where T : dbObject { string tableName = typeof(T).Name; using (SqlCeCommand query = dbWorker.NewQuery(string.Concat(@"DELETE FROM ", tableName))) { query.ExecuteNonQuery(); } } /// <summary> </summary> /// <param name="tableName"> </param> public static void ClearAllDataFromTable(string tableName) { using (SqlCeCommand query = dbWorker.NewQuery(string.Concat(@"DELETE FROM ", tableName))) { query.ExecuteNonQuery(); } } /// <summary> </summary> public static void ClearAll() { // ClearAllDataFromTable(typeof(Maps).Name); ClearAllDataFromTable(typeof(Cases).Name); ClearAllDataFromTable(typeof(ElectronicUnits).Name); ClearAllDataFromTable(typeof(Lamps).Name); ClearAllDataFromTable(typeof(Models).Name); ClearAllDataFromTable(typeof(Party).Name); // ClearAllDataFromTable(typeof(AcceptanceOfNewComponents).Name); ClearAllDataFromTable(typeof(AcceptanceOfNewComponentsDetails).Name); //³ ... ClearAllDataFromTable(typeof(SendingToCharge).Name); ClearAllDataFromTable(typeof(SubSendingToChargeChargeTable).Name); ClearAllDataFromTable(typeof(SendingToExchange).Name); ClearAllDataFromTable(typeof(SubSendingToExchangeUploadTable).Name); ClearAllDataFromTable(typeof(SendingToRepair).Name); ClearAllDataFromTable(typeof(SubSendingToRepairRepairTable).Name); // ... ClearAllDataFromTable(typeof(AcceptanceAccessoriesFromRepair).Name); ClearAllDataFromTable(typeof(SubAcceptanceAccessoriesFromRepairRepairTable).Name); ClearAllDataFromTable(typeof(AcceptanceAccessoriesFromExchange).Name); ClearAllDataFromTable(typeof(AcceptanceAccessoriesFromExchangeDetails).Name); ClearAllDataFromTable(typeof(SubAcceptanceAccessoriesFromExchangeExchange).Name); // ClearAllDataFromTable(typeof(Movement).Name); } } }
f9e59183fd227933fa6741e0aa53eaa262da9e08
C#
tddold/Telerik-Academy-Homeworks
/OOP/DefiningClassesPartTwoHomework/Attributes/VersionAttribute.cs
3.421875
3
namespace Attributes { using System; [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Method, AllowMultiple = false)] public class VersionAttribute : Attribute { public VersionAttribute(string version) { this.Version = version; } public string Version { get; private set; } public static void Main() { Type type = typeof(TestClass); object[] a = type.GetCustomAttributes(false); foreach (VersionAttribute item in a) { Console.WriteLine("Version: {0}", item.Version); } } } }
2057cdeafd9a429aefe09ce314aa0684a9739f16
C#
Vyrdian/spaceway
/Assets/Scripts/Level Spawning/ObstaclePool.cs
2.78125
3
using System.Collections.Generic; using UnityEngine; public class ObstaclePool : MonoBehaviour { [SerializeField] private Obstacle[] _obstaclePrefabs = null; [SerializeField] private int _initialObstacles = 100; private Queue<Obstacle> _obstacles = new Queue<Obstacle>(); void Awake() => AddObstacle(_initialObstacles); private void AddObstacle(int num) { for(int i = 0; i < num; i++) { Obstacle obstacle = Instantiate(_obstaclePrefabs[Random.Range(0, _obstaclePrefabs.Length)], transform, true); obstacle.transform.SetParent(transform); obstacle.gameObject.SetActive(false); _obstacles.Enqueue(obstacle); } } public Obstacle GetObstacle() { if (_obstacles.Count == 0) AddObstacle(1); return _obstacles.Dequeue(); } public void ReturnToQueue(Obstacle obstacle) { _obstacles.Enqueue(obstacle); obstacle.gameObject.SetActive(false); } }
b3548010b767b6b4bc2b49d3dc89a3974df2c450
C#
JayArrowz/ChatApp
/ChatApp/Program.cs
3.0625
3
using DotNetty.Buffers; using System; using System.Net; using System.Text; using System.Threading.Tasks; namespace ChatApp { public class Program { static async Task Main(string[] args) { await MainAsync(); } private static async Task MainAsync() { var serverEndpoint = new IPEndPoint(IPAddress.Loopback, 5252); var server = new Server(serverEndpoint); var client = new Client(serverEndpoint); await server.BindAsync(); var channel = await client.ConnectAsync(); while (true) { Console.WriteLine("Enter message to send: "); var testMessage = Encoding.UTF8.GetBytes(Console.ReadLine()); var buffer = Unpooled.WrappedBuffer(testMessage); await channel.WriteAndFlushAsync(buffer); } } } }
987699d0687d101b3f4c511e3a6dadcac49f0a46
C#
bvsundeep/ProjectManager
/ProjectManager.Entity/Context/UnitOfWork.cs
2.546875
3
using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace ProjectManager.Entity.Context { using ProjectManager.Entity.Data; using ProjectManager.Entity.Mapping; using ProjectManager.Entity.Interface; public class UnitOfWork : DbContext, IUnitOfWork { public UnitOfWork() : base("AppDBConnectionString") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.Configurations.Add<User>(new UserMap()); modelBuilder.Configurations.Add<Project>(new ProjectMap()); modelBuilder.Configurations.Add<Task>(new TaskMap()); base.OnModelCreating(modelBuilder); } public DbSet<User> User { get; set; } public DbSet<Project> Project { get; set; } public DbSet<Task> Task { get; set; } public override int SaveChanges() { return base.SaveChanges(); } } }
9505d7663edcd0ea19738f32fa41ba86a4deeeb7
C#
deryaunver/BasicProgramming
/Inheritance/Program.cs
3.3125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Inheritance { class Program { static void Main(string[] args) { Person[] people = new Person[3] { new Person { FirstName="Derya" },new Customer { FirstName="Seyma" },new Student { FirstName="Duygu" } }; foreach (var person in people) { Console.WriteLine(person.FirstName); } Console.ReadKey(); } } class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } class Customer:Person { public string Adress { get; set; } } class Student:Person { public string Departmant { get; set; } } }
f1688f8b22d4ea3d15afc901fa2b9fd83bfd3075
C#
pugking9/SquetBot
/SquetBot/Helpers/MusicHelper.cs
3
3
using System; using System.Threading.Tasks; using YoutubeExplode; using YoutubeExplode.Videos.Streams; namespace SquetBot.Helpers { // Track class to store track information public class Track { public string Title { get; set; } public string Url { get; set; } public string StreamUrl { get; set; } public Track(string title, string url, string streamUrl) { Title = title; Url = url; StreamUrl = streamUrl; } } internal class MusicHelper { //Determine if url or search term public static bool IsUrl(string input) { return Uri.TryCreate(input, UriKind.Absolute, out Uri? uriResult) && (uriResult?.Scheme == Uri.UriSchemeHttp || uriResult?.Scheme == Uri.UriSchemeHttps); } //Determine which platform the url is from, return stream url /*public static string GetStreamUrl(string input) { }*/ //Search for track on youtube, return stream url public static async Task<string?> SearchYoutubeAsync(string input) { var youtube = new YoutubeClient(); var video = await youtube.Videos.GetAsync(input); var streamManifest = await youtube.Videos.Streams.GetManifestAsync(video.Id); var streamInfo = streamManifest.GetAudioOnlyStreams().GetWithHighestBitrate(); if (streamInfo == null) { return null; } return streamInfo.Url; } } }
0cf365b32e3a414cbb442ab6167fbb360dea1f96
C#
edornd/lockstep-sample
/Assets/Simulation/Network/NetServer.cs
2.828125
3
using LiteNetLib; using LiteNetLib.Utils; using System; using System.Collections.Generic; namespace Game.Network { /// <summary> /// Wrapper around NetManager, inheriting from NetBase and implementing a simple network server. /// </summary> public class NetServer : NetBase { #region Private variables private List<NetPeer> clients; private Queue<NetMessage> outputMessages; private int listenPort; private bool ready; #endregion #region Constructors public NetServer(int port, NetConfig config) : this(port, 8, config) { } public NetServer(int port, int maxConnections, NetConfig config) : base (maxConnections, config){ outputMessages = new Queue<NetMessage>(); clients = new List<NetPeer>(); listenPort = port; ready = false; } #endregion #region Public methods /// <summary> /// Starts the server by initializing the network on the given port. /// </summary> public void Start() { network.Start(listenPort); ready = true; } /// <summary> /// Listens to the network events. /// </summary> public void Listen() { if (ready) { network.PollEvents(); } } /// <summary> /// Stops the server by stopping the net manager. /// </summary> public void Stop() { clients.Clear(); network.Stop(); ready = false; } /// <summary> /// Checks whether the server is currently ready to work or not. /// </summary> /// <returns>true if is ready, false otherwise</returns> public bool IsReady() { return ready; } /// <summary> /// Adds a message to be sent during the next game server update. /// </summary> /// <param name="message">message to be sent</param> public void AddOutputMessage(NetMessage message) { outputMessages.Enqueue(message); } /// <summary> /// Sends to everybody, except for the client specified into the message instance. /// </summary> /// <param name="message">message to be sent</param> public void AddMessageExcluding(PacketBase packet, NetPeer excluded) { if (excluded != null) { foreach (NetPeer client in clients) { if (client != excluded) AddOutputMessage(new NetMessage(packet, client)); } } else { AddOutputMessage(new NetMessage(packet, null)); } } /// <summary> /// Sends every message in the output queue. /// </summary> public void SendMessages() { if (!ready) { NetUtils.DebugWriteError("Server not ready!"); return; } while (outputMessages.Count > 0) { Send(outputMessages.Dequeue()); } } /// <summary> /// Disconnect the given client fro mthe server, sending the extra info. /// </summary> /// <param name="peer">client to disconnect</param> /// <param name="extra">serialized extra info</param> public void Disconnect(NetPeer peer, byte[] extra) { network.DisconnectPeer(peer, extra); } #endregion #region Private methods /// <summary> /// Sends the message to a single client, or to every client if it's not specified. /// </summary> /// <param name="message"></param> private void Send(NetMessage message) { if (message.Client != null) { Send(message.Client, message.Packet); } else { foreach (NetPeer client in clients) { Send(client, message.Packet); } } } /// <summary> /// Sends raw data to the given client by serializing the packet. /// This function uses the reliable channel. /// </summary> /// <param name="client">receiver</param> /// <param name="packet">data to be sent</param> private void Send(NetPeer client, PacketBase packet) { writer.Reset(); packet.Serialize(writer); client.Send(writer, SendOptions.ReliableOrdered); } #endregion #region EventListener implementation public override void OnPeerConnected(NetPeer peer) { clients.Add(peer); HandleEvent(NetPacketType.PeerConnect, peer, new NetEventArgs()); } public override void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) { clients.Remove(peer); HandleEvent(NetPacketType.PeerDisconnect, peer, new NetEventArgs(disconnectInfo)); } public override void OnNetworkError(NetEndPoint endPoint, int socketErrorCode) { HandleEvent(NetPacketType.NetError, null, new NetEventArgs(socketErrorCode)); } public override void OnNetworkReceive(NetPeer peer, NetDataReader reader) { NetPacketType type = (NetPacketType)reader.GetUShort(); HandleEvent(type, peer, new NetEventArgs(reader)); } public override void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType) { NetUtils.DebugWrite(ConsoleColor.Black,"[SERVER] Received data from unconnected peer, type: " + messageType); } public override void OnNetworkLatencyUpdate(NetPeer peer, int latency) { //HandleEvent(NetPacketType.PeerLatency, peer, new NetEventArgs(latency)); } #endregion } }
493cae19ca57ef3885f44d167da8d8123ceec03a
C#
jjmv/EstudioC-
/Funciones/Funciones/functions.cs
3.453125
3
namespace Funciones { class functions { static void Main(string[] args) { double Base = 5, Altura = 7.5; double area = Rectangulo(Base, Altura); System.Console.WriteLine(area); System.Console.ReadKey(); }//Fin del metodo Main public static double Rectangulo(double Base, double Altura) { double resultado = Base * Altura; return resultado; }//Fin de la funcion Rectangulo() }//Fin de la clase functions }//Fin del namespace
5d37ed6e9857cac984b0f00c7350680c289e1ab6
C#
FernandoVelcic/tp2014-gdd-los-normalizadores
/src/FrbaHotel/Models/Reservas/Estadia.cs
2.546875
3
using MyActiveRecord; using System; using System.Collections.Generic; using System.Linq; using System.Text; using FrbaHotel.Models.Exceptions; namespace FrbaHotel.Models { public class Estadia : ActiveRecord { public override String table { get { return "estadias"; } } public Reserva reserva { get; set; } public String fecha_inicio { get; set; } public int cant_noches { get; set; } public int cantidad_maxima_personas() { return reserva.cantidad_maxima_personas(); } public override void preSave() { if (String.IsNullOrEmpty(fecha_inicio)) { throw new ValidationException("La fecha de inicio es obligatoria"); } } } }
c64c2216fd0b247503c3987d8d613f765042a036
C#
baturayp/SpaceTow
/Assets/Scripts/SongInfo.cs
2.515625
3
using System.Collections.Generic; using System.Linq; using UnityEngine; [CreateAssetMenu(menuName = "Song Info")] public class SongInfo : ScriptableObject { [Header( "Set relevant song audio clip" )] public AudioClip song; [Header( "Set relevant song json" )] public TextAsset json; public string songTitle; [HideInInspector] public float songOffset; [Header("Meteor appear offsets")] public Tempo[] appearTime; [Header("Just for reference, notes populated automatically, edit them from NoteEditor")] public Track[] tracks = new Track[4]; [Header("When to finish scene shows up, in seconds")] public float endTime; [System.Serializable] public class JsonData { public string name; public int BPM; public int offset; public JsonNote[] notes; } [System.Serializable] public class JsonNote { public int LPB; public int num; public int block; } // {note class} [System.Serializable] public class Note { public float dueTo; public int track; } [System.Serializable] public class Track { public Note[] notes; } // you can change tempo over time if needed [System.Serializable] public class Tempo { public float startTime; public float offsetVal; } private static JsonData FromJson(string json) { var jsonData = JsonUtility.FromJson<JsonData>(json); return jsonData; } public void OnEnable() { var jsonData = FromJson(json.ToString()); var jsonNotes = jsonData.notes.ToList(); var notes = new List<Note>(); songOffset = jsonData.offset == 0 ? 0 : 1f - (44100f - jsonData.offset) / 44100f; if (string.IsNullOrEmpty(songTitle)) { songTitle = jsonData.name; } foreach (var jsonNote in jsonNotes) { notes.Add(ToAsset(jsonNote, jsonData.BPM, jsonNote.block)); } var track0 = notes.Where(note => note.track == 0).ToList(); tracks[0].notes = track0.ToArray(); var track1 = notes.Where(note => note.track == 1).ToList(); tracks[1].notes = track1.ToArray(); var track2 = notes.Where(note => note.track == 2).ToList(); tracks[2].notes = track2.ToArray(); var track3 = notes.Where(note => note.track == 3).ToList(); tracks[3].notes = track3.ToArray(); } private static Note ToAsset(JsonNote note, int bpm, int track) { var noteAsset = new Note { dueTo = track >= 2 ? (float)note.num / note.LPB / (bpm / 60f) + 0.1f : (float)note.num / note.LPB / (bpm / 60f), track = track }; return noteAsset; } }
ec0050080330c20a49974c59476d0c1f02aba578
C#
Gaharit/C-Sharp
/Chess/Chess/Program.cs
3.671875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chess { class Program { static void ChessTest(string position1, string position2) { Console.WriteLine("\nPossibility of this turn:\n"); Console.Write("For bishop: "); if (BishopTest(position1, position2)) Console.WriteLine("possible"); else Console.WriteLine("impossible"); Console.Write("For knight: "); if (KnightTest(position1, position2)) Console.WriteLine("possible"); else Console.WriteLine("impossible"); ; Console.Write("For rook: "); if (RookTest(position1, position2)) Console.WriteLine("possible"); else Console.WriteLine("impossible"); Console.Write("For queen: "); if (RookTest(position1, position2) || BishopTest(position1, position2)) Console.WriteLine("possible"); else Console.WriteLine("impossible"); Console.Write("For king: "); if (KingTest(position1, position2)) Console.WriteLine("possible"); else Console.WriteLine("impossible"); } static bool BishopTest(string position1, string position2) { return (Math.Abs(position2[0] - position1[0]) == Math.Abs(position2[1] - position1[1]) && (position2[0] - position1[0]) * (position2[1] - position1[1]) != 0); } static bool KnightTest(string position1, string position2) { return (Math.Abs(position2[0] - position1[0]) == 2 && Math.Abs(position2[1] - position1[1]) == 1 || Math.Abs(position2[0] - position1[0]) == 1 && Math.Abs(position2[1] - position1[1]) == 2); } static bool RookTest(string position1, string position2) { return (position2[0] == position1[0] ^ position2[1] == position1[1]); } static bool KingTest(string position1, string position2) { return (Math.Max(Math.Abs(position2[0] - position1[0]), Math.Abs(position2[1] - position1[1])) == 1); } static bool CheckInput(string position) { if (position[0] < 'a' || position[0] > 'h' || position[1] < '1' || position[1] > '8') return false; return true; } static void Main(string[] args) { Console.WriteLine("Enter position 1 and position 2: "); string[] input = Console.ReadLine().Split(' '); if (!CheckInput(input[0]) || !CheckInput(input[1])) { Console.WriteLine("Wrong input."); Console.ReadKey(); return; } ChessTest(input[0], input[1]); Console.ReadKey(); } } }
a2b17d951dbb63007f30a7ab293436aa96156bf6
C#
DrShushen/RBush
/RBush.SpeedTest/RBushSpeedTest.cs
3.140625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // using System.Threading; using RBush; namespace RBush.SpeedTest { public class Item : ISpatialData { private readonly Envelope _envelope; public Item(double minX, double minY, double maxX, double maxY) { _envelope = new Envelope(minX, minY, maxX, maxY); } public ref readonly Envelope Envelope { get { return ref _envelope; } } } public static class ItemListGenerator { static Random _random = new Random(); private static Item generateItem(double scale) { List<double> points = new List<double>() { _random.NextDouble() * scale, _random.NextDouble() * scale, _random.NextDouble() * scale, _random.NextDouble() * scale }; points.Sort(); return new Item(points[0], points[2], points[1], points[3]); } public static IEnumerable<Item> GenerateItems(int numberOfItems, double spaceScale) { List<Item> result = new List<Item>(numberOfItems); for (int i = 0; i < numberOfItems; i++) { result.Add(generateItem(spaceScale)); } return result.AsEnumerable(); } } public class RBushSpeedTester { public void RunTest(string name, int itemCount, Action execute) { long elapsedMs = 0; var watch = System.Diagnostics.Stopwatch.StartNew(); Console.Write(String.Format("{0:n0}", itemCount) + " items: " + name + "... "); watch.Reset(); watch.Start(); execute(); watch.Stop(); elapsedMs = watch.ElapsedMilliseconds; Console.Write("Time (ms): " + String.Format("{0:n0}", elapsedMs)); Console.WriteLine(); } public void RunTestGroup(int maxEntries, int numberOfItems) { RBush<Item> rBush = new RBush<Item>(maxEntries); double spaceScale = 50; IEnumerable<Item> items = ItemListGenerator.GenerateItems(numberOfItems, spaceScale); Console.WriteLine("maxEntries = " + maxEntries); // Tests: RunTest("BulkLoad", numberOfItems, () => { rBush.BulkLoad(items); }); RunTest("Search OLD", numberOfItems, () => { rBush.Search_Old(); }); RunTest("Search NEW", numberOfItems, () => { rBush.Search(); }); RunTest("Search envelope (Inf. bounds) OLD", numberOfItems, () => { rBush.Search_Old(Envelope.InfiniteBounds); }); RunTest("Search envelope (Inf. bounds) NEW", numberOfItems, () => { rBush.Search(Envelope.InfiniteBounds); }); RunTest("Iterate through IEnumerable [for comparison]", numberOfItems, () => { foreach (Item i in items) { } }); Console.ReadLine(); } } class RBushSpeedTest { static void Main(string[] args) { RBushSpeedTester tester = new RBushSpeedTester(); tester.RunTestGroup(9, 10000); tester.RunTestGroup(9, 50000); tester.RunTestGroup(9, 100000); tester.RunTestGroup(16, 10000); tester.RunTestGroup(16, 100000); tester.RunTestGroup(16, 200000); tester.RunTestGroup(32, 10000); tester.RunTestGroup(32, 100000); tester.RunTestGroup(32, 500000); //tester.RunTestGroup(32, 1000000); // Slowest. } } }
3409687e627aa650a1b9b698f5e4fdec1185aa83
C#
ThyWoof/VGAudio
/src/VGAudio/Utilities/BitWriter.cs
3.109375
3
using System; using System.Diagnostics; namespace VGAudio.Utilities { public class BitWriter { public byte[] Buffer { get; } public int LengthBits { get; } public int Position { get; set; } public int Remaining => LengthBits - Position; public BitWriter(byte[] buffer) { Buffer = buffer; LengthBits = Buffer.Length * 8; } public void AlignPosition(int multiple) { int newPosition = Helpers.GetNextMultiple(Position, multiple); int bits = newPosition - Position; Write(0, bits); } public void Write(int value, int bitCount) { Debug.Assert(bitCount >= 0 && bitCount <= 32); if (bitCount > Remaining) { throw new InvalidOperationException("Not enough bits left in output buffer"); } int byteIndex = Position / 8; int bitIndex = Position % 8; if (bitCount <= 9 && Remaining >= 16) { int outValue = ((value << (16 - bitCount)) & 0xFFFF) >> bitIndex; Buffer[byteIndex] |= (byte)(outValue >> 8); Buffer[byteIndex + 1] = (byte)outValue; } else if (bitCount <= 17 && Remaining >= 24) { int outValue = ((value << (24 - bitCount)) & 0xFFFFFF) >> bitIndex; Buffer[byteIndex] |= (byte)(outValue >> 16); Buffer[byteIndex + 1] = (byte)(outValue >> 8); Buffer[byteIndex + 2] = (byte)outValue; } else if (bitCount <= 25 && Remaining >= 32) { int outValue = (int)(((value << (32 - bitCount)) & 0xFFFFFFFF) >> bitIndex); Buffer[byteIndex] |= (byte)(outValue >> 24); Buffer[byteIndex + 1] = (byte)(outValue >> 16); Buffer[byteIndex + 2] = (byte)(outValue >> 8); Buffer[byteIndex + 3] = (byte)outValue; } else { WriteFallback(value, bitCount); } Position += bitCount; } private void WriteFallback(int value, int bitCount) { int byteIndex = Position / 8; int bitIndex = Position % 8; while (bitCount > 0) { if (bitIndex >= 8) { bitIndex = 0; byteIndex++; } int toShift = 8 - bitIndex - bitCount; int shifted = toShift < 0 ? value >> -toShift : value << toShift; int bitsToWrite = Math.Min(bitCount, 8 - bitIndex); int mask = ((1 << bitsToWrite) - 1) << 8 - bitIndex - bitsToWrite; int outByte = Buffer[byteIndex] & ~mask; outByte |= shifted & mask; Buffer[byteIndex] = (byte)outByte; bitIndex += bitsToWrite; bitCount -= bitsToWrite; } } } }
1d2e316feffeeb690ce1fcf06245855a48eefdcd
C#
sclshu3714/Framework-Electron-CSharp
/WinformServers/Controller/Services/TimeLineServicesr.cs
2.5625
3
using JpFramework.Tools; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Net; using System.Text; namespace JpFramework { /// <summary> /// 历史记录操作类 /// </summary> public class TimeLineServicesr { /// <summary> /// 查询所有 /// </summary> /// <returns></returns> public DataTable GetTimeLine(int type) { var sql =string.Format("select id,title,remake,CONVERT(varchar(100), times, 102) from s_timeline where type='{0}' order by times asc", type); return DBHelper.GetTable(sql); } /// <summary> /// 添加 /// </summary> /// <returns></returns> public void AddTimeLine(string title,string remake,string times,string type) { var sql = "insert into s_timeline (title,remake,times,type) values ('{0}','{1}','{2}','{3}')"; sql = string.Format(sql,title, remake, times,type); DBHelper.ExecuteSql(sql); } } }
8336c517c4908488e7973f768505710bd539f770
C#
karnalta/Features-Tasks
/Features-Tasks/SuperDecimal.cs
3.5
4
using System; using System.Text; namespace Features_Tasks { /// <summary> /// Decimal number allowing a maximum value of 4,294,967,296 with up to 4,294,967,296 decimals. /// </summary> public class SuperDecimal { private readonly UInt32[] _superDecimal; private readonly int _decimalCount = 0; private readonly int _arraySize = 0; /// <summary> /// Gets the array of elements. /// </summary> /// <value> /// The array. /// </value> public UInt32[] Array { get { return _superDecimal; } } /// <summary> /// Gets the decimal count. /// </summary> /// <value> /// The decimal count. /// </value> public int DecimalCount { get { return _decimalCount; } } /// <summary> /// Gets the size of the array. /// </summary> /// <value> /// The size of the array. /// </value> public int ArraySize { get { return _arraySize; } } /// <summary> /// Initializes a new instance of the <see cref="SuperDecimal"/> class. /// </summary> /// <param name="initialValue">The initial value.</param> /// <param name="decimalCount">The decimal count.</param> public SuperDecimal(UInt32 initialValue, int decimalCount) { _decimalCount = decimalCount; _arraySize = (int)Math.Ceiling((float)decimalCount * 0.104) + 2; // Array size based on 2e32 base _superDecimal = new UInt32[_arraySize]; _superDecimal[0] = initialValue; } /// <summary> /// Assigns the value. /// </summary> /// <param name="value">The value.</param> /// <exception cref="Exception">SuperDecimal numbers provided cannot operate together.</exception> public void AssignValue(SuperDecimal value) { if (!IsValidForOperators(value)) throw new Exception("SuperDecimal numbers provided cannot operate together."); for (int i = 0; i < _arraySize; i++) { _superDecimal[i] = value.Array[i]; } } /// <summary> /// Determines whether a SuperDecimal can apply operations against another. /// </summary> /// <param name="value">The value.</param> /// <returns> /// <c>true</c> if [is valid for operators] [the specified value]; otherwise, <c>false</c>. /// </returns> public bool IsValidForOperators(SuperDecimal value) { // Cannot operate with itself if (Object.ReferenceEquals(this, value)) return false; // Have to be the same size if (value.DecimalCount != _decimalCount) return false; return true; } /// <summary> /// Determines whether this instance is zero. /// </summary> /// <returns> /// <c>true</c> if this instance is zero; otherwise, <c>false</c>. /// </returns> public bool IsZero() { foreach (UInt32 item in _superDecimal) { if (item != 0) return false; } return true; } public override string ToString() { SuperDecimal temp = new SuperDecimal(0, _decimalCount); temp.AssignValue(this); StringBuilder sb = new StringBuilder(); sb.Append(temp.Array[0]); sb.Append(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator); int digitCount = 0; while (digitCount < _decimalCount) { temp.Array[0] = 0; temp = temp * 100000; sb.AppendFormat("{0:D5}", temp.Array[0]); digitCount += 5; } return sb.ToString(); } /// <summary> /// Compute the arc tangent result. /// </summary> /// <param name="multiplicand">The multiplicand.</param> /// <param name="reciprocal">The reciprocal.</param> public SuperDecimal ArcTan(UInt32 multiplicand, UInt32 reciprocal) { SuperDecimal result = new SuperDecimal(0, _decimalCount); SuperDecimal X = new SuperDecimal(multiplicand, _decimalCount); X = X / reciprocal; reciprocal *= reciprocal; result.AssignValue(X); SuperDecimal term = new SuperDecimal(0, _decimalCount); UInt32 divisor = 1; bool subtractTerm = true; while (true) { X = X / reciprocal; term.AssignValue(X); divisor += 2; term = term / divisor; if (term.IsZero()) break; if (subtractTerm) result = result - term; else result = result + term; subtractTerm = !subtractTerm; } return result; } /// <summary> /// Implements the operator +. /// </summary> /// <param name="valueA">The value a.</param> /// <param name="valueB">The value b.</param> /// <returns> /// The result of the operator. /// </returns> /// <exception cref="Exception">SuperDecimal numbers provided cannot operate together.</exception> public static SuperDecimal operator + (SuperDecimal valueA, SuperDecimal valueB) { if (!valueA.IsValidForOperators(valueB)) throw new Exception("SuperDecimal numbers provided cannot operate together."); int index = valueA.ArraySize - 1; while (index >= 0 && valueB.Array[index] == 0) index--; UInt32 carry = 0; while (index >= 0) { UInt64 result = (UInt64)valueA.Array[index] + valueB.Array[index] + carry; valueA.Array[index] = (UInt32)result; if (result >= 0x100000000U) carry = 1; else carry = 0; index--; } return valueA; } /// <summary> /// Implements the operator -. /// </summary> /// <param name="valueA">The value a.</param> /// <param name="valueB">The value b.</param> /// <returns> /// The result of the operator. /// </returns> /// <exception cref="Exception">SuperDecimal numbers provided cannot operate together.</exception> public static SuperDecimal operator -(SuperDecimal valueA, SuperDecimal valueB) { if (!valueA.IsValidForOperators(valueB)) throw new Exception("SuperDecimal numbers provided cannot operate together."); int index = valueA.ArraySize - 1; while (index >= 0 && valueB.Array[index] == 0) index--; UInt32 borrow = 0; while (index >= 0) { UInt64 result = 0x100000000U + (UInt64)valueA.Array[index] - valueB.Array[index] - borrow; valueA.Array[index] = (UInt32)result; if (result >= 0x100000000U) borrow = 0; else borrow = 1; index--; } return valueA; } /// <summary> /// Implements the operator *. /// </summary> /// <param name="valueA">The value a.</param> /// <param name="valueB">The value b.</param> /// <returns> /// The result of the operator. /// </returns> public static SuperDecimal operator *(SuperDecimal valueA, UInt32 valueB) { int index = valueA.ArraySize - 1; while (index >= 0 && valueA.Array[index] == 0) index--; UInt32 carry = 0; while (index >= 0) { UInt64 result = (UInt64)valueA.Array[index] * valueB + carry; valueA.Array[index] = (UInt32)result; carry = (UInt32)(result >> 32); index--; } return valueA; } /// <summary> /// Implements the operator /. /// </summary> /// <param name="valueA">The value a.</param> /// <param name="valueB">The value b.</param> /// <returns> /// The result of the operator. /// </returns> public static SuperDecimal operator /(SuperDecimal valueA, UInt32 valueB) { int index = 0; while (index < valueA.ArraySize && valueA.Array[index] == 0) index++; UInt32 carry = 0; while (index < valueA.ArraySize) { UInt64 result = valueA.Array[index] + ((UInt64)carry << 32); valueA.Array[index] = (UInt32)(result / (UInt64)valueB); carry = (UInt32)(result % (UInt64)valueB); index++; } return valueA; } } }
7cf200f48eaec6da2c7dd6908be9be9b36252d5d
C#
thirumoorthysivan/MGGP
/MGGP/BAL.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MGGP { public class BAL { private string[] _listOfStatements = new string[50]; private string[] _questions = new string[15]; private string[] _decutionStatements = new string[15]; private string[] _answerList = new string[15]; private static Dictionary<string, string> _qRomans = new Dictionary<string, string>(); private static Dictionary<string, string> _qUnknownRomans = new Dictionary<string, string>(); private static Dictionary<string, int> _romans = new Dictionary<string, int>(); private static RomanToNumber _romanTonumeric = new RomanToNumber(); private static NumericToRoman _NumericToRoman = new NumericToRoman(); public void Build() { string test = _NumericToRoman.ToRoman(18999); //int value = _NumericToRoman.toNumber(test); _romans.Add("I", 1); _romans.Add("V", 5); _romans.Add("X", 10); _romans.Add("L", 50); _romans.Add("C", 100); _romans.Add("D", 500); _romans.Add("M", 1000); string endWordInStatement = string.Empty; string statement; string bstatement; int i = 0; int ds = 0; int qs = 0; do { statement = string.Empty; bstatement = Console.ReadLine(); statement = bstatement.ToUpper().Replace("PISH","VALMI82GHEE"); string[] wordsOfStatement = statement.Split(' '); _listOfStatements[i] = statement; int totalWordsInStatement = (wordsOfStatement.Length) - 1; endWordInStatement = wordsOfStatement[totalWordsInStatement].ToString().Trim().ToLower(); if (endWordInStatement == "credits") { _decutionStatements[ds] = statement; ds++; } else if (endWordInStatement == "?") { _questions[qs] = statement; qs++; } else if (isINRomans(endWordInStatement)) { if (isNotInQRomans(wordsOfStatement[0])) { _qRomans.Add(wordsOfStatement[0].ToUpper(), endWordInStatement.ToUpper()); } } i++; } while (endWordInStatement != "."); // start process decutionStatementsValues(); answerQuestion(); for (int x = 0; x < _answerList.Length; x++) { Console.Write(_answerList[x]); } string endProgram = Console.ReadLine(); if(endProgram == ".") { } } private static bool isINRomans(string roman) { bool isRoman = false; foreach (KeyValuePair<string, int> eromans in _romans) { if(eromans.Key == roman.ToUpper()) { isRoman = true; break; } } return isRoman; } private static bool isNotInQRomans(string roman) { bool isRoman = true; foreach (KeyValuePair<string, string> eromans in _qRomans) { if (eromans.Key == roman.ToUpper()) { isRoman = false; break; } } return isRoman; } private void decutionStatementsValues() { string[] splitByIs; string[] keyStatement; int creditsvalue = 0; string decutionStatement; string knownValues; double findUnKnownKeyValue; string UnknownKey; for (int i = 0; i < _decutionStatements.Length; i++) { findUnKnownKeyValue = 0; decutionStatement = string.Empty; UnknownKey = string.Empty; knownValues = string.Empty; decutionStatement = _decutionStatements[i]; if (decutionStatement != null && decutionStatement != "" && decutionStatement.Length != 0) { string[] stringSeparators = new string[] { "IS" }; splitByIs = decutionStatement.Split(stringSeparators, StringSplitOptions.None); keyStatement = splitByIs[0].Trim().Split(' '); string[] getcreditValue = splitByIs[1].Trim().Split(' '); creditsvalue = Tools.ConvertToNumeric(getcreditValue[0].ToString()); for (int j = 0; j < keyStatement.Length; j++) { if (keyStatement[j] != "" || keyStatement[j] != string.Empty) { string value = getqRomanValue(keyStatement[j].ToUpper()); if (value != null && value != string.Empty) { knownValues = knownValues + value; } else { UnknownKey = keyStatement[j].ToUpper(); } if (UnknownKey.Length > 0) { findUnKnownKeyValue = (creditsvalue / _romanTonumeric.toNumber(knownValues)); _qRomans.Add(UnknownKey, _NumericToRoman.ToRoman(Tools.ConvertToNumeric(findUnKnownKeyValue))); _qUnknownRomans.Add(UnknownKey, _NumericToRoman.ToRoman(Tools.ConvertToNumeric(findUnKnownKeyValue))); } } } } } } private string getqRomanValue(string key) { string value = string.Empty; foreach (KeyValuePair<string, string> eromans in _qRomans) { if (eromans.Key == key.ToUpper()) { value = eromans.Value; break; } } return value; } private string getqUnknownRomanValue(string key) { string value = string.Empty; foreach (KeyValuePair<string, string> eromans in _qUnknownRomans) { if (eromans.Key == key.ToUpper()) { value = eromans.Value; break; } } return value; } private void answerQuestion() { string question; string[] splitByIs; string[] questionSeprators = new string[] { "IS" }; string knownValues; int unknownValues; string CreditString; string answerStatement; for (int i = 0; i < _questions.Length; i++) { knownValues = string.Empty; unknownValues = 0; CreditString = string.Empty; answerStatement = string.Empty; question = _questions[i]; if (question != null && question.Length > 0) { string[] splitQuestion; splitByIs = question.Split(questionSeprators, StringSplitOptions.None); if (splitByIs.Length == 2) { string creditBeforeIs = splitByIs[0].Trim(); string qromansAfterIs = splitByIs[1].Trim(); string[] questionkeys = qromansAfterIs.Split(' '); string[] findCreditKey = creditBeforeIs.Split(' '); int creditBeforeIsCount = findCreditKey.Length - 1; if (findCreditKey[creditBeforeIsCount].ToString() == "CREDITS") { CreditString = "CREDITS"; } for (int j = 0; j < questionkeys.Length - 1; j++) { string value = getqRomanValue(questionkeys[j].ToUpper()); if (value != null && value != string.Empty) { string qUnknownRomanValue = getqUnknownRomanValue(questionkeys[j]); if (qUnknownRomanValue.Length > 0) { unknownValues = _romanTonumeric.toNumber(qUnknownRomanValue); } else { knownValues = knownValues + value; } if (answerStatement.Length == 0) { answerStatement = questionkeys[j]; } else { answerStatement = answerStatement + " " + questionkeys[j]; } } } int result; if (unknownValues == 0) { result = _romanTonumeric.toNumber(knownValues); } else { result = _romanTonumeric.toNumber(knownValues) * unknownValues; } _answerList[i] = answerStatement.Replace("VALMI82GHEE","PISH") + " is " + result + " " + CreditString +"\n"; } else { _answerList[i] = "I have no idea what you are talking about" + "\n"; } } } } } }
8ed000f7d69b0ba41d7f5bee8b41425275abe26a
C#
Ricardocanul7/Snake-ConsoleGame
/Snake-ConsoleGame/Datos/ConexionSQLite.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SQLite; using Snake_ConsoleGame.Modelos; namespace Snake_ConsoleGame.Datos { class ConexionSQLite { private string DatabasePath; private string DatabaseTableName; public ConexionSQLite() { DatabasePath = "Puntuaciones.sqlite"; DatabaseTableName = "Puntuaciones"; this.CrearTabla(); } // Se crea archivo y tabla en caso de no existir public void CrearTabla() { try { if(!System.IO.File.Exists(System.IO.Directory.GetCurrentDirectory() + "/" + DatabasePath)) { SQLiteConnection.CreateFile(DatabasePath); SQLiteConnection conexion = new SQLiteConnection("Data Source=" + DatabasePath + ";Version=3;"); conexion.Open(); string sql = "CREATE TABLE IF NOT EXISTS " + DatabaseTableName + "(id INTEGER PRIMARY KEY, " + "nombre VARCHAR(60) NOT NULL, " + "puntuacion INTEGER, " + "fecha TEXT)"; SQLiteCommand command = new SQLiteCommand(sql, conexion); command.ExecuteNonQuery(); conexion.Close(); command.Dispose(); } } catch(SQLiteException e) { Console.SetCursorPosition(1, 1); Console.WriteLine("ERROR CREATE TABLE - " + e.Message); Console.ReadKey(); } } public void InsertarJugador(Jugador jugador) { try { SQLiteConnection conexion = new SQLiteConnection("Data Source=" + DatabasePath + ";Version=3;"); conexion.Open(); string sql = "INSERT INTO " + DatabaseTableName + "(nombre, puntuacion, fecha)" + "values(" + "'" + jugador.Nombre + "'," + jugador.Puntuacion + "," + "'" + jugador.Fecha.ToString() + "'" + ")"; SQLiteCommand command = new SQLiteCommand(sql, conexion); command.ExecuteNonQuery(); conexion.Close(); command.Dispose(); }catch(SQLiteException e) { Console.SetCursorPosition(1, 1); Console.WriteLine("ERROR INSERT INTO - " + e.Message); Console.ReadKey(); } } public List<Jugador> SelectAllJugadores() { List<Jugador> jugadores = new List<Jugador>(); try { SQLiteConnection conexion = new SQLiteConnection("Data Source=" + DatabasePath + ";Version=3;"); conexion.Open(); string sql = "SELECT id, nombre, fecha, puntuacion FROM " + DatabaseTableName + ";"; SQLiteCommand command = new SQLiteCommand(sql, conexion); SQLiteDataReader result = command.ExecuteReader(); while (result.Read()) { long id = (long)result["id"]; string nombre = (string)result["nombre"]; long puntuacion = (long)result["puntuacion"]; string fechaStr = (string)result["fecha"]; DateTime fecha = DateTime.Parse(fechaStr); jugadores.Add(new Jugador(id, nombre, puntuacion, fecha)); } conexion.Close(); command.Dispose(); } catch (SQLiteException e) { Console.SetCursorPosition(1, 1); Console.WriteLine("ERROR SELECT INTO - " + e.Message); Console.ReadKey(); } return jugadores; } public void DeleteAllJugadores() { try { SQLiteConnection conexion = new SQLiteConnection("Data Source=" + DatabasePath + ";Version=3;"); conexion.Open(); string sql = "DELETE FROM " + DatabaseTableName + ";"; SQLiteCommand command = new SQLiteCommand(sql, conexion); command.ExecuteNonQuery(); conexion.Close(); command.Dispose(); } catch (SQLiteException e) { Console.SetCursorPosition(1, 1); Console.WriteLine("ERROR DELETE TABLE - " + e.Message); Console.ReadKey(); } } } }
70e4e9c9cd358de840ccd869749e8e4fe966bc27
C#
Janosch76/snippets
/src/Js.Snippets.CSharp/DateUtils/DateTimeExtensions.cs
3.90625
4
namespace Js.Snippets.CSharp.DateUtils { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// <see cref="TimeSpan"/> based extension methods /// </summary> public static class DateTimeExtensions { /// <summary> /// Formats the date in ISO format. /// </summary> /// <param name="date">The date.</param> /// <returns>The ISO format string representation of the date.</returns> public static string ToDateIso(this DateTime date) { return date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); } /// <summary> /// Formats the timestamp in ISO format. /// </summary> /// <param name="timestamp">The timestamp.</param> /// <returns>The ISO format string representation of the timestamp.</returns> public static string ToDateTimeIso(this DateTime timestamp) { return timestamp.ToString("o"); } /// <summary> /// Determines whether the date/time is in the specified range (inclusive). /// </summary> /// <param name="value">The value.</param> /// <param name="start">The start time of the range.</param> /// <param name="end">The end time of the range.</param> /// <returns> /// <c>true</c> if the value is between the specified lower and upper bounds; otherwise, <c>false</c>. /// </returns> public static bool IsBetween(this DateTime value, DateTime start, DateTime end) { return value.Ticks >= start.Ticks && value.Ticks <= end.Ticks; } /// <summary> /// Determines if the date is a working day (disregarding holidays...). /// </summary> /// <param name="date">The date.</param> /// <returns> /// <c>false</c> if the specified date is weekend; otherwise, <c>true</c>. /// </returns> public static bool IsWorkingDay(this DateTime date) { return !date.IsWeekend(); } /// <summary> /// Determines if the date is a weekend. /// </summary> /// <param name="date">The date.</param> /// <returns> /// <c>true</c> if the specified date is weekend; otherwise, <c>false</c>. /// </returns> public static bool IsWeekend(this DateTime date) { return date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday; } /// <summary> /// Gets the next workday after today (disregarding holidays...). /// </summary> /// <param name="date">The date.</param> /// <returns>The next workday.</returns> public static DateTime NextWorkday(this DateTime date) { while (!date.IsWorkingDay()) { date = date.AddDays(1); } return date; } /// <summary> /// Determine the next date of a given day of the week. For example, from this date, when is the next Tuesday? /// </summary> /// <param name="date">The date.</param> /// <param name="dayOfWeek">The day of the week to find.</param> /// <returns>The date of the next given day of week.</returns> public static DateTime Next(this DateTime date, DayOfWeek dayOfWeek) { while (date.DayOfWeek != dayOfWeek) { date = date.AddDays(1); } return date; } } }
6b2496ff1be82c858c14ed237b01de9fc90df6c9
C#
devcrux/Border-Animation-in-Xamarin-Forms
/BorderAnimation/BorderAnimation/MainPage.xaml.cs
2.84375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace BorderAnimation { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); Task.Run(AnimateBorder); } private async void AnimateBorder() { Action<double> tealMovement = tInput => tealGrad.Offset = (float)tInput; Action<double> orangeMovement = oInput => orangeGrad.Offset = (float)oInput; while (true) { mainRect.Animate(name: "forward", callback: tealMovement, start: 0, end: 1, length: 1000, easing: Easing.SinIn); await Task.Delay(1000); mainRect.Animate(name: "backward", callback: tealMovement, start: 1, end: 0, length: 1000, easing: Easing.SinIn); await Task.Delay(1000); mainRect.Animate(name: "forward2", callback: orangeMovement, start: 1, end: 0, length: 1000, easing: Easing.SinIn); await Task.Delay(1000); mainRect.Animate(name: "backward2", callback: orangeMovement, start: 0, end: 1, length: 1000, easing: Easing.SinIn); await Task.Delay(1000); } } } }
5b40344b6d274394148f22fe985eb3e7792115c2
C#
capnmidnight/ideas
/website from 2008/seanmcbeth.com/App_Code/InstAfraidService.cs
2.703125
3
using System; using System.Collections; using System.Configuration; using System.IO; using System.Net; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; [WebService(Namespace = "http://www.seanmcbeth.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class InstAfraidService : System.Web.Services.WebService { public InstAfraidService() { } [WebMethod] public int GetMaxUserID() { return int.Parse(ConfigurationManager.AppSettings["GDNetMaxUserID"]); } [WebMethod] public string GetStandardMessage(int userID, int maxPostLength) { string message = ""; try { string input = InstAfraidService.GetProfileHtml(userID); string name = InstAfraidService.ExtractUserName(input); message = InstAfraidService.ExtractLatestPost(input); if (message == null) message = ConfigurationManager.AppSettings["GDNetDefaultMessage"]; else if (message.Length > maxPostLength) { message = message.Substring(0, message.IndexOf(' ', maxPostLength)) + "..."; message = string.Format("says stuff like \"{0}\"", message); } message = string.Format("{0}\n", InstAfraidService.ConstructMessage(name, message)); } catch (Exception exp) { message = string.Format("I'm sorry, but there was an error. Could you please tell capn_midnight that '{0}' came up? Thanks. The stacktrace comes next, it's kinda long\nSTACKTRACE: {1}", exp.Message, exp.StackTrace); } return message; } private static string ExtractLatestPost(string profileHtml) { string post = null; int start = profileHtml.IndexOf("TD CLASS=altforumcell"); if (start > -1) { start = profileHtml.IndexOf("<SPAN CLASS=SmallFont>", start) + 22; int end = profileHtml.IndexOf("</SPAN>", start); post = profileHtml.Substring(start, end - start).Replace("\n", "").Replace("\r", "").Replace("&#111;", "o").Trim(); } return post; } [WebMethod] public string GetUserName(int userID) { return ExtractUserName(GetProfileHtml(userID)); } private static string ExtractUserName(string profileHtml) { int start = profileHtml.IndexOf("Get to know ") + 12; int end = profileHtml.IndexOf("...", start); return profileHtml.Substring(start, end - start); } private static string ConstructMessage(string name, string message) { return string.Format("I think {0} is a cool guy. eh {1} and now he doesn't afraid of anything.", name, message); } private static string GetProfileHtml(int userID) { string input = null; Uri profileUri = new Uri(string.Format("http://www.gamedev.net/community/forums/viewprofile.asp?ID={0}", userID)); WebRequest req = HttpWebRequest.CreateDefault(profileUri); WebResponse rep = req.GetResponse(); using (StreamReader reader = new StreamReader(rep.GetResponseStream())) { input = reader.ReadToEnd(); } return input; } }
eb6c45d09a626ad7ea2c69c433312168dace57a1
C#
damy90/Telerik-all
/OOP/Teamwork/screencast accord demo/Sources/Views/CaptureWindow.cs
2.71875
3
// Screencast Capture, free screen recorder // http://screencast-capture.googlecode.com // // Copyright © César Souza, 2012-2013 // cesarsouza at gmail.com // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // namespace ScreenCapture.Views { using System; using System.Drawing; using System.Windows.Forms; using ScreenCapture.ViewModels; /// <summary> /// Capture Window Window. /// </summary> /// /// <remarks> /// <para> /// This is the (almost) invisible window which follows the mouse /// when the user selects the "Capture from a Window" option. It /// is an almost fully transparent window, excepts for the text /// message which accompanies the mouse cursor and a two pixel /// wide square which is directly under the mouse cursor.</para> /// /// <para> /// This window contains a timer which continuously relocates /// the window to the cursor's position. When the user clicks, /// the user actually clicks on a two pixel wide square panel /// and the click is intercepted.</para> /// </remarks> /// [System.Security.SecurityCritical] public partial class CaptureWindow : Form { RecorderViewModel viewModel; /// <summary> /// Initializes a new instance of the <see cref="CaptureWindow"/> class. /// </summary> /// /// <param name="viewModel">The main view model.</param> /// public CaptureWindow(RecorderViewModel viewModel) : this() { if (viewModel == null) throw new ArgumentNullException("viewModel"); this.viewModel = viewModel; this.viewModel.ShowTargetWindow += viewModel_TargetWindowRequested; } /// <summary> /// Initializes a new instance of the <see cref="CaptureWindow"/> /// class. Should not be called without passing a view model. /// </summary> /// public CaptureWindow() { InitializeComponent(); } private void viewModel_TargetWindowRequested(object sender, EventArgs e) { Show(); } /// <summary> /// Triggers when the user clicks the mouse when the window is being shown. /// </summary> /// private void squarePanel_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Hide(); viewModel.SelectWindowUnderCursor(); } } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Control.VisibleChanged"/> event. /// </summary> /// protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged(e); Location = Cursor.Position; timer.Enabled = Visible; } /// <summary> /// Relocates the window when a timer ticks. /// </summary> /// private void OnTimerTick(object sender, EventArgs e) { this.Location = Cursor.Position; this.Focus(); } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Control.MouseLeave"/> event. /// </summary> /// protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); this.Location = Cursor.Position; } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Control.MouseMove"/> event. /// </summary> /// protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); this.Location = Cursor.Position; } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Form.Load"/> event. /// </summary> /// protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.Location = Cursor.Position; } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Control.PreviewKeyDown"/> event. /// </summary> /// protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e) { if (e == null) throw new ArgumentNullException("e"); if (e.KeyCode == Keys.Escape) this.Hide(); base.OnPreviewKeyDown(e); } } }
36416aedee03e4e7127d711fce14abc082d67f27
C#
Eimriik/Unity-Demo
/Assets/Source/Runtime/Injection/Attributes.cs
2.546875
3
using System; using JetBrains.Annotations; using Zenject; namespace StudioEntropy.Injection { /// <summary> /// Used to decorate a "Constructor" method for use by Zenject when constructing Monobehaviours. /// </summary> [ MeansImplicitUse, AttributeUsage( AttributeTargets.Method ) ] public sealed class MonoConstructorAttribute : InjectAttribute { } /// <summary> /// Denotes that the parameter of a Monobehaviours "constructor" <see cref="MonoConstructorAttribute"/> method is /// optional. /// </summary> [ MeansImplicitUse, AttributeUsage( AttributeTargets.Parameter ) ] public sealed class OptionalAttribute : InjectOptionalAttribute { } /// <summary> /// Identifies field and property members as members whos values should be provided via dependency injection. /// </summary> /// <remarks> /// This attribute is decorated with the <see cref="UsedImplicitlyAttribute"/> to suppress unecessary "variable not /// assigned" warnings. /// </remarks> [ MeansImplicitUse ] public sealed class DependencyAttribute : InjectAttribute { } }
2af97a093256a3e991ea65a35169eeabb5304cda
C#
JonathanCarey13/TextGame
/GameProject/Room.cs
2.71875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using static GameProject.ProgramUI; namespace GameProject { public class Room { public string Splash { get; } public List<Item> Items { get; } public List<string> Exits { get; } public List<Event> Events { get; } public void RemoveItem(Item item) { if (Items.Contains(item)) { Items.Remove(item); }; } public void ResolveEvent(Event resolvedEvent) { if (Events.Contains(resolvedEvent)) { Events.Remove(resolvedEvent); } } public Room(string splash, List<string> exits, List<Item> items, List<Event> events) { Splash = splash; Exits = exits; Items = items; Events = events; } } }
146a2020fe8e10b104ec3cf3e1823cc853a3dfed
C#
samhuynhle/csharp_classes_interface_OOP_course
/access_modifiers/Program.cs
3.84375
4
using System; namespace access_modifiers { class Program { public class Person { private DateTime _birthdate; // with private we can't access this field outside the Person class public void SetBirthdate(DateTime birthdate) { // implement logic for birthdate _birthdate = birthdate; } public DateTime GetBirthdate() { return _birthdate; } } static void Main(string[] args) { var person = new Person(); person.SetBirthdate(new DateTime(1995, 08, 31)); System.Console.WriteLine(person.GetBirthdate()); } } }
51c447c2e3b159b694659e3263fd08a7ad316370
C#
nguyenlinh3836/AP
/lab04/Faculty.cs
3.109375
3
using Microsoft.SqlServer.Server; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab04 { public class Faculty : Employee { private int hour; private string rank; public Faculty(int hour, string rank,int department,double salary,string datahired) : base(department,salary,datahired) { this.hour = hour; this.rank = rank; } public override void CaculateVacation() { if (this.hour >= 3) { Console.WriteLine("Has 5 week"); } else if (this.hour >= 3 && rank == "Senior Lecturer") { Console.WriteLine("Has 6 week "); } else { Console.WriteLine("Has 4 week "); } } public override void CaculateBonus() { double CaculateBonus = 1000 + 0.05 * salary; } } }
6605cd877754411db86f509f207e041850babc32
C#
Elitsa-Georgieva/SoftUni-CSharp_Fundamentals
/Associative_Arrays/06.Courses/Program.cs
3.515625
4
using System; using System.Collections.Generic; using System.Linq; namespace _06.Courses { class Program { static void Main(string[] args) { Dictionary<string, List<string>> studentsByCourse = new Dictionary<string, List<string>>(); while (true) { string line = Console.ReadLine(); if (line == "end") { break; } string[] parts = line .Split(" : ", StringSplitOptions.RemoveEmptyEntries); string course = parts[0]; string student = parts[1]; if (!studentsByCourse.ContainsKey(course)) { studentsByCourse.Add(course, new List<string>()); } // studentsByCourse[course] - s towa dostypvame Value-то(в случая празен списък, който създадохме //ред нагоре studentsByCourse[course].Add(student); //използвай ми списъка, който стои срещу този ключ[course] в речника studentsByCourse и към него // добави студента, който получихме от parts[1] от конзолата сега. } Dictionary<string, List<string>> sortedCourses = studentsByCourse .OrderByDescending(c => c.Value.Count) //(за всеки курс искаме да го сортираме като достъпим value-то - x => x.Value - това до тук обаче връща списък и // но за целта ни е необходима бройката в списъка, затова ползваме Value.Count - count пропъртито на списъка. .ToDictionary(x => x.Key, x => x.Value); //направихме нов речник със същите структура и данни, но сортирани в ред какъвто ние сме оказали. foreach (var kvp in sortedCourses) { Console.WriteLine($"{kvp.Key}: {kvp.Value.Count}"); List<string> sortedStudents = kvp.Value .OrderBy(s => s) .ToList(); //СЪЩОТО КАТО: kvp.Value.Sort(); foreach (var student in kvp.Value) { Console.WriteLine($"-- {student}"); } } } } }
15865e4bf6c9e67b46b24cb7b3188cbdbd258a27
C#
agglerithm/CJRPDF
/PdfCore/Utilities/PdfFileReader.cs
2.5625
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CJRPDF.PdfCore.Utilities { public class PdfFileReader { public PdfFile Load(string fileName) { using (var strm = File.OpenRead(fileName)) { return Load(strm); } } private PdfFile Load(FileStream strm) { return new PdfFile(strm); } } }
9268c2be24292cf4a42de0a2a140d92abada0e1d
C#
Fredj90/Commerical-v2
/fcomm/Metier/metier.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.OleDb; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace fcomm { class metier { public metier() { OpenDBConnexion1(); } public Boolean exit = false; public MySqlConnection mycon; private bool OpenDBConnexion1() { bool connectSucceeded = false; System.IO.StreamReader str = new System.IO.StreamReader(Application.StartupPath + "/config.inf"); string strcon = ""; try { strcon = str.ReadLine(); strcon += ";database=f_commerce;charset=utf8;"; Program.Str_con = strcon; } catch { } str.Close(); mycon = new MySqlConnection(strcon); try { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); if (ping.Send(mycon.DataSource).Status == System.Net.NetworkInformation.IPStatus.Success) { mycon.Open(); connectSucceeded = true; } else { MessageBox.Show("Impossible de connecter.\n Le serveur " + mycon.DataSource + " Inaccéssible. "); exit = true; } } catch (Exception) { //verif_db(); } return connectSucceeded; } public DataSet recuperer_table(String req, DataSet ds, String Table) { try { MySqlDataAdapter myadap = new MySqlDataAdapter(req, mycon); try { ds.Tables[Table].Rows.Clear(); } catch { } myadap.Fill(ds, Table); return ds; } catch { return null; } } public DataSet recuperer_table(String req, String Table) { try { MySqlDataAdapter myadap = new MySqlDataAdapter(req, mycon); DataSet ds = new DataSet(); myadap.Fill(ds, Table); return ds; } catch { return null; } } public Boolean Execute(String req) { MySqlCommand cmd = new MySqlCommand(req, mycon); int i = cmd.ExecuteNonQuery(); if (i == 0) { return false; } else { mycon.BeginTransaction().Commit(); return true; } } } }
643be3ab1cd385d9e4015ce2a571b6a3490b05a2
C#
Gao851021/TEMS
/API/temsAPI/temsAPI/Data/Managers/EquipmentLabelManager.cs
2.8125
3
using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using temsAPI.Contracts; using temsAPI.Data.Entities.EquipmentEntities; using temsAPI.Helpers.ReusableSnippets; using temsAPI.System_Files; namespace temsAPI.Data.Managers { public class EquipmentLabelManager : IEquipmentLabelManager { readonly IUnitOfWork _unitOfWork; readonly IEquipmentLabelHelper _labelHelper; public EquipmentLabelManager( IUnitOfWork unitOfWork, IEquipmentLabelHelper labelHelper) { _unitOfWork = unitOfWork; _labelHelper = labelHelper; } /// <summary> /// Sets equipment label. If equipment has children, they will get labeled as well. /// </summary> /// <param name="equipment"></param> /// <returns></returns> public async Task SetLabel(Equipment equipment) { if (equipment.EquipmentDefinition == null || equipment.EquipmentDefinition.EquipmentType == null || equipment.EquipmentDefinition.EquipmentType.Parents.IsNullOrEmpty()) { // If Parents is empty (not null), we will fetch the type one more time // with parents included just to be sure. equipment.EquipmentDefinition = await GetEquipmentDefinition(equipment); } equipment.SetLabel(_labelHelper.GetAppropriateLabel(equipment)); if (equipment.Children.IsNullOrEmpty()) { // Fetch children along with their relevant information (definiton, type, parents). equipment.Children = (await GetChildren(equipment)).ToList(); } if (!equipment.Children.IsNullOrEmpty()) { foreach(var child in equipment.Children) { // In some cases, parentId is not set (Ex. When creating an equipment, the parentID is not set // because at the moment of creation, parent does not exist (First children are inserted, then - parent) child.ParentID = equipment.Id; await SetLabel(child); } } } /// <summary> /// Set a label directly (Must be used with caution) /// </summary> /// <param name="equipment"></param> /// <param name="label"></param> /// <returns></returns> public void SetLabel(Equipment equipment, EquipmentLabel label) { equipment.SetLabel(label); } /// <summary> /// </summary> /// <param name="equipment"></param> /// <returns>Returns equipment's definition, with type information included</returns> private async Task<EquipmentDefinition> GetEquipmentDefinition(Equipment equipment) { return (await _unitOfWork.EquipmentDefinitions .Find<EquipmentDefinition>( where: q => q.Id == equipment.EquipmentDefinitionID, include: q => q.Include(q => q.EquipmentType) .ThenInclude(q => q.Parents))) .FirstOrDefault(); } /// <summary> /// </summary> /// <param name="equipment"></param> /// <returns>Returns equipment's children along with their definitions => types => type parents list included</returns> private async Task<IEnumerable<Equipment>> GetChildren(Equipment equipment) { return await _unitOfWork.Equipments .FindAll<Equipment>( where: q => q.ParentID == equipment.Id, include: q => q.Include(q => q.EquipmentDefinition) .ThenInclude(q => q.EquipmentType) .ThenInclude(q => q.Parents)); } } }
ec2899f23c455d653681bde5d4bf75dcc4b05ef3
C#
penegiashok/Three-Muskeeters
/QuizBee/QuizBee/Controllers/QuizCategoryController.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using QuizBee.Models; namespace QuizBee.Controllers { public class QuizCategoryController : ApiController { static readonly ICategoryRepository repository = new CategoryRepository(); public IEnumerable<QuizzCategory> GetAllcategories() { return repository.GetAll(); } public QuizzCategory GetAnswer(int id) { QuizzCategory result = repository.Get(id); if (result == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return result; } public HttpResponseMessage PostAnswer(QuizzCategory cat) { cat = repository.Add(cat); var response = Request.CreateResponse<QuizzCategory>(HttpStatusCode.Created, cat); string uri = Url.Link("QuizzCategory", new { id = cat.CategoryID }); response.Headers.Location = new Uri(uri); return response; } public void PutAnswer(int id, QuizzCategory cat) { cat.CategoryID = id; if (!repository.update(cat)) { throw new HttpResponseException(HttpStatusCode.NotFound); } } public void DeleteAnswer(int id) { QuizzCategory ans = repository.Get(id); if (ans == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } repository.Remove(id); } } }
40d0c73fcad660d8f8226c088bbf72735b5831cd
C#
pawan9489/ConcurrencyIn.Net
/ReactiveAppComposition/Program.cs
3.203125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Reactive.Linq; namespace ReactiveAppComposition { class Program { static void Main(string[] args) { // To test IObservables => create Virtual event stream by converting IEnumerable to IObservable var textBox = new TextBox(); var form = new Form { Controls = { textBox } }; var msg = Observable.FromEventPattern(textBox, "TextChanged"); var text = (from e in msg select ((TextBox)e.Sender).Text) .DistinctUntilChanged() .Throttle(TimeSpan.FromSeconds(0.5)); Console.WriteLine(getN(new Person())); Console.WriteLine(Person.func()(4)); using (text.Subscribe(Console.WriteLine)) { Application.Run(form); } } static int getN(Person p) { return p?.Name?.Substring(1, 2).Length ?? -1; } } class Person { public string Name { get; set; } public static Func<int, int> func() { int dbl(int x) => x * 2; return dbl; } } }
ca70530531c755c0d9d840a04607d4dd4ec78c30
C#
DanielaPopova/TelerikAcademy_Homeworks
/C#2/08.TextFiles_HW/Problem06_SaveSortedNames/SaveSortedNames.cs
3.84375
4
using System; using System.Collections.Generic; using System.IO; class SaveSortedNames { static void Main() { try { List<string> names = new List<string>(); using (StreamReader readNames = new StreamReader("../../input.txt")) { string name = readNames.ReadLine(); while (name != null) { names.Add(name); name = readNames.ReadLine(); } } //NICE //for (string currName = unsorted.ReadLine(); currName != null; currName = unsorted.ReadLine()) //{ // names.Add(currName); //} names.Sort(); using (StreamWriter writeNames = new StreamWriter("../../output.txt")) { foreach (var name in names) { writeNames.WriteLine(name); } } Console.WriteLine("Done! Check output.txt"); } catch (FileNotFoundException fnfe) { Console.WriteLine(fnfe.Message); } catch (DirectoryNotFoundException dnfe) { Console.WriteLine(dnfe.Message); } catch (IOException ioe) { Console.WriteLine(ioe.Message); } } } /* Write a program that reads a text file containing a list of strings, sorts them and saves them to another text file. Example: input.txt output.txt Ivan Ivan Peter George Maria Maria George Peter */
5e8e0a9407ac8563978c7af80e72d29966a4bbce
C#
kubczas/EightQueensPuzzle
/Extenstions/IntegerExtension.cs
3.28125
3
namespace Extenstions { public static class IntegerExtension { public static bool IsWithin(this int value, int medium, int scope) { return value >= medium-scope && value <= medium+scope; } public static bool IsBetween(this int value, int min, int max) { return value >= min && value <= max; } } }
ac8f2368ebcfeb94aa649588ba821ae312c6fd8b
C#
Schnefalt/Head-First-Design-Patterns
/ch7-Adapter/InterfaceAndClass.cs
3.375
3
public interface IDuck { void Quack(); void Fly(); } public interface ITurkey { void Gobble(); void Fly(); } public class MallardDuck : IDuck { public void Fly() => System.Console.WriteLine("Flap, flap!"); public void Quack() => System.Console.WriteLine("Quack!"); } public class WildTurkey : ITurkey { public void Fly() => System.Console.WriteLine("Barely flying..."); public void Gobble() => System.Console.WriteLine("Gobble, gobble!"); } public class TurkeyAdapter : IDuck { private ITurkey _turkey; public TurkeyAdapter(ITurkey turkey) { _turkey = turkey; } public void Fly() { _turkey.Fly(); } public void Quack() { _turkey.Gobble(); } }
dac184def5b9c55c4b3cb68a2bd406c2aa208306
C#
salahbedeiwi/CSharp-Course
/StructExample/StructExample/Program.cs
3.828125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StructExample { //how to create your own type => struct //like when you create class type, string type, int type, //here i want to have struct type => my own //can struct inherit from class? no //can struct implement from interface? yes //struct is used for your structure/create your own building structure class Company { } abstract class School { } interface Shopping { } interface Masjid { } //if i implement interfaces, i must use what's inside it. struct Employee: Shopping, Masjid { private string _Name; //don't ever initialize a variable (give value ) on strucs //private string _Name = "s"; //---wrong public string Name { get { return _Name; } set { _Name = value; } } private int _EmpNo; public int EmpNo { get { return _EmpNo; } set { _EmpNo = value; } } public string _Address; public void Print() { Console.WriteLine("Welcome to your own struct"); } public void PrintAll() { Console.WriteLine("Welcome {0}, Your address is {1} and Id is {2}", _Name , _Address, _EmpNo); } //how to create constructor in struc //steps: //must use "all" "properties" to be assigned //must have parameters passed, can't be empty (parameterless) //must have parameters that have been declared to be assigned inside the constructor //you can pass any paramters or not. public Employee(int id) { //must assign this this._EmpNo = id; _Name = ""; this._Address = ""; Console.WriteLine("Your Id is {0}", id); } public Employee(string name) { //must assign any property/attribute that was declared this._EmpNo = 0; this._Name = name; this._Address = ""; Console.WriteLine("Your Name is {0}", name); } //you can't assign a default value on parameters: //public Employee(string address = "361 81st Ave") //wrooooooooooong //can't declare the same one parameters like only passing string only and //have constructors multiple times the same public Employee(string address, string name, int empId) { _EmpNo = empId; this._Name = name; _Address = address; Console.WriteLine("Your Address is {0}.\nYour Name is {1}.\nYour Emp Id is {2}.", address, name, empId); } } class Program { static void CoolLine(string addInfo) { Console.WriteLine("\n=========={0}=========\n", addInfo); } static void Main(string[] args) { //call struct: exactly like class CoolLine("Fire Normal Struc - No Param passed"); //note also on class, when i have a constructor, i must follow the initial one //like to pass param if i build a constructor method like that. //even we don't have an empty/allowed constructor for struc, //we can create an object of it without passing info on there. Employee e1 = new Employee(); //please note one thing here: I could pass parameters or not: //cool one feaure here, it doesn't fire anything by default when //creating an object of it. Look how declared a constructors with param above CoolLine("Fire Method on Struc"); e1.Print(); e1.Name = "Salah"; e1.EmpNo = 150; e1._Address = "Minnesota, Usa"; CoolLine("Fire Method on Struc - after assigned value"); e1.PrintAll(); //print all info //now let's use the constructors: CoolLine("Fire New Object on Struc - pass id param"); Employee e2 = new Employee(e1.EmpNo);//print id only CoolLine("Fire New Object on Struc - pass address, name and id params"); Employee e3 = new Employee(e1._Address,e1.Name, e1.EmpNo); //print all info CoolLine("Fire New Object on Struc - pass name param"); Employee e4 = new Employee(e1.Name);//print name only Console.ReadKey(); } } } /* Results ==========Fire Normal Struc - No Param passed========= ==========Fire Method on Struc========= Welcome to your own struct ==========Fire Method on Struc - after assigned value========= Welcome Salah, Your address is Minnesota, Usa and Id is 150 ==========Fire New Object on Struc - pass id param========= Your Id is 150 ==========Fire New Object on Struc - pass address, name and id params========= Your Address is Minnesota, Usa. Your Name is Salah. Your Emp Id is 150. ==========Fire New Object on Struc - pass name param========= Your Name is Salah */
83caffe6a8d196a97c0802c8a11b1d9dd1fd4198
C#
PedroSilvaMorais/Consultorio
/WebAPI/WebAPI/DesafioBuiltCode/Models/Dados/Patient.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data; using System.Data.SqlClient; using Dapper; namespace DesafioBuiltCode.Models.Dados { public class Patient { private string strConexao; public Patient() { strConexao = ConfigurationManager.ConnectionStrings["ConsultorioDB"].ConnectionString; } public void Incluir(Models.Entidade.Patient pPatient) { SqlConnection DBConnection = new SqlConnection(strConexao); DBConnection.Open(); var insert = "INSERT INTO tbPatient(Nome,BirthDate,CPF,NomeDoctor) VALUES (@Nome,@BirthDate,@CPF,@NomeDoctor)"; DBConnection.Execute(insert, pPatient); } public IEnumerable<dynamic> Listar(Models.Entidade.Patient pPatient) { SqlConnection DBConnection = new SqlConnection(strConexao); var p = new DynamicParameters(); //p.Add("@Id", (pPatient.Id == int.MinValue ? (int?)null : pPatient.Id)); // p.Add("@Nome", pPatient.Nome == string.Empty ? (string)null : pPatient.Nome); DBConnection.Open(); var select = "spSel_Patient"; var Result = DBConnection.Query(select, p, commandType: CommandType.StoredProcedure); return Result; } public void Atualizar(Models.Entidade.Patient pPatient) { SqlConnection DBConnection = new SqlConnection(strConexao); var update = "UPDATE tbPatient SET Nome = @Nome, BirthDate = @BirthDate, CPF = @CPF, NomeDoctor = @NomeDoctor WHERE Id = @Id"; DBConnection.Open(); DBConnection.Execute(update, pPatient); } public void Excluir(Models.Entidade.Patient pPatient) { SqlConnection DBConnection = new SqlConnection(strConexao); var delete = "DELETE FROM tbPatient WHERE Id = @Id"; DBConnection.Open(); DBConnection.Execute(delete, pPatient); } public IEnumerable<dynamic> VerificaCpfExiste(Models.Entidade.Patient pPatient) { SqlConnection DBConnection = new SqlConnection(strConexao); var p = new DynamicParameters(); p.Add("@CPF", (pPatient.CPF == string.Empty ? (string)null : pPatient.CPF)); p.Add("@Id", (pPatient.Id <=0 ? (int?)null : pPatient.Id)); DBConnection.Open(); var select = "spSel_VerificaCpfExistente"; var Result = DBConnection.Query(select, p, commandType: CommandType.StoredProcedure); return Result; } } }
86ed46f53853d7b9c9eb873a08bfa68e8b5b0370
C#
Sammmte/Paps-StateMachines-Core
/Paps-StateMachines-Core/Assets/StateMachines Core/Extensions/EventDispatcherStateMachineExtensions.cs
2.71875
3
using System; namespace Paps.StateMachines.Extensions { public static class EventDispatcherStateMachineExtensions { public static void SubscribeEventHandlerTo<TState, TTrigger>(this IEventDispatcherStateMachine<TState, TTrigger> fsm, TState stateId, Func<IEvent, bool> method) { fsm.SubscribeEventHandlerTo(stateId, new DelegateStateEventHandler(method)); } public static void UnsubscribeEventHandlerFrom<TState, TTrigger>(this IEventDispatcherStateMachine<TState, TTrigger> fsm, TState stateId, Func<IEvent, bool> method) { fsm.UnsubscribeEventHandlerFrom(stateId, new DelegateStateEventHandler(method)); } public static bool HasEventHandler<TState, TTrigger>(this IEventDispatcherStateMachine<TState, TTrigger> fsm, TState stateId, Func<IEvent, bool> method) { return fsm.HasEventHandlerOn(stateId, new DelegateStateEventHandler(method)); } public static void SubscribeEventHandlersTo<TState, TTrigger>(this IEventDispatcherStateMachine<TState, TTrigger> fsm, TState stateId, params IStateEventHandler[] eventHandlers) { foreach (var eventHandler in eventHandlers) { fsm.SubscribeEventHandlerTo(stateId, eventHandler); } } public static void SubscribeEventHandlersTo<TState, TTrigger>(this IEventDispatcherStateMachine<TState, TTrigger> fsm, TState stateId, params Func<IEvent, bool>[] methods) { foreach(var method in methods) { fsm.SubscribeEventHandlerTo(stateId, new DelegateStateEventHandler(method)); } } } }
478367395dab017e7f28b19c8fe44fc76c38c0e8
C#
trueouter/RepoDb
/RepoDb/RepoDb.Tests/RepoDb.UnitTests/QueryGroups/QueryGroupTestParseDynamicForNotBetweenOperation.cs
2.640625
3
using Microsoft.VisualStudio.TestTools.UnitTesting; using RepoDb.Enumerations; using RepoDb.Exceptions; namespace RepoDb.UnitTests { public partial class QueryGroupTest { // NotBetween [TestMethod] public void TestParseDynamicParseDynamicNotBetweenOperation() { // Setup var expression = new { Field1 = new { Operation = Operation.NotBetween, Value = new[] { 1, 2 } } }; // Act var actual = QueryGroup.Parse(expression).GetString(); var expected = $"([Field1] NOT BETWEEN @Field1_BetweenLeft AND @Field1_BetweenRight)"; // Assert Assert.AreEqual(expected, actual); } [TestMethod, ExpectedException(typeof(InvalidQueryExpressionException))] public void ThrowExceptionOnParseDynamicIfNotBetweenOperationValueIsNotAnArray() { // Setup var expression = new { Field1 = new { Operation = Operation.NotBetween, Value = "NotAnArray" } }; // Act/Assert QueryGroup.Parse(expression); } [TestMethod, ExpectedException(typeof(InvalidQueryExpressionException))] public void ThrowExceptionOnParseDynamicIfNotBetweenOperationValuesAreNotOnTheSameTypes() { // Setup var expression = new { Field1 = new { Operation = Operation.NotBetween, Value = new object[] { 1, "2" } } }; // Act/Assert QueryGroup.Parse(expression); } [TestMethod, ExpectedException(typeof(InvalidQueryExpressionException))] public void ThrowExceptionOnParseDynamicIfNotBetweenOperationValuesLengthIsNotEqualsTo2() { // Setup var expression1 = new { Field1 = new { Operation = Operation.NotBetween, Value = new object[] { 1 } } }; var expression2 = new { Field1 = new { Operation = Operation.NotBetween, Value = new object[] { 1, 2, 3 } } }; // Act/Assert QueryGroup.Parse(expression1); QueryGroup.Parse(expression2); } } }
65b96b2d8ccc8b7b4cb7d534a6d3da3321fb433e
C#
NwlSmith/PvP-Space-Shooter
/Assets/Scripts/Utilities/UI/AnnouncementController.cs
2.78125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /* * Date created: 10/3/2018 * Creator: Nate Smith * * Description: The Controller for announcements ingame. * Controls the displayed text in each announcement and their movement into and out of screen. */ public class AnnouncementController : MonoBehaviour { // Public objects. [HideInInspector] public Text[] texts; // Private objects. private Animator anim; private GameManager gm; private void Start() { // Retrieve needed Components and GameManager. texts = GetComponentsInChildren<Text>(); anim = GetComponent<Animator>(); gm = GameManager.instance; // Set initial text on the Announcement. NextStage(); } /* * Update text for new stage. * Invoked in Start(), and in GameManager in StartGame() and PlayerHit(). */ public void NextStage() { string newText = "Stage " + gm.stage.ToString(); if (gm.stage == gm.maxStages - 1) newText = "FINAL ROUND!"; UpdateText(newText); } /* * Update the text in each text object. * Invoked in NextStage() and EndGame(). * newText: the text that will be displayed. */ private void UpdateText(string newText) { foreach (Text text in texts) text.text = newText; } /* * Set the text to show the winner of the game. * Invoked at the end of the game in GameManager.PlayerHit(). */ public void EndGame() { UpdateText("Player " + (gm.player1Points > gm.player2Points ? "1" : "2") + " wins!!!"); } /* * Triggers movement animations. * Invoked in GameManager in StartGame() and PlayerHit() when text needs to be displayed. */ public void TriggerMovement() { anim.SetTrigger("Move"); } }
1f75170c3a19973df8cea7f2d171ea7310cb221a
C#
wxf1116/study
/WebApp002/WebApp002/Dao/StudentDao.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using MySql.Data.MySqlClient; using stud = WebApp002.Models.StudentModels; namespace WebApp002.Dao { public class StudentDao { string s = "server = localhost; database = test; user = root; password = 123456; charset = utf8"; public int Add(stud stu) { int a = 0; using(MySqlConnection conn = new MySqlConnection(s)) { try { conn.Open(); string name = stu.name; string sql = "insert into student(name) values ('"+name+"')"; MySqlCommand cmd = new MySqlCommand(sql, conn); a = cmd.ExecuteNonQuery(); } catch(Exception e) { Console.WriteLine(e); } } return a; } } }
e9109c23eb739b06ef9ad079b532b24a2a2f26a2
C#
truongdothienhoang/test
/Controllers/ViewModels/PagedList.cs
2.515625
3
using System; namespace WebrootUI2.Web.Mvc.Controllers.ViewModels { public class PagedList { public int ItemCount { get; set; } public int PageCount { get { return (int)Math.Ceiling((double)this.ItemCount / this.PageSize); } } public int PageIndex { get; set; } public int PageSize { get; set; } public bool IsPreviousPage { get { return (PageIndex > 0); } } public bool IsNextPage { get { return (PageIndex + 1) * PageSize <= ItemCount; } } } }
11ff748f4bf7cb7ad4f52358809260bc7778ee90
C#
oguzhankiyar/old-projects
/iTunesMusic/UniversalWindows/1.1.0.0/iTunesMusic/iTunesMusic/iTunesMusic.Shared/Parsings/AlbumParsing.cs
2.734375
3
using iTunesMusic.Entities; using System; using System.Collections.Generic; using System.Text; using iTunesMusic.Entities.EntityListItems; using Newtonsoft.Json.Linq; namespace iTunesMusic.Parsings { class AlbumParsing { public static List<AlbumListItem> ParseTopAlbums(string json) { try { List<AlbumListItem> albums = new List<AlbumListItem>(); JObject obj = JObject.Parse(json); JArray array = (obj["feed"])["entry"] as JArray; for (int i = 0; i < array.Count; i++) { JObject albumObject = array[i] as JObject; AlbumListItem album = new AlbumListItem(); album.Id = Convert.ToInt32(((albumObject["id"])["attributes"])["im:id"].ToString()); album.Name = (albumObject["im:name"])["label"].ToString(); album.ImageSource = new ImageSource() { Sizex30 = ((albumObject["im:image"])[0])["label"].ToString(), Sizex60 = ((albumObject["im:image"])[1])["label"].ToString(), Sizex100 = ((albumObject["im:image"])[2])["label"].ToString() }; album.ArtistName = (albumObject["im:artist"])["label"].ToString(); album.ReleaseDate = Convert.ToDateTime((albumObject["im:releaseDate"])["label"].ToString()); album.Sort = i + 1; albums.Add(album); } return albums; } catch (Exception) { return null; } } public static Album ParseDetails(string json) { Album album = new Album(); try { JObject obj = JObject.Parse(json); JArray array = obj["results"] as JArray; JObject albumObject = array[0] as JObject; album.Id = Convert.ToInt32(albumObject["artistId"].ToString()); album.Name = albumObject["collectionName"].ToString(); album.Artist = new Artist() { Id = Convert.ToInt32(albumObject["artistId"].ToString()), Name = albumObject["artistName"].ToString() }; album.ImageSource = new ImageSource() { Sizex60 = albumObject["artworkUrl60"].ToString(), Sizex100 = albumObject["artworkUrl100"].ToString() }; album.ReleaseDate = Convert.ToDateTime(albumObject["releaseDate"].ToString()); album.Genre = new Genre() { Id = Convert.ToInt32(albumObject["primaryGenreId"].ToString()), Name = albumObject["primaryGenreName"].ToString() }; } catch (Exception) { } return album; } public static List<SongListItem> ParseSongs(string json) { try { List<SongListItem> songs = new List<SongListItem>(); JObject obj = JObject.Parse(json); JArray array = obj["results"] as JArray; for (int i = 1; i < array.Count; i++) { JObject songObject = array[i] as JObject; SongListItem song = new SongListItem(); song.Id = Convert.ToInt32(songObject["trackId"].ToString()); song.Name = songObject["trackName"].ToString(); song.ArtistName = songObject["artistName"].ToString(); song.ImageSource = new ImageSource() { Sizex30 = songObject["artworkUrl30"].ToString(), Sizex60 = songObject["artworkUrl60"].ToString(), Sizex100 = songObject["artworkUrl100"].ToString() }; songs.Add(song); } return songs; } catch (Exception) { return null; } } } }
fb3b94679ba015722b3ebb68a67c2c130ddfdee8
C#
abhishekbhalani/Catel
/src/Catel.Core/Catel.Core.Shared/Data/EventArgs/AdvancedPropertyChangingEventArgs.cs
2.703125
3
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AdvancedPropertyChangingEventArgs.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Data { using System.ComponentModel; /// <summary> /// Class with additional control on the <see cref="INotifyPropertyChanging"/> interface. /// </summary> public class AdvancedPropertyChangingEventArgs : PropertyChangingEventArgs { /// <summary> /// Initializes a new instance of the <see cref="T:System.ComponentModel.PropertyChangingEventArgs" /> class. /// </summary> /// <param name="propertyName">The name of the property whose value is changing.</param> public AdvancedPropertyChangingEventArgs(string propertyName) : base(propertyName) { Cancel = false; } /// <summary> /// Gets or sets a value indicating whether the setter action should be canceled. /// </summary> /// <value><c>true</c> if cancel; otherwise, <c>false</c>.</value> public bool Cancel { get; set; } } }
b151907297b1cd0ea099c17ffd70bf37a25a0d5e
C#
NASOKILA/SoftUni
/2.Prgramming fundamentals/kurs fundamental 2017/17.RegularExpressions/05.MatchNumbers/MatchNumbers.cs
3.375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace _05.MatchNumbers { class MatchNumbers { static void Main(string[] args) { string input = Console.ReadLine(); string pattern = @"(^|(?<=\s))-?\d+(\.\d+)?($|(?=\s))"; Regex regex = new Regex(pattern); var matches = regex.Matches(input) .Cast<Match>() .Select(a => a.Value) .ToArray(); Console.WriteLine(string.Join(" ", matches)); } } }
7f3996822394fd134d874b77db987779f803d058
C#
jdswift13/cowboy-cafe
/Data/AngryChicken.cs
3.25
3
using System; using System.Collections.Generic; using System.Text; namespace CowboyCafe.Data { /// <summary> /// Class which represents Angry Chicken entree menu item /// </summary> public class AngryChicken : Entree { /// <summary> /// If dish should be served with bread /// </summary> public bool Bread { get { return bread; } set { bread = value; } } private bool bread = true; /// <summary> /// If dish should be served with pickle /// </summary> public bool Pickle { get; set; } = true; public override uint Calories { get { return 190; } } public override double Price { get { return 5.99; } } /// <summary> /// List which holds special instructions /// </summary> public override List<string> SpecialInstructions { get { List<string> instructions = new List<string>(); if (!Bread){ instructions.Add("hold bread"); } if (!Pickle) { instructions.Add("hold pickle"); } return instructions; } } /// <summary> /// ToString function /// </summary> /// <returns></returns> public override string ToString() { return "Angry Chicken"; } } }
71eb1912887e90d62f145b0a89e893a89aded5da
C#
Golcio/Automatically-Switched-Network-Emulator
/Network Manager/AddNewEntryClient.cs
2.625
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 Network_Manager { public partial class AddNewEntryClient : Form { NetworkManagerMain nmm; string nodeName; public AddNewEntryClient(NetworkManagerMain nmm, string nodeName) { this.nmm = nmm; this.nodeName = nodeName; InitializeComponent(); fillTable(); } private void button1_Click(object sender, EventArgs e) { string newEntry = textBox1.Text + "_" + textBox2.Text + "_" + textBox3.Text; nmm.tables[nodeName].Add(newEntry); nmm.sendClientTable(nodeName); fillTable(); } private void fillTable() { dataGridView1.Rows.Clear(); for (int i = 0; i < nmm.tables[nodeName].Count; i++) { int n = dataGridView1.Rows.Add(); string[] split = nmm.tables[nodeName][i].Split('_'); dataGridView1.Rows[n].Cells[0].Value = split[0]; dataGridView1.Rows[n].Cells[1].Value = split[1]; dataGridView1.Rows[n].Cells[2].Value = split[2]; } } } }
50edc49003a58603cb5b01a2721e4a810c34814c
C#
cell-lang/download
/examples/chat-server/main.cs
3.03125
3
using System; using System.IO; using System.Linq; using CellLang; static class ChatServerMain { public static void Main(string[] args) { Generated.Logins logins = new Generated.Logins(); // Logging in a bunch of users logins.Execute("login(user_id: 0, name: \"emy\")"); logins.Execute("login(user_id: 1, name: \"jake\")"); logins.Execute("login(user_id: 2, name: \"sarah\")"); logins.Execute("login(user_id: 3, name: \"paul\")"); // Printing the usernames relations Tuple<long, string>[] usernames = logins.Usernames(); for (int i=0 ; i < usernames.Length ; i++) Console.WriteLine("({0}, {1})", usernames[i].Item1, usernames[i].Item2); Console.WriteLine(""); // This attempt to log in will fail because of a duplicate username try { logins.Execute("login(user_id: 4, name: \"jake\")"); // We're not supposed to ever get here Console.WriteLine("Error (1)!"); return; } catch { // The error was expected, ignoring it } // Checking that the username relation was not // affected by after the failed login attempt Tuple<long, string>[] usernames2 = logins.Usernames(); if (!usernames2.SequenceEqual(usernames)) { Console.WriteLine("Error (2)!"); return; } StreamWriter stdOutWriter = new StreamWriter(Console.OpenStandardOutput()); stdOutWriter.AutoFlush = true; // Reading and printing the current state of the automaton logins.ReadState().Print(stdOutWriter); Console.WriteLine("\n"); // Making a copy of logins Generated.Logins loginsCopy = new Generated.Logins(); string stateStr = logins.ReadState().ToString(); loginsCopy.SetState(stateStr); // Printing the state of loginsCopy loginsCopy.ReadState().Print(stdOutWriter); Console.WriteLine(""); } }
5142a820886c91f530dcf2f7ac67fd2969e60d13
C#
talaku-Abraham/DesignPatternExamples
/Strategy/Heroes/SuperHeroes/Batman.cs
2.8125
3
namespace Strategy.SuperHeroes { public class Batman : IHero { public void Fight() { System.Console.WriteLine("Batman beating thugs with fancy gadgets"); } public void Taunt() { System.Console.WriteLine("I am Batman!"); } } }
dbc76edfad754545de95483c80435634e82d8c3d
C#
antsacc93/PreAcademyG---Week6
/ExceptionWeek6.Demo/Week6.AppComune/Entities/Vigile.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Week6.AppComune.Entities { public class Vigile { public string Matricola { get; set; } public string Nome { get; set; } public string Cognome { get; set; } public IList<Contravvenzione> ContravvenzioniEffettuate { get; set; } = new List<Contravvenzione>(); public void MultaVeicolo(Contravvenzione contravvenzione) { contravvenzione.Vigile = this; ContravvenzioniEffettuate.Add(contravvenzione); } public void MultaVeicolo(string luogo, Veicolo veicolo, int numero) { Contravvenzione nuovaContravvenzione = new Contravvenzione { Numero = numero, Luogo = luogo, Veicolo = veicolo, Vigile = this }; ContravvenzioniEffettuate.Add(nuovaContravvenzione); } } }
65d5b83699009408184091cd35d6548b74573502
C#
patrycjarychlik/notebook
/Memos/SQL/Data/Element.cs
3.171875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; namespace SQL.Data { public class Element { #region Zmienne /// <summary> /// Rekord dla tej klasy /// </summary> protected DataRow m_drRekord; #endregion Zmienne #region Kontruktory /// <summary> /// Prywatny konstruktor /// </summary> protected Element() { } /// <summary> /// Publiczny kontruktor /// </summary> /// <param name="drRekord">Rekord obiektu</param> public Element(DataRow drRekord) { this.m_drRekord = drRekord; } #endregion Konstruktory #region Wlasciwosci /// <summary> /// DataRow powiazany z elementem /// </summary> public DataRow ElementDataRow { get { return m_drRekord; } } public object this[int id] { get { return m_drRekord[id]; } set { m_drRekord[id] = value; } } public object this[string columnName] { get { return m_drRekord[columnName]; } set { m_drRekord[columnName] = value; } } public string[] ColumnName { get { List<string> name = new List<string>(); foreach (System.Data.DataColumn column in m_drRekord.Table.Columns) { name.Add(column.ColumnName); } return name.ToArray(); } } #endregion } }
ed3ee9fd1a9129bff93c642970e9b5e62aa7eb38
C#
AllanJone/jikan.net
/JikanDotNet/JikanDotNet.Test/AdvancedSearchTestClass.cs
2.671875
3
using System.Linq; using System.Threading.Tasks; using Xunit; namespace JikanDotNet.Tests { public class AdvancedSearchTestClass { private readonly IJikan jikan; public AdvancedSearchTestClass() { jikan = new Jikan(true); } [Theory] [InlineData("berserk")] [InlineData("danganronpa")] [InlineData("death")] public void ShouldReturnNotNullSearchAnime(string query) { var searchConfig = new AnimeSearchConfig { Type = AnimeType.TV }; AnimeSearchResult returnedAnime = Task.Run(() => jikan.SearchAnime(query, searchConfig)).Result; Assert.NotNull(returnedAnime); } [Fact] public void ShouldReturnDanganronpaAnime() { var searchConfig = new AnimeSearchConfig { Type = AnimeType.TV }; AnimeSearchResult danganronpaAnime = Task.Run(() => jikan.SearchAnime("danganronpa", searchConfig)).Result; Assert.Equal(1, danganronpaAnime.ResultLastPage); } [Fact] public void ShouldFilterFairyTailAnimeScore() { var searchConfig = new AnimeSearchConfig { Type = AnimeType.TV, Score = 8 }; AnimeSearchResult fairyTailAnime = Task.Run(() => jikan.SearchAnime("Fairy Tail", searchConfig)).Result; Assert.Equal("Fairy Tail (2014)", fairyTailAnime.Results.First().Title); Assert.Equal("Fairy Tail: Final Series", fairyTailAnime.Results.Skip(1).First().Title); } [Fact] public void ShouldFilterBleachMecha() { var searchConfig = new AnimeSearchConfig(); searchConfig.Genres.Add(GenreSearch.Mecha); AnimeSearchResult returnedAnime = Task.Run(() => jikan.SearchAnime("Bleach", searchConfig)).Result; Assert.Contains("Blame! Movie", returnedAnime.Results.Select(x => x.Title)); Assert.Contains("Bubblegum Crisis", returnedAnime.Results.Select(x => x.Title)); } [Fact] public void ShouldFilterBleachMechaMovie() { var searchConfig = new AnimeSearchConfig { Type = AnimeType.Movie }; searchConfig.Genres.Add(GenreSearch.Mecha); AnimeSearchResult returnedAnime = Task.Run(() => jikan.SearchAnime("Bleach", searchConfig)).Result; Assert.Equal("Blame! Movie", returnedAnime.Results.First().Title); } [Fact] public void ShouldFilterBleachAfter2018() { System.DateTime configDate = new System.DateTime(2018, 1, 1); var searchConfig = new AnimeSearchConfig { StartDate = configDate }; AnimeSearchResult returnedAnime = Task.Run(() => jikan.SearchAnime("Bleach", searchConfig)).Result; Assert.Contains("Full Metal Panic! Invisible Victory", returnedAnime.Results.Select(x => x.Title)); Assert.Contains("Beatless", returnedAnime.Results.Select(x => x.Title)); } [Theory] [InlineData("berserk")] [InlineData("monster")] [InlineData("death")] public void ShouldReturnNotNullSearchManga(string query) { var searchConfig = new MangaSearchConfig { Type = MangaType.Manga }; MangaSearchResult returnedManga = Task.Run(() => jikan.SearchManga(query, searchConfig)).Result; Assert.NotNull(returnedManga); } [Fact] public void ShouldReturnDanganronpaManga() { var searchConfig = new MangaSearchConfig { Type = MangaType.Manga }; MangaSearchResult danganronpaManga = Task.Run(() => jikan.SearchManga("danganronpa", searchConfig)).Result; Assert.Equal(1, danganronpaManga.ResultLastPage); } [Fact] public void ShouldReturnDanganronpaMangaScore() { var searchConfig = new MangaSearchConfig { Type = MangaType.Manga, Score = 8 }; MangaSearchResult danganronpaManga = Task.Run(() => jikan.SearchManga("danganronpa", searchConfig)).Result; Assert.Equal("New Danganronpa V3: Minna no Koroshiai Shingakki Comic Anthology", danganronpaManga.Results.First().Title); } [Fact] public void ShouldFilterMetalGame() { var searchConfig = new MangaSearchConfig { Type = MangaType.Manga, }; searchConfig.Genres.Add(GenreSearch.Game); MangaSearchResult returnedManga = Task.Run(() => jikan.SearchManga("metal", searchConfig)).Result; Assert.Equal("Metal Fight Beyblade", returnedManga.Results.First().Title); } [Fact] public void ShouldFilterMetalGameEndDate() { var searchConfig = new MangaSearchConfig { EndDate = new System.DateTime(2015, 1, 1) }; MangaSearchResult returnedManga = Task.Run(() => jikan.SearchManga("metal", searchConfig)).Result; Assert.Contains("Metallica Metalluca", returnedManga.Results.Select(x => x.Title)); Assert.Contains("Full Metal Panic! Another", returnedManga.Results.Select(x => x.Title)); } } }
95582d60d75b58f9e628b6798b2b317153de22b1
C#
Lchaos/TimeTableProblem
/TimeTableProblem/CourseCollection.cs
2.5625
3
using System.Collections.Generic; using System.Linq; using System; using System.Collections; using System.Collections.Immutable; namespace TimeTableProblem { public class CourseCollection:List<Course> { public List<Course> Subjects; public List<DeterminedCourse> DeterminedCourses; public CourseCollection(IEnumerable<Course> sub,IEnumerable<DeterminedCourse> DeterminedCourse):base() { this.AddRange(DeterminedCourse); this.AddRange(sub); DeterminedCourses = new List<DeterminedCourse>(DeterminedCourse); Subjects = new List<Course>(sub); for (int i = 0; i < this.Count; i++) { this[i].index = i; } } } public class CourseInfoCollection : List<CourseSetting> { internal CourseCollection courseInfos; internal int DeterminedCourseNum; public ViolationInfo Info = new ViolationInfo(); public IImmutableList<int>[] lst_EmptyPlace; public static System.Random g_r = new Random(); public int[] room; public CourseInfoCollection(CourseCollection info) : base() { //System.Collections.ArrayList.Synchronized courseInfos = info; DeterminedCourseNum = info.DeterminedCourses.Count; init(); } public List<DeterminedCourse> getSerObjects() { List<DeterminedCourse> ll = new List<DeterminedCourse>(); for (int i = 0; i < this.Count; i++) { DeterminedCourse tmp = new DeterminedCourse(); tmp.From(courseInfos[i]); var tmp2 = this[i]; tmp.semester = tmp2.semester; tmp.koma = tmp2.koma; tmp.day = tmp2.day; ll.Add(tmp); } return ll; } public string ToJson() { return ServiceStack.Text.JsonSerializer.SerializeToString<List<DeterminedCourse>>(getSerObjects()); } public string ToCSV() { return ServiceStack.Text.CsvSerializer.SerializeToString<List<DeterminedCourse>>(getSerObjects()); } public void init() { lst_EmptyPlace = new IImmutableList<int>[5]; this.Clear(); foreach (var item in courseInfos) { this.Add(new CourseSetting()); } var lsttmp = new List<int>(); for (int j = 0; j < 5; j++) { for (int i = 0; i < 90; i++) { lsttmp.Add(i); } var tmp = ImmutableList.Create<int>(lsttmp.ToArray()); lst_EmptyPlace[j] = tmp; } int cnt = this.Count; for (int i = 0; i < cnt; i++) { this[i].index = i; } room = new int[3 * 5 * 6]; } public void refreshEmptyPlace() { //lst_EmptyPlace.Clear(); var lsttmp = new List<int>[5]; for (int j = 0; j < 5; j++) { //lst_EmptyPlace[j].Clear(); lsttmp[j] = new List<int>(); for (int i = 0; i < 90; i++) { lsttmp[j].Add(i); } } for (int i = 0; i < this.Count; i++) { lsttmp[courseInfos[i].PlaceID].Remove(this[i].ToId()); } for (int j = 0; j < 5; j++) { var tmp = ImmutableList.Create<int>(lsttmp[j].ToArray()); lst_EmptyPlace[j] = tmp; } } //public void SetSetting(int index, System.Action<CourseSetting> act) //{ // var setting = this[index]; // act(setting); // getEmptyPlace(courseInfos[index]).Remove(setting.ToId()); //} public void SetDeterminedCourse() { for (int i = 0; i < DeterminedCourseNum; i++) { var setting = this[i]; var info = courseInfos.DeterminedCourses[i]; setting.Set(info); //getEmptyPlace(info).Remove(setting.ToId()); //if (info.length == 2) //{ // getEmptyPlace(info).Remove(setting.ToId() + 1); //} } refreshEmptyPlace(); } public bool Exchange(int index1, int index2) { var setting1 = this[index1]; var setting2 = this[index2]; var info1 = courseInfos[index1]; var info2 = courseInfos[index2]; if (info1.PlaceID != info2.PlaceID) return false; if (info2.length == info1.length) { if (info2.length == 1) { setting1.Exchange(setting2); } else { setting1.Exchange(setting2); this[info1.nextID].Exchange(this[info2.nextID]); } return true; } else { if (info2.length > info1.length) { var tmp1 = info1; var tmp2 = setting1; info1 = info2; setting1 = setting2; info2 = tmp1; setting2 = tmp2; } var place = getEmptyPlace(info1); if (setting2.koma < 6 && place.Contains(setting2.ToId() + 1)) { setting1.Exchange(setting2); removeEmptyPlace(info1,setting1.ToId() + 1); addEmptyPlace(info2,this[info1.nextID].ToId()); this[info1.nextID].FromId(setting1.ToId() + 1); } else if (setting2.koma > 1 && place.Contains(setting2.ToId() - 1)) { setting1.Exchange(setting2); addEmptyPlace(info2,this[info1.nextID].ToId()); removeEmptyPlace(info1,setting1.ToId() - 1); this[info1.nextID].FromId(setting1.ToId() - 1); }; } //else if (info1.length == 1 && info2.length == 2) //{ // var place = getEmptyPlace(info2); // if (setting2.koma < 6) // return place.Contains(setting2.ToId() + 1); // return setting2.koma >1 && place.Contains(setting2.ToId() - 1); //} return false; } public IImmutableList<int> getEmptyPlace(Course info) { return lst_EmptyPlace[info.PlaceID]; } public void removeEmptyPlace(Course info,int id) { lst_EmptyPlace[info.PlaceID] = lst_EmptyPlace[info.PlaceID].Remove(id); } public void addEmptyPlace(Course info, int id) { lst_EmptyPlace[info.PlaceID] = lst_EmptyPlace[info.PlaceID].Add(id); } public bool Exchange(CourseSetting index1, CourseSetting index2) { return Exchange(index1.index, index2.index); } //public void Exchange(int index1, int index2) //{ // if (CanExchange(index1,index2)) // { // __Exchange(index1, index2); // } //} internal void __Exchange(int index1, int index2) { var setting1 = this[index1]; var setting2 = this[index2]; var info1 = courseInfos[index1]; var info2 = courseInfos[index2]; if (info2.length == info1.length) { setting1.Exchange(setting2); } else if (info2.length == 2 && info1.length == 1) { addEmptyPlace(info1,setting1.ToId() + 1); removeEmptyPlace(info2,setting2.ToId() + 1); } else if (info1.length == 1 && info2.length == 2) { addEmptyPlace(info2,setting2.ToId() + 1); removeEmptyPlace(info1,setting1.ToId() + 1); } } public void CountVioInfo() { Info.reset(); var compilsoryCourse = courseInfos.DeterminedCourses.Where(c => c.compilsory == 1); var subCompilsoryCourse = courseInfos.Subjects.Where(c => c.compilsory == 1).ToList(); foreach (var dec in compilsoryCourse) { var subCompilsoryCourseVio = subCompilsoryCourse.Where(c => dec.grade - c.grade == 1 && this[c.index].Equals(this[dec.index])); Info.grade += subCompilsoryCourseVio.Count(); } var subContinueCourse = courseInfos.Subjects.Where(c => c.continue_semester == 1); foreach (var item in subContinueCourse) { int cnt = courseInfos.Count; for (int i = item.index + 1; i < cnt; i++) { var setting = courseInfos[i]; if (setting.IsSameCourse(item)) { var info1 = this[item.index]; var info2 = this[setting.index]; if (info1.semester == info2.semester || info1.day != info2.day || info1.koma != info2.koma) { Info.continueYear++; } if (item.length > 1) { if (info1.semester != info2.semester || info1.day != info2.day || (info1.koma != info2.koma && Math.Abs(info1.koma - info2.koma) != 1)) Info.continued++; else if (info1.koma == 2 && info2.koma == 3 || info1.koma == 3 && info2.koma == 2) { Info.crossLanchTime++; } } } } } Info.sixthCourse = this.Where(c => c.koma == 6).Count(); Dictionary<int, int> dic = new Dictionary<int, int>(); foreach (var item in subCompilsoryCourse) { var key = _CourseinfoKeyFunc(item); if (!dic.ContainsKey(key)) dic[key] = 1; else dic[key] += 1; } Info.compilsory = dic.Values.Where(i => i > 4).Count(); dic.Clear(); foreach (var item in courseInfos.Subjects.Where(i => i.grade == 3)) { var key = _CourseinfoKeyFunc(item); if (!dic.ContainsKey(key)) dic[key] = 1; else dic[key]++; } Info.channel = dic.Values.Where(i => i > 2).Count(); dic.Clear(); foreach (var item in courseInfos) { var keyday = _CourseinfoKeyFunc(item); var key = keyday * 10 + this[item.index].koma; if (!dic.ContainsKey(key)) { dic[key] = 1; if (!dic.ContainsKey(keyday)) { dic[keyday] = 1; } else dic[keyday]++; } } for (int i = 1; i < 4; i++) { int jstr = 1, jend = 4; if (i!=3) { jstr = 0; jend = 1; } for (int j = jstr; j < jend; j++) { for (int l = 1; l < 4; l++) { for (int m = 1; m < 6; m++) { if (dic.ContainsKey(i * 1000 + j * 100 + l * 10 + m)) { var val = dic[i * 1000 + j * 100 + l * 10 + m]; if (DayCountVioMap.ContainsKey(val)) { Info.Violation += DayCountVioMap[val]; Info.days++; } } else { Info.Violation += DayCountVioMap[0]; Info.days++; } } } } } //foreach (var item in dic.Keys) //{ // var val = dic[item]; // if (DayCountVioMap.ContainsKey(val)) // { // Info.Violation += DayCountVioMap[val]; // Info.days++; // } //} Info.Count(); } static CourseInfoCollection() { DayCountVioMap.Add(0, 15); DayCountVioMap.Add(1, 10); //DayCountVioMap.Add(2, 5); DayCountVioMap.Add(6, 5); } public static Dictionary<int, int> DayCountVioMap = new Dictionary<int, int>(); int _CourseinfoKeyFunc(Course info) { var c = this[info.index]; if (info.grade < 3) { return info.grade * 1000 + c.semester * 10 + c.day; } return info.grade * 1000 + info.profession * 100 + c.semester * 10 + c.day; } //public void SetRandomPositionInEmpty(int index) //{ // if (index < DeterminedCourseNum) return; // var setting = this[index]; // var info = courseInfos[index]; // var emptyflag = setting.ToId(); // if (emptyflag != -1) // { // lst_EmptyPlace.Add(emptyflag); // } // int idIndex = g_r.Next(0, lst_EmptyPlace.Count); // int newposition=lst_EmptyPlace[idIndex]; // if (info.length == 2) // { // while (CourseSetting.getkoma(newposition) == 6 || !lst_EmptyPlace.Contains(newposition)) // { // idIndex = g_r.Next(0, lst_EmptyPlace.Count); // newposition = lst_EmptyPlace[idIndex]; // } // } // setting.FromId(newposition); // lst_EmptyPlace.RemoveAt(idIndex); // if (info.length == 2) // { // lst_EmptyPlace.Remove(newposition + 1); // } // setting.FromId(newposition); //} private bool _ContainsNearPosition(IImmutableList<int> emptyPlace, int id) { int koma = CourseSetting.getkoma(id); if (koma < 6 && emptyPlace.Contains(id + 1)) return true; if (koma > 1 && emptyPlace.Contains(id - 1)) return true; return false; } private int _NearEmptyPosition(IImmutableList<int> emptyPlace, int id) { int koma = CourseSetting.getkoma(id); if (koma == 1 && emptyPlace.Contains(id + 1)) return id + 1; if (koma == 6 && emptyPlace.Contains(id - 1)) return id - 1; if (koma > 1 && koma < 6) { var flag1 = emptyPlace.Contains(id + 1); var flag2 = emptyPlace.Contains(id - 1); lock (g_r) { if (flag1 && flag2) return g_r.NextDouble() < 0.5 ? id + 1 : id - 1; else if (flag1) return id + 1; else if (flag2) return id - 1; } } return -1; } public bool InitRandomPositionInEmpty(int index, int semester = -1) { if (index < DeterminedCourseNum) return false; var setting = this[index]; var info = courseInfos[index]; var emptyflag = setting.ToId(); var emptyPlace = getEmptyPlace(info); if (emptyflag >= 0) { return true; //emptyPlace.Add(emptyflag); } int idIndex = g_r.Next(0, emptyPlace.Count); int newposition = 0; var p = info.length == 2 ? emptyPlace.Where((r) => ((CourseSetting.getsemester(r) == semester) || semester == -1) && _ContainsNearPosition(emptyPlace, r)).ToList() : emptyPlace.Where((r) => CourseSetting.getsemester(r) == semester || semester == -1).ToList(); if (p.Count == 0) { return false; } idIndex = g_r.Next(0, p.Count); newposition = p[idIndex]; setting.FromId(newposition); if (info.length == 2) { //emptyPlace.Remove(newposition + 1); for (int i = index + 1; i < this.Count; i++) { if (this.courseInfos[i].IsSameCourse(info)) { int id = _NearEmptyPosition(emptyPlace, newposition); if (id == -1 && _ContainsNearPosition(emptyPlace, newposition)) { } this[i].FromId(id); courseInfos[i].nextID = info.index; info.nextID = courseInfos[i].index; lst_EmptyPlace[info.PlaceID] = emptyPlace.Remove(id); lst_EmptyPlace[info.PlaceID] = lst_EmptyPlace[info.PlaceID].Remove(newposition); break; } } } else { lst_EmptyPlace[info.PlaceID] = emptyPlace.Remove(newposition); } setting.FromId(newposition); return true; } public bool IsDeterminedPosition(int id,int placeid) { for (int i = 0; i < DeterminedCourseNum; i++) { if (courseInfos[i].PlaceID== placeid && this[i].ToId() == id) { return true; } } return false; } public int PlacedIndex(int id, int PlaceID, int length) { var p = courseInfos.Where(r => r.PlaceID == PlaceID); var koma = CourseSetting.getkoma(id); var emptyPlace = lst_EmptyPlace[PlaceID]; if (length == 1) { if (emptyPlace.Contains(id)) return -1; foreach (var item in p) { var itemid = this[item.index].ToId(); if (itemid == id) { return item.index; } } return -1; } else// if(length == 2) { if (emptyPlace.Contains(id) && _ContainsNearPosition(emptyPlace, id)) { return -1; } foreach (var item in p) { var itemid = this[item.index].ToId(); if (itemid == id) { return item.index; } if (koma < 6 && id == itemid + 1) { return item.index; } else if (koma > 1 && id == itemid - 1) { return item.index; } } return -1; } } public static int[] g_DayKomaIDS = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 }; public void SetPositionLVRandom(LevyFilght lv, int index, bool exchangable = true) { int mC; var emptyplace = getEmptyPlace(courseInfos[index]); var orgid = this[index].ToId(); var Place = g_DayKomaIDS.OrderBy(r => emptyplace.Contains(r)? 0:1 + (Math.Max(r, orgid%30)- Math.Min(r, orgid % 30)) *2 ).ToList(); //var sameSemster = emptyplace.Where(r => CourseSetting.getsemester(r) == this[index].semester).OrderBy(r=>Math.Abs( r-this[index].ToId())).ToList(); //if (sameSemster.Count == 0) { // SetPositionRandom(index); } //else { do { lock (g_r) { int lvr = (int)lv.next(1, 29); //lvr = 2 * lvr - g_r.Next(1, 2); //int flag = g_r.NextDouble() < 0 ? -1 : 1; mC = Place[lvr]; } } while (IsDeterminedPosition(mC, courseInfos[index].PlaceID)); SetPosition(mC, index, exchangable); } } public void SetPositionRandom(int index, bool exchangable = true) { int mC; do { lock (g_r) { mC = g_r.Next(0, 30) + (this[index].semester - 1) * 30; } } while (IsDeterminedPosition(mC, courseInfos[index].PlaceID)); SetPosition(mC, index, exchangable); } public void SetPosition(int id, int index, bool exchangable = true) { if (index < DeterminedCourseNum) { return; } if (IsDeterminedPosition(id, courseInfos[index].PlaceID)) { return; } var setting = this[index]; var info = courseInfos[index]; var emptyflag = setting.ToId(); var emptyPlace = getEmptyPlace(info); if (emptyflag < 0) { return; } var placedindx = PlacedIndex(id, info.PlaceID, info.length); if (placedindx!=-1) { if (placedindx < DeterminedCourseNum) { return; } if (exchangable) Exchange(placedindx,index); return; } int newposition = id; if (info.length == 2) { var nearid = _NearEmptyPosition(emptyPlace, newposition); if (nearid!=-1) { lst_EmptyPlace[info.PlaceID] = emptyPlace.Remove(nearid); lst_EmptyPlace[info.PlaceID] = lst_EmptyPlace[info.PlaceID].Remove(newposition); lst_EmptyPlace[info.PlaceID] = lst_EmptyPlace[info.PlaceID].Add(this[info.nextID].ToId()); lst_EmptyPlace[info.PlaceID] = lst_EmptyPlace[info.PlaceID].Add(setting.ToId()); this[info.nextID].FromId(nearid); setting.FromId(newposition); } //if (CourseSetting.getkoma(newposition) < 6 && emptyPlace.Contains(newposition + 1)) //{ // emptyPlace.Add(emptyflag); // setting.FromId(newposition); // emptyPlace.Add(emptyflag + 1); // emptyPlace.Remove(newposition); // emptyPlace.Remove(newposition + 1); //} //else if (CourseSetting.getkoma(newposition) > 1 && emptyPlace.Contains(newposition - 1)) //{ // emptyPlace.Add(emptyflag); // setting.FromId(newposition - 1); // emptyPlace.Add(emptyflag + 1); // emptyPlace.Remove(newposition); // emptyPlace.Remove(newposition - 1); //} } else { setting.FromId(newposition); lst_EmptyPlace[info.PlaceID] = emptyPlace.Remove(newposition); lst_EmptyPlace[info.PlaceID] = lst_EmptyPlace[info.PlaceID].Add(emptyflag); } //foreach (var iitem in this) //{ // if (iitem.ToId() < 0) // { // continue; // } // foreach (var iiitem in this) // { // if (iiitem.ToId() < 0) // { // continue; // } // if (iiitem.index != iitem.index) // { // if (courseInfos[iitem.index].PlaceID == courseInfos[iiitem.index].PlaceID && iiitem.ToId() == iitem.ToId()) // { // throw new Exception(); // } // } // } //} } //public void SetPositionInEmpty(int id,int index) //{ // if (index < DeterminedCourseNum) return; // var setting = this[index]; // var info = courseInfos[index]; // var emptyflag = setting.ToId(); // var emptyPlace = getEmptyPlace(info); // if (emptyflag == -1) return; // emptyPlace.Add(emptyflag); // int newposition = id; // if (info.length == 2) // { // if (CourseSetting.getkoma(newposition)< 6 && emptyPlace.Contains(newposition + 1)) // { // setting.FromId(newposition); // emptyPlace.Add(emptyflag+1); // emptyPlace.Remove(newposition); // emptyPlace.Remove(newposition + 1); // } // else if(CourseSetting.getkoma(newposition) > 1 && emptyPlace.Contains(newposition - 1)) // { // setting.FromId(newposition-1); // emptyPlace.Add(emptyflag + 1); // emptyPlace.Remove(newposition); // emptyPlace.Remove(newposition -1); // } // } // else // { // setting.FromId(newposition); // emptyPlace.Remove(newposition); // } //} public void CopyFrom(CourseInfoCollection cc) { for (int j = 0; j < cc.Count; j++) { this[j].Set(cc[j]); } this.refreshEmptyPlace(); this.Info.set(cc.Info); } public void ResetPosition() { } } }
e46588124080551aaeaf79e0cb515f4ff8e88700
C#
CeSiumUA/TestTask
/TestTask/Controllers/PositionController.cs
2.640625
3
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using TestTask.Models; namespace TestTask.Controllers { [Route("api/[controller]")] [ApiController] public class PositionController : ControllerBase { private DatabaseContext databaseContext; public PositionController(DatabaseContext databaseContext) { this.databaseContext = databaseContext; } [HttpPost("addposition")] public async Task<IActionResult> AddPosition([FromBody] Position Position) { if ((await databaseContext.Positions.FirstOrDefaultAsync(x => x.PositionName.ToLower() == Position.PositionName.ToLower())) != null) { return Conflict(); } await databaseContext.Positions.AddAsync(Position); await databaseContext.SaveChangesAsync(); return Ok(); } [HttpGet("positions")] public async Task<IActionResult> GetPositions() { var positions = await databaseContext.Positions.ToListAsync(); return new JsonResult(positions); } } }
93749d1fea5545c76d8532dd1113e0a2bd3a8242
C#
stjeong/DotNetSamples
/WinConsole/PEFormat/PEFormatSample/Program.cs
2.578125
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using WindowsPE; #pragma warning disable IDE0051, CA1031 namespace PEFormatSample { class Program { static int Main(string[] args) { //// Is DLL managed/unmanaged? //CheckDlls(); //// Show exported functions from EXPORT Data Directory //ShowExportFunctions(true); //ShowExportFunctions(false); //// Show debug info from DEBUG Data Directory //ShowPdbInfo(true); //ShowPdbInfo(false); //// Show how to download PDB from Microsoft Symbol Server //DownloadPdbs(true); //DownloadPdbs(false); if (args.Length >= 2) { // ex) // PEFormatSample pdb http://msdl.microsoft.com/download/symbols/ntdll.pdb/6DFD0B387E7941A587A3B64F824B1CAC1/ntdll.pdb if (args[0] == "pdb") { string dirPath = Path.GetDirectoryName(typeof(Program).Assembly.Location); Uri uri = new Uri(args[1]); string localFilePath = Path.Combine(dirPath, uri.GetFileName()); DownloadPdbFile(uri, localFilePath); bool downloaded = File.Exists(localFilePath); Console.WriteLine($"{localFilePath}: {downloaded}"); return downloaded == true ? 0 : 1; } } return 0; } private static void DownloadPdbs(bool fromFile) { string rootPathToSave = Path.Combine(Environment.CurrentDirectory, "sym"); if (Directory.Exists(rootPathToSave) == false) { Directory.CreateDirectory(rootPathToSave); } Process currentProcess = Process.GetCurrentProcess(); foreach (ProcessModule pm in currentProcess.Modules) { Console.WriteLine($"[{pm.FileName}, 0x{pm.BaseAddress.ToString("x")}]"); PEImage pe; if (fromFile == true) { pe = PEImage.ReadFromFile(pm.FileName); } else { pe = PEImage.ReadFromMemory(pm.BaseAddress, pm.ModuleMemorySize); } if (pe == null) { Console.WriteLine("Failed to read images"); return; } string modulePath = pm.FileName; DownloadPdb(modulePath, rootPathToSave); Console.WriteLine(); } } private static void DownloadPdb(string modulePath, string rootPathToSave) { if (File.Exists(modulePath) == false) { Console.WriteLine("NOT Found: " + modulePath); return; } PEImage pe = PEImage.ReadFromFile(modulePath); if (pe == null) { Console.WriteLine("Failed to read images"); return; } Uri baseUri = new Uri("https://msdl.microsoft.com/download/symbols/"); foreach (CodeViewRSDS codeView in pe.EnumerateCodeViewDebugInfo()) { if (string.IsNullOrEmpty(codeView.PdbFileName) == true) { continue; } string pdbFileName = codeView.PdbFileName; if (Path.IsPathRooted(codeView.PdbFileName) == true) { pdbFileName = Path.GetFileName(codeView.PdbFileName); } Console.WriteLine("\tFileName: " + pdbFileName); Console.WriteLine("\tPdbFileName: " + codeView.PdbFileName); Console.WriteLine("\tLocal: " + codeView.PdbLocalPath); Console.WriteLine("\tUri: " + codeView.PdbUriPath); string localPath = Path.Combine(rootPathToSave, codeView.PdbLocalPath); string localFolder = Path.GetDirectoryName(localPath); if (Directory.Exists(localFolder) == false) { try { Directory.CreateDirectory(localFolder); } catch (DirectoryNotFoundException) { Console.WriteLine("NOT Found on local: " + codeView.PdbLocalPath); continue; } } if (File.Exists(localPath) == true) { Console.WriteLine("Found on local: " + pdbFileName); continue; } if (CopyPdbFromLocal(modulePath, codeView.PdbFileName, localPath) == true) { Console.WriteLine("Found on local: " + pdbFileName); continue; } Uri target = new Uri(baseUri, codeView.PdbUriPath); Console.WriteLine(target); Uri pdbLocation = GetPdbLocation(target); if (pdbLocation == null) { string underscorePath = ProbeWithUnderscore(target.AbsoluteUri); pdbLocation = GetPdbLocation(new Uri(underscorePath)); } if (pdbLocation != null) { DownloadPdbFile(pdbLocation, localPath); } else { Console.WriteLine("Not Found on symbol server: " + codeView.PdbFileName); } } Console.WriteLine(); } private static bool CopyPdbFromLocal(string modulePath, string pdbFileName, string localTargetPath) { if (File.Exists(pdbFileName) == true) { File.Copy(pdbFileName, localTargetPath); return File.Exists(localTargetPath); } string fileName = Path.GetFileName(pdbFileName); string pdbPath = Path.Combine(Environment.CurrentDirectory, fileName); if (File.Exists(pdbPath) == true) { File.Copy(pdbPath, localTargetPath); return File.Exists(localTargetPath); } pdbPath = Path.ChangeExtension(modulePath, ".pdb"); if (File.Exists(pdbPath) == true) { File.Copy(pdbPath, localTargetPath); return File.Exists(localTargetPath); } return false; } private static string ProbeWithUnderscore(string path) { path = path.Remove(path.Length - 1); path = path.Insert(path.Length, "_"); return path; } private static void DownloadPdbFile(Uri target, string pathToSave) { System.Net.HttpWebRequest req = System.Net.WebRequest.Create(target) as System.Net.HttpWebRequest; using (System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse) using (FileStream fs = new FileStream(pathToSave, FileMode.CreateNew, FileAccess.Write, FileShare.None)) using (BinaryWriter bw = new BinaryWriter(fs)) { BinaryReader reader = new BinaryReader(resp.GetResponseStream()); long contentLength = resp.ContentLength; while (contentLength > 0) { byte[] buffer = new byte[4096]; int readBytes = reader.Read(buffer, 0, buffer.Length); bw.Write(buffer, 0, readBytes); contentLength -= readBytes; } } } private static Uri GetPdbLocation(Uri target) { System.Net.HttpWebRequest req = System.Net.WebRequest.Create(target) as System.Net.HttpWebRequest; req.Method = "HEAD"; try { using (System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse) { return resp.ResponseUri; } } catch (System.Net.WebException) { return null; } } private static void ShowPdbInfo(bool fromFile) { Process currentProcess = Process.GetCurrentProcess(); foreach (ProcessModule pm in currentProcess.Modules) { Console.WriteLine($"[{pm.FileName}, 0x{pm.BaseAddress.ToString("x")}]"); PEImage pe; if (fromFile == true) { pe = PEImage.ReadFromFile(pm.FileName); } else { pe = PEImage.ReadFromMemory(pm.BaseAddress, pm.ModuleMemorySize); } if (pe == null) { Console.WriteLine("Failed to read images"); return; } foreach (IMAGE_DEBUG_DIRECTORY debugDir in pe.EnumerateDebugDir()) { Console.WriteLine("\tDebugType: " + Enum.GetName(typeof(DebugDirectoryType), debugDir.Type)); } foreach (CodeViewRSDS codeView in pe.EnumerateCodeViewDebugInfo()) { Console.WriteLine("\t\t" + codeView.PdbLocalPath); } Console.WriteLine(); } } private static void CheckDlls() { Console.WriteLine("native.dll: IsManaged == " + PEImage.ReadFromFile("native.dll").IsManaged); Console.WriteLine("net20.dll: IsManaged == " + PEImage.ReadFromFile("net20.dll").IsManaged); Console.WriteLine("net40.dll: IsManaged == " + PEImage.ReadFromFile("net40.dll").IsManaged); Console.WriteLine("WindowsPE.dll: IsManaged == " + PEImage.ReadFromFile("WindowsPE.dll").IsManaged); } private static void ShowExportFunctions(bool fromFile) { Process currentProcess = Process.GetCurrentProcess(); foreach (ProcessModule pm in currentProcess.Modules) { Console.WriteLine($"[{pm.FileName}, 0x{pm.BaseAddress.ToString("x")}]"); PEImage pe; if (fromFile == true) { pe = PEImage.ReadFromMemory(pm.BaseAddress, pm.ModuleMemorySize); } else { pe = PEImage.ReadFromFile(pm.FileName); } if (pe == null) { Console.WriteLine("Failed to read images"); return; } foreach (IMAGE_SECTION_HEADER section in pe.EnumerateSections()) { Console.WriteLine(section); } Console.WriteLine(); // foreach (ExportFunctionInfo efi in pe.EnumerateExportFunctions()) foreach (ExportFunctionInfo efi in pe.EnumerateExportFunctions().Take(5)) { Console.WriteLine("\t" + efi); } Console.WriteLine("\t..."); Console.WriteLine(); } } } static class Extension { public static string GetFileName(this Uri uri) { string path = uri.LocalPath; int pos1 = path.LastIndexOf('\\'); int pos2 = path.LastIndexOf('/'); int epos = Math.Max(pos1, pos2); return path.Substring(epos + 1); } } }
2456d64063c0c6fc27525a0dc168a119548e83ce
C#
emehiel/Horizon
/src/Utilities/Complex.cs
3.078125
3
// Copyright (c) 2016 California Polytechnic State University // Authors: Morgan Yost (morgan.yost125@gmail.com) Eric A. Mehiel (emehiel@calpoly.edu) using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; namespace Utilities { [Serializable] //[ExcludeFromCodeCoverage] public class Complex<T> : ICloneable, ISerializable { #region Properties /// <summary> /// Contains the real part of a complex number /// </summary> public T Re { get; set; } /// <summary> /// Contains the imaginary part of a complex number /// </summary> public T Im { get; set; } /// <summary> /// Imaginary unit /// </summary> public static Complex<T> i { get { return new Complex<T>((T)Convert.ChangeType(0, typeof(T)), (T)Convert.ChangeType(1, typeof(T))); } } /// <summary> /// Imaginary unit /// </summary> public static Complex<T> j { get { return new Complex<T>((T)Convert.ChangeType(0, typeof(T)), (T)Convert.ChangeType(1, typeof(T))); } } /// <summary> /// Complex number zero (additive Identity). /// </summary> public static Complex<T> Zero { get { return new Complex<T>((T)Convert.ChangeType(0, typeof(T)), (T)Convert.ChangeType(0, typeof(T))); } } /// <summary> /// Complex number one (multiplicative identity). /// </summary> public static Complex<T> I { get { return new Complex<T>((T)Convert.ChangeType(1, typeof(T)), (T)Convert.ChangeType(0, typeof(T))); } } #endregion #region Constructors /// <summary> /// Represents a complex number with zero real and imaginary part. /// </summary> public Complex() { Re = (T)Convert.ChangeType(0, typeof(T)); Im = (T)Convert.ChangeType(0, typeof(T)); } /// <summary> /// Represents a complex number with imaginary part equal to zero /// </summary> /// <param name="realPart"></param> public Complex(T realPart) { Re = realPart; Im = (T)Convert.ChangeType(0, typeof(T)); } /// <summary> /// Represents a complex number. /// </summary> /// <param name="realPart">The real part of the complex number</param> /// <param name="imaginaryPart">The imaginary part of the complex number</param> public Complex(T realPart, T imaginaryPart) { Re = realPart; Im = imaginaryPart; } #endregion #region Operators /// <summary> /// Returns the sum of the complex numbers c1 and c2. /// </summary> public static Complex<T> operator +(Complex<T> c1, Complex<T> c2) { return new Complex<T>((dynamic)c1.Re + c2.Re, (dynamic)c1.Im + c2.Im); } /// <summary> /// Returns the difference of the complex numbers c1 and c2. /// </summary> public static Complex<T> operator -(Complex<T> c1, Complex<T> c2) { return new Complex<T>((dynamic)c1.Re - c2.Re, (dynamic)c1.Im - c2.Im); } /// <summary> /// Returns the additive inverse of the complex number c. /// </summary> public static Complex<T> operator -(Complex<T> c) { return new Complex<T>(-(dynamic)c.Re, -(dynamic)c.Im); } /// <summary> /// Returns the multiplicative product of the complex numbers c1 and c2 /// </summary> public static Complex<T> operator *(Complex<T> c1, Complex<T> c2) { return new Complex<T>((dynamic)c1.Re * c2.Re - (dynamic)c1.Im * c2.Im, (dynamic)c1.Re * c2.Im + (dynamic)c2.Re * c1.Im); } /// <summary> /// Returns the rationalized complex quotent of c1 and c2 /// </summary> /// <param name="c1"></param> /// <param name="c2"></param> /// <returns></returns> public static Complex<double> operator /(Complex<T> c1, Complex<T> c2) { if (c1 == Complex<T>.Zero) return Complex<double>.Zero; else if (c2 == Complex<T>.Zero) throw new Exception("cannot divide by zero: operation Complex<T> c1 / Complex<T> c2"); else { Double ac2 = Complex<T>.Abs(c2); Complex<T> num = c1 * Complex<T>.Conj(c2); Double ReNum = (dynamic)num.Re; Double ImNum = (dynamic)num.Im; return new Complex<double>(ReNum / ac2 / ac2, ImNum / ac2 / ac2); } } public static bool operator >(Complex<T> c1, Complex<T> c2) { if (Complex<T>.Abs(c1) == Complex<T>.Abs(c2)) return (Complex<T>.Angle(c1) > Complex<T>.Angle(c2)); else return (Complex<T>.Abs(c1) > Complex<T>.Abs(c2)); } public static bool operator <(Complex<T> c1, Complex<T> c2) { return !(c1 > c2); } public static bool operator >=(Complex<T> c1, Complex<T> c2) { if (Complex<T>.Abs(c1) == Complex<T>.Abs(c2)) return (Complex<T>.Angle(c1) >= Complex<T>.Angle(c2)); else return (Complex<T>.Abs(c1) >= Complex<T>.Abs(c2)); } public static bool operator <=(Complex<T> c1, Complex<T> c2) { if (Complex<T>.Abs(c1) == Complex<T>.Abs(c2)) return (Complex<T>.Angle(c1) <= Complex<T>.Angle(c2)); else return (Complex<T>.Abs(c1) <= Complex<T>.Abs(c2)); } /// <summary> /// Returns a boolean value indicating if the complex numbers, c1 and c2, are the same /// </summary> /// <param name="c1"></param> /// <param name="c2"></param> /// <returns></returns> public static bool operator ==(Complex<T> c1, Complex<T> c2) { return ((dynamic)c1.Re == c2.Re && (dynamic)c1.Im == c2.Im); } /// <summary> /// Returns a boolean value indicating if the complex numbers, c1 and c2, are not the same /// </summary> /// <param name="c1"></param> /// <param name="c2"></param> /// <returns></returns> public static bool operator !=(Complex<T> c1, Complex<T> c2) { return !(c1 == c2); } /// <summary> /// Creates a Complex<T> number from a type T number with real part r1 and imaginary part 0.0 /// </summary> /// <param name="r1"></param> /// <returns></returns> public static implicit operator Complex<T>(T r1) { return new Complex<T>(r1); } /// <summary> /// Creates a Double number from a Complex by accessing the real part of the complex number. /// Returns an exception if the number is not purely real. /// </summary> /// <param name="d1"></param> /// <returns></returns> public static explicit operator T(Complex<T> d1) { return d1.Re; } public static explicit operator Complex<T>(Matrix<T> m) { if (m.NumElements == 1) return new Complex<T>(m[1]); else { String message = "Cannot convert a " + m.NumRows.ToString() + " by " + m.NumCols.ToString() + " matrix into a single complex number."; throw new ArgumentOutOfRangeException("Matrix Size", message); } } #endregion #region Interfaces public object Clone() // ICloneable { Complex<T> c = new Complex<T>(Re, Im); return c; } // ISerializable public void GetObjectData(SerializationInfo info, StreamingContext ctx) { info.AddValue("Real", Re); info.AddValue("Complex", Im); } #endregion #region Statics /// <summary> /// Returns the complex conjugate of the complex number c /// </summary> /// <param name="c1"></param> public static Complex<T> Conj(Complex<T> c) { return new Complex<T>(c.Re, -(dynamic)c.Im); } /// <summary> /// Returns the absolute value (or norm) of the complex number c /// </summary> /// <param name="c"></param> /// <returns>double</returns> public static double Abs(Complex<T> c) { return System.Math.Sqrt((dynamic)c.Re * c.Re + (dynamic)c.Im * c.Im); } /// <summary> /// Returns the absolute value (or norm) of the complex number c /// </summary> /// <param name="c"></param> /// <returns>double</returns> public static double Norm(Complex<T> c) { return Complex<T>.Abs(c); } public static double Angle(Complex<T> c) { return System.Math.Atan2((dynamic)c.Im, (dynamic)c.Re); } /// <summary> /// Returns the Inverse of a complex number /// </summary> /// <param name="c"></param> /// <returns>Complex</returns> public static Complex<T> Inv(Complex<T> c) { return Conj(c) / (dynamic)(Abs(c) * Abs(c)); } /// <summary> /// Complex exponential function. /// </summary> /// <param name="c"></param> /// <returns></returns> public static Complex<T> Exp(Complex<T> c) { return new Complex<T>(System.Math.Exp((dynamic)c.Re) * System.Math.Cos((dynamic)c.Im), System.Math.Exp((dynamic)c.Re) * System.Math.Sin((dynamic)c.Im)); } public static Complex<T> Max(Complex<T> c1, Complex<T> c2) { if (c1 >= c2) return c1; else return c2; } public static Complex<T> Min(Complex<T> c1, Complex<T> c2) { { if (c1 <= c2) return c1; else return c2; } } #endregion #region Overrides /// <summary> /// Converts a Comlex number to a string such as: "3.2 + 4.3j" /// </summary> /// <returns></returns> public override string ToString() { if (IsReal()) return (string.Format("{0}", Re)); else if ((dynamic)Im < 0) return (string.Format("{0} - {1}j", Re, System.Math.Abs((dynamic)Im))); else return (string.Format("{0} + {1}j", Re, Im)); } /// <summary> /// Determines if two complex numbers are equal by comparing ToString() method /// </summary> /// <param name="obj"></param> /// <returns>bool</returns> public override bool Equals(object obj) { return obj.ToString() == ToString(); } /// <summary> /// Gets the hash code of a complex based on the ToString() method /// </summary> /// <returns>int</returns> public override int GetHashCode() { return ToString().GetHashCode(); } #endregion #region Dynamics public bool IsReal() { return (dynamic)Im == 0.0; } public bool IsImaginary() { return (dynamic)Re == 0.0; } #endregion } }
6d2d9574f80a53597746a792f6ba100ed34ec872
C#
optimax/SimpleRazor
/SimpleRazor/Razor.cs
2.515625
3
using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Web.Razor; using Microsoft.CSharp; namespace SimpleRazor { /// <summary> /// Provides access to the SimpleRazor engine. /// </summary> public static class Razor { /// <summary> /// Gets the last templates generated code. /// </summary> /// <value> /// The generated code. /// </value> public static string LastGeneratedCode { get; private set; } /// <summary> /// Renders the specified template and model. /// </summary> /// <typeparam name="T">The model type.</typeparam> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <returns>The rendered template output.</returns> /// <exception cref="TemplateCompileException">Thrown when template compiling fails.</exception> public static string Render<T>(string template, T model) { var anonymous = model.GetType().IsAnonymousType(); var host = new RazorEngineHost(new CSharpRazorCodeLanguage()) { DefaultBaseClass = anonymous ? "TemplateBase<dynamic>" : string.Format("TemplateBase<{0}>", typeof (T).FullName), DefaultClassName = "GeneratedTemplate", DefaultNamespace = "SimpleRazor" }; host.NamespaceImports.Add("System"); host.NamespaceImports.Add("System.Collections.Generic"); host.NamespaceImports.Add("System.Linq"); var engine = new RazorTemplateEngine(host); var reader = new StringReader(template); var razorResult = engine.GenerateCode(reader); reader.Dispose(); var codeProvider = new CSharpCodeProvider(); using (var writer = new StringWriter()) { codeProvider.GenerateCodeFromCompileUnit(razorResult.GeneratedCode, writer, new CodeGeneratorOptions()); LastGeneratedCode = writer.ToString(); } var referencedAssemblies = new List<string> { Assembly.GetExecutingAssembly().Location, // Hack: Ensure System.Linq and Microsoft.CSharp are loaded typeof (System.Linq.Enumerable).Assembly.Location, typeof (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.Location }; referencedAssemblies.AddRange(GetReferencedAssemblies<T>()); var compilerParameters = new CompilerParameters(referencedAssemblies.Distinct().ToArray()) { GenerateInMemory = true }; var compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode); if (compilerResults.Errors.HasErrors) { throw new TemplateCompileException(compilerResults.Errors); } dynamic templateInstance; if (anonymous) { templateInstance = (TemplateBase<dynamic>) compilerResults.CompiledAssembly.CreateInstance("SimpleRazor.GeneratedTemplate"); templateInstance.Model = model.ToExpando(); } else { templateInstance = (TemplateBase<T>) compilerResults.CompiledAssembly.CreateInstance("SimpleRazor.GeneratedTemplate"); templateInstance.Model = model; } return templateInstance.ToString(); } private static IEnumerable<string> GetReferencedAssemblies<T>() { var declaringAssembly = typeof (T).Assembly; yield return declaringAssembly.Location; foreach (var assemblyName in declaringAssembly.GetReferencedAssemblies()) { yield return Assembly.ReflectionOnlyLoad(assemblyName.FullName).Location; } } } }
bdce192022d066741b0e4403e05ac7852124b529
C#
ahmedfathy74/Search-Engine
/third module/Finalmodule/Finalmodule/Models/algorithms.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Finalmodule.Models; namespace Finalmodule.Models { public class algorithms { public string soundexalgorithm(string stringdata) { string x = ""; x += stringdata[0]; List<int> intgersss = new List<int>(); for (int i = 1; i < stringdata.Length; i++) { x += changeletter(stringdata[i]); if (x[i - 1] == x[i]) { intgersss.Add(i); } } for (int y = intgersss.Count - 1; y >= 0; y--) { x = x.Remove(intgersss[y], 1); } x = x.Replace("0", ""); x = x.Trim(); while (x.Length < 4) { x += "0"; } if (x.Length > 4) { x = x.Substring(0, 4); } return x; } public List<string> k_gram_algorithm(string data_str) { // ahmed ---> $ah,ahm,hme,med,ed$ string y = "$" + data_str.Substring(0, 2); List<string> list1 = new List<string>(); list1.Add(y); int j = 2; for (int i = 1; i < data_str.Length - 1; i++) { string x = list1[i - 1].Substring(1, 2); string x2 = x + data_str[j]; j++; list1.Add(x2); } int last_two = data_str.Length - 2; string last = data_str.Substring(last_two, 2) + "$"; list1.Add(last); return list1; } private char changeletter(char character) { if ("bfpv".Contains(character)) { return '1'; } if ("cgjkqsxz".Contains(character)) { return '2'; } if ("dt".Contains(character)) { return '3'; } if ('l' == character) { return '4'; } if ("mn".Contains(character)) { return '5'; } if ('r' == character) { return '6'; } return '0'; } } }
493fade25ff7b1d9da6fc1d6cf5dfa1dca60346f
C#
seanmobrien/CryptoKitties.Net.Api
/src/CryptoKitties.Net.Api/Api/Models/KittyBase.cs
2.515625
3
using System; using System.Runtime.Serialization; namespace CryptoKitties.Net.Api.Models { /// <summary> /// Base class shared by all kitties /// </summary> [DataContract] [KnownType(typeof(KittySummary))] [KnownType(typeof(Kitty))] [KnownType(typeof(RelatedKitty))] public class KittyBase { /// <summary> /// Kitty Id /// </summary> [DataMember(Name="id")] public Int64 Id { get; set; } /// <summary> /// Nickname /// </summary> [DataMember(Name="name")] public string Name { get; set; } /// <summary> /// URL to kitty image /// </summary> [DataMember(Name="image_url")] public string ImageUrl { get; set; } /// <summary> /// URL to cdn-based kitty image /// </summary> [DataMember(Name="image_url_cdn")] public string ImageUrlCdn { get; set; } /// <summary> /// The Generation of this kitty /// </summary> [DataMember(Name="generation")] public int Generation { get; set; } /// <summary> /// When the kitty was created /// </summary> [DataMember(Name="created_at")] public DateTime CreatedAt { get; set; } /// <summary> /// The color of the kitty /// </summary> [DataMember(Name="color")] public string Color{ get; set; } /// <summary> /// If <c>true</c> then the kitty is fancy. /// </summary> [DataMember(Name="is_fancy")] public bool IsFancy { get; set; } /// <summary> /// The name of this kitty&apos;s &quot;Fancy&quot; type. /// </summary> [DataMember(Name="fancy_type")] public string FancyType { get; set; } /// <summary> /// If set to <c>true</c> then this is an exclusive kitty. /// </summary> [DataMember(Name="is_exclusive")] public bool IsExclusive { get; set; } /// <summary> /// A <see cref="Profile"/> describing the owner. /// </summary> [DataMember(Name="owner")] public Profile Owner { get; set; } /// <summary> /// A <see cref="KittyStatus"/> containing kitty status. /// </summary> [DataMember(Name="status")] public KittyStatus Status { get; set; } /// <summary> /// Whether or not this kitty was hatched? /// </summary> [DataMember(Name="hatched")] public bool Hatched { get; set; } } }
e65b3b7e6a1c6190d61e6222854b5ebabd602599
C#
milchr/Sports-meeting
/SportsMeeting/Shared/Dto/PageResult.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SportsMeeting.Shared.Dto { public class PageResult<T> { public List<T> Items { get; set; } public int TotalPages { get; set; } public int ItemFrom { get; set; } public int ItemTo { get; set; } public int TotalItemCount { get; set; } public PageResult(List<T> items, int totalCount, int quantity, int page) { Items = items; TotalItemCount = totalCount; ItemFrom = quantity * (page - 1) + 1; ItemTo = ItemFrom + quantity - 1; TotalPages = (int)Math.Ceiling(totalCount /(double) quantity); } } }
ec926675455e03d9d0dca034f6425aee21f6396f
C#
uira-alberto/LanchesDemo
/Singleton/CookList.cs
3.28125
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using LanchesDemo.Models; using LanchesDemo.Util; namespace LanchesDemo.Singleton { public class CookList { public CookList() { items = new List<Cook>(); ItemsWaiting = new Queue<Cook>(); } /// <summary> /// Lista de Itens / ReadOnly /// </summary> private List<Cook> items; public List<Cook> Items { get { return items; } } /// <summary> /// Adiciona itens na lista. Se lista esta cheia {AppSettings.CookListMax} Adiciona na fila. /// </summary> /// <param name="cook"></param> public void AddItem(Cook cook) { if (Items.Count >= AppSettings.CookListMax) { ItemsWaiting.Enqueue(cook); } else { Items.Add(cook); } } //Alterar o status de preparação de um item da lista. public Cook ChangePreparationStatus(int idCook, Cook.Status status) { var selitem = Items.Where(x => x.Id == idCook).FirstOrDefault(); selitem.PreparationStatus = status; //se for o final da preparação retira o //elemento da lista e adiciona novo da fila. if (selitem.PreparationStatus == Cook.Status.delivered) { Items.Remove(selitem); if (ItemsWaiting.Count() > 0) { Items.Add(ItemsWaiting.Dequeue()); } } return selitem; } public Queue<Cook> ItemsWaiting {get; set;} } }
b844e509842e0477c9ac2b961f0d24c95124c6b2
C#
Matheus1923/Miltec
/MiltecEstagio/MiltecEstagio/Controllers/TutorController.cs
2.703125
3
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MiltecEstagio.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MiltecEstagio.Controllers { [Route("api/[controller]")] [ApiController] public class TutorController : ControllerBase { public Contexto contexto { get; set; } public TutorController(Contexto novoContexto) { this.contexto = novoContexto; } [HttpGet] public List<Tutor> Get() { return contexto.Tutors.ToList(); } [HttpGet("{id}")] public Tutor Get(int id) { return contexto.Tutors.First(e => e.IdTutor == id); } [HttpPost] public String Post([FromBody] Tutor tutor) { try { tutor.IdTutor = 0; contexto.Tutors.Add(tutor); contexto.SaveChanges(); return "ok"; } catch (Exception e) { return "Erro" + e.Message; } } [HttpPut] public String Put([FromBody] Tutor tutor) { try { contexto.Tutors.Update(tutor); contexto.SaveChanges(); return "ok"; }catch (Exception e) { return "Erro" + e.Message; } } } }
b7775bc53c74c796983b0c133c902d2415a8fe23
C#
willardf/InfiniteCyborg
/InfiniteCyborg/Lights/FOVSolver.cs
2.90625
3
using InfCy.GameCore; using InfCy.Maths; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InfCy.Lights { class FOVSolver { public int X { get; private set; } public int Y { get; private set; } private float[][] lightMap; public int Radius { get; private set; } private Func<float, float> rStrat; private Map map; private readonly static int[] Directions = { 1, 1, -1, -1, 1 }; public FOVSolver(int radius) { this.Radius = radius; lightMap = new float[radius * 2][]; for (int i = 0; i < lightMap.Length; ++i) { lightMap[i] = new float[radius * 2]; } } public void calculateFOV(Map resistanceMap, int startx, int starty, Func<float, float> rStrat) { this.X = startx; this.Y = starty; this.rStrat = rStrat; this.map = resistanceMap; for (int i = 0; i < lightMap.Length; ++i) { for (int j = 0; j < lightMap.Length; ++j) lightMap[i][j] = 0; } lightMap[startx - X + Radius][starty - Y + Radius] = rStrat(0);//light the starting cell for (int i = 0; i < Directions.Length - 1; ++i) { castLight(1, 1.0f, 0.0f, 0, Directions[i], Directions[i + 1], 0); castLight(1, 1.0f, 0.0f, Directions[i], 0, 0, Directions[i + 1]); } } private void castLight(int row, float start, float end, int xx, int xy, int yx, int yy) { if (start < end) return; float newStart = 0.0f; bool blocked = false; for (int distance = row; distance <= Radius && !blocked; distance++) { int deltaY = -distance; for (int deltaX = -distance; deltaX <= 0; deltaX++) { int currentX = X + deltaX * xx + deltaY * xy; int currentY = Y + deltaX * yx + deltaY * yy; float leftSlope = (deltaX - 0.5f) / (deltaY + 0.5f); float rightSlope = (deltaX + 0.5f) / (deltaY - 0.5f); if (!(currentX >= 0 && currentY >= 0 && currentX < map.Width && currentY < map.Height) || start < rightSlope) { continue; } else if (end > leftSlope) { break; } //check if it's within the lightable area and light if needed var rLen = Length(deltaX, deltaY); if (rLen < Radius) { lightMap[currentX - X + Radius][currentY - Y + Radius] = rStrat(rLen); } if (blocked) //previous cell was a blocking one { if (!map.Transparent(currentX, currentY)) //hit a wall { newStart = rightSlope; continue; } else { blocked = false; start = newStart; } } else { if (!map.Transparent(currentX, currentY) && distance < Radius) { // hit a wall within sight line blocked = true; castLight(distance + 1, start, leftSlope, xx, xy, yx, yy); newStart = rightSlope; } } } } } private static float Length(int x, int y) { return (float)Math.Sqrt(x * x + y * y); } internal float getIntensity(int lx, int ly) { return lightMap[lx][ly]; } } }
9e198d20f8779ce5ba589a91f84deee89cedc688
C#
xnlzg/LebiShop
/DB.shop/Bussiness/B_Lebi_Order.cs
2.5625
3
using System; using System.Data; using System.Collections.Generic; using System.Text.RegularExpressions; using LB.DataAccess; namespace DB.LebiShop { /// <summary> /// 业务逻辑类B_Lebi_Order 的摘要说明。 /// </summary> public partial class B_Lebi_Order { public B_Lebi_Order() {} #region 成员方法 /// <summary> /// 返回单个字符串 /// </summary> public static string GetValue(string col,string where, int seconds=0) { return D_Lebi_Order.Instance.GetValue(col,where,seconds); } /// <summary> /// 返回记录条数 /// </summary> public static int Counts(string where, int seconds=0) { return D_Lebi_Order.Instance.Counts(where,seconds); } public static int Counts(SQLPara para, int seconds=0) { return D_Lebi_Order.Instance.Counts(para,seconds); } /// <summary> /// 增加一条数据 /// </summary> public static int Add(Lebi_Order model) { return D_Lebi_Order.Instance.Add(model); } /// <summary> /// 更新一条数据 /// </summary> public static void Update(Lebi_Order model) { D_Lebi_Order.Instance.Update(model); } /// <summary> /// 删除一条数据 /// </summary> public static void Delete(int id) { D_Lebi_Order.Instance.Delete(id); } /// <summary> /// 删除多条数据 by where条件 /// </summary> public static void Delete(string where) { D_Lebi_Order.Instance.Delete(where); } /// <summary> /// 删除多条数据 /// </summary> public static void Delete(SQLPara para) { D_Lebi_Order.Instance.Delete(para); } /// <summary> /// 得到一个对象实体 /// </summary> public static Lebi_Order GetModel(int id, int seconds=0) { return D_Lebi_Order.Instance.GetModel(id,"",seconds); } /// <summary> /// 得到一个对象实体 by where条件 /// </summary> public static Lebi_Order GetModel(string where, int seconds=0) { return D_Lebi_Order.Instance.GetModel(where,"",seconds); } public static Lebi_Order GetModel(SQLPara para, int seconds=0) { return D_Lebi_Order.Instance.GetModel(para,seconds); } /// <summary> /// 得到最大ID /// </summary> public static int GetMaxId() { return D_Lebi_Order.Instance.GetMaxID(""); } public static int GetMaxId(SQLPara para) { return D_Lebi_Order.Instance.GetMaxID(para); } public static int GetMaxId(string strWhere) { return D_Lebi_Order.Instance.GetMaxID(strWhere); } /// <summary> /// 获得数据列表 /// </summary> public static List<Lebi_Order> GetList(string strWhere,string strFieldOrder, int seconds=0) { return D_Lebi_Order.Instance.GetList(strWhere,"",strFieldOrder,seconds); } public static List<Lebi_Order> GetList(string strWhere, string strFieldShow,string strFieldOrder, int seconds=0) { return D_Lebi_Order.Instance.GetList(strWhere,strFieldShow,strFieldOrder,seconds); } public static List<Lebi_Order> GetList(SQLPara para, int seconds=0) { return D_Lebi_Order.Instance.GetList(para,seconds); } public static List<Lebi_Order> GetList(string strWhere, string strFieldOrder, int PageSize, int page, int seconds=0) { return D_Lebi_Order.Instance.GetList(strWhere,"",strFieldOrder,PageSize,page,seconds); } public static List<Lebi_Order> GetList(string strWhere, string strFieldShow, string strFieldOrder, int PageSize, int page, int seconds=0) { return D_Lebi_Order.Instance.GetList(strWhere,strFieldShow,strFieldOrder,PageSize,page,seconds); } public static List<Lebi_Order> GetList(SQLPara para, int PageSize, int page, int seconds=0) { return D_Lebi_Order.Instance.GetList(para,PageSize,page,seconds); } /// <summary> /// 绑定表单数据 /// </summary> public static Lebi_Order BindForm(Lebi_Order model) { return D_Lebi_Order.Instance.BindForm(model); } /// <summary> /// 安全方式绑定表单数据 /// </summary> public static Lebi_Order SafeBindForm(Lebi_Order model) { return D_Lebi_Order.Instance.SafeBindForm(model); } #endregion 成员方法 } }
8348899a9d841a7eb5706b31107a140c24b9e017
C#
pavoldecky/docker-demo
/Demo 4/src/Database.cs
2.578125
3
using Microsoft.EntityFrameworkCore; public class DatabaseContext : DbContext { public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { this.Database.EnsureCreated(); } public DbSet<Product> Products { get; set; } } public class Product { public int Id { get; set; } public string Name { get; set; } }
6117c8c2fa2698c1c59d0542cf54e24d07f2f2b2
C#
aceven24/ShipStation4Net
/ShipStation4Net/Filters/ProductsFilter.cs
2.578125
3
#region License /* * Copyright 2017 Brandon James * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using ShipStation4Net.Domain.Enumerations; using System; using System.Collections.Generic; namespace ShipStation4Net.Filters { public class ProductsFilter : Filter { /// <summary> /// Returns products that match the specified SKU. /// </summary> public string Sku { get; set; } /// <summary> /// Returns products that match the specified product name. /// </summary> public string Name { get; set; } /// <summary> /// Returns products that match the specified productCategoryId. /// </summary> public string ProductCategoryId { get; set; } /// <summary> /// Returns products that match the specified productTypeId. /// </summary> public string ProductTypeId { get; set; } /// <summary> /// Returns products that match the specified tagId. /// </summary> public string TagId { get; set; } /// <summary> /// Returns products that were created after the specified date. /// </summary> public DateTime? StartDate { get; set; } /// <summary> /// Returns products that were created before the specified date. /// </summary> public DateTime? EndDate { get; set; } /// <summary> /// Sorts the order of the response based off the specified value. /// Possible values: /// SKU , ModifyDate , CreateDate. /// </summary> public ProductsSortBy? SortBy { get; set; } /// <summary> /// Sets the direction of the sort order. /// </summary> public SortDir? SortDir { get; set; } /// <summary> /// Specifies whether the list should include inactive products. /// Default: false. /// </summary> public bool? ShowInactive { get; set; } protected override Dictionary<string, object> GetFilters() { var res = base.GetFilters(); res["sku"] = Sku; res["name"] = Name; res["productCategoryId"] = ProductCategoryId; res["productTypeId"] = ProductTypeId; res["tagId"] = TagId; res["startDate"] = StartDate; res["endDate"] = EndDate; res["sortBy"] = SortBy; res["sortDir"] = SortDir; res["showInactive"] = ShowInactive; return res; } } }
54744b216c92e42fd770b0e3e911d66ec35edc87
C#
MohamedSadat/R.Gear
/CHead.cs
2.65625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RGear { public class CHead { public readonly string _EndTag = "</head>"; public readonly string _BeginTag = "<head>"; public readonly string _BeginStyle = "<style>"; public readonly string _EndStyle = "</style>"; private readonly string _beginTitle = "<title>"; private readonly string _endTitle = "</title>"; public string _Meta = "<meta charset=\"UTF-8\" />"; //html5 standard private string _title = ""; private string _style=""; private StringBuilder s = new StringBuilder(); public CHead() { s.Append(_BeginTag); s.Append(_BeginStyle); } public CHead(string title) { Title = title; s.Append(_BeginTag); s.Append(_BeginStyle); } public string Title { get { return _beginTitle+_title+ _endTitle; } set { _title = value; } } public string Meta { get { return _Meta; } set { _Meta = value; } } public string Style { get { return _style; } set { _style = value; } } public void AddTitle(string title) { Title = title; //s.Append(title); } public void AddStyle(string style) { s.Append(style); } public void AddMeta(string meta) { Meta = meta; } public string GenerateTag() { // s.Append(Title); s.Append(_EndStyle); s.Append(Title); s.Append(Meta); s.Append(_EndTag); return s.ToString(); } } }
be2774b84009535a1bd7e7b8199e5eadc863bd5c
C#
chadphanson/Cherwell_ChadHanson_CodeTest
/TriangleAPI/Controllers/TriangleController.cs
3.171875
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Drawing; namespace TriangleAPI.Controllers { [RoutePrefix("api/triangles")] public class TriangleController : ApiController { public Dictionary<string, int> RowNumbers = new Dictionary<string, int>(); [Route("getcoordinatesbyrowandcolumn/{row}/{column}")] public HttpResponseMessage GetCoordinatesByRowAndColumn(string Row, int Column) { List<Point> returnPoints = new List<Point>(); bool columnIsEven = Column % 2 == 0; // load row/letter mapping LoadDictionary(); // check for valid input value if (!RowNumbers.Any(c => c.Key == Row) || (Column < 1 || Column > 12)) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "That is not a valid row/column input."); } int RowNumber = RowNumbers.Single(c => c.Key == Row).Value; // *** FIRST COORDINATE *** int Coord1X = 0; // get X pos // -- if column is even, multiply it by 10 then reduce by half. // -- else, multiple it by 10, subtract 10, then divide in half Coord1X = columnIsEven ? ((Column * 10) / 2) : (((Column * 10) - 10) / 2); // get Y pos. if column is even, add 10 int Coord1Y = RowNumber * -10; if (columnIsEven) { Coord1Y += 10; } Point Coord1 = new Point(Coord1X, Coord1Y); returnPoints.Add(Coord1); // *** SECOND COORDINATE *** // get X pos // -- if column is even, subtract 10 from Coord1X, else use Coord1X int Coord2X = columnIsEven ? Coord2X = Coord1X - 10 : Coord2X = Coord1X; // get Y pos // -- if column is even, use Coord1Y, else add 10 to Coord1Y int Coord2Y = columnIsEven ? Coord2Y = Coord1Y : Coord2Y = Coord1Y + 10; Point Coord2 = new Point(Coord2X, Coord2Y); returnPoints.Add(Coord2); // *** THIRD COORDINATE *** // get X pos // -- if column is even, use Coord1X, else add 10 to Coord1X int Coord3X = columnIsEven ? Coord3X = Coord1X : Coord3X = Coord1X + 10; // get Y pos // -- if column is even, use Coord1Y - 10, else use Coord1Y int Coord3Y = columnIsEven ? Coord3Y = Coord1Y - 10 : Coord3Y = Coord1Y; Point Coord3 = new Point(Coord3X, Coord3Y); returnPoints.Add(Coord3); return Request.CreateResponse(HttpStatusCode.OK, returnPoints); } [Route("getrowandcolumnbycoordinates")] [HttpPost] public HttpResponseMessage GetRowAndColumnByCoordinates([FromBody] List<Point> coords) { // load row/letter mapping LoadDictionary(); Point Coord1 = coords[0]; Point Coord2 = coords[1]; Point Coord3 = coords[2]; // determine if triangle is oriented up (odd column) or down (even column) based on given coords bool columnIsEven = Coord2.X == Coord1.X - 10 ? true : false; // calculate to find Row and Column values int Row = columnIsEven ? Math.Abs(Coord1.Y / 10) + 1 : Math.Abs(Coord1.Y / 10); int Column = columnIsEven ? (Coord1.X / 5) : (((Coord1.X / 10) * 2) + 1); // check for values outside of acceptable ranges if (!RowNumbers.Any(c => c.Value == Row) || (Column < 1 || Column > 12)) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No triangle found for those coordinates."); } string RowStr = RowNumbers.Single(c => c.Value == Row).Key; string ColumnStr = Column.ToString(); return Request.CreateResponse(HttpStatusCode.OK, RowStr + ColumnStr); } public void LoadDictionary() { RowNumbers.Add("A", 1); RowNumbers.Add("B", 2); RowNumbers.Add("C", 3); RowNumbers.Add("D", 4); RowNumbers.Add("E", 5); RowNumbers.Add("F", 6); } } }
ccbc364368950bb93869caf6930a02e2e6944cfb
C#
pjtown/csharp-oauth
/OAuth/Core/OAuthParameter.cs
2.6875
3
// Copyright 2013 Peter Townsend // Licensed under the MIT License namespace OAuth.Core { public class OAuthParameter { private string name; private string value; public OAuthParameter(string name) { this.Name = name; } public string Name { get { return this.name; } set { this.name = value; this.EncodedName = RFC3986.Encode(this.name); } } public string Value { get { return this.value; } set { this.value = value; this.EncodedValue = RFC3986.Encode(this.value); } } public string EncodedName { get; set; } public string EncodedValue { get; set; } public override string ToString() { return string.Format("{0}=\"{1}\"", this.EncodedName, this.EncodedValue); } } }
7a81fc5f13c249194c8f86dd0ddea8b8d00d2dbb
C#
miRoox/Leetcode
/csharp/merge-two-sorted-lists/tests/ListUnitTest.cs
2.828125
3
using System; using Xunit; namespace MergeTwoSortedLists.Tests { public class ListUnitTest { [Fact] public void Test0() { Assert.Null(ListNode.Create()); } [Fact] public void Test1() { Assert.Equal(new ListNode(1), ListNode.Create(1)); } [Fact] public void Test2() { Assert.Equal(new ListNode(1, new ListNode(2)), ListNode.Create(1, 2)); } } }
388643f991b41256f20c57e85f5bd7ad98ebb6e0
C#
natsnudasoft/EgamiFlowScreensaver
/src/EgamiFlowScreensaver/IImageScaleService.cs
2.59375
3
// <copyright file="IImageScaleService.cs" company="natsnudasoft"> // Copyright (c) Adrian John Dunstan. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> namespace Natsnudasoft.EgamiFlowScreensaver { using System.Drawing; /// <summary> /// Provides an interface describing methods for performing scaling of images. /// </summary> public interface IImageScaleService { /// <summary> /// Scales the specified image to the specified size using the specified /// <see cref="ImageScaleMode"/>. /// </summary> /// <param name="image">The original image to scale.</param> /// <param name="scaleSize">The area that the image is being scaled to.</param> /// <param name="imageScaleMode">The image scale mode to use.</param> /// <returns>A <see cref="Bitmap"/> of the scaled image.</returns> Bitmap ScaleImage(Image image, Size scaleSize, ImageScaleMode imageScaleMode); } }
5273f849e3b52775265f9eca9d4ff48baf76ea5a
C#
antwit/CourseChecker_
/ConsoleApp1/ConsoleApp1/SiteReader/GetCourseUrlsFromIntegrata.cs
2.921875
3
using CourseChecker.Course; using HtmlAgilityPack; using NLog; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace CourseChecker.SiteReader { /// <summary> /// Sammelt alle URL's zu den Kursen auf der gegebenen Seite /// </summary> class GetCourseUrlsFromIntegrata { private static Logger logger = LogManager.GetCurrentClassLogger(); private HtmlWeb webContent = new HtmlWeb(); internal Queue<Uri> SetsOfUrls { get; set; } private List<Uri> listURI = new List<Uri>(); private List<string> listIDs = new List<string>(); internal List<Kurse> GetCourses { get; set; } /// <summary> /// Kostruktor /// </summary> /// <param name="listUris">URL's zu den entsprechenden Webseiten</param> /// <param name="listIDs">Liste mit ID's werden benutzt um die Daten Selektieren zu können</param> public GetCourseUrlsFromIntegrata(List<Uri> listUris, List<String> listIDs) { SetsOfUrls = new Queue<Uri>(); this.listIDs.AddRange(listIDs); this.listURI.AddRange(listUris); CollectUrls(); } /// <summary> /// Aus der URL wird der Quelltext extrahiert /// </summary> private void CollectUrls() { Parallel.For(0,listURI.Count, i => { HtmlDocument htmlDoc = webContent.Load(this.listURI[i]); GetSingleUrls(htmlDoc, this.listIDs[i]); }); } /// <summary> /// Extrahieren der Links zu den gegebenen Quelltext /// </summary> /// <param name="htmlDoc">Quelltext</param> /// <param name="strID">Liste mit ID's werden benutzt um die Daten Selektieren zu können</param> private void GetSingleUrls(HtmlDocument htmlDoc, string strID) { HtmlNode nodeID = htmlDoc.DocumentNode.SelectSingleNode("//*[@id='" + strID + "']"); HtmlNodeCollection collNode = nodeID.SelectNodes(".//a[@class='column-group__sub-item-link']"); foreach(HtmlNode singleNode in collNode) { Uri uri = new Uri(singleNode.Attributes["href"].Value); SetsOfUrls.Enqueue(uri); } } } }
685153db26960e52db1759aa96e6928077e74428
C#
TVetrovsky/SudokuSolver
/SudokuSolver/MatrixConsolePrinter.cs
3.03125
3
/* * Created by SharpDevelop. * User: tomas * Date: 24.09.2017 * Time: 21:59 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Linq; namespace SudokuSolver { public static class MatrixConsolePrinter { public static void Print(Matrix m) { for(int i = 0; i < Matrix.MAX; i++) { for(int triple = 0 ; triple <3; triple++) { for(int j = 0; j < Matrix.MAX; j++) { var states = m[i, j].GetValidStates().Skip(triple*3).Take(3).ToArray(); Console.Write(String.Join("", states).PadRight(3)); if((j % 3) == 2) Console.Write(" * "); else Console.Write(" | "); } Console.WriteLine(); } if((i % 3) == 2) Console.WriteLine(String.Empty.PadRight(6*9, '*')); else Console.WriteLine(String.Empty.PadRight(6*9, '-')); } } } }