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
|
|---|---|---|---|---|---|---|
633cc61dfa41f70413116a28b8647ccbd5c198be
|
C#
|
yokandro/number_game
|
/number_game/Program.cs
| 3.875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace number_game
{
class Game
{
static int guess = 0;
static int target = 5;
static string Input = "";
static Random RandomNumber = new Random();
public static void Play()
{
target = RandomNumber.Next(10);
Console.Write("The number that was made...");
Input = Console.ReadLine();
if(int.TryParse(Input, out guess))
{
if(guess == target)
{
Console.WriteLine("Congratulations! You guessed " + guess + ". the number that was made " + target + ".");
}
else
{
Console.WriteLine("You did not guess! " + guess + ". the number that was made " + target + ". Try again!");
}
}
else
{
Console.WriteLine("Enter the number!");
Console.WriteLine("Press Enter to continue!");
Console.ReadLine();
Play();
}
Console.Read();
}
}
class Program
{
static void Main()
{
Game.Play();
}
}
}
|
4f1dcffc3ae1cb1e94ab052d2c5cd8604834de4b
|
C#
|
PatrykOlejniczak/WPK.TransportSystem
|
/Data.DAL/Migrations/Seed/SeedQuestionnaire.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using Data.Core.Repository;
using Data.Core.UnitOfWork;
using Data.Entities;
namespace Data.Core.Migrations.Seed
{
public class SeedQuestionnaire : ISeedMethod
{
private readonly DataContext _dataContext;
private readonly IRepository<Employee> _employeeRepository;
private readonly List<Questionnaire> _questionnaires = new List<Questionnaire>()
{
new Questionnaire() { Id = 1, Question = "Sample Question 1", StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(1.0), IsDeleted = false },
new Questionnaire() { Id = 2, Question = "Sample Question 2", StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(1.0), IsDeleted = false },
new Questionnaire() { Id = 3, Question = "Sample Question 3", StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(1.0), IsDeleted = false }
};
public SeedQuestionnaire(DataContext dataContext, IRepository<Employee> employeeRepository)
{
_dataContext = dataContext;
_employeeRepository = employeeRepository;
}
public void FillTable()
{
_employeeRepository.EnrollUnitOfWork(_dataContext);
var employee = _employeeRepository.FindAll().First();
for (int i = 0; i < _questionnaires.Count; i++)
{
var questionnaires = _questionnaires[i];
questionnaires.Employee = employee;
_dataContext.Set<Questionnaire>().AddOrUpdate(questionnaires);
}
_dataContext.SaveChanges();
}
}
}
|
447723e50e5b4270ff89d1f6efbc0d123e229853
|
C#
|
Egor92/TrumpSoftware-Foundation
|
/TrumpSoftware.Shared/Converters/DoubleToGridLenghtConverter.cs
| 2.53125
| 3
|
using System;
#if WPF
using System.Windows;
using CultureArgumentType = System.Globalization.CultureInfo;
#elif WINRT
using Windows.UI.Xaml;
using CultureArgumentType = System.String;
#endif
#if WPF
namespace TrumpSoftware.Wpf.Converters
#elif WINRT
namespace TrumpSoftware.WinRT.Converters
#endif
{
public class DoubleToGridLenghtConverter : ChainConverter<double,GridLength>
{
protected override GridLength Convert(double value, Type targetType, object parameter, CultureArgumentType cultureArgument)
{
return new GridLength(value, GridUnitType.Pixel);
}
protected override double ConvertBack(GridLength value, Type targetType, object parameter, CultureArgumentType cultureArgument)
{
return value.Value;
}
}
}
|
7c7a4643018b4c6bc9adbe433f397cc72b9c014b
|
C#
|
benny1337/ocr
|
/businesscardapp/businesscardapp/Communicator/CardCommunicator.cs
| 2.890625
| 3
|
using models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace businesscardapp.Communicator
{
public class CardCommunicator
{
public async Task<BusinessCard> GetCardAsync(string Base64)
{
var client = new HttpClient();
var url = "http://ocrbusinesscard.azurewebsites.net/api/ocr";
var img = new Image()
{
Base64 = Base64
};
var json = JsonConvert.SerializeObject(img);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
if(!response.IsSuccessStatusCode)
{
throw new Exception("Error: " + response.ReasonPhrase);
}
var jsonResult = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<BusinessCard>(jsonResult);
}
}
}
|
c10dd63734513ecab2e16f51dabda227f59bfb24
|
C#
|
kupokev/ComServer
|
/src/OnyxCore/Server/Log.cs
| 3.296875
| 3
|
using System;
namespace OnyxCore.Server
{
public class Log : IDisposable
{
// Planning on changing all the Console.WriteLine commands to log in database eventually.
public Log()
{
}
/// <summary>
/// Dispose of current instance
/// </summary>
public void Dispose()
{
}
/// <summary>
/// Add a new log entry
/// </summary>
/// <param name="message"></param>
public void Add(string message)
{
Console.WriteLine(message);
}
/// <summary>
/// Logs multiple errors
/// </summary>
/// <param name="messages">Ex. new string[] { "param1", "param2" }</param>
public void Error(string[] messages)
{
Console.WriteLine("Error(s):");
foreach (var message in messages)
{
Console.WriteLine(message);
}
}
/// <summary>
/// Logs an error
/// </summary>
/// <param name="message"></param>
public void Error(string message)
{
Console.WriteLine("Error:");
Console.WriteLine(message);
}
/// <summary>
/// Creates a new line in the console window. (Specifically used for console logging)
/// </summary>
public void NewLine()
{
Console.WriteLine(Environment.NewLine);
}
}
}
|
e2cef9486c872625b32b9a5c9d08813fe113de2b
|
C#
|
HippoT/ProAspCore
|
/src/EssentialCSharpFeatures/Controllers/HomeController.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EssentialCSharpFeatures.Models;
using Microsoft.AspNetCore.Mvc;
namespace EssentialCSharpFeatures.Controllers
{
public class HomeController : Controller
{
bool FilterByPrice(Product p)
{
return (p?.Price ?? 0) >= 20;
}
public IActionResult Index()
{
//List<string> results = new List<string>();
//foreach (Product p in Product.GetProducts())
//{
// string name = p?.Name??"<No Name>";
// decimal? price = p?.Price ?? 0;
// string relatedName = p?.Related?.Name ?? "<No Name>";
// results.Add(string.Format($"Name: {name}, Price: {price:C2}, Related: {relatedName}, Instock: {p?.InStock}"));
//}
//return View(results);
Product[] products = { new Product { Name = "Tran", Price = 275M },
new Product { Name = "Minh", Price = 48.95M },
new Product { Name = "Tuan", Price = 16M },
new Product { Name = "Min", Price = 21M }
};
var list = new[]
{
new {Name = "Tran", Price = 123},
new {Name = "Minh", Price = 124},
new {Name = "Tuan", Price = 125}
};
Func<Product, bool> nameFilter = delegate (Product p)
{
return p?.Name?[0] == 'T';
};
decimal productsTotal = products.Filter(p => (p?.Price ?? 0) >= 20).TotalPrice();
decimal product = products.Filter(p => (p?.Name?[0] == 'T')).TotalPrice();
return View(new string[]
{
$"{nameof(productsTotal)}: {productsTotal:c2}",
$"{nameof(product)}: {product:c2}"
});
}
}
}
|
0e024fe3b9675846dffde7fe9f3a624de9bcae03
|
C#
|
happy-potato18/workers-registration-mvc-app
|
/WorkersRegistrationApp/WorkersRegistrationApp/WorkersRegistrationApp/Domain/SqlDataFlow.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace WorkersRegistrationApp.Domain
{
/// <summary>
/// The <c>SqlDataFlow</c> class.
/// Contains methods for passing requests and getting responses from database
/// </summary>
public static class SqlDataFlow
{
//string to create connection to database
private static readonly string _connectionString = Base.strConnect;
/// <summary>
/// Retrieves all workers' info from database
/// </summary>
/// <returns>
/// List of class <see cref="Domain.Worker"/>
/// </returns>
public static List<Worker> GetWorkerList()
{
SqlConnection connection = new SqlConnection(_connectionString);
//adds info about appropriate company to its worker to response
string sqlExpression = "SELECT * FROM companyworkersdb.dbo.worker LEFT JOIN companyworkersdb.dbo.company ON" +
" companyworkersdb.dbo.worker.company_id = companyworkersdb.dbo.company.id";
List<Worker> workers = new List<Worker>();
using (connection)
{
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Worker worker = new Worker()
{
Id = (int)reader.GetValue(0),
Name = (string)reader.GetValue(1),
MiddleName = (string)reader.GetValue(2),
Surname = (string)reader.GetValue(3),
Date = ((DateTime)reader.GetValue(4)).Date,
Job = (string)reader.GetValue(5),
CompanyId = (int)reader.GetValue(6)
};
Company company = new Company() // adds info about company to worker object
{
Id = (int)reader.GetValue(7),
Title = (string)reader.GetString(8),
LegalForm = (string)reader.GetString(9)
};
worker.Company = company;
workers.Add(worker);
}
}
reader.Close();
connection.Close();
}
return workers;
}
/// <summary>
/// Adds new <paramref name="worker"/> info to database.
/// </summary>
public static void AddWorker(Worker worker)
{
SqlConnection connection = new SqlConnection(_connectionString);
string sqlExpression = $"INSERT INTO companyworkersdb.dbo.worker " +
$"VALUES ('{worker.Name}','{worker.Surname}','{worker.MiddleName}','{DateToSqlFriendlyDate(worker.Date)}'," +
$"'{worker.Job}',{worker.CompanyId})";
using (connection)
{
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
command.ExecuteNonQuery();
connection.Close();
}
}
/// <summary>
/// Retrieves worker with specified <paramref name="id"/> from database
/// </summary>
/// <returns>
/// <see cref="Domain.Worker"/> object with info from database
/// </returns>
public static Worker FindWorkerById(int? id)
{
SqlConnection connection = new SqlConnection(_connectionString);
string sqlExpression = $"SELECT * FROM companyworkersdb.dbo.worker WHERE id ={id}";
Worker worker = default;
using (connection)
{
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
worker = new Worker()
{
Id = (int)reader.GetValue(0),
Name = (string)reader.GetValue(1),
MiddleName = (string)reader.GetValue(2),
Surname = (string)reader.GetValue(3),
Date = ((DateTime)reader.GetValue(4)).Date,
Job = (string)reader.GetValue(5),
CompanyId = (int)reader.GetValue(6)
};
}
}
reader.Close();
connection.Close();
}
return worker;
}
/// <summary>
/// Delete info about <paramref name="worker"/> from database
/// </summary>
public static void DeleteWorker(Worker worker)
{
SqlConnection connection = new SqlConnection(_connectionString);
string sqlExpression = $"DELETE FROM companyworkersdb.dbo.worker WHERE id ={worker.Id}";
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
command.ExecuteNonQuery();
connection.Close();
}
/// <summary>
/// Update info about <paramref name="worker"/> in database
/// </summary>
public static void UpdateWorker(Worker worker)
{
SqlConnection connection = new SqlConnection(_connectionString);
string sqlExpression = $"UPDATE companyworkersdb.dbo.worker SET" +
$" name = '{worker.Name}', surname ='{worker.Surname}', middle_name = '{worker.MiddleName}'," +
$"employment_date = '{DateToSqlFriendlyDate(worker.Date)}'," +
$"job = '{worker.Job}'," +
$"company_id ={worker.CompanyId} WHERE id = {worker.Id}";
using (connection)
{
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
command.ExecuteNonQuery();
connection.Close();
}
}
/// <summary>
/// Retrieves all companies info from database
/// </summary>
/// <returns>
/// List of class <see cref="Domain.Company"/>
/// </returns>
public static List<Company> GetCompanyList()
{
SqlConnection connection = new SqlConnection(_connectionString);
string sqlExpression = "SELECT * FROM companyworkersdb.dbo.company";
List<Company> companies = new List<Company>();
using (connection)
{
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Company company = new Company()
{
Id = (int)reader.GetValue(0),
Title = (string)reader.GetString(1),
LegalForm = (string)reader.GetString(2)
};
company.CountOfWorkers = CountWorkers(company.Id);
companies.Add(company);
}
}
reader.Close();
connection.Close();
}
return companies;
}
/// <summary>
/// Adds new <paramref name="company"/> info to database.
/// </summary>
public static void AddCompany(Company company)
{
SqlConnection connection = new SqlConnection(_connectionString);
string sqlExpression = $"INSERT INTO companyworkersdb.dbo.company " +
$"VALUES ('{company.Title}','{company.LegalForm}')";
using (connection)
{
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
command.ExecuteNonQuery();
connection.Close();
}
}
/// <summary>
/// Retrieves company with specified <paramref name="id"/> from database
/// </summary>
/// <returns>
/// <see cref="Domain.Company"/> object with info from database
/// </returns>
public static Company FindCompanyById(int? id)
{
SqlConnection connection = new SqlConnection(_connectionString);
string sqlExpression = $"SELECT * FROM companyworkersdb.dbo.company WHERE id ={id}";
Company company = default;
using (connection)
{
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
company = new Company()
{
Id = (int)reader.GetValue(0),
Title = (string)reader.GetValue(1),
LegalForm = (string)reader.GetValue(2)
};
}
}
reader.Close();
connection.Close();
}
return company;
}
/// <summary>
/// Delete info about <paramref name="company"/> from database
/// </summary>
public static void DeleteCompany(Company company)
{
SqlConnection connection = new SqlConnection(_connectionString);
string sqlExpression = $"DELETE FROM companyworkersdb.dbo.company WHERE id ={company.Id}";
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
command.ExecuteNonQuery();
connection.Close();
}
/// <summary>
/// Update info about <paramref name="company"/> in database
/// </summary>
public static void UpdateCompany(Company company)
{
SqlConnection connection = new SqlConnection(_connectionString);
string sqlExpression = $"UPDATE companyworkersdb.dbo.company SET" +
$" title = '{company.Title}', legal_form ='{company.LegalForm}'WHERE id = {company.Id}";
using (connection)
{
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
command.ExecuteNonQuery();
connection.Close();
}
}
/// <summary>
/// Changes format of <paramref name="date"/>
/// Used when adding date value to database
/// <see cref="AddWorker(Worker)"/>
/// <see cref="AddCompany(Company)"/>
/// </summary>
private static string DateToSqlFriendlyDate(DateTime date)
{
return date.Year.ToString() +"-"+ date.Month.ToString() +"-"+ date.Day.ToString();
}
/// <summary>
/// Counts workers in company with specified <paramref name="id"/>
/// Used when retrieving info about companies <see cref="GetCompanyList"/>
/// </summary>
private static int CountWorkers(int id)
{
SqlConnection connection = new SqlConnection(_connectionString);
string sqlExpression = $"SELECT COUNT(*) FROM companyworkersdb.dbo.worker WHERE company_id = {id}";
int count = 0;
using (connection)
{
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows) // если есть данные
{
if (reader.Read()) // построчно считываем данные
{
count = reader.GetInt32(0);
}
}
reader.Close();
connection.Close();
}
return count;
}
}
}
|
d528510134de7af48e8244ad9fe8011d466d9a9b
|
C#
|
gordiig/Hexa-C
|
/MiniC/Generators/Expressions/BinaryOperators/InclusiveOrGenerator.cs
| 2.53125
| 3
|
using Antlr4.Runtime;
namespace MiniC.Generators.Expressions.BinaryOperators
{
public class InclusiveOrGenerator: BaseCodeGenerator
{
public override AsmCodeWriter GenerateCodeForContext(ParserRuleContext context, AsmCodeWriter currentCode)
{
var inclusiveOrExprCtx = context as MiniCParser.InclusiveOrExpressionContext;
var exclisiveOrExpression = inclusiveOrExprCtx.exclusiveOrExpression();
var inclusiveOrExpression = inclusiveOrExprCtx.inclusiveOrExpression();
var exclusiveOrGenerator = new ExclusiveOrGenerator();
// With inclusive or expr
if (inclusiveOrExpression != null)
{
// Вычисление rvalue
currentCode = exclusiveOrGenerator.GenerateCodeForContext(exclisiveOrExpression, currentCode);
var rValueRegister = getValueFromExpression(currentCode);
// Привод типов если нужно
convertTypeIfNeeded(currentCode, rValueRegister, exclisiveOrExpression);
// Вычисление lvalue
var inclusiveOrGen = new InclusiveOrGenerator();
currentCode = inclusiveOrGen.GenerateCodeForContext(inclusiveOrExpression, currentCode);
var lValueRegister = getValueFromExpression(currentCode);
// Привод типов если нужно
convertTypeIfNeeded(currentCode, lValueRegister, inclusiveOrExpression);
// Вычисление результата
currentCode.AddComment("Doing | operator");
var resultRegister = currentCode.GetFreeRegister();
currentCode.AddRegisterOrRegister(resultRegister, lValueRegister, rValueRegister);
// Чистка регистров
currentCode.FreeRegister(rValueRegister);
currentCode.FreeRegister(lValueRegister);
}
// Exclusive or only
else
currentCode = exclusiveOrGenerator.GenerateCodeForContext(exclisiveOrExpression, currentCode);
return currentCode;
}
}
}
|
7de4872c7ec60b71917fa90dc1c62135cfef2a33
|
C#
|
lisiara/Practice-2019
|
/BikersBlog/RealBlog/Models/DBModel/User.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace RealBlog.Models
{
public class User
{
[Key]
public int Id { get; set; }
[Display(Name = "Псевдоним")]
[Required(ErrorMessage = "Псевдоним не задан")]
[MaxLength(20, ErrorMessage = "Псевдоним до 20 символов")]
[MinLength(3, ErrorMessage = "Псевдоним от 3 символов")]
[RegularExpression(@"^(?=.*[A-Za-z])[A-Za-z\d_]{3,20}", ErrorMessage = "Псевдоним некорректен")]
[Description("От 3 до 20 символов") ]
public string Nickname { get; set; }
[Display(Name = "Пароль")]
[Required(ErrorMessage = "Пароль не задан")]
[MaxLength(20, ErrorMessage = "Пароль до 20 символов")]
[MinLength(6, ErrorMessage = "Пароль от 6 символов")]
[RegularExpression(@"^(?=.*[A-Za-z])[A-Za-z\d_]{6,20}", ErrorMessage = "Пароль некорректен")]
[Description("От 6 до 20 символов")]
public string Password { get; set; }
[NotMapped]
[Display(Name = "Подтверждение пароля")]
[MaxLength(20, ErrorMessage = "Пароль до 20 символов")]
[MinLength(6, ErrorMessage = "Пароль от 6 символов")]
public string PasswordConfirm { get; set; }
[EmailAddress]
[Display(Name = "Почта")]
[Required(ErrorMessage = "Почта не задана")]
[MaxLength(31, ErrorMessage = "Почта до 31 символов")]
public string Email { get; set; }
public string Photourl { get; set; }
[Display(Name = "Имя")]
[MaxLength(31, ErrorMessage = "Имя до 31 символов")]
public string FirstName { get; set; }
[Display(Name = "Фамилия")]
[MaxLength(31, ErrorMessage = "Фамилия до 31 символов")]
public string LastName { get; set; }
[Display(Name = "Контакты")]
[MaxLength(255, ErrorMessage = "Контактная информация До 255 символов")]
public string ContactInfo { get; set; }
[Display(Name = "ТТх мотоцикла")]
[MaxLength(255, ErrorMessage = "ТТХ До 255 символов")]
public string BikeSpecifications { get; set; }
[Display(Name = "Увлечения")]
[MaxLength(255, ErrorMessage = "Хобби До 255 символов")]
public string Hobbies { get; set; }
}
}
|
3bb9b97f43f15dd137ebca550c4e69dd303d5ff0
|
C#
|
yuchaoonline/Cartisan
|
/Cartisan/Infrastructure/AssertionConcern.cs
| 3.15625
| 3
|
using System;
namespace Cartisan.Infrastructure {
public static class AssertionConcern {
public static void Equals(object object1, object object2, string message) {
if (!object1.Equals(object2)) {
throw new InvalidOperationException(message);
}
}
public static void NotEquals(object object1, object object2, string message) {
if (object1.Equals(object2)) {
throw new InvalidOperationException(message);
}
}
public static void Length(string stringValue, int maximum, string message) {
int length = stringValue.Trim().Length;
if (length > maximum) {
throw new InvalidOperationException(message);
}
}
public static void Length(string stringValue, int minimum, int maximum, string message) {
int length = stringValue.Trim().Length;
if (length < minimum || length > maximum) {
throw new InvalidOperationException(message);
}
}
public static void Matches(string pattern, string stringValue, string message) {
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);
if (!regex.IsMatch(stringValue)) {
throw new InvalidOperationException(message);
}
}
public static void NotEmpty(string stringValue, string message) {
if (stringValue == null || stringValue.Trim().Length == 0) {
throw new InvalidOperationException(message);
}
}
public static void NotNull(object object1, string message) {
if (object1 == null) {
throw new InvalidOperationException(message);
}
}
public static void Range(double value, double minimum, double maximum, string message) {
if (value < minimum || value > maximum) {
throw new InvalidOperationException(message);
}
}
public static void Range(float value, float minimum, float maximum, string message) {
if (value < minimum || value > maximum) {
throw new InvalidOperationException(message);
}
}
public static void Range(int value, int minimum, int maximum, string message) {
if (value < minimum || value > maximum) {
throw new InvalidOperationException(message);
}
}
public static void Range(long value, long minimum, long maximum, string message) {
if (value < minimum || value > maximum) {
throw new InvalidOperationException(message);
}
}
public static void True(bool boolValue, string message) {
if (!boolValue) {
throw new InvalidOperationException(message);
}
}
public static void False(bool boolValue, string message) {
if (boolValue) {
throw new InvalidOperationException(message);
}
}
}
}
|
51eb56d9b82ceab04bad69c1e3d94ce4cf9c360e
|
C#
|
jjeffery/SecurePay
|
/src/SecurePay.Tests/YearMonthTests.cs
| 2.890625
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SecurePay.Model;
namespace SecurePay.Tests
{
[TestClass]
public class YearMonthTests
{
[TestMethod]
public void Parse()
{
var testData = new[]
{
new {Text = "1/1", Month = 1, Year = 2001},
new {Text = "12/2019", Month = 12, Year = 2019},
new {Text = "\t\t11 /\t 2091 ", Month = 11, Year = 2091},
new {Text = "13/2091 ", Month = 0, Year = 0},
new {Text = "12/0000 ", Month = 0, Year = 0},
new {Text = null as string, Month = 0, Year = 0},
new {Text = " ", Month = 0, Year = 0},
new {Text = string.Empty, Month = 0, Year = 0},
new {Text = "not-valid", Month = 0, Year = 0}
};
foreach (var td in testData)
{
var yearMonth = new YearMonth(td.Text);
Assert.AreEqual(td.Year, yearMonth.Year);
Assert.AreEqual(td.Month, yearMonth.Month);
if (yearMonth.Month == 0)
{
Assert.AreEqual(0, yearMonth.Year);
Assert.AreEqual(false, yearMonth.HasValue);
}
else
{
Assert.AreEqual(true, yearMonth.HasValue);
}
}
}
[TestMethod]
public void ToStringTest()
{
var testData = new[] {
new { Month = 1, Year = 1, Text = "01/2001"},
new { Month = 12, Year = 2098, Text = "12/2098"},
new { Month = 0, Year = 0, Text = string.Empty},
};
foreach (var td in testData)
{
var yearMonth = new YearMonth(td.Year, td.Month);
Assert.AreEqual(td.Text, yearMonth.ToString());
}
}
[TestMethod]
public void Equality()
{
var equalTestData = new[] {
"01/2001",
"12/2072",
};
foreach (var date in equalTestData)
{
var ym1 = new YearMonth(date);
var ym2 = new YearMonth(date);
Assert.IsTrue(ym1.Equals(ym2));
Assert.IsTrue(ym2.Equals(ym1));
Assert.IsTrue(ym1 == ym2);
Assert.IsTrue(ym2 == ym1);
Assert.IsFalse(ym1 != ym2);
Assert.IsFalse(ym2 != ym1);
Assert.IsTrue(ym1 <= ym2);
Assert.IsTrue(ym2 <= ym1);
Assert.IsTrue(ym1 >= ym2);
Assert.IsTrue(ym2 >= ym1);
}
}
[TestMethod]
public void Inequality()
{
var equalTestData = new[] {
new { Date1 = "01/2091", Date2 = "02/2092" },
new { Date1 = "01/2081", Date2 = "01/2082" },
new { Date1 = "01/2071", Date2 = "11/2071" },
};
foreach (var testData in equalTestData) {
var ym1 = new YearMonth(testData.Date1);
var ym2 = new YearMonth(testData.Date2);
Assert.IsFalse(ym1.Equals(ym2));
Assert.IsFalse(ym2.Equals(ym1));
Assert.IsFalse(ym1 == ym2);
Assert.IsFalse(ym2 == ym1);
Assert.IsTrue(ym1 != ym2);
Assert.IsTrue(ym2 != ym1);
}
}
[TestMethod]
public void LessThan()
{
var equalTestData = new[] {
new { Date1 = "01/2091", Date2 = "02/2092" },
new { Date1 = "12/2081", Date2 = "01/2082" },
new { Date1 = "01/2071", Date2 = "11/2071" },
};
foreach (var testData in equalTestData) {
var ym1 = new YearMonth(testData.Date1);
var ym2 = new YearMonth(testData.Date2);
Assert.IsTrue(ym1 < ym2);
Assert.IsFalse(ym2 < ym1);
Assert.IsTrue(ym1 <= ym2);
Assert.IsFalse(ym2 <= ym1);
}
}
[TestMethod]
public void GreaterThan()
{
var equalTestData = new[] {
new { Date1 = "02/2092", Date2 = "01/2092" },
new { Date1 = "01/2082", Date2 = "12/2081" },
new { Date1 = "9/2071", Date2 = "8/2071" },
};
foreach (var testData in equalTestData) {
var ym1 = new YearMonth(testData.Date1);
var ym2 = new YearMonth(testData.Date2);
Assert.IsTrue(ym1 > ym2);
Assert.IsFalse(ym2 > ym1);
Assert.IsTrue(ym1 >= ym2);
Assert.IsFalse(ym2 >= ym1);
}
}
}
}
|
3a2d0f470ab11ae92ce6e5d351b829a071a518a9
|
C#
|
lulzzz/Iris
|
/DashboardBackend/Data/UpdatesRepository.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Common;
using DashboardBackend.Models;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
namespace DashboardBackend.Data
{
public class UpdatesRepository : IUpdatesRepository
{
private readonly IMongoCollection<UpdateEntity> _collection;
public UpdatesRepository(ApplicationDbContext context)
{
_collection = context.Updates;
}
public Task<int> CountAsync()
{
return _collection.AsQueryable().CountAsync();
}
public Task<List<UpdateEntity>> Get(PageSearchParams searchParams)
{
IMongoQueryable<UpdateEntity> updates = _collection.AsQueryable()
.Skip(searchParams.PageSize * searchParams.PageIndex)
.Take(searchParams.PageSize);
return updates.ToListAsync();
}
public async Task AddAsync(UpdateEntity update)
{
await _collection.InsertOneAsync(update);
}
public async Task DeleteAsync(Guid id)
{
UpdateEntity update = await _collection.FindOneAndDeleteAsync(u => u.Id == id);
if (update.Id == id)
{
return;
}
throw new InvalidOperationException();
}
}
}
|
c3235c5b1381c1be940b82a4361dff72048a3ab4
|
C#
|
tasadar2/RpgMakerEncoder
|
/RpgMakerEncoder/Conversion/JTokenConverter.cs
| 2.984375
| 3
|
using System.Linq;
using Newtonsoft.Json.Linq;
using RpgMakerEncoder.Ruby;
namespace RpgMakerEncoder.Conversion
{
public class JTokenConverter : IConvert<RubyToken, JToken>
{
public JToken Convert(RubyToken ruby)
{
switch (ruby.Type)
{
case RubyTokenType.Array:
var arrayToken = new JArray();
foreach (var item in ruby)
{
arrayToken.Add(Convert(item));
}
return arrayToken;
case RubyTokenType.Object:
var rubyObject = (RubyObject)ruby;
var objectToken = new JObject(new JProperty("typeName", new JValue(rubyObject.RubyClass.Name)));
foreach (var property in rubyObject.Properties.OrderBy(prop => prop.Key))
{
objectToken[property.Key] = Convert(property.Value);
}
return objectToken;
case RubyTokenType.Null:
return new JValue((object)null);
case RubyTokenType.Boolean:
return new JValue(ruby.GetValue<bool>());
case RubyTokenType.String:
return new JValue(ruby.GetValue<string>());
default:
return new JValue(((RubyValue)ruby).Value);
}
}
}
}
|
dc67f158ed26ccd047adf8f586da0f529bbf8c38
|
C#
|
Tarak-Chandra-Sarkar/DesignPatternsCode
|
/PasswordChecker/PasswordChecker/Rules/PasswordCannotContainUsername.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace PasswordChecker.Rules
{
public class PasswordCannotContainUsername : IPasswordRule
{
public bool BreakOnFailure { get { return false; } }
public RuleResult CheckPassword(string username, string password)
{
String usernameRegex = String.Format("({0})+", username);
if (Regex.IsMatch(password, usernameRegex, RegexOptions.IgnoreCase))
{
return RuleResult.CreateFailResult($"Your username of {username} may not be used as part of the password");
}
return RuleResult.CreatePassResult();
}
}
}
|
64b4c375715eeccd96ed639e6f9441625bf7d911
|
C#
|
jassbhatia0786/video_rental
|
/video_rental/video_rental.cs
| 2.578125
| 3
|
using System;
using System.Data;
using System.Windows.Forms;
namespace video_rental
{
public partial class video_rental : Form
{
database_operation f = new database_operation();
public video_rental()
{
InitializeComponent();
}
private void addmoview_button_Click(object sender, EventArgs e)
{
f.Add_movi(rating_text.Text, title_text.Text, year_text.Text, copies_text.Text, plot_text.Text, genre_text.Text);
MessageBox.Show("Movie Added");
DataTable h = f.MoviData();
movie_Grid.DataSource = h;
}
private void delete_button_Click(object sender, EventArgs e)
{
bool result = f.Delete_movi(Convert.ToInt16(moveid_text.Text));
if (result == true)
{
MessageBox.Show("Movie deleted");
}
else
{
MessageBox.Show("Movie rented by customer so not deleted");
}
DataTable h = f.MoviData();
movie_Grid.DataSource = h;
}
private void update_button_Click(object sender, EventArgs e)
{
f.Update_movi(Convert.ToInt16(moveid_text.Text), rating_text.Text, title_text.Text, year_text.Text, copies_text.Text, plot_text.Text, genre_text.Text);
MessageBox.Show("Movie updated");
DataTable h = f.MoviData();
movie_Grid.DataSource = h;
}
private void issue_button_Click(object sender, EventArgs e)
{
f.Issue_Movi(Convert.ToInt16(movieid_text.Text), Convert.ToInt16(Custid_text.Text), Convert.ToDateTime(rentdate_text.Text), 1);
MessageBox.Show("Movie issues");
DataTable g = f.RentData();
rentalGrid.DataSource = g;
}
private void return_button_Click(object sender, EventArgs e)
{
f.Return_Movi(Convert.ToInt16(RMID_text.Text), Convert.ToInt16(movieid_text.Text), Convert.ToDateTime(rentdate_text.Text), Convert.ToDateTime(returndate_text.Text), 1);
MessageBox.Show("Book Returned");
DataTable g = f.RentData();
rentalGrid.DataSource = g;
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable g = f.RentData();
rentalGrid.DataSource = g;
DataTable h = f.MoviData();
movie_Grid.DataSource = h;
DataTable h1 = f.CustData();
customer_Grid.DataSource = h1;
}
private void rentedout__CheckedChanged(object sender, EventArgs e)
{
DataTable g = f.RentoutData();
rentalGrid.DataSource = g;
}
private void allrent_radio_CheckedChanged(object sender, EventArgs e)
{
DataTable g = f.RentData();
rentalGrid.DataSource = g;
}
private void movie_Grid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.RowIndex >= 0)//check the rowindex
{
DataGridViewRow row = this.movie_Grid.Rows[e.RowIndex];//pick the row index
moveid_text.Text = row.Cells[0].Value.ToString();//will get the vale for moveid
rating_text.Text = row.Cells[1].Value.ToString();//will get the vale for rating
title_text.Text = row.Cells[2].Value.ToString();//will get the vale for title
year_text.Text = row.Cells[3].Value.ToString();//will get the vale for year
rentalcost_text.Text = row.Cells[4].Value.ToString();//will get the vale for rental cost
copies_text.Text = row.Cells[5].Value.ToString();//will get the vale for copies
plot_text.Text = row.Cells[6].Value.ToString();//will get the vale for plot
genre_text.Text = row.Cells[7].Value.ToString();//will get the vale for genre
}
}
catch (Exception e1)
{
}
}
private void rentalGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.rentalGrid.Rows[e.RowIndex];
RMID_text.Text = row.Cells[0].Value.ToString();
movieid_text.Text = row.Cells[1].Value.ToString();//setting the movie text
Custid_text.Text = row.Cells[2].Value.ToString();//setting the customerid
rentdate_text.Text = row.Cells[3].Value.ToString();//setting the rent date
returndate_text.Text = row.Cells[4].Value.ToString();//setting return date
}
}
private void customer_Grid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.customer_Grid.Rows[e.RowIndex];//setting the index
textBox1.Text = row.Cells[0].Value.ToString();//setting custid
fname_text.Text = row.Cells[1].Value.ToString();//setting fname
lname_text.Text = row.Cells[2].Value.ToString();//setting lname
address_text.Text = row.Cells[3].Value.ToString();//setting address
phone_text.Text = row.Cells[4].Value.ToString();//setting phone
}
}
private void addcustomer_button_Click(object sender, EventArgs e)
{
f.Add_cust(fname_text.Text, lname_text.Text, address_text.Text, phone_text.Text);
MessageBox.Show("Customer Added");
DataTable h1 = f.CustData();
customer_Grid.DataSource = h1;
}
private void button2_Click(object sender, EventArgs e)
{
f.Update_cust(Convert.ToInt16(textBox1.Text), fname_text.Text, lname_text.Text, address_text.Text, Convert.ToInt32(phone_text.Text));
MessageBox.Show("Customer Updated");
DataTable h1 = f.CustData();
customer_Grid.DataSource = h1;
}
private void Top_buy_Click_1(object sender, EventArgs e)
{
String str = f.Top_Movie();
MessageBox.Show(str);
}
private void Best_buy_Click(object sender, EventArgs e)
{
String str = f.Best_Buyer();
MessageBox.Show(str);
}
private void DeleteCust_Click(object sender, EventArgs e)
{
bool result = f.Delete_cust(Convert.ToInt16(textBox1.Text));
if (result == true)
{
MessageBox.Show("Customer deleted");
}
else
{
MessageBox.Show("Customer rented a movie so not deleted");
}
DataTable h1 = f.CustData();
customer_Grid.DataSource = h1;
}
}
}
|
d5b6680968ad37e951adc78f2df44866e08995d1
|
C#
|
GSIL-Monitor/hotel
|
/Mzl.Model/Proxy/CTripHotel/RoomDesInfo/LengthOfStay.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mzl.EntityModel.Proxy.CTripHotel.RoomDesInfo
{
public class LengthOfStay
{
/// <summary>
/// 连续入住时长促销:
/// Max-最大连住时长;
/// Min-最小连住时长;
/// </summary>
public string MinMaxType { get; set; }
/// <summary>
/// 连续入住的时长数值
/// </summary>
public int Time { get; set; }
/// <summary>
/// 时长数值的单位:
/// Year-年;
/// Month-月;
/// Week-周;
/// Day-天(默认);
/// Hour-小时;
/// Minute-分钟;
/// Second-秒数;
/// </summary>
public string TimeUnit { get; set; }
/// <summary>
/// 实际入住时长为预设入住时长的倍数时,是否也可享受该促销优惠:True-是;False-否 (默认)。
/// </summary>
public bool MustBeMultiple { get; set; }
}
}
|
aab636e378bb4b430e125132d7bb7ed48af7b48a
|
C#
|
rcarubbi/Carubbi.AuthenticationManager
|
/Carubbi.AuthenticationManager/FormBasedAuthenticationManager.cs
| 2.75
| 3
|
using System;
using System.Text;
using System.Web;
using System.Web.Security;
namespace Carubbi.AuthenticationManager
{
/// <inheritdoc />
/// <summary>
/// Gerenciador de Autenticação baseado na abordagem do Asp.net Form based Authentication
/// </summary>
public class FormBasedAuthenticationManager : IAuthenticationManager
{
/// <inheritdoc />
/// <summary>
/// Monta um formulário HTML padrão de autenticação e inclui o mesmo no Response da requisição
/// </summary>
public void ExibirTelaLogin()
{
var stbHtml = new StringBuilder();
stbHtml.AppendLine("<div class=\"login-body\">");
stbHtml.AppendLine("<div class=\"login-field\"><label for=\"username\">Usuário</label>");
stbHtml.AppendLine("<input type=\"text\" id=\"username\"/></div>");
stbHtml.AppendLine("<div class=\"login-field\"><label for=\"password\">Senha</label>");
stbHtml.AppendLine("<input type=\"password\" id=\"password\" /></div>");
stbHtml.AppendLine("</div>");
stbHtml.AppendLine("<div class=\"footer\">");
stbHtml.AppendLine("<input type=\"checkbox\" id=\"rememberMe\" /><label for=\"rememberMe\">Lembrar-me</label>");
stbHtml.AppendLine("<div>");
stbHtml.AppendLine("<button type=\"submit\" id=\"btn-login\" class=\"btn btn-success\" style=\"vertical-align: middle;\">Login</button>");
stbHtml.AppendLine("</div>");
stbHtml.AppendLine("</div>");
stbHtml.AppendLine("<div id=\"error-message\"></div>");
HttpContext.Current.Response.Write(stbHtml.ToString());
}
/// <inheritdoc />
/// <summary>
/// Indica se o contexto HTTP está autenticado
/// </summary>
/// <param name="context">Contexto HTTP</param>
/// <returns></returns>
public bool IsAuthenticated(HttpContext context)
{
return context.User.Identity.IsAuthenticated;
}
/// <inheritdoc />
/// <summary>
/// Recupera dados customizados do usuário autenticado no contexto HTTP informado
/// </summary>
/// <param name="context">contexto HTTP</param>
/// <returns>dados customizados do usuário</returns>
public string GetUserData(HttpContext context)
{
if (!context.User.Identity.IsAuthenticated) return string.Empty;
var id = (FormsIdentity)context.User.Identity;
var ticket = id.Ticket;
return ticket.UserData;
}
/// <inheritdoc />
/// <summary>
/// Recupera o nome do usuário autenticado no contexto HTTP informado
/// </summary>
/// <param name="context">contexto HTTP</param>
/// <returns>Nome do usuário</returns>
public string GetUserName(HttpContext context)
{
if (!context.User.Identity.IsAuthenticated) return string.Empty;
var id = (FormsIdentity)context.User.Identity;
var ticket = id.Ticket;
return ticket.Name;
}
/// <inheritdoc />
/// <summary>
/// Executa o processo de autenticação baseando-se na regra de autenticação informada como parâmetro
/// </summary>
/// <param name="context">Contexto HTTP</param>
/// <param name="username">Login do usuário</param>
/// <param name="rememberMe">indica se deve ser armazenado um cookie permanente na máquina do cliente</param>
/// <param name="userData">dados customizados do usuário</param>
/// <param name="authenticationHandler">Método que contem a regra de autenticação</param>
/// <returns></returns>
public AuthenticationResult Logon(HttpContext context, string username, bool rememberMe, string userData, Func<bool> authenticationHandler)
{
var result = new AuthenticationResult();
if (authenticationHandler())
{
var tkt = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), rememberMe, userData);
var cookiestr = FormsAuthentication.Encrypt(tkt);
var ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (rememberMe)
{
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
}
context.Response.Cookies.Add(ck);
var strRedirect = context.Request["ReturnUrl"];
if (strRedirect != null)
{
result.ReturnUrl = strRedirect;
}
result.Success = true;
}
else
{
result.Success = false;
}
return result;
}
/// <inheritdoc />
/// <summary>
/// Efetua o logoff do usuário no contexto HTTP informado
/// </summary>
/// <param name="context">Contexto HTTP</param>
public void Logoff(HttpContext context)
{
FormsAuthentication.SignOut();
}
/// <inheritdoc />
/// <summary>
/// Redireciona o contexto HTTP corrente para a url informada no AuthenticationResult caso haja uma
/// </summary>
/// <param name="result"></param>
public void RedirecionarUrl(AuthenticationResult result)
{
if (!string.IsNullOrEmpty(result.ReturnUrl))
{
HttpContext.Current.Response.Redirect(result.ReturnUrl);
}
}
}
}
|
e8d0d2d273190a62a93c6c56a8e4c6e410689184
|
C#
|
tavisca-ragul/Data-Structure
|
/DataStructure/LinkedListOperations.cs
| 3.875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructure
{
class LinkedListOperations
{
private LinkedList _List;
private int _Data, _Position;
public LinkedListOperations()
{
_List = new LinkedList();
_Data = 0;
_Position = 0;
}
public void InvokeMethods()
{
int choice = 0;
Console.WriteLine("\t\tLinkedList Operations\n1.Add\n2.Remove\n3.Display\n4.Sort\n5.Insert at the Specific Location\n6.Remove from the specific Location\n7.Exit\nEnter your Choice : ");
choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("Enter Data : ");
_Data = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(_List.Add(_Data));
InvokeMethods();
break;
case 2:
Console.WriteLine(_List.Remove());
InvokeMethods();
break;
case 3:
Console.WriteLine(_List.Display());
InvokeMethods();
break;
case 4:
Console.WriteLine(_List.Sort());
InvokeMethods();
break;
case 5:
Console.WriteLine("Enter Data : ");
_Data = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Position (index starts from 0): ");
_Position = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(_List.AddAtPosition(_Data, _Position));
InvokeMethods();
break;
case 6:
Console.WriteLine("Enter Position (index starts from 0) : ");
_Position = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(_List.RemoveFromPosition(_Position));
InvokeMethods();
break;
case 7:
Environment.Exit(0);
break;
default:
Console.WriteLine("Wrong choice, try again");
break;
}
}
}
}
|
5a15e38dcab325839a244b7857643f7c114b13fe
|
C#
|
Eden-AQI/Eden-AQI
|
/Server/Eden.Web.Framework/WebTools.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Eden.Web.Framework
{
public class WebTools
{
public static void CopyProperties(object from, object to, bool excludeNull = true)
{
var fromPs = from.GetType().GetProperties();
var toPs = to.GetType().GetProperties();
foreach (var p in toPs)
{
var fromP = fromPs.Where(fp => fp.Name == p.Name).FirstOrDefault();
if (null == fromP)
continue;
object val = fromP.GetValue(from);
if (excludeNull && null == val)
continue;
p.SetValue(to, val);
}
}
}
}
|
2a95b7cd1d9674ec37d4089e64519087acd1cb3d
|
C#
|
merklol/C-sharp-Basics
|
/main/apps/Loops.cs
| 3.984375
| 4
|
using System;
//6. Write a program, the running result of following program is as follows(using looping)
// 5
// 666
// 77777
// 8888888
public class Loops : Application
{
private string line1 = "";
private string line2 = "";
private string line3 = "";
private string line4 = "";
public Loops(string title) : base(title) { }
public override void main()
{
for (int i = 0; i < 10; i++)
{
if (i != 5) line1 += " "; else line1 += "5";
if (i == 4)
for (int j = 0; j < 3; j++) line2 += "6";
else
line2 += " ";
if (i == 3)
for (int k = 0; k < 5; k++) line3 += "7";
else
line3 += " ";
if (i == 2)
for (int k = 0; k < 7; k++) line4 += "8";
else
line4 += " ";
}
Console.WriteLine(line1);
Console.WriteLine(line2);
Console.WriteLine(line3);
Console.WriteLine(line4);
}
}
|
58ebc8e85cf3356c89346da667467e801e9391a4
|
C#
|
wlniao/xcore
|
/Wlniao.XCore/Extend/Type/StringExtend.cs
| 3.21875
| 3
|
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace Wlniao
{
/// <summary>
/// String类常用方法扩展
/// </summary>
public static class StringExtend
{
/// <summary>
/// 是否为空
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsNullOrEmpty(this string input)
{
return string.IsNullOrEmpty(input);
}
/// <summary>
/// 是否不为空
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsNotNullAndEmpty(this string input)
{
return !string.IsNullOrEmpty(input);
}
/// <summary>
/// 是否为手机号
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsMobile(this string input)
{
return input != null && strUtil.IsNumber(input) && input.Length == 11 && input.StartsWith("1");
}
/// <summary>
/// 是否为邮箱地址
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsEmail(this string input)
{
return Regex.IsMatch(input, @"^\w+@\w+\.\w+$");
}
/// <summary>
/// 分割字符串(不包含空字符串)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string[] SplitBy(this string input)
{
return input.SplitBy(new[] { "," });
}
/// <summary>
/// 分割字符串(不包含空字符串)
/// </summary>
/// <param name="input"></param>
/// <param name="separator">用指定字符分割</param>
/// <returns></returns>
public static string[] SplitBy(this string input, params String[] separator)
{
if (string.IsNullOrEmpty(input))
{
return new string[0];
}
if (separator == null || separator.Length == 0)
{
separator = new[] { "," };
}
return input.Split(separator, StringSplitOptions.RemoveEmptyEntries);
}
/// <summary>
/// 移除字符串中的BOM(UTF)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string RemoveBOM(this string input)
{
return Regex.Replace(input, new string(new char[] { (char)65279 }), "");
}
}
}
|
76caaf9e1e1aacdcc1039c4c41e21a92d63be68e
|
C#
|
Magofna68/AnimalShelter.Solution
|
/AnimalShelter/Migrations/20210611192048_SeedData.cs
| 2.640625
| 3
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace AnimalShelter.Migrations
{
public partial class SeedData : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Pets",
keyColumn: "PetId",
keyValue: 1);
migrationBuilder.AlterColumn<double>(
name: "Age",
table: "Pets",
type: "double",
nullable: false,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.InsertData(
table: "Pets",
columns: new[] { "PetId", "Age", "Breed", "Description", "Gender", "Name", "Type" },
values: new object[,]
{
{ 3, 1.2, "Maine Coon", "Massive fat cat; looking to be ~25lbs when fully grown", "Female", "Mango", "Cat" },
{ 4, 8.5, "Chiwawa", "Mi quero Taco Bell", "Female", "Taco", "Dog" },
{ 5, 4.0, "Great Dane", "Long Haired; White/Orangish in color", "Male", "Sebashian", "Dog" },
{ 6, 12.0, "Golden Retriever", "Golden in color; great with kids", "Male", "Doug", "Dog" },
{ 7, 3.75, "Calico", "Long Haired; very fiesty; loves tuna treats", "Female", "Meow", "Cat" }
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Pets",
keyColumn: "PetId",
keyValue: 3);
migrationBuilder.DeleteData(
table: "Pets",
keyColumn: "PetId",
keyValue: 4);
migrationBuilder.DeleteData(
table: "Pets",
keyColumn: "PetId",
keyValue: 5);
migrationBuilder.DeleteData(
table: "Pets",
keyColumn: "PetId",
keyValue: 6);
migrationBuilder.DeleteData(
table: "Pets",
keyColumn: "PetId",
keyValue: 7);
migrationBuilder.AlterColumn<int>(
name: "Age",
table: "Pets",
type: "int",
nullable: false,
oldClrType: typeof(double),
oldType: "double");
migrationBuilder.InsertData(
table: "Pets",
columns: new[] { "PetId", "Age", "Breed", "Description", "Gender", "Name", "Type" },
values: new object[] { 1, 3, "RagaMuffin", "Long Haired; White/Orangish in color", "Female", "Tiffany", "Cat" });
}
}
}
|
18ba6897e825a0f91920e3ec7dc8381674eb0ae1
|
C#
|
OliaSednev/CodeValue_HW
|
/Backgammon_OliaSednev/BackgammonLogic/GameLogic.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BackgammonInterfaces;
using BackgammonImplementation;
namespace BackgammonLogic
{
class GameLogic: IGameLogic
{
public IBoard GameBoard { get; set; }
public IPlayer X_Player { get; set; }
public IPlayer O_Player { get; set; }
public IDiceGenerator Dice { get; set; }
public int Dice_Counter { get; private set; }
public bool RolledDice { get; private set; } //indication about if dice rolled
public int? PlayerSourceCell { get; private set; }
public void SetPlayerSourse(int? index)
{
PlayerSourceCell = index;
}
public GameLogic()
{
X_Player = new Player("The X Player", Token.X);
O_Player = new Player("The O Player", Token.O);
X_Player.MyTurn = true;
GameBoard = new Board();
Dice = new DiceGenerator();
}
public void SwapTurns()
{
X_Player.MyTurn = !X_Player.MyTurn;
O_Player.MyTurn = !O_Player.MyTurn;
}
public void RollTheDice()
{
Dice.RollDice();
RolledDice = true;
Dice.RolledDouble = Dice.Cube1 == Dice.Cube2; // check if Double
}
public void ResetCube1()
{
Dice.Cube1 = 0;
}
public void ResetCube2()
{
Dice.Cube2 = 0;
}
public void DiceCounter()
{
Dice_Counter = Dice.RolledDouble ? 4 : 2;
}
public void ResetDiceCounter()
{
Dice_Counter = 0;
}
private void ResetCubeByTarget(int target)
{
if (!Dice.RolledDouble)
{
if (O_Player.MyTurn)
{
ResetCube(target, 1);
}
else
{
ResetCube(target, -1);
}
}
}
private void ResetCube(int target, int coefficient)
{
if ((coefficient*PlayerSourceCell - coefficient * target) == Dice.Cube1) // reset if the cube was used
{
ResetCube1();
}
else
{
ResetCube2();
}
}
private void ResetCubeByNumber(int cube)
{
if (!Dice.RolledDouble)
{
if (cube == Dice.Cube1)
{
ResetCube1();
}
if (cube == Dice.Cube2)
{
ResetCube2();
}
}
}
public bool LegalOption(int source)
{
return X_Player.MyTurn ? IsItLegalOption(source, X_Player) : IsItLegalOption(source, O_Player);
}
public bool IsItLegalOption(int source, IPlayer player)
{
if (player.TokenOfPlayer == Token.X)
{
return GameBoard.CellsList[source].TokenType == Token.X && GameBoard.TokensInTheJail_X == 0;
}
//if (TokenOfPlayer == Token.O)
return GameBoard.CellsList[source].TokenType == Token.O && GameBoard.TokensInTheJail_O == 0;
}
public bool LegalMove(int target)
{
if (X_Player.MyTurn)
{
return Move(X_Player, target, 1);
}
return Move(O_Player, target, -1);
}
private bool Move(IPlayer player, int target, int coefficient)
{
if (Dice.RolledDouble)
{
return IsItLegalMove(player, PlayerSourceCell.Value, target, Dice.Cube1, coefficient);
}
return IsItLegalMove(player, PlayerSourceCell.Value, target, Dice.Cube1, coefficient) ||
IsItLegalMove(player, PlayerSourceCell.Value, target, Dice.Cube2, coefficient);
}
public bool IsItLegalMove(IPlayer player, int source, int target, int cubeNumber, int coefficient)
{
return coefficient * target - coefficient * source == cubeNumber &&
(GameBoard.CellsList[target].TokenType == null || //free cell
GameBoard.CellsList[target].TokenType == player.TokenOfPlayer);
}
public void SetMove(int target, bool tokenWasEaten)
{
if (!tokenWasEaten) // if tokenWasEaten false, cell is empty, just need to add token to list and if tokenWasEaten true, one token eats another, there is no need to add token
{
GameBoard.CellsList[target].SumOfTokens++; //add token to target cell
}
if (PlayerSourceCell >= 0 && PlayerSourceCell <= 23) // board moves
{
GameBoard.CellsList[PlayerSourceCell.Value].SumOfTokens--; // reduce token from source cell
if (GameBoard.CellsList[PlayerSourceCell.Value].SumOfTokens == 0) //if cell empty set null
{
GameBoard.CellsList[PlayerSourceCell.Value].TokenType = null;
}
}
else // (PlayerSourceCell <= 0 && PlayerSourceCell >= 23) the move from Jail.
{
GameBoard.RemoveTokenFromJail(X_Player.MyTurn ? X_Player.TokenOfPlayer : O_Player.TokenOfPlayer);
}
if (GameBoard.CellsList[target].SumOfTokens == 1) // if was eaten or empty, change to current Token
{
GameBoard.CellsList[target].TokenType = X_Player.MyTurn ? X_Player.TokenOfPlayer : O_Player.TokenOfPlayer;
}
ResetCubeByTarget(target); // reset the used cube
PlayerSourceCell = null;
Dice_Counter--;
}
public bool LegalMoveToEat(int target)
{
return MoveToEat(target, X_Player.MyTurn ? X_Player : O_Player);
}
public bool MoveToEat(int target, IPlayer player)
{
if (Dice.RolledDouble)
{
return IsItLegalToEat(player, PlayerSourceCell.Value, target, Dice.Cube1);
}
return IsItLegalToEat(player, PlayerSourceCell.Value, target, Dice.Cube1) ||
IsItLegalToEat(player, PlayerSourceCell.Value, target, Dice.Cube2);
}
public bool IsItLegalToEat(IPlayer player, int source, int target, int cubeNumber)
{
if (player.TokenOfPlayer == Token.X)
{
return target - source == cubeNumber &&
GameBoard.CellsList[target].TokenType == Token.O && // not my tokens
GameBoard.CellsList[target].SumOfTokens == 1; // and one token, then i can eat him
}
//if (TokenOfPlayer == Token.O)
return source - target == cubeNumber &&
GameBoard.CellsList[target].TokenType == Token.X && // not my tokens
GameBoard.CellsList[target].SumOfTokens == 1; // and one token, then i can eat him
}
public void SetMoveToEat(int index)
{
GameBoard.AddTokenToJail(X_Player.MyTurn ? O_Player.TokenOfPlayer : X_Player.TokenOfPlayer);
SetMove(index, true);
}
public void SetJailMove(int cube)
{
GameBoard.CellsList[PlayerSourceCell.Value].SumOfTokens--;
if (GameBoard.CellsList[PlayerSourceCell.Value].SumOfTokens == 0)
{
GameBoard.CellsList[PlayerSourceCell.Value].TokenType = null;
}
ResetCubeByNumber(cube);
PlayerSourceCell = null;
Dice_Counter--;
}
public bool IsLegalToExit(out int cubeUsed)
{
cubeUsed = Dice.Cube1 < Dice.Cube2 ? Dice.Cube1 : Dice.Cube2;
if (X_Player.MyTurn)
{
bool isLegalMoveCube1 = IsExitMove(X_Player, PlayerSourceCell.Value, Dice.Cube1);
bool isLegalMoveCube2 = IsExitMove(X_Player, PlayerSourceCell.Value, Dice.Cube2);
return Dice.RolledDouble ? IsExitMove(X_Player, PlayerSourceCell.Value, Dice.Cube1) :
LegalMoveForExit(ref cubeUsed, isLegalMoveCube1, isLegalMoveCube2);
}
else
{
bool isLegalMoveCube1 = IsExitMove(O_Player, PlayerSourceCell.Value, Dice.Cube1);
bool isLegalMoveCube2 = IsExitMove(O_Player, PlayerSourceCell.Value, Dice.Cube2);
return Dice.RolledDouble ? IsExitMove(O_Player, PlayerSourceCell.Value, Dice.Cube1) :
LegalMoveForExit(ref cubeUsed, isLegalMoveCube1, isLegalMoveCube2);
}
}
public bool IsExitMove(IPlayer player, int source, int cubeNumber)
{
return player.TokenOfPlayer == Token.X ? (source + cubeNumber >= 24) : (source - cubeNumber <= -1);
}
public bool LegalMoveForExit(ref int cubeUsed, bool isLegalMoveCube1, bool isLegalMoveCube2)
{
if (isLegalMoveCube1)
{
cubeUsed = Dice.Cube1;
}
if (isLegalMoveCube2)
{
cubeUsed = Dice.Cube2;
}
if (isLegalMoveCube1 && isLegalMoveCube2)
{
cubeUsed = Dice.Cube1 < Dice.Cube2 ? Dice.Cube1 : Dice.Cube2;
}
return isLegalMoveCube1 || isLegalMoveCube2;
}
public void UpdateAtHome(IPlayer player)
{
if (player.TokenOfPlayer == Token.X)
{
CountTokensAtHome(player, 18, 23);
}
if (player.TokenOfPlayer == Token.O)
{
CountTokensAtHome(player, 0, 5);
}
}
public void CountTokensAtHome(IPlayer player, int lowRange, int hightRange)
{
player.SumOfTokensAtHome = 0;
for (int i = lowRange; i <= hightRange; i++)
{
if (GameBoard.CellsList[i].TokenType == player.TokenOfPlayer)
{
player.SumOfTokensAtHome += GameBoard.CellsList[i].SumOfTokens;
}
}
}
public bool CanStartToTakeOutTokens(IPlayer player)
{
return player.TokenOfPlayer == Token.X ?
ThereAreTokensOutsideTheHome(player, 0, 17, GameBoard.TokensInTheJail_X) :// in the jail, also outside the home
ThereAreTokensOutsideTheHome(player, 6, 23, GameBoard.TokensInTheJail_O);
}
public bool ThereAreTokensOutsideTheHome(IPlayer player, int lowRange, int hightRange, int sumOfOutsideTheHome)
{
for (int i = lowRange; i <= hightRange; i++)
{
if (GameBoard.CellsList[i].TokenType == player.TokenOfPlayer)// if there are tokens outside the home
{
sumOfOutsideTheHome += GameBoard.CellsList[i].SumOfTokens;
}
}
return (sumOfOutsideTheHome == 0);
}
public IEnumerable<KeyValuePair<int, int>> GetAllMoves(IPlayer player)
{
return player.TokenOfPlayer == Token.X ? GetAllMovesForXPlayer() : GetAllMovesForOPlayer();
}
public IEnumerable<KeyValuePair<int, int>> GetAllMovesForXPlayer()
{
var legalMoves = new List<KeyValuePair<int, int>>();
if (GameBoard.TokensInTheJail_X == 0)
{
for (int i = 0; i < GameBoard.CellsList.Count; i++)
{
if (!Dice.RolledDouble)
{
if (Dice.Cube1 != 0 && i + Dice.Cube1 <= 23 &&
IsItLegalOption(i, X_Player) &&
IsItLegalMove(X_Player, i, i + Dice.Cube1, Dice.Cube1, 1))
{
legalMoves.Add(new KeyValuePair<int, int>(i, i + Dice.Cube1));
}
if (Dice.Cube2 != 0 && i + Dice.Cube2 <= 23 &&
IsItLegalOption(i, X_Player) &&
IsItLegalMove(X_Player, i, i + Dice.Cube2, Dice.Cube2, 1))
{
legalMoves.Add(new KeyValuePair<int, int>(i, i + Dice.Cube2));
}
}
}
return legalMoves;
}
return GetAllMovesFromJail(X_Player);
}
public IEnumerable<KeyValuePair<int, int>> GetAllMovesForOPlayer()
{
var legalMoves = new List<KeyValuePair<int, int>>();
if (GameBoard.TokensInTheJail_O == 0)
{
for (int i = 0; i < GameBoard.CellsList.Count; i++)
{
if (!Dice.RolledDouble)
{
if (Dice.Cube1 != 0 && i - Dice.Cube1 >= 0 &&
IsItLegalOption(i, O_Player) &&
IsItLegalMove(O_Player, i, i - Dice.Cube1, Dice.Cube1, -1))
{
legalMoves.Add(new KeyValuePair<int, int>(i, i - Dice.Cube1));
}
if (Dice.Cube2 != 0 && i - Dice.Cube2 >= 0 &&
IsItLegalOption(i, O_Player) &&
IsItLegalMove(O_Player, i, i - Dice.Cube2, Dice.Cube2, -1))
{
legalMoves.Add(new KeyValuePair<int, int>(i, i - Dice.Cube2));
}
}
}
return legalMoves;
}
return GetAllMovesFromJail(O_Player);
}
public IEnumerable<KeyValuePair<int, int>> GetAllMovesToEat(IPlayer player)
{
return player.TokenOfPlayer == Token.X ? GetAllMovesToEatForXPlayer() : GetAllMovesToEatForOPlayer();
}
public IEnumerable<KeyValuePair<int, int>> GetAllMovesToEatForXPlayer()
{
var legalMoves = new List<KeyValuePair<int, int>>();
if (GameBoard.TokensInTheJail_X == 0)
{
for (int i = 0; i < GameBoard.CellsList.Count; i++)
{
if (!Dice.RolledDouble)
{
if (Dice.Cube1 != 0 && (i + Dice.Cube1 <= 23) &&
IsItLegalOption(i, X_Player) &&
IsItLegalMove(X_Player, i, i + Dice.Cube1, Dice.Cube1, 1))
{
legalMoves.Add(new KeyValuePair<int, int>(i, i + Dice.Cube1));
}
}
if (Dice.Cube2 != 0 && i + Dice.Cube2 <= 23 &&
IsItLegalOption(i, X_Player) &&
IsItLegalMove(X_Player, i, i + Dice.Cube2, Dice.Cube2, 1))
{
legalMoves.Add(new KeyValuePair<int, int>(i, i + Dice.Cube2));
}
}
return legalMoves;
}
return GetAllMovesFromJail(X_Player);
}
public IEnumerable<KeyValuePair<int, int>> GetAllMovesToEatForOPlayer()
{
var legalMoves = new List<KeyValuePair<int, int>>();
if (GameBoard.TokensInTheJail_O == 0)
{
for (int i = 0; i < GameBoard.CellsList.Count; i++)
{
if (!Dice.RolledDouble)
{
if (Dice.Cube1 != 0 && (i - Dice.Cube1 >= 0) &&
IsItLegalOption(i, O_Player) &&
IsItLegalMove(O_Player, i, i - Dice.Cube1, Dice.Cube1, -1))
{
legalMoves.Add(new KeyValuePair<int, int>(i, i - Dice.Cube1));
}
}
if (Dice.Cube2 != 0 && i - Dice.Cube2 >= 0 &&
IsItLegalOption(i, O_Player) &&
IsItLegalMove(O_Player, i, i - Dice.Cube2, Dice.Cube2, -1))
{
legalMoves.Add(new KeyValuePair<int, int>(i, i - Dice.Cube2));
}
}
return legalMoves;
}
return GetAllMovesFromJail(O_Player);
}
public IEnumerable<KeyValuePair<int, int>> GetAllMovesFromJail(IPlayer player)
{
return player.TokenOfPlayer == Token.X ? GetAllMovesFromJailForXPlayer() : GetAllMovesFromJailForOPlayer();
}
public IEnumerable<KeyValuePair<int, int>> GetAllMovesFromJailForXPlayer()
{
var legalMoves = new List<KeyValuePair<int, int>>();
if (Dice.Cube1 != 0 && IsItLegalMove(X_Player, -1, -1 + Dice.Cube1, Dice.Cube1, 1))
{
legalMoves.Add(new KeyValuePair<int, int>(-1, -1 + Dice.Cube1));
}
if (Dice.Cube2 != 0 && IsItLegalMove(X_Player, -1, -1 + Dice.Cube2, Dice.Cube2, 1))
{
legalMoves.Add(new KeyValuePair<int, int>(-1, -1 + Dice.Cube2));
}
return legalMoves;
}
public IEnumerable<KeyValuePair<int, int>> GetAllMovesFromJailForOPlayer()
{
var legalMoves = new List<KeyValuePair<int, int>>();
if (Dice.Cube1 != 0 && IsItLegalMove(O_Player, 24, 24 - Dice.Cube1, Dice.Cube1, -1))
{
legalMoves.Add(new KeyValuePair<int, int>(24, 24 - Dice.Cube1));
}
if (Dice.Cube2 != 0 && IsItLegalMove(O_Player, 24, 24 - Dice.Cube2, Dice.Cube2, -1))
{
legalMoves.Add(new KeyValuePair<int, int>(24, 24 - Dice.Cube2));
}
return legalMoves;
}
public IEnumerable<KeyValuePair<int, int>> GetAllMovesToEatFromJail(IPlayer player)
{
return player.TokenOfPlayer == Token.X ? GetAllMovesToEatFromJailForXPlayer() : GetAllMovesToEatFromJailForOPlayer();
}
public IEnumerable<KeyValuePair<int, int>> GetAllMovesToEatFromJailForXPlayer()
{
var legalMoves = new List<KeyValuePair<int, int>>();
if (Dice.Cube1 != 0 &&
IsItLegalToEat(X_Player, -1, -1 + Dice.Cube1, Dice.Cube1))
{
legalMoves.Add(new KeyValuePair<int, int>(-1, -1 + Dice.Cube1));
}
if (Dice.Cube2 != 0 &&
IsItLegalToEat(X_Player, -1, -1 + Dice.Cube2, Dice.Cube2))
{
legalMoves.Add(new KeyValuePair<int, int>(-1, -1 + Dice.Cube2));
}
return legalMoves;
}
public IEnumerable<KeyValuePair<int, int>> GetAllMovesToEatFromJailForOPlayer()
{
var legalMoves = new List<KeyValuePair<int, int>>();
if (Dice.Cube1 != 0 &&
IsItLegalToEat(O_Player, 24, 24 - Dice.Cube1, Dice.Cube1))
{
legalMoves.Add(new KeyValuePair<int, int>(24, 24 - Dice.Cube1));
}
if (Dice.Cube2 != 0 &&
IsItLegalToEat(O_Player, 24, 24 - Dice.Cube2, Dice.Cube2))
{
legalMoves.Add(new KeyValuePair<int, int>(24, 24 - Dice.Cube2));
}
return legalMoves;
}
public IEnumerable<KeyValuePair<int, int>> ExitMoves(IPlayer player)
{
return player.TokenOfPlayer == Token.X ? ExitMovesOfPlayer(X_Player, 18, 23) : ExitMovesOfPlayer(O_Player, 0, 5);
}
public IEnumerable<KeyValuePair<int, int>> ExitMovesOfPlayer(IPlayer player, int lowRange, int hightRange)
{
var legalMoves = new List<KeyValuePair<int, int>>();
for (int i = lowRange; i <= hightRange; i++)
{
if (!Dice.RolledDouble &&
Dice.Cube1 != 0 &&
IsItLegalOption(i, player) &&
IsExitMove(player, i, Dice.Cube1))
{
legalMoves.Add(new KeyValuePair<int, int>(i, Dice.Cube1));
}
//if RolledDouble only this will be check
if (Dice.Cube2 != 0 &&
IsItLegalOption(i, player) &&
IsExitMove(player, i, Dice.Cube2))
{
legalMoves.Add(player.TokenOfPlayer == Token.O
? new KeyValuePair<int, int>(i, i - Dice.Cube2)
: new KeyValuePair<int, int>(i, Dice.Cube2));
}
}
return legalMoves;
}
public bool ThereAreLegalMoves(IPlayer player)
{
return GetAllMoves(player).ToList().Count + GetAllMovesToEat(player).ToList().Count > 0;
}
public bool ThereAreLegalExitMoves(IPlayer player)
{
return ExitMoves(player).ToList().Count > 0;
}
public bool ThereAreLegalMovesFromJail(IPlayer player)
{
return GetAllMovesFromJail(player).ToList().Count + GetAllMovesToEatFromJail(player).ToList().Count > 0;
}
public bool PlayerMoves()
{
return X_Player.MyTurn ? ThereAreLegalMoves(X_Player) :
ThereAreLegalMoves(O_Player);
}
public bool PlayerFromJailMoves()
{
return X_Player.MyTurn ? ThereAreLegalMovesFromJail(X_Player) :
ThereAreLegalMovesFromJail(O_Player);
}
public bool PlayerExitMoves()
{
return X_Player.MyTurn ? ThereAreLegalExitMoves(X_Player) :
ThereAreLegalExitMoves(O_Player);
}
}
}
|
a35e26709fd7a8c3c0a5cd66b773aaa5df9c6104
|
C#
|
thePurpleMonkey/CS586_Train_Database
|
/CS586_Train_Database/Registration_form.cs
| 2.65625
| 3
|
using Npgsql;
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CS586_Train_Database
{
/* This part is to validate email format, but won't work!
public class RegexUtilities
{
public static bool IsValidEmail(string email)
{
if (string.IsNullOrWhiteSpace(email))
return false;
try
{
// Normalize the domain
email = Regex.Replace(email, @"(@)(.+)$", DomainMapper,
RegexOptions.None, TimeSpan.FromMilliseconds(200));
// Examines the domain part of the email and normalizes it.
string DomainMapper(Match match)
{
// Use IdnMapping class to convert Unicode domain names.
var idn = new IdnMapping();
// Pull out and process domain name (throws ArgumentException on invalid)
var domainName = idn.GetAscii(match.Groups[2].Value);
return match.Groups[1].Value + domainName;
}
}
catch (RegexMatchTimeoutException e)
{
return false;
}
catch (ArgumentException e)
{
return false;
}
try
{
return Regex.IsMatch(email,
@"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
}
*/
public partial class Registration_form : Form
{
private NpgsqlConnection conn;
private string Role;
public Registration_form()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
}
private string GetPassfilePath()
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "postgresql", "pgpass.conf");
if (File.Exists(path))
{
return path;
}
path = Path.Combine(Directory.GetCurrentDirectory(), "pgpass.conf");
if (File.Exists(path))
{
return path;
}
else
{
return null;
}
}
private void User_Rbtn_CheckedChanged(object sender, EventArgs e)
{
Role = "User";
}
private void Admin_Rbtn_CheckedChanged(object sender, EventArgs e)
{
Role = "Admin";
}
private void Submit_btn_Click(object sender, EventArgs e)
{
if (email_txt.Text == "" || Pass_txt.Text == "" || Name_txt.Text == "" || Phone_txt.Text == "")
MessageBox.Show("Please fill all the rows indicated with red star");
else if (Pass_txt.Text != PassConf_txt.Text)
MessageBox.Show("Password confirmation doesn't match");
else
{
// Build connection string
NpgsqlConnectionStringBuilder builder = new NpgsqlConnectionStringBuilder();
builder.Host = "dbclass.cs.pdx.edu";
builder.Database = "w19wdb19";
builder.Username = "w19wdb19";
builder.Passfile = GetPassfilePath();
if (builder.Passfile == null)
{
MessageBox.Show(@"PostgreSQL password file not found! Please create a password file at %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile).", "ERROR: No password file found", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
builder.SslMode = SslMode.Require;
builder.TrustServerCertificate = true;
using (var conn = new NpgsqlConnection(builder.ConnectionString))
{
conn.Open();
using (var cmd = new NpgsqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO train.user (email, password, name, phone,role) VALUES ('" + email_txt.Text + "', '" + Pass_txt.Text + "', '" + Name_txt.Text + "', '" + Phone_txt.Text + "', '" + Role + "');";
cmd.ExecuteNonQuery();
}
}
this.Close();
}
}
}
}
|
bf9329b9441ca027dff417746325dace9b64d59b
|
C#
|
elunadanilo/FrontEndCrud
|
/PersonaFrontEnd/PersonaFrontEnd/Services/PersonaService.cs
| 2.65625
| 3
|
using Newtonsoft.Json;
using PersonaFrontEnd.Dao;
using PersonaFrontEnd.Models;
using PersonaFrontEnd.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
namespace PersonaFrontEnd.Services
{
public class PersonaService : IPersonaDao
{
string BaseUrl = "http://localhost:55459/api/";
public async Task<OperationResponse> Delete(int id)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseUrl);
var deleteTask = client.DeleteAsync($"persona/" + id.ToString());
deleteTask.Wait();
var result = deleteTask.Result;
if (result.IsSuccessStatusCode)
{
await Task.Delay(1000);
return new OperationResponse(1);
}
else
{
await Task.Delay(1000);
return new OperationResponse(0);
}
}
}
catch (Exception exc)
{
Debug.WriteLine(exc);
return new OperationResponse(0);
}
}
public async Task<OperationResponse> GetAll()
{
try
{
List<PersonaModel> persona = new List<PersonaModel>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseUrl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage res = await client.GetAsync("persona");
if (res.IsSuccessStatusCode)
{
var personaResponse = res.Content.ReadAsStringAsync().Result;
persona = JsonConvert.DeserializeObject<List<PersonaModel>>(personaResponse);
}
return new OperationResponse(1, persona);
}
}
catch (Exception exc)
{
Debug.WriteLine(exc);
return new OperationResponse(0);
}
}
public async Task<OperationResponse> GetById(int id)
{
try
{
PersonaModel persona = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseUrl);
var responseTask = client.GetAsync("persona/" + id.ToString());
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<PersonaModel>();
readTask.Wait();
persona = readTask.Result;
}
}
return new OperationResponse(1,persona);
}
catch (Exception exc)
{
Debug.WriteLine(exc);
return new OperationResponse(0);
}
}
public async Task<OperationResponse> Save(PersonaModel t)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:55459/api/persona");
var postTask = client.PostAsJsonAsync<PersonaModel>("persona", t);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
await Task.Delay(1000);
return new OperationResponse(1);
}
else
{
await Task.Delay(1000);
return new OperationResponse(0);
}
}
}
catch (Exception exc)
{
Debug.WriteLine(exc);
return new OperationResponse(0);
}
}
public async Task<OperationResponse> Update(int id, PersonaModel t)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseUrl);
var putTask = client.PutAsJsonAsync($"persona/{t.IdPersona}", t);
putTask.Wait();
var result = putTask.Result;
if (result.IsSuccessStatusCode)
{
await Task.Delay(1000);
return new OperationResponse(1);
}
else
{
await Task.Delay(1000);
return new OperationResponse(0);
}
}
}
catch (Exception exc)
{
Debug.WriteLine(exc);
return new OperationResponse(0);
}
}
}
}
|
5f181248ee6198f5e5e625daac24072dccc5386d
|
C#
|
garyemerson/jim_and_his_lan_party
|
/jim_and_his_lan_party.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class ConnectedCompenent {
// game -> num players for that game in this conn comp
public Dictionary<int, int> NumPlayersByGame;
// player in this conn comp
public List<int> players;
}
class Solution {
static void Main(String[] args) {
int numPlayers;
int numGames;
int numWires;
getParamsData(out numPlayers, out numGames, out numWires);
Dictionary<int, int> playerToGame;
Dictionary<int, int> totalPlayersForGame;
getGameData(out playerToGame, out totalPlayersForGame);
Dictionary<int, int> gameToStartTime = new Dictionary<int, int>();
for (int i = 1; i <= numGames; i++) {
gameToStartTime[i] = -1;
}
Dictionary<int, ConnectedCompenent> components = getInitialComponents(
playerToGame,
numPlayers,
gameToStartTime,
totalPlayersForGame);
for (int wire = 1; wire <= numWires; wire++) {
List<int> players = Console.ReadLine().Trim().Split(null).Select(s => int.Parse(s)).ToList();
int p1 = players[0];
int p2 = players[1];
if (components[p1].NumPlayersByGame.Count > components[p2].NumPlayersByGame.Count) {
// combine game player counts
foreach (int game in components[p2].NumPlayersByGame.Keys) {
if (!components[p1].NumPlayersByGame.ContainsKey(game)) {
components[p1].NumPlayersByGame[game] = 0;
}
components[p1].NumPlayersByGame[game] += components[p2].NumPlayersByGame[game];
if (components[p1].NumPlayersByGame[game] >= totalPlayersForGame[game] &&
gameToStartTime[game] == -1)
{
gameToStartTime[game] = wire;
}
}
// all players in p2's component now go to p1's component
foreach (int p in components[p2].players) {
components[p] = components[p1];
components[p1].players.Add(p);
}
} else {
// combine game player counts
foreach (int game in components[p1].NumPlayersByGame.Keys) {
if (!components[p2].NumPlayersByGame.ContainsKey(game)) {
components[p2].NumPlayersByGame[game] = 0;
}
components[p2].NumPlayersByGame[game] += components[p1].NumPlayersByGame[game];
if (components[p2].NumPlayersByGame[game] >= totalPlayersForGame[game] &&
gameToStartTime[game] == -1)
{
gameToStartTime[game] = wire;
}
}
// all players in p1's component now go to p2's component
foreach (int p in components[p1].players) {
components[p] = components[p2];
components[p2].players.Add(p);
}
}
}
for (int game = 1; game <= numGames; game++) {
Console.WriteLine(gameToStartTime[game]);
}
}
static Dictionary<int, ConnectedCompenent> getInitialComponents(
Dictionary<int, int> playerToGame,
int numPlayers,
Dictionary<int, int> gameToStartTime,
Dictionary<int, int> totalPlayersForGame)
{
Dictionary<int, ConnectedCompenent> components = new Dictionary<int, ConnectedCompenent>();
for (int p = 1; p <= numPlayers; p++) {
if (totalPlayersForGame[playerToGame[p]] == 1) {
gameToStartTime[playerToGame[p]] = 0;
}
components[p] = new ConnectedCompenent() {
NumPlayersByGame = new Dictionary<int, int>() {
{ playerToGame[p] , 1 }
},
players = new List<int>() { p },
};
}
return components;
}
static void getParamsData(out int numPlayers, out int numGames, out int numWires) {
List<int> data = Console.ReadLine().Trim().Split(null).Select(s => int.Parse(s)).ToList();
numPlayers = data[0];
numGames = data[1];
numWires = data[2];
}
static void getGameData(out Dictionary<int, int> playerToGame, out Dictionary<int, int> totalPlayersForGame) {
List<int> games = Console.ReadLine().Trim().Split(null).Select(s => int.Parse(s)).ToList();
playerToGame = new Dictionary<int, int>();
totalPlayersForGame = new Dictionary<int, int>();
for (int i = 0; i < games.Count; i++) {
playerToGame[i + 1] = games[i];
if (!totalPlayersForGame.ContainsKey(games[i])) {
totalPlayersForGame[games[i]] = 0;
}
totalPlayersForGame[games[i]]++;
}
}
}
|
a56495bec2a0dd418b4895f46d0b6c9e2c738134
|
C#
|
ChesterTheCheese/physical
|
/physical/math/Vector3f.cs
| 2.8125
| 3
|
using System;
namespace physical.math {
public class Vector3f : VectorFloat {
public const int SIZE = 3;
public const int OX = 0, OY = 1, OZ = 2;
public float X { get { return Data[0]; } set { Data[0] = value; } }
public float Y { get { return Data[1]; } set { Data[1] = value; } }
public float Z { get { return Data[2]; } set { Data[2] = value; } }
public Vector3f ( Vector3f vector ) : base( vector ) {
}
public Vector3f ( float[] data ) : base( data, SIZE ) {
}
public Vector3f () : base( new float[SIZE] ) {
}
public Vector3f ( float x, float y, float z ) : base( new float[]{ x, y, z } ) {
}
public Vector3f set ( float x, float y, float z ) {
X = x;
Y = y;
Z = z;
return this;
}
public Vector3f add ( float x, float y, float z ) {
X += x;
Y += y;
Z += z;
return this;
}
public Vector3f scale ( float x, float y, float z ) {
X *= x;
Y *= y;
Z *= z;
return this;
}
public float dot ( float x, float y, float z ) {
return X * x + Y * y + Z * z;
}
public Vector3f cross ( Vector3f vector ) {
return new Vector3f( cross( data, vector.data ) );
}
public Vector3f getNormal ( Vector3f v1, Vector3f v2 ) {
return new Vector3f( getNormal( data, v1.data, v2.data ) );
}
static public float[] cross ( float[] v1, float[] v2 ) {
return new float[] {
v1[1] * v2[2] - v1[2] * v2[1],
v1[2] * v2[0] - v1[0] * v2[2],
v1[0] * v2[1] - v1[1] * v2[0]
};
}
static public float[] getNormal ( float[] v1, float[] v2, float[] v3 ) {
float[] norm = cross(
new float[]{ v2[0] - v1[0], v2[1] - v1[1], v2[2] - v1[2] },
new float[]{ v3[0] - v1[0], v3[1] - v1[1], v3[2] - v1[2] } );
normalize( norm );
return norm;
}
static public float distance ( float x1, float y1, float z1, float x2, float y2, float z2 ) {
return (float) Math.Sqrt( distanceSq( x1, y1, z1, x2, y2, z2 ) );
}
static public float distanceSq ( float x1, float y1, float z1, float x2, float y2, float z2 ) {
float x = x2 - x1, y = y2 - y1, z = z2 - z1;
return x * x + y * y + z * z;
}
}
}
|
19d86e61f41944815165b5120b01309322b497b7
|
C#
|
nielsbakkers/Software
|
/Euro-Dollar-Converter/Euro-Dollar-Converter/Form1.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Euro_Dollar_Converter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
decimal Euro = Convert.ToDecimal(textBox1.Text);
decimal Koers = numericUpDown1.Value;
decimal Dollar = Euro * Koers;
textBox2.Text = Dollar.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
decimal Dollar = Convert.ToDecimal(textBox2.Text);
decimal Koers = numericUpDown1.Value;
decimal Euro = Dollar / Koers;
textBox1.Text = Euro.ToString();
}
}
}
|
203230f5ea53cc89affa98f49c3acbc566ff5de1
|
C#
|
ctcb57/lemonade_Stand
|
/lemonade_Stand/lemonade_Stand/Player.cs
| 3.5625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lemonade_Stand
{
public class Player
{
//member variables
public string name;
public int weeklyProfit;
private int cashOnHand;
public int CashOnHand
{
get
{
return cashOnHand;
}
set
{
if (value <= 0)
{
cashOnHand = 0;
}
else
{
cashOnHand = value;
}
}
}
//constructor
public Player()
{
cashOnHand = 100;
}
//member methods
public void ChooseName()
{
name = Console.ReadLine().Trim();
Console.Clear();
}
public int CalculateWeeklyProfit(int startingCash)
{
weeklyProfit = cashOnHand - startingCash;
return weeklyProfit;
}
}
}
|
fa31e053572a8b7457486726f9dc1d3611c16354
|
C#
|
curicm/BitFaster.Caching
|
/BitFaster.Caching.Benchmarks/DataStructureBenchmarks.cs
| 3
| 3
|
using BenchmarkDotNet.Attributes;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BitFaster.Caching.Benchmarks
{
[MemoryDiagnoser]
public class DataStructureBenchmarks
{
private static readonly ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>(8, 9, EqualityComparer<int>.Default);
LinkedList<int> intList = new LinkedList<int>(new int[] { 1, 2, 3 });
ConcurrentQueue<int> queue = new ConcurrentQueue<int>(new int[] { 1, 2, 3 });
private int counter = 0;
[Benchmark(Baseline = true)]
public void ConcurrentQueueSwapLastToFirst()
{
Interlocked.Decrement(ref counter);
var wasDequeue = queue.TryDequeue(out var result);
queue.Enqueue(result);
Interlocked.Increment(ref counter);
}
[Benchmark()]
public void LinkedListSwapFirstToLast()
{
var first = intList.First;
intList.RemoveFirst();
intList.AddLast(first);
}
[Benchmark()]
public void LinkedListLockSwapFirstToLast()
{
lock (this.intList)
{
var first = intList.First;
intList.RemoveFirst();
intList.AddLast(first);
}
}
[Benchmark()]
public void DictionaryGetOrAdd()
{
Func<int, int> func = x => x;
dictionary.GetOrAdd(1, func);
}
}
}
|
e07cc1672ee5f1851ce61784aec47b6c420baa13
|
C#
|
bjavanderdoef/NWD
|
/Website/App_Code/SupportedImageFormats.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Web.UI.WebControls;
public static class ImageUploadHelpers
{
#region Private Fields/Properties - Image Formats
private static SortedDictionary<Guid, string> _ImageFormats = null;
private static SortedDictionary<Guid, string> ImageFormats
{
get
{
if (_ImageFormats == null)
{
_ImageFormats = new SortedDictionary<Guid, string>();
// Set up the dictionary
_ImageFormats.Add(ImageFormat.Bmp.Guid, "image/bmp");
_ImageFormats.Add(ImageFormat.Emf.Guid, "image/emf");
_ImageFormats.Add(ImageFormat.Exif.Guid, "image/exif");
_ImageFormats.Add(ImageFormat.Gif.Guid, "image/gif");
_ImageFormats.Add(ImageFormat.Jpeg.Guid, "image/jpeg");
_ImageFormats.Add(ImageFormat.Png.Guid, "image/png");
_ImageFormats.Add(ImageFormat.Tiff.Guid, "image/tiff");
_ImageFormats.Add(ImageFormat.Wmf.Guid, "image/wmf");
}
return _ImageFormats;
}
}
#endregion
#region Public Methods
public static string GetMimeType(FileUpload mageUploadControl)
{
if (mageUploadControl.HasFile && mageUploadControl.PostedFile != null)
{
string extention = Path.GetExtension(mageUploadControl.PostedFile.FileName).ToLower();
string MIMEType = "image/" + extention.Replace(".", "");
return MIMEType;
}
else
return null;
}
public static byte[] GetUploadedPicture(FileUpload imageUploadControl)
{
byte[] thePicture = null;
if (imageUploadControl.HasFile && imageUploadControl.PostedFile != null)
{
if (ImageFormats.ContainsValue(GetMimeType(imageUploadControl)))
{
long size = imageUploadControl.PostedFile.InputStream.Length;
if (size < int.MaxValue)
{
byte[] ImageBytes = new byte[size];
imageUploadControl.PostedFile.InputStream.Read(ImageBytes, 0, (int)size);
thePicture = ImageBytes;
}
else
throw new Exception(string.Format("Image is too big. Images must be smaller than {0} btyes in size.",
int.MaxValue));
}
else
{
throw new Exception("Invalid file type uploaded - only picture files are allowed.");
}
}
return thePicture;
}
#endregion
}
|
6bb65e770bb6314c59c6b86e21a178c5dceef435
|
C#
|
nikolay-doichev/Csharp-Entity-Framework-Core-October-2019
|
/04. Code-First/P01. Hospital Database/Data/HospitalContext.cs
| 2.53125
| 3
|
using Microsoft.EntityFrameworkCore;
using P01_HospitalDatabase.Data.Models;
namespace P01_HospitalDatabase.Data
{
public class HospitalContext : DbContext
{
public HospitalContext()
{
}
public HospitalContext(DbContextOptions options) :
base(options)
{
}
public DbSet<Patient> Patients { get; set; }
public DbSet<Visitation> Visitations { get; set; }
public DbSet<Diagnose> Diagnoses { get; set; }
public DbSet<Medicament> Medicaments { get; set; }
public DbSet<PatientMedicament> PatientMedicaments { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(Configuration.ConnectionString);
}
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Patient>(entity =>
{
entity.HasKey(p => p.PatientId);
entity.Property(p => p.FirstName)
.HasMaxLength(50)
.IsUnicode(true)
.IsRequired(true);
entity.Property(p => p.LastName)
.HasMaxLength(50)
.IsUnicode(true)
.IsRequired(true);
entity.Property(p => p.Address)
.HasMaxLength(250)
.IsUnicode(true)
.IsRequired(true);
entity.Property(p => p.Email)
.HasMaxLength(80)
.IsUnicode(false)
.IsRequired(false);
entity.Property(p => p.HasInsurance)
.IsRequired(true);
});
modelBuilder.Entity<Visitation>(entity =>
{
entity.HasKey(v => v.VisitationId);
entity.Property(p => p.Date)
.HasColumnType("DATETIME2")
.IsRequired(true);
entity.Property(p => p.Comments)
.HasMaxLength(250)
.IsRequired(true)
.IsUnicode(true);
entity
.HasOne(p => p.Patient)
.WithMany(v => v.Visitations)
.HasForeignKey(p => p.PatientId);
});
modelBuilder.Entity<Diagnose>(entity =>
{
entity.HasKey(d => d.DiagnoseId);
entity.Property(p => p.Name)
.HasMaxLength(50)
.IsRequired(true)
.IsUnicode(true);
entity.Property(p => p.Comments)
.HasMaxLength(250)
.IsRequired(true)
.IsUnicode(true);
entity
.HasOne(p => p.Patient)
.WithMany(d => d.Diagnoses)
.HasForeignKey(p => p.PatientId);
});
modelBuilder.Entity<Medicament>(entity =>
{
entity.HasKey(m => m.MedicamentId);
entity.Property(p => p.Name)
.HasMaxLength(50)
.IsRequired(true)
.IsUnicode(true);
});
modelBuilder.Entity<PatientMedicament>(entity =>
{
entity.HasKey(pm => new { pm.PatientId, pm.MedicamentId });
entity
.HasOne(m => m.Medicament)
.WithMany(pm => pm.Prescriptions)
.HasForeignKey(m => m.MedicamentId);
entity
.HasOne(p => p.Patient)
.WithMany(pm => pm.Prescriptions)
.HasForeignKey(p => p.PatientId);
});
}
}
}
|
85600afd39cf996ef56d300b94c1a2f3963fb827
|
C#
|
hmthanh/FileSharing
|
/Client/Client.cs
| 2.796875
| 3
|
using FileSharing.Client.Clients;
using FileSharing.Commons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Client
{
class Client
{
private string masterServerIP;
private int masterServerPort;
private List<FileDetailsWithDownloadEndPoint> fileList = new List<FileDetailsWithDownloadEndPoint>();
public Client(string masterServerIP, int masterServerPort)
{
this.masterServerIP = masterServerIP;
this.masterServerPort = masterServerPort;
}
public async Task GetFileList()
{
var masterServiceClient = new MasterServiceClient(new MasterServiceClientSettings()
{
MasterServerIP = this.masterServerIP,
MasterServerPort = this.masterServerPort
});
masterServiceClient.Start();
// Always set callback at first.
masterServiceClient.FileListReceived += (sender, args) =>
{
this.fileList.Clear();
this.fileList.AddRange(args.FileList);
Console.Beep();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thông báo: Đã nhận được danh sách tập tin.");
Console.ResetColor();
masterServiceClient.Stop();
};
await masterServiceClient.MasterServer.RequestFileList();
}
public async Task DownloadFile(int index)
{
FileDetailsWithDownloadEndPoint fileDetails;
try
{
fileDetails = this.fileList[index - 1];
}
catch (IndexOutOfRangeException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Cảnh báo: Chỉ mục của tập tin vượt khoảng hợp lệ.");
Console.ResetColor();
return;
}
var fileServiceClient = new FileServiceClient(new FileServiceClientSettings()
{
FileName = fileDetails.Name,
FileServerIP = fileDetails.DownloadIP,
FileServerPort = fileDetails.DownloadPort
});
try
{
await fileServiceClient.Download();
} catch (UnknownFileException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Thông báo: Tập tin {fileDetails.Name} không tồn tại trên File Server.");
Console.ResetColor();
return;
} catch (CorruptedFileException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Thông báo: Tập tin {fileDetails.Name} không toàn vẹn trong quá trình truyền tải.");
Console.ResetColor();
return;
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Thông báo: Đã tải xong tập tin {fileDetails.Name}.");
Console.ResetColor();
}
public void PrintFileList()
{
int index = 1;
Console.WriteLine($"{"Index",5}|{"File Name",32}");
foreach (var file in this.fileList)
{
Console.WriteLine($"{index++,5}|{file.Name,32}");
}
}
}
}
|
7e0f713c48c8280ce57a05a0dc7b5dbb6a81c391
|
C#
|
kgp-developments/WindowsFolderEditor
|
/ReFolder/Dir/MainDir.cs
| 2.734375
| 3
|
using ReFolder.Dir.Description;
using System;
using System.Collections.Generic;
namespace ReFolder.Dir
{
[Serializable]
public class MainDir : Dir, IEditableDirWithChildren
{
public List<IEditableDirWithChildrenAndParent> Children { get; set; } = new List<IEditableDirWithChildrenAndParent>();
#region constructors
public MainDir(IMutableSystemObjectDescription description, List<IEditableDirWithChildrenAndParent> children) : this(description)
{
if (children == null) throw new ArgumentNullException("one or more arguments are null");
this.Children = children;
}
public MainDir(IMutableSystemObjectDescription description) : base(description)
{
}
public MainDir() { }
#endregion
//usuwa childDir
public void DeleteChildDirFromList(IEditableDirWithChildrenAndParent child)
{
Children.Remove(child);
}
//usuwa childrenDiry
public void DeleteChildrenDirsFromList(List<IEditableDirWithChildrenAndParent> children)
{
for (int i = 0; i < children.Count; i++)
{
DeleteChildDirFromList(children[i]);
}
}
// dodaje childDir
public void AddChildToChildrenList(IEditableDirWithChildrenAndParent child)
{
if (DirValidate.IsNameExistingInChildrenDirs(this, child.Description.Name)) throw new InvalidOperationException($"folder named as {child.Description.Name} exist in structure");
child.ParentDir = this;
DirManagement.AutoGenerateDirFullName(child);
if (DirValidate.IsfolderExisting(child.Description.FullName)) throw new InvalidOperationException("you can't create folder that exist");
Children.Add(child);
}
// dodaje childrenDiry
public void AddChildrenToChildrenList(List<IEditableDirWithChildrenAndParent> children)
{
foreach (IEditableDirWithChildrenAndParent child in children)
{
AddChildToChildrenList(child);
}
}
/// <summary>
/// insert child in to Children list at the specified position
/// </summary>
/// <param name="children"></param>
/// <param name="index"></param>
public void AddChildOnSpecifiedIndex(IEditableDirWithChildrenAndParent children, int index)
{
Children.Insert(index, children);
}
/// <summary>
/// insert children in to Children list at the specified position
/// </summary>
/// <param name="children"></param>
/// <param name="index"></param>
public void AddChildrenOnSpecifiedIndex(List<IEditableDirWithChildrenAndParent> children, int index)
{
Children.InsertRange(index, children);
}
public override bool Equals(object obj)
{
return obj is MainDir dir &&
base.Equals(obj) &&
EqualityComparer<List<IEditableDirWithChildrenAndParent>>.Default.Equals(Children, dir.Children);
}
public override int GetHashCode()
{
var hashCode = 812589192;
hashCode = hashCode * -1521134295 + base.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<List<IEditableDirWithChildrenAndParent>>.Default.GetHashCode(Children);
return hashCode;
}
}
}
|
65d715b97381f0c41de3ac067fdd36b008308764
|
C#
|
ghhv/GrowattApi
|
/Ealse.Growatt.Api/Ealse.Growatt.Api/Converters/DictionaryBaseConverter.cs
| 2.96875
| 3
|
using Ealse.Growatt.Api.Exceptions;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Ealse.Growatt.Api.Converters
{
public abstract class DictionaryBaseConverter<TKey, TVal> : JsonConverter<Dictionary<TKey, TVal>>
{
public override Dictionary<TKey, TVal> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.StartObject)
{
var ret = new Dictionary<TKey, TVal>();
reader.Read();
while (reader.TokenType != JsonTokenType.EndObject)
{
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new UnexpectedTokenException();
}
var key = GetKey(reader.GetString());
reader.Read();
if (reader.TokenType != JsonTokenType.String)
{
throw new UnexpectedTokenException();
}
var value = GetValue(reader.GetString());
ret.Add(key, value);
reader.Read();
}
return ret;
}
return new Dictionary<TKey, TVal>();
}
public override void Write(Utf8JsonWriter writer, Dictionary<TKey, TVal> value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public abstract TKey GetKey(string propertyName);
public abstract TVal GetValue(string propertyValue);
}
}
|
8405c27e0764d9cfa1d0f74d9a8f3062525611e2
|
C#
|
patrickhitch/Middleware
|
/src/RateLimiting/RateLimitingOptions.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
namespace Hellang.Middleware.RateLimiting
{
public class RateLimitingOptions
{
private List<Check<bool>> Safelists { get; } = new List<Check<bool>>();
private List<Check<bool>> Blocklists { get; } = new List<Check<bool>>();
private List<ThrottleCheck> Throttles { get; } = new List<ThrottleCheck>();
public void Safelist(string name, Func<HttpContext, bool> predicate)
{
Safelist(name, ctx => new ValueTask<bool>(predicate(ctx)));
}
public void Safelist(string name, Func<HttpContext, ValueTask<bool>> predicate)
{
Safelists.Add(new Check<bool>(name, predicate));
}
public void Blocklist(string name, Func<HttpContext, bool> predicate)
{
Blocklist(name, ctx => new ValueTask<bool>(predicate(ctx)));
}
public void Blocklist(string name, Func<HttpContext, ValueTask<bool>> predicate)
{
Blocklists.Add(new Check<bool>(name, predicate));
}
public void Throttle(string name,
Func<HttpContext, ValueTask<int>> limit,
Func<HttpContext, ValueTask<TimeSpan>> period,
Func<HttpContext, ValueTask<string>> discriminator)
{
Throttles.Add(new ThrottleCheck(name, limit, period, discriminator));
}
[DebuggerStepThrough]
internal Task<bool> IsSafelisted(HttpContext context)
{
return HasMatch(Safelists, context);
}
[DebuggerStepThrough]
internal Task<bool> IsBlocklisted(HttpContext context)
{
return HasMatch(Blocklists, context);
}
internal async Task<bool> IsThrottled(HttpContext context, IDistributedCache cache)
{
foreach (var throttle in Throttles)
{
if (await throttle.Matches(context, cache))
{
return true;
}
}
return false;
}
private static async Task<bool> HasMatch(IEnumerable<Check<bool>> checks, HttpContext context)
{
foreach (var check in checks)
{
if (await check.Predicate.Invoke(context))
{
return true;
}
}
return false;
}
private class Check<T>
{
public Check(string name, Func<HttpContext, ValueTask<T>> predicate)
{
Name = name;
Predicate = predicate;
}
public string Name { get; }
public Func<HttpContext, ValueTask<T>> Predicate { get; }
}
private class ThrottleCheck : Check<string>
{
public ThrottleCheck(string name,
Func<HttpContext, ValueTask<int>> limit,
Func<HttpContext, ValueTask<TimeSpan>> period,
Func<HttpContext, ValueTask<string>> discriminator)
: base(name, discriminator)
{
Limit = limit;
Period = period;
}
private Func<HttpContext, ValueTask<int>> Limit { get; }
private Func<HttpContext, ValueTask<TimeSpan>> Period { get; }
public async Task<bool> Matches(HttpContext context, IDistributedCache cache)
{
var discriminator = await Predicate.Invoke(context);
if (string.IsNullOrEmpty(discriminator))
{
return false;
}
var period = await Period.Invoke(context);
var limit = await Limit.Invoke(context);
var key = $"{Name}:{discriminator}";
var count = await cache.CountAsync(key, period, context.RequestAborted);
return count > limit;
}
}
}
}
|
fb16cc9242e17f8a1acfd4c03a804a2d17b9195b
|
C#
|
Kulawy/NineMensMorris
|
/NineMensMorrisBack/Model/Morris.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NineMensMorrisBack.Model
{
public class Morris
{
public int Id { get; }
public Tile One { get; set; }
public Tile Two { get; set; }
public Tile Three { get; set; }
public Morris(int id)
{
Id = id;
}
public override bool Equals(object obj)
{
bool flag;
Morris compering = obj as Morris;
if( One.Equals(compering.One) && Two.Equals(compering.Two) && Three.Equals(compering.Three))
{
flag = true;
}
else if (One.Equals(compering.Two) && Two.Equals(compering.One) && Three.Equals(compering.Three))
{
flag = true;
}
else if (One.Equals(compering.One) && Two.Equals(compering.Three) && Three.Equals(compering.Two))
{
flag = true;
}
else if (One.Equals(compering.Three) && Two.Equals(compering.Two) && Three.Equals(compering.One))
{
flag = true;
}
else if (One.Equals(compering.Two) && Two.Equals(compering.Three) && Three.Equals(compering.One))
{
flag = true;
}
else if (One.Equals(compering.Three) && Two.Equals(compering.One) && Three.Equals(compering.Two))
{
flag = true;
}
else
{
flag = false;
}
return flag;
}
}
}
|
0c24741171cff22925c783e9d4c724556d13df09
|
C#
|
SoCreate/service-fabric-distributed-cache
|
/examples/Services/ClientApp/Controllers/CacheDemoController.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
namespace ClientApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CacheDemoController : ControllerBase
{
private readonly IDistributedCache _distributedCache;
public CacheDemoController(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
[HttpGet("SetSlidingCacheItem")]
public async Task<ActionResult<string>> SetSlidingCacheItem()
{
var options = new DistributedCacheEntryOptions();
options.SlidingExpiration = TimeSpan.FromSeconds(20);
await _distributedCache.SetAsync("SlidingCacheItem", Encoding.UTF8.GetBytes(DateTime.Now.ToString()), options);
return new EmptyResult();
}
[HttpGet("GetSlidingCacheItem")]
public async Task<ActionResult<string>> GetSlidingCacheItem()
{
var bytes = await _distributedCache.GetAsync("SlidingCacheItem");
if (bytes != null)
return Content(Encoding.UTF8.GetString(bytes));
return new EmptyResult();
}
[HttpGet("SetAbsoluteExpirationCacheItem")]
public async Task<ActionResult<string>> SetAbsoluteExpirationCacheItem()
{
var options = new DistributedCacheEntryOptions();
options.AbsoluteExpiration = DateTime.Now.AddSeconds(20);
await _distributedCache.SetAsync("AbsoluteExpirationCacheItem", Encoding.UTF8.GetBytes(DateTime.Now.ToString()), options);
return new EmptyResult();
}
[HttpGet("GetAbsoluteExpirationCacheItem")]
public async Task<ActionResult<string>> GetAbsoluteExpirationCacheItem()
{
var bytes = await _distributedCache.GetAsync("AbsoluteExpirationCacheItem");
if (bytes != null)
return Content(Encoding.UTF8.GetString(bytes));
return new EmptyResult();
}
[HttpGet("{key}")]
public async Task<ActionResult<string>> Get(string key)
{
var bytes = await _distributedCache.GetAsync(key);
if(bytes != null)
return Content(Encoding.UTF8.GetString(bytes));
return new EmptyResult();
}
[HttpPut("{key}")]
public async Task Put(string key)
{
var request = HttpContext.Request;
using (var reader = new StreamReader(request.Body))
{
var content = await reader.ReadToEndAsync();
var options = new DistributedCacheEntryOptions();
options.SlidingExpiration = TimeSpan.FromDays(1);
await _distributedCache.SetAsync(key, Encoding.UTF8.GetBytes(content), options);
}
}
[HttpDelete("{key}")]
public async Task Delete(string key)
{
await _distributedCache.RemoveAsync(key);
}
}
}
|
d6c7d53ae57b5d9a2e48bd5018901031a8bf1e4d
|
C#
|
Maxluciani/Entra21-web
|
/Domain/Players/Player.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
namespace Domain
{
public class Player : person
{
public Guid Id { get; private set; } = Guid.NewGuid();
public int Goals {get; private set; }
public Player(string name) : base(name) {}
public (IList<string> Errors,bool IsValid) Validate()
{
var errors = new List<string>();
if(!ValidateName())
{
errors.Add("Nome invalido");
}
return(errors,errors.Count == 0);
}
}
}
|
b3983c2a751b0b3b5ddca63c429a7f16add3c1d9
|
C#
|
dotnet/arcade
|
/src/Microsoft.DotNet.Build.Tasks.Packaging/src/NugetPropertyStringProvider.cs
| 2.65625
| 3
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Collections.Generic;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class NuspecPropertyStringProvider
{
public static Dictionary<string, string> GetNuspecPropertyDictionary(string[] nuspecProperties)
{
if (nuspecProperties == null)
{
return null;
}
var propertyDictionary = new Dictionary<string, string>();
foreach (var propertyString in nuspecProperties)
{
var property = GetKeyValuePair(propertyString);
propertyDictionary[property.Item1] = property.Item2;
}
return propertyDictionary;
}
public static Func<string, string> GetNuspecPropertyProviderFunction(string[] nuspecPropertyStrings)
{
var propertyDictionary = GetNuspecPropertyDictionary(nuspecPropertyStrings);
if (propertyDictionary == null)
{
return null;
}
return k => propertyDictionary[k];
}
private static Tuple<string, string> GetKeyValuePair(string propertyString)
{
propertyString = propertyString.Trim();
var indexOfEquals = propertyString.IndexOf("=", StringComparison.Ordinal);
if (indexOfEquals == -1)
{
throw new InvalidDataException($"Nuspec property {propertyString} does not have an \'=\' character in it");
}
if (indexOfEquals == propertyString.Length - 1)
{
throw new InvalidDataException($"Nuspec property {propertyString} does not have a value");
}
if (indexOfEquals == 0)
{
throw new InvalidDataException($"Nuspec property {propertyString} does not have a key");
}
var key = propertyString.Substring(0, indexOfEquals);
var valueStartIndex = indexOfEquals + 1;
var valueLength = propertyString.Length - valueStartIndex;
var value = propertyString.Substring(valueStartIndex, valueLength);
return new Tuple<string, string>(key, value);
}
}
}
|
edb608bfb0437479b3c67ab3340cc44db8de715c
|
C#
|
LukeStanislaus/SailingWeb
|
/SQL.cs
| 3.140625
| 3
|
using Dapper;
using SailingWeb.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
namespace SailingWeb
{
public static class Sql
{
private static string _race = Program.Globals.RacenameTable;
/// <summary>
/// Returns a stored procedure that returns all classes from boat data db.
/// </summary>
/// <returns>List of all classes.</returns>
public static List<string> ReturnClass()
{
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
// Runs query.
return connection.Query<string>("call returnclass").ToList();
}
}
/// <summary>
/// Returns a list of all the distinct names in the fulllist db. Used a array due to
/// compatibility with javascript.
/// </summary>
/// <returns>List of names.</returns>
public static String[] GetNames()
{
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
// Returns a list of all the distinct names in the fulllist db.
string[] listOfNames = connection.Query<string>("call returnnames").Distinct().ToArray();
return listOfNames;
}
}
/// <summary>
/// Returns the list of racers
/// </summary>
/// <returns>Returns boat data, including if the person is a crew or not.</returns>
public static List<BoatsRacing> GetRacers()
{
// Tables names cannot have spaces.
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
// Appends together the query. Stops SQL injection.
var sql1 = new StringBuilder();
sql1.Append("select * from ");
sql1.Append(_race);
sql1.Append(";");
return connection.Query<BoatsRacing>(sql1.ToString()).ToList();
}
}
/// <summary>
/// Get boats of a specific person.
/// </summary>
/// <param name="name">Person to search for boats.</param>
/// <returns></returns>
public static List<Boats> GetBoats(string name)
{
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
//Runs stored procedure.
return connection.Query<Boats>("call returnboatsspecific(@name)", new
{ name = name }).ToList();
}
}
/// <summary>
/// Gets the list of distinct boats which have been sailed before.
/// </summary>
/// <returns>Array of all boats used before.</returns>
public static String[] GetBoats()
{
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
// Query.
return connection.Query<string>("call returnboats").Distinct().ToArray();
}
}
/// <summary>
/// Adds a new boat/person
/// </summary>
/// <param name="boat">Boat data to add.</param>
public static void SetNewFullBoat(Boats boat)
{
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
//Appends together the query, stops SQL injection.
var sql = new StringBuilder();
sql.Append("insert into fulllist values ('");
sql.Append(boat.Name);
sql.Append("', '");
sql.Append(boat.BoatName);
sql.Append("', ");
sql.Append(boat.BoatNumber);
sql.Append(");");
// Query.
connection.Query(sql.ToString());
}
}
/// <summary>
/// Removes boats, knows if they are crew or not.
/// </summary>
/// <param name="boat"></param>
public static void RemoveBoats(Boats boat)
{
// Cannot have table name with space
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
// Creates query.
var sql1 = new StringBuilder();
sql1.Append("select * from ");
sql1.Append(_race);
sql1.Append(" where boat ='");
sql1.Append(boat.BoatName);
sql1.Append("' and boatNumber=");
sql1.Append(boat.BoatNumber);
sql1.Append(" and crew=1;");
try
{
var name = connection.Query<BoatsRacing>(sql1.ToString()).FirstOrDefault().Name;
var sql = new StringBuilder();
sql.Append("delete from ");
sql.Append(_race);
sql.Append(" where name ='");
sql.Append(boat.Name);
sql.Append("';");
connection.Query(sql.ToString());
sql = new StringBuilder();
sql.Append("delete from ");
sql.Append(_race);
sql.Append(" where name ='");
sql.Append(name);
sql.Append("';");
connection.Query(sql.ToString());
}
catch
// Else just remove them.
{
var sql = new StringBuilder();
sql.Append("delete from ");
sql.Append(_race);
sql.Append(" where name ='");
sql.Append(boat.Name);
sql.Append("';");
connection.Query(sql.ToString());
}
}
}
/// <summary>
/// Inserts sailor into a named race.
/// </summary>
/// <param name="boat">Boat data of person to add.</param>
/// <param name="crew">Are they crew?</param>
private static void InsertInto(Boats boat, int crew)
{
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
var sql = new StringBuilder();
sql.Append("insert into ");
sql.Append(_race);
sql.Append(" values('");
sql.Append(boat.Name);
sql.Append("','");
sql.Append(boat.BoatName);
sql.Append("',");
sql.Append(boat.BoatNumber);
sql.Append(",");
sql.Append(crew);
sql.Append(");");
connection.Query(sql.ToString());
}
}
/// <summary>
/// Adds boats to the race db. Runs logic for for whether they have crew or not.
/// </summary>
/// <param name="boat"></param>
public static void SetBoats(Boats boat)
{
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
// If they don't have crew remove single.
if (Program.Globals.Crew == null)
{
// Try to add them.
try
{
InsertInto(boat, 0);
}
// Else add new DB for new race then add them
catch
{
var sql = new StringBuilder();
sql.Append("CREATE TABLE if not exists ");
sql.Append(_race);
sql.Append(
" (`name` varchar(50) NOT NULL,`boat` varchar(50) DEFAULT NULL," +
"`boatNumber` int(11) DEFAULT NULL," +
"`crew` int(1) DEFAULT NULL,PRIMARY KEY(`name`)) ENGINE = InnoDB DEFAULT CHARSET" +
" = utf8mb4;");
connection.Execute(sql.ToString());
InsertInto(boat,0);
}
}
//Else remove both.
else
{
// Try to add one person.
try
{
InsertInto(boat,0);
}
// Else create db and then add person.
catch
{
var sql = new StringBuilder();
sql.Append("CREATE TABLE if not exists ");
sql.Append(_race);
sql.Append(
" (`name` varchar(50) NOT NULL,`boat` varchar(50) DEFAULT NULL," +
"`boatNumber` int(11) DEFAULT NULL," +
"`crew` int(1) DEFAULT NULL,PRIMARY KEY(`name`)) ENGINE = InnoDB DEFAULT CHARSET" +
" = utf8mb4;");
connection.Execute(sql.ToString());
InsertInto(boat,0);
}
// In every case we will add the second without fail.
// finally
// {
var boats1 = new Boats(Program.Globals.Crew, boat.BoatName, boat.BoatNumber);
InsertInto(boats1,1);
// }
}
}
}
/// <summary>
/// Returns the number of crew a boat has.
/// </summary>
/// <param name="boatName">Class of boat</param>
/// <returns>The number of crew a particular boat has.</returns>
public static int GetCrew(string boatName)
{
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
return connection.Query<int>("call returncrew(@boatName)", new{boatName = boatName}).FirstOrDefault();
}
}
/// <summary>
/// Inserts into the db calendar a single event.
/// </summary>
/// <param name="cal">A single event.</param>
public static void Newcalendar(Calendar cal)
{
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
connection.Query("call newcalendar(@summary, @description, @date)", new
{
summary = cal.Summary,
description = cal.Description,
date = cal.DateTime
});
}
}
/// <summary>
/// Finds what events are on today with stored procedure.
/// </summary>
/// <returns>List of events on a particular day.</returns>
public static List<Calendar> Todaysevent()
{
using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal()))
{
var value = connection.Query<Calendar>("call todaysevent").ToList();
return value;
}
}
}
}
|
8c6bb2861fe3a4c6507f4f44198ff24510541cef
|
C#
|
cbirkeland/Plugg
|
/vecka1/Övningar-dag-2-c#/4.3-Validation-KLAR.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp53
{
class Program
{
static void Main(string[] args)
{
string[] peopleArray; // Skapar Array direkt
string separator = AskUserForSeparator();
bool error = AskUserForErrorMessage();
while (true) // När vi inte vet hur många gånger användaren kommer skriva fel.
// While true betyder evig loop.
{
string svar = GetInput();
peopleArray = MinArray(svar, separator); // Här används arrayen först och string svar ovan.
CleanArray(peopleArray); // Efter MinArray går det till CleanArray. Hänvisa parameter till arrayen peopleArray.
if (ValideraArray(peopleArray, error))
{
break;
}
}
SvaraUser(peopleArray);
}
private static string GetInput()
{
Console.Write("Skriv in namn: ");
string name = Console.ReadLine();
return name;
}
private static string[] MinArray(string svar, string separator) // Här börjar Arrayen, glöm ej []
{
if (separator.Length == 0)
{
string[] list = svar.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return list;
}
else
{
string[] list2 = svar.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);
return list2;
}
}
private static void SvaraUser(string[] peopleArray)
{
// Lägger till if-sats för om man inte skriver något namn alls
if (peopleArray.Length == 0)
{
Console.WriteLine("Saknas namn i listan");
return;
}
// Lägger till Foreach-sats. Där varje namn Trimmas och får ToUpper.
foreach (string item in peopleArray)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"***SUPER-{item.ToUpper()}***");
}
}
private static void CleanArray(string[] peopleArray)
{
for (int i = 0; i < peopleArray.Length; i++) // Glöm ej .Length !!!!
{
peopleArray[i] = peopleArray[i].Trim();
}
}
private static bool ValideraArray(string[] peopleArray, bool error)
{
if (peopleArray.Length == 0) // Ensam if-sats för om du inte skriva några bokstäver
{
if (error == true)
{
Console.WriteLine("Du skrev inga bokstäver");
}
return false;
}
foreach (string item in peopleArray) // foreach-sats med if-sats med krav på antal bokstäver
{
if (item.Length <= 1 || item.Length >= 10)
{
if (error == true)
{
Console.WriteLine("Namnet måste vara mellan 2-9 bokstäver");
}
return false;
}
}
return true;
}
private static string AskUserForSeparator()
{
Console.Write("Which separator would you like to use?: ");
string separator = (Console.ReadLine());
return separator;
}
private static bool AskUserForErrorMessage()
{
Console.WriteLine("Do you want to see error messages?");
string check = (Console.ReadLine());
if (check == ("no"))
{
return false;
}
return true;
}
//private static bool AskForErrorMessage()
//{
// Console.Write("Do you want to see error messages (default is yes)");
}
}
|
83d3c8d0f2cdd50095c4fba3cc4a47c1b824b012
|
C#
|
AngeloMelo/DDDReact
|
/DDD.Infra.Data/Repositories/RepositoryBase.cs
| 2.71875
| 3
|
using DDD.Domain.Contracts.Repositories;
using DDD.Infra.Data.Context;
using System;
//using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DDD.Infra.Data.Repositories
{
public class RepositoryBase<TEntity> : IDisposable, IRepositoryBase<TEntity> where TEntity : class
{
protected DDDContext db;
public RepositoryBase(DDDContext ctx)
{
this.db = ctx;
}
public void Add(TEntity obj)
{
db.Set<TEntity>().Add(obj);
db.SaveChanges();
}
public void Dispose()
{
}
public IEnumerable<TEntity> GetAll()
{
return db.Set<TEntity>().ToList();
}
public TEntity GetById(int id)
{
return db.Set<TEntity>().Find(id);
}
public void Remove(TEntity obj)
{
db.Set<TEntity>().Remove(obj);
db.SaveChanges();
}
public void Update(TEntity obj)
{
db.Set<TEntity>().Update(obj);
//db.Entry(obj).State = EntityState.Modified;
db.SaveChanges();
}
}
}
|
d95b1cf6960506b4b68c6f54ea809ffa11fca1b1
|
C#
|
kobraks/Callender
|
/Client/Connection.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using Core;
namespace Client
{
public class Connection : IDisposable
{
TcpClient client = new TcpClient();
NetworkStream stream = null;
bool disposed = false;
public Connection() { }
public void Connect(string ip, int port)
{
try
{
client.Connect(ip, port);
}
catch(Exception)
{
return;
}
stream = client.GetStream();
}
public void Disconnect()
{
stream.Dispose();
client.Close();
}
public void Send(string[] message)
{
Packet packet = new Packet();
foreach(var obj in message)
{
packet.Add(obj);
}
packet.Send(client);
}
public string[] Answer()
{
Packet packet = new Packet();
packet = packet.Take(client);
return packet.List;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
Disconnect();
}
disposed = true;
}
}
}
|
b04bd7698a50339d76ce8202535e280a4d376de1
|
C#
|
fatihkucukkara/EFGRApiDemo
|
/EFGRApiDemo.Dal/Repositories/GenericRepository.cs
| 2.875
| 3
|
using EFGRApiDemo.Dal.Base.Interfaces;
using EFGRApiDemo.Data.Context;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;
using System.Linq;
namespace EFGRApiDemo.Dal.Repositories
{
public class GenericRepository<T> : IRepository<T> where T : class
{
private readonly DbContext _context;
private DbSet<T> _entities;
public GenericRepository(SchoolContext context)
{
_context = context;
}
public void Delete(T entity)
{
if (entity == null)
throw new ArgumentNullException(nameof(entity));
try
{
Entities.Remove(entity);
_context.SaveChanges();
}
catch (DbUpdateException exception)
{
throw new Exception("");
}
}
//public void Delete(T entity)
//{
// _context.Set<T>().Remove(entity);
// _context.SaveChanges();
//}
public T GetById(int Id)
{
return Entities.Find(Id);
}
public int Insert(T entity)
{
if (entity == null)
throw new ArgumentNullException();
Entities.Add(entity);
//_context.Set<T>().Add(entity);
var id =_context.SaveChanges();
return id;
}
public void Insert(IEnumerable<T> entities)
{
if (entities == null)
throw new ArgumentNullException();
Entities.AddRange(entities);
_context.SaveChanges();
}
public virtual void Update(T entity)
{
if (entity == null)
throw new ArgumentNullException();
Entities.AddOrUpdate(entity);
_context.SaveChanges();
}
public IQueryable<T> Table => Entities;
protected virtual DbSet<T> Entities
{
get
{
if (_entities == null)
_entities = _context.Set<T>();
return _entities;
}
}
}
}
|
6ba26b9f46d980adc112d1c508908f97a94158bb
|
C#
|
hrimar/MyFirstOwnWebProject-FishSpinDays
|
/FishSpinDays/FishSpinDays.Web/Common/ApplicationBuilderAuthExtensions.cs
| 2.625
| 3
|
namespace FishSpinDays.Web.Common
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using FishSpinDays.Common.Constants;
using FishSpinDays.Models;
using Microsoft.Extensions.DependencyInjection;
using FishSpinDays.Data;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System;
using System.IO;
using Newtonsoft.Json;
using FishSpinDays.Common.Admin.ViewModels;
using System.Collections.Generic;
public static class ApplicationBuilderAuthExtensions
{
private const string DefaultAdminPasswprd = WebConstants.DefaultAdminPassowrd;
private static readonly IdentityRole[] roles =
{
new IdentityRole(WebConstants.AdminRole)
};
public static async void SeedDatabase(this IApplicationBuilder app)
{
var serviceFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
var scope = serviceFactory.CreateScope();
using (scope)
{
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<User>>();
foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role.Name))
{
var result = await roleManager.CreateAsync(role);
}
}
var admin = await userManager.FindByNameAsync("admin");
if (admin == null)
{
admin = new User()
{
UserName = "admin",
Email = "admin@example.com"
};
var result = await userManager.CreateAsync(admin, DefaultAdminPasswprd);
result = await userManager.AddToRoleAsync(admin, roles[0].Name);
}
// -----seed of main sections and sections:
var context = scope.ServiceProvider.GetService<FishSpinDaysDbContext>();
context.Database.Migrate();
if (!context.MainSections.Any())
{
var jsonMainSections = File.ReadAllText(@"wwwroot\seedfiles\mainsections.json");
var mainSectionDtos = JsonConvert.DeserializeObject<MainSectionDto[]>(jsonMainSections);
SeedMainSections(context, mainSectionDtos);
}
//-----seed of publication:
if (!context.Publications.Any())
{
SeedPublication(context);
}
}
}
private static void SeedMainSections(FishSpinDaysDbContext context, MainSectionDto[] mainSectionDtos)
{
var mainSectionToCreate = mainSectionDtos
.Select(ms => new MainSection
{
Name = ms.Name,
Sections = ms.Sections.Select(s => new Section
{
Name = s
}).ToArray()
}).ToArray();
context.MainSections.AddRange(mainSectionToCreate);
context.SaveChanges();
}
private static void SeedPublication(FishSpinDaysDbContext context)
{
var author = context.Users.FirstOrDefault(u => u.UserName == "admin");
var seaPublication = new Publication()
{
SectionId = 1,
Author = author,
Title = "Sardinia: Holy Land",
Description = @"How many times have we heard call our island HOLY LAND … how many times have we smug smile at the name aware of some nice catches … but how many times have we cursed his marine sterility … Often the holy land has asked “our blood”, night sleep of a few hours, cold water, burning sun, wind and launches with an average of missed catch really embarrassing. That’s why the holy land has defined as such, needs sacrifice …The days of easy catches are gone, indeed ever known. This report will be a tribute of images and colors to my land surrounded by some “fish” few words but many pictures. Unfortunately I go fishing only with my phone (in addition to rod and lures), otherwise the spectacle of nature, with a camera, would have come out in all its glory .." +
"<img src=\"http://www.seaspin.com/eng/wp-content/uploads/2015/11/TS32-.jpg\" style=\"width: 40%; float: left;\">" +
"The beauty of sunrises and sunsets … that is the holy land!!!!Nature gives us details of which I didn’t even know the existence.Moving on cliffs or through vegetation often happens to come across creatures that seem to come from the Amazon rainforest.Let’s say that the variety of fish is not lacking," +
"from small amberjack to greenhouse, from sea bass to dorado, from bonitos to the barracudas …" +
"This year every corner of the coast for a few days was registered in green gold, even dolphinfish lost its charm for the ease with which you could catch it.Last year or two years ago however very few managed so… I still remember well the bad feeling I had seeing them follow any kind of lure without attacking: I could have smashed the rod on the rocks.Then the choice of fishing with smaller baits sometimes saved me from a washout, making me go home with a pretty stupid smile on my face.",
};
context.Publications.Add(seaPublication);
context.SaveChanges();
}
}
}
|
3adbe50811249c022177e4a07233d05189ee4e3c
|
C#
|
JozefR/CoffeTime
|
/Algorithms/Searching/Binary/Program.cs
| 3.9375
| 4
|
namespace Binary
{
class Program
{
static void Main(string[] args)
{
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
var target = 53;
BinarySearch(primes, target);
BinarySearchRecursion(primes, 3, 0, primes.Length);
}
#region binarySearch
private static int BinarySearch(int[] array, int target)
{
int left = 0;
int right = array.Length - 1;
while (right > left)
{
var guess = (left + right) / 2;
if (array[guess] == target)
{
return guess;
}
if (array[guess] < target)
{
left = guess + 1;
}
else
{
right = guess - 1;
}
}
return -1;
}
#endregion
#region binarySearchRecursion
private static int BinarySearchRecursion(int[] array, int target, int left, int rightIndex)
{
if (left > rightIndex)
return -1;
int middle = (left + rightIndex) / 2;
if (array[middle] == target)
return target;
if (target > array[middle])
return BinarySearchRecursion(array, target, middle + 1, rightIndex);
if (target < array[middle])
return BinarySearchRecursion(array, target, left, middle - 1);
return middle;
}
#endregion
}
}
|
e1bfe985272ae0e9b90d55c048811c8d326785f6
|
C#
|
NikiSpasov/CSharp-Advanced
|
/SetsAndDictionaries/02.SetsOfElements/SetsOfElements.cs
| 3.890625
| 4
|
namespace _02.SetsOfElements
{
using System;
using System.Collections.Generic;
using System.Linq;
class SetsOfElements
{
static void Main()
{
int[] input = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
int lengthFirstSet = input[0];
int lengthSecondSet = input[1];
HashSet<int> firstSet = new HashSet<int>();
HashSet<int> secondSet = new HashSet<int>();
for (int i = 0; i < lengthFirstSet + lengthSecondSet; i++)
{
int n = int.Parse(Console.ReadLine());
if (i < lengthFirstSet)
{
firstSet.Add(n);
continue;
}
secondSet.Add(n);
}
firstSet.IntersectWith(secondSet);
foreach (var number in firstSet)
{
Console.WriteLine(number);
}
}
}
}
|
93725c84e9f8b8910a0216f3864ccf893d065a97
|
C#
|
ghj123h/Taicai
|
/archive/history/2018-19/1-3/190103/code.cs
| 3.015625
| 3
|
// 190103 Key: a/1006/y/1/125.04/5.0
using System;
using System.Collections.Generic;
using TaicaiLib;
namespace Taicai190103
{
public class ProblemFactory
{
public static bool seasonal = true;
public static IEnumerable<Problem> GetProblems()
{
List<Problem> list = new List<Problem>();
Problem tmp;
// Problem 1
tmp = new DefaultProblem("a");
list.Add(tmp);
// Problem 2
tmp = new NumberProblem(1006, 0.8, 1);
list.Add(tmp);
// Problem 3
tmp = new DefaultProblem("y");
list.Add(tmp);
// Problem 4
tmp = new DefaultProblem("1");
list.Add(tmp);
// Problem 5
tmp = new NumberProblem(125.04, NumberProblem.ACE * 2.5);
list.Add(tmp);
// Problem 6
tmp = new OffsetProblem(5.0, 0.87, 0.5);
list.Add(tmp);
return list;
}
// Score Methods
}
}
|
2b47967bbf20ca68347acee4703dcd89ce59c443
|
C#
|
paurbano/TalleresConsola
|
/OReillyFundamentalsDelegados/Program.cs
| 3.421875
| 3
|
using System;
namespace OReillyFundamentalsDelegados
{
/// <summary>
/// Ejemplo de uso de delegados, esta aplicación simula un procesador de imagen y diferentes efectos que un usuario puede aplicarle(opacidad, rotar, recortar,etc..)
/// el usuario puede seleccionar uno o varios y luego aplicarlos en la secuencia seleccionada.
/// Para más información ver:
/// https://msdn.microsoft.com/es-es/library/aa288459(v=vs.71).aspx
/// </summary>
public class Imagen
{
public Imagen()
{
Console.WriteLine("Una Imagen Creada o Cargada");
}
}
//Declaración Delegado
public delegate void AplicarEfecto();
public class ProcesadorImagen
{
//Variables miembro privadas
private AplicarEfecto[] arregloEfectos;
private Imagen imagen;
private int numeroEfectosSeleccionados=0;
//Crea varios delegados estáticos atados a métodos miembro
public AplicarEfecto EfectoDifuminar = new AplicarEfecto(Difuminar);
public AplicarEfecto EfectoFiltro = new AplicarEfecto(Filtro);
public AplicarEfecto EfectoRotar = new AplicarEfecto(Rotar);
public AplicarEfecto EfectoAfilar = new AplicarEfecto(Afilar);
/// <summary>
/// El problema con los delegados estáticos es que deben instanciarse, se usen o no.
/// Se puede mejorar esto haciendo los delegados propiedades de las clases, para asi llamarlos directamente por estas con la ventaja
/// de que el delegado no es creado, sino hasta que es solicitado
/// por ejemplo:
/// public static EfectoDifuminar
/// {
/// get
/// {
/// return new AplicarEfecto(Difuminar);
/// }
/// }
///
/// </summary>
//El constructor inicializa la imagen y el arreglo de afectos a aplicar
public ProcesadorImagen(Imagen imagen)
{
this.imagen = imagen;
arregloEfectos = new AplicarEfecto[10];
}
//Metodos para procesar imagen
//En una aplicación real de tratamiento de imagenes
//estos métodos serían un poco más complejos
public static void Difuminar()
{
Console.WriteLine("Difuminando Imagen!...");
}
public static void Filtro()
{
Console.WriteLine("Filtrando Imagen!...");
}
public static void Rotar()
{
Console.WriteLine("Rotando Imagen...");
}
public static void Afilar()
{
Console.WriteLine("Afilando Imagen...");
}
/// <summary>
/// En una solución real se usaria una colección dinamica, no de tamaño fija
/// </summary>
/// <param name="efecto"></param>
public void AgregarEfectos(AplicarEfecto efecto)
{
if (numeroEfectosSeleccionados >= 10)
throw new Exception("Demasiados Efectos en la lista");
arregloEfectos[numeroEfectosSeleccionados++] = efecto;
}
//Aplicar los efectos a la imagen
public void ProcesarImagen()
{
for (int i = 0; i < numeroEfectosSeleccionados; i++)
{
arregloEfectos[i]();
}
}
}
class Editor
{
static void Main(string[] args)
{
Imagen imagen = new Imagen();
//Cargar los métodos de efectos a aplicar, adicionarlos según se requieran
//Llamar al procesador de imagenes y correr los métodos en el orden seleccionado
//
ProcesadorImagen procesador = new ProcesadorImagen(imagen);
//Instanciación Delegados usando la clase
//Cambiar orden y ver resultado
procesador.AgregarEfectos(procesador.EfectoRotar);
procesador.AgregarEfectos(procesador.EfectoFiltro);
procesador.AgregarEfectos(procesador.EfectoDifuminar);
procesador.AgregarEfectos(procesador.EfectoAfilar);
//Aplicar los efectos deacuerdo al orden creado previamente
//Ejecutar los métodos del arreglo <<arregloEfectos>>
procesador.ProcesarImagen();
}
}
}
|
97d8b0b50290a4c2dbcf23c6f570e22d0b5754ba
|
C#
|
VISAB-ORG/CBR-Shooter
|
/CBRS/Assets/Scripts/TCPIP/ConnectionToPathViewer.cs
| 2.734375
| 3
|
using System;
using UnityEngine;
using System.Net.Sockets;
using System.IO;
using Assets.Scripts.Util;
using Assets.Scripts.CBR.Model;
using System.Threading;
using System.Text;
using Assets.Scripts.AI;
namespace Assets.Scripts.TCPIP
{
/**
* Diese Klasse stellt die Verbindung via TCP/IP zum Java Projekt her.
*/
public class ConnectionToPathViewer
{
/**
* TCP-Client
*/
private TcpClient mClient;
/**
* Data Stream.
*/
private Stream mStream;
/**
* Diese Methode stellt konkret die Verbindung her.
*/
private void InitiateConnection()
{
mClient = new TcpClient();
mClient.Connect(Constants.HOST_ADDRESS, 5558);
mStream = mClient.GetStream();
}
~ConnectionToPathViewer()
{
Console.WriteLine("Connection closed");
CloseConnection();
}
/**
* Diese Methode schließt die Verbindung zwischen C# und Java.
*/
private void CloseConnection()
{
if (mClient != null && mClient.Connected)
{
Console.WriteLine("Shutting down TCP/IP");
mClient.Close();
}
}
/**
* Diese Methode sendet die gesammelten Daten des Frame an das Java-Projekt.
*/
public StatisticsForPathViewer Send(StatisticsForPathViewer statistics)
{
InitiateConnection();
string json = JsonParser<StatisticsForPathViewer>.SerializeObject(statistics) + Environment.NewLine;
ASCIIEncoding asen = new ASCIIEncoding();
byte[] data = asen.GetBytes(json);
mStream.Write(data, 0, data.Length);
Thread.Sleep(100);
CloseConnection();
return statistics;
}
}
}
|
8807c7b7806bd0c7f7faa5054ec82af6451d71b1
|
C#
|
howie1329/LifeSims2
|
/Data/BadActs.cs
| 3.234375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Console = System.Console;
namespace LifeSims2.Data
{
class BadActs
{
public string BadActsName { get; set; }
public void BadActsMenu()
{
Console.Clear();
const string menuitem = "================Bad Acts================";
const string menuitem1 = "Drinking";
const string menuitem2 = "Drugs";
Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem.Length / 2) + "}", menuitem);
Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem1.Length / 2) + "}", menuitem1);
Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem2.Length / 2) + "}", menuitem2);
Console.WriteLine("What are you going to do?");
BadPick();
}
public void BadPick()
{
var ActInput = Console.ReadLine();
switch (ActInput.ToLower())
{
case "drinking":
Drinking();
break;
case "drugs":
Drugs();
break;
default:
BadActsMenu();
break;
}
}
public void Drinking()
{
const string menuitem = "================Drink Menu================";
const string menuitem1 = "Beer";
const string menuitem2 = "Whiskey";
const string menuitem3 = "Vodka";
Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem.Length / 2) + "}", menuitem);
Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem1.Length / 2) + "}", menuitem1);
Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem2.Length / 2) + "}", menuitem2);
Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem3.Length / 2) + "}", menuitem3);
}
public void Drugs()
{
const string menuitem = "================Drugs================";
const string menuitem1 = "Weed";
const string menuitem2 = "Crack";
Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem.Length / 2) + "}", menuitem);
Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem1.Length / 2) + "}", menuitem1);
Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem2.Length / 2) + "}", menuitem2);
}
}
}
|
080fca87d7be50d77c26699a726118ac057a360a
|
C#
|
Maoni0/docs
|
/docs/csharp/programming-guide/concepts/linq/codesnippet/CSharp/introduction-to-linq-queries_3.cs
| 2.84375
| 3
|
// Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
|
78b2154a21afd7abf280b37d52e10696580557b3
|
C#
|
dteixeir/food-truck
|
/api/DataLayer/Managers/AuthManager.cs
| 2.734375
| 3
|
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using api.Domain;
using api.DataLayer.Interfaces;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.Extensions.Configuration;
using System.Security.Claims;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace api.DataLayer
{
using BCrypt = BCrypt.Net.BCrypt;
public class AuthManager : IAuthManager {
private ApplicationDbContext _context;
private IConfiguration _config;
private IBaseManager _baseManager;
private IUserManager _userManager;
public AuthManager(
ApplicationDbContext context,
IConfiguration config,
IBaseManager baseManager,
IUserManager userManager)
{
_context = context;
_config = config;
_baseManager = baseManager;
_userManager = userManager;
}
public async Task<string> Authenticate(string username, string password) {
User user = await _userManager.GetUser(username);
if(user == null ){
throw new Exception("Invalid credentials");
}
return BCrypt.Verify(password, user?.Password) ? await BuildToken(user) : null;
}
// register and piggyback into authenticate?
public async Task<User> Register(User entity) {
if(await _userManager.GetUser(entity.Username) != null) {
throw new Exception("Username is taken, please choose another one.");
}
entity.Id = Guid.NewGuid();
entity.Password = BCrypt.HashPassword(entity.Password);
entity.CreateDateTime = DateTime.UtcNow;
entity.IsActive = true;
entity.IsDeleted = false;
entity.CreateUserId = entity.Id;
await _baseManager.Add(entity);
return entity;
}
public bool HasClaim(string token, string claimValue) {
var tokenReader = new JwtSecurityTokenHandler();
var tokenBody = token.Split("Bearer ")[1];
var decodedToken = tokenReader.ReadJwtToken(tokenBody);
var hasClaim = decodedToken.Claims.FirstOrDefault(claim => claim.Value == claimValue);
return hasClaim != null;
}
private async Task<string> BuildToken(User user)
{
List<Claim> claims = new List<Claim> {
new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName),
new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim("User_Id", user.Id.ToString()),
new Claim("User_Email", user.Email)
};
var roles = await _userManager.GetRoles(user);
foreach(Role role in roles) {
claims.Add(new Claim(ClaimTypes.Role, role.Name));
}
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
private string EncryptPassword(string password) {
// generate a 128-bit salt using a secure PRNG
byte[] salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
// derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 10000,
numBytesRequested: 256 / 8));
Console.WriteLine($"Hashed: {hashed}");
return hashed;
}
}
}
|
8d5fd58067a9710c5ef0595df88304489af0b5de
|
C#
|
shendongnian/download4
|
/code4/583225-13642986-32546975-1.cs
| 3.3125
| 3
|
public ArrayList FindDuplicateRows(DataTable dTable, string colName)
{
Hashtable hTable = new Hashtable();
ArrayList duplicateList = new ArrayList();
//add duplicate item value in arraylist.
foreach (DataRow drow in dTable.Rows)
{
if (hTable.Contains(drow[colName]))
duplicateList.Add(drow);
else
hTable.Add(drow[colName], string.Empty);
}
return duplicateList;
}
|
a915c9dec479e11bfeba0ca1f64b8c2c7cccb298
|
C#
|
DeanZhouLin/BackendPrjs_BaseLibrary
|
/Com.BaseLibrary.Common/Collection/IKeyedList.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
namespace Com.BaseLibrary.Collection
{
/// <summary>
/// Represents a collection of IKeyedObject that can be accessed by index.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IKeyedList<TKey, TItem> : ICollection<TItem> where TItem : IKeyedItem<TKey>
{
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
TItem this[int index] { get; }
/// <summary>
/// Gets or sets the element with the specified key value.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
TItem this[TKey key] { get; }
/// <summary>
/// Gets the item by key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
TItem GetItemByKey(TKey key);
/// <summary>
/// Indicates if the collection contains an object with the specified key value.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
bool Contains(TKey key);
}
}
|
b08a0036600211b7e69464f3f5db0306112189e3
|
C#
|
sms-apps/faalon
|
/source/ConsoleGame/ConsoleGame.Engine/IScreenBuffer.cs
| 2.546875
| 3
|
using ConsoleGame.Engine.Core;
namespace ConsoleGame.Engine
{
public interface IScreenBuffer
{
void Clear();
string Retrieve();
//char Retrieve(SimplePoint point);
//string Retrieve(SimplePoint point, int length);
void Store(char input, SimplePoint point);
void Store(string input, SimplePoint point);
}
}
|
e954283d600ea7ab7ab5c1b9904b17af316e4e8a
|
C#
|
AngleSharp/AngleSharp
|
/src/AngleSharp/Html/Dom/Events/ModifierExtensions.cs
| 2.796875
| 3
|
namespace AngleSharp.Html.Dom.Events
{
using System;
/// <summary>
/// A couple of useful extensions for the modifier list.
/// </summary>
static class ModifierExtensions
{
public static Boolean IsCtrlPressed(this String modifierList)
{
return false;
}
public static Boolean IsMetaPressed(this String modifierList)
{
return false;
}
public static Boolean IsShiftPressed(this String modifierList)
{
return false;
}
public static Boolean IsAltPressed(this String modifierList)
{
return false;
}
public static Boolean ContainsKey(this String modifierList, String key)
{
return modifierList.Contains(key);
}
}
}
|
7b5107d2512ae4a1c464a49621101be1e482b31a
|
C#
|
SHSongs/CowardGame
|
/assassin/Assets/Script/player/Move.cs
| 2.609375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
private Rigidbody2D _rigidbody2D;
public float speed = 1;
// Start is called before the first frame update
void Start()
{
_rigidbody2D = this.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Vector3 move = new Vector3();
move.x = speed * Input.GetAxis("Horizontal");
move.y = speed * Input.GetAxis("Vertical");
this.transform.position += move;
}
private void GetAxis(string v)
{
throw new NotImplementedException();
}
}
|
21853f73ea7eb5ae3af5c87a015f671b0c331d6d
|
C#
|
CorinaCiocanea/TrainingCSharp
|
/Homework 9/CodeFirst/CodeFirst/Program.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace CodeFirst
{
class Program
{
static void Main(string[] args)
{
using (var db = new SampleData())
{
// Console.Write("Enter a name for a new Blog: ");
var x = db.Database.Connection.ConnectionString;
// var name = Console.ReadLine();
var studentList = new List<Student>()
{
new Student { LastName = "Ion", FirstName = "Marin", BirthDate = new DateTime(1991, 3, 17), CNP = 1278748322, Specialization = Specializations.English, Notess = new List<Note>()
{
new Note {Grade = 6, Material=Materials.Computer_networks},
new Note {Grade = 9, Material=Materials.POO}
}},
new Student { LastName = "Maria", FirstName = "Vasi", BirthDate = new DateTime(1990, 6, 10), CNP = 23278748322, Specialization = Specializations.Geography, Notess = new List<Note>()
{
new Note {Grade = 10, Material=Materials.Database},
new Note {Grade = 9, Material=Materials.POO}
}},
new Student { LastName = "Vicky", FirstName = "Max", BirthDate = new DateTime(1993, 4, 20), CNP = 13178748322, Specialization = Specializations.Informatics, Notess = new List<Note>()
{
new Note {Grade = 8, Material=Materials.Computer_networks},
new Note {Grade = 9, Material=Materials.Database}
}},
new Student { LastName = "Max", FirstName = "Marin", BirthDate = new DateTime(1991, 9, 11), CNP = 1278748343, Specialization = Specializations.Sociology, Notess = new List<Note>()
{
new Note {Grade = 5, Material=Materials.Computer_networks},
new Note {Grade = 9, Material=Materials.POO}
}},
new Student { LastName = "Merlin", FirstName = "Ieremia", BirthDate = new DateTime(1999, 3, 16), CNP = 1278748566, Specialization = Specializations.History, Notess = new List<Note>()
{
new Note {Grade = 8, Material=Materials.Database},
new Note {Grade = 9, Material=Materials.POO}
}}
};
foreach (var stud in studentList)
{
db.Studentss.Add(stud);
}
db.SaveChanges();
var query = from b in db.Studentss
orderby b.LastName
select b;
Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
Console.WriteLine(item.LastName);
}
IEnumerable<Student> a2 = from item2 in db.Studentss
where item2.Specialization == Specializations.English
orderby item2.BirthDate descending
select item2;
foreach (var item in a2)
{
Console.WriteLine(item.FirstName);
}
IEnumerable<Student> a3 = from item2 in db.Studentss
where item2.Specialization == Specializations.English
orderby item2.YearOfStudy descending
select item2;
foreach (var item in a3)
{
Console.WriteLine(item.FirstName);
}
//var average1 = from aver in db.Notess
// group aver by aver.Id into averGroup
// select new
// {
// Name = averGroup.Key,
// AverScor = averGroup.Average(x => x.Grade),
// };
//var average2 = from aver2 in db.Studentss
// group aver2 by aver2.FirstName
// into Average(aver2.
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
}
|
eec76f7d9fbdffa61e9eb40ade28293d69dac280
|
C#
|
lefterisdiakakis/MisterApplicationsAPI
|
/Persistance/BaseHttplClient.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Persistance
{
public abstract class BaseHttplClient : IDisposable
{
private static object _locker = new object();
private static volatile HttpClient _client;
public static HttpClient Client
{
get
{
if (_client == null)
{
lock (_locker)
{
if (_client == null)
{
HttpClientHandler _handler = new HttpClientHandler();
_handler.AllowAutoRedirect = false;
_handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
_client = new HttpClient(_handler);
}
}
}
return _client;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_client != null)
{
_client.Dispose();
}
_client = null;
}
}
}
}
|
022df85d3fbce4738bbc76ad28665f18c6eab679
|
C#
|
nhonduyen/designpatter
|
/Prototype/ShapeCache.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace Prototype
{
class ShapeCache
{
public static Dictionary<int, Shape> shapeMap = new Dictionary<int, Shape>();
public static Shape getShape(int id)
{
Shape cachedShape;
if (!shapeMap.TryGetValue(id, out cachedShape))
return null;
return (Shape)cachedShape.Clone();
}
public static void loadCache()
{
DataTable shapes = mgrDataSQL.ExecuteStoreReader("GET_ALL_SHAPE");
for (int i = 0; i < shapes.Rows.Count; i++ )
{
string type = shapes.Rows[i]["type"].ToString().Trim().ToLower();
switch (type)
{
case "rectangle":
Rectangle rec = new Rectangle();
rec.setId(Convert.ToInt32(shapes.Rows[i]["id"]));
shapeMap.Add(rec.getId(), rec);
break;
case "circle":
Circle cir = new Circle();
cir.setId(Convert.ToInt32(shapes.Rows[i]["id"]));
shapeMap.Add(cir.getId(), cir);
break;
case "square":
Square square = new Square();
square.setId(Convert.ToInt32(shapes.Rows[i]["id"]));
shapeMap.Add(square.getId(), square);
break;
}
}
}
}
}
|
6eb2ad6dc73c7c9648123cc19527e3577c94efe9
|
C#
|
sergiorykov/Caramba
|
/src/Caramba/Generators/OffsetIndexGenerator.cs
| 2.8125
| 3
|
using System;
namespace Caramba
{
public class OffsetIndexGenerator : IIndexGenerator
{
private readonly IIndexGenerator _generator;
private readonly int _offset;
public OffsetIndexGenerator(int offset, IIndexGenerator generator)
{
if (generator == null)
throw new ArgumentNullException(nameof(generator));
_offset = offset;
_generator = generator;
}
public int Next()
{
return _offset + _generator.Next();
}
}
}
|
eaa005bf97e2f87a55acbb7c6931711e1834b661
|
C#
|
stevelinz/A6_Media_Abstract_Classes_Linz
|
/Program.cs
| 2.734375
| 3
|
namespace A6_MovieOO.Models
{
public class Program
{
static void Main(string[] args)
{
GoAgain:
System.Console.WriteLine("View: [M]ovie, [S]how, [V]ideo, [E]xit");
string typePick = System.Console.ReadLine();
if (typePick == "V" || typePick == "v")
{
InputFileVideo input2 = new InputFileVideo();
input2.Display();
}
else if (typePick == "M" || typePick == "m")
{
InputFileMovie input = new InputFileMovie();
input.Display();
}
else if (typePick == "S" || typePick == "s")
{
InputFileShow input3 = new InputFileShow();
input3.Display();
}
else if (typePick == "E" || typePick == "e")
{
System.Environment.Exit(0);
}
if (typePick != "E" || typePick != "e")
{
goto GoAgain;
}
}
}
}
|
894a02df62e31ab426573d56741e2f08907999ad
|
C#
|
turbo25mike/myBook
|
/DrawIt/DrawIt.iOS/DrawView.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using MonoTouch.CoreGraphics;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace DrawIt
{
// Original Source: http://stackoverflow.com/questions/21029440/xamarin-ios-drawing-onto-image-after-scaling-it
public class DrawView : UIView
{
public DrawView (RectangleF frame) : base (frame)
{
DrawPath = new CGPath ();
CurrentLineColor = UIColor.Black;
PenWidth = 5.0f;
Lines = new List<VESLine> ();
InFocus = true;
}
private PointF PreviousPoint;
private CGPath DrawPath;
private byte IndexCount;
private UIBezierPath CurrentPath;
private List<VESLine> Lines;
public UIColor CurrentLineColor { get; set; }
public float PenWidth { get; set; }
public bool InFocus { get; set; }
public void Clear ()
{
DrawPath.Dispose ();
DrawPath = new CGPath ();
SetNeedsDisplay ();
}
public override void TouchesBegan (NSSet touches, UIEvent evt)
{
IndexCount++;
var path = new UIBezierPath
{
LineWidth = PenWidth
};
var touch = (UITouch)touches.AnyObject;
PreviousPoint = touch.PreviousLocationInView (this);
var newPoint = touch.LocationInView (this);
path.MoveTo (newPoint);
InvokeOnMainThread (SetNeedsDisplay);
CurrentPath = path;
var line = new VESLine
{
Path = CurrentPath,
Color = CurrentLineColor,
Index = IndexCount
};
Lines.Add (line);
}
public override void TouchesMoved (NSSet touches, UIEvent evt)
{
if (InFocus)
{
var touch = (UITouch)touches.AnyObject;
var currentPoint = touch.LocationInView(this);
if (Math.Abs(currentPoint.X - PreviousPoint.X) >= 4 ||
Math.Abs(currentPoint.Y - PreviousPoint.Y) >= 4)
{
var newPoint = new PointF((currentPoint.X + PreviousPoint.X) / 2, (currentPoint.Y + PreviousPoint.Y) / 2);
CurrentPath.AddQuadCurveToPoint(newPoint, PreviousPoint);
PreviousPoint = currentPoint;
}
else
{
CurrentPath.AddLineTo(currentPoint);
}
InvokeOnMainThread(SetNeedsDisplay);
}
}
public override void TouchesEnded (NSSet touches, UIEvent evt)
{
InvokeOnMainThread (SetNeedsDisplay);
}
public override void TouchesCancelled (NSSet touches, UIEvent evt)
{
InvokeOnMainThread (SetNeedsDisplay);
}
public override void Draw (RectangleF rect)
{
foreach (var line in Lines) {
line.Color.SetStroke ();
line.Path.Stroke ();
}
}
}
}
|
7dc80451bf87c07e2ed3f1ed7df83376fb294c5f
|
C#
|
atomic7777/SimpleMap
|
/Map/Google/GoogleRectangle.cs
| 2.90625
| 3
|
using System;
using System.Drawing;
using SimpleMap.Map.Types;
namespace SimpleMap.Map.Tile
{
public class ScreenRectangle : ICloneable, IComparable
{
public static readonly ScreenRectangle Empty = new ScreenRectangle();
public ScreenCoordinate LeftTop
{
get
{
return new ScreenCoordinate(Left, Top, Level);
}
}
public ScreenCoordinate RightBottom
{
get
{
return new ScreenCoordinate(Right, Bottom, Level);
}
}
public long Left { get; private set; }
public long Right { get; private set; }
public long Top { get; private set; }
public long Bottom { get; private set; }
public int Level { get; private set; }
private ScreenRectangle()
{
Left = 0;
Right = 0;
Top = 0;
Bottom = 0;
Level = 0;
}
public ScreenRectangle(long left, long top, long right, long bottom, int level)
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
Level = level;
}
public ScreenRectangle(ScreenCoordinate pLeftTop, ScreenCoordinate pRightBottom)
{
if (pRightBottom.Level != pLeftTop.Level)
{
pRightBottom = new ScreenCoordinate(pRightBottom, pLeftTop.Level);
}
Left = pLeftTop.X;
Top = pLeftTop.Y;
Right = pRightBottom.X;
Bottom = pRightBottom.Y;
Level = pLeftTop.Level;
}
public ScreenRectangle(CoordinateRectangle coordinateRect, int level)
{
var pLeftTop = new ScreenCoordinate(coordinateRect.LeftTop, level);
var pRightBottom = new ScreenCoordinate(coordinateRect.RightBottom, level);
Left = pLeftTop.X;
Top = pLeftTop.Y;
Right = pRightBottom.X;
Bottom = pRightBottom.Y;
Level = level;
}
public ScreenRectangle(CoordinatePoligon coordinatePoligon, int level)
{
for (var i = 0; i < coordinatePoligon.Count; i++)
{
var pt = new ScreenCoordinate(coordinatePoligon.Coordinates[i], level);
if (i == 0)
{
Left = pt.X;
Right = pt.X;
Top = pt.Y;
Bottom = pt.Y;
}
else
{
if (pt.X < Left) Left = pt.X;
if (pt.X > Right) Right = pt.X;
if (pt.Y < Top) Top = pt.Y;
if (pt.Y > Bottom) Bottom = pt.Y;
}
}
Level = level;
}
#region ICloneable Members
public object Clone()
{
return new ScreenRectangle(Left, Top, Right, Bottom, Level);
}
#endregion
#region IComparable Members
public int CompareTo(Object obj)
{
var rectangle = (ScreenRectangle)obj;
var res = LeftTop.CompareTo(rectangle.LeftTop);
if (res != 0) return res;
return RightBottom.CompareTo(rectangle.RightBottom);
}
#endregion
public static implicit operator CoordinateRectangle(ScreenRectangle Tile)
{
return new CoordinateRectangle(Tile.LeftTop, Tile.RightBottom);
}
/// <summary>
/// Tile bitmap block count for (X, Y)
/// </summary>
public Rectangle BlockView
{
get
{
return Rectangle.FromLTRB(
(int) (Left / TileBlock.BlockSize),
(int) (Top / TileBlock.BlockSize),
(int) ((Right - TileBlock.BlockSize) / TileBlock.BlockSize) + 1,
(int) ((Bottom - TileBlock.BlockSize) / TileBlock.BlockSize) + 1);
}
}
public Rectangle GetScreenRect(ScreenRectangle screenView)
{
if (Level != screenView.Level)
{
screenView = new ScreenRectangle(
new CoordinateRectangle(screenView.LeftTop, screenView.RightBottom), Level);
}
var pt1 = LeftTop.GetScreenPoint(screenView);
var pt2 = RightBottom.GetScreenPoint(screenView);
return Rectangle.FromLTRB(pt1.X, pt1.Y, pt2.X, pt2.Y);
}
public IntersectResult PointContains(GeomCoordinate point)
{
return ((CoordinateRectangle)this).PointContains(point);
}
public IntersectResult RectangleContains(CoordinateRectangle rectangle)
{
return ((CoordinateRectangle)this).RectangleContains(rectangle);
}
public IntersectResult LineContains(CoordinateRectangle line)
{
return ((CoordinateRectangle)this).LineContains(line);
}
public IntersectResult PoligonContains(CoordinatePoligon poligon)
{
return ((CoordinateRectangle)this).PoligonContains(poligon);
}
}
}
|
ea90924094ce2ddbfe2803842ec0547d46e07c95
|
C#
|
luizamunk/RPGProjectOOP
|
/RpgProject/RpgProject/CharacterClasses/Entity.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RpgProject.CharacterClasses
{
public enum EntityGender { Male, Female, Unknown, Androginous }
public abstract class Entity
{
#region Fields Region
protected string name;
protected EntityGender gender;
protected int strength, dexterity, wisdom, inteligence, charism, health;
protected int strenghtModifier, dexterityModifier, wisdomModifier, inteligenceModifier, charismModifier, healthModifier;
#endregion
#region Properties
public string Name
{
get { return name; }
protected set { name = value; }
}
public EntityGender Gender { get; set; }
public int Strenght
{
get { return strength + strenghtModifier; }
protected set { strength = value; }
}
public int Dexterity
{
get { return dexterity + dexterityModifier; }
protected set { dexterity = value; }
}
public int Wisdom
{
get { return wisdom + wisdomModifier; }
protected set { wisdom = value; }
}
public int Inteligence
{
get { return inteligence + inteligenceModifier; }
protected set { inteligence = value; }
}
public int Charism
{
get { return charism + charismModifier; }
protected set { charism = value; }
}
public int Health
{
get { return health + healthModifier; }
protected set { health = value; }
}
public int Attack
{
get { return attack; }
protected set { attack = value; }
}
public int Damage
{
get { return damage; }
protected set { damage = value; }
}
public int Defense
{
get { return defense; }
protected set { defense = value; }
}
public int Level
{
get { return level; }
protected set { level = value; }
}
public long Experience
{
get { return experience; }
protected set { experience = value; }
}
#endregion
#region Combat
protected int attack;
protected int damage;
protected int defense;
protected int level;
protected long experience;
#endregion
#region Constructor
public Entity()
{
Name = string.Empty;
Strenght = 0;
Dexterity = 0;
Wisdom = 0;
Inteligence = 0;
Charism = 0;
Health = 0;
}
#endregion
#region Methods
#endregion
}
}
|
ac6a81e73dedaf361d78cf0a89465bde587a4d27
|
C#
|
yoyo02222803/TEoG_Unity_2
|
/Assets/Items/Scrips/Edibles/MealRation.cs
| 2.546875
| 3
|
using UnityEngine;
namespace ItemScripts
{
[CreateAssetMenu(fileName = "MealRation", menuName = "Item/Edibles/MealRation")]
public class MealRation : Edibles
{
public MealRation() : base(ItemIds.MealRation, "Meal ration")
{
}
// use function aka what the item does, base.use() calls Use function of this class's base class (Item.Use) which does nothing.
public override string Use(BasicChar user)
{
return base.Use(user);
}
}
}
|
f21dd12722fc44ca1ff268f0e62db194760c9a30
|
C#
|
sameerkapps/smart-switch
|
/PowerUpApp/Powerup.core/ViewModels/IBluetoothManager.cs
| 2.890625
| 3
|
// Copyright (c) 2015 Sameer Khandekar
// Provided as is with MIT License
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Powerup.core.ViewModels
{
/// <summary>
/// This encapsulates the functionality that needs to be supported
/// by bluetooth manager on each platform.If an exception occurs, it should be
/// thrown with appropriate message. So view model will catch it and dispaly error message to
/// the user.
/// </summary>
public interface IBluetoothManager
{
/// <summary>
/// True when Bluetooth manager is connected to device
/// </summary>
bool IsConnected { get; }
/// <summary>
/// Obtains the list of Paired devices on the phone.
/// </summary>
/// <returns>List of Paired Devices</returns>
Task<List<DeviceInfo>> GetPairedDevices();
/// <summary>
/// Connects to ta device given device host name.
/// </summary>
/// <param name="deviceHostName">This is the hostName</param>
/// <returns>Success or failure</returns>
Task<bool> ConnectAsync(string deviceHostName);
/// <summary>
/// Sends on/off message to the device
/// </summary>
/// <param name="isOn">Flag indicating on/off</param>
/// <returns>Number of bytes sent.</returns>
Task<uint> SendOnOffAsync(bool isOn);
/// <summary>
/// Disconnect from the bluetooth
/// </summary>
void Disconnect();
}
}
|
65b50bdcaa9a7f9afd3e8c0fd81db7f212b1378e
|
C#
|
devanshachaudhari/SampleExercise
|
/MemberClaimsExercise/CsvHelper/CsvParserService.cs
| 2.8125
| 3
|
using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace CsvHelperLib
{
public class CsvParserService<T> : ICsvParserService<T> where T : class
{
public List<T> ReadCsvFileToModel(string path)
{
try
{
using (var reader = new StreamReader(path))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<T>();
return records?.ToList();
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
}
|
db2c34c729cbf5f73fa76f38a302a04d2914927f
|
C#
|
rhom6us/Airspace
|
/Rhombus.Wpf.Airspace/Rhombus.Wpf.Airspace/Controls/VisualWrapper.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Rhombus.Wpf.Airspace.Controls {
/// <summary>
/// The VisualWrapper simply integrates a raw Visual child into a tree
/// of FrameworkElements.
/// </summary>
[System.Windows.Markup.ContentProperty("Child")]
public class VisualWrapper<T> : System.Windows.FrameworkElement where T : System.Windows.Media.Visual {
public T Child {
get => _child;
set {
if (_child != null)
this.RemoveVisualChild(_child);
_child = value;
if (_child != null)
this.AddVisualChild(_child);
}
}
protected override int VisualChildrenCount => _child != null
? 1
: 0;
protected override System.Windows.Media.Visual GetVisualChild(int index) {
if (_child != null && index == 0)
return _child;
throw new ArgumentOutOfRangeException("index");
}
private T _child;
}
/// <summary>
/// The VisualWrapper simply integrates a raw Visual child into a tree
/// of FrameworkElements.
/// </summary>
public class VisualWrapper : VisualWrapper<System.Windows.Media.Visual> { }
}
|
42f65691cefdc906b07c16b3f6404e206b94d6b1
|
C#
|
ArseniBarsegyan/ReminderXamarin
|
/ReminderXamarin/ReminderXamarin/ReminderXamarin/Elements/BindableToolbarItem.cs
| 2.671875
| 3
|
using Xamarin.Forms;
namespace ReminderXamarin.Elements
{
public class BindableToolbarItem : ToolbarItem
{
public static readonly BindableProperty IsVisibleProperty =
BindableProperty.Create(propertyName: nameof(IsVisible),
returnType: typeof(bool),
declaringType: typeof(BindableToolbarItem),
defaultValue: true,
defaultBindingMode: BindingMode.TwoWay,
propertyChanged: OnIsVisibleChanged);
public bool IsVisible
{
get => (bool)GetValue(IsVisibleProperty);
set => SetValue(IsVisibleProperty, value);
}
private static void OnIsVisibleChanged(BindableObject bindable,
object oldvalue, object newvalue)
{
var item = bindable as BindableToolbarItem;
if (item == null || item.Parent == null)
{
return;
}
var toolbarItems = ((ContentPage)item.Parent).ToolbarItems;
var isVisible = (bool)newvalue;
if (isVisible && !toolbarItems.Contains(item))
{
Device.BeginInvokeOnMainThread(() => { toolbarItems.Add(item); });
}
else if (!isVisible && toolbarItems.Contains(item))
{
Device.BeginInvokeOnMainThread(() => { toolbarItems.Remove(item); });
}
else if (isVisible && toolbarItems.Contains(item))
{
Device.BeginInvokeOnMainThread(() =>
{
toolbarItems.Remove(item);
toolbarItems.Add(item);
});
}
}
}
}
|
95d90890e5127d91f4b2c307acac7f0484e91b2e
|
C#
|
ryanlacombe/Battle-Tanks
|
/GraphicalTestApp/Cannon.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GraphicalTestApp
{
class Cannon : Actor
{
//Creates the variables needed for the Cannon Class
private Sprite _cannonSprite;
private int _playerNum;
private int _shellCount1;
private int _shellCount2;
//Creates the Constructor for Cannon
public Cannon(float x, float y, int playerNum)
{
_cannonSprite = new Sprite("sprites/barrelGreen_outline.png");
_cannonSprite.Y = -50;
AddChild(_cannonSprite);
_playerNum = playerNum;
OnUpdate += RotateCannon;
OnUpdate += Fire;
}
public void RotateCannon(float deltaTime)
{
//Checks if the User has the "E" key held down
if (Input.IsKeyDown(69) && _playerNum == 0)
{
//Rotates the cannon clockwise
Rotate(0.5f * deltaTime);
}
//Checks if User has the "Q" key held down
else if (Input.IsKeyDown(81) && _playerNum == 0)
{
//Rotates the cannon counter-clockwise
Rotate(-0.5f * deltaTime);
}
//Checks if User has the "O" key held down
else if (Input.IsKeyDown(79) && _playerNum == 1)
{
//Rotates the cannon clockwise
Rotate(0.5f * deltaTime);
}
//Checks if User has the "U" key held down
else if (Input.IsKeyDown(85) && _playerNum ==1)
{
//Rotates the cannon counter-clockwise
Rotate(-0.5f * deltaTime);
}
}
public void Fire(float deltaTime)
{
//Checks if User pressed the "F" key
if (Input.IsKeyPressed(70) && _playerNum == 0)
{
//Checks if User has already fired 5 times
if(_shellCount1 < 5)
{
//Creates a shell with its direction
Shell shell = new Shell(XAbsolute, YAbsolute, _playerNum);
Vector3 direction = GetDirectionAbsolute();
//Fires the shell at appropriate rotation, direction, and velocity
shell.Rotate(GetRotationAbsolute());
shell.X += direction.x * -50f;
shell.Y += direction.y * -50f;
shell.XVelocity += direction.x * -300f;
shell.YVelocity += direction.y * -300f;
Parent.Parent.AddChild(shell);
//Increases the amount of shells fired by one for reload
_shellCount1++;
}
}
//Checks if User has pressed the "R" key
else if(Input.IsKeyPressed(82) && _playerNum == 0)
{
//Reloads the cannon
_shellCount1 = 0;
}
//Checks if the User has pressed the ";" key
else if (Input.IsKeyPressed(59) && _playerNum == 1)
{
//Checks if User has already fired 5 times
if (_shellCount2 < 5)
{
//Creates a shell with its direction
Shell shell = new Shell(XAbsolute, YAbsolute, _playerNum);
Vector3 direction = GetDirectionAbsolute();
//Fires the shell at appropriate rotation, direction, and velocity
shell.Rotate(GetRotationAbsolute());
shell.X += direction.x * -50f;
shell.Y += direction.y * -50f;
shell.XVelocity += direction.x * -300f;
shell.YVelocity += direction.y * -300f;
Parent.Parent.AddChild(shell);
//Increases the amount of shells fired by one for reload
_shellCount2++;
}
}
//Checks if User has pressed the "P" key
else if (Input.IsKeyPressed(80) && _playerNum == 1)
{
//Reloads the cannon
_shellCount2 = 0;
}
}
}
}
|
acf5dbf2fc183dab4a10fcc6afaa3abe6bb6328e
|
C#
|
ByrkoAnton/ITVDNEssentialAbstraction
|
/abstraction03/Player.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace abstraction03
{
class Player : IPlayable, IRecodable
{
public void Pause()
{
Console.WriteLine("IPlayable pause");
}
void IRecodable.Pause()
{
Console.WriteLine("Ircordable pause"); //для разнообразия переопределил
}
public void Play()
{
Console.WriteLine("play");
}
public void Record()
{
Console.WriteLine("rec");
}
public void Stop()
{
Console.WriteLine("stop");
}
}
}
|
e099ebe90df6a50b7b9bdaa4307dc6d6e82f02f6
|
C#
|
mr-krustev/Telerik-Academy-Course
|
/C# OOP/ExtensionMethodsDelegatesLambdaLINQ/StudentSystem/Start.cs
| 3.21875
| 3
|
namespace StudentSystem
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Start
{
static void Main()
{
var allStudents = new List<Student>()
{
new Student("Pesho", "Ivanov", 134506, "02873963", "pesho@abv.bg", new List<double>(){3.25, 4.50, 6.00}, 3),
new Student("Ivan", "Petrov", 112345, "02893859", "ivan.petrov@gmail.com", new List<double>(){2.00, 2.00, 4.30}, 1),
new Student("Mario", "Jelqzkov", 167123, "04411858938", "geparda@abv.bg", new List<double>(){4.25, 2.00, 6.00}, 2),
new Student("Martin", "Bagrqnov", 143106, "06498868389", "magrqnov@abv.bg", new List<double>(){5.25, 5.50, 5.00}, 1),
new Student("Cesar", "Justinian", 156731, "06395070384", "cesar@rome.org", new List<double>(){6.00, 6.00, 6.00}, 2),
};
#region Problem 09. Student groups
var groupTwoStudents =
from st in allStudents
where st.GroupNumber == 2
orderby st.FirstName
select st;
Print(groupTwoStudents);
#endregion
#region Problem 10. Student groups extensions
var studentsFromGroup = allStudents.GetStudentsFromGroup(2);
Print(studentsFromGroup);
#endregion
#region Problem 11. Extract students by email
Console.WriteLine("All @abv.bg accounts: \n");
var allABVStudents = allStudents.Where(st => st.EMail.Substring(st.EMail.IndexOf('@')) == "@abv.bg");
Print(allABVStudents);
#endregion
#region Problem 12. Extract students by phone
Console.WriteLine("All students with sofia phones: \n");
var allSofiaStudents = allStudents.Where(st => st.Telephone.Substring(0, 2) == "02");
Print(allSofiaStudents);
#endregion
#region Problem 13. Extract students by marks
Console.WriteLine("Students with at least one excellent mark: \n");
var allStudentsWithExcellMark = allStudents.Where(st => st.Marks.Contains(6.00));
Print(allStudentsWithExcellMark);
#endregion
#region Problem 14. Extract students with two marks
Console.WriteLine("All students with 2 marks equal to 2: \n");
var exactMarkTwoTimes = allStudents.GetStudentWithMarkExactTimes(2.00, 2);
Print(exactMarkTwoTimes);
#endregion
#region Problem 15. Extract marks
Console.WriteLine("Marks of students who studied in 2006: \n");
var allTwoThousandAndSixStudents = allStudents.Where(st => st.FacultyNumber.ToString().Substring(4) == "06");
foreach (var st in allTwoThousandAndSixStudents)
{
Console.WriteLine(string.Join(", ", st.Marks));
}
#endregion
}
private static void Print(IEnumerable<Student> students)
{
foreach (var st in students)
{
Console.WriteLine(st);
Console.WriteLine(new string('-', 40));
}
}
}
}
|
1c9e0079e63571e4ae03f79caf7ed143a9ed7de9
|
C#
|
vgjenks/EnterpriseLayers
|
/EnterpriseLayers.Data.Access/UnitOfWorkFactory.cs
| 3.078125
| 3
|
using EnterpriseLayers.Contract.DataAccess;
using System;
namespace EnterpriseLayers.Data.Access {
public class UnitOfWorkFactory {
public IUnitOfWork UnitOfWork { get; set; }
public UnitOfWorkFactory(string databasePlatform) {
UnitOfWork = Create(databasePlatform);
}
public static IUnitOfWork Create(string databasePlatform) {
/**
* Conditional logic to choose which UoW
* implementation to return (ADO, EF, etc.)
**/
IUnitOfWork uow = null;
switch (databasePlatform) {
case "MsSqlEF":
uow = new MsSqlEFUnitOfWork();
break;
case "MySqlEF":
uow = new MySqlEFUnitOfWork();
break;
default:
throw new InvalidOperationException(
"ERROR: You must provide a valid database platform argument to invoke a new Unit of Work.");
}
return uow;
}
}
}
|
e8e572ed556e24ea9c8749444b4f38d4834850d9
|
C#
|
dragobaltov/Functions-Exercises
|
/PredicateForNames/PredicateForNames/Program.cs
| 3.609375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace PredicateForNames
{
class Program
{
static void Main(string[] args)
{
int maxLength = int.Parse(Console.ReadLine());
Predicate<int> predicate = n => n <= maxLength;
Action<string> printer = n => Console.WriteLine(n);
Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Where(n => predicate(n.Length)).ToList().ForEach(printer);
}
}
}
|
addae243190568a3f9add69ebab2756adc38dffb
|
C#
|
JokePenny/VikingVillage
|
/Vik/Buildquarry.cs
| 2.734375
| 3
|
using System.Drawing;
namespace Vik
{
class Buildquarry : Build
{
private byte distance;// растояние
private static byte ID = 15;// индефикатор объекта
public Buildquarry(byte X, byte Y, byte Distance) : base(X, Y)
{
x = X;
y = Y;
distance = Distance;
}
public Buildquarry()
{
}
public void SetImage()
{
Game.arr[x, y].BackgroundImage = Image.FromFile("D:\\01Programms\\PHCS6\\Project\\Vikings\\builds\\images\\tree_155.png");
}
public void SetDeleteImage()
{
Game.arr[x, y].BackgroundImage = Image.FromFile("D:\\01Programms\\PHCS6\\Project\\Vikings\\images\\tree_03.png");
}
//геттеры
public byte GetDistance()
{
return distance;
}
public byte GetID()
{
return ID;
}
//сеттеры
public void SetDistance(byte A)
{
distance = A;
}
}
}
|
831591dc5850c1772880789ac1c08828952549ef
|
C#
|
thuliomariano/SimpleSocketClient
|
/SimpleSocketClient/View/Client.cs
| 2.640625
| 3
|
using SimpleSocketClient.Controller;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace SimpleSocketClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string mensagem;
public string historico;
Conexao conexao = new Conexao();
//cria uma stancia para iniciar uma conexão do socket
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private void button1_Click(object sender, EventArgs e)
{
//conecta com o servidor
try
{
Conexao con = new Conexao();
con.Name = txtNome.Text;
con.Ip = txtIp.Text;
con.Port = Convert.ToInt32(txtPort.Text);
//conecta ao ip no caso meu mesmo e uma porta
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(con.Ip), con.Port);
sck.Connect(endPoint);
txtHistorico.Text = "Mensagem: Cliente conectado com o Servidor!";
String usuario = "Usuário: " + conexao.Name + " conectado";
txtHistorico.Text = "Mensagem: Cliente conectado com o Servidor! \n" + usuario;
}
catch (Exception)
{
MessageBox.Show("Erro de comunicação com o servidor, por favor verifique se o mesmo está acessivel", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
txtIp.Enabled = false;
txtPort.Enabled = false;
btnConectar.Enabled = false;
btnEncerrar.Enabled = true;
txtMensagem.Enabled = true;
btnEnviar.Enabled = true;
}
private void btnEnviar_Click(object sender, EventArgs e)
{
try
{
//envia informações para o servidor
mensagem = txtMensagem.Text;
//enviando minha menssagem
byte[] msgBuffer = Encoding.Default.GetBytes(mensagem);
sck.Send(msgBuffer, 0, msgBuffer.Length, 0);
txtHistorico.Text = "Mensagem cliente: enviado mensagem com sucesso...";
//recebendo minha menssagem
byte[] buffer = new byte[255];
int rec = sck.Receive(buffer, 0, buffer.Length, 0);
Array.Resize(ref buffer, rec);
txtHistorico.Text = Encoding.Default.GetString(buffer);
}
catch (Exception)
{
MessageBox.Show("Erro inesperado: ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, EventArgs e)
{
sck.Close();
txtIp.Enabled = true;
txtPort.Enabled = true;
btnConectar.Enabled = true;
btnEncerrar.Enabled = false;
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
txtIp.Enabled = false;
txtPort.Enabled = false;
btnConectar.Enabled = false;
btnEncerrar.Enabled = false;
btnEnviar.Enabled = false;
txtMensagem.Enabled = false;
}
private void txtHistorico_TextChanged(object sender, EventArgs e)
{
}
private void txtNome_TextChanged(object sender, EventArgs e)
{
}
private void btnRegistro_Click(object sender, EventArgs e)
{
txtIp.Enabled = true;
txtPort.Enabled = true;
btnConectar.Enabled = true;
conexao.Name = txtNome.Text;
}
}
}
|
4d0cae677c8c96a601a96f6c0dad34c4cd779460
|
C#
|
riverswb/LifeQuantified
|
/LifeQuantified/LifeQuantifiedDB.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using SQLite;
namespace LifeQuantified
{
class LifeQuantifiedDB
{
static readonly Lazy<SQLiteAsyncConnection> lazyInitializer = new Lazy<SQLiteAsyncConnection>(() =>
{
return new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
});
static SQLiteAsyncConnection Database => lazyInitializer.Value;
static bool initialized = false;
public LifeQuantifiedDB()
{
InitializeAsync().SafeFireAndForget(false);
}
async Task InitializeAsync()
{
if (!initialized)
{
if (!Database.TableMappings.Any(m => m.MappedType == typeof(Quantity).Name))
{
await Database.CreateTableAsync(CreateFlags.None, typeof(Quantity)).ConfigureAwait(false);
initialized = true;
}
}
}
public Task<List<Quantity>> GetQuantitiesAsync()
{
return Database.Table<Quantity>().ToListAsync();
}
public Task<Quantity> GetQuantityAsync(int id)
{
return Database.Table<Quantity>().Where(i => i.ID == id).FirstOrDefaultAsync();
}
public Task<int> SaveQuantityAsync(Quantity quantity)
{
if (quantity.ID != 0)
{
return Database.UpdateAsync(quantity);
}
else
{
return Database.DeleteAsync(quantity);
}
}
public Task<int> DeleteQuantityAsync(Quantity quantity)
{
return Database.DeleteAsync(quantity);
}
}
}
|
42fbecd24d91c505b0db53920b4a98bf01b7894d
|
C#
|
cmccrain/Project-Dollhouse
|
/TSOClient/tso.simantics/engine/VMRouteFinder.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using TSO.Files.formats.iff.chunks;
namespace TSO.Simantics.engine
{
public class VMRouteFinder
{
/// <summary>
/// This method will find all the avaliable locations within the criteria ordered by proximity to the optimal proximity
/// External functions can then decide which is most desirable. E.g. the nearest slot to the object may be the longest route if
/// its in another room.
/// </summary>
/// <param name="position"></param>
/// <param name="flags"></param>
/// <param name="minProximity"></param>
/// <param name="maxProximity"></param>
/// <param name="desiredProximity"></param>
/// <returns></returns>
public static List<VMFindLocationResult> FindAvaliableLocations(Vector2 center, SLOTFlags flags, int minProximity, int maxProximity, int desiredProximity)
{
/**
* Start at min proximity and circle around the object to find the avaliable locations.
* Then pick the one nearest to the optimal value
*/
var result = new List<VMFindLocationResult>();
var proximity = minProximity;
var proximityIncrement = 16;
var proximityNudge = proximityIncrement * 0.25f;
var currentDepth = 1.0f;
while (proximity <= maxProximity){
var angle = 0.0f;
/** Every time we move out by 1 tile in proximity, there will be more tiles to look at **/
var angleIncrement = 360.0f / (currentDepth * 8);
while (angle < 360.0f){
var radians = angle * (Math.PI / 180.0f);
var radius = proximity + proximityNudge;
var xpos = Math.Round(radius * Math.Cos(radians));
var ypos = Math.Round(radius * Math.Sin(radians));
var tileX = (float)Math.Round(xpos / 16.0f) + center.X;
var tileY = (float)Math.Round(ypos / 16.0f) + center.Y;
var direction = GetDirection(center, new Vector2(tileX, tileY));
if ((flags&direction) == direction)
{
//TODO: Check if slot is occupied or out of bounds
/** This is acceptible to the slot :) **/
result.Add(new VMFindLocationResult {
Direction = direction,
Position = new Vector2(tileX, tileY),
Proximity = proximity
});
}
angle += angleIncrement;
}
proximity += proximityIncrement;
}
/** Sort by how close they are to desired proximity **/
result.Sort(new VMProximitySorter(desiredProximity));
return result;
}
/// <summary>
/// Returns which direction (n/s/e/w/ne/nw/se/sw) a target is in relation to an object.
/// </summary>
/// <param name="center"></param>
/// <param name="target"></param>
/// <returns></returns>
public static SLOTFlags GetDirection(Vector2 center, Vector2 target){
target.X -= center.X;
target.Y -= center.Y;
if (target.Y < 0){
if (target.X > 0){
return SLOTFlags.NORTH_EAST;
}else if (target.X < 0){
return SLOTFlags.NORTH_WEST;
}
return SLOTFlags.NORTH;
}else if (target.Y > 0){
if (target.X > 0){
return SLOTFlags.SOUTH_EAST;
}else if (target.Y < 0){
return SLOTFlags.SOUTH_WEST;
}
return SLOTFlags.SOUTH;
}
if (target.X < 0) { return SLOTFlags.WEST; }
return SLOTFlags.EAST;
}
}
public class VMFindLocationResult
{
public SLOTFlags Direction;
public Vector2 Position;
public int Proximity;
}
public class VMProximitySorter : IComparer<VMFindLocationResult>
{
private int DesiredProximity;
public VMProximitySorter(int desiredProximity){
this.DesiredProximity = desiredProximity;
}
#region IComparer<VMFindLocationResult> Members
public int Compare(VMFindLocationResult x, VMFindLocationResult y)
{
var distanceX = Math.Abs(x.Proximity - DesiredProximity);
var distanceY = Math.Abs(y.Proximity - DesiredProximity);
if (distanceX < distanceY){
return -1;
}else if (distanceX > distanceY)
{
return -1;
}else
{
return ((int)x.Direction).CompareTo((int)y.Direction);
}
}
#endregion
}
}
|
65688d2b6e0d713097f9e54eb8f643e6f0619d0f
|
C#
|
chavesandres1009/dbk
|
/AppKoralitos/ConfigView.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppKoralitos.Controller;
namespace AppKoralitos
{
public partial class ConfigView : Form
{
private MainController mcontroller;
public ConfigView()
{
mcontroller = new MainController();
InitializeComponent();
init();
}
private void init()
{
this.textBox4.Text = mcontroller.get_ced();
this.textBox1.Text = mcontroller.get_iv().ToString();
this.textBox2.Text = mcontroller.get_is().ToString();
this.textBox3.Text = mcontroller.get_cant_mesas().ToString();
init_combo();
}
private void init_combo()
{
foreach(string im in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
this.comboBox1.Items.Add(im);
if(im == mcontroller.get_impresora())
{
this.comboBox1.Text = im;
}
}
}
private void save_changes()
{
this.mcontroller.set_ced(this.textBox4.Text);
this.mcontroller.set_iv(float.Parse(this.textBox1.Text));
this.mcontroller.set_is(float.Parse(this.textBox2.Text));
this.mcontroller.set_cant_mesas(int.Parse(this.textBox3.Text));
this.mcontroller.set_impresora(this.comboBox1.Text);
this.mcontroller.save_changes();
}
private void button1_Click(object sender, EventArgs e)
{
this.save_changes();
MessageBox.Show("Los cambios se han guardado correctamente, reinicie la aplicación para vizualizar los cambios");
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
3e0d390caefecf6eb618089e06c7779c2bbe3e35
|
C#
|
astnt/parser-net
|
/Parser/Model/Hash.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Parser.Model
{
public class Hash : IExecutable
{
private Dictionary<String, Object> dictionary = new Dictionary<String, Object>();
public Hash()
{
}
public void addKey(Caller caller)
{
string key = ((Text) ((Parametr) caller.Childs[0]).Childs[0]).Body;
string value = ((Text)((Parametr)caller.Childs[1]).Childs[0]).Body;
if(dictionary.ContainsKey(key))
{
dictionary[key] = value;
}
else
{
dictionary.Add(key, value);
}
}
public string getKey(Caller caller)
{
StringBuilder key = new StringBuilder(((Text)((Parametr)caller.Childs[0]).Childs[0]).Body);
return dictionary[key.ToString()].ToString();
}
public void each(Caller caller)
{
string variableNameOfKey = ((Text)((Parametr)caller.Childs[0]).Childs[0]).Body;
string variableNameOfValue = ((Text)((Parametr)caller.Childs[1]).Childs[0]).Body;
Parametr bodyOfEachCycle = ((Parametr)caller.Childs[2]);
foreach (KeyValuePair<string, object> pair in dictionary)
{
// update переменных в начале цикла.
exec.ContextManager.AddVar(variableNameOfKey, pair.Key);
exec.ContextManager.AddVar(variableNameOfValue, pair.Value);
// выполнение тела цикла.
exec.Run(bodyOfEachCycle.Childs);
}
}
private Executor exec;
public void AddExecutor(Executor executor)
{
exec = executor;
}
}
}
|
aafcd06e0cf38555f0ae2ee38edd80f29193f754
|
C#
|
FrostySoup/XplicityProject
|
/ExplicityForm/Repository/Repository/UsageDataRepository.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using DataLayer.DatabaseData;
using Microsoft.Data.Entity;
namespace Repository.Repository
{
public class UsageDataRepository
{
public async Task<UsageData> GetItemAsync(Expression<Func<UsageData, bool>> predicate)
{
using (var context = new MetrixContext())
{
return await context.UsageDatas
.FirstOrDefaultAsync(predicate);
}
}
public bool AddNewItem(UsageData usageData)
{
using (var context = new MetrixContext())
{
try
{
context.UsageDatas.Add(usageData);
context.SaveChanges();
}
catch
{
return false;
}
return true;
}
}
public List<UsageData> GetAllItemsWhere(Expression<Func<UsageData, bool>> predicate)
{
using (var context = new MetrixContext())
{
return context.UsageDatas
.Where(predicate)
.ToList();
}
}
}
}
|
08ae73b72263482fd4f0c0819c94b3153ced38f6
|
C#
|
GOODVIN39/GeekBrains
|
/HomeworkL2.7/Program.cs
| 3.859375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HomeworkL2._7
{
class Program
{
static void Main(string[] args)
{
// Шаповаленко Александр Не выполненно, т.к. не понимаю что такое рекурсия и как её правильно описывать.
//7.
//a) Разработать рекурсивный метод, который выводит на экран числа от a до b(a < b).
//б) *Разработать рекурсивный метод, который считает сумму чисел от a до b.
Console.WriteLine("Вывод чисел от минимально до максимального значения с помощью рекурсии");
Console.WriteLine("Введите минимально число: "); int a = int.Parse(Console.ReadLine());
Console.WriteLine("Введите максимальное число: "); int b = int.Parse(Console.ReadLine());
int result;
int value;
if (a <= b)
{
for (int i = a; i <= b; i++)
{
Console.WriteLine(a++);
result = 0;
value = i;
while (value > 0)
{
MethodSumm(ref result, ref value);
}
Console.WriteLine($"Сума цифр числа {i} = {result}");
}
}
else if (a >= b)
{
Console.WriteLine("Ошибка: первое число больше второго");
}
Console.ReadLine();
}
private static void MethodSumm(ref int result, ref int value)
{
result += value % 10;
value /= 10;
}
}
}
|
1134abd5609682aac34e680ebc44b454a8b84c0c
|
C#
|
AlexTorrenti/EjemplosEFCore
|
/EjercicioLINQ/LINQ.cs
| 3.375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Day1
{
public class LINQ
{
class Voice
{
public int Downloads { get; set; }
public double Rating { get; set; }
public string Name { get; set; }
public double Version { get; set; }
public Voice(string name, int downloads, double version, double rating)
{
Name = name;
Downloads = downloads;
Version = version;
Rating = rating;
}
public override string ToString()
{
return string.Format("{0} - downloads: {1}", Name, Downloads);
}
}
class PopularVoice
{
public string Name { get; set; }
public double Version { get; set; }
public override string ToString()
{
return string.Format("{0} - version: {1}", Name, Version);
}
}
public LINQ()
{
List<Voice> voiceList = new List<Voice>();
voiceList.Add(new Voice("Robot", 1000, 1.0, 4.4));
voiceList.Add(new Voice("Kong", 500, 2.0, 3.4));
voiceList.Add(new Voice("Zombie", 3000, 1.0, 5.0));
voiceList.Add(new Voice("Alien", 1500, 1.0, 3.5));
voiceList.Add(new Voice("UnderWater", 1200, 2.0, 1.5));
voiceList.Add(new Voice("Franky", 700, 1.0, 4.4));
voiceList.Add(new Voice("Android", 550, 1.0, 5.0));
voiceList.Add(new Voice("Dark", 900, 2.0, 2.4));
voiceList.Add(new Voice("Echo", 1200, 2.0, 3.4));
voiceList.Add(new Voice("Fan", 3000, 3.0, 4.0));
voiceList.Add(new Voice("Chipmunk", 1150, 3.0, 4.0));
var query = from Voice voice in voiceList
where voice.Downloads > 1000
orderby voice.Downloads descending
select voice;
Console.WriteLine("Voices over 1000 ordered descending");
foreach (Voice v in query)
Console.WriteLine(v);
var allVoices = from Voice voice in voiceList select (Downloads: voice.Downloads, Name: voice.Name);
Console.WriteLine(string.Format(">1000:{0:0.00} vs all:{1:0.00}", query.Average(x => x.Downloads), allVoices.Average(x => x.Downloads)));
Console.WriteLine("Total Downloads: {0}", allVoices.Sum(x => x.Downloads));
var groupedVoices = from Voice voice in voiceList
group voice by voice.Version;
foreach (var groupVoice in groupedVoices)
{
Console.WriteLine(string.Format("{0:0.0}", groupVoice.Key));
foreach (Voice voice in groupVoice.OrderByDescending(x => x.Downloads))
{
Console.WriteLine("\t{0}", voice);
}
}
var groupedVoices2 = from Voice voice in voiceList
group voice by voice.Name[0] into groupedVoice
orderby groupedVoice.Key
select groupedVoice;
foreach (var groupVoice in groupedVoices2)
{
Console.WriteLine(string.Format("{0:0.0}", groupVoice.Key));
foreach (Voice voice in groupVoice.OrderByDescending(x => x.Downloads))
{
Console.WriteLine("\t{0}", voice);
}
}
var popularVoices = from Voice voice in voiceList
let popularFactor = voice.Rating * voice.Downloads
where (popularFactor >= allVoices.Average(x => x.Downloads * 2.5) * 1.2)
orderby voice.Downloads descending
select new PopularVoice { Name = voice.Name, Version = voice.Version };
Console.WriteLine("Popular Voices");
foreach (var popularVoice in popularVoices)
Console.WriteLine(popularVoice);
}
}
}
|
7bc58b71b197c9a6ee4243aa06403aeec1cc7319
|
C#
|
dogiaplinh/ktcnpm
|
/ktcnpm/Core/Models/RouteItem.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Core.Models
{
public class RouteItem : BindableBase
{
private double npv;
public RouteItem(List<int> paths)
{
Paths = new List<int>(paths);
}
public RouteItem(string paths)
{
Paths = new List<int>();
foreach (string item in paths.Split('_'))
{
Paths.Add(int.Parse(item));
}
}
public string Description { get; set; }
public double Npv
{
get { return npv; }
set { SetProperty(ref npv, value); }
}
public List<int> Paths { get; private set; }
public override string ToString()
{
string str = "";
foreach (int item in Paths)
{
str += item.ToString() + " ";
}
return str;
}
}
}
|
bb269ef00aa0b40a51042a75f62a39f3e55c6781
|
C#
|
lucasschmidtt/ProvaRaquel
|
/Services/InscricaoService.cs
| 2.609375
| 3
|
using System.Linq;
using System.Collections.Generic;
using edital.Data;
using edital.Model;
using edital.Services.Interfaces;
using System;
using Microsoft.EntityFrameworkCore;
namespace edital.Services
{
public class InscricaoService : IInscricaoService
{
private readonly ApplicationDbContext _context;
public InscricaoService(ApplicationDbContext context)
{
_context = context;
}
public bool CadastrarInscricao(Inscricao inscricao)
{
bool resp = true;
try {
_context.inscricao.Add(inscricao);
_context.SaveChanges();
} catch(Exception ex) {
resp = false;
Console.WriteLine(ex);
}
return resp;
}
public List<Inscricao> GetInscricoesPessoaJuridica(int pessoajuridica_id)
{
return _context.inscricao.Include(i => i.pessoajuridica)
.Where(e => e.pessoajuridica_id == pessoajuridica_id)
.ToList();
}
public List<Inscricao> GetInscricoes()
{
List<Inscricao> inscricoes = new List<Inscricao>();
inscricoes = _context.inscricao.Include(i => i.pessoajuridica).ToList();
return inscricoes;
}
public Segmento GetPessoaSegmento(int id)
{
Segmento segmento = _context.segmento.Include(i => i.edital).SingleOrDefault(e => e.id == id);
return segmento;
}
public Representante GetRepresentante(int id)
{
Representante representante = _context.representante.Include(i => i.contato).Include(i => i.endereco).SingleOrDefault(e => e.id == id);
return representante;
}
}
}
|
91350130ee868fe201b98d912b99a4967cc902cc
|
C#
|
Freelooppowter/Calculator
|
/SimpleCalculatorV2.0/SimpleCalculator/Model/CalculatorManager.cs
| 3.09375
| 3
|
using SimpleCalculator.DataAccess;
using SimpleCalculator.Domain;
using System;
using System.Collections.Generic;
namespace SimpleCalculator.Model
{
/// <summary>
/// 四则运算计算类
/// </summary>
public class CalculatorManager
{
public static CalculatorManager GetInstance()
{
if (_instance == null)
{
lock (_synObject)
{
if (_instance == null)
{
_instance = new CalculatorManager();
}
}
}
return _instance;
}
public void Calculate(double firstNumber, double secondNumber, string strOperator, out bool isSuccess)
{
double doubleResult = 0;
isSuccess = true;
switch (strOperator)
{
case "+":
doubleResult = firstNumber + secondNumber;
break;
case "-":
doubleResult = firstNumber - secondNumber;
break;
case "*":
doubleResult = firstNumber * secondNumber;
break;
case "/":
if (secondNumber == 0)
{
isSuccess = false;
}
else
{
doubleResult = firstNumber / secondNumber;
}
break;
}
if (isSuccess)
{
try
{
CalculatorRecord calculator = new CalculatorRecord();
calculator.FirstNumber = firstNumber;
calculator.SecondNumber = secondNumber;
calculator.Operator = strOperator;
calculator.Result = doubleResult;
calculator.OperateDateTime = DateTime.Now;
_repository.SaveCalculator(calculator);
}
catch (Exception ex) { throw ex; }
CalculateCompletedEventArgs eventArgs = new CalculateCompletedEventArgs { Result = doubleResult };
FireCalculateCompletedEvent(eventArgs);
}
}
public List<string> Operators = new List<string> { "+", "-", "*", "/" };
public List<CalculatorRecord> QueryAllCalculatorRecord()
{
return _repository.QueryAllCalculatorRecord();
}
public bool DeleteCalculatorRecord(int Id)
{
return _repository.DeleteCalculator(Id);
}
public event EventHandler<CalculateCompletedEventArgs> CalculateCompletedEvent;
private static CalculatorManager _instance = null;
private static readonly object _synObject = new object();
private void FireCalculateCompletedEvent(CalculateCompletedEventArgs eventArgs)
{
CalculateCompletedEvent?.Invoke(this, eventArgs);
}
private CalculatorManager() { }
private CalculatorRepository _repository = new CalculatorRepository();
}
public class CalculateCompletedEventArgs : EventArgs
{
public double Result { get; set; }
}
}
|
9509cb298d910d2dba22492103bdac79e4c7760a
|
C#
|
Lehcim1995/ProjectEuler
|
/ProjectEuler/Problems/Problem12.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectEuler.Classes;
using ProjectEuler.Interfaces;
namespace ProjectEuler.Problems
{
class Problem12 : IProblem
{
public long Answer(params long[] arguments)
{
MyMaths mm = new MyMaths();
for (int i = 0; i < 2000000; i++)
{
int tri = mm.TriangleNumber(i);
int dev = mm.NumberOfDevisors(tri);
if (dev > 500)
{
return tri;
}
}
return 0;
}
}
}
|
20f35124f0cd65fec24f944db89e0d7e482fe1f5
|
C#
|
inmovery/ProxyGrabber
|
/ProxyGrabber/Models/Proxy.cs
| 2.734375
| 3
|
namespace ProxyGrabber.Models {
public class Proxy {
public string Ip { get; set; }
public string Port { get; set; }
public ProxyType Type { get; set; }
public Location Location { get; set; }
public Anonymity Anonymity { get; set; }
public int Speed { get; set; }
public Proxy(string ipAddress, string port, ProxyType type, Location location, Anonymity anonymity, int speed) {
this.Ip = ipAddress;
this.Port = port;
this.Type = type;
this.Location = location;
this.Anonymity = anonymity;
this.Speed = speed;
}
public Proxy() { }
}
}
|
bd31f72a7b87ee7148fc501f4c35ceea5b4d3a21
|
C#
|
Ehasaniceiu04/R-D
|
/RD/Program.cs
| 3.171875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Dynamic;
namespace ProblemSolving
{
class Program
{
static void Main(string[] args)
{
var test = GetDynamicData(2);
Console.WriteLine(test.Name);
}
public static dynamic GetDynamicData(dynamic i)
{
dynamic listdata = new[]
{ new {
Id=1,
Name = "Ehasanul Hoque",
Position = "Senior Software Engineeer"
},
new {
Id=2,
Name = "Ehasanul Hoque",
Position = "Senior Software Engineeer"
}
,
new {
Id=3,
Name = "Ehasanul Hoque",
Position = "Senior Software Engineeer"
}
}.ToList();
var data = ((IEnumerable< dynamic >) listdata).Where(x => x.Id == i).SingleOrDefault();
return data;
}
}
}
|
4cd13474d9bfe04c5163074879d75a0d6fdb932c
|
C#
|
zhanwei103/AlumniPlatform
|
/Common.DbFactory/Factory.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.DbFactory
{
public sealed class Factory
{
private static volatile Factory singleFactory = null;
private static object syncObj = new object();
/// <summary>
/// Factory类构造函数
/// </summary>
private Factory()
{
}
/// <summary>
/// 获得Factory类的实例
/// </summary>
/// <returns>Factory类实例</returns>
public static Factory GetInstance()
{
if (singleFactory == null)
{
lock (syncObj)
{
if (singleFactory == null)
{
singleFactory = new Factory();
}
}
}
return singleFactory;
}
/// <summary>
/// 建立AbstractFactory类实例
/// </summary>
/// <returns>Factory类实例</returns>
public AbstractFactory CreateInstance()
{
string name = ConfigurationManager.AppSettings["defaultDataBase"];
return CreateInstance(name);
}
public AbstractFactory CreateInstance(string name)
{
AbstractFactory abstractFactory = null;
string dataBaseType=ConfigurationManager.ConnectionStrings[name].ProviderName;
switch (dataBaseType)
{
case "System.Data.SqlClient":
{
abstractFactory = new SqlFactory(name);
break;
}
case "System.Data.OracleClient":
{
abstractFactory = new OracleFactory(name);
break;
}
case "MySql.Data.MySqlClient":
{
abstractFactory = new MySqlFactory(name);
break;
}
default: abstractFactory = null;
break;
}
return abstractFactory;
}
}
}
|
34c1cb99ccbc5d56f3476292b2483ab70ce86f45
|
C#
|
KevinShevchuk/ProgrammingPracticeProblems
|
/ProgrammingPracticeProblems/Project Euler/EvenFibonacciNumbers.cs
| 4.1875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PracticeProblems
{
class EvenFibonacciNumbers
{
//Each new term in the Fibonacci sequence is generated by adding the previous two terms.By starting with 1 and 2, the first 10 terms will be:
//1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
//By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
public EvenFibonacciNumbers()
{
Console.WriteLine("Input the value to sum even Fibonacci numbers up to:");
string input = Console.ReadLine();
int max = 0;
if (int.TryParse(input, out max))
{
Console.WriteLine("----------Solution 1:-----------");
Solution1(max);
}
else
{
Console.WriteLine("Invalid Input.");
}
}
private void Solution1(int max)//O(n)
{
int x = 1;
int y = 2;
int sum = 0;
while (x < max && y < max)
{
if (y > x)
{
if (y % 2 == 0)
{
sum += y;
}
x += y;
}
else
{
if (x % 2 == 0)
{
sum += x;
}
y += x;
}
}
Console.WriteLine(sum);
}
}
}
|
ac769f30c5edfead74a6c8b2d0bcd8ec0ec1417c
|
C#
|
falseinteger/xamarinStocks
|
/Stocks/Core.cs
| 2.515625
| 3
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Stocks.Data;
namespace Stocks
{
public static class Core
{
/// <summary>
/// Действие когда выполняется обновление валют, при условии что есть данные
/// </summary>
public static Action ActionUpdate;
static Task taskListUpdate;
static CancellationTokenSource taskListUpdateCancellationTokenSource;
/// <summary>
/// Запустить задачу на получение новых/обновление валют
/// </summary>
public static void StartUpdateStocks() {
System.Diagnostics.Debug.WriteLine("[StartUpdateStocks] Create new task update");
if (taskListUpdateCancellationTokenSource != null)
taskListUpdateCancellationTokenSource.Cancel();
taskListUpdateCancellationTokenSource = new CancellationTokenSource();
taskListUpdate = Task.Factory.StartNew ( async () => {
System.Diagnostics.Debug.WriteLine("[StartUpdateStocks] send rule CoreWeb");
var cacheData = await CoreWeb.GetDataCurrency();
if (cacheData == null)
return;
System.Diagnostics.Debug.WriteLine("[StartUpdateStocks] Have good data");
// Если пришли данные по валютам обновляем
Global.DataOfStocks = new DataStocks(cacheData);
ActionUpdate?.Invoke();
System.Diagnostics.Debug.WriteLine("[StartUpdateStocks] End");
}, taskListUpdateCancellationTokenSource.Token);
}
/// <summary>
/// Закрытие всех задач
/// </summary>
public static void DisposeUpdateStocks() {
System.Diagnostics.Debug.WriteLine("[DisposeUpdateStocks] Remove all");
if (taskListUpdateCancellationTokenSource != null)
taskListUpdateCancellationTokenSource.Cancel();
taskListUpdateCancellationTokenSource = null;
taskListUpdate = null;
}
}
}
|
020d24911bb55f476787b52209518208a1311833
|
C#
|
Pawel-kutsenko/CurrencyExchanger
|
/WinFormsMVP.Tests/Tests.cs
| 2.671875
| 3
|
using System.Collections.Generic;
using System.Linq;
using Moq;
using WinFormsMVP.Model;
using WinFormsMVP.Presenter;
using WinFormsMVP.View;
using Xunit;
namespace WinFormsMVP.Tests
{
public class PresenterTests
{
private readonly List<Customer> stubCustomerList = new List<Customer> {
new Customer {Name = "Jack", Currency = "Rub", Cash = "123456"},
new Customer {Name = "Jill", Currency = "Rub", Cash = "124456"},
new Customer {Name = "Sam", Currency = "Blr Rub", Cash = "125456"}
};
private readonly ICustomerView mockCustomerView;
private readonly ICustomerRepository mockCustomerRepository;
private readonly CustomerPresenter presenter;
public PresenterTests()
{
mockCustomerView = Mock.Of<ICustomerView>(view =>
view.CustomerList == new List<string>());
mockCustomerRepository = Mock.Of<ICustomerRepository>(repository =>
repository.GetAllCustomers() == stubCustomerList);
presenter = new CustomerPresenter(mockCustomerView, mockCustomerRepository);
}
[Fact]
public void Presenter_constructor_ShouldFillViewCustomerList()
{
var customerNames = from customer in stubCustomerList select customer.Name;
Assert.Equal<IList<string>>(mockCustomerView.CustomerList, customerNames.ToList());
}
[Fact]
public void Presenter_UpdateCustomerView_ShouldPopulateViewWithRightCustomer()
{
var mockRepo = Mock.Get(mockCustomerRepository);
mockRepo.Setup(repository => repository.GetCustomer(1)).Returns(stubCustomerList[1]);
presenter.UpdateCustomerView(1);
var mockView = Mock.Get(mockCustomerView);
mockView.VerifySet(view => view.CustomerName = stubCustomerList[1].Name);
mockView.VerifySet(view => view.Currency = stubCustomerList[1].Currency);
mockView.VerifySet(view => view.Cash = stubCustomerList[1].Cash);
}
[Fact]
public void Presenter_SaveCustomer_ShouldSaveSelectedCustomerToRepository()
{
var mockView = Mock.Get(mockCustomerView);
mockView.Setup(view => view.SelectedCustomer).Returns(2);
mockView.Setup(view => view.CustomerName).Returns(stubCustomerList[2].Name);
mockView.Setup(view => view.Currency).Returns(stubCustomerList[2].Currency);
mockView.Setup(view => view.Cash).Returns(stubCustomerList[2].Cash);
presenter.SaveCustomer();
var mockRepo = Mock.Get(mockCustomerRepository);
mockRepo.Verify(repository => repository.SaveCustomer(2, stubCustomerList[2]));
}
}
}
|
58df9c2440cb857802fed4a917b245c7b7c0b93a
|
C#
|
karlzakhary/god-of-war-mini
|
/Assets/Scripts/Melee Enemy/MeleeAttack.cs
| 2.609375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MeleeAttack : MonoBehaviour {
[Tooltip("Attack range of the Melee Enemy.")]
public float range = 2.2f;
[Tooltip("Time (in seconds) to wait between attacks.")]
public float timeBetweenAttacks = 2f;
[Tooltip("Weapon colliders of the Melee Enemy.")]
public Collider[] weaponColliders;
private Animator anim;
private GameObject player;
private bool playerInRange;
private string[] attacks = { "Sword Attack", "Sword&Sheild Attack"};
private MeleeHealth MeleeHealth;
// Use this for initialization
void Start () {
player = GameManager.instance.GetPlayer();
anim = GetComponent<Animator>();
StartCoroutine(attack());
MeleeHealth = GetComponent<MeleeHealth>();
}
// Update is called once per frame
void Update () {
if(Vector3.Distance(transform.position, player.transform.position) < range){
playerInRange = true;
rotateTowards(player.transform);
} else {
playerInRange = false;
}
}
IEnumerator attack(){
if(playerInRange && attacks.Length > 0 && !GameManager.instance.gameOver && MeleeHealth.isAlive){
int attackIndex = Random.Range(0, attacks.Length);
anim.Play(attacks[attackIndex]);
yield return new WaitForSeconds(timeBetweenAttacks);
}
yield return null;
StartCoroutine(attack());
}
public void DisableShield()
{
weaponColliders[1].enabled = false;
}
public void EnableShield()
{
weaponColliders[1].enabled = true;
}
public void DisableSword()
{
weaponColliders[0].enabled = false;
}
public void EnableSword(){
weaponColliders[0].enabled = true;
}
private void rotateTowards(Transform player) {
Vector3 direction = (player.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 1f);
}
}
|
be607ffe396289bfce0734d5b0377bae06947bab
|
C#
|
mygithub222225/designPatterns
|
/设计模式的艺术/FacadePattern/Sample2/NewEncryptFacade.cs
| 2.703125
| 3
|
using FacadePattern.Sample1;
namespace FacadePattern.Sample2
{
/// <summary>
/// 新加密外观类:具体外观类
/// </summary>
public class NewEncryptFacade : AbstractEncryptFacade
{
private readonly FileReader _reader = new();
private readonly NewCipherMachine _cipher = new();
private readonly FileWriter _writer = new();
public override void FileEncrypt(string fileNameSrc, string fileNameDes)
{
var plainStr = _reader.Read(fileNameSrc);
var encryptStr = _cipher.Encrypt(plainStr);
_writer.Write(encryptStr, fileNameDes);
}
}
}
|
f15550692918910914dc040bd8d56997e602873c
|
C#
|
shendongnian/download4
|
/first_version_download2/138568-9997960-22886654-2.cs
| 2.5625
| 3
|
private void Form1()
{
InitializeComponent();
if (IsInWinFormsDesignMode())
{
// your code stuff here
}
}
public static bool IsInWinFormsDesignMode()
{
bool returnValue = false;
#if DEBUG
if ( System.ComponentModel.LicenseManager.UsageMode ==
System.ComponentModel.LicenseUsageMode.Designtime )
{
returnValue = true;
}
#endif
return returnValue;
}
|
00dc77d12b991bbe1b7104a5b65566fde1016d22
|
C#
|
Kleiboy92/dev-Squares
|
/dev-Squares/Backend/ResultContainer.cs
| 2.859375
| 3
|
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
namespace dev_Squares.Backend
{
public class ResultContainer : IEnumerable<Result>
{
public bool Finished { get; private set; } = false;
public bool Started { get; private set; } = false;
public int Length { get { return results.Count; } }
private ConcurrentQueue<Result> results = new ConcurrentQueue<Result>();
public ResultContainer()
{
}
public void Add(Result result)
{
this.results.Enqueue(result);
}
private CancellationTokenSource ct = new CancellationTokenSource();
public void Start(CancellationTokenSource ct)
{
this.Started = true;
this.Finished = false;
this.ct = ct;
}
public void End()
{
this.Started = false;
this.Finished = true;
}
public void Clear()
{
this.ct.Cancel();
this.results = new ConcurrentQueue<Result>();
Finished = false;
Started = false;
}
public IEnumerator<Result> GetEnumerator()
{
return results.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return results.GetEnumerator();
}
}
}
|