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
dd32c3b7efc8a210ab3d56360dc1309b44298c63
C#
XemioNetwork/CommonLibrary
/Xemio.CommonLibrary/Administration/Impersonator.cs
2.609375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Permissions; using System.Security.Principal; using System.Text; using Xemio.CommonLibrary.Common; namespace Xemio.CommonLibrary.Administration { /// <summary> /// Provides impersonation as another user. /// </summary> public class Impersonator { #region Fields public string Domain { get; private set; } public string Username { get; private set; } public string Password { get; private set; } private IntPtr _token; private WindowsImpersonationContext _context; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Impersonator"/> class. /// </summary> /// <param name="domain">The domain.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> public Impersonator(string domain, string username, string password) { this.Domain = domain; this.Username = username; this.Password = password; } #endregion #region Methods /// <summary> /// Impersonates the current user as <see cref="Username"/>. /// </summary> public IDisposable Impersonate() { if (this._context != null) throw new InvalidOperationException("You can't impersonate while already impersonating. Don't nest the Impersonate calls."); //Just do nothing when no credentials are provided. //Makes it more stable because we don't throw exceptions everywhere... if (string.IsNullOrWhiteSpace(this.Username) || string.IsNullOrWhiteSpace(this.Password) || string.IsNullOrWhiteSpace(this.Domain)) { return new ActionDisposer(() => { }); } try { this._token = IntPtr.Zero; bool logonSuccessfull = LogonUser(this.Username, this.Domain, this.Password, 2, 0, ref _token); if (logonSuccessfull == false) { int error = Marshal.GetLastWin32Error(); throw new Win32Exception(error); } WindowsIdentity identity = new WindowsIdentity(_token); this._context = identity.Impersonate(); return new ActionDisposer(this.LeaveImpersonation); } catch (Exception exception) { throw new InvalidCredentialException("The impersonation failed. For more information see the inner exception.", exception); } } #endregion #region Private Methods /// <summary> /// Leaves the impersonation. /// </summary> private void LeaveImpersonation() { this._context.Undo(); if (this._token != IntPtr.Zero) CloseHandle(this._token); } #endregion #region Windows API [DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); #endregion } }
52334596cba7be0df84fe3472e99f28b976ad998
C#
Trushkeen/RKSI.Net-Solved
/Lab6/Logger.cs
3.125
3
using System.IO; using System.Text; namespace Lab6 { class Logger { string Path { get; } public Logger(string path) { Path = path; } public void WriteLog(string text) { using (StreamWriter sw = new StreamWriter(Path, true, Encoding.Default)) { sw.WriteLine(" " + text); } } public void Calculator_OnDidChangeOperation(ICalculator sender, CalculatorEventArgs eventArgs) { WriteLog(eventArgs.Message + " " + eventArgs.Operation.Value); } public void Calculator_OnDidChangeRight(ICalculator sender, CalculatorEventArgs eventArgs) { WriteLog(eventArgs.Message + " " + eventArgs.RightValue); } public void Calculator_OnDidChangeLeft(ICalculator sender, CalculatorEventArgs eventArgs) { WriteLog(eventArgs.Message + " " + eventArgs.LeftValue); } public void Calculator_OnDidCompute(ICalculator sender, CalculatorEventArgs eventArgs) { var e = eventArgs as ComputeEventArgs; WriteLog($"Посчитано {e.LeftValue} {(char)(CalculatorOperation)e.Operation} {e.RightValue}={e.Result}"); } public void Calculator_OnUnableToCompute(ICalculator sender, CalculatorEventArgs eventArgs) { WriteLog(eventArgs.Message); } } }
4e8a1e94a91b39d5aa6e7077e7198cee66f3dab7
C#
sr-invisible/UCRMS
/UCRMS/UCRMS/Controllers/TeacherController.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using UCRMS.Manager; using UCRMS.Models; namespace UCRMS.Controllers { public class TeacherController : Controller { DesignationManager designationManager = new DesignationManager(); DepartmentManager departmentManager = new DepartmentManager(); TeacherManager teacherManager = new TeacherManager(); // GET: Teacher public ActionResult Save() { ViewBag.Designations = designationManager.GetAllDesignations(); ViewBag.Departments = departmentManager.ShowAllDepartments(); return View(); } [HttpPost] public ActionResult Save(Teacher teacher) { ViewBag.Designations = designationManager.GetAllDesignations(); ViewBag.Departments = departmentManager.ShowAllDepartments(); try { ViewBag.Message = teacherManager.Save(teacher) ? "Teacher Saved" : "Teacher Saved Failed"; } catch (Exception exception) { ViewBag.Message = exception.Message; } return View(); } public JsonResult CheckName(string Email) { var student = teacherManager.IsEmailExist(Email); if (student == true) return Json(false); return Json(true); } } }
bd9c3e37506e0c40a6f2bd4a11b9871ee1b44bc5
C#
aloisdg/Nepholo
/Nepholo.Plugin.Cloud.OneDrive/FileConverter.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; using System.Web.UI; using OneDriveRestAPI.Model; namespace Nepholo.Plugin.Cloud.OneDrive { public static class FileConverter { public static List<File> ToFiles(this IEnumerable<OneDriveRestAPI.Model.File> files) { return files.Select(ToFile).ToList(); } public static File ToFile(this OneDriveRestAPI.Model.File file) { var neo = new File { Id = file.Id, Name = file.Name, IsFolder = file.Type.Equals("folder"), Size = file.Size.ToReadableBytes(), Type = file.Type, Path = file.From.Id, Icon = file.Type.Equals("folder").ToIcon(), ModifiedDate = DateTime.Parse(file.Updated_Time) }; if (!file.Type.Equals("folder") || file.Data == null || !file.Data.Any()) { neo.Files = null; return neo; } foreach (var item in file.Data) neo.Files.Add(item.ToFile()); return neo; } private static string ToIcon(this bool isFolder) { return isFolder ? "https://www.dropbox.com/static/images/icons128/folder.png" : "https://www.dropbox.com/static/images/icons128/page_white.png"; } // http://stackoverflow.com/a/4975942 private static string ToReadableBytes(this long byteCount) { string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; if (byteCount == 0) return "0" + suf[0]; var bytes = Math.Abs(byteCount); var place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024))); var num = Math.Round(bytes / Math.Pow(1024, place), 1); return (Math.Sign(byteCount) * num) + suf[place]; } public static Account ToAccount(this User info, UserQuota quota) { return new Account { Storage = new Storage { Total = quota.Quota, Remaining = quota.Available, Used = quota.Quota - quota.Available }, Email = info.Emails != null ? info.Emails.Preferred : String.Empty, Name = info.Name }; } } }
3d57e764fbcc3af75185211952bbfae5bf64bbbc
C#
shendongnian/download4
/first_version_download2/420744-36931434-116908180-2.cs
2.703125
3
public void db1_read() { if (con_opened == false) { con = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");//Version=3; con_opened = true; con.Open(); } string sql = "select * from bestscore WHERE materie LIKE 'literatura'"; SQLiteCommand command = new SQLiteCommand(sql, con); SQLiteDataReader reader = command.ExecuteReader(); reader.Read(); bs_lit = Int32.Parse(reader[1].ToString()); command.Dispose(); reader.Dispose(); sql = "select * from bestscore WHERE materie LIKE 'informatica'"; SQLiteCommand cmd = new SQLiteCommand(sql, con); SQLiteDataReader rdr = cmd.ExecuteReader(); rdr.Read(); bs_info = Int32.Parse(rdr[1].ToString()); cmd.Dispose(); rdr.Dispose(); con.Close(); con_opened = false; }
7932039fd222f43f99976daad159dc6684420669
C#
SvetoslavPetsev/Arrays---Lab
/07. Equal Arrays/Program.cs
4.03125
4
using System; using System.Linq; namespace _07._Equal_Arrays { class Program { static void Main(string[] args) { int[] arrayA = Console.ReadLine() .Split(' ') .Select(int.Parse) .ToArray(); int[] arrayB = Console.ReadLine() .Split(' ') .Select(int.Parse) .ToArray(); int sum = 0; int counterEqual = 0; int firstDifference = 0; bool findDifference = false; for (int i = 0; i < arrayA.Length; i++) { int currentA = arrayA[i]; int currentB = arrayB[i]; if (currentA == currentB) { sum += currentA; counterEqual++; } else if (currentA != currentB && findDifference == false) { firstDifference = i; findDifference = true; } } if (counterEqual == arrayA.Length) { Console.WriteLine($"Arrays are identical. Sum: {sum}"); } else { Console.WriteLine($"Arrays are not identical. Found difference at {firstDifference} index"); } } } }
d4426031e9d48426501a43b735c5c80cb2b1eb80
C#
iowen/Tricare
/TriCare/TriCare/Views/RefillPage.cs
2.640625
3
using System; using System.Collections.Generic; using TriCare.Data; using Xamarin.Forms; namespace TriCare { public class RefillPage :ContentPage { public RefillPage () { this.BackgroundColor = Color.White; var rRepo = new RefillRepo(); Title = "Refills"; var ra =rRepo.GetAllRefillAmounts(); var qa =rRepo.GetAllRefillQuantities(); var medL = new Label { TextColor = Color.Navy, Text = "Medicine : "+App.CurrentPrescription.Medicine.MedicineName.Trim() }; var amL = new Label { TextColor = Color.Navy, Text = "Refill Amount in Grams", }; var aqL = new Label { TextColor = Color.Navy, Text = "Refill Quantity" }; var refillAmountPicker = new Picker { Title = "Amount", BackgroundColor =Color.Transparent, }; var refillQuantPicker = new Picker { Title = "Quantity", BackgroundColor =Color.Transparent }; var continueButton = new Button { Text = "Continue", BackgroundColor = Color.FromRgba(128, 128, 128, 128), TextColor = Color.White }; continueButton.IsEnabled = false; refillAmountPicker.SelectedIndexChanged += (sender, e) => { if(refillAmountPicker.SelectedIndex >= 0 && refillQuantPicker.SelectedIndex >= 0) { continueButton.IsEnabled = true; } else{ continueButton.IsEnabled = false; } }; refillQuantPicker.SelectedIndexChanged += (sender, e) => { if(refillAmountPicker.SelectedIndex >= 0 && refillQuantPicker.SelectedIndex >= 0) { continueButton.IsEnabled = true; } else{ continueButton.IsEnabled = false; } }; continueButton.Clicked += async (sender, e) => { App.CurrentPrescription.Refill = new TriCare.Models.RefillModel(); App.CurrentPrescription.Refill.Amount = ra[refillAmountPicker.SelectedIndex].RefillAmountId; App.CurrentPrescription.Refill.Quantity = qa[refillQuantPicker.SelectedIndex].RefillQuantityId; await App.np.PushAsync(new VerifyPage()); }; foreach(var r in ra) { refillAmountPicker.Items.Add (r.Amount.ToString ()+" Grams"); } foreach (var q in qa) { if (q.Quantity > 0) { refillQuantPicker.Items.Add (q.Quantity.ToString ()); } else { if (q.Quantity == 0) refillQuantPicker.Items.Add ("NR"); else refillQuantPicker.Items.Add ("PRN"); } } Content = new StackLayout { VerticalOptions = LayoutOptions.FillAndExpand, Padding = new Thickness(40), Children = { medL, amL, refillAmountPicker, aqL,refillQuantPicker,continueButton } }; } } }
3706f09a8d47461b51d4bb3a5d5bb7348155160b
C#
deepaknasa/Coding-Assessments
/IKMAssessment/CSharp/ActionHandler.cs
3.03125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IKMAssessment.CSharp { public delegate void MyActionHandler(List<int> list); class ActionHandler { public event MyActionHandler OnMyMethod; public ActionHandler() { } public void Init() { try { Processor processor = new Processor(); } catch (Exception ex) { Console.WriteLine(ex.GetType().ToString()); } Console.ReadLine(); } public void Execute() { OnMyMethod(new List<int>()); } } class Processor { public Processor() { ActionHandler program = new ActionHandler(); program.OnMyMethod += new MyActionHandler(Method1); program.Execute(); program.OnMyMethod += new MyActionHandler(Method2); program.OnMyMethod += new MyActionHandler(Method3); //program.OnMyMethod(new List<int>()); program.Execute(); } public void Method1(List<int> list) { Console.WriteLine("In method1"); } public void Method2(List<int> list) { Console.WriteLine("In method2"); } public void Method3(List<int> list) { Console.WriteLine("In method3"); } } }
3be5c37b1befd11f3998f4c8ff75a994e51f7d00
C#
Aptacode/Aptacode.TaskPlex
/TaskPlex/Stories/Transformations/BoolTransformation.cs
2.53125
3
using System; namespace Aptacode.TaskPlex.Stories.Transformations { public sealed class BoolTransformation<TClass> : UpdateAtEndTransformation<TClass, bool> where TClass : class { /// <summary> /// Update a bool property on the target to the value returned by the given Func after the task duration /// </summary> public BoolTransformation(TClass target, string property, TimeSpan duration, bool endValue) : base(target, property, duration, endValue) { } } }
22ce73ef433cbeb0f441c39f7c0bfd1e7631d7be
C#
mrvenus314/MyProject
/CSharpDesignMode/CSharpDesignMode/StatePatternSample/Card/PartnerB.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StatePatternModel.Card { public class PartnerB : AbstractCardPartner { public PartnerB(string nickName, int money) { this.NickName = nickName; this.Money = money; } public override void ChangeMoney(int money, AbstractMediator mediator) { mediator.ChangeMoney(money); } } }
cee9bc384e602ded325545c693ac56984382c5f8
C#
SatenikH/IEnumerator_IEnumerable
/ConsoleApp14/PersonList.cs
3.28125
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp14 { public class PersonList:IEnumerable { Person[] persones = new Person[4]; public PersonList() { persones[0] = new Person { Name = "Bijay Thapa", Age = 20}; persones[1] = new Person { Name = "Jack", Age = 18}; persones[2] = new Person { Name = "Anil min", Age = 26}; persones[3] = new Person { Name = "Jim sin", Age = 20 }; } public int Count() { return persones.Count(); } public Person this[int index] { get { return persones[index]; } } public IEnumerator GetEnumerator() { return persones.GetEnumerator(); // we can do this but we are going to make our own Enumerator } } }
f83551d0f7e62c4e0679a8fb86e884abb8ac7dce
C#
Desocrit/BoDCode
/Characters/Stats/StatModifier.cs
2.703125
3
using System; [Serializable] public class StatModifier : IEquatable<StatModifier> { // Stat to be modified. public Statistic modifiedStat; // Amount stat is to be modified. public float modifier; // If the stat should be multiplied instead of added. public bool isMultiplier; // If the stat modifier can be applied multiple times. public bool stackable; private StatModifier() { // For serializer. } public StatModifier(Statistic stat, float mod, bool isMultiplier) { modifiedStat = stat; modifier = mod; this.isMultiplier = isMultiplier; } public bool Equals(StatModifier other) { return modifiedStat == other.modifiedStat && modifier == other.modifier && isMultiplier == other.isMultiplier; } }
68ee3fd08f297847175a966db59e33afd86a0df3
C#
ObjectivityLtd/Bot.Common.Dialogs
/Objectivity.Bot.BaseDialogs/Dialogs/PromptValueDialog.cs
2.6875
3
namespace Objectivity.Bot.BaseDialogs.Dialogs { using System; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Builder.Luis.Models; [Serializable] public abstract class PromptValueDialog<T> : BaseLuisDialog<T> { public string PromptMessage { get; set; } /// <summary> /// This method should be called when Intent is received. /// </summary> public virtual async Task HandleIntent(IDialogContext context, LuisResult result) { var value = this.GetValue(context, result); if (value != null) { this.EndDialog(context, value); } else { await this.PostAndWaitAsync(context, this.UnrecognizedAnswerMessage); } } public override async Task StartAsync(IDialogContext context) { if (!string.IsNullOrEmpty(this.PromptMessage)) { await context.PostAsync(this.PromptMessage); } context.Wait(this.MessageReceived); } protected abstract T GetValue(IDialogContext context, LuisResult result); } }
6a8869de11acb3b8d10e244e014002998683269e
C#
2106-Module1/2106-Module1
/HotelManagementSystem-Module1/HotelManagementSystem-Module1/Domain/IPromoCodeService.cs
2.65625
3
using HotelManagementSystem.Domain.Models; using System.Collections.Generic; /* * Owner of IPromoCodeService Interface: Mod 1 Team 4 */ namespace HotelManagementSystem.Domain { public interface IPromoCodeService { /// <summary> /// Search and retrieve all existing promo code /// </summary> /// <returns>A Enumerable list of promo code records</returns> IEnumerable<PromoCode> GetAllPromoCode(); /// <summary> /// Search and retrieve the existing promo code by promo code input /// </summary> /// <param name="promoCode">The promo code string</param> /// <returns>A promo code object</returns> PromoCode GetPromoCode(string promoCode); /// <summary> /// Create a promo code based on the promo code object /// </summary> /// <param name="promoCode">The promo code string</param> /// <returns>true, if promo code is created successfully</returns> bool CreatePromoCode(PromoCode promoCode); /// <summary> /// Delete a promo code based on the promo code id /// </summary> /// <param name="promoCode">The Id of promo code</param> /// <returns>true, if promo code is deleted successfully</returns> bool DeletePromoCode(int id); /// <summary> /// Update a promo code based on the promo code object /// </summary> /// <param name="promoCode">The promo code object</param> /// <returns>true, if promo code is updated successfully</returns> bool UpdatePromoCode(PromoCode promoCode); } }
24962c137ffc21dbbe48d8445407233d4c8a7557
C#
shimunmatic/iOrder
/BackendUndWeb/iOrder/Backend/Services/Implementation/CategoryService.cs
2.78125
3
using Backend.Models.Business; using Backend.Repositories.Interface; using Backend.Services.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Backend.Services.Implementation { public class CategoryService : ICategoryService { private ICategoryRepository CategoryRepository; //private IEstablishmentService EstablishmentService; private IProductService ProductService; public CategoryService(ICategoryRepository categoryRepository, IProductService productService)//IEstablishmentService establishmentService { CategoryRepository = categoryRepository; // EstablishmentService = establishmentService; ProductService = productService; } public void Delete(object id) { CategoryRepository.Delete(CategoryRepository.GetById(id)); } public IEnumerable<Category> GetAll() { return CategoryRepository.GetAll(); } public IEnumerable<Category> GetAllForEstablishment(long id) { return null; } public IEnumerable<Category> GetAllForOwner(string username) { return CategoryRepository.GetCategoriesOfOwner(username); } public IEnumerable<Category> GetAllForWarehouseId(long id) { var products = ProductService.GetProductsForWarehouseId(id); var categories = new List<Category>(); var categoryIds = (from s in products select s.CategoryId).Distinct().ToList(); foreach (var catId in categoryIds) { var cat = CategoryRepository.GetById(catId); cat.Products = (from p in products where p.CategoryId == catId select p).ToList(); categories.Add(cat); } return categories; } public Category GetById(object id) { return CategoryRepository.GetById(id); } public void Save(Category t) { CategoryRepository.Save(t); } public void Update(object id, Category t) { CategoryRepository.Update(id, t); } } }
d1bed7aae4dceba98d60a8b78007f6449fce62a4
C#
MelissaTorres/GiftshopBackend
/SS.Gift-Shop.Core/IEmailSender.cs
2.84375
3
using System; using System.Net.Mail; using System.Threading.Tasks; namespace SS.GiftShop.Core { public interface IEmailSender { Task Send(MailMessage message); } public static class EmailSenderExtensions { public static Task Send(this IEmailSender emailSender, string subject, string email, string body, bool isBodyHtml = true) { if (emailSender == null) { throw new ArgumentNullException(nameof(emailSender)); } if (email == null) { throw new ArgumentNullException(nameof(email)); } if (subject == null) { throw new ArgumentNullException(nameof(subject)); } if (body == null) { throw new ArgumentNullException(nameof(body)); } var mailMessage = CreateMailMessage(subject, email, body, isBodyHtml); return emailSender.Send(mailMessage); } private static MailMessage CreateMailMessage(string subject, string to, string body = null, bool isBodyHtml = true) { var mailMessage = new MailMessage(); mailMessage.To.Add(to); mailMessage.Subject = subject; if (!string.IsNullOrEmpty(body)) { mailMessage.Body = body; mailMessage.IsBodyHtml = isBodyHtml; } return mailMessage; } } }
449c8696e71949c509907c707d0ea66c1c17ddea
C#
WorldExcSoft/Community
/Community.BLL/ExamCourseBLL.cs
2.578125
3
using System; using System.Collections.Generic; using Community.DAL; using Community.Model; namespace Community.BLL { public class ExamCourseBLL { ExamCourseDAL dal = new ExamCourseDAL(); #region 业务逻辑层其他扩展方法 #endregion #region 业务逻辑层基本方法 /// <summary> /// 增加 /// </summary> /// <param name="ExamCourse">ExamCourse实体对象</param> /// <returns>bool值,判断是否操作成功</returns> public bool Add(ExamCourse model) { return dal.Add(model); } /// <summary> /// 增加 /// </summary> /// <param name="ExamCourse">ExamCourse实体对象</param> /// <returns>int值,返回自增ID</returns> public int AddReturnId(ExamCourse model) { return dal.AddReturnId(model); } /// <summary> /// 修改 /// </summary> /// <param name="ExamCourse">ExamCourse实体对象</param> /// <returns>bool值,判断是否操作成功</returns> public bool Change(ExamCourse model) { return dal.Change(model); } /// <summary> /// 删除 /// </summary> /// <param name="Id">主键Id</param> /// <returns>bool值,判断是否操作成功</returns> public bool Delete(int Id) { return dal.Delete(Id); } /// <summary> /// 根据条件删除 /// </summary> /// <param name="WhereString">删除条件</param> /// <returns>bool值,判断是否操作成功</returns> public bool DeleteByWhere(string WhereString) { return dal.DeleteByWhere(WhereString); } /// <summary> /// 查询全部 /// </summary> public List<ExamCourse> SelectAll() { return dal.SelectAll(); } /// <summary> /// 通过Id查询 /// </summary> /// <param name="Id">主键Id</param> public ExamCourse SelectById(int Id) { return dal.SelectById(Id); } /// <summary> /// 通过条件查询 /// </summary> /// <param name="WhereString">查询条件</param> public List<ExamCourse> SelectByWhere(string WhereString) { return dal.SelectByWhere(WhereString); } /// <summary> /// 通过条件查询并分页 /// </summary> /// <param name="WhereString">查询条件</param> /// <param name="PageIndex">当前页码</param> /// <param name="PageSize">页大小(每页显示多少条数据)</param> /// <param name="OrderString">排序条件</param> /// <param name="TotalCount">返回符合条件的数据总的记录数</param> public List<ExamCourse> SelectByWhereAndPage(string WhereString,int PageIndex,int PageSize,string OrderString,out int TotalCount) { return dal.SelectByWhereAndPage(WhereString , PageIndex , PageSize , OrderString, out TotalCount); } #endregion } }
78664b2bd0002836754042258b7b2c245a381b28
C#
cokceken/Password-Kata1
/Domain/Service/UserService.cs
2.71875
3
using Password.Domain.Contract.UserContract; using Password.Domain.Model; using Password.Domain.Model.Exception; using Password.Domain.UnitOfWork; namespace Password.Domain.Service { public class UserService : IUserService { private readonly IUserDataService _userDataService; public UserService(IUserDataService userDataService) { _userDataService = userDataService; } [UnitOfWork] public User GetUserWithUsername(string username) { var user = _userDataService.GetUserWithUsername(username); if (user == null) { throw new UserNotFoundException($"User not found with username: {username}"); } return user; } public User GetUserWithEmail(string email) { var user = _userDataService.GetUserWithEmail(email); if (user == null) { throw new UserNotFoundException($"User not found with email: {email}"); } return user; } public void UpdateUser(User user) { _userDataService.UpdateUser(user); } } }
f4d0aeffa17bacc975d8be1d111eea378b86e509
C#
danishtech/YouthApp
/YouthApp/Insanity.cs
2.515625
3
//using System; //using System.Collections.Generic; //using System.Linq; //using System.Threading.Tasks; //namespace YouthApp //{ // public class Insanity // { // public async Task<IEnumerable> Quarterly(byte start, byte end) // { // //return await new ApplicationDbContext(dco).Revenues.Select(x => new // { // x.AccountName, // x.AccountNumber, // x.Bank, // x.Source, // Revenue = x.Transactions.Where(t => t.TransactionDate.Year == DateTime.Now.Year && t.TransactionDate.Month >= start && t.TransactionDate.Month <= end && t.TransactionsTypesID == (short)TranTypes.Revenue).GroupBy(t => t.TransactionItems, (k, v) => new // { // Item = k, // Amount = v.Sum(t => t.Amount) // }).ToList(), // Expenditure = x.Transactions.Where(t => t.TransactionDate.Year == DateTime.Now.Year && t.TransactionDate.Month >= start && t.TransactionDate.Month <= end && t.TransactionsTypesID == (short)TranTypes.Expenditure).GroupBy(t => t.TransactionItems, (k, v) => new // { // Item = k, // Amount = v.Sum(t => t.Amount) // }).ToList() // }).ToListAsync(); // } // } //}
c9098d744f9ef8623c3e7572433e3a2b2a2092e3
C#
Imiolak/StochasticCheckers
/Checkers.Experiment/Measurement/GameEndedWithResultMeasurement.cs
2.90625
3
using Checkers.Engine; using Checkers.Engine.Display; namespace Checkers.Experiment.Measurement { public class GameEndedWithResultMeasurement : IMeasurement { private readonly GameResult _result; private int _winCount; public GameEndedWithResultMeasurement(GameResult result) { _result = result; } public string Description => $"Games ended with result {_result}"; public double Result => _winCount; public void AddEntry(IGame game) { if (game.Result == _result) _winCount++; } } }
3d77a4adeef8b7e95eb1b84c22987f6d4eb66f10
C#
SaberZA/CqrsRestService
/CqrsRestService.Core/ConsoleLoggingService.cs
2.546875
3
using CqrsRestService.CorePortable; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CqrsRestService.Core { public class ConsoleLoggingService : ILogger//, IServerLogger { private string _hostInfo; public ConsoleLoggingService() { } public ConsoleLoggingService(string hostInfo) { _hostInfo = hostInfo; } public void Log(string message, LogLevel logLevel = LogLevel.Information) { //var previousColor = Console.ForegroundColor; //var logColor = Console.ForegroundColor; //switch (logLevel) //{ // case LogLevel.Information: logColor = ConsoleColor.White; break; // case LogLevel.Warning: logColor = ConsoleColor.Yellow; break; // case LogLevel.Error: logColor = ConsoleColor.Red; break; // default: logColor = ConsoleColor.White; break; //} //Console.ForegroundColor = logColor; Debug.WriteLine(message); //Console.ForegroundColor = previousColor; } } public enum LogLevel { Information, Warning, Error } }
bd4a005c20d32dc8066bd8547d993057668bd2b0
C#
yasuzo/simple-2d-unity-app
/Assets/Scripts/DropArranger.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DropArranger : MonoBehaviour { //objekt koji ce se kreirati public GameObject theDrop; //runda/nivo na kojem je igrac public int round; //broj kockica koje ce se instancirati public int startingNumber; public int numberPerLevel; //granice unutur kojih ce objekt biti stvoren public float minX; public float maxX; public float minY; public float maxY; //X i Y koordinate mjesta na kojem ce objekt biti stvoren float posX, posY; // Use this for initialization void Start () { //stvara određeni broj kockica for(int i = 0; i < startingNumber; i++) { //X i Y koordinate se nasumicno biraju unutar granica posX = Random.Range(minX, maxX); posY = Random.Range(minY, maxY); //instancira objekt Instantiate(theDrop, new Vector2(posX, posY), transform.rotation); } } //instancira jos kockica ako je potrebno public void InstantiateMore() { //stvara određeni broj kockica for (int i = 0; i < numberPerLevel; i++) { //X i Y koordinate se nasumicno biraju unutar granica posX = Random.Range(minX, maxX); posY = Random.Range(minY, maxY); //instancira objekt Instantiate(theDrop, new Vector2(posX, posY), transform.rotation); } } //kada kocka prijeđe granicu vidljivosti public void OnDropExit(GameObject obj) { //X i Y koordinate se nasumicno biraju unutar granica posX = Random.Range(minX, maxX); posY = Random.Range(minY, maxY); //vraca objekt(kocku) na vrh na nasumicno odabranu lokaciju obj.transform.position = new Vector2(posX, posY); //obnavlja kocku obj.GetComponent<Drop>().Renew(); } //funkcija koja ce se pozvati po zavrsetku igre //ponovno ce pozicionirati kocku i obnoviti ju public void OnGameEnd() { Drop[] drops = FindObjectsOfType<Drop>(); foreach(Drop d in drops) { //X i Y koordinate se nasumicno biraju unutar granica posX = Random.Range(minX, maxX); posY = Random.Range(minY, maxY); //vraca objekt(kocku) na vrh na nasumicno odabranu lokaciju d.transform.position = new Vector2(posX, posY); d.Renew(); } } }
d2162a1d59880d5e3757423c17fcca04c6551c10
C#
MariamEssam/DataStructure-AlgorithmsSuite
/AlgoSuite/UniqueSequence.cs
3.09375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgoSuite { /// <summary> /// https://aonecode.com/amazon-online-assessment-winning-sequence /// <ID>5012</ID> /// </summary> class UniqueSequence { public int[] generateSequence(int num, int lower, int upper) { if (num == 0 || (upper - lower) * 2 + 1 < num) return new int[0]; int[] result = new int[num]; int peek = Math.Min(num - 1, upper - lower + 1); int mid = num - peek; result[mid] = upper; int val = upper; for(int i=mid-1;i>=0;i--) { val--; result[i] = val; } val = upper; for (int i = mid + 1; i<num; i++) { val--; result[i] = val; } return result; } } }
40aebca0adcff0f8e02c6dd49463c77c4011c6fd
C#
qq651267797/Learning-every-day_2
/LearningEveryDay_2/3,字符串转换整数-8/MyAtoi.cs
3.671875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _3_字符串转换整数_8 { //请你来实现一个 atoi 函数,使其能将字符串转换成整数。 //该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。 //第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号; //假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。 //假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为[−231, 231− 1]。 //如果数值超过这个范围,qing返回 INT_MAX(231 − 1) 或 INT_MIN(−231) 。 public class Solution { public int MyAtoi(string InputStr) { int OutputInt = 0; int InputStringLength = InputStr.Length; if (InputStr == null || InputStringLength == 0) { return OutputInt; } //为正则是 true 为负就是 false bool Flag = true; int Left = 0; //int Right = 0; //int IntmAX = int.MaxValue; //int IntMin = int.MinValue; //去除前面的空格 for (int i = 0; i < InputStringLength; i++) { if (InputStr[i] == ' ') { Left++; //Right++; } else { break; } } //如果是 正号 if (InputStr[Left] == '+') { Left++; //Right++; if (Left < InputStringLength && !(InputStr[Left] >= '0' && InputStr[Left] <= '9')) { return OutputInt; } } //如果是 负号 else if (InputStr[Left] == '-') { Left++; //Right++; Flag = false; if (Left < InputStringLength && !(InputStr[Left] >= '0' && InputStr[Left] <= '9')) { return OutputInt; } } //Left 和 Right 在同一起点线上 for (int i = Left; i < InputStringLength; i++) { //如果是 数字 if (InputStr[Left] >= '0' && InputStr[i] <= '9') { int InputStr_Int = InputStr[Left] - '0'; //如果为 正数,但是大于int MAX if (Flag && OutputInt >= (int.MaxValue / 10) && InputStr_Int > 7) { OutputInt = int.MaxValue; return OutputInt; } //如果为 负数,并且小于int Min else if (!Flag && OutputInt <= Math.Abs((int.MinValue / 10)) && InputStr_Int > 8) { OutputInt = int.MinValue; return OutputInt; } //如果不为加完后 不大于且不小于,那就先加 else { OutputInt = OutputInt * 10 + InputStr_Int; Left++; if (Left < InputStringLength && !(InputStr[Left] >= '0' && InputStr[Left] <= '9')) { break; } } } //如果是 字母 或者 其他符号 else { if (OutputInt == 0) { return 0; } else { break; } } } OutputInt = (Flag ? OutputInt : (~OutputInt + 1)); return OutputInt; } } class MyAtoi { static void Main(string[] args) { Solution ff = new Solution(); string InputStr = "42"; int OutputInt = ff.MyAtoi(InputStr); Console.WriteLine(); Console.WriteLine(OutputInt); Console.WriteLine(); Console.WriteLine(); InputStr = " -42 ds"; Console.WriteLine(); OutputInt = ff.MyAtoi(InputStr); Console.WriteLine(OutputInt); Console.WriteLine(); Console.WriteLine(); InputStr = "-4193 with words"; Console.WriteLine(); OutputInt = ff.MyAtoi(InputStr); Console.WriteLine(OutputInt); Console.WriteLine(); Console.WriteLine(); InputStr = "words and 987"; Console.WriteLine(); OutputInt = ff.MyAtoi(InputStr); Console.WriteLine(OutputInt); Console.WriteLine(); Console.WriteLine(); InputStr = "-words and 987"; Console.WriteLine(); OutputInt = ff.MyAtoi(InputStr); Console.WriteLine(OutputInt); Console.WriteLine(); Console.WriteLine(); InputStr = "-4444-44"; Console.WriteLine(); OutputInt = ff.MyAtoi(InputStr); Console.WriteLine(OutputInt); Console.WriteLine(); Console.WriteLine(); InputStr = "-6666+66"; Console.WriteLine(); OutputInt = ff.MyAtoi(InputStr); Console.WriteLine(OutputInt); Console.WriteLine(); Console.WriteLine(); InputStr = "-2147483649"; Console.WriteLine(); OutputInt = ff.MyAtoi(InputStr); Console.WriteLine(OutputInt); Console.WriteLine(); Console.WriteLine(); InputStr = "2147483648"; Console.WriteLine(); OutputInt = ff.MyAtoi(InputStr); Console.WriteLine(OutputInt); Console.WriteLine(); Console.WriteLine(); Console.ReadKey(); } } }
7fea3ab2e0551d56b0091a043c0ef473e1eebb08
C#
ebruyasar11/retrieve-octocat-console
/SeleniumOctocatRetrieve/Program.cs
2.6875
3
using System; using System.Diagnostics; using System.IO; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Interactions; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; namespace SeleniumOctocatRetrieve { class Program { #region Cropped Image Information const int LOCATION_X = 450; //multiple caret using const int LOCATION_Y = 130; const int WIDTH = 825; const int HEIGHT = 900; #endregion static void Main(string[] args) { #region Configuration const int SAMPLE_COUNT = 20; const bool FULLSCREEN = false; #endregion #region Main Stopwatch watch = new Stopwatch(); watch.Start(); Console.WriteLine("Project Started"); var driver = InitializeAndNavigate(); for (int i = 0; i < SAMPLE_COUNT; i++) { Randomize(driver); FixOctocat(driver); Guid guid = Guid.NewGuid(); var screenShot = driver.GetScreenshot(); if (FULLSCREEN) { SaveFullScreenShot(guid, screenShot); } SaveOctocat(guid, screenShot); } driver.Quit(); watch.Stop(); Console.WriteLine(string.Format("Elapsed time for {0} images : {1} seconds",SAMPLE_COUNT,watch.Elapsed.TotalSeconds.ToString())); #endregion } #region Methods private static void CreateFolderIfNotExists() { var path = Directory.GetCurrentDirectory() + "//scr"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } private static void SaveOctocat(Guid guid, Screenshot screenshot) { CreateFolderIfNotExists(); var image = Image.Load<Rgba32>(screenshot.AsByteArray); var rectangle = new Rectangle(LOCATION_X, LOCATION_Y, WIDTH, HEIGHT); //magic number image.Mutate(x => x.Crop(rectangle)); image.SaveAsPng(string.Format("scr//octocat-cropped-{0}.png", guid)); } private static void SaveFullScreenShot(Guid guid, Screenshot screenshot) { CreateFolderIfNotExists(); screenshot.SaveAsFile(string.Format("scr//octocat-full-{0}.png", guid), ScreenshotImageFormat.Png); } private static void FixOctocat(ChromeDriver driver) { IWebElement element = driver.FindElementById("octocat"); Console.WriteLine("Octocat found."); Actions actions = new Actions(driver); actions.MoveToElement(element).Build().Perform(); } private static void Randomize(ChromeDriver driver) { driver.FindElementById("radomize").Click(); Console.WriteLine("Randomize clicked"); } private static ChromeDriver InitializeAndNavigate() { var options = new ChromeOptions(); options.AddArgument("headless"); ChromeDriver driver = new ChromeDriver(options); driver.Url = "https://myoctocat.com/build-your-octocat/"; Console.WriteLine("Chrome Driver initialized."); driver.Navigate(); Console.WriteLine("Navigating to site."); return driver; } #endregion } }
5830f134b09d7903c63818af973be4368acfb18e
C#
EmptyBucket/DungeonCrawlBot
/BehindTheNameGenerator/UrlBuilder/BehindTheNameUrlBuilder.cs
2.96875
3
using BehindTheNameGenerator.ParametersFactory; namespace BehindTheNameGenerator.UrlBuilder { //builder pattern public class BehindTheNameUrlBuilder : IUrlBuilder { private readonly IParametersFactory _parametersFactory; private const string BaseUrl = "https://www.behindthename.com/random/random.php"; public BehindTheNameUrlBuilder(IParametersFactory parametersFactory) { _parametersFactory = parametersFactory; } public string Build() { var parameters = _parametersFactory.Factory(); var url = $"{BaseUrl}?{parameters}"; return url; } } }
943a06fd532d65443ce4ea51de64d465abd36451
C#
levonaramyan/CodeFights_Tasks
/Arcade/The Core/04. Loop Tunnel/CountSumOfTwoRepresentations2/Program.cs
3.828125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // Given integers n, l and r, find the number of ways to represent n as a sum // of two integers A and B such that l ≤ A ≤ B ≤ r. // Example: // For n = 6, l = 2, and r = 4, the output should be // countSumOfTwoRepresentations2(n, l, r) = 2. // There are just two ways to write 6 as A + B, where 2 ≤ A ≤ B ≤ 4: 6 = 2 + 4 and 6 = 3 + 3. namespace CountSumOfTwoRepresentations2 { class Program { static void Main(string[] args) { // Testing and printing the result Console.WriteLine(countSumOfTwoRepresentations2(6,2,4)); Console.ReadKey(); } // Returns the number of possible n = A + B representations, l <= A <= B <= r. static int countSumOfTwoRepresentations2(int n, int l, int r) { int sum = 0; if (n <= 2 * r && n >= 2 * l) for (int i = l; i <= n - l && i <= n / 2; i++) { int dif = n - i; if (dif >= l && dif <= r) sum++; } return sum; } } }
5a247ae5ffacec4d5662cad284330150c2553a1b
C#
askguanyu/CodePlexDevLib
/main/Product/Codes/DevLib.Data/DbHelperParameterCache.cs
2.578125
3
//----------------------------------------------------------------------- // <copyright file="DbHelperParameterCache.cs" company="YuGuan Corporation"> // Copyright (c) YuGuan Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace DevLib.Data { using System; using System.Collections; using System.Data; using System.Data.Common; using System.Diagnostics.CodeAnalysis; /// <summary> /// Provides functions to leverage a static cache of procedure parameters, and the ability to discover parameters for stored procedures at run-time. /// </summary> public static class DbHelperParameterCache { /// <summary> /// Field ParamCache. /// </summary> private static readonly Hashtable ParamCache = Hashtable.Synchronized(new Hashtable()); /// <summary> /// Add parameter array to the cache. /// </summary> /// <param name="connectionString">A valid connection string for a DbConnection.</param> /// <param name="commandText">The stored procedure name or T-SQL command.</param> /// <param name="commandParameters">An array of DbParameter to be cached.</param> public static void CacheParameterSet(string connectionString, string commandText, params DbParameter[] commandParameters) { if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentNullException("connectionString"); } if (string.IsNullOrEmpty(commandText)) { throw new ArgumentNullException("commandText"); } string hashKey = connectionString + ":" + commandText; ParamCache[hashKey] = commandParameters; } /// <summary> /// Retrieve a parameter array from the cache. /// </summary> /// <param name="connectionString">A valid connection string for a DbConnection.</param> /// <param name="commandText">The stored procedure name or T-SQL command.</param> /// <returns>An array of DbParameter.</returns> public static DbParameter[] GetCachedParameterSet(string connectionString, string commandText) { if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentNullException("connectionString"); } if (string.IsNullOrEmpty(commandText)) { throw new ArgumentNullException("commandText"); } string hashKey = connectionString + ":" + commandText; DbParameter[] cachedParameters = ParamCache[hashKey] as DbParameter[]; if (cachedParameters == null) { return null; } else { return CloneParameters(cachedParameters); } } /// <summary> /// Retrieves the set of DbParameter appropriate for the stored procedure. /// </summary> /// <param name="dbProviderFactory">The database provider factory.</param> /// <param name="discoverParametersAction">The discover parameters action.</param> /// <param name="spName">The name of the stored procedure.</param> /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results.</param> /// <returns>An array of DbParameter.</returns> public static DbParameter[] GetSpParameterSet(DbProviderFactory dbProviderFactory, Action<DbCommand> discoverParametersAction, string spName, bool includeReturnValueParameter = false) { if (dbProviderFactory == null) { throw new ArgumentNullException("dbProviderFactory"); } if (string.IsNullOrEmpty(spName)) { throw new ArgumentNullException("spName"); } using (DbConnection dbConnection = dbProviderFactory.CreateConnection()) { return GetSpParameterSetInternal(dbConnection, discoverParametersAction, spName, includeReturnValueParameter); } } /// <summary> /// Retrieves the set of DbParameter appropriate for the stored procedure. /// </summary> /// <param name="connection">A valid DbConnection object.</param> /// <param name="discoverParametersAction">The discover parameters action.</param> /// <param name="spName">The name of the stored procedure.</param> /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results.</param> /// <returns>An array of DbParameter.</returns> public static DbParameter[] GetSpParameterSet(DbConnection connection, Action<DbCommand> discoverParametersAction, string spName, bool includeReturnValueParameter = false) { if (connection == null) { throw new ArgumentNullException("connection"); } if (string.IsNullOrEmpty(spName)) { throw new ArgumentNullException("spName"); } using (DbConnection clonedDbConnection = (DbConnection)((ICloneable)connection).Clone()) { return GetSpParameterSetInternal(clonedDbConnection, discoverParametersAction, spName, includeReturnValueParameter); } } /// <summary> /// Resolve at run time the appropriate set of DbParameter for a stored procedure. /// </summary> /// <param name="connection">A valid DbConnection object.</param> /// <param name="discoverParametersAction">The discover parameters action.</param> /// <param name="spName">The name of the stored procedure.</param> /// <param name="includeReturnValueParameter">Whether or not to include their return value parameter.</param> /// <returns>The parameter array discovered.</returns> [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "Reviewed.")] private static DbParameter[] DiscoverSpParameterSet(DbConnection connection, Action<DbCommand> discoverParametersAction, string spName, bool includeReturnValueParameter) { if (connection == null) { throw new ArgumentNullException("connection"); } if (string.IsNullOrEmpty(spName)) { throw new ArgumentNullException("spName"); } DbCommand dbCommand = connection.CreateCommand(); dbCommand.CommandText = spName; dbCommand.CommandType = CommandType.StoredProcedure; if (connection.State != ConnectionState.Open) { connection.Open(); } if (discoverParametersAction != null) { discoverParametersAction(dbCommand); } connection.Close(); if (!includeReturnValueParameter) { dbCommand.Parameters.RemoveAt(0); } DbParameter[] discoveredParameters = new DbParameter[dbCommand.Parameters.Count]; dbCommand.Parameters.CopyTo(discoveredParameters, 0); foreach (DbParameter discoveredParameter in discoveredParameters) { discoveredParameter.Value = DBNull.Value; } return discoveredParameters; } /// <summary> /// Deep copy of cached DbParameter array. /// </summary> /// <param name="originalParameters">Original parameters.</param> /// <returns>A deep copy of original parameters.</returns> private static DbParameter[] CloneParameters(DbParameter[] originalParameters) { DbParameter[] clonedParameters = new DbParameter[originalParameters.Length]; for (int i = 0; i < originalParameters.Length; i++) { clonedParameters[i] = (DbParameter)((ICloneable)originalParameters[i]).Clone(); } return clonedParameters; } /// <summary> /// Retrieves the set of DbParameter appropriate for the stored procedure. /// </summary> /// <param name="connection">A valid DbConnection object.</param> /// <param name="discoverParametersAction">The discover parameters action.</param> /// <param name="spName">The name of the stored procedure.</param> /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results.</param> /// <returns>An array of DbParameter.</returns> private static DbParameter[] GetSpParameterSetInternal(DbConnection connection, Action<DbCommand> discoverParametersAction, string spName, bool includeReturnValueParameter) { if (connection == null) { throw new ArgumentNullException("connection"); } if (string.IsNullOrEmpty(spName)) { throw new ArgumentNullException("spName"); } string hashKey = connection.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : string.Empty); DbParameter[] cachedParameters = null; cachedParameters = ParamCache[hashKey] as DbParameter[]; if (cachedParameters == null) { DbParameter[] spParameters = DiscoverSpParameterSet(connection, discoverParametersAction, spName, includeReturnValueParameter); ParamCache[hashKey] = spParameters; cachedParameters = spParameters; } return CloneParameters(cachedParameters); } } }
9fd6d15ea53863dad0316787ffbe11f54d8caeda
C#
JavaJoe127/WeatherStationRaspPi
/Conversions/Rounding.cs
3.390625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WeatherStation.Conversions { public class Rounding { public static decimal RoundToSignificantFigures(double num, int n) { if (num == 0) { return 0; } // We are only looking for the next power of 10... // The double conversion could impact in some corner cases, // but I'm not able to construct them... int d = (int)Math.Ceiling(Math.Log10((double)Math.Abs(num))); int power = n - d; // Same here, Math.Pow(10, *) is an integer number var magnitude = (double)Math.Pow(10, power); // I'm using the MidpointRounding.AwayFromZero . I'm not sure // having a MidpointRounding.ToEven would be useful (is Banker's // rounding used for significant figures?) var shifted = Math.Round(num * magnitude, 0, MidpointRounding.AwayFromZero); var ret = shifted / magnitude; return (decimal)ret; } } }
d3fa2c44180cd7439fdefa3f1b37359be61d28c0
C#
callehellebjork/squealing-chainsaw
/auseTxtGame/planting.cs
3.140625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace auseTxtGame { class planting { public static void plant() { String[] seeds = new string[4]; seeds[0] = "empty"; seeds[1] = "empty"; seeds[2] = "empty"; seeds[3] = "cuccumber"; seeds[4] = "watermelom"; try { Program.trixPrint("what seed do you want to plant?"); Console.Write(seeds[0] + seeds[1] +seeds[2]+ seeds[3]+ seeds[4]); } catch { } } } }
203afd6643c82c4bf8cec5577e50aba035aba76b
C#
edirgarcia/CodeFights
/InterviewPractice/DataStructures/LinkedLists/LinkedLists/ListNode.cs
3.703125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LinkedLists { public class ListNode<T> { public T value { get; set; } public ListNode<T> next { get; set; } public static ListNode<int> GetLinkedList(int[] arr) { ListNode<int> head = null; for (int i = arr.Length - 1; i >= 0; i--) { ListNode<int> tmp = new ListNode<int>(); tmp.value = arr[i]; tmp.next = head; head = tmp; } return head; } public override string ToString() { StringBuilder sb = new StringBuilder(); ListNode<T> curr = this; while (curr != null) { sb.Append(curr.value + " "); curr = curr.next; } return sb.ToString(); } } }
bbc2391e3ea3dbb4d18480295b7c5536d8987f39
C#
JHilmarch/codekata
/Kata04.DataMunging/Kata04.DataMunging.Tests/Model/WeatherDataTests.cs
3.125
3
using System; using FluentAssertions; using Xunit; namespace Kata04.DataMunging.Tests.Model { public class WeatherDataTests { [Theory] [InlineData(-1)] [InlineData(0)] public void ConstructWeatherData_DayNumberIsNotPositiveNumber_ThrowsArgumentOutOfRangeException(int dayNumber) { //Act Action action = () => new WeatherData(dayNumber, 0D, 0D); //Assert action.Should().Throw<ArgumentOutOfRangeException>(); } [Fact] public void ConstructWeatherData_DayNumberIsPositiveNumber_DayNumberIsSet() { //Arrange const int dayNumber = 3; //Act var wheatherData = new WeatherData(dayNumber, 0D, 0D); //Assert wheatherData.DayNumber.Should().Be(dayNumber); } [Fact] public void ConstructWeatherData_WithMaximumTemperature_MaximumTemperatureIsSet() { //Arrange const double maximumTemperature = 13.3; //Act var wheatherData = new WeatherData(1, maximumTemperature, 0D); //Assert wheatherData.MaximumTemperature.Should().Be(maximumTemperature); } [Fact] public void ConstructWeatherData_WithMinimumTemperature_MinimumTemperatureIsSet() { //Arrange const double minimumTemperature = 13.3; //Act var wheatherData = new WeatherData(1, 100, minimumTemperature); //Assert wheatherData.MinimumTemperature.Should().Be(minimumTemperature); } [Fact] public void ConstructWeatherData_WithMaxAndMinTemperature_TemperatureSpreadIsSet() { //Arrange const double maximumTemperature = 15.3; const double minimumTemperature = 13.3; //Act var wheatherData = new WeatherData(1, maximumTemperature, minimumTemperature); //Assert wheatherData.TemperatureSpread.Should().Be(2); } [Fact] public void ConstructWeatherData_MinimumTemperatureIsHigherThanMaximumTemperature_ThrowsArgumentException() { //Arrange const double maximumTemperature = 15.3; const double minimumTemperature = 17.3; //Act Action action = () => new WeatherData(1, maximumTemperature, minimumTemperature); //Assert action.Should().Throw<ArgumentException>(); } } }
a124d0c863b9580a0b33d076535ddc69062b1430
C#
JokkRus/Counter-Strike
/CounterStrike/CounterStrike/Team.cs
3.015625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace CounterStrike { class Team { public int Score { get; set; } public List<Gun> guns; public List<Person> persons; protected int count; public string commandName { get; protected set; } public Team() { Score = 0; } public void Buy() { foreach(Person p in persons) { p.Buy(guns); Thread.Sleep(50); } } public void Move(List<Location> locations) { foreach(Person p in persons) { p.Move(locations); Thread.Sleep(50); } } } }
b686dff9ee3b4226104ef2476ffc068b1191920b
C#
jianminchen/Leetcode_Julia
/By Algorithms/Leetcode 236 Lowest Common Ancestor/by topics/Fix naive solution timeout with complicated function/236 play with return backtracking For fun.cs
3.265625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace lowest_common_ancestor_236_timeout { public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } } class Program { static void Main(string[] args) { runTestcase(); } public static void runTestcase() { var root0 = new TreeNode(0); var root1 = new TreeNode(1); var root2 = new TreeNode(2); var root3 = new TreeNode(3); var root4 = new TreeNode(4); var root5 = new TreeNode(5); var root6 = new TreeNode(6); var root7 = new TreeNode(7); var root8 = new TreeNode(8); root3.left = root5; root3.right = root1; root5.left = root6; root5.right = root2; root2.left = root7; root2.right = root4; root1.left = root0; root1.right = root8; var result = LowestCommonAncestor(root3, root5, root1); } public static List<TreeNode> rootToP, rootToQ; public static bool findP, findQ; /// <summary> /// Leetcode 236 lowest common ancestor in binary tree /// - in general case, I like to propose the idea to find both nodes in the tree first, /// and also the path infomration will be recorded. /// /// Problem found: /// Time out in one of test cases /// </summary> /// <param name="root"></param> /// <param name="p"></param> /// <param name="q"></param> /// <returns></returns> public static TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || p == null || q == null) return null; rootToP = new List<TreeNode>(); rootToQ = new List<TreeNode>(); findP = false; findQ = false; traversalPreorder(root, p, q, rootToP, rootToQ); if (rootToP.Count == 0 || rootToQ.Count == 0) { return null; } int index = 0; TreeNode ancestor = null; while (index < rootToP.Count && index < rootToQ.Count) { if (rootToP[index] == rootToQ[index]) { ancestor = rootToP[index]; } else break; // index++; } return ancestor; } /// <summary> /// I like to solve timeout problem, and space complexity O(height of tree) /// 1. remove current argument /// 2. remove array copy /// 3. remove ... /// Design return: /// 0 - return false /// 1 - true - find p /// 2 - true - find q /// Training purposes: /// 1. understand backtracking /// 2. build good habit to use back track for a few benefits /// </summary> /// <param name="root"></param> /// <param name="current"></param> /// <param name="p"></param> /// <param name="q"></param> /// <param name="prefix"></param> private static void traversalPreorder(TreeNode root, TreeNode p, TreeNode q, List<TreeNode> prefixP, List<TreeNode> prefixQ) { if (root == null) { return; } if (!findP) prefixP.Add(root); if (!findQ) prefixQ.Add(root); if (root == p) { findP = true; } if (root == q) { findQ = true; } traversalPreorder(root.left, p, q, prefixP, prefixQ); traversalPreorder(root.right, p, q, prefixP, prefixQ); if (!findP) prefixP.RemoveAt(prefixP.Count - 1); if (!findQ) prefixQ.RemoveAt(prefixQ.Count - 1); return; } } }
a1b32e962c66f813213233bfa2bc57bebf2dc079
C#
shanzm/DesignPatterns
/03单例模式/03单例模式-读取配置文件/AppConfig.cs
3.078125
3
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03单例模式_读取配置文件 { public class AppConfig { //定义字段,用于存储唯一实例。注意是静态的 private static AppConfig appConfig = null; //对应配置文件设置相应的属性,注意是只读的 public string Server { private set; get; } public string DataBase { private set; get; } public string UserId { private set; get; } public string PassWord { private set; get; } //构造函数私有化 private AppConfig() { Server = ConfigurationManager.AppSettings["server"]; DataBase = ConfigurationManager.AppSettings["database"]; UserId = ConfigurationManager.AppSettings["uid"]; PassWord = ConfigurationManager.AppSettings["pwd"]; } //获取唯一实例。注意是静态的 public static AppConfig GetInstance() { if (appConfig == null) { appConfig = new AppConfig(); } return appConfig; } } }
f5d7ccbcba91c44873902bc69d4a29ec5297ad19
C#
CarterCommunity/Carter
/src/Carter/Request/StreamExtensions.cs
3.265625
3
namespace Carter.Request; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; public static class StreamExtensions { /// <summary> /// Gets the <see cref="HttpRequest" /> Body <see cref="Stream"/> as <see cref="string"/> asynchronously in the optional <see cref="Encoding"/> /// </summary> /// <param name="stream">Current <see cref="Stream"/></param> /// <param name="encoding">The character encoding to use or <see cref="Encoding.UTF8"/> by default</param> /// <param name="cancellationToken">The cancellation instruction if required</param> /// <returns>Awaited <see cref="Task{String}"/></returns> public static async Task<string> AsStringAsync(this Stream stream, Encoding encoding = null, CancellationToken cancellationToken = default) { using (var reader = new StreamReader(stream, encoding ?? Encoding.UTF8, leaveOpen:true)) { var readStream = await reader.ReadToEndAsync(); if (stream.CanSeek) { stream.Position = 0; } return readStream; } } }
edff2165dccee6c9a7ac9851e622a14b9eaf9792
C#
dmedrzak/ZTP
/ZTP/Controllers/CurrentLoggedUser.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ZTP.Models; namespace ZTP.Controllers { public sealed class CurrentLoggedUser { private User _user; private static CurrentLoggedUser _instance=null; private static readonly object padlock = new object(); public static CurrentLoggedUser Instance { get { if (_instance == null) { lock (padlock) { if (_instance == null) { _instance = new CurrentLoggedUser(); } } } return _instance; } } private CurrentLoggedUser() { } public void SetLoggedUser(User user) { this._user = user; } public User GetLoggedUser() { return this._user; } public string GetUserName() { return _user.Login; } } }
d54045b46e661482b7bcc0eb7db048e8b2b1dcd0
C#
ThePickingSolution/TPS-System
/Development/TPS/Picking.Hardware.Handler/Business/ReceivedMqttMessage.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Picking.Hardware.Handler.Business { public class ReceivedMqttMessage { public string Message { get; private set; } public bool IsReceived { get { return Message.Split(';')[0].Trim().Equals("RECEIVED"); } } public bool IsConfirm { get { return Message.Split(';')[0].Trim().Equals("DONE"); } } public string ItemId { get { return Message.Split(';')[1].Trim(); } } public int MessageNumber { get { return Int32.Parse(Message.Split(';')[2].Trim()); } } public int Quantity { get { return IsConfirm ? Int32.Parse(Message.Split(';')[3].Trim()) : 0; } } public ReceivedMqttMessage(string message) { this.Message = message; } } }
96fc4659bc5b58963ea5400009b40e1c0ff29ee6
C#
SWATOPLUS/RandomizedAlgorithms
/RA12BadElement/RA12BadElement/Program.cs
2.953125
3
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace RA12BadElement { internal class Program { private const string InputFileName = "element.in"; private const string OutputFileName = "element.out"; private const int CheckIterations = 20; private const bool NoBadElementMode = false; private static void Main() { var lines = File.ReadAllLines(InputFileName); var queue = new Queue<string>(lines); var random = new Random(42); var outputBuilder = new StringBuilder(); while (queue.Any()) { var size = int.Parse(queue.Dequeue()); if (size == 0) { break; } var a = ParseMatrix(queue.Dequeue(), size); var b = ParseMatrix(queue.Dequeue(), size); var c = ParseMatrix(queue.Dequeue(), size); var result = FindBadElement(random, a, b, c, size); if (NoBadElementMode) { if (result == null) { outputBuilder.AppendLine("YES"); } else { outputBuilder.AppendLine("NO"); } } else { if (result == null) { outputBuilder.AppendLine("No"); } else { outputBuilder.AppendLine("Yes"); outputBuilder.AppendLine($"{result.Value.Item1 + 1} {result.Value.Item2 + 1}"); } } } File.WriteAllText(OutputFileName, outputBuilder.ToString()); } private static (int, int)? FindBadElement(Random random, BitArray[] a, BitArray[] b, BitArray[] c, int size) { for (var i = 0; i < CheckIterations; i++) { var x = random.NextBitArray(size); var bx = MultiplyMatrixColumn(b, x); var abx = MultiplyMatrixColumn(a, bx); var cx = MultiplyMatrixColumn(c, x); var diffX = abx.FindDiffIndex(cx); if (diffX != -1) { var indexX = size - diffX - 1; var ab = MultiplyRowMatrix(a[indexX], b); var diffY = ab.FindDiffIndex(c[indexX]); var indexY = size - diffY - 1; return (indexX, indexY); } } return null; } private static BitArray MultiplyMatrixColumn(BitArray[] matrix, BitArray column) { var result = new BitArray(matrix.Length); for (var i = 0; i < matrix.Length; i++) { var element = ((BitArray) matrix[i].Clone()).And(column); result.Set(matrix.Length - i - 1, element.CountSetBits() % 2 == 1); } return result; } private static BitArray MultiplyRowMatrix(BitArray r, BitArray[] matrix) { var result = new BitArray(matrix.Length); for (var i = 0; i < matrix.Length; i++) { if (r[i]) { result = result.Xor(matrix[matrix.Length - i - 1]); } } return result; } private static BitArray[] ParseMatrix(string matrix, int size) { var shift = (4 - size % 4) % 4; return matrix .Split(' ') .Select(ParseMatrixRow) .Select(x => { var array = x.RightShift(shift); array.Length = size; return array; }) .ToArray(); } private static BitArray ParseMatrixRow(string row) { var fixedRow = row.Length % 2 == 0 ? row : "0" + row; var leadZeroCount = (16 - fixedRow.Length % 16) % 16; var bytes = new byte[(leadZeroCount + fixedRow.Length) / 2]; for (var i = 0; i < fixedRow.Length / 2; i++) { var low = fixedRow[fixedRow.Length - i * 2 - 1].ParseHex(); var high = fixedRow[fixedRow.Length - i * 2 - 2].ParseHex(); bytes[i] = (byte) (high * 16 + low); } return new BitArray(bytes); } } public static class RandomExtensions { public static BitArray NextBitArray(this Random random, int size) { var byteCount = size.DivUp(8); var bytes = new byte[byteCount]; random.NextBytes(bytes); return new BitArray(bytes) {Length = size}; } } public static class NumericExtensions { public static int DivUp(this int number, int divider) { if (number % divider == 0) { return number / divider; } return number / divider + 1; } } public static class StringExtensions { public static int ParseHex(this char c) { unchecked { if ('0' <= c && c <= '9') { return c - '0'; } if ('A' <= c && c <= 'F') { return c - 'A' + 10; } return -1; } } } public static class CollectionExtensions { public static uint CountSetBits(this BitArray bitArray) { unchecked { var ints = new int[(bitArray.Count >> 5) + 1]; bitArray.CopyTo(ints, 0); var count = 0; // fix for not truncated bits in last integer that may have been set to true with SetAll() ints[ints.Length - 1] &= ~(-1 << (bitArray.Count % 32)); for (Int32 i = 0; i < ints.Length; i++) { Int32 c = ints[i]; // magic (http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel) unchecked { c -= ((c >> 1) & 0x55555555); c = (c & 0x33333333) + ((c >> 2) & 0x33333333); c = ((c + (c >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; } count += c; } return (uint) count; } } public static int FindDiffIndex(this BitArray a, BitArray b) { for (var i = 0; i < a.Count; i++) { if (a[i] != b[i]) { return i; } } return -1; } } }
1a4d6bbacc19d2c778ce2320c59e8a1e69991165
C#
bartosz-szymanski/ID3EntropiaApp
/EntropiaApp/Utils/FileReader.cs
2.765625
3
using System.Collections.Generic; using System.IO; namespace EntropiaApp.Utils { class FileReader { public List<string[]> Arrays { get; set; } private readonly string fileName = "/Users/bartosz/Documents/test123.txt"; public void ReadFile() { Arrays = new List<string[]>(); var lines = File.ReadAllLines(fileName); foreach (var line in lines) { Arrays.Add(line.Split(',')); } } } }
6fdcf103de4d4a5bdfa8ab4a6ef44927f2a89ed9
C#
alaeners/AED
/TI_FINAL_AED/TI_FINAL_AED/VeiculosHash.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TI_FINAL_AED { public class VeiculosHash { VeiculosListas[] _hashtab; public int contaColisao() { int cont = 0; for (int i = 0; i < hashtab.Length; i++) { cont = cont + hashtab[i].colisao; } return cont; } public VeiculosHash() { hashtab = new VeiculosListas[10000]; for (int i = 0; i < hashtab.Length; i++) { hashtab[i] = new VeiculosListas(); } } public VeiculosListas[] hashtab { get { return _hashtab; } set { _hashtab = value; } } public void Inserir(Veiculos novo) { hashtab[hashCodeNumerica(novo.placa)].inserir(novo); } private int hashCodeNumerica(string placa) { int parteNumerica; parteNumerica = int.Parse(placa.Substring(4)); return parteNumerica; } public Veiculos buscar(string placa) { Veiculos holder = hashtab[hashCodeNumerica(placa)].procurar(placa); return holder; } } }
57b35eb030b59d4e2a597eb47be7a3593d62cbda
C#
Shaansh2601/Shantanu_HandsOn
/DesignPatternCaseStudy/DesignPattern_PracticeCaseStudy2/DesignPatternHandsOn2/SteveObserver.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PracticeCaseStudyObserverPattern { class SteveObserver : INotificationObserver { public string Name { get { return "Steve"; } } public void OnServerDown() { Console.WriteLine("Notification has been recieved by " + Name); } } }
e27c29c66a16c1f2a23e1269d93e7e3e7b401c70
C#
BCProgramming/DodgerX
/DodgerX/DodgerX/iGameState.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; namespace DodgerX { public class GameRunnerData { private List<Particle> _Particles=new List<Particle>(); private List<AttackingObject> _Attackers= new List<AttackingObject>(); private Player _PlayerObject; public List<Particle> Particles { get { return _Particles; } set { _Particles = value; } } public List<AttackingObject> Attackers { get { return _Attackers; } set { _Attackers = value; } } public Player PlayerObject { get { return _PlayerObject; } set { _PlayerObject = value; } } public void Draw(DodgerX gameobject, GameTime gt) { foreach (Particle p in Particles) { p.Draw(gameobject, gt); } foreach (AttackingObject ao in Attackers) ao.Draw(gameobject); if (PlayerObject != null) PlayerObject.Draw(gameobject,gt); String FPSString = Math.Round(gameobject.CurrentFPS, 2).ToString() + " fps"; Vector2 FPSSize = gameobject.DefaultFont.MeasureString(FPSString); String ParticleCount = Particles.Count.ToString(); gameobject.spriteBatch.DrawString(gameobject.DefaultFont, FPSString + " " + ParticleCount + " Particles.", new Vector2(0, gameobject.Window.ClientBounds.Height - FPSSize.Y), Color.Black); } public void Update(DodgerX gameobject, GameTime gt) { List<AttackingObject> removeattackers = new List<AttackingObject>(); List<Particle> removeparticles = new List<Particle>(); foreach (AttackingObject loopattacker in Attackers) { if (loopattacker.PerformFrame(gameobject,gt)) { removeattackers.Add(loopattacker); } } foreach (Particle loopparticle in Particles) { if (loopparticle.Update(gameobject, gt)) { removeparticles.Add(loopparticle); } } foreach (var iterate in removeattackers) Attackers.Remove(iterate); foreach (var remparticle in removeparticles) { Particles.Remove(remparticle); } if(_PlayerObject !=null) _PlayerObject.PerformFrame(gameobject,gt); } } public interface iGameRunner { GameRunnerData grd { get; set; } } public interface iGameState { Cue MusicTrack { get; } void Draw(DodgerX gameobject,GameTime gameTime); void Update(DodgerX gameobject,GameTime gameTime); } }
04611d3541c723fc1fea5829e0e00dd0753f21ee
C#
ComputerMaster1st/Railgun
/Railgun/Core/ServerCount.cs
2.78125
3
using System; using System.Threading.Tasks; using System.Timers; using Discord; using Discord.WebSocket; using Railgun.Core.Configuration; namespace Railgun.Core { public class ServerCount { private readonly MasterConfig _config; private readonly DiscordShardedClient _client; private readonly Timer _timer = new Timer(TimeSpan.FromMinutes(30).TotalMilliseconds); public int PreviousGuildCount { get; set; } = 0; public ServerCount(MasterConfig config, DiscordShardedClient client) { _config = config; _client = client; } public void Start() { _timer.AutoReset = true; _timer.Elapsed += async (sender, args) => await Task.Factory.StartNew(async () => await UpdateServerCountAsync()); _timer.Start(); } private async Task UpdateServerCountAsync() { if (PreviousGuildCount == _client.Guilds.Count) return; PreviousGuildCount = _client.Guilds.Count; await _client.SetGameAsync($"{_config.DiscordConfig.Prefix}help {SystemUtilities.GetSeparator} {PreviousGuildCount} Servers!", type:ActivityType.Watching); } } }
93cd1c945b0771f9e5221ba6f727626ba8d14c25
C#
dragobaltov/Programming-Basics-And-Fundamentals
/TrackDownloader/TrackDownloader/Program.cs
3.328125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrackDownloader { class Program { static void Main(string[] args) { List<string> blacklistedWords = Console.ReadLine().Split(' ').ToList(); List<string> newList = new List<string>(); string fileName = Console.ReadLine(); bool contain = false; while (fileName != "end") { if (!Condition(blacklistedWords, newList, fileName, contain)) { newList.Add(fileName); } fileName = Console.ReadLine(); } PrintingNewList(newList); } static bool Condition(List<string> blacklistedWords, List<string> newList, string fileName, bool contain) { for (int i = 0; i < blacklistedWords.Count; i++) { if (fileName.Contains(blacklistedWords[i])) return true; } return false; } static void PrintingNewList(List<string> newList) { newList.Sort(); for (int i = 0; i < newList.Count; i++) { Console.WriteLine(newList[i]); } } } }
a21d98c790c50f1a754059d88d83986d1f511d90
C#
dmitrygboyko/algorithms
/Tests/SortingTests.cs
2.90625
3
using Xunit; using Algorithms.Sorting; namespace Tests { public class SortingTests { [Fact] public void SelectionSort() { var array = new int[] { 6, 5, 4, 3, 212, 1, 32, 2 }; Selection.Sort(array); Assert.Equal(new int[] { 1, 2, 3, 4, 5, 6, 32, 212 }, array); } [Fact] public void InsertionSort() { var array = new int[] { 6, 5, 4, 3, 212, 1, 32, 2 }; Insertion.Sort(array); Assert.Equal(new int[] { 1, 2, 3, 4, 5, 6, 32, 212 }, array); } [Fact] public void MergeSort() { var array = new int[] { 6, 5, 4, 3, 212, 1, 32, 2 }; Merge.Sort(array); Assert.Equal(new int[] { 1, 2, 3, 4, 5, 6, 32, 212 }, array); } [Fact] public void QuickSort() { var array = new int[] { 6, 5, 4, 3, 212, 1, 32, 2 }; Quick.Sort(array); Assert.Equal(new int[] { 1, 2, 3, 4, 5, 6, 32, 212 }, array); } } }
cc0cfa98a0827ba4a0e58289def31874c9fece6d
C#
Aspectrus/MultiThread-Random-Text-Generator
/ThreadGeneration/ApplicationWindow.cs
2.71875
3
using System; using System.Windows.Forms; using System.IO; using System.Configuration; namespace ThreadGeneration { public partial class ApplicationWindow : Form { private bool ThreadGenerationIsOn = false; ThreadTimers threadtimers; AccessDatabase accessdatabase; private string fileName = "threadData.mdb"; private int MinThreadCount = int.Parse(ConfigurationManager.AppSettings["MinThreadCount"]); private int MaxThreadCount = int.Parse(ConfigurationManager.AppSettings["MaxThreadCount"]); public ApplicationWindow() { InitializeComponent(); historyListView.Columns[0].Text = "Thread ID"; historyListView.Columns[1].Text = "Generated string"; historyListView.Columns[0].Width = (int)(historyListView.Width * 0.30); historyListView.Columns[1].Width = (int)(historyListView.Width * 0.69); } private void StartButton_Click(object sender, EventArgs e) { if (!int.TryParse(ThreadNumberInput.Text, out int NumberOfThreads)) { MessageBox.Show("Incorrect input"); return; } if (NumberOfThreads > MaxThreadCount || NumberOfThreads < MinThreadCount) MessageBox.Show("Incorrect number of threads"); else { if (ThreadGenerationIsOn) { threadtimers.KillAllThreadTimers(); threadtimers = null; accessdatabase = null; StartStopButton.Text = "Start"; ThreadGenerationIsOn = false; ThreadNumberInput.ReadOnly = false; } else { accessdatabase = new AccessDatabase(); if (!accessdatabase.CreateNewAccessDatabase(fileName)) MessageBox.Show("mdb file could not be created"); threadtimers = new ThreadTimers(NumberOfThreads, fileName); StartStopButton.Text = "Stop"; ThreadGenerationIsOn = true; threadtimers.LaunchThreads(historyListView); ThreadNumberInput.ReadOnly = true; } } } private void ApplicationWindow_ResizeEnd(object sender, EventArgs e) { historyListView.Columns[0].Width = (int)(historyListView.Width * 0.30); historyListView.Columns[1].Width = (int)(historyListView.Width * 0.69); } } }
1d34b2ec589348a9053fc7e468d57303f956e582
C#
intrepion/zetcode-csharp-sqlite-tutorial-version
/Version/Program.cs
2.953125
3
using System; using System.Data.SQLite; namespace Version { class Program { static void Main(string[] args) { string cs = "Data Source=:memory:"; string stm = "SELECT SQLITE_VERSION()"; using var con = new SQLiteConnection(cs); con.Open(); using var cmd = new SQLiteCommand(stm, con); string version = cmd.ExecuteScalar().ToString(); Console.WriteLine($"SQLite version: {version}"); } } }
11e16121047f5f5ea5ac94c14302e0cf6f77daa9
C#
YigaoFan/TestLanguage
/CSharpSrc/ContinuedAction.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConfigureParser { public class ContinuedAction { private readonly List<Action> _actions; public ContinuedAction(List<Action> actions) { this._actions = actions; } ~ContinuedAction() { _actions.ForEach(a => a()); } } }
e49db47e00cbd2c2f5fa884ae0b30f1a7eb65e7b
C#
BorisBorshevsky/spaceinvaders-ex2
/SpaceInvadersGame/ObjectModel/SpaceShipComposite.cs
2.578125
3
using System; using System.Collections.Generic; using System.Text; using XnaGamesInfrastructure.ServiceInterfaces; using XnaGamesInfrastructure.Services; using XnaGamesInfrastructure.ObjectModel; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using XnaGamesInfrastructure.ObjectInterfaces; using SpaceInvadersGame.Interfaces; using SpaceInvadersGame.ObjectModel.Screens; using XnaGamesInfrastructure.ObjectModel.Animations.ConcreteAnimations; using XnaGamesInfrastructure.ObjectModel.Animations; namespace SpaceInvadersGame.ObjectModel { /// <summary> /// A composite class that holds a SpaceShip and her bullets /// </summary> public class SpaceShipComposite : CompositeDrawableComponent<IGameComponent> { private SpaceShip m_SpaceShip; #region CTOR's public SpaceShipComposite(Game i_Game, SpaceShip i_SpaceShip) : base(i_Game) { m_SpaceShip = i_SpaceShip; m_SpaceShip.ReleasedShot += new AddGameComponentDelegate(spaceShip_ReleasedShot); this.Add(m_SpaceShip); } #endregion /// <summary> /// Gets the SpaceShip component /// </summary> public SpaceShip SpaceShip { get { return m_SpaceShip; } } /// <summary> /// Catch the ReleasedShot event and adds the new bullet to the /// components list /// </summary> /// <param name="i_Component">The bullet that the space ship shot</param> private void spaceShip_ReleasedShot(IGameComponent i_Component) { this.Add(i_Component); } } }
35b23a8f3db60099ee6c43ff60325966159ce8c6
C#
OpportunityLiu/MvvmUniverse
/Opportunity.MvvmUniverse/Commands/~AsyncCommandWithProgress/~Action{T, TProgress}.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation; namespace Opportunity.MvvmUniverse.Commands { /// <summary> /// Execution body of <see cref="AsyncCommandWithProgress{T, TProgress}"/>. /// </summary> /// <param name="command">Current command of execution.</param> /// <param name="parameter">Current parameter of execution.</param> public delegate IAsyncActionWithProgress<TProgress> AsyncActionWithProgressExecutor<T, TProgress>(AsyncCommandWithProgress<T, TProgress> command, T parameter); internal sealed class AsyncActionCommandWithProgress<T, TProgress> : AsyncCommandWithProgress<T, TProgress> { public AsyncActionCommandWithProgress( AsyncActionWithProgressExecutor<T, TProgress> execute, AsyncPredicate<T> canExecute) { this.canExecute = canExecute; this.execute = execute ?? throw new ArgumentNullException(nameof(execute)); } private readonly AsyncPredicate<T> canExecute; private readonly AsyncActionWithProgressExecutor<T, TProgress> execute; protected override IAsyncAction StartExecutionAsync(T parameter) { var p = this.execute.Invoke(this, parameter); var e = ProgressChangedEventArgs<T, TProgress>.Create(parameter, default); p.Progress = (sender, pg) => { e.Progress = pg; OnProgress(e.EventArgs); }; return p.AsTask().AsAsyncAction(); } protected override bool CanExecuteOverride(T parameter) { if (!base.CanExecuteOverride(parameter)) return false; if (this.canExecute is AsyncPredicate<T> p) return p(this, parameter); return true; } } }
79439afe2290b56df179f86683fd8068f3a6e980
C#
ekolis/FrEee
/FrEee/Utility/IPopulator.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace FrEee.Utility { public interface IPopulator { /// <summary> /// Performs potentially expensive lookup logic to retrieve that data which needs to be populated /// into the cache. /// </summary> /// <param name="context"></param> /// <returns>The data retrieved, or null if it was not found.</returns> public object? Populate(object? context); } }
0e918e78cfdd6cde4619229a3ae94326ef07676a
C#
polytronicgr/httpclone
/src/HttpClone.Library/Common/PathExclusionList.cs
2.578125
3
#region Copyright 2011 by Roger Knapp, Licensed under the Apache License, Version 2.0 /* 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 System; using System.Collections.Generic; using System.Net; using System.IO; using System.Text; namespace CSharpTest.Net.HttpClone.Common { public class PathExclusionList { private readonly List<string> _items; public PathExclusionList() { _items = new List<string>(); } public PathExclusionList(IEnumerable<string> items) : this() { AddRange(items); } public void Add(string item) { if (String.IsNullOrEmpty(item)) return; item = item.Trim(); if (String.IsNullOrEmpty(item) || item[0] != '/' || IsExcluded(item)) return; int pos = _items.BinarySearch(item, StringComparer.Ordinal); if (pos < 0) _items.Insert(~pos, item); } public void AddRange(IEnumerable<string> items) { if (items != null) { foreach (string item in items) Add(item); } } public bool IsExcluded(string path) { int pos = _items.BinarySearch(path, StringComparer.Ordinal); if (pos >= 0) return true; pos = ~pos; if (pos > 0 && path.StartsWith(_items[pos - 1], StringComparison.Ordinal)) return true; return false; } public bool ReadRobotsFile(Uri baseUri, string userAgent) { HttpRequestUtil http = new HttpRequestUtil(baseUri); if (http.Get("/robots.txt") != HttpStatusCode.OK) return false; using(TextReader rdr = new StreamReader(new MemoryStream(http.Content), Encoding.UTF8)) { string line; bool matched = false; char[] divide = new[] {':'}; while(null != (line = rdr.ReadLine())) { if (line.Length == 0 || line[0] == '#') continue; string[] parts = line.Split(divide, 2); if(parts.Length != 2) continue; parts[0] = parts[0].Trim().ToLower(); switch(parts[0]) { case "user-agent": matched = parts[1].Trim() == "*" || parts[1].Trim() == userAgent; break; case "disallow": if(matched) Add(parts[1]); break; } } } return true; } } }
418ccc7508fe458561090c08e80d1d7b9b1edcc7
C#
fahad1226/MS_DotNET
/C#-Basics/FirstApp/Program.cs
3.59375
4
using System; using System.Collections.Generic; using System.Collections; namespace FirstApp { class Program { static string Name(string name) { return name; } static int Name(int age) { return age; } static void Main(string[] args) { // String name = Console.ReadLine(); // Console.WriteLine(name); // string firstName = "John"; // string lastName = "Doe"; // string name = $"My full name is: {firstName} {lastName}"; // Console.WriteLine(name); // Console.WriteLine(Math.Max(10, 20)); // string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; // Console.WriteLine(cars[1]); // Name("Ryzen PC"); // Console.WriteLine(Name(29823)); List<int>numbers = new List<int>(); // etate type ta bole dite hobe, fixed numbers.Add(10); numbers.Add(20); // numbers[0] = 30; we cannot use this in List or whatever collection // numbers[1] = 20; foreach (int number in numbers) { Console.WriteLine(number); } ArrayList myFriends = new ArrayList(); // ArrayList e type na bolleo hobe, dynamic type arki JS er moto myFriends.Add("Ross"); myFriends.Add(100); myFriends.Add("Joey"); foreach(var friend in myFriends) { Console.WriteLine(friend); } } } }
a6e88dde881f683aa10ae3a782056cb795dfa27b
C#
jestemlidzia/Design-and-development-of-high-level-object-oriented-system
/Metody fabryczne i fabryki abstrakcyjne/FruitIce.cs
3.40625
3
namespace LAB05_IceCreamFactory { class FruitIce : Icecream { public bool waffle; public string icing; public FruitIce(int price_, string taste_, bool waffle_, string icing_) : base(price_, taste_) { waffle = waffle_; icing = icing_; } public override string ToString() { string txt = $"{taste} fruit ice cream"; if (waffle) txt += " in waffle"; if (icing != "" && icing != "None") txt += $" with {icing}"; txt += $". Cost: {price}$."; return txt; } } }
1f7409a17c5a29da867e72182b735898d9f907a3
C#
eyassug/ApexReusables
/Apex.Common/Net/EmailAccount.cs
2.765625
3
using System.Net.Mail; namespace Apex.Common.Net { public class EmailAccount { private readonly string _name; private readonly MailAddress _address; public EmailAccount(string address) : this(string.Empty,address) { } public EmailAccount(string name, string address) { _name = name; _address = new MailAddress(address); } public string Name { get { return _name; } } public string Address { get { return _address.Address; } } } }
df00f0cc6ae387b091af8e3b46d0e7550576ca34
C#
Delubear/RandomItemGenerator
/RPGItemGenerator/ItemGeneration/SecondaryProperties/PropertyClasses/DamageTypes/Slashing.cs
2.96875
3
using static RPGItemGenerator.ItemGeneration.Enums; namespace RPGItemGenerator.ItemGeneration { public class Slashing : SecondaryProperties { public Slashing() { Key = 1; this.PropDescription = "Slashing"; } public override void Execute(Item item) { if (r.Next(0, 2) == 0) { item.PrefixList.Add("Slashing" + " "); } else { item.SuffixList.Add(" " + "of Slashing"); } item.Value = (int)(item.Value *1.1); if(item.ItemType == ItemTypes.Weapon) { item.GetType().GetProperty("DamageType").SetValue(item, DamageTypes.Slashing); } } } }
9d47481968d835f47360aecbc03f2d5af8f07f22
C#
SamusKerenos/Alhorithms
/DelegateRepresetnation/DelegateRepresetnation/Program.cs
3.5625
4
using System; namespace DelegateRepresetnation { class Program { private static Action<string> _showCondition = condition => { Console.WriteLine($"это фильтрация для {condition}"); }; static void Main() { // вот тут мы инициализируем переменную делегата методом Func<string, bool> _conditionResolver = ConditionalResolver; string userInput = Console.ReadLine(); ShowResult(_conditionResolver, userInput); userInput = Console.ReadLine(); // вот тут мы инициализируем переменную делегата лямбдой // которая так же как и метод выше полностью удовлетворяет // делегату типа Func<string, bool> _conditionResolver = input => { string _condition = "Мышь"; _showCondition(_condition); return input.Equals(_condition); }; ShowResult(_conditionResolver, userInput); } // метод полностью удовлетворяет делегату типа Func<string, bool> // по этому его можно использовать для инициализации переменных // делегата типа Func<string, bool> private static bool ConditionalResolver(string input) { string _condition = "жаба"; _showCondition(_condition); return input.Equals(_condition); } private static void ShowResult(Func<string, bool> filter, string input) { if (filter(input)) { Console.WriteLine("Мы нашли"); } else { Console.WriteLine("Здесь такого нет"); } } } }
1abcf476cc4945d1a8c288a946bd42f5ae6ada87
C#
sadiel06/Proyecto-final-compiladores
/Procesos/AnalizadorSintactico.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Procesos { public class AnalizadorSintactico { public AnalizadorSintactico() { TablaSimbolos = new TablaSimbolos(); } public TablaSimbolos TablaSimbolos { get; set; } public void ConstruirTablaSimbolos(List<Lexema> lexemas) { TablaSimbolos = new TablaSimbolos(); TablaSimbolos.ProcesarListadoLexemas(lexemas); } #region Reglas public string AplicarReglasTipoVar(int indice, List<Lexema> lexemas) { string mensajeError = ""; Lexema lexema = lexemas[indice]; //Saco el elemento para el cual voy a analizar if (lexema.TipoElemento != Enums.TipoElemento.TipoDato) //Si no es del tipo var, exploto { throw new ArgumentException("El tipo de elemento no es del tipo identificador de tipeo"); } if (!EsUltimoElemento(indice, lexemas)) { Lexema lexemaSiguiente = lexemas[indice + 1]; if (lexemaSiguiente.TipoElemento != Enums.TipoElemento.Variable && lexemaSiguiente.TipoElemento != Enums.TipoElemento.Corchete) { mensajeError = "Error de sintaxis, se esperaba un identificador, pero se encontró " + lexemaSiguiente.Texto + ". Elemento: " + lexema.Texto; } else if (lexemaSiguiente.TipoElemento == Enums.TipoElemento.Corchete) { if (lexemaSiguiente.Texto == "]") { mensajeError = "Error de sintaxis, construccion erronea de un arreglo. Elemento: " + lexema.Texto; } else { for (int i = indice + 1; i < lexemas.Count; i++) { if (lexemas[i].Texto == ";") { mensajeError = "Error de sintaxis, construccion erronea de un arreglo. Elemento: " + lexema.Texto; break; } if (TablaSimbolos.Tokens[i].NombreToken == "]") { break; } } } } } else { mensajeError = "Error de sintaxis, se esperaba ;. Elemento: " + lexema.Texto; } return mensajeError; } public string AplicarReglasVariable(int indice, List<Lexema> lexemas) { string mensajeError = ""; Lexema lexema = lexemas[indice]; //Saco el elemento para el cual voy a analizar if (lexema.TipoElemento != Enums.TipoElemento.Variable) //Si no es del tipo var, exploto { throw new ArgumentException("El tipo de elemento no es del tipo variable"); } if (!EsUltimoElemento(indice, lexemas)) { Lexema lexemaSiguiente = lexemas[indice + 1]; if (lexemaSiguiente.TipoElemento != Enums.TipoElemento.OperadorAsignacion && lexemaSiguiente.TipoElemento != Enums.TipoElemento.OperadorAritmetico && lexemaSiguiente.TipoElemento != Enums.TipoElemento.OperadorDecremental && lexemaSiguiente.TipoElemento != Enums.TipoElemento.OperadorIncremental && lexemaSiguiente.TipoElemento != Enums.TipoElemento.OperadorLogico && lexemaSiguiente.TipoElemento != Enums.TipoElemento.OperadorRelacional && lexemaSiguiente.TipoElemento != Enums.TipoElemento.Coma && lexemaSiguiente.TipoElemento != Enums.TipoElemento.OperadorTerminador && lexemaSiguiente.TipoElemento != Enums.TipoElemento.Parentesis) { mensajeError = "Sintaxis incorrecta para el tipo variable. Elemento: " + lexema.Texto; } } else { mensajeError = "Error de sintaxis, se esperaba ;. Elemento: " + lexema.Texto; } return mensajeError; } public string AplicarReglasAsignacion(int indice, List<Lexema> lexemas) { string mensajeError = ""; Lexema lexema = lexemas[indice]; //Saco el elemento para el cual voy a analizar if (lexema.TipoElemento != Enums.TipoElemento.OperadorAsignacion) //Si no es del tipo var, exploto { throw new ArgumentException("El tipo de elemento no es del tipo operador asignacion"); } if (!EsUltimoElemento(indice, lexemas)) { Lexema lexemaSiguiente = lexemas[indice + 1]; if (lexemaSiguiente.TipoElemento != Enums.TipoElemento.Variable && lexemaSiguiente.TipoElemento != Enums.TipoElemento.Numero && lexemaSiguiente.TipoElemento != Enums.TipoElemento.Cadena && lexemaSiguiente.TipoElemento != Enums.TipoElemento.Caracter && lexemaSiguiente.TipoElemento != Enums.TipoElemento.Parentesis) { mensajeError = "Sintaxis incorrecta, asignacion no válida. Elemento: " + lexema.Texto; } } else { mensajeError = "Error de sintaxis, se esperaba un valor para asignar. Elemento: " + lexema.Texto; } return mensajeError; } public string AplicarReglasOperadorAritmetico(int indice, List<Lexema> lexemas) { string mensajeError = ""; Lexema lexema = lexemas[indice]; //Saco el elemento para el cual voy a analizar if (lexema.TipoElemento != Enums.TipoElemento.OperadorAritmetico) //Si no es del tipo var, exploto { throw new ArgumentException("El tipo de elemento no es del tipo operador aritmetico"); } if (!EsUltimoElemento(indice, lexemas)) { Lexema lexemaSiguiente = lexemas[indice + 1]; Lexema lexemaAnterior = lexemas[indice - 1]; if ((lexemaAnterior.TipoElemento != Enums.TipoElemento.Numero && lexemaAnterior.TipoElemento != Enums.TipoElemento.Variable && lexemaAnterior.TipoElemento != Enums.TipoElemento.Parentesis) || (lexemaSiguiente.TipoElemento != Enums.TipoElemento.Numero && lexemaSiguiente.TipoElemento != Enums.TipoElemento.Variable && lexemaSiguiente.TipoElemento != Enums.TipoElemento.Parentesis)) { mensajeError = "Sintaxis incorrecta, uso inadecuado del operador. Elemento: " +"\""+ lexema.Texto + "\""; } } else { mensajeError = "Error de sintaxis, se esperaba un valor para operar. Elemento: " + lexema.Texto; } return mensajeError; } public bool EsUltimoElemento(int indice, List<Lexema> lexemas) { return indice == lexemas.Count - 1; } #endregion public List<Bloque> RealizarAnalisisSintax(List<Lexema> lexemas,ref int posCursor, int indiceStop = 0, int finBloquePadre = 0) { List<Bloque> bloques = new List<Bloque>(); while (posCursor < indiceStop) { bloques.Add(ObtenerSiguienteBloque(lexemas,ref posCursor, finBloquePadre)); } return bloques; } public Bloque ObtenerSiguienteBloque(List<Lexema> lexemas,ref int posCursor, int finBloquePadre) { Bloque bloque = new Bloque(); //Si el elemento leido es del tipo int,float,char, etc if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.TipoDato) { //Debo verficar que si se trata de una sentencia o de una funcion if (lexemas[posCursor + 1].TipoElemento == Enums.TipoElemento.Variable) { bloque = ProcesarTipoVariable(lexemas, ref posCursor, finBloquePadre); } else { bloque = BloqueError(lexemas, "Se esperaba una declaración despues de " + lexemas[posCursor].Texto, ref posCursor, finBloquePadre); } } else if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.Variable) { bloque = ProcesarVariable(lexemas, ref posCursor, finBloquePadre); } else if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.PalabraReservada && lexemas[posCursor].Texto == "return") { bloque = AnalizarSentencia(lexemas, ref posCursor, finBloquePadre); } else if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.PalabraReservada && lexemas[posCursor].Texto == "for") { bloque = AnalizarFor(lexemas, ref posCursor, finBloquePadre); } else if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.PalabraReservada && lexemas[posCursor].Texto == "while") { bloque = AnalizarWhile(lexemas, ref posCursor, finBloquePadre); } else if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.PalabraReservada && lexemas[posCursor].Texto == "do") { bloque = AnalizarDoWhile(lexemas, ref posCursor, finBloquePadre); } else if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.PalabraReservada && lexemas[posCursor].Texto == "if") { bloque = AnalizarIf(lexemas, ref posCursor, finBloquePadre); } else if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.PalabraReservada && lexemas[posCursor].Texto == "else") { bloque = AnalizarElse(lexemas, ref posCursor, finBloquePadre); } return bloque; } #region Procesador de sintaxis public Bloque ProcesarTipoVariable(List<Lexema> lexemas, ref int posCursor, int finBloquePadre) { if (posCursor + 2 < lexemas.Count - 1 && lexemas[posCursor + 2].Texto == "(") //Se trata de una funcion { int indiceBalance = IndiceBalance(lexemas, posCursor + 3, "(", ")"); if (indiceBalance == -1) { return BloqueError(lexemas, "Parentesis mal construidos", ref posCursor, finBloquePadre); } if (lexemas[indiceBalance + 1].Texto == "{") { return AnalizarBloqueFuncion(lexemas, ref posCursor, finBloquePadre); } else if (lexemas[indiceBalance + 1].TipoElemento == Enums.TipoElemento.OperadorAritmetico || lexemas[indiceBalance + 1].TipoElemento == Enums.TipoElemento.OperadorLogico || lexemas[indiceBalance + 1].TipoElemento == Enums.TipoElemento.OperadorRelacional || lexemas[indiceBalance + 1].TipoElemento == Enums.TipoElemento.OperadorTerminador) { return AnalizarSentencia(lexemas, ref posCursor, finBloquePadre); } return BloqueError(lexemas, "Error en la forma de llamar/construir una funcion", ref posCursor, finBloquePadre); } else if (posCursor + 2 < lexemas.Count - 1 && lexemas[posCursor + 2].TipoElemento == Enums.TipoElemento.OperadorAsignacion) { return AnalizarSentencia(lexemas, ref posCursor, finBloquePadre); } else { //Se trata de una sentencia return AnalizarSentencia(lexemas, ref posCursor, finBloquePadre); } } public Bloque ProcesarVariable(List<Lexema> lexemas, ref int posCursor, int finBloquePadre) { int indicePuntoComa = IndicePuntoComa(lexemas, posCursor); if (indicePuntoComa == -1 && PuntoComaCorrecto(lexemas, posCursor, indicePuntoComa) == false) { Bloque bloqueR = new Bloque() { Incia = posCursor, Error = "Sentencia de tipo variable mal construida, faltan ;" }; posCursor++; return bloqueR; } if (lexemas[posCursor + 1].Texto == "=" || lexemas[posCursor + 1].Texto == "++" || lexemas[posCursor + 1].Texto == "--" || lexemas[posCursor + 1].Texto == "+=" || lexemas[posCursor + 1].Texto == "-=" || lexemas[posCursor + 1].Texto == "*=" || lexemas[posCursor + 1].Texto == "/=") { return AnalizarSentencia(lexemas, ref posCursor, finBloquePadre); } return BloqueError(lexemas, "Se esperaba un simbolo de asignacion pero se encontro: " + lexemas[posCursor].Texto, ref posCursor, finBloquePadre); } public Bloque AnalizarBloqueFuncion(List<Lexema> lexemas, ref int posCursor, int finBloquePadre) { Bloque bloque = new Bloque(); bloque.TipoBloque = Enums.TipoBloque.Funcion; bloque.Incia = posCursor; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; if (lexemas[posCursor].Texto == "(") { if (lexemas.FirstOrDefault(x => x.Texto == ")") != null) { int indexFinParen = IndiceBalance(lexemas, posCursor + 1, "(", ")"); //Leo hasta el parentesis for (int i = posCursor; i <= indexFinParen; i++) { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } if (lexemas[posCursor].Texto == "{") { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; //Debo mandar a leer mas bloques int indexBalance = IndiceBalance(lexemas, posCursor, "{", "}"); if (indexBalance != -1) //Entonces esta balanceada { bloque.BloquesInterno = RealizarAnalisisSintax(lexemas, ref posCursor, indexBalance - 1, indexBalance); bloque.Finaliza = posCursor; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } else { bloque.Error = "Se esperaba cierre de funcion \"}\""; } } else { bloque.Error = "Se esperaba {"; } } else { bloque.Error = "Se esperaba )"; } } else { bloque.Error = "Se esperaba ("; } return bloque; } public Bloque AnalizarFor(List<Lexema> lexemas, ref int posCursor, int finBloquePadre) { Bloque bloque = new Bloque(); bloque.TipoBloque = Enums.TipoBloque.Estructura; bloque.Incia = posCursor; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; if (lexemas.ElementAtOrDefault(posCursor) != null && lexemas[posCursor].Texto == "(") { if (lexemas.FirstOrDefault(x => x.Texto == ")") != null) { int indexFinParen = IndiceBalance(lexemas, posCursor + 1, "(", ")"); //Validar estructura del for int indicePrimerPuntoComa = IndicePuntoComa(lexemas, posCursor); if (indicePrimerPuntoComa != -1 && InitForCorrecto(lexemas, posCursor, indicePrimerPuntoComa)) { //Leo hasta el primer punto coma for (int i = posCursor; i <= indicePrimerPuntoComa; i++) { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } int indiceSeguntoPuntoComa = IndicePuntoComa(lexemas, posCursor); if (indiceSeguntoPuntoComa != -1 && CondicionEstructuraCorrecta(lexemas, posCursor, indiceSeguntoPuntoComa)) { //Leo hasta el segundo punto coma for (int i = posCursor; i <= indiceSeguntoPuntoComa; i++) { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } if (IncrementoForCorrecto(lexemas, posCursor, indexFinParen)) { //Leo hasta el parentesis for (int i = posCursor; i <= indexFinParen; i++) { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } if (lexemas.ElementAtOrDefault(posCursor) != null && lexemas[posCursor].Texto == "{") { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; //Debo mandar a leer mas bloques int indexBalance = IndiceBalance(lexemas, posCursor, "{", "}"); if (indexBalance != -1) //Entonces esta balanceada { bloque.BloquesInterno = RealizarAnalisisSintax(lexemas, ref posCursor, indexBalance - 1, indexBalance); bloque.Finaliza = posCursor; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } else { bloque.Error = "Se esperaba cierre de funcion \"}\""; } } else { bloque.Error = "Se esperaba {"; } } else { bloque.Error = "Estructura del for incorrecta, condicion de incremento incorrecta"; } } else { bloque.Error = "Estructura del for incorrecta, condicion del for incorrecta"; } } else { bloque.Error = "Estructura del for incorrecta, inicializador del for incorrecto"; } } else { bloque.Error = "Se esperaba )"; } } else { bloque.Error = "Se esperaba ("; } if (string.IsNullOrEmpty(bloque.Error) == false) { finBloquePadre = finBloquePadre == 0 ? lexemas.Count : finBloquePadre; for (int i = posCursor; i < finBloquePadre; i++) { bloque.Lexemas.Add(lexemas[i]); posCursor++; } } return bloque; } public Bloque AnalizarWhile(List<Lexema> lexemas, ref int posCursor, int finBloquePadre) { Bloque bloque = new Bloque(); bloque.TipoBloque = Enums.TipoBloque.Estructura; bloque.Incia = posCursor; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; if (lexemas[posCursor].Texto == "(") { if (lexemas.FirstOrDefault(x => x.Texto == ")") != null) { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; int indexFinParen = IndiceBalance(lexemas, posCursor + 1, "(", ")"); if (CondicionEstructuraCorrecta(lexemas, posCursor, indexFinParen)) { //Leo hasta el parentesis for (int i = posCursor; i <= indexFinParen; i++) { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } if (lexemas[posCursor].Texto == "{") { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; //Debo mandar a leer mas bloques int indexBalance = IndiceBalance(lexemas, posCursor, "{", "}"); if (indexBalance != -1) //Entonces esta balanceada { bloque.BloquesInterno = RealizarAnalisisSintax(lexemas, ref posCursor, indexBalance - 1, indexBalance); bloque.Finaliza = posCursor; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } else { bloque.Error = "Se esperaba cierre de funcion \"}\""; } } else { bloque.Error = "Se esperaba \"{\""; } } else { bloque.Error = "La condicion del while es incorrecta"; } } else { bloque.Error = "Se esperaba \")\""; } } else { bloque.Error = "Se esperaba \"(\""; } if (string.IsNullOrEmpty(bloque.Error) == false) { finBloquePadre = finBloquePadre == 0 ? lexemas.Count : finBloquePadre; for (int i = posCursor; i < finBloquePadre; i++) { bloque.Lexemas.Add(lexemas[i]); posCursor++; } } return bloque; } public Bloque AnalizarDoWhile(List<Lexema> lexemas, ref int posCursor, int finBloquePadre) { Bloque bloque = new Bloque(); bloque.TipoBloque = Enums.TipoBloque.Estructura; bloque.Incia = posCursor; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; if (lexemas[posCursor].Texto == "{") { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; //Debo mandar a leer mas bloques int indexBalance = IndiceBalance(lexemas, posCursor, "{", "}"); if (indexBalance != -1) //Entonces esta balanceada { bloque.BloquesInterno = RealizarAnalisisSintax(lexemas, ref posCursor, indexBalance - 1, indexBalance); //Procedo a leer el while if (lexemas[posCursor].Texto == "}") { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; if (lexemas[posCursor].Texto == "while") { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; if (lexemas[posCursor].Texto == "(") { if (lexemas.FirstOrDefault(x => x.Texto == ")") != null) { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; int indexFinParen = IndiceBalance(lexemas, posCursor + 1, "(", ")"); if (CondicionEstructuraCorrecta(lexemas, posCursor, indexFinParen)) { //Leo hasta el parentesis for (int i = posCursor; i <= indexFinParen; i++) { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.OperadorTerminador) { bloque.Lexemas.Add(lexemas[posCursor]); bloque.Finaliza = posCursor; posCursor++; } else { bloque.Error = "La sentencia do...while requiere terminar con \";\""; } } else { bloque.Error = "La condicion del while es incorrecta"; } } else { bloque.Error = "Se esperaba \")\""; } } else { bloque.Error = "Se esperaba \"(\""; } } else { bloque.Error = "Estructura do...while incorrecta, falta la condicion \"while\" "; } } else { bloque.Error = "Se esperaba cierre de funcion \"}\""; } } else { bloque.Error = "Se esperaba cierre de funcion \"}\""; } } else { bloque.Error = "Se esperaba \"{\""; } if (string.IsNullOrEmpty(bloque.Error) == false) { finBloquePadre = finBloquePadre == 0 ? lexemas.Count : finBloquePadre; for (int i = posCursor; i < finBloquePadre; i++) { bloque.Lexemas.Add(lexemas[i]); posCursor++; } } return bloque; } public Bloque AnalizarIf(List<Lexema> lexemas, ref int posCursor, int finBloquePadre) { Bloque bloque = new Bloque(); bloque.TipoBloque = Enums.TipoBloque.Estructura; bloque.Incia = posCursor; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; if (lexemas[posCursor].Texto == "(") { if (lexemas.FirstOrDefault(x => x.Texto == ")") != null) { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; int indexFinParen = IndiceBalance(lexemas, posCursor + 1, "(", ")"); if (CondicionEstructuraCorrecta(lexemas, posCursor, indexFinParen)) { //Leo hasta el parentesis for (int i = posCursor; i <= indexFinParen; i++) { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } if (lexemas[posCursor].Texto == "{") { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; //Debo mandar a leer mas bloques int indexBalance = IndiceBalance(lexemas, posCursor, "{", "}"); if (indexBalance != -1) //Entonces esta balanceada { bloque.BloquesInterno = RealizarAnalisisSintax(lexemas, ref posCursor, indexBalance - 1, indexBalance); bloque.Finaliza = posCursor; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } else { bloque.Error = "Se esperaba cierre de funcion \"}\""; } } else { bloque.Error = "Se esperaba \"{\""; } } else { bloque.Error = "La condicion del if es incorrecta"; } } else { bloque.Error = "Se esperaba \")\""; } } else { bloque.Error = "Se esperaba \"(\""; } if (string.IsNullOrEmpty(bloque.Error) == false) { finBloquePadre = finBloquePadre == 0 ? lexemas.Count : finBloquePadre; for (int i = posCursor; i < finBloquePadre; i++) { bloque.Lexemas.Add(lexemas[i]); posCursor++; } } return bloque; } public Bloque AnalizarElse(List<Lexema> lexemas, ref int posCursor, int finBloquePadre) { Bloque bloque = new Bloque(); bloque.TipoBloque = Enums.TipoBloque.Estructura; bloque.Incia = posCursor; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; //Hay que ir a ver que haya un if justo arriba del else if (lexemas[posCursor].Texto == "{") { bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; //Debo mandar a leer mas bloques int indexBalance = IndiceBalance(lexemas, posCursor, "{", "}"); if (indexBalance != -1) //Entonces esta balanceada { bloque.BloquesInterno = RealizarAnalisisSintax(lexemas, ref posCursor, indexBalance - 1, indexBalance); bloque.Finaliza = posCursor; bloque.Lexemas.Add(lexemas[posCursor]); posCursor++; } else { bloque.Error = "Se esperaba cierre de funcion \"}\""; } } else { bloque.Error = "Se esperaba \"{\""; } if (string.IsNullOrEmpty(bloque.Error) == false) { finBloquePadre = finBloquePadre == 0 ? lexemas.Count : finBloquePadre; for (int i = posCursor; i < finBloquePadre; i++) { bloque.Lexemas.Add(lexemas[i]); posCursor++; } } return bloque; } public Bloque AnalizarSentencia(List<Lexema> lexemas, ref int posCursor, int finBloquePadre) { //Debo leer hasta encontrar un ; int indicePuntoComa = IndicePuntoComa(lexemas, posCursor); Bloque bloque = new Bloque(); bloque.Incia = posCursor; if (indicePuntoComa == -1 || PuntoComaCorrecto(lexemas, posCursor, indicePuntoComa) == false) { bloque.Error = "Se esperaba ;"; finBloquePadre = finBloquePadre == 0 ? lexemas.Count : finBloquePadre; for (int i = posCursor; i < finBloquePadre; i++) { bloque.Lexemas.Add(lexemas[i]); posCursor++; } } else if (!DelimitadoresBalanceados(lexemas, "(", ")", posCursor, indicePuntoComa)) { return BloqueError(lexemas, "Los parentesis para esta sentencia no estan balanceados", ref posCursor, finBloquePadre); } else { for (int i = posCursor; i <= indicePuntoComa; i++) { string error = BuscarError(lexemas[i], i, lexemas); if (string.IsNullOrEmpty(error)) { bloque.Lexemas.Add(lexemas[i]); } else { bloque.Error = error; } posCursor++; } //for (int i = posCursor; i <= indicePuntoComa; i++) //{ // bloque.Lexemas.Add(lexemas[i]); // posCursor++; //} } bloque.Finaliza = posCursor - 1; return bloque; } public string BuscarError(Lexema lexema,int indiceLexema, List<Lexema> lexemas) { switch (lexema.TipoElemento) { case Enums.TipoElemento.Variable: return AplicarReglasVariable(indiceLexema, lexemas); case Enums.TipoElemento.TipoDato: return AplicarReglasTipoVar(indiceLexema, lexemas); case Enums.TipoElemento.OperadorAritmetico: return AplicarReglasOperadorAritmetico(indiceLexema, lexemas); case Enums.TipoElemento.OperadorRelacional: return ""; case Enums.TipoElemento.OperadorLogico: return ""; case Enums.TipoElemento.OperadorAsignacion: return AplicarReglasAsignacion(indiceLexema, lexemas); case Enums.TipoElemento.OperadorMisc: return ""; case Enums.TipoElemento.PalabraDefinicion: return ""; case Enums.TipoElemento.OperadorTerminador: return ""; case Enums.TipoElemento.OperadorIncremental: return ""; case Enums.TipoElemento.OperadorDecremental: return ""; case Enums.TipoElemento.Cadena: return ""; case Enums.TipoElemento.Caracter: return ""; } return ""; } #endregion #region Utilidades public bool DelimitadoresBalanceados(List<Lexema> lexemas, string simbolApertura, string simbolCierre, int indiceInicial, int indiceFinal) { int apertura = 0; int cierre = 0; for (int i = indiceInicial; i < indiceFinal; i++) { if (lexemas[i].Texto == simbolApertura) { apertura++; } else if (lexemas[i].Texto == simbolCierre) { cierre++; } } return apertura == cierre; } public int IndiceBalance(List<Lexema> lexemas, int posCursor, string simboloApertura, string simboloCierre) { bool salir = false; int abiertos = 0; do { if (posCursor < lexemas.Count) { if (lexemas[posCursor].Texto == simboloApertura) { abiertos++; } else if (lexemas[posCursor].Texto == simboloCierre) { if (abiertos == 0) //Me encontre un } y no hay abiertos { salir = true; break; } else { abiertos--; } } posCursor++; } else { posCursor = -1; salir = true; } } while (!salir); return posCursor; } public int IndicePuntoComa(List<Lexema> lexemas, int posCursor) { bool salir = false; do { if (posCursor < lexemas.Count) { if (lexemas[posCursor].Texto == ";") { salir = true; } else { posCursor++; } } else { salir = true; posCursor = -1; } } while (!salir); return posCursor; } public Bloque BloqueError(List<Lexema> lexemas, string mensajeError, ref int posCursor, int finBloquePadre) { Bloque bloque = new Bloque() { Incia = posCursor, Error = mensajeError }; finBloquePadre = finBloquePadre == 0 ? lexemas.Count : finBloquePadre; for (int i = posCursor; i < finBloquePadre; i++) { bloque.Lexemas.Add(lexemas[i]); posCursor++; } return bloque; } public bool PuntoComaCorrecto(List<Lexema> lexemas, int posCursor, int indicePuntoComa) { int asignaciones = 0; int declarartipoVar = 0; int llaves = 0; for (int i = posCursor; i < indicePuntoComa; i++) { if (lexemas[i].TipoElemento == Enums.TipoElemento.OperadorAsignacion) { asignaciones++; } if (lexemas[i].TipoElemento == Enums.TipoElemento.TipoDato) { declarartipoVar++; } if (lexemas[i].TipoElemento == Enums.TipoElemento.Llave) { llaves++; } } if (asignaciones > 1 || declarartipoVar > 1 || llaves > 0) { return false; } return true; } public bool InitForCorrecto(List<Lexema> lexemas, int posCursor, int indicePuntoComa) { if (indicePuntoComa - posCursor == 5) //Analizar bloque de asignacion y declaracion { if (lexemas[posCursor + 1].Texto == "int" && lexemas[posCursor + 2].TipoElemento == Enums.TipoElemento.Variable && lexemas[posCursor + 3].TipoElemento == Enums.TipoElemento.OperadorAsignacion && lexemas[posCursor + 4].TipoElemento == Enums.TipoElemento.Numero) { return true; } else { return false; } } else if (indicePuntoComa - posCursor == 4) { if (lexemas[posCursor + 1].TipoElemento == Enums.TipoElemento.Variable && lexemas[posCursor + 2].TipoElemento == Enums.TipoElemento.OperadorAsignacion && lexemas[posCursor + 3].TipoElemento == Enums.TipoElemento.Numero) { return true; } else { return false; } } else { return false; } } public bool CondicionEstructuraCorrecta(List<Lexema> lexemas, int posCursor, int indiceFin) { if ((lexemas[posCursor].TipoElemento == Enums.TipoElemento.Numero || lexemas[posCursor].TipoElemento == Enums.TipoElemento.Variable) && (lexemas[posCursor + 1].TipoElemento == Enums.TipoElemento.OperadorLogico || lexemas[posCursor + 1].TipoElemento == Enums.TipoElemento.OperadorRelacional) && (lexemas[posCursor + 2].TipoElemento == Enums.TipoElemento.Numero || lexemas[posCursor + 2].TipoElemento == Enums.TipoElemento.Variable)) { return true; } return false; } public bool IncrementoForCorrecto(List<Lexema> lexemas, int posCursor, int indiceParentesis) { if (indiceParentesis - posCursor == 2) //Estamos ante una estructura contractada { if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.Variable && lexemas[posCursor + 1].TipoElemento == Enums.TipoElemento.OperadorIncremental) { return true; } if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.Variable && lexemas[posCursor + 1].TipoElemento == Enums.TipoElemento.OperadorDecremental) { return true; } return false; } else if (indiceParentesis - posCursor == 5) //Estamos ante una estructura completa { if (lexemas[posCursor].TipoElemento == Enums.TipoElemento.Variable && lexemas[posCursor + 1].TipoElemento == Enums.TipoElemento.OperadorAsignacion && lexemas[posCursor + 2].Texto == lexemas[posCursor].Texto && lexemas[posCursor + 3].TipoElemento == Enums.TipoElemento.OperadorAritmetico && lexemas[posCursor + 4].TipoElemento == Enums.TipoElemento.Numero) { return true; } return false; } return false; } #endregion //Procesador de Sintaxis public List<string> ExtraerErroresBloques(List<Bloque> bloques) { List<string> errores = new List<string>(); foreach (Bloque bloque in bloques) { if (!string.IsNullOrEmpty(bloque.Error)) { errores.Add(bloque.ErrorCompleto()); } List<string> erroresParciales = bloque.ErroresHijo(); if (erroresParciales != null && erroresParciales.Count > 0) { errores.AddRange(erroresParciales.Where(y => !string.IsNullOrEmpty(y))); } } return errores; } } }
66feaa7a479d949fb7bffc8c0f44956fa00d5619
C#
shendongnian/download4
/latest_version_download2/165741-34223956-106169389-2.cs
2.828125
3
private bool Authenticate(string user, string password) { using ( var context = new PrincipalContext(ContextType.Domain, Environment.UserDomainName) ) { return context.ValidateCredentials(user.Trim(), password.Trim()); } }
7e10dd7b8933fd0f028fb7fda8a93ca75b40b1ac
C#
Dimaematveev/Balance_NEW
/Meccanici/Meccanici.DAL/DBConnection.cs
3.234375
3
using System.Configuration; using System.Data.Common; using System.Data.SqlClient; using System.Threading.Tasks; namespace Meccanici.DAL { /// <summary> /// Соединение с БД /// </summary> public class DBConnection { /// <summary> /// экземпляр объекта Соединения с БД /// </summary> public static DBConnection instance; /// <summary> /// Подключение к БД /// </summary> public SqlConnection connection; public DBConnection() { instance = this; } /// <summary> /// Открыть соединение с БД /// </summary> public void Connect() { if (connection == null) { string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; connection = new SqlConnection(connectionString); } else { connection.Close(); } connection.Open(); } /// <summary> /// Выполнить запрос /// </summary> /// <param name="query">Запрос</param> /// <returns>Вывод данных</returns> public DbDataReader ExecuteQuery(string query) { Connect(); SqlCommand command = new SqlCommand(query, connection); return command.ExecuteReader(); } /// <summary> /// Вставить данные /// </summary> /// <param name="table">Таблица для вставки</param> /// <param name="names"> Имена столбцов через запятую </param> /// <param name="values"> Значения через запятую</param> public void InsertInto(string table, string names, string values) { string query = string.Format("insert into {0}.{1}({2}) values ({3})", connection.Database, table, names, values); ExecuteQuery(query); } /// <summary> /// Удалить данные /// </summary> /// <param name="table">Таблица для удаления</param> /// <param name="id"> Как можно индефицировать id удаляемого элемента</param> public void Delete(string table, string id) { string query = string.Format("update {0}.{1} set IsDelete=1 where {2}", connection.Database, table, id); ExecuteQuery(query); } /// <summary> /// Закрыть соединение /// </summary> public void Close() { connection.Close(); } } }
b3a86695f9e6db1cacca0ec318b5eae68befb3bc
C#
elipmoc/Function_calculator
/Function_calculator/Program.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Function_calculator { class Program { //拡張BNF記法 // []は 0回か1回を表し // {}を0回以上の繰り返し // +を1回以上の繰り返しとする /* 文 : 式 || 変数宣言 ; 変数宣言 : 識別子,"=",式 ; 式 : 項 , { "+" || "-" , 項 } ; 項 :[-], 実数 || 関数 || 変数 || ラムダ呼び出し ||( "(" , 式 , ")" ) , { "*" || "/", 項 } ; ラムダ呼び出し :ラムダ定義,"(",")" ; ラムダ定義 :"(",")","{",式,"}" ; 関数 :識別子,"(",引数,")" ; 変数 :識別子 ; 識別子 :(a-z)+ ; 引数 :[式 , {"," , 式}] ; */ static void Main(string[] args) { while (true) { var tokenStream=LexicalAnalyzer.Lexicalanalysis(Console.ReadLine()); if(tokenStream==null) { Console.WriteLine("syntax error!!"); continue; } //デバッグ用 /* for (int i = 0; i < tokenStream.Size; i++) tokenStream[i].DebugPrint();*/ var ast = CreateAST.CreateStatementAST(tokenStream); if (ast == null) Console.WriteLine("error!!"); else ast.Do(); Console.WriteLine(); } } } }
990ef99eb526fe613d5fd715ff4330039b31c399
C#
Fawel/AutoImageSeacrh
/src/AIS.Persistance/ImageFiles/InMemoryImageFileRepository.cs
2.8125
3
using AIS.Application.Interfaces.Repositories; using AIS.Domain.ImageFiles; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace AIS.Persistance.ImageFiles { public class InMemoryImageFileRepository : IImageFileRepository { private static int _currentMaxId = 0; private static readonly object _lockObject = new object(); private readonly Dictionary<int, ImageFile> _imageFileStore = new Dictionary<int, ImageFile>(); public Task<ImageFile[]> GetAllImageFiles(CancellationToken token = default) { token.ThrowIfCancellationRequested(); return Task.FromResult(_imageFileStore.Values.ToArray()); } public Task<ImageFile> GetByMd5(Md5Info md5Info, CancellationToken token = default) { token.ThrowIfCancellationRequested(); var imageFile = _imageFileStore.Values.FirstOrDefault(x => x.Md5 == md5Info); return Task.FromResult(imageFile); } public Task<int> SaveImageFile(ImageFile imageFile, CancellationToken token = default) { token.ThrowIfCancellationRequested(); if (imageFile.IsIdSet()) { _imageFileStore[imageFile.Id] = imageFile; return Task.FromResult(imageFile.Id); } else { lock (_lockObject) { _currentMaxId++; imageFile.SetId(_currentMaxId); _imageFileStore[_currentMaxId] = imageFile; return Task.FromResult(imageFile.Id); } } } } }
c0babce6c17ef146dc444972376ad07d5346e19e
C#
robert-impey/CodingExperiments
/C-Sharp/ImperativeMapping/ImperativeMapping/Program.cs
3.59375
4
using System.Diagnostics; using static System.Console; namespace ImperativeMapping { internal class Program { private static void Main(string[] args) { const int size = 10 * 1000 * 1000; var ys = new int[size]; var stopWatch = new Stopwatch(); stopWatch.Start(); for (var i = 0; i < size; i++) { ys[i] = i + i; } stopWatch.Stop(); WriteLine($"Time to run one loop with many iterations: {stopWatch.ElapsedMilliseconds}"); var zs = new int[10]; stopWatch.Restart(); for (var i = 0; i < size; i++) { for (var j = 0; j < zs.Length; j++) { zs[j] = j + j; } } stopWatch.Stop(); WriteLine($"Time to run many loops with few iterations: {stopWatch.ElapsedMilliseconds}"); stopWatch.Restart(); for (var i = 0; i < size; i++) { ys[i] = F(i); } stopWatch.Stop(); WriteLine($"Time to run one loop with a function with many iterations: {stopWatch.ElapsedMilliseconds}"); stopWatch.Restart(); for (var i = 0; i < size; i++) { for (var j = 0; j < zs.Length; j++) { zs[j] = F(j); } } stopWatch.Stop(); WriteLine($"Time to run with a function many loops with few iterations: {stopWatch.ElapsedMilliseconds}"); } private static int F(int x) { return x + x; } } }
1a4106cf5c3e421a7fc128d1c2f2c460b962ec62
C#
ViktoriiaKlymenko/HomeWorks
/ASP.Net/WebApplicationFoodService/WebApplicationFoodService/Controllers/ProductController.cs
2.59375
3
using EntityFrameworkTask; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using PastriesDelivery; using System.Collections.Generic; namespace WebApplicationFoodService.Controllers { [ApiController] [Route("[controller]")] public class ProductController : ControllerBase { private readonly ILogger<ProductController> _logger; private readonly IProductService _productService; public ProductController(ILogger<ProductController> logger, IProductService productService) { _logger = logger; _productService = productService; } [HttpGet] public IEnumerable<Product> Get() { return _productService.ExtractProducts(); } [HttpPost] public IActionResult CreateProduct(string name, decimal price, int amount, double weight, int categoryId, int providerId) { _productService.AddProduct(name, price, amount, weight, categoryId, providerId); return Ok(); } [HttpPut] public IActionResult UpdateProduct([FromQuery] Product product, [FromBody] Product newProduct) { _productService.UpdateProduct(product, newProduct); return Ok(); } [HttpDelete] public IActionResult DeleteProduct(Product product) { _productService.Remove(product); return Ok(); } } }
30c980c1f53c88fc172f836a80396085c548fc0c
C#
dukeofharen/armyknife
/src/Armyknife.Tools/Implementations/TinyUrlTool.cs
2.671875
3
using Armyknife.Business.Interfaces; using Armyknife.Exceptions; using Armyknife.Models; using Armyknife.Resources; using Armyknife.Services.Interfaces; using Armyknife.Utilities; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Armyknife.Tools.Implementations { internal class TinyUrlTool : IAsynchronousTool { private readonly IWebService _webService; public TinyUrlTool(IWebService webService) { _webService = webService; } public string Name => "tinyurl"; public string Description => ToolResources.TinyUrlDescription; public string Category => CategoryResources.WebCategory; public string HelpText => ToolResources.TinyUrlHelp; public bool ShowToolInHelp => true; public async Task<string> ExecuteAsync(IDictionary<string, string> args) { string input = args.GetValue(Constants.InputKey); if (string.IsNullOrWhiteSpace(input)) { throw new ArmyknifeException(ExceptionResources.NoInput); } string url = $"http://tinyurl.com/api-create.php?url={WebUtility.UrlEncode(input)}"; var request = new HttpRequestMessage { RequestUri = new Uri(url) }; var response = await _webService.DoRequestAsync(request); if(response.StatusCode != HttpStatusCode.OK) { throw new ArmyknifeException($"TinyURL returned unexpected HTTP status code '{response.StatusCode}'."); } string result = await response.Content.ReadAsStringAsync(); return result; } } }
0471a8a1c8e6417c5201cdcacec4cbe8aa10478d
C#
Petermarcu/Projects
/Pi/Raspberry.IO.GeneralPurpose/PinConfiguration.cs
3.078125
3
#region References using System; #endregion namespace Raspberry.IO.GeneralPurpose { /// <summary> /// Represents the configuration of a pin. /// </summary> public abstract class PinConfiguration { #region Instance Management /// <summary> /// Initializes a new instance of the <see cref="PinConfiguration"/> class. /// </summary> /// <param name="pin">The pin.</param> protected PinConfiguration(ProcessorPin pin) { Pin = pin; } #endregion #region Properties /// <summary> /// Gets the pin. /// </summary> public ProcessorPin Pin { get; private set; } /// <summary> /// Gets the direction. /// </summary> public abstract PinDirection Direction { get; } /// <summary> /// Gets or sets the name. /// </summary> /// <value> /// The name. /// </value> public string Name { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="PinConfiguration"/> is reversed. /// </summary> /// <value> /// <c>true</c> if reversed; otherwise, <c>false</c>. /// </value> /// <remarks>If set to <c>true</c>, pin value will be enabled when no signal is present, and disabled when a signal is present.</remarks> public bool Reversed { get; set; } /// <summary> /// Gets or sets the status changed action. /// </summary> /// <value> /// The status changed action. /// </value> public Action<bool> StatusChangedAction { get; set; } #endregion #region Internal Methods internal bool GetEffective(bool value) { return Reversed ? !value : value; } #endregion } }
f13787434f180828e029353dd5e9114ad1de2935
C#
DobromirZlatkov/TELERIK-Academy-Master
/TELERIK C# OOP/TELERIK-OOP-HW3/AllNumbersDivisibleBy3and7/AllNumbersDivisibleBy3and7.cs
4.21875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AllNumbersDivisibleBy3and7 { /*Write a program that prints from given array of integers all numbers that are divisible by 7 and 3. Use the built-in extension methods and lambda expressions. Rewrite the same with LINQ. */ class AllNumbersDivisibleBy3and7 { static void Main(string[] args) { int[] array = new int[100]; for (int i = 0; i < array.Length; i++) { array[i] = i; } NumbersDivisibleBy3and7(array); } private static void NumbersDivisibleBy3and7(int[] array) { //with LAMBDA var divisibleBy3and7 = array.Where(num => num % 21 == 0).Select(num => num); //with LINQ var divisibleBy3and7LINQ = from num in array where num % 21 == 0 select num; foreach (var item in divisibleBy3and7) { Console.WriteLine(item); } } } }
a5b0c5de6be415bdcf4859e5d4c8d8791a83913b
C#
panaiotuzunov/Basics-Second-Run
/Simple Conditional Statements/Metric Converter/Program.cs
3.0625
3
using System; namespace Metric_Converter { class Program { static void Main(string[] args) { double num = double.Parse(Console.ReadLine()); string fromUnit = Console.ReadLine(); string toUnit = Console.ReadLine(); double numInM = num; double result = numInM; switch (fromUnit) { case "mm": numInM = num / 1000; break; case "cm": numInM = num / 100; break; case "mi": numInM = num / 0.000621371192; break; case "in": numInM = num / 39.3700787; break; case "km": numInM = num / 0.001; break; case "ft": numInM = num / 3.2808399; break; case "yd": numInM = num / 1.0936133; break; } switch (toUnit) { case "mm": result = numInM * 1000; break; case "cm": result = numInM * 100; break; case "mi": result = numInM * 0.000621371192; break; case "in": result = numInM * 39.3700787; break; case "km": result = numInM * 0.001; break; case "ft": result = numInM * 3.2808399; break; case "yd": result = numInM * 1.0936133; break; case "m": result = numInM; break; } Console.WriteLine(result); } } }
69933fb70d8994b6d5941e56e370473a3d76a896
C#
Albawab/MyWork
/C-/OOP/02 - Inheritance/02 - Inheritance/Cars.cs
2.96875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _02___Inheritance { class Cars { // The relation is "is a kind" public string model; public string make; string year; public void printModel() { Console.WriteLine($"{model}"); } } }
7e374a23a62a1b5b83d6438c18703dea02dbbed4
C#
TheTFo/LightBDD
/src/LightBDD.Framework/Commenting/StepExecutionExtensions.cs
2.734375
3
using LightBDD.Core.Configuration; using LightBDD.Framework.Commenting.Configuration; using LightBDD.Framework.ExecutionContext; using LightBDD.Framework.Extensibility.Implementation; namespace LightBDD.Framework.Commenting { /// <summary> /// Extension class for <see cref="StepExecution"/> allowing to comment currently running steps. /// </summary> public static class StepExecutionExtensions { /// <summary> /// Comments currently executed step with a <paramref name="comment"/> text. /// The comment would be included in progress notification, as well as in execution reports. /// <para>This feature has to be enabled in <see cref="LightBddConfiguration"/> via <see cref="CommentingConfigurationExtensions.EnableStepCommenting"/>() prior to usage.</para> /// </summary> /// <param name="execution">Current step execution instance.</param> /// <param name="comment">Comment to add. If comment is <c>null</c> or empty, it will not be added.</param> public static void Comment(this StepExecution execution, string comment) { if (!string.IsNullOrWhiteSpace(comment)) ScenarioExecutionContext.Current.Get<CurrentStepProperty>().Step.Comment(comment); } } }
af3e7cd5f89eb673c4d1a66c9ea8e48603096b8b
C#
Yewert/AS-Trace
/AS-Route/AdressInfo.cs
2.875
3
using System.Net; namespace AS_Route { public class AdressInfo : IAddressInfo { public AdressInfo(IPAddress address, string country, string autonomousSystem, string internetServiceProvider) { Address = address; Country = country; AutonomousSystem = autonomousSystem; InternetServiceProvider = internetServiceProvider; } public override string ToString() { return $"Address: {Address}, Country: {Country}, AutonomousSystem: {AutonomousSystem}, InternetServiceProvider: {InternetServiceProvider}"; } public IPAddress Address { get; } public string Country { get; } public string AutonomousSystem { get; } public string InternetServiceProvider { get; } } }
7fe8c499555cf6517305e8259dab832ede807890
C#
Rudy95/Workflow
/Workflow_BL/DAL/UserRepository.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Workflow_Models; using Workflow_Models.Models; namespace Workflow_BL.DAL { public class UserRepository : GenericRepository<User> { public UserRepository(DatabaseConfiguration context) : base(context) { Entity = ((DatabaseConfiguration)context).User; } public User GetUser(int id) { try { return Read(id); } catch (Exception) { throw; } } public IList<User> GetAllUsers() { return Entity.ToList(); } public void AddUser(User user) { Create(user); Context.SaveChanges(); } internal User GetUserByEmail(string name) { return Entity.FirstOrDefault(x=>x.Email==name); } } }
a139b025749272dd286c5810e7eb8488d348cbf5
C#
jazmincbp/trabajo
/21Julio/CLASE8/CLASE8/Program.cs
3.75
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CLASE8 { class MayorMenor { private int v1,v2,v3; private int May,Men; public void CargarValores() { Console.WriteLine("Digite valor 1"); v1 = int.Parse(Console.ReadLine()); Console.WriteLine("Digite valor 2"); v2 = int.Parse(Console.ReadLine()); Console.WriteLine("Digite valor 3"); v3 = int.Parse(Console.ReadLine()); May = CalcularMayor( v1, v2, v3); Men = CalcularMenor(v1, v2, v3); Console.WriteLine("El valor mayor es" + May); Console.WriteLine("El valor menor es" + Men); } public int CalcularMayor(int v1,int v2,int v3){ int m; if(v1>v2 && v1>v3){ m=v1; } else{ if (v2>v3) { m=v2; } else { m=v3; } } return m; } public int CalcularMenor(int v1, int v2, int v3){ int m; if(v1<v2 && v1<v2){ m = v1; } else { if (v2 < v3) { m = v2; } else { m = v3; } } return m; } static void Main(string[] args) { MayorMenor mm = new MayorMenor(); mm.CargarValores(); Console.ReadLine(); } } }
1aef10d69b2b850fc6d786cad264f8759ca6fc6b
C#
lucamihai/TextMining
/TextMining.Entities/TextData.cs
2.71875
3
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace TextMining.Entities { [ExcludeFromCodeCoverage] public class TextData { public Dictionary<string, int> WordDictionary { get; set; } public Dictionary<string, int> AcronymDictionary { get; set; } public int GetTotalWordCount() { return WordDictionary?.Values.Sum() ?? 0; } public int GetUniqueWordCount() { return WordDictionary?.Select(x => x.Key).Distinct().Count() ?? 0; } public int GetTotalAcronymCount() { return AcronymDictionary?.Values.Sum() ?? 0; } public int GetUniqueAcronymCount() { return AcronymDictionary?.Select(x => x.Key).Distinct().Count() ?? 0; } } }
37063b500023c5b9604185e2eb838c665b6de265
C#
austinjwilson/CSharpClass
/Labs/Lab2.cs
2.765625
3
using System; namespace CSharpClass.Labs { public class Counting { public void MyLab2() { for (int value = 0; value < 50; value++) { if (value % 3 == 0) { Console.WriteLine(value); } } } } }
ccbe01f2845eabfc61afd1e1d517d86e9e2985df
C#
jeongroseok/Astro-Game-Framework
/Astro.Networking/Messaging/NetworkMessage.cs
2.78125
3
using System; using System.IO; namespace Astro.Networking { public class NetworkMessage { private byte[] buffer; public short OwnerId { get; private set; } public Stream Stream { get { return new MemoryStream(buffer); } } internal NetworkMessage(byte[] buffer) { this.buffer = buffer; } public byte[] ToArray() { byte[] copy = new byte[buffer.Length]; Buffer.BlockCopy(buffer, 0, copy, 0, buffer.Length); return copy; } } }
7a0d527accd2a97cc6d2b8121a7d759426c7f1dd
C#
andreweua/ArduinoRFID
/Server/InnerSoft.MeEncontre.InfraStructure/Images/ImageHelper.cs
2.640625
3
using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; namespace MeEncontre.Infrastructure.Images { public static class ImageHelper { public enum AnchorPosition { Top, Center, Bottom, Left, Right } public static void ConfirmarImagem(string CodProdutoChave, string CodProduto, string imageFolderTemp, string imageFolder, string fileExtension) { //save uploaded image bool objReturn = false; string PathNormalTempImage = imageFolderTemp + string.Format(@"\{0}{1}", CodProdutoChave, fileExtension); string PathThumbTempImage = imageFolderTemp + string.Format(@"\{0}thumb{1}", CodProdutoChave, fileExtension); string PathZoomTempImage = imageFolderTemp + string.Format(@"\{0}zoom{1}", CodProdutoChave, fileExtension); string PathNormalImage = imageFolder + string.Format(@"\{0}{1}", CodProduto, fileExtension); string PathThumbImage = imageFolder + string.Format(@"\{0}thumb{1}", CodProduto, fileExtension); string PathZoomImage = imageFolder + string.Format(@"\{0}zoom{1}", CodProduto, fileExtension); if (File.Exists(PathNormalImage)) File.Delete(PathNormalImage); if (File.Exists(PathThumbImage)) File.Delete(PathThumbImage); if (File.Exists(PathZoomImage)) File.Delete(PathZoomImage); File.Move(PathNormalTempImage, PathNormalImage); File.Move(PathThumbTempImage, PathThumbImage); File.Move(PathZoomTempImage, PathZoomImage); } public static void ConfirmarImagemSimples(string CodProdutoChave, string CodProduto, string imageFolderTemp, string imageFolder, string fileExtension) { //save uploaded image bool objReturn = false; string PathNormalTempImage = imageFolderTemp + string.Format(@"\{0}{1}", CodProdutoChave, fileExtension); string PathNormalImage = imageFolder + string.Format(@"\{0}{1}", CodProduto, fileExtension); if (File.Exists(PathNormalImage)) File.Delete(PathNormalImage); File.Move(PathNormalTempImage, PathNormalImage); } public static void SalvarImagem(string Foto, byte[] image, string imageFolder, string fileExtension, bool produto) { string PathNormalImage = imageFolder + string.Format(@"\n{0}", Foto); string PathThumbImage = imageFolder + string.Format(@"\{0}", Foto); string PathZoomImage = imageFolder + string.Format(@"\z{0}", Foto); if (File.Exists(PathNormalImage)) File.Delete(PathNormalImage); if (File.Exists(PathThumbImage)) File.Delete(PathThumbImage); if (File.Exists(PathZoomImage)) File.Delete(PathZoomImage); MemoryStream file = new MemoryStream(image); System.Drawing.Image tmpImage = Image.FromStream(file); tmpImage = ResizeImageProporcional(tmpImage, 1000, 1000); tmpImage.Save(PathZoomImage, tmpImage.RawFormat); tmpImage.Dispose(); file.Dispose(); System.Drawing.Image NormalImage = ResizeImageProporcional(PathZoomImage, 200, 200); if (NormalImage != null) { System.Drawing.Imaging.ImageFormat imageFormat = new System.Drawing.Imaging.ImageFormat(new Guid()); switch (fileExtension.ToLower()) { case ".jpg": imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; break; case ".png": imageFormat = System.Drawing.Imaging.ImageFormat.Png; break; case ".gif": imageFormat = System.Drawing.Imaging.ImageFormat.Gif; break; default: imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; break; } NormalImage.Save(PathNormalImage, imageFormat); NormalImage.Dispose(); } System.Drawing.Image ThumbImage = ResizeImageProporcional(PathZoomImage, 80, 80); if (ThumbImage != null) { System.Drawing.Imaging.ImageFormat imageFormat = new System.Drawing.Imaging.ImageFormat(new Guid()); switch (fileExtension.ToLower()) { case ".jpg": imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; break; case ".png": imageFormat = System.Drawing.Imaging.ImageFormat.Png; break; case ".gif": imageFormat = System.Drawing.Imaging.ImageFormat.Gif; break; default: imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; break; } ThumbImage.Save(PathThumbImage, imageFormat); ThumbImage.Dispose(); } } public static void SalvarImagemSimples(string CodProduto, byte[] image, string imageFolder, string fileExtension) { string PathNormalImage = imageFolder + string.Format(@"\{0}{1}", CodProduto, fileExtension); if (File.Exists(PathNormalImage)) File.Delete(PathNormalImage); MemoryStream file = new MemoryStream(image); System.Drawing.Image tmpImage = Image.FromStream(file); tmpImage.Save(PathNormalImage, tmpImage.RawFormat); tmpImage.Dispose(); file.Dispose(); } public static byte[] GetBytesFromUrl(string url) { byte[] b; System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.WebResponse myResp = myReq.GetResponse(); Stream stream = myResp.GetResponseStream(); //int i; using (BinaryReader br = new BinaryReader(stream)) { //i = (int)(stream.Length); b = br.ReadBytes(500000); br.Close(); } myResp.Close(); return b; } public static void WriteBytesToFile(string fileName, byte[] content) { FileStream fs = new FileStream(fileName, FileMode.Create); BinaryWriter w = new BinaryWriter(fs); try { w.Write(content); } finally { fs.Close(); w.Close(); } } public static Image ResizeImage(string pathImageTemp, int imageWidth, int imageHeight) { System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(pathImageTemp); return ResizeImage(fullSizeImg, imageHeight, imageHeight); } public static Image ResizeImage(Image imgPhoto, int Width, int Height) { int sourceWidth = imgPhoto.Width; int sourceHeight = imgPhoto.Height; Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); bmPhoto.MakeTransparent(Color.Transparent); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.Clear(Color.Transparent); grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(imgPhoto, new Rectangle(-1, -1, Width + 1, Height + 1), new Rectangle(0, 0, sourceWidth, sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); imgPhoto.Dispose(); return bmPhoto; } public static System.Drawing.Image ResizeImageProporcional(System.Drawing.Image Image, int maxWidth, int maxHeight) { System.Drawing.Image fullSizeImg = Image; decimal WidthFactor = (decimal)maxWidth / (decimal)fullSizeImg.Width; decimal HeigntFactor = (decimal)maxHeight / (decimal)fullSizeImg.Height; decimal Factor = (HeigntFactor > WidthFactor) ? WidthFactor : HeigntFactor; int newWidth = (int)((decimal)fullSizeImg.Width * Factor); int newHeight = (int)((decimal)fullSizeImg.Height * Factor); return ResizeImage(fullSizeImg, newWidth, newHeight); } public static System.Drawing.Image ResizeImageProporcional(string pathImageTemp, int MaxWidth, int MaxHeight) { System.Drawing.Image image = null; try { image = ResizeImageProporcional(System.Drawing.Image.FromFile(pathImageTemp), MaxWidth, MaxHeight); } catch { } return image; } public static System.Drawing.Image CropImage(System.Drawing.Image imgPhoto, int Width, int Height, AnchorPosition Anchor) { int sourceWidth = imgPhoto.Width; int sourceHeight = imgPhoto.Height; int sourceX = 0; int sourceY = 0; int destX = 0; int destY = 0; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; nPercentW = ((float)Width / (float)sourceWidth); nPercentH = ((float)Height / (float)sourceHeight); if (nPercentH < nPercentW) { nPercent = nPercentW; switch (Anchor) { case AnchorPosition.Top: destY = 0; break; case AnchorPosition.Bottom: destY = (int) (Height - (sourceHeight * nPercent)); break; default: destY = (int) ((Height - (sourceHeight * nPercent)) / 2); break; } } else { nPercent = nPercentH; switch (Anchor) { case AnchorPosition.Left: destX = 0; break; case AnchorPosition.Right: destX = (int) (Width - (sourceWidth * nPercent)); break; default: destX = (int) ((Width - (sourceWidth * nPercent)) / 2); break; } } int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); return bmPhoto; } public static bool ResizeAndSaveImageProporcional(string pathImageTemp, byte[] file, int MaxWidth, int MaxHeight) { bool objReturn = false; try { MemoryStream imageStream = new MemoryStream(file); System.Drawing.Image fullSizeImg = System.Drawing.Image.FromStream(imageStream); System.Drawing.Image AdjustedImage = ResizeImageProporcional(fullSizeImg, MaxWidth, MaxHeight); System.Drawing.Imaging.ImageFormat imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; if (AdjustedImage != null) { switch (pathImageTemp.Substring(pathImageTemp.Length - 4)) { case ".jpg": imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; break; case ".png": imageFormat = System.Drawing.Imaging.ImageFormat.Png; break; case ".gif": imageFormat = System.Drawing.Imaging.ImageFormat.Gif; break; default: imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; break; } AdjustedImage.Save(pathImageTemp, imageFormat); AdjustedImage.Dispose(); objReturn = true; } imageStream.Close(); imageStream.Dispose(); } catch { } return objReturn; } } }
90453ab64d1483796ab73814621d07fbc6df65ca
C#
wite/Kata
/TakeANumberAndSumItsDigitsRaised.cs
3.71875
4
using System; using System.Collections.Generic; public class SumDigPower { public static long[] SumDigPow(long a, long b) { List<long> numbersWithProperty = new List<long>(); for (long x = a; x <= b; x++) { string valueAsString = x.ToString(); long power = valueAsString.Length; double valueSecond = 0; for (int i = 0; i < power; i++) { valueSecond += Math.Pow(Char.GetNumericValue(valueAsString[i]), i + 1); } if (x == valueSecond) numbersWithProperty.Add(x); } return numbersWithProperty.ToArray(); } }
3b004a0b412ae410c8f68c1bd59ae76f74cc2025
C#
HoaiNN1/AdventureGame
/Adventure/Controllers/CharacterController.cs
2.625
3
using Adventure.Commom.Models; using Adventure.Services.Characters; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Adventure.Controllers { [ApiController] [Route("[controller]")] public class CharacterController : ControllerBase { private readonly ICharacterService _characterService; public CharacterController(ICharacterService characterService) { _characterService = characterService; } [HttpGet("GetAll")] public async Task<IActionResult> GetAll() { return Ok(await _characterService.GetAllCharacters()); } [HttpGet("{id}")] public async Task<IActionResult> Get(int id) { return Ok(await _characterService.GetCharacterById(id)); } [HttpPost] public async Task<IActionResult> Add(Character newCharacter) { return Ok(await _characterService.AddCharacter(newCharacter)); } [HttpPut] public async Task<IActionResult> Update(Character updatedCharacter) { return Ok(); } [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { return Ok(); } } }
53810ea71550414a5aa3b67f14a9cb5d49168cb6
C#
phamhoanghaison0402/Fsoft-Fresher-.NET-2017
/Projects/source/IPM/IPM.Service/InterviewerService.cs
2.78125
3
using System.Collections.Generic; using IPM.Business; using IPM.Model.Models; namespace IPM.Service { /// <summary> /// </summary> public interface IInterviewerService { /// <summary> /// Gets all. /// </summary> /// <param name="searchString">The search string.</param> /// <returns></returns> IEnumerable<User> GetAll(string searchString); } /// <summary> /// </summary> /// <seealso cref="IPM.Service.IInterviewerService" /> public class InterviewerService : IInterviewerService { private readonly IInterviewerBusiness _interviewerBusiness; /// <summary> /// Initializes a new instance of the <see cref="InterviewerService" /> class. /// </summary> /// <param name="interviewerBusiness">The interviewer business.</param> public InterviewerService(IInterviewerBusiness interviewerBusiness) { _interviewerBusiness = interviewerBusiness; } /// <summary> /// Gets all. /// </summary> /// <param name="searchString">The search string.</param> /// <returns></returns> public IEnumerable<User> GetAll(string searchString) { if (string.IsNullOrEmpty(searchString)) { return _interviewerBusiness.GetAll(searchString); } return _interviewerBusiness.GetAll(searchString); } } }
d64c7c42f83ac7119f20f8e0f2019dfad1b9b497
C#
dnartub/sample-aspcore-vue-dockers
/src-back/common/Cqrs/Interfaces/ICqrsService.cs
2.75
3
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Cqrs.Interfaces { /// <summary> /// Фабрика получения обработчиков действий (комманд и запросов) /// Выполнение обработчиков /// </summary> public interface ICqrsService { /// <summary> /// Выполнение команды на изменение данных /// </summary> /// <typeparam name="TCommand"></typeparam> /// <param name="command"></param> Task Execute<TCommand>(TCommand command) where TCommand : ICommand; /// <summary> /// Отмена команды /// </summary> /// <typeparam name="TCommand"></typeparam> /// <param name="command"></param> /// <returns></returns> Task Down<TCommand>(TCommand command) where TCommand : ICommand; /// <summary> /// Выполнение запроса на получение данных /// </summary> TResult GetResult<TResult>(IQuery<TResult> query); /// <summary> /// Получение обработчика для выполнения команды /// </summary> /// <typeparam name="TCommand"></typeparam> /// <param name="command"></param> /// <returns></returns> ICommandHandler<TCommand> GetHandler<TCommand>() where TCommand : ICommand; /// <summary> /// Получение обработчика для выпонения запроса /// </summary> /// <typeparam name="TQuery"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="query"></param> /// <returns></returns> IQueryHandler<TQuery, TResult> GetHandler<TQuery, TResult>() where TQuery : IQuery<TResult>; } }
12740aea20f29a7d50ddc295254cfef03dd52796
C#
sajayantony/oci-anoymous-pull-dotnet
/ContentStore.cs
2.625
3
using System; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Azure.ContainerRegistry; using System.Text; using System.Text.Json; using System.Threading; using Microsoft.Rest; using System.Net.Http.Headers; using System.IO; namespace OCIArtifact.Samples { public class ContentStore { public static async Task PullAsync(string registry, string repo, string tag) { var image = new ImageRef() { HostName = registry, Repository = repo, Tag = tag }; var loginUri = $"https://{registry}"; AzureContainerRegistryClient runtimeClient = new AzureContainerRegistryClient(registry, new AnonymousToken(image)); //Get manifest var manifestResponse = runtimeClient.Manifests.GetAsync(repo, tag, "application/vnd.oci.image.manifest.v1+json").Result; Console.WriteLine("Manifest:"); Console.WriteLine(JsonSerializer.Serialize(manifestResponse, new JsonSerializerOptions() { WriteIndented = true }).ToString()); //Dowload multiple layers here. Console.WriteLine("Starting Layer Download....."); for (int i = 0; i < manifestResponse.Layers.Count; i++) { var l0 = manifestResponse.Layers[0]; var blobStream = await runtimeClient.Blob.GetAsync(repo, l0.Digest); var fileName = l0.Annotations.Title; Console.WriteLine($"Writing File: {fileName}"); using (FileStream fs = File.OpenWrite(fileName)) { await blobStream.CopyToAsync(fs); } } } class AnonymousToken : ServiceClientCredentials { public ImageRef _image; public AnonymousToken(ImageRef image) { _image = image; } public override void InitializeServiceClient<T>(ServiceClient<T> client) { base.InitializeServiceClient(client); } private async Task<string> GetAccessToken() { HttpClient c = new HttpClient(); var service = _image.HostName; var repo = _image.Repository; var hostname = System.Environment.MachineName; var scope = $"repository:{repo}:pull"; string uri = $"https://{service}/oauth2/token?client={hostname}&scope={scope}&service={service}"; var response = c.GetAsync(uri).Result; var strResponse = await response.Content.ReadAsStringAsync(); //Console.WriteLine(strResponse); var jToken = JsonSerializer.Deserialize<AuthToken>(strResponse); return jToken.access_token; } public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var accessToken = GetAccessToken().Result; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return base.ProcessHttpRequestAsync(request, cancellationToken); } } class AuthToken { public string access_token { get; set; } } public class ImageRef { public string HostName { get; set; } public string Repository { get; set; } public string Tag { get; set; } } } }
42adf285f850ddc9e583882159f4cc142de50f7a
C#
roman-belfer/VGA
/VipGuardAccounter/Common.UI/Controls/RateControl.xaml.cs
2.78125
3
using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; namespace Common.UI.Controls { public partial class RateControl : UserControl { public RateControl() { InitializeComponent(); RateCollection = new ObservableCollection<bool>(); for (int i = 0; i < 5; i++) RateCollection.Add(false); } public static readonly DependencyProperty RateProperty = DependencyProperty.Register("Rate", typeof(int), typeof(RateControl), new PropertyMetadata(OnRateChanged)); public static readonly DependencyProperty RateCollectionProperty = DependencyProperty.Register("RateCollection", typeof(ObservableCollection<bool>), typeof(RateControl), new PropertyMetadata()); public int Rate { get { return (int)GetValue(RateProperty); } set { SetValue(RateProperty, value); } } public ObservableCollection<bool> RateCollection { get { return (ObservableCollection<bool>)GetValue(RateCollectionProperty); } set { SetValue(RateCollectionProperty, value); } } private static void OnRateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var rate = (int)e.NewValue; if (d is RateControl rateControl && rate > 0 && rate <= 5) { for (int i = 0; i < rate; i++) rateControl.RateCollection[i] = true; } } } }
488f90783a99d80ee43c0bf943236a3260b0cf0f
C#
TsvetelinIvanov/SoftUni-CSharpFundamentals-I2018
/CSharpAdvanced/02MultidimensionalArraysExercise/08RadioactiveMutantVampireBunnies.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; namespace _08RadioactiveMutantVampireBunnies { class Program { static void Main(string[] args) { int[] lairDimensions = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse).ToArray(); int rowsCount = lairDimensions[0]; int colsCount = lairDimensions[1]; char[,] lair = new char[rowsCount, colsCount]; char[,] bunnyLair = new char[rowsCount, colsCount]; int[] playerPosition = new int[2]; for (int row = 0; row < rowsCount; row++) { char[] rowValues = Console.ReadLine().ToCharArray(); for (int col = 0; col < colsCount; col++) { lair[row, col] = rowValues[col]; bunnyLair[row, col] = rowValues[col]; if (lair[row, col] == 'P') { playerPosition[0] = row; playerPosition[1] = col; } } } Queue<char> directions = new Queue<char>(Console.ReadLine().ToCharArray()); bool isDead = false; bool isWon = false; int lastCellRow = 0; int lastCellCol = 0; while (true) { char moving = directions.Dequeue(); switch (moving) { case 'U': int row = playerPosition[0]; int col = playerPosition[1]; if (row == 0) { isWon = true; lastCellRow = row; lastCellCol = col; lair[row, col] = '.'; bunnyLair[row, col] = '.'; } else if (lair[row - 1, col] == 'B') { isDead = true; lastCellRow = row - 1; lastCellCol = col; lair[row, col] = '.'; bunnyLair[row, col] = '.'; } else if (lair[row - 1, col] == '.') { lair[row - 1, col] = 'P'; bunnyLair[row - 1, col] = 'P'; lair[row, col] = '.'; bunnyLair[row, col] = '.'; playerPosition[0] = row - 1; } break; case 'D': row = playerPosition[0]; col = playerPosition[1]; if (row == lair.GetLength(0) - 1) { isWon = true; lastCellRow = row; lastCellCol = col; lair[row, col] = '.'; bunnyLair[row, col] = '.'; } else if (lair[row + 1, col] == 'B') { isDead = true; lastCellRow = row + 1; lastCellCol = col; lair[row, col] = '.'; bunnyLair[row, col] = '.'; } else if (lair[row + 1, col] == '.') { lair[row + 1, col] = 'P'; bunnyLair[row + 1, col] = 'P'; lair[row, col] = '.'; bunnyLair[row, col] = '.'; playerPosition[0] = row + 1; } break; case 'L': row = playerPosition[0]; col = playerPosition[1]; if (col == 0) { isWon = true; lastCellRow = row; lastCellCol = col; lair[row, col] = '.'; bunnyLair[row, col] = '.'; } else if (lair[row, col - 1] == 'B') { isDead = true; lastCellRow = row; lastCellCol = col - 1; lair[row, col] = '.'; bunnyLair[row, col] = '.'; } else if (lair[row, col - 1] == '.') { lair[row, col - 1] = 'P'; bunnyLair[row, col - 1] = 'P'; lair[row, col] = '.'; bunnyLair[row, col] = '.'; playerPosition[1] = col - 1; } break; case 'R': row = playerPosition[0]; col = playerPosition[1]; if (col == lair.GetLongLength(1) - 1) { isWon = true; lastCellRow = row; lastCellCol = col; lair[row, col] = '.'; bunnyLair[row, col] = '.'; } else if (lair[row, col + 1] == 'B') { isDead = true; lastCellRow = row; lastCellCol = col + 1; lair[row, col] = '.'; bunnyLair[row, col] = '.'; } else if (lair[row, col + 1] == '.') { lair[row, col + 1] = 'P'; bunnyLair[row, col + 1] = 'P'; lair[row, col] = '.'; bunnyLair[row, col] = '.'; playerPosition[1] = col + 1; } break; } for (int row = 0; row < lair.GetLength(0); row++) { for (int col = 0; col < lair.GetLength(1); col++) { if (lair[row, col] == 'B') { if (IsInLair(lair, row - 1, col)) { if (lair[row - 1, col] == 'P') { isDead = true; lastCellRow = row - 1; lastCellCol = col; } bunnyLair[row - 1, col] = 'B'; } if (IsInLair(lair, row + 1, col)) { if (lair[row + 1, col] == 'P') { isDead = true; lastCellRow = row + 1; lastCellCol = col; } bunnyLair[row + 1, col] = 'B'; } if (IsInLair(lair, row, col + 1)) { if (lair[row, col + 1] == 'P') { isDead = true; lastCellRow = row; lastCellCol = col + 1; } bunnyLair[row, col + 1] = 'B'; } if(IsInLair(lair, row, col - 1)) { if (lair[row, col - 1] == 'P') { isDead = true; lastCellRow = row; lastCellCol = col - 1; } bunnyLair[row, col - 1] = 'B'; } } } } for (int row = 0; row < lair.GetLength(0); row++) { for (int col = 0; col < lair.GetLength(1); col++) { lair[row, col] = bunnyLair[row, col]; } } if (isDead || isWon) { break; } } for (int row = 0; row < lair.GetLength(0); row++) { for (int col = 0; col < lair.GetLength(1); col++) { Console.Write(lair[row, col]); } Console.WriteLine(); } if (isWon) { Console.WriteLine("won: " + lastCellRow + " " + lastCellCol); } else if (isDead) { Console.WriteLine("dead: " + lastCellRow + " " + lastCellCol); } } private static bool IsInLair(char[,] matrix, int row, int col) { return row >= 0 && row < matrix.GetLength(0) && col >= 0 && col < matrix.GetLength(1); } } }
a63151ed1068b12765cf899a0896c81e1acbed37
C#
constantlearning/unitri
/unitri-pds/Aula06/aula06-ex03/aula06-ex03/repository/ConnectionFactory.cs
2.671875
3
using System; using System.Data.SqlClient; namespace aula06_ex03.repository { class ConnectionFactory { private static string connString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Lucas\Documents\Projetos VS2017\unitri-pds\Aula06\aula06-ex03\aula06ex03.mdf;Integrated Security=True;Connect Timeout=30"; public static SqlConnection GetConnection() { SqlConnection connection = new SqlConnection(connString); connection.Open(); return connection; } public static void CloseConnection(SqlConnection connection) { try { connection.Close(); } catch(Exception ex) { } } } }
3ea306ca24e6009bfb5d77bd33c433685a9d27d2
C#
PavelRunchev/Dot.Net-Advanced
/C# Advanced/8. Functional Programming - Exercise/5. Applied Arithmetics/AppliedArithmetics.cs
4.09375
4
using System; using System.Linq; namespace AppliedArithmetics { class AppliedArithmetics { static void Main() { Action<int[]> printCollection = numbers => Console.WriteLine(String.Join(" ", numbers)); Func<int[], int[]> encrementAllElements = numbers => { for (int i = 0; i < numbers.Length; i++) { numbers[i]++; } return numbers; }; Func<int[], int[]> multiplyAllElements = numbers => { for (int i = 0; i < numbers.Length; i++) { numbers[i] *= 2; } return numbers; }; Func<int[], int[]> subtractAllElements = numbers => { for (int i = 0; i < numbers.Length; i++) { numbers[i]--; } return numbers; }; int[] inputElements = Console.ReadLine().Split().Select(int.Parse).ToArray(); string commands; while((commands = Console.ReadLine()) != "end") { switch (commands) { case "add": inputElements = encrementAllElements(inputElements); break; case "multiply": inputElements = multiplyAllElements(inputElements); break; case "subtract": inputElements = subtractAllElements(inputElements); break; case "print": printCollection(inputElements); break; } } } } }
a5000b79a82804cfe2500f0a13ef4267dd96c6fa
C#
NshanKepityan/assignment_12
/MathServer/TCPServer.cs
3.34375
3
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using System.Text.RegularExpressions; namespace MathServer { public class TCPMathServer { private IPAddress ipAd; private TcpListener listener; private Socket socket; private string op; private double op1; private double op2; private double result; private bool flag; private MathService mathServices = new MathService(); public double ReadOperation() { switch(this.op) { case "+": this.result = mathServices.Add(this.op1, this.op2); break; case "-": this.result = mathServices.Sub(this.op1, this.op2); break; case "*": this.result = mathServices.Mult(this.op1, this.op2); break; case "/": this.result = mathServices.Div(this.op1, this.op2); break; default:throw new ArgumentOutOfRangeException(); } return this.result; } public void Run() { Console.WriteLine("Tcp is running"); Console.WriteLine("The server is running"); Console.WriteLine("Waiting for a connection....."); this.ipAd = IPAddress.Parse("127.0.0.1"); this.listener = new TcpListener(ipAd, 65410); this.listener.Start(); this.socket = this.listener.AcceptSocket(); Console.WriteLine("Connection accepted from " + this.socket.RemoteEndPoint.Serialize()); this.flag = true; while (this.flag) { try { byte[] resivedMsg = new byte[100]; int k = this.socket.Receive(resivedMsg); string msg = Encoding.UTF8.GetString(resivedMsg, 0, resivedMsg.Length); if (msg.Trim() == "Quit") { this.flag = false; break; } string pattern = @"([+-/*]):([0-9]*):([0-9]*)"; Regex regex = new Regex(pattern); Match match = regex.Match(msg); if (match.Success && match.Groups[1].Value != null && match.Groups[2].Value != null && match.Groups[2].Value != null) { this.op = match.Groups[1].Value; this.op1 = Convert.ToDouble(match.Groups[2].Value); this.op2 = Convert.ToDouble(match.Groups[3].Value); ReadOperation(); } else throw new NotSupportedException(); Console.WriteLine("Recieved..."); Console.WriteLine(msg); Console.WriteLine("the answer is {0}", this.result); this.socket.Send(Encoding.ASCII.GetBytes($"The result is {this.result}.")); } catch (NotSupportedException e) { Console.WriteLine("The expression was inccorect" + e.StackTrace); this.socket.Send(Encoding.ASCII.GetBytes($"The expression was inccorect.")); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("The second argument was inccorect" + e.StackTrace); this.socket.Send(Encoding.ASCII.GetBytes("The second argument was inccorect.")); } } this.socket.Close(); this.listener.Stop(); } } }
e59f99a685c543abae042a33fc101f4e189a8a80
C#
duckstop/charapp
/CharApp/Repositories/CharacterRepository.cs
2.9375
3
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using CharApp.Abstract; using CharApp.Models; namespace CharApp.Repositorys { public class CharacterRepository : ICharacterRepository //Repository af typen Character. { ApplicationDbContext _db = new ApplicationDbContext(); public List<Character> GetAll() { return _db.Characters.ToList(); } public Character Find(int id) { return _db.Characters.Find(id); } public void Delete(int id) { _db.Characters.Remove(_db.Characters.Find(id)); } public void InsertOrUpdate(Character character) { if (character.CharID == default(int)) { _db.Characters.Add(character); } else { _db.Entry(character).State = EntityState.Modified; } } public void Save() { _db.SaveChanges(); } } }
647285f5466fb26e5fd35942698b8e531b2b00e6
C#
Brannos1970/PGDrive
/PGDrive/PGoogleDrive/Internal/Models/General/PGDriveConfig.cs
2.578125
3
using System; using System.Configuration; namespace PGoogleDrive.Internal.Models.General { internal class PGDriveConfig { public static PGDriveConfigSection _Config = ConfigurationManager.GetSection("PGDrive") as PGDriveConfigSection; public static ApiKeyPGDriveElementCollection GetApiKeysDrives() { return _Config.ApiKeyDrives; } public static OAuthPGDriveElementCollection GetOAuthDrives() { return _Config.OAuthDrives; } public static OAuthGDriveElement GetOAuthElement(string Name) { foreach(OAuthGDriveElement element in GetOAuthDrives()) { if (element.Name == Name) return element; } return null; } public static ApiKeyGDriveElement GetApiKeyElement(string Name) { foreach (ApiKeyGDriveElement element in GetApiKeysDrives()) { if (element.Name == Name) return element; } return null; } } public class PGDriveConfigSection : ConfigurationSection { //Decorate the property with the tag for your collection. [ConfigurationProperty("OAuthDrives")] public OAuthPGDriveElementCollection OAuthDrives { get { return (OAuthPGDriveElementCollection)this["OAuthDrives"]; } } [ConfigurationProperty("ApiKeyDrives")] public ApiKeyPGDriveElementCollection ApiKeyDrives { get { return (ApiKeyPGDriveElementCollection)this["ApiKeyDrives"]; } } } [ConfigurationCollection(typeof(OAuthGDriveElement), AddItemName ="drive")] public class OAuthPGDriveElementCollection : ConfigurationElementCollection { public OAuthGDriveElement this[int index] { get { return (OAuthGDriveElement)BaseGet(index); } set { if (BaseGet(index) != null) BaseRemoveAt(index); BaseAdd(index, value); } } protected override ConfigurationElement CreateNewElement() { return new OAuthGDriveElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((OAuthGDriveElement)element).Name; } } public class OAuthGDriveElement : ConfigurationElement { [ConfigurationProperty("name", IsRequired = true)] public string Name { get { return (string)this["name"]; } set { this["name"] = value; } } [ConfigurationProperty("applicationName", IsRequired = true)] public string ApplicationName { get { return (string)this["applicationName"]; } set { this["applicationName"] = value; } } [ConfigurationProperty("clientSecretPath", IsRequired = true)] public string ClientSecretPath { get { return (string)this["clientSecretPath"]; } set { this["clientSecretPath"] = value; } } [ConfigurationProperty("default", IsRequired = false, DefaultValue = true)] public bool Default { get { return (bool)this["default"]; } set { this["default"] = value; } } } [ConfigurationCollection(typeof(OAuthGDriveElement), AddItemName ="drive")] public class ApiKeyPGDriveElementCollection : ConfigurationElementCollection { public ApiKeyGDriveElement this[int index] { get { return (ApiKeyGDriveElement)BaseGet(index); } set { if (BaseGet(index) != null) BaseRemoveAt(index); BaseAdd(index, value); } } protected override ConfigurationElement CreateNewElement() { return new ApiKeyGDriveElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((ApiKeyGDriveElement)element).Name; } } public class ApiKeyGDriveElement : ConfigurationElement { [ConfigurationProperty("name", IsRequired = true)] public string Name { get { return (string)this["name"]; } set { this["name"] = value; } } [ConfigurationProperty("apiKey", IsRequired = true)] public string ApiKey { get { return (string)this["apiKey"]; } set { this["apiKey"] = value; } } [ConfigurationProperty("default", IsRequired = false, DefaultValue = true)] public bool Default { get { return (bool)this["default"]; } set { this["default"] = value; } } } }
ee65fc82e6e81bd77d10223b07e9c1aa0873b0de
C#
philanderson888/2019-06-c-sharp-labs
/labs/lab_43_database_app/MainWindow.xaml.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace lab_43_database_app { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { List<Customer> customers; Customer customer; public MainWindow() { InitializeComponent(); Initialise(); } void Initialise() { using (var db = new NorthwindEntities()) { customers = db.Customers.ToList(); } ListBoxCustomers.ItemsSource = customers; } private void ButtonAdd_Click(object sender, RoutedEventArgs e) { // if ButtonAdd content = "Clear" then clear all textboxes // out and set content back to 'add' if (ButtonAdd.Content.ToString() == "Clear") { TextBoxID.Text = "TEST1"; TextBoxName.Text = "Phil"; TextBoxCompany.Text = "Company"; TextBoxCity.Text = "City"; TextBoxCountry.Text = "Country"; ButtonAdd.Content = "Add"; } else if(TextBoxID.Text !="" && TextBoxCompany.Text != "") { MessageBox.Show("about to add a new customer"); var newCustomer = new Customer() { CustomerID = TextBoxID.Text, ContactName = TextBoxName.Text, City = TextBoxCity.Text, Country =TextBoxCountry.Text }; // unbind listbox first ListBoxCustomers.ItemsSource = null; customers = null; // add new customer using (var db = new NorthwindEntities()) { db.Customers.Add(newCustomer); db.SaveChanges(); customers = db.Customers.ToList(); } ListBoxCustomers.ItemsSource = customers; ButtonAdd.Content = "Clear"; } } private void ButtonEdit_Click(object sender, RoutedEventArgs e) { if (ButtonEdit.Content.ToString() == "Edit") { TextBoxID.IsEnabled = true; TextBoxName.IsEnabled = true; TextBoxCity.IsEnabled = true; TextBoxCompany.IsEnabled = true; TextBoxCountry.IsEnabled = true; TextBoxID.Background = Brushes.White; TextBoxName.Background = Brushes.White; TextBoxCompany.Background = Brushes.White; TextBoxCity.Background = Brushes.White; TextBoxCountry.Background = Brushes.White; ButtonEdit.Content = "Save"; } else if(ButtonEdit.Content.ToString() == "Save") { if (customer != null) { using (var db = new NorthwindEntities()) { var customerToEdit = db.Customers .Where(c => c.CustomerID == customer.CustomerID) .FirstOrDefault(); MessageBox.Show($"customer ready to edit {customerToEdit.CustomerID}"); customerToEdit.ContactName = TextBoxName.Text; customerToEdit.CompanyName = TextBoxCompany.Text; customerToEdit.City = TextBoxCity.Text; customerToEdit.Country = TextBoxCountry.Text; db.SaveChanges(); // refresh view ListBoxCustomers.ItemsSource = null; // disconnect listbox from formal customer list // because we are about to change it customers = db.Customers.ToList(); // get a new list from db ListBoxCustomers.ItemsSource = customers; } } } } private void ButtonDelete_Click(object sender, RoutedEventArgs e) { if (ButtonDelete.Content.ToString() == "Delete") { if (customer == null) { MessageBox.Show("no customer selected"); return; } ButtonDelete.Content = "Confirm"; ButtonDelete.Background = Brushes.Red; } else if (ButtonDelete.Content.ToString() == "Confirm") { // find record by ID and delete it using (var db = new NorthwindEntities()) { var customerToDelete = db.Customers.Find(customer.CustomerID); db.Customers.Remove(customerToDelete); db.SaveChanges(); // refresh ListBoxCustomers.ItemsSource = null; customers = db.Customers.ToList(); ListBoxCustomers.ItemsSource = customers; } } } private void ListBoxCustomers_SelectionChanged(object sender, SelectionChangedEventArgs e) { ButtonAdd.Content = "Clear"; customer = (Customer)ListBoxCustomers.SelectedItem; if (customer != null) { ListBoxLog.Items.Insert(0, " "); ListBoxLog.Items.Insert(0, DateTime.Now); ListBoxLog.Items.Insert(0, "Customer Selected"); //ListBoxLog.Items.Insert(0,$"{customer.CustomerID,-7},{customer.ContactName} from {customer.City}"); // fill text boxes TextBoxID.Text = customer.CustomerID; TextBoxName.Text = customer.ContactName; TextBoxCity.Text = customer.City; TextBoxCountry.Text = customer.Country; TextBoxCompany.Text = customer.CompanyName; // set to read only also TextBoxID.IsEnabled = false; TextBoxName.IsEnabled = false; TextBoxCity.IsEnabled = false; TextBoxCompany.IsEnabled = false; TextBoxCountry.IsEnabled = false; } } } }
968ef0ad24f29704864d7861a457aba2e1f94459
C#
Agilsaav/TFM
/tfm/Assets/Scripts/Movement/LinearMovement.cs
2.984375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; //Class not used: Moves an object in a direction. public class LinearMovement : MonoBehaviour { [SerializeField] float distanceToMove = 5.0f; [SerializeField] float speed = 1.0f; [SerializeField] Vector3 direction = new Vector3(1.0f, 0.0f, 0.0f); Vector3 initialPos; Vector3 lastPos; float initialPosDir; float distanceMoved; private void Start() { initialPos = transform.position; initialPosDir = Vector3.Dot(initialPos, direction); distanceMoved = 0.0f; } void Update() { lastPos = transform.position; if (Vector3.Dot(transform.position, direction) - initialPosDir < distanceToMove || distanceMoved < distanceToMove) { transform.position += direction * speed * Time.deltaTime; distanceMoved += Vector3.Distance(transform.position, lastPos); } else { distanceMoved = 0.0f; direction = -direction; transform.position -= direction * speed * Time.deltaTime; //distanceMoved += Vector3.Distance(transform.position, lastPos); } } }
08abbfbbf6c560877504b7d8ce73296fc53b3389
C#
looki666/LanguageProject
/LanguageProjectUnity/Assets/Scripts/AI/Cognition/Inference/Pattern/EvaluationPattern.cs
2.984375
3
using System; using System.Collections.Generic; public enum EntailmentContext { Upward, Downward, None } public class EvaluationPattern { public IPattern pattern { get; protected set; } public EntailmentContext context { get; protected set; } public EvaluationPattern(IPattern pattern, EntailmentContext context) { this.pattern = pattern; this.context = context; } public static EntailmentContext MergeContext(EntailmentContext a, EntailmentContext b) { if (a == EntailmentContext.None || b == EntailmentContext.None) { return EntailmentContext.None; } if (a == EntailmentContext.Upward) { return b; } if (a == EntailmentContext.Downward) { if (b == EntailmentContext.Upward) { return EntailmentContext.Downward; } else { return EntailmentContext.Upward; } } return EntailmentContext.None; } public override String ToString() { String contextString = "."; if (context == EntailmentContext.Upward) { contextString = "+"; } if (context == EntailmentContext.Downward) { contextString = "-"; } return pattern.ToString() + contextString; } }
59d61b84c5398f384ae52c2c2c1194139434e333
C#
matheushcamilo/Cadastro-DIO
/Cadastros/Cadastros/Classes/RepositorioSeries.cs
3.515625
4
using Cadastros.Interfaces; using System; using System.Collections.Generic; namespace Cadastros.Classes { public class RepositorioSeries : IRepositorios<Series> { private List<Series> listaSerie = new List<Series>(); public void Atualizar(int i, Series objeto) { listaSerie[i - 1] = objeto; } public void Excluir(int i) { listaSerie.RemoveAt(i - 1); } public void Inserir(Series objeto) { listaSerie.Add(objeto); } public List<Series> Lista() { return listaSerie; } public int Tamanho() { return listaSerie.Count; } public Series RetornaPorId(int id) { return listaSerie[id - 1]; } public bool isEmpty() { return Tamanho() == 0; } public string ToString() { if(isEmpty()) { Console.WriteLine("Lista vazia"); return "Catálogo de séries vazio!"; } int count = 1; string str = ""; while(count <= Tamanho()) { str += "Série " + count + ":\n"; str += RetornaPorId(count).toString(); count++; } return str; } } }
731a23b849981b231d74f851b0201104001ef87f
C#
damjik/Colorful.Console
/src/Colorful.Console.Tests/TextPatternTests.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using Colorful; using System.Drawing; namespace Colorful.Console.Tests { public sealed class TextPatternTests { private static readonly string dummyString = "cat"; private static readonly string dummyRegexPattern = "[0-9]"; [Fact] public void GetMatchLocations_ReturnsOneMatchLocation_WhenIdenticalStringIsMatchedAgainst() { TextPattern pattern = new TextPattern(dummyString); Assert.Single(pattern.GetMatchLocations(dummyString)); } [Fact] public void GetMatchLocations_ReturnsThreeMatchLocations_When666IsMatchedAgainst() { string matchTarget = "666"; TextPattern pattern = new TextPattern(dummyRegexPattern); Assert.Equal(3, pattern.GetMatchLocations(matchTarget).Count()); } [Fact] public void GetMatches_ReturnsExpectedMatches_When012IsMatchedAgainst() { string matchTarget = "012"; TextPattern pattern = new TextPattern(dummyRegexPattern); List<string> matches = pattern.GetMatches(matchTarget).ToList(); bool allMatch = true; for (int i = 0; i < matches.Count; i++) { if (i != int.Parse(matches[i])) { allMatch = false; } } Assert.True(allMatch); } } }
0008425874b50b466c3cadfa64adf1fcc5a2396a
C#
caffeine239/BeatSaberCloneScoreServer
/Database/DataBase.cs
2.78125
3
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; public class DB { public static Database _current = new Database(); } public class Database { public int RowCount { get; set; } public static MySqlConnection Connection; public static MySql.Data.MySqlClient.MySqlDataReader SqlData; internal static void Init(string host, string user, string password, string database, int port) { Connection = new MySqlConnection("Server=" + host + ";User Id=" + user + ";Port=" + port + ";" + "Password=" + password + ";Database=" + database + ";charset=utf8;Allow Zero Datetime=True"); try { Connection.Open(); Console.WriteLine("Successfully connected to " + host + " " + port + " " + database); } catch (MySqlException ex) { Console.WriteLine(ex.ToString()); return; } } public bool Execute(string sql, params object[] args) { StringBuilder sqlString = new StringBuilder(); // Fix for floating point problems on some languages sqlString.AppendFormat(CultureInfo.GetCultureInfo("en-US").NumberFormat, sql, args); MySqlCommand sqlCommand = new MySqlCommand(sqlString.ToString(), Connection); try { sqlCommand.ExecuteNonQuery(); return true; } catch (MySqlException ex) { Console.WriteLine(ex.Message); return false; } } public SQLResult Select(string sql, params object[] args) { SQLResult retData = new SQLResult(); StringBuilder sqlString = new StringBuilder(); // Fix for floating point problems on some languages sqlString.AppendFormat(CultureInfo.GetCultureInfo("en-US").NumberFormat, sql, args); MySqlCommand sqlCommand = new MySqlCommand(sqlString.ToString(), Connection); try { SqlData = sqlCommand.ExecuteReader(CommandBehavior.Default); retData.Load(SqlData); retData.Count = retData.Rows.Count; SqlData.Close(); } catch (MySqlException ex) { Console.WriteLine(ex.Message); } return retData; } public class SQLResult : DataTable { public int Count { get; set; } public T Read<T>(int row, string columnName) { return (T)Convert.ChangeType(Rows[row][columnName], typeof(T)); } } }
a7417e0e7a58344d31172dd2b8feb2294945f393
C#
dnknitro/photoname2date
/src/NameFix/NameFixProgram.cs
2.546875
3
using System; using System.Collections.Generic; using System.Windows.Forms; using NameFix.AppCode; using NameFix.Properties; namespace NameFix { internal static class NameFixProgram { public static FilesList FilesList; public static RenamerConfig RenamerConfig; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static void Main(string[] args) { RenamerConfig = new RenamerConfig(); FilesList = new FilesList(); var folder = Environment.CurrentDirectory; var argsDic = new Dictionary<string, string>(); var key = string.Empty; for(var i = 0; i < args.Length; i++) { var arg = args[i]; if(!string.IsNullOrEmpty(key)) { argsDic[key] = arg; key = string.Empty; } else if(arg[0] == '-') { key = arg.ToUpper(); argsDic[key] = null; } else { folder = arg; } } foreach(var pair in argsDic) { if(pair.Key == "-E") Settings.Default.Extensions = pair.Value; if(pair.Key == "-P") Settings.Default.RenamePattern = pair.Value; if(pair.Key == "-T") Settings.Default.Touch = string.IsNullOrEmpty(pair.Value) || bool.Parse(pair.Value); if(pair.Key == "-R") Settings.Default.RecurseSubdirs = string.IsNullOrEmpty(pair.Value) || bool.Parse(pair.Value); } FilesList.Message += LogMessage; if(argsDic.ContainsKey("-UI")) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } else if(argsDic.ContainsKey("-H")) { Console.WriteLine("NameFix.exe <Path To Folder> will rename all files in provided folder"); Console.WriteLine("-ui runs application in interactive mode"); Console.WriteLine("-e *.jpg;*.cr2;*.avi specifies list of files extensions which should be handled"); Console.WriteLine("-p \"yyyy-MM-dd HH-mm-ss\" specifies file rename pattern"); Console.WriteLine("-t true|false specifies if file modified date should be changed"); Console.WriteLine("-r true|false specifies if application should look up files in all subfolder of the provided folder"); } else { Console.WriteLine("NameFix.exe -h displays command line help"); FilesList.PreviewFinished += FilesListOnPreviewFinished; FilesList.DoPreview(null, folder); } } private static void FilesListOnPreviewFinished(object sender, string message) { FilesList.DoRename(null); } private static void LogMessage(object sender, string message) { Log.Append(message); } } }
ede6315cd5823a003a0097eea45fa149bc309048
C#
tsandtm/BOEdu
/SourceCode/project.web/Components/Range.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace project.web.Utils { public class Range { public static List<int> GetYears(int intRange) { List<int> ltIntOutput = new List<int>(); for (int i = 0; i < intRange; i++) ltIntOutput.Add(i); return ltIntOutput; } public static List<int> GetYears(int intLowerRange, int intUpperRange) { List<int> ltIntOutput = new List<int>(); for (int i = intLowerRange; i < intUpperRange; i++) ltIntOutput.Add(i); return ltIntOutput; } public static List<int> GetYears(int intLowerRange, int intUpperRange, int intStep) { List<int> ltIntOutput = new List<int>(); if (intLowerRange < intUpperRange && intStep > 0) { for (int i = intLowerRange; i < intUpperRange; i += intStep) ltIntOutput.Add(i); } else if (intLowerRange > intUpperRange && intStep < 0) { for (int i = intLowerRange; i > intUpperRange; i += intStep) ltIntOutput.Add(i); } return ltIntOutput; } public static List<NamHoc> GetDSNamHoc(int intLowerRange, int intUpperRange, int intStep) { List<NamHoc> listOutput = new List<NamHoc>(); if (intLowerRange < intUpperRange && intStep > 0) { for (int i = intLowerRange; i < intUpperRange; i += intStep) { NamHoc namHoc = new NamHoc() { Ten = GetNamHoc(i), Nam = i }; listOutput.Add(namHoc); } } else if (intLowerRange > intUpperRange && intStep < 0) { for (int i = intLowerRange; i > intUpperRange; i += intStep) { NamHoc namHoc = new NamHoc() { Ten = GetNamHoc(i), Nam = i }; listOutput.Add(namHoc); } } return listOutput; } public static string GetNamHoc(int selectYear) { return String.Format("{0}-{1}", selectYear, (selectYear + 1)); } } public struct NamHoc { public string Ten { get; set; } public int Nam { get; set; } } }
cd099f6d8f39ab34d797422acd1152cbf9bc580b
C#
Silmaverd/KALAMBURY-BETA
/KalamburySerwer/GameClient.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace KalamburySerwer { class GameClient { private Client clientInstance { set; get; } public void Connect(Socket clientSocket, int id) { this.clientInstance = new Client(clientSocket, id); } public string GetStatus() { return this.clientInstance.GetStatus(); } public void SetStatus(string status) { this.clientInstance.SetStatus(status); } public void UpdateScore() { this.clientInstance.SetScore(this.clientInstance.GetScore() + 100); } public string GetScore() { return Convert.ToString(this.clientInstance.GetScore()); } public void ClearScore() { this.clientInstance.SetScore(0); } public int GetRoomId() { return this.clientInstance.GetRoomId(); } public void SetRoomId(int roomId) { this.clientInstance.SetRoomId(roomId); } public void CloseConnection() { this.clientInstance.CloseConnection(); } public bool DataAvalible() { return this.clientInstance.Avalible(); } public string RecieveMessage() { return this.clientInstance.RecieveMessage(); } public void SendMessage(string message) { this.clientInstance.SendMessage(message); } public void SetUserName(string userName) { this.clientInstance.SetUserName(userName); } public string GetUserName() { return this.clientInstance.GetUsername(); } public int GetID() { return this.clientInstance.GetID(); } public GameClient() { } } }
cbeb716a367216a71a6e974137bf1ec50ed11cd0
C#
DylanSoler/ProyectoDAM
/UWP/FootballTrainingManager/FootballTrainingManagerUI/ViewModels/Converters/clsConverterRutaImagenFormTact.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Data; namespace FootballTrainingManagerUI.ViewModels.Converters { public class clsConverterRutaImagenFormTact : IValueConverter { //Dado un sistema (Ej. 4-2-3-1), se convierte al source de la imagen correspondiente de dicha tactica public object Convert(object value, Type targetType, object parameter, string language) { string sistema = (string)value; sistema = "ms-appx:///Assets/"+sistema+".png"; return sistema; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } }