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
|
|---|---|---|---|---|---|---|
e3870d696900a022f483ea6cc60b05c80a94bb09
|
C#
|
121jigowatts/Mvc5WebApp
|
/Mvc5WebApp.SQLServerRepositories/PeopleRepository.cs
| 2.890625
| 3
|
using Mvc5WebApp.Contracts;
using Mvc5WebApp.Models;
using Mvc5WebApp.RepositoryInterfaces;
using Mvc5WebApp.SQLServerRepositories.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mvc5WebApp.SQLServerRepositories
{
public class PeopleRepository : IPeopleRepository
{
private readonly IObjectMapper _mapper;
public PeopleRepository(IObjectMapper mapper)
{
this._mapper = mapper;
}
public IList<Models.Person> Get()
{
using (var context = new EFContext())
{
var query = from x in context.People
select x;
var list = query.ToList<SQLServerRepositories.Database.Person>();
var people = _mapper.Map<List<Models.Person>>(list);
return people;
}
}
public Models.Person GetById(int id)
{
using (var context = new EFContext())
{
var query = from x in context.People
where x.ID == id
select x;
if (query.Count() == 1)
{
var result = query.SingleOrDefault();
var person = _mapper.Map<Models.Person>(result);
return person;
}
return new Models.Person();
}
}
}
}
|
0280ae5c5433a3c9c92fea8cf63d01cbe996bf74
|
C#
|
TheColonel2688/EntryPoint
|
/src/EntryPoint/Arguments/ArgumentModel.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EntryPoint.Common;
using EntryPoint.Exceptions;
using EntryPoint.Parsing;
using EntryPoint.Help;
using System.Reflection;
namespace EntryPoint.Arguments {
internal class ArgumentModel {
internal ArgumentModel(BaseCliArguments cliArguments) {
CliArguments = cliArguments;
Options = cliArguments.GetOptions();
Operands = cliArguments.GetOperands();
EnvironmentVariables = cliArguments.GetEnvironmentVariables();
Help = cliArguments.GetHelpAttribute();
HelpFacade = new HelpFacade(cliArguments);
}
public BaseCliArguments CliArguments { get; private set; }
// Help attribute applied to the class itself
public HelpAttribute Help { get; private set; }
// Options defined by the class
public List<Option> Options { get; set; }
// Operands defined by the class
public List<Operand> Operands { get; set; }
// Environment Variables defined by the class
public List<EnvironmentVariable> EnvironmentVariables { get; set; }
// Facade for invoking Help
public HelpFacade HelpFacade { get; set; }
// ** Helpers **
// Find the ModelOption for the given Token, or null
public Option FindOptionByToken(Token token) {
var option = this.Options
.FirstOrDefault(o => token.InvokesOption(o));
if (option == null) {
throw new UnknownOptionException(
$"The option {token.Value} was not recognised. "
+ "Please ensure all given arguments are valid. Try --help");
}
return option;
}
public List<Option> WhereOptionsNotIn(List<TokenGroup> tokenGroups) {
return this.Options
.Where(o => !tokenGroups.Any(tg => tg.Option.InvokesOption(o)))
.ToList();
}
// ** Model Validation **
public void Validate() {
ValidateNoDuplicateOptionNames();
ValidateContigiousOperandMapping();
ValidateTypes();
}
// Check that operand positions have the form: [ 1, 2, 3, 4 ](contigious)
// As opposed to [ 0, 1, 2, 3 ](less than 1) OR [ 1, 2, 4, 5 ](gaps)
void ValidateContigiousOperandMapping() {
int lastPosition = 0;
var operands = Operands.OrderBy(o => o.Definition.Position);
foreach (var operand in operands) {
int position = operand.Definition.Position;
int diff = position - lastPosition;
// Position should always be greater than 1
if (position < 1) {
throw new InvalidModelException("Negative Operand Position. "
+ $"Operand(position: {position}) on "
+ $"{operand.Property.Name} was < 1. The first position is 1");
// Position should always increase by 1
} else if (diff != 1) {
throw new InvalidModelException("Missing Operand Position(s). "
+ $"Operand positions should always increment by 1 from first->last. Positions {position} and {lastPosition} leave a gap");
}
lastPosition = position;
}
}
// Check model contains only unique names
void ValidateNoDuplicateOptionNames() {
// Check the single dash options
var singleDashes = this.Options
.Where(o => o.Definition.ShortName > char.MinValue)
.Select(o => o.Definition.ShortName.ToString())
.Duplicates(StringComparer.CurrentCulture);
if (singleDashes.Any()) {
AssertDuplicateOptionsInModel(singleDashes);
}
// Check the double dash options
var doubleDashes = this.Options
.Where(o => o.Definition.LongName.HasValue())
.Select(o => o.Definition.LongName)
.Duplicates(StringComparer.CurrentCultureIgnoreCase);
if (doubleDashes.Any()) {
AssertDuplicateOptionsInModel(doubleDashes);
}
}
static void AssertDuplicateOptionsInModel(List<string> duplicateOptionNames) {
throw new InvalidModelException(
$"There are duplicate option names: `{String.Join("/", duplicateOptionNames)}`");
}
void ValidateTypes() {
foreach (var option in Options) {
ValidatePropertyType(option.Property);
}
foreach (var operand in Operands) {
ValidatePropertyType(operand.Property);
}
}
void ValidatePropertyType(PropertyInfo property) {
if (property.PropertyType.IsList()) {
var listTypeArg = property.PropertyType.GenericTypeArguments[0];
ValidateTypeIsSupported(listTypeArg);
} else {
ValidateTypeIsSupported(property.PropertyType);
}
}
void ValidateTypeIsSupported(Type type) {
if (type.GetTypeInfo().IsPrimitive) {
return;
}
if (type.GetTypeInfo().IsEnum) {
return;
}
if (type == typeof(string)) {
return;
}
if (type == typeof(decimal)) {
return;
}
if (type.IsNullable()) {
ValidateTypeIsSupported(Nullable.GetUnderlyingType(type));
return;
}
AssertTypeNotSupported(type);
}
void AssertTypeNotSupported(Type type) {
throw new InvalidModelException(
$"The type `{type.Name}` is not currently supported as an Option/Operand type");
}
}
}
|
99eec72f26d28016ac4d763574bc00d798960da0
|
C#
|
vitodtagliente/FiltroDiKalman
|
/KalmanLib/TriangleGenerationService.cs
| 3.1875
| 3
|
using System.Collections.Generic;
namespace KalmanLib
{
public class TriangleGenerationService : PacketGenerationService
{
List<int> Sizes = new List<int>();
int _counter = 0;
public int Counter
{
get
{
int value = _counter;
_counter++;
if (_counter >= Sizes.Count)
_counter = 0;
return value;
}
private set { _counter = value; }
}
public TriangleGenerationService(int max, int min = 500, int step = 500)
{
int x = min;
while(x < max)
{
Sizes.Add(x);
x += step;
}
Sizes.Add(max);
int y = max - min;
while(y >= 2 * min)
{
Sizes.Add(y);
y -= step;
}
}
public override int Size()
{
return Sizes[Counter];
}
}
}
|
6e43e4188e9e52dda77937df11959b0e875f192b
|
C#
|
microsoft/MRDL_Unity_LunarModule
|
/Assets/HoloToolKit/Input/Scripts/Cursor/ObjectCursor.cs
| 3.03125
| 3
|
using System;
using UnityEngine;
namespace HoloToolkit.Unity.InputModule
{
/// <summary>
/// The object cursor can switch between different game objects based on its state.
/// It simply links the game object to set to active with its associated cursor state.
/// </summary>
public class ObjectCursor : Cursor
{
[Serializable]
public struct ObjectCursorDatum
{
public string Name;
public CursorStateEnum CursorState;
public GameObject CursorObject;
}
[SerializeField]
public ObjectCursorDatum[] CursorStateData;
/// <summary>
/// Sprite renderer to change. If null find one in children
/// </summary>
public Transform ParentTransform;
/// <summary>
/// On enable look for a sprite renderer on children
/// </summary>
protected override void OnEnable()
{
if(ParentTransform == null)
{
ParentTransform = transform;
}
for (int i = 0; i < ParentTransform.childCount; i++)
{
ParentTransform.GetChild(i).gameObject.SetActive(false);
}
base.OnEnable();
}
/// <summary>
/// Override OnCursorState change to set the correct animation
/// state for the cursor
/// </summary>
/// <param name="state"></param>
public override void OnCursorStateChange(CursorStateEnum state)
{
base.OnCursorStateChange(state);
if (state != CursorStateEnum.Contextual)
{
// First, try to find a cursor for the current state
var newActive = new ObjectCursorDatum();
for(int cursorIndex = 0; cursorIndex < CursorStateData.Length; cursorIndex++)
{
ObjectCursorDatum cursor = CursorStateData[cursorIndex];
if (cursor.CursorState == state)
{
newActive = cursor;
break;
}
}
// If no cursor for current state is found, let the last active cursor be
// (any cursor is better than an invisible cursor)
if (newActive.Name == null)
{
return;
}
// If we come here, there is a cursor for the new state,
// so de-activate a possible earlier active cursor
for(int cursorIndex = 0; cursorIndex < CursorStateData.Length; cursorIndex++)
{
ObjectCursorDatum cursor = CursorStateData[cursorIndex];
if (cursor.CursorObject.activeSelf)
{
cursor.CursorObject.SetActive(false);
break;
}
}
// ... and set the cursor for the new state active.
newActive.CursorObject.SetActive(true);
}
}
}
}
|
b80727d37a521d7c53059cac0e969fed29fcb955
|
C#
|
kveler/Discsnordbort
|
/Commands/LolCommands.cs
| 2.75
| 3
|
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace DiscordBot.Commands
{
public class LolCommands : BaseCommandModule
{
[Command("lol")]
[Description("Doe league commands")]
public async Task LeagueOfLegends(CommandContext ctx, string para1, string username)
{
switch (para1)
{
case "tftlevel":
var client = new RestClient("https://euw1.api.riotgames.com/tft/summoner/v1/summoners/by-name/" + username);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("X-Riot-Token", "RGAPI-8c75386f-79df-4804-b44d-9c7e5c2aa559"); //Verloopt dagelijks
IRestResponse response = client.Execute(request);
var result = JsonConvert.DeserializeObject<LolTftReply>(response.Content);
string message = "Name: " + result.Name + "\nLevel: " + result.SummonerLevel;
await ctx.Channel.SendMessageAsync(message).ConfigureAwait(false);
break;
default:
await ctx.Channel.SendMessageAsync("Dit snap ik nog niet :(").ConfigureAwait(false);
break;
}
}
}
}
|
8d868245d57f7c998a49c2b2fecbb80dcc0d2c7c
|
C#
|
0xCM/Meta.Core
|
/src/Meta.Core.Dynamics/Expressions/Vocabulary/SelectionModel.cs
| 2.765625
| 3
|
//-------------------------------------------------------------------------------------------
// OSS developed by Chris Moore and licensed via MIT: https://opensource.org/licenses/MIT
// This license grants rights to merge, copy, distribute, sell or otherwise do with it
// as you like. But please, for the love of Zeus, don't clutter it with regions.
//-------------------------------------------------------------------------------------------
namespace Meta.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
/// <summary>
/// Defines a set of members together with the criteria used to determine a selected collection
/// </summary>
public class SelectionModel
{
readonly Expression X;
public SelectionModel
(
Expression X,
MemberSelection SelectedMembers,
Option<MemberOrdering> Order,
IEnumerable<Junction> Junctions,
params SelectionFacet[] Facets
)
{
this.X = X;
this.MemberOrder = Order;
this.SelectedMembers = SelectedMembers;
this.Facets = Facets;
this.Junctions = Junctions.ToList();
}
/// <summary>
/// The members that represent the columns to be selected
/// </summary>
public MemberSelection SelectedMembers { get; }
/// <summary>
/// Optional order-by specification
/// </summary>
public Option<MemberOrdering> MemberOrder { get; }
/// <summary>
/// A sequence of con/dis-junctions that will fitler the results set
/// and effectively represents a WHERE clausee
/// </summary>
public IReadOnlyList<Junction> Junctions { get; }
/// <summary>
/// Facets such as TOP and DISTINCT
/// </summary>
public IReadOnlyList<SelectionFacet> Facets { get; }
}
public static class LinqXtend
{
public static SelectionModel BuildSelectionModel<T>(this IQueryable<T> queryable, params SelectionFacet[] facets)
=> SelectionModelBuilder.CreateModel(queryable);
}
}
|
cc4fe9c76d6a4cb2cc8ed392ab400b747bafa6d2
|
C#
|
pawanparashar/Algorithm
|
/Algorithm/StackMinimum/Program.cs
| 3.40625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackMinimum
{
class Program
{
Stack<int> RealStacker = new Stack<int>();
Stack<int> MinStacker = new Stack<int>();
static void Main(string[] args)
{
Program P = new Program();
P.CustomPush(1);
P.CustomPush(200);
P.CustomPush(3);
P.CustomPush(400);
P.CustomPush(1);
P.CustomPush(0);
}
public void CustomPush(int Content)
{
RealStacker.Push(Content);
if(MinStacker.Count ==0)
{
MinStacker.Push(Content);
}
else
{
if(MinStacker.Peek() <=Content)
{
MinStacker.Push(MinStacker.Peek());
}
else
{
MinStacker.Push(Content);
}
}
}
public void CustomPop()
{
RealStacker.Pop();
MinStacker.Pop();
}
}
}
|
fa453f048185d4598fabfc2c9cb914d734ad8ead
|
C#
|
210329-UTA-SH-UiPath/P1_Jeffrey_Breiner
|
/PizzaBox.FrontEnd/PizzaBox.FrontEnd/FEPizzaClient.cs
| 2.671875
| 3
|
using IO.Swagger.Model;
using PizzaBox.FrontEnd.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace PizzaBox.FrontEnd
{
public class FEPizzaClient
{
static string url = "https://localhost:44368/api/";
static public IEnumerable<APizza> GetPizzas()
{
using var client = new HttpClient();
client.BaseAddress = new Uri(url);
var response = client.GetAsync("Pizza/");
response.Wait();
var result = response.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<APizza[]>();
readTask.Wait();
return readTask.Result;
}
else
{
return null;
}
}
static public IEnumerable<APizza> GetPizzaTypes()
{
return GetPizzas().GroupBy(pizza => pizza.Pizza).Select(first => first.First());
}
static public APizza GetPizzaInfo(APizza pizza)
{
using var client = new HttpClient();
if (pizza.Pizza == PIZZAS.CUSTOM)
{
List<TOPPINGS> TOPPING = new List<TOPPINGS>();
foreach (ATopping topping in pizza.Toppings)
{
TOPPING.Add(topping.Topping);
}
client.BaseAddress = new Uri($"{url}{pizza.Pizza}/{pizza.Size.Size}/{pizza.Size.Size}?{TOPPING}");
}
else
{
client.BaseAddress = new Uri($"{url}{pizza.Pizza}/{pizza.Size.Size}");
}
var response = client.GetAsync("Values/");
response.Wait();
var result = response.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<APizza>();
readTask.Wait();
return readTask.Result;
}
else
{
return null;
}
}
}
}
|
c8e478df8e423e5b4c82098e305121cccf7958eb
|
C#
|
wmltogether/Project-Console-Game-Localization
|
/PS2/Shin Megami Tensei III/DDT3Extractor/DDT3Extractor/DDTExtractor/Compression/LBC.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using AtlusGames.Extension;
namespace AtlusGames.Compression
{
public class LBCPythonWrapper
{
public static byte[] LB_Decompress(byte[] input, int decompressLength)
{
byte[] result;
LBC.Decompress(input, input.Length,decompressLength,out result);
return result;
}
public static byte[] LB_Compress(byte[] input)
{
byte[] result;
int resultLength;
LBC.Compress(input, out result,out resultLength);
return result;
}
}
public class LBC
{
public static void Compress(byte[] inputData, out byte[] dstBytes, out int compressLength)
{
compressLength = 0;
dstBytes = new byte[0];
//这个方法很污,完全不压缩数据,很容易出问题,不要模仿
int MAX_WND = 0x10;
MemoryStream inputStream = new MemoryStream(inputData);
BinaryReader br = new BinaryReader(inputStream);
br.BaseStream.Seek(0, SeekOrigin.Begin);
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter bw = new BinaryWriter(ms))
{
int vLen = inputData.Length;
int vCounts = 0;
if (vLen % MAX_WND == 0)
{
vCounts = vLen / MAX_WND;
}
else
{
vCounts = vLen / MAX_WND + 1;
}
BitIO.BitWrite bitWrite = new BitIO.BitWrite(bw);
byte[] tmp = new byte[MAX_WND];
for (int i = 0; i < vCounts; i++)
{
tmp = br.ReadBytes(MAX_WND);
bw.Write((byte)0);
bw.Write((ushort)tmp.Length);
bw.Write(tmp);
}
bw.Write((byte)0xff);
}
dstBytes = ms.ToArray();
compressLength = dstBytes.Length;
}
}
public static void Decompress(byte[] data, int compressLength, int decompressLength, out byte[] dstBytes)
{
dstBytes = new byte[decompressLength];
int comPos = 0; //压缩位置
int decomPos = 0;//解压位置
int flag = 0;//压缩标记
int off = 0;
int retLength = 0;
int retOff = 0;
byte[] wnd = new byte[0];
byte tmp = (byte)0;
using (MemoryStream ms = new MemoryStream(data))
{
using (BinaryReader br = new BinaryReader(ms))
{
BitIO.BitReader bitReader = new BitIO.BitReader(br);
while (decomPos < decompressLength)
{
comPos = (int)br.BaseStream.Position;
flag = bitReader.ReadBits(3);
off = bitReader.ReadBits(5);
//Console.WriteLine(String.Format("flag:{0:x8},off:{1:x8},at offset:{2:x8},decoffset:{3:x8}", flag,off, comPos, decomPos));
if (flag == 0)
{
//如果前三个bit 0 0 0,不压缩,原样输出后面的off字节到解压流
if (off == 0)
{
off = br.ReadInt16();
}
wnd = br.ReadBytes(off);
Buffer.BlockCopy(wnd, 0, dstBytes, decomPos, off);
decomPos += off;
}
else if (flag == 1)
{
tmp = 0;
//如果前三个bit是0 0 1 ,压缩,默认填充0,让解压流向后填充off字节
if (off == 0)
{
off = br.ReadInt16();
}
if (off == -1)
{
off = br.ReadByte() * 0x100;
}
wnd = Enumerable.Repeat((byte)0, off).ToArray();
Buffer.BlockCopy(wnd, 0, dstBytes, decomPos, off);
decomPos += off;
}
else if (flag == 2)
{
if (off == 0)
{
off = br.ReadInt16();
}
//如果前三个bit是0 1 0,压缩,复制输出后面的1字节当作填充,让解压流向后填充off字节
tmp = br.ReadByte();
wnd = Enumerable.Repeat((byte)tmp, off).ToArray();
Buffer.BlockCopy(wnd, 0, dstBytes, decomPos, off);
decomPos += off;
}
else if (flag == 3)
{
//如果前三个bit是0 1 1 压缩,回退并复制之前的内容
if (off == 0)
{
//如果后5位是0, 则向下读3字节
retLength = br.ReadInt16();//向后复制量
retOff = br.ReadByte();//回退读取量
}
else
{
retLength = off;//向后复制量
retOff = br.ReadByte();//回退读取量
}
wnd = new byte[retOff];
Buffer.BlockCopy(dstBytes, decomPos - retOff, wnd, 0, retOff);//从dstBytes复制之前的内容到临时的wnd
int kL = 0;
int kO = 0;
while (kL < retLength)
{
dstBytes[decomPos + kL] = wnd[kO];
kO += 1;
kL += 1;
if (kO >= retOff) kO = 0;
}
decomPos += retLength;
}
else if (flag == 4)
{
//如果前三个bit是1 0 0 压缩,让压缩流回退retOff字节,并复制之前的内容(复制retLength个字节)
if (off == 0)
{
//如果后5位是0, 则向下读4字节
retLength = br.ReadInt16();//向后复制量
retOff = br.ReadInt16();
}
else
{
retLength = off;//向后复制量
retOff = br.ReadInt16();//回退读取量
}
wnd = new byte[retOff];
Buffer.BlockCopy(dstBytes, decomPos - retOff, wnd, 0, retOff);//从dstBytes复制之前的内容到临时的wnd
int kL = 0;
int kO = 0;
while (kL < retLength)
{
dstBytes[decomPos + kL] = wnd[kO];
kO += 1;
kL += 1;
if (kO >= retOff) kO = 0;
}
decomPos += retLength;
}
else if (flag == 5)
{
//扩展补位,1字节变2字节
int extLen = off;
if (off == 0)
{
extLen = br.ReadInt16();
}
//如果前三个bit是1 0 1 ,让压缩流往下读off字节,每个字节从8bit扩展到16bit,写入到解压流
for (int i = 0; i < extLen * 2; i+=2)
{
tmp = br.ReadByte();
dstBytes[decomPos + i] = tmp;
}
decomPos += (extLen * 2);
}
else if (flag == 6)
{
//???怎么还有6
Console.WriteLine(String.Format("unk flag:{0:x8},at offset:{1:x8},decompress::{2:x8}", flag, comPos, decomPos));
}
else if (flag == 7)
{
//如果前三个bit是1 1 1break,停止解压操作
break;
}
else
{
Console.WriteLine(String.Format("unk flag:{0:x8},at offset:{1:x8},decompress::{2:x8}", flag, comPos, decomPos));
}
}
}
}
}
}
}
|
d8d8c4f93059cd616166f6d63426240bb5cd73e6
|
C#
|
Cynthia6/Softuni-csharp-basics
|
/2/21/Program.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _21
{
class Program
{
static void Main(string[] args)
{
int field = int.Parse(Console.ReadLine());
double grapes1km = double.Parse(Console.ReadLine());
int litersneeded = int.Parse(Console.ReadLine());
int workers = int.Parse(Console.ReadLine());
double grapes = grapes1km * field;
double actualWine1 = ((grapes * 0.4 ) / 2.5);
double difference1 = Math.Abs(actualWine1 - litersneeded);
if (actualWine1 >= litersneeded)
{
double LpWorker = (difference1 / workers);
Console.WriteLine("Good harvest this year! Total wine: {0} liters.\n{1} liters left -> {2} liters per person.", Math.Floor( actualWine1), Math.Ceiling( difference1), Math.Ceiling( LpWorker));
}
if (actualWine1 < litersneeded)
{
Console.WriteLine("It will be a tough winter! More {0} liters wine needed.", (int)( difference1) );
}
}
}
}
|
6ce391ed807e8f3d323232fb50f0926008cbdbc2
|
C#
|
Jeke21/Trabajo-ECommerce
|
/CapaNegocio/Pago.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CapaNegocio
{
public class Pago
{
//Atriutos
private string id;
private DateTime fechaPago;
private string pago;
//Propiedades
public string Id { get => id; set => id = value; }
public DateTime FechaPago { get => fechaPago; set => fechaPago = value; }
public string PagoProp { get => pago; set => pago = value; }
//Metodos u Operaciones
public string Pagar()
{
return "No se ha implementado este metodo";
}
public string Cancelar()
{
return "No se ha implementado este metodo";
}
}
}
|
734155e33a06f7b8deeeeb9c2c1a9c4e18b5dd5a
|
C#
|
kovacevicemir/GradeBook
|
/GradeBook/GradeBook.cs
| 3.671875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grade
{
public class GradeBook
{
//constructor
public GradeBook()
{
grades = new List<float>();
}
//add grades method
public void AddGrades(float grade)
{
grades.Add(grade);
}
//Statistics
public GradeStatistics ComputeStatistics()
{
//create new instance of grade statistics
GradeStatistics stats = new GradeStatistics();
float sum = 0;
foreach (float grade in grades)
{
sum += grade;
stats.MinimumGrade = Math.Min(grade,stats.MinimumGrade);
stats.MaximumGrade = Math.Max(grade, stats.MaximumGrade);
}
stats.AverageGrade = sum / grades.Count;
return stats;
}
List<float> grades;
}
}
|
dc91f3a3046a41ebdcbb206f43f323fd4bb71b5c
|
C#
|
fischettijw/Custome-Control
|
/ColorSelector.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Custome_Control
{
public partial class ColorSelector : UserControl
{
private Color controlColor;
public event EventHandler ColorChanged;
public Color ControlColor
{
get { return controlColor; }
set { controlColor = value; }
}
protected virtual void OnColorChanged(EventArgs e)
{
ColorChanged?.Invoke(this, e);
}
public ColorSelector()
{
InitializeComponent();
}
private void Tbr_Scroll(object sender, EventArgs e)
{
int redValue = TbrRed.Value;
int greenValue = TbrGreen.Value;
int blueValue = TbrBlue.Value;
Color ctrlColor = Color.FromArgb(redValue, greenValue, blueValue);
PnlColor.BackColor = ctrlColor;
controlColor = ctrlColor;
OnColorChanged(EventArgs.Empty);
}
}
}
|
1698dd02f4921ab1a24925e240acaeee86913881
|
C#
|
MarioVasilev99/CSharp-Advanced-Jan2019
|
/Stacks and Queues/StackAndQuenes_Lab/ReverseStrings_P01.cs
| 3.25
| 3
|
namespace ReverseStrings
{
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string input = Console.ReadLine();
Stack<char> inputStack = new Stack<char>(input);
foreach (char symbol in inputStack)
{
Console.Write(symbol);
}
}
}
}
|
8e892accae10086ec206f25e4bcdab683701f5c4
|
C#
|
thieupepijn/CubeDrawer
|
/CubeDrawer/Program.cs
| 3.34375
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
namespace CubeDrawer
{
class Program
{
static void Main(string[] args)
{
if (args.Length < 4)
{
Console.WriteLine("Draws a cube to specified image-file");
Console.WriteLine("Usage: CubeDrawer <CubeWidth> <CubeHeight> <CubeDepth> <ImageFilePath>");
Console.WriteLine("Or: CubeDrawer <CubeWidth> <CubeHeight> <CubeDepth> <ImageFilePath> <ImageFileWidth> <ImageFileHeight>");
return;
}
int cubeWidth = 0, cubeHeight = 0, cubeDepth = 0;
try
{
cubeWidth = ParseDimensionParameter(args[0]);
cubeHeight = ParseDimensionParameter(args[1]);
cubeDepth = ParseDimensionParameter(args[2]);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
string outputFilepath = args[3];
int outputfileWidth = 2000;
int outputfileHeight = 2000;
if (args.Length == 6)
{
outputfileWidth = ParseDimensionParameter(args[4]);
outputfileHeight = ParseDimensionParameter(args[5]);
}
using (Bitmap bitmap = new Bitmap(outputfileWidth, outputfileHeight))
{
Coord3D cubeorigin = new Coord3D(0, 0, 0);
Cube3D Cube = new Cube3D(cubeorigin, cubeWidth, cubeHeight, cubeDepth);
using (Graphics graafix = Graphics.FromImage(bitmap))
{
Cube.Draw(graafix, new Coord2D(outputfileWidth / 2, outputfileHeight / 2), outputfileHeight);
try
{
bitmap.Save(outputFilepath);
}
catch
{
Console.WriteLine("Could not write to file \"{0}\"", outputFilepath);
}
}
}
}
private static int ParseDimensionParameter(string dimension)
{
try
{
int number = Convert.ToInt16(dimension);
if (number < 1)
{
throw new Exception(string.Format("{0} is not a valid cube- or image-dimension", dimension), null);
}
else
{
return number;
}
}
catch
{
throw new Exception(string.Format("{0} is not a valid cube- or image-dimension", dimension), null);
}
}
}
}
|
66aced8d167048052d7de1b1c0ce0cfa780c3093
|
C#
|
ElGuayaba/FileServer
|
/FileServer.Infrastructure.Repository/Repositories/AlumnoRepository.cs
| 2.5625
| 3
|
using System;
using FileServer.Common.Model;
using FileServer.Infrastructure.Repository.Interfaces;
namespace FileServer.Infrastructure.Repository.Repositories
{
public class AlumnoRepository : IAlumnoRepository
{
public bool Filled(Alumno alumno)
{
if (alumno.Id <= 0
|| String.IsNullOrEmpty(alumno.Nombre)
|| String.IsNullOrEmpty(alumno.Apellido)
|| String.IsNullOrEmpty(alumno.Dni))
{
return false;
}
return true;
}
public Alumno Add(Alumno alumno)
{
Environment.CurrentDirectory = Environment.GetEnvironmentVariable("VUELING_HOME");
string path = "Alumno.json";
FileManager fm = new FileManager();
fm.FileCreate(path);
string alumnoJson = fm.JsonSerialize(alumno);
fm.FileWrite(alumnoJson,path);
return alumno;
}
}
}
|
e9deaf1f430160bcaf1e4b3ab3a22597c8907fe4
|
C#
|
rockyjvec/GameWasm
|
/GameWasm/WebAssembly/Type.cs
| 3
| 3
|
using System;
using System.Linq;
namespace GameWasm.Webassembly
{
public class Type
{
public const byte i32 = 0x7F, i64 = 0x7E, f32 = 0x7D, f64 = 0x7C, localGet = 0xFF, localSet = 0xFE, globalGet = 0xFD, globalSet = 0xFC, load32 = 0xFB, store32 = 0xFA, and32 = 0xF9, add32 = 0xF8;
public byte[] Parameters;
public byte[] Results;
public Type(byte[] parameters, byte[] results)
{
Parameters = new byte[] { };
if(parameters != null) Parameters = parameters;
Results = new byte[] { };
if(results != null) Results = results;
}
public bool SameAs(Type item)
{
return Parameters.SequenceEqual(item.Parameters) && Results.SequenceEqual(item.Results);
}
public static string Pretify(Value v)
{
switch (v.type)
{
case Type.i32:
return ((Int32)v.i32).ToString();
case Type.i64:
return ((Int64)v.i64).ToString();
case Type.f32:
return v.f32.ToString();
case Type.f64:
return v.f64.ToString();
default:
return "unknown (" + v.type + ")";
}
}
public override string ToString()
{
string result = "(";
for(int i = 0; i < Parameters.Length; i++)
{
switch(Parameters[i])
{
case 0x7F:
result += "i32";
break;
case 0x7E:
result += "i64";
break;
case 0x7D:
result += "f32";
break;
case 0x7C:
result += "f64";
break;
default:
result += "??";
break;
}
if(i + 1 < Parameters.Length)
{
result += ", ";
}
}
result += ") => (";
for (int i = 0; i < Results.Length; i++)
{
switch (Results[i])
{
case 0x7F:
result += "i32";
break;
case 0x7E:
result += "i64";
break;
case 0x7D:
result += "f32";
break;
case 0x7C:
result += "f64";
break;
default:
result += "??";
break;
}
if (i + 1 < Results.Length)
{
result += ", ";
}
}
return result + ")";
}
}
}
|
110c60549ef351a28612e8505edbf55f42905826
|
C#
|
ILoveMilktea/Dogfight
|
/Assets/Scripts/ReflectionLab.cs
| 2.8125
| 3
|
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class refl
{
public string f1;
public int p1 { get; set; }
public int p2 { get; private set; }
public refl()
{
f1 = "a";
p1 = 1;
p2 = 2;
}
}
public class ReflectionLab : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
refl test = new refl();
Type t = test.GetType();
PropertyInfo[] properties = t.GetProperties();
foreach (PropertyInfo item in properties)
{
Debug.Log(item.Name);
Debug.Log(item.PropertyType);
Debug.Log(item.GetValue(test));
}
}
// Update is called once per frame
void Update()
{
}
}
|
3d153c1bedfb884a62f2903e637ecaa424536b63
|
C#
|
yancyn/drawandworkout
|
/HLGranite.Drawing.Test/InventoriesTest.cs
| 2.5625
| 3
|
using HLGranite.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace HLGranite.Drawing.Test
{
/// <summary>
///This is a test class for InventoriesTest and is intended
///to contain all InventoriesTest Unit Tests
///</summary>
[TestClass()]
public class InventoriesTest
{
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///A test for SaveToFile
///</summary>
[TestMethod()]
public void AddInventoryTest()
{
Inventories target = DatabaseObject.Inventories;
Inventory inventory = new Inventory();
inventory.Stock = new Stock { Code = "TAN", Name1 = "Tan Brown" };
inventory.Warehouse = new Warehouse { Name1 = "Bukit Pinang" };
inventory.Width = 72;
inventory.Height = 24;
target.Add(50, inventory);
//target.SaveToFile();
}
[TestMethod()]
public void AddInventoryWIPTest()
{
Inventories target = DatabaseObject.Inventories;
Inventory inventory = new Inventory();
inventory.Stock = new Stock { Code = "TAN", Name1 = "Tan Brown" };
inventory.Warehouse = new Warehouse { Name1 = "Bukit Pinang" };
inventory.Width = 72;
inventory.Height = 24;
InventoryWIP w1 = new InventoryWIP();
w1.Width = 50;
w1.Height = 24;
InventoryWIP w2 = new InventoryWIP();
w2.Width = 22;
w2.Height = 12;
InventoryWIP w3 = new InventoryWIP();
w3.Width = 22;
w3.Height = 12;
inventory.Collection.Add(w1);
inventory.Collection.Add(w2);
inventory.Collection.Add(w3);
inventory.Save();
//target.Add(50, inventory);
//target.SaveToFile();
}
}
}
|
fc6fd1907e9fda5c929f919a87eeebb737d7969c
|
C#
|
NikoNodaros/SECUR-O-TECK-REST-WEB-API_csharp
|
/SecuroteckWebApplication/Models/User.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Collections.ObjectModel;
using System.Web.Http;
using static SecuroteckWebApplication.Models.User;
using System.ComponentModel.DataAnnotations.Schema;
namespace SecuroteckWebApplication.Models
{
public class User
{
public enum Roles
{
User,
Admin
}
#region Task2
[Key]
public string ApiKey { get; set; }
public string UserName { get; set; }
public virtual ICollection<Log> Logs { get; set; }
public Roles Role { get; set; }
public User()
{
Logs = new Collection<Log>();
}
#endregion
}
#region Task13?
// TODO: You may find it useful to add code here for Logging
public class Log
{
[Key]
public string LogID { get; set; }
public string LogString { get; set; }
public DateTime LogDateTime { get; set; }
public Log(string pLine)
{
LogID = Guid.NewGuid().ToString();
LogString = pLine;
LogDateTime = DateTime.Now;
}
public Log() { }
}
public class LogArchive
{
[Key]
public string LogArchiveID { get; set; }
public string User_ApiKey { get; set; }
public string LogArchiveString { get; set; }
public DateTime LogDateTime { get; set; }
public DateTime ArchivedDate { get; set; }
public LogArchive(string pGuid, string pApiKey, string pLine, DateTime pLogDateTime)
{
LogArchiveID = pGuid;
User_ApiKey = pApiKey;
LogArchiveString = pLine;
LogDateTime = pLogDateTime;
ArchivedDate = DateTime.Now;
}
public LogArchive() { }
}
#endregion
public class UserDatabaseAccess
{
#region Task3
// TODO: Make methods which allow us to read from/write to the database
public static User CreateUser(string pUserName)
{
using (var dB = new UserContext())
{
IQueryable<User> uQuery = from user in dB.Users where user.Role == Roles.Admin select user;
var newRole = Roles.User;
if (!uQuery.Any()) newRole = Roles.Admin;
var virginUser = new User()
{
UserName = pUserName,
ApiKey = Guid.NewGuid().ToString(),
Role = newRole
};
dB.Users.Add(virginUser);
dB.SaveChanges();
return virginUser;
}
}
public static bool UserExists(Guid pApiKey, out User pUser)
{
using (var dB = new UserContext())
{
return (pUser = dB.Users.SingleOrDefault(c => c.ApiKey == pApiKey.ToString())) == null ? false : true;
}
}
public static bool UserExists(string pUserName)
{
using (var dB = new UserContext())
{
IQueryable<User> userQuery = from user in dB.Users where user.UserName == pUserName select user;
foreach (User user in userQuery)
{
return true;
}
return false;
}
}
public static bool UserExists(string pApiKey, string pUserName)
{
using (var dB = new UserContext())
{
IQueryable<User> userQuery = from user in dB.Users where user.ApiKey == pApiKey select user;
foreach (User user in userQuery)
{
if (user.UserName == pUserName)
{
return true;
}
}
}
return false;
}
public static bool ChangeRole(string pUserName, Roles pNewRole)
{
try
{
using (var dB = new UserContext())
{
IQueryable<User> userQuery = from user in dB.Users where user.UserName == pUserName select user;
foreach (User user in userQuery)
{
user.Role = pNewRole;
}
dB.SaveChanges();
return true;
}
} catch { return false; }
}
public static void DeleteUser(string pApiKey)
{
using (var dB = new UserContext())
{
User user = dB.Users.SingleOrDefault(c => c.ApiKey == pApiKey.ToString());
int count = user.Logs.Count();
for (int i = 0; i < count; i++)
{
Log log = user.Logs.ElementAt(i);
dB.LogArchives.Add(new LogArchive(log.LogID, user.ApiKey, log.LogString, log.LogDateTime));
dB.Logs.Remove(log);
count--;
i = -1;
}
dB.Users.Remove(user);
dB.SaveChanges();
}
}
public static void Log(string pLogDescription, string pApiKey)
{
using (var dB = new UserContext())
{
User user = dB.Users.SingleOrDefault(c => c.ApiKey == pApiKey.ToString());
Log log = new Log(pLogDescription);
dB.Logs.Add(log);
user.Logs.Add(log);
dB.SaveChanges();
}
}
#endregion
}
}
|
2da1f5bfb5092f222a3e43acdcbbc966ccc42edc
|
C#
|
fiado07/QueryLite
|
/QueryLite/Common/Helpers.cs
| 2.796875
| 3
|
using QueryLite.Enums;
using QueryLite.Parameters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
namespace QueryLite.Common
{
public static class Helpers
{
public static void SetParameters(this IDbCommand command, SqlAndParameters sqlParameter)
{
// check befor use
sqlParameter?.Parameter?.ForEach(keyValueParameter =>
{
IDbDataParameter parameters = command.CreateParameter();
parameters.ParameterName = keyValueParameter.ParameterKey;
parameters.Value = keyValueParameter.ParameterValue;
command.Parameters.Add(parameters);
});
}
public static void SetParameters<T>(this IDbCommand command, T dataValueObject, DbProviderType DbProvider, List<string> excludeProperties = null, bool isStoredProcedure = false)
{
string TableName = dataValueObject.GetType().Name;
string propertyFieldNames = string.Empty;
string paramsFieldKeys = string.Empty;
List<string> listColumn = new List<string>();
propertyFieldNames = dataValueObject.GetPropertyNames(excludeProperties);
paramsFieldKeys = dataValueObject.GetParamTypeString(DbProvider, excludeProperties);
// set sql
command.CommandText = $"insert into {TableName} ({propertyFieldNames}) values({paramsFieldKeys}) ";
// set command type
command.CommandType = isStoredProcedure ? CommandType.StoredProcedure : CommandType.Text;
// get properties to save to db
listColumn = dataValueObject.GetParamListName(excludeProperties);
// set parameters
listColumn.ForEach(keyValueParameter =>
{
IDbDataParameter parameters = command.CreateParameter();
object ParameterValue = dataValueObject.GetType().GetProperty(keyValueParameter).GetValue(dataValueObject, null);
parameters.ParameterName = keyValueParameter.GetParamType(DbProvider);
parameters.Value = ParameterValue;
command.Parameters.Add(parameters);
});
}
public static void SetParameters<T>(this IDbCommand command, T dataValueObject, DbProviderType DbProvider, string condition, List<string> excludeProperties = null, bool isStoredProcedure = false)
{
string TableName = dataValueObject.GetType().Name;
List<string> listColumn = new List<string>();
string UpdateSet = string.Empty;
UpdateSet = dataValueObject.GetParamTypeUpdateSet(DbProvider, excludeProperties);
// set sql
command.CommandText = $"update {TableName} set {UpdateSet} where {condition} ";
// set command type
command.CommandType = isStoredProcedure ? CommandType.StoredProcedure : CommandType.Text;
// get properties to save to db
listColumn = dataValueObject.GetParamListName(excludeProperties);
// set parameters
listColumn.ForEach(keyValueParameter =>
{
IDbDataParameter parameters = command.CreateParameter();
object ParameterValue = dataValueObject.GetType().GetProperty(keyValueParameter).GetValue(dataValueObject, null);
parameters.ParameterName = keyValueParameter.GetParamType(DbProvider);
parameters.Value = ParameterValue;
command.Parameters.Add(parameters);
});
}
public static string GetStringFromExpression<T>(this Expression<Func<T, bool>> expression)
{
var replacements = new Dictionary<string, string>();
string bodyCondition = string.Empty;
WalkExpression(replacements, expression);
string body = expression.Body.ToString();
foreach (var parm in expression.Parameters)
{
var parmName = parm.Name;
var parmTypeName = parm.Type.Name;
body = body.Replace(parmName + ".", parmTypeName + ".");
}
foreach (var replacement in replacements)
{
body = body.Replace(replacement.Key, replacement.Value);
}
bodyCondition = ReplaceWithLike(body).Replace(typeof(T).Name + ".", "");
return bodyCondition;
}
private static string ReplaceWithLike(string sql)
{
string sqlCondition = string.Empty;
sqlCondition = ReplaceContains(sql).ReplaceEndsWith().ReplaceStartsWith();
return sqlCondition;
}
private static string ReplaceContains(string sql)
{
string sqlCondition = sql;
sqlCondition = sql.Replace("==", "=").
Replace("AndAlso", " And ").
Replace("OrElse", " or ").
Replace(@"\", "").
Replace(@"""", "'");
if (sqlCondition.Contains(".Contains") || sqlCondition.Contains(".EndsWith") || sqlCondition.Contains(".StartsWith"))
{
sqlCondition = sqlCondition.Replace(".Contains('", " like ('%");
string[] Values = sqlCondition.Split(new char[] { '%', ')' });
var ValuesContain = Values.Where(x => string.IsNullOrEmpty(x) == false && x.Contains("like") == false && x.Contains("EndsWith") == false && x.Contains("StartsWith") == false).ToList();
ValuesContain.ForEach((y) => { sqlCondition = sqlCondition.Replace(y, y.Replace("'", "") + "%'"); });
}
return sqlCondition;
}
private static string ReplaceEndsWith(this string sqlCondition)
{
if (sqlCondition.Contains(".Contains") || sqlCondition.Contains(".EndsWith") || sqlCondition.Contains(".StartsWith"))
{
string[] Values = sqlCondition.Split(new char[] { '%', ')' });
var ValuesEndsWith = Values.Where(x => string.IsNullOrEmpty(x) == false && x.Contains("like") == false && x.Contains("EndsWith") == true).ToList();
ValuesEndsWith?.ForEach((y) =>
{
var EndWithValues = y.Split(new string[] { ".EndsWith" }, StringSplitOptions.None);
sqlCondition = sqlCondition.Replace(y, EndWithValues[0] + " like ('" + EndWithValues[1].Replace("'", "").Replace("(", "") + "%'");
});
}
return sqlCondition;
}
private static string ReplaceStartsWith(this string sqlCondition)
{
if (sqlCondition.Contains(".Contains") || sqlCondition.Contains(".EndsWith") || sqlCondition.Contains(".StartsWith"))
{
sqlCondition = sqlCondition.Replace(".StartsWith('", " like ('%").Replace("(", "").Replace(")", "");
}
return sqlCondition;
}
private static void WalkExpression(Dictionary<string, string> replacements, Expression expression)
{
switch (expression.NodeType)
{
case ExpressionType.MemberAccess:
string replacementExpression = expression.ToString();
if (replacementExpression.Contains("value("))
{
string replacementValue = Expression.Lambda(expression).Compile().DynamicInvoke().ToString();
if (!replacements.ContainsKey(replacementExpression))
{
replacements.Add(replacementExpression, replacementValue.ToString());
}
}
break;
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.OrElse:
case ExpressionType.AndAlso:
case ExpressionType.Equal:
var bexp = expression as BinaryExpression;
WalkExpression(replacements, bexp.Left);
WalkExpression(replacements, bexp.Right);
break;
case ExpressionType.Call:
var mcexp = expression as MethodCallExpression;
foreach (var argument in mcexp.Arguments)
{
WalkExpression(replacements, argument);
}
break;
case ExpressionType.Lambda:
var lexp = expression as LambdaExpression;
WalkExpression(replacements, lexp.Body);
break;
case ExpressionType.Constant:
//do nothing
break;
default:
//Trace.WriteLine("Unknown type");
break;
}
}
private static string GetParamType(this string ParamName, DbProviderType DbProvider)
{
string paramType = string.Empty;
if (DbProvider == DbProviderType.SqlClient || DbProvider == DbProviderType.MySqlClient)
{
paramType = "@" + ParamName;
}
else if (DbProvider == DbProviderType.ODBCClient)
{
paramType = "?";
}
return paramType;
}
private static List<string> GetParamListName<T>(this T dataValueObject, List<string> excludeProperties = null)
{
List<string> listColumn = new List<string>();
if (excludeProperties != null)
{
listColumn = dataValueObject.GetType().GetProperties().Where(u => !excludeProperties.Exists(p => p.Equals(u.Name, StringComparison.OrdinalIgnoreCase))).Select(x => x.Name).ToList();
}
else
{
listColumn = dataValueObject.GetType().GetProperties().Select(x => x.Name).ToList();
}
return listColumn;
}
private static string GetParamTypeUpdateSet<T>(this T dataValueObject, DbProviderType DbProvider, List<string> excludeProperties = null)
{
string paramType = string.Empty;
List<string> listColumn = new List<string>();
List<string> listColumnout = new List<string>();
listColumn = dataValueObject.GetParamListName(excludeProperties);
listColumn.ForEach(ParamName =>
{
if (DbProvider == DbProviderType.SqlClient || DbProvider == DbProviderType.MySqlClient)
{
paramType = "@" + ParamName;
}
else if (DbProvider == DbProviderType.ODBCClient)
{
paramType = "?";
}
listColumnout.Add(ParamName + "=" + paramType);
});
return string.Join(",", listColumnout);
}
private static string GetParamTypeString<T>(this T dataValueObject, DbProviderType DbProvider, List<string> excludeProperties = null)
{
string paramType = string.Empty;
List<string> listColumn = new List<string>();
List<string> listColumnout = new List<string>();
listColumn = dataValueObject.GetParamListName(excludeProperties);
listColumn.ForEach(ParamName =>
{
if (DbProvider == DbProviderType.SqlClient || DbProvider == DbProviderType.MySqlClient)
{
paramType = "@" + ParamName;
}
else if (DbProvider == DbProviderType.ODBCClient)
{
paramType = "?";
}
listColumnout.Add(paramType);
});
return string.Join(",", listColumnout);
}
public static string GetPropertyNames<T>(this T dataObject, List<string> excludeProperties = null)
{
List<string> listColumn = new List<string>();
if (excludeProperties != null)
{
listColumn = dataObject.GetType().GetProperties().Where(u => !excludeProperties.Exists(p => p.Equals(u.Name, StringComparison.OrdinalIgnoreCase))).Select(x => "[" + x.Name + "]").ToList();
}
else
{
listColumn = dataObject.GetType().GetProperties().Select(x => "[" + x.Name + "]").ToList();
}
return string.Join(",", listColumn);
}
}
}
|
f0403694cded43358fbcc52917c1880f3dededef
|
C#
|
jmptrader/DtronixModel
|
/DtronixModelTests/Utilities.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DtronixModelTests {
public class Utilities {
public static string GetFileContents(string sampleFile) {
var asm = Assembly.GetExecutingAssembly();
var resource = string.Format("DtronixModelTests.{0}", sampleFile);
using (var stream = asm.GetManifestResourceStream(resource)) {
if (stream != null) {
var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
}
return string.Empty;
}
}
}
|
024c86b1db8a136ad866dd825445a5a1bd29b9ce
|
C#
|
mandov/02.CSharp-Advanced
|
/01.Arrays/ConsoleApplication1/CompareArrays.cs
| 3.96875
| 4
|
using System;
class CompareCharArrays
{
static void Main()
{
string firstWord = Console.ReadLine();
string secondWord = Console.ReadLine();
int ouput = Math.Min(firstWord.Length, secondWord.Length);
for (int i = 0; i < ouput; i++)
{
if (firstWord[i] > secondWord[i] || i == ouput - 1 && firstWord.Length > secondWord.Length)
{
Console.WriteLine(">");
return;
}
else if (firstWord[i] < secondWord[i] || i == ouput - 1 && firstWord.Length < secondWord.Length)
{
Console.WriteLine("<");
return;
}
else if (i == ouput - 1 && firstWord.Length == secondWord.Length)
{
Console.WriteLine("=");
break;
}
}
}
}
|
024399b0e1239d483bdee3cc15f97ee4c5b046f7
|
C#
|
rabyjaycie14/lengthConverterProgram
|
/Form1.cs
| 3.390625
| 3
|
using System;
using System.Windows.Forms;
namespace LengthConverter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Handler Interface
public interface IHandlerInterface
{
// Method for building the chain of responsibility
IHandlerInterface SetNextObject(IHandlerInterface handler);
// Method for executing a request (conversion type)
string Handle(string request, double convertToNewMetric);
}
// Handler Abstract Class
public abstract class AbstractHandler : IHandlerInterface
{
protected IHandlerInterface nextObject;
//Set next objects in chain of responsibility (COR)
public IHandlerInterface SetNextObject(IHandlerInterface handler)
{
nextObject = handler;
return handler;
}
// Pass through all in COR
public virtual string Handle(string request, double convertToNewMetric)
{
if (nextObject != null)
{
return nextObject.Handle(request, convertToNewMetric);
}
else
{
return null;
}
}
}
// Concrete Handler 1
// Convert from kilometers to miles
private class KilometersToMiles : AbstractHandler
{
public override string Handle(string request, double convertToNewMetric)
{
if ((request as string) == "miles")
{
var output = (convertToNewMetric / 1.609).ToString();
return output;
}
else
{
return base.Handle(request, convertToNewMetric);
}
}
}
// Concrete Handler 2
// Convert from kilometers to yards
private class KilometersToYards : AbstractHandler
{
public override string Handle(string request, double convertToNewMetric)
{
if ((request as string) == "yards")
{
var output = (convertToNewMetric * 1093.61).ToString();
return output;
}
else
{
return base.Handle(request, convertToNewMetric);
}
}
}
// Concrete Handler 3
// Convert from kilometers to feet
private class KilometersToFeet : AbstractHandler
{
public override string Handle(string request, double convertToNewMetric)
{
if ((request as string) == "feet")
{
var output = (convertToNewMetric * 3280.84).ToString();
return output;
}
else
{
return base.Handle(request, convertToNewMetric);
}
}
}
// Decorator Abstract Class
// Extends AbstractHandler class to be interchangeable with
// its concrete decorators
public abstract class Decorator : AbstractHandler
{
public abstract override string Handle(string request, double convertToNewMetric);
}
// Concrete Decorator 1
// Round output to 2nd decimal (e.g., 218.723 to 218.72)
public class Rounded2DecimalPlaces : Decorator
{
private AbstractHandler handler;
public Rounded2DecimalPlaces()
{
}
public Rounded2DecimalPlaces(AbstractHandler handler)
{
this.handler = handler;
}
public override string Handle(string request, double convertToNewMetric)
{
string token = handler.Handle(request, convertToNewMetric).ToString();
decimal newToken = decimal.Parse(token);
string output = newToken.ToString("F2");
return output;
}
}
// Concrete Decorator 2
// Write output in exp.notation(e.g., 218.72 to 2.1872e2 )
public class ExpNotation : Decorator
{
private AbstractHandler handler;
public ExpNotation()
{
}
public ExpNotation(AbstractHandler handler)
{
this.handler = handler;
}
public override string Handle(string request, double convertToNewMetric)
{
string token = handler.Handle(request, convertToNewMetric).ToString();
decimal newToken = decimal.Parse(token);
string output = newToken.ToString("#0.0e0");
return output;
}
}
// Concrete Decorator 3
// Add the unit name to the converted amount (e.g., 2.1872e2 to 2.1872e2 Yards)
public class AddUnitName : Decorator
{
private AbstractHandler handler;
public AddUnitName()
{
}
public AddUnitName(AbstractHandler handler)
{
this.handler = handler;
}
public override string Handle(string request, double convertToNewMetric)
{
string token = handler.Handle(request, convertToNewMetric).ToString();
return token + " " + request;
}
}
// Client
public class ClientRequest
{
public static string ClientInput(AbstractHandler handler, string conversionType, double userInput)
{
//Console.WriteLine($"Client wants to convert {userInput} kilometers to {conversionType} \n");
object result = handler.Handle(conversionType, userInput);
if (result != null)
{
return ($"{result}");
}
else
{
return ($"{conversionType} was not utilized.\n");
}
}
}
// Label1 on the GUI that states the metric type: kilometers
private void label1_Click(object sender, EventArgs e)
{
}
// Convert button on the GUI
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = string.Empty; // clear textbox2
double input = double.Parse(textBox1.Text); // get user input kilometers
string text = comboBox1.GetItemText(comboBox1.SelectedItem); //get item the user selects in the combo box
//Create the chain links
AbstractHandler miles = new KilometersToMiles();
AbstractHandler yards = new KilometersToYards();
AbstractHandler feet = new KilometersToFeet();
miles.SetNextObject(yards).SetNextObject(feet);
//string finalResult = ClientRequest.ClientInput(miles, text, input); //no decorators, only chain of responsibility
//textBox2.AppendText(finalResult); //output to textbox
miles = new Rounded2DecimalPlaces(miles); //add decorator 1
miles = new ExpNotation(miles); //add decorator 2
miles = new AddUnitName(miles); //add decorator 3
string finalResult = ClientRequest.ClientInput(miles, text, input); //all three decorators
textBox2.AppendText(finalResult); //output to textbox
}
// Combobox on GUI: {miles, yards, feet}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
// Textbox1 on the GUI that accepts user input
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
// Textbox2 on the GUI that displays the conversion result
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
|
c032d7f668151c9babf7a87870f55743754f4f84
|
C#
|
BitMiracle/libjpeg.net
|
/Jpeg/Program.cs
| 2.640625
| 3
|
using System;
using System.IO;
using BitMiracle.LibJpeg.Classic;
namespace BitMiracle.Jpeg
{
public partial class Program
{
class Options
{
public string InputFileName = "";
public string OutputFileName = "";
}
static bool m_printedVersion = false;
static string m_programName; /* program name for error messages */
public static void Main(string[] args)
{
m_programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
Options options = parseArguments(args);
if (options == null)
{
usage();
return;
}
/* Open the input file. */
using (FileStream inputFile = openInputFile(options.InputFileName))
{
if (inputFile == null)
return;
/* Open the output file. */
using (FileStream outputFile = createOutputFile(options.OutputFileName))
{
if (outputFile == null)
return;
CompressOptions compressOptions = options as CompressOptions;
if (compressOptions != null)
compress(inputFile, compressOptions, outputFile);
DecompressOptions decompressOptions = options as DecompressOptions;
if (decompressOptions != null)
decompress(inputFile, decompressOptions, outputFile);
}
}
}
static Options parseArguments(string[] argv)
{
if (argv.Length <= 1)
{
//usage();
return null;
}
bool modeCompress;
if (argv[0] == "-c")
modeCompress = true;
else if (argv[0] == "-d")
modeCompress = false;
else
return null;
if (modeCompress)
return parseSwitchesForCompression(argv);
else
return parseSwitchesForDecompression(argv);
}
static FileStream openInputFile(string fileName)
{
try
{
return new FileStream(fileName, FileMode.Open);
}
catch (Exception e)
{
Console.WriteLine(string.Format("{0}: can't open {1}", m_programName, fileName));
Console.WriteLine(e.Message);
return null;
}
}
static FileStream createOutputFile(string fileName)
{
try
{
return new FileStream(fileName, FileMode.Create);
}
catch (Exception e)
{
Console.WriteLine(string.Format("{0}: can't open {1}", m_programName, fileName));
Console.WriteLine(e.Message);
return null;
}
}
private static void usage()
{
Console.WriteLine(string.Format("usage: {0} (-c | -d) [switches] inputfile outputfile", m_programName));
Console.WriteLine(" -c Compress inputfile");
Console.WriteLine(" -d Decompress inputfile");
usageForCompression();
usageForDecompression();
}
/// <summary>
/// complain about bad command line
/// </summary>
private static void usageForCompression()
{
Console.WriteLine("\n");
Console.WriteLine("Switches for compression (names may be abbreviated):");
Console.WriteLine(" -quality N Compression quality (0..100; 5-95 is useful range)");
Console.WriteLine(" -grayscale Create monochrome JPEG file");
Console.WriteLine(" -optimize Optimize Huffman table (smaller file, but slow compression)");
Console.WriteLine(" -progressive Create progressive JPEG file");
Console.WriteLine("Switches for advanced users:");
writeUsageForDCT();
Console.WriteLine(" -restart N Set restart interval in rows, or in blocks with B");
Console.WriteLine(" -smooth N Smooth dithered input (N=1..100 is strength)");
Console.WriteLine(" -outfile name Specify name for output file");
Console.WriteLine(" -verbose or -debug Emit debug output");
Console.WriteLine("Switches for wizards:");
Console.WriteLine(" -baseline Force baseline quantization tables");
Console.WriteLine(" -qtables file Use quantization tables given in file");
Console.WriteLine(" -qslots N[,...] Set component quantization tables");
Console.WriteLine(" -sample HxV[,...] Set component sampling factors");
}
/// <summary>
/// Complain about bad command line
/// </summary>
private static void usageForDecompression()
{
Console.WriteLine("\n");
Console.WriteLine("Switches for decompression (names may be abbreviated):");
Console.WriteLine(" -colors N Reduce image to no more than N colors");
Console.WriteLine(" -fast Fast, low-quality processing");
Console.WriteLine(" -grayscale Force grayscale output");
Console.WriteLine(" -scale M/N Scale output image by fraction M/N, eg, 1/8");
Console.WriteLine(" -os2 Select BMP output format (OS/2 style)");
Console.WriteLine("Switches for advanced users:");
writeUsageForDCT();
Console.WriteLine(" -dither fs Use F-S dithering (default)");
Console.WriteLine(" -dither none Don't use dithering in quantization");
Console.WriteLine(" -dither ordered Use ordered dither (medium speed, quality)");
Console.WriteLine(" -map FILE Map to colors used in named image file");
Console.WriteLine(" -nosmooth Don't use high-quality upsampling");
Console.WriteLine(" -onepass Use 1-pass quantization (fast, low quality)");
Console.WriteLine(" -outfile name Specify name for output file");
Console.WriteLine(" -verbose or -debug Emit debug output");
}
private static void writeUsageForDCT()
{
Console.WriteLine(" -dct int Use integer DCT method {0}", (JpegConstants.JDCT_DEFAULT == J_DCT_METHOD.JDCT_ISLOW) ? " (default)" : "");
Console.WriteLine(" -dct fast Use fast integer DCT (less accurate) {0}", (JpegConstants.JDCT_DEFAULT == J_DCT_METHOD.JDCT_IFAST) ? " (default)" : "");
Console.WriteLine(" -dct float Use floating-point DCT method {0}", (JpegConstants.JDCT_DEFAULT == J_DCT_METHOD.JDCT_FLOAT) ? " (default)" : "");
}
}
}
|
ad6a5c521e9f4b91e257eef6d978457c7657a0c7
|
C#
|
sillsdev/genericinstaller
|
/CustomActions/CustomActions/CustomAction.cs
| 2.53125
| 3
|
using System;
using System.Drawing;
using System.IO;
using Microsoft.Deployment.WindowsInstaller;
namespace CustomActions
{
public class CustomActions
{
[CustomAction]
public static ActionResult CheckAppPath(Session session)
{
//Referenced by CustomAction CheckApplicationPath
session.Log("Checking Application Path.");
string apppath = session["APPFOLDER"];
string datapath = session["DATAFOLDER"];
string dataFolderFound = session["DATAFOLDERFOUND"];
char[] trimchars = new[] { Path.DirectorySeparatorChar };
apppath = apppath.TrimEnd(trimchars);
datapath = datapath.TrimEnd(trimchars);
//set the message if WixUIValidatePath found an error.
if (session["WIXUI_INSTALLDIR_VALID"] != "1")
session["InvalidDirText"] = "Installation directory must be on a local hard drive.";
//return failure if the app path is the program files directory
string progFilesDir = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
string progFiles86Dir = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
//On 32bit XP machines ProgramFilesX86 will return an empty string.
if (String.IsNullOrEmpty(progFiles86Dir))
progFiles86Dir = progFilesDir;
//If both values point to the x86 dir, truncate one.
if (progFiles86Dir.EndsWith(" (x86)") && progFilesDir.EndsWith(" (x86)"))
{
progFilesDir = progFilesDir.Substring(0, progFilesDir.IndexOf(" (x86)", StringComparison.OrdinalIgnoreCase));
}
//If neither value points to the x86 dir, concat x86 onto one.
if (!progFiles86Dir.EndsWith(" (x86)") && !progFilesDir.EndsWith(" (x86)"))
{
progFiles86Dir = progFiles86Dir + " (x86)";
}
//Find the drive letter of the system volume
string driveRoot = progFilesDir.Substring(0, progFilesDir.IndexOf(Path.DirectorySeparatorChar));
CheckPath(session, apppath, driveRoot, progFilesDir, progFiles86Dir);
//This change will only check the project folder path if it is a newly defined one.
//If there already was a path defined in the registry then just accept it and move on.
if (dataFolderFound == "NotFound")
CheckPath(session, datapath, driveRoot, progFilesDir, progFiles86Dir);
return ActionResult.Success;
}
private static void CheckPath(Session session, string path, string root, string pfDir, string pf86Dir)
{
//make sure the selected path is not one of these bad places to put stuff.
if (path.EndsWith(":") ||
path.Equals(pfDir, StringComparison.OrdinalIgnoreCase) ||
path.Equals(pf86Dir, StringComparison.OrdinalIgnoreCase) ||
path.Equals(root + Path.DirectorySeparatorChar + "Windows", StringComparison.OrdinalIgnoreCase) ||
path.Equals(root + Path.DirectorySeparatorChar + "Users", StringComparison.OrdinalIgnoreCase) ||
path.Equals(root + Path.DirectorySeparatorChar + "Users" + Path.DirectorySeparatorChar + "Public", StringComparison.OrdinalIgnoreCase) ||
path.Equals(root + Path.DirectorySeparatorChar + "i386", StringComparison.OrdinalIgnoreCase) ||
path.Equals(Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory), StringComparison.OrdinalIgnoreCase) ||
path.Equals(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), StringComparison.OrdinalIgnoreCase) ||
path.Equals(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), StringComparison.OrdinalIgnoreCase) ||
path.Equals(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), StringComparison.OrdinalIgnoreCase) ||
path.Equals(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), StringComparison.OrdinalIgnoreCase) ||
path.Equals(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), StringComparison.OrdinalIgnoreCase) ||
path.Equals(Environment.GetFolderPath(Environment.SpecialFolder.System), StringComparison.OrdinalIgnoreCase) ||
path.Equals(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), StringComparison.OrdinalIgnoreCase))
{
session["InvalidDirText"] = String.Format("Cannot install to {0}.", path);
session["WIXUI_INSTALLDIR_VALID"] = "0";
}
}
[CustomAction]
public static ActionResult VerifyDataDirPath(Session session)
{
//Referenced by CustomAction VerifyDataPath
session.Log("Begin VerifyDataPath in custom action dll");
string registryKey = session["REGISTRYDATAKEY"];
string valueName = session["REGISTRYDATAVALUENAME"];
string regDataPath = GetDataDirFromRegistry(registryKey, valueName, session);
if (string.IsNullOrEmpty(regDataPath))
{
session["REGDATAFOLDER"] = null;
session["DATAFOLDERFOUND"] = "NotFound";
return ActionResult.Success;
}
session["REGDATAFOLDER"] = regDataPath;
if (Directory.Exists(regDataPath) && Directory.GetFiles(regDataPath).Length > 0)
session["DATAFOLDERFOUND"] = "AlreadyExisting";
else
{
session["DATAFOLDERFOUND"] = "InvalidRegEntry";
}
return ActionResult.Success;
}
[CustomAction]
public static ActionResult ClosePrompt(Session session)
{
//Referenced by CustomAction CloseApplications
session.Log("Begin PromptToCloseApplications");
try
{
var productName = session["ProductName"];
var processes = session["PromptToCloseProcesses"].Split(',');
var displayNames = session["PromptToCloseDisplayNames"].Split(',');
if (processes.Length != displayNames.Length)
{
session.Log(@"Please check that 'PromptToCloseProcesses' and 'PromptToCloseDisplayNames' exist and have same number of items.");
return ActionResult.Failure;
}
for (var i = 0; i < processes.Length; i++)
{
session.Log("Prompting process {0} with name {1} to close.", processes[i], displayNames[i]);
using (var prompt = new PromptCloseApplication(session, productName, processes[i], displayNames[i]))
if (!prompt.Prompt())
return ActionResult.Failure;
}
}
catch (Exception ex)
{
session.Log("Missing properties or wrong values. Please check that 'PromptToCloseProcesses' and 'PromptToCloseDisplayNames' exist and have same number of items. \nException:" + ex.Message);
return ActionResult.Failure;
}
session.Log("End PromptToCloseApplications");
return ActionResult.Success;
}
[CustomAction]
public static ActionResult DeleteVersionNumberFromRegistry(Session sessionb)
{
//Referenced by CustomAction DeleteRegistryVersionNumber
string versionKeyPath = sessionb["REGISTRYVERSIONKEY"];
string versionKeyWow = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\" + versionKeyPath + "\\";
string versionKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\" + versionKeyPath + "\\";
try
{
if (RegistryU.KeyExists(versionKey))
RegistryU.DelKey(versionKey);
if (RegistryU.KeyExists(versionKeyWow))
RegistryU.DelKey(versionKeyWow);
}
catch (Exception e)
{
sessionb.Log("Exception occured while deleting a registry key." + e.Message);
}
return ActionResult.Success;
}
[CustomAction]
public static ActionResult LookForInstalledFonts(Session session)
{
//Referenced by CustomAction SetFontValues
//Check for each font that we want to install
session["DOULOS_INSTALLED"] = DoesFontExist(session, "Doulos SIL", FontStyle.Regular).ToString();
if (session["DOULOS_INSTALLED"].Equals("False"))
File.Delete(@"C:\\Windows\\Fonts\\DoulosSIL-R.ttf");
session["SBLHEB_INSTALLED"] = DoesFontExist(session, "SBL Hebrew", FontStyle.Regular).ToString();
if (session["SBLHEB_INSTALLED"].Equals("False"))
File.Delete(@"C:\\Windows\\Fonts\\SBL_Hbrw.ttf");
session["CHARIS_INSTALLED"] = DoesFontExist(session, "Charis SIL", FontStyle.Regular).ToString();
if (session["CHARIS_INSTALLED"].Equals("False"))
{
File.Delete(@"C:\\Windows\\Fonts\\CharisSIL-B.ttf");
File.Delete(@"C:\\Windows\\Fonts\\CharisSIL-BI.ttf");
File.Delete(@"C:\\Windows\\Fonts\\CharisSIL-I.ttf");
File.Delete(@"C:\\Windows\\Fonts\\CharisSIL-R.ttf");
}
session["APPARATUS_INSTALLED"] = DoesFontExist(session, "Apparatus SIL", FontStyle.Regular).ToString();
if (session["APPARATUS_INSTALLED"].Equals("False"))
{
File.Delete(@"C:\\Windows\\Fonts\\AppSILB.TTF");
File.Delete(@"C:\\Windows\\Fonts\\AppSILBI.TTF");
File.Delete(@"C:\\Windows\\Fonts\\AppSILI.TTF");
File.Delete(@"C:\\Windows\\Fonts\\AppSILR.TTF");
}
session["GALATIA_INSTALLED"] = DoesFontExist(session, "Galatia SIL", FontStyle.Regular).ToString();
if (session["GALATIA_INSTALLED"].Equals("False"))
{
File.Delete(@"C:\\Windows\\Fonts\\GalSILB.ttf");
File.Delete(@"C:\\Windows\\Fonts\\GalSILR.ttf");
}
session["EZRA_INSTALLED"] = DoesFontExist(session, "Ezra SIL", FontStyle.Regular).ToString();
if (session["EZRA_INSTALLED"].Equals("False"))
{
File.Delete(@"C:\\Windows\\Fonts\\SILEOT.ttf");
File.Delete(@"C:\\Windows\\Fonts\\SILEOTSR.ttf");
}
return ActionResult.Success;
}
private static string GetDataDirFromRegistry(string path, string valueName, Session session)
{
string dataPathKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\" + path;
string dataPathKeyWow = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\" + path;
string projPath = "";
try
{
if (RegistryU.KeyExists(dataPathKey))
projPath = RegistryU.GetKey("HKLM", "SOFTWARE\\" + path).GetValue(valueName).ToString();
if (RegistryU.KeyExists(dataPathKeyWow))
projPath = RegistryU.GetKey("HKLM", "SOFTWARE\\Wow6432Node\\" + path).GetValue(valueName).ToString();
}
catch (Exception ex)
{
session.Log(ex.Message);
}
return projPath;
}
public static bool DoesFontExist(Session session, string fontFamilyName, FontStyle fontStyle)
{
bool result;
try
{
using (FontFamily family = new FontFamily(fontFamilyName))
result = family.IsStyleAvailable(fontStyle);
}
catch (ArgumentException)
{
result = false;
}
session.Log("Return Value for " + fontFamilyName + " : " + fontStyle.ToString() + " is " + result);
return result;
}
}
}
|
84bc300735d6946bad2fc35d1bbd25b78592774a
|
C#
|
ulanscodes/atata
|
/src/Atata/Components/Fields/Select`1.cs
| 2.53125
| 3
|
namespace Atata
{
/// <summary>
/// Represents the text select control (<c><select></c>).
/// Default search is performed by the label.
/// Selects an option using text.
/// Option selection is configured via <see cref="SelectOptionBehaviorAttribute"/>.
/// Possible selection behavior attributes are: <see cref="SelectByTextAttribute"/>, <see cref="SelectByValueAttribute"/>, <see cref="SelectByLabelAttribute"/> and <see cref="SelectByAttribute"/>.
/// Default option selection is performed by text using <see cref="SelectByTextAttribute"/>.
/// </summary>
/// <typeparam name="TOwner">The type of the owner page object.</typeparam>
public class Select<TOwner> : Select<string, TOwner>
where TOwner : PageObject<TOwner>
{
}
}
|
4c1b0c7e4ac1810de5e3c5d1981faf779c6f9c81
|
C#
|
RobertoHGMV/ProductsWs
|
/src/ProductsWs.Infra/Repositories/ProductRepository.cs
| 2.90625
| 3
|
using ProdctsWs.Domain.Models;
using ProdctsWs.Domain.Repositories;
using ProductsWs.Infra.Contexts;
using System.Collections.Generic;
using System.Linq;
namespace ProductsWs.Infra.Repositories
{
public class ProductRepository : IProductRepository
{
ProductDataContext _context;
public ProductRepository()
{
_context = ProductDataContext.Instance;
}
public Product Get(string itemCode)
{
return _context.Products.FirstOrDefault(c => itemCode.Equals(c.ItemCode));
}
public List<Product> GetAll()
{
return _context.Products;
}
public void Add(Product product)
{
_context.Products.Add(product);
}
public void Update(Product product)
{
var productDb = Get(product.ItemCode);
productDb.ItemCode = product.ItemCode;
productDb.ItemName = product.ItemName;
productDb.Quantity = product.Quantity;
productDb.Price = product.Price;
productDb.CalcTotal();
}
public void Delete(Product product)
{
_context.Products.Remove(product);
}
}
}
|
191f6e6cf678139ac2375cf08aba69931ae4e4fd
|
C#
|
vvk120380/FB2Snitch
|
/FB2Snitch/BLL/FB2Base.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
namespace FB2Snitch.BLL
{
public class FB2Person
{
public FB2Person()
{
}
public String firstname;
public String middlename;
public String lastname;
public String nickname;
public String homepage;
public String email;
public override string ToString()
{
String strRet = "";
if (firstname != null && firstname.Length > 0) strRet += firstname;
if (middlename != null && middlename.Length > 0)
{
if (strRet.Length > 0) strRet = strRet + " " + middlename;
else strRet = strRet + middlename;
}
if (lastname != null && lastname.Length > 0)
{
if (strRet.Length > 0) strRet = strRet + " " + lastname;
else strRet = strRet + lastname;
}
return strRet;
}
public Boolean Parse(XmlNodeList nodelist)
{
Boolean retVal = true;
foreach (XmlNode nPerson in nodelist)
{
switch (nPerson.Name)
{
case "first-name": { firstname = nPerson.InnerText; break; }
case "middle-name": { middlename = nPerson.InnerText; break; }
case "last-name": { lastname = nPerson.InnerText; break; }
case "nickname": { nickname = nPerson.InnerText; break; }
case "home-page": { homepage = nPerson.InnerText; break; }
case "email": { email = nPerson.InnerText; break; }
default: { retVal = false; break; }
}
}
return retVal;
}
}
public class FB2TitleInfo
{
public FB2TitleInfo()
{
genre = new List<String>();
author = new List<FB2Person>();
translator = new FB2Person();
}
public List<String> genre; //Жанр произведения
public List<FB2Person> author; //Автор произведения
public String book_title; //Название книги
public String annotation; //Аннотация. Краткое текстовое описание книги
public String keywords; //Список ключевых слов, с помощью которых библиотечный софт может искать книгу
public String date; //Дата написания книги
public String coverpage; //Картинка обложки. Содержит внутри элемент image, в который непосредственно и находится ссылка на bin-объект. Элементов image может быть несколько
public String lang; //Язык, на котором написана книга
public String src_lang; //Язык, на котором написан оригинал (для переводных книг)
public FB2Person translator; //Информация о переводчике (для переводных книг) ФИО
public String sequence; //Серия, в которую входит книга. Допускается неограниченное число вложенных серий.
public Boolean Parse(XmlNodeList nodelist)
{
Boolean retVal = true;
foreach (XmlNode nTitleInfo in nodelist)
{
switch (nTitleInfo.Name)
{
case "genre": { genre.Add(nTitleInfo.InnerText); break; }
case "author":
{
FB2Person fb2person = new FB2Person();
fb2person.Parse(nTitleInfo.ChildNodes);
author.Add(fb2person);
break;
}
case "book-title": { book_title = nTitleInfo.InnerText; break; }
case "annotation": { annotation = nTitleInfo.InnerText; break; }
case "keywords": { keywords = nTitleInfo.InnerText; break; }
case "date": { date = nTitleInfo.InnerText; break; }
case "coverpage":
{
/*
* обложка книги. Внутри может содержать только тэг <image/>. От нуля до одного вхождения.
* (значок # говорит, что эта ссылка локальная, то есть адресует в пределах документа).
*/
XmlNodeList nLImage = nTitleInfo.ChildNodes;
foreach (XmlNode nImage in nLImage)
{
//XmlNodeList nLAttr = nImage.Attributes.Count;
if (nImage.Name == "image")
for (int i = 0; i < nImage.Attributes.Count; i++)
{
if (nImage.Attributes[i].LocalName == "href")
{
coverpage = nImage.Attributes[i].Value;
//удаляем значек # в начале
if (coverpage.IndexOf("#") == 0) coverpage = coverpage.Substring(1);
}
}
}
break;
}
case "lang": { lang = nTitleInfo.InnerText; break; }
case "src-lang": { src_lang = nTitleInfo.InnerText; break; }
case "translator": { translator.Parse(nTitleInfo.ChildNodes); break; }
case "sequence":
{
if (nTitleInfo.Attributes.Count != 0)
{
for (int i = 0; i < nTitleInfo.Attributes.Count; i++)
{
switch (nTitleInfo.Attributes[i].Name)
{
case "name":
{
if (!String.IsNullOrEmpty(sequence))
sequence += ("; " + nTitleInfo.Attributes[i].Value);
else
sequence = nTitleInfo.Attributes[i].Value;
break;
}
case "number":
{
if (!String.IsNullOrEmpty(sequence))
{
sequence += (", №" + nTitleInfo.Attributes[i].Value);
}
break;
}
}
}
}
//sequence = nTitleInfo.InnerText;
break;
}
default: { retVal = false; break; }
}
}
return (retVal);
}
}
public class FB2DocumentInfo
{
public FB2DocumentInfo()
{
history = new List<String>();
author = new FB2Person();
}
public FB2Person author; //Cоздатель электронной книги
public String program_used; //Программное обеспечение, использовавшееся при создании книги.
public String date; //Дата создания файла
public String src_url; //Ссылка на сайт, если исходный текст книги был скачан из Интернета
public String src_ocr; //Информация о людях, которые сканировали (набирали) и вычитывали книгу
public String id; //Уникальный идентификационный номер книги
public String version; //Номер версии файла
public List<String> history; //История изменений, вносившихся в файл
public Boolean Parse(XmlNodeList nodelist)
{
Boolean retVal = true;
foreach (XmlNode nDocumentInfo in nodelist)
{
switch (nDocumentInfo.Name)
{
case "author": { author.Parse(nDocumentInfo.ChildNodes); break; }
case "program-used": { program_used = nDocumentInfo.InnerText; break; }
case "date": { date = nDocumentInfo.InnerText; break; }
case "src-url": { src_url = nDocumentInfo.InnerText; break; }
case "src-ocr": { src_ocr = nDocumentInfo.InnerText; break; }
case "id": { id = nDocumentInfo.InnerText; break; }
case "version": { version = nDocumentInfo.InnerText; break; }
case "history": { foreach (XmlNode nHistory in nDocumentInfo.ChildNodes) history.Add(nHistory.InnerText); break; }
default: { retVal = false; break; }
}
}
return retVal;
}
}
public class FB2PublishInfo
{
public FB2PublishInfo()
{
}
public String bookname; //Название бумажного оригинала
public String publisher; //Название издательства, выпустившего бумажный оригинал.
public String city; //Город, в котором был издан бумажный оригинал
//Год выхода бумажного оригинала
public String year; //Год выхода бумажного оригинала
//ISBN-код бумажного оригинала
public String isbn; //ISBN-код бумажного оригинала
public String sequence; //Серия, в которую входит книга. Допускается неограниченное число вложенных серий.
public Boolean Parse(XmlNodeList nodelist)
{
Boolean retVal = true;
foreach (XmlNode nPublishInfo in nodelist)
{
switch (nPublishInfo.Name)
{
case "book-name": //Название бумажного оригинала.
{
bookname = nPublishInfo.InnerText;
break;
}
case "publisher":
{
publisher = nPublishInfo.InnerText;
break;
}
case "city":
{
city = nPublishInfo.InnerText;
break;
}
case "year":
{
year = nPublishInfo.InnerText;
break;
}
case "isbn":
{
isbn = nPublishInfo.InnerText;
break;
}
case "sequence":
{
sequence = nPublishInfo.InnerText;
break;
}
default:
{
retVal = false;
break;
}
}
}
return retVal;
}
}
public class FB2Description
{
public FB2Description()
{
titleinfo = new FB2TitleInfo();
srctitleinfo = new FB2TitleInfo();
documentinfo = new FB2DocumentInfo();
publishinfo = new FB2PublishInfo();
}
public FB2TitleInfo titleinfo; // Содержит базовую информацию о книге (заголовок, информация об авторе и переводчике, аннотация, вхождение в серию и т.д.)
public FB2TitleInfo srctitleinfo; //Cодержит базовую информацию о книге-оригинале (для переводных книг)
public FB2DocumentInfo documentinfo; //Информация о самом файле FictionBook — кем, когда и с помощью каких программных средств создана данная электронная книга
public FB2PublishInfo publishinfo; //Информация о бумажном оригинале книги, если таковой существовал в природе
public Boolean Parse(XmlNodeList nodelist)
{
Boolean retVal = true;
foreach (XmlNode nDescription in nodelist)
{
switch (nDescription.Name)
{
case "title-info":
{
XmlNodeList nLTitleInfo = nDescription.ChildNodes;
titleinfo.Parse(nLTitleInfo);
break;
}
case "src-title-info":
{
XmlNodeList nLSrcTitleInfo = nDescription.ChildNodes;
srctitleinfo.Parse(nLSrcTitleInfo);
break;
}
case "document-info":
{
XmlNodeList nLDocumentInfo = nDescription.ChildNodes;
documentinfo.Parse(nLDocumentInfo);
break;
}
case "publish-info": //Информация о бумажном оригинале книги, если таковой существовал в природе
{
XmlNodeList nLPublishInfo = nDescription.ChildNodes;
publishinfo.Parse(nLPublishInfo);
break;
}
case "custom-info":
{
XmlNodeList nLCustomInfo = nDescription.ChildNodes;
foreach (XmlNode nCustomInfo in nLCustomInfo)
{
//Console.WriteLine(" <" + nCustomInfo.Name + ">" + " - " + nCustomInfo.InnerText);
}
break;
}
}
}
return retVal;
}
}
class FB2Image
{
public FB2Image(string id, string type, string data)
{
this.id = id;
this.type = type;
this.data = data;
}
public string id; // идентификатор изображения
public string type; // тип изображения - jpeg или png
public string data; // само изображение в формате Base64
}
class FB2Binary
{
private List<FB2Image> images; //Жанр произведения
public FB2Binary()
{
images = new List<FB2Image>();
}
public void Add(XmlNode node)
{
//Раздел "binary" должен содержать 2 обязательных аттрибута "id" и "content-type"
//Из картинок поддерживаются форматы JPG (тип image/jpeg) и PNG (тип image/png) - поле "content-type"
//Порядок аттрибутов может быть любой!!!!
if (node.Attributes.Count >= 2)
{
if (node.Attributes[0].Name == "id" && node.Attributes[1].Name == "content-type" && (node.Attributes[1].Value == "image/jpeg" || node.Attributes[1].Value == "image/png"))
{
if (node.ChildNodes.Count != 0)
{
FB2Image fb2image = new FB2Image(node.Attributes[0].Value, node.Attributes[1].Value, node.FirstChild.Value);
images.Add(fb2image);
}
}
else
if (node.Attributes[1].Name == "id" && node.Attributes[0].Name == "content-type" && (node.Attributes[0].Value == "image/jpeg" || node.Attributes[0].Value == "image/png"))
{
if (node.ChildNodes.Count != 0)
{
FB2Image fb2image = new FB2Image(node.Attributes[1].Value, node.Attributes[0].Value, node.FirstChild.Value);
images.Add(fb2image);
}
}
}
}
public int Count
{
get
{
return images.Count;
}
}
public FB2Image this[string id]
{
get
{
if (String.IsNullOrEmpty(id)) return null;
FB2Image image = images.Find(x => x.id == id);
if (image != null) return image; else return null;
}
}
public FB2Image this[int num]
{
get
{
if (num > Count) return null;
FB2Image image = images[num];
if (image != null) return image; else return null;
}
}
}
class FB2Manager
{
public static Encoding GetEncoding(String fn)
{
try
{
using (XmlReader xml = XmlReader.Create(fn))
{
while (xml.Read())
switch (xml.NodeType)
{
case XmlNodeType.XmlDeclaration:
{
String encoding = xml.GetAttribute("encoding");
if (!String.IsNullOrEmpty(encoding))
return (Encoding.GetEncoding(xml.GetAttribute("encoding")));
break;
}
}
return null;
}
}
catch (XmlException ex)
{
return null;
}
}
static public FB2Description ReadDecriptionFast(string filename)
{
FB2Description FB2Desc = new FB2Description();
XmlDocument doc = new XmlDocument();
Encoding xmlEncode = GetEncoding(filename);
try
{
using (XmlReader xml = xmlEncode == null ? XmlReader.Create(new StreamReader(filename)) : XmlReader.Create(new StreamReader(filename, xmlEncode)))
{
while (xml.Read())
{
switch (xml.NodeType)
{
case XmlNodeType.Element:
{
if (xml.Name == "description")
{
String desc = xml.ReadOuterXml();
doc.LoadXml(desc);
XmlNodeList nodeList = doc.ChildNodes;
FB2Desc = new FB2Description();
FB2Desc.Parse(nodeList[0].ChildNodes);
return FB2Desc;
}
break;
}
}
}
}
}
catch (XmlException ex)
{
Console.WriteLine(String.Format("ERROR! {0} - {1}", filename, ex.Message));
throw new FB2BaseException("Ошибка загрузки fb2."); ;
}
return FB2Desc;
}
static public FB2Description ReadDecription(string filename)
{
FB2Description FB2Desc = new FB2Description();
XmlDocument doc = new XmlDocument();
try
{
//using (FileStream fStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
//{
TimeSpan ts_load;
TimeSpan ts_parse;
string elapsedTime;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
doc.LoadXml(System.IO.File.ReadAllText(filename));
ts_load = stopWatch.Elapsed;
stopWatch.Restart();
//doc.Load(fStream);
Encoding fileEncoding = null;
// The first child of a standard XML document is the XML declaration.
// The following code assumes and reads the first child as the XmlDeclaration.
if (doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
{
// Get the encoding declaration.
fileEncoding = Encoding.GetEncoding(((XmlDeclaration)doc.FirstChild).Encoding);
}
if (fileEncoding != null)
{
doc.LoadXml(System.IO.File.ReadAllText(filename, fileEncoding));
Console.WriteLine(fileEncoding.ToString());
}
XmlNodeList nodes = doc.DocumentElement.GetElementsByTagName("description");
if (nodes.Count >= 1)
FB2Desc.Parse(nodes[0].ChildNodes);
else
throw new FB2BaseException("Ошибка загрузки fb2. Элемент <description> не найден");
ts_parse = stopWatch.Elapsed;
stopWatch.Stop();
Console.WriteLine("--- read fb2 description");
Console.WriteLine(String.Format("--- load {0:00}.{1:00} - parse {2:00}.{3:00}",
ts_load.Seconds, ts_load.Milliseconds, ts_parse.Seconds, ts_parse.Milliseconds));
//}
}
catch (Exception ex)
{
Console.WriteLine(String.Format("ERROR! {0} - {1}", filename, ex.Message));
throw new FB2BaseException("Ошибка загрузки fb2."); ;
}
return (FB2Desc);
}
static public FB2Binary ReadBinary(string filename)
{
FB2Binary FB2Bin = new FB2Binary();
XmlDocument doc = new XmlDocument();
doc.LoadXml(System.IO.File.ReadAllText(filename));
Encoding fileEncoding = null;
// The first child of a standard XML document is the XML declaration.
// The following code assumes and reads the first child as the XmlDeclaration.
if (doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
{
// Get the encoding declaration.
fileEncoding = Encoding.GetEncoding(((XmlDeclaration)doc.FirstChild).Encoding);
}
if (fileEncoding != null)
{
doc.LoadXml(System.IO.File.ReadAllText(filename, fileEncoding));
}
XmlNodeList nodes = doc.DocumentElement.GetElementsByTagName("binary");
foreach (XmlNode node in nodes)
{
FB2Bin.Add(node);
}
return (FB2Bin);
}
}
}
|
705d6acc1ed331dd732ba42886389c2b929380dc
|
C#
|
Alexandrfromminsk/Algorithms
|
/Sorting/Sorting/Program.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sorting
{
class Program
{
static void Main(string[] args)
{
//My Implementation for Learning
IComparable[] testList = Helper.generateRandonArray(100);
Console.WriteLine("Original list:");
Helper.printArray(testList);
Console.WriteLine("Is original list sorted?");
Console.WriteLine(Sort.isSorted(testList));
/* InsertionSort
InsertionSort.insertionSort(testList);
Console.WriteLine("InsertionSort list:");
Helper.printArray(testList);
Console.WriteLine("Is new list sorted?");
Console.WriteLine(Sort.isSorted(testList));
*/
//SelectionSort
SelectionSort.selectionSort(testList);
Console.WriteLine("SelectionSort list:");
Helper.printArray(testList);
Console.WriteLine("Is new list sorted?");
Console.WriteLine(Sort.isSorted(testList));
Console.ReadKey();
}
}
}
|
efcabcf8010cb82a01114cb937a62852c62569d4
|
C#
|
JonathanCPWarner/RollingBallGame
|
/Rolling Ball Lab/Assets/Scripts/CamSwitch.cs
| 2.59375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamSwitch : MonoBehaviour
{
public GameObject cameraZoomedOut; //CameraZoomedOut = "CameraTarget"
public GameObject cameraZoomedIn; //CameraZoomedIn = "CameraFollowPlayer"
private bool cameraSwitch = false; //Boolean to determine which camera is active
private void Update()
{
if (Input.GetKeyDown("Q"))
{
cameraSwitch = !cameraSwitch;
}
if (cameraSwitch == true)
{
cameraZoomedOut.SetActive(false);
cameraZoomedIn.SetActive(true);
}
if (cameraSwitch == false)
{
cameraZoomedOut.SetActive(true);
cameraZoomedIn.SetActive(false);
}
}
}
|
c3a7890e49c9a0ce66aa4711c64fb429d92d806a
|
C#
|
brianhill-bfs/DefaultDocumentation
|
/source/DefaultDocumentation/Model/NonMember/ReturnItem.cs
| 2.5625
| 3
|
using System;
using System.Xml.Linq;
using DefaultDocumentation.Helper;
using DefaultDocumentation.Model.Base;
using Mono.Cecil;
namespace DefaultDocumentation.Model.NonMember
{
internal sealed class ReturnItem : AItem
{
public override string Header => "Returns";
public TypeReference Type { get; }
public bool IsVoid => Type.FullName == "System.Void";
public ReturnItem(AMemberItem parent, XElement element)
: base(parent, element)
{
Type = parent switch
{
MethodItem methodItem => methodItem.Method.ReturnType,
OperatorItem operatorItem => operatorItem.Method.ReturnType,
_ => throw new NotSupportedException()
};
}
public override void Write(Converter converter, DocWriter writer)
{
writer.WriteLine($"### {Header}");
if (!IsVoid)
{
string returnTypeName = Type.FullName.Replace('/', '.');
converter.Items.TryGetValue($"{TypeItem.Id}{returnTypeName}", out AMemberItem returnTypeItem);
writer.WriteLine(returnTypeItem?.AsLink() ?? returnTypeName.AsDotNetApiLink());
}
converter.WriteSummary(writer, this);
}
}
}
|
b1538a6c9b9f615fc78d8794d81bd8f8f098b405
|
C#
|
GalaDe/CodeFights
|
/Data_Structures_Tranning/HashTables/SwapLexOrderExercise_1.cs
| 3.640625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data_Structures_Tranning.HashTables
{
public class SwapLexOrderExercise_1
{
public static string swapLexOrder(string str, int[][] pairs)
{
// lexicographically largest string:
// a) We only need to look on the order of pair letters
// b) They should be decreasing order
//P.S: This solution is not correct!!!
List<char[]> strList = new List<char[]>();
if (str.Length == 1)
return str;
//string str = "abdc"
for (int i = 0; i < pairs.Length; i++)
{
var arrayStr = str.ToCharArray();
for (int j = 0; j < 1; j++)
{
char temp = arrayStr[(pairs[i][j]) - 1];
arrayStr[(pairs[i][j]) - 1] = arrayStr[(pairs[i][++j]) - 1];
arrayStr[(pairs[i][j]) - 1] = temp;
}
strList.Add(arrayStr);
}
int largerest_char_pos = 0;
string result = "";
for (int i = 0; i < strList.Count - 1; i++)
{
for (int j = i + 1; j < strList[i].Length - 1; j++)
{
if (strList[i][j] > strList[j][i])
{
result += strList[i][largerest_char_pos];
}
}
i = largerest_char_pos + 1;
}
return null;
}
}
}
|
c993088d54eca013186999769afb3a026557eaaa
|
C#
|
KiroKirilov/SoftUni
|
/ProfessionalModules/C#Fundamentals/C#OOPAdvanced/Generics/CustomListIterator/CustomList.cs
| 3.578125
| 4
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class CustomList<T> : IEnumerable<T>
where T:IComparable<T>
{
private List<T> items;
public CustomList()
{
this.items = new List<T>();
}
public void Add(T element)
{
this.items.Add(element);
}
public T Remove(int index)
{
var item = this.items[index];
this.items.RemoveAt(index);
return item;
}
public bool Contains(T element)
{
return this.items.Contains(element);
}
public void Swap(int index1, int index2)
{
var tempItem = this.items[index1];
this.items[index1] = this.items[index2];
this.items[index2] = tempItem;
}
public int CountGreaterThan(T element)
{
return this.items.Count(i => i.CompareTo(element) > 0);
}
public T Max()
{
return this.items.Max();
}
public T Min()
{
return this.items.Min();
}
public void Sort()
{
this.items = this.items.OrderBy(i => i).ToList();
}
public override string ToString()
{
return string.Join(Environment.NewLine, this.items);
}
public IEnumerator<T> GetEnumerator()
{
return items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
|
cba422df13fd447256dcee1806a843267d4c6668
|
C#
|
L30n4rd031/SilveR
|
/SilveR/Controllers/UserOptionsController.cs
| 2.515625
| 3
|
using Microsoft.AspNetCore.Mvc;
using SilveR.Models;
using System;
using System.Threading.Tasks;
namespace SilveR.Controllers
{
public class UserOptionsController : Controller
{
private readonly ISilveRRepository repository;
public UserOptionsController(ISilveRRepository repository)
{
this.repository = repository;
}
[HttpGet]
public async Task<IActionResult> Index()
{
UserOption options = await repository.GetUserOptions();
return View(options);
}
[HttpPost]
public async Task<IActionResult> UpdateUserOptions(UserOption userOption, string submitButtonValue)
{
if (submitButtonValue == "save")
{
await repository.UpdateUserOptions(userOption);
return RedirectToAction("Index", "Home");
}
else if (submitButtonValue == "reset")
{
await repository.ResetUserOptions(userOption); //remove the useroptions
return RedirectToAction ("Index");
}
else
throw new ArgumentException("submitButtonValue is not valid!");
}
}
}
|
f1f86ccd201178a167acf228aade4eb158116e81
|
C#
|
UdiRahav/CSharpOOP
|
/MainMenu/Ex04.Menus.Delegates/AbstrectItem.cs
| 2.703125
| 3
|
namespace Ex04.Menus.Delegates
{
public abstract class AbstrectItem
{
protected readonly string r_ItemName;
public AbstrectItem(string i_ItemName)
{
this.r_ItemName = i_ItemName;
}
public string ItemName
{
get { return this.r_ItemName; }
}
public abstract void ActiveItem();
}
}
|
ab3b1e7ebb1f3ff1d56443bb14c95728e6e24584
|
C#
|
russjudge/ArtemisMissionEditor
|
/ArtemisMissionEditor/Utility Classes/DictionaryPropertyGridAdapter.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections;
namespace ArtemisMissionEditor
{
public sealed class DictionaryPropertyDescriptor : PropertyDescriptor
{
//PropertyDescriptor provides 3 constructors. We want the one that takes a string and an array of attributes:
IDictionary _dictionary;
object _key;
internal DictionaryPropertyDescriptor(IDictionary d, object key)
: base(key.ToString(), null)
{
_dictionary = d;
_key = key;
}
//The attributes are used by PropertyGrid to organise the properties into categories, to display help text and so on.
//We don't bother with any of that at the moment, so we simply pass null.
//The first interesting member is the PropertyType property. We just get the object out of the dictionary and ask it:
public override Type PropertyType { get { if (_dictionary[_key] == null) return typeof(object); return _dictionary[_key].GetType(); } }
//If you knew that all of your values were strings, for example, you could just return typeof(string).
//Then we implement SetValue and GetValue:
//The component parameter passed to these two methods is whatever value was returned from ICustomTypeDescriptor.GetPropertyOwner.
//If it weren't for the fact that we need the dictionary object in PropertyType, we could avoid using the _dictionary member, and just grab it using this mechanism.
public override void SetValue(object component, object value) { _dictionary[_key] = value; }
public override object GetValue(object component) { return _dictionary[_key]; }
#region Boring Stuff
public override bool IsReadOnly { get { return false; } }
public override Type ComponentType { get { return null; } }
public override bool CanResetValue(object component) { return false; }
public override void ResetValue(object component) { }
public override bool ShouldSerializeValue(object component) { return false; }
#endregion
}
public sealed class DictionaryPropertyGridAdapter : ICustomTypeDescriptor
{
IDictionary _dictionary;
#region Boring Stuff
public DictionaryPropertyGridAdapter(IDictionary d) { _dictionary = d; }
public string GetComponentName() { return TypeDescriptor.GetComponentName(this, true); }
public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); }
public string GetClassName() { return TypeDescriptor.GetClassName(this, true); }
public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); }
EventDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); }
public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); }
public object GetPropertyOwner(PropertyDescriptor pd) { return _dictionary; }
public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); }
public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); }
public PropertyDescriptor GetDefaultProperty() { return null; }
#endregion
PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor)this).GetProperties(new Attribute[0]);
}
//We iterate over the IDictionary, creating a property descriptor for each entry:
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
ArrayList properties = new ArrayList();
foreach (DictionaryEntry e in _dictionary)
{
properties.Add(new DictionaryPropertyDescriptor(_dictionary, e.Key));
}
PropertyDescriptor[] props =
(PropertyDescriptor[])properties.ToArray(typeof(PropertyDescriptor));
return new PropertyDescriptorCollection(props);
}
}
}
|
e2f3e61ccd799f63ee9bf00fee9eab1b5fba9037
|
C#
|
zxh19890103/z-commerce
|
/Nt.BLL/SecurityService.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Nt.BLL
{
public class SecurityService
{
/// <summary>
/// 获取加密的字符串
/// </summary>
/// <param name="s">输入值</param>
/// <returns></returns>
public string Md5(string s)
{
//获取加密服务
System.Security.Cryptography.MD5CryptoServiceProvider md5CSP
= new System.Security.Cryptography.MD5CryptoServiceProvider();
//获取要加密的字段,并转化为Byte[]数组
byte[] testEncrypt = System.Text.Encoding.Unicode.GetBytes(s);
//加密Byte[]数组
byte[] resultEncrypt = md5CSP.ComputeHash(testEncrypt);
//将加密后的数组转化为字段(普通加密)
//string testResult = System.Text.Encoding.Unicode.GetString(resultEncrypt);
//作为密码方式加密
string EncryptPWD = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "MD5");
return EncryptPWD;
}
/// <summary>
/// verify if Encrypted s equals to md5
/// </summary>
/// <param name="s">pwd</param>
/// <param name="md5">Encrypted pwd</param>
/// <returns></returns>
public bool VerifyMd5(string s, string md5)
{
string md5OfS = Md5(s);
// Create a StringComparer an comare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(md5OfS, md5))
{
return true;
}
else
{
return false;
}
}
}
}
|
fce4871633de3714e7d2832f6b7e6f216947aaf1
|
C#
|
florenciagonzalezteti96/tp_laboratorio_2
|
/Gonzalez.Teti.Florencia.2A.TP3/Archivos/IArchivo.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Archivos
{
public interface IArchivo<T>
{
/// <summary>
/// Esta funcion permite guardar un archivo con datos
/// </summary>
/// <param name="archivo">El path del archivo</param>
/// <param name="datos">Los datos que se guardaran en el archivo</param>
/// <returns>Retorna true si logro guardar, caso contrario retorna false</returns>
bool Guardar(string archivo, T datos);
/// <summary>
/// Esta funcion permite leer un archivo con datos guardados
/// </summary>
/// <param name="archivo">El path del archivo</param>
/// <param name="datos">El objeto en el cual se guardaran los datos leidos del archivo</param>
/// <returns>Retorna true si logro leer, caso contrario retorna false</returns>
bool Leer(string archivo, out T datos);
}
}
|
167245b5d3e9b67ad6b63935fedb6f8659eeafd5
|
C#
|
cmoinard/AppTrainTrain
|
/src/Shared/Shared.Core/NonEmptyList.cs
| 3.21875
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Shared.Core.Extensions;
namespace Shared.Core
{
public class NonEmptyList<T> : IReadOnlyList<T>
{
private readonly List<T> _internalList;
public NonEmptyList(T value, params T[] values)
{
_internalList =
new [] {value}
.Concat(values)
.ToList();
}
public NonEmptyList(IEnumerable<T> values)
{
var valueList = values.ToList();
if (valueList.None())
throw new ArgumentException("Cannot be empty");
_internalList = valueList.ToList();
}
public IEnumerator<T> GetEnumerator() => _internalList.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public int Count => _internalList.Count;
public T this[int index] => _internalList[index];
}
}
|
5eea05d8c4c2c7ac8048659449b4adb22a3227d0
|
C#
|
shendongnian/download4
|
/latest_version_download2/106841-20660802-53966068-2.cs
| 2.734375
| 3
|
flatList
.GroupBy(i => i.FatherId)
.Select(g => new Father()
{
id = g.Key,
propertyF,
children =
g
.Select(c => new Child()
{
id = ChildrenId,
prop1,
prop2
})
.ToList()
})
|
95bd382a1f747bee8a71347526be95937e3157d0
|
C#
|
Kesco-m/Kesco.Lib.Win.Data
|
/Options/OptionCollection.cs
| 3
| 3
|
using System;
using System.Collections;
namespace Kesco.Lib.Win.Data.Options
{
public class OptionCollection : CollectionBase
{
private static Type t = typeof (Option);
public Option this[int index]
{
get { return ((Option) List[index]); }
set { List[index] = value; }
}
public int Add(Option value)
{
return (List.Add(value));
}
public int IndexOf(Option value)
{
return (List.IndexOf(value));
}
public void Insert(int index, Option value)
{
List.Insert(index, value);
}
public void Remove(Option value)
{
List.Remove(value);
}
/// <summary>
/// Checks whether specific value can be found in options
/// </summary>
/// <returns>If value is not of type Int16, this will return false</returns>
public bool Contains(Option value)
{
return (List.Contains(value));
}
protected override void OnInsert(int index, Object value)
{
if (!(value.GetType() == t || value.GetType().IsSubclassOf(t)))
throw new ArgumentException("value must inherit from type " + t.FullName, "value");
}
protected override void OnRemove(int index, Object value)
{
if (!(value.GetType() == t || value.GetType().IsSubclassOf(t)))
throw new ArgumentException("value must inherit from type " + t.FullName, "value");
}
protected override void OnSet(int index, Object oldValue, Object newValue)
{
if (!(newValue.GetType() == t || newValue.GetType().IsSubclassOf(t)))
throw new ArgumentException("newValue must inherit from type " + t.FullName, "newValue");
}
protected override void OnValidate(Object value)
{
if (!(value.GetType() == t || value.GetType().IsSubclassOf(t)))
throw new ArgumentException("value must inherit from type " + t.FullName);
}
}
}
|
9d461d025187fde202875cd541f8ded2f2f28313
|
C#
|
ctzuchiang/DataStructure
|
/DataStructure/Math/MyMath.cs
| 3.828125
| 4
|
using System.Collections.Generic;
using System.Linq;
namespace DataStructure.Math
{
public class MyMath
{
public int GCD(int a, int b)
{
while ((a %= b) != 0 && (b %= a) != 0) ;
return System.Math.Max(a, b);
}
public int GCD1(int a, int b)
{
var _a = System.Math.Max(a, b);
var _b = System.Math.Min(a, b);
while (_b != 0)
{
var tmp = _b;
_b = _a % _b;
_a = tmp;
}
return _a;
}
public int GCD_Recursive(int a, int b)
{
if ((a %= b) != 0 && (b %= a) != 0)
return GCD_Recursive(a, b);
return System.Math.Max(a, b);
}
public int GCD1_Recursive(int a, int b)
{
if (b > a)
return GCD1_Recursive(b, a);
var r = a % b;
if (r != 0)
return GCD1_Recursive(b, r);
return b;
}
public int[] Prime(int n)
{
if (n < 2)
return new int[] { };
int[] isPrime = new int[n+1];
for (var i = 2; i <= System.Math.Sqrt(n); i++)
{
if (isPrime[i] == 0)
{
for (var j = i * 2; j <= n; j += i)
{
isPrime[j] = 1;
}
}
}
var result = new List<int>();
for (int i = 2; i <= n; i++)
{
if (isPrime[i] == 0)
result.Add(i);
}
return result.ToArray();
}
public IEnumerable<int> PrimeList(int n)
{
int[] list = new int[n + 1];
for (int i = 2; i <= n; i++)
{
list[i] = i;
}
for (int i=2;i<System.Math.Sqrt(n);i++)
{
if (list[i] != 0)
{
for (int y=i*2;y<=n;y+=i)
{
list[y] = 0;
}
}
}
return list.Where(t => t != 0).ToArray();
}
}
}
|
d9127f632161a44fba397525e33d2f8b20b35946
|
C#
|
Plenituz/NodeGame
|
/Assets/VisualEditor/BackEnd/Impl/Nodes/NegateNode.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using VisualEditor.Visuals;
namespace VisualEditor.BackEnd.Impl
{
[Serializable]
public class NegateNode : Node
{
MultiDataInput inp;
AnyTypeOutput outp;
public override void BeginSetup()
{
inp = new MultiDataInput(this, new List<Type>(new Type[] { typeof(Vector2), typeof(Vector3), typeof(float) }));
outp = new AnyTypeOutput(this, typeof(object));
inputs.Add(inp);
}
public override Type GetAssociatedVisualClass()
{
return typeof(NegateNodeVisual);
}
public override string GetDocumentation()
{
return "Multiplies the input by -1 (minus one)";
}
public override Type[] GetPossibleInputTypes()
{
return new Type[] { typeof(Vector2), typeof(Vector3), typeof(float) };
}
public override Type[] GetPossibleOutputTypes()
{
return new Type[] { typeof(Vector2), typeof(Vector3), typeof(float) };
}
public override string[] GetSearchableNames()
{
return new string[] { "Negate", "*-1" };
}
protected override void DoReset()
{
}
protected override void ProcessInputs(out bool processAllOutputs)
{
if (inp.GetDataType() == typeof(Vector2))
{
//vec2
Vector2 vec1 = (Vector2)inp.GetData();
outp.SetData(Vec2Operation(vec1));
}
else if (inp.GetDataType() == typeof(Vector3))
{
//vec3
Vector3 vec1 = (Vector3)inp.GetData();
outp.SetData(Vec3Operation(vec1));
}
else if (inp.GetDataType() == typeof(float))
{
//float
float f1 = (float)inp.GetData();
outp.SetData(FloatOperation(f1));
}
else
{
Debug.LogError("type fucked in the butt, this shouldn't happen (NegateNode)");
}
processAllOutputs = true;
}
private object FloatOperation(float f1)
{
return f1 * -1f;
}
private object Vec3Operation(Vector3 vec1)
{
return vec1 * -1f;
}
private object Vec2Operation(Vector2 vec1)
{
return vec1 * -1f;
}
internal override void PartialSetup()
{
if(inp.GetDataType() != null)
{
outp.SetDataType(inp.GetDataType());
if(outputs.Count == 0)
outputs.Add(outp);
}
if (inp.GetDataType() == null)
outputs.Clear();
}
}
}
|
66ec2df786d83b450aab4ad9ced091cb4bbfe5da
|
C#
|
htutich/3dlearn
|
/Assets/Scripts/Gun/EnemyTurretBulletController.cs
| 2.53125
| 3
|
using UnityEngine;
namespace learn3d
{
public class EnemyTurretBulletController : MonoBehaviour
{
#region Fields
private Rigidbody _myRigidbody;
private float _speed = 60.0f;
private float _lifeTime = 5.0f;
private float _minDamage = 1.0f;
private float _maxDamage = 10.0f;
private float _damageToGive;
#endregion
#region UnityMethods
private void Start()
{
_myRigidbody = GetComponent<Rigidbody>();
_myRigidbody.AddForce(transform.forward * _speed, ForceMode.Impulse);
_damageToGive = Random.Range(_minDamage, _maxDamage);
Destroy(gameObject, _lifeTime);
}
private void OnCollisionEnter(Collision other)
{
var playerHealthManager = other.gameObject.GetComponent<PlayerHealthManager>();
playerHealthManager?.HurtPlayer(_damageToGive);
var dorHealthManager = other.gameObject.GetComponent<DoorHealthManager>();
dorHealthManager?.HurtEnemy(_damageToGive);
Destroy(gameObject);
}
#endregion
}
}
|
4b87edb7e53e075f59b9300ba95dfba2f2769151
|
C#
|
gsilvasts/LocalizaLab.CadastroDeSeries
|
/LocalizaLabSeries/Entities/Serie.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LocalizaLabSeries.Entities
{
public class Serie : EntidadeBase
{
public Serie(int id, string titulo, string descricao, int ano, bool excluido, GeneroEnum genero)
{
Id = id;
Titulo = titulo;
Descricao = descricao;
Ano = ano;
Excluido = excluido;
Genero = genero;
}
public string Titulo { get; private set; }
public string Descricao { get; private set; }
public int Ano { get; private set; }
public bool Excluido { get; private set; }
public GeneroEnum Genero { get; private set; }
public void Excluir()
{
Excluido = true;
}
public void Atualizar(string titulo, string descricao, int ano, GeneroEnum genero)
{
Titulo = titulo;
Descricao = descricao;
Ano = ano;
Genero = genero;
}
}
}
|
29487254aa88175f0d1e5a8f23776effaad25dfe
|
C#
|
Nikolamv95/SoftUni-Software-Engineering
|
/CSharp-OOP/12.DesignPatterns/1.Lecture/CreationalPatterns/DecoratorPattern/Models/PaymentSystemDecorator.cs
| 3.640625
| 4
|
using System;
namespace DecoratorPattern
{
public class PaymentSystemDecorator : IPaymentSystem
{
private IPaymentSystem paymentSystem;
public PaymentSystemDecorator(IPaymentSystem system)
{
this.paymentSystem = system;
}
public void LoanMoney(string from, string to, int ammount)
{
Console.WriteLine("We can make whatever we want in this LoanMoney Method");
paymentSystem.LoanMoney(from, to, ammount);
}
public void PayMoney(string from, string to, int ammount)
{
Console.WriteLine("We can make whatever we want in this PaidMoney Method");
paymentSystem.PayMoney(from, to, ammount);
}
}
}
|
fb1f08f17272067042ea59e336e64156cd6eecbc
|
C#
|
ZeXVex/OnlineRetailer_Partial-master
|
/OrderApi/Data/DbInitializer.cs
| 2.734375
| 3
|
using System.Collections.Generic;
using System.Linq;
using OrderApi.Models;
using System;
namespace OrderApi.Data
{
public class DbInitializer : IDbInitializer
{
// This method will create and seed the database.
public void Initialize(OrderApiContext context)
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
// Look for any Products
if (context.Orders.Any())
{
return; // DB has been seeded
}
List<ProductDTO> products = new List<ProductDTO>
{
new ProductDTO { OrderId = 1, ProductId = 1, PriceForAll = 4, Quantity = 34}
};
List<Order> orders = new List<Order>
{
new Order { Date = DateTime.Today, Products = products},
new Order {Date = DateTime.Today}
};
context.Orders.AddRange(orders);
context.SaveChanges();
}
}
}
|
bb0e4c57d4a4f3b0963e89dde4b79dd7a0cba64d
|
C#
|
rafamartinsbr/.net-core
|
/BookModule.Web.Api/Controllers/BooksController.cs
| 2.625
| 3
|
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BookModule.Web.Api.Controllers
{
[Route("api/[controller]")]
public class BooksController : Controller
{
private readonly IBookQueries _bookQueries;
private readonly IBookCommands _bookCommands;
public BooksController(IBookQueries bookQueries, IBookCommands bookCommands)
{
_bookQueries = bookQueries;
_bookCommands = bookCommands;
}
// GET api/books
[HttpGet]
public async Task<IEnumerable<Book>> Get()
{
var bookCollection = await _bookQueries.GetBooksAsync();
return bookCollection;
}
// GET api/books/5
[HttpGet("{id}")]
public async Task<Book> Get(string instrument)
{
var book = await _bookQueries.GetBookAsync(instrument);
return book;
}
}
}
|
27a4a03e7d368b46db535ca6202b1b1da6b12fb8
|
C#
|
Maxwolf/WolfCurses.Example
|
/src/Program.cs
| 3.09375
| 3
|
// Created by Ron 'Maxwolf' McDowell (ron.mcdowell@gmail.com)
// Timestamp 01/07/2016@7:10 PM
using System;
using System.Threading;
namespace WolfCurses.Example
{
/// <summary>
/// Example console application using wolf curses library to power interaction.
/// </summary>
internal static class Program
{
/// <summary>
/// Main entry point for the application being startup.
/// </summary>
private static void Main()
{
// Create console with title, no cursor, make CTRL-C act as input.
Console.Title = "WolfCurses Console Application";
Console.WriteLine("Starting...");
Console.CursorVisible = false;
Console.CancelKeyPress += Console_CancelKeyPress;
// Entry point for the entire simulation.
ConsoleSimulationApp.Create();
// Hook event to know when screen buffer wants to redraw the entire console screen.
ConsoleSimulationApp.Instance.SceneGraph.ScreenBufferDirtyEvent += Simulation_ScreenBufferDirtyEvent;
// Prevent console session from closing.
while (ConsoleSimulationApp.Instance != null)
{
// Simulation takes any numbers of pulses to determine seconds elapsed.
ConsoleSimulationApp.Instance.OnTick(true);
// Check if a key is being pressed, without blocking thread.
if (Console.KeyAvailable)
{
// GetModule the key that was pressed, without printing it to console.
var key = Console.ReadKey(true);
// If enter is pressed, pass whatever we have to simulation.
// ReSharper disable once SwitchStatementMissingSomeCases
switch (key.Key)
{
case ConsoleKey.Enter:
ConsoleSimulationApp.Instance.InputManager.SendInputBufferAsCommand();
break;
case ConsoleKey.Backspace:
ConsoleSimulationApp.Instance.InputManager.RemoveLastCharOfInputBuffer();
break;
default:
ConsoleSimulationApp.Instance.InputManager.AddCharToInputBuffer(key.KeyChar);
break;
}
}
// Do not consume all of the CPU, allow other messages to occur.
Thread.Sleep(1);
}
// Make user press any key to close out the simulation completely, this way they know it closed without error.
Console.Clear();
Console.WriteLine("Goodbye!");
Console.WriteLine("Press ANY KEY to close this window...");
Console.ReadKey();
}
/// <summary>Write all text from objects to screen.</summary>
/// <param name="tuiContent">The text user interface content.</param>
private static void Simulation_ScreenBufferDirtyEvent(string tuiContent)
{
var tuiContentSplit = tuiContent.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
for (var index = 0; index < Console.WindowHeight - 1; index++)
{
Console.CursorLeft = 0;
Console.SetCursorPosition(0, index);
var emptyStringData = new string(' ', Console.WindowWidth);
if (tuiContentSplit.Length > index)
{
emptyStringData = tuiContentSplit[index].PadRight(Console.WindowWidth);
}
Console.Write(emptyStringData);
}
}
/// <summary>
/// Fired when the user presses CTRL-C on their keyboard, this is only relevant to operating system tick and this view
/// of simulation. If moved into another framework like game engine this statement would be removed and just destroy
/// the simulation when the engine is destroyed using its overrides.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
// Destroy the simulation.
ConsoleSimulationApp.Instance.Destroy();
// Stop the operating system from killing the entire process.
e.Cancel = true;
}
/// <summary>
/// Forces the current simulation app to close and return control to underlying operating system.
/// </summary>
public static void Destroy()
{
ConsoleSimulationApp.Instance.Destroy();
}
}
}
|
95246aff04ca0a5c9534a87e6921cea6ed96b3cc
|
C#
|
OKYAKUSAN/Testweb
|
/BLL/TeamsGroup.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TestWeb.DAL;
using TestWeb.Model;
namespace TestWeb.BLL
{
public class TeamsGroup
{
private List<Team> _teamList = new List<Team>();
public TeamsGroup()
{
TeamListXml teamListData = new TeamListXml();
_teamList = teamListData.GetTeamList();
}
public List<Team> GetGroup(string words)
{
List<Team> _resultList = new List<Team>();
foreach (Team tempTeam in _teamList)
{
if (words == "西部联盟" || words == "东部联盟")
{
if (tempTeam.Conference == words) _resultList.Add(tempTeam);
}
else
{
if (tempTeam.Zone == words) _resultList.Add(tempTeam);
}
}
return _resultList;
}
public Team GetTeam(string words)
{
Team _resultTeam = new Team();
foreach (Team _tempTeam in _teamList)
{
if (_tempTeam.EName == words || _tempTeam.CName == words) _resultTeam = _tempTeam;
}
return _resultTeam;
}
}
}
|
1e56c62623f9d20fe6579df6c7745919dedd31f1
|
C#
|
Trukhaibit/Ch09Ex1NFLTeams
|
/NFLTeams/Models/TeamListViewModel.cs
| 2.671875
| 3
|
using System.Collections.Generic;
namespace NFLTeams.Models
{
public class TeamListViewModel : TeamViewModel
{
public List<Team> Teams { get; set; }
public string UserName { get; set; }
// use full properties for Conferences and Divisions
// so can add 'All' item at beginning
private List<Conference> conferences;
public List<Conference> Conferences {
get => conferences;
set {
conferences = new List<Conference> {
new Conference { ConferenceID = "all", Name = "All" }
};
conferences.AddRange(value);
}
}
private List<Division> divisions;
public List<Division> Divisions {
get => divisions;
set {
divisions = new List<Division> {
new Division { DivisionID = "all", Name = "All" }
};
divisions.AddRange(value);
}
}
// methods to help view determine active link
public string CheckActiveConf(string c) =>
c.ToLower() == ActiveConf.ToLower() ? "active" : "";
public string CheckActiveDiv(string d) =>
d.ToLower() == ActiveDiv.ToLower() ? "active" : "";
}
}
|
714925011cad025b6175a0650285bc502703996b
|
C#
|
Chips100/Sunflower
|
/Sunflower.Data/EntityRepositoryFactory.cs
| 3.234375
| 3
|
using Sunflower.Data.Contracts;
using System;
using System.Threading.Tasks;
namespace Sunflower.Data
{
/// <summary>
/// Factory for repositories to make changes to the persistent storage.
/// </summary>
public sealed class EntityRepositoryFactory : IEntityRepositoryFactory
{
/// <summary>
/// Provides a repository to make changes to the persistent storage.
/// </summary>
/// <param name="action">Action to perform changes with the repository.</param>
/// <returns>A task that will complete when the changes have been applied.</returns>
public async Task Use(Action<IEntityRepository> action)
{
using (var context = CreateContext())
{
action(new EntityRepository(context));
await context.SaveChangesAsync();
}
}
/// <summary>
/// Provides a repository to make changes to the persistent storage.
/// </summary>
/// <param name="action">Asynchronous action to perform changes with the repository.</param>
/// <returns>A task that will complete when the changes have been applied.</returns>
public async Task Use(Func<IEntityRepository, Task> asyncAction)
{
using (var context = CreateContext())
{
await asyncAction(new EntityRepository(context));
await context.SaveChangesAsync();
}
}
/// <summary>
/// Creates an EntityFramework context to access the persistent storage.
/// </summary>
/// <returns>An EntityFramework context.</returns>
private SunflowerDbContext CreateContext()
{
return new SunflowerDbContext();
}
}
}
|
5a661d4a33961c3c4b65e18d26f440ca38fb9410
|
C#
|
tenevdev/academy-csharp
|
/csharp-meeting-1/ConsoleInputOutput/2. PrintCirclePerimeterAndArea/PrintCirclePerimeterAndArea.cs
| 3.78125
| 4
|
using System;
class PrintCirclePerimeterAndArea
{
static void Main(string[] args)
{
double radius = double.Parse(Console.ReadLine());
double area = Math.PI * radius * radius;
double perimeter = 2 * Math.PI * radius;
Console.WriteLine("The circle's area is: {0}", area);
Console.WriteLine("The circle's perimeter is: {0}", perimeter);
}
}
|
0a614d22db4ea0a8935408b20f717b2b9474fa29
|
C#
|
Doombull/DiceRoller
|
/DiceRoller/Warmachine/CataclysmIrusk.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DiceRoller
{
class CataclysmIrusk : IRunnable
{
protected int IruskHealth = 17;
protected int IruskBaseArmour = 15;
protected int IruskBaseDefense = 15;
protected int CataclysmStr = 15;
/// <summary>
/// This runs the simulation
/// </summary>
/// <returns>True if Irusk dies</returns>
public bool Run(out int damage)
{
damage = 0;
//damage
damage += CataclysmStr - IruskBaseArmour + Dice.Roll(3);
damage += CataclysmStr - IruskBaseArmour + Dice.Roll(3);
//tough
if (damage >= IruskHealth && Dice.Roll(1) < 4)
return true;
return false;
}
}
}
|
b36d7cbb1956e2edb0adeb0953b63b56fb2a4337
|
C#
|
gitter-badger/logmagic
|
/src/LogMagic.Test/FormattingTest.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace LogMagic.Test
{
[TestFixture]
public class FormattingTest
{
private TestWriter _writer;
private ILog _log = L.G();
[SetUp]
public void SetUp()
{
_writer = new TestWriter();
L.Config.ClearWriters();
L.Config
.WriteTo.Trace()
.WriteTo.Custom(_writer)
.EnrichWith.ThreadId()
.EnrichWith.Constant("node", "test");
}
[SetUp]
public void TearDown()
{
L.Shutdown();
}
private string Message => _writer.Message;
private LogEvent Event => _writer.Event;
[Test]
public void Mixed_IntegerAndString_Formats()
{
_log.D("one {0} string {1}", 1, "s");
L.Flush();
Assert.AreEqual("one 1 string s", Message);
}
[Test]
[Ignore("list formatting is unstable")]
public void IEnumerable_SmallList_Formats()
{
var lst = new List<string> {"one", "two", "three" };
_log.D("the {0} format", lst);
L.Flush();
Assert.AreEqual("the [3 el: {one}, {two}, {three}] format", Message);
}
[Test]
[Ignore("list formatting is unstable")]
public void IEnumerable_LargeList_Formats()
{
var lst = new List<string> { "one", "two", "three", "four", "five", "six", "seven" };
_log.D("the {0} format", lst);
L.Flush();
Assert.AreEqual("the [7 el: {one}, {two}, {three}, {four}, {five} +2 more] format", Message);
}
[Test]
public void String_NoTransform_Formats()
{
_log.D("the {0}", "string");
L.Flush();
Assert.AreEqual("the string", Message);
}
[Test]
public void SourceName_Reflected_ThisClass()
{
_log.D("testing source");
L.Flush();
Assert.AreEqual("LogMagic.Test.FormattingTest", Event.SourceName);
}
[Test]
public void Structured_NamedString_Formats()
{
_log.D("the {Count} kettles", 5);
L.Flush();
Assert.AreEqual("the 5 kettles", Message);
Assert.AreEqual(5, (int)Event.GetProperty("Count"));
}
[Test]
public void Structured_Mixed_Formats()
{
_log.D("{0} kettles and {three:D2} lamps{2}", 5, 3, "...");
L.Flush();
Assert.AreEqual("5 kettles and 03 lamps...", Message);
Assert.AreEqual(3, Event.GetProperty("three"));
}
}
}
|
dc9e1aca1ce1c707b3e196ebf39a96a25e699def
|
C#
|
jchhh912/WebSocketDemo
|
/WebSocketDemo/Sockets/SocketsMiddleware.cs
| 2.84375
| 3
|
using Microsoft.AspNetCore.Http;
using System;
using System.Buffers;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketDemo
{
public class SocketsMiddleware
{
private SocketsHandler _Handler { get; }
//如果不是websocket请求
private readonly RequestDelegate _next;
public SocketsMiddleware(RequestDelegate next, SocketsHandler handle)
{
_Handler = handle;
_next = next;
}
/// <summary>
/// 接收连接-----接收数据长度如果超过设置的buffer 程序会出错
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task InvokeAsync(HttpContext context)
{
if (context.WebSockets.IsWebSocketRequest)
{
//转换为ws连接
var socket = await context.WebSockets.AcceptWebSocketAsync();
await _Handler.OnConnected(socket);
//接收消息 使用默认小缓存池 需要合理设置,太小websocket接收缓存不足时,会自行断开后,过大会造成浪费大量内存
//var buffer = new byte[1024 * 4];
//var offset = 0;
//缓存池
var samePool = ArrayPool<byte>.Shared;
int newSize = 0;
// var newBuffer = samePool.Rent(buffer.Length);
var newBuffer = samePool.Rent(1024 * 4);
//缓存池是否溢出
var free = 1024*4;
StringBuilder msgString = new StringBuilder();
//监听数据
while (socket.State == WebSocketState.Open)
{
//监听消息 每次传输的大小为4096
WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(newBuffer), CancellationToken.None);
//初始化
free -= result.Count;
//当缓存池接收没问题时 直接发送消息
if (result.EndOfMessage && free > 0)
{
switch (result.MessageType)
{
case WebSocketMessageType.Text:
await _Handler.Receive(socket, result, newBuffer);
free = newBuffer.Length;
break;
case WebSocketMessageType.Binary:
break;
case WebSocketMessageType.Close:
await _Handler.OnDisconnected(socket);
break;
default:
throw new AbandonedMutexException();
}
};
//当缓存池不足时,对缓存池进行扩容
if (free <= 0)
{
// 每次消息的长度总和,超过将不发送
newSize += newBuffer.Length;
//超出缓存池最大限制 8k-2.5mb 之间 计算方法https://stackoverflow.com/questions/2811006/what-is-a-good-buffer-size-for-socket-programming
if (newSize > 15000 && result.EndOfMessage)
{
//用户自己检查问题
await _Handler.SendMessage(socket, "数据传输失败!请检查网络!");
//避免浪费
msgString.Clear();
//将使用的放回共享缓存池
samePool.Return(newBuffer,true);
newSize = 0;
free =newBuffer.Length;
continue;
}
//深拷贝 buffer效率更高 但要注意计算机字节序 可能会导致数据没有拷贝完整 https://blog.csdn.net/qq826364410/article/details/79729727
// Array.Copy(buffer, 0, newBuffer, 0, buffer.Length);
Buffer.BlockCopy(newBuffer, 0,newBuffer,0,newBuffer.Length);
// buffer = newBuffer;
//将接收到的数据一块一块切割保存
msgString.Append(Encoding.UTF8.GetString(newBuffer, 0, result.Count));
//是否完整接收数据
if (result.EndOfMessage && result.MessageType == WebSocketMessageType.Text)
{
await _Handler.Receive(socket, msgString.ToString());
//将使用的放回共享缓存池
samePool.Return(newBuffer, true);
msgString.Clear();
newSize = 0;
//重置
free = newBuffer.Length;
continue;
};
}
}
}
else
{
await _next(context);
}
}
}
}
|
3b0a4eb4ea0d6d514d117c8f00c9ecf8bd17119b
|
C#
|
hankshuangs/Visual-C
|
/BookExercise C#/CH10/DirectoryGetDirectories_ex/DirectoryGetDirectories_ex/Form1.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO; //新增此命名空間
namespace DirectoryGetDirectories_ex
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnListDirs_Click(object sender, EventArgs e)
{
string DirPath = @"C:\";
string msg = "", dirName = "";
if (Directory.Exists(DirPath))
{
msg = msg + "目錄:[" + DirPath + "]有找到!\n";
msg = msg + "子目錄清單如下:\n";
var files = Directory.GetDirectories(DirPath);
foreach (var obj in files)
{
dirName = obj.Substring(obj.LastIndexOf("\\") + 1);
msg = msg + dirName + "\n";
}
MessageBox.Show(msg, "Directory.GetDirectories()方法");
rtxtListDirs.Text = msg;
}
else
{
msg = msg + "目錄:[" + DirPath + "]不存在!\n";
msg = msg + "沒有任何子目錄!!";
MessageBox.Show(msg, "Directory.GetDirectories()方法");
}
}
}
}
|
6ac95df6c03fcc03d0803d5c6ca3d23755a4d3cb
|
C#
|
sarn3792/API_ControlEntregas_Magnetos
|
/API_ControlEntregas/Models/ClienteModel.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace API_ControlEntregas.Models
{
public class ClienteModel
{
public async Task <List<Cliente>> Get()
{
try
{
String query = String.Format("SELECT * FROM Clientes");
DataBaseSettings db = new DataBaseSettings();
DataTable aux = await db.GetDataTable(query);
List<Cliente> data = aux.AsEnumerable().Select(m => new Cliente()
{
idCliente = m.Field<int>("IDCliente"),
nombreEmpresa = m.Field<String>("NombreEmpresa"),
contactoSistemas = m.Field<String>("ContactoSistemas"),
telefono = m.Field<String>("Telefono"),
email = m.Field<String>("Email"),
grupo = m.Field<String>("Grupo"),
activo = m.Field<bool>("Estatus")
}).ToList();
return data;
} catch (Exception ex)
{
throw ex;
}
}
public async Task Insert(Cliente data)
{
try
{
String query = String.Format(@"INSERT INTO [dbo].[Clientes]
([NombreEmpresa]
,[ContactoSistemas]
,[Telefono]
,[Email]
,[Grupo]
,[Estatus])
VALUES
('{0}'
,'{1}'
,'{2}'
,'{3}'
,'{4}'
,{5})", data.nombreEmpresa, data.contactoSistemas, data.telefono, data.email, data.grupo, data.activo == true ? 1 : 0);
DataBaseSettings db = new DataBaseSettings();
await db.ExecuteQuery(query);
} catch (Exception ex)
{
throw ex;
}
}
public async Task UpdateStatus(Cliente data)
{
try
{
String query = String.Format("UPDATE Clientes SET Estatus = {0} WHERE IDCliente = {1}", data.activo == true ? 1 : 0, data.idCliente);
DataBaseSettings db = new DataBaseSettings();
await db.ExecuteQuery(query);
} catch (Exception ex)
{
throw ex;
}
}
}
public class Cliente
{
public int idCliente;
public String nombreEmpresa;
public String contactoSistemas;
public String telefono;
public String email;
public String grupo;
public bool activo;
public Cliente()
{
}
}
}
|
998495e9a7c0f322fcd6ef86dece1d1928fd18e7
|
C#
|
MartinZPetrov/TelerikAcademy
|
/C# Part I/Exam/Task4/Task4.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Task4
{
static void Main()
{
int N = Int32.Parse(Console.ReadLine());
int Width = N * 2 - 1;
int leftnakCounter = 0;
int leftWhiteSpaceCounter = N - 1;
int rightXCounter = 0;
int rightNakCounter = N - 3;
for (int i = 0; i < N - 1; i++)
{
if (i == 0)
{
Console.Write(new string(' ', N - 1));
Console.Write(new string(':', 1));
Console.Write(new string(':', N - 1));
leftWhiteSpaceCounter--;
leftnakCounter++;
Console.WriteLine();
}
else if (i == 1)
{
Console.Write(new string(' ', leftWhiteSpaceCounter));
Console.Write(new string(':', 1));
Console.Write(new string('/', leftnakCounter));
Console.Write(new string('/', rightNakCounter));
Console.Write(new string(':', 2));
leftnakCounter++;
leftWhiteSpaceCounter--;
rightNakCounter--;
rightXCounter++;
Console.WriteLine();
}
else
{
Console.Write(new string(' ', leftWhiteSpaceCounter));
Console.Write(new string(':', 1));
Console.Write(new string('/', leftnakCounter));
Console.Write(new string('/', rightNakCounter));
Console.Write(new string(':', 1));
Console.Write(new string('X', rightXCounter));
Console.Write(new string(':', 1));
leftnakCounter++;
leftWhiteSpaceCounter--;
rightNakCounter--;
rightXCounter++;
Console.WriteLine();
}
}
Console.Write(new string(':', N));
Console.Write(new string('X', N - 2));
Console.WriteLine(new string(':', 1));
rightXCounter = N - 2 - 1;
int rightWhiteSpaceCounter = 1;
for (int i = 0; i < N - 1; i++)
{
if (rightXCounter == -1)
{
Console.Write(new string(':', N));
}
else if (rightXCounter == 0)
{
Console.Write(new string(':', 1));
Console.Write(new string(' ', N - 2));
Console.Write(new string(':', 1));
Console.WriteLine(new string(':', 1));
rightXCounter--;
}
else
{
Console.Write(new string(':', 1));
Console.Write(new string(' ', N - 2));
Console.Write(new string(':', 1));
Console.Write(new string('X', rightXCounter));
Console.Write(new string(':', 1));
Console.WriteLine(new string(' ', rightWhiteSpaceCounter));
rightWhiteSpaceCounter++;
rightXCounter--;
}
}
}
}
|
5155e57e943fef085b2c569368642c6fa058e5e2
|
C#
|
SebastianBienert/Advent-Of-Code-2017
|
/Day10/Program.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Day10
{
class Program
{
static void Main(string[] args)
{
List<string> data = new List<string>() { "" };
List<int> additional = new List<int>() {17, 31, 73, 47, 23};
List<int> seq = new List<int>();
foreach (var word in data)
{
byte[] asciiBytes = Encoding.ASCII.GetBytes(word);
foreach (var asciiByte in asciiBytes)
{
seq.Add(asciiByte);
}
}
// seq = new List<int>() {3,4,1,5};
seq.AddRange(additional);
List<int> list = new List<int>();
for(int i = 0; i < 256; i++)
list.Add(i);
int currentPos = 0;
int skipSize = 0;
int seqIndex = 0;
for (int i = 0; i < 64; i++)
{
seqIndex = 0;
do
{
if ((currentPos + seq[seqIndex]) < list.Count)
list.Reverse(currentPos, seq[seqIndex]);
else
{
customReverse(list, currentPos, seq[seqIndex]);
}
currentPos += seq[seqIndex] + skipSize;
currentPos %= list.Count;
skipSize++;
seqIndex++;
} while (seqIndex < seq.Count);
}
List<int> denseHash = new List<int>();
for (int i = 0; i < 16; i++)
{
int output = list[i * 16];
for (int j = (i * 16) + 1; j < (i * 16) + 16; j++)
{
output ^= list[j];
}
denseHash.Add(output);
}
string result = String.Empty;
for (int i = 0; i < 16; i++)
{
string hexValue = denseHash[i].ToString("X");
if (hexValue.Length == 1)
hexValue = "0" + hexValue;
result += hexValue;
}
Console.WriteLine(result);
Console.ReadKey();
}
private static void customReverse(List<int> list, int pos, int count)
{
var newList = new List<int>();
int counter = count;
for (int i = pos; count > 0; i++)
{
newList.Add(list[i % list.Count]);
count--;
}
newList.Reverse();
int j = 0;
for (int i = pos; counter > 0; i++)
{
list[i % list.Count] = newList[j];
counter--;
j++;
}
}
private static void printList(List<int> list)
{
foreach (var it in list)
{
Console.Write($"{it} ");
}
Console.WriteLine();
}
}
}
|
cc1316a50fee0df4f31257d7d0ad03eec95e487c
|
C#
|
MiraNedeva/SoftUni
|
/Programming Fundamentals C#/2.Methods And Debugging-Exercices/Geometry Calculator/Program.cs
| 4.125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/* Write a program that can calculate the area of four different geometry figures - triangle, square, rectangle and circle.
On the first line you will get the figure type. Next you will get parameters for the chosen figure, each on a different line
• Triangle - side and height
• Square - side
• Rectangle - width and height
• Circle - radius
The output should be rounded to the second digit after the decimal point */
namespace GeometryCalculator
{
class Program
{
static void Main(string[] args)
{
string type = Console.ReadLine();
switch (type)
{
case "triangle":
double side = double.Parse(Console.ReadLine());
double height = double.Parse(Console.ReadLine());
Console.WriteLine("{0:f2}", TriangleArea(side, height));
break;
case "square":
double sideSquare = double.Parse(Console.ReadLine());
Console.WriteLine("{0:f2}", SquareArea(sideSquare));
break;
case "rectangle":
double widht = double.Parse(Console.ReadLine());
double heightRect = double.Parse(Console.ReadLine());
Console.WriteLine("{0:f2}", RectangleArea(widht, heightRect));
break;
case "circle":
double radius = double.Parse(Console.ReadLine());
Console.WriteLine("{0:f2}", CircleArea(radius));
break;
}
}
/////////// Methods///////////
static double TriangleArea(double side, double height)
{
double result = (side * height) / 2;
return result;
}
static double SquareArea(double side)
{
double result = side * side;
return result;
}
static double RectangleArea(double width, double height)
{
double result = width * height;
return result;
}
static double CircleArea(double radius)
{
double result = Math.PI * (radius * radius);
return result;
}
}
}
|
24909bdafb228695594b7c5eb1d0596fd0b4bee4
|
C#
|
imoduatv/TriangleBlockPuzzleGame
|
/Assets/Scripts/Dta_TenTen/Block.cs
| 3.09375
| 3
|
namespace Dta.TenTen
{
public class Block
{
private int color;
private int x;
private int y;
public Block()
{
color = -1;
x = -1;
y = -1;
}
public Block(int c)
{
color = c;
}
public Block(int c, int x, int y)
{
color = c;
this.x = x;
this.y = y;
}
public Block(Block block)
{
color = block.Color();
x = block.GetX();
y = block.GetY();
}
public int GetX()
{
return x;
}
public int GetY()
{
return y;
}
public int Color()
{
return color;
}
}
}
|
4ea67954172c83d49d7cf514b2f77ece0d2223f9
|
C#
|
carrot13/SoftUni-Projects
|
/Programming-Basics-With-C#/01.FirstStepsInCodingExercise/VacantionBooksList/Program.cs
| 2.9375
| 3
|
using System;
namespace VacantionBooksList
{
class Program
{
static void Main(string[] args)
{
int pagesCount = int.Parse(Console.ReadLine());
double pagesForHour = double.Parse(Console.ReadLine());
int countDays = int.Parse(Console.ReadLine());
double hoursPerDay = (pagesCount / pagesForHour) / countDays;
Console.WriteLine(hoursPerDay);
}
}
}
|
acf10a2359952d19abc79cb465c42c16d68a1934
|
C#
|
Rule-the-Waves-2-Mods/Thalassic
|
/Thalassic/Registry/Rtw2VersionRegistry.cs
| 2.515625
| 3
|
using Thalassic.Mods;
using Microsoft.Extensions.Configuration;
using Semver;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
namespace Thalassic.Registry
{
/// <summary>
/// Must be initialized by calling Update()
/// </summary>
public class Rtw2VersionRegistry
{
public List<Rtw2Version> Rtw2Versions { get; private set; } = new List<Rtw2Version>();
public Rtw2Version CurrentRtw2Version { get; private set; }
private readonly string _versionCachePath = Path.Combine(Program.Rtw2ExecutableDirectory, "rtw2_versions.ini");
public Rtw2VersionRegistry()
{
}
public void Update(IList<string> mirrors = null)
{
if (!File.Exists(_versionCachePath) && mirrors == null)
{
throw new Exception($"RTW2 version cache not found at {_versionCachePath} and no mirrors provided");
}
if (File.Exists(_versionCachePath))
{
UpdateKnownVersionsFromCache();
}
if (mirrors != null)
{
UpdateKnownRTW2VersionsFromMirrors(mirrors);
}
var checksum = GetChecksum(File.ReadAllBytes(Path.Combine(Program.Rtw2ExecutableDirectory, "RTW2.exe")));
Log.Debug($"Identified checksum {checksum}");
try
{
CurrentRtw2Version = Rtw2Versions.First(v => v.Checksum.Equals(checksum));
}
catch (Exception e)
{
Log.Error($"Couldn't find RTW2 version associated with checksum {checksum}", e);
CurrentRtw2Version = new Rtw2Version(SemVersion.Parse("1.0.0"), checksum);
}
Log.Debug($"Running Rule the Waves 2 {CurrentRtw2Version.Version}");
}
internal void UpdateKnownVersionsFromCache()
{
Log.Debug($"Loading RTW2 versions from {Path.Combine(Program.Rtw2ExecutableDirectory, "rtw2_versions.ini")}");
try
{
var rawFileContents = File.ReadAllText(Path.Combine(Program.Rtw2ExecutableDirectory, "rtw2_versions.ini"));
Rtw2Versions.AddRange(ModConfigurationReader.Rtw2VersionsFromString(rawFileContents).ToList());
}
catch (Exception e)
{
Log.Error($"Failed to parse version data", e);
}
}
internal void UpdateKnownRTW2VersionsFromMirrors(IList<string> mirrors)
{
var allKnownVersions = new List<Rtw2Version>(Rtw2Versions);
foreach (var mirror in mirrors)
{
Log.Debug($"Retrieving version information from {mirror} if available");
var mirrorKnownVersions = new List<Rtw2Version>();
var versionsUrl = Path.Combine(mirror, "rtw2_versions.ini");
using (var client = new WebClient())
{
try
{
var response = client.DownloadString(versionsUrl);
mirrorKnownVersions.AddRange(ModConfigurationReader.Rtw2VersionsFromString(response));
}
catch (Exception e)
{
Log.Error($"Didn't find a RTW2 version listing at {versionsUrl}", e);
}
}
foreach (var version in mirrorKnownVersions)
{
if (!allKnownVersions.Any(existing => version.Checksum == existing.Checksum))
{
allKnownVersions.Add(version);
}
}
}
Rtw2Versions.AddRange(allKnownVersions);
UpdateCache();
}
internal void UpdateCache()
{
// Update cache
var versions = Rtw2Versions.Select(v => $"{v.Version}={v.Checksum}");
Log.Debug($"Updating cache with {String.Join("\n\r", versions)}");
File.WriteAllLines(
Path.Combine(Program.Rtw2ExecutableDirectory, "rtw2_versions.ini"),
Rtw2Versions.Select(v => $"{v.Version}={v.Checksum}").Distinct());
}
internal string GetChecksum(byte[] bytes)
{
return Program.GetChecksum(bytes);
}
}
}
|
5d3d638ba7e8a74977905bf06276ccb82b4e24b1
|
C#
|
DmitryEvmenov/having-fun-with-shapes
|
/Shapes/Concrete/Ellipsis.cs
| 3.1875
| 3
|
using System.Collections.Generic;
namespace Shapes.Concrete
{
public class Ellipsis : Circle
{
public double StretchingX { get; }
public double StretchingY { get; }
public Ellipsis(int centerX, int centerY, int radius, double stretchingX, double stretchingY) : base(centerX, centerY, radius)
{
StretchingX = stretchingX;
StretchingY = stretchingY;
}
public override IDictionary<string, object> CustomDrawObjects
{
get
{
var fromBase = base.CustomDrawObjects;
fromBase.Add(nameof(StretchingX), StretchingX);
fromBase.Add(nameof(StretchingY), StretchingY);
return fromBase;
}
}
}
}
|
53821c28c9abb388b7d493322d3bdcf940ea96f8
|
C#
|
AbnerSquared/OpenTDB.Net
|
/src/TdbClient.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace OpenTDB
{
public class TdbClient : IDisposable
{
private readonly HttpClient _client;
// private string _session;
public TdbClient()
{
_client = new HttpClient();
}
public async Task<string> RequestSessionTokenAsync()
{
var args = new List<string>
{
$"command={TokenCommand.Request.ToString().ToLower()}"
};
string endpoint = API.CreateQuery(API.TokenEndpoint, args);
var result = await GetAsync<SessionToken>(endpoint);
return result?.Token;
}
public async Task<bool> ResetSessionTokenAsync(string token)
{
if (string.IsNullOrWhiteSpace(token))
throw new ArgumentNullException(nameof(token), "Expected a value for the specified token");
var args = new List<string>
{
$"command={TokenCommand.Reset.ToString().ToLower()}",
$"token={token}"
};
string endpoint = API.CreateQuery(API.TokenEndpoint, args);
var result = await GetAsync<ResetResult>(endpoint);
return result?.ResponseCode == ResponseCode.Success;
}
public async Task<TriviaSession> CreateSessionAsync()
{
var result = await RequestSessionTokenAsync();
if (string.IsNullOrWhiteSpace(result))
throw new Exception("An error has occurred while requesting a new session token.");
return new TriviaSession(result);
}
public async Task<List<TriviaCategory>> GetAllCategoriesAsync()
{
var result = await GetAsync<CategoryCollection>(API.CategoryEndpoint);
return result?.Categories;
}
public async Task<CategoryQuestionCount> GetQuestionCountAsync(int categoryId)
{
var args = new List<string>
{
$"category={categoryId}"
};
string endpoint = API.CreateQuery(API.CountEndpoint, args);
var result = await GetAsync<CategoryCount>(endpoint);
return result?.Count;
}
public async Task<List<TriviaQuestion>> GetQuestionsAsync(TriviaSession session)
{
if (DateTime.UtcNow - session.LastRequest >= TimeSpan.FromHours(API.SessionTokenTimeoutHours))
throw new Exception("The specified session has expired due to inactivity.");
var questions = await GetQuestionsAsync(session.QuestionCount, session.CategoryId, session.Difficulty, session.Type, session.Token);
if (questions == null)
throw new Exception("An error has occurred while attempting to retrieve questions.");
session.LastRequest = DateTime.UtcNow;
return questions;
}
public async Task<List<TriviaQuestion>> GetQuestionsAsync(int amount = 50, int? categoryId = null,
Difficulty? difficulty = null, QuestionType? type = null, string token = null)
{
amount = amount < 0 ? 0 : amount;
if (amount == 0)
return new List<TriviaQuestion>();
var args = new List<string>
{
$"amount={amount}"
};
if (categoryId.HasValue)
args.Add($"category={categoryId.Value}");
if (difficulty.HasValue) // Check if the specified difficulty is an actual flag
args.Add($"difficulty={difficulty.Value.ToString().ToLower()}");
if (type.HasValue)
args.Add($"type={type.Value.ToString().ToLower()}");
args.Add($"encode={ResponseEncoding.Base64.ToString().ToLower()}");
if (!string.IsNullOrWhiteSpace(token))
args.Add($"token={token}");
string endpoint = API.CreateQuery(API.BaseEndpoint, args);
var result = await GetAsync<QuestionResult>(endpoint);
return result?.Questions.Select(API.DecodeQuestion).ToList();
}
protected async Task<T> GetAsync<T>(string endpoint)
{
HttpResponseMessage result = await _client.GetAsync($"{API.BaseUrl}{endpoint}");
return result.IsSuccessStatusCode
? JsonConvert.DeserializeObject<T>(await result.Content.ReadAsStringAsync()) : default;
}
public void Dispose()
{
_client.Dispose();
}
}
}
|
a2929ca299812c29ad20778823f5717d639c96dc
|
C#
|
Maxel-Uds/Curso-C-Sharp
|
/Membros_Estáticos/exercicio2/Program.cs
| 3.171875
| 3
|
using System;
using System.Globalization;
namespace exercicio2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Digite os dados do funcionário: ");
Console.Write("Nome: ");
Funcionario.Nome = Console.ReadLine();
Console.Write("Salário Bruto: ");
Funcionario.SalarioBruto = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Console.Write("Imposto: ");
Funcionario.Imposto = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Funcionario.SalarioLiquido();
Console.WriteLine("Funcionário" + Funcionario.Nome + ", $ " + Funcionario.SalarioLiqui.ToString("F2", CultureInfo.InvariantCulture));
Console.Write("Digite a porcentagem para aumentar o salário: ");
double porcentagem = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Funcionario.AumentarSalario(porcentagem);
Console.WriteLine("Dados atualizados: " + Funcionario.Nome + ", $ " + Funcionario.SalarioLiqui.ToString("F2", CultureInfo.InvariantCulture));
}
}
}
|
c3410c8724ef89ac74c26e5dc288fcd4864ae53c
|
C#
|
ShokoAnime/ShokoServer
|
/Shoko.Server/Utilities/LinuxFS.cs
| 2.78125
| 3
|
using System;
using Mono.Unix;
namespace Shoko.Server.Utilities;
public static class LinuxFS
{
private static UnixUserInfo RealUser;
private static bool CanRun()
{
return Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix;
}
public static void SetLinuxPermissions(string path, long uid, long gid, int mode)
{
if (!CanRun())
return;
RealUser ??= UnixUserInfo.GetRealUser();
// if uid is not valid (<0), skip
// if uid = 0 (trying to set as root), and we are not root (RealUser.UserId != 0), then set it to the current user
// if uid = 0 and we are root (RealUser.UserId = 0), then nothing changes, and it can use those values
if (uid == 0 && RealUser.UserId != 0)
uid = RealUser.UserId;
if (gid == 0 && RealUser.GroupId != 0)
gid = RealUser.GroupId;
var file = new UnixFileInfo(path);
var newMode = (FileAccessPermissions)Convert.ToInt32(mode.ToString(), 8);
// new user ID is valid (>= 0) and has changed (or same for group ID)
var shouldChangeOwner = uid >= 0 && uid != file.OwnerUserId || gid >= 0 && file.OwnerGroupId != gid;
// mode is valid and different
var shouldChangePermissions = mode > 0 && file.FileAccessPermissions != newMode;
// if we didn't change anything, then return
if (!shouldChangeOwner && !shouldChangePermissions) return;
Utils.ShokoServer.AddFileWatcherExclusion(path);
try
{
if (shouldChangeOwner) file.SetOwner(uid, gid);
if (shouldChangePermissions) file.FileAccessPermissions = newMode;
// guarantee immediate flush
file.Refresh();
}
finally
{
Utils.ShokoServer.RemoveFileWatcherExclusion(path);
}
}
}
|
10ac899bb6da5916de926ff40645c9f42cc6a2e1
|
C#
|
autumn009/CSharpSourceDance
|
/Answers/LanguageKeywords/case/case/Program.cs
| 3.40625
| 3
|
using System;
class Program
{
static void Main()
{
int[] array = { 1, 0, 1, -1 };
foreach (var item in array)
{
switch (item)
{
case 0: Console.Write("ZERO "); break;
case 1: Console.Write("ONE "); break;
default: Console.Write("MASQUERADE"); break;
}
}
}
}
|
b9aad1dd94a12d9e0cb37cf930f567995c7eb611
|
C#
|
math039h/ObligatoriskeTCP-Server5
|
/TCP-ServerEcho/Worker.cs
| 3.0625
| 3
|
using System;
using System.IO;
using System.Net.Sockets;
namespace TCP_ServerEcho
{
internal class Worker
{
public Worker()
{
}
public void Start()
{
using (TcpClient socket = new TcpClient("localhost", 4646))
using (StreamReader sr = new StreamReader(socket.GetStream()))
using (StreamWriter sw = new StreamWriter(socket.GetStream()))
{
string str = "Besked la la";
sw.WriteLine(str);
sw.Flush();
string s = sr.ReadLine();
Console.WriteLine(s);
}
}
}
}
|
28da77a433a7c922522818ea7bbdc2c933923116
|
C#
|
danielnutu/NemoExpressSolution
|
/src/CmdSolutions.Shipping.NemoExpress/Converters/NemoExpressEpochConverter.cs
| 2.8125
| 3
|
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CmdSolutions.Shipping.NemoExpress.Converters
{
sealed class NemoExpressEpochConverter : JsonConverter<DateTime>
{
private static readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0);
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var date = reader.TokenType switch
{
JsonTokenType.Number => _epoch.AddSeconds(reader.GetInt64()),
JsonTokenType.String => _epoch.AddSeconds(double.Parse(reader.GetString())),
_ => DateTime.Now
};
return date;
}
// have a look at
// https://referencesource.microsoft.com/#System.Web.Extensions/Script/Serialization/JavaScriptSerializer.cs
// SerializeDateTime where they use ticks
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
long unixTime = Convert.ToInt64((value - _epoch).TotalSeconds);
string formatted = FormattableString.Invariant($"{unixTime}");
writer.WriteStringValue(formatted);
}
}
}
|
01d00a8008910ed5f41dcf1fff177bb1e82f1215
|
C#
|
sunc123/PatternLearn
|
/PatternLearn/Factory Method/Factory.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PatternLearn
{
abstract class Factory
{
public Product Creat(string owner)
{
Product p = CreatProduct(owner);
RegisterProduct(p);
return p;
}
protected abstract Product CreatProduct(string owner);
protected abstract void RegisterProduct(Product product);
}
}
|
687d30132c4434af0f557ad7c3cf6173b7c09e16
|
C#
|
Kawser-nerd/CLCDSA
|
/Source Codes/AtCoder/abc119/D/4430027.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace CSharpSample01
{
class Program
{
static long[] shrine;
static long[] temple;
static long[] posi;
static int A;
static int B;
static int Q;
const long EAST = 100000000000;
const long WEST = -100000000000;
static int LowerBound(long[] data, long key)
{
int left = -1;
int right = data.Count();
while(right - left > 1)
{
int mid = left + (right - left) / 2;
if(data[mid] >= key)
{
right = mid;
}
else
{
left = mid;
}
}
return right;
}
static void Main(string[] args)
{
string[] str = Console.ReadLine().Split(' ');
A = int.Parse(str[0]);
B = int.Parse(str[1]);
Q = int.Parse(str[2]);
shrine = new long[A];
temple = new long[B];
posi = new long[Q];
for(int i = 0; i < A; i++)
{
shrine[i] = long.Parse(Console.ReadLine());
}
for(int i = 0; i < B; i++)
{
temple[i] = long.Parse(Console.ReadLine());
}
for(int i = 0; i < Q; i++)
{
posi[i] = long.Parse(Console.ReadLine());
}
int right = 0;
long s1, s2;
long t1, t2;
for(int i = 0; i < Q; i++)
{
long x = posi[i];
right = LowerBound(shrine, x);
if(right == A)
{
s1 = shrine[right - 1];
s2 = EAST;
}
else if(right == 0)
{
s1 = WEST;
s2 = shrine[right];
}
else
{
s1 = shrine[right - 1];
s2 = shrine[right];
}
right = LowerBound(temple, x);
if (right == B)
{
t1 = temple[right - 1];
t2 = EAST;
}
else if (right == 0)
{
t1 = WEST;
t2 = temple[right];
}
else
{
t1 = temple[right - 1];
t2 = temple[right];
}
var cstlist = new List<long>();
cstlist.Add(Math.Abs(x - s1) + Math.Abs(t1 - s1));
cstlist.Add(Math.Abs(x - s1) + Math.Abs(t2 - s1));
cstlist.Add(Math.Abs(x - s2) + Math.Abs(t1 - s2));
cstlist.Add(Math.Abs(x - s2) + Math.Abs(t2 - s2));
cstlist.Add(Math.Abs(x - t1) + Math.Abs(s1 - t1));
cstlist.Add(Math.Abs(x - t1) + Math.Abs(s2 - t1));
cstlist.Add(Math.Abs(x - t2) + Math.Abs(s1 - t2));
cstlist.Add(Math.Abs(x - t2) + Math.Abs(s2 - t2));
cstlist.Sort();
Console.WriteLine(cstlist.First());
}
}
}
}
|
289e3bbaaa817ba0be81d443732717de487217d5
|
C#
|
OlgaKulina/DiaryAppOlga
|
/TestBootstrap/Repository/ScheduleRepository.cs
| 2.71875
| 3
|
using DiaryAppOlga.Models;
using System.Collections.Generic;
using System.Linq;
namespace DiaryAppOlga.Repository
{
public class ScheduleRepository: IRepository {
private ScheduleContext context;
public ScheduleRepository(ScheduleContext ctx) => context = ctx;
public IEnumerable<UserTask> UserTasks => context.UserTasks.ToArray();
public UserTask GetUserTask(int key) => context.UserTasks.Find(key);
public void AddUserTask(UserTask userTask)
{
this.context.UserTasks.Add(userTask);
this.context.SaveChanges();
}
//public void AddMonthlyTask(MonthlyTask monthlyTask)
//{
// this.context.MonthlyTask.Add(monthlyTask);
// this.context.SaveChanges();
//}
public void UpdateUserTask(UserTask userTask)
{
context.UserTasks.Update(userTask);
context.SaveChanges();
}
public void DeleteUserTask(UserTask userTask) {
context.UserTasks.Remove(userTask);
context.SaveChanges();
}
}
}
|
6d178a35c9123a6e3576911515ef94db08daf1fc
|
C#
|
zmalosh/HockeyData
|
/HockeyData.Processors/NhlCom/Processors/TeamsProcessor.cs
| 2.5625
| 3
|
using HockeyData.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HockeyData.Processors.NhlCom.Processors
{
public class TeamsProcessor : IProcessor
{
private readonly string NhlSeasonKey;
private readonly JsonUtility JsonUtility;
public TeamsProcessor(string nhlSeasonKey = null)
{
this.NhlSeasonKey = nhlSeasonKey;
this.JsonUtility = new JsonUtility(7 * 24 * 60 * 60);
}
public void Run(HockeyDataContext dbContext)
{
var url = Feeds.TeamsFeed.GetFeedUrl(this.NhlSeasonKey);
var rawJson = this.JsonUtility.GetRawJsonFromUrl(url);
var feed = Feeds.TeamsFeed.FromJson(rawJson);
var teamsDict = dbContext.Teams.ToDictionary(x => x.NhlTeamId, y => y);
var apiTeams = feed.Teams.OrderBy(x => x.Name).ToList();
foreach (var apiTeam in apiTeams)
{
if (!teamsDict.TryGetValue(apiTeam.Id, out Team dbTeam))
{
dbTeam = new Team
{
NhlTeamId = apiTeam.Id,
FirstYearOfPlay = apiTeam.FirstYearOfPlay,
TeamAbbr = apiTeam.Abbreviation,
TeamFullName = apiTeam.Name,
TeamLocation = apiTeam.LocationName,
TeamName = apiTeam.TeamName,
TeamShortName = apiTeam.ShortName,
WebSiteUrl = apiTeam.OfficialSiteUrl,
TimeZoneAbbr = apiTeam.Venue?.TimeZone?.TimeZoneAbbr,
TimeZoneName = apiTeam.Venue?.TimeZone?.TimeZoneName,
TimeZoneOffset = apiTeam.Venue?.TimeZone?.Offset,
};
teamsDict.Add(apiTeam.Id, dbTeam);
dbContext.Teams.Add(dbTeam);
dbContext.SaveChanges();
}
else if (HasUpdates(dbTeam, apiTeam))
{
dbTeam.TeamFullName = apiTeam.Name;
dbTeam.TeamLocation = apiTeam.LocationName;
dbTeam.TeamName = apiTeam.TeamName;
dbTeam.TeamShortName = apiTeam.ShortName;
dbTeam.WebSiteUrl = apiTeam.OfficialSiteUrl;
dbTeam.TeamAbbr = apiTeam.Abbreviation;
dbContext.SaveChanges();
}
}
}
private bool HasUpdates(Team dbTeam, Feeds.TeamsFeed.ApiTeam apiTeam)
{
return dbTeam.TeamFullName != apiTeam.Name
|| dbTeam.TeamLocation != apiTeam.LocationName
|| dbTeam.TeamName != apiTeam.TeamName
|| dbTeam.TeamShortName != apiTeam.ShortName
|| dbTeam.WebSiteUrl != apiTeam.OfficialSiteUrl
|| dbTeam.TeamAbbr != apiTeam.Abbreviation;
}
}
}
|
49df86a670089df904dd44b82f987617f01ab136
|
C#
|
Will-D-James/DotsAndBoxes
|
/DotsAndBoxes/DAB.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DotsAndBoxes
{
public partial class FrmDAB : Form
{
private int mainCounter;
private int playerOneScore;
private int playerTwoScore;
public FrmDAB()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
mainCounter = 0;
playerOneScore = 0;
playerTwoScore = 0;
foreach (Control c in Controls)
{
if (c.Name.Count() == 1)
{
c.Text = "";
}
}
}
private void label_Click(object sender, EventArgs eventArgs)
{
//Evens are player 1, odds are player 2.
((Label)sender).BackColor = PlayerColor();
var firstLabelLetter = ((Label)sender).Name.Substring(0, 1);
var secondLabelLetter = ((Label)sender).Name.Substring(1, 1);
if (CheckBox(firstLabelLetter))
{
CompleteBox(firstLabelLetter);
}
if (!char.IsDigit(secondLabelLetter.FirstOrDefault()))
{
if (CheckBox(secondLabelLetter))
{
CompleteBox(secondLabelLetter);
}
}
mainCounter++;
}
public bool CheckBox(string letter)
{
var boxSides = Controls.OfType<Label>().Where(x => x.Name.Contains(letter) && x.Name.Count() == 2).ToList();
var counter = 0;
foreach (Label a in boxSides)
{
if (a.BackColor != Color.White) counter++;
}
return (counter == 4);
}
public void CompleteBox(string letter)
{
Controls.OfType<Label>().Where(x => x.Name == letter).FirstOrDefault().Text = "W";
Controls.OfType<Label>().Where(x => x.Name == letter).FirstOrDefault().ForeColor = PlayerColor();
if (mainCounter % 2 == 0)
playerOneScore++;
else
playerTwoScore++;
lbl1Score.Text = playerOneScore.ToString();
lbl2Score.Text = playerTwoScore.ToString();
if (playerOneScore == 9)
{
MessageBox.Show("Player 1 has won!");
return;
}
if (playerTwoScore == 9)
{
MessageBox.Show("Player 2 has won!");
return;
}
}
public Color PlayerColor()
{
return (mainCounter % 2 == 0) ? Color.Red : Color.Blue;
}
}
}
|
729226ca405ff05b1abb909919fc877c1cae9e71
|
C#
|
teodortenchev/C-Sharp-Advanced-Coursework
|
/C# OOP Advanced/Generics/P9CustomListIterator/CommandInterpreter.cs
| 3.9375
| 4
|
namespace P9CustomListIterator
{
using System;
public class CommandInterpreter<T> : ICommandInterpreter<T>
where T : IComparable<T>
{
private CustomList<T> list;
public CommandInterpreter()
{
list = new CustomList<T>();
}
public void Add(T element)
{
list.Add(element);
}
public void Contains(T element)
{
Console.WriteLine(list.Contains(element));
}
public void Greater(T element)
{
Console.WriteLine(list.CountGreaterThan(element));
}
public void Max()
{
Console.WriteLine(list.Max());
}
public void Min()
{
Console.WriteLine(list.Min());
}
public void Print()
{
foreach (var item in list)
{
Console.WriteLine(item);
}
}
public void Remove(int index)
{
list.Remove(index);
}
public void Swap(int index1, int index2)
{
list.Swap(index1, index2);
}
public void Sort()
{
list.Sort();
}
}
}
|
8a7dd9ff430b22c59fb197035fc3ce357c027c87
|
C#
|
I-Mircheva/text-filter-calastone
|
/TextFilter/Filters/FilterLetterT.cs
| 3.1875
| 3
|
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace TextFilter
{
public class FilterLetterT : FilterBase
{
public FilterLetterT() : base("FilterLetterT") { }
public override OutputText Apply(OutputText text)
{
string returnString = text.text;
var words = Regex.Split(text.text, @"\W")
.Where(str => !String.IsNullOrEmpty(str)); //Empty string messes up the count!
foreach (string word in words)
{
if (word.Contains("t"))
{
// \b - word boundary, so it matches "in" in " in;" but not "in" in "beginning"
String regex = "\\b" + word + "\\b";
returnString = Regex.Replace(returnString, regex, "");
}
}
return new OutputText(returnString);
}
}
}
|
36c94749277996f96a45a7e9aa7b8102ac052f60
|
C#
|
JaimeAlbertoMonroyLopez/masglobal
|
/DataLayer/DataAccess/DataAccessClass.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Net;
using Entities.Employee;
using System.Resources;
using System.Reflection;
namespace DataAccess
{
public class DataAccessClass
{
private static string EmployeeAPIurl= "http://masglobaltestapi.azurewebsites.net/api/Employees";
HttpClient testAPIclient = new HttpClient();
public List<EmployeeDTO> ConsumeEmployeesTestAPI()
{
return this.GetEmployeeSync(EmployeeAPIurl);
}
public EmployeeDTO ConsumeEmployeesTestAPI(double empId)
{
return this.GetEmployeeSyncById(EmployeeAPIurl, empId);
}
List<EmployeeDTO> GetEmployeeSync(string path)
{
List<EmployeeDTO> employeeList = null;
string employeeString = string.Empty;
HttpResponseMessage response = testAPIclient.GetAsync(path).Result;
if (response.IsSuccessStatusCode)
{
employeeString = (response.Content).ReadAsStringAsync().Result;
}
employeeList = DataLayerHelperClass.DeserializeObjectEmployee(employeeString);
return employeeList;
}
EmployeeDTO GetEmployeeSyncById(string path, double empId)
{
List<EmployeeDTO> employeeList = null;
string employeeString = string.Empty;
HttpResponseMessage response = testAPIclient.GetAsync(path).Result;
if (response.IsSuccessStatusCode)
{
employeeString = (response.Content).ReadAsStringAsync().Result;
}
employeeList = DataLayerHelperClass.DeserializeObjectEmployee(employeeString);
return employeeList.Where(x=>x.id==empId).FirstOrDefault();
}
}
}
|
37f36cbd5fc84eedcfcafc3ecaf66a629767365e
|
C#
|
yufw/RayTracingInOneWeekend
|
/Sphere.cs
| 2.609375
| 3
|
using System;
public class Sphere : IHitable
{
private Vec3 center;
private float radius;
private Material mat;
public Sphere() { }
public Sphere(Vec3 cen, float r, Material m) { center = cen; radius = r; mat = m; }
public bool hit(Ray r, float tMin, float tMax, ref HitRecord rec)
{
Vec3 oc = r.origin() - center;
float a = Vec3.dot(r.direction(), r.direction());
float b = Vec3.dot(oc, r.direction());
float c = Vec3.dot(oc, oc) - radius * radius;
float discriminant = b * b - a * c;
if (discriminant > 0)
{
float temp = (-b - (float)Math.Sqrt(b*b - a*c))/a;
if (temp > tMin && temp < tMax)
{
rec.t = temp;
rec.p = r.pointAtParameter(rec.t);
rec.normal = (rec.p - center) / radius;
rec.mat = mat;
return true;
}
temp = (-b + (float)Math.Sqrt(b*b - a*c))/a;
if (temp > tMin && temp < tMax)
{
rec.t = temp;
rec.p = r.pointAtParameter(rec.t);
rec.normal = (rec.p - center) / radius;
rec.mat = mat;
return true;
}
}
return false;
}
}
|
d25f08ca191cf97f4d2bef6dfff0f29822242868
|
C#
|
Dragicafit/JeuNul
|
/Assets/Scripts2/Status.cs
| 2.71875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Status
{
public readonly float duration;
public StatusEnum Se { get; protected set; }
public float StartTime { protected get; set; }
private GameObject go;
public Status(GameObject go, float dur)
{
StartTime = Time.time;
this.go = go;
duration = dur;
}
public abstract void ApplyEffect();
public override bool Equals(object other)
{
return GetType().Equals(other.GetType());
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public bool IsDone()
{
return Time.time - StartTime >= duration;
}
}
public abstract class StatusFactory
{
protected readonly float duration;
public StatusFactory(float dur)
{
this.duration = dur;
}
public abstract Status GenerateStatus(GameObject go);
}
|
ea7ad26017e3c22a6850aab67db275ec009f54e1
|
C#
|
ALGutierrez/EDSAChallenge
|
/Repository/APIStudentRepository.cs
| 2.6875
| 3
|
using Gestion_Alumnos_v1.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Threading.Tasks;
namespace Gestion_Alumnos_v1.Repository
{
public class APIStudentRepository : IAPIStudentRepository
{
private readonly ApplicationDbContext _context;
public APIStudentRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<ActionResult<Student>> DeleteStudentAPI(int id)
{
var student = _context.Students.Find(id);
_context.Students.Remove(student);
await _context.SaveChangesAsync();
return student;
}
public async Task<bool> EditStudentAPI(Student student)
{
try
{
_context.Entry(student).State = EntityState.Modified;
var studentEntity = _context.Students.Find(student.Id);
studentEntity.Name = student.Name;
studentEntity.DNI = student.DNI;
var grade = _context.Grades.Find(student.IdGrade);
studentEntity.Grade = grade;
studentEntity.Phone = student.Phone;
studentEntity.Enabled = student.Enabled;
_context.Students.Update(studentEntity);
var entries = await _context.SaveChangesAsync();
return entries > 0;
}
catch (Exception)
{
return false;
}
}
public bool ExistAPI(Student student)
{
throw new NotImplementedException();
}
public async Task<ActionResult<IEnumerable<Student>>> GetAllStudentsAPI()
{
return await _context.Students.ToListAsync();
}
public async Task<ActionResult<Student>> GetStudentByIdAPI(int id)
{
return await _context.Students.Include(x => x.Grade).FirstOrDefaultAsync(m => m.Id == id);
}
public async Task<bool> NewStudentAPI(Student student)
{
try
{
_context.Students.Add(student);
var entries = await _context.SaveChangesAsync();
return entries > 0;
}
catch (Exception)
{
return false;
}
}
}
}
|
46e1896a5ce7f5706c33744d71ddee9ed3fb22c5
|
C#
|
SharpKit/SharpKit-SDK
|
/Defs/ExtJs/Ext.slider.Multi.cs
| 2.6875
| 3
|
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:41 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext.slider
{
#region Multi
/// <inheritdocs />
/// <summary>
/// <p>Slider which supports vertical or horizontal orientation, keyboard adjustments, configurable snapping, axis clicking
/// and animation. Can be added as an item to any container.</p>
/// <p>Sliders can be created with more than one thumb handle by passing an array of values instead of a single one:</p>
/// <pre><code><see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.slider.Multi">Ext.slider.Multi</see>', {
/// width: 200,
/// values: [25, 50, 75],
/// increment: 5,
/// minValue: 0,
/// maxValue: 100,
/// // this defaults to true, setting to false allows the thumbs to pass each other
/// constrainThumbs: false,
/// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>()
/// });
/// </code></pre>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class Multi : Ext.form.field.Base
{
/// <summary>
/// Determines whether or not clicking on the Slider axis will change the slider.
/// Defaults to: <c>true</c>
/// </summary>
public bool clickToChange;
/// <summary>
/// True to disallow thumbs from overlapping one another.
/// Defaults to: <c>true</c>
/// </summary>
public bool constrainThumbs;
/// <summary>
/// The number of decimal places to which to round the Slider's value.
/// To disable rounding, configure as <strong>false</strong>.
/// Defaults to: <c>0</c>
/// </summary>
public object decimalPrecision;
/// <summary>
/// How many units to change the slider when adjusting by drag and drop. Use this option to enable 'snapping'.
/// Defaults to: <c>0</c>
/// </summary>
public JsNumber increment;
/// <summary>
/// How many units to change the Slider when adjusting with keyboard navigation. If the increment
/// config is larger, it will be used instead.
/// Defaults to: <c>1</c>
/// </summary>
public JsNumber keyIncrement;
/// <summary>
/// The maximum value for the Slider.
/// Defaults to: <c>100</c>
/// </summary>
public JsNumber maxValue;
/// <summary>
/// The minimum value for the Slider.
/// Defaults to: <c>0</c>
/// </summary>
public JsNumber minValue;
/// <summary>
/// A function used to display custom text for the slider tip.
/// Defaults to null, which will use the default on the plugin.
/// </summary>
public System.Delegate tipText;
/// <summary>
/// True to use an Ext.slider.Tip to display tips for the value. This option may also
/// provide a configuration object for an Ext.slider.Tip.
/// Defaults to: <c>true</c>
/// </summary>
public object useTips;
/// <summary>
/// Array of Number values with which to initalize the slider. A separate slider thumb will be created for each value
/// in this array. This will take precedence over the single value config.
/// </summary>
public JsNumber values;
/// <summary>
/// Orient the Slider vertically rather than horizontally.
/// Defaults to: <c>false</c>
/// </summary>
public bool vertical;
/// <summary>
/// Set to true to calculate snap points based on increments from zero as opposed to
/// from this Slider's minValue.
/// By Default, valid snap points are calculated starting <see cref="Ext.slider.MultiConfig.increment">increment</see>s from the <see cref="Ext.slider.MultiConfig.minValue">minValue</see>
/// Defaults to: <c>false</c>
/// </summary>
public bool zeroBasedSnapping;
/// <summary>
/// Determines whether or not a click to the slider component is considered to be a user request to change the value. Specified as an array of [top, bottom],
/// the click event's 'top' property is compared to these numbers and the click only considered a change request if it falls within them. e.g. if the 'top'
/// value of the click event is 4 or 16, the click is not considered a change request as it falls outside of the [5, 15] range
/// Defaults to: <c>[5, 15]</c>
/// </summary>
private JsNumber clickRange{get;set;}
/// <summary>
/// True while the thumb is in a drag operation
/// Defaults to: <c>false</c>
/// </summary>
public bool dragging{get;set;}
/// <summary>
/// Array containing references to each thumb
/// Defaults to: <c>[]</c>
/// </summary>
public JsArray thumbs{get;set;}
/// <summary>
/// Creates a new thumb and adds it to the slider
/// </summary>
/// <param name="value"><p>The initial value to set on the thumb.</p>
/// <p>Defaults to: <c>0</c></p></param>
/// <returns>
/// <span><see cref="Ext.slider.Thumb">Ext.slider.Thumb</see></span><div><p>The thumb</p>
/// </div>
/// </returns>
public Thumb addThumb(object value=null){return null;}
/// <summary>
/// Given a value within this Slider's range, calculates a Thumb's percentage CSS position to map that value.
/// </summary>
/// <param name="v">
/// </param>
private void calculateThumbPosition(object v){}
/// <summary>
/// Returns the nearest thumb to a click event, along with its distance
/// </summary>
/// <param name="trackPoint"><p>local pixel position along the Slider's axis to find the Thumb for</p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>The closest thumb object and its distance from the click event</p>
/// </div>
/// </returns>
private object getNearest(JsNumber trackPoint){return null;}
/// <summary>
/// Returns the ratio of pixels to mapped values. e.g. if the slider is 200px wide and maxValue - minValue is 100,
/// the ratio is 2
/// </summary>
/// <returns>
/// <span><see cref="Number">Number</see></span><div><p>The ratio of pixels to mapped values</p>
/// </div>
/// </returns>
private JsNumber getRatio(){return null;}
/// <summary>
/// Given an [x, y] position within the slider's track (Points outside the slider's track are coerced to either the minimum or maximum value),
/// calculate how many pixels from the slider origin (left for horizontal Sliders and bottom for vertical Sliders) that point is.
/// If the point is outside the range of the Slider's track, the return value is <c>undefined</c>
/// </summary>
/// <param name="xy"><p>The point to calculate the track point for</p>
/// </param>
private void getTrackpoint(JsArray<Number> xy){}
/// <summary>
/// Returns the current value of the slider
/// </summary>
/// <param name="index"><p>The index of the thumb to return a value for</p>
/// </param>
/// <returns>
/// <span><see cref="Number">Number</see>/<see cref="Number">Number</see>[]</span><div><p>The current value of the slider at the given index, or an array of all thumb values if
/// no index is given.</p>
/// </div>
/// </returns>
public object[] getValue(JsNumber index){return null;}
/// <summary>
/// Returns an array of values - one for the location of each thumb
/// </summary>
/// <returns>
/// <span><see cref="Number">Number</see>[]</span><div><p>The set of thumb values</p>
/// </div>
/// </returns>
public JsNumber[] getValues(){return null;}
/// <summary>
/// Adds keyboard and mouse listeners on this.el. Ignores click events on the internal focus element.
/// </summary>
private void initEvents(){}
/// <summary>
/// Returns a snapped, constrained value when given a desired value
/// </summary>
/// <param name="value"><p>Raw number value</p>
/// </param>
/// <returns>
/// <span><see cref="Number">Number</see></span><div><p>The raw value rounded to the correct d.p. and constrained within the set max and min values</p>
/// </div>
/// </returns>
private JsNumber normalizeValue(JsNumber value){return null;}
/// <summary>
/// Moves the thumb to the indicated position.
/// Only changes the value if the click was within this.clickRange.
/// </summary>
/// <param name="trackPoint"><p>local pixel offset <strong>from the origin</strong> (left for horizontal and bottom for vertical) along the Slider's axis at which the click event occured.</p>
/// </param>
private void onClickChange(JsNumber trackPoint){}
/// <summary>
/// Handler for any keypresses captured by the slider. If the key is UP or RIGHT, the thumb is moved along to the right
/// by this.keyIncrement. If DOWN or LEFT it is moved left. Pressing CTRL moves the slider to the end in either direction
/// </summary>
/// <param name="e"><p>The Event object</p>
/// </param>
private void onKeyDown(EventObject e){}
/// <summary>
/// Mousedown handler for the slider. If the clickToChange is enabled and the click was not on the draggable 'thumb',
/// this calculates the new value of the slider and tells the implementation (Horizontal or Vertical) to move the thumb
/// </summary>
/// <param name="e"><p>The click event</p>
/// </param>
private void onMouseDown(EventObject e){}
/// <summary>
/// Moves the given thumb above all other by increasing its z-index. This is called when as drag
/// any thumb, so that the thumb that was just dragged is always at the highest z-index. This is
/// required when the thumbs are stacked on top of each other at one of the ends of the slider's
/// range, which can result in the user not being able to move any of them.
/// </summary>
/// <param name="topThumb"><p>The thumb to move to the top</p>
/// </param>
private void promoteThumb(Thumb topThumb){}
/// <summary>
/// Given a Thumb's percentage position along the slider, returns the mapped slider value for that pixel.
/// E.g. if we have a slider 200px wide with minValue = 100 and maxValue = 500, reversePercentageValue(25)
/// returns 200
/// </summary>
/// <param name="pos"><p>The percentage along the slider track to return a mapped value for</p>
/// </param>
/// <returns>
/// <span><see cref="Number">Number</see></span><div><p>The mapped value for the given position</p>
/// </div>
/// </returns>
private JsNumber reversePercentageValue(JsNumber pos){return null;}
/// <summary>
/// Given a pixel location along the slider, returns the mapped slider value for that pixel.
/// E.g. if we have a slider 200px wide with minValue = 100 and maxValue = 500, reversePixelValue(50)
/// returns 200
/// </summary>
/// <param name="pos"><p>The position along the slider to return a mapped value for</p>
/// </param>
/// <returns>
/// <span><see cref="Number">Number</see></span><div><p>The mapped value for the given position</p>
/// </div>
/// </returns>
private JsNumber reversePixelValue(JsNumber pos){return null;}
/// <summary>
/// Sets the maximum value for the slider instance. If the current value is more than the maximum value, the current
/// value will be changed.
/// </summary>
/// <param name="val"><p>The new maximum value</p>
/// </param>
public void setMaxValue(JsNumber val){}
/// <summary>
/// Sets the minimum value for the slider instance. If the current value is less than the minimum value, the current
/// value will be changed.
/// </summary>
/// <param name="val"><p>The new minimum value</p>
/// </param>
public void setMinValue(JsNumber val){}
/// <summary>
/// Programmatically sets the value of the Slider. Ensures that the value is constrained within the minValue and
/// maxValue.
/// </summary>
/// <param name="index"><p>Index of the thumb to move</p>
/// </param>
/// <param name="value"><p>The value to set the slider to. (This will be constrained within minValue and maxValue)</p>
/// </param>
/// <param name="animate"><p>Turn on or off animation</p>
/// <p>Defaults to: <c>true</c></p></param>
public void setValue(JsNumber index, JsNumber value, object animate=null){}
/// <summary>
/// Synchronizes thumbs position to the proper proportion of the total component width based on the current slider
/// value. This will be called automatically when the Slider is resized by a layout, but if it is rendered
/// auto width, this method can be called from another resize handler to sync the Slider if necessary.
/// </summary>
public void syncThumbs(){}
public Multi(MultiConfig config){}
public Multi(){}
public Multi(params object[] args){}
}
#endregion
#region MultiConfig
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class MultiConfig : Ext.form.field.BaseConfig
{
/// <summary>
/// Turn on or off animation.
/// Defaults to: <c>true</c>
/// </summary>
public bool animate;
/// <summary>
/// Determines whether or not clicking on the Slider axis will change the slider.
/// Defaults to: <c>true</c>
/// </summary>
public bool clickToChange;
/// <summary>
/// True to disallow thumbs from overlapping one another.
/// Defaults to: <c>true</c>
/// </summary>
public bool constrainThumbs;
/// <summary>
/// The number of decimal places to which to round the Slider's value.
/// To disable rounding, configure as <strong>false</strong>.
/// Defaults to: <c>0</c>
/// </summary>
public object decimalPrecision;
/// <summary>
/// How many units to change the slider when adjusting by drag and drop. Use this option to enable 'snapping'.
/// Defaults to: <c>0</c>
/// </summary>
public JsNumber increment;
/// <summary>
/// How many units to change the Slider when adjusting with keyboard navigation. If the increment
/// config is larger, it will be used instead.
/// Defaults to: <c>1</c>
/// </summary>
public JsNumber keyIncrement;
/// <summary>
/// The maximum value for the Slider.
/// Defaults to: <c>100</c>
/// </summary>
public JsNumber maxValue;
/// <summary>
/// The minimum value for the Slider.
/// Defaults to: <c>0</c>
/// </summary>
public JsNumber minValue;
/// <summary>
/// A function used to display custom text for the slider tip.
/// Defaults to null, which will use the default on the plugin.
/// </summary>
public System.Delegate tipText;
/// <summary>
/// True to use an Ext.slider.Tip to display tips for the value. This option may also
/// provide a configuration object for an Ext.slider.Tip.
/// Defaults to: <c>true</c>
/// </summary>
public object useTips;
/// <summary>
/// Array of Number values with which to initalize the slider. A separate slider thumb will be created for each value
/// in this array. This will take precedence over the single value config.
/// </summary>
public JsNumber values;
/// <summary>
/// Orient the Slider vertically rather than horizontally.
/// Defaults to: <c>false</c>
/// </summary>
public bool vertical;
/// <summary>
/// Set to true to calculate snap points based on increments from zero as opposed to
/// from this Slider's minValue.
/// By Default, valid snap points are calculated starting <see cref="Ext.slider.MultiConfig.increment">increment</see>s from the <see cref="Ext.slider.MultiConfig.minValue">minValue</see>
/// Defaults to: <c>false</c>
/// </summary>
public bool zeroBasedSnapping;
public MultiConfig(params object[] args){}
}
#endregion
#region MultiEvents
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class MultiEvents : Ext.form.field.BaseEvents
{
/// <summary>
/// Fires before the slider value is changed. By returning false from an event handler, you can cancel the
/// event and prevent the slider from changing.
/// </summary>
/// <param name="slider"><p>The slider</p>
/// </param>
/// <param name="newValue"><p>The new value which the slider is being changed to.</p>
/// </param>
/// <param name="oldValue"><p>The old value which the slider was previously.</p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void beforechange(Multi slider, JsNumber newValue, JsNumber oldValue, object eOpts){}
/// <summary>
/// Fires when the slider value is changed by the user and any drag operations have completed.
/// </summary>
/// <param name="slider"><p>The slider</p>
/// </param>
/// <param name="newValue"><p>The new value which the slider has been changed to.</p>
/// </param>
/// <param name="thumb"><p>The thumb that was changed</p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void changecomplete(Multi slider, JsNumber newValue, Thumb thumb, object eOpts){}
/// <summary>
/// Fires continuously during the drag operation while the mouse is moving.
/// </summary>
/// <param name="slider"><p>The slider</p>
/// </param>
/// <param name="e"><p>The event fired from <see cref="Ext.dd.DragTracker">Ext.dd.DragTracker</see></p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void drag(Multi slider, EventObject e, object eOpts){}
/// <summary>
/// Fires after the drag operation has completed.
/// </summary>
/// <param name="slider"><p>The slider</p>
/// </param>
/// <param name="e"><p>The event fired from <see cref="Ext.dd.DragTracker">Ext.dd.DragTracker</see></p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void dragend(Multi slider, EventObject e, object eOpts){}
/// <summary>
/// Fires after a drag operation has started.
/// </summary>
/// <param name="slider"><p>The slider</p>
/// </param>
/// <param name="e"><p>The event fired from <see cref="Ext.dd.DragTracker">Ext.dd.DragTracker</see></p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void dragstart(Multi slider, EventObject e, object eOpts){}
public MultiEvents(params object[] args){}
}
#endregion
}
|
92b467b74764c92a0a7f98b24fcaddee6aa410a7
|
C#
|
ZumrudAliyeva/Final-project_Limak.az
|
/Repos/OrderRepository.cs
| 2.59375
| 3
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Limak.az.Contexts;
using Limak.az.Interfaces;
using Limak.az.Models;
using Limak.az.ViewModels;
namespace Limak.az.Repos
{
public class OrderRepository : IOrderRepository
{
private readonly LimakDbContext _context;
private readonly IMapper mapper;
public OrderRepository(LimakDbContext context, IMapper mapper)
{
_context = context;
this.mapper = mapper;
}
public async Task<bool> Create(OrderViewModel orderViewModel)
{
var order = mapper.Map<Order>(orderViewModel);
await _context.Orders.AddAsync(order);
var result = await _context.SaveChangesAsync() > 0;
return result;
}
public async Task Delete(int id)
{
var order = await _context.Orders.FindAsync(id);
_context.Orders.Remove(order);
await _context.SaveChangesAsync();
}
public async Task<Order> GetOrderById(int id)
{
var order = await _context.Orders.FindAsync(id);
return order;
}
//public bool Pay(int id, string userId)
//{
// var currencyId = 2;
// var order = _context.Orders.Find(id);
// if (order.CountryId == 2)
// {
// currencyId = 2;
// }
// else
// {
// currencyId = 3;
// }
// var result = false;
// var userbalance = _context.UserBalances.FirstOrDefault(x => x.UserId == userId && x.CurrencyId == currencyId);
// var balance = userbalance.Balance;
// var amount = order.PriceResult;
// if (order.OrderStatusId == 1)
// {
// if (amount <= balance)
// {
// order.OrderStatusId = 2;
// _context.Orders.Update(order);
// userbalance.Balance = balance - amount;
// _context.UserBalances.Update(userbalance);
// _context.SaveChanges();
// result = true;
// }
// }
// return result;
//}
}
}
|
4b7ecc12b7b737d7d207c3c6dbe747475cab6d4d
|
C#
|
diegomachado7/Comanda
|
/ComandaEletronica/Models/Produto.cs
| 2.578125
| 3
|
using ComandaEletronica.DAL;
using ComandaEletronica.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComandaEletronica.Models
{
internal class Produto
{
private int _produtoId;
private string _nome;
private string _descricao;
private string _valor;
internal int ProdutoId { get => _produtoId; set => _produtoId = value; }
internal string Nome { get => _nome; set => _nome = value; }
internal string Descricao { get => _descricao; set => _descricao = value; }
internal string Valor { get => _valor; set => _valor = value; }
internal List<Produto> ObterPorPalavraChave(string palavra)
{
if (palavra.Length > 0)
return new ProdutoDAO().ObterPorPalavraChave(palavra);
else
return null;
}
internal int Gravar()
{
if (_produtoId >= 0 && _nome.Length > 0)
return new ProdutoDAO().Gravar(this);
else
return -10;
}
internal Produto Obter(int id)
{
if (id > 0)
return new ProdutoDAO().Obter(id);
else
return null;
}
internal int Excluir(int id)
{
if (id > 0)
return new ProdutoDAO().Excluir(id);
else
return -10;
}
}
}
|
e3dd959911bf50405b330eb9468b2ae026a9f0fc
|
C#
|
sro-boeing-wave-2/hamming-distance-csharp-problem-Hrishi246
|
/Hamming/Hamming.cs
| 3.875
| 4
|
using System;
namespace Hamming
{
public class Hamming
{
public static int Distance(string original, string current)
{
int hammingDistance = 0;
if (original == null)
{
throw new ArgumentNullException("original");
}
if (current == null)
{
throw new ArgumentNullException("current");
}
if (original.Length != current.Length)
{
throw new ArgumentException("Hamming Distance can only be calculated over strings of equal length");
}
char[] set1 = original.ToCharArray();
char[] set2 = current.ToCharArray();
for (int i = 0; i < set1.Length; i++)
{
if (set1[i] != set2[i])
{
hammingDistance++;
}
}
return hammingDistance;
}
}
}
|
b9e83c746d4deb21a94c3410dac52d5551295866
|
C#
|
dTaba/ECommerceCanchasWeb
|
/TutuCanchas.DAO/CanchasTiposDAO.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TutuCanchas.DTO;
using System.Data;
using System.Data.SqlClient;
using TutuCanchas.DAO;
namespace TutuCanchas.DAO
{ //CRUD
public class CanchasTiposDAO
{
protected SqlConnection Conexion = new SqlConnection("Server=SQL5042.site4now.net;Database=DB_9CF8B6_Canchas;User Id=DB_9CF8B6_Canchas_admin;Password=huergo2019;");
SqlCommand Comando = new SqlCommand();
internal static string connectionString = @"Server=SQL5042.site4now.net;Database=DB_9CF8B6_Canchas;User Id=DB_9CF8B6_Canchas_admin;Password=huergo2019;";
public void Create(CanchasTiposDTO canchastipo)
{
string SQL_NuevoTipo = "insert into CanchasTipos values (" + canchastipo.Nombre + ")";
SqlConnection con = new SqlConnection();
con.ConnectionString = connectionString;
con.Open();
SqlCommand cmd = new SqlCommand(SQL_NuevoTipo, con);
cmd.ExecuteNonQuery();
con.Close();
}
public List<CanchasTiposDTO> ReadAll()
{
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(
"SELECT * FROM CanchasTipos " , DAOHelper.connectionString))
{
da.Fill(dt);
}
CanchasTiposDTO dto;
List<CanchasTiposDTO> lista = new List<CanchasTiposDTO>();
foreach (DataRow dr in dt.Rows)
{
dto = new CanchasTiposDTO();
if (!dr.IsNull("Id")) dto.Id = (int)dr["Id"];
if (!dr.IsNull("Nombre")) dto.Nombre = (string)dr["Nombre"];
lista.Add(dto);
}
return lista;
}
}
}
|
ac8eac662c57b53c98b8d1ce5a1cdd6779346cdc
|
C#
|
ericsebesta/unity-toolbelt
|
/Runtime/ExclusiveChooser.cs
| 2.765625
| 3
|
using UnityEngine;
namespace com.ericsebesta.toolbelt
{
/// <summary>
/// A behavior that ensures that exactly 1 (or 0 if no children) gameobjects are active. If at any point more than 1 child
/// is active, the first child will be preferred.
/// </summary>
/// This class functions along with the help of ExclusiveChooserChild class which this class automatically adds
/// to all children of this class. The helper class auto-removes itself if reparented.
[ExecuteAlways]
public class ExclusiveChooser : MonoBehaviour
{
//The currently chosen child gameobject
private GameObject m_chosenChild;
//Whether we are in the process of choosing an active child or not (necessary to prevent re-entry issues from callbacks).
private bool m_currentlyChoosing;
//handle an edge case with deactivating the first child. @see ReActivate
private GameObject m_reactivationTarget;
/// <summary>
/// Select the given child as the active chosen one, disable all others. If null, we'll choose the first child.
/// The result of any call to this method will be exactly 1 child being activated, unless there are no children.
/// </summary>
/// <param name="go">The gameobject to choose if found as a child. Can be null which means "choose the first child"</param>
public void ChooseChild(GameObject go)
{
if (m_currentlyChoosing)
return;
m_currentlyChoosing = true;
var foundSelection = false;
for (var i = 0; i < gameObject.transform.childCount; i++)
{
var child = gameObject.transform.GetChild(i);
if (go && child == go.transform)
{
var childGameObject = child.gameObject;
childGameObject.SetActive(true);
foundSelection = true;
m_chosenChild = childGameObject;
}
else
{
child.gameObject.SetActive(false);
}
}
if (!foundSelection && gameObject.transform.childCount > 0)
{
var child = gameObject.transform.GetChild(0);
var childGameObject = child.gameObject;
if (m_chosenChild == childGameObject)
{
//in this specific situation, we are re-activating the node we *think* was already active.
//Most likely, this means that the first child was requested to be deactivated (which logic dictates
//should be reactivated here). Doing so inline of the callstack requesting to DISable it will throw
//an error, so delay the reactivation to a future frame. This could probably be done later in the same
//frame rather than waiting until the next frame.
m_reactivationTarget = childGameObject;
Invoke(nameof(ReActivate), .05f);
}
else
{
childGameObject.SetActive(true);
}
m_chosenChild = childGameObject;
}
m_currentlyChoosing = false;
}
/// <summary>
/// When waking up, ensure that only the FIRST active child remains active, disable all others.
/// Also ensure that all children have the helper component.
/// </summary>
private void Awake()
{
GameObject childToSelect = null;
//choose the first active child
for (var i = 0; i < gameObject.transform.childCount; i++)
{
var child = gameObject.transform.GetChild(i);
if (child.gameObject.activeSelf)
{
childToSelect = child.gameObject;
break;
}
}
//add child component to all children
for (var i = 0; i < gameObject.transform.childCount; i++)
{
var child = gameObject.transform.GetChild(i);
if (!child.GetComponent<ExclusiveChooserChild>())
{
//adding components results in OnActivate called and we don't want to process it like a selection
m_currentlyChoosing = true;
child.gameObject.AddComponent<ExclusiveChooserChild>();
m_currentlyChoosing = false;
}
}
//select the first item (null is fine)
ChooseChild(childToSelect);
}
/// <summary>
/// When our children change, ensure that newly-added ones get the helper component, and ensure that only the
/// FIRST active child remains active.
/// </summary>
private void OnTransformChildrenChanged()
{
for (var i = 0; i < gameObject.transform.childCount; i++)
{
var child = gameObject.transform.GetChild(i);
if (!child.GetComponent<ExclusiveChooserChild>())
{
//adding components results in OnActivate called and we don't want to process it like a selection
m_currentlyChoosing = true;
child.gameObject.AddComponent<ExclusiveChooserChild>();
m_currentlyChoosing = false;
}
}
//we may have removed the only active child, or we may have added a second active child. Resolve this.
ChooseChild(m_chosenChild ? m_chosenChild : null);
}
/// <summary>
/// This method exists to handle an edge case of deactivating the first child, which should re-enable it.
/// This will cause an error if we directly call SetActive(true) within the handling of OnDisable. So we delay
/// the call and handle it here.
/// </summary>
private void ReActivate()
{
m_reactivationTarget.SetActive(true);
m_reactivationTarget = null;
}
}
}
|
686a723da7b912571dec81d70287906579cb4443
|
C#
|
cookgreen/TaleworldsProductSerialKeyVerifier
|
/ModProfile.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TaleworldsProductSerialKeyVerifier
{
public class ModProfile
{
private string gameRunPath;
public string Name { get; set; }
public string DisplayName { get; set; }
public string ModID { get; set; }
public Scenario RequireDLC { get; set; }
public string Key { get; set; }
public ModProfile(string profileFullPath, string gameRunPath)
{
this.gameRunPath = gameRunPath;
parseProfile(profileFullPath);
}
public ModProfile(string gameRunPath)
{
this.gameRunPath = gameRunPath;
}
private void parseProfile(string profileFullPath)
{
using (StreamReader reader = new StreamReader(profileFullPath))
{
while (reader.Peek() > -1)
{
string line = reader.ReadLine();
string[] tokens = line.Split('=');
string key = tokens[0].Trim();
switch (key)
{
case "Name":
Name = tokens[1].Trim();
break;
case "DisplayName":
DisplayName = tokens[1].Trim();
break;
case "ModID":
ModID = tokens[1].Trim();
break;
case "RequireDLC":
RequireDLC = (Scenario)Enum.Parse(typeof(Scenario), tokens[1].Trim());
break;
case "Key":
Key = tokens[1].Trim();
break;
}
}
}
}
public void Start()
{
}
}
}
|
95693cdc38111775fd72ce6d462ffe10e8f8135f
|
C#
|
crocomoth/NET.S.2018.Popivnenko.Test
|
/Task1.Solution/Service/PasswordCheckerSevice.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Task1.Solution.Interface;
using Task1.Solution.Model;
namespace Task1.Solution.Service
{
public class PasswordCheckerSevice : IPasswordChecker
{
private IRepository repository;
public PasswordCheckerSevice(IRepository repository)
{
this.repository = repository ?? throw new ArgumentNullException(nameof(repository));
}
public Tuple<bool, string> VerifyPassword(string password, User user)
{
// user will be created after password creation
// for it is only a placeholder (no password etc. but already has a Role
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
if (password == null)
throw new ArgumentNullException(nameof(password));
if (password == string.Empty)
return Tuple.Create(false, $"{nameof(password)} is empty ");
// check if length more than 7 chars
if (password.Length <= 7)
return Tuple.Create(false, $"{nameof(password)} length too short");
if (user.Role == Role.Admin)
{
if (password.Length <= 10)
{
return Tuple.Create(false, $"{nameof(password)} length too short for admin");
}
}
// check if length more than 10 chars for admins
if (password.Length >= 15)
return Tuple.Create(false, $"{password} length too long");
// check if password conatins at least one alphabetical character
if (!password.Any(char.IsLetter))
return Tuple.Create(false, $"{password} hasn't alphanumerical chars");
// check if password conatins at least one digit character
if (!password.Any(char.IsNumber))
return Tuple.Create(false, $"{password} hasn't digits");
repository.Create(password);
user.Password = password;
return Tuple.Create(true, "Password is Ok. User was created");
}
}
}
|
00aab161a886999b2401028b36c92957bf00d72a
|
C#
|
Lak5han/EventManagmentapp
|
/Eventmanagement/DataBaseOperatios/ApplicationLevelDataBaseOps.cs
| 2.71875
| 3
|
using DataLayer;
using ExceptionLogging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Eventmanagement.DataBaseOperatios
{
public class ApplicationLevelDataBaseOps
{
private EventmanagementDbContext db = new EventmanagementDbContext();
/// <summary>
/// Get user detail by user name this will use in different places in the application
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public User GetUserDetailByUserName(string username)
{
User userdetails = new User();
try
{
userdetails = db.Users.First(c => c.UserName == username);
}
catch (Exception ex)
{
ExceptionTracker.SendErrorToText(ex);
}
return userdetails;
}
/// <summary>
/// This will use in different places in the application and userrole will return user details and role details
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public UserRole GetUserRolebyUserID(int userID)
{
UserRole userdetails = new UserRole();
try
{
userdetails = db.UserRoles.First(c => c.User.UserID == userID);
}
catch (Exception ex)
{
ExceptionTracker.SendErrorToText(ex);
}
return userdetails;
}
public List<EventDetail> GetAllEventDetail()
{
List<EventDetail> listofEvents = new List<EventDetail>();
try
{
listofEvents = db.EventDetails.ToList();
}
catch (Exception ex)
{
ExceptionTracker.SendErrorToText(ex);
}
return listofEvents;
}
public List<Collage> GetAllCollage()
{
List<Collage> listofCollage = new List<Collage>();
try
{
listofCollage = db.Collages.ToList();
}
catch (Exception ex)
{
ExceptionTracker.SendErrorToText(ex);
}
return listofCollage;
}
}
}
|
c926e95427fde2397d1315f9432432da604165fc
|
C#
|
miggello/pluralsight
|
/Sandbox/Program.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
class Program
{
static void Main()
{
Logger logger = new Logger();
WriterDelegate writer = new WriterDelegate(logger.WriteMessage);
writer("This is NOT A TEST!!!");
}
}
public class Logger
{
public void WriteMessage(String message)
{
Console.WriteLine(message);
}
}
}
|
91f9aa3f90c75ca07e4cac90929d5037d0de7893
|
C#
|
sharparchitecture/Sharp-Architecture
|
/Src/Tests/SharpArch.XunitTests/SharpArch.Domain/DomainModel/BaseObjectEqualityComparerTests.cs
| 2.703125
| 3
|
// ReSharper disable UnusedAutoPropertyAccessor.Local
namespace Tests.SharpArch.Domain.DomainModel
{
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentAssertions;
using global::SharpArch.Domain.DomainModel;
using global::SharpArch.Testing.Helpers;
using Xunit;
public class BaseObjectEqualityComparerTests
{
class ConcreteBaseObject : BaseObject
{
public string Name { get; set; } = null!;
protected override PropertyInfo[] GetTypeSpecificSignatureProperties()
{
return GetType().GetProperties();
}
}
class ConcreteEntityWithDomainSignatureProperties : Entity<int>
{
[DomainSignature]
public string Name { get; set; } = null!;
}
class ConcreteEntityWithNoDomainSignatureProperties : Entity<int>
{
public string Name { get; set; } = null!;
}
class ConcreteValueObject : ValueObject
{
public string Name { get; set; } = null!;
}
[Fact]
public void CanBeUsedByLinqSetOperatorsSuchAsIntersect()
{
IList<ConcreteEntityWithDomainSignatureProperties> objects1 =
new List<ConcreteEntityWithDomainSignatureProperties>();
var obj1 = new ConcreteEntityWithDomainSignatureProperties {Name = @"Billy McCafferty"};
EntityIdSetter.SetIdOf(obj1, 2);
objects1.Add(obj1);
IList<ConcreteEntityWithDomainSignatureProperties> objects2 =
new List<ConcreteEntityWithDomainSignatureProperties>();
var obj2 = new ConcreteEntityWithDomainSignatureProperties {Name = @"Jimi Hendrix"};
EntityIdSetter.SetIdOf(obj2, 1);
objects2.Add(obj2);
var obj3 = new ConcreteEntityWithDomainSignatureProperties
{
Name =
"Doesn't Matter since the Id will match and the presence of the domain signature will go overridden"
};
EntityIdSetter.SetIdOf(obj3, 2);
objects2.Add(obj3);
objects1.Intersect(
objects2, new BaseObjectEqualityComparer<ConcreteEntityWithDomainSignatureProperties>())
.Should().HaveCount(1);
objects1.Intersect(
objects2, new BaseObjectEqualityComparer<ConcreteEntityWithDomainSignatureProperties>()).First()
.Equals(obj1).Should().BeTrue();
objects1.Intersect(
objects2, new BaseObjectEqualityComparer<ConcreteEntityWithDomainSignatureProperties>()).First()
.Equals(obj3).Should().BeTrue();
}
[Fact]
public void CanCompareBaseObjects()
{
var comparer = new BaseObjectEqualityComparer<BaseObject>();
var obj1 = new ConcreteBaseObject {Name = "Whatever"};
var obj2 = new ConcreteBaseObject {Name = "Whatever"};
comparer.Equals(obj1, obj2).Should().BeTrue();
obj2.Name = "Mismatch";
comparer.Equals(obj1, obj2).Should().BeFalse();
}
[Fact]
public void CanCompareEntitiesWithDomainSignatureProperties()
{
var comparer = new BaseObjectEqualityComparer<Entity<int>>();
var obj1 = new ConcreteEntityWithDomainSignatureProperties {Name = "Whatever"};
var obj2 = new ConcreteEntityWithDomainSignatureProperties {Name = "Whatever"};
comparer.Equals(obj1, obj2).Should().BeTrue();
obj2.Name = "Mismatch";
comparer.Equals(obj1, obj2).Should().BeFalse();
EntityIdSetter.SetIdOf(obj1, 1);
EntityIdSetter.SetIdOf(obj2, 1);
comparer.Equals(obj1, obj2).Should().BeTrue();
}
[Fact]
public void CanCompareEntitiesWithNoDomainSignatureProperties()
{
var comparer = new BaseObjectEqualityComparer<BaseObject>();
var obj1 = new ConcreteEntityWithNoDomainSignatureProperties {Name = "Whatever"};
var obj2 = new ConcreteEntityWithNoDomainSignatureProperties {Name = @"asdf"};
comparer.Equals(obj1, obj2).Should().BeFalse();
EntityIdSetter.SetIdOf(obj1, 1);
EntityIdSetter.SetIdOf(obj2, 1);
comparer.Equals(obj1, obj2).Should().BeTrue();
}
[Fact]
public void CanCompareNulls()
{
var comparer = new BaseObjectEqualityComparer<BaseObject>();
comparer.Equals(null, null).Should().BeTrue();
comparer.Equals(null, new ConcreteBaseObject()).Should().BeFalse();
comparer.Equals(new ConcreteBaseObject(), null).Should().BeFalse();
}
[Fact]
public void CanCompareValueObjects()
{
var comparer = new BaseObjectEqualityComparer<BaseObject>();
var obj1 = new ConcreteValueObject {Name = "Whatever"};
var obj2 = new ConcreteValueObject {Name = "Whatever"};
comparer.Equals(obj1, obj2).Should().BeTrue();
obj2.Name = "Mismatch";
comparer.Equals(obj1, obj2).Should().BeFalse();
}
[Fact]
public void CannotSuccessfullyCompareDifferentlyTypedObjectsThatDeriveFromBaseObject()
{
var comparer = new BaseObjectEqualityComparer<BaseObject>();
var obj1 = new ConcreteBaseObject {Name = "Whatever"};
var obj2 = new ConcreteValueObject {Name = "Whatever"};
comparer.Equals(obj1, obj2).Should().BeFalse();
}
}
}
|
8c84db0ff4b41ff18bc5183f8ff87ee1abd7fefc
|
C#
|
CloudDevStudios/SkillSystemUnity
|
/Assets/SkillTreeSystem/Language/SkillConditionTokenizer.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityScript.Parser;
namespace Assets.SkillTreeSystem.Language
{
public static class SkillConditionTokenizer
{
public static List<SkillConditionToken> Tokenize(string unprocessedText)
{
var result = new List<SkillConditionToken>();
var textToken = new SkillConditionToken(SkillConditionTokenType.TextOrNumber);
var text = unprocessedText.Replace("\t", string.Empty).Replace(" ", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty);
for (int i = 0; i < text.Length; i++)
{
switch(text[i])
{
case '&':
PopulizeTextToken(textToken, result);
textToken = new SkillConditionToken(SkillConditionTokenType.TextOrNumber);
result.Add(new SkillConditionToken(SkillConditionTokenType.And, "&"));
break;
case '|':
PopulizeTextToken(textToken, result);
textToken = new SkillConditionToken(SkillConditionTokenType.TextOrNumber);
result.Add(new SkillConditionToken(SkillConditionTokenType.Or, "|"));
break;
case '[':
PopulizeTextToken(textToken, result);
textToken = new SkillConditionToken(SkillConditionTokenType.TextOrNumber);
result.Add(new SkillConditionToken(SkillConditionTokenType.SquareBracketOpen, "["));
break;
case ']':
PopulizeTextToken(textToken, result);
textToken = new SkillConditionToken(SkillConditionTokenType.TextOrNumber);
result.Add(new SkillConditionToken(SkillConditionTokenType.SquareBracketClose, "["));
break;
case '(':
PopulizeTextToken(textToken, result);
textToken = new SkillConditionToken(SkillConditionTokenType.TextOrNumber);
result.Add(new SkillConditionToken(SkillConditionTokenType.RoundBracketOpen, "("));
break;
case ')':
PopulizeTextToken(textToken, result);
textToken = new SkillConditionToken(SkillConditionTokenType.TextOrNumber);
result.Add(new SkillConditionToken(SkillConditionTokenType.RoundBracketClose, ")"));
break;
case ',':
PopulizeTextToken(textToken, result);
textToken = new SkillConditionToken(SkillConditionTokenType.TextOrNumber);
result.Add(new SkillConditionToken(SkillConditionTokenType.Comma, ","));
break;
case ':':
PopulizeTextToken(textToken, result);
textToken = new SkillConditionToken(SkillConditionTokenType.TextOrNumber);
result.Add(new SkillConditionToken(SkillConditionTokenType.DoubleDot, ":"));
break;
default:
textToken.Value += text[i];
break;
}
}
PopulizeTextToken(textToken, result);
return result;
}
private static void PopulizeTextToken(SkillConditionToken textToken, List<SkillConditionToken> result)
{
if (!string.IsNullOrEmpty(textToken.Value))
{
result.Add(textToken);
}
}
}
}
|
ead342656ef08bd7b736a43e649b270452ce21ba
|
C#
|
expcat/DotNetSamples
|
/Rabbit.ConsoleApp/Headers.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace Rabbit.ConsoleApp
{
public class Headers
{
private static readonly string exchange = "headersexchange";
public static void HeadersPublish(ConnectionFactory factory)
{
Console.WriteLine(" Press [enter] to begin.");
Console.ReadLine();
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
var headers_0 = new Dictionary<string, object>() { { "name", "rabbit" }, { "bit", "true" } };
var headers_1 = new Dictionary<string, object>() { { "name", "rabbit" }, { "bit", "false" } };
for (int i = 0; i < 10; i++)
{
var body = Encoding.UTF8.GetBytes("hello " + i);
var prop = channel.CreateBasicProperties();
prop.Headers = i % 2 == 0 ? headers_0 : headers_1;
channel.BasicPublish(exchange, string.Empty, prop, body);
// Console.WriteLine("Sent: {0}", message);
}
}
Console.WriteLine(" Press [Ctrl + C] to exit.");
}
public static void HeadersReceive(ConnectionFactory factory, string index, bool isAny)
{
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
channel.ExchangeDeclare(exchange, ExchangeType.Topic, false, false, null);
string queue = "headersqueue_" + index;
channel.QueueDeclare(queue, false, false, false, null);
string match = isAny ? "any" : "all";
channel.QueueBind(queue, exchange, string.Empty, new Dictionary<string, object>() { { "x-match", match }, { "name", "rabbit" }, { "bit", "true" } });
EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var message = Encoding.UTF8.GetString(ea.Body);
Console.WriteLine("[{0}] Received {1}", index, message);
};
channel.BasicConsume(queue, true, consumer);
Console.WriteLine("{0} receive started.", queue);
Thread.Sleep(Timeout.Infinite);
}
}
}
}
|
4ad09820368f354fd1b583a5cbdccdfbbe2ac730
|
C#
|
mfmese/FileUploaderWebApi
|
/FileUploader.Infrastructure/Repositories/FileUploadRepository.cs
| 2.515625
| 3
|
using FileUploader.Domain.Models;
using FileUploader.Domain.Ports;
using FileUploader.Infrastructure.Contexts;
using FileUploader.Infrastructure.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace FileUploader.Infrastructure.Repositories
{
internal class FileUploadRepository : IFileUploadPort
{
private readonly FileUploadDataContext _fileUploadDataContext;
private readonly ILogPort _log;
public FileUploadRepository(FileUploadDataContext fileUploadDataContext, ILogPort log)
{
_fileUploadDataContext = fileUploadDataContext;
_log = log;
}
public async Task<GetFilesResponse> GetAllFilesAsync()
{
var response = new GetFilesResponse();
try
{
var fileInfos = await _fileUploadDataContext.FileInfos.ToListAsync();
response.Data = fileInfos.Map();
response.SetSuccess();
return response;
}
catch (Exception ex)
{
response.Data = null;
response.SetError("Error occured while getting files");
await _log.InsertLogAsync("Error occured while getting files", ex);
return response;
}
}
public async Task<FileUploadResponse> CreateFileAsync(FileUploader.Domain.Models.FileInfo file)
{
var response = new FileUploadResponse();
try
{
var isFileExists = _fileUploadDataContext.FileInfos.Any(x => x.FileName == file.FileName);
if(isFileExists)
{
response.Data.IsFileUploaded = false;
response.SetError("File name already exists",null, file.FileName);
return response;
}
var path = AppDomain.CurrentDomain.BaseDirectory + "fileUploads\\";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
using (FileStream fileStream = File.Create(path + file.FileName))
{
MemoryStream stream = new MemoryStream(file.FileContent);
stream.CopyTo(fileStream);
fileStream.Flush();
}
var fileInfoEntity = new Entities.FileInfo
{
FileName = file.FileName,
FileSize = file.FileSize,
FileType = file.FileType,
UploadedDate = DateTime.Now
};
_fileUploadDataContext.Add(fileInfoEntity);
bool result = await _fileUploadDataContext.SaveChangesAsync() > 0;
response.Data.IsFileUploaded = result;
response.SetSuccess();
return response;
}
catch (Exception ex)
{
response.Data.IsFileUploaded = false;
response.SetError("Error occured while uploading file", ex, file.FileName);
return response;
}
}
}
}
|
a4f1340908cc1833bf8c77aa94f0db3972430ed2
|
C#
|
Henriquedevb/foccoEmFrente
|
/src/FoccoEmFrente.Kanban.Application/Services/ActivityServices.cs
| 2.6875
| 3
|
using FoccoEmFrente.Kanban.Application.Entities;
using FoccoEmFrente.Kanban.Application.Repositories;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace FoccoEmFrente.Kanban.Application.Services
{
public class ActivityServices : IActivityServices
{
private readonly IActivityRepository _activityRepository;
public ActivityServices(IActivityRepository activityRepository)
{
_activityRepository = activityRepository;
}
public async Task<IEnumerable<Activity>> GetAllAsync(Guid userId)
{
return await _activityRepository.GetAllAsync(userId);
}
public async Task<Activity> GetByIdAsync(Guid id, Guid userId)
{
return await _activityRepository.GetByIdAsync(id, userId);
}
public async Task<bool> ExistAsync(Guid id, Guid userId)
{
return await _activityRepository.ExistAsync(id, userId);
}
public async Task<Activity> AddAsync(Activity activity)
{
var newActivity = _activityRepository.Add(activity);
await _activityRepository.UnitOfWorks.CommitAsync();
return newActivity;
}
public async Task<Activity> UpdateAsync(Activity activity)
{
var activitieExists = await ExistAsync(activity.Id, activity.UserId);
if (!activitieExists)
throw new Exception("Atividade não pode ser encontrada.");
var updateActivity = _activityRepository.Update(activity);
await _activityRepository.UnitOfWorks.CommitAsync();
return updateActivity;
}
public async Task<Activity> RemoveAsync(Activity activity)
{
var activitieExists = await ExistAsync(activity.Id, activity.UserId);
if (!activitieExists)
throw new Exception("Atividade não pode ser encontrada.");
var removeActivity = _activityRepository.Remove(activity);
await _activityRepository.UnitOfWorks.CommitAsync();
return removeActivity;
}
public async Task<Activity> RemoveAsync(Guid id, Guid userId)
{
var activityToBeRemoved = await GetByIdAsync(id, userId);
if (activityToBeRemoved == null)
throw new Exception("Atividade não pode ser encontrada.");
var removeActivity = _activityRepository.Remove(activityToBeRemoved);
await _activityRepository.UnitOfWorks.CommitAsync();
return removeActivity;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
}
|
ab39694606a306fed887085691ed22363f0b1290
|
C#
|
AnnaFrank17/EPAM
|
/GenericCollection/UnitTestStack/UnitTest1.cs
| 2.8125
| 3
|
using System;
using GenericCollection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestStack
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Stack<int> stack = new Stack<int>(8);
stack.Push(45);
Assert.AreEqual(1, stack.Count);
}
[TestMethod]
public void Pop()
{
Stack<int> stack = new Stack<int>(8);
stack.Push(45);
Assert.AreEqual(45, stack.Pop());
Assert.AreEqual(0, stack.Count);
}
}
}
|
d502865cc5d41cbae4e30afcf91b9b3d5448f0b7
|
C#
|
evd0kim/PrivateNotes
|
/PrivateNotesAddin/PasswordEntry.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Mono.Unix;
namespace Tomboy.PrivateNotes
{
/// <summary>
/// utility class that is able to display a password-entry
/// dialog, while the sync process is running.
/// not that straightforward, because we are running in a separate
/// thread (the sync-thread) and not the gui thread, so we have to
/// take care of that
/// </summary>
public class PasswordEntry : Gtk.Dialog
{
AutoResetEvent autoReset;
Gtk.Entry pw;
Gtk.Entry pw2;
Gtk.Label match_label;
public PasswordEntry()
{
autoReset = new AutoResetEvent(false);
Title = Catalog.GetString("Please enter the password");
Gtk.VBox pwbox = new Gtk.VBox(false, 6);
pwbox.PackStart(new Gtk.Label(Catalog.GetString("Please enter the password:")), true, true, 6);
pw = new Gtk.Entry();
// set password style:
pw.InvisibleChar = '*';
pw.Visibility = false;
pw.Text = "";
pwbox.PackStart(pw);
pw2 = new Gtk.Entry();
// set password style:
pw2.InvisibleChar = '*';
pw2.Visibility = false;
pw2.Text = "";
pwbox.PackStart(pw2);
pw.Changed += PasswordChanged;
pw2.Changed += PasswordChanged;
match_label = new Gtk.Label();
match_label.Markup = Catalog.GetString(AddinPreferences.MATCH_TEXT);
pwbox.PackStart(match_label);
Gtk.Button button = (Gtk.Button)AddButton(Gtk.Stock.Ok, Gtk.ResponseType.Ok);
button.CanDefault = true;
//button.Show();
pwbox.PackStart(button);
//this.VBox.PackStart(button);
Gtk.AccelGroup accel_group = new Gtk.AccelGroup();
AddAccelGroup(accel_group);
button.AddAccelerator("activate",
accel_group,
(uint)Gdk.Key.Escape,
0,
0);
AddActionWidget(button, Gtk.ResponseType.Ok);
DefaultResponse = Gtk.ResponseType.Ok;
accel_group.AccelActivate += OnAction;
Response += OnResponse;
DeleteEvent += new Gtk.DeleteEventHandler(PasswordEntry_DeleteEvent);
pwbox.ShowAll();
this.VBox.PackStart(pwbox);
// show() must happen on ui thread
Gtk.Application.Invoke(RunInUiThread);
}
/// <summary>
/// used to show the dialog via the UI-Thread
/// </summary>
/// <param name="sender"></param>
/// <param name="ea"></param>
public void RunInUiThread(object sender, EventArgs ea)
{
Present();
}
public void PasswordChanged(object sender, EventArgs args)
{
if (pw.Text.Equals(pw2.Text))
{
match_label.Markup = Catalog.GetString(AddinPreferences.MATCH_TEXT);
}
else
{
match_label.Markup = Catalog.GetString(AddinPreferences.MATCH_NOT_TEXT);
}
}
/// <summary>
/// waits for a correct password to be put in
/// </summary>
/// <param name="o"></param>
/// <param name="args"></param>
public void OnAction(object o, Gtk.AccelActivateArgs args)
{
if (pw.Text.Equals(pw2.Text))
{
// action
autoReset.Set();
Hide();
}
}
// forward other events
public void OnResponse(object o, Gtk.ResponseArgs args) {
OnAction(null, null);
}
// forward other events
// react to the [x]-button being pressed
void PasswordEntry_DeleteEvent(object o, Gtk.DeleteEventArgs args)
{
OnAction(null, null);
}
/// <summary>
/// returns the password that was entered
/// WARNING: after you called this, the gui of this object cannot be reused! (because
/// destory is called)
/// </summary>
/// <returns>the password that was entered</returns>
public String getPassword()
{
String password = null;
autoReset.WaitOne();
password = pw.Text;
// dispose the gui thigns
pw.Text = "";
pw2.Text = "";
Destroy();
return password;
}
}
}
|