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
|
|---|---|---|---|---|---|---|
ab0890d79219f0f515164703152dcc0f477cf290
|
C#
|
camelot123456/QuanLiNhanSu_Winform_c-
|
/INDIVIDUAL_PROJECT_CS414SC_2020S/repository/PRRepository.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace INDIVIDUAL_PROJECT_CS414SC_2020S.repository
{
class PRRepository
{
AbstractDAO dao;
public PRRepository()
{
dao = new AbstractDAO();
}
public DataTable find()
{
string sql = "SELECT * FROM LUONG";
return dao.queryForList(sql);
}
public DataTable findIdOfNhanVienByTypeJob(string typeJob)
{
string sql = "SELECT * FROM NHANVIEN WHERE LOAICONGVIEC = N'"+typeJob+"'";
return dao.queryForList(sql);
}
public int deleteOne(string maluong)
{
string sql = "DELETE FROM LUONG WHERE MALUONG = " + maluong + "";
return dao.executeUpdate(sql);
}
//--------------------------------------------------Full-time----------------------------------------------------
public DataTable getLuongByTypeJobIsFulltime()
{
string sql = @"
SELECT L.MALUONG, N.AVATAR, N.TENNV, L.LUONGCOBAN, L.HESOLUONG, L.LUONG1NGAY, L.SONGAYLAM, L.LUONGTHUONG, THANHLUONG
FROM LUONG L, NHANVIEN N WHERE L.MANV = N.MANV AND N.LOAICONGVIEC = N'Fulltime'
";
return dao.queryForList(sql);
}
public int saveByFull(double lcb, double hsl, double l1n, double snl, double lt, double thanhluong, int manv)
{
string sql = "INSERT INTO LUONG(LUONGCOBAN, HESOLUONG, LUONG1NGAY, SONGAYLAM, LUONGTHUONG, THANHLUONG, MANV) " +
"VALUES(" + lcb + ", " + hsl + ", " + l1n + ", " + snl + ", " + lt + ", " + thanhluong + ", " + manv + ")";
return dao.executeUpdate(sql);
}
public int updateOneByFull(double lcb, double hsl, double l1n, double snl, double lt, double thanhluong, string maluong)
{
string sql = "UPDATE LUONG SET LUONGCOBAN=" + lcb + ", HESOLUONG=" + hsl + ", LUONG1NGAY=" + l1n + ", SONGAYLAM=" + snl + ", LUONGTHUONG=" + lt + ", THANHLUONG=" + thanhluong + " WHERE MALUONG=" + maluong + "";
return dao.executeUpdate(sql);
}
//--------------------------------------------------Part-time----------------------------------------------------
public DataTable getLuongByTypeJobIsParttime()
{
string sql = @"
SELECT L.MALUONG, N.AVATAR, N.TENNV, L.LUONG1GIO, L.SOGIOLAM, L.SONGAYLAM, L.LUONGTHUONG, THANHLUONG
FROM LUONG L, NHANVIEN N WHERE L.MANV = N.MANV AND N.LOAICONGVIEC = N'Parttime'
";
return dao.queryForList(sql);
}
public int saveByPart(double l1g, double snl, double sgl, double lt, double thanhluong, int manv)
{
string sql = "INSERT INTO LUONG(LUONG1GIO, SONGAYLAM, SOGIOLAM, LUONGTHUONG, THANHLUONG, MANV) " +
"VALUES(" + l1g + ", " + snl + ", " + sgl + ", " + lt + ", " + thanhluong + ", " + manv + ")";
return dao.executeUpdate(sql);
}
public int updateOneByPart(double l1g, double snl, double sgl, double lt, double thanhluong, string maluong)
{
string sql = "UPDATE LUONG SET LUONG1GIO=" + l1g + ", SONGAYLAM=" + snl + ", SOGIOLAM=" + sgl + ", LUONGTHUONG=" + lt + ", THANHLUONG=" + thanhluong + " WHERE MALUONG=" + maluong + "";
return dao.executeUpdate(sql);
}
}
}
|
32cbbdee818e7ca2a5dc3a3c2fc7234e49c8cf23
|
C#
|
FedericoCampanozzi/OOP20-HotLineCesena-C-Sharp
|
/Corradino/Main/Controller/Entities/Player/Command/ICommand.cs
| 2.71875
| 3
|
using Main.Model.Entities.Actors.Player;
namespace Main.Controller.Entities.Player.Command
{
/// <summary>
/// Interface used for applying the Command pattern.
/// </summary>
public interface ICommand
{
/// <summary>
/// Allows to invoke one or more <see cref="IPlayer"/> methods.
/// </summary>
/// <param name="player">the <see cref="IPlayer"/> instance this
/// command will be given to</param>
void Execute(IPlayer player);
}
}
|
29c6fb052278ec80f4b680fecaa41b0b62a491e6
|
C#
|
Armienn/NeaKitSharp
|
/NeaKit/Language/Sound.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NeaKit
{
/// <summary>
/// A simple implementation of sound representation (compared to the Language/Sound one).
/// Initiation is assumed to be pulmonic and airstream is assumed to be egressive.
/// </summary>
public struct Sound : IEquatable<Sound>
{
public ArticulationPoint Point;
public ArticulationManner Manner;
public TongueShape Shape;
public bool Rounded;
public bool Nasal;
public Voice Voice;
public Sound(
ArticulationPoint point = ArticulationPoint.DorsalPalatal,
ArticulationManner manner = ArticulationManner.Open,
TongueShape shape = TongueShape.Central,
bool rounded = false,
bool nasal = false,
Voice voice = Voice.Modal)
{
Point = point;
Manner = manner;
Shape = shape;
Rounded = rounded;
Nasal = nasal;
Voice = voice;
}
public static Sound GetRandom()
{
Sound sound = new Sound();
Random random = new Random();
do
{
Array enums = Enum.GetValues(typeof(ArticulationPoint));
sound.Point = (ArticulationPoint)enums.GetValue(random.Next(enums.Length));
enums = Enum.GetValues(typeof(ArticulationManner));
sound.Manner = (ArticulationManner)enums.GetValue(random.Next(enums.Length));
enums = Enum.GetValues(typeof(TongueShape));
sound.Shape = (TongueShape)enums.GetValue(random.Next(enums.Length));
enums = Enum.GetValues(typeof(Voice));
sound.Voice = (Voice)enums.GetValue(random.Next(enums.Length));
sound.Rounded = random.Next(2) == 0;
sound.Nasal = random.Next(2) == 0;
}
while (!sound.IsValid);
sound.Standardise();
return sound;
}
public bool IsValid
{
get
{
if (Rounded)
{
switch (Point)
{
case ArticulationPoint.LabialLabial:
case ArticulationPoint.LabialDental:
case ArticulationPoint.CoronalLabial:
return false;
}
}
if (Voice == Voice.Voiceless)
{
//this isn't really invalid, just very unusual
switch (Manner)
{
case ArticulationManner.Close:
case ArticulationManner.NearClose:
case ArticulationManner.CloseMid:
case ArticulationManner.Mid:
case ArticulationManner.OpenMid:
case ArticulationManner.NearOpen:
case ArticulationManner.Open:
return false;
}
}
if (Voice == Voice.Aspirated)
{
switch (Manner)
{
case ArticulationManner.Stop:
break;
default:
return false;
}
}
if (Manner == ArticulationManner.Closed && !Nasal) return false;
switch (Point)
{
case ArticulationPoint.LabialLabial:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
return true;
default:
return false;
}
case ArticulationPoint.LabialDental:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
return true;
default:
return false;
}
case ArticulationPoint.CoronalLabial:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
return true;
default:
return false;
}
case ArticulationPoint.CoronalDental:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
return true;
default:
return false;
}
case ArticulationPoint.CoronalAlveolar:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
return true;
default:
return false;
}
case ArticulationPoint.CoronalPostAlveolar:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
return true;
default:
return false;
}
case ArticulationPoint.CoronalRetroflex:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
return true;
default:
return false;
}
case ArticulationPoint.DorsalPostAlveolar:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
return true;
default:
return false;
}
case ArticulationPoint.DorsalPalatal:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
case ArticulationManner.Close:
case ArticulationManner.NearClose:
case ArticulationManner.CloseMid:
case ArticulationManner.Mid:
case ArticulationManner.OpenMid:
case ArticulationManner.NearOpen:
case ArticulationManner.Open:
return true;
default:
return false;
}
case ArticulationPoint.DorsalPalVel:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
case ArticulationManner.Close:
case ArticulationManner.NearClose:
case ArticulationManner.CloseMid:
case ArticulationManner.Mid:
case ArticulationManner.OpenMid:
case ArticulationManner.NearOpen:
case ArticulationManner.Open:
return true;
default:
return false;
}
case ArticulationPoint.DorsalVelar:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
case ArticulationManner.Close:
case ArticulationManner.NearClose:
case ArticulationManner.CloseMid:
case ArticulationManner.Mid:
case ArticulationManner.OpenMid:
case ArticulationManner.NearOpen:
case ArticulationManner.Open:
return true;
default:
return false;
}
case ArticulationPoint.DorsalVelUlu:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
case ArticulationManner.Close:
case ArticulationManner.NearClose:
case ArticulationManner.CloseMid:
case ArticulationManner.Mid:
case ArticulationManner.OpenMid:
case ArticulationManner.NearOpen:
case ArticulationManner.Open:
return true;
default:
return false;
}
case ArticulationPoint.DorsalUvular:
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
case ArticulationManner.Close:
case ArticulationManner.NearClose:
case ArticulationManner.CloseMid:
case ArticulationManner.Mid:
case ArticulationManner.OpenMid:
case ArticulationManner.NearOpen:
case ArticulationManner.Open:
return true;
default:
return false;
}
case ArticulationPoint.RadicalPharyngeal:
switch (Manner)
{
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
return true;
default:
return false;
}
case ArticulationPoint.RadicalEpiglottal:
switch (Manner)
{
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
return true;
default:
return false;
}
case ArticulationPoint.Glottal:
switch (Manner)
{
case ArticulationManner.Stop:
case ArticulationManner.Fricative:
return true;
default:
return false;
}
default:
throw new Exception("Weird");
}
}
}
public void Standardise()
{
if (Shape == TongueShape.Sibilant)
{
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Close:
case ArticulationManner.NearClose:
case ArticulationManner.CloseMid:
case ArticulationManner.Mid:
case ArticulationManner.OpenMid:
case ArticulationManner.NearOpen:
case ArticulationManner.Open:
Shape = TongueShape.Central;
break;
}
switch (Point)
{
case ArticulationPoint.LabialLabial:
case ArticulationPoint.LabialDental:
case ArticulationPoint.CoronalLabial:
case ArticulationPoint.DorsalPalatal:
case ArticulationPoint.DorsalPalVel:
case ArticulationPoint.DorsalVelar:
case ArticulationPoint.DorsalVelUlu:
case ArticulationPoint.DorsalUvular:
case ArticulationPoint.RadicalPharyngeal:
case ArticulationPoint.RadicalEpiglottal:
case ArticulationPoint.Glottal:
Shape = TongueShape.Central;
break;
}
}
if (Shape == TongueShape.Lateral)
{
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Trill:
case ArticulationManner.Close:
case ArticulationManner.NearClose:
case ArticulationManner.CloseMid:
case ArticulationManner.Mid:
case ArticulationManner.OpenMid:
case ArticulationManner.NearOpen:
case ArticulationManner.Open:
Shape = TongueShape.Central;
break;
}
switch (Point)
{
case ArticulationPoint.LabialLabial:
case ArticulationPoint.LabialDental:
case ArticulationPoint.RadicalPharyngeal:
case ArticulationPoint.RadicalEpiglottal:
case ArticulationPoint.Glottal:
Shape = TongueShape.Central;
break;
}
}
if (Point == ArticulationPoint.DorsalPalVel)
{
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
Point = ArticulationPoint.DorsalPalatal;
break;
}
}
if (Point == ArticulationPoint.DorsalVelUlu)
{
switch (Manner)
{
case ArticulationManner.Closed:
case ArticulationManner.Stop:
case ArticulationManner.Flap:
case ArticulationManner.Trill:
case ArticulationManner.Fricative:
case ArticulationManner.Approximant:
Point = ArticulationPoint.DorsalUvular;
break;
}
}
}
public int Encode()
{
int enc = (int)Point;
enc += 16 * (int)Manner;
enc += 16 * 13 * (int)Shape;
enc += 16 * 13 * 3 * (int)Voice;
enc += 16 * 13 * 3 * 5 * (Rounded ? 1 : 0);
enc += 16 * 13 * 3 * 5 * 2 * (Nasal ? 1 : 0);
return enc;
}
public static Sound Decode(int enc)
{
Sound sound = new Sound();
int res = enc / (16 * 13 * 3 * 5 * 2);
sound.Nasal = res == 1;
enc -= res * (16 * 13 * 3 * 5 * 2);
res = enc / (16 * 13 * 3 * 5);
sound.Rounded = res == 1;
enc -= res * (16 * 13 * 3 * 5);
res = enc / (16 * 13 * 3);
sound.Voice = (Voice)res;
enc -= res * (16 * 13 * 3);
res = enc / (16 * 13);
sound.Shape = (TongueShape)res;
enc -= res * (16 * 13);
res = enc / 16;
sound.Manner = (ArticulationManner)res;
enc -= res * 16;
sound.Point = (ArticulationPoint)enc;
return sound;
}
public string Save()
{
return ToValueField().Save();
}
public ValueField ToValueField()
{
return new ValueField("Sound",
new ValueField("Point", Point.ToString()),
new ValueField("Manner", Manner.ToString()),
new ValueField("Shape", Shape.ToString()),
new ValueField("Rounded", Rounded.ToString()),
new ValueField("Nasal", Nasal.ToString()),
new ValueField("Voice", Voice.ToString()));
}
public void Load(string source)
{
Load(new ValueField(source));
}
public void Load(ValueField vf)
{
Point = NeaUtility.ParseEnum<ArticulationPoint>(vf["Point"].Value);
Manner = NeaUtility.ParseEnum<ArticulationManner>(vf["Manner"].Value);
Shape = NeaUtility.ParseEnum<TongueShape>(vf["Shape"].Value);
Rounded = NeaReader.ParseBoolean(vf["Rounded"].Value);
Nasal = NeaReader.ParseBoolean(vf["Nasal"].Value);
Voice = NeaUtility.ParseEnum<Voice>(vf["Voice"].Value);
}
public bool Equals(Sound other)
{
return Point == other.Point && Manner == other.Manner && Shape == other.Shape && Rounded == other.Rounded && Nasal == other.Nasal && Voice == other.Voice;
}
}
public enum ArticulationPoint
{
LabialLabial, LabialDental,
CoronalLabial, CoronalDental, CoronalAlveolar, CoronalPostAlveolar, CoronalRetroflex,
DorsalPostAlveolar, DorsalPalatal, DorsalPalVel, DorsalVelar, DorsalVelUlu, DorsalUvular, //Front, NearFront, Central, NearBack, Back
RadicalPharyngeal, RadicalEpiglottal, Glottal
}
public enum ArticulationManner
{
Closed, Stop, Flap, Trill, Fricative, Approximant,
Close, NearClose, CloseMid, Mid, OpenMid, NearOpen, Open
}
public enum TongueShape
{
Central, Lateral, Sibilant
}
public enum Voice
{
Aspirated, Voiceless, Breathy, Modal, Creaky //the first one is only for stops
}
}
|
4b13088b730c1a11778f4faf9363aa7369c4927b
|
C#
|
SneakyPeet/supermarketpricing
|
/Core/PricingModels/QuantityFreeForQuantityPricing.cs
| 3.328125
| 3
|
using System;
namespace Core.PricingModels
{
internal class QuantityFreeForQuantityPricing : IPricingModel
{
private readonly int quantityToBuy;
private readonly int quantityFree;
public QuantityFreeForQuantityPricing(int quantityToBuy, int quantityFree)
{
this.quantityToBuy = quantityToBuy;
this.quantityFree = quantityFree;
}
public int CalculatePrice(int cost, int quantity)
{
var itemsToCalculate = quantity;
var price = 0;
while(itemsToCalculate > 0)
{
if(itemsToCalculate <= quantityToBuy)
{
price += itemsToCalculate * cost;
itemsToCalculate = 0;
}
else
{
price += quantityToBuy * cost;
itemsToCalculate -= quantityToBuy;
if(itemsToCalculate > quantityFree)
{
itemsToCalculate -= quantityFree;
}
else
{
itemsToCalculate = 0;
}
}
}
return price;
}
public string PricingInUnits(string token, int factor, int cost)
{
return string.Format("{0} - Buy {1} For {2}", this.GetPricingInUnit(token, factor, cost), (this.quantityToBuy + this.quantityFree), this.GetPricingInUnit(token, factor, this.quantityToBuy * cost));
}
private string GetPricingInUnit(string token, int factor, int cost)
{
return token + ((decimal)cost / factor).ToString("0.00");
}
}
}
|
1d2a3d647c52169c882eb9feca34e4dc895c51c7
|
C#
|
PPaszkowski21/PoFlightSystem
|
/SystemRezerwacjiBiletówFirmyLotniczej/Flight.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SystemRezerwacjiBiletówFirmyLotniczej
{
public class Flight : ObjectID
{
public Route Route { get; set; }
public Airplane Airplane { get; set; }
public DateTime DepartureTime { get; set; }
public DateTime ArrivalTime { get; set; }
public List<Client> Clients { get; set; }
public Flight(FlightSystem flightSystem, Route route, DateTime departureTime)
{
this.Route = route;
this.Airplane = flightSystem.GetAirplane(route);
this.DepartureTime = departureTime;
this.ArrivalTime = departureTime.AddHours(CalculateTravelTimeHours());
}
public Flight(Flight flight, double days)
{
this.Route = flight.Route;
this.Airplane = flight.Airplane;
this.DepartureTime = flight.DepartureTime.AddDays(days);
this.ArrivalTime = flight.DepartureTime.AddDays(days).AddHours(CalculateTravelTimeHours());
}
double CalculateTravelTimeHours()
{
return Route.Distance / Airplane.Speed;
}
}
}
|
de24575394930066d978832a1102f6ab930b7327
|
C#
|
AnaBrando/EstruturaDados
|
/Pilha/Pilha/Program.cs
| 3.203125
| 3
|
using Domain;
using System;
using System.Collections.Generic;
namespace Pilha
{
class Program
{
static void Main(string[] args)
{
Stack<Aluno> minhaPilha = new Stack<Aluno>();
var opcao = 0;
var id = 0;
do
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Bem vindos a pilha!");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Digite a opção desejada");
Console.WriteLine("1- Cadastrar Aluno:");
Console.WriteLine("2- Cadastrar Nota do Aluno:");
Console.WriteLine("3- Ver Nota do Aluno:");
Console.WriteLine("4- Ver Nota não cadastrada do Aluno:");
Console.WriteLine("5- Buscar aluno pelo código");
Console.WriteLine("6- Excluir aluno");
Console.WriteLine("7- Ver Pilha");
opcao = Convert.ToInt32(Console.ReadLine());
switch (opcao)
{
case 1:
Console.WriteLine("Digite o código do aluno:");
id = Convert.ToInt32(Console.ReadLine());
minhaPilha.Push(new Aluno { Id = id });
Console.WriteLine("Aluno cadastrado com sucesso!");
break;
case 2:
Console.WriteLine("Digite o código do aluno:");
id = Convert.ToInt32(Console.ReadLine());
foreach (var aluno in minhaPilha)
{
if (aluno.Id == id)
{
Console.WriteLine("Digite a nota do aluno:");
var nota = Convert.ToDouble(Console.ReadLine());
if (nota > 0)
{
aluno.Nota = nota;
break;
}
else
{
Console.WriteLine("Nota não é maior que 0");
break;
}
}
Console.WriteLine("Aluno não encontrado");
break;
}
break;
case 3:
Console.WriteLine("Digite o código do aluno:");
id = Convert.ToInt32(Console.ReadLine());
foreach (var aluno in minhaPilha)
{
var notas = 0.0;
if (aluno.Nota > 0)
{
notas = +aluno.Nota;
}
if (aluno.Id == id)
{
if (aluno.Nota > 0)
{
Console.WriteLine("Média:" + (notas / minhaPilha.Count));
}
else
{
Console.WriteLine("Aluno sem nota");
break;
}
}
}
break;
case 4:
foreach (var item in minhaPilha)
{
if (item.Nota == 0)
{
Console.WriteLine($"Aluno {item.Id} sem nota: {item.Nota}");
}
}
break;
case 5:
Console.WriteLine("Digite o código do aluno:");
id = Convert.ToInt32(Console.ReadLine());
foreach (var item in minhaPilha)
{
if (item.Id == id)
{
Console.WriteLine($"[Aluno {item.Id} nota: {item.Nota}]");
}
}
break;
case 6:
minhaPilha.Pop();
break;
case 7:
foreach (var item in minhaPilha)
{
Console.WriteLine("[Aluno: " + item.Id + ", Nota: " + item.Nota + "]");
break;
}
Console.WriteLine("Pilha vazia");
break;
}
} while (opcao != 0);
}
}
}
|
2ab11aac064203a7738be43036260f94e85b5f98
|
C#
|
Dwayne75/WurmAssistant3
|
/src/Apps/WurmAssistant/WurmAssistant3/Areas/Granger/Creature.cs
| 2.65625
| 3
|
using System;
using System.Linq;
using System.Text.RegularExpressions;
using AldursLab.Essentials.Extensions.DotNet.Drawing;
using AldursLab.WurmAssistant3.Areas.Granger.DataLayer;
using JetBrains.Annotations;
namespace AldursLab.WurmAssistant3.Areas.Granger
{
public class Creature
{
static readonly System.Drawing.Color? DefaultBestBreedHintColor = (System.Drawing.Color)(new HslColor(120D, 240D, 180D));
readonly GrangerContext context;
readonly CreatureColorDefinitions creatureColorDefinitions;
readonly FormGrangerMain mainForm;
double? cachedBreedValue = null;
public Creature(
FormGrangerMain mainForm,
CreatureEntity entity,
GrangerContext context,
[NotNull] CreatureColorDefinitions creatureColorDefinitions)
{
if (creatureColorDefinitions == null) throw new ArgumentNullException(nameof(creatureColorDefinitions));
BreedHintColor = null;
this.mainForm = mainForm;
Entity = entity;
this.context = context;
this.creatureColorDefinitions = creatureColorDefinitions;
}
public CreatureEntity Entity { get; private set; }
public int Value => mainForm.CurrentValuator.GetValueForCreature(this);
public int PotentialPositiveValue => mainForm.CurrentValuator.GetPotentialPositiveValueForCreature(this);
public int PotentialNegativeValue => mainForm.CurrentValuator.GetPotentialNegativeValueForCreature(this);
double? BreedValue
{
get
{
var breedResults = mainForm.CurrentAdvisor.GetBreedingValue(this);
if (breedResults.HasValue)
{
if (breedResults.Value.Ignored) return null;
else if (breedResults.Value.Discarded) return double.NegativeInfinity;
else return breedResults.Value.Value;
}
else return null;
}
}
public double? CachedBreedValue => cachedBreedValue;
public void RebuildCachedBreedValue()
{
cachedBreedValue = BreedValue;
}
/// <summary>
/// Used to color entire row, null if no color set
/// </summary>
public System.Drawing.Color? BreedHintColor { get; private set; }
/// <summary>
/// Null if candidate is not best, else contains default best candidate color
/// </summary>
public System.Drawing.Color? CreatureBestCandidateColor { get; set; }
public void RefreshBreedHintColor(double minBreedValue, double maxBreedValue)
{
if (CachedBreedValue == maxBreedValue)
{
CreatureBestCandidateColor = DefaultBestBreedHintColor;
}
if (mainForm.SelectedSingleCreature != null)
{
BreedHintColor = mainForm.CurrentAdvisor.GetHintColor(this, minBreedValue, maxBreedValue);
}
}
public void ClearColorHints()
{
BreedHintColor = null;
CreatureBestCandidateColor = null;
}
public System.Drawing.Color? CreatureColorBkColor
{
get
{
CreatureColor hcolor = Color;
if (hcolor == CreatureColor.GetDefaultColor()) return null;
else return hcolor.SystemDrawingColor;
}
}
public CreatureTrait[] Traits
{
get { return Entity.Traits.ToArray(); }
set
{
Entity.Traits = value.ToList();
}
}
public override string ToString()
{
return Entity.ToString();
}
public CreatureColor Color
{
get { return creatureColorDefinitions.GetForId(Entity.CreatureColorId); }
set
{
Entity.CreatureColorId = value.CreatureColorId;
}
}
public Creature GetMate()
{
if (!HasMate()) return null;
var mate =
context.Creatures.Where(x => x.Id == this.Entity.PairedWith)
.Select(x => new Creature(mainForm, x, context, creatureColorDefinitions))
.ToArray();
if (mate.Length == 1)
return mate.First();
else if (mate.Length == 0)
return null;
else throw new Exception("duplicate creatures found?");
}
public bool HasMate()
{
if (this.Entity.PairedWith == null) return false;
else return true;
}
public void SetMate(Creature value)
{
if (value == null)
{
var mate = GetMate();
if (mate != null) mate.Entity.PairedWith = null;
this.Entity.PairedWith = null;
}
else
{
this.Entity.PairedWith = value.Entity.Id;
value.Entity.PairedWith = this.Entity.Id;
}
}
public bool IsMale
{
get { return (Entity.IsMale ?? false); }
set { Entity.IsMale = value; }
}
public DateTime NotInMoodUntil
{
get { return (Entity.NotInMood ?? DateTime.MinValue); }
set { Entity.NotInMood = value; }
}
public DateTime GroomedOn
{
get { return (Entity.GroomedOn ?? DateTime.MinValue); }
set { Entity.GroomedOn = value; }
}
public DateTime PregnantUntil
{
get { return (Entity.PregnantUntil ?? DateTime.MinValue); }
set { Entity.PregnantUntil = value; }
}
public DateTime BirthDate
{
get { return (Entity.BirthDate ?? DateTime.MinValue); }
set { Entity.BirthDate = value; }
}
public bool CheckTag(string name)
{
return Entity.CheckTag(name);
}
public void SetTag(string name, bool state)
{
Entity.SetTag(name, state);
}
public float TraitsInspectSkill
{
get { return Entity.TraitsInspectedAtSkill ?? 0; }
set { Entity.TraitsInspectedAtSkill = value; }
}
public bool EpicCurve
{
get { return Entity.EpicCurve ?? false; }
set { Entity.EpicCurve = value; }
}
public CreatureAge Age
{
get { return Entity.Age; }
set { Entity.Age = value; }
}
public string Name { get { return Entity.Name; } set { Entity.Name = value; } }
public string InnerName => GetInnerNameInfo(Entity.Name).InnerName;
public string Father { get { return Entity.FatherName; } set { Entity.FatherName = value; } }
public string Mother { get { return Entity.MotherName; } set { Entity.MotherName = value; } }
public string TakenCareOfBy { get { return Entity.TakenCareOfBy; } set { Entity.TakenCareOfBy = value; } }
public string BrandedFor { get { return Entity.BrandedFor; } set { Entity.BrandedFor = value; } }
public string Comments { get { return Entity.Comments; } set { Entity.Comments = value; } }
public string Herd
{
get { return Entity.Herd; }
set
{
if (this.Herd == value) return;
var targetHerd =
context.Creatures.Where(x => x.Herd == value)
.Select(x => new Creature(mainForm, x, context, creatureColorDefinitions));
foreach (var creature in targetHerd)
{
if (creature.IsNotUniquelyIdentifiableWhenComparedTo(this))
{
throw new Exception("can not change herd because nonunique creatures already exists in target herd");
}
}
Entity.Herd = value;
}
}
[CanBeNull]
public string ServerName
{
get { return Entity.ServerName; }
set { Entity.ServerName = value ?? string.Empty; }
}
public bool IsNotUniquelyIdentifiableWhenComparedTo(Creature other)
{
return !this.Entity.IsUniquelyIdentifiableWhenComparedTo(other.Entity);
}
public string HerdAspect => Entity.Herd;
public string NameAspect => Entity.Name;
public string FatherAspect => Entity.FatherName;
public string MotherAspect => Entity.MotherName;
public string TraitsAspect => CreatureTrait.GetShortString(Entity.Traits.ToArray(), mainForm.CurrentValuator);
public TimeSpan NotInMoodForAspect
{
get
{
if (!Entity.NotInMood.HasValue) return TimeSpan.MinValue;
else
{
return Entity.NotInMood.Value - DateTime.Now;
}
}
}
public TimeSpan PregnantForAspect
{
get
{
if (!Entity.PregnantUntil.HasValue) return TimeSpan.MinValue;
else
{
return Entity.PregnantUntil.Value - DateTime.Now;
}
}
}
public TimeSpan GroomedAgoAspect
{
get
{
if (!Entity.GroomedOn.HasValue) return TimeSpan.MaxValue;
else
{
return DateTime.Now - Entity.GroomedOn.Value;
}
}
}
public DateTime BirthDateAspect => Entity.BirthDate ?? DateTime.MinValue;
public TimeSpan ExactAgeAspect => !Entity.BirthDate.HasValue ? TimeSpan.MaxValue : DateTime.Now - Entity.BirthDate.Value;
public string GenderAspect => Entity.GenderAspect;
public string TakenCareOfByAspect => Entity.TakenCareOfBy;
public TraitsInspectedContainer TraitsInspectedAtSkillAspect
{
get
{
float val = Entity.TraitsInspectedAtSkill ?? 0;
return new TraitsInspectedContainer()
{
Skill = val,
EpicCurve = Entity.EpicCurve ?? false
};
}
}
public CreatureAge AgeAspect => this.Age;
public string ColorAspect
=> Entity.CreatureColorId == CreatureColorId.Unknown ? string.Empty : Color.ToString();
public string TagsAspect { get { return string.Join(", ", Entity.SpecialTags.OrderBy(x => x)); } }
public string CommentsAspect => Entity.Comments;
public int ValueAspect => this.Value;
public string PotentialValueAspect
{
get
{
int potPositive = PotentialPositiveValue;
int potNegative = PotentialNegativeValue;
return string.Format("{0}, {1}",
potPositive > 0 ? "+" + potPositive.ToString() : potPositive.ToString(),
potNegative.ToString());
}
}
public double? BreedValueAspect => this.CachedBreedValue;
public string PairedWithAspect
{
get
{
Creature mate = GetMate();
if (mate == null) return string.Empty;
return mate.ToString();
}
}
public string BrandedForAspect => Entity.BrandedFor ?? string.Empty;
public string ServerAspect => Entity.ServerName ?? "-Unknown-";
public override bool Equals(System.Object obj)
{
if (obj == null)
{
return false;
}
Creature p = obj as Creature;
if ((System.Object)p == null)
{
return false;
}
return this.Entity.Id == p.Entity.Id;
}
public bool Equals(Creature p)
{
if ((object)p == null)
{
return false;
}
return this.Entity.Id == p.Entity.Id;
}
public override int GetHashCode()
{
return this.Entity.Id;
}
public static bool operator ==(Creature a, Creature b)
{
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
if (((object)a == null) || ((object)b == null))
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(Creature a, Creature b)
{
return !(a == b);
}
public bool NotInMood => this.NotInMoodUntil > DateTime.Now;
public bool Pregnant => this.PregnantUntil > DateTime.Now;
public bool PregnantInLast24H => this.PregnantUntil > DateTime.Now - TimeSpan.FromHours(24);
internal bool IsInbreedWith(Creature otherCreature)
{
if ( Name == otherCreature.Mother
|| Name == otherCreature.Father
|| Mother == otherCreature.Name
|| Father == otherCreature.Name
|| (!string.IsNullOrEmpty(Mother) && Mother == otherCreature.Mother)
|| (!string.IsNullOrEmpty(Father) && Father == otherCreature.Father))
return true;
else return false;
}
internal bool IsFoal()
{
return Age.CreatureAgeId == CreatureAgeId.YoungFoal || Age.CreatureAgeId == CreatureAgeId.AdolescentFoal;
}
public static InnerCreatureNameInfo GetInnerNameInfo(string name)
{
var match = Regex.Match(name, @"'(.+)'", RegexOptions.Compiled);
if (match.Success)
{
return new InnerCreatureNameInfo()
{
HasInnerName = true,
InnerName = match.Groups[1].Value
};
}
else
{
return new InnerCreatureNameInfo()
{
HasInnerName = false,
InnerName = string.Empty
};
}
}
public DateTime SmilexamineLastDate
{
get { return (Entity.SmilexamineLastDate ?? DateTime.MinValue); }
set { Entity.SmilexamineLastDate = value; }
}
}
}
|
cf944065151931b23d2d013f0bdc623c6c7ba4c6
|
C#
|
nimazein/LABA-12
|
/LABA 12/LABA 12 v2/Program.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LABA_12_v2
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
Console.Write("Размер коллекции: ");
int size = 0;
try
{
size = Convert.ToInt32(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
Environment.Exit(0);
}
TestCollections collections = new TestCollections(size);
Console.WriteLine("Коллекция создана");
Console.WriteLine();
Console.WriteLine("Заполним коллекцию!");
Console.Write("Желаемое количество объектов: ");
int numberOfObjects = 0;
try
{
numberOfObjects = Convert.ToInt32(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
Environment.Exit(0);
}
if (numberOfObjects > size)
{
throw new OutOfRangeException("В коллекцию не поместится столько объектов");
}
collections.FillRandomly(numberOfObjects);
Console.WriteLine("Коллекция заполнена");
Console.WriteLine();
Console.ReadKey();
Console.Clear();
Console.WriteLine("Тестирование метода Contains для коллекции StringValue");
Console.WriteLine();
Console.WriteLine("Время поиска первого элемента: ");
collections.Contains(collections.StringValue[0]);
Console.WriteLine("Время поиска среднего элемента: ");
collections.Contains(collections.StringValue[numberOfObjects / 2]);
Console.WriteLine("Время поиска последнего элемента: ");
collections.Contains(collections.StringValue[numberOfObjects - 1]);
Console.WriteLine("Время поиска несуществующего элемента: ");
collections.Contains("я строка");
Console.ReadKey();
Console.WriteLine("Тестирование метода Contains для коллекции AnimalValue");
Console.WriteLine();
Console.WriteLine("Время поиска первого элемента: ");
collections.Contains(collections.AnimalValue[0]);
Console.WriteLine("Время поиска среднего элемента: ");
collections.Contains(collections.AnimalValue[numberOfObjects / 2]);
Console.WriteLine("Время поиска последнего элемента: ");
collections.Contains(collections.AnimalValue[numberOfObjects - 1]);
Console.WriteLine("Время поиска несуществующего элемента: ");
collections.Contains(new KingdomAnimals(80, "Человек"));
Console.ReadKey();
Console.WriteLine("Тестирование метода ContainsKey для коллекции StringKeyMammalValue");
Console.WriteLine();
Console.WriteLine("Время поиска первого элемента: ");
collections.ContainsKey(collections.StringValue[0]);
Console.WriteLine("Время поиска среднего элемента: ");
collections.ContainsKey(collections.StringValue[numberOfObjects / 2]);
Console.WriteLine("Время поиска последнего элемента: ");
collections.ContainsKey(collections.StringValue[numberOfObjects - 1]);
Console.WriteLine("Время поиска несуществующего элемента: ");
collections.ContainsKey("я строка");
Console.ReadKey();
Console.WriteLine("Тестирование метода ContainsKey для коллекции AnimalKeyMammalValue");
Console.WriteLine();
Console.WriteLine("Время поиска первого элемента: ");
collections.ContainsKey(collections.AnimalValue[0]);
Console.WriteLine("Время поиска среднего элемента: ");
collections.ContainsKey(collections.AnimalValue[numberOfObjects / 2]);
Console.WriteLine("Время поиска последнего элемента: ");
collections.ContainsKey(collections.AnimalValue[numberOfObjects - 1]);
Console.WriteLine("Время поиска несуществующего элемента: ");
collections.ContainsKey(new KingdomAnimals(80, "Человек"));
Console.ReadKey();
Console.WriteLine("Тестирование метода ContainsValue для коллекции AnimalKeyMammalValue");
Console.WriteLine();
Console.WriteLine("Время поиска первого элемента: ");
string key = collections.StringValue[0];
collections.ContainsValue(collections.StringKeyMammalValue[key]);
Console.WriteLine("Время поиска среднего элемента: ");
string keyMiddle = collections.StringValue[numberOfObjects / 2];
collections.ContainsValue(collections.StringKeyMammalValue[keyMiddle]);
Console.WriteLine("Время поиска последнего элемента: ");
string keyEnd = collections.StringValue[numberOfObjects - 1];
collections.ContainsValue(collections.StringKeyMammalValue[keyEnd]);
Console.WriteLine("Время поиска несуществующего элемента: ");
collections.ContainsValue(new ClassMammals(7,12,5,"Кошка"));
Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Демонстрация метода Remove");
Random rnd = new Random();
int delIdx = rnd.Next(0, numberOfObjects);
string delKey = collections.StringValue[rnd.Next(delIdx)];
collections.Remove(collections.StringKeyMammalValue[delKey]);
Console.WriteLine($"Объект с индексом {delIdx} и ключом {delKey} был удален");
Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Демонстрация работы исключений");
Console.Write("Индекс искомого объекта: ");
int index = 0;
try
{
index = Convert.ToInt32(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
Environment.Exit(0);
}
collections.GetByIndex(index);
}
}
}
|
72f8903413cc201f56126c1cd832180b2a797b82
|
C#
|
ngc2392/CSharpLab
|
/Assignment3/Enumerations.cs
| 3.640625
| 4
|
using System;
namespace Assignment3 {
enum VolumeLevels {
low = 1,
medium = 2,
high = 3
}
class Enumerations {
static void Main (string[] args) {
Console.WriteLine ("Please enter a number from 1-3");
int userInput = Convert.ToInt32 (Console.ReadLine ());
string userChoice = ProcessUserInput (userInput);
if (userChoice != "ERROR") {
Console.WriteLine ("You choose " + userChoice);
} else {
Console.WriteLine ("Please enter correct input");
}
}
static public string ProcessUserInput (int input) {
String choice = "";
switch (input) {
case 1:
choice = Enum.GetName (typeof (VolumeLevels), 1);
return choice;
case 2:
choice = Enum.GetName (typeof (VolumeLevels), 2);
return choice;
case 3:
choice = Enum.GetName (typeof (VolumeLevels), 3);
return choice;
default:
return "ERROR";
}
}
}
}
|
efb11d7a10d77fb2a886d34c240631d1fb83bf15
|
C#
|
shuningzhou/Ruffles
|
/Ruffles/Core/SocketManager.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Threading;
using Ruffles.Configuration;
namespace Ruffles.Core
{
/// <summary>
/// A socket manager that can run Ruffles in a threaded mode.
/// </summary>
public class SocketManager
{
private readonly List<RuffleSocket> _sockets = new List<RuffleSocket>();
private Thread _thread;
/// <summary>
/// The thread lock that has to be grabbed to modify the underlying connections when running in threaded mode.
/// Modifications includes all connection APIs.
/// </summary>
/// <value>The object to lock.</value>
public object ThreadLock { get; } = new object();
/// <summary>
/// Gets a value indicating whether this <see cref="T:Ruffles.Core.RufflesManager"/> is threaded.
/// </summary>
/// <value><c>true</c> if is threaded; otherwise, <c>false</c>.</value>
public bool IsThreaded { get; }
/// <summary>
/// Gets a value indicating whether this <see cref="T:Ruffles.Core.RufflesManager"/> is running.
/// </summary>
/// <value><c>true</c> if is running; otherwise, <c>false</c>.</value>
public bool IsRunning { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="T:Ruffles.Core.RufflesManager"/> class.
/// </summary>
/// <param name="threaded">If set to <c>true</c> threaded.</param>
public SocketManager(bool threaded = true)
{
this.IsThreaded = threaded;
}
/// <summary>
/// Init this manager instance.
/// </summary>
public void Init()
{
if (IsRunning)
{
throw new InvalidOperationException("Manager is already started");
}
IsRunning = true;
if (IsThreaded)
{
_thread = new Thread(() =>
{
while (IsRunning)
{
RunAllInternals();
}
});
_thread.Start();
}
}
/// <summary>
/// Stops this instance.
/// </summary>
public void Shutdown()
{
if (!IsRunning)
{
throw new InvalidOperationException("Manager is not started");
}
IsRunning = false;
if (IsThreaded)
{
_thread.Join();
}
}
private void RunAllInternals()
{
if (!IsRunning)
{
throw new InvalidOperationException("Manager is not started");
}
for (int i = 0; i < _sockets.Count; i++)
{
if (IsThreaded)
{
lock (ThreadLock)
{
_sockets[i].RunInternalLoop();
}
}
else
{
_sockets[i].RunInternalLoop();
}
}
}
/// <summary>
/// Adds a local socket to the manager.
/// </summary>
/// <returns>The local socket.</returns>
/// <param name="config">The socket configuration.</param>
public RuffleSocket AddSocket(SocketConfig config)
{
if (!IsRunning)
{
throw new InvalidOperationException("Manager is not started");
}
RuffleSocket socket = new RuffleSocket(config);
if (IsThreaded)
{
lock (ThreadLock)
{
_sockets.Add(socket);
}
}
else
{
_sockets.Add(socket);
}
return socket;
}
/// <summary>
/// Runs all the internals. Only usable when not using a threaded manager.
/// Calling this is not neccecary, the PollAllSockets will do it for you.
/// </summary>
public void RunInternals()
{
if (!IsRunning)
{
throw new InvalidOperationException("Manager is not started");
}
if (IsThreaded)
{
throw new InvalidOperationException("Cannot run the internals when using a threaded manager");
}
RunAllInternals();
}
/// <summary>
/// Runs all the internals and polls all the sockets for events.
/// </summary>
/// <returns>The first event.</returns>
public NetworkEvent PollAllSockets()
{
if (!IsRunning)
{
throw new InvalidOperationException("Manager is not started");
}
if (!IsThreaded)
{
RunInternals();
}
if (IsThreaded)
{
lock (ThreadLock)
{
for (int i = 0; i < _sockets.Count; i++)
{
NetworkEvent @event = _sockets[i].Poll();
if (@event.Type != NetworkEventType.Nothing)
{
return @event;
}
}
}
}
else
{
for (int i = 0; i < _sockets.Count; i++)
{
NetworkEvent @event = _sockets[i].Poll();
if (@event.Type != NetworkEventType.Nothing)
{
return @event;
}
}
}
return new NetworkEvent()
{
Connection = null,
Socket = null,
Data = new ArraySegment<byte>(),
AllowUserRecycle = false,
InternalMemory = null,
Type = NetworkEventType.Nothing,
ChannelId = 0,
SocketReceiveTime = DateTime.Now
};
}
}
}
|
7753e78f293024df41921249c3e5226edf264e2a
|
C#
|
HaydenroborrRIT/CsharpPlayersGuide
|
/HelloWorld/Program.cs
| 3.640625
| 4
|
using System;
/*
Console.WriteLine("Hello!");
string firstName = "Hayden ";
string lastName = "Orr";
string name = firstName + lastName;
Console.WriteLine("My name is " + name);
Console.WriteLine("I'm still new at this but I\'m here to learn!");
Console.WriteLine("Please tell me more about how I can help all of you!");
Console.WriteLine("Tell me!"); */
/*
Console.WriteLine("Bread is ready. \n Who is the bread for?");
string yourName = Console.ReadLine();
Console.WriteLine("Noted: " + yourName + " got bread."); */
//Ask user for description of the thing
Console.WriteLine("What kind of thing are we talking about?");
string thing = Console.ReadLine();
//Ask user for the adjective
Console.WriteLine("How would you describe it? Big? Aure? Tattered?");
string adj = Console.ReadLine();
//Combine description with adjective and print
string closer = "of Doom 3000";
Console.WriteLine("The {0} {1} {2}!", adj, thing, closer);
Console.WriteLine("The " + adj + " " + thing + closer + "!");
|
e655bd6bb59c3d62311ba9adb48b5bcc0e1fbab6
|
C#
|
wujia6/ExamOnline
|
/Infrastructure/Utils/RouteConvention.cs
| 2.53125
| 3
|
using System.Linq;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Routing;
namespace Infrastructure.Utils
{
/// <summary>
/// 添加全局路由统一前缀
/// </summary>
public class RouteConvention : IApplicationModelConvention
{
private readonly AttributeRouteModel _centralPrefix;
public RouteConvention(IRouteTemplateProvider routeTemplateProvider)
{
this._centralPrefix = new AttributeRouteModel(routeTemplateProvider);
}
//实现接口
public void Apply(ApplicationModel application)
{
//循环所有controller
foreach (var controller in application.Controllers)
{
//已标记的RouteAttribute的controller
var matcheds = controller.Selectors.Where(x => x.AttributeRouteModel != null).ToList();
if (matcheds.Any())
{
foreach (var selectorModel in matcheds)
{
//当前路由前添加路由前缀
selectorModel.AttributeRouteModel = AttributeRouteModel
.CombineAttributeRouteModel(this._centralPrefix, selectorModel.AttributeRouteModel);
}
}
//未标记的RouteAttribute的controller
var unMatcheds = controller.Selectors.Where(x => x.AttributeRouteModel == null).ToList();
if (unMatcheds.Any())
{
foreach (var selectModel in unMatcheds)
{
//当前路由前添加路由前缀
selectModel.AttributeRouteModel = this._centralPrefix;
}
}
}
}
}
}
|
c4fc414e0ebee3d6dbb761e43d2776b4b3f35ac9
|
C#
|
Niccktor/Slam-C-
|
/Bonhomme qui bouge/Program.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bonhomme_qui_bouge
{
class Program
{
private static void Main(string[] args)
{
int x = 0;
int y = 0;
int largeur = 40;
int longueur = 22;
Console.WriteLine(@" . , ");
Console.WriteLine(@" '. '. \ \ ");
Console.WriteLine(@" ._ '-.'. `\ \ ");
Console.WriteLine(@" '-._; .'; `-.'. ");
Console.WriteLine(@" `~-.; '. '. ");
Console.WriteLine(@" '--,` '. ");
Console.WriteLine(@" -='. ; ");
Console.WriteLine(@" .--=~~=-, -.; ; ");
Console.WriteLine(@" .-=`; `~,_.; / ");
Console.WriteLine(@"` ,-`' .-; | ");
Console.WriteLine(@" .-~`. .; ; ");
Console.WriteLine(@" .;.- .-; ,\ ");
Console.WriteLine(@" `.' ,=; .-' `~.-._");
Console.WriteLine(@" .'; .'; .' .' '-. ");
Console.WriteLine(@" .\ ; ; ,.' _ a', ");
Console.WriteLine(" .'~\"; -` ; ; \"~` `'-=.) ");
Console.WriteLine(@" .' .' . _; ;', ;");
Console.WriteLine(@" '-.._`~`.' \ ; ; : ");
Console.WriteLine(@" `~' _'\\_ \\_ ");
Console.WriteLine(" /=`^^=`\"\"/`)-. ");
Console.WriteLine(@" \ = _ = =\ ");
Console.WriteLine(@" `""` `~-. = ;");
while (true)
{
ConsoleKeyInfo info = Console.ReadKey(true);
switch (info.Key)
{
case ConsoleKey.Q:
if (x > 0)
{
Console.MoveBufferArea(x, y, largeur, longueur, x - 1, y);
x--;
}
break;
case ConsoleKey.D:
if (x < Console.WindowWidth - largeur)
{
Console.MoveBufferArea(x, y, largeur, longueur, x + 1, y);
x++;
}
break;
case ConsoleKey.Z:
if (y > 0)
{
Console.MoveBufferArea(x, y, largeur, longueur, x, y - 1);
y--;
}
break;
case ConsoleKey.S:
Console.MoveBufferArea(x, y, largeur, longueur, x, y + 1);
y++;
break;
}
if (info.Key == ConsoleKey.Backspace)
break;
}
}
}
}
|
f582aa8788497e6d08dc552e3e77227efcbacd22
|
C#
|
kbarov/SoftUniExamsAndExercises
|
/ProgrammingFundamentalsCSharp/Exercises/StringsAndTextProcessingExercises/06.SentenceSplit/SentenceSplit.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _06.SentenceSplit
{
class SentenceSplit
{
static void Main(string[] args)
{
string input = Console.ReadLine();
string delimiter = Console.ReadLine();
string[] result = input.Split(new string[] { delimiter },
StringSplitOptions.None);
Console.WriteLine("["+string.Join(", ",result)+"]");
}
}
}
|
1b23345a79ef30f89ddaff22a84a1fde89de3c50
|
C#
|
OlgaBikova/CSharpCourse
|
/2_lesson/CSharpSyntax/7_Enums/Program.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpSyntax
{
class Program
{
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
enum Season
{
Winter = 2, // every next element will be increased by 1
Spring, // has value 3
Summer = 7,
Autumn //has value 8
}
////You cant use string as value for enums
//enum Cars
//{
// Mazda = "MX5",
// Renault = "Koleos",
// Bmw = "M5"
//}
//Display attribute
enum Cars
{
[Display(Name = "Mazda MX5")]
Mazda = 1,
[Display(Name = "Renault Koleos")]
Renault = 2,
[Display(Name = "BMW M5")]
Bmw = 3
}
enum Colors { Red, Green, Blue, Yellow };
enum Status { Active, Inactive, Draft }
static void Main(string[] args)
{
//Days WeekdayStart = Days.Mon;
//int WeekdayEnd = (int)Days.Fri;
//Console.WriteLine("Monday: {0}", WeekdayStart);
//Console.WriteLine("Friday: {0}", WeekdayEnd);
//Console.WriteLine("");
//int winter = (int)Season.Winter;
//int spring = (int)Season.Spring;
//int summer = (int)Season.Summer;
//int autumn = (int)Season.Autumn;
//Console.WriteLine("winter: {0}", winter);
//Console.WriteLine("spring: {0}", spring);
//Console.WriteLine("summer: {0}", summer);
//Console.WriteLine("autumn: {0}", autumn);
//Console.WriteLine("");
//int operationEnum;
//Console.WriteLine("Add: {0}", operationEnum = (int)OperationEnum.Add);
//Console.WriteLine("Substract: {0}", operationEnum = (int)OperationEnum.Subtract);
//Console.WriteLine("None: {0}", operationEnum = (int)OperationEnum.None);
//Console.WriteLine("Percentage: {0}", operationEnum = (int)OperationEnum.divide);
//Console.WriteLine("");
//MathOperations.MathOp(5, 7, OperationEnum.None);
//Get Enum String values
Console.WriteLine("Enum to string {0}", Cars.Bmw.ToString());
Console.WriteLine("Enum display value {0}", EnumHelper<Cars>.GetDisplayValue(Cars.Mazda));
var displayedValue = EnumHelper<Cars>.GetDisplayValue(Cars.Mazda);
Console.WriteLine("Enum value from decsription {0}", EnumHelper<Cars>.GetValueFromDescription<Cars>(displayedValue));
//Enum Parse
string carName = "Mazda";
int carNumber = 9; //try with 9
Console.WriteLine("Enum parsing {0}", Enum.Parse(typeof(Cars), carName));
Console.WriteLine("Enum parsing {0}", Enum.Parse(typeof(Cars), carNumber.ToString())); //int should be converted to string
string carName2 = "RENAULT";
Console.WriteLine("Enum parsing ignoring case {0}", Enum.Parse(typeof(Cars), carName2, true));
//Console.WriteLine("Enum parsing using case{0}", Enum.Parse(typeof(Cars), carName2, false));
//Enum.GetValues
Console.WriteLine("Car values:");
foreach (var carValue in Enum.GetValues(typeof(Cars)))
{
Console.WriteLine((int)carValue);
}
//Enum GetName
Console.WriteLine("The 4th value of the Colors Enum is {0}", Enum.GetName(typeof(Colors), 3));
//Enum GetNames
Console.WriteLine("List of statuses:");
foreach (var status in Enum.GetNames(typeof(Status)))
{
Console.WriteLine(status);
}
Console.ReadKey();
}
}
}
|
7e9ac900094678c198eb2c8b010938e25a3bea40
|
C#
|
Ripiter/TestingCodeConsoleApp
|
/TestingCodeConsoleApp/SaveAndLoadForRpg/Player.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestingCodeConsoleApp
{
enum PlayerType
{
Hero,
Demon,
Undead
}
class Player
{
public string CurrectChapter { get; set; }
public string Name
{
get { return name; }
set { name = value; }
}
public int Hp
{
get { return hp; }
set { hp = value; }
}
public int Mana
{
get { return mana; }
set { mana = value; }
}
public int CritChance
{
get { return critChance; }
set { critChance = value; }
}
private string name;
private int hp;
private int mana;
private int critChance;
public Inventory Inventory
{
get { return inventory; }
set { inventory = value; }
}
Inventory inventory;
public void AddItemToInventory(Item item)
{
inventory.AddItemToList(item);
}
private PlayerType typeOfPlayer;
public PlayerType TypeOfPlayer
{
get { return typeOfPlayer; }
set { typeOfPlayer = value; }
}
public Player(string name, int hp, int mana, int critChance, PlayerType type)
{
inventory = new Inventory();
TypeOfPlayer = type;
//inventory.AddedToList += AddToPlayerInvetory;
Name = name;
Hp = hp;
Mana = mana;
CritChance = critChance;
}
}
}
|
969b36f0a7731523e0273910c1cbf02ff776808d
|
C#
|
jariz/CorsairGTA
|
/Lightings/WastedLighting.cs
| 2.609375
| 3
|
using CUE.NET.Devices.Keyboard;
using GTA;
using System.Drawing;
using CUE.NET.Brushes;
using System.Collections.Generic;
namespace CorsairGTA
{
class WastedLighting : Lighting
{
public override string Name()
{
return "Wasted";
}
public override string Description()
{
return "Indicates when you are 'wasted', aka\ndeath with a flashing red color on\nyour keyboard.";
}
//UIText debugText = new UIText("INIT!!!!!", new Point(10, 10), 0.4f, Color.WhiteSmoke, 0, false);
public WastedLighting()
{
Tick += HealthLighting_Tick;
}
private void HealthLighting_Tick(CorsairKeyboard keyboard)
{
//debugText.Draw();
if (Game.Player.Character.IsInjured)
{
isActive = true;
var brush = new SolidColorBrush(Color.Red);
int modifier = 50;
brush.Brightness = (float)TickNum / (float)modifier;
if(TickNum > modifier)
{
brush.Brightness = 2f + (brush.Brightness * -1);
}
if(TickNum > (modifier * 2))
{
TickNum = 0;
}
//debugText.Caption = "brightness: " + Convert.ToString(brush.Brightness) + " tick: " + TickNum;
keyboard.Brush = brush;
UsedBrushes = new List<IBrush>();
UsedBrushes.Add(keyboard.Brush);
}
else
{
if(isActive)
{
isActive = false;
CorsairGTA.ClearKeyboard(keyboard);
}
}
}
}
}
|
1f79cbfc338cdaa71bd6033d72039bf5f8e495fe
|
C#
|
sureshballa/xamarin-realtors-app
|
/Realtors/PropertyCell.cs
| 2.53125
| 3
|
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
using System.Threading.Tasks;
using System.Net.Http;
namespace Realtors
{
partial class PropertyCell : UITableViewCell
{
private Property _property;
public Property Property {
set {
this._property = value;
refreshUI ();
}
}
public PropertyCell (IntPtr handle) : base (handle)
{
}
private async void refreshUI()
{
this.Address.Text = this._property.Address;
this.Summary.Text = "Beds: " + this._property.Beds + ", Baths: " + this._property.Baths;
var taskResult = await this.LoadImage(this._property.Image);
this.PropertyImage.Image = taskResult;
}
private async Task<UIImage> LoadImage (string imageUrl)
{
var httpClient = new HttpClient();
Task<byte[]> contentsTask = httpClient.GetByteArrayAsync (imageUrl);
var contents = await contentsTask;
return UIImage.LoadFromData (NSData.FromArray (contents));
}
}
}
|
99f24a12e5ff0f276a608ef81cf7e8b7c5f0bbfb
|
C#
|
HelgeStenstrom/csProject2017
|
/Vinbank/Winecellar/WineManager.cs
| 3.34375
| 3
|
//WineManager.cs
//Ann-Marie Bergström ai2436
//2018
using System;
using System.Collections.Generic;
using System.Linq;
namespace Winecellar
{
/// <summary>
/// Handles the list of wines in this program
/// </summary>
public class WineManager
{
#region Fields
private List<Wine> wines; //declare list of wine
/// <summary>
/// Events that are sent when wines are added, changed or removed from the list.
/// </summary>
public event EventHandler<WineEventArgs> WineChanged_handlers;
#endregion Fields
#region Properties
/// <summary>
/// Property returning number of wines
/// Only read access
/// </summary>
public int WineCount
{
get => wines.Count;
}
/// <summary>
/// The count of empty bottles in the list (bottles that have been consumed)
/// </summary>
private int EmptyBottles => wines.Count(wine => wine.IsConsumed);
/// <summary>
/// The count of full bottles in the list.
/// </summary>
private int FullBottles => wines.Count(wine => !wine.IsConsumed);
/// <summary>
/// The count of full bottles of white wine in the list.
/// </summary>
private int FullWhites => wines.Count(wine => !wine.IsConsumed && (wine is WhiteWine));
/// <summary>
/// The count of full bottles of red wine in the list. Traditional implementation.
/// </summary>
private int FullReds
{
get
{
int count = 0;
foreach (var wine in wines)
{
if (!wine.IsConsumed && (wine is RedWine))
{
count++;
}
}
return count;
}
}
#endregion Properties
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public WineManager()
{
wines = new List<Wine>(); //create list of wines
}
#endregion Constructors
#region Methods
/// <summary>
/// Add a wine to the wine cellar
/// </summary>
/// <param name="wineIn"></param>
public void AddWine(Wine wineIn)
{
Wine wineObj = wineIn.Clone(); //declare and create wine object
wines.Add(wineObj);
OnWineChangedSender("Adding wine");
}
/// <summary>
/// Remove wine from wine cellar
/// </summary>
/// <param name="index"></param>
public bool RemoveWine(int index)
{
if (CheckIndex(index))
{
wines.RemoveAt(index);
OnWineChangedSender("Removing wine");
return true;
}
else
return false;
}
/// <summary>
/// Change an existing wine
/// </summary>
/// <param name="wine">Wine to replace the wine at the index</param>
/// <param name="index">Index of the wine to be replaced</param>
public bool ChangeWine(Wine wine, int index)
{
if (CheckIndex(index))
{
wines[index] = wine;
OnWineChangedSender("Changing wine");
return true;
}
else
return false;
}
/// <summary>
/// Get the details of an existing wine
/// </summary>
/// <param name="index"></param>
public Wine GetWine(int index)
{
if (CheckIndex(index))
return wines[index].Clone();
else throw new IndexOutOfRangeException();
}
/// <summary>
/// Check if index is valid
/// </summary>
/// <param name="index"></param>
private bool CheckIndex(int index)
{
if (index > -1 && index < WineCount)
return true;
else
return false;
}
/// <summary>
/// Construct texts for the wine table that is used in the MainForm.
/// One list item per wine, each item being a string array of table cells.
/// </summary>
public List<String[]> WinesAsRows
{
get
{
List<string[]> listOfCellsForOneRow = new List<string[]>();
foreach (var wine in wines)
{
listOfCellsForOneRow.Add(wine.RowStrings);
}
return listOfCellsForOneRow;
}
}
/// <summary>
/// clear list
/// </summary>
public void ClearList()
{
wines.Clear();
}
#region serialize functions
/// <summary>
/// Serialize the wine manager into a binary file
/// </summary>
/// <param name="binFileName">name of the file to save to</param>
public void BinarySerialize(string binFileName)
{
Serializer.Serialize(binFileName, wines);
}
/// <summary>
/// Read in a previously saved file with wine manager data. Replaces the current content of the wine manager.
/// </summary>
/// <param name="binFileName"></param>
public void BinaryDeSerialize(string binFileName)
{
wines = Serializer.DeSerialize<List<Wine>>(binFileName);
}
#endregion serialize functions
/// <summary>
/// Called to send an event containing a text message.
/// </summary>
/// <param name="message">The message to send</param>
private void OnWineChangedSender(string message)
{
if (WineChanged_handlers != null)
{
var msg = $"Det finns {WineCount} flaskor vin i källaren, varav {FullBottles} är fulla, varav {FullReds} är röda.";
WineChanged_handlers(this, new WineEventArgs(){Message = msg, When = DateTime.Now});
}
}
#endregion Methods
}
}
|
c40198fa11210ad1d86427e61f31357b9c8a3088
|
C#
|
hiepxuan2008/ChessBattle3DUnity
|
/Assets/Scripts/Chessman/Pawn.cs
| 2.53125
| 3
|
using UnityEngine;
using System.Collections;
using System;
public class Pawn : Chessman {
public override string Annotation()
{
return "P";
}
public override bool[,] PossibleEat()
{
bool[,] moves = new bool[8, 8];
Chessman c1;
// white team moves
if (isWhite)
{
// Diagonal left
if (CurrentX != 0 && CurrentY != 7)
{
c1 = BoardManager.Instance.Chessmans[CurrentX - 1, CurrentY + 1];
if (c1 == null)
{
moves[CurrentX - 1, CurrentY + 1] = true;
}
}
// Diagonal right
if (CurrentX != 7 && CurrentY != 7)
{
c1 = BoardManager.Instance.Chessmans[CurrentX + 1, CurrentY + 1];
if (c1 == null)
{
moves[CurrentX + 1, CurrentY + 1] = true;
}
}
}
else
{
// Diagonal left
if (CurrentX != 0 && CurrentY != 0)
{
c1 = BoardManager.Instance.Chessmans[CurrentX - 1, CurrentY - 1];
if (c1 == null)
{
moves[CurrentX - 1, CurrentY - 1] = true;
}
}
// Diagonal right
if (CurrentX != 7 && CurrentY != 0)
{
c1 = BoardManager.Instance.Chessmans[CurrentX + 1, CurrentY - 1];
if (c1 == null)
{
moves[CurrentX + 1, CurrentY - 1] = true;
}
}
}
return moves;
}
public override bool[,] PossibleMove()
{
bool[,] moves = new bool[8, 8];
int[] e = BoardManager.Instance.EnPassantMove;
Chessman c1, c2;
// white team moves
if (isWhite)
{
// Diagonal left
if (CurrentX != 0 && CurrentY != 7)
{
if (e[0] == CurrentX - 1 && e[1] == CurrentY + 1)
moves[CurrentX - 1, CurrentY + 1] = true;
c1 = BoardManager.Instance.Chessmans[CurrentX - 1, CurrentY + 1];
if (c1 != null && !c1.isWhite)
{
moves[CurrentX - 1, CurrentY + 1] = true;
}
}
// Diagonal right
if (CurrentX != 7 && CurrentY != 7)
{
if (e[0] == CurrentX + 1 && e[1] == CurrentY + 1)
moves[CurrentX + 1, CurrentY + 1] = true;
c1 = BoardManager.Instance.Chessmans[CurrentX + 1, CurrentY + 1];
if (c1 != null && !c1.isWhite)
{
moves[CurrentX + 1, CurrentY + 1] = true;
}
}
// Middle
if (CurrentY != 7)
{
c1 = BoardManager.Instance.Chessmans[CurrentX, CurrentY + 1];
if (c1 == null)
{
moves[CurrentX, CurrentY + 1] = true;
}
}
// Middle on first move
if (CurrentY == 1)
{
c1 = BoardManager.Instance.Chessmans[CurrentX, CurrentY + 1];
c2 = BoardManager.Instance.Chessmans[CurrentX, CurrentY + 2];
if (c1 == null && c2 == null)
{
moves[CurrentX, CurrentY + 2] = true;
}
}
} else
{
// Diagonal left
if (CurrentX != 0 && CurrentY != 0)
{
if (e[0] == CurrentX - 1 && e[1] == CurrentY + 1)
moves[CurrentX - 1, CurrentY - 1] = true;
c1 = BoardManager.Instance.Chessmans[CurrentX - 1, CurrentY - 1];
if (c1 != null && c1.isWhite)
{
moves[CurrentX - 1, CurrentY - 1] = true;
}
}
// Diagonal right
if (CurrentX != 7 && CurrentY != 0)
{
if (e[0] == CurrentX + 1 && e[1] == CurrentY - 1)
moves[CurrentX + 1, CurrentY - 1] = true;
c1 = BoardManager.Instance.Chessmans[CurrentX + 1, CurrentY - 1];
if (c1 != null && c1.isWhite)
{
moves[CurrentX + 1, CurrentY - 1] = true;
}
}
// Middle
if (CurrentY != 0)
{
c1 = BoardManager.Instance.Chessmans[CurrentX, CurrentY - 1];
if (c1 == null)
{
moves[CurrentX, CurrentY - 1] = true;
}
}
// Middle on first move
if (CurrentY == 6)
{
c1 = BoardManager.Instance.Chessmans[CurrentX, CurrentY - 1];
c2 = BoardManager.Instance.Chessmans[CurrentX, CurrentY - 2];
if (c1 == null && c2 == null)
{
moves[CurrentX, CurrentY - 2] = true;
}
}
}
return moves;
}
}
|
7da088cd311e371f8e1d7e87adb189c608056e65
|
C#
|
fgheysels/arcus.templates
|
/src/Arcus.Templates.Tests.Integration/Fixture/ProjectOptions.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GuardNet;
namespace Arcus.Templates.Tests.Integration.Fixture
{
/// <summary>
/// Represents all the available project options on the a template project.
/// </summary>
public class ProjectOptions
{
private readonly IEnumerable<string> _arguments;
private readonly IEnumerable<Action<DirectoryInfo, DirectoryInfo>> _updateProject;
/// <summary>
/// Initializes a new instance of the <see cref="ProjectOptions"/> class.
/// </summary>
public ProjectOptions()
: this(Enumerable.Empty<string>(),
Enumerable.Empty<Action<DirectoryInfo, DirectoryInfo>>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ProjectOptions"/> class.
/// </summary>
public ProjectOptions(ProjectOptions options)
: this(options?._arguments,
options?._updateProject)
{
}
private ProjectOptions(
IEnumerable<string> arguments,
IEnumerable<Action<DirectoryInfo, DirectoryInfo>> updateProject)
{
Guard.NotNull(arguments, nameof(arguments), "Cannot create web API project without project options");
Guard.NotNull(updateProject, nameof(updateProject), "Cannot create web API project without post-project-created actions");
_arguments = arguments;
_updateProject = updateProject;
}
/// <summary>
/// Adds an option to the project that should be added for a project template.
/// </summary>
/// <param name="argument">The console argument to pass along the 'dotnet new' command.</param>
protected ProjectOptions AddOption(string argument)
{
Guard.NotNullOrWhitespace(argument, nameof(argument));
return new ProjectOptions(_arguments.Append(argument), _updateProject);
}
/// <summary>
/// Adds an option to the project that should be added for a project template.
/// </summary>
/// <param name="argument">The console argument to pass along the 'dotnet new' command.</param>
/// <param name="updateProject">The custom action to be executed in order that the created project uses the project option correctly.</param>
protected ProjectOptions AddOption(string argument, Action<DirectoryInfo, DirectoryInfo> updateProject)
{
Guard.NotNullOrWhitespace(argument, nameof(argument));
return new ProjectOptions(
_arguments.Append(argument),
_updateProject.Append(updateProject));
}
/// <summary>
/// Converts all the project options to a command line representation that can be passed along a 'dotnet new' command.
/// </summary>
internal string ToCommandLineArguments()
{
return String.Join(" ", _arguments);
}
/// <summary>
/// Update the created project at the given <paramref name="projectDirectory"/> with a set of custom action in order that the created project is using the options correctly.
/// After this update the project is ready to start.
/// </summary>
/// <param name="fixtureDirectory">The project directory where the fixtures for the newly created project is located.</param>
/// <param name="projectDirectory">The project directory where the newly project from a template is located.</param>
internal void UpdateProjectToCorrectlyUseOptions(DirectoryInfo fixtureDirectory, DirectoryInfo projectDirectory)
{
Guard.NotNull(projectDirectory, nameof(projectDirectory), "Cannot execute any post-create custom actions without a project directory");
Guard.For<ArgumentException>(() => !projectDirectory.Exists, "Cannot execute any post-create custom action on a project directory that doesn't exists on disk");
foreach (Action<DirectoryInfo, DirectoryInfo> postBuildAction in _updateProject)
{
postBuildAction(fixtureDirectory, projectDirectory);
}
}
}
}
|
12b413e811b54a22b55f3bc129e0b65bc202ace3
|
C#
|
AlexandrPetrovichev/YP
|
/YP1/YP1/Program.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace YP1
{
class Program
{
static void Main(string[] args)
{
Table t = new Table();
List<string> word = new List<string> { "" };
string path = @"C:\Users\User\source\repos\YP1\YP1\input.txt";
using (StreamReader sr = new StreamReader(path))
{
string line;
while ((line = sr.ReadLine()) != null)
{
for (int i = 0; i < line.Length; i++)
{
while (!t.delimiter(line[i].ToString()) && !t.space(line[i].ToString()))
{
word[word.Count - 1] += line[i];
i++;
}
if (t.delimiter(line[i].ToString()))
word.Add(line[i].ToString());
else
word.Add("");
}
}
}
for(int i = 0; i < word.Count; i++)
{
if (t.contains(word[i]))
t.Out(t.search(word[i]));
else
{
try
{
Int32.Parse(word[i + 2]);
t.hashtable.set(word[i]);
t.hashtable.set_val(word[i], Int32.Parse(word[i + 2]));
t.Out(word[i]);
}
catch (FormatException e)
{
}
}
}
string s = "return";
ID id = t.search(s);
int f;
//t.Out(id);
HashTable h = new HashTable(1);
h.set("flag");
h.set("flag]");
h.set_val("flag", 1);
h.set_val("flag]", 1345);
h.set_val("flag]", 1343565);
//Console.WriteLine(h.get("flag]")[0]);
//Console.WriteLine(h.get("flag]")[1]);
//id.Out();
}
}
}
|
b40b466e1c07f0b8d4bc1c693a4678bd29215737
|
C#
|
milankoster/Advent-Of-Code-2020
|
/Day 8/Computer.cs
| 3.828125
| 4
|
using System;
using System.Collections.Generic;
namespace Day_8
{
public class Computer
{
public int Accumulator { get; private set; }
public string[] Instructions { get; set; }
public int Pointer { get; private set; }
public Computer(string[] instructions)
{
Accumulator = 0;
Pointer = 0;
Instructions = instructions;
}
public Tuple<int,bool> FindLoop()
{
List<int> indexes = new List<int>();
while (Pointer < Instructions.Length)
{
if (indexes.Contains(Pointer))
return new Tuple<int, bool>(Accumulator, false);
indexes.Add(Pointer);
var parsed = Parse(Instructions[Pointer]);
var number = int.Parse(parsed[1]);
switch (parsed[0])
{
case "acc":
ExecuteAcc(number);
break;
case "jmp":
ExecuteJump(number);
break;
case "nop":
ExecuteNop();
break;
}
}
return new Tuple<int, bool>(Accumulator, true);
}
private void ExecuteAcc(int number)
{
Accumulator += number;
Pointer++;
}
private void ExecuteJump(int number)
{
Pointer += number;
}
private void ExecuteNop()
{
Pointer++;
}
private static string[] Parse(string instruction)
{
return instruction.Split(" ");
}
}
}
|
7bcdf55b1ac0ebd7eab72bf4a4383bcdd01f438a
|
C#
|
dorian195/CCTV-monitoring
|
/CameraWPF/VideoRecorder/Transmission.xaml.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CCTVSystem.Client
{
/// <summary>
/// Logika interakcji dla klasy Transmission.xaml
/// </summary>
public partial class Transmission : UserControl
{
public class Values
{
public string W { get; set; }
public string H { get; set; }
}
public Transmission()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var values = new Values
{
W = this.textbox1.Text,
H = this.textbox2.Text
};
MessageBox.Show("You Entered: \n" + "Width: " + textbox1.Text + "\nHeight: " + textbox2.Text);
}
private void KeyDown_textbox2(object sender, KeyEventArgs e)
{
var values = new Values
{
W = this.textbox1.Text,
H = this.textbox2.Text
};
if (e.Key == Key.Return)
MessageBox.Show("You Entered: \n" + "Width: " + textbox1.Text + "\nHeight: " + textbox2.Text);
if (e.Key == Key.A || e.Key == Key.B || e.Key == Key.C || e.Key == Key.D || e.Key == Key.E || e.Key == Key.F || e.Key == Key.G || e.Key == Key.H || e.Key == Key.I || e.Key == Key.J || e.Key == Key.K || e.Key == Key.L || e.Key == Key.M || e.Key == Key.N || e.Key == Key.O || e.Key == Key.P || e.Key == Key.R || e.Key == Key.S || e.Key == Key.T || e.Key == Key.U || e.Key == Key.V || e.Key == Key.W || e.Key == Key.X || e.Key == Key.Y || e.Key == Key.Z)
{
MessageBox.Show("Enter correct value!");
textbox2.Clear();
}
}
private void KeyDown_textbox1(object sender, KeyEventArgs e)
{
if (e.Key == Key.A || e.Key == Key.B || e.Key == Key.C || e.Key == Key.D || e.Key == Key.E || e.Key == Key.F || e.Key == Key.G || e.Key == Key.H || e.Key == Key.I || e.Key == Key.J || e.Key == Key.K || e.Key == Key.L || e.Key == Key.M || e.Key == Key.N || e.Key == Key.O || e.Key == Key.P || e.Key == Key.R || e.Key == Key.S || e.Key == Key.T || e.Key == Key.U || e.Key == Key.V || e.Key == Key.W || e.Key == Key.X || e.Key == Key.Y || e.Key == Key.Z)
{
MessageBox.Show("Enter correct value!");
textbox1.Clear();
}
}
}
}
|
c93820efd56cd7c32091def37cd3a0a7e6b55a3a
|
C#
|
zephlord/BodyBuilder
|
/Assets/Scripts/Caregiver/Utilities/InitializeSocketHere.cs
| 2.546875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using SocketIO;
///<summary>
/// sets up the socket connection to the server
/// calls functions once connection is established
///</summary>
public class InitializeSocketHere : MonoBehaviour {
[SerializeField]
private SocketIOComponent _socket;
[SerializeField]
private UnityEvent _events;
private bool _needsInitialize;
private bool _hasConnectionAttempt;
void Start() {
_socket.On(Constants.CONNECTED_MESSAGE, initializationEvents);
}
void Update()
{
if(!_hasConnectionAttempt)
{
_socket.Connect();
_hasConnectionAttempt = true;
}
if(_needsInitialize)
{
_events.Invoke();
_needsInitialize = false;
}
}
void initializationEvents(SocketIOEvent ev)
{
_needsInitialize = true;
}
}
|
28d838bc64c298fc00929db591b641fb851cc9b8
|
C#
|
elieak/Labs
|
/Backgammon/BackgammonLogic/Components/NoWhere.cs
| 2.625
| 3
|
using System.Drawing;
namespace BackgammonLogic.Components
{
internal class NoWhere : AbstractField
{
private NoWhere(Rectangle _Rect)
: base(_Rect, ColorsAndConstants.Nowhere)
{
}
public static NoWhere GetNowhere()
{
var rectangle = new Rectangle(14 * ColorsAndConstants.FieldSize, 0, ColorsAndConstants.FieldSize, 12 * ColorsAndConstants.FieldSize);
return new NoWhere(rectangle);
}
public override void Draw(Graphics graphics)
{
graphics.FillRectangle(ColorsAndConstants.BandBrush, Rect);
}
public override void DrawWithLight(Graphics graphics, Color color)
{
graphics.FillRectangle(ColorsAndConstants.BandBrush, Rect);
var p = new Pen(color);
graphics.DrawRectangle(p, Rect);
}
public override bool IsAccessibleFor(PColorEnum playerColor)
{
return true;
}
}
}
|
792703d82c9ce1e49bd77c237650aef868d66dff
|
C#
|
Ideine/Xmf2.iOS.Extensions
|
/src/Extensions/FoundationExtensions.cs
| 2.734375
| 3
|
using System;
using System.Linq;
using Foundation;
// ReSharper disable InconsistentNaming
namespace Xmf2.iOS.Extensions.Extensions
{
public static class FoundationExtensions
{
private static readonly DateTime _reference = new(2001, 1, 1, 0, 0, 0);
private static readonly DateTime _referenceForNSDate = new(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Convert NSDate to DateTime
/// </summary>
public static DateTime ToDateTime(this NSDate date)
{
return _reference.AddSeconds(date.SecondsSinceReferenceDate).ToLocalTime();
}
public static NSDate ToNSDate(this DateTime date)
{
return NSDate.FromTimeIntervalSinceReferenceDate((date.ToUniversalTime() - _referenceForNSDate).TotalSeconds);
}
public static string ConcatToString(this NSData data, string format = "x2")
{
return string.Join(string.Empty, data.Select(x => x.ToString(format)));
}
public static bool TryGet<T>(this NSDictionary source, string key, out T value) where T : class
{
return source.TryGet(new NSString(key), out value);
}
public static bool TryGet<T>(this NSDictionary source, NSString key, out T value) where T : class
{
if (source.ContainsKey(key) && source[key] is T result)
{
value = result;
return true;
}
value = default;
return false;
}
}
}
|
40ea6f0faf54c5f5c637acc7bdd22948ccdbfb86
|
C#
|
rstarkov/HowMuchLeague
|
/LeagueOfStats.GlobalData/Enums.cs
| 2.90625
| 3
|
using System;
namespace LeagueOfStats.GlobalData
{
public enum Region
{
BR = 1,
EUNE = 2,
EUW = 3,
JP = 4,
KR = 5,
LAN = 6,
LAS = 7,
NA = 8,
OCE = 9,
TR = 10,
RU = 11,
PBE = 12,
}
static class EnumConversion
{
public static byte ToByte(this Region region)
{
var result = (int) region;
if (result >= 0 && result <= 255)
return (byte) result;
throw new Exception("Unexpected region type");
}
public static Region ToRegion(this byte region)
{
if (region < 0 || region > 255)
throw new Exception();
return Check((Region) region);
}
public static string ToApiHost(this Region region)
{
switch (region)
{
case Region.BR: return "br1.api.riotgames.com";
case Region.EUNE: return "eun1.api.riotgames.com";
case Region.EUW: return "euw1.api.riotgames.com";
case Region.JP: return "jp1.api.riotgames.com";
case Region.KR: return "kr.api.riotgames.com";
case Region.LAN: return "la1.api.riotgames.com";
case Region.LAS: return "la2.api.riotgames.com";
case Region.NA: return "na1.api.riotgames.com";
case Region.OCE: return "oc1.api.riotgames.com";
case Region.TR: return "tr1.api.riotgames.com";
case Region.RU: return "ru.api.riotgames.com";
case Region.PBE: return "pbe1.api.riotgames.com";
default: throw new Exception();
}
}
public static T Check<T>(T value)
{
if (!Enum.IsDefined(typeof(T), value))
throw new Exception();
return value;
}
}
}
|
78341a255b7ce8205cb70c56ccff352fa920921a
|
C#
|
hardsky/music-head
|
/web/App_Code/JamLog.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
using System.Configuration;
namespace Jam
{
/// <summary>
/// Summary description for JamLog
/// </summary>
public class JamLog
{
public enum enEntryType
{
info = 0,
warning,
error
}
public JamLog()
{
//
// TODO: Add constructor logic here
//
}
static public void log(enEntryType entrytype, string sSource, string sMessage)
{
MySqlConnection con = null;
try
{
string sConStr = ConfigurationManager.ConnectionStrings["JamConnectionString"].ToString();
con = new MySqlConnection(sConStr);
con.Open();
if (con != null)
{
MySqlCommand cmd = new MySqlCommand(@"insert into jamlog (entry_type, entry_source, entry_msg, created)
values(?entry_type, ?entry_source, ?entry_msg, UTC_TIMESTAMP())", con);
cmd.Parameters.Add("?entry_type", MySqlDbType.Int16).Value = (Int16)entrytype;
cmd.Parameters.Add("?entry_source", MySqlDbType.VarChar, 80).Value = sSource;
cmd.Parameters.Add("?entry_msg", MySqlDbType.VarChar, 2048).Value = sMessage.Length > 2048 ? sMessage.Substring(0, 2048) : sMessage;
cmd.ExecuteNonQuery();
}
}
catch// (Exception ex)
{
//JamLog.log(JamLog.enEntryType.error, "string", "string: " + ex.Message);
}
finally
{
if (con != null)
con.Close();
}
}
}
}
|
7215ce9aff1e15d7514774a0450a8f5f4be9d50e
|
C#
|
grecojoao/RestaurantVoting
|
/Voting.Domain.Infra/Data/DataContextInMemory.cs
| 2.515625
| 3
|
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Voting.Domain.Entities;
using Voting.Domain.Entities.ValueObjects;
namespace Voting.Domain.Infra.Data
{
public class DataContextInMemory
{
private List<HungryProfessional> _hungryProfessionalsTemp;
private List<Vote> _votesTemp;
private List<FavoriteRestaurant> _favoriteRestaurantsTemp;
private List<WinnerRestaurant> _winnerRestaurantsTemp;
private List<HungryProfessional> _hungryProfessionals;
private List<Vote> _votes;
private List<FavoriteRestaurant> _favoriteRestaurants;
private List<WinnerRestaurant> _winnerRestaurants;
public DataContextInMemory()
{
_hungryProfessionalsTemp = new List<HungryProfessional>();
_votesTemp = new List<Vote>();
_favoriteRestaurantsTemp = new List<FavoriteRestaurant>();
_winnerRestaurantsTemp = new List<WinnerRestaurant>();
_hungryProfessionals = new List<HungryProfessional>();
_votes = new List<Vote>();
_favoriteRestaurants = new List<FavoriteRestaurant>();
_winnerRestaurants = new List<WinnerRestaurant>();
InitialSettings();
}
private void InitialSettings()
{
_hungryProfessionalsTemp.Add(new HungryProfessional(new Code("123456"), name: "Mateus", password: "1234!@#$"));
_hungryProfessionalsTemp.Add(new HungryProfessional(new Code("789123"), name: "Marcos", password: "1234!@#$"));
_hungryProfessionalsTemp.Add(new HungryProfessional(new Code("456789"), name: "Lucas", password: "1234!@#$"));
_hungryProfessionalsTemp.Add(new HungryProfessional(new Code("987654"), name: "João", password: "1234!@#$"));
_hungryProfessionals.Add(new HungryProfessional(new Code("123456"), name: "Mateus", password: "1234!@#$"));
_hungryProfessionals.Add(new HungryProfessional(new Code("789123"), name: "Marcos", password: "1234!@#$"));
_hungryProfessionals.Add(new HungryProfessional(new Code("456789"), name: "Lucas", password: "1234!@#$"));
_hungryProfessionals.Add(new HungryProfessional(new Code("987654"), name: "João", password: "1234!@#$"));
_favoriteRestaurantsTemp.Add(new FavoriteRestaurant(new Code("8765"), "Bistrô Gastronomia"));
_favoriteRestaurantsTemp.Add(new FavoriteRestaurant(new Code("9456"), "Trôbis Gastronomia"));
_favoriteRestaurants.Add(new FavoriteRestaurant(new Code("8765"), "Bistrô Gastronomia"));
_favoriteRestaurants.Add(new FavoriteRestaurant(new Code("9456"), "Trôbis Gastronomia"));
}
public ReadOnlyCollection<HungryProfessional> HungryProfessionals => _hungryProfessionals.AsReadOnly();
public ReadOnlyCollection<Vote> Votes => _votes.AsReadOnly();
public ReadOnlyCollection<FavoriteRestaurant> FavoriteRestaurants => _favoriteRestaurants.AsReadOnly();
public ReadOnlyCollection<WinnerRestaurant> WinnerRestaurants => _winnerRestaurants.AsReadOnly();
public async Task SaveChanges()
{
_hungryProfessionals = _hungryProfessionalsTemp;
_votes = _votesTemp;
_favoriteRestaurants = _favoriteRestaurantsTemp;
_winnerRestaurants = _winnerRestaurantsTemp;
}
public async Task Discard()
{
_hungryProfessionalsTemp = _hungryProfessionals;
_votesTemp = _votes;
_favoriteRestaurantsTemp = _favoriteRestaurants;
_winnerRestaurantsTemp = _winnerRestaurants;
}
public async Task AddVote(Vote vote) => _votesTemp.Add(vote);
public async Task AddHungryProfessional(HungryProfessional hungryProfessional) =>
_hungryProfessionalsTemp.Add(hungryProfessional);
public async Task AddFavoriteRestaurant(FavoriteRestaurant restaurant) =>
_favoriteRestaurantsTemp.Add(restaurant);
public async Task AddWinner(WinnerRestaurant result) => _winnerRestaurantsTemp.Add(result);
}
}
|
ed7e14d5ec84e7362940ed30f85fa60d610cceb1
|
C#
|
YagaTeam/SimpleApi
|
/src/SimpleApi/Controllers/NameController.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace SimpleApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class NameController : Controller
{
private static readonly string[] Names = new[] {
"Ruslan", "Olga", "Ivan", "Sofia"
};
[HttpGet]
public IActionResult Get() => Ok(Names);
[HttpGet]
public IActionResult Get(int id) => id < Names.Length ? Ok(Names[id]) : NotFound();
[HttpGet]
public IActionResult Sort()
{
string[] arr=new string[Names.Length];
Array.Copy(Names, arr, Names.Length);
Array.Sort(arr);
return Ok(arr);
}
}
}
|
cce0f579dfd494433bff65ed48a892f4b7ab6329
|
C#
|
Majolx/Arcadia
|
/Arcadia/Arcadia/Gamestates/Pong/Arena.cs
| 2.828125
| 3
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Arcadia.Gamestates.Pong
{
class Arena
{
private ArenaComponent[] acComponents;
public ArenaComponent[] Components
{
get { return acComponents; }
set { acComponents = value; }
}
public Arena()
{
acComponents = null;
}
public Arena(ArenaComponent component)
{
ArenaComponent[] components = new ArenaComponent[1];
components[0] = component;
acComponents = components;
}
public Arena(ArenaComponent[] components)
{
acComponents = components;
}
public bool IsCollidingWith(Rectangle collisionBox)
{
foreach (ArenaComponent wall in acComponents)
{
if (wall.CollisionBox.Intersects(collisionBox))
{
return true;
}
}
return false;
}
public void Draw(SpriteBatch spriteBatch)
{
foreach (ArenaComponent component in acComponents)
{
component.Draw(spriteBatch);
}
}
}
}
|
b48345662735f905baff1b7bdca63ae2bae1b3c6
|
C#
|
agunawan19/MHWTool
|
/NetCore/Mhw.Console/Program.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using MHWLibrary.Models;
namespace MHWToolConsole
{
class Program
{
static void Main(string[] args)
{
try
{
//Test();
Console.WriteLine("Hello World!");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void Test()
{
ArmorSet armorSet = new ArmorSet
{
Id = 1,
Name = "Test",
ArmorSetBonusSkill = null,
Armors = new List<IArmor>
{
new Head
{
Defense = 10
}
}
};
}
}
}
|
351b1338d11d11a8f8443b150764bbf3bf8a15cb
|
C#
|
georgi4c/Algorithms
|
/10. Exam-Preparation-Problems-Solutions-Tests/01. Group-Permutations/GroupPermutations-Nakov.cs
| 3.75
| 4
|
using System;
using System.Linq;
using System.Text;
class GroupPermutations
{
static char[] letters;
static int[] letterCount = new int['Z' + 1];
static StringBuilder result = new StringBuilder();
static void Main()
{
string str = Console.ReadLine();
letters = str.Distinct().ToArray();
foreach (char letter in str)
{
letterCount[letter]++;
}
Permute(0);
Console.Write(result);
}
static void Permute(int index)
{
if (index == letters.Length)
{
Print();
return;
}
for (int i = index; i < letters.Length; i++)
{
Swap(i, index);
Permute(index + 1);
Swap(i, index);
}
}
static void Swap(int index1, int index2)
{
var old = letters[index1];
letters[index1] = letters[index2];
letters[index2] = old;
}
static void Print()
{
foreach (var l in letters)
{
for (int i = 0; i < letterCount[l]; i++)
{
result.Append(l);
}
}
result.AppendLine();
}
}
|
4de62dab955c227b78034a670bb814df91d72ca0
|
C#
|
shendongnian/download4
|
/first_version_download2/85027-5571277-11959408-2.cs
| 2.875
| 3
|
var input = new[] { "01.0", "01.4", "01.5", "0.20", "02.5",
"02.6", "03.0", "03.2" };
var integers = input.Select(i =>
(int)double.Parse(i,
System.Globalization.CultureInfo.InvariantCulture))
.Distinct().ToArray();
|
e5eae7abadbfbad94e734b0ed28dd76fdc31bfb2
|
C#
|
BlueDress/School
|
/C# OOP Basics/Exams/Exam - 25 August 2016/Paw Inc/Core/Engine.cs
| 2.953125
| 3
|
using System;
using System.Linq;
namespace Paw_Inc.Core
{
public class Engine
{
private CentresOperationsController processedData;
public Engine()
{
this.processedData = new CentresOperationsController();
}
public void Run()
{
ReadData(this.processedData);
PrintCentresData(this.processedData);
}
private void PrintCentresData(CentresOperationsController processedData)
{
Console.WriteLine("Paw Incorporative Regular Statistics");
Console.WriteLine($"Adoption Centers: {processedData.AdoptionCentres.Count}");
Console.WriteLine($"Cleansing Centers: {processedData.CleansingCentres.Count}");
if (processedData.GetAllAdoptedAnimals().Count > 0)
{
Console.WriteLine($"Adopted Animals: {string.Join(", ", processedData.GetAllAdoptedAnimals())}");
}
else
{
Console.WriteLine("Adopted Animals: None");
}
if (processedData.GetAllCleansedAnimals().Count > 0)
{
Console.WriteLine($"Cleansed Animals: {string.Join(", ", processedData.GetAllCleansedAnimals())}");
}
else
{
Console.WriteLine("Cleansed Animals: None");
}
Console.WriteLine($"Animals Awaiting Adoption: {processedData.AnimalsWaitingForAdoption()}");
Console.WriteLine($"Animals Awaiting Cleansing: {processedData.AnimalsWaitingForCleansing()}");
}
private static void ReadData(CentresOperationsController processedData)
{
while (true)
{
var input = Console.ReadLine();
if (input.Equals("Paw Paw Pawah"))
{
break;
}
else
{
var tokens = input.Split(new[] { ' ', '|' }, StringSplitOptions.RemoveEmptyEntries).ToList();
var command = tokens[0];
tokens.RemoveAt(0);
var cmdArgs = tokens.ToArray();
switch (command)
{
case "RegisterCleansingCenter":
var cleansingCentreName = cmdArgs[0];
processedData.RegisterCleansingCenter(cleansingCentreName);
break;
case "RegisterAdoptionCenter":
var adoptionCentreName = cmdArgs[0];
processedData.RegisterAdoptionCenter(adoptionCentreName);
break;
case "RegisterCastrationCenter":
var castrationCenterName = cmdArgs[0];
processedData.RegisterCastrationCenter(castrationCenterName);
break;
case "RegisterDog":
processedData.RegisterDog(cmdArgs);
break;
case "RegisterCat":
processedData.RegisterCat(cmdArgs);
break;
case "SendForCleansing":
var adoptCentreName = cmdArgs[0];
var cleansCentreName = cmdArgs[1];
processedData.SendForCleansing(adoptCentreName, cleansCentreName);
break;
case "SendForCastration":
var adopCentreName = cmdArgs[0];
var castrationCentreName = cmdArgs[1];
processedData.SendForCastration(adopCentreName, castrationCentreName);
break;
case "Cleanse":
var cleanCentreName = cmdArgs[0];
processedData.Cleanse(cleanCentreName);
break;
case "Castrate":
var castrCenterName = cmdArgs[0];
processedData.Castrate(castrCenterName);
break;
case "Adopt":
var adCentreName = cmdArgs[0];
processedData.Adopt(adCentreName);
break;
case "CastrationStatistics":
Console.WriteLine("Paw Inc. Regular Castration Statistics");
Console.WriteLine($"Castration Centers: {processedData.CastrationCentres.Count()}");
if (processedData.GetAllCastratedAnimals().Count > 0)
{
Console.WriteLine($"Castrated Animals: {string.Join(", ", processedData.GetAllCastratedAnimals())}");
}
else
{
Console.WriteLine("Castrated Animals: None");
}
break;
}
}
}
}
}
}
|
cb2ee6ab85bc9e315c699b653e12d7d9d04462c1
|
C#
|
vxchin/CSharp8NewFeatures
|
/CSharpNewFeatures/Patterns.cs
| 2.953125
| 3
|
using ConsumerVehicleRegistration;
using CommercialRegistration;
using LiveryRegistration;
using System;
namespace CSharpNewFeatures
{
public static class Patterns
{
public static void Demo()
{
var soloDriver = new Car();
var twoRideShare = new Car { Passengers = 1 };
var threeRideShare = new Car { Passengers = 2 };
var fullVan = new Car { Passengers = 5 };
var emptyTaxi = new Taxi();
var singleFare = new Taxi { Fares = 1 };
var doubleFare = new Taxi { Fares = 2 };
var fullVanPool = new Taxi { Fares = 5 };
var lowOccupantBus = new Bus { Capacity = 90, Riders = 15 };
var normalBus = new Bus { Capacity = 90, Riders = 75 };
var fullBus = new Bus { Capacity = 90, Riders = 85 };
var heavyTruck = new DeliveryTruck { GrossWeightClass = 7500 };
var truck = new DeliveryTruck { GrossWeightClass = 4000 };
var lightTruck = new DeliveryTruck { GrossWeightClass = 2500 };
Console.WriteLine($"The toll for a solo driver is {CalculateToll(soloDriver)}");
Console.WriteLine($"The toll for a two ride share is {CalculateToll(twoRideShare)}");
Console.WriteLine($"The toll for a three ride share is {CalculateToll(threeRideShare)}");
Console.WriteLine($"The toll for a fullVan is {CalculateToll(fullVan)}");
Console.WriteLine($"The toll for an empty taxi is {CalculateToll(emptyTaxi)}");
Console.WriteLine($"The toll for a single fare taxi is {CalculateToll(singleFare)}");
Console.WriteLine($"The toll for a double fare taxi is {CalculateToll(doubleFare)}");
Console.WriteLine($"The toll for a full van taxi is {CalculateToll(fullVanPool)}");
Console.WriteLine($"The toll for a low-occupant bus is {CalculateToll(lowOccupantBus)}");
Console.WriteLine($"The toll for a regular bus is {CalculateToll(normalBus)}");
Console.WriteLine($"The toll for a bus is {CalculateToll(fullBus)}");
Console.WriteLine($"The toll for a truck is {CalculateToll(heavyTruck)}");
Console.WriteLine($"The toll for a truck is {CalculateToll(truck)}");
Console.WriteLine($"The toll for a truck is {CalculateToll(lightTruck)}");
try
{
CalculateToll("this will fail");
}
catch (ArgumentException)
{
Console.WriteLine("Caught an ArgumentException when using the wrong type.");
}
try
{
CalculateToll(null);
}
catch (ArgumentNullException)
{
Console.WriteLine("Caught an ArgumentNullException when using null.");
}
}
static decimal CalculateToll(object? vehicle) =>
vehicle switch
{
Car { Passengers: 3 } => 1.00m,
Car { Passengers: 2 } => 1.50m,
Car _ => 2.00m,
Taxi _ => 3.50m,
Bus _ => 5.00m,
DeliveryTruck _ => 10.00m,
{ } => throw new ArgumentException(message: "Not a known vehicle type", paramName: null),
null => throw new ArgumentNullException(nameof(vehicle)),
};
#region Advanced
static bool IsWeekDay(DateTime timeOfToll) =>
timeOfToll.DayOfWeek switch
{
DayOfWeek.Saturday => false,
DayOfWeek.Sunday => false,
_ => true,
};
enum TimeBand
{
MorningRush,
Daytime,
EveningRush,
Overnight
}
static TimeBand GetTimeBand(DateTime timeOfToll)
{
var hour = timeOfToll.Hour;
if (hour < 6) return TimeBand.Overnight;
else if (hour < 10) return TimeBand.MorningRush;
else if (hour < 16) return TimeBand.Daytime;
else if (hour < 20) return TimeBand.EveningRush;
else return TimeBand.Overnight;
}
static decimal PeakTimePremium(DateTime timeOfToll, bool inbound) =>
(IsWeekDay(timeOfToll), GetTimeBand(timeOfToll), inbound) switch
{
(true, TimeBand.Overnight, _) => 0.75m,
(true, TimeBand.Daytime, _) => 1.5m,
(true, TimeBand.MorningRush, true) => 2.0m,
(true, TimeBand.EveningRush, false) => 2.0m,
(_, _, _) => 1.0m,
};
#endregion
}
}
/// <summary>
/// 非营运车辆
/// </summary>
namespace ConsumerVehicleRegistration
{
/// <summary>
/// 家用轿车
/// </summary>
public class Car
{
/// <summary>
/// 乘客人数
/// </summary>
public int Passengers { get; set; }
}
}
/// <summary>
/// 商业车辆
/// </summary>
namespace CommercialRegistration
{
/// <summary>
/// 运货卡车
/// </summary>
public class DeliveryTruck
{
/// <summary>
/// 车辆毛重
/// </summary>
public int GrossWeightClass { get; set; }
}
}
/// <summary>
/// 载客车辆
/// </summary>
namespace LiveryRegistration
{
/// <summary>
/// 出租车
/// </summary>
public class Taxi
{
/// <summary>
/// 乘客数量
/// </summary>
public int Fares { get; set; }
}
/// <summary>
/// 公交车
/// </summary>
public class Bus
{
/// <summary>
/// 核定载客人数
/// </summary>
public int Capacity { get; set; }
/// <summary>
/// 实际载客人数
/// </summary>
public int Riders { get; set; }
}
}
|
f88865f6c9769f0525235b540845d3c9a46922da
|
C#
|
ericbrunner/SimpleInjector
|
/SimpleInjector/ShoppingCart2.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleInjector
{
public class ShoppingCart2 : IShoppingCart
{
private readonly Func<IOrder> _order;
public ShoppingCart2(Func<IOrder> order)
{
_order = order;
}
public void CheckOut()
{
Console.WriteLine(this.GetType().Name + " gets checked out ...");
_order().Process();
}
}
}
|
0e305abcb18072205aa0c2a180aa5d43278d6faa
|
C#
|
poo92/AdraFinal
|
/DataAccessLibrary/Migrations/Configuration.cs
| 2.546875
| 3
|
namespace DataAccessLibrary.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<DataAccessLibrary.AdraFullTestFinalContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(DataAccessLibrary.AdraFullTestFinalContext context)
{
// This method will be called after migrating to the latest version.
var accountbalances = new List<AccountBalance>
{
new AccountBalance{year=2017, month=1, rnd=5602.02, canteen=639.25, ceocar=-6500.00, marketing=4500.00, parking=5600.25, uid=1},
new AccountBalance{year=2017, month=2, rnd=10245.00, canteen=4523.02, ceocar=-789.025, marketing=63.02, parking=789.02, uid=1},
new AccountBalance{year=2017, month=3, rnd=562.02, canteen=6394.25, ceocar=-6540.00, marketing=4500.00, parking=600.25, uid=1},
new AccountBalance{year=2017, month=4, rnd=560.02, canteen=6394.25, ceocar=-600.00, marketing=450.00, parking=500.25, uid=1},
new AccountBalance{year=2017, month=5, rnd=602.02, canteen=6539.25, ceocar=-6700.00, marketing=4200.00, parking=5606.25, uid=1},
};
accountbalances.ForEach(s => context.AccountBalances.AddOrUpdate(p => new { p.year, p.month }, s));
context.SaveChanges();
}
}
}
|
812e5b020e49a959ff24abc681b8329e640c90e8
|
C#
|
zhomas/GalvosCutsceneParser
|
/GalvosCutsceneParser/Chunks/WaitStep.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace GalvosCutsceneParser
{
public class WaitStep : BaseStep
{
public int milliseconds { get; private set; }
public static bool IsMatch(StepInput input)
{
return input.chunks.Count > 1 && input.chunks[0] == "wait";
}
public WaitStep(StepInput input)
{
this.milliseconds = RegexUtilities.GetDigitsFromString(input.chunks[1]);
}
}
}
|
82c9957ba5571748877cea14ffda0cc80a0e58c9
|
C#
|
nabajatad/webbeds-poc
|
/WebBeds.Test/TestWebBed.cs
| 2.59375
| 3
|
namespace WebBeds.Test
{
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebBeds.Repository;
using WebBeds.Service;
using Xunit;
public class TestWebBed
{
private readonly string authCode = "aWH1EX7ladA8C/oWJX5nVLoEa4XKz2a64yaWVvzioNYcEo8Le8caJw==";
private readonly string apiMethodName = "findBargain";
/// <summary>
/// Throws exception when GetHotel is called then exception is thrown
/// </summary>
[Fact]
public async void GivenRepositoryThrowsException_WhenGetHotelsIsCalled_ThenExceptionIsThrown()
{
// Given
var destinationId = 279;
var nights = 2;
var repository = new Mock<IWebBedsRepository>();
repository.Setup(item => item.GetHotels(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<string>())).Throws<Exception>();
var hotelService = new HotelService(repository.Object);
// When
Func<Task> action = async () => await hotelService.GetHotels(apiMethodName, destinationId, nights, authCode);
await Assert.ThrowsAnyAsync<Exception>(action);
}
/// <summary>
/// Returns null when GetHotel is called then null is return
/// </summary>
[Fact]
public async void GivenRepositoryReturnsNull_WhenGetHotelsIsCalled_ThenNullIsReturned()
{
// Given
var destinationId = 279;
var nights = 2;
var repository = new Mock<IWebBedsRepository>();
repository.Setup(item => item.GetHotels(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<string>())).ReturnsAsync((List<FindAPIJsonObject>)null);
var hotelService = new HotelService(repository.Object);
// When
var response = await hotelService.GetHotels(apiMethodName, destinationId, nights, authCode);
// Then
Assert.True(!response.HotelList.Any());
}
/// <summary>
/// Returns data when GetHotel is called then null is return
/// </summary>
[Fact]
public async void GivenRepositoryReturnsData_WhenGetHotelsIsCalled_ThenDataIsReturnedInTheView()
{
// Given
var destinationId = 279;
var nights = 2;
var repository = new Mock<IWebBedsRepository>();
var geoId = 1;
var name = "TestData";
var propId = 1;
var rating = 5;
var expectedResponse = new List<FindAPIJsonObject>
{
new FindAPIJsonObject
{
hotel = new Repository.Entity.Hotel
{
GeoId = geoId,
Name = name,
PropertyID = propId,
Rating = rating
},
rates = new List<Repository.Entity.Rate>
{
new Repository.Entity.Rate
{
RateType= "Test",
BoardType = "Test",
Value = 22
},
new Repository.Entity.Rate
{
RateType= "Test",
BoardType = "Test",
Value = 25
}
}
}
};
repository.Setup(item => item.GetHotels(apiMethodName, destinationId, nights, authCode)).ReturnsAsync(expectedResponse);
var hotelService = new HotelService(repository.Object);
// When
var response = await hotelService.GetHotels(apiMethodName, destinationId, nights, authCode);
// Then
Assert.True(response.HotelList.Count > 0);
}
}
}
|
4b919bc1e6437f3215cf513bfea111b029d9a353
|
C#
|
CheAle14/bot-chess
|
/ChessClient/Classes/ChessPlayer.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace ChessClient.Classes
{
public class ChessPlayer : APIObject<int>
{
public string Name { get; set; }
public PlayerSide Side { get; set; }
public override void FromJson(JObject json)
{
Name = json["name"].ToObject<string>();
Id = json["id"].ToObject<int>();
Side = json["side"].ToObject<PlayerSide>();
}
public override JObject ToJson()
{
throw new NotImplementedException();
}
}
}
|
090bc78887aa2b8ed62e493d914c06f191dedf63
|
C#
|
FDYdarmstadt/BoSSS
|
/src/Utils/bcl/nativelib_inst.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace bcl.nativelib_inst {
class Program : IProgram {
#region IProgram Members
public void Execute() {
CopyNative(StartDir);
}
DirectoryInfo StartDir = bcl.myEnv.BOSSS_ROOT;
public void DecodeArgs(string[] args) {
if (args.Length != 1)
throw new UserInputException("wrong number of arguments");
if (args.Length > 0) {
DirectoryInfo di = new DirectoryInfo(bcl.BrowsePath(args[0]));
if (!di.Exists)
throw new UserInputException("'" + args[0] + "' either does not exist or is no directory.");
StartDir = di;
}
}
public void PrintUsage() {
Console.WriteLine("Usage: bcl nativelib-inst $directory");
Console.WriteLine();
Console.WriteLine("Deploys the recent version of native the libraries");
Console.WriteLine("into the specified directory");
Console.WriteLine("Arguments:");
Console.WriteLine(" directory directory to start the recursive installation");
Console.WriteLine(" of native libraries; if not specified, $BOSSS_ROOT is ");
Console.WriteLine(" used");
Console.WriteLine();
}
#endregion
/// <summary>
/// Copies the native binaries to
/// <paramref name="targetDirectory"/>.
/// </summary>
private void CopyNative(DirectoryInfo targetDirectory) {
bool MustContainNative = true;
if (MustContainNative) {
Console.WriteLine("INFO: installing native binaries in :'" + targetDirectory.FullName + "'");
CopyDirectoryRec(bcl.myEnv.BOSSS_BIN_NATIVE, targetDirectory, "amd64");
}
}
/// <summary>
/// (tries to) do a recursive copy of a directory
/// </summary>
/// <param name="srcDir"></param>
/// <param name="dstDir"></param>
/// <param name="filter">search pattern/filter</param>
public static void CopyDirectoryRec(DirectoryInfo srcDir, DirectoryInfo dstDir, string filter) {
FileInfo[] srcFiles = srcDir.GetFiles();
foreach (FileInfo srcFile in srcFiles) {
TryCopy(srcFile.FullName, Path.Combine(dstDir.FullName, srcFile.Name));
}
DirectoryInfo[] subDirs;
if (filter == null)
subDirs = srcDir.GetDirectories();
else
subDirs = srcDir.GetDirectories(filter);
foreach (DirectoryInfo srcSubDir in subDirs) {
DirectoryInfo dstSubDir = new DirectoryInfo(Path.Combine(dstDir.FullName, srcSubDir.Name));
if (!dstSubDir.Exists)
dstSubDir.Create();
CopyDirectoryRec(srcSubDir, dstSubDir, null);
}
}
/// <summary>
/// Utility function which tries to copy a file from
/// <paramref name="sourceFileName"/> to
/// <paramref name="destFileName"/> overwriting existing files if
/// required. Issues a warning (but proceeds as normal) if the copy
/// process fails.
/// </summary>
/// <param name="sourceFileName">
/// The path to the file to be copied
/// </param>
/// <param name="destFileName">The path to the destination</param>
private static void TryCopy(string sourceFileName, string destFileName) {
try {
File.Copy(sourceFileName, destFileName, true);
} catch (Exception e) {
Console.WriteLine("WARNING: Unable to copy to: '"
+ destFileName + "': " + e.GetType().Name + " says:'" + e.Message + "'");
}
}
}
}
|
f577ae118dbe33d31e2e47553fba6e9d90ce23e8
|
C#
|
02Mehmet/DesignPatternExamples
|
/DesignPatternsDemo/SingletonPattern/SingletonPatternService.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DesignPatternsDemo.SingletonPattern
{
public class SingletonPatternService : ISingletonPatternService
{
public static int creationCount = 0;
public static readonly SingletonPatternService _mySingletonServiceInstance = new SingletonPatternService();
public SingletonPatternService()
{
creationCount++;
}
//public static SingletonPatternService GetInstance() => _mySingletonServiceInstance;
public int GetCreationCount() => creationCount;
}
}
|
8ce51175753c549305fec662db3a31231e071b3e
|
C#
|
jpho/2.1-software-arch-OES
|
/OrderEntrySystem/ViewModels/FrameWork/ProductViewModel.cs
| 2.671875
| 3
|
using OrderEntryDataAccess;
using OrderEntryEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace OrderEntrySystem
{
public class ProductViewModel : WorkspaceViewModel
{
public MultiProductViewModel AllProducts;
private bool isSelected;
private Product product;
private Repository repositorys;
public ICommand saveCommand;
public virtual Category Category
{
get
{
return this.product.Category;
}
set
{
this.product.Category = value;
this.OnPropertyChanged("Category");
}
}
public IEnumerable<Category> Categories
{
get
{
return this.repositorys.GetCategories();
}
}
public virtual Location Location {
get
{
return this.product.Location;
}
set
{
this.product.Location = value;
this.OnPropertyChanged("Location");
}
}
public IEnumerable<Location> Locations
{
get
{
return this.repositorys.GetLocations();
}
}
public ProductViewModel(Product product, Repository repository)
: base("Product")
{
this.product = product;
this.repositorys = repository;
}
public Condition Condition
{
get
{
return this.product.Condition;
}
set
{
this.product.Condition = value;
this.OnPropertyChanged("Condition");
}
}
public IEnumerable<Condition> Conditions
{
get
{
return Enum.GetValues(typeof(Condition)) as IEnumerable<Condition>;
}
}
/// <summary>
/// The name of the product.
/// </summary>
public string Name
{
get
{
return this.product.Name;
}
set
{
this.product.Name = value;
this.OnPropertyChanged("Name");
}
}
public string Description
{
get
{
return this.product.Description;
}
set
{
this.product.Description = value;
this.OnPropertyChanged("Description");
}
}
public decimal Price
{
get
{
return this.product.Price;
}
set
{
this.product.Price = value;
this.OnPropertyChanged("Price");
}
}
public ICommand SaveCommand
{
get
{
if (this.saveCommand == null)
{
this.saveCommand = new DelegateCommand(p => this.Save());
}
return this.saveCommand;
}
}
public void Save()
{
this.repositorys.AddProduct(this.product);
this.repositorys.SaveToDatabase();
}
public bool IsSelected
{
get
{
return this.isSelected;
}
set
{
this.isSelected = value;
this.OnPropertyChanged("IsSelected");
}
}
/// <summary>
/// Saves the changes in the window.
/// </summary>
private void OkExecute()
{
this.Save();
this.CloseAction(true);
}
/// <summary>
/// Discards the changes in the window.
/// </summary>
private void CancelExecute()
{
this.CloseAction(false);
}
/// <summary>
/// The create commands associated with the class.
/// </summary>
protected override void CreateCommands()
{
this.Commands.Add(new CommandViewModel("OK", new DelegateCommand(p => this.OkExecute())));
this.Commands.Add(new CommandViewModel("Cancel", new DelegateCommand(p => this.CancelExecute())));
}
}
}
|
571e843760f3746bfae3c21df48295f8fa362a27
|
C#
|
shendongnian/download4
|
/code9/1557880-58676528-212120792-6.cs
| 3.109375
| 3
|
/// <summary>
/// Return User informations as a JObject. To get username and email, if return isn't null :
/// username = json["name"].ToString();
/// email = json["emails"]["account"].ToString();
/// </summary>
/// <param name="accessToken">accesstoken of Onedrive account</param>
/// <returns>JObject value</returns>
public static async Task<JObject> GetUserInfos(string accessToken)
{
JObject json = null;
Uri uri = new Uri($"https://apis.live.net/v5.0/me?access_token={accessToken}");
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage result = await httpClient.GetAsync(uri);
//user info returnd as JSON
string jsonUserInfo = await result.Content.ReadAsStringAsync();
if (jsonUserInfo != null)
{
json = JObject.Parse(jsonUserInfo);
//username = json["name"].ToString();
//email = json["emails"]["account"].ToString();
}
return json;
}
|
c8a5fd80dc63cfaef370d8bf4422e591e6771077
|
C#
|
petedg/CommonScheduler
|
/CommonScheduler/DAL/ServerModelBehavior/DictionaryValue.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommonScheduler.DAL
{
public partial class DictionaryValue
{
private serverDBEntities context;
public DictionaryValue(serverDBEntities context)
{
this.context = context;
}
public DictionaryValue()
{
}
public void SetContext(serverDBEntities context)
{
this.context = context;
}
public string GetValue (string dictionaryName, int dictionaryValueId)
{
var dictionaryValues = from dictionaryValue in context.DictionaryValue
join dictionary in context.Dictionary on dictionaryValue.DICTIONARY_ID equals dictionary.ID
where dictionary.NAME.Equals(dictionaryName) && dictionaryValue.DV_ID == dictionaryValueId
select dictionaryValue;
var selectedDictionaryValue = dictionaryValues.FirstOrDefault();
return selectedDictionaryValue.VALUE;
}
public int GetId(string dictionaryName, string value)
{
var dictionaryValues = from dictionaryValue in context.DictionaryValue
join dictionary in context.Dictionary on dictionaryValue.DICTIONARY_ID equals dictionary.ID
where dictionary.NAME.Equals(dictionaryName) && dictionaryValue.VALUE == value
select dictionaryValue;
var selectedDictionaryValue = dictionaryValues.FirstOrDefault();
return selectedDictionaryValue.DV_ID;
}
public List<DictionaryValue> GetSemesterTypes()
{
var dictionaryValues = from dictionaryValue in context.DictionaryValue
join dictionary in context.Dictionary on dictionaryValue.DICTIONARY_ID equals dictionary.ID
where dictionary.NAME.Equals("Typy semestrów")
select dictionaryValue;
return dictionaryValues.ToList();
}
public List<DictionaryValue> GetMajorDegrees()
{
var dictionaryValues = from dictionaryValue in context.DictionaryValue
join dictionary in context.Dictionary on dictionaryValue.DICTIONARY_ID equals dictionary.ID
where dictionary.NAME.Equals("Poziomy studiów")
select dictionaryValue;
return dictionaryValues.ToList();
}
public List<DictionaryValue> GetMajorTypes()
{
var dictionaryValues = from dictionaryValue in context.DictionaryValue
join dictionary in context.Dictionary on dictionaryValue.DICTIONARY_ID equals dictionary.ID
where dictionary.NAME.Equals("Typy studiów")
select dictionaryValue;
return dictionaryValues.ToList();
}
public List<DictionaryValue> GetTeacherDegrees()
{
var dictionaryValues = from dictionaryValue in context.DictionaryValue
join dictionary in context.Dictionary on dictionaryValue.DICTIONARY_ID equals dictionary.ID
where dictionary.NAME.Equals("Stopnie naukowe nauczycieli")
select dictionaryValue;
return dictionaryValues.ToList();
}
public List<DictionaryValue> GetClassesTypes()
{
var dictionaryValues = from dictionaryValue in context.DictionaryValue
join dictionary in context.Dictionary on dictionaryValue.DICTIONARY_ID equals dictionary.ID
where dictionary.NAME.Equals("Typy zajęć")
select dictionaryValue;
return dictionaryValues.ToList();
}
public string GetTeacherDegree(Teacher teacher)
{
var dictionaryValues = from dictionaryValue in context.DictionaryValue
join dictionary in context.Dictionary on dictionaryValue.DICTIONARY_ID equals dictionary.ID
where dictionary.NAME.Equals("Stopnie naukowe nauczycieli") && dictionaryValue.DV_ID == teacher.DEGREE_DV_ID
select dictionaryValue.VALUE;
string teacherDegree = dictionaryValues.FirstOrDefault();
if (!teacherDegree.Equals("brak"))
{
return teacherDegree + " ";
}
return "";
}
public List<DictionaryValue> GetYearsOfStudy()
{
var dictionaryValues = from dictionaryValue in context.DictionaryValue
join dictionary in context.Dictionary on dictionaryValue.DICTIONARY_ID equals dictionary.ID
where dictionary.NAME.Equals("Lata studiów")
select dictionaryValue;
return dictionaryValues.ToList();
}
}
}
|
8f7c8f67cbd116b28a8fae7c2c4b52ad16017d8c
|
C#
|
Dwelp/TBAConcept
|
/TBA Concept Prototype/Assets/_Scripts/AI/AIBehavior.cs
| 2.640625
| 3
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class AIBehavior : MonoBehaviour {
protected AIUnit unit;
protected Unit activeTarget;
protected bool waitingForAction;
protected UnitAction pendingAction;
protected virtual void Awake()
{
unit = gameObject.GetComponent<AIUnit>();
}
// Use this for initialization
protected virtual void Start ()
{
}
// Update is called once per frame
protected virtual void Update()
{
}
public virtual void ProcessTurn()
{
FindTarget();
StartCoroutine(CProcessTurn());
}
protected virtual IEnumerator CProcessTurn()
{
yield return null;
}
protected virtual IEnumerator WaitForAction(UnitAction action)
{
yield return null;
}
protected virtual void FindTarget()
{
Unit[] combatUnits = GameObject.FindObjectsOfType<Unit>();
combatUnits = combatUnits.Where(p => p.unitOwner == UnitOwner.Player).ToArray();
activeTarget = combatUnits[0];
}
public virtual void ActionFinished(UnitAction action)
{
}
public virtual List<Unit> GetAllTargetsInRange(float range)
{
List<Unit> unitsInRange = CombatManager.Instance.GetCombatUnits();
unitsInRange = unitsInRange.Where(p => Vector3.Distance(transform.position, p.transform.position) <= range).ToList();
return unitsInRange;
}
public virtual Unit GetClosestTarget(List<Unit> targetList)
{
float nearestDistanceSqr = Mathf.Infinity;
Unit nearestUnit = null;
foreach(Unit unit in targetList)
{
Vector3 unitPos = unit.transform.position;
float distanceSqr = (unitPos - transform.position).sqrMagnitude;
if (distanceSqr < nearestDistanceSqr)
{
nearestUnit = unit;
nearestDistanceSqr = distanceSqr;
}
}
return nearestUnit;
}
}
|
69898055ce4a98a0a0cff98c390a843ab3c359e7
|
C#
|
MrYonaxx/GodfatherGameJam2020-Team20
|
/Assets/Script/Characters/CharacterRotation.cs
| 2.578125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterRotation : MonoBehaviour
{
[SerializeField]
private float raycastLenght = 1;
[SerializeField]
private float rotationSpeed = 1;
private Quaternion targetRotation;
// Update is called once per frame
void Update()
{
GetGroundRotation();
UpdateRotation();
}
private void GetGroundRotation()
{
// Bit shift the index of the layer (8) to get a bit mask
int layerMask = 1 << 0;
// This would cast rays only against colliders in layer 8.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
//layerMask = ~layerMask;
RaycastHit hit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(transform.position, Vector3.down, out hit, raycastLenght, layerMask))
{
targetRotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
//transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
/*hit.normal;
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");*/
}
else
{
targetRotation = Quaternion.Euler(0, 0, 0);
}
Debug.DrawRay(transform.position, Vector3.down * raycastLenght, Color.yellow);
}
private void UpdateRotation()
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
|
6dda705cf7351173158079c7e3e46715fbc37e7f
|
C#
|
uffekhansen/Foosball-project
|
/Foosball/Tests/When_Querying_For_Lousy_Foosball_Players.cs
| 2.6875
| 3
|
using System;
using System.Linq;
using System.Collections.Generic;
using DataAccess.Domain;
using Mvno.TestHelpers;
using DataAccess.Infrastructure;
using DataAccess.Specifications;
using Xunit;
namespace Tests
{
public class When_Querying_For_Lousy_Foosball_Players : BehaviorTesting<Repository<FoosballPlayer>>
{
private const string StefanAniff = "Stefan Aniff";
private const int Rank = 1000;
public IEnumerable<FoosballPlayer> Result { get; private set; }
protected override void Given()
{
var lousyFoosballPlayer = new FoosballPlayer
{
Id = Guid.NewGuid(),
Name = StefanAniff,
Born = new DateTime(1985, 9, 12),
Rank = Rank
};
ClassUnderTest.Add(lousyFoosballPlayer);
var bestFoosballPlayer = new FoosballPlayer
{
Id = Guid.NewGuid(),
Name = "Frederic Collignon",
Born = new DateTime(1980, 2, 15),
Rank = 1
};
ClassUnderTest.Add(bestFoosballPlayer);
}
protected override void When()
{
Result = ClassUnderTest.FindAll(new LousyFoosballPlayersBornBefore(1990)).ToList();
}
[Then]
public void There_Should_Only_Be_One_Lousy_Player()
{
Assert.Equal(1, Result.Count());
}
[Then]
public void The_Lousy_Players_Name_Is_Stefan_Aniff()
{
Assert.Equal(StefanAniff, Result.First().Name);
}
[Then]
public void The_Lousy_Players_Rank_Is_1000()
{
Assert.Equal(1000, Result.First().Rank);
}
}
}
|
0ff82643458798b499ff07e759113587674356c7
|
C#
|
dixon01/Dev-Jasper
|
/backend/Common/Formats/Source/AlphaNT/Common/IColor.cs
| 2.640625
| 3
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IColor.cs" company="Gorba AG">
// Copyright © 2011-2014 Gorba AG. All rights reserved.
// </copyright>
// <summary>
// Defines the IColor type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Gorba.Common.Formats.AlphaNT.Common
{
/// <summary>
/// Interface to get the values of a color.
/// Alpha NT does not support alpha-values, therefore colors only have red, green and blue components.
/// </summary>
public interface IColor
{
/// <summary>
/// Gets the red value.
/// </summary>
byte R { get; }
/// <summary>
/// Gets the green value.
/// </summary>
byte G { get; }
/// <summary>
/// Gets the blue value.
/// </summary>
byte B { get; }
/// <summary>
/// Gets a value indicating whether this color is transparent (i.e. has no color at all).
/// </summary>
bool Transparent { get; }
}
}
|
32d7756c9976a4b455f5863d7fcd382c9ba5e9d7
|
C#
|
ivkrivanov/datadesign
|
/Ser2022/Store/Store/Store.Web/Modules/Administration/User/Authentication/MultyTenancy.cs
| 2.65625
| 3
|
namespace Store
{
using System;
using System.Linq;
using System.Security.Claims;
public static class ClaimsPrincipalExtensions
{
public static int GetTenantId(this ClaimsPrincipal user)
{
if (user is null)
throw new ArgumentNullException(nameof(user));
var tenantClaim = user.Claims.FirstOrDefault(x => x.Type == "TenantId");
if (tenantClaim is null)
throw new NullReferenceException("TenantId claim not found");
return int.Parse(tenantClaim.Value);
}
}
}
|
d6c3564e3fb379fa2e127fa1da1abee95536a4c1
|
C#
|
Activict/Structures
|
/LinkedList/QueueNode.cs
| 3.65625
| 4
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Structures
{
class QueueNode<T> : IEnumerable<T>
{
public Node<T> Tail { get; private set; }
public Node<T> Head { get; private set; }
public int Count { get; private set; }
public void Enqueue(T value)
{
if (Head == null)
{
Head = Tail = new Node<T>(value);
Count++;
}
else
{
Tail.Next = new Node<T>(value);
Tail = Tail.Next;
Count++;
}
}
public T Dequeue()
{
if (Head == null)
throw new Exception("Queue is empty");
else if (Count > 1)
{
T first = Head.Value;
Head = Head.Next;
Count--;
return first;
}
else
{
T first = Head.Value;
Head = Tail = null;
Count--;
return first;
}
}
public T First()
{
if (Head == null)
throw new Exception("Queue is empty");
return Head.Value;
}
public T Last()
{
if (Head == null)
throw new Exception("Queue is empty");
return Tail.Value;
}
public void Clear()
{
Head = Tail = null;
}
public bool Contains(T value)
{
Node<T> current = Head;
while (current != null)
{
if (current.Value.Equals(value))
return true;
}
return false;
}
public IEnumerator<T> GetEnumerator()
{
Node<T> current = Head;
while (current != null)
{
yield return current.Value;
current = current.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
}
}
|
b99d8e1db3bc0cd4cb29170a87cd664f21e48313
|
C#
|
ivanpointer/NuLog
|
/NuLog/Layouts/StandardPropertyParser.cs
| 3.078125
| 3
|
/* © 2020 Ivan Pointer
MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE
Source on GitHub: https://github.com/ivanpointer/NuLog */
using System;
using System.Collections.Generic;
using System.Reflection;
namespace NuLog.Layouts {
/// <summary>
/// The standard implementation of a property parser.
/// </summary>
public class StandardPropertyParser : IPropertyParser {
private static readonly Type DictionaryType = typeof(IDictionary<string, object>);
private readonly IDictionary<Type, IDictionary<string, PropertyInfo>> typeCache;
private readonly IDictionary<Type, bool> dictionaryTypes;
public StandardPropertyParser() {
this.typeCache = new Dictionary<Type, IDictionary<string, PropertyInfo>>();
this.dictionaryTypes = new Dictionary<Type, bool>();
}
public object GetProperty(object zobject, string[] path) {
// Check for a null path
if (path == null) {
return null;
}
// Recurse it
return GetPropertyRecurse(zobject, path);
}
/// <summary>
/// The internal recursive function for searching for an object by name. This is where the
/// "heavy lifting" of searching for a property within the log event is performed.
///
/// The complexity (cyclomatic) of this one is going to be high, which may not be avoidable,
/// as this is no-kidding recursion.
/// </summary>
private object GetPropertyRecurse(object zobject, string[] propertyChain, int depth = 0) {
// Exit condition
if (zobject == null || depth >= propertyChain.Length) {
// Either we have hit a dead-end (null) Or we have reached the end of the name chain
// (depth) and we have our value
return zobject;
}
// We haven't hit the bottom of the chain, keep digging
return GetPropertyInternal(zobject, propertyChain, depth);
}
private object GetPropertyInternal(object zobject, string[] propertyChain, int depth) {
var zobjectType = zobject.GetType();
var chainItem = propertyChain[depth];
// Determine if the object is a dictionary, otherwise treat it as just an object
if (!IsDictionaryType(zobjectType)) {
return GetObjectProperty(zobjectType, zobject, chainItem, propertyChain, depth);
} else {
return GetDictionaryProperty(zobject, chainItem, propertyChain, depth);
}
}
private object GetObjectProperty(Type zobjectType, object zobject, string chainItem, string[] propertyChain, int depth) {
// Try to get the element in the dictionary with the next name
var propertyDict = GetPropertyInfo(zobjectType);
var propertyInfo = propertyDict.ContainsKey(chainItem)
? propertyDict[chainItem]
: null;
if (propertyInfo != null) {
return GetPropertyRecurse(propertyInfo.GetValue(zobject, null), propertyChain, depth + 1);
} else {
return null;
}
}
private object GetDictionaryProperty(object zobject, string chainItem, string[] propertyChain, int depth) {
// Try to get the property of the object with the next name
var dictionary = (IDictionary<string, object>)zobject;
if (dictionary.ContainsKey(chainItem)) {
return GetPropertyRecurse(dictionary[chainItem], propertyChain, depth + 1);
} else {
return null;
}
}
/// <summary>
/// A property for retrieving the PropertyInfo of an object type Uses caching because the
/// work of getting th properties of an object type is expensive.
/// </summary>
private IDictionary<string, PropertyInfo> GetPropertyInfo(Type objectType) {
// Check the cache to see if we already have property info for the type\ Otherwise, get
// and cache the property info for the type
if (!typeCache.ContainsKey(objectType)) {
var propertyInfo = objectType.GetProperties();
var dict = new Dictionary<string, PropertyInfo>();
foreach (var property in propertyInfo) {
dict[property.Name] = property;
}
typeCache[objectType] = dict;
return dict;
}
// Return the item from the cache
return typeCache[objectType];
}
/// <summary>
/// Determines if the given type is the dictionary type that we traverse.
///
/// We use a hash set to cache the types we know to be dictionary types - so we can avoid the
/// cost of reflection.
/// </summary>
private bool IsDictionaryType(Type objectType) {
if (dictionaryTypes.ContainsKey(objectType)) {
return dictionaryTypes[objectType];
}
var isAssignable = DictionaryType.IsAssignableFrom(objectType);
dictionaryTypes[objectType] = isAssignable;
return isAssignable;
}
}
}
|
b3fa1853b110eeea61530d683547437f82eeb3e3
|
C#
|
tofitaV/SeleniumTest
|
/Test/UnitTest1.cs
| 2.6875
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.Threading;
namespace Test
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
using (IWebDriver driver = new ChromeDriver())
{
driver.Url = "http://automationpractice.com";
driver.FindElement(By.XPath(".//*[@class='login']")).Click();
Thread.Sleep(500);
driver.FindElement(By.XPath(".//*[@name='email_create']")).SendKeys("test342424421@gmail.com");
driver.FindElement(By.XPath(".//*[@id='SubmitCreate']")).Click();
Thread.Sleep(2000);
driver.FindElement(By.XPath(".//*[@id='customer_firstname']")).SendKeys("name");
driver.FindElement(By.XPath(".//*[@id='customer_lastname']")).SendKeys("lastname");
driver.FindElement(By.XPath(".//*[@id='passwd']")).SendKeys("123456789");
driver.FindElement(By.XPath(".//*[@id='firstname']")).SendKeys("firstname");
driver.FindElement(By.XPath(".//*[@id='lastname']")).SendKeys("lastname");
driver.FindElement(By.XPath(".//*[@id='address1']")).SendKeys("street");
driver.FindElement(By.XPath(".//*[@id='city']")).SendKeys("kherson");
SelectElement oSelect = new SelectElement(driver.FindElement(By.XPath(".//*[@id='id_state']")));
oSelect.SelectByText("Texas");
driver.FindElement(By.XPath(".//*[@id='postcode']")).SendKeys("73000");
SelectElement oSelectC = new SelectElement(driver.FindElement(By.XPath(".//*[@id='id_state']")));
oSelectC.SelectByValue("21");
driver.FindElement(By.XPath(".//*[@id='phone_mobile']")).SendKeys("+3801234567");
Thread.Sleep(3000);
driver.FindElement(By.XPath(".//*[@id='submitAccount']")).Click();
Thread.Sleep(2000);
IWebElement element = driver.FindElement(By.XPath(".//*[@class='account']"));
String attValue = element.Text;
Assert.AreEqual("name lastname", attValue);
}
}
}
}
|
fddc0145d13f06381944a02b2cc89313c5ad4051
|
C#
|
yuki332/DGM1600_repo
|
/var and function/Assets/varAndFunc.cs
| 2.921875
| 3
|
using UnityEngine;
using System.Collections;
public class varAndFunc : MonoBehaviour
{
int myInt = 60;
// Use this for initialization
void Start () {
int first = devideByTwo (myInt);
int second = multipleByThree (myInt);
Debug.Log (first);
Debug.Log (second);
}
int devideByTwo (int number)
{
int rel;
rel = number / 2;
return rel;
}
int multipleByThree (int number)
{
int rel;
rel = number * 3;
return rel;
}
}
|
60b2618c67e86b9a8131e3316ad17a21ad496253
|
C#
|
putschoeglwe/SemVer
|
/SemVer/SemVer/Ident.cs
| 2.828125
| 3
|
namespace SemVer
{
public abstract class Ident {}
public class Numeric : Ident
{
public Numeric(ulong n)
{
Number = n;
}
public ulong Number { get; }
}
public class AlphaNumeric : Ident
{
public AlphaNumeric(string value)
{
Value = value;
}
public string Value { get; }
}
}
|
2c91aa02dbcd2e150cf6aabfe1e737871d4e0cb8
|
C#
|
MartinRichards23/SystemPlus
|
/SystemPlus.Windows/Converters/DoubleIntConverter.cs
| 2.953125
| 3
|
using System;
using System.Globalization;
using System.Windows.Data;
namespace SystemPlus.Windows.Converters
{
/// <summary>
/// Converts a Double to Int
/// </summary>
[ValueConversion(typeof(int), typeof(double))]
public class DoubleIntConverter : IValueConverter
{
public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return 0;
return System.Convert.ToDouble(value, CultureInfo.CurrentCulture);
}
public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return 0;
return System.Convert.ToInt32(value, CultureInfo.CurrentCulture);
}
}
}
|
b1eec0eca7f1dc17858812f2840450c2a183b5f4
|
C#
|
shendongnian/download4
|
/code9/1646663-46666030-158013652-6.cs
| 2.546875
| 3
|
using System;
using System.Windows.Input;
using System.Windows.Media;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
Test.MouseEnter += TestOnMouseEnter;
Test.MouseLeave += TestOnMouseLeave;
MouseDown += OnMouseDown;
}
private void TestOnMouseEnter(object sender, MouseEventArgs mouseEventArgs)
{
Console.WriteLine("(Test) MouseEnter");
Test.Fill = Brushes.Coral;
}
private void TestOnMouseLeave(object sender, MouseEventArgs mouseEventArgs)
{
Console.WriteLine("(Test) MouseLeave");
Test.Fill = Brushes.Blue;
}
private void OnMouseMove(object sender, MouseEventArgs mouseEventArgs)
{
Console.WriteLine("(Window) MouseMove");
var pos = NativeMouseHook.GetMousePosition();
Line.X2 = pos.X;
Line.Y2 = pos.Y;
}
private void OnMouseDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
Console.WriteLine("(Window) MouseDown");
NativeMouseHook.RegisterMouseHandler(NativeMouseHook.MouseMessages.WM_MOUSEMOVE, (MouseEventHandler)OnMouseMove);
NativeMouseHook.RegisterMouseHandler(NativeMouseHook.MouseMessages.WM_LBUTTONUP, OnMouseUp);
var pos = mouseButtonEventArgs.GetPosition(this);
Line.X1 = pos.X;
Line.Y1 = pos.Y;
}
private void OnMouseUp(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
Console.WriteLine("(Window) MouseUp");
NativeMouseHook.UnregisterMouseHandler(NativeMouseHook.MouseMessages.WM_MOUSEMOVE, (MouseEventHandler)OnMouseMove);
NativeMouseHook.UnregisterMouseHandler(NativeMouseHook.MouseMessages.WM_LBUTTONUP, OnMouseUp);
}
}
}
|
fa19f67066d680b9cd17aab5f0ef085cff0ac9b8
|
C#
|
Niels-Ver/StraatModel
|
/StraatModel/DataReader.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml;
namespace StraatModel
{
public class DataReader
{
public void leesData()
{
char[] seperator = { ';' };
string[] gesplitsteData;
string data;
//Uitlezen van WRdata en aanmaken van een segmentenMap
Dictionary<int, List<Segment>> segmentMap = new Dictionary<int, List<Segment>>();
using (StreamReader r = new StreamReader(@"D:\Niels\School\Prog3\WRdata\WRdata.csv"))
{
Dictionary<int, Knoop> knoopMap = new Dictionary<int, Knoop>();
r.ReadLine(); //eerste lijn staat info over bestand, dit is niet nodig
while ((data = r.ReadLine()) != null)
{
gesplitsteData = data.Split(seperator);
int linkerstraatId = int.Parse(gesplitsteData[6]);
int rechterStraatId = int.Parse(gesplitsteData[7]);
if (!(linkerstraatId == -9 && rechterStraatId == -9))
{
string geo = gesplitsteData[1];
geo = geo.Substring(11);
geo = geo.Trim('(', ')');
string[] splitGeo = geo.Split(',');
List<Punt> vertices = new List<Punt>();
foreach (string coords in splitGeo)
{
string coordsTrim = coords.Trim();
String[] splitCoords = coordsTrim.Split(' ');
//Console.WriteLine($"x Coord = {splitCoords[0]}, y coord = {splitCoords[1]}");
Punt punt = new Punt(decimal.Parse(splitCoords[0].Replace('.', ',')), decimal.Parse(splitCoords[1].Replace('.', ',')));
vertices.Add(punt);
}
//Opmaken van het ingelezen wegsegment
int wegSegmentId = int.Parse(gesplitsteData[0]);
int beginWegknoopID = int.Parse(gesplitsteData[4]);
int eindWegknoopID = int.Parse(gesplitsteData[5]);
if (!knoopMap.ContainsKey(beginWegknoopID))
{
Knoop beginKnoop = new Knoop(beginWegknoopID, vertices.First());
knoopMap.Add(beginWegknoopID, beginKnoop);
}
if (!knoopMap.ContainsKey(eindWegknoopID))
{
Knoop eindKnoop = new Knoop(eindWegknoopID, vertices.First());
knoopMap.Add(eindWegknoopID, eindKnoop);
}
Segment segment = new Segment(wegSegmentId, knoopMap[beginWegknoopID], knoopMap[eindWegknoopID], vertices);
addToSegmentMap(linkerstraatId, segment);
addToSegmentMap(rechterStraatId, segment);
}
}
}
void addToSegmentMap(int straatId, Segment segment)
{
//checken of de linkerstraat een geldige input heeft
if (straatId != -9)
{
//kijken of de linkerstraat al een bestaande graaf in de map heeft
if (segmentMap.ContainsKey(straatId))
{
//Kijken of het aangemaakte segment nog niet aanwezig is in de graaf
if (!segmentMap[straatId].Contains(segment))
{
segmentMap[straatId].Add(segment);
}
}
else
{
List<Segment> segmentList = new List<Segment>();
segmentList.Add(segment);
segmentMap.Add(straatId, segmentList);
}
}
}
//Uitlezen van Straatnamen bij straatId en aanmaken van een dictionary van alle straten.
Dictionary<int, String> straatNaamDictionary = new Dictionary<int, String>();
Dictionary<int, Straat> straatDictionary = new Dictionary<int, Straat>();
int graafId = 1;
using (StreamReader r = new StreamReader(@"D:\Niels\School\Prog3\WRdata\WRstraatnamen.csv"))
{
r.ReadLine(); //eerste lijn staat info over bestand, dit is niet nodig
r.ReadLine(); //2de lijn staat ook onnodige info
while ((data = r.ReadLine()) != null)
{
gesplitsteData = data.Split(seperator);
int straatId = int.Parse(gesplitsteData[0]);
string straatNaam = gesplitsteData[1];
straatNaamDictionary.Add(straatId,straatNaam.Trim());
}
foreach (int straatId in segmentMap.Keys)
{
straatDictionary.Add(straatId, new Straat(straatId, straatNaamDictionary[straatId], Graaf.buildGraaf(graafId, segmentMap[straatId])));
graafId++;
}
}
//Uitlezen van link tussen gemeenteId en straatId
Dictionary<int, List<Straat>> gemeenteStraatIdDictionary = new Dictionary<int, List<Straat>>();
using (StreamReader r = new StreamReader(@"D:\Niels\School\Prog3\WRdata\WRGemeenteID.csv"))
{
r.ReadLine(); //eerste lijn staat info over bestand, dit is niet nodig
while ((data = r.ReadLine()) != null)
{
gesplitsteData = data.Split(seperator);
int straatnaamId = int.Parse(gesplitsteData[0]);
int gemeenteId = int.Parse(gesplitsteData[1]);
if(segmentMap.ContainsKey(straatnaamId))
{
if (gemeenteStraatIdDictionary.ContainsKey(gemeenteId))
gemeenteStraatIdDictionary[gemeenteId].Add(straatDictionary[straatnaamId]);
else
{
List<Straat> straatList = new List<Straat>();
straatList.Add(straatDictionary[straatnaamId]);
gemeenteStraatIdDictionary.Add(gemeenteId, straatList);
}
}
}
}
//Uitlezen van Gemeentenamen en aanmaken dictionary van alle gemeentes
Dictionary<int, Gemeente> gemeenteDictionary = new Dictionary<int, Gemeente>();
using (StreamReader r = new StreamReader(@"D:\Niels\School\Prog3\WRdata\WRGemeentenaam.csv"))
{
r.ReadLine(); //eerste lijn staat info over bestand, dit is niet nodig
while ((data = r.ReadLine()) != null)
{
gesplitsteData = data.Split(seperator);
if (gesplitsteData[2] == "nl")
{
int gemeenteId = int.Parse(gesplitsteData[1]);
string gemeenteNaam = gesplitsteData[3];
//Lijst opmaken met alle straten die bij deze gemeente horen
if(gemeenteStraatIdDictionary.ContainsKey(gemeenteId))
{
gemeenteDictionary.Add(gemeenteId, new Gemeente(gemeenteId, gemeenteNaam.Trim(), gemeenteStraatIdDictionary[gemeenteId]));
}
}
}
}
//Uitlezen Province Id en Provincie Naam
Dictionary<int, Provincie> provincieDictionary = new Dictionary<int, Provincie>();
List<int> provincieIdList = new List<int>();
using (StreamReader r = new StreamReader(@"D:\Niels\School\Prog3\WRdata\ProvincieInfo.csv"))
{
r.ReadLine(); //eerste lijn staat info over bestand, dit is niet nodig
while ((data = r.ReadLine()) != null)
{
gesplitsteData = data.Split(seperator);
int gemeenteId = int.Parse(gesplitsteData[0]);
int provincieId = int.Parse(gesplitsteData[1]);
string taalcode = gesplitsteData[2];
string provincieNaam = gesplitsteData[3];
if (taalcode == "nl")
{
if(gemeenteDictionary.ContainsKey(gemeenteId))
{
if (provincieDictionary.ContainsKey(provincieId))
provincieDictionary[provincieId].gemeentes.Add(gemeenteDictionary[gemeenteId]);
else
{
List<Gemeente> gemeentes = new List<Gemeente>();
gemeentes.Add(gemeenteDictionary[gemeenteId]);
Provincie toeTeVoegenProvincie = new Provincie(provincieId, provincieNaam.Trim(), gemeentes);
provincieDictionary.Add(provincieId, toeTeVoegenProvincie);
}
}
}
}
}
//Uitlezen te verwerken Provincies en een Dictionairy opmaken met enkel deze provincies
Dictionary<int, Provincie> finaleDictionary = new Dictionary<int, Provincie>();
using (StreamReader r = new StreamReader(@"D:\Niels\School\Prog3\WRdata\ProvincieIDsVlaanderen.csv"))
{
data = r.ReadLine();
gesplitsteData = data.Split(',');
foreach (String id in gesplitsteData)
{
var filteredDictionary = provincieDictionary.Where(p => p.Key == int.Parse(id));
foreach (var dictionary in filteredDictionary)
{
finaleDictionary.Add(dictionary.Key, dictionary.Value);
}
}
}
generateRaport(finaleDictionary);
//serializeData(finaleDictionary);
}
public void generateRaport(Dictionary<int, Provincie> provincies)
{
string path = @"D:\Niels\School\Prog3\Rapport.txt";
if (File.Exists(path))
{
File.Delete(path);
}
using (StreamWriter sw = new StreamWriter(path, true))
{
int totaalAantalStratenProvincies = 0;
foreach (Provincie provincie in provincies.Values)
{
var straten = provincie.gemeentes.Select(g => g.straatList.Count());
foreach (var item in straten)
{
totaalAantalStratenProvincies += item;
}
}
sw.WriteLine($"Totaal aantal straten: {totaalAantalStratenProvincies}\n");
sw.WriteLine("Totaal aantal straten per provincie");
foreach (int provincieId in provincies.Keys)
{
int aantalStraten = 0;
var straten = provincies[provincieId].gemeentes.Select(g => g.straatList.Count());
foreach (var item in straten)
{
aantalStraten += item;
}
sw.WriteLine($"\t{provincies[provincieId].provincieNaam} : {aantalStraten}");
}
sw.WriteLine("\n");
foreach (int provincieId in provincies.Keys)
{
sw.WriteLine("StraatInfo " + provincies[provincieId].provincieNaam);
foreach (Gemeente gemeente in provincies[provincieId].gemeentes)
{
decimal totaleLengte = 0;
Straat kortsteStraat = gemeente.straatList[0];
Straat langsteStraat = gemeente.straatList[0];
decimal lengteKortsteStraat = 0;
decimal lengteLangsteStraat = 0;
for (int i = 0; i < gemeente.straatList.Count; i++)
{
Straat straat = gemeente.straatList[i];
decimal straatLengte = calculateLength(straat);
totaleLengte += straatLengte;
if (i == 0)
{
kortsteStraat = straat;
langsteStraat = straat;
lengteKortsteStraat = straatLengte;
lengteLangsteStraat = straatLengte;
}
else
{
if (straatLengte > lengteLangsteStraat)
{
langsteStraat = straat;
lengteLangsteStraat = straatLengte;
}
else if (straatLengte < lengteKortsteStraat)
{
kortsteStraat = straat;
lengteKortsteStraat = straatLengte;
}
}
}
sw.WriteLine($"\t* {gemeente.gemeenteNaam} : <{gemeente.straatList.Count()}>, <{Math.Round(totaleLengte, 2)}>");
sw.WriteLine($"\t\t kortste straat: {kortsteStraat.straatnaam.Trim()} met Id: {kortsteStraat.straatId} met een lengte van {Math.Round(lengteKortsteStraat, 2)}");
sw.WriteLine($"\t\t langste straat: {langsteStraat.straatnaam.Trim()} met Id: {langsteStraat.straatId} met een lengte van {Math.Round(lengteLangsteStraat, 2)}");
}
}
}
decimal calculateLength(Straat straat)
{
HashSet<Segment> uniqueSegments = new HashSet<Segment>();
//Alle segmenten uit de graaf in 1 collectie steken
IEnumerable<Segment> segmentList = straat.graaf.map.SelectMany(x => x.Value);
//Segmenten in een hashset steken zodat we segmenten geen 2 keer bij de lengte bij rekenen
foreach (Segment segment in segmentList)
{
uniqueSegments.Add(segment);
}
decimal totaleLengte = 0;
foreach (Segment segment in uniqueSegments)
{
for (int i = 0; i < segment.vertices.Count - 1; i++)
{
Punt punt1 = segment.vertices[i];
Punt punt2 = segment.vertices[i + 1];
double lengteTussenPunten = Math.Sqrt(Math.Pow(((double)punt1.x - (double)punt2.x), 2) + Math.Pow(((double)punt1.y - (double)punt2.y), 2));
totaleLengte += (decimal)lengteTussenPunten;
}
}
return totaleLengte;
}
}
public void serializeData(Dictionary<int, Provincie> provincies)
{
Dictionary<int, Provincie> testProvincie = new Dictionary<int, Provincie>();
testProvincie.Add(1, provincies[1]);
string path = @"D:\Niels\School\Prog3\XMLSerial.xml";
var serializer = new DataContractSerializer(provincies.GetType());
string xmlString;
using (var sw = new StreamWriter(path))
{
using (var writer = new XmlTextWriter(sw))
{
writer.Formatting = Formatting.Indented; // indent the Xml so it's human readable
serializer.WriteObject(writer, provincies);
writer.Flush();
xmlString = sw.ToString();
}
}
}
}
}
|
e49ae8c480ccd4747a7090e220dcf54895c6b0c3
|
C#
|
carlos-hribeiro/Versus-Fighter
|
/PorradaEngine/Collision/HittableBox.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace PorradaEngine.Collision
{
/// <summary>
/// Representa os boxes de colisao do tipo Hit
/// </summary>
public class HittableBox : CollisionBox
{
public HittableBox(int x, int y, int w, int h)
: base(x, y, w, h)
{
}
protected override Color getColorRectangle()
{
return new Color(0, 0, 200, 100);
}
protected override Color getColorBorderRectangle()
{
return new Color(0, 0, 220);
}
}
}
|
49173cb5ddf901e7218998abe78ae018503a0f95
|
C#
|
Azure-Samples/service-fabric-dotnet-web-reference-app
|
/ReferenceApp/Web.Service/Controllers/OrdersController.cs
| 2.546875
| 3
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Web.Service.Controllers
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Common;
using CustomerOrder.Domain;
using Microsoft.ServiceFabric.Actors;
using Microsoft.ServiceFabric.Actors.Client;
using Microsoft.AspNetCore.Mvc;
public class OrdersController : Controller
{
private const string CustomerOrderServiceName = "CustomerOrderActorService";
/// <summary>
/// POST api/orders
/// Based on a shopping cart passed into the method, PostCheckout creates an actor proxy object to activate an actor instance of CustomerOrderActor,
/// which is used to represent the state of the customer order. Through the actor proxy, the FulfillOrderAsync method is invoked on the actor
/// to fulfill the customer order by removing items from inventory.
///
/// In the current version of this example, the shopping cart which a customer uses to check out exists
/// entirely on the client side. A shopping cart, in this example, is therefore stateless and its state is
/// only committed to memory when a customer order is created and an Actor Id is associated with it.
///
/// Because the status of an order is changed inside the FulfillOrderAsync method, the OrdersController relies
/// on a separate GetStatus method that the client can call to see if the Status of the order has changed to completed.
/// There is currently no event notification to the WebUI frontend if an order completes.
///
/// </summary>
/// <param name="cart"></param>
/// <returns>Guid to identify the order and allow for status look-up later.</returns>
[HttpPost]
[Route("api/orders")]
public async Task<Guid> PostCheckout(List<CustomerOrderItem> cart)
{
ServiceEventSource.Current.Message("Now printing cart for POSTCHECKOUT...");
foreach (CustomerOrderItem item in cart)
{
ServiceEventSource.Current.Message("Guid {0}, quantity {1}", item.ItemId.ToString(), item.Quantity.ToString());
}
Guid orderId = Guid.NewGuid();
ServiceUriBuilder builder = new ServiceUriBuilder(CustomerOrderServiceName);
//We create a unique Guid that is associated with a customer order, as well as with the actor that represents that order's state.
ICustomerOrderActor customerOrder = ActorProxy.Create<ICustomerOrderActor>(new ActorId(orderId), builder.ToUri());
try
{
await customerOrder.SubmitOrderAsync(cart);
ServiceEventSource.Current.Message("Customer order submitted successfully. ActorOrderID: {0} created", orderId);
}
catch (InvalidOperationException ex)
{
ServiceEventSource.Current.Message("Web Service: Actor rejected {0}: {1}", customerOrder, ex);
throw;
}
catch (Exception ex)
{
ServiceEventSource.Current.Message("Web Service: Exception {0}: {1}", customerOrder, ex);
throw;
}
return orderId;
}
/// <summary>
/// Looks up a customer order based on its Guid identifier and by using an ActorProxy, retrieves the order's status and returns it to the client.
/// </summary>
/// <param name="customerOrderId"></param>
/// <returns>String</returns>
[HttpGet]
[Route("api/orders/{customerOrderId}")]
public Task<string> GetOrderStatus(Guid customerOrderId)
{
ServiceUriBuilder builder = new ServiceUriBuilder(CustomerOrderServiceName);
ICustomerOrderActor customerOrder = ActorProxy.Create<ICustomerOrderActor>(new ActorId(customerOrderId), builder.ToUri());
try
{
return customerOrder.GetOrderStatusAsStringAsync();
}
catch (Exception ex)
{
ServiceEventSource.Current.Message("Web Service: Exception {0}: {1}", customerOrder, ex);
throw;
}
}
}
}
|
0524a2b79036821f7ce8efbc29611267bfb57feb
|
C#
|
GlitchEnzo/Hayao
|
/Vapor/Graphics/VertexPositionTextureNormal.cs
| 2.5625
| 3
|
namespace Vapor
{
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
public struct VertexPositionTextureNormal : IVertexType
{
public Vector4 Position;
public Vector3 TextureCoordinates;
public Vector3 Normal;
public VertexPositionTextureNormal(Vector4 position, Vector3 texCoords, Vector3 normal)
{
Position = position;
TextureCoordinates = texCoords;
Normal = normal;
}
public InputElement[] GetInputElements()
{
// TODO: Optimize it by caching the array?
return new InputElement[]
{
new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), // 4 bytes * 4 = 16 bytes
new InputElement("TEXCOORD", 0, Format.R32G32B32_Float, 16, 0), // 4 bytes * 3 = 12 bytes
new InputElement("NORMAL", 0, Format.R32G32B32_Float, 28, 0)
};
}
}
}
|
6efbf6e2911b3cc9441ab4ac9c98694b0519b37d
|
C#
|
sk8tz/quantfabric
|
/src/Foundations/CurrentAppDomain.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Foundations
{
public static class CurrentAppDomain
{
/// <summary>
/// Get all of the loaded assemblies in the current app domain
/// </summary>
/// <returns>List of loaded assemblies OR null if System.AppDomain.CurrentDomain.GetAssemblies is not available</returns>
public static List<Assembly> GetAssemblies()
{
try
{
var currentdomain = typeof(string)
.GetTypeInfo()
.Assembly
.GetType("System.AppDomain")
.GetRuntimeProperty("CurrentDomain")
.GetMethod
.Invoke(null, new object[] { });
var getassemblies = currentdomain
.GetType()
.GetRuntimeMethod("GetAssemblies", new Type[] { });
var assemblies = getassemblies
.Invoke(currentdomain, new object[] { }) as Assembly[];
return assemblies.ToList();
}
catch (Exception)
{
return null;
}
}
}
}
|
afce75bb4713f79ca14ccd930622df1f45bff83d
|
C#
|
Altadsa/Rocket
|
/Assets/Scripts/Rocket.cs
| 2.578125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Rocket
{
public class Rocket : MonoBehaviour
{
public static int starsCollected = 0;
[SerializeField]
Vector2Constant startPos;
[SerializeField]
Sprite defaultSprite;
[SerializeField]
Event onGameOver;
#region SINGLETON
private static Rocket instance;
private static readonly object padlock = new object();
public static Rocket Instance
{
get
{
lock (padlock)
{
if (!instance)
{
instance = FindObjectOfType<Rocket>();
}
return instance;
}
}
}
#endregion
private void OnEnable()
{
transform.position = startPos.Value;
starsCollected = 0;
}
public Sprite GetActiveSprite()
{
Sprite activeSprite = GetComponentInChildren<SpriteRenderer>().sprite;
if (!activeSprite) { return null; }
return activeSprite;
}
public Sprite GetDefaultSprite()
{
if (!defaultSprite) { return null; }
return defaultSprite;
}
public void SetActiveSprite(Sprite spriteToSet)
{
GetComponentInChildren<SpriteRenderer>().sprite = spriteToSet;
}
public void DestroyRocket()
{
gameObject.SetActive(false);
PlayerPreferences.CurrentPlayerPreferences.AddStars(starsCollected);
onGameOver.Raise();
}
public void AddItem(GameObject itemToAdd)
{
HandleLaserCannonItem(itemToAdd);
}
private void HandleLaserCannonItem(GameObject itemToAdd)
{
if (CanRocketEquipItem(itemToAdd))
{
GameObject itemInstance = Instantiate(itemToAdd);
itemInstance.transform.parent = transform;
}
else
{
GetComponentInChildren<LaserCannon>().AddAmmo();
}
}
private bool CanRocketEquipItem(GameObject itemToAdd)
{
if (!GetComponentInChildren<LaserCannon>()
|| itemToAdd.GetComponent<EDT>()
|| itemToAdd.GetComponent<TDD>())
{
return true;
}
return false;
}
public void AddStar()
{
starsCollected++;
}
}
}
|
da53baa0d17f99f00bac0b061d2991a11e0d7b25
|
C#
|
Zeeger/email-template
|
/VisualEmailTemplater/VisualEmailTemplater/GenericFunctions.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VisualEmailTemplater
{
class GenericFunctions<T>
{
public string ConcatenateList(IList<T> input, T delimiter)
{
var output = string.Empty;
foreach (var item in input)
{
output += item.ToString() + delimiter;
}
output = output.TrimEnd(delimiter.ToString().ToCharArray());
return output;
}
}
}
|
5146ff8191b727cd84172e240be887bd29022da3
|
C#
|
AlexLunyov/TypiconOnline
|
/TypiconOnline.Domain.Rules/Serialization/RuleXmlSerializerContainer T.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using TypiconOnline.Domain.Interfaces;
namespace TypiconOnline.Domain.Serialization
{
/// <summary>
/// Реализация контейнера фабрик для xml-вариации представления элементов правил
/// </summary>
/// <typeparam name="T"></typeparam>
public class RuleXmlSerializerContainer<T> : RuleSerializerContainerBase<T> where T: IRuleElement
{
public RuleXmlSerializerContainer(IRuleSerializerRoot serializerRoot) : base(serializerRoot, new XmlDescriptor()) { }
protected override void LoadFactories()
{
/*
* делаем выборку всех классов - наследников RuleXmlFactoryBase
* и где T является базовым для реализаций IRuleFactory<T>
*/
var typesInThisAssembly = GetTypes();
foreach (var type in typesInThisAssembly)
{
//IRuleFactory<T> factory1 = Activator.CreateInstance(type, _unitOfWork);
var factory = Activator.CreateInstance(type, SerializerRoot) as IRuleSerializer;
if (factory.ElementNames != null)
{
foreach (string name in factory.ElementNames)
{
Factories.Add(name, factory);
}
}
}
}
protected virtual IEnumerable<Type> GetTypes()
{
return (from type in Assembly.GetExecutingAssembly().GetTypes()
from z in type.GetInterfaces()
where type.IsSubclassOf(typeof(RuleXmlSerializerBase))
&& !type.IsAbstract
&& z.Name == typeof(IRuleSerializer<T>).Name
&& (z.GenericTypeArguments[0].Equals(typeof(T))
|| z.GenericTypeArguments[0].IsSubclassOf(typeof(T)))
select type).Distinct();
}
}
}
|
158d5897781752dba5851c88bb03f2a5e0de27f5
|
C#
|
joopspide/MailMergeLib
|
/MailMergeLib.Tests/Helper.cs
| 2.984375
| 3
|
using System;
using System.IO;
using System.Reflection;
namespace MailMergeLib.Tests
{
internal class Helper
{
/// <summary>
/// Gets the path of code base for the executing assembly.
/// </summary>
/// <remarks>
/// The Assembly.Location property sometimes gives wrong results when using NUnit (where assemblies run from a temporary folder).
/// That's why we need reliable way to find the assembly location, which is the base for relativ data folders.
/// </remarks>
/// <returns></returns>
public static string GetCodeBaseDirectory()
{
return Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
}
internal static int Compare(Stream a, Stream b)
{
if (a == null && b == null) return 0;
if (a == null || b == null) throw new ArgumentNullException(a == null ? "a" : "b");
a.Position = b.Position = 0;
if (a.Length < b.Length) return -1;
if (a.Length > b.Length) return 1;
int bufa;
while ((bufa = a.ReadByte()) != -1)
{
var bufb = b.ReadByte();
var diff = bufa.CompareTo(bufb);
if (diff != 0) return diff;
}
return 0;
}
}
}
|
b47a4351c3dae25e4ecfc9d6ad3131f4b014318e
|
C#
|
nikogrig/Software-University
|
/02 Prog. Fundamentals Extended - C#/15 - Lists - Exercises/15 - Lists - Exercises/03.01 FoldAndSum/FoldAndSum.cs
| 3.671875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03._01_FoldAndSum
{
class FoldAndSum
{
static void Main(string[] args)
{
int[] arrNums = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
int parameter = arrNums.Length / 4;
int[] upperArr = new int[parameter * 2];
int[] lowerArr = new int[parameter * 2];
for (int i = 0; i < parameter; i++)
{
upperArr[i] = arrNums[parameter - 1 - i];
upperArr[upperArr.Length - i - 1] = arrNums[arrNums.Length - parameter + i];
}
for (int i = 0; i < parameter * 2; i++)
{
lowerArr[i] = arrNums[i + parameter];
}
int[] sumOfArrs = new int[upperArr.Length];
for (int i = 0; i < upperArr.Length; i++)
{
sumOfArrs[i] = upperArr[i] + lowerArr[i];
}
Console.WriteLine(string.Join(" ", sumOfArrs));
}
}
}
|
d6f2385eb41488ba79116cde8492dc907eefaa68
|
C#
|
ake698/Diary_Plus
|
/TestDemo/Program.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace TestDemo
{
class Program
{
static void Main(string[] args)
{
string a = "d";
Assembly assembly = Assembly.Load("Diary.BLL");
var classes = assembly.GetTypes().ToList().Where(s => !s.IsInterface && s.Name.EndsWith("Profiles"));
foreach (var c in classes)
{
Console.WriteLine(c);
var p = c.GetInterfaces()
.ToList()
.Where(s => s.Name.Equals($"I{c.Name}"));
}
}
}
}
|
36bbdb0b94797da7d08a9d9c3dd2919f029975c4
|
C#
|
AlefNaught/Daily
|
/CorvinsDay_v1/CorvinsDay_v1/CorvinsDay_v1/Program.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using System.Xml.XPath;
namespace CorvinsDay_v1
{
public static class Items
{
static public List<Item> items;
static public void ItemsInGame()
{
items.Add(new Item{ItemName = "Test0"});
items.Add(new Item{ItemName = "Test1"});
items.Add(new Item{ItemName = "Test2"});
items.Add(new Item{ItemName = "Test3"});
}
}
public class Item
{
public static List<Item> items;
public string ItemName { get; set; }
public bool IsHeld { get; set; }
public string take { get; set; }
public string discard { get; set; }
public override string ToString()
{
return string.Join(",", ItemName);
}
}
class Program
{
public Item instItem = new Item();
public List<Item> onCharacter = new List<Item>();
public void Inventory()
{
onCharacter.Add(new Item{IsHeld = false, ItemName = "Test0"});
onCharacter.Add(new Item{IsHeld = false, ItemName = "Test1"});
onCharacter.Add(new Item{IsHeld = false, ItemName = "Test2"});
onCharacter.Add(new Item{IsHeld = false, ItemName = "Test3"});
foreach (var x in onCharacter)
{
Console.WriteLine(x);
}
}
public void Dialog(string message)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(message);
Console.ResetColor();
}
public void Continue(string forward)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(forward);
Console.ResetColor();
}
public void Character()
{
Dialog("Welcome to Corvin's Day. Now, you'll need a name.\nPlease enter it: ");
string charName = Console.ReadLine();
if (charName != "Corvin")
{
Dialog("No your name is Corvin.\n");
Dialog("The game is called Corvin's Day you dumbass.\n");
Continue("Press any key to continue...\n");
Console.ReadLine();
Dialog("Here, I'll just do it for since you're apparently autistic beyond belief.\n");
Dialog(">string charName = 'Corvin'\n");
Dialog("It was too easy, jesus.\n");
charName = "Corvin";
Continue("Press any key to continue...\n");
}
else
{
Dialog("Welcome to class Corvin.\n");
Continue("Press any key to continue...\n");
Console.ReadLine();
}
}
static void Main(string[] args)
{
Program runProg = new Program();
runProg.Character();
}
}
}
|
2519fd713bfbf61c61bef4c4e25c6fb1ac820327
|
C#
|
HebaSamirAli/workshop.webapp
|
/backend/Services/WorkshopService/WorkshopService.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using backend.model;
namespace backend.Services.WorkshopService
{
public class WorkshopService : IWorkshopService
{
private readonly ApplicationDbContetxt _db;
public WorkshopService(ApplicationDbContetxt db)
{
_db = db;
}
public async Task<List<Workshop>> GetAllWorkshops()
{
List<Workshop> workshopsFromDb = new List<Workshop>();
foreach (Workshop workshop in _db.Workshop) { workshopsFromDb.Add(workshop); };
return workshopsFromDb;
}
public async Task<Workshop> GetWorkshopDetails(int id)
{
Workshop workshopsFromDb = new Workshop();
foreach (Workshop workshop in _db.Workshop)
{
if (workshop.WorkshopId == id) { workshopsFromDb = workshop; }
};
return workshopsFromDb;
}
}
}
|
df7b1cc1f7308576123c2a2dadce39782e413fc4
|
C#
|
dipaksutare101/OrderIT.CS
|
/OrderIT.Model/Partials/Order2.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace OrderIT.Model {
public partial class Order : IDataErrorInfo {
void OnActualShippingDateChanged(Nullable<System.DateTime> value){
if (value.HasValue && EstimatedShippingDate.HasValue && value.Value < EstimatedShippingDate.Value) {
//errors.Add("ActualShippingDate", "Actual shipping date cannot be lower that estimated shipping date");
}
}
Dictionary<string, string> errors = new Dictionary<string, string>();
#region IDataErrorInfo Members
string IDataErrorInfo.Error {
get { return errors.Any() ? "There are errors" : String.Empty; }
}
string IDataErrorInfo.this[string columnName] {
get {
if (errors.ContainsKey(columnName))
return errors[columnName];
else
return String.Empty;
}
}
#endregion
}
}
|
c69f76d828ceff3caae512d002fe4678babc70f3
|
C#
|
Biomancer81/Corvinus
|
/src/Corvinus.Data/Serialization/XmlSerializer.cs
| 3
| 3
|
// <copyright file="XmlSerializer.cs" company="Corvinus Software">
// Copyright (c) Corvinus Software. All rights reserved.
// </copyright>
namespace Corvinus.Data.Serialization
{
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
/// <summary>
/// Provides methods for easily serializing and deserializing objects to xml.
/// </summary>
public class XmlSerializer : IDeserializeFile, IDeserializeStream, IDeserializeString, ISerializeFile, ISerializeStream, ISerializeString
{
/// <summary>
/// Initializes a new instance of the <see cref="XmlSerializer"/> class.
/// </summary>
public XmlSerializer()
{
}
/// <summary>Deserializes an object from a XML file.</summary>
/// <typeparam name="T">Type of object to deserialize.</typeparam>
/// <param name="path">Source file path.</param>
/// <returns>Deserialized object.</returns>
public T DeserializeFile<T>(string path)
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (XmlReader xmlReader = XmlReader.Create(path))
{
return (T)serializer.Deserialize(xmlReader);
}
}
/// <summary>Deserializes an object from a XML stream. Will not close the stream.</summary>
/// <typeparam name="T">Type of object to deserialize.</typeparam>
/// <param name="input">Input stream.</param>
/// <returns>Deserialized object.</returns>
public T DeserializeStream<T>(Stream input)
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (XmlReader xmlReader = XmlReader.Create(input))
{
return (T)serializer.Deserialize(xmlReader);
}
}
/// <summary>Deserializes an object from a XML string.</summary>
/// <typeparam name="T">Type of object to deserialize.</typeparam>
/// <param name="input">Input string.</param>
/// <returns>Deserialized object.</returns>
public T DeserializeString<T>(string input)
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (XmlReader xmlReader = XmlReader.Create(input))
{
return (T)serializer.Deserialize(xmlReader);
}
}
/// <summary>Serializes an object as XML to a file.</summary>
/// <param name="input">Object to serialize.</param>
/// <param name="path">Destination file path.</param>
/// <param name="append">If true and the file exists it will be appended to,
/// otherwise it will be overwritten.</param>
public void SerializeFile(object input, string path, bool append = false)
{
Type type = input.GetType();
if (type.IsSerializable)
{
var serializer = new System.Xml.Serialization.XmlSerializer(type);
using (TextWriter xmlWriter = new StreamWriter(path, append))
{
serializer.Serialize(xmlWriter, input);
}
}
}
/// <summary>Serializes an object as XML to a stream. Will not close the stream.</summary>
/// <param name="input">Object to serialize.</param>
/// <param name="outStream">Output stream.</param>
public void SerializeStream(object input, Stream outStream)
{
Type type = input.GetType();
if (type.IsSerializable)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
StreamWriter streamWriter = new StreamWriter(
outStream,
Encoding.UTF8,
bufferSize: 4096,
leaveOpen: true);
using (XmlTextWriter xmlWriter = new XmlTextWriter(streamWriter))
{
serializer.Serialize(xmlWriter, input);
}
}
}
/// <summary>Serializes an object to a XML string.</summary>
/// <param name="input">Object to serialize.</param>
/// <returns>String the object was serialized to.</returns>
public string SerializeString(object input)
{
Type type = input.GetType();
if (type.IsSerializable)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
using (StringWriter xmlWriter = new StringWriter())
{
serializer.Serialize(xmlWriter, input);
return xmlWriter.ToString();
}
}
else
{
return null;
}
}
}
}
|
66a0487f0814db0fb304a8287e2f673dd4ef750c
|
C#
|
DevVKorenkov/TruckReport
|
/TruckReportLibF/Abstract/Report.cs
| 2.9375
| 3
|
using System;
using System.IO;
using TruckReportLibF.Models;
namespace TruckReportLibF.Abstract
{
/// <summary>
/// Абстрактный класс отчета
/// </summary>
[Serializable]
public abstract class Report
{
public string id;
/// <summary>
/// Номер объекта
/// </summary>
public string TruckNumber { get; set; }
/// <summary>
/// Должность сотрудника
/// </summary>
public string EmployeePosition { get; set; }
/// <summary>
/// Дата начала отчета
/// </summary>
public DateTime StartReportDate { get; set; }
public DateTime CurrentReportDate { get; set; }
/// <summary>
/// Тип отчета
/// </summary>
public ReportType ReportType { get; set; }
/// <summary>
/// Переодичность формирования отчета
/// </summary>
public Frequency Frequency { get; set; }
public Report(string truckNumber, string employeePosition, ReportType reportType, Frequency frequency)
{
id = Path.GetRandomFileName();
TruckNumber = truckNumber;
EmployeePosition = employeePosition;
ReportType = reportType;
Frequency = frequency;
}
public Report()
{
}
}
}
|
097fc050779482eac225ba0170583825a9846ed2
|
C#
|
dannyseins/Arca
|
/Verdezul.IDH.DataAccess/EstadoAlumnoDataAccess.Basicos.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Verdezul.IDH.Entidades;
namespace Verdezul.IDH.DataAccess
{
/// <summary>
/// Clase de Acceso a Datos para EstadoAlumno
/// </summary>
public partial class EstadoAlumnoDataAccess : GenericDataAccess
{
/// <summary>
/// Selecciona EstadoAlumnos.
/// </summary>
/// <param name="Id">Id de EstadoAlumno</param>
/// <returns>EstadoAlumnoDataSet</returns>
public EstadoAlumnoDataSet.EstadoAlumnoDataTable Seleccionar(int id)
{
return ((EstadoAlumnoDataSet)SQLConexion.Seleccionar("EstadoAlumno_Seleccionar", id, typeof(EstadoAlumnoDataSet))).EstadoAlumno;
}
/// <summary>
/// Inserta un nuevo EstadoAlumno.
/// </summary>
/// <param name="ds">Conjunto de datos tipo EstadoAlumno a Insertar.</param>
/// <returns>Id de EstadoAlumno Insertado</returns>
public int Insertar(EstadoAlumnoDataSet ds)
{
EstadoAlumnoDataSet.EstadoAlumnoRow cr = ds.EstadoAlumno[0];
SqlParameter[] parametros = {
SqlParameterOutput("Id", DbType.Int32),
SqlParameterInput("Nombre", cr.Nombre)
};
return SQLConexion.Insertar("EstadoAlumno_Insertar", parametros);
}
/// <summary>
/// Modifica un EstadoAlumno.
/// </summary>
/// <param name="ds">Conjunto de datos tipo EstadoAlumno a Modificar.</param>
public int Modificar(EstadoAlumnoDataSet ds)
{
EstadoAlumnoDataSet.EstadoAlumnoRow cr = ds.EstadoAlumno[0];
SqlParameter[] parametros = {
SqlParameterInput("Id", cr.Id),
SqlParameterInput("Nombre", cr.Nombre)
};
return SQLConexion.Modificar("EstadoAlumno_Modificar", parametros);
}
/// <summary>
/// Borra un EstadoAlumno
/// </summary>
/// <param name="ds">Conjunto de datos tipo EstadoAlumno a Borrar.</param>
public int Borrar(EstadoAlumnoDataSet ds)
{
EstadoAlumnoDataSet.EstadoAlumnoRow cr = ds.EstadoAlumno[0];
SqlParameter[] parametros = { SqlParameterInput("Id", cr.Id) };
return SQLConexion.Borrar("EstadoAlumno_Borrar", parametros);
}
/// <summary>
/// Borra un EstadoAlumno
/// </summary>
/// <param name="id">Identificador de EstadoAlumno</param>
public int Borrar(int id)
{
SqlParameter[] parametros = { SqlParameterInput("Id", id) };
return SQLConexion.Borrar("EstadoAlumno_Borrar", parametros);
}
}
}
|
fe09c26635dc618051ad7272cd726aed3badc79a
|
C#
|
AD1967/backlog
|
/KALITKA-master/Actual Project/Assets/Scripts/GameLog/Events/RollDiceButtonScript.cs
| 2.625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// Скрипт для кнопки броска кубиков.
// Прикреплен к кнопке, соответственно,
// работает с кнопкой
public class RollDiceButtonScript : MonoBehaviour
{
public AudioClip RollAudio;
void Update(){
if(GameSettings.GameWithBot && MapGenerator.turn && MapGenerator.turn_count == 0 && MapGenerator.players[0] > 0 && MapGenerator.players[1] > 0){
RollDice();
GameBot.frame = 0;
}
// Делаем кнопку недоступной если пользователь ещё может сходить (MapGenerator.turn_count > 0;
GetComponent<Button>().interactable = (MapGenerator.turn_count == 0 && MapGenerator.players[0] > 0 && MapGenerator.players[1] > 0);
}
///<summary>
/// Функция броска кубиков.
/// При срабатывании меняет количество ходов пользователя
/// от 1 до 3 (включительно).
///</summary>
public void RollDice(){
//Присваиваем переменной количества ходов рандомное значение от 1 до 3 включительно.
PlaySound(RollAudio);
MapGenerator.turn_count = Random.Range(1, 4);
}
private void PlaySound(AudioClip sound)
{
//Объявляем компонент на объекте скрипта
var Source = GetComponent<AudioSource>();
//Меняем на нужный нам звук
Source.clip = sound;
//Меняем звук в зависимости на которые в настройках игры
Source.volume = GameSettings.GameVolume;
//Проигрываем звук
Source.Play();
}
}
|
3acb16848eacdb109cd7af052e1ffd00ddc0295a
|
C#
|
txdv/meetcurses
|
/MeetCurses/Widgets/Entry.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using Mono.Terminal;
namespace MeetCurses
{
public class Entry : Widget
{
private int position = 0;
public int Position {
get {
return position;
}
set {
int oldPosition = position;
if (value > Text.Length) {
position = text.Length;
OnPositionChanged(oldPosition);
} else if (value <= 0) {
position = 0;
OnPositionChanged(oldPosition);
} else if (position != value) {
position = value;
OnPositionChanged(oldPosition);
}
}
}
private string text = "";
public string Text {
get {
return text;
}
set {
position = Math.Min(position, (value.Length > 0 ? value.Length + 1 : 0));
string oldText = text;
text = value;
OnTextChanged(oldText);
}
}
public Entry()
: base()
{
}
public override bool CanFocus {
get {
return true;
}
}
public override void Redraw()
{
base.Redraw();
Fill(Text);
SetCursorPosition();
}
protected int GetFirstNonWhiteSpace()
{
int i = Position;
while (i >= Text.Length) {
i--;
}
for (; i > 0; i--) {
if (Text[i] != ' ') {
return i;
}
}
return 0;
}
protected int GetFirstWhiteSpace()
{
int i = Position;
while (i >= Text.Length) {
i--;
}
for (; i > 0; i--) {
if (Text[i] == ' ') {
return i;
}
}
return 0;
}
protected int GetFirst()
{
if (Text[Position - 1] == ' ') {
return GetFirstNonWhiteSpace();
} else {
return GetFirstWhiteSpace();
}
}
const int ctrl = 96;
public override bool ProcessKey(int key)
{
char ch = (char)key;
Invalid = true;
switch (key) {
case (int)'a' - ctrl:
Position = 0;
return true;
case (int)'e' - ctrl:
Position = Text.Length;
return true;
case (int)'w' - ctrl:
if (Position == 1) {
Text = Text.Substring(1);
Position = 0;
} else if (Position != 0) {
int i = GetFirst() + 1;
if (i == 1) {
Text = Text.Substring(Position);
Position = 0;
} else {
Text = Text.Substring(0, i);
Position = i;
}
}
return true;
case 126:
if (Position < Text.Length) {
Text = Text.Substring(0, Text.Length - 1);
}
return true;
case 127:
case Curses.Key.Backspace:
if (Position > 0) {
Text = Text.Substring(0, Position - 1) + Text.Substring(Position);
Position--;
}
return true;
case Curses.Key.Left:
if (Position > 0) {
Position--;
}
return true;
case Curses.Key.Right:
if (Position < Text.Length) {
Position++;
}
return true;
case Curses.Key.Delete:
if (Position < Text.Length) {
Text = Text.Substring(0, Position) + Text.Substring(Position + 1);
}
return true;
case 10:
OnEnter();
return true;
default:
if (key < 32 || key > 255) {
return false;
} else {
Text = Text.Substring(0, Position) + ch + Text.Substring(Position);
Position++;
return true;
}
}
}
public override void SetCursorPosition()
{
Move(Position, 0);
}
protected virtual void OnTextChanged(string oldText)
{
if (TextChanged != null) {
TextChanged(oldText);
}
}
public event Action<string> TextChanged;
protected virtual void OnPositionChanged(int oldPosition)
{
if (PositionChanged != null) {
PositionChanged(oldPosition);
}
}
public event Action<int> PositionChanged;
protected virtual void OnEnter()
{
if (Enter != null) {
Enter();
}
}
public event Action Enter;
}
}
|
2d589397ebcda49ea8ea989d387d106111e20f35
|
C#
|
alincamv/TwitterRepository
|
/Models/UserModel_LOCAL_8300.cs
| 2.515625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Models
{
public class UserModel
{ [RegularExpression("^([0]\\d{8})|([+]\\d{11})",
ErrorMessage = "You've entered the wrong format number")]
public string PhoneNumber { get; set; }
public string Avatar { get; set; }
public int Id { get; set; }
[Required]
[RegularExpression("^([A-Za-z]{3,25})\\s([A-Za-z]{3,25})",
ErrorMessage = "* Please enter your full name")]
public string FullName { get; set; }
[Required]
[RegularExpression("^([a-zA-Z0-9_\\-\\.]+)@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$",
ErrorMessage = "* Email is not a valid e-mail address.")]
public string Email { get; set; }
[Required]
[RegularExpression("^[\\._a-zA-Z0-9]{3,30}",
ErrorMessage = "* Username can contain folowing characters:_,A-Z,0-9")]
public string Username { get; set; }
[Required]
[RegularExpression("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\.#?!@$%^&*-]).{6,}$",
ErrorMessage = "The password must contain: A-Z,a-z,0-9,.@#$%^&*" +
"The minimum length should be 6 characters")]
public string Password { get; set; }
public string Location { get; set; }
public DateTime? DateOfBirth { get; set; }
public DateTime? DateOfRegistration { get; set; }
public virtual ICollection<TweetModel> Tweet { get; set; }
}
}
|
18be4f04ad641c22098ef97543513618383e8888
|
C#
|
ilMes/MiscUtilsLib
|
/Src/LinqExtensions.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace BtmI2p.MiscUtils
{
public static class LinqExtensions
{
public static IEnumerable<Tuple<int, T1>> WithIndex<T1>(
this IEnumerable<T1> enumerable
)
{
return enumerable.Select((item, i) => Tuple.Create(i, item));
}
}
}
|
aaa2b0d283bf8f057268d78f425a0597ada10194
|
C#
|
Kaliumhexacyanoferrat/GenHTTP
|
/Modules/Conversion/Providers/Forms/FormContent.cs
| 2.515625
| 3
|
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using GenHTTP.Api.Protocol;
namespace GenHTTP.Modules.Conversion.Providers.Forms
{
public sealed class FormContent : IResponseContent
{
#region Get-/Setters
public ulong? Length => null;
private Type Type { get; }
private object Data { get; }
#endregion
#region Initialization
public FormContent(Type type, object data)
{
Type = type;
Data = data;
}
#endregion
#region Functionality
public ValueTask<ulong?> CalculateChecksumAsync()
{
return new ValueTask<ulong?>((ulong)Data.GetHashCode());
}
public async ValueTask WriteAsync(Stream target, uint bufferSize)
{
using var writer = new StreamWriter(target, Encoding.UTF8, (int)bufferSize, true);
var query = HttpUtility.ParseQueryString(string.Empty);
foreach (var property in Type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var value = DeriveValue(property.GetValue(Data), property.PropertyType);
if (value is not null)
{
query[property.Name] = Convert.ToString(value, CultureInfo.InvariantCulture);
}
}
foreach (var field in Type.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
var value = DeriveValue(field.GetValue(Data), field.FieldType);
if (value is not null)
{
query[field.Name] = Convert.ToString(value, CultureInfo.InvariantCulture);
}
}
var replaced = query?.ToString()?
.Replace("+", "%20")
.Replace("%2b", "+");
await writer.WriteAsync(replaced);
}
private static object? DeriveValue(object? value, Type sourceType)
{
if (sourceType == typeof(bool) && value is not null)
{
return ((bool)value) ? 1 : 0;
}
return value;
}
#endregion
}
}
|
9fbc49746b7cb0bdb984ad0320ea0b7e5db949a9
|
C#
|
Team-Mieszalnik/CuadradosDeMiedo
|
/Assets/MainMenu/Scripts/StatsManager.cs
| 2.5625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StatsManager
{
public static float BestTime
{
get => PlayerPrefs.GetFloat("BestTime", 0);
set
{
float prevBestTime = PlayerPrefs.GetFloat("BestTime", 0);
if (value < prevBestTime)
PlayerPrefs.SetFloat("BestTime", value);
}
}
public static int HighestLevel
{
get => PlayerPrefs.GetInt("HighestLevel", 0);
set
{
int prevBestLevel = PlayerPrefs.GetInt("HighestLevel", 0);
if (value > prevBestLevel)
PlayerPrefs.SetInt("HighestLevel", value);
}
}
public static int EnemiesKilled
{
get => PlayerPrefs.GetInt("EnemiesKilled", 0);
set
{
int prevKills = PlayerPrefs.GetInt("EnemiesKilled", 0);
prevKills += value;
PlayerPrefs.SetInt("EnemiesKilled", prevKills);
}
}
}
|
9dd36407c99ecce733558c6b98ec99b799892ca2
|
C#
|
mobileappsgame/Adventures-of-Zombies
|
/Assets/Scripts/Menu/UI/ChangeSettingsButton.cs
| 2.578125
| 3
|
using UnityEngine;
using UnityEngine.UI;
namespace Cubra
{
public abstract class ChangeSettingsButton : MonoBehaviour
{
[Header("Спрайты кнопок")]
[SerializeField] protected Sprite[] _sprites;
// Ссылка на компонент
protected Image _imageButton;
protected virtual void Awake()
{
_imageButton = GetComponent<Image>();
}
/// <summary>
/// Изменение спрайта кнопки настроек
/// </summary>
/// <param name="number">номер спрайта</param>
protected virtual void ChangeSprite(int number)
{
_imageButton.sprite = _sprites[number];
}
}
}
|
6bebfb96dff2b2c2a73546c8c8310aa29f7e1c08
|
C#
|
FS-Frost/Asu.Utilidades
|
/Core/AssFile/AttachedGraphic.cs
| 2.875
| 3
|
using Asu.Utils.Constants;
using System.Collections.Generic;
namespace Asu.Utils.Core.AssFile {
/// <summary>
/// Representa una imagen adjunta a un archivo ASS.
/// </summary>
public class AttachedGraphic : AttachedFile {
public override AttachedFileType Type => AttachedFileType.Graphic;
/// <summary>
/// Inicializa una nueva instancia de la clase <see cref="AttachedGraphic"/>.
/// </summary>
public AttachedGraphic() {
Name = string.Empty;
Data = new List<string>();
}
/// <summary>
/// Inicializa una nueva instancia de la clase <see cref="AttachedGraphic"/>.
/// </summary>
/// <param name="name">Nombre de la imagen.</param>
/// <param name="data">Lista con los datos.</param>
public AttachedGraphic(string name, List<string> data) {
Name = name;
Data = data;
}
}
}
|
bfa8b36f22ccb83bf157802f725daa60322a643b
|
C#
|
EivindTvedtenErsland/net_project
|
/net_project.Api/Repositories/MongoDBItemsRepository.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;
using net_project.Api.Api.Interfaces;
using net_project.Api.Api.Models;
namespace net_project.Api.Api.Repositories
{
public class MongoDBItemsReposity : ItemsRepositoryInterface
{
private readonly IMongoCollection<Item> itemsCollectionMongoDB;
private const string databaseName = "mongodb";
private const string collectionName = "items";
private readonly FilterDefinitionBuilder<Item> filterBuilder = Builders<Item>.Filter;
public MongoDBItemsReposity(IMongoClient mongoClient)
{
IMongoDatabase mongoDB = mongoClient.GetDatabase(databaseName);
itemsCollectionMongoDB = mongoDB.GetCollection<Item>(collectionName);
}
public async Task<Item> GetItemAsync(Guid guid)
{
var filter = filterBuilder.Eq(item => item.Id, guid);
return await itemsCollectionMongoDB.Find(filter).SingleOrDefaultAsync();
}
public async Task<IEnumerable<Item>> GetItemsAsync()
{
return await itemsCollectionMongoDB.Find(new BsonDocument()).ToListAsync();
}
public async Task PostItemAsync(Item item)
{
await itemsCollectionMongoDB.InsertOneAsync(item);
}
public async Task DeleteItemAsync(Item item)
{
var filter = filterBuilder.Eq(existingItem => existingItem.Id, item.Id);
await itemsCollectionMongoDB.DeleteOneAsync(filter);
}
public async Task PutItemAsync(Item item)
{
var filter = filterBuilder.Eq(existingItem => existingItem.Id, item.Id);
await itemsCollectionMongoDB.ReplaceOneAsync(filter, item);
}
}
}
|
41f47d6e01ae2d3b2547ac8577935e340618f4a7
|
C#
|
trigger-segfault/TriggersTools.SharpUtils
|
/src/TriggersTools.SharpUtils/Collections/ImmutableArrayLW.cs
| 2.578125
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
namespace TriggersTools.SharpUtils.Collections {
/// <summary>
/// A lightweight immutable array so that including System.Collections.Immutable is not required.
/// </summary>
/// <typeparam name="T">The element type of the array.</typeparam>
[Serializable]
[DebuggerDisplay("Length = {Count}")]
[DebuggerTypeProxy(typeof(TriggersTools_CollectionDebugView<>))]
public class ImmutableArrayLW<T> : IReadOnlyList<T>, IList<T>, IList {
#region Fields
/// <summary>
/// The wrapped array of items contained in the immutable array.
/// </summary>
private readonly T[] array;
#endregion
#region Constructors
public ImmutableArrayLW(IEnumerable<T> source) {
if (source == null)
throw new ArgumentNullException(nameof(source));
if (source is ICollection<T> collection) {
array = new T[collection.Count];
collection.CopyTo(array, 0);
}
else if (source is IReadOnlyList<T> readOnlyList) {
array = new T[readOnlyList.Count];
for (int i = 0; i < array.Length; i++)
array[i] = readOnlyList[i];
}
else if (source is IReadOnlyCollection<T> readOnlyCollection) {
array = new T[readOnlyCollection.Count];
int i = 0;
foreach (T item in readOnlyCollection) {
array[i] = item;
i++;
}
}
else {
array = source.ToArray();
}
}
#endregion
#region Properties
public int Count => array.Length;
bool IList.IsFixedSize => true;
bool IList.IsReadOnly => true;
bool ICollection<T>.IsReadOnly => true;
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => array.SyncRoot;
#endregion
#region IList Implementation (Accessors)
public T this[int index] {
get => array[index];
set => ThrowImmutable();
}
object IList.this[int index] {
get => array[index];
set => ThrowImmutable();
}
public bool Contains(T item) => ((ICollection<T>) array).Contains(item);
bool IList.Contains(object value) => ((IList) array).Contains(value);
public void CopyTo(T[] array, int arrayIndex) => ((ICollection<T>) array).CopyTo(array, arrayIndex);
void ICollection.CopyTo(Array array, int index) => array.CopyTo(array, index);
public int IndexOf(T item) => ((IList<T>) array).IndexOf(item);
int IList.IndexOf(object value) => ((IList) array).IndexOf(value);
public T[] ToArray() {
T[] newArray = new T[array.Length];
Array.Copy(array, newArray, array.Length);
return newArray;
}
public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>) array).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => array.GetEnumerator();
#endregion
#region IList Implementation (Not Supported)
void ICollection<T>.Add(T item) => ThrowImmutable();
int IList.Add(object value) {
ThrowImmutable();
return 0;
}
void ICollection<T>.Clear() => ThrowImmutable();
void IList.Clear() => ThrowImmutable();
void IList<T>.Insert(int index, T item) => ThrowImmutable();
void IList.Insert(int index, object value) => ThrowImmutable();
void IList<T>.RemoveAt(int index) => ThrowImmutable();
void IList.RemoveAt(int index) => ThrowImmutable();
bool ICollection<T>.Remove(T item) {
ThrowImmutable();
return false;
}
void IList.Remove(object value) => ThrowImmutable();
#endregion
#region Private Helpers
/// <summary>
/// Throws a <see cref="NotSupportedException"/> within mutator methods.
/// </summary>
///
/// <exception cref="NotSupportedException">
/// A mutator method is being called.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void ThrowImmutable() {
throw new NotSupportedException("Collection is immutable!");
}
#endregion
}
}
|
f5a38866d2ce1fed2584b3b6590bfb477a93cfd9
|
C#
|
erusseva/CSharp
|
/CSharp Part 2 HW/3.Methods/10. N Factorial/10. N Factorial.cs
| 4.21875
| 4
|
using System;
class NFactorial
{
//Write a program to calculate n! for each n in the range [1..100].
public static string NumberMultiplyer(string number, int digit)
{
string result = null;
int step = 0;
for (int i = number.Length - 1; i >= 0; i--)
{
int currentDigit = int.Parse(number[i].ToString());
int currentProduct = currentDigit * digit;
if (currentProduct + step < 10)
{
result = (currentProduct + step) + result;
}
else
{
result = ((currentProduct + step) % 10) + result;
step = (currentProduct + step) / 10;
}
}
if (step != 0)
{
result = step + result;
}
return result;
}
public static void Main()
{
Console.Write("Enter a positive integer [1..100]: ");
int n = int.Parse(Console.ReadLine());
string answer = "1";
for (int i = 2; i <= n; i++)
{
answer = NumberMultiplyer(answer, i);
}
Console.WriteLine("{0}! = {1}", n, answer);
}
}
|
51a56d6831b390c67a6b1121e896a92faa22c11c
|
C#
|
Strialck/Sea-Battle-Game
|
/SeaBattle/SeaBattle.CSharp.Tests/RectTests.cs
| 2.953125
| 3
|
using NUnit.Framework;
using SeatBattle.CSharp;
namespace SeaBattle.CSharp.Tests
{
public class RectTests
{
[Test, ExpectedException]
public void Cannot_Create_Rect_With_Negative_Width_In_Ctor()
{
var rect = new Rect(0, 0, -1, 1);
}
[Test, ExpectedException]
public void Cannot_Create_Rect_With_Zero_Width_In_Ctor()
{
var rect = new Rect(0, 0, 0, 1);
}
[Test]
public void Width_Accepts_Positive_Value()
{
// Arrange
var rect = new Rect(0, 0, 1, 1);
// Act
rect.Width = 2;
// Assert
Assert.AreEqual(2, rect.Width);
}
[Test, ExpectedException]
public void Width_DoesNot_Accept_Negative_Value()
{
// Arrange
var rect = new Rect(0, 0, 1, 1);
// Act
rect.Width = -1;
}
[Test, ExpectedException]
public void Width_DoesNot_Accept_Zero_Value()
{
// Arrange
var rect = new Rect(0, 0, 1, 1);
// Act
rect.Width = 0;
}
[Test, ExpectedException]
public void Cannot_Create_Rect_With_Negative_Height_In_Ctor()
{
var rect = new Rect(0, 0, 1, -1);
}
[Test, ExpectedException]
public void Cannot_Create_Rect_With_Zero_Height_In_Ctor()
{
var rect = new Rect(0, 0, 1, 0);
}
[Test]
public void Height_Accepts_Positive_Value()
{
// Arrange
var rect = new Rect(0, 0, 1, 1);
// Act
rect.Height = 2;
// Assert
Assert.AreEqual(2, rect.Height);
}
[Test, ExpectedException]
public void Height_DoesNot_Accept_Negative_Value()
{
// Arrange
var rect = new Rect(0, 0, 1, 1);
// Act
rect.Height = -1;
}
[Test, ExpectedException]
public void Height_DoesNot_Accept_Zero_Value()
{
// Arrange
var rect = new Rect(0, 0, 1, 1);
// Act
rect.Height = 0;
}
[Test]
public void Cointains_ShouldReturn_False_For_Outside_Rect()
{
// Arrange
var outer = new Rect(0, 0, 10, 10);
var outer2 = new Rect(11, 11, 5, 5);
// Act
var result = outer.Contains(outer2);
// Assert
Assert.IsFalse(result);
}
[Test]
public void Cointains_ShouldReturn_True_For_Inside_Rect()
{
// Arrange
var outer = new Rect(0, 0, 10, 10);
var inner = new Rect(1, 1, 5, 5);
// Act
var result = outer.Contains(inner);
// Assert
Assert.IsTrue(result);
}
[Test]
public void Cointains_ShouldReturn_True_For_Inside_Rect_AtTopLeftCorner()
{
// Arrange
var outer = new Rect(0, 0, 10, 10);
var inner = new Rect(0, 0, 5, 5);
// Act
var result = outer.Contains(inner);
// Assert
Assert.IsTrue(result);
}
[Test]
public void Cointains_ShouldReturn_True_For_Inside_Rect_AtTopRightCorner()
{
// Arrange
var outer = new Rect(0, 0, 10, 10);
var inner = new Rect(5, 5, 5, 5);
// Act
var result = outer.Contains(inner);
// Assert
Assert.IsTrue(result);
}
[Test]
public void Cointains_ShouldReturn_True_For_Inside_Rect_AtBottomLeftCorner()
{
// Arrange
var outer = new Rect(0, 0, 10, 10);
var inner = new Rect(0, 9, 5, 1);
// Act
var result = outer.Contains(inner);
// Assert
Assert.IsTrue(result);
}
[Test]
public void Cointains_ShouldReturn_True_For_Inside_Rect_AtBottomRightCorner()
{
// Arrange
var outer = new Rect(0, 0, 10, 10);
var inner = new Rect(8, 8, 2, 2);
// Act
var result = outer.Contains(inner);
// Assert
Assert.IsTrue(result);
}
[Test]
public void Cointains_ShouldReturn_False_For_Intersecting_Rect()
{
// Arrange
var outer = new Rect(0, 0, 10, 10);
var outer2 = new Rect(-10, 5, 100, 3);
// Act
var result = outer.Contains(outer2);
// Assert
Assert.IsFalse(result);
}
[Test]
public void Intersects_ShouldReturn_False_For_NonIntersectingRects()
{
// Arrange
var r1 = new Rect(0, 0, 10, 10);
var r2 = new Rect(11, 11, 10, 10);
// Act
var result1 = r1.IntersectsWith(r2);
var result2 = r2.IntersectsWith(r1);
// Assert
Assert.IsFalse(result1);
Assert.IsFalse(result2);
}
[Test]
public void Intersects_ShouldReturn_True_For_CrossingRects()
{
// Arrange
var r1 = new Rect(0, 3, 10, 2);
var r2 = new Rect(4, 0, 2, 10);
// Act
var result1 = r1.IntersectsWith(r2);
var result2 = r2.IntersectsWith(r1);
// Assert
Assert.IsTrue(result1);
Assert.IsTrue(result2);
}
[Test]
public void Intersects_ShouldReturn_True_For_IntersectingRects_At_TopLeft_BottomRight()
{
// Arrange
var r1 = new Rect(1, 1, 5, 5);
var r2 = new Rect(3, 3, 6, 6);
// Act
var result1 = r1.IntersectsWith(r2);
var result2 = r2.IntersectsWith(r1);
// Assert
Assert.IsTrue(result1);
Assert.IsTrue(result2);
}
[Test]
public void Intersects_ShouldReturn_True_For_IntersectingRects_At_TopRight_BottomLeft()
{
// Arrange
var r1 = new Rect(4, 1, 5, 5);
var r2 = new Rect(0, 4, 6, 6);
// Act
var result1 = r1.IntersectsWith(r2);
var result2 = r2.IntersectsWith(r1);
// Assert
Assert.IsTrue(result1);
Assert.IsTrue(result2);
}
[Test]
public void Intersects_ShouldReturn_True_For_Contained_Rect()
{
// Arrange
var outer = new Rect(0, 0, 10, 10);
var inner = new Rect(5, 5, 2, 2);
// Act
var result1 = outer.IntersectsWith(inner);
var result2 = inner.IntersectsWith(outer);
// Assert
Assert.IsTrue(result1);
Assert.IsTrue(result2);
}
[Test]
public void Intersects_ShouldReturn_False_For_Touching_Rects()
{
// Arrange
var rect = new Rect(0, 0, 10, 10);
var n = new Rect(0, -10, 10, 10);
var ne = new Rect(10, -10, 10, 10);
var e = new Rect(10,0,10,10);
var se = new Rect(10,10,10,10);
var s = new Rect(0,10,10,10);
var sw = new Rect(-10,10,10,10);
var w = new Rect(-10,0,10,10);
var nw = new Rect(-10,-10,10,10);
// Act
var result1 = rect.IntersectsWith(n);
var result2 = rect.IntersectsWith(ne);
var result3 = rect.IntersectsWith(e);
var result4 = rect.IntersectsWith(se);
var result5 = rect.IntersectsWith(s);
var result6 = rect.IntersectsWith(sw);
var result7 = rect.IntersectsWith(w);
var result8 = rect.IntersectsWith(nw);
// Assert
Assert.IsFalse(result1);
Assert.IsFalse(result2);
Assert.IsFalse(result3);
Assert.IsFalse(result4);
Assert.IsFalse(result5);
Assert.IsFalse(result6);
Assert.IsFalse(result7);
Assert.IsFalse(result8);
}
}
}
|
8394f092a321f2c9608f2b5a44ca18074832696e
|
C#
|
jaideng123/Useful-Unity
|
/Base Classes/VariableScriptableObject.cs
| 2.5625
| 3
|
using UnityEngine;
public abstract class VariableScriptableObject<T> : ScriptableObject
{
public T defaultValue;
[SerializeField]
private T _currentValue;
public T currentValue
{
get { return _currentValue; }
set { _currentValue = value; }
}
private void OnEnable()
{
hideFlags = HideFlags.DontUnloadUnusedAsset;
_currentValue = defaultValue;
}
public override string ToString()
{
return currentValue.ToString();
}
}
|
c6c1addc82013cd4e4cd62b05fbba60c341e7fa5
|
C#
|
Kaster/CalibreCatalog
|
/KasterUtil/Exception/BaseException.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KasterUtil.Exception {
/// <summary>
/// Base class for all Auto Panel exceptions.
/// </summary>
public abstract class BaseException : System.Exception {
/// <summary> Holder for the original exception. </summary>
public System.Exception originalException { get; set; }
public string message { get; set; }
public string name { get; set; }
public bool toDump { get; set; }
/// <summary>
/// Default constructor
/// </summary>
public BaseException() {
this.name = "Generic AutoPanel Exception";
this.toDump = true;
}
/// <summary>
/// Constructor taking representative name of the exception family
/// </summary>
/// <param name="name"></param>
public BaseException(string name) {
this.name = name;
this.toDump = true;
}
/// <summary>
/// Setter that initializes the oroginal exception data.
/// </summary>
/// <param name="e"></param>
public BaseException set(System.Exception e) {
return this.set(e, null, true);
}
/// <summary>
/// Setter than initializes the custom message.
/// </summary>
/// <param name="message"></param>
public BaseException set(string message) {
return this.set(null, message, true);
}
/// <summary>
/// Setter that initializes both the original exception and the custom message.
/// </summary>
/// <param name="e"></param>
/// <param name="message"></param>
public BaseException set(System.Exception e, string message) {
return this.set(e, message, true);
}
/// <summary>
/// Setter that initailized the original exception and message, while also
/// marking whether this particular excepton needs to be dumped or not.
/// </summary>
/// <param name="e"></param>
/// <param name="message"></param>
/// <param name="toDump"></param>
/// <returns></returns>
public BaseException set(System.Exception e, string message, bool toDump) {
this.originalException = e;
this.message = message;
this.toDump = toDump;
return this;
}
}
}
|
4677d98b2766b51fe9bdc2b9cffd071b1fd12e08
|
C#
|
BDmitriev/US-Wahlkampf
|
/US_Whal_Grafisch/US_Whal_Grafisch/Program.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using US_Whal_Grafisch.model;
namespace US_Whal_Grafisch
{
public enum Geschlecht { Weiblich, Maenlich, Default }
public enum Alter { Erstwaehler, Bis30, Bis40, Bis50, Restliche, Default }
public enum Schicht { Unterschicht, Unteremittelschicht, Oberemittelschicht, Oberschicht, Default }
public enum PolitischeHeimat { Republikaner, Demokraten, Default }
public enum Beeinflussbarkeit { Leicht, Mittel, Schwer, Default }
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Console.ReadLine();
}
public static List<Wähler> Filtern(Form1.Parameter p)
{
List<Wähler> wl_link = new List<Wähler>();
FileStream fs9 = File.Open("us_wahl_liste.txt", FileMode.Open);
StreamReader sr9 = new StreamReader(fs9);
string line;
Geschlecht geschlecht = Geschlecht.Default;
Alter alter = Alter.Default;
Schicht schicht = Schicht.Default;
PolitischeHeimat ph = PolitischeHeimat.Default;
Beeinflussbarkeit be = Beeinflussbarkeit.Default;
while ((line = sr9.ReadLine()) != null)
{
switch (line.Split(' ')[4])
{
case "Maenlich":
geschlecht = Geschlecht.Maenlich;
break;
case "Weiblich":
geschlecht = Geschlecht.Weiblich;
break;
}
switch (line.Split(' ')[5])
{
case "Erstwaehler":
alter = Alter.Erstwaehler;
break;
case "Bis30":
alter = Alter.Bis30;
break;
case "Bis40":
alter = Alter.Bis40;
break;
case "Bis50":
alter = Alter.Bis50;
break;
case "Restliche":
alter = Alter.Restliche;
break;
}
switch (line.Split(' ')[6])
{
case "Unterschicht":
schicht = Schicht.Unterschicht;
break;
case "Unteremittelschicht":
schicht = Schicht.Unteremittelschicht;
break;
case "Oberemittelschicht":
schicht = Schicht.Oberemittelschicht;
break;
case "Oberschicht":
schicht = Schicht.Oberschicht;
break;
}
switch (line.Split(' ')[7])
{
case "Demokraten":
ph = PolitischeHeimat.Demokraten;
break;
case "Republikaner":
ph = PolitischeHeimat.Republikaner;
break;
}
switch (line.Split(' ')[8])
{
case "Leicht":
be = Beeinflussbarkeit.Leicht;
break;
case "Mittel":
be = Beeinflussbarkeit.Mittel;
break;
case "Schwer":
be = Beeinflussbarkeit.Schwer;
break;
}
wl_link.Add( new Wähler() { ID = line.Split(' ')[0],
Vorname = line.Split(' ')[1],
Nachname = line.Split(' ')[2],
PLZ = line.Split(' ')[3],
Geschlecht = geschlecht,
Alter = alter,
Schicht = schicht,
PolitischeHeimat = ph,
Beeinflussbarkeit = be
});
}
fs9.Close();
var wl_link2 = from wähler in wl_link
where
wähler.PolitischeHeimat == p.PolitischeHeimat &&
wähler.Geschlecht == p.Geschlecht
//wähler.Alter == Alter.Erstwaehler &&
//wähler.Schicht == Schicht.OBERSCHICHT &&
//wähler.PLZ > 47111 &&
//wähler.PLZ < 80000 &&
//wähler.Beeinflussbarkeit == Beeinflussbarkeit.Leicht
select wähler;
List<Wähler> ww = wl_link2.ToList();
return wl_link2.ToList();
}
}
}
|
9b932faeaccfa9710f8dd425e0d8967fd92f9ea6
|
C#
|
MichaelMcQuirk/BusinessgameProductionManager
|
/Businessgame Production Manager/TSector.cs
| 2.671875
| 3
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
public class TSector
{
public string name = "";
public double price = 0.00;
public double employees = 0.00;
public double fixedprice = 0.00;
public int units = 0;
public List<TProduct> Machinery = new List<TProduct>();
public List<TProduct> Input = new List<TProduct>();
public List<TProduct> Output = new List<TProduct>();
//For Extra Features
public int unitsBeforeBuyMode = 0;
public TSector(string _name = "", double _price = 0, double _employees = 0, double _fixedprice = 0, int _units = 0, List<TProduct> _machinery = null, List<TProduct> _input = null, List<TProduct> _output = null)
{
name = _name;
price = _price;
employees = _employees;
fixedprice = _fixedprice;
units = _units;
if (_machinery != null) Machinery = _machinery;
if (_input != null) Input = _input;
if (_output != null) Output = _output;
}
}
}
|
6b8ef80db876691d8e26cbde670ab64532bfe8ea
|
C#
|
malsoft-pl/dotnet-concept-vertical
|
/Concept.Vertical.Messaging.InMemory/MessagePublisher.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Concept.Vertical.Messaging.Abstractions;
using Newtonsoft.Json;
namespace Concept.Vertical.Messaging.InMemory
{
public class MessagePublisher : IMessagePublisher
{
private readonly JsonSerializer _jsonSerializer;
private const string JsonContent = "application/json";
public MessagePublisher(JsonSerializer jsonSerializer)
{
_jsonSerializer = jsonSerializer;
}
public Task PublishAsync<TMessage>(TMessage message, CancellationToken token)
{
var routingKey = typeof(TMessage).Name;
var body = SerializeMessage(message);
var props = new BasicProperties
{
Type = routingKey,
ContentType = JsonContent,
Headers = new Dictionary<string, string>(),
MessageId = Guid.NewGuid().ToString()
};
MessageBroker.BasicPublish(routingKey, props, body);
return Task.CompletedTask;
}
private byte[] SerializeMessage(object message)
{
using (var writer = new StringWriter())
using (var jsonWriter = new JsonTextWriter(writer))
{
_jsonSerializer.Serialize(jsonWriter, message);
var json = writer.ToString();
return Encoding.UTF8.GetBytes(json);
}
}
}
}
|
8bfe2500fa0a1971af36b6547a7efd396b6d0977
|
C#
|
gishjl/DataManager
|
/satics_school/csDBHelper.cs
| 2.875
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace satics_school
{
public enum enumSaticsType
{
eCount,
eArea,
eUnknown
}
public class csDBHelper
{
#region 存储过程操作
/// <summary>
/// 执行存储过程 返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>OracleDataReader</returns>
public static void RunProcedure(string connectionString, string storedProcName)
{
using (OracleConnection connection = new OracleConnection(connectionString))
{
try
{
connection.Open();
OracleCommand command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = storedProcName;
command.ExecuteNonQuery();
connection.Close();
}
catch {
connection.Close();
}
}
}
/// <summary>
/// 执行存储过程 返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>OracleDataReader</returns>
public static void RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters)
{
using (OracleConnection connection = new OracleConnection(connectionString))
{
try
{
connection.Open();
OracleCommand command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = storedProcName;
foreach (OracleParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
command.ExecuteNonQuery();
connection.Close();
}
catch {
connection.Close();
}
}
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="tableName">DataSet结果中的表名</param>
/// <returns>DataSet</returns>
public static DataSet RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName)
{
using (OracleConnection connection = new OracleConnection(connectionString))
{
DataSet dataSet = new DataSet();
connection.Open();
OracleDataAdapter sqlDA = new OracleDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.Fill(dataSet, tableName);
connection.Close();
return dataSet;
}
}
/// <summary>
/// 构建 OracleCommand 对象(用来返回一个结果集,而不是一个整数值)
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>OracleCommand</returns>
private static OracleCommand BuildQueryCommand(OracleConnection connection, string storedProcName, IDataParameter[] parameters)
{
OracleCommand command = new OracleCommand(storedProcName, connection);
command.CommandType = CommandType.StoredProcedure;
if(parameters != null)
{
foreach (OracleParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
return command;
}
/// <summary>
/// 执行存储过程,返回影响的行数
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="rowsAffected">影响的行数</param>
/// <returns></returns>
public static int RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, out int rowsAffected)
{
using (OracleConnection connection = new OracleConnection(connectionString))
{
int result;
connection.Open();
OracleCommand command = BuildIntCommand(connection, storedProcName, parameters);
rowsAffected = command.ExecuteNonQuery();
result = (int)command.Parameters["ReturnValue"].Value;
//Connection.Close();
return result;
}
}
/// <summary>
/// 创建 OracleCommand 对象实例(用来返回一个整数值)
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>OracleCommand 对象实例</returns>
private static OracleCommand BuildIntCommand(OracleConnection connection, string storedProcName, IDataParameter[] parameters)
{
OracleCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.Parameters.Add(new OracleParameter("ReturnValue",
OracleType.Int32, 4, ParameterDirection.ReturnValue,
false, 0, 0, string.Empty, DataRowVersion.Default, null));
return command;
}
#endregion
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static string ExecuteOracleSql(string connectionString, string SQLString)
{
using (OracleConnection connection = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand(SQLString, connection))
{
try
{
connection.Open();
OracleString strRowid = "";
int rows = cmd.ExecuteOracleNonQuery(out strRowid);
return strRowid.Value;
}
catch (System.Data.OracleClient.OracleException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static void ExecuteSqlTran(string connectionString, ArrayList SQLStringList)
{
using (OracleConnection conn = new OracleConnection(connectionString))
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch (System.Data.OracleClient.OracleException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string connectionString, string SQLString)
{
using (OracleConnection connection = new OracleConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
OracleDataAdapter command = new OracleDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.OracleClient.OracleException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
}
|
ca93b9b8a5d9a0a2056d031f89d11cc3ac9d7323
|
C#
|
KseniyaMikhailiuk/PAINt
|
/PaintF/UserFigure.cs
| 3.25
| 3
|
using System.Collections.Generic;
using System.Drawing;
using AbstractClassLibrary;
namespace PaintF
{
public class UserFigure: Figure
{
public static int FieldWidth;
public static int FieldHeight;
public List<Figure> UserFigureList = new List<Figure>();
public override bool IsPointIn(Point point)
{
return true;
}
public override object Clone()
{
UserFigure clonedFigure = new UserFigure();
foreach (var figure in UserFigureList)
{
clonedFigure.UserFigureList.Add((Figure)figure.Clone());
}
return clonedFigure;
}
public override void Draw(Graphics g, Pen pen, Point StartPoint, Point FinishPoint)
{
foreach (var figure in UserFigureList)
{
if (figure != null)
{
float widthDif = (FinishPoint.X - StartPoint.X) / (float)FieldWidth;
figure.StartPoint = CountStartPoint(figure, widthDif);
figure.FinishPoint = CountFinishPoint(figure, widthDif);
figure.Draw(g, figure.Pen, figure.StartPoint, figure.FinishPoint);
}
}
}
public Point CountStartPoint(Figure figure, float widthDif)
{
int tempStartX = (int)(StartPoint.X + figure.FixedStartPoint.X * widthDif);
int tempStartY = (int)(StartPoint.Y + figure.FixedStartPoint.Y * widthDif);
return new Point(tempStartX, tempStartY);
}
public Point CountFinishPoint(Figure figure, float widthDif)
{
int tempFinishX = (int)(StartPoint.X + figure.FixedFinishPoint.X * widthDif);
int tempFinishY = (int)(StartPoint.Y + figure.FixedFinishPoint.Y * widthDif);
return new Point(tempFinishX, tempFinishY);
}
public override void Add(List<Figure> list)
{
foreach (var figure in UserFigureList)
{
figure.FixedFinishPoint = figure.FinishPoint;
figure.FixedStartPoint = figure.StartPoint;
list.Add(figure);
}
}
}
}
|
1ea6a617489556c95413233957e067852575f0a7
|
C#
|
apkoltun/CSC651WebSitev2
|
/App_Code/RoleRegister.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
/// Utitily class for registering roles
public class RoleRegister
{
private RoleStore<IdentityRole> roleStore;
private RoleManager<IdentityRole> roleManager;
public RoleRegister()
{
roleStore = new RoleStore<IdentityRole>();
roleManager = new RoleManager<IdentityRole>(roleStore);
}
//Register role
public void createRole(string rolename)
{
if (!roleManager.RoleExists(rolename))
roleManager.Create(new IdentityRole(rolename));
else
throw new Exception("Role already exists");
}
//Assigns role to given user
public void assignRole(string username, string rolename)
{
var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
var user = userManager.FindByName(username);
if (roleManager.RoleExists(rolename)&&user!=null)
{
userManager.AddToRole(user.Id, rolename);
}
}
}
|
a51aff0ca9c49ed2f3fab3b89af012487a13e05e
|
C#
|
muh-kubraozer/WinForm-Uygulama
|
/VoyageFramework/VoyageFramework/BusExpedition.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VoyageFramework
{
public class BusExpedition
{
DriverCollection<Driver> driverCollection = new DriverCollection<Driver>();
HostCollection<Host> hostCollection = new HostCollection<Host>();
TicketCollection<Ticket> ticketCollection = new TicketCollection<Ticket>();
public Driver driver;
public Host host;
public string Code { get { return Codes(); } }
private Bus _bus;
public Bus Bus {
get { return _bus; }
set
{
if (driverCollection.Length > 0)
{
foreach (var item in driverCollection)
{
if (this.Bus is LuxuryBus && item.LicenseType == LicenseType.HighLicense || this.Bus is StandardBus && item.LicenseType != LicenseType.None)
_bus = value;
else
throw new Exception("Hata:Sürücü Eklenemedi.");
}
}
}
}
//public Driver[] Drivers { get; }
//public Host[] Hosts { get; }
public Route Route { get; }
public DateTime DepartureTime { get; } //planlı kalkış zamanı
public DateTime _estimatedDepartureTime;
public DateTime EstimatedDepartureTime
{
get { return _estimatedDepartureTime; }
set {if (HasDelay == true)
value = EstimatedDepartureTime;
else
value = DepartureTime;
}
}
private DateTime _estimatedArrivalTime; //tahmini varış zamanı
public DateTime EstimatedArrivalTime { get
{
TimeSpan duration = TimeSpan.Parse(Route.Duration.ToString());
if (HasDelay == true)
{
return _estimatedDepartureTime + duration;
}
return DepartureTime + duration;
}
}
public bool HasDelay { get { return DepartureTime != EstimatedDepartureTime ? true : false; } }
public bool HasSnackService;
private bool IsDriverLicenseTypeSuitable(Driver driver)//lisans uygunlugu
{
bool suitable = true;
if (driver.LicenseType == LicenseType.None)
{
suitable = false;
throw new Exception("sürücü lisans uygun değil");
}
if (this.Bus != null)
{
if (this.Bus is LuxuryBus)
{
if (driver.LicenseType != LicenseType.HighLicense)
{
suitable = false;
throw new Exception("sürücü Lisans uygun değil");
}
}
}
return suitable;
}
private Ticket[] _ticket;
public Ticket[] Ticket
{
get
{
return _ticket;
}
}
public string Codes()
{
Random rnd = new Random();
int rn = rnd.Next(1000, 9999);
string code = "";
if (this.Bus is LuxuryBus)
{
code = "LX" + DepartureTime.ToString("YYMMDD") + rn.ToString();
}
else
{
code = "SX" + DepartureTime.ToString("YYMMDD") + rn.ToString();
}
return code;
}
//private Driver[] _drivers;
//private Host[] _host;
public void AddDriver(Driver driver)
{
int addDriver = (Route.Distance / 400) + 1;
if (addDriver > driverCollection.Length && IsDriverLicenseTypeSuitable(driver))
driverCollection.Add(driver);
//int drivers = (Route.Distance / 400)+1;
//if(_drivers.Length < drivers)
// {
// Array.Resize(ref _drivers, _drivers.Length + 1);
// _drivers[_drivers.Length - 1] = driver;
// }
}
public void AddHost(Host host)
{
int addHost = (Route.Distance / 400) + 1;
if (addHost > hostCollection.Length)
hostCollection.Add(host);
//int hosts = (Route.Distance / 600)+1;
//if(_host.Length < hosts)
// {
// Array.Resize(ref _host, _host.Length + 1);
// _host[_host.Length - 1] = host;
// }
}
public void RemoveAtDriver(int index)
{
driverCollection.RemoveAt(index);
}
public void RemoveDriver(Driver driver)
{
driverCollection.Remove(driver);
// int index = -1;
// for (int i = 0; i < _drivers.Length; i++)
// {
// if (driver.IdentityNumber == _drivers[i].IdentityNumber)
// {
// index = i;
// break;
// }
// }
// for (int j = index; j < _drivers.Length; j++)
// {
// _drivers[j] = _drivers[j + 1];
// }
// Array.Resize(ref _drivers, _drivers.Length - 1);
}
public void RemoveHost(Host host)
{
//int index = -1;
//for (int i = 0; i < _host.Length; i++)
//{
// if (host.IdentityNumber == _host[i].IdentityNumber)
// {
// index = i;
// break;
// }
//}
//for (int j = index; j < _host.Length; j++)
//{
// _host[j] = _host[j + 1];
//}
//Array.Resize(ref _host, _host.Length - 1);
hostCollection.Remove(host);
}
public void RemoveAtHost(int index)
{
hostCollection.RemoveAt(index);
}
public decimal GetPriceOf(int seatNumber)
{
SeatInformation selection = new SeatInformation();
if (Bus.Capacity == 30)
{
if (selection.Section == SeatSection.LeftSide)
{
return Route.BasePrice * 125 / 100;
}
else
{
return Route.BasePrice * 120 / 100;
}
}
else
{
return Route.BasePrice * 135 / 100;
}
}
//public void AddTicket(Ticket ticket)
//{
// Array.Resize(ref _ticket, _ticket.Length + 1);
// _ticket[_ticket.Length - 1] = ticket;
//}
public Ticket SellTicket(Person person,int seatNumber,decimal fee)
{
decimal kar = 105 / 100;
if (IsSeatAvailableFor(seatNumber,person.Gender) && IsSeatEmpty(seatNumber))
{
if (person is Driver || person is Host)
fee = Route.BasePrice;
else
fee = Route.BasePrice + Route.BasePrice * kar;
Ticket ticket = new Ticket(this,GetSeatInformation(seatNumber), person, fee);
ticketCollection.Add(ticket);
return ticket;
}
else
{
throw new Exception("HATA!!Lütfen Ödeme Yapınız..");
}
}
public Ticket[] SellDoubleTickets(Person person1,Person person2,int seatNumber,decimal fee)
{
decimal kar = 105 / 100;
Ticket[] tickets = new Ticket[2];
if (Bus is StandardBus && GetSeatInformation(seatNumber).Category != SeatCategory.Singular && IsSeatEmpty(seatNumber))
{
int nearSeat = seatNumber % 3 == 2 ? seatNumber - 1 : seatNumber % 3 == 0 ? seatNumber - 1 :
throw new Exception("Çift Kişilik Bir Secim Yapınız..");
if (IsSeatEmpty(seatNumber))
{
if (person1 is Driver || person1 is Host && person2 is Driver || person2 is Host)
{
fee = Route.BasePrice;
tickets[0] = new Ticket(this, GetSeatInformation(seatNumber), person1, fee / 2);
tickets[1] = new Ticket(this, GetSeatInformation(seatNumber), person2, fee / 2);
ticketCollection.Add(tickets[0]);
ticketCollection.Add(tickets[1]);
}
else
{
fee = Route.BasePrice * kar;
tickets[0] = new Ticket(this, GetSeatInformation(seatNumber), person1, fee / 2);
tickets[1] = new Ticket(this, GetSeatInformation(seatNumber), person2, fee / 2);
ticketCollection.Add(tickets[0]);
ticketCollection.Add(tickets[1]);
}
}
else
throw new Exception("Secilen koltuklar doludur");
}
else
throw new Exception("HATA:Lüks otobüs için çift koltuk seçimi yapılamaz..");
return tickets;
}
public bool IsSeatEmpty(int seatNumber)
{
for(int i=0; i < _ticket.Length; i++)
{
if (_ticket[i].SeatInformation.Number == seatNumber)
return false;
}
return true;
}
public bool IsSeatAvailableFor(int seatNumber,Gender gender)
{
bool result = true;
if (Bus is StandardBus && GetSeatInformation(seatNumber).Category != SeatCategory.Singular && IsSeatEmpty(seatNumber))
{
int nearSeat = seatNumber % 3 == 2 ? seatNumber + 1 : seatNumber % 3 == 0 ? seatNumber - 1 : -1;
foreach (Ticket ticket in _ticket)
{
if (ticket.SeatInformation.Number == nearSeat)
{
result = ticket.Passenger.Gender == gender;
break;
}
}
}
else result = false;
return result;
}
public SeatInformation GetSeatInformation(int seatNumber)
{
SeatSection section = new SeatSection();
SeatCategory category = new SeatCategory();
SeatInformation seatInformation = new SeatInformation(seatNumber,section,category);
if(Bus is StandardBus)
{
if (seatNumber % 3 == 1)
{
section = SeatSection.LeftSide;
category = SeatCategory.Singular;
}
else if (seatNumber % 3 == 2)
{
section = SeatSection.RightSide;
category = SeatCategory.Corridor;
}
else if (seatNumber % 3 == 0)
{
section = SeatSection.RightSide;
category = SeatCategory.Window;
}
}
else
{
if (seatNumber % 2 == 1)
{
section = SeatSection.LeftSide;
}
else if (seatNumber % 2 == 0)
{
section = SeatSection.RightSide;
}
}
return seatInformation;
}
public void CanselTicket(Ticket ticket)
{
ticketCollection.Remove(ticket);
//int index = 0;
//for (int i = 0; i < _ticket.Length; i++)
//{
// if (_ticket[i].SeatInformation.Number == ticket.SeatInformation.Number)
// {
// index = i;
// continue;
// }
// var yeniİndis = i > index ? i - 1 : i;
// _ticket[yeniİndis] = _ticket[i];
//}
//Array.Resize(ref _ticket, _ticket.Length - 1);
}
}
}
|
3ec48c79d49d066bb88d4699045236758000ad31
|
C#
|
shuvoamin/SoftwareDesignPatterns
|
/DesignPatterns/MvcPattern/MvcPatternDemo.cs
| 3.375
| 3
|
namespace DesignPatterns.MvcPattern
{
public class MvcPatternDemo
{
public StudentController StudentController
{
get
{
throw new System.NotImplementedException();
}
}
public static void Output()
{
//fetch student record based on his roll no from the database
var model = RetriveStudentFromDatabase();
//Create a view : to write student details on console
var view = new StudentView();
var controller = new StudentController(model, view);
//update model data
controller.UpdateView("John => Name updated (previous name Robert)", 2);
}
private static Student RetriveStudentFromDatabase()
{
var student = new Student();
student.Name = "Robert";
student.Id = 2;
return student;
}
}
}
|
8dc9e9cebfed7d21557d9c4bf2232d447496c444
|
C#
|
shendongnian/download4
|
/first_version_download2/577695-55604269-195474646-2.cs
| 2.640625
| 3
|
[Test]
public async Task TestAsync()
{
using (var context = new TestDbContext())
{
Console.WriteLine("Thread Before Async: " + Thread.CurrentThread.ManagedThreadId.ToString());
var names = context.Customers.Select(x => x.Name).ToListAsync();
Console.WriteLine("Thread Before Await: " + Thread.CurrentThread.ManagedThreadId.ToString());
var result = await names;
Console.WriteLine("Thread After Await: " + Thread.CurrentThread.ManagedThreadId.ToString());
}
}
|
16244b1012a55a43559c985ab51f1ec8224231e9
|
C#
|
huwman/Fortis
|
/Fortis.CSharp.Test/ResultTest.cs
| 2.5625
| 3
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.Contracts;
namespace Fortis.CSharp.Tests
{
[TestClass]
public class ResultTest
{
[TestMethod]
public void Error_EqualityTest()
{
var p = Result.Error<string, int>("Error");
var q = Result.Error<string, int>("Error");
Assert.AreEqual(p, q);
Assert.IsTrue(p == q);
}
[TestMethod]
public void Success_EqualityTest()
{
var p = Result.Success<string, int>(5);
var q = Result.Success<string, int>(5);
Assert.AreEqual(p, q);
Assert.IsTrue(p == q);
}
[TestMethod]
public void SuccessAndError_EqualityTest()
{
var p = Result.Success<string, int>(5);
var q = Result.Error<string, int>("5");
Assert.AreNotEqual(p, q);
Assert.IsTrue(p != q);
}
[TestMethod]
public void MapIntToString()
{
var p = Result.Success<string, int>(5);
var q = p.Map(v => v.ToString());
Assert.IsTrue(q.IsSuccess());
Assert.AreEqual(q, Result.Success<string, string>("5"));
}
[TestMethod]
public void Error_FormatError()
{
var p = Result.Error<int, int>(-1);
var q = p.FormatError(e => String.Format("Error code {0}", e));
Assert.IsTrue(q.IsError());
}
[TestMethod]
public void Success_AndThen()
{
var p = Result.Success<string, int>(5);
var q = p.AndThen(v => Result.Success<string, int>(v));
Assert.IsTrue(q.IsSuccess());
}
}
}
|