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
|
|---|---|---|---|---|---|---|
48dc004d3fdb938e95f656b9deb400fb604b2aa6
|
C#
|
SolidSquib/fighter
|
/Assets/Scripts/Utility/GameplayStatics.cs
| 2.984375
| 3
|
using UnityEngine;
namespace Fighter
{
public static class GameplayStatics
{
/* This accounts for perspective camera projections and ensures that vertical joystick movement always
* moves the character directly forwards and backwards instead of being influenced by the camera's
* perspective. It feels much nicer that the default behaviour. */
public static Vector3 ProjectInputVectorToCamera(Camera targetCamera, Transform referenceTransform, Vector3 inputVector)
{
Vector3 outputVector = inputVector;
if (!targetCamera.orthographic)
{
Vector3 forwardDirection = GetProjectedForwardVector(targetCamera, referenceTransform);
Vector3 lateral = targetCamera.transform.right * inputVector.x;
Vector3 forward = forwardDirection * inputVector.z;
outputVector = (lateral + forward).normalized;
}
return outputVector;
}
public static Vector3 GetProjectedForwardVector(Camera targetCamera, Transform referenceTransform)
{
Vector3 screenPoint = targetCamera.WorldToScreenPoint(referenceTransform.position);
Ray ray = targetCamera.ScreenPointToRay(screenPoint);
Vector3 forwardDirection = ray.direction;
forwardDirection.y = 0;
return forwardDirection.normalized;
}
}
}
|
ce17af83754ed49ee32071c6b5168d264a53e3aa
|
C#
|
johannprell/FivePrototypes
|
/01_AugustPrototype/Assets/Scripts/Pooling/ParticlesPool.cs
| 2.78125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Domination
{
public class ParticlesPool : MonoBehaviour
{
/* --- MEMBER VARIABLES --- */
[SerializeField]
private GameObject _particleObj;
[SerializeField]
private int _instancesInPool;
[SerializeField]
private int _currentIndex;
private List<PooledParticle> _pooledParticles;
/* --- UNITY METHODS --- */
void Start()
{
InitiatePool();
}
void Update()
{
}
/* --- CUSTOM METHODS --- */
public void PlaceAndPlayParticle(Vector3 position, Quaternion rotation)
{
_pooledParticles[_currentIndex].PlaceAndPlay(position, rotation);
CycleIndex();
}
private void InitiatePool()
{
_pooledParticles = new List<PooledParticle>();
for (int i = 0; i < _instancesInPool; i++)
{
_pooledParticles.Add(Instantiate(_particleObj, transform.position, transform.rotation, transform).GetComponent<PooledParticle>());
}
}
private void CycleIndex()
{
if(_currentIndex == _pooledParticles.Count - 1)
{
_currentIndex = 0;
}
else
{
_currentIndex++;
}
}
}
}
|
baf991549567e132f65c7d7fd0002c53f0d2c081
|
C#
|
adina-blanaru/AutomationPractice
|
/AutomationPractice.PageObjects/PageObjects/BasePage.cs
| 3.28125
| 3
|
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using System;
namespace AutomationPractice.PageObjects.PageObjects
{
public static class BasePage
{
public static void HoverOver(IWebDriver driver, IWebElement element)
{
Actions action = new Actions(driver);
action.MoveToElement(element).Perform();
}
public static string GetCurrentTimestamp()
{
return DateTime.Now.ToString("MM-dd-yyyy-HH-mm-ss");
}
public static string GetCurrentDate(string format)
{
return DateTime.Now.ToString(format);
}
public static int GetRandomNumberBetween(int min, int max)
{
var random = new Random();
return random.Next(min, max);
}
public static double CurrencyToDouble(string value)
{
//converts "$28.98" to 28.98
return double.Parse(value.Substring(1));
}
}
}
|
db4e6b35b8ee983e59c833517edd7ce9e0bdb2bb
|
C#
|
radtek/Checkmarx_Query
|
/Objc/Cx/General/Find_Downloaded_Data.cs
| 2.515625
| 3
|
// Find_Downloaded_Data
// ----------------------------------------------
// This query finds all url strings that contain http scheme (http or https according to parameter), as well as all
// NSData objects that were retrieved from these http urls via connection delegates.
if (param.Length > 0)
{
CxList http = param[0] as CxList;
CxList downloadData = All.NewCxList();
CxList methods = Find_Methods();
CxList connections = methods.FindByMemberAccess("NSURLConnection.connectionWithRequest:delegate:");
List<string> connectionsMethodsNames = new List<string>() {
"initWithRequest:delegate:","initWithRequest:delegate:startImmediately:",
"*WithContentsOfURL:*","*initWithContentsOfURL:*",
//Swift
"init:request:delegate:","init:delegate:","init:request:delegate:startImmediately:",
"init:delegate:startImmediately:"
};
connections.Add(methods.FindByShortNames(connectionsMethodsNames));
connections.Add(methods.FindByShortName("NSURLConnection:delegate:").FindByParameterName("request", 0));
connections.Add(methods.FindByShortName("NSURLConnection:delegate:startImmediately:").FindByParameterName("request", 0));
connections.Add(methods.FindByShortName("NSData:").FindByParameterName("contentsOf", 0));
CxList classDecl = Find_Classes();
CxList methodDecl = Find_MethodDecls();
CxList declarator = Find_Declarators();
CxList typeRef = Find_TypeRef();
CxList connectionParamers0 = All.GetParameters(connections, 0);
CxList connectionParamers1 = All.GetParameters(connections, 1);
CxList paramDef = All.FindDefinition(connectionParamers1);
List<string> allDidReceiveDataMethodsNames = new List<string>() {
"connection:didReceiveData:","URLSession:dataTask:didReceiveData:",
"urlSession:dataTask:didReceive:","urlSession:didReceive:"
};
CxList allDidReceiveData = methodDecl.FindByShortNames(allDidReceiveDataMethodsNames);
CxList didReceiveDataParams = All.GetParameters(allDidReceiveData, 1);
didReceiveDataParams -= didReceiveDataParams.FindByType(typeof(Param));
foreach (CxList connection in connections)
{
CxList pathPart1 = connectionParamers0.GetParameters(connection, 0).DataInfluencedBy(http);
if (pathPart1.Count > 0)
{
CxList connectionDelegate = connectionParamers1.GetParameters(connection, 1);
connectionDelegate -= connectionDelegate.FindByType(typeof(Param));
bool isThis = (connectionDelegate.FindByType(typeof(ThisRef)).Count > 0);
pathPart1 = pathPart1.ConcatenatePath(connectionDelegate);
if (!isThis)
{
pathPart1 = pathPart1.ConcatenatePath(paramDef.FindDefinition(connectionDelegate));
}
// Find all the class declarators that are a reference of the delgate (self)
CxList delegateClass = classDecl.FindAllReferences(connectionDelegate);
// Find the case where the delegate is not for self, but of another class
CxList delegateDelarator = declarator.FindAllReferences(connectionDelegate);
CxList declarators = delegateDelarator.GetAncOfType(typeof(VariableDeclStmt));
if (declarators.Count > 0)
{
CxList definition = All.FindByType(typeRef.GetByAncs(declarators));
CxList classDef = classDecl.FindDefinition(definition);
delegateClass.Add(classDef);
}
foreach (CxList cls in delegateClass)
{
if (!isThis)
{
pathPart1 = pathPart1.ConcatenatePath(cls);
}
CxList didReceiveData = allDidReceiveData.GetByAncs(cls);
downloadData.Add(pathPart1.ConcatenatePath(didReceiveDataParams.GetParameters(didReceiveData, 1)));
}
}
}
List<string> urlMethodsNames = new List<string>() {
"*WithContentsOfURL:*","*initWithContentsOfURL:*"
};
CxList urlMethods = methods.FindByShortNames(urlMethodsNames);
urlMethods.Add(methods.FindByShortName("NSString:encoding:*").FindByParameterName("contentsOf", 0));
urlMethods.Add(methods.FindByShortName("NSString:encoding:*").FindByParameterName("contentsOfURL", 0));
urlMethods.Add(methods.FindByShortName("NSString:encoding:*").FindByParameterName("format:", 0));
urlMethods.Add(methods.FindByShortName("String:encoding:*").FindByParameterName("contentsOf:", 0));
downloadData.Add(urlMethods);
//for swift
CxList swift_potential_connection_methods = All.NewCxList();
List<string> swiftPotentialConnectionMethodsNames = new List<string>() {
"NSString:encoding:*","NSString:usedEncoding:*","NSMutableString:encoding:*",
"NSMutableString:usedEncoding:*","NSData:","NSData:options:*","NSMutableData:","NSMutableData:options:*",
"NSArray:","NSMutableArray:","NSDictionary:","NSMutableDictionary:","NSMutableDictionary:",
"dataTaskWithURL:","dataTaskWithURL:completionHandler:"
};
CxList allConnectionsMethods = methods.FindByShortNames(swiftPotentialConnectionMethodsNames);
swift_potential_connection_methods.Add(allConnectionsMethods);
swift_potential_connection_methods.Add(allConnectionsMethods.FindByParameterName("contentsOf", 0));
swift_potential_connection_methods.Add(allConnectionsMethods.FindByParameterName("contentsOfURL", 0));
swift_potential_connection_methods.Add(allConnectionsMethods.FindByParameterName("format:", 0));
CxList relevant_http = Find_By_Type_And_Casting(http, "NSURL");
relevant_http.Add(Find_By_Type_And_Casting(http, "URL"));
CxList first_params = relevant_http.GetParameters(methods, 0);
CxList swift_connection_methods = swift_potential_connection_methods * methods.FindByParameters(first_params);
downloadData.Add(swift_connection_methods);
result = downloadData;
}
|
0329a09a0f26cdeaf8a5bb1f641f6551e42fd9ce
|
C#
|
AntoniaChavdarova/EasyTravel
|
/Services/EasyTravel.Services.Data/BookingsService.cs
| 2.765625
| 3
|
namespace EasyTravel.Services.Data
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EasyTravel.Data.Common.Repositories;
using EasyTravel.Data.Models;
using EasyTravel.Services.Mapping;
using Microsoft.EntityFrameworkCore;
public class BookingsService : IBookingsSerivece
{
private readonly IDeletableEntityRepository<Booking> bookingsRepository;
private readonly IDeletableEntityRepository<Property> propertiesRepository;
public BookingsService(
IDeletableEntityRepository<Booking> bookingsRepository,
IDeletableEntityRepository<Property> propertiesRepository)
{
this.bookingsRepository = bookingsRepository;
this.propertiesRepository = propertiesRepository;
}
public async Task MakeBookingAsync(string userId, int propertyId, DateTime checkIn, DateTime checkOut, int guestsCount)
{
if (!this.IsDatesValid(checkIn, checkOut))
{
throw new Exception($"Invalid dates");
}
if (!this.IsDatesAvailable(propertyId, checkIn, checkOut))
{
throw new Exception($"The dates are not available ");
}
if (!this.IsDatesBetweenExistingReservation(propertyId, checkIn, checkOut))
{
throw new Exception($"The dates are not available ");
}
if (!this.IsCheckInBettweenExistingReservation(propertyId, checkIn, checkOut))
{
throw new Exception($"The dates are not available ");
}
if (!this.IsCheckOutBettweenExistingReservation(propertyId, checkIn, checkOut))
{
throw new Exception($"The dates are not available ");
}
if (this.ProperyMaxGuestCount(propertyId) < guestsCount)
{
throw new Exception($"The Capacity of the property it is not enough");
}
var booking = this.bookingsRepository.All()
.FirstOrDefault(x => x.UserId == userId && x.PropertyId == propertyId && x.CheckIn == checkIn && x.CheckOut == checkOut);
if (booking == null)
{
booking = new Booking
{
UserId = userId,
PropertyId = propertyId,
CheckIn = checkIn,
CheckOut = checkOut,
PeopleCount = guestsCount,
};
await this.bookingsRepository.AddAsync(booking);
}
await this.bookingsRepository.SaveChangesAsync();
}
public async Task<IEnumerable<T>> MyBookings<T>(string userId)
{
return await this.bookingsRepository.AllWithDeleted()
.Where(x => x.UserId == userId)
.OrderBy(x => x.CheckIn)
.To<T>()
.ToListAsync();
}
public async Task<T> GetByIdAsync<T>(int id)
{
return
await this.bookingsRepository
.All()
.Where(x => x.Id == id)
.To<T>().FirstOrDefaultAsync();
}
public async Task DeleteAsync(int id)
{
var booking =
await this.bookingsRepository
.All()
.Where(x => x.Id == id)
.FirstOrDefaultAsync();
this.bookingsRepository.Delete(booking);
await this.bookingsRepository.SaveChangesAsync();
}
private bool IsDatesBetweenExistingReservation(int propertyId, DateTime checkIn, DateTime checkOut)
{
var booking = this.bookingsRepository.AllAsNoTracking()
.FirstOrDefault(x => x.PropertyId == propertyId && checkIn >= x.CheckIn && checkOut <= x.CheckOut);
if (booking == null)
{
return true;
}
return false;
}
private bool IsCheckInBettweenExistingReservation(int propertyId, DateTime checkIn, DateTime checkOut)
{
var booking = this.bookingsRepository.AllAsNoTracking()
.FirstOrDefault(x => x.PropertyId == propertyId && checkIn >= x.CheckIn && checkIn < x.CheckOut
|| x.PropertyId == propertyId && checkIn < x.CheckIn && checkOut <= x.CheckOut && checkOut > x.CheckIn);
if (booking == null)
{
return true;
}
return false;
}
private bool IsCheckOutBettweenExistingReservation(int propertyId, DateTime checkIn, DateTime checkOut)
{
var booking = this.bookingsRepository.AllAsNoTracking()
.FirstOrDefault(x => x.PropertyId == propertyId && checkOut > x.CheckIn && checkOut <= x.CheckOut);
if (booking == null)
{
return true;
}
return false;
}
private bool IsDatesAvailable(int propertyId, DateTime checkIn, DateTime checkOut)
{
var booking = this.bookingsRepository.AllAsNoTracking()
.FirstOrDefault(x => x.PropertyId == propertyId && x.CheckIn == checkIn && x.CheckOut == checkOut);
if (booking == null)
{
return true;
}
return false;
}
private bool IsDatesValid(DateTime checkIn, DateTime checkOut)
{
if (checkIn > checkOut)
{
return false;
}
if (checkIn < DateTime.UtcNow && checkOut <= DateTime.UtcNow)
{
return false;
}
return true;
}
private int ProperyMaxGuestCount(int propertyId)
{
var maxGuestCount = this.propertiesRepository
.All()
.FirstOrDefault(x => x.Id == propertyId)
.Capacity;
return maxGuestCount;
}
}
}
|
8d7b7f42aad9834a34e8f0273da6adeef5d0947e
|
C#
|
TKseniya/Game
|
/Lab_game/Core.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Lab_game
{
public static class Core
{
static Core()
{
Factory.CreateRandomArmy(0);
Factory.CreateRandomArmy(1);
}
public static void Start()
{
Factory.CreateRandomArmy(0);
Factory.CreateRandomArmy(1);
//Consts.Condition = new Condition();
var comparer = new UnitComparer();
using (Consts.Sw = new StreamWriter("Battle.txt", false))
{
for (var i = 0; i < 2; i++)
{
Consts.Sw.WriteLine("Армия {0} :", Consts.PlayerName[i]);
foreach (var unit in Consts.Stacks[i].Distinct(comparer))
Consts.Sw.WriteLine("{0}: {1}", unit.Name,
Consts.Stacks[i].FindAll(p => p.Name == unit.Name).Count);
}
Consts.Sw.WriteLine();
Consts.Strategy.ShowArmies();
do
{
Battle();
} while (Consts.Stacks[0].Count != 0 && Consts.Stacks[1].Count != 0 && !Consts.DeadHeat);
End();
Consts.Sw.Close();
}
}
private static void End()
{
if (!Consts.DeadHeat)
{
Consts.Sw.WriteLine("{0} won",
(Consts.Stacks[0].Count() > 0 ? Consts.PlayerName[0] : Consts.PlayerName[1]));
}
}
private static void Battle()
{
Consts.N ++;
Consts.Sw.WriteLine("\nState: {0}\n", Consts.N);
Consts.Strategy.Battle();
Consts.Sw.WriteLine();
if (Consts.Stacks[0].Count == 0 || Consts.Stacks[1].Count == 0)
return;
IUnit unit;
int Range;
var i = Consts.Strategy.CalcIndex(out Range);
if (Consts.SomeoneDied)
{
Consts.Strategy.ShowArmies();
Consts.SomeoneDied = false;
Consts.SomeoneCloned = false;
if (Consts.Stacks[0].Count == 0 || Consts.Stacks[1].Count == 0)
return;
}
Consts.Sw.WriteLine("\nTry SpecialAction\n");
if (Consts.Stacks[0].Count > i[0] || Consts.Stacks[1].Count > i[1])
do
{
//выбираем первого
int id = Consts.Rand.Next(2);
//поочереди для 2 юнитов с одинаковыми индексами вызывается спешл экшен
for (var j = 0; j < 2; j++)
{
//если юнит с нужным индексом существует
if (Consts.Stacks[Math.Abs(id - j)].Count > i[Math.Abs(id - j)])
{
//выбранный юнит
unit = Consts.Stacks[Math.Abs(id - j)][i[Math.Abs(id - j)]];
if (unit is ISpecialAction)
{
//список юнитов, на которых данный юнит может воздействовать
var list = new List<IUnit>(Consts.Strategy.GetUnits((ISpecialAction) unit));
if (list.Count > 0)
{
var u = ((ISpecialAction) unit).SpecialAction(list);
if (u != null)
{
if (u.HP <= 0)
{
Consts.Strategy.ChangeIndex(u, ref i);
if (Consts.SomeoneDied)
{
Consts.Stacks[u.PlayerId].RemoveAll(dead => dead.HP <= 0);
}
}
}
}
}
}
i[Math.Abs(id - j)]++;
}
} while (i[0] < Range && i[1] < Range);
else
{
Consts.Sw.WriteLine("No special actions\n");
}
// Consts.Condition.RecordCondition();
if (Consts.DeadHeat)
{
Consts.Sw.WriteLine("Friendship won!");
return;
}
Consts.Sw.WriteLine();
if (Consts.SomeoneDied || Consts.SomeoneCloned)
{
Consts.Strategy.ShowArmies();
Consts.SomeoneDied = false;
Consts.SomeoneCloned = false;
}
}
}
public class UnitComparer : IEqualityComparer<IUnit>
{
public bool Equals(IUnit x, IUnit y)
{
return String.CompareOrdinal(x.Name, y.Name) == 0;
}
public int GetHashCode(IUnit obj)
{
if (ReferenceEquals(obj, null)) return 0;
var hashName = obj.Name == null ? 0 : obj.Name.GetHashCode();
return hashName;
}
}
}
|
12ae58379e48d48614df88cc6d3267e2175fa4c4
|
C#
|
tanishi109/try-unity
|
/Project Tanuki/Assets/Scripts/PlayerModel.cs
| 2.671875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerModel : MonoBehaviour {
public float[] legStates;
private float maxLegState = 5.0f;
private float minLegState = 0.0f;
private float jumpDuration = 0.5f;
private float legGrowSpeed = 0.5f;
private float legShrinkSpeed = -1.0f;
void Awake() {
legStates = new float[] {0f, 0f, 0f};
}
public void GrowLeg(int index, bool isGrow) {
float amount = isGrow ? legGrowSpeed : legShrinkSpeed;
float newState = legStates [index] + amount;
if (newState > maxLegState) {
newState = maxLegState;
}
if (newState < minLegState) {
newState = minLegState;
}
legStates [index] = newState;
}
public Vector3 GetLegScale(int index) {
return new Vector3 (0.25f, 0.25f, legStates [index] + 1f);
}
public int GetMimicType () {
int extendedLegs = 0;
foreach (float state in legStates) {
if (IsExtended(state)) {
extendedLegs++;
}
}
if (extendedLegs == 0) {
return 0; // Rock
}
if (extendedLegs == 2) {
return 1; // Scissors
}
if (extendedLegs == 3) {
return 2; // Paper
}
return -1; // Other
}
public IEnumerator JumpTo (Vector3 to) {
Vector3 currentPos = transform.position;
float t = 0f;
while(t < 1) {
t += Time.deltaTime / jumpDuration;
transform.position = Vector3.Lerp(currentPos, to, t);
yield return null;
}
}
private bool IsExtended (float legState) {
return legState >= maxLegState / 2;
}
}
|
23d24dc3780ffd1fb5906a5d454f71e5f7654287
|
C#
|
jmmccota/EFCore
|
/EfCore/Controllers/TesteController.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Persistence.Data;
using Persistence.Models;
using Persistence.Services;
namespace EfCore.Controllers
{
[Route("api/[controller]/[action]")]
public class TesteController : Controller
{
private BookService BookService;
private AuthorService AuthorService;
public TesteController(LibraryContext ctx)
{
BookService = new BookService(ctx);
AuthorService = new AuthorService(ctx);
}
/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Sample request:
///
/// POST /Todo
/// {
/// "id": 1,
/// "name": "Item1",
/// "isComplete": true
/// }
///
/// </remarks>
/// <param name="item"></param>
/// <returns>A newly-created TodoItem</returns>
/// <response code="201">Returns the newly-created item</response>
/// <response code="400">If the item is null</response>
[HttpGet]
public string Povoa()
{
var b = new Book
{
Author = new Author { Name = "Joao", MailId = "2" },
Description = "Meu livro",
Title = "Livro"
};
BookService.Salvar(b);
return b.BookId.ToString();
}
[HttpGet]
public ICollection<Book> ListarTodos()
{
return BookService.ObterTodos();
}
[HttpPut]
public Book PutLivro([FromBody]Book value)
{
BookService.Salvar(value);
return value;
}
[HttpDelete("{id}")]
public void DeleteLivro(int id)
{
BookService.ExcluirPorId(id);
}
[HttpGet]
public ICollection<Author> AutoresComMais10Livros()
{
return AuthorService.ListarAutoresComMaisDe10Livros();
}
}
}
|
194f57397506acf5f3a8d967f34c50a54db135bf
|
C#
|
Anton2725/Unit14_3
|
/Contact.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Unit14_3
{
public class Contact // модель класса
{
public Contact(string name, string lastName, long phoneNumber, String email) // метод-конструктор
{
Name = name;
LastName = lastName;
PhoneNumber = phoneNumber;
Email = email;
}
public String Name { get; }
public String LastName { get; }
public long PhoneNumber { get; }
public String Email { get; }
}
}
|
268a191052081a6c3f7218b9550fa5f7fc822875
|
C#
|
FremyXS/lab04
|
/lab04.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Security;
namespace lab04
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Введите текст");
string text = Console.ReadLine();
List <string> PerehodMexhClass = new List<string>();
SentencesParserTask p1 = new SentencesParserTask();
p1.ListSentence(text, ref PerehodMexhClass);
Console.WriteLine("---------------------------------------------------------------------------------------");
FrequencyAnalysisTask p2 = new FrequencyAnalysisTask();
p2.DictSentence(PerehodMexhClass);
}
}
class SentencesParserTask
{
public void ListSentence(string text, ref List<string> Sentence)
{
Sentence.AddRange(text.Trim().ToLower().Split('.', '!', '?', ';', ':', '(', ')'));
int KolSentence = 0;
foreach (string i in Sentence)
KolSentence++;
List<string> Words = new List<string>();
for (int i = 0; i < KolSentence; i++)
Words.AddRange(Sentence[i].Trim().Split(' ', ','));
int WordsIt = 0;
foreach (string i in Words)
WordsIt++;
List<string> NewListWords = new List<string>();
for (int i = 0; i < WordsIt; i++)
{
if (Words[i] != "")
NewListWords.Add(Words[i]);
}
foreach (string i in NewListWords)
Console.WriteLine(i);
}
}
class FrequencyAnalysisTask
{
public void DictSentence(List <string> Words)
{
List<string> xxx = new List<string>();
List<string> yyy = new List<string>();
int WordIt = 0;
foreach (string i in Words)
WordIt++;
int Kol;
for (int i = 0; i < WordIt; i++)
{
string[] MassiveWords = Words[i].ToLower().Trim().Split(' ', ',');
Kol = 0;
foreach (string n in MassiveWords)
Kol++;
if (Kol > 1)
{
for (int t = 0; t < Kol - 1; t++)
{
xxx.Add(MassiveWords[t]);
yyy.Add(MassiveWords[t + 1]);
}
}
}
int KolXandY = 0;
foreach (string i in xxx)
KolXandY++;
List<string> NewXXX = new List<string>();
List<string> NewYYY = new List<string>();
int KolXXX = 0;
int KolYYY = 0;
foreach (string i in xxx)
KolXXX++;
foreach (string i in yyy)
KolYYY++;
for (int i = 0; i < KolXXX; i++)
{
if (xxx[i] != "")
NewXXX.Add(xxx[i]);
}
for (int i = 0; i < KolYYY; i++)
{
if (yyy[i] != "")
NewYYY.Add(yyy[i]);
}
Dictionary<string, string> DictWords = new Dictionary<string, string>();
for (int i = 0; i < KolXandY; i++)
{
DictWords.Add(NewXXX[i], NewYYY[i]);
}
foreach (KeyValuePair<string, string> keyValue in DictWords)
{
Console.WriteLine(keyValue.Key + " : " + keyValue.Value);
}
}
}
}
|
839b8e2f2b1d4b143d48a653b922251059693109
|
C#
|
SweDark/Library
|
/Library.Infrastructure/Services/BookService.cs
| 3.09375
| 3
|
using Library.Application.Interfaces;
using Library.Domain;
using Library.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Library.Infrastructure.Services
{
public class BookService : IBookService
{
private readonly ApplicationDbContext context;
public BookService(ApplicationDbContext context)
{
this.context = context;
}
public void AddBook(BookDetails book)
{
context.Add(book);
context.SaveChanges();
}
public ICollection<BookDetails> GetAllBooks()
{
// Here we are using .Include() to eager load the author, read more about loading related data at https://docs.microsoft.com/en-us/ef/core/querying/related-data
return context.BookDetails.Include(x => x.Author).Include(y => y.Copies).OrderBy(x => x.Title).ToList();
}
public ICollection<BookDetails> GetAllAvailableBooks(ICollection<Loan> loanedBooks)
{
var books = GetAllBooks();
// prestanda problem?
foreach(var loanedbook in loanedBooks)
{
foreach (var book in books)
{
if(loanedbook.bookCopy.Details.ID == book.ID)
{
book.Copies.Remove(loanedbook.bookCopy);
}
}
}
return books.Where(x => x.Copies.Count != 0).OrderBy(x => x.Title).ToList();
}
public BookDetails GetBook(int? id)
{
BookDetails book = new BookDetails();
book = context.BookDetails.Include(y => y.Copies).SingleOrDefault(x => x.ID == id);
return book;
}
public void UpdateBookDetails(BookDetails book)
{
context.Update(book);
context.SaveChanges();
}
public void UpdateBookDetails(int id, BookDetails book)
{
context.Update(book);
context.SaveChanges();
}
public void DeleteBookDetails(BookDetails book, ICollection<Loan> loanedBooks)
{
if(loanedBooks.Count == 0)
{
context.Remove(book);
context.SaveChanges();
}
else
{
throw new OperationCanceledException();
}
}
public ICollection<BookDetails> GetBooksBySearch(string searchString)
{
var search = context.BookDetails.Where(s => s.Title.Contains(searchString)).Include(x => x.Copies).Include(x => x.Author).OrderBy(x => x.Title).ToList();
if(search.Count > 0)
{
return search;
} else
{
throw new KeyNotFoundException();
}
}
}
}
|
f00a8164de60952a1828018f5b526c8196af8be9
|
C#
|
tcm/csharp_snip
|
/day18/DataTableDemo.cs
| 3.203125
| 3
|
using System;
using System.Data;
// Compilieren mit:
// mcs DataTableDemo.cs -r:System.Data.dll -r:System.Data.DataSetExtensions.dll
class DataTableDemo
{
static void Main ()
{
// DataTable holen.
DataTable data = GetTable ();
// Schleife um alle Datensätze zurückzugeben.
foreach (DataRow row in data.Rows)
{
Console.WriteLine(row.Field<int>(0));
}
}
static DataTable GetTable ()
{
DataTable table = new DataTable();
// Tabelle mit 4 Feldern anlegen.
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// 5 Datensätze hinzufügen.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
return table;
}
}
|
2f8636e2879f05a0d60c63dea5fe9c03ec633f4c
|
C#
|
karpediemnow/mysql-class-generator
|
/MysqlClassGenerator/ClassModellator/XmlDocumentatiionModellator.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ClassModellator
{
/// <summary>
/// http://msdn.microsoft.com/it-it/library/5ast78ax(VS.80).aspx
/// </summary>
public class XmlDocumentationModellator
{
/*
<param name="name"> permette di specificare i parametri passati ad un metodo
<paramref name="name"> permette di specificare che una determinata parola è un parametro
<returns> il valore di ritorno del metodo
<exceptions cref="type"> permette di specifire le eccezioni che possono verificarsi
<permission cref="type"> permette di specificare il livello di accesso
<value> consente di descrivere una proprietà
<example> specifica un esempio relativo all’utilizzo del codice
<c> il testo deve essere identificato come codice
<code> più righe devono essere identificato come codice
<para> Si può inserire all’interno di alcuni tag come <summary>, <remarks> o <returns>, e permette di aggiungere una struttura al testo.
*/
#region encapsulated property
private String _summary;
/// <summary>
/// Una descrizione generica di un metodo, una classe o altro
/// </summary>
public String Summary
{
get { return _summary; }
set { _summary = value; }
}
private List<xmlDocListModellator> _listList;
public List<xmlDocListModellator> List
{
get { return _listList; }
set { _listList = value; }
}
private List<xmlIncludeModellator> _includeList;
public List<xmlIncludeModellator> Include
{
get { return _includeList; }
set { _includeList = value; }
}
private String _remarks;
/// <summary>
/// informazioni addizionali
/// </summary>
public String Remarks
{
get { return _remarks; }
set { _remarks = value; }
}
private List<xmlParamNameMolellator> _paramNameList;
public List<xmlParamNameMolellator> ParamName
{
get { return _paramNameList; }
set { _paramNameList = value; }
}
//private Hashtable _paramref;
//public Hashtable Paramref
//{
// get { return _paramref; }
// set { _paramref = value; }
//}
private string _returns;
public string Returns
{
get { return _returns; }
set { _returns = value; }
}
private List<xmlDoxExcepionModellator> _exceptionsList;
public List<xmlDoxExcepionModellator> Exceptions
{
get { return _exceptionsList; }
set { _exceptionsList = value; }
}
private String _permission;
public String Permission
{
get { return _permission; }
set { _permission = value; }
}
private String _value;
public String Value
{
get { return _value; }
set { _value = value; }
}
private string _example;
public string Example
{
get { return _example; }
set { _example = value; }
}
//private String _c;
//public String C
//{
// get { return _c; }
// set { _c = value; }
//}
private string _code;
public string Code
{
get { return _code; }
set { _code = value; }
}
//private string _para;
//public string Para
//{
// get { return _para; }
// set { _para = value; }
//}
#endregion
#region costructor
public XmlDocumentationModellator()
{
_paramNameList = new List<xmlParamNameMolellator>();
_exceptionsList = new List<xmlDoxExcepionModellator>();
_listList = new List<xmlDocListModellator>();
_includeList = new List<xmlIncludeModellator>();
}
#endregion
#region public functions
public void setParamName(List<VariableModellator> listaVariabili)
{
foreach (VariableModellator var in listaVariabili)
{
_paramNameList.Add(new xmlParamNameMolellator( var.Name, var.Description));
}
}
public string getXmlDocumentation()
{
StringBuilder sb = new StringBuilder();
#region summary
if (_summary != null)
{
sb.Append(Environment.NewLine);
sb.Append("/// <summary>" + Environment.NewLine);
sb.Append("/// " + _summary.Replace("\r", String.Empty).Replace("\n", Environment.NewLine + "///") + Environment.NewLine);
sb.Append("/// </summary>" + Environment.NewLine);
foreach (xmlDocListModellator list in _listList)
{
sb.Append(list.ToString());
}
}
#endregion
#region remarks
if (_remarks != null && _remarks.Length != 0)
{
sb.Append("/// <remarks>" + Environment.NewLine);
sb.Append("/// " + _remarks.Replace("\r",String.Empty).Replace("\n", Environment.NewLine + "///") + Environment.NewLine);
sb.Append("/// </remarks>" + Environment.NewLine);
}
#endregion
#region include list
foreach (xmlIncludeModellator include in _includeList)
{
sb.Append(include.ToString());
}
#endregion
#region example / code
if (_code != null && _code.Length != 0 && (_example == null || _example.Length == 0))
{
throw new ArgumentNullException("Example", "Attenction if set the Code param you can be set Example param");
}
else if (_example != null && _example.Length != 0)
{
sb.Append("/// <example> " + _example.Replace("\r",String.Empty).Replace("\n", Environment.NewLine + "///") + Environment.NewLine);
if (_code != null && _code.Length != 0)
{
sb.Append("/// <code>" + Environment.NewLine);
sb.Append("/// " + _code.Replace("\r",String.Empty).Replace("\n", Environment.NewLine + "///") + Environment.NewLine);
sb.Append("/// </code>" + Environment.NewLine);
}
sb.Append("/// </example>"+ Environment.NewLine);
}
#endregion
#region param name
foreach (xmlParamNameMolellator paramName in _paramNameList)
{
sb.Append(paramName.ToString());
}
#endregion
#region exception
foreach (xmlDoxExcepionModellator tmpEX in _exceptionsList){
sb.Append(tmpEX.ToString());
// sb.Append("/// <exception cref=\"" + tmpEX.CRefenence + "\">" + tmpEX.Description + "</exception>" + Environment.NewLine);
}
#endregion
#region value
if (_value != null && _value.Length != 0)
{
// /// <value>
// /// The Name property gets/sets the _name data member.
// /// </value>
sb.Append("/// <value>" +Environment.NewLine);
sb.Append("/// "+_value.Replace("\r",String.Empty).Replace("\n", Environment.NewLine + "///") +Environment.NewLine);
sb.Append("/// </value>" + Environment.NewLine);
}
#endregion
#region returns
if (_returns != null && _returns.Length != 0)
{
sb.Append("/// <returns>" +Environment.NewLine);
sb.Append("/// "+_returns.Replace("\r",String.Empty).Replace("\n", Environment.NewLine + "///") +Environment.NewLine);
sb.Append("/// </returns>" + Environment.NewLine);
}
#endregion
return sb.ToString();
}
#endregion
}
/// <summary>
/// http://msdn.microsoft.com/it-it/library/w1htk11d(VS.80).aspx
/// </summary>
public class xmlDoxExcepionModellator
{
String _description;
public String Description
{
get { return _description; }
set { _description = value; }
}
String _cRefenence;
public String CRefenence
{
get { return _cRefenence; }
set { _cRefenence = value; }
}
public xmlDoxExcepionModellator()
{
_cRefenence = _description = null;
}
public override string ToString()
{
return "\t/// <exception cref=\"" + _cRefenence.Replace("\n", String.Empty) + "\">" + _description.Replace("\n", String.Empty) + "</exception>" + Environment.NewLine;
}
}
/// <summary>
/// http://msdn.microsoft.com/it-it/library/y3ww3c7e(VS.80).aspx
/// </summary>
public class xmlDocListModellator
{
String _type;
public String Type
{
get { return _type; }
set { _type = value; }
}
List<string> _description;
public List<string> Description
{
get { return _description; }
set { _description = value; }
}
public xmlDocListModellator()
{
_description = new List<string>();
_type = String.Empty;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("/// <list type=\"" + _type.Replace("\n"," ") + "\">" + Environment.NewLine);
foreach (string tmpSTR in _description)
{
sb.Append("/// <item>" + Environment.NewLine);
sb.Append("/// <description>" + tmpSTR.Replace("\n", Environment.NewLine + "\t///") + "</description>" + Environment.NewLine);
sb.Append("/// </item>" + Environment.NewLine);
}
sb.Append("/// </list>"+Environment.NewLine);
return sb.ToString();
}
}
/// <summary>
/// http://msdn.microsoft.com/it-it/library/9h8dy30z(VS.80).aspx
/// </summary>
public class xmlIncludeModellator
{
//Nome del file che contiene la documentazione. È possibile qualificare il nome del file tramite un percorso. Racchiudere filename tra virgolette singole (' ').
String _filename;
public String Filename
{
get { return _filename; }
set { _filename = value; }
}
//Percorso dei tag di filename che porta al name del tag. Racchiudere il percorso tra virgolette singole (' ').
String _tagpath;
public String Tagpath
{
get { return _tagpath; }
set { _tagpath = value; }
}
//Identificatore del nome contenuto nel tag che precede i commenti. name ha sempre un id.
String _name;
public String Name
{
get { return _name; }
set { _name = value; }
}
//ID del tag che precede i commenti. Racchiudere l'ID tra virgolette doppie (" ").
String _id;
public String Id
{
get { return _id; }
set { _id = value; }
}
public xmlIncludeModellator()
{
_filename = _id = _name = _tagpath = String.Empty;
}
public override string ToString()
{
return "<include file='" + _filename.Replace("\n",string.Empty) + "' path='" + _tagpath.Replace("\n", String.Empty) + "[@" + _name.Replace("\n",string.Empty) + "=\"" + _id + "\"]' />";
}
}
/// <summary>
/// http://msdn.microsoft.com/it-it/library/8cw818w8(VS.80).aspx
/// </summary>
public class xmlParamNameMolellator
{
// /// <param name="Int1">Used to indicate status.</param>
//Nome di un parametro di metodo. Racchiudere il nome tra virgolette doppie (" ").
String _name;
public String Name
{
get { return _name; }
set { _name = value; }
}
//Descrizione del parametro.
String _description;
public String Description
{
get { return _description; }
set { _description = value; }
}
public xmlParamNameMolellator()
{
_name = String.Empty;
_description = String.Empty;
}
public xmlParamNameMolellator(String Name_Param ,String Description_Param )
{
_name = Name_Param;
_description = Description_Param;
}
public override string ToString()
{
if (_description == null)
{
_description = " ";
}
return "/// <param name=\"" + _name.Replace("\n", String.Empty) + "\">" + _description.Replace("\n",string.Empty) + "</param>" + Environment.NewLine;
}
}
/// <summary>
/// http://msdn.microsoft.com/it-it/library/h9df2kfb(VS.80).aspx
/// </summary>
public class xmlPermissionMolellator
{
//<permission cref="member">description</permission>
//Nome di un parametro di metodo. Racchiudere il nome tra virgolette doppie (" ").
String _name;
public String Name
{
get { return _name; }
set { _name = value; }
}
//Descrizione del parametro.
String _description;
public String Description
{
get { return _description; }
set { _description = value; }
}
public xmlPermissionMolellator()
{
_name = _description =String.Empty;
}
public xmlPermissionMolellator(String Name_Param, String Description_Param)
{
_name = Name_Param;
_description = Description_Param;
}
public override string ToString()
{
return "\t/// <permission cref=\"" + _name + "\">" + _description + "</permission>" + Environment.NewLine;
}
}
}
|
c0ad2c9af38a93c166a13f998a54eada3c88f2a8
|
C#
|
benjamin-hodgson/Sawmill
|
/Sawmill/Rewriter.RewriteIter.cs
| 3.328125
| 3
|
using System;
using System.Threading.Tasks;
namespace Sawmill;
public static partial class Rewriter
{
/// <summary>
/// Rebuild a tree by repeatedly applying a transformation function to every node in the tree,
/// until a fixed point is reached. <paramref name="transformer" /> should always eventually return
/// its argument unchanged, or this method will loop.
/// That is, <c>x.RewriteIter(transformer).SelfAndDescendants().All(x => transformer(x) == x)</c>.
/// <para>
/// This is typically useful when you want to put your tree into a normal form
/// by applying a collection of rewrite rules until none of them can fire any more.
/// </para>
/// </summary>
/// <typeparam name="T">The rewritable tree type.</typeparam>
/// <param name="rewriter">The rewriter.</param>
/// <param name="transformer">
/// A transformation function to apply to every node in <paramref name="value" /> repeatedly.
/// </param>
/// <param name="value">The value to rewrite.</param>
/// <returns>
/// The result of applying <paramref name="transformer" /> to every node in the tree
/// represented by <paramref name="value" /> repeatedly until a fixed point is reached.
/// </returns>
public static T RewriteIter<T>(this IRewriter<T> rewriter, Func<T, T> transformer, T value)
where T : class
{
if (rewriter == null)
{
throw new ArgumentNullException(nameof(rewriter));
}
if (transformer == null)
{
throw new ArgumentNullException(nameof(transformer));
}
using var traversal = new RewriteIterTraversal<T>(rewriter, transformer);
return traversal.Go(value);
}
private class RewriteIterTraversal<T> : RewriteTraversal<T>
{
public RewriteIterTraversal(IRewriter<T> rewriter, Func<T, T> transformer)
: base(rewriter, transformer)
{
}
protected override T Transform(T value)
{
var newValue = Transformer(value);
if (!ReferenceEquals(value, newValue))
{
return Go(newValue);
}
return value;
}
}
/// <summary>
/// Rebuild a tree by repeatedly applying an asynchronous transformation function to every node in the tree,
/// until a fixed point is reached. <paramref name="transformer" /> should always eventually return
/// its argument unchanged, or this method will loop.
/// That is, <c>x.RewriteIter(transformer).SelfAndDescendants().All(x => await transformer(x) == x)</c>.
/// <para>
/// This is typically useful when you want to put your tree into a normal form
/// by applying a collection of rewrite rules until none of them can fire any more.
/// </para>
/// </summary>
/// <typeparam name="T">The rewritable tree type.</typeparam>
/// <param name="rewriter">The rewriter.</param>
/// <param name="transformer">
/// An asynchronous transformation function to apply to every node in <paramref name="value" /> repeatedly.
/// </param>
/// <param name="value">The value to rewrite.</param>
/// <returns>
/// The result of applying <paramref name="transformer" /> to every node in the tree
/// represented by <paramref name="value" /> repeatedly until a fixed point is reached.
/// </returns>
/// <remarks>This method is not available on platforms which do not support <see cref="ValueTask" />.</remarks>
public static async ValueTask<T> RewriteIter<T>(
this IRewriter<T> rewriter,
Func<T, ValueTask<T>> transformer,
T value
)
where T : class
{
if (rewriter == null)
{
throw new ArgumentNullException(nameof(rewriter));
}
if (transformer == null)
{
throw new ArgumentNullException(nameof(transformer));
}
using var traversal = new RewriteIterAsyncTraversal<T>(rewriter, transformer);
return await traversal.Go(value).ConfigureAwait(false);
}
private class RewriteIterAsyncTraversal<T> : RewriteAsyncTraversal<T>
{
public RewriteIterAsyncTraversal(IRewriter<T> rewriter, Func<T, ValueTask<T>> transformer)
: base(rewriter, transformer)
{
}
protected override async ValueTask<T> Transform(T value)
{
var newValue = await Transformer(value).ConfigureAwait(false);
if (!ReferenceEquals(value, newValue))
{
return await Go(newValue).ConfigureAwait(false);
}
return value;
}
}
}
|
7c09a4822a3fe50d2f7f3611e64e7d30e44613ec
|
C#
|
irenecho75/menu_hub
|
/Assets/Scripts/UDPClient.cs
| 2.875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Linq;
using System.Net.NetworkInformation;
public class UDPClient : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
UDPTest();
}
void UDPTest() {
UdpClient client = new UdpClient(5600);
try {
client.Connect("127.0.0.1", 5500);
// server used on my own computer, local host
UdpSend(client);
UdpReceive(client);
client.Close();
// Closes the client
}
catch (Exception e) {
Debug.Log("Exception thrown: " + e.Message);
}
}
void UdpSend(UdpClient client) {
byte[] sendBytes = Encoding.ASCII.GetBytes("Hello from the client");
// converts the string to a byte array
client.Send(sendBytes, sendBytes.Length);
// client sends a message
}
void UdpReceive(UdpClient client) {
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
// Any indicates that Socket instance must listen for client activity
// on all network interfaces.
byte[] receiveBytes = client.Receive(ref remoteEndPoint);
// Receive blocks execution until it receives a message
// remoteEndPoint is the local host
string receivedString = Encoding.ASCII.GetString(receiveBytes);
print("Message received from the server \n" + receivedString);
}
}
|
2b6e30e6d35212edb6f100ce8108670698981bec
|
C#
|
LuGeorgiev/CSharpSelfLearning
|
/SoftUniCSAdvanced/ObJCommunicationEvents/P3_DependencyInversion/StartUp.cs
| 3.359375
| 3
|
using P3_DependencyInversion;
using P3_DependencyInversion.Strategies;
using P3_DependencyInversion.Contracts;
using System;
namespace P3_DependencyInversion
{
class StartUp
{
static void Main(string[] args)
{
PrimitiveCalculator calculator = new PrimitiveCalculator(new AdditionStrategy());
string input;
while ((input=Console.ReadLine())!="End")
{
string[] tokens = input.Split();
string firstArg = tokens[0];
if (firstArg=="mode")
{
char @operator = tokens[1][0];
ICalculationStrategy strategy=null;
if (@operator == '+')
{
strategy = new AdditionStrategy();
}
else if (@operator == '-')
{
strategy = new SubtractionStrategy();
}
else if (@operator == '/')
{
strategy = new DivisionStrategy();
}
else if (@operator == '*')
{
strategy = new MultiplicationStrategy();
}
if (strategy==null)
{
throw new ArgumentException("Invalid mode");
}
calculator.ChangeStrategy(strategy);
}
else
{
int firstOperand = int.Parse(tokens[0]);
int secondOperand = int.Parse(tokens[1]);
int result = calculator.PerformCalculation(firstOperand, secondOperand);
Console.WriteLine(result);
}
}
}
}
}
|
4387b4217492bc31f8c04b909cd2a80baffa8fb7
|
C#
|
iby-dev/Experimentation-API
|
/src/Services/Experimentation/Experimentation.Api/Controllers/FeaturesController.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Experimentation.Domain.Entities;
using Experimentation.Domain.Exceptions;
using Experimentation.Logic.Directors;
using Experimentation.Logic.Mapper;
using Experimentation.Logic.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Experimentation.Api.Controllers
{
[Route("[controller]")]
public class FeaturesController : Controller
{
private readonly IFeaturesDirector _director;
private readonly IDtoToEntityMapper<BaseFeatureViewModel, Feature> _mapper;
private readonly ILogger<FeaturesController> _logger;
public FeaturesController(IFeaturesDirector director,
IDtoToEntityMapper<BaseFeatureViewModel, Feature> mapper,
ILogger<FeaturesController> logger)
{
_director = director;
_mapper = mapper;
_logger = logger;
}
/// <summary>
/// Retrieves all available features switches found in the API.
/// </summary>
/// <remarks>A simple sure fire way of finding out what is inside the api - use this endpoint when administering the API.
/// As it reveals feature switch names and ids. Go ahead and hit the 'Try it Out' button' - there are no parameters required for this
/// action method.</remarks>
/// <response code="200">Request processed successfully.</response>
/// <returns>a list of feature switches.</returns>
[HttpGet("")]
[ProducesResponseType(typeof(ListViewModel<Feature>), 200)]
public async Task<IActionResult> GetAllFeatures()
{
var allFeatures = await _director.GetAllFeatures();
var model = new ListViewModel<Feature>(allFeatures);
return Ok(model);
}
/// <summary>
/// Retrieves a feature switch object by its ID value.
/// </summary>
/// <remarks>The 'ID' parameter should be like: e.g: 59e4c8190b637e1524aea56f</remarks>
/// <response code="200">Requested feature switch found.</response>
/// <response code="404">Requested feature switch not found.</response>
/// <returns>a feature switch object.</returns>
[HttpGet("{id}")]
[ProducesResponseType(typeof(ViewModel<Feature>), 200)]
[ProducesResponseType(typeof(void), 404)]
public async Task<IActionResult> GetFeatureByIdAsync(
[Required(AllowEmptyStrings = false, ErrorMessage = "The id parameter cannot be null or contain whitespace.")]
string id)
{
var feature = await _director.GetFeatureById(id);
if (feature == null)
{
return NotFound();
}
var model = new ViewModel<Feature>(feature);
return Ok(model);
}
/// <summary>
/// Retrieves a feature switch object by its friendly ID value.
/// </summary>
/// <remarks>The 'friendlyId' parameter should be a unique non-negative numeric value like: e.g: 1 </remarks>
/// <response code="200">Requested feature switch found.</response>
/// <response code="404">Requested feature switch not found.</response>
/// <returns>a feature switch object.</returns>
[HttpGet("{friendlyId:int}")]
[ProducesResponseType(typeof(ViewModel<Feature>), 200)]
[ProducesResponseType(typeof(void), 404)]
public async Task<IActionResult> GetFeatureByFriendlyId(
[Required] [Range(1, int.MaxValue)] int friendlyId)
{
var feature = await _director.GetFeatureByFriendlyId(friendlyId);
if (feature == null)
{
return NotFound();
}
var model = new ViewModel<Feature>(feature);
return Ok(model);
}
/// <summary>
/// Retrieves a feature switch object by its name value.
/// </summary>
/// <remarks>The 'name' parameter should be a unique value like: e.g: 'NewMongoDB_Switch'. The style/convention you apply to the names
/// is entirely upto but consistency is key. </remarks>
/// <response code="200">Requested feature switch found.</response>
/// <response code="404">Requested feature switch not found.</response>
/// <returns>a feature switch object.</returns>
[HttpGet("name/{name}")]
[ProducesResponseType(typeof(ViewModel<Feature>), 200)]
[ProducesResponseType(typeof(void), 404)]
public async Task<IActionResult> GetFeatureByName(
[Required(AllowEmptyStrings = false, ErrorMessage = "The name parameter cannot be null or contain whitespace.")]
string name)
{
var feature = await _director.GetFeatureByName(name);
if (feature == null)
{
return NotFound();
}
var model = new ViewModel<Feature>(feature);
return Ok(model);
}
/// <summary>
/// Adds the new feature switch to the API.
/// </summary>
/// <param name="item">The feature to add.</param>
/// <remarks>
/// The name must be a unique value that follows some naming convention for consistency purposes.
/// The 'friendlyId' should be a unique non-negative numeric value like: e.g: 1
/// The bucketList can be left to empty which will default the behaviour = for all users.
/// Otherwise provide an string based ID for a guided feature switch.
/// </remarks>
/// <response code="201">Feature switch created.</response>
/// <response code="400">Invalid name or friendlyId provided for feature switch.</response>
/// <response code="500">Internal server error.</response>
/// <returns>a confirmation of the newly added feature switch.</returns>
[HttpPost]
[ProducesResponseType(typeof(Feature), 201)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(typeof(string), 500)]
public async Task<IActionResult> AddNewFeature([FromBody] BaseFeatureViewModel item)
{
var mappedFeature = _mapper.Map(item);
try
{
var newlyAddedFeature = await _director.AddNewFeature(mappedFeature);
return CreatedAtAction("AddNewFeature", new {id = newlyAddedFeature.Id}, newlyAddedFeature);
}
catch (NonUniqueValueDetectedException e)
{
const string title = "SaveError";
var message = $"The api was unable to save a new entity with name: {item.Name} and FriendlyId: {item.FriendlyId}.";
ModelState.AddModelError(e.GetType().Name, e.Message);
_logger.LogError($"{title} - {message}", e);
_logger.LogError(e, "");
return BadRequest(ModelState);
}
catch (Exception e)
{
const string title = "SaveError";
const string message = "Internal Server Error - See server logs for more info.";
ModelState.AddModelError(e.GetType().Name, e.Message);
_logger.LogError($"{title} - {message}", e);
_logger.LogError(e, "");
return StatusCode(500, message);
}
}
/// <summary>
/// Updates the existing feature switch in the API.
/// </summary>
/// <param name="model">The feature switch to update.</param>
/// <returns>A confirmation message.</returns>
/// <remarks> When updating an existing switch then all fields are updated into the database apart from
/// the ID field. This field is unique and after being generated it cannot be re-assigned or updated.
///
/// The 'Id' must be an existing id otherwise a 404 status code will be returned.
/// Change the name field to a unique value.
/// Change the 'friendlyId' to unique non-negative numeric value.
/// The bucketList can be left to empty which will default the behaviour = for all users.
/// Otherwise provide an string based identifier for a guided feature switch.
/// </remarks>
/// <response code="200">Feature switch updated.</response>
/// <response code="404">Feature switch not found.</response>
/// <response code="400">Invalid name or friendlyId provided for feature switch.</response>
/// <response code="500">Internal Server Error.</response>
[HttpPut("")]
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(typeof(void), 404)]
[ProducesResponseType(typeof(string), 500)]
public async Task<IActionResult> UpdateExistingFeature([FromBody] FeatureViewModel model)
{
try
{
var existingFeature = await _director.GetFeatureById(model.Id);
if (existingFeature == null)
{
return NotFound();
}
existingFeature.Name = model.Name;
existingFeature.FriendlyId = model.FriendlyId;
existingFeature.BucketList = model.BucketList;
await _director.UpdateFeature(existingFeature);
return new OkObjectResult("Request processed successfully");
}
catch (NonUniqueValueDetectedException e)
{
const string title = "UpdateError";
var message = $"The api was unable to update entity with id: {model.Id}";
ModelState.AddModelError(e.GetType().Name, e.Message);
_logger.LogError($"{title} - {message}", e);
_logger.LogError(e, "");
return BadRequest(ModelState);
}
catch (Exception e)
{
const string title = "UpdateError";
const string message = "Internal Server Error - See server logs for more info.";
ModelState.AddModelError(e.GetType().Name, e.Message);
_logger.LogError($"{title} - {message}", e);
_logger.LogError(e, "");
return StatusCode(500, message);
}
}
/// <summary>
/// Deletes the feature switch from the API.
/// </summary>
/// <param name="id">The ID of the switch to delete.</param>
/// <returns>No Content Result when successful.</returns>
/// <remarks>When deleting feature switches from the API simply provide the unique ID of the switch to this action method
/// and the API will do the rest.
///
/// The 'Id' must be an existing id otherwise a 404 status code will be returned.</remarks>
/// <response code="204">Feature switch deleted succesfully.</response>
/// <response code="404">Feature switch not found.</response>
/// <response code="500">Internal server error, the api has been unsuccesful in deleting the feature switch.</response>
[HttpDelete("{id}")]
[ProducesResponseType(typeof(void), 204)]
[ProducesResponseType(typeof(void), 404)]
[ProducesResponseType(typeof(void), 500)]
public async Task<IActionResult> DeleteFeature(
[Required(AllowEmptyStrings = false, ErrorMessage = "The name parameter cannot be null or contain whitespace.")]
string id)
{
try
{
var result = await _director.FeatureExistsById(id);
if (result == false)
{
return NotFound();
}
await _director.DeleteFeature(id);
return new NoContentResult();
}
catch (Exception e)
{
const string title = "DeleteError";
var message = $"The api was unable to delete entity with id: {id}";
ModelState.AddModelError(title, message);
_logger.LogError($"{title} - {message}", e);
return StatusCode(500, message);
}
}
// BUCKETS CRUD METHODS
/// <summary>
/// Get the bucket list on a feature by the feature Id.
/// </summary>
/// <param name="id">The ID of the switch to retrieve.</param>
/// <returns>a list of bucket ids.</returns>
/// <remarks>The 'Id' must be of an existing id otherwise a 404 status code will be returned.</remarks>
/// <response code="200">Bucket list retrieved successfully.</response>
/// <response code="404">Feature switch not found.</response>
[HttpGet("{id}/bucket")]
[ProducesResponseType(typeof(List<string>), 200)]
[ProducesResponseType(typeof(void), 404)]
public async Task<IActionResult> GetBucketByFeatureId(string id)
{
var feature = await _director.GetFeatureById(id);
if (feature == null)
{
return NotFound();
}
return new OkObjectResult(feature.BucketList);
}
/// <summary>
/// Returns true or false if specified bucketId is contained on bucket list found on feature switch.
/// </summary>
/// <param name="id">The Id of feature switch to retrieve.</param>
/// <param name="bucketId">The bucketId to query for.</param>
/// <returns>A true or false value if bucketId exists on bucket list.</returns>
/// <remarks>The 'Id' must be of an existing id otherwise a 404 status code will be returned.
/// The 'bucketId' is a string based identifier; the api will do a contains check on the bucket list to see if it is known or unknown
/// to the bucket.</remarks>
/// <response code="200">Bucket list queried successfully.</response>
/// <response code="404">Feature switch not found.</response>
[HttpGet("{id}/bucket/{bucketId}")]
[ProducesResponseType(typeof(bool), 200)]
[ProducesResponseType(typeof(void), 404)]
public async Task<IActionResult> QueryFeatureBucketByFeatureId(string id, string bucketId)
{
var feature = await _director.GetFeatureById(id);
if (feature == null)
{
return NotFound();
}
var result = feature.BucketList.Contains(bucketId);
return new OkObjectResult(result);
}
/// <summary>
/// Adds the identifier to the feature switches bucket list.
/// </summary>
/// <param name="id">The feature switch id to retrieve.</param>
/// <param name="bucketId">The bucket identifier to add to the bucket.</param>
/// <returns>a status message based on request outcome.</returns>
/// <remarks>The 'Id' must be of an existing id otherwise a 404 status code will be returned.
/// the 'bucketId' is a string based identifier that will get added to the bucket list on the feature switch. Semantically this means
/// the switch is now buided by the identifiers found only on the list.</remarks>
/// <response code="200">Bucket list updated successfully.</response>
/// <response code="404">Feature switch not found.</response>
[HttpPut("{id}/bucket/{bucketId}")]
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(typeof(void), 404)]
public async Task<IActionResult> AddIdToFeatureBucket(string id, string bucketId)
{
var feature = await _director.GetFeatureById(id);
if (feature == null)
{
return NotFound();
}
feature.BucketList.Add(bucketId);
await _director.UpdateFeature(feature);
return new OkObjectResult("Request processed successfully");
}
/// <summary>
/// Removes the identifier from the feature switches bucket list.
/// </summary>
/// <param name="id">The id of the feature switch to retrieve.</param>
/// <param name="bucketId">The bucket id to remove from the bucket.</param>
/// <returns>a status message based on request outcome.</returns>
/// <response code="200">Bucket list updated successfully.</response>
/// <response code="404">Feature switch not found.</response>
[HttpDelete("{id}/bucket/{bucketId}")]
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(typeof(void), 404)]
public async Task<IActionResult> RemoveIdFromFeatureBucket(string id, string bucketId)
{
var feature = await _director.GetFeatureById(id);
if (feature == null)
{
return NotFound();
}
feature.BucketList.Remove(bucketId);
await _director.UpdateFeature(feature);
return new OkObjectResult("Request processed successfully");
}
}
}
|
5dcfdf463fe576961b0f9ad0e3bf77a0103edd00
|
C#
|
AndriiTomashevsky/ModelBinding
|
/MvcModels/Controllers/HomeController.cs
| 2.65625
| 3
|
using Microsoft.AspNetCore.Mvc;
using MvcModels.Models;
using System.Collections.Generic;
namespace MvcModels.Controllers
{
public class HomeController : Controller
{
private IRepository repository;
public HomeController(IRepository repo)
{
repository = repo;
}
public IActionResult Index([FromQuery] int? id)
{
Person person;
if (id.HasValue && (person = repository[id.Value]) != null)
{
return View(person);
}
else
{
return NotFound();
}
}
public ViewResult Header(HeaderModel model)
{
return View(model);
}
public ViewResult Body()
{
return View();
}
[HttpPost]
public Person Body([FromBody]Person model)
{
return model;
}
}
}
|
d9210e477e49b6f9aa954371d34539e47d25f2b1
|
C#
|
RedCaplan/.Net_Elementary_Tasks
|
/Task1/Task1/Models/BoardSize.cs
| 2.59375
| 3
|
namespace Task1.Models
{
public struct BoardSize
{
public readonly int Height;
public readonly int Width;
public BoardSize(int height, int width)
{
Height = height;
Width = width;
}
}
}
|
671444ba65b7be090dad0e967fd589d4ed547fb7
|
C#
|
Fzzy2j/KeyboardSplitterXbox
|
/XInputWrapper/XinputController.cs
| 2.578125
| 3
|
namespace XinputWrapper
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using XinputWrapper.Enums;
using XinputWrapper.Structs;
public class XinputController
{
public const int MaxControllerCount = 4;
public const int FirstControllerIndex = 0;
public const int LastControllerIndex = MaxControllerCount - 1;
public const int DefaultUpdateFrequency = (int)(1000 / 30.0);
private static XinputController[] controllers;
private static bool keepRunning;
private static int updateFrequency;
private static int waitTime;
private static bool isRunning;
private static object syncLock;
private static Thread pollingThread;
private static List<uint> freeLeds;
private int playerIndex;
private object tag;
private bool stopMotorTimerActive;
private DateTime stopMotorTime;
private XInputBatteryInformation batteryInformationGamepad;
private XInputBatteryInformation batterInformationHeadset;
private XInputState gamepadStatePrev = new XInputState();
private XInputState gamepadStateCurrent = new XInputState();
static XinputController()
{
XinputController.controllers = new XinputController[MaxControllerCount];
XinputController.syncLock = new object();
for (int i = XinputController.FirstControllerIndex; i <= XinputController.LastControllerIndex; ++i)
{
XinputController.controllers[i] = new XinputController(i);
}
XinputController.UpdateFrequency = XinputController.DefaultUpdateFrequency;
freeLeds = new List<uint>() { 0, 1, 2, 3 };
}
private XinputController(int playerIndex)
{
this.playerIndex = playerIndex;
this.gamepadStatePrev.Copy(this.gamepadStateCurrent);
}
public event EventHandler<XinputControllerStateChangedEventArgs> StateChanged;
public event EventHandler PluggedChanged;
public static int UpdateFrequency
{
get
{
return XinputController.updateFrequency;
}
set
{
XinputController.updateFrequency = value;
XinputController.waitTime = 1000 / XinputController.updateFrequency;
}
}
public static int EmptyBusSlotsCount
{
get
{
return controllers.Where(x => !x.IsConnected).Count();
}
}
public uint PlayerIndex
{
get
{
return (uint)this.playerIndex;
}
}
public uint LedNumber
{
get
{
return this.PlayerIndex + 1;
}
}
public object Tag
{
get
{
lock (syncLock)
{
return this.tag;
}
}
set
{
lock (syncLock)
{
this.tag = value;
}
}
}
public XInputBatteryInformation BatteryInformationGamepad
{
get { return this.batteryInformationGamepad; }
internal set { this.batteryInformationGamepad = value; }
}
public XInputBatteryInformation BatteryInformationHeadset
{
get { return this.batterInformationHeadset; }
internal set { this.batterInformationHeadset = value; }
}
public bool IsConnected
{
get;
private set;
}
public bool? IsGamepad
{
get
{
if (!this.IsConnected)
{
return null;
}
return ((BatteryType)this.BatteryInformationGamepad.BatteryType) != BatteryType.Disconnected;
}
}
public bool? IsWired
{
get
{
if (!this.IsConnected)
{
return null;
}
if (this.IsGamepad == true)
{
return (BatteryType)this.BatteryInformationGamepad.BatteryType == BatteryType.Wired;
}
else
{
return (BatteryType)this.BatteryInformationHeadset.BatteryType == BatteryType.Wired;
}
}
}
public BatteryLevel BatteryLevel
{
get
{
if (!this.IsConnected)
{
return Enums.BatteryLevel.Empty;
}
if (this.IsGamepad == true)
{
return (BatteryLevel)this.BatteryInformationGamepad.BatteryLevel;
}
else
{
return (BatteryLevel)this.BatteryInformationHeadset.BatteryLevel;
}
}
}
public static XinputController RetrieveController(int index)
{
if (index < 0 || index > 3)
{
throw new InvalidOperationException("index must be in range 0-3");
}
return XinputController.controllers[index];
}
public static void StartPolling()
{
foreach (var controller in XinputController.controllers)
{
controller.IsConnected = false;
}
if (!XinputController.isRunning)
{
lock (XinputController.syncLock)
{
if (!XinputController.isRunning)
{
XinputController.pollingThread = new Thread(XinputController.PollerLoop);
XinputController.pollingThread.Start();
}
}
}
}
public static void StopPolling()
{
foreach (var controller in XinputController.controllers)
{
controller.IsConnected = false;
}
if (XinputController.isRunning)
{
XinputController.keepRunning = false;
}
}
public XInputCapabilities GetCapabilities()
{
var capabilities = new XInputCapabilities();
NativeMethods.XInputGetCapabilities(this.playerIndex, XInputConstants.XinputFlagGamepad, ref capabilities);
return capabilities;
}
public ControllerSubtype GetControllerSubType()
{
return (ControllerSubtype)this.GetCapabilities().SubType;
}
public void Vibrate(double leftMotor, double rightMotor)
{
this.Vibrate(leftMotor, rightMotor, TimeSpan.MinValue);
}
public void Vibrate(double leftMotor, double rightMotor, TimeSpan length)
{
leftMotor = Math.Max(0d, Math.Min(1d, leftMotor));
rightMotor = Math.Max(0d, Math.Min(1d, rightMotor));
var vibration = new XInputVibration()
{
LeftMotorSpeed = (ushort)(65535d * leftMotor),
RightMotorSpeed = (ushort)(65535d * rightMotor)
};
this.Vibrate(vibration, length);
}
public void Vibrate(XInputVibration strength)
{
this.stopMotorTimerActive = false;
NativeMethods.XInputSetState(this.playerIndex, ref strength);
}
public void Vibrate(XInputVibration strength, TimeSpan length)
{
NativeMethods.XInputSetState(this.playerIndex, ref strength);
if (length != TimeSpan.MinValue)
{
this.stopMotorTime = DateTime.Now.Add(length);
this.stopMotorTimerActive = true;
}
}
public bool GetButtonState(XinputButton button)
{
return (this.gamepadStateCurrent.Gamepad.Buttons & (int)button) == (int)button;
}
public byte GetTriggerState(XinputTrigger trigger)
{
switch (trigger)
{
case XinputTrigger.Left:
return this.gamepadStateCurrent.Gamepad.LeftTrigger;
case XinputTrigger.Right:
return this.gamepadStateCurrent.Gamepad.RightTrigger;
default:
throw new NotImplementedException("Not implemented xinput trigger: " + trigger);
}
}
public short GetAxisState(XinputAxis axis)
{
switch (axis)
{
case XinputAxis.X:
return this.gamepadStateCurrent.Gamepad.ThumbLX;
case XinputAxis.Y:
return this.gamepadStateCurrent.Gamepad.ThumbLY;
case XinputAxis.Rx:
return this.gamepadStateCurrent.Gamepad.ThumbRX;
case XinputAxis.Ry:
return this.gamepadStateCurrent.Gamepad.ThumbRY;
default:
throw new NotImplementedException("Not implemented xbox axis: " + axis);
}
}
public override string ToString()
{
return this.playerIndex.ToString();
}
private static void PollerLoop()
{
lock (XinputController.syncLock)
{
if (XinputController.isRunning == true)
{
return;
}
XinputController.isRunning = true;
}
XinputController.keepRunning = true;
while (XinputController.keepRunning)
{
for (int i = XinputController.FirstControllerIndex; i <= XinputController.LastControllerIndex; ++i)
{
XinputController.controllers[i].UpdateState();
}
Thread.Sleep(XinputController.updateFrequency);
}
lock (XinputController.syncLock)
{
XinputController.isRunning = false;
}
}
private void OnStateChanged()
{
if (this.StateChanged != null)
{
var args = new XinputControllerStateChangedEventArgs();
args.CurrentInputState = this.gamepadStateCurrent;
args.PreviousInputState = this.gamepadStatePrev;
args.Controller = XinputController.controllers[this.PlayerIndex];
this.StateChanged(this, args);
}
}
private void UpdateState()
{
int result = NativeMethods.XInputGetState(this.playerIndex, ref this.gamepadStateCurrent);
bool isCurrentlyConnected = this.IsConnected;
this.IsConnected = result == 0;
if (isCurrentlyConnected != this.IsConnected)
{
this.OnControllerPluggedChanged();
}
this.UpdateBatteryState();
if (this.gamepadStateCurrent.PacketNumber != this.gamepadStatePrev.PacketNumber)
{
this.OnStateChanged();
}
this.gamepadStatePrev.Copy(this.gamepadStateCurrent);
if (this.stopMotorTimerActive && (DateTime.Now >= this.stopMotorTime))
{
var stopStrength = new XInputVibration()
{
LeftMotorSpeed = 0,
RightMotorSpeed = 0
};
NativeMethods.XInputSetState(this.playerIndex, ref stopStrength);
}
}
private void UpdateBatteryState()
{
var headset = new XInputBatteryInformation();
var gamepad = new XInputBatteryInformation();
NativeMethods.XInputGetBatteryInformation(this.playerIndex, (byte)BatteryDeviceType.BATTERY_DEVTYPE_GAMEPAD, ref gamepad);
NativeMethods.XInputGetBatteryInformation(this.playerIndex, (byte)BatteryDeviceType.BATTERY_DEVTYPE_HEADSET, ref headset);
this.BatteryInformationHeadset = headset;
this.BatteryInformationGamepad = gamepad;
}
private void OnControllerPluggedChanged()
{
if (this.PluggedChanged != null)
{
this.PluggedChanged(this, EventArgs.Empty);
}
}
}
}
|
97c1e6668257e9fc4cd3cfc2033939ec63f3d47e
|
C#
|
DeveloperIlnaz/DataStructures
|
/DataStructures/Queue/IQueue.cs
| 2.71875
| 3
|
using System.Collections;
using System.Collections.Generic;
namespace DataStructures.Queue
{
public interface IQueue<T> : IEnumerable, IEnumerable<T>
{
T Peek();
void Enqueue(T item);
T Dequeue();
void Clear();
bool Contains(T item);
}
}
|
fc0d9d4c6b868bc956c67ff62b0de7d11468aedb
|
C#
|
sajeelaa/Chatbot
|
/MainWindow.xaml.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Chatbot1
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
BotEngine bot = new BotEngine();
Storage speicher = new Storage();
Message test = new Message("ka", "iergendwas");
public MainWindow()
{
InitializeComponent();
// Load muss ausgeführt werden
BotEngine bot = new BotEngine();
Storage speicher = new Storage();
speicher.Load();
}
private void Send_Click(object sender, RoutedEventArgs e)
{
Chat.Text += $"Du: {Schreibbox.Text}\n";
// Die Methode getAntwort ausführen von Botengine
if (bot.GetAnswer(Schreibbox.Text) != "@#-%&")
{
Chat.Text += $"Bot: {bot.GetAnswer(Schreibbox.Text)}\n";
}
else
{
Chat.Text += $"Bot: Antwort konnte nicht gefunden werden :( \n";
}
Schreibbox.Clear();
}
private void Chat_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void Schreibbox_TextChanged(object sender, TextChangedEventArgs e)
{
}
}
}
|
d46075481b46b38a3f11fd5e42465d181f778968
|
C#
|
AimalKhanOfficial/Problem-Solving
|
/LongestSubstring/LongestSubstring/Program.cs
| 3.984375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LongestSubstring
{
class Program
{
List<char> list = new List<char>();
static void Main(string[] args)
{
//Finding the unique alphabets with in a String!!
Program program = new Program();
int len = program.LengthOfLongestSubstring("pwwkew");
Console.WriteLine("Length: " + len);
Console.Read();
}
public void display(int start, int end, char[] arr)
{
for (int i = start; i < end; i++)
{
if (!list.Contains(arr[i]))
{
list.Add(arr[i]);
}
}
}
public int LengthOfLongestSubstring(String s)
{
char[] nameArr = s.ToCharArray();
//string sequence = "";
for (int i = 0; i < nameArr.Length; i++)
{
for (int j = i + 1; j <= nameArr.Length; j++)
{
if (j == nameArr.Length)
{
break;
}
display(i, j, nameArr);
Console.WriteLine();
//Console.WriteLine(nameArr[j]);
}
Console.WriteLine();
}
return nameArr.Length;
}
}
}
|
ef5b1dffb8be2dda5781fd189fdb595fcb73d8e7
|
C#
|
noptran/pcm
|
/Common_Objects/Models/ProblemSubCategoryModel.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Common_Objects.Models
{
public class ProblemSubCategoryModel
{
public Problem_Sub_Category GetSpecificProblemSubCategory(int problemSubCategoryId)
{
Problem_Sub_Category problemSubCategory;
var dbContext = new SDIIS_DatabaseEntities();
try
{
var problemSubCategoryList = (from r in dbContext.Problem_Sub_Categories
where r.Problem_Sub_Category_Id.Equals(problemSubCategoryId)
select r).ToList();
problemSubCategory = (from r in problemSubCategoryList
select r).FirstOrDefault();
}
catch (Exception)
{
return null;
}
return problemSubCategory;
}
public List<Problem_Sub_Category> GetListOfProblemSubCategories()
{
List<Problem_Sub_Category> problemSubCategories;
using (var dbContext = new SDIIS_DatabaseEntities())
{
try
{
var problemSubCategoryList = (from r in dbContext.Problem_Sub_Categories
select r).ToList();
problemSubCategories = (from r in problemSubCategoryList
select r).ToList();
}
catch (Exception)
{
return null;
}
}
return problemSubCategories;
}
}
}
|
7835fb6542f3b8a6d115b4c697bef5e30b60e2f1
|
C#
|
kizisoft/TelerikAcademy
|
/OOP/04. OOP Fundamental Principles – Part I/01. School/SchoolClass.cs
| 3.453125
| 3
|
namespace _01.School
{
using System;
using System.Collections.Generic;
public class SchoolClass : SchoolNoneHumanObject
{
private List<Student> studentList;
private List<Teacher> teacherList;
public SchoolClass(string name, List<Student> studentList = null, List<Teacher> teacherList = null, string comments = null)
: base(name, comments)
{
if (studentList != null)
{
this.StudentList = studentList;
}
else
{
this.studentList = new List<Student>();
}
if (teacherList != null)
{
this.TeacherList = teacherList;
}
else
{
this.teacherList = new List<Teacher>();
}
}
public List<Student> StudentList
{
get { return new List<Student>(this.studentList); }
private set { this.studentList = value; }
}
public List<Teacher> TeacherList
{
get { return new List<Teacher>(this.teacherList); }
private set { this.teacherList = value; }
}
// Add Student in the students list
public void AddStudent(Student student)
{
if (student == null)
{
throw new ArgumentNullException("School parameter is Null!");
}
this.studentList.Add(student);
}
// Remove Student from the students list
public bool RemoveStudent(Student student)
{
if (student == null)
{
throw new ArgumentNullException("School parameter is Null!");
}
if (!this.studentList.Contains(student))
{
return false;
}
return this.studentList.Remove(student);
}
// Add Teacher in the list
public void AddTeacher(Teacher teacher)
{
if (teacher == null)
{
throw new ArgumentNullException("Teacher parameter is Null!");
}
this.teacherList.Add(teacher);
}
// Remove Teacher from the list
public bool RemoveTeacher(Teacher teacher)
{
if (teacher == null)
{
throw new ArgumentNullException("Teacher parameter is Null!");
}
if (!this.teacherList.Contains(teacher))
{
return false;
}
return this.teacherList.Remove(teacher);
}
// Return the string representation of object
public override string ToString()
{
return string.Format("[SCHOOL CLASS]:{0}{1}{0}{0}{2}{0}{3}", Environment.NewLine, base.ToString(), string.Join(Environment.NewLine, this.studentList), string.Join(Environment.NewLine, this.teacherList));
}
}
}
|
77601670199b9f9bbe16d3f7044d361a4cc3a81d
|
C#
|
kenrazo/SproutExam
|
/SproutExam/SproutExam.DataAccess/Repositories/EmployeeRepository.cs
| 2.8125
| 3
|
using Microsoft.EntityFrameworkCore;
using SproutExam.DataAccess.DataContext;
using SproutExam.DataAccess.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SproutExam.DataAccess.Repositories
{
public class EmployeeRepository : IEmployeeRepository
{
private readonly EmployeeDbContext _context;
public EmployeeRepository(EmployeeDbContext context)
{
_context = context;
}
public async Task Add(Employee employee)
{
await _context.Employee.AddAsync(employee);
await _context.SaveChangesAsync();
}
public async Task<IEnumerable<Employee>> Get()
{
return await _context.Employee.ToListAsync();
}
public async Task<Employee> GetById(Guid id)
{
return await _context.Employee.Where(m => m.Id == id).FirstOrDefaultAsync();
}
}
}
|
e6e674d665a3de6bb0da488ffc5ee6b3bd272afb
|
C#
|
luckydimdim/Infrastructure.Configuration
|
/Infrastructure.Configuration/ConfigurationHelper.cs
| 2.78125
| 3
|
using System;
using Microsoft.Extensions.Options;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace Cmas.Infrastructure.Configuration
{
public static class ConfigurationHelper
{
public static CmasConfiguration GetConfiguration(this IServiceProvider serviceProvider)
{
return ((IOptions<CmasConfiguration>) serviceProvider.GetService(typeof(IOptions<CmasConfiguration>))).Value;
}
public static string EncryptString(string text, string keyString)
{
var key = Encoding.UTF8.GetBytes(keyString);
using (var aesAlg = Aes.Create())
{
using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
{
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(text);
}
var iv = aesAlg.IV;
var decryptedContent = msEncrypt.ToArray();
var result = new byte[iv.Length + decryptedContent.Length];
Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);
return Convert.ToBase64String(result);
}
}
}
}
public static string DecryptString(string cipherText, string keyString)
{
if (string.IsNullOrEmpty(cipherText) || string.IsNullOrEmpty(keyString))
return null;
var fullCipher = Convert.FromBase64String(cipherText);
var iv = new byte[16];
var cipher = new byte[16];
Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
var key = Encoding.UTF8.GetBytes(keyString);
using (var aesAlg = Aes.Create())
{
using (var decryptor = aesAlg.CreateDecryptor(key, iv))
{
string result;
using (var msDecrypt = new MemoryStream(cipher))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
result = srDecrypt.ReadToEnd();
}
}
}
return result;
}
}
}
public static Database WithDefaults(this Database database, string schema, string host, string login, string password)
{
if (string.IsNullOrEmpty(database.Schema))
{
database.Schema = schema;
}
if (string.IsNullOrEmpty(database.Host))
{
database.Host = host;
}
if (string.IsNullOrEmpty(database.Login))
{
database.Login = login;
}
if (string.IsNullOrEmpty(database.Password))
{
database.Password = password;
}
return database;
}
}
}
|
2abf403d3a9926e221f63cbe1844f3bac63e3987
|
C#
|
VorobeY1326/Memory_Tests
|
/LastTask/3_TheCakeIsALie/Program.cs
| 2.53125
| 3
|
namespace _3_TheCakeIsALie
{
public static class Program
{
public static void Main()
{
const int threadsCount = 20;
const int count = 1000000;
var usualCountersTest = new UsualCountersTest(threadsCount, count);
var wideCountersTest = new WideCountersTest(threadsCount, count);
usualCountersTest.Run();
wideCountersTest.Run();
}
}
}
|
9de085785a23248315197e0fa23957023bfe6ce5
|
C#
|
brwBruno/ExeplosThiago
|
/TesteMariana/TesteMariana.Dominio/Funcionalidades/Materias/Materia.cs
| 3.203125
| 3
|
using System;
using System.Text.RegularExpressions;
using TesteMariana.Dominio.Base;
namespace TesteMariana.Dominio
{
public class Materia : Entidade
{
public string Nome { get; set; }
public Disciplina Disciplina { get; set; }
public Serie Serie { get; set; }
public Materia()
{
}
public override string ToString()
{
return String.Format("{0} - {1} : {2} - {3}", Id, Nome, Disciplina.Nome, Serie.Descricao);
}
public override void Valida()
{
if (string.IsNullOrEmpty(Nome))
throw new InvalidOperationException("O nome da matéria é obrigatório!");
if (Nome.Length < 4)
throw new InvalidOperationException("O nome da matéria deve ter mais que 4 caracteres!");
if (Disciplina == null)
throw new InvalidOperationException("A matéria deve ter uma disciplina!");
if (Serie == null)
throw new InvalidOperationException("A matéria deve ter uma série!");
if (Nome.Length > 30)
throw new InvalidOperationException("O nome da matéria deve ser menor que 30 caracteres!");
if (!Regex.IsMatch(Nome.ToLower(), @"^[a-z-A-Z_á-úçãõâêôà\s]+$"))
throw new InvalidOperationException("O nome da matéria não pode conter caractres especiais ou números!");
}
}
}
|
db0705bebf71aeb05e8646ff8ec4752991b7b1e6
|
C#
|
tausif-fardin/Bank-Management-System
|
/AccountManagementSystem/Account.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace AccountManagementSystem
{
internal struct Date
{
private byte day, month;
private ushort year;
internal Date(byte day, byte month, ushort year)
{
this.day = day;
this.month = month;
this.year = year;
}
internal void ShowDate()
{
Console.WriteLine("Opening Date: {0}/{1}/{2}", this.day, this.month, this.year);
}
}
internal struct Address
{
private byte aptNo, roadNo;
private string district, country;
internal Address(byte aptNo, byte roadNo, string district, string country)
{
this.aptNo = aptNo;
this.roadNo = roadNo;
this.district = district;
this.country = country;
}
internal void ShowAddress()
{
Console.WriteLine("Address: Apartment-{0},Road-{1},District-{2},Country-{3}", this.aptNo, this.roadNo, this.district, this.country);
}
}
internal class Account
{
private static int serialNo = 1000;
private string name, id, accType;
private Date openingDate;
private Address address;
private decimal balance;
internal string Name
{
set { this.name = value; }
get { return this.name; }
}
internal virtual string Id
{
set { this.id = value; }
get { return this.id; }
}
internal string AccType
{
set { this.accType = value; }
get { return this.accType; }
}
internal Date OpeningDate
{
set { this.openingDate = value; }
get { return this.openingDate; }
}
internal Address Address
{
set { this.address = value; }
get { return this.address; }
}
internal decimal Balance
{
set { this.balance = value; }
get { return this.balance; }
}
internal Account()
{
}
internal Account(string name, string accType, Date openingDate, Address address, decimal balance)
{
this.Name = name;
this.Id = (++serialNo).ToString();
this.AccType = accType;
this.OpeningDate = openingDate;
this.Address = address;
this.Balance = balance;
}
internal virtual void ShowInfo()
{
Console.WriteLine("Account Information:");
Console.WriteLine("Name:{0}", this.Name);
Console.WriteLine("ID:{0}", this.Id);
Console.WriteLine("Account Type:{0}", this.AccType);
this.OpeningDate.ShowDate();
this.Address.ShowAddress();
Console.WriteLine("Balance:{0}", this.Balance);
}
}
}
|
ce1d2dc0d7c450ecf3cae6f54065f56eae6bd82a
|
C#
|
teskeras/Settlements
|
/Settlements/Controllers/SettlementsController.cs
| 2.5625
| 3
|
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Settlements.Core;
using Settlements.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Settlements.Controllers
{
[Route("api/[controller]")]
public class SettlementsController : Controller
{
private readonly ISettlementsService settlementsService;
public SettlementsController(ISettlementsService settlementsService)
{
this.settlementsService = settlementsService;
}
[HttpGet("[action]")]
public IActionResult GetSettlements([FromQuery] SettlementParameters settlementParameters)
{
var settlements = settlementsService.GetSettlements(settlementParameters);
var metadata = new
{
settlements.TotalCount,
settlements.PageSize,
settlements.CurrentPage,
settlements.TotalPages,
settlements.HasNext,
settlements.HasPrevious
};
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(metadata));
return Ok(settlements);
}
[HttpGet("[action]/{id}")]
public IActionResult GetSettlement(int id)
{
var settlement = settlementsService.GetSettlement(id);
return Ok(settlement);
}
[HttpPost("[action]")]
public IActionResult CreateSettlement([FromBody] SettlementDTOPost settlementDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var settlement = settlementsService.CreateSettlement(settlementDto);
return Created($"api/Settlements/GetSettlement/{settlement.Id}", settlement.Id);
}
[HttpPut("[action]/{id}")]
public IActionResult EditSettlement([FromBody] SettlementDTOPut settlementDto, int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var settlement = settlementsService.EditSettlement(settlementDto, id);
if (settlement == null)
{
return BadRequest();
}
return NoContent();
}
[HttpDelete("[action]/{id}")]
public IActionResult DeleteSettlement(int id)
{
settlementsService.DeleteSettlement(id);
return NoContent();
}
[HttpGet("[action]/{search}")]
public IActionResult GetCountries(string search)
{
if (string.IsNullOrWhiteSpace(search) || string.IsNullOrEmpty(search)) return BadRequest("Required search string");
var list = settlementsService.GetCountries(search);
return Ok(list);
}
}
}
|
f2cf3927f74d8a7400b4d1c7a2890dbcbf2a0063
|
C#
|
210503-Reston-NET/Malik-Sehar-P1
|
/SBL/ProductBL.cs
| 2.78125
| 3
|
using System.Collections.Generic;
using Models;
using SDL;
using System;
namespace SBL
{
public class ProductBL: IProductBL
{
private IRepository _repo;
public ProductBL(IRepository repo){
_repo = repo;
}
public MProduct DeleteAProduct(MProduct mProduct)
{
return _repo.DeleteAProduct(mProduct);
}
public MProduct GetProductById(string Barcode)
{
return _repo.GetProductById(Barcode);
}
public MProduct AddAProduct(MProduct product)
{
return _repo.AddProduct(product);
}
public List<MProduct> GetAllProducts()
{
return _repo.GetAllProductss();
}
public MProduct GetAProduct(MProduct product){
Console.WriteLine(product.ToString());
if(_repo.GetAProduct(product) != null){
throw new Exception("Product already Exit!");
}
return _repo.GetAProduct(product);
}
public MProduct searchAProduct(string barcode)
{
return _repo.searchAProduct(barcode);
}
public MProduct UpdateProduct(MProduct product)
{
return _repo.UpdateProduct(product);
}
}
}
|
7828ce43f903e688a56918a76d33be716cd0d0f6
|
C#
|
asunar/CQRS
|
/TaskFlamingo/Data/TaskRetriever.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace TaskFlamingo.Data
{
using System.Configuration;
using System.Data.SqlClient;
using Dapper;
using TaskFlamingo.Models;
public class TaskRetriever
{
public static SqlConnection GetOpenConnection()
{
var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
return new SqlConnection(connectionString);
}
private bool IsSupervisor(Guid personId)
{
using (var connection = GetOpenConnection())
{
return connection.Query<bool>(@"SELECT IsSupervisor FROM dbo.People WHERE PersonId = @personId", new { personId }).First();
}
}
public IEnumerable<DashboardTask> GetDashboardTasks(Guid personId)
{
var isSupervisor = this.IsSupervisor(personId);
if (isSupervisor)
{
// show all tasks
using (var connection = GetOpenConnection())
{
return connection.Query<DashboardTask>(@"
SELECT
TaskId,
Name,
DueDate,
Status
FROM
dbo.vw_DashboardTask
");
}
}
// show published tasks assigned to this person only
using (var connection = GetOpenConnection())
{
return connection.Query<DashboardTask>(@"
SELECT
TaskId,
Name,
DueDate,
Status
FROM
dbo.vw_DashboardTask
WHERE
PersonId = @personId
AND Status = @published
", new { personId, published = (int)Status.Published });
}
}
}
}
|
68cacf8f293324890e6ee83218db74edb7020d20
|
C#
|
Brylex/c-wzorce-projektowe-steven-john-metsker
|
/lib/Credit/ICreditCheck.cs
| 2.75
| 3
|
namespace Credit
{
/// <summary>
/// Interfejs definiujcy wsplne metody dla klas sprawdzajcych
/// limit kredytowy online i offline.
/// </summary>
public interface ICreditCheck
{
/// <summary>
/// Zwraca dopuszczalny limit kredytowy dla klienta o podanym
/// identyfikatorze.
/// </summary>
/// <param name="id">identyfikator klienta</param>
/// <returns>limit kredytowy</returns>
double CreditLimit(int id);
}
}
|
cfcad03cf275f37febee8ed3f2344c2522065d6c
|
C#
|
Berk1034/Tests-Generator
|
/TestsGenerator/TestsGenerator/bin/Babaika.cs
| 2.71875
| 3
|
namespace Human
{
public class Student
{
public void Learn()
{
Console.WriteLine("I am Learning!");
}
}
}
namespace Creature
{
public class Babaika
{
public void Boo()
{
Console.WriteLine("Boo!");
}
}
}
|
f841d79b636be466a003585f9c50d47a66882ea4
|
C#
|
gabriellaxh/CSharp-Fundamentals
|
/C# OOP Advanced/Iterators And Comparators/09.LinkedListTraversal/MyLinkedList.cs
| 3.828125
| 4
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace _09.LinkedListTraversal
{
public class MyLinkedList<T> : IEnumerable<T>
{
private LinkedList<T> List { get; set; }
public MyLinkedList()
{
this.List = new LinkedList<T>();
}
public void Add(T element)
{
this.List.AddLast(element);
}
public bool Remove(T element)
{
if (this.List.Contains(element))
{
this.List.Remove(element);
return true;
}
return false;
}
public int Count()
{
return this.List.Count;
}
public IEnumerator<T> GetEnumerator()
{
foreach (var item in this.List)
{
yield return item;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
|
95f3cdc828f139edb5194382104d9584b57f5deb
|
C#
|
colindj1120/Mp3_Player
|
/Mp3PlayerApplication/Mp3PlayerApplication/Functions/Miscellaneous.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Mp3.Functions
{
class Miscellaneous
{
public static bool checkNull(DataGridViewRow row)
{
bool isNull = false;
if (row.Cells[0].Value == null && row.Cells[1].Value == null && row.Cells[2].Value == null &&
row.Cells[3].Value == null && row.Cells[4].Value == null && row.Cells[5].Value == null &&
row.Cells[6].Value == null && row.Cells[7].Value == null && row.Cells[8].Value == null)
{
isNull = true;
}
return isNull;
}
public static void ProcessDirectory(string targetDirectory, List<string> listSongs)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
listSongs.Add(fileName);
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory, listSongs);
}
public static int totalTime(String length)
{
string[] split = length.Split(':');
int seconds = int.Parse(split[2]);
int minutes = int.Parse(split[1]);
int hours = int.Parse(split[0]);
int total = (hours * 3600) + (minutes * 60) + seconds;
return total;
}
}
}
|
723a4c659a8b948f8e5dd168ac1f0ec7001d9b4c
|
C#
|
shendongnian/download4
|
/first_version_download2/203226-15634126-38080154-2.cs
| 3.6875
| 4
|
using System;
using System.Collections;
class Program
{
static void Main()
{
Hashtable hsTbl = new Hashtable();
hsTbl.Add(1, "Suhas");
hsTbl.Add(2, "Madhuri");
hsTbl.Add(3, "Om");
DictionaryEntry[] entries = new DictionaryEntry[hsTbl.Count];
hsTbl.CopyTo(entries, 0);
hsTbl.Clear();
foreach(DictionaryEntry de in entries) hsTbl.Add(de.Value, de.Key);
// check it worked
foreach(DictionaryEntry de in hsTbl)
{
Console.WriteLine("{0} : {1}", de.Key, de.Value);
}
}
}
|
95f71cfb5fd76615bfb8b1b9a78540bd9f3a5260
|
C#
|
mustiian/GDSJam2020
|
/MIBvsAliens/Assets/Scripts/UntiControlSystem/EnemyDetectingSystem.cs
| 2.59375
| 3
|
using System;
using DataStructures;
using UnityEngine;
public class EnemyDetectingSystem : MonoBehaviour
{
private bool _initialized;
private Race _race;
public void Initialize(Race race)
{
if (_initialized)
return;
_race = race;
TargetsQueue = new Queue<FightingSystem>();
_initialized = true;
}
public Queue<FightingSystem> TargetsQueue { get; private set; }
public event EventHandler EnemyDetected;
public event EventHandler NoEnemiesAround;
private void OnTriggerEnter2D(Collider2D other)
{
if (!_initialized)
return;
if (other.TryGetComponent<BaseCreature>(out var otherCreature) &&
other.TryGetComponent<FightingSystem>(out var otherFightingSystem) &&
other.TryGetComponent<UnitControlSystem>(out var otherControlSystem))
{
if (otherCreature.race == _race)
return;
if (!otherFightingSystem.IsValidTarget)
return;
otherFightingSystem.Died += EnemyDied;
otherControlSystem.WillBeDestroyed += EnemyWillBeDestroyed;
TargetsQueue.Enqueue(otherFightingSystem);
OnEnemyDetected();
}
}
private void EnemyWillBeDestroyed(object sender, EventArgs e)
{
if (sender is UnitControlSystem controlSystem)
{
RemoveEnemy(controlSystem);
}
}
private void RemoveEnemy(UnitControlSystem controlSystem, FightingSystem fightingSystem = null)
{
controlSystem.WillBeDestroyed -= EnemyWillBeDestroyed;
if (fightingSystem == null)
fightingSystem = controlSystem.GetComponent<FightingSystem>();
RemoveFightingSystemFromQueue(fightingSystem);
}
private void EnemyDied(object sender, EventArgs e)
{
if (sender is FightingSystem fightingSystem)
{
var controlSystem = fightingSystem.GetComponent<UnitControlSystem>();
RemoveEnemy(controlSystem, fightingSystem);
}
}
private void RemoveFightingSystemFromQueue(FightingSystem fightingSystem)
{
TargetsQueue.TryRemove(fightingSystem);
fightingSystem.Died -= EnemyDied;
if (TargetsQueue.IsEmpty())
OnNoEnemiesAround();
}
private void OnTriggerExit2D(Collider2D other)
{
if (!_initialized)
return;
//is it even possible?
}
private void OnEnemyDetected()
{
EnemyDetected?.Invoke(this, EventArgs.Empty);
}
private void OnNoEnemiesAround()
{
NoEnemiesAround?.Invoke(this, EventArgs.Empty);
}
public void Dispose()
{
FightingSystem fs = null;
while (TargetsQueue.TryDequeue(out fs))
{
fs.Died -= EnemyDied;
}
}
}
|
80b9db5f7ecadc2fffe2541288a65111e753f536
|
C#
|
aabdugaliyev/Machine-Learning
|
/ML/ML/Form1.cs
| 2.5625
| 3
|
using System;
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 ML
{
public partial class form : Form
{
List<Tuple<string, Image>> teams = new List<Tuple<string, Image>>();
List<Label> labelList = new List<Label>();
int team1Index = 0;
int team2Index = 0;
public form()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
fillTeams();
team1Index = 0;
team2Index = 5;
changeTeam1(team1Index);
changeTeam2(team2Index);
walp.Image = Properties.Resources.walp;
Width = walp.Image.Width;
Height = walp.Image.Height;
walp.Location = new Point(0, 0);
walp.SizeMode = PictureBoxSizeMode.AutoSize;
team1.BackColor = Color.Transparent;
team2.BackColor = Color.Transparent;
team1.Parent = walp;
team2.Parent = walp;
t1Label.BackColor = Color.Transparent;
t1Label.Parent = walp;
t2Label.BackColor = Color.Transparent;
t2Label.Parent = walp;
t1Left.BackColor = Color.Transparent;
t1Left.Parent = walp;
t1Left.BackgroundImageLayout = ImageLayout.Stretch;
t1Right.BackColor = Color.Transparent;
t1Right.Parent = walp;
t1Right.BackgroundImageLayout = ImageLayout.Stretch;
t2Left.BackColor = Color.Transparent;
t2Left.Parent = walp;
t2Left.BackgroundImageLayout = ImageLayout.Stretch;
t2Right.BackColor = Color.Transparent;
t2Right.Parent = walp;
t2Right.BackgroundImageLayout = ImageLayout.Stretch;
team1.BackgroundImageLayout = ImageLayout.Stretch;
team1.SizeMode = PictureBoxSizeMode.StretchImage;
team2.BackgroundImageLayout = ImageLayout.Stretch;
team2.SizeMode = PictureBoxSizeMode.StretchImage;
t1Label.ForeColor = Color.WhiteSmoke;
t1Label.Font = new Font("Arial", 14 , FontStyle.Bold);
t2Label.ForeColor = Color.WhiteSmoke;
t2Label.Font = new Font("Arial", 14, FontStyle.Bold);
t1Win.ForeColor = Color.DarkBlue;
t1Win.Font = new Font("Arial", 14, FontStyle.Bold);
t2Win.ForeColor = Color.DarkRed;
t2Win.Font = new Font("Arial", 14, FontStyle.Bold);
draw.ForeColor = Color.White;
draw.Font = new Font("Arial", 14, FontStyle.Bold);
t1Win.BackColor = Color.Transparent;
t1Win.Parent = walp;
t2Win.BackColor = Color.Transparent;
t2Win.Parent = walp;
draw.BackColor = Color.Transparent;
draw.Parent = walp;
button1.BackColor = Color.White;
button1.Parent = walp;
button1.Text = "Calculate";
//walp.Hide();
int step = 100;
for (int i = 0; i < 100; i++)
{
Label l = new Label();
l.Location = new Point(step, 300);
l.BackColor = Color.Transparent;
l.Width = 5;
l.Height = 20;
Controls.Add(l);
labelList.Add(l);
l.Parent = walp;
step += 5;
}
}
public void fillTeams()
{
teams.Add(Tuple.Create("Roma", Image.FromFile("roma.png")));
teams.Add(Tuple.Create("Atletico", Image.FromFile("atletico.png")));
teams.Add(Tuple.Create("Barcelona", Image.FromFile("barcelona.png")));
teams.Add(Tuple.Create("Bayern", Image.FromFile("bayern.png")));
teams.Add(Tuple.Create("Chelsea", Image.FromFile("chelsea.png")));
teams.Add(Tuple.Create("Juventus", Image.FromFile("juventus.png")));
teams.Add(Tuple.Create("Liverpool", Image.FromFile("liverpool.png")));
teams.Add(Tuple.Create("MC", Image.FromFile("mc.png")));
teams.Add(Tuple.Create("PSG", Image.FromFile("psg.png")));
teams.Add(Tuple.Create("RealMadrid", Image.FromFile("realmadrid.png")));
teams.Add(Tuple.Create("Sevilla", Image.FromFile("sevilla.png")));
teams.Add(Tuple.Create("Tottenham", Image.FromFile("tottenham.png")));
}
private void label1_Click(object sender, EventArgs e)
{
}
public void changeTeam1(int index)
{
team1.Image = teams[index].Item2;
t1Label.Text = teams[index].Item1;
}
public void changeTeam2(int index)
{
team2.Image = teams[index].Item2;
t2Label.Text = teams[index].Item1;
}
private void t1Left_Click(object sender, EventArgs e)
{
team1Index--;
if (team1Index < 0)
{
team1Index = teams.Count - 1;
}
changeTeam1(team1Index);
}
private void t1Right_Click(object sender, EventArgs e)
{
team1Index++;
if (team1Index == teams.Count)
{
team1Index = 0;
}
changeTeam1(team1Index);
}
private void t2Left_Click(object sender, EventArgs e)
{
team2Index--;
if (team2Index < 0)
{
team2Index = teams.Count - 1;
}
changeTeam2(team2Index);
}
private void t2Right_Click(object sender, EventArgs e)
{
team2Index++;
if (team2Index == teams.Count)
{
team2Index = 0;
}
changeTeam2(team2Index);
}
public static string ReadData(string str)
{
string[] lines = File.ReadAllLines(str);
string data = "";
foreach (string l in lines)
{
data += l;
}
return data;
}
public static List<string> ConvertToList(string[] arr)
{
List<string> listString = new List<string>();
for (int i = 0; i < arr.Length; i++)
{
listString.Add(arr[i]);
}
return listString;
}
//Берем инфу через название команды, т.е счеты, показатели игроков
public static List<string> FindTeamScores(List<string> list, string teamName)
{
List<string> TeamNameList = new List<string>();
string teamStringSepparated = "";
for (int i = 0; i < list.Count; i++)
{
if (list[i].Substring(0, teamName.Length) == teamName)
{
string currentString = list[i];
teamStringSepparated = currentString.Substring(teamName.Length + 1, currentString.Length - teamName.Length - 2);
int betweenPosition = teamStringSepparated.IndexOf('[');
TeamNameList.Add(teamStringSepparated.Substring(1, betweenPosition - 2));
TeamNameList.Add(teamStringSepparated.Substring(betweenPosition + 1, teamStringSepparated.Length - betweenPosition - 2));
}
}
return TeamNameList;
}
//Сплитим голы, находим среднее количество голов забитых и пропущенных
static Tuple<double, double> GoalCounting(string str)
{
double GoalDid = 0;
double GoalGet = 0;
double totalGames = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ':')
{
double a = Int32.Parse(str[i - 1].ToString());
double b = Int32.Parse(str[i + 1].ToString());
GoalDid += a;
GoalGet += b;
totalGames++;
}
}
double AverageGoalDid = GoalDid / totalGames;
double AverageGoalGet = GoalGet / totalGames;
return Tuple.Create(AverageGoalDid, AverageGoalGet);
}
static int[] calculateWins(string str)
{
int[] calcWin = new int[3];
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ':')
{
double a = Int32.Parse(str[i - 1].ToString());
double b = Int32.Parse(str[i + 1].ToString());
if (a > b)
{
calcWin[0]++;
}
else if (a < b)
{
calcWin[1]++;
}
else
{
calcWin[2]++;
}
}
}
for (int i = 0; i < 3; i++)
{
Console.WriteLine(calcWin[i].ToString());
}
return calcWin;
}
//Записываем показатели игроков З,П,Н,В
static List<string> teamSorting(string str)
{
int x = 0, y = 0;
List<string> cor = new List<string>();
string[] teamComposition = str.Split(' ');
for (int i = 0; i < teamComposition.Length; i++)
{
for (int j = 0; j < teamComposition[i].Length; j++)
{
if (teamComposition[i][j] == '(')
{
x = j + 1;
}
else if (teamComposition[i][j] == ')')
{
y = j;
cor.Add(teamComposition[i].Substring(x, y - x));
}
}
}
return cor;
}
//Среднее значение каждой категории З,П,Н,В
static List<double> splitComposition(List<string> strArray)
{
List<string[]> listOfSplittedCompositions = new List<string[]>();
for (int i = 0; i < strArray.Count; i++)
{
string[] splittedTeam = strArray[i].Split(',');
listOfSplittedCompositions.Add(splittedTeam);
}
List<List<double>> averageList = new List<List<double>>();
for (int i = 0; i < listOfSplittedCompositions.Count; i++)
{
List<double> scores = new List<double>();
for (int j = 0; j < listOfSplittedCompositions[i].Length; j++)
{
StringBuilder sb = new StringBuilder(listOfSplittedCompositions[i][j]);
sb.Replace('.', ',');
string s = sb.ToString();
double d = Double.Parse(s);
scores.Add(d);
}
averageList.Add(scores);
}
List<double> aver = new List<double>();
for (int i = 0; i < averageList.Count; i++)
{
double d = 0;
for (int j = 0; j < averageList[i].Count; j++)
{
d += averageList[i][j];
}
aver.Add(d / averageList[i].Count);
}
/* for (int i = 0; i < aver.Count; i++)
{
Console.WriteLine(aver[i].ToString());
}*/
/* foreach (double d in aver)
{
Console.WriteLine(d.ToString());
}*/
return aver;
}
static void Menu()
{
Console.WriteLine("This is football prediction app, enter 2 teams...");
}
static double TotalAverage(List<double> list)
{
double totalAverage = 0;
for (int i = 0; i < list.Count; i++)
{
totalAverage += list[i];
}
return totalAverage / list.Count;
}
static double[] computeTotal(int[] t1, int[] t2)
{
double[] total = new double[3];
total[0] = t1[0] + t2[1];
total[1] = t1[2] + t2[2];
total[2] = t1[1] + t2[0];
total[0] = (total[0] / 14) * 100;
total[1] = (total[1] / 14) * 100;
total[2] = (total[2] / 14) * 100;
return total;
}
static double[] calc(double[] d, double per1, double per2)
{
double[] win = new double[2];
win[0] = d[0] * per1 * 2;
win[1] = d[1] * per2 * 2;
return win;
}
void Calc()
{
string force = ReadData("dataset.txt");
string[] datasetArray = force.Split('~');
List<string> dataset = ConvertToList(datasetArray);
Menu();
Console.Write("Team 1 is: ");
string t1 = t1Label.Text;
Console.Write("Team 2 is: ");
string t2 = t2Label.Text + " A";
List<string> Team1 = FindTeamScores(dataset, t1);
List<string> Team2 = FindTeamScores(dataset, t2);
Tuple<double, double> team1GoalStat = GoalCounting(Team1[0]);
Tuple<double, double> team2GoalStat = GoalCounting(Team2[0]);
int[] team1Wins = calculateWins(Team1[0]);
int[] team2Wins = calculateWins(Team2[0]);
List<string> team1TeamStat = teamSorting(Team1[1]);
List<string> team2TeamStat = teamSorting(Team2[1]);
List<double> team1AverageStat = splitComposition(team1TeamStat);
List<double> team2AverageStat = splitComposition(team2TeamStat);
double t1Average = TotalAverage(team1AverageStat);
double t2Average = TotalAverage(team2AverageStat);
double all = t1Average + t2Average;
double per1 = t1Average * 100 / all;
double per2 = t2Average * 100 / all;
Console.WriteLine(per1.ToString() + "\n" + per2.ToString() + "\n");
double[] prediction = computeTotal(team1Wins, team2Wins);
double[] wins = calc(prediction, per1, per2);
per1 = ((per1 * 2) / 100) * prediction[0];
per2 = ((per2 * 2) / 100) * prediction[2];
double dr = 100 - per1 - per2;
//double draw = 100 - wins[0] + wins[1];
t1Win.Text = per1.ToString();
t2Win.Text = per2.ToString();
draw.Text = dr.ToString();
for (int i = 0; i < 100; i++)
{
if (i < (int)per1)
labelList[i].BackColor = Color.DarkBlue;
else if ((i - per1) < (int)dr)
labelList[i].BackColor = Color.White;
else if ((i - per1 - dr) < (int)per2)
labelList[i].BackColor = Color.DarkRed;
}
Console.WriteLine("\nTeam " + t1 + " on average scores " + team1GoalStat.Item1 + " on average misses " +
team1GoalStat.Item2 + ".\n " + "Their average Goalkeeper, Defenders, Semidefenders and Attackers are " +
team1AverageStat[0] + " " + team1AverageStat[1] + " " + team1AverageStat[2] + " " + team1AverageStat[3] + ".\n"
);
Console.WriteLine("Team " + t2 + " on average scores " + team2GoalStat.Item1 + " on average misses " +
team2GoalStat.Item2 + ".\n " + "Their average Goalkeeper, Defenders, Semidefenders and Attackers are " +
team2AverageStat[0] + " " + team2AverageStat[1] + " " + team2AverageStat[2] + " " + team2AverageStat[3] + ".\n"
);
Console.WriteLine("Probability of winning " + t1 + " is: " + wins[0] + "%.\n");
Console.WriteLine("Probability of winning " + t2 + " is: " + wins[1] + "%.\n");
double draww = 100 - wins[0] - wins[1];
Console.WriteLine("Draw is " + draww);
Console.ReadLine();
}
private void button1_Click(object sender, EventArgs e)
{
Calc();
}
}
}
|
fcd31f084a6ba9841bdae71da50614488432886d
|
C#
|
ARLM-Attic/metalinq
|
/Releases/SerializableV1/ExpressionBuilder/Expressions/EditableMemberInitExpression.cs
| 2.59375
| 3
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization;
namespace ExpressionBuilder
{
[DataContract]
public class EditableMemberInitExpression : EditableExpression
{
EditableMemberBindingCollection _memberBindings = new EditableMemberBindingCollection();
EditableNewExpression _new;
[DataMember]
public EditableNewExpression NewExpression { get { return _new; } set { _new = value; } }
[DataMember]
public EditableMemberBindingCollection Bindings { get { return _memberBindings; } set { _memberBindings = value; } }
public override ExpressionType NodeType
{
get
{
return ExpressionType.MemberInit;
}
set
{
// throw new Exception("The method or operation is not implemented.");
}
}
public EditableMemberInitExpression()
{
}
public EditableMemberInitExpression(MemberInitExpression membInit)
: this(EditableExpression.CreateEditableExpression(membInit.NewExpression) as EditableNewExpression,membInit.Bindings)
{}
public EditableMemberInitExpression(EditableNewExpression newEx, IEnumerable<MemberBinding> bindings)
{
_memberBindings = new EditableMemberBindingCollection(bindings);
_new = newEx;
}
public EditableMemberInitExpression(NewExpression newRawEx, IEnumerable<MemberBinding> bindings)
: this(EditableExpression.CreateEditableExpression(newRawEx) as EditableNewExpression,bindings)
{}
public override Expression ToExpression()
{
return Expression.MemberInit(_new.ToExpression() as NewExpression, _memberBindings.GetMemberBindings());
}
}
}
|
e14eb1821174c442221bd9fa2e2b3eb6d0bec617
|
C#
|
jmcupidon/openstack.net
|
/src/corelib/Configuration.cs
| 2.515625
| 3
|
using System;
using Flurl.Http;
using Flurl.Http.Configuration;
using Newtonsoft.Json;
using OpenStack.Authentication;
using OpenStack.Serialization;
namespace OpenStack
{
/// <summary>
/// A static container for global configuration settings affecting OpenStack.NET behavior.
/// </summary>
/// <threadsafety static="true" instance="false"/>
public static class OpenStackNet
{
private static readonly object ConfigureLock = new object();
private static bool _isConfigured = false;
/// <summary>
/// Provides thread-safe accesss to OpenStack.NET's global configuration options.
/// <para>
/// Can only be called once at application start-up, before instantiating any OpenStack.NET objects.
/// </para>
/// </summary>
/// <param name="configureFlurl">Addtional configuration of Flurl's global settings <seealso cref="Flurl.Http.FlurlHttp.Configure"/>.</param>
/// <param name="configureJson">Additional configuration of Json.NET's glboal settings <seealso cref="Newtonsoft.Json.JsonConvert.DefaultSettings"/>.</param>
public static void Configure(Action<FlurlHttpConfigurationOptions> configureFlurl = null, Action<JsonSerializerSettings> configureJson = null)
{
if (_isConfigured)
return;
lock (ConfigureLock)
{
if (_isConfigured)
return;
JsonConvert.DefaultSettings = () =>
{
// Apply our default settings
var settings = new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new EmptyEnumerableResolver()
};
// Apply application's default settings
if (configureJson != null)
configureJson(settings);
return settings;
};
FlurlHttp.Configure(c =>
{
// Apply our default settings
c.HttpClientFactory = new AuthenticatedHttpClientFactory();
// Apply application's default settings
if (configureFlurl != null)
configureFlurl(c);
});
_isConfigured = true;
}
}
}
}
|
aded104bf330b9080d073fb3f0f5430d11238e00
|
C#
|
ErikNoren/StronglyTypedConfiguration
|
/StronglyTypedConfiguration.Tests/MultiValueTests.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StronglyTypedConfiguration.Tests
{
[TestClass]
public class MultiValueTests
{
[TestMethod]
public void MultiValueString()
{
var setting = new List<string>(ConfigurationManager.AppSettings.GetValuesOrDefault<string>("multiString"));
var values = new List<string>() { "Apple", "Banana", "Carrot", "Dish Soap" };
Assert.AreEqual(4, setting.Count());
Assert.IsFalse(setting.Except(values).Any());
}
[TestMethod]
public void MultiValueInt()
{
var setting = ConfigurationManager.AppSettings.GetValuesOrDefault<int>("multiInt");
var values = new List<int>() { 16, 8, 32, 500, 2140000000, 1 };
Assert.AreEqual(6, setting.Count());
Assert.IsFalse(setting.Except(values).Any());
}
[TestMethod]
public void MultiValueLong()
{
var setting = ConfigurationManager.AppSettings.GetValuesOrDefault<long>("multiLong");
var values = new List<long>() { 16, 8, 32, 500, 9223372036854775806, 1 };
Assert.AreEqual(6, setting.Count());
Assert.IsFalse(setting.Except(values).Any());
}
[TestMethod]
public void MultiValueDouble()
{
var setting = ConfigurationManager.AppSettings.GetValuesOrDefault<double>("multiDouble");
var values = new List<double>() { 23.99, 100.514, 867.5309, 0 };
Assert.AreEqual(4, setting.Count());
Assert.IsFalse(setting.Except(values).Any());
}
[TestMethod]
public void MultiValueGuid()
{
var setting = ConfigurationManager.AppSettings.GetValuesOrDefault<Guid>("multiGuid");
var values = new List<Guid>() { Guid.Parse("{351C24E4-9029-4F86-9F19-CC0629663ED5}"), Guid.Parse("{2883FFBE-8C3C-451F-8C58-794307F9D5BF}"), Guid.Parse("{5D9950ED-079F-4853-9736-35D6C417069B}") };
Assert.AreEqual(3, setting.Count());
Assert.IsFalse(setting.Except(values).Any());
}
[TestMethod]
public void MultiValueDateTime()
{
var setting = ConfigurationManager.AppSettings.GetValuesOrDefault<DateTime>("multiDateTime");
var values = new List<DateTime>() { DateTime.Parse("2010-01-01 5:00:00am"), DateTime.Parse("2016 -11-30 6:30:00pm"), DateTime.Parse("1999-12-31 11:59:59pm") };
Assert.AreEqual(3, setting.Count());
Assert.IsFalse(setting.Except(values).Any());
}
[TestMethod]
public void MultiValueBool()
{
var setting = ConfigurationManager.AppSettings.GetValuesOrDefault<bool>("multiBool");
var values = new List<bool>() { true, false, false, true };
Assert.AreEqual(4, setting.Count());
Assert.IsFalse(setting.Except(values).Any());
}
}
}
|
c703f41cf14371c2dcee692d284ec2df965d8398
|
C#
|
RegJoshua/XPS
|
/XPS/XPS/Forms/DeleteUserForm.cs
| 2.8125
| 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 XPS.Logic;
using XPS.Models;
namespace XPS.Forms
{
/**************************************************************************
* Class Delete User Form
*
* Administrators use this form to delete users from the database. The
* administrator enters the Mustang ID of the user to be deleted and then
* clicks the "Get User" key. XPS displays the first and last name of the
* user to be deleted for confirmation. If the correct user is displayed,
* the admin clicks the "Delete User" button; if not, admin selects the
* "Cancel" button and the form returns to its opening state.
*
**************************************************************************/
public partial class DeleteUserForm : Form
{
// create the objects used by the form in the deletion process
private DatabaseManager _thisOne;
private User _deleteMe;
private AdminForm _AdminForm;
/**********************************************************************
*
* Constructor
* @param: AdminForm anAdminForm
*
**********************************************************************/
public DeleteUserForm(AdminForm anAdminForm)
{
_AdminForm = anAdminForm;
InitializeComponent();
}
/**********************************************************************
*
* private void DeleteUserForm_FormClosing
* @param: object sender, FormClosingEventArgs e
* @return: NA
* @closes this form and displays the admin form passed into the
* constructor
*
**********************************************************************/
private void DeleteUserForm_FormClosing(object sender, FormClosingEventArgs e)
{
_AdminForm.Show();
}
/**********************************************************************
*
* private void dAdminMenu_Click
* @param: object sender, EventArgs e
* @return: NA
* @closes this form and displays the admin form passed into the
* constructor
*
**********************************************************************/
private void dAdminMenu_Click(object sender, EventArgs e)
{
this.Hide();
_AdminForm.Show();
}
/**********************************************************************
*
* private dGetUserButton_Click
* @param: object sender, EventArgs e
* @return: NA
* @queries the database through the database manager with the
* Mustang ID entered by the user.
*
**********************************************************************/
private void dGetUserButton_Click(object sender, EventArgs e)
{
try
{
_thisOne = new DatabaseManager();
_deleteMe = _thisOne.GetUser(Int32.Parse(dMustangBox.Text));
dFirstnameBox.Text = _deleteMe.FirstName;
dLastnameBox.Text = _deleteMe.LastName;
dInstructionBox.Hide();
dVerifyBox.Show();
dDeleteUserButton.Show();
dFirstnameLabel.Show();
dFirstnameBox.Show();
dLastnameLabel.Show();
dLastnameBox.Show();
dMustangBox.Text = "";
}
catch(Exception ex)
{
MessageBox.Show("No record found for that Mustang ID.");
dMustangBox.Text = "";
}
}
/**********************************************************************
*
* private dDeleteUserButton_Click
* @param: object sender, EventArgs e
* @return: NA
* @First displays confirmation message box; upon confirmation, deletes
* user from database through the agency of the database manager. Absent
* confirmation, restores form to its opening configuration.
*
**********************************************************************/
private void dDeleteUserButton_Click(object sender, EventArgs e)
{
// first display confirmation message box
DialogResult result1 = MessageBox.Show("Do you want to delete " +
_deleteMe.FirstName + " " + _deleteMe.LastName + "?",
"About to delete", MessageBoxButtons.YesNo);
// if confirmed, delete the user
if (result1 == DialogResult.Yes)
{
try
{
bool deleteSuccessful = _thisOne.DeleteUser(_deleteMe.UserID);
if (deleteSuccessful)
{
MessageBox.Show(_deleteMe.FirstName +
" " + _deleteMe.LastName + " deleted from users table.");
dMustangBox.Text = "";
dFirstnameBox.Text = "";
dLastnameBox.Text = "";
dInstructionBox.Show();
dVerifyBox.Hide();
dDeleteUserButton.Hide();
dFirstnameLabel.Hide();
dFirstnameBox.Hide();
dLastnameLabel.Hide();
dLastnameBox.Hide();
}
}
catch (Exception ex) { }
}
// if "no" was selected on confirmation, display form in opening
// configuration
else
{
dMustangBox.Text = "";
dFirstnameBox.Text = "";
dLastnameBox.Text = "";
dInstructionBox.Show();
dVerifyBox.Hide();
dDeleteUserButton.Hide();
dFirstnameLabel.Hide();
dFirstnameBox.Hide();
dLastnameLabel.Hide();
dLastnameBox.Hide();
}
}
/**********************************************************************
*
* private dCancelButton_Click
* @param: object sender, EventArgs e
* @return: NA
* @restores form to its opening configuration.
*
**********************************************************************/
private void dCancelButton_Click(object sender, EventArgs e)
{
dMustangBox.Text = "";
dFirstnameBox.Text = "";
dFirstnameBox.Hide();
dLastnameBox.Text = "";
dLastnameBox.Hide();
dDeleteUserButton.Hide();
dVerifyBox.Hide();
dInstructionBox.Show();
}
}
}
|
8db4e025532f3f0507b8ba33ebccaf8e61731515
|
C#
|
eabronskill/Event_Horizon
|
/Event Horizon/Assets/Scripts/Triggers/Enemies/EnemyTrigger.cs
| 2.515625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyTrigger : MonoBehaviour
{
public List<GameObject> enemies;
public GameObject parent;
private bool activate = false;
private bool triggered = false;
void Start()
{
if (parent != null)
{
foreach (Enemy o in parent.GetComponentsInChildren<Enemy>())
{
enemies.Add(o.gameObject);
}
}
}
void Update()
{
if (activate && !triggered)
{
triggered = true;
foreach(GameObject enemy in enemies)
{
enemy.gameObject.GetComponent<Enemy>().active = true;
}
}
}
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Player")
{
activate = true;
}
}
}
|
57ea2c0bacf325cf4e6a9e5b231e3ef006e8c751
|
C#
|
zhaoyuanhai/guangyu.bownt
|
/CompanyUI/App_Start/WhiteSpaceFilter.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
namespace CompanyUI.App_Start
{
public class WhiteSpaceFilter : Stream
{
private Stream _shrink;
private Func<string, string> _filter;
private System.Text.Encoding _encoding;
public WhiteSpaceFilter(HttpResponse response, Func<string, string> filter)
{
_encoding = response.ContentEncoding;
_shrink = response.Filter;
_filter = filter;
}
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } }
public override bool CanWrite { get { return true; } }
public override void Flush() { _shrink.Flush(); }
public override long Length { get { return _shrink.Length; } }
public override long Position { get; set; }
public override int Read(byte[] buffer, int offset, int count)
{
return _shrink.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _shrink.Seek(offset, origin);
}
public override void SetLength(long value)
{
_shrink.SetLength(value);
}
public override void Close()
{
_shrink.Close();
}
public override void Write(byte[] buffer, int offset, int count)
{
// capture the data and convert to string
byte[] data = new byte[count];
Buffer.BlockCopy(buffer, 0, data, 0, count);
string s = _encoding.GetString(data);
// filter the string
s = _filter(s);
// write the data to stream
byte[] outdata = _encoding.GetBytes(s);
_shrink.Write(outdata, offset, outdata.Length);
}
}
}
|
3195b0108985562943a88cb5f11db40cd286be68
|
C#
|
ashwini-mnnit/Coding-Practice
|
/SerializeTree/Program.cs
| 3.21875
| 3
|
using System;
namespace SerializeTree {
class Program {
static void Main (string[] args) {
TreeNode One = new TreeNode (1);
TreeNode Two = new TreeNode (2);
TreeNode Three = new TreeNode (3);
//One.Left= Two;
//One.Right = Three;
Solution sln = new Solution ();
//Console.WriteLine(sln.Serialize(One));
One.Left = Two;
Two.Left = Three;
//PrintTree(One, " ", false);
string treestring = sln.Serialize(One);
Console.WriteLine (treestring);
TreeNode tree = sln.Deserialize(treestring);
Console.WriteLine (sln.Serialize (One));
}
public static void PrintTree (TreeNode tree, String indent, bool last) {
if(tree == null)
{
return;
}
Console.Write (indent + "+- " + tree.Val);
indent += last ? " " : "| ";
PrintTree (tree.Left, indent, false);
PrintTree (tree.Right, indent, true);
}
}
}
|
2e4000b7127248fee55ffd3aae23a870011f7152
|
C#
|
cfmis/cf01
|
/CLS/ExpToExcel.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Data;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;
namespace cf01.CLS
{
public class ExpToExcel
{
private static string strFileName;
public static string GetFileName(DataGridView _dgv)
{
//申明保存对话框
SaveFileDialog dlg = new SaveFileDialog();
//默認文件后缀
dlg.DefaultExt = "xls ";
//文件后缀列表
dlg.Filter = "EXCEL文件(*.XLS)|*.xls ";
//默認路径是系统当前路径
dlg.InitialDirectory = Directory.GetCurrentDirectory();
//打开保存对话框
if (dlg.ShowDialog() == DialogResult.Cancel) return null;
//返回文件路径
strFileName = dlg.FileName;
//验证strFileName是否为空或值无效
if (strFileName.Trim() == " ") return null;
//定义表格内数据的行数和列数
int rowscount = _dgv.Rows.Count;
int colscount = _dgv.Columns.Count;
//行数必须大于0
if (rowscount <= 0)
{
MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return null;
}
//列数必须大于0
if (colscount <= 0)
{
MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return null;
}
//行数不可以大于65536
if (rowscount > 65536)
{
MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return null;
}
//列数不可以大于255
if (colscount > 255)
{
MessageBox.Show("数据记录行数太多,不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return null;
}
//验证以fileNameString命名的文件是否存在,如果存在删除它
FileInfo file = new FileInfo(strFileName);
if (file.Exists)
{
try
{
file.Delete();
}
catch (Exception error)
{
MessageBox.Show(error.Message, "删除失败 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return null;
}
}
return strFileName;
}
public void SaveToExcel(DataGridView _dgv, BackgroundWorker _worker)
{
string strFileName = ExpToExcel.GetFileName(_dgv);
if (strFileName == "" || strFileName == null)
{
return;
}
int rowscount = _dgv.Rows.Count;
int colscount = _dgv.Columns.Count;
int intValue = 0;
//创建空EXCEL对象
Microsoft.Office.Interop.Excel.Application objExcel = null;
Microsoft.Office.Interop.Excel.Workbook objWorkbook = null;
Microsoft.Office.Interop.Excel.Worksheet objSheet = null;
Microsoft.Office.Interop.Excel.Range rg = null;
try
{
//申明对象
objExcel = new Microsoft.Office.Interop.Excel.Application();
objWorkbook = objExcel.Workbooks.Add(Missing.Value);
objSheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkbook.Worksheets[1];//强制类型转换
//设置EXCEL不可见(后台运行)
objExcel.Visible = false;
//向Excel中写入表格的表头
int displayColumnsCount = 1;
for (int i = 0; i <= _dgv.ColumnCount - 1; i++)
{
if (_dgv.Columns[i].Visible == true)
{
objExcel.Cells[1, displayColumnsCount] = _dgv.Columns[i].HeaderText.Trim();
displayColumnsCount++;
}
}
//向Excel中逐行逐列写入表格中的数据
for (int row = 0; row <= _dgv.RowCount - 1; row++)
{
displayColumnsCount = 1;
for (int col = 0; col < colscount; col++)
{
if (_dgv.Columns[col].Visible == true)
{
if (col == 4 || col == 5)//_dgv.Columns[col].HeaderText == "size" || _dgv.Columns[col].HeaderText == "size_desc"
{
objExcel.Cells[row + 2, displayColumnsCount] = "'" + _dgv.Rows[row].Cells[col].Value.ToString().Trim();
}
else
{
objExcel.Cells[row + 2, displayColumnsCount] = _dgv.Rows[row].Cells[col].Value.ToString().Trim();
}
if (_dgv.Rows[row].Cells[col].Value.ToString() == "Sub-Total" || _dgv.Rows[row].Cells[col].Value.ToString() == "Sum-Total")
{
rg = (Microsoft.Office.Interop.Excel.Range)
objSheet.Range[objSheet.Cells[row + 2, 1], objSheet.Cells[row + 2, colscount]];
rg.Font.Bold = true;
rg.Font.Size = 15;
rg.Interior.ColorIndex = 35;
rg.Interior.Pattern = -4105;
}
displayColumnsCount++;
}
}
intValue++;
string strMessage = ((100 * intValue) / rowscount).ToString() + "%";
Thread.Sleep(100);
_worker.ReportProgress(((100 * intValue) / rowscount), strMessage); //注意:这里向子窗体返回两个信息值,一个用于进度条,一个用于label的。
System.Windows.Forms.Application.DoEvents();
}
//objSheet.Columns.EntireColumn.AutoFit();//列宽自适应
//保存文件
objWorkbook.SaveAs(strFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
}
catch (Exception error)
{
MessageBox.Show(error.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
//关闭Excel应用
if (objWorkbook != null) objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);
if (objExcel.Workbooks != null) objExcel.Workbooks.Close();
if (objExcel != null) objExcel.Quit();
//清空工作表
objSheet = null;
//清空工作薄
objWorkbook = null;
objExcel = null;
//强行杀死最近打开的excel进程
KillProcess("EXCEL");
MessageBox.Show(strFileName + "\n\n导出成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#region 关闭Excel进程
/// <summary>
/// 关闭Excel进程
/// </summary>
/// <param name="processName">进程名称</param>
public static void KillProcess(string processName)
{
//获得进程对象,以用来操作
System.Diagnostics.Process proce = new System.Diagnostics.Process();
//得到所有打开的进程
try
{
//获得需要杀死的进程名
foreach (Process thisproc in Process.GetProcessesByName(processName))
{
//立即杀死进程
thisproc.Kill();
}
}
catch (Exception exc)
{
throw new Exception(exc.Message);
}
}
#endregion
#region 打开导出的Excel文件
/// <summary>
/// 打开导出的Excel文件
/// </summary>
/// <param name="fileName"></param>
private void OpenExcel(string fileName)
{
System.Diagnostics.ProcessStartInfo info = new ProcessStartInfo();
//info.WorkingDirectory = System.Windows.Forms.Application.StartupPath;
//指定要打开的文件的路径
info.FileName = fileName;
System.Diagnostics.Process.Start(info);
}
#endregion
public void DataTableToExcel(DataTable dtData)
{
//這個是用來將表dataTable進行快速匯出
string path;
path = getfilename();
if (path == "")
return;
if (File.Exists(path))
{
File.Delete(path);
}
Encoding encoding = Encoding.GetEncoding("big5");
StreamWriter writer = new StreamWriter(File.Open(path, FileMode.CreateNew), encoding);
HtmlTextWriter writer2 = new HtmlTextWriter(writer);
System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
grid.DataSource = dtData;// dtData;
grid.DataBind();
grid.RenderControl(writer2);
writer.Close();
}
private string getfilename()
{
//申明保存对话框
SaveFileDialog dlg = new SaveFileDialog();
//默然文件后缀
dlg.DefaultExt = "xls ";
//文件后缀列表
dlg.Filter = "EXCEL文件(*.XLS)|*.xls ";
//默然路径是系统当前路径
dlg.InitialDirectory = Directory.GetCurrentDirectory();
//打开保存对话框
if (dlg.ShowDialog() == DialogResult.Cancel)
return "";
//返回文件路径
string fileNameString = dlg.FileName;
//验证strFileName是否为空或值无效
if (fileNameString.Trim() == " ")
MessageBox.Show("文件名為空!", "匯出文件", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return fileNameString.Trim();
}
public void DvExportToExcel(DataGridView _dgv)
{
//這個是用來將表格dataGridView進行快速匯出
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.Filter = "Excel files(*.xls)|*.xls";
saveFile.FilterIndex = 0;
saveFile.RestoreDirectory = true;
saveFile.CreatePrompt = true;
saveFile.Title = "导出數據到Excel文件";
if (saveFile.ShowDialog() == DialogResult.OK)
{
Stream myStream;
myStream = saveFile.OpenFile();
StreamWriter sw = new StreamWriter(myStream, Encoding.GetEncoding("big5"));
string str = " ";
//写标题
for (int i = 0; i < _dgv.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += _dgv.Columns[i].HeaderText.ToString();// dv.Table.Columns[i].ColumnName;
}
sw.WriteLine(str);
//写内容
for (int rowNo = 0; rowNo < _dgv.RowCount; rowNo++)
{
string tempstr = " ";
for (int columnNo = 0; columnNo < _dgv.ColumnCount; columnNo++)
{
if (_dgv.Columns[columnNo].Visible == true)
{
if (columnNo > 0)
{
tempstr += "\t";
}
if (_dgv.Rows[rowNo].Cells[columnNo].Value != null)
{
if (columnNo == 4 || columnNo == 5)
{
tempstr += "'" + _dgv.Rows[rowNo].Cells[columnNo].Value.ToString().Trim();
}
else
{
tempstr += _dgv.Rows[rowNo].Cells[columnNo].Value.ToString().Trim();
}
}
else
{
tempstr += "";
}
}
}
sw.WriteLine(tempstr);
}
sw.Close();
myStream.Close();
MessageBox.Show("匯出EXCEL成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#region 将Excel数据绑定到dataGridView
public void ExcelToDGV()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "打开(Open)"; //标题
ofd.ShowHelp = true;
ofd.Filter = "文本文件(*txt)|*.txt|RTF文件(*.rtf)|*.rtf|excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
ofd.FilterIndex = 1; //格式索引
ofd.RestoreDirectory = false;
ofd.InitialDirectory = Directory.GetCurrentDirectory();
ofd.Multiselect = true;
ofd.ValidateNames = true; //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名
ofd.CheckFileExists = true; //验证路径有效性
ofd.CheckPathExists = true; //验证文件有效性
string path = "";
if (ofd.ShowDialog() == DialogResult.OK)
path = ofd.FileName; //完整路径
DataSet m_ds = new DataSet();
string strConn = @"Provider = Microsoft.Jet.OLEDB.4.0;Data Source = "
+ path + ";Extended Properties=Excel 8.0";
string strSheetName = "sheet1"; //默认sheet1
string strExcel = string.Format("select * from [{0}$]", strSheetName);
//using (OleDbConnection conn = new OleDbConnection(strConn))
//{
// try
// {
// conn.Open();
// OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
// adapter.Fill(m_ds, strSheetName);
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.ToString());
// }
// finally
// {
// conn.Close();
// }
//}
//this.dataGridView1.DataSource = m_ds.Tables[strSheetName];
//return m_ds;
//StreamReader read = File.OpenText(filename);
//string str;
//while (str = read.ReadLine() != null)
//{
// //将读出的字符串在richTextBox1中显示
// this.richTextBox1.Text += str;
//}
}
#endregion
/// <summary>
/// 將DataGridView中的內容匯出到Excel
/// allen_leung 2014-10-09
/// </summary>
/// <param name="m_DataView"></param>
public static void DataGridViewToExcel(DataGridView m_DataView)
{
SaveFileDialog kk = new SaveFileDialog();
kk.Title = "保存EXECL 文件";
kk.Filter = "EXECL文件(*.xls)|*.xls";
kk.FilterIndex = 1;
if (kk.ShowDialog() == DialogResult.OK)
{
string FileName = kk.FileName;// +".xls";
if (File.Exists(FileName))
File.Delete(FileName);
FileStream objFileStream;
StreamWriter objStreamWriter;
string strLine = "";
objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
for (int i = 0; i < m_DataView.Columns.Count; i++)
{
if (m_DataView.Columns[i].Visible == true)
{
strLine = strLine + m_DataView.Columns[i].HeaderText.ToString() + Convert.ToChar(9);
}
}
objStreamWriter.WriteLine(strLine);
strLine = "";
for (int i = 0; i < m_DataView.Rows.Count; i++)
{
if (m_DataView.Columns[0].Visible == true)
{
if (m_DataView.Rows[i].Cells[0].Value == null)
strLine = strLine + " " + Convert.ToChar(9);
else
strLine = strLine + m_DataView.Rows[i].Cells[0].Value.ToString() + Convert.ToChar(9);
}
for (int j = 1; j < m_DataView.Columns.Count; j++)
{
if (m_DataView.Columns[j].Visible == true)
{
if (m_DataView.Rows[i].Cells[j].Value == null)
strLine = strLine + " " + Convert.ToChar(9);
else
{
string rowstr = "";
rowstr = m_DataView.Rows[i].Cells[j].Value.ToString();
if (rowstr.IndexOf("\r\n") > 0)
rowstr = rowstr.Replace("\r\n", " ");
if (rowstr.IndexOf("\t") > 0)
rowstr = rowstr.Replace("\t", " ");
strLine = strLine + rowstr + Convert.ToChar(9);
}
}
}
objStreamWriter.WriteLine(strLine);
strLine = "";
}
objStreamWriter.Close();
objFileStream.Close();
MessageBox.Show("匯出EXCEL成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
//****************2016-03-24********************
//因之前的匯出EXCEL,打開時老彈出提示格式不正確
//增加了匯出版本的判斷,新增的匯出方法。
//*********************************************
/// <summary>
/// 參數為DataGridView格式
/// </summary>
/// <param name="myDGV"></param>
public void ExportExcel(DataGridView myDGV)
{
if (myDGV.Rows.Count > 0)
{
//bool fileSaved = false;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Title = "保存EXECL文件";
saveDialog.Filter = "EXECL文件|*.xls";
saveDialog.FilterIndex = 1;
if (saveDialog.ShowDialog() == DialogResult.OK)
{
string FileName = saveDialog.FileName;
if (File.Exists(FileName))
{
File.Delete(FileName);
}
int FormatNum;//保存excel文件的格式
string Version;//excel版本號
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("無法創建Excel對象,可能當前操作系統上未安裝有Excel");
return;
}
Version = xlApp.Version;//獲取當前使用excel版本號
if (Convert.ToDouble(Version) < 12)//You use Excel 97-2003
{
FormatNum = -4143;
}
else //you use excel 2007 or later
{
FormatNum = 56;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
cf01.Forms.frmProgress wForm = new cf01.Forms.frmProgress();
new Thread((ThreadStart)delegate
{
wForm.TopMost = true;
wForm.ShowDialog();
}).Start();
//寫入標題
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
}
//寫入數值
for (int r = 0; r < myDGV.Rows.Count; r++)
{
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
wForm.Invoke((EventHandler)delegate { wForm.Close(); });
if (FileName != "")
{
try
{
workbook.Saved = true;
//workbook.SaveCopyAs(saveFileName);
workbook.SaveAs(FileName, FormatNum);
//fileSaved = true;
}
catch (Exception ex)
{
//fileSaved = false;
MessageBox.Show("導出文件出錯或者文件可能已被打開!\n" + ex.Message);
}
}
xlApp.Quit();
GC.Collect();//强行销毁
// if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL
clsUtility.myMessageBox("匯出EXCEL成功!", "提示信息");
//MessageBox.Show("匯出EXCEL成功!", "系統提示", MessageBoxButtons.OK);
}
}
else
{
MessageBox.Show("無要匯出EXCEL之數據!", "提示信息", MessageBoxButtons.OK);
}
}
public void ExportToExcel_Fast(DataGridView _dgv)
{
//這個是用來將表格dataGridView進行快速匯出
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.Filter = "Excel files(*.xls)|*.xls";
saveFile.FilterIndex = 0;
saveFile.RestoreDirectory = true;
saveFile.CreatePrompt = true;
saveFile.Title = "导出數據到Excel文件";
if (saveFile.ShowDialog() == DialogResult.OK)
{
Stream myStream = saveFile.OpenFile();
StreamWriter sw = new StreamWriter(myStream, Encoding.GetEncoding("big5"));
string str = "";
//写标题
for (int i = 0; i < _dgv.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += _dgv.Columns[i].HeaderText.ToString();// dv.Table.Columns[i].ColumnName;
}
sw.WriteLine(str);
//写内容
for (int rowNo = 0; rowNo < _dgv.RowCount; rowNo++)
{
string tempstr = "";
for (int columnNo = 0; columnNo < _dgv.ColumnCount; columnNo++)
{
if (_dgv.Columns[columnNo].Visible == true)
{
if (columnNo > 0)
{
tempstr += "\t";
}
if (_dgv.Rows[rowNo].Cells[columnNo].Value != null)
{
tempstr += _dgv.Rows[rowNo].Cells[columnNo].Value.ToString().Trim();
}
else
{
tempstr += "";
}
}
}
sw.WriteLine(tempstr);
}
sw.Close();
myStream.Close();
MessageBox.Show("匯出EXCEL成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
|
c7baf5a8f1bfce5ba8ea8d7f639f151a5c98097b
|
C#
|
MichaelSong9/when-its-done
|
/WhenItsDone/Tests/LibTests/WhenItsDone.Models.Tests/ClientTests/ClientRatingTests.cs
| 2.640625
| 3
|
using NUnit.Framework;
using System.Linq;
using WhenItsDone.Models.Constants;
namespace WhenItsDone.Models.Tests.ClientTests
{
[TestFixture]
public class ClientRatingTests
{
[Test]
public void Rating_ShouldHave_RangeAttribute()
{
var obj = new Client();
var result = obj.GetType()
.GetProperty("Rating")
.GetCustomAttributes(false)
.Where(x => x.GetType() == typeof(System.ComponentModel.DataAnnotations.RangeAttribute))
.Any();
Assert.IsTrue(result);
}
[Test]
public void Rating_ShouldHave_RightMinValueFor_RangeAttribute()
{
var obj = new Client();
var result = obj.GetType()
.GetProperty("Rating")
.GetCustomAttributes(false)
.Where(x => x.GetType() == typeof(System.ComponentModel.DataAnnotations.RangeAttribute))
.Select(x => (System.ComponentModel.DataAnnotations.RangeAttribute)x)
.SingleOrDefault();
Assert.IsNotNull(result);
Assert.AreEqual(ValidationConstants.RatingMinValue, result.Minimum);
}
[Test]
public void Rating_ShouldHave_RightMaxValueFor_RangeAttribute()
{
var obj = new Client();
var result = obj.GetType()
.GetProperty("Rating")
.GetCustomAttributes(false)
.Where(x => x.GetType() == typeof(System.ComponentModel.DataAnnotations.RangeAttribute))
.Select(x => (System.ComponentModel.DataAnnotations.RangeAttribute)x)
.SingleOrDefault();
Assert.IsNotNull(result);
Assert.AreEqual(ValidationConstants.RatingMaxValue, result.Maximum);
}
[TestCase(6)]
[TestCase(54353453)]
public void Rating_GetAndSetShould_WorkProperly(int randomNumber)
{
var obj = new Client();
obj.Rating = randomNumber;
Assert.AreEqual(randomNumber, obj.Rating);
}
}
}
|
bb79f7f8c7a2ef91c13b725fbe52330e76262efb
|
C#
|
MichalGiemza/Algorytmy-II
|
/2-CNF/Program.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2_CNF
{
class Program
{
static void Main(string[] args)
{
const string wyr1 = "1|3 & 1|-4 & 2|-4 & 2|-5 & 3|-5 & 1|-6 & 2|-6 & 3|-6 & 4|7 & 5|7 & 6|7";
const string wyr2 = "1|1 & -1|-1";
const string wyr3 = "1|2 & 2|3 & 3|1 & 4|-2 & -3|-4";
bool r1 = _2_CNF.CzySpelnialne(wyr1);
bool r2 = _2_CNF.CzySpelnialne(wyr2);
bool r3 = _2_CNF.CzySpelnialne(wyr3);
Console.WriteLine(wyr1);
Console.WriteLine("Wyrażenie jest spełnialne: " + (r1 ? "Prawda" : "Fałsz"));
Console.WriteLine();
Console.WriteLine(wyr2);
Console.WriteLine("Wyrażenie jest spełnialne: " + (r2 ? "Prawda" : "Fałsz"));
Console.WriteLine();
Console.WriteLine(wyr3);
Console.WriteLine("Wyrażenie jest spełnialne: " + (r3 ? "Prawda" : "Fałsz"));
Console.ReadLine();
}
}
}
//Graf g = new Graf(8);
//
//{
// g.DodajKrawedzSkierowana(0, 1);
//
// g.DodajKrawedzSkierowana(1, 2);
// g.DodajKrawedzSkierowana(1, 4);
// g.DodajKrawedzSkierowana(1, 5);
//
// g.DodajKrawedzSkierowana(2, 3);
// g.DodajKrawedzSkierowana(2, 6);
//
// g.DodajKrawedzSkierowana(3, 2);
// g.DodajKrawedzSkierowana(3, 7);
//
// g.DodajKrawedzSkierowana(4, 0);
// g.DodajKrawedzSkierowana(4, 5);
//
// g.DodajKrawedzSkierowana(5, 6);
//
// g.DodajKrawedzSkierowana(6, 5);
// g.DodajKrawedzSkierowana(6, 7);
//
// g.DodajKrawedzSkierowana(7, 7);
//} // Dodawanie krawedzi
|
6fd2f3de3ff8daa7616a984d8beedb756adae95e
|
C#
|
ebcbvbbbsrbbbbbb/rcgp
|
/simple_file_search/simple_file_search/Utility.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using System.Threading;
using System.Windows.Threading;
using System.Text.RegularExpressions;
namespace simple_file_search
{
public static class Utility
{
public static bool IsTextBased(string filePath, ManualResetEvent mrEvent, CancellationToken token)
{
int currentChar;
using (StreamReader sr = new StreamReader(filePath))
{
while ((currentChar = sr.Read()) != -1)
{
if (token.IsCancellationRequested)
{
break;
}
mrEvent.WaitOne(Timeout.Infinite);
if (currentChar > 0 && currentChar < 8 || currentChar > 13 && currentChar < 26)
return false;
}
return true;
}
}
public static void FileSearch(Settings CurrentSettings, State currentState, TreeView tv, Dispatcher d, ManualResetEvent mrEvent, CancellationToken token)
{
List<string> fileList;
List<string> GetDirList(string rootFolder)
{
List<string> result = new List<string>();
List<string> rootFolders = new List<string>();
rootFolders.AddRange(Directory.GetDirectories(rootFolder, "*.*", SearchOption.TopDirectoryOnly).ToList());
void MakeDirList(string currentFolder)
{
try
{
List<string> temp = Directory.GetDirectories(currentFolder, "*.*", SearchOption.TopDirectoryOnly).ToList();
foreach (string folder in temp)
{
if (token.IsCancellationRequested)
{
break;
}
mrEvent.WaitOne(Timeout.Infinite);
try
{
if (Directory.GetDirectories(folder, "*.*", SearchOption.TopDirectoryOnly).Count() == 0)
{
result.Add(folder);
d.Invoke(() => currentState.TotalFolders += 1);
}
else
{
if (!result.Contains(folder))
{
result.Add(folder);
d.Invoke(() => currentState.TotalFolders += 1);
}
currentFolder = folder;
MakeDirList(currentFolder);
}
}
catch { continue; }
}
}
catch { };
}
foreach (string s in rootFolders)
{
try
{
MakeDirList(s);
result.Add(s);
d.Invoke(() => currentState.TotalFolders += 1);
}
catch { continue; }
}
result.Add(rootFolder);
result.Sort();
return result;
}
List<string> GetFiles(string root, string mask, bool isMaskRegexp)
{
List<string> filestList = new List<string>();
List<string> dirList = GetDirList(root);
switch (isMaskRegexp)
{
case true:
Regex regEx = new Regex(CurrentSettings.FileName);
foreach (string folder in dirList)
{
if (token.IsCancellationRequested)
{
break;
}
mrEvent.WaitOne(Timeout.Infinite);
try
{
var temp = Directory.GetFiles(folder, "*.*", SearchOption.TopDirectoryOnly);
foreach (string s in temp)
{
if (token.IsCancellationRequested)
{
break;
}
mrEvent.WaitOne(Timeout.Infinite);
if (regEx.Match(s.Split('\\').Last()).Success)
{
filestList.Add(s);
}
}
}
catch { continue; }
}
break;
case false:
foreach (string folder in dirList)
{
if (token.IsCancellationRequested)
{
break;
}
mrEvent.WaitOne(Timeout.Infinite);
try
{
filestList.AddRange(Directory.GetFiles(folder, mask, SearchOption.TopDirectoryOnly));
}
catch { continue; }
}
break;
}
return filestList;
}
bool CheckFileContent(bool isRegExp, string searchText, string _fileName)
{
using (StreamReader sr = new StreamReader(_fileName))
{
string currentString;
bool result = false;
switch (isRegExp)
{
case true:
Regex regEx = new Regex(searchText);
while ((currentString = sr.ReadLine()) != null)
{
if (token.IsCancellationRequested)
{
break;
}
mrEvent.WaitOne(Timeout.Infinite);
if (regEx.IsMatch(currentString)) result = true;
break;
}
break;
case false:
while ((currentString = sr.ReadLine()) != null)
{
if (token.IsCancellationRequested)
{
break;
}
mrEvent.WaitOne(Timeout.Infinite);
if (currentString.Contains(searchText)) result = true;
break;
}
break;
}
return result;
}
}
void AddNode(string filepath)
{
string[] pathParts = filepath.Split('\\');
var currentNode = tv.Nodes;
int i = 0;
void recursionAddNode()
{
while (i < pathParts.Count())
{
if (currentNode.IndexOfKey(pathParts[i]) == -1)
{
currentNode.Add(pathParts[i], pathParts[i]);
var p = currentNode.IndexOfKey(pathParts[i]);
currentNode = currentNode[p].Nodes;
i++;
}
else
{
var p = currentNode.IndexOfKey(pathParts[i]);
currentNode = currentNode[p].Nodes;
i++;
recursionAddNode();
}
}
}
recursionAddNode();
}
fileList = GetFiles(CurrentSettings.StartFolder, CurrentSettings.FileName, CurrentSettings.IsFileNameRegExp);
if (fileList.Count > 0)
{
int i = 0;
d.Invoke(() => currentState.TotalFiles = fileList.Count);
foreach (string s in fileList)
{
if (token.IsCancellationRequested)
{
d.Invoke(() => tv.Nodes.Clear());
break;
}
mrEvent.WaitOne(Timeout.Infinite);
d.Invoke(() => currentState.FilesDone = ++i);
d.Invoke(() => currentState.CurrentFile = s);
if (CurrentSettings.SearchText != "")
{
if (IsTextBased(s, mrEvent, token) && CheckFileContent(CurrentSettings.IsSearchTextRegExp, CurrentSettings.SearchText, s))
{
d.Invoke(() => AddNode(s));
d.Invoke(() => currentState.MatchesFound++);
}
}
else
{
d.Invoke(() => currentState.MatchesFound++);
d.Invoke(() => AddNode(s));
}
}
}
else
{
d.Invoke(() => currentState.CurrentFile = "По заданным критериям файлов не найдено");
}
}
}
}
|
7bdeb85759a481534b16d8a8cc1a046214d6458a
|
C#
|
Vazul25/MVC-Gyakorlat
|
/BLL/MegrendelesManager.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BLL
{
public static class MegrendelesManager
{
public static List<Megrendeles> Search(string nev, DateTime fromDate, DateTime toDate)
{
using (CRMEntities oc = new CRMEntities())
{
return (from m in oc.Megrendeles.Include("Statusz").Include("Telephely.Vevo")
where m.Telephely.Vevo.Nev.Contains(nev)
&& m.Datum >= fromDate
&& m.Datum <= toDate
orderby m.Telephely.Vevo.Nev
select m).ToList();
}
}
public static List<MegrendelesTetel> ListTetel(int megrendelesId)
{
using (CRMEntities oc = new CRMEntities())
{
return (from m in oc.MegrendelesTetel.Include("Termek").Include("Statusz")
where m.MegrendelesID == megrendelesId
select m).ToList();
}
}
public static List<string> ListVevo(string nev)
{
using (CRMEntities oc = new CRMEntities())
{
return (from v in oc.Vevo
where v.Nev.Contains(nev)
select v.Nev).Distinct().ToList();
}
}
}
}
|
4e7b36d1b9a661f94554ed23f9f658f3ed466e35
|
C#
|
ayhan-karaman/BtkAcademyDesignPatterns
|
/Sigleton/DoubleCheckhedLockinGreetingManager.cs
| 3.40625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Singleton
{
public class DoubleCheckhedLockinGreetingManager : IGreetingService
{
private static DoubleCheckhedLockinGreetingManager _instance;
private static object _lockObject = new object();
private string _baseGreet = $"{new Random().Next(2, 100)} Greetings for";
private DoubleCheckhedLockinGreetingManager() { }
public static IGreetingService Instance
{
get
{
if (_instance is null)
{
lock (_lockObject)
{
if (_instance == null)
{
_instance = new DoubleCheckhedLockinGreetingManager();
}
}
}
return _instance;
}
}
public void Greet(string name)
{
Console.WriteLine($"{_baseGreet} {name}");
}
}
}
|
852cbc0c39028c55c0f8ae2207eb912a25b12ad3
|
C#
|
Serandrus/Touchless
|
/Touchless/Assets/Scripts/WinObject.cs
| 2.78125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// This class defines the condition to win the game.
/// </summary>
public class WinObject : MonoBehaviour
{
public Player player;
bool active;
//Searchs the player.
void Awake()
{
player = FindObjectOfType<Player>().GetComponent<Player>();
}
//Stop the game when the player collides with it.
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.GetComponent<Player>())
{
active = !active;
Time.timeScale = (active) ? 0 : 1f;
}
}
}
|
cf8f0ee7535fb1dfd8cb78591463bd96a561d7c4
|
C#
|
petegamble/justgoride.cc
|
/src/JustGoRide.cc.Web/Controllers/Api/ClubController.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JustGoRide.cc.Services;
using JustGoRide.cc.Services.Interfaces;
using JustGoRide.cc.Web.Models.Http;
using Microsoft.AspNetCore.Mvc;
namespace JustGoRide.cc.Web.Controllers.Api
{
public class ClubController : Controller
{
private IClubService _service;
public ClubController(IClubService service)
{
_service = service;
}
[HttpGet("api/clubs")]
public IActionResult Get()
{
var clubs = _service.GetClubs();
return Ok(clubs);
}
[HttpGet("api/club/{id}")]
public IActionResult Get(Guid id)
{
var club = _service.GetClub(id);
if (club == null)
{
var errorState = new ErrorState{ HttpStatusCode = 400, Message = "Club Not Found", Description = $"There are no clubs with the following ID: {id}"};
return BadRequest(errorState);
}
return Ok(club);
}
}
}
|
9a747b60ec7e054d537398d6f836f48fc5cfd864
|
C#
|
lucky-ly/CbsTest
|
/CbsTest.Web.Shared/City/CityHttpClient.cs
| 2.59375
| 3
|
using System.Net.Http.Json;
namespace CbsTest.Web.Shared.City
{
public class CityHttpClient
{
private readonly HttpClient _httpClient;
public CityHttpClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<IEnumerable<CityResponse>> GetAllAsync()
{
return (await _httpClient.GetFromJsonAsync<CityResponse[]>("api/city")) ?? Array.Empty<CityResponse>();
}
public async Task<CityResponse> CreateAsync(CreateCityRequest request)
{
var response = await _httpClient.PostAsJsonAsync($"api/city", request);
var returnValue = await response.Content.ReadFromJsonAsync<CityResponse>();
return returnValue;
}
public Task UpdateAsync(UpdateCityRequest request)
{
return _httpClient.PutAsJsonAsync($"api/city/{request.Id}", request);
}
public Task DeleteAsync(Guid id)
{
return _httpClient.DeleteAsync($"api/city/{id}");
}
}
}
|
ceeb5f0404e486c44feb45341e5ca2923e9c8f05
|
C#
|
jewer3330/thor
|
/client/Assets/ThorEditor/Runtime/GameObjectMap.cs
| 2.8125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class MapItem
{
public string name;
public GameObject go;
}
public class GameObjectMap : MonoBehaviour
{
public MapItem[] mapItems = new MapItem[] { };
private Dictionary<string, GameObject> mapsItemsDic;
private bool isInit = false;
void Init()
{
if (!isInit)
{
mapsItemsDic = new Dictionary<string, GameObject>();
foreach (var k in mapItems)
{
if (!mapsItemsDic.ContainsKey(k.name))
mapsItemsDic.Add(k.name, k.go);
else
Debug.LogError($"duplicate name {k.name}");
}
isInit = true;
}
}
public Object Get(string name)
{
if (mapsItemsDic == null)
{
Init();
}
GameObject ret;
if (!mapsItemsDic.TryGetValue(name,out ret))
{
return null;
}
return ret;
}
}
|
cf663c830b564ccfdb78a7884a888ca5bf051120
|
C#
|
sumgup/CleanCodeWorkshops
|
/Tracks/SOLID_Design_Principles/WeekThree-LSP-ISP-DIP/LSP/Problem/LSPDemo/Rectangle.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LSPDemo
{
// 1. Making a decision that square ISA Rectangle
public class Rectangle
{
private double width;
private double height;
public virtual double Width
{
get { return width; }
set { width = value; }
}
public virtual double Height
{
get { return height; }
set { height = value; }
}
}
// 2. Waste of inheritance becase square doesnt need both height and width variable
public class Square2 : Rectangle
{
// 3. Change in width results in height change
public new double Width
{
set
{
base.Width = value;
base.Height = value;
}
}
public new double Height
{
set
{
base.Height = value;
base.Width = value;
}
}
}
}
|
5a260aa8fa57ea18a3a02533de5d494a9d327360
|
C#
|
JRobinsonR/Sneak-Snack-Attack
|
/Assets/Scripts/Respawn.cs
| 2.734375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Respawn : MonoBehaviour
{
//Put this script onto whatever collider should kill the player.
[SerializeField]
private Transform Player; //When you apply this script, designate the "Player" to what the player character is.
[SerializeField]
private Transform respawnPoint; //Make an invisible/"empty" object and put it where you want the player to respawn.
//Then assign that object to "respawn point" when they ask.
void OnTriggerEnter(Collider other)
{
Player.transform.position = respawnPoint.transform.position;
}//Establised player and respawn point. Made it so when triggered player position will become whatever the respawn is designated as.
//Script given to me by Davon.
}
|
12fb8c4a668f6d96a6d08d1982a66349fe64e730
|
C#
|
jon101514/Dark-Patterns
|
/Assets/Scripts/VictoryFruit.cs
| 2.640625
| 3
|
/** Jonathan So, jds7523@rit.edu
* Victory Fruit is created when the player successfully completes a mission; they have randomized sprites and move on the screen like confetti.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class VictoryFruit : MonoBehaviour {
public Sprite[] fruits; // The different fruit sprites this can choose from.
private Rigidbody2D rb;
private Image img;
private void Awake() {
rb = GetComponent<Rigidbody2D>();
img = GetComponent<Image>();
img.sprite = fruits[Random.Range(0, fruits.Length - 1)];
}
private void Start() {
transform.position = new Vector2(Random.Range(-600f, 600f), Random.Range(400f, 600f));
rb.velocity = (new Vector2(Random.Range(-1f, 1f) * 512f, Random.Range(-1f, 1f) * 512f));
}
}
|
8166cb8923b7a0528007a831fc2110a7f53fb25b
|
C#
|
sam1169/xobnu-web-interface
|
/CorporateContacts.Domain/Concrete/EFCCNoteRepo.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xobnu.Domain.Abstract;
using Xobnu.Domain.Entities;
namespace Xobnu.Domain.Concrete
{
public class EFCCNoteRepo : ICCNoteRepo
{
private EFDBContextClient context = new EFDBContextClient();
public IQueryable<CCNote> CCNotes
{
get { return context.CCNotes; }
set { }
}
public CCNote SaveNote(CCNote noteObj)
{
if (noteObj.NotesID == 0)
{
context.CCNotes.Add(noteObj);
context.SaveChanges();
}
else
{
CCNote dbEntry = context.CCNotes.Find(noteObj.NotesID);
if (dbEntry != null)
{
dbEntry.value = noteObj.value;
context.SaveChanges();
}
}
return noteObj;
}
public void SetConnectionString(string connStr)
{
this.context.ConnStr = connStr;
}
}
}
|
cc85213df39242d433a901bfba021fb59ed0c380
|
C#
|
officialmoonbyte/GlobalSSH
|
/GlobalSSH/GlobalSSH/EntryPoint.cs
| 2.90625
| 3
|
using System.Threading;
using System;
using System.Net.Sockets;
using Renci.SshNet;
namespace IndieGoat.Net.SSH
{
public class GlobalSSH
{
#region Vars
public SshClient SSHClient;
#endregion
#region Startup
/// <summary>
/// Connects to the SSH server on startup
/// </summary>
public GlobalSSH(string SSHIP, int SSHPORT, string Username, string Password, bool AutoConnect = true)
{
if (AutoConnect) ConnectSSH(SSHIP, SSHPORT, Username, Password);
}
#endregion
#region Connect
/// <summary>
/// Connects to the SSH server
/// </summary>
public void ConnectSSH(string SSHIP, int SSHPORT, string Username, string Password)
{
if (!this.IsConnected())
{
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(SSHIP, SSHPORT, Username, Password);
SSHClient = new SshClient(connectionInfo);
SSHClient.Connect();
} else { Console.WriteLine("[GlobalSSH] SSH client is currently connected!"); }
}
/// <summary>
/// Gets the status of the SSH server to see if it is connected
/// </summary>
/// <returns></returns>
public bool IsConnected() { try { if (SSHClient != null) { return SSHClient.IsConnected; } else { return false; } } catch { return false; } }
#endregion
#region Port
#region Legacy
/// <summary>
/// Returns true if the port can be used.
/// </summary>
public bool CheckLocalPort(int PORT)
{
bool IsPortOpen = false;
using (TcpClient client = new TcpClient())
{
try
{
client.Connect("127.0.0.1", PORT);
IsPortOpen = false;
client.Close();
}
catch (Exception e)
{
IsPortOpen = true;
}
}
return IsPortOpen;
}
public bool TunnelLocalPort(string IP, string PORT, bool Async = false)
{
if (CheckLocalPort(int.Parse(PORT)) && this.IsConnected())
{
var forPort = new ForwardedPortLocal("127.0.0.1", uint.Parse(PORT), IP, uint.Parse(PORT));
SSHClient.AddForwardedPort(forPort);
forPort.Start();
return forPort.IsStarted;
}
else
{
Console.WriteLine("Port is currently in use! Ignoring incase port is open in diffrent ssh tunnel.");
if (Async) ThreadedPortLocal(IP, PORT);
return false;
}
}
#endregion
#region Threaded
private void ThreadedPortLocal(string IP, string PORT)
{
Console.WriteLine("Started a Threaded Local Port thread... Waiting for port to be avaialble.");
new Thread(new ThreadStart(() =>
{
while (true)
{
if (CheckLocalPort(int.Parse(PORT)) && this.IsConnected())
{
var forPort = new ForwardedPortLocal("127.0.0.1", uint.Parse(PORT), IP, uint.Parse(PORT));
SSHClient.AddForwardedPort(forPort);
forPort.Start();
}
Thread.Sleep(1000);
}
})).Start();
}
#endregion
#endregion
}
}
|
d00dd533091b84c2aaaf15ca212efe1367a6db87
|
C#
|
mynameiskate/TCP-file-exchange
|
/Form1.cs
| 2.703125
| 3
|
using System;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TCPClientApp
{
public partial class FileSender : Form
{
private User _user;
private string _savePath;
private Progress<string> _progress;
public FileSender()
{
InitializeComponent();
sendBtn.Enabled = false;
_progress = new Progress<string>(s => statusTextBox.Text += s);
}
private async void sendBtn_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
openFileDialog.AutoUpgradeEnabled = true;
string fileName = openFileDialog.FileName;
IPAddress receiverIP;
if (IPAddress.TryParse(IPBox.Text, out receiverIP))
{
int receiverPort;
if (int.TryParse(receiverPortTB.Text, out receiverPort))
{
await _user.Send(fileName, receiverIP, receiverPort, _progress);
}
else MessageBox.Show("Incorrect port of the receiver!");
}
else MessageBox.Show("Incorrect IP-address of the receiver!");
}
}
private async void startBtn_Click(object sender, EventArgs e)
{
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
_savePath = folderBrowserDialog.SelectedPath;
pathTB.Text = _savePath;
_user = new User();
portTextBox.Text = _user.GetPort().ToString();
sendBtn.Enabled = true;
userIPTextBox.Text = User.GetLocalIP().ToString();//IPAddress.Loopback.ToString();
await _user.Listen(_savePath, _progress);
}
}
private void FileSender_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
|
ef8e4538eb577ab435fbe741c35e3140d05bd478
|
C#
|
rodrigoborgesmachado/copiarServidor
|
/SubirServidor/Model/MD_Caminhosservidor.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
/// <summary>
/// [CaminhosServidor] Tabela da classe
/// </summary>
public class MD_Caminhosservidor
{
#region Atributos e Propriedades
/// <summary>
/// DAO que representa a classe
/// </summary>
public DAO.MD_Caminhosservidor DAO = null;
#endregion Atributos e Propriedades
#region Construtores
public MD_Caminhosservidor(int codigo)
{
Util.CL_Files.WriteOnTheLog("MD_Caminhosservidor()", Util.Global.TipoLog.DETALHADO);
this.DAO = new DAO.MD_Caminhosservidor( codigo);
}
#endregion Construtores
#region Métodos
/// <summary>
///
/// </summary>
/// <returns></returns>
public static List<Model.MD_Caminhosservidor> RetornaTodos()
{
Util.CL_Files.WriteOnTheLog("MD_Caminhosservidor().RetornaTodos()", Util.Global.TipoLog.DETALHADO);
string sentenca = new DAO.MD_Caminhosservidor().table.CreateCommandSQLTable();
List<Model.MD_Caminhosservidor> servidores = new List<MD_Caminhosservidor>();
DbDataReader reader = DataBase.Connection.Select(sentenca);
while (reader.Read())
{
servidores.Add(new MD_Caminhosservidor(int.Parse(reader["CODIGO"].ToString())));
}
reader.Close();
return servidores;
}
#endregion Métodos
}
}
|
24300df13b2cc063c91a75e12087ed2e0915292b
|
C#
|
pjjtah/Bonfire
|
/Assets/Scripts/Monologue.cs
| 2.65625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class Monologue : MonoBehaviour
{
public AudioSource audioS;
public Text text;
public string[] lines;
int counter = -1;
public void Start()
{
ReadNext();
}
public void ReadNext()
{
counter += 1;
text.text = "";
StopAllCoroutines();
StartCoroutine(FillText());
}
IEnumerator FillText()
{
yield return new WaitForSeconds(0.15f);
for (int i = 0; i < lines[counter].Length; i++)
{
text.text += lines[counter][i];
audioS.pitch = counter * -0.1f + Random.Range(0.5f, 1.5f);
audioS.Play();
yield return new WaitForSeconds(0.05f);
}
audioS.Stop();
yield return new WaitForSeconds(2f);
text.text = "";
}
}
|
8b1150bb949142537ab791ff7e617a74473c6ffa
|
C#
|
bubdm/guluwin
|
/SunnyChen.Common/Windows/Forms/PropertyEditor.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace SunnyChen.Common.Windows.Forms
{
/// <summary>
/// Provides the user interface of editing the properties of a given object.
/// </summary>
public partial class PropertyEditor : Form
{
/// <summary>
/// Default constructor that initailzes the components by default.
/// </summary>
public PropertyEditor()
{
InitializeComponent();
}
/// <summary>
/// Gets or sets the object on which the properties should be shown or modified.
/// </summary>
public object SelectedObject
{
get { return propertyGrid.SelectedObject; }
set { propertyGrid.SelectedObject = value; }
}
/// <summary>
/// Opens the property editor.
/// </summary>
/// <param name="_text">The description text that will be shown on the screen.</param>
/// <param name="_selected">The object on which the properties should be shown or modified.</param>
/// <returns>The dialog result of the property editor.</returns>
public static DialogResult ShowModal(string _text, object _selected)
{
PropertyEditor frmPropertyEditor = new PropertyEditor();
frmPropertyEditor.Text = _text;
frmPropertyEditor.SelectedObject = _selected;
return frmPropertyEditor.ShowDialog();
}
/// <summary>
/// Opens the property editor in a MDI container.
/// </summary>
/// <param name="_parent">The MDI parent window.</param>
/// <param name="_text">The description text that will be shown on the screen.</param>
/// <param name="_selected">The object on which the properties should be shown or modified.</param>
public static void ShowInMDI(Form _parent, string _text, object _selected)
{
PropertyEditor frmPropertyEditor = new PropertyEditor();
frmPropertyEditor.MdiParent = _parent;
frmPropertyEditor.Text = _text;
frmPropertyEditor.SelectedObject = _selected;
frmPropertyEditor.Show();
}
private void btnOK_Click(object sender, EventArgs e)
{
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}
|
038d9aee7a6e107ac2f4e3b78ba79d70ac5b6c7a
|
C#
|
emote-project/Scenario2
|
/Code/CaseBasedController/CaseBasedController/GameInfo/Player.cs
| 2.890625
| 3
|
using EmoteEnercitiesMessages;
namespace CaseBasedController.GameInfo
{
public class Player
{
public Gender Gender;
public string Name;
public EnercitiesRole Role;
public Player(string name, EnercitiesRole role, Gender gender = Gender.Male)
{
this.Name = name;
this.Role = role;
this.Gender = gender;
}
public bool IsAI()
{
return Role == EnercitiesRole.Mayor;
}
public override string ToString()
{
return string.Format("'{0}':{1}", Name, Role);
}
}
}
|
586992d5d9d263087fe77b9d05ddb9844aded1a8
|
C#
|
Fenriswolf-VieR/Statusbits
|
/bin/x86/Debug/AppX/BitDecryption.cs
| 2.984375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
namespace BitDecryption
{
public class BitDecryption
{
private string binary;
private string hex;
private string signedDec;
private string dec;
public enum BaseType
{
Decimal = 10,
Binary = 2,
Hex = 16,
SignedDecimal = 10
}
public enum Bitness
{
Bit64 = 64,
Bit32 = 32
}
private void ValidateValue(string value, BaseType baseType)
{
if (!Regex.IsMatch(value, "^[01]+$") && baseType == BaseType.Binary)
{
throw new Exception("The system ran into an error. The given input can't be parsed to a binary number. Check for invalid characters.");
}
else if (!Regex.IsMatch(value, "^[0-9A-Fa-f]+$") && baseType == BaseType.Hex)
{
throw new Exception("The system ran into an error. The given input can't be parsed to a hexadecimal number. Check for invalid characters.");
}
else if (!Regex.IsMatch(value, "^[-0-9]+$") && baseType == BaseType.Decimal)
{
throw new Exception("The system ran into an error. The given input can't be parsed to a decimal number. Check for invalid characters.");
}
}
//Calculate Values
public List<string> CalculateFromBase(string value, Bitness bit, BaseType baseType)
{
if (string.IsNullOrEmpty(value))
{
value = "0";
}
value = value.Replace(" ", "");
ValidateValue(value, baseType);
UInt64 unsignedDecValue;
//check if value is negative for conversion to uint64
try
{
if (Convert.ToInt64(value, (int)baseType) < 0)
{
Int64 temp = Convert.ToInt64(value, (int)baseType);
value = Convert.ToString(temp, 2);
baseType = BaseType.Binary;
}
}
catch { }
unsignedDecValue = Convert.ToUInt64(value, (int)baseType);
switch (bit)
{
case Bitness.Bit32:
dec = Convert.ToString(unsignedDecValue & 0xffffffff);
hex = Convert.ToString((long)unsignedDecValue & 0xffffffff, 16);
binary = Convert.ToString((long)unsignedDecValue & 0xffffffff, 2);
break;
case Bitness.Bit64:
dec = Convert.ToString(unsignedDecValue);
hex = Convert.ToString((long)unsignedDecValue, 16);
binary = Convert.ToString((long)unsignedDecValue, 2);
break;
}
return new List<string>() { dec, signedDec, hex, binary };
}
//Update all Values from selected Checkboxes
public List<string> CalculateFromCheckBoxes(IList<object> items, List<string> allStatusbits, Bitness bit)
{
IEnumerator item = items.GetEnumerator();
Int64 decimalNumber = 0;
int index;
string currentItem;
for (int i = 0; i < items.Count; i++)
{
item.MoveNext();
currentItem = item.Current.ToString();
index = (int)bit - 1 - allStatusbits.IndexOf(currentItem);
decimalNumber += (Int64)Math.Pow(2, index);
}
List<string> values = new List<string>();
values = CalculateFromBase(decimalNumber.ToString(), bit, BaseType.Decimal);
return FormatString(values);
}
public IList<object> CalculateActiveCheckboxes(List<string> allStatusBits, IList<object> items, string number, Bitness bit, BaseType baseType)
{
for (int i = items.Count - 1; i >= 0; i--)
{
items.RemoveAt(i);
}
if (string.IsNullOrEmpty(number))
{
number = "0";
}
//replace spaces from formatting
number = number.Replace(" ", "");
UInt64 unsignedDecValue;
unsignedDecValue = Convert.ToUInt64(number, (int)baseType);
int index = 0;
while (unsignedDecValue > 0)
{
if (unsignedDecValue % 2 == 1)
{
items.Add(allStatusBits[(int)bit - 1 - index]);
}
index++;
unsignedDecValue /= 2;
}
return items;
}
public int CalculateCOT(List<string> allStatusBits, IList<object> items)
{
List<string> cot = new List<string>();
allStatusBits.Reverse();
cot = allStatusBits.GetRange(32, 6);
allStatusBits.Reverse();
int value = 0;
for (int i = 0; i < cot.Count; i++)
{
if (items.Contains(cot[i]))
{
value += (int)Math.Pow(2, i);
}
}
return value;
}
private List<string> FormatString(List<string> values)
{
int spacesBinary = 0;
int spacesDecimal = 0;
int spacesHexadecimal = 0;
for (int i = 1; i < values[3].Length; i++)
{
//binary => space every 4 digits: 0000 0000 0000
if (i % 4 == 0 && i < binary.Length)
{
values[3] = values[3].Insert(values[3].Length - (i + spacesBinary), " ");
spacesBinary += 1;
}
//decimal => space every 3 digits: 100 000 000
if (i % 3 == 0 && i < dec.Length)
{
values[0] = values[0].Insert(values[0].Length - (i + spacesDecimal), " ");
spacesDecimal++;
}
//hex => space every 2 digits: FF FF FF
if (i % 2 == 0 && i < hex.Length)
{
values[2] = values[2].Insert(values[2].Length - (i + spacesHexadecimal), " ");
spacesHexadecimal++;
}
}
return values;
}
}
}
|
05dfe41a1a7eabd9746d13e76f8dd8e2409e7acc
|
C#
|
pmzeitler/mgtextwindows
|
/TextWindowSystemLib/EnumWindowInteractions.cs
| 2.609375
| 3
|
namespace net.PhoebeZeitler.TextWindowSystem
{
/// <summary>
/// A convenience class that standardizes all possible user inputs to an active window.
/// </summary>
public enum WindowInteractions
{
// Confirm/advance
OK,
// Cancel one
CANCEL,
// Close all windows
CANCEL_ALL,
// d-pad/arrow up
CURSOR_UP,
// d-pad/arrow down
CURSOR_DOWN,
// d-pad/arrow left
CURSOR_LEFT,
// d-pad/arrow right
CURSOR_RIGHT,
// advance a counter by ten
CURSOR_BIGUP,
// decrement a counter by ten
CURSOR_BIGDOWN,
// jump to the top of a menu/list
CURSOR_JUMPTOP,
// jump to the bottom of a menu/list
CURSOR_JUMPBOTTOM
}
/// <summary>
/// A convenience class that encapsulates reactions to user input on an active window.
/// </summary>
public class WindowResponse
{
private bool operationCompleted = false;
public bool OperationCompleted { get { return operationCompleted; } }
private bool keepWindowOpen = false;
public bool KeepWindowOpen { get { return keepWindowOpen; } }
private bool payloadExists = false;
public bool PayloadExists { get { return payloadExists; } }
private object payload = null;
public object Payload { get { return payload; } }
public WindowResponse(bool operationCompleted, bool keepWindowOpen, bool payloadExists, object payload)
{
this.operationCompleted = operationCompleted;
this.keepWindowOpen = keepWindowOpen;
this.payloadExists = payloadExists;
this.payload = payload;
}
}
}
|
cf63b52a1f5e116f9412197001b60ab64334612c
|
C#
|
jppoamaral/DecolaTech
|
/WatchList/WatchList/Classes/SeriesRepository.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using WatchList.Interfaces;
namespace WatchList
{
public class SeriesRepository : IRepository<Series>
{
private List<Series> seriesLst = new List<Series>();
public List<Series> List()
{
return seriesLst;
}
public Series returnById(int id)
{
return seriesLst[id];
}
public void Insert(Series obj)
{
seriesLst.Add(obj);
}
public void Watch(int id)
{
seriesLst[id].Watch();
}
public void Remove(int id)
{
seriesLst[id].Remove();
}
public void Update(int id, Series obj)
{
seriesLst[id] = obj;
}
public int nextId()
{
return seriesLst.Count;
}
}
}
|
206f5e0f548d51714853dc589b5f8df5afa88387
|
C#
|
KiDeokKim/coTest
|
/Programmers_4.cs
| 3.578125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Programmers_4
{
/***
* LV1
* Programmers
* 3개의 값 더해서 소수 구하기
* https://programmers.co.kr/learn/courses/30/lessons/12977
*/
public int solution(int[] nums)
{
int count = 0;
for (int i = 0; i < nums.Length; i++)
{
for (int j = i + 1; j < nums.Length; j++)
{
for (int k = j + 1; k < nums.Length; k++)
{
int dummy = nums[i] + nums[j] + nums[k];
bool notPrimeNum = false;
for (int l = 2; l < dummy; l++)
{
if (dummy % l == 0)
{
notPrimeNum = true;
break;
}
}
if (!notPrimeNum)
{
count += 1;
}
}
}
}
return count;
}
}
}
|
14019b541bef1f5d011397324c9edde504f15cfc
|
C#
|
MdSamreAlam/Project
|
/CalculatorTest.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Calculator.Test
{
public class CalculatorTest
{
Calculator calculator = new Calculator();
[Fact]
public void ShouldAddTwoNumber()
{
//Arrange
int number1 = 10;
int number2 = 15;
int expected = 25;
//Act
int actual = calculator.Add(number1, number2);
//Assert
Assert.Equal(expected, actual);
}
[Fact]
public void ShouldSubtract()
{
// Arranage
int number1 = 20;
int number2 = 15;
int expected = 5;
//Act
int actual = calculator.Subtract(number1, number2);
//Assert
Assert.Equal(expected, actual);
}
[Fact]
public void ShouldMulTwoNumber()
{
//Arrange
int number1 = 5;
int number2 = 4;
int expected = 20;
//Act
int actual= calculator.Mul(number1, number2);
//Assert
Assert.Equal(expected, actual);
}
}
}
|
e44cb8190374cbc8219b804bc6100507f7804f44
|
C#
|
Manojkumarupm/CustomerADO
|
/CustomerADO/DataLayer/XmlToDataset.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace DataLayer
{
public class XmlToDataSet
{
public DataSet ReadXmlToDataSet(string File)
{
try
{
DataSet dataSet = new DataSet();
dataSet.ReadXml(File, XmlReadMode.InferSchema);
return dataSet;
}
catch (Exception)
{
throw;
}
}
public string InsertIntoDatabase(DataSet ds)
{
try
{
string Result = null ;
foreach (DataTable dt in ds.Tables)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLDBConnectionString"].ToString());
// Creating Query for Table Creation
string Query = CreateTableQuery(dt);
con.Open();
// Deletion of Table if already Exist
SqlCommand cmd = new SqlCommand("IF OBJECT_ID('dbo." +
dt.TableName + "', 'U') IS NOT NULL DROP TABLE dbo." + dt.TableName + ";", con);
cmd.ExecuteNonQuery();
// Table Creation
cmd = new SqlCommand(Query, con);
int check = cmd.ExecuteNonQuery();
if (check != 0)
{
// Copy Data from DataTable to Sql Table
using (var bulkCopy = new SqlBulkCopy
(con.ConnectionString, SqlBulkCopyOptions.KeepIdentity))
{
// my DataTable column names match my SQL Column names,
// so I simply made this loop.
//However if your column names don't match,
//just pass in which datatable name matches the SQL column name in Column Mappings
foreach (DataColumn col in dt.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
bulkCopy.BulkCopyTimeout = 600;
bulkCopy.DestinationTableName = dt.TableName;
bulkCopy.WriteToServer(dt);
}
Result = "Created Successfully";
}
con.Close();
}
return Result;
}
catch (Exception)
{
throw;
}
}
// Getting Query for Table Creation
public string CreateTableQuery(DataTable table)
{
string sqlsc = "CREATE TABLE " + table.TableName + "(";
for (int i = 0; i < table.Columns.Count; i++)
{
sqlsc += "[" + table.Columns[i].ColumnName + "]";
string columnType = table.Columns[i].DataType.ToString();
switch (columnType)
{
case "System.Int32":
sqlsc += " int ";
break;
case "System.Int64":
sqlsc += " bigint ";
break;
case "System.Int16":
sqlsc += " smallint";
break;
case "System.Byte":
sqlsc += " tinyint";
break;
case "System.Decimal":
sqlsc += " decimal ";
break;
case "System.DateTime":
sqlsc += " datetime ";
break;
case "System.String":
default:
sqlsc += string.Format(" nvarchar({0}) ",
table.Columns[i].MaxLength == -1 ? "max" :
table.Columns[i].MaxLength.ToString());
break;
}
if (table.Columns[i].AutoIncrement)
sqlsc += " IDENTITY(" + table.Columns[i].AutoIncrementSeed.ToString() +
"," + table.Columns[i].AutoIncrementStep.ToString() + ") ";
if (!table.Columns[i].AllowDBNull)
sqlsc += " NOT NULL ";
sqlsc += ",";
}
return sqlsc.Substring(0, sqlsc.Length - 1) + "\n)";
}
}
}
|
c0b895f636e5466ba330e95fcf330703e6004e14
|
C#
|
lukusbeaur/Generic_Lambda
|
/GenericLINQ_Lamnda/Examples/PartialMethods.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenericLINQ_Lamnda.Examples
{
partial class PartialMethods//(1)
{
//declaration = ([modifier] dataType variable Name);
//This version of will act as if the partial method doesn't exist.
partial void MyWidgetStart(int count);//method definition
partial void MywidgetEnd(int count);//method definition
partial void MywidgetEnd(int count)//method definition
{
Console.WriteLine(count);//methods implementation
}
partial void MyWidgetStart(int count)//method definition
{
Console.WriteLine(count);//methods implementation
}
public PartialMethods()//class constructor
{
int count = 0;
MyWidgetStart(++count);
Console.WriteLine("Constructor");
MywidgetEnd(++count);
}//output: count = 0
//========================================================//
//Partial methods are methods where the definition of the method
//is specified in the declration of the partial CLASSS(1) but
//the implementation for the method is not provided in that same
//declaration of the partial class. In fact there doesn't have to
//have any implementation anywhere, and the compiler will not
//emit any IL code. Acting as it was never written.
//========================================================//
//===============
//This is mainly for writing large programs in teams. Creating
//this partial method to easily call at a later time (IF YOU WANT)
//if you don't want the compiler never wastes Any Memory on IL code.
//===============
}
}
|
6538ff539f9381a12b0da7d7df4b204ec6c0df13
|
C#
|
asimplestd/ComponentIoC
|
/Runtime/BehaviourExtensions/ObservableBehaviour.cs
| 2.609375
| 3
|
using System.Threading.Tasks;
using System.Threading;
using UnityEngine;
public abstract class ObservableBehaviour : ObservableBehaviour<bool>
{
protected void Complete()
{
Complete(true);
}
}
public abstract class ObservableBehaviour<TResult> : MonoBehaviour
{
private TaskCompletionSource<TResult> _observationCs;
private CancellationTokenSource _completeTs = new CancellationTokenSource();
public bool Completed { get; private set; }
protected CancellationToken CompleteToken => _completeTs.Token;
private TResult _result;
public Task<TResult> Observe()
{
if (Completed)
{
return Task.FromResult(_result);
}
if (_observationCs == null)
{
_observationCs = new TaskCompletionSource<TResult>();
}
return _observationCs.Task;
}
public void WithCancellation(CancellationToken cancellationToken)
{
cancellationToken.Register(OnCancellationRequested);
}
private void Start()
{
OnStart();
}
protected virtual void OnStart()
{ }
protected virtual void OnDestroy()
{
if (!Completed)
{
Complete(default);
}
}
private void OnCancellationRequested()
{
if (!Completed)
{
Complete(default);
}
}
protected void Complete(TResult result)
{
if (Completed)
{
return;
}
Completed = true;
_completeTs.Cancel();
Destroy(gameObject);
if (_observationCs != null)
{
_observationCs.TrySetResult(result);
}
_completeTs.Dispose();
}
}
|
fead4debdb109e523a3540bb069121a945e10bb0
|
C#
|
AIBrain/UnitsOfMeasure
|
/UnitsOfMeasure Tests/LengthTest.cs
| 2.875
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UnitsOfMeasure;
using UnitsOfMeasure.Length;
using UnitsOfMeasure.Length.Imperial;
using UnitsOfMeasure.Length.Metric;
namespace UnitsOfMeasure_Tests {
[TestClass]
public class LengthTest {
[TestMethod]
public void AddInchesToFeet() {
var f = new Feet {
Value = 3.5
};
var i = new Inches {
Value = 6
};
f = f.Add( ( Feet )i );
Assert.AreEqual( 4, f.Value );
}
[TestMethod]
public void Area1() {
var x = new Feet {
Value = 5
};
var y = new Feet {
Value = 7
};
var a = x.Multiply( y );
Assert.AreEqual( 35, a.Value );
}
[TestMethod]
public void FeetToMeters() {
var feet = new Feet {
Value = 35
};
Meters meter = feet;
Assert.AreEqual( 10.668, meter.Value, 1e-10 );
}
[TestMethod]
public void FeetToMiles() {
var f = new Feet {
Value = 7920
};
Miles m = f;
Assert.AreEqual( 1.5, m.Value );
}
[TestMethod]
public void InchesToFeet() {
var i = new Inches {
Value = 24
};
Feet f = i;
Assert.AreEqual( 2, f.Value );
}
[TestMethod]
public void MilesToInches() {
var m = new Miles {
Value = 3.5
};
Inches i = m;
Assert.AreEqual( 221760, i.Value );
}
[TestMethod]
public void Volume1() {
var x = new Feet {
Value = 3
};
var y = new Feet {
Value = 5
};
var z = new Feet {
Value = 7
};
var v = x.Multiply( y ).Multiply( z );
Assert.AreEqual( 105, v.Value );
}
}
}
|
3f34468c6702b7b12199b89db7bf0bc1bc60d749
|
C#
|
donnieholstrom/Cooking-Master
|
/Assets/Scripts/PlayerInteraction.cs
| 2.578125
| 3
|
using UnityEngine;
public class PlayerInteraction : MonoBehaviour
{
public PlayerMovement.PlayerNumber playerNumber;
private string interactInput;
private bool hovering;
public enum Interactable
{
Nothing,
Veggies,
Greens,
Citrus,
Melons,
Pasta,
Rice,
CuttingBoard1,
CuttingBoard2,
PickupZone1,
PickupZone2,
DeliveryZone1,
DeliveryZone2,
DeliveryZone3,
DeliveryZone4,
Trashcan
}
private Interactable hoveringOn = Interactable.Nothing;
public Customer.Ingredient heldIngredient1 = Customer.Ingredient.None;
public Customer.Ingredient heldIngredient2 = Customer.Ingredient.None;
public SpriteRenderer holding1;
public SpriteRenderer holding2;
public Sprite leaves;
public Sprite slice;
public Sprite bowl;
public Color veggiesColor;
public Color greensColor;
public Color citrusColor;
public Color melonsColor;
public Color pastaColor;
public Color riceColor;
public Color plateColor;
public CuttingBoard cuttingBoard;
public bool holdingMeal = false;
public SpriteRenderer mealSprite1;
public SpriteRenderer mealSprite2;
public SpriteRenderer mealSprite3;
public SpriteRenderer mealPlate;
private Customer.Ingredient mealIngredient1;
private Customer.Ingredient mealIngredient2;
private Customer.Ingredient mealIngredient3;
private CustomerManager customerManager;
private GameManager gameManager;
// grabs the customer manager and the game manager
private void Awake()
{
customerManager = GameObject.FindGameObjectWithTag("Managers").GetComponent<CustomerManager>();
gameManager = GameObject.FindGameObjectWithTag("Managers").GetComponent<GameManager>();
}
// sets the proper input based on player number
private void Start()
{
switch (playerNumber)
{
case (PlayerMovement.PlayerNumber.PlayerOne):
interactInput = "Interact1";
break;
case (PlayerMovement.PlayerNumber.PlayerTwo):
interactInput = "Interact2";
break;
}
}
// figures out where the player is standing so interacting works with the proper object
private void OnTriggerEnter2D(Collider2D collision)
{
if (hovering)
{
return;
}
switch (collision.tag)
{
case "Veggies":
hoveringOn = Interactable.Veggies;
break;
case "Greens":
hoveringOn = Interactable.Greens;
break;
case "Citrus":
hoveringOn = Interactable.Citrus;
break;
case "Melons":
hoveringOn = Interactable.Melons;
break;
case "Pasta":
hoveringOn = Interactable.Pasta;
break;
case "Rice":
hoveringOn = Interactable.Rice;
break;
case "CuttingBoard1":
hoveringOn = Interactable.CuttingBoard1;
break;
case "CuttingBoard2":
hoveringOn = Interactable.CuttingBoard2;
break;
case "PickupZone1":
hoveringOn = Interactable.PickupZone1;
break;
case "PickupZone2":
hoveringOn = Interactable.PickupZone2;
break;
case "DeliveryZone1":
hoveringOn = Interactable.DeliveryZone1;
break;
case "DeliveryZone2":
hoveringOn = Interactable.DeliveryZone2;
break;
case "DeliveryZone3":
hoveringOn = Interactable.DeliveryZone3;
break;
case "DeliveryZone4":
hoveringOn = Interactable.DeliveryZone4;
break;
case "Trashcan":
hoveringOn = Interactable.Trashcan;
break;
}
hovering = true;
}
// makes sure it grabs the second interactable if it slides between two
private void OnTriggerStay2D(Collider2D collision)
{
if (hoveringOn == Interactable.Nothing)
{
switch (collision.tag)
{
case "Veggies":
hoveringOn = Interactable.Veggies;
break;
case "Greens":
hoveringOn = Interactable.Greens;
break;
case "Citrus":
hoveringOn = Interactable.Citrus;
break;
case "Melons":
hoveringOn = Interactable.Melons;
break;
case "Pasta":
hoveringOn = Interactable.Pasta;
break;
case "Rice":
hoveringOn = Interactable.Rice;
break;
case "CuttingBoard1":
hoveringOn = Interactable.CuttingBoard1;
break;
case "CuttingBoard2":
hoveringOn = Interactable.CuttingBoard2;
break;
case "PickupZone1":
hoveringOn = Interactable.PickupZone1;
break;
case "PickupZone2":
hoveringOn = Interactable.PickupZone2;
break;
case "DeliveryZone1":
hoveringOn = Interactable.DeliveryZone1;
break;
case "DeliveryZone2":
hoveringOn = Interactable.DeliveryZone2;
break;
case "DeliveryZone3":
hoveringOn = Interactable.DeliveryZone3;
break;
case "DeliveryZone4":
hoveringOn = Interactable.DeliveryZone4;
break;
case "Trashcan":
hoveringOn = Interactable.Trashcan;
break;
default:
break;
}
hovering = true;
}
}
// clears hoveringOn when player leaves that specific area
private void OnTriggerExit2D(Collider2D collision)
{
if (hovering = true && hoveringOn.ToString().Contains(collision.tag.ToString()))
{
hoveringOn = Interactable.Nothing;
hovering = false;
}
}
// gets input from player
private void Update()
{
if (Input.GetButtonDown(interactInput) && hovering)
{
Interact(hoveringOn);
}
}
// handles all interactions
private void Interact(Interactable interacting)
{
switch (interacting)
{
case Interactable.Veggies:
Pickup(Customer.Ingredient.Veggies);
break;
case Interactable.Greens:
Pickup(Customer.Ingredient.Greens);
break;
case Interactable.Citrus:
Pickup(Customer.Ingredient.Citrus);
break;
case Interactable.Melons:
Pickup(Customer.Ingredient.Melons);
break;
case Interactable.Pasta:
Pickup(Customer.Ingredient.Pasta);
break;
case Interactable.Rice:
Pickup(Customer.Ingredient.Rice);
break;
case Interactable.CuttingBoard1:
if (playerNumber == PlayerMovement.PlayerNumber.PlayerOne)
{
if (!cuttingBoard.boardEmpty && cuttingBoard.numberChopped < 3)
{
cuttingBoard.Interact(Customer.Ingredient.None);
}
else if (heldIngredient1 != Customer.Ingredient.None)
{
cuttingBoard.Interact(heldIngredient1);
heldIngredient1 = Customer.Ingredient.None;
holding1.color = Color.clear;
}
else if (heldIngredient2 != Customer.Ingredient.None)
{
cuttingBoard.Interact(heldIngredient2);
heldIngredient2 = Customer.Ingredient.None;
holding2.color = Color.clear;
}
else
{
cuttingBoard.Interact(Customer.Ingredient.None);
}
}
break;
case Interactable.CuttingBoard2:
if (playerNumber == PlayerMovement.PlayerNumber.PlayerTwo)
{
if (!cuttingBoard.boardEmpty && cuttingBoard.numberChopped < 3)
{
cuttingBoard.Interact(Customer.Ingredient.None);
}
else if (heldIngredient1 != Customer.Ingredient.None)
{
if (cuttingBoard.Interact(heldIngredient1))
{
heldIngredient1 = Customer.Ingredient.None;
holding1.color = Color.clear;
}
}
else if (heldIngredient2 != Customer.Ingredient.None)
{
if (cuttingBoard.Interact(heldIngredient2))
{
heldIngredient2 = Customer.Ingredient.None;
holding2.color = Color.clear;
}
}
else
{
cuttingBoard.Interact(Customer.Ingredient.None);
}
}
break;
case Interactable.PickupZone1:
if (playerNumber == PlayerMovement.PlayerNumber.PlayerOne)
{
if (!holdingMeal)
{
cuttingBoard.TakeMeal();
}
}
break;
case Interactable.PickupZone2:
if (playerNumber == PlayerMovement.PlayerNumber.PlayerTwo)
{
if (!holdingMeal)
{
cuttingBoard.TakeMeal();
}
}
break;
case Interactable.DeliveryZone1:
if (!holdingMeal)
{
break;
}
customerManager.DeliverMeal(playerNumber, 1, mealIngredient1, mealIngredient2, mealIngredient3);
holdingMeal = false;
mealPlate.color = Color.clear;
mealSprite1.color = Color.clear;
mealIngredient1 = Customer.Ingredient.None;
mealSprite2.color = Color.clear;
mealIngredient2 = Customer.Ingredient.None;
mealSprite3.color = Color.clear;
mealIngredient3 = Customer.Ingredient.None;
break;
case Interactable.DeliveryZone2:
if (!holdingMeal)
{
break;
}
customerManager.DeliverMeal(playerNumber, 2, mealIngredient1, mealIngredient2, mealIngredient3);
holdingMeal = false;
mealPlate.color = Color.clear;
mealSprite1.color = Color.clear;
mealIngredient1 = Customer.Ingredient.None;
mealSprite2.color = Color.clear;
mealIngredient2 = Customer.Ingredient.None;
mealSprite3.color = Color.clear;
mealIngredient3 = Customer.Ingredient.None;
break;
case Interactable.DeliveryZone3:
if (!holdingMeal)
{
break;
}
customerManager.DeliverMeal(playerNumber, 3, mealIngredient1, mealIngredient2, mealIngredient3);
holdingMeal = false;
mealPlate.color = Color.clear;
mealSprite1.color = Color.clear;
mealIngredient1 = Customer.Ingredient.None;
mealSprite2.color = Color.clear;
mealIngredient2 = Customer.Ingredient.None;
mealSprite3.color = Color.clear;
mealIngredient3 = Customer.Ingredient.None;
break;
case Interactable.DeliveryZone4:
if (!holdingMeal)
{
break;
}
customerManager.DeliverMeal(playerNumber, 4, mealIngredient1, mealIngredient2, mealIngredient3);
holdingMeal = false;
mealPlate.color = Color.clear;
mealSprite1.color = Color.clear;
mealIngredient1 = Customer.Ingredient.None;
mealSprite2.color = Color.clear;
mealIngredient2 = Customer.Ingredient.None;
mealSprite3.color = Color.clear;
mealIngredient3 = Customer.Ingredient.None;
break;
case Interactable.Trashcan:
Trash();
break;
case Interactable.Nothing:
break;
}
}
// handles which slot the ingredients go to
private void Pickup(Customer.Ingredient ingredient)
{
if (heldIngredient1 == Customer.Ingredient.None)
{
heldIngredient1 = ingredient;
holding1.sprite = GetIngredientSprite(ingredient);
holding1.color = GetIngredientColor(ingredient);
return;
}
else if (heldIngredient2 == Customer.Ingredient.None)
{
heldIngredient2 = ingredient;
holding2.sprite = GetIngredientSprite(ingredient);
holding2.color = GetIngredientColor(ingredient);
return;
}
else
{
return;
}
}
// handles interacting with the trashcan
private void Trash()
{
if (holdingMeal)
{
gameManager.AddScore(playerNumber, -250);
holdingMeal = false;
mealPlate.color = Color.clear;
mealSprite1.color = Color.clear;
mealIngredient1 = Customer.Ingredient.None;
mealSprite2.color = Color.clear;
mealIngredient2 = Customer.Ingredient.None;
mealSprite3.color = Color.clear;
mealIngredient3 = Customer.Ingredient.None;
}
if (heldIngredient1 != Customer.Ingredient.None)
{
heldIngredient1 = Customer.Ingredient.None;
holding1.color = Color.clear;
return;
}
else if (heldIngredient2 != Customer.Ingredient.None)
{
heldIngredient2 = Customer.Ingredient.None;
holding2.color = Color.clear;
return;
}
}
// takes the meal from the cutting board
public void TakeMeal(Customer.Ingredient boardMealIngredient1, Customer.Ingredient boardMealIngredient2, Customer.Ingredient boardMealIngredient3)
{
holdingMeal = true;
mealPlate.color = plateColor;
mealSprite1.sprite = GetIngredientSprite(boardMealIngredient1);
mealSprite1.color = GetIngredientColor(boardMealIngredient1);
mealIngredient1 = boardMealIngredient1;
mealSprite2.sprite = GetIngredientSprite(boardMealIngredient2);
mealSprite2.color = GetIngredientColor(boardMealIngredient2);
mealIngredient2 = boardMealIngredient2;
mealSprite3.sprite = GetIngredientSprite(boardMealIngredient3);
mealSprite3.color = GetIngredientColor(boardMealIngredient3);
mealIngredient3 = boardMealIngredient3;
}
#region Ingredient Image references
// returns the sprite that corresponds to the passed ingredient
public Sprite GetIngredientSprite(Customer.Ingredient ingredient)
{
switch (ingredient)
{
case Customer.Ingredient.None:
return leaves;
case Customer.Ingredient.Veggies:
return leaves;
case Customer.Ingredient.Greens:
return leaves;
case Customer.Ingredient.Citrus:
return slice;
case Customer.Ingredient.Melons:
return slice;
case Customer.Ingredient.Pasta:
return bowl;
case Customer.Ingredient.Rice:
return bowl;
}
return leaves;
}
// returns the color that corresponds to the passed ingredient
public Color GetIngredientColor(Customer.Ingredient ingredient)
{
switch (ingredient)
{
case Customer.Ingredient.None:
return Color.clear;
case Customer.Ingredient.Veggies:
return veggiesColor;
case Customer.Ingredient.Greens:
return greensColor;
case Customer.Ingredient.Citrus:
return citrusColor;
case Customer.Ingredient.Melons:
return melonsColor;
case Customer.Ingredient.Pasta:
return pastaColor;
case Customer.Ingredient.Rice:
return riceColor;
}
return Color.clear;
}
#endregion
}
|
f7acba6906dfd6988e8135f43b5b81e6d471f3ea
|
C#
|
mnasif786/PortalAPIs
|
/PBS.Core/CQRS/Command/CommandDispatcher.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StructureMap;
namespace PBS.Core.CQRS.Command
{
public class CommandDispatcher : ICommandDispatcher
{
private readonly IContainer _container;
public CommandDispatcher(IContainer container)
{
_container = container;
}
public void Dispatch<TParameter>(TParameter command) where TParameter : ICommand
{
if (command == null)
{
throw new ArgumentNullException("command");
}
dynamic handler = _container.GetInstance( typeof(ICommandHandler<TParameter>) );
handler.Execute((dynamic) command);
}
public TResult Dispatch<TParameter, TResult>(TParameter command) where TParameter : ICommand
{
if (command == null)
{
throw new ArgumentNullException("command");
}
dynamic handler = _container.GetInstance(typeof(ICommandHandler<TParameter, TResult>));
return handler.Execute((dynamic)command);
}
}
}
|
53fa8a4a0ba343a62393204fcd4d0d93f0cc3197
|
C#
|
rlsadiz/SOS
|
/Assets/Scripts/SnapToGrid.cs
| 2.546875
| 3
|
using UnityEngine;
using System.Collections;
// SOS!
// Created by: Ronald Louie R. Sadiz
// Copyright 2015
// All Rights Reserved.
public class SnapToGrid : MonoBehaviour {
public float xDimension;
public float yDimension;
public float zDimension;
void Update()
{
//gets the current position of the object
Vector3 newPosition = transform.position;
//translates the position to its nearest grid value
newPosition.x = Mathf.Round(newPosition.x / xDimension) * xDimension;
newPosition.y = Mathf.Round(newPosition.y / yDimension) * yDimension;
newPosition.z = Mathf.Round(newPosition.z / zDimension) * zDimension;
//transforms the objects position
transform.position = newPosition;
}
}
|
e6d665643e551a5b2674b6bf7873056bd9e87c44
|
C#
|
guildfau/Bermuda-Triangle
|
/Bermuda-Triangle/Assets/Scripts/Entity.cs
| 2.640625
| 3
|
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
/// <summary>
/// Created by Daniel Resio.
/// Class that is the base of all entities in the game.
/// Some animations already implemented in code
/// needs rigidbody
/// TODO: collider info
/// </summary>
public abstract class Entity : MonoBehaviour {
private List<Collider2D> collisions = new List<Collider2D>();
private Animator anim;
private bool canMove = true;
#region public variables
public GameObject bullet;
public GameObject meleeUp;
public GameObject meleeDown;
public GameObject meleeLeft;
public GameObject meleeRight;
#endregion
/// <summary>
/// returns what the movement vector should be
/// </summary>
/// <returns></returns>
public abstract Vector2 getMovement();
/// <summary>
/// Handles all of the melee information
/// </summary>
public abstract void melee();
/// <summary>
/// method that checks for parts needed and if absent, will return errors
/// </summary>
public abstract void checkForParts();
/// <summary>
/// method that allows for managing of animation and other items at start
/// </summary>
public abstract void atStart();
/// <summary>
/// uses the collisions object to handle information about collisions
/// </summary>
public abstract void handleCollisions();
/// <summary>
/// checks for parts to avoid errors. Other things can go here too if need be
/// </summary>
public void Start()
{
checkForParts();
atStart();
Rigidbody2D rigidbody = (Rigidbody2D)gameObject.GetComponent("Rigidbody2D");
rigidbody.freezeRotation = true;
}
/// <summary>
/// things to do at update
/// </summary>
public virtual void FixedUpdate()
{
//code that moves entity
if (isMoving() && canMove)
gameObject.transform.Translate(getMovement());
handleCollisions();
handleAnimation();
}
/// <summary>
/// swings at target
/// </summary>
/// <param name="target"></param>
public void meleeToTarget(Vector2 target)
{
Vector2 lOC = gameObject.transform.position;
float difx = -(target.x - lOC.x);
float dify = -(target.y - lOC.y);
//uses math functions to find rotation angle needed
float angle = Mathf.Atan(dify / difx);
angle = angle * Mathf.Rad2Deg;
//complicated logic to make angle in correct quadrant
#region quadrant solver (angle now correct)
if (difx < 0 && dify < 0)
{
//Debug.Log("Q1");
angle -= 90;
}
else if (difx < 0 && dify > 0)
{
//Debug.Log("Q4");
angle -= 90;
}
else if (difx > 0 && dify < 0)
{
//Debug.Log("Q2");
angle += 90;
}
else if (difx > 0 && dify > 0)
{
//Debug.Log("Q3");
angle += 90;
}
#endregion
#region Handles attack directions
if (angle < -45 && angle > -135)
{
StartCoroutine(AttackRight());
}
else if (angle > -45 && angle < 45)
{
StartCoroutine(AttackUp());
}
else if(angle > 45 && angle < 135)
{
StartCoroutine(AttackLeft());
}
else
{
StartCoroutine(AttackDown());
}
#endregion
}
/// <summary>
/// Handels the firing of the projectile
/// </summary>
public void fire()
{
Quaternion angle;
//finds mouse position
Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 charPos = gameObject.transform.position;
Vector2 direction = -(charPos - pos);
if (Mathf.Abs(direction.x) > Mathf.Abs(direction.y))
{
if (direction.x < 0)
{
angle = Quaternion.Euler(0,0,90);
}
else
{
angle = Quaternion.Euler(0, 0, -90);
}
}
else
{
if (direction.y < 0)
{
angle = Quaternion.Euler(0, 0, 180);
}
else
{
angle = Quaternion.Euler(0, 0, 0);
}
}
Instantiate(bullet, gameObject.transform.position, angle);
}
#region boolean questions
/// <summary>
/// returns true if the player should be moving
/// </summary>
/// <returns></returns>
public bool isMoving()
{
if (getMovement().x != 0 || getMovement().y != 0 )
return true;
return false;
}
/// <summary>
/// returns if entity can attack
/// </summary>
/// <returns></returns>
public bool canAttack()
{
if (Player_Stats.stats.cooldown <= 0)
return true;
return false;
}
#endregion
#region adds and removes collisions from list
/// <summary>
/// adds collisions to the list
/// </summary>
/// <param name="c"></param>
void OnTriggerEnter2D(Collider2D c)
{
collisions.Add(c);
}
/// <summary>
/// removes collisions from the list
/// </summary>
/// <param name="c"></param>
void OnTriggerExit2D(Collider2D c)
{
string tag = c.gameObject.tag;
for (int i = 0; i < collisions.Count; i++)
if (collisions[i].gameObject.tag == tag)
collisions.RemoveAt(i);
}
#endregion
#region attack systems
private IEnumerator AttackRight()
{
canMove = false;
getAnimator().SetBool("MeleeRight", true);
yield return new WaitForSeconds(.8f);
getAnimator().SetBool("MeleeRight", false);
canMove = true;
}
private IEnumerator AttackUp()
{
canMove = false;
getAnimator().SetBool("MeleeBack", true);
yield return new WaitForSeconds(.8f);
getAnimator().SetBool("MeleeBack", false);
canMove = true;
}
private IEnumerator AttackLeft()
{
canMove = false;
getAnimator().SetBool("MeleeLeft", true);
yield return new WaitForSeconds(.8f);
getAnimator().SetBool("MeleeLeft", false);
canMove = true;
}
private IEnumerator AttackDown()
{
canMove = false;
getAnimator().SetBool("MeleeFront", true);
yield return new WaitForSeconds(.8f);
getAnimator().SetBool("MeleeFront", false);
canMove = true;
}
#endregion
/// <summary>
/// Checks if object is colliding with object with tag
/// </summary>
/// <param name="tag name"></param>
/// <returns></returns>
public Collider2D isColliding(string c)
{
for (int i = 0; i < collisions.Count; i++)
{
if (collisions[i].gameObject.tag == c)
return collisions[i];
}
return null;
}
/// <summary>
/// this is to handle all of the animation switches
/// </summary>
private void handleAnimation()
{
if (isMoving() && canMove)
{
Vector2 temp = getMovement();
getAnimator().SetBool("Movement", true);
#region sets variables for directions
if (Mathf.Abs(temp.x) > Mathf.Abs(temp.y))
{
if (temp.x > 0 && getAnimator().GetInteger("Direction") != 3)
{
//3 is right
getAnimator().SetInteger("Direction", 3);
}
else if (temp.x < 0 && getAnimator().GetInteger("Direction") != 2)
{
//2 is left
getAnimator().SetInteger("Direction", 2);
}
}
else
{
if (temp.y > 0 && getAnimator().GetInteger("Direction") != 1)
{
//1 is up
getAnimator().SetInteger("Direction", 1);
}
else if (temp.y < 0 && getAnimator().GetInteger("Direction") != 0)
{
//0 is down
getAnimator().SetInteger("Direction", 0);
}
}
#endregion
}
else
{
getAnimator().SetBool("Movement", false);
}
}
#region getter and setter
public void setAnimator(Animator newAnimator)
{
anim = newAnimator;
}
public Animator getAnimator()
{
return anim;
}
#endregion
}
|
c43c6c5e7099a883ab84e66ed6cee01084d775c9
|
C#
|
Codeology/BoidsSimulation
|
/Assets/Flock.cs
| 2.6875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Flock : MonoBehaviour
{
public FlockAgent agentPrefab;
List<FlockAgent> agents = new List<FlockAgent>();
public FlockBehavior behavior;
// Instantiation for Flock
[Range(10, 500)]
public int startingCount = 250;
const float agentDensity = 0.08f;
// Behavior variables
[Range(1f, 100f)]
public float driveFactor = 10f;
[Range(1f, 100f)]
public float maximumSpeed = 5f;
// Neighbor variables
[Range(1f, 10f)]
public float neighborRadius = 5f;
[Range(0f, 1f)]
public float avoidanceRadiusMultiplier = .5f;
// Utility based on maxSpeed and radius - avoiding math
float squareMaxSpeed;
float squareNeighborRadius;
float squareAvoidanceRadius;
public float SquareAvoidanceRadius { get { return squareAvoidanceRadius; } }
// Start is called before the first frame update
void Start()
{
squareMaxSpeed = maximumSpeed * maximumSpeed;
squareNeighborRadius = neighborRadius * neighborRadius;
squareAvoidanceRadius = squareNeighborRadius * avoidanceRadiusMultiplier * avoidanceRadiusMultiplier;
for (int i = 0; i < startingCount; i ++)
{
FlockAgent newAgent = Instantiate(
agentPrefab,
Random.insideUnitCircle * startingCount * agentDensity,
Quaternion.Euler(Vector3.forward * Random.Range(0f, 360f)),
this.transform);
newAgent.name = "Agent: " + i;
agents.Add(newAgent);
}
}
// Update is called once per frame
void Update()
{
// Going through and getting neighbors
foreach (FlockAgent agent in agents)
{
List<Transform> context = GetNearbyObjects(agent);
// Coolness!
agent.GetComponentInChildren<SpriteRenderer>().color = Color.Lerp(Color.white, Color.red, context.Count / 6f);
Vector2 move = behavior.CalculateMove(agent, context, this);
// Make speed more speedy!
move *= driveFactor;
if (move.sqrMagnitude > squareMaxSpeed)
{
// If we're going any faster than we want, we normalize and bring it back to the max speed.
move = move.normalized * maximumSpeed;
}
// Make our agents move.
agent.Move(move);
}
}
List<Transform> GetNearbyObjects(FlockAgent agent)
{
List<Transform> nearby = new List<Transform>();
Collider2D[] nearbyColliders = Physics2D.OverlapCircleAll(agent.transform.position, neighborRadius);
foreach (Collider2D c in nearbyColliders)
{
if (c != agent.AgentCollider)
{
nearby.Add(c.transform);
}
}
return nearby;
}
}
|
91065b725dd560442736cac80f1838f77c235912
|
C#
|
ERNICommunity/View4Logs
|
/src/View4Logs.Core/LogFormats/LogFileFormatBase.cs
| 2.65625
| 3
|
using System;
using System.IO;
using View4Logs.Common.Interfaces;
namespace View4Logs.Core.LogFormats
{
public abstract class LogFileFormatBase : ILogFormat
{
public abstract string Name { get; }
public bool CheckCompatibility(Uri uri)
{
try
{
if (!uri.IsFile)
{
return false;
}
var path = uri.LocalPath;
if (!CheckFilename(path))
{
return false;
}
using (var fileStream = new FileStream(uri.LocalPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
if (!CheckContent(fileStream))
{
return false;
}
}
return true;
}
catch (Exception)
{
return false;
}
}
public abstract ILogSource CreateSource(Uri uri);
protected virtual bool CheckFilename(string path) => true;
protected abstract bool CheckContent(FileStream stream);
}
}
|
e9f53aad738899773be3a101bab2910ba3c0e340
|
C#
|
VelinDimitrov/FMI-Plovdiv
|
/first year/first year third trimester-Algorithms and Data structures/Pipes/Pipes/BTree.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pipes
{
class BTree
{
public BNode root;
public BTree(int value,double water)
{
this.root = new BNode(value,100,water);
}
private void PrintTree(BNode node)
{
if (node == null)
{
return;
}
PrintTree(node.LeftChild);
if (node.LeftChild==null &&node.RightChild==null)
{
Console.Write(node.Value);
Console.WriteLine("\t" + node.Water);
}
PrintTree(node.RightChild);
}
public void PrintTree()
{
PrintTree(root);
}
public void Add(string information)
{
int[] info = information.Split(' ').Select(x=>int.Parse(x)).ToArray();
BNode nodeToAddElementsIn = null;
GetElement(info[0],root,ref nodeToAddElementsIn);
if (nodeToAddElementsIn==null)
{
Console.WriteLine("Value not found.Wrong input!"); // test purpose
return;
}
nodeToAddElementsIn.LeftChild=new BNode(info[1],info[2],nodeToAddElementsIn.Water);
nodeToAddElementsIn.RightChild = new BNode(info[3], info[4], nodeToAddElementsIn.Water);
}
private void GetElement(int value, BNode currentNode,ref BNode returnNode)
{
if (currentNode==null)
{
return;
}
else if (value==currentNode.Value)
{
returnNode = currentNode;
return;
}
GetElement(value, currentNode.LeftChild,ref returnNode);
if (returnNode==null)
{
GetElement(value, currentNode.RightChild, ref returnNode);
}
return;
}
}
}
|
96213489954693145df42ec59b8b6b7a01304855
|
C#
|
BigNikO/soft-uni-repos
|
/CSharp/C#Fundamentals/C#Advanced/04-FunctionalProgramming/Exercises/01-1-ActionPrint/ActionPrint.cs
| 3.640625
| 4
|
using System;
using System.Linq;
namespace Ex1ActionPrint
{
class ActionPrint
{
static void Main(string[] args)
{
var names = Console.ReadLine().Split(' ');
Action<string> printAction = print;
foreach (var name in names)
{
printAction(name);
}
}
static void print(string name)
{
Console.WriteLine(name);
}
}
}
|
8b4de9d85f42b5e435568ecb9a2092b985ceaea3
|
C#
|
mrlacey/StringToNumber
|
/StringToNumber/Extensions.cs
| 3.265625
| 3
|
//-----------------------------------------------------------------------
// <copyright file="Extensions.cs" company="Matt Lacey (http://mrlacey.co.uk/)">
// Copyright © 2009 Matt Lacey
// All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace StringToNumber
{
/// <summary>
/// Extension methods implementing the StringToNumber functionality
/// </summary>
public static class Extensions
{
/// <summary>
/// Converts the string to a byte.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as a byte</returns>
public static byte ToByte(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToByte(words);
}
/// <summary>
/// Converts the string to a byte.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as a byte</returns>
public static byte ToByte(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToByte(words);
}
/// <summary>
/// Converts the string to a signed byte.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as a sbyte</returns>
public static sbyte ToSByte(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToSByte(words);
}
/// <summary>
/// Converts the string to a signed byte.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as a sbyte</returns>
public static sbyte ToSByte(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToSByte(words);
}
/// <summary>
/// Converts the string to an unsigned 16bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as a UInt16</returns>
public static UInt16 ToUInt16(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToUInt16(words);
}
/// <summary>
/// Converts the string to an unsigned 16 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as a UInt16</returns>
public static UInt16 ToUInt16(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToUInt16(words);
}
/// <summary>
/// Converts the string to an unsigned 32bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as a UInt32</returns>
public static UInt32 ToUInt32(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToUInt32(words);
}
/// <summary>
/// Converts the string to an unsigned 32 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as a UInt32</returns>
public static UInt32 ToUInt32(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToUInt32(words);
}
/// <summary>
/// Converts the string to an unsigned 32bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as a UInt</returns>
public static uint ToUInt(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToUInt(words);
}
/// <summary>
/// Converts the string to an unsigned 32 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as a UInt</returns>
public static uint ToUInt(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToUInt(words);
}
/// <summary>
/// Converts the string to an unsigned 64bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as a UInt64</returns>
public static UInt64 ToUInt64(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToUInt64(words);
}
/// <summary>
/// Converts the string to an unsigned 64 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as a UInt64</returns>
public static UInt64 ToUInt64(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToUInt64(words);
}
/// <summary>
/// Converts the string to an unsigned 64 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="scale">The numeric scale to use when interpreting large numbers.</param>
/// <returns>The value as an Int64</returns>
public static UInt64 ToUInt64(this string words, Scale scale)
{
return new NumberParser(scale, CultureInfo.CurrentCulture).ToUInt64(words);
}
/// <summary>
/// Converts the string to an unsigned 64 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="scale">The numeric scale to use when interpreting large numbers.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as an Int64</returns>
public static UInt64 ToUInt64(this string words, Scale scale, CultureInfo culture)
{
return new NumberParser(scale, culture).ToUInt64(words);
}
/// <summary>
/// Converts the string to an unsigned short.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as a ushort</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ushort", Justification = "Deliberately also including type names to provide more usage options")]
public static ushort ToUShort(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToUShort(words);
}
/// <summary>
/// Converts the string to an unsigned short.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as a ushort</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ushort", Justification = "Deliberately also including type names to provide more usage options")]
public static ushort ToUShort(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToUShort(words);
}
/// <summary>
/// Converts the string to a 16 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as an Int16</returns>
public static Int16 ToInt16(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToInt16(words);
}
/// <summary>
/// Converts the string to a 16 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as an Int16</returns>
public static Int16 ToInt16(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToInt16(words);
}
/// <summary>
/// Converts the string to a short.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as a short</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "short", Justification = "Deliberately also including type names to provide more usage options")]
public static short ToShort(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToShort(words);
}
/// <summary>
/// Converts the string to a short.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as a short</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "short", Justification = "Deliberately also including type names to provide more usage options")]
public static short ToShort(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToShort(words);
}
/// <summary>
/// Converts the string to a 32 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as an Int32</returns>
public static Int32 ToInt32(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToInt32(words);
}
/// <summary>
/// Converts the string to a 32 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as an Int32</returns>
public static Int32 ToInt32(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToInt32(words);
}
/// <summary>
/// Converts the string to a long.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as an Int64</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "long", Justification = "Deliberately also including type names to provide more usage options")]
public static long ToLong(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToLong(words);
}
/// <summary>
/// Converts the string to a long.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as an Int64</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "long", Justification = "Deliberately also including type names to provide more usage options")]
public static long ToLong(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToLong(words);
}
/// <summary>
/// Converts the string to a long.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="scale">The numeric scale to use when interpreting large numbers.</param>
/// <returns>The value as an Int64</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "long", Justification = "Deliberately also including type names to provide more usage options")]
public static long ToLong(this string words, Scale scale)
{
return new NumberParser(scale, CultureInfo.CurrentCulture).ToLong(words);
}
/// <summary>
/// Converts the string to a long.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="scale">The numeric scale to use when interpreting large numbers.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as an Int64</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "long", Justification = "Deliberately also including type names to provide more usage options")]
public static long ToLong(this string words, Scale scale, CultureInfo culture)
{
return new NumberParser(scale, culture).ToLong(words);
}
/// <summary>
/// Converts the string to a 64 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as an Int64</returns>
public static Int64 ToInt64(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToInt64(words);
}
/// <summary>
/// Converts the string to a 64 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as an Int64</returns>
public static Int64 ToInt64(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToInt64(words);
}
/// <summary>
/// Converts the string to a 64 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="scale">The numeric scale to use when interpreting large numbers.</param>
/// <returns>The value as an Int64</returns>
public static Int64 ToInt64(this string words, Scale scale)
{
return new NumberParser(scale, CultureInfo.CurrentCulture).ToInt64(words);
}
/// <summary>
/// Converts the string to a 64 bit Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="scale">The numeric scale to use when interpreting large numbers.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as an Int64</returns>
public static Int64 ToInt64(this string words, Scale scale, CultureInfo culture)
{
return new NumberParser(scale, culture).ToInt64(words);
}
/// <summary>
/// Converts the string to an Integer.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as an int</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "int", Justification = "Deliberately also including type names to provide more usage options")]
public static int ToInt(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToInt(words);
}
/// <summary>
/// Converts the string to an Integer.
/// </summary>
/// <param name="words">The text to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as an int</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "int", Justification = "Deliberately also including type names to provide more usage options")]
public static int ToInt(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToInt(words);
}
/// <summary>
/// Converts the string to an unsigned long.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <returns>The value as a ulong</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ulong", Justification = "Deliberately also including type names to provide more usage options")]
public static ulong ToULong(this string words)
{
return new NumberParser(CultureInfo.CurrentCulture).ToULong(words);
}
/// <summary>
/// Converts the string to an unsigned long.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as a ulong</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ulong", Justification = "Deliberately also including type names to provide more usage options")]
public static ulong ToULong(this string words, CultureInfo culture)
{
return new NumberParser(culture).ToULong(words);
}
/// <summary>
/// Converts the string to an unsigned long.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="scale">The numeric scale to use when interpreting large numbers.</param>
/// <returns>The value as a ulong</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ulong", Justification = "Deliberately also including type names to provide more usage options")]
public static ulong ToULong(this string words, Scale scale)
{
return new NumberParser(scale, CultureInfo.CurrentCulture).ToULong(words);
}
/// <summary>
/// Converts the string to an unsigned long.
/// </summary>
/// <param name="words">The words to convert.</param>
/// <param name="scale">The numeric scale to use when interpreting large numbers.</param>
/// <param name="culture">The culture identifying the language the words are written in.</param>
/// <returns>The value as a ulong</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ulong", Justification = "Deliberately also including type names to provide more usage options")]
public static ulong ToULong(this string words, Scale scale, CultureInfo culture)
{
return new NumberParser(scale, culture).ToULong(words);
}
}
}
|
42c6e50c8189ca020aa318ce3937778174aed232
|
C#
|
JetBrains/TeamCity.VSTest.TestAdapter
|
/TeamCity.VSTest.TestLogger.Tests/MessageWriter/FileMessageWriterTests.cs
| 2.671875
| 3
|
namespace TeamCity.VSTest.TestLogger.Tests.MessageWriter
{
using System;
using System.Linq;
using System.Text;
using MessageWriters;
using Moq;
using Xunit;
public class FileMessageWriterTests
{
[Fact]
public void ShouldAddNewLineAndWriteBytesForUtf8Encoding()
{
// Given
var bytesWriterMock = new Mock<IBytesWriter>();
var writer = new FileMessageWriter(bytesWriterMock.Object);
var message = "msg";
var expectedBytes = Encoding.UTF8.GetBytes(message + Environment.NewLine);
// When
writer.Write(message);
// Then
bytesWriterMock.Verify(x => x.Write(It.Is<byte[]>(b => b.SequenceEqual(expectedBytes))));
}
}
}
|
ea41db9cc7eb6c3c4aef12b7f192891393010531
|
C#
|
joaoazevedo65485/tasksddd
|
/EventsManager.API/Controllers/TaskController.cs
| 2.625
| 3
|
using EventsManager.Application.Dtos;
using EventsManager.Application.Interfaces;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
namespace EventsManager.API.Controllers
{
[Route("[controller]")]
[ApiController]
public class TaskController : ControllerBase
{
private readonly IApplicationTaskService applicationTaskService;
public TaskController(IApplicationTaskService applicationTaskService)
{
this.applicationTaskService = applicationTaskService;
}
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return Ok(applicationTaskService.GetAll());
}
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return Ok(applicationTaskService.GetById(id));
}
[HttpPost]
public ActionResult Post([FromBody] TaskDto taskDto)
{
try
{
if (taskDto == null)
{
return NotFound();
}
applicationTaskService.Add(taskDto);
return Ok("Task criada com sucesso!");
}
catch (Exception ex)
{
throw ex;
}
}
[HttpPut]
public ActionResult Put([FromBody] TaskDto taskDto)
{
try
{
if (taskDto == null)
{
return NotFound();
}
applicationTaskService.Update(taskDto);
return Ok("Task atualizada com sucesso!");
}
catch (Exception ex)
{
throw ex;
}
}
[HttpDelete]
public ActionResult Delete([FromBody] TaskDto taskDto)
{
try
{
if (taskDto == null)
{
return NotFound();
}
applicationTaskService.Add(taskDto);
return Ok("Task removida com sucesso!");
}
catch (Exception ex)
{
throw ex;
}
}
}
}
|
432a57c40447bd6a103c416edd7b00d01461c53b
|
C#
|
shendongnian/download4
|
/first_version_download2/377110-46240468-156240279-2.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Web.Script.Serialization;
namespace SomeNamespace
{
#region Class CustomJavaScriptSerializer
/// <summary>
/// Custom JavaScript serializer, see https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptconverter%28v=vs.110%29.aspx
/// </summary>
/// <remarks>
/// Used to enhance functionality of standard <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>.
/// E.g. to support <see cref="JsonPropertyAttribute"/> that provides some properties known from Newtonsoft's JavaScript serializer,
/// see https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonPropertyAttribute.htm.
/// Additionally, there is an attribute <see cref="JsonClassAttribute"/> that can be applied to the class
/// to manipulate JSON serialization behavior of all properties of the class.
/// Use this JSON serializer when including Newtonsoft's JavaScript serializer is not an option for you.
///
/// Usage:
///
/// - Just derive your class to be JSON serialized / deserialized from this class.
/// - You now can decorate the properties of your class with e.g. [JsonProperty( "someName" )]. See <see cref="JsonPropertyAttribute"/> for details.
/// - Additionally, you can decorate your class with e.g. [JsonClass( DoNotLowerCaseFirstLetter = true)]. See <see cref="JsonClassAttribute"/> for details.
/// - Important! Use static methods <see cref="JsonSerialize"/> and <see cref="JsonDeserialize"/> of this class for JSON serialization / deserialization.
/// - For further customization specific to your class, you can override <see cref="GetSerializedProperty"/> and <see cref="SetDeserializedProperty"/> in your derived class.
///
/// Example:
///
/// <![CDATA[
///
/// [JsonClass( DoNotLowerCaseFirstLetter = true )]
/// public class ChartDataItem : CustomJavaScriptSerializer
/// {
///
/// /// <summary>
/// /// The data item's tooltip. Will be transferred to JavaScript as "tooltext".
/// /// </summary>
/// [JsonProperty( "tooltext" )]
/// public string Tooltip
/// {
/// get;
/// set;
/// }
///
/// ...
/// }
///
/// ]]>
/// </remarks>
public abstract class CustomJavaScriptSerializer : JavaScriptConverter
{
#region Fields
/// <summary>
/// Dictionary to collect all derived <see cref="CustomJavaScriptSerializer"/> to be registered with <see cref="JavaScriptConverter.RegisterConverters"/>
/// </summary>
private static Dictionary<Type, CustomJavaScriptSerializer> convertersToRegister = new Dictionary<Type, CustomJavaScriptSerializer>();
/// <summary>
/// Sync for <see cref="convertersToRegister"/>.
/// </summary>
private static readonly object sync = new object();
#endregion
#region Properties
/// <summary>
/// All derived <see cref="CustomJavaScriptSerializer"/> to be registered with <see cref="JavaScriptConverter.RegisterConverters"/>
/// </summary>
public static IEnumerable<CustomJavaScriptSerializer> ConvertersToRegister
{
get
{
return CustomJavaScriptSerializer.convertersToRegister.Values;
}
}
/// <summary>
/// <see cref="JsonClassAttribute"/> retrieved from decoration of the derived class.
/// </summary>
/// <remarks>
/// Is only set when an instance of this class is used for serialization. See constructor for details.
/// </remarks>
protected JsonClassAttribute ClassAttribute
{
get;
private set;
}
#endregion
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public CustomJavaScriptSerializer()
{
Type type = this.GetType();
if ( CustomJavaScriptSerializer.convertersToRegister.ContainsKey( type ) )
return;
lock( sync )
{
// Remember this CustomJavaScriptSerializer instance to do serialization for this type.
if ( CustomJavaScriptSerializer.convertersToRegister.ContainsKey( type ) )
return;
// Performance: Set ClassAttribute only for the instance used for serialization.
this.ClassAttribute = ( this.GetType().GetCustomAttributes( typeof( JsonClassAttribute ), true ).FirstOrDefault() as JsonClassAttribute ) ?? new JsonClassAttribute();
convertersToRegister[ type ] = this;
}
}
#endregion
#region Public Methods
/// <summary>
/// Converts <paramref name="obj"/> to a JSON string.
/// </summary>
/// <param name="obj">The object to serialize.</param>
/// <returns>The serialized JSON string.</returns>
public static string JsonSerialize( object obj )
{
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters( CustomJavaScriptSerializer.ConvertersToRegister );
serializer.MaxJsonLength = int.MaxValue;
return serializer.Serialize( obj );
}
/// <summary>
/// Converts a JSON-formatted string to an object of the specified type.
/// </summary>
/// <param name="input">The JSON string to deserialize.</param>
/// <param name="targetType">The type of the resulting object.</param>
/// <returns>The deserialized object.</returns>
public static object JsonDeserialize( string input, Type targetType )
{
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters( CustomJavaScriptSerializer.ConvertersToRegister );
serializer.MaxJsonLength = int.MaxValue;
return serializer.Deserialize( input, targetType );
}
/// <summary>
/// Converts the specified JSON string to an object of type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type of the resulting object.</typeparam>
/// <param name="input">The JSON string to be deserialized.</param>
/// <returns>The deserialized object.</returns>
public static T JsonDeserialize<T>( string input )
{
return (T)CustomJavaScriptSerializer.JsonDeserialize( input, typeof( T ) );
}
/// <summary>
/// Get this object serialized as JSON string.
/// </summary>
/// <returns>This object as JSON string.</returns>
public string ToJson()
{
return CustomJavaScriptSerializer.JsonSerialize( this );
}
#endregion
#region Overrides
/// <summary>
/// Return list of supported types. This is just a derived class here.
/// </summary>
[ScriptIgnore]
public override IEnumerable<Type> SupportedTypes
{
get
{
return new ReadOnlyCollection<Type>( new List<Type>(){ this.GetType() } );
}
}
/// <summary>
/// Serialize the passed <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The object to serialize.</param>
/// <param name="serializer">The <see cref="JavaScriptSerializer"/> calling this method.</param>
/// <returns>A dictionary with name value pairs representing property name value pairs as they shall appear in JSON. </returns>
public override IDictionary<string, object> Serialize( object obj, JavaScriptSerializer serializer )
{
var result = new Dictionary<string, object>();
if ( obj == null )
return result;
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
PropertyInfo[] properties = this.GetType().GetProperties( bindingFlags );
foreach ( PropertyInfo property in properties )
{
KeyValuePair<string, object> kvp = this.GetSerializedProperty( obj, property );
if ( !string.IsNullOrEmpty( kvp.Key ) )
result[ kvp.Key ] = kvp.Value;
}
return result;
}
/// <summary>
/// Deserialize <paramref name="dictionary"/> to <paramref name="type"/>.
/// </summary>
/// <remarks>
/// Reverse method to <see cref="Serialize"/>
/// </remarks>
/// <param name="dictionary">The dictionary to be deserialized.</param>
/// <param name="type">Type to deserialize to. This is the type of the derived class, see <see cref="SupportedTypes"/>.</param>
/// <param name="serializer">The <see cref="JavaScriptSerializer"/> calling this method.</param>
/// <returns>An object of type <paramref name="type"/> with property values set from <paramref name="dictionary"/>.</returns>
public override object Deserialize( IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer )
{
if ( dictionary == null )
throw new ArgumentNullException( "dictionary" );
if ( type == null )
throw new ArgumentNullException( "type" );
if ( serializer == null )
throw new ArgumentNullException( "serializer" );
// This will fail if type has no default constructor.
object result = Activator.CreateInstance( type );
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
PropertyInfo[] properties = this.GetType().GetProperties( bindingFlags );
foreach ( PropertyInfo property in properties )
{
this.SetDerializedProperty( result, property, dictionary, serializer );
}
return result;
}
#endregion
#region Protected Methods
/// <summary>
/// Get a key value pair as base for serialization, based on the passed <paramref name="property"/>.
/// </summary>
/// <remarks>
/// The returned <see cref="KeyValuePair"/> key represents the property's name in JSON, the value its value.
/// </remarks>
/// <param name="obj">The object to serialize.</param>
/// <param name="property">The <see cref="PropertyInfo"/>To be serialized.</param>
/// <returns>The requested key value pair or an empty key value pair (key = null) to ignore this property.</returns>
protected virtual KeyValuePair<string, object> GetSerializedProperty( object obj, PropertyInfo property )
{
var result = new KeyValuePair<string, object>();
if ( property == null || !property.CanRead )
return result;
object value = property.GetValue( obj );
if ( value == null && !this.ClassAttribute.SerializeNullValues )
return result;
JsonPropertyAttribute jsonPropertyAttribute = this.GetJsonPropertyAttribute( property );
if ( jsonPropertyAttribute == null || jsonPropertyAttribute.Ignored )
return result;
if ( value != null && jsonPropertyAttribute.UseToString )
value = value.ToString();
string name = jsonPropertyAttribute.PropertyName;
return new KeyValuePair<string, object>( name, value );
}
/// <summary>
/// Set <paramref name="property"/> of <paramref name="obj"/> with value provided in <paramref name="dictionary"/>.
/// </summary>
/// <param name="obj">The object to set <paramref name="property of"/>.</param>
/// <param name="property">The property to set its value.</param>
/// <param name="dictionary">Dictionary with property name - value pairs to query for <paramref name="property"/> value.</param>
/// <param name="serializer">The <see cref="JavaScriptSerializer"/> calling this method.</param>
public virtual void SetDerializedProperty( object obj, PropertyInfo property, IDictionary<string, object> dictionary, JavaScriptSerializer serializer )
{
if ( obj == null || property == null || !property.CanWrite || dictionary == null || serializer == null )
return;
JsonPropertyAttribute jsonPropertyAttribute = this.GetJsonPropertyAttribute( property );
if ( jsonPropertyAttribute == null || jsonPropertyAttribute.Ignored || jsonPropertyAttribute.UseToString )
return;
string name = jsonPropertyAttribute.PropertyName;
if ( !dictionary.ContainsKey( name ) )
return;
object value = dictionary[ name ];
// Important! Use JavaScriptSerializer.ConvertToType so that CustomJavaScriptSerializers of properties of this class are called recursively.
object convertedValue = serializer.ConvertToType( value, property.PropertyType );
property.SetValue( obj, convertedValue );
}
/// <summary>
/// Gets a <see cref="JsonPropertyAttribute"/> for the passed <see cref="PropertyInfo"/>.
/// </summary>
/// <param name="property">The property to examine. May not be null.</param>
/// <returns>A <see cref="JsonPropertyAttribute"/> with properties set to be used directly as is, never null.</returns>
protected JsonPropertyAttribute GetJsonPropertyAttribute( PropertyInfo property )
{
if ( property == null )
throw new ArgumentNullException( "property" );
object[] attributes = property.GetCustomAttributes( true );
JsonPropertyAttribute jsonPropertyAttribute = null;
bool ignore = false;
foreach ( object attribute in attributes )
{
if ( attribute is ScriptIgnoreAttribute )
ignore = true;
if ( attribute is JsonPropertyAttribute )
jsonPropertyAttribute = (JsonPropertyAttribute)attribute;
}
JsonPropertyAttribute result = jsonPropertyAttribute ?? new JsonPropertyAttribute();
result.Ignored |= ignore;
if ( string.IsNullOrWhiteSpace( result.PropertyName ) )
result.PropertyName = property.Name;
if ( !this.ClassAttribute.DoNotLowerCaseFirstLetter && ( jsonPropertyAttribute == null || string.IsNullOrWhiteSpace( jsonPropertyAttribute.PropertyName ) ) )
{
string name = result.PropertyName.Substring( 0, 1 ).ToLowerInvariant();
if ( result.PropertyName.Length > 1 )
name += result.PropertyName.Substring( 1 );
result.PropertyName = name;
}
return result;
}
#endregion
}
#endregion
#region Class JsonClassAttribute
/// <summary>
/// Attribute to be used in conjunction with <see cref="CustomJavaScriptSerializer"/>.
/// </summary>
/// <remarks>
/// Decorate your class derived from <see cref="CustomJavaScriptSerializer"/> with this attribute to
/// manipulate how JSON serialization / deserialization is done for all properties of your derived class.
/// </remarks>
[AttributeUsage( AttributeTargets.Class )]
public class JsonClassAttribute : Attribute
{
#region Properties
/// <summary>
/// By default, all property names are automatically converted to have their first letter lower case (as it is convention in JavaScript). Set this to true to avoid that behavior.
/// </summary>
public bool DoNotLowerCaseFirstLetter
{
get;
set;
}
/// <summary>
/// By default, properties with value null are not serialized. Set this to true to avoid that behavior.
/// </summary>
public bool SerializeNullValues
{
get;
set;
}
#endregion
}
#endregion
#region Class JsonPropertyAttribute
/// <summary>
/// Attribute to be used in conjunction with <see cref="CustomJavaScriptSerializer"/>.
/// </summary>
/// <remarks>
/// Among others, used to define a property's name when being serialized to JSON.
/// Implements some functionality found in Newtonsoft's JavaScript serializer,
/// see https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonPropertyAttribute.htm
/// </remarks>
[AttributeUsage( AttributeTargets.Property )]
public class JsonPropertyAttribute : Attribute
{
#region Properties
/// <summary>
/// True to ignore this property.
/// </summary>
public bool Ignored
{
get;
set;
}
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
public string PropertyName
{
get;
set;
}
/// <summary>
/// When true, the value of this property is serialized using value.ToString().
/// </summary>
/// <remarks>
/// Can be handy when serializing e.g. enums or types.
/// Do not set this to true when deserialization is needed, since there is no general inverse method to ToString().
/// When this is true, the property is just ignored when deserializing.
/// </remarks>
public bool UseToString
{
get;
set;
}
#endregion
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public JsonPropertyAttribute()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonPropertyAttribute"/> class with the specified name.
/// </summary>
/// <param name="propertyName">Name of the property</param>
public JsonPropertyAttribute( string propertyName )
{
this.PropertyName = propertyName;
}
#endregion
}
#endregion
}
|
17932a348bc99ec32af7925255a8c0a96e205164
|
C#
|
jasonhuber/2010FallB_CIS407
|
/day4/website/getProductDetail.aspx.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _getProductDetail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection();
Conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("app_data/productsdb.mdb");
Conn.Open();
//Response.Write(Conn.State);
System.Data.OleDb.OleDbCommand Comm = new System.Data.OleDb.OleDbCommand();
System.Data.OleDb.OleDbDataReader dr;
Comm.Connection = Conn;
Comm.CommandText = "select productid, productname, productiondescription, price, qoh, imagelocation from products";
if (Request.Params["prodid"] != null && Request.Params["prodid"].Length >0)
{
Comm.CommandText += " where productid = ?" ;
Comm.Parameters.AddWithValue("anything", Request.Params["prodid"].ToString());
}
dr = Comm.ExecuteReader();
bool firstone = true;
if (!dr.HasRows)
{
Response.Write("Sorry that productid was not found!");
}
while (dr.Read())
{
Response.Write("<h3>" + dr[1].ToString() + "</h3>");
}
}
}
|
d4762f3e348407d9bb3ea5cc7d768e9d0942c2b6
|
C#
|
MitchReed123/FinalGoldBadge
|
/ConsoleAppChallenges/Cafe/MenuRepository.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cafe
{
public class MenuRepository
{
private List<Menu> _menu = new List<Menu>();
public void AddContentToMenu(Menu item)
{
_menu.Add(item);
}
public void DeleteContentFromMenu(Menu item)
{
_menu.Remove(item);
}
public Menu GetByName(string name)
{
foreach (Menu item in _menu)
{
if (item.MealName.ToLower() == name.ToLower())
{
return item;
}
}
return null;
}
public bool RemoveContentFromList(string title)
{
Menu content = GetByName(title);
if (content == null)
{
return false;
}
int initialCount = _menu.Count;
_menu.Remove(content);
if (initialCount > _menu.Count)
{
return true;
}
else
{
return false;
}
}
public List<Menu> GetMenu()
{
return _menu;
}
public bool DeleteItems(Menu item)
{
return _menu.Remove(item);
}
}
}
|
31f63f92526d204aad1d3e4cf83b2b301b62a814
|
C#
|
den090312/xt_q2
|
/Task02/2.4.MY STRING/Program.cs
| 3.90625
| 4
|
using System;
namespace _2._4.MY_STRING
{
public class Program
{
private static void Main(string[] args)
{
//создание объекта через массив
var myString1 = new MyString(new char[] { 'a', 'b', 'c', 'd', 'e', 'i', 'j'});
Console.WriteLine("MyString1:");
WriteMyString(myString1);
//создание объекта через строку
var myString2 = new MyString("46371825");
Console.WriteLine("MyString2:");
WriteMyString(myString2);
//конкатенация
var myString3 = myString1 + myString2;
Console.WriteLine("MyString1 + MyString2:");
WriteMyString(myString3);
//сортировка
Console.WriteLine("Сортировка MyString3:");
WriteMyString(myString3.Sort());
//реверс
Console.WriteLine("Обратный MyString3:");
WriteMyString(myString3.Reverse());
//поиск элемента
Console.WriteLine("Поиск в MyString3:");
var myChar = '3';
if (myString3.TryFind(myChar, out int index))
{
Console.WriteLine($"Значение '{myChar}' найдено, индекс первого вхождения элемента: {index}");
}
else
{
Console.WriteLine("Значение не найдено");
}
Console.WriteLine();
//получаем значение по индексу
Console.WriteLine("Индексатор:");
Console.WriteLine($"MyString3[0] = '{myString3[0]}'");
Console.WriteLine();
//получаем длину массива
Console.WriteLine("Длина MyString3:");
Console.WriteLine(myString3.Length);
Console.WriteLine();
}
private static void WriteMyString(MyString myString)
{
var charArray = myString.ToCharArray();
foreach (char element in charArray)
{
Console.Write($"{element}");
}
Console.WriteLine();
Console.WriteLine();
}
}
}
|
5c563e6540f775267cfd1c1ad28f34e5e0fb7e5c
|
C#
|
dabbers/ProxyScanner
|
/ProxyTool/Form1.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Threading;
using ProxyTool.ProxyFindingParser;
using System.Net;
namespace ProxyTool
{
public delegate void PerformCallback(ConcurrentBag<Proxy> list);
public partial class Form1 : Form
{
Thread action;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
var lines = richTextBox1.Lines;
if (checkBox1.Checked)
{
action = new Thread(() => performVerify(donecb, performLinks(lines)));
}
else
{
action = new Thread(() => performLinks(donecb, lines));
}
action.Name = "Action";
action.IsBackground = true;
action.Start();
}
private void performVerify(PerformCallback cb, ConcurrentBag<Proxy> list)
{
IExecutingContext ctx = new ExecutingContext(new ParsingFactory());
ConcurrentBag<Proxy> results = new ConcurrentBag<Proxy>();
richTextBox2.Invoke(new Action(() =>
{
status_action.Text = "Proxy Verification";
richTextBox2.Text = String.Empty;
progressBar.Maximum = list.Count();
progressBar.Value = 0;
}));
Parallel.ForEach(list, (item) =>
{
var task = new ProxyTesterTask();
task.SetTask(item.ToString());
task.Run(ctx);
if (task.Result)
{
richTextBox2.Invoke(new Action(() =>
{
richTextBox2.AppendText(item.ToString() + Environment.NewLine);
}));
}
richTextBox2.Invoke(new Action(() =>
{
progressBar.Value++;
}));
});
richTextBox2.Invoke(new Action(() =>
{
status_action.Text = "Idle.";
button1.Enabled = true;
}));
//cb(results);
}
private void donecb(ConcurrentBag<Proxy> list)
{
richTextBox2.Invoke(new Action(() =>
{
richTextBox2.Text = String.Empty;
foreach(var l in list)
{
richTextBox2.AppendText(l.ToString() + Environment.NewLine);
}
status_action.Text = "Idle.";
button1.Enabled = true;
}));
}
public ConcurrentBag<Proxy> performLinks(string[] lines)
{
ConcurrentBag<Proxy> proxyList = new ConcurrentBag<Proxy>();
richTextBox2.Invoke(new Action(() =>
{
status_action.Text = "Proxy fetching";
richTextBox2.Text = String.Empty;
progressBar.Maximum = lines.Count();
progressBar.Value = 0;
}));
if (lines[0].StartsWith("http"))
{
IExecutingContext ctx = new ExecutingContext(new ParsingFactory());
Parallel.ForEach(lines, (line) =>
{
if (!String.IsNullOrEmpty(line))
{
ProxyFinderTask task = new ProxyFinderTask();
task.SetTask(line);
task.Run(ctx);
var results = task.Results;
foreach (var result in results)
{
if (proxyList.Where(p => p.Host == result.Host).Count() == 0)
{
IPAddress ip = Dns.GetHostAddresses(result.Host).FirstOrDefault();
result.Host = ip.ToString();
if (proxyList.Where(p => p.Host == result.Host).Count() == 0)
{
proxyList.Add(result);
}
}
}
richTextBox2.Invoke(new Action(() =>
{
progressBar.Value++;
}));
}
});
}
else
{
foreach(var line in lines)
{
try
{
richTextBox2.Invoke(new Action(() =>
{
progressBar.Value++;
}));
var result = new Proxy(line);
if (proxyList.Where(p => p.Host == result.Host).Count() == 0)
{
proxyList.Add(result);
}
}
catch { }
}
}
return proxyList;
}
public void performLinks(PerformCallback cb, string[] lines)
{
cb(performLinks(lines));
}
}
}
|
fdd9d88708a34d5c52760abdadfc2dfd91328b53
|
C#
|
fazzer123/Gruppe-5---Just-Drink
|
/Projekt Mappe/DrinkzyWCF/WCF/OrderLineService.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ModelLayer;
using BusinessLayer;
namespace WCF
{
public class OrderLineService : IOrderLineService
{
OrderLineController olCtr;
public OrderLineService()
{
olCtr = new OrderLineController();
}
public void CreateOrderLine(OrderLine orderline, int orderID)
{
olCtr.CreateOrderLine(orderline, orderID);
}
public void CreateOrderLineHelflask(OrderLine orderline, int orderID)
{
olCtr.CreateOrderLineHelflask(orderline, orderID);
}
public void CreateOrderLineAlchohol(OrderLine orderline, int orderID)
{
olCtr.CreateOrderLineAlchohol(orderline, orderID);
}
public IEnumerable<OrderLine> GetAllOrderlines()
{
return olCtr.GetAllOrderLines();
}
public OrderLine GetOrderLine(int ID)
{
return olCtr.GetOrderLine(ID);
}
public OrderLine GetOrderLineHelflask(int ID)
{
return olCtr.GetOrderLineHelflask(ID);
}
public void DeleteOrderLineByID(string type, int orderlineID, int id)
{
olCtr.DeleteOrderLineByID(type, orderlineID, id);
}
public void EditOrderLine(OrderLine orderLine)
{
olCtr.EditOrderLine(orderLine);
}
public void EditOrderLineHelflask(OrderLine orderLine)
{
olCtr.EditOrderLineHelflask(orderLine);
}
public void EditOrderLinePrice(int id, int orderID, string text)
{
olCtr.EditOrderLinePrice(id, orderID, text);
}
public Drink GetDrink(int id)
{
return olCtr.getDrink(id);
}
public HelFlask GetHelflask(int id)
{
return olCtr.GetHelflask(id);
}
public Alchohol GetAlchohol(int id)
{
return olCtr.GetALchohol(id);
}
}
}
|
926d673eb6748f7cf53305875bd9fcbaaeb9ebe5
|
C#
|
emagineNull/csharp-beginner
|
/nested-loops/NestedLoopsExercise/Fishing/Program.cs
| 3.5625
| 4
|
using System;
namespace Fishing
{
class Program
{
static void Main(string[] args)
{
int quota = int.Parse(Console.ReadLine());
string fishName = Console.ReadLine();
int fish = 0;
double total = 0;
double totalWon = 0;
double totalLost = 0;
while (fishName != "Stop")
{
fish++;
int characterAsciiNum = 0;
double fishPrice = 0;
double fishWeight = double.Parse(Console.ReadLine());
for (int i = 0; i < fishName.Length; i++)
{
characterAsciiNum = fishName[i];
fishPrice += characterAsciiNum;
}
fishPrice /= fishWeight;
if (fish % 3 == 0)
{
totalWon += fishPrice;
}
else
{
totalLost += fishPrice;
}
if (fish == quota)
{
Console.WriteLine("Lyubo fulfilled the quota!");
break;
}
fishName = Console.ReadLine();
}
if (totalWon > totalLost)
{
total = totalWon - totalLost;
Console.WriteLine($"Lyubo's profit from {fish} fishes is {total:f2} leva.");
}
else
{
total = totalLost - totalWon;
Console.WriteLine($"Lyubo lost {total:f2} leva today.");
}
}
}
}
|
61cc0ea7ce23c7f48a4d9860e99979b185d3f3de
|
C#
|
rgomesnet/RGomes.Escola
|
/src/RGomes.Escola.Domain/Aluno/Email.cs
| 2.71875
| 3
|
namespace RGomes.Escola.Domain.Aluno
{
using System;
public class Email
{
public Email(string endereco)
{
if (!endereco.Matches(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))
{
throw new ArgumentException("O e-mail informado não é um valor válido.");
}
this.Endereco = endereco;
}
public string Endereco { get; }
}
}
|
7d0ad61c5f46fbb505f841f6ef023e0e50f2d950
|
C#
|
mkbiltek/.NET
|
/LightIndexer/LightIndexerGUI/Classes/DisksTreeNodeProvider.cs
| 2.59375
| 3
|
using System.IO;
using System.Linq;
using System.Windows.Forms;
using PDNUtils.Help;
using PDNUtils.Tree;
namespace LightIndexerGUI.Forms
{
public class DisksTreeNodeProvider : ITreeNodeProvider
{
public TreeNode[] GetChildNodes()
{
var driveNamesChecked = CheckedManager.Instance.AllChecked.Select(p => p.Substring(0, 3).ToUpper()).Distinct();
var driveNamesInSystem = DriveInfo.GetDrives().Select(d => d.Name);
var driveNamesVirtual = driveNamesChecked.Where(dn => !driveNamesInSystem.Contains(dn));
var mergedDrives = driveNamesInSystem.Union(driveNamesChecked).Distinct().Select(dn => new DriveInfo(dn));
var driveNodes = from drive in mergedDrives
select new TreeNode
{
//NodeFont = driveNamesVirtual.Contains(drive.Name) ? virtualFont : null,
Tag = driveNamesVirtual.Contains(drive.Name) ? "virtual" : null,
Checked = CheckedManager.Instance.IsChecked(drive.RootDirectory.FullName),
Text = drive.Name,
};
return driveNodes.ToArray();
}
}
}
|
a73bc40e72ed70505097324a321c10a920597ec6
|
C#
|
EdgarVerona/gamejam-floatilla
|
/Assets/Health/HealthBar.cs
| 2.515625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
[SerializeField]
float UpdateSpeedInSeconds = 0.2f;
[SerializeField]
float PositionOffset = 2.0f;
[SerializeField]
Image ForegroundImage;
private Health _health;
private Camera _mainCamera;
private void Start()
{
_mainCamera = Camera.main;
}
internal void SetHealth(Health health)
{
_health = health;
_health.OnHealthPercentChanged += HandleHealthChanged;
}
private void HandleHealthChanged(float percent)
{
StartCoroutine(ChangeToPercent(percent));
}
private IEnumerator ChangeToPercent(float percent)
{
float preChangePercent = this.ForegroundImage.fillAmount;
float elapsed = 0.0f;
while (elapsed < this.UpdateSpeedInSeconds)
{
elapsed += Time.deltaTime;
this.ForegroundImage.fillAmount = Mathf.Lerp(preChangePercent, percent, elapsed / this.UpdateSpeedInSeconds);
yield return null;
}
this.ForegroundImage.fillAmount = percent;
}
private void LateUpdate()
{
// Screen point for the person's health bar, and a configured offset above it.
// Note that _health is attached to the object in the game that has health.
this.transform.position = _mainCamera.WorldToScreenPoint(_health.transform.position + Vector3.forward * this.PositionOffset);
}
}
|
fe377c20df588789898515cbcb020658fcb6ab12
|
C#
|
Chlosans/OstaraUnity
|
/Assets/Scripts/Ostara.cs
| 2.546875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using ChoicePasseur;
public class Ostara : MonoBehaviour
{
public static string choice;
public static void Choice(string data)
{
Debug.Log(data);
choice = data;
}
public void GoodOrBad()
{
// récpetion choix des joueurs Obstacle 1 pour lancer tel ou tel cinématique désert (Rosalie/Voiture)
if (choice == "{\"data\":\"voiture\"}")
{
SceneManager.LoadScene(9);
}
if (choice == "{\"data\":\"rosalie\"}")
{
SceneManager.LoadScene(8);
}
}
}
|
563fcb4b260198f4bc37d222ec3b5b855af170d5
|
C#
|
soharle/algebra-de-conjuntos
|
/Actions/OperatorReverse.cs
| 3.15625
| 3
|
using algebra_de_conjuntos.Models;
using System;
using System.Text.RegularExpressions;
namespace algebra_de_conjuntos.Actions
{
class OperatorReverse
{
public static Set ReversivelProdutoDasPartes(Set a)
{
string name = a.Name.Substring(a.Name.IndexOf('('), (a.Name.IndexOf(')')));
name = Regex.Replace(name, @"\(|\)", "");
Set newSet = new Set
{
Name = name
};
string allElements = a.ElementsSetToString();
string pattern = @"\(|\)|{|}|\s";
string replacement = "";
string body;
body = Regex.Replace(allElements, pattern, replacement);
string[] elements = body.Split(',');
for (int i = 0; i < elements.Length; i++)
{
if (!elements[i].Equals(""))
{
newSet.AddElement(new Element
{
Value = elements[i]
});
}
}
return newSet;
}
public static Tuple<Set, Set> ReversivelProdutoCartesiano(Set a)
{
string[] names = a.Name.Split('x');
Set conjuntoA = new Set
{
Name = names[0].Trim()
};
Set conjuntoB = new Set
{
Name = names[1].Trim()
};
for (int i = 0; i < a.ListElements.Count; i++)
{
string element = a.ListElements[i].Value;
string pattern = @"\(|\)";
string replacement = "";
string body;
body = Regex.Replace(element, pattern, replacement);
string[] elements = body.Split(',');
conjuntoA.AddElement(new Element
{
Value = elements[0].Trim()
});
conjuntoB.AddElement(new Element
{
Value = elements[1].Trim()
});
}
return new Tuple<Set, Set>(conjuntoA, conjuntoB);
}
}
}
|
7ca3187c4fbf87959525726f7da22fdc391628e5
|
C#
|
Killface1980/ONI-Modloader
|
/Source/MaterialColor/Extensions/Color32Extensions.cs
| 3.015625
| 3
|
namespace MaterialColor.Extensions
{
using System;
using ONI_Common.Data;
using UnityEngine;
public static class Color32Extensions
{
public static float GetBrightness(this Color32 color)
{
float currentBrightness = Math.Max((float)color.r / byte.MaxValue, (float)color.g / byte.MaxValue);
currentBrightness = Math.Max(currentBrightness, (float)color.b / byte.MaxValue);
return currentBrightness;
}
public static Color32 Multiply(this Color32 color, Color32Multiplier multiplier)
{
color.r = (byte)Mathf.Clamp(color.r * multiplier.Red, byte.MinValue, byte.MaxValue);
color.g = (byte)Mathf.Clamp(color.g * multiplier.Green, byte.MinValue, byte.MaxValue);
color.b = (byte)Mathf.Clamp(color.b * multiplier.Blue, byte.MinValue, byte.MaxValue);
return color;
}
public static Color32 SetBrightness(this Color32 color, float targetBrightness)
{
float currentBrightness = color.GetBrightness();
Color32 result = color.Multiply(new Color32Multiplier(targetBrightness / currentBrightness));
return result;
}
public static Color32 TintToWhite(this Color32 currentColor)
{
byte r = (byte)(byte.MaxValue - currentColor.r);
byte g = (byte)(byte.MaxValue - currentColor.g);
byte b = (byte)(byte.MaxValue - currentColor.b);
Color32 result = new Color32 { r = r, g = g, b = b, a = byte.MaxValue };
return result;
}
public static Color32 ToColor32(this int hexVal)
{
byte r = (byte)((hexVal >> 16) & 0xFF);
byte g = (byte)((hexVal >> 8) & 0xFF);
byte b = (byte)(hexVal & 0xFF);
return new Color32(r, g, b, 0xFF);
}
public static int ToHex(this Color32 color)
{
return color.r << 16 | color.g << 8 | color.b;
}
}
}
|