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
|
|---|---|---|---|---|---|---|
dca1498b089b6f2b84e6fe01eed0ceffb3980d70
|
C#
|
marcelltoth/ObjectCloner
|
/tests/ObjectCloner.Tests/DeepClone/PolymorphismTests.cs
| 3.03125
| 3
|
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace ObjectCloner.Tests.DeepClone
{
public class PolymorphismTests
{
[Fact]
public void DeepClonesByInterface()
{
TestClassTwo innerData = new TestClassTwo(42);
TestClass original = new TestClass(innerData);
TestClass clone = ObjectCloner.DeepClone(original);
Assert.NotSame(clone.TestListPolymorphic, original.TestListPolymorphic);
Assert.NotSame(clone.TestListPolymorphic.Last(), original.TestListPolymorphic.Last());
Assert.Equal(clone.TestListPolymorphic.Last().SomeProp, original.TestListPolymorphic.Last().SomeProp);
}
private class TestClass
{
public TestClass(params TestClassTwo[] testData)
{
TestListPolymorphic = testData;
}
public IEnumerable<TestClassTwo> TestListPolymorphic { get; }
}
private class TestClassTwo
{
public TestClassTwo(int someProp)
{
SomeProp = someProp;
}
public int SomeProp { get; }
}
}
}
|
75809a3d331c9b6410d1228dfc7c5c7d20902d3a
|
C#
|
Brianspha/RUTimetable
|
/RUTimetable/RUTimetable/Classes/NameRemover.cs
| 2.90625
| 3
|
using System;
namespace RUTimetable
{
class NameRemover
{
string venueLocation;
public NameRemover(string venueLocation)
{
this.venueLocation = venueLocation;
}
internal string Process()
{
int index = 0;
var temp = "";
while (venueLocation[index++] != ':') ;
index++;
while (venueLocation.Length > index) { if (venueLocation[index] == '"') { index++; continue; } temp += venueLocation[index++]; }
return temp;
}
}
}
|
6e1d61722721d4f2e9a332e3cd460e49e8ab9589
|
C#
|
Deldeldeldel/Items
|
/Items/Controllers/ItemApiController.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Items.Models;
namespace Items.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ItemApiController : ControllerBase
{
private readonly ItemdataContext _context;
// koska konstrukri vaatii parametrin, joka tulee ulkopuolelta, on laitettava connection string startup.cssään
public ItemApiController(ItemdataContext context)
{
_context = context;
}
// GET: api/ItemApi
[HttpGet]
public List<Item> GetItem() //IEnumerable
{
ItemdataContext context = new ItemdataContext();
List<Item> all = _context.Item.ToList();
return all;
//return _context.Item; alkuperäinen
}
// GET: api/ItemApi/5
[HttpGet("{id}")]
public async Task<IActionResult> GetItem([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var item = await _context.Item.FindAsync(id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
// PUT: api/ItemApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutItem([FromRoute] int id, [FromBody] Item item)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != item.ItemId)
{
return BadRequest();
}
_context.Entry(item).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ItemExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/ItemApi
[HttpPost]
public async Task<IActionResult> PostItem([FromBody] Item item)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Item.Add(item);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (ItemExists(item.ItemId))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtAction("GetItem", new { id = item.ItemId }, item);
}
// DELETE: api/ItemApi/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteItem([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var item = await _context.Item.FindAsync(id);
if (item == null)
{
return NotFound();
}
_context.Item.Remove(item);
await _context.SaveChangesAsync();
return Ok(item);
}
private bool ItemExists(int id)
{
return _context.Item.Any(e => e.ItemId == id);
}
}
}
|
3c32580140cdb4fe90565531a7a2b05459c1bb45
|
C#
|
vlad0696/oop3
|
/ООП_3/OOP_3/OOP_3/Serialization.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
namespace OOP_3
{
public interface Serialize
{
void Serialize(List<food> FoodList, string fileName);
List<food> Deserialize(string fileName);
}
public class SerializationXML : Serialize
{
List<food> Serialize.Deserialize(string fileName)
{
food[] FoodArr;
List<food> f = new List<food>();
XmlSerializer xml = new XmlSerializer(typeof(food[]));
using (var fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
{
try
{
FoodArr = (food[])xml.Deserialize(fStream);
return FoodArr.ToList<food>();
}
catch
{
MessageBox.Show("Неверный тип файла");
}
return f;
}
}
void Serialize.Serialize(List<food> FoodList, string fileName)
{
XmlSerializer xml = new XmlSerializer(typeof(food[]));
using (var fStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
xml.Serialize(fStream, FoodList.ToArray());
}
}
}
public class SerializationBin : Serialize
{
public void Serialize(List<food> jewList, string fileName)
{
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
{
formatter.Serialize(fs, jewList);
}
}
public List<food> Deserialize(string fileName)
{
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
{
return (List<food>)formatter.Deserialize(fs);
}
}
}
public class SerializationTxt : Serialize
{
public Dictionary<string, FoodFactory> ListFoodFactory = new Dictionary<string, FoodFactory>();
void FFactory()
{
ListFoodFactory.Add("Молочная продукция", new MilckFactory());
ListFoodFactory.Add("Мясные изделия", new MeatFactory());
ListFoodFactory.Add("Бакалея", new GroceryFactory());
ListFoodFactory.Add("Мучные продукты ", new FlourFactory());
ListFoodFactory.Add("Напитки", new BeveragesFactory());
ListFoodFactory.Add("Консервы", new ConserveFacotry());
}
public List<food> Deserialize(string fileName)
{
List<food> ListFood = new List<food>();
FFactory();
string[] lines = File.ReadAllLines(fileName);
foreach (string info in lines)
{
string[] Properties = info.Split(new char[] { '_' });
if (Properties[0] != "Консервы")
{
ListFood.Add(ListFoodFactory[(Properties[0])].GetFood());
ListFood[ListFood.Count - 1].StringProperty = info;
ListFood[ListFood.Count - 1].SetMainProperties(Properties);
ListFood[ListFood.Count - 1].SetIntemediate(Properties);
ListFood[ListFood.Count - 1].SetProperties(Properties);
}
else
{
Properties = info.Split(new char[] { '_' });
ListFood.Add(ListFoodFactory[(Properties[0])].GetFood());
ListFood[ListFood.Count - 1].StringProperty = info;
}
}
return ListFood;
}
public void Serialize(List<food> FoodList, string fileName)
{
using (StreamWriter file = new StreamWriter(fileName))
{
foreach (food f in FoodList)
{
if (f.ClassName() != "Консервы")
{
file.WriteLine(f.StringProperty);
}
else
{
Conserve conserve = new Conserve();
conserve = (Conserve)f;
file.WriteLine(conserve.StringProperty + "$" + conserve.MeatConserve.StringProperty + "$" + conserve.GroceryConserve.StringProperty);
}
}
}
}
}
}
|
91d4ae13132c48661ef9f755c553b567c4230751
|
C#
|
cofl/SnipeSharp
|
/SnipeSharp/Models/Enumerations/AvailableAction.cs
| 2.796875
| 3
|
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Runtime.Serialization;
namespace SnipeSharp.Models.Enumerations
{
/// <summary>
/// Members of this enumeration are operations that may be performed through the API.
/// </summary>
/// <seealso cref="IAvailableActions"/>
[JsonConverter(typeof(StringEnumConverter))]
[Flags]
public enum AvailableAction
{
/// <summary>There are no available actions.</summary>
None = 0,
/// <summary>The associated object may be checked out.</summary>
[EnumMember(Value = "checkout")]
CheckOut = 1,
/// <summary>The associated object may be checked in.</summary>
[EnumMember(Value = "checkin")]
CheckIn = 2,
/// <summary>The associated object may be cloned.</summary>
[EnumMember(Value = "clone")]
Clone = 4,
/// <summary>The associated object may be deleted from the database.</summary>
/// <remarks>Deleting may not be a full deletion, but merely an assigning of the "Deleted" status.</remarks>
[EnumMember(Value = "delete")]
Delete = 8,
/// <summary>The associated object may be restored.</summary>
[EnumMember(Value = "restore")]
Restore = 16,
/// <summary>The associated object may have its properties set and updated.</summary>
[EnumMember(Value = "update")]
Update = 32,
/// <summary>The associated object may be requested.</summary>
[EnumMember(Value = "request")]
Request = 64,
/// <summary>The associated request may be canceled.</summary>
[EnumMember(Value = "cancel")]
CancelRequest = 128,
}
}
|
a4dbd8dbe86235771b95a045830e05adca5d6671
|
C#
|
MessageBOX/shriek-fx
|
/src/Shriek.ServiceProxy.Http/ReturnAttributes/XmlReturnAttribute.cs
| 2.59375
| 3
|
using Shriek.ServiceProxy.Abstractions.Attributes;
using Shriek.ServiceProxy.Abstractions.Context;
using Shriek.ServiceProxy.Http.Contexts;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Shriek.ServiceProxy.Http.ReturnAttributes
{
/// <summary>
/// 表示将回复的Xml结果作反序化为指定类型
/// </summary>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Method)]
public class XmlReturnAttribute : ApiReturnAttribute
{
/// <summary>
/// 获取异步结果
/// </summary>
/// <param name="context">上下文</param>
/// <returns></returns>
public override async Task<object> GetTaskResult(ApiActionContext context)
{
if (!(context is HttpApiActionContext httpContext)) return Task.CompletedTask;
if (httpContext.ResponseMessage.Content.Headers.ContentType.MediaType != "application/xml")
return null;
var response = httpContext.ResponseMessage;
var dataType = context.ApiActionDescriptor.ReturnDataType;
var xmlSerializer = new XmlSerializer(dataType);
using (var stream = new MemoryStream())
{
await response.Content.CopyToAsync(stream);
stream.Position = 0;
return xmlSerializer.Deserialize(stream);
}
}
}
}
|
d36f6a9b72c507749ecc7237bf527a31c245b249
|
C#
|
andreip0pa/passCracker
|
/PasswordCrackerServer/PasswordCrackerServer/Program.cs
| 3.28125
| 3
|
using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PasswordCrackerServer
{
class Program
{
static void Main(string[] args)
{
List<Chunk> chunkList = new List<Chunk>();
Console.WriteLine("Welcome to Awesome International's Password Cracker!");
Console.WriteLine("Please enter number of chunks to split dictionary into:");
chunkList = ChunkMaker.CreateChunks(Convert.ToInt32(Console.ReadLine()));
Console.WriteLine("Server strated, ready for client's to connect.");
TcpWorker t = new TcpWorker(9999, IPAddress.Any,chunkList);
t.Start();
Console.ReadKey();
}
/* static List<Chunk> CreateChunks(int number)
{
List<string> fullDicionary = new List<string>();
string filename = "webster-dictionary.txt";
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
using (StreamReader sr = new StreamReader(fs))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
fullDicionary.Add(line);
}
}
int maxi = fullDicionary.Count / number;
List<Chunk> chunkList = new List<Chunk>();
for (int j = 0; j <= number-1; j++)
{
int initiali = maxi - fullDicionary.Count / number;
List<string> list1 = new List<string>();
for (int i = initiali; i < maxi; i++)
{
list1.Add(fullDicionary[i]);
}
chunkList.Add(new Chunk(list1));
maxi += fullDicionary.Count / number;
}
return chunkList;
}*/
}
}
|
1d2050d8d35f7347910332adcbb91effc6579586
|
C#
|
PetarHr/e-Doc
|
/Services/Attributes/EGN.cs
| 2.796875
| 3
|
using System;
using System.ComponentModel.DataAnnotations;
namespace eDoc.Services.Attributes
{
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class EGN : ValidationAttribute
{
public EGN()
{
this.ErrorMessage = "Моля, въведете валидно ЕГН.";
}
public override bool IsValid(object value)
{
if (value is string personalIDNumber)
{
if (personalIDNumber.Length != 10)
{
return false;
}
foreach (char digit in personalIDNumber)
{
if (!Char.IsDigit(digit))
{
return false;
}
}
int month = int.Parse(personalIDNumber.Substring(2, 2));
int year = 0;
if (month < 13)
{
year = int.Parse("19" + personalIDNumber.Substring(0, 2));
}
else if (month < 33)
{
month -= 20;
year = int.Parse("18" + personalIDNumber.Substring(0, 2));
}
else
{
month -= 40;
year = int.Parse("20" + personalIDNumber.Substring(0, 2));
}
int day = int.Parse(personalIDNumber.Substring(4, 2));
DateTime dateOfBirth = new DateTime();
if (!DateTime.TryParse(String.Format("{0}/{1}/{2}", day, month, year), out dateOfBirth))
{
return false;
}
int[] weights = new int[] { 2, 4, 8, 5, 10, 9, 7, 3, 6 };
int totalControlSum = 0;
for (int i = 0; i < 9; i++)
{
totalControlSum += weights[i] * (personalIDNumber[i] - '0');
}
int controlDigit = 0;
int reminder = totalControlSum % 11;
if (reminder < 10)
{
controlDigit = reminder;
}
int lastDigitFromIDNumber = int.Parse(personalIDNumber[9..]);
if (lastDigitFromIDNumber != controlDigit)
{
return false;
}
return true;
}
return false;
}
}
}
|
5497c48fa626faf592f3508c853feed72edd56fd
|
C#
|
rmzone/Rmzone.Sdl2
|
/src/Rmzone.Sdl2/DrawingExtensions.cs
| 2.8125
| 3
|
using Rmzone.Sdl2.Internal;
namespace Rmzone.Sdl2;
public static class DrawingExtensions
{
public static void DrawPixel(this Renderer renderer, Point pt)
{
Sdl2Native.SDL_RenderDrawPoint(renderer.Handle, pt.X, pt.Y);
}
public static void DrawLine(this Renderer renderer, Point pt1, Point pt2)
{
Sdl2Native.SDL_RenderDrawLine(renderer.Handle, pt1.X, pt1.Y, pt2.X, pt2.Y);
}
public static void FillRect(this Renderer renderer, Rectangle rect)
{
var box = new Sdl2Native.SDL_Rect {x = rect.X, y = rect.Y, w = rect.Width, h = rect.Height};
Sdl2Native.SDL_RenderFillRect(renderer.Handle, ref box);
}
}
|
50f4e75c5d9fb3141ad5da662fbeca8b22f29d4e
|
C#
|
fragmental/07-Glitch-Garden
|
/Assets/Scripts/Shooter.cs
| 2.515625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooter : MonoBehaviour {
public GameObject projectile, gun;
private GameObject projectileParent;
private Animator animator;
private Spawner myLaneSpawner;
private void Start()
{
animator = GetComponent<Animator>();
//Finds parent or creates one, if necessary
projectileParent = GameObject.Find("Projectiles");
if (!projectileParent)
{
projectileParent = new GameObject("Projectiles");
Debug.Log("Projectiles parent was missing. New Projectiles created.");
}
SetMyLaneSpawner();
//Debug.Log(myLaneSpawner);
}
private void Update()
{
if (IsAttackerAheadInLane())
{
animator.SetBool("isAttacking", true);
}
else
{
animator.SetBool("isAttacking", false);
}
}
//Look through all spawners and set myLaneSpawner if found
void SetMyLaneSpawner()
{
Spawner[] spawnerArray = GameObject.FindObjectsOfType<Spawner>();
foreach (Spawner spawner in spawnerArray)
{
if(spawner.transform.position.y == transform.position.y)
{
myLaneSpawner = spawner;
return;
}
}
Debug.LogError(name + "can't find spawner in lane");
}
bool IsAttackerAheadInLane()
{
//Exit if no attackers in lane
if(myLaneSpawner.transform.childCount <= 0)
{
return false;
}
else
{
//if there are attacker, are they ahead?
foreach (Transform attacker in myLaneSpawner.transform)
{
if (attacker.transform.position.x > transform.position.x)
{
return true;
}
else
{
return false;
}
}
}
return false;
}
private void Fire()
{
GameObject newProjectile = Instantiate(projectile);
newProjectile.transform.parent = projectileParent.transform;
newProjectile.transform.position = gun.transform.position;
}
//animator = GetComponent<Animator>();
private void OnBecameInvisible()
{
Destroy(gameObject);
}
}
|
44c7e75452ae631883940cc109ee3620f2305411
|
C#
|
sonicpro/SmallCSTests
|
/ReadOnlyCollection/ReadOnlyCollection.linq
| 2.890625
| 3
|
<Query Kind="Statements">
<Namespace>System.Collections.ObjectModel</Namespace>
</Query>
ReadOnlyCollection<string> dinos = new ReadOnlyCollection<string>(new[] { "Veloc", "Trex" });
string[] array = new string[dinos.Count + 2];
dinos.CopyTo(array, 1);
Console.WriteLine(array.Length);
foreach(var d in array)
{
Console.WriteLine(d);
}
|
ce30577d8809a476d07513aff9515643ee9cce0c
|
C#
|
skokwkod/SzkolenieDzienPierwszy
|
/lab31 - MetodyRozszerzajace(Cwiczenie)/ExtensionDateTime.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lab31___MetodyRozszerzajace_Cwiczenie_
{
public static class ExtensionDateTime
{
public static int DaysOnEarth (this DateTime birthDayDate)
{
return Convert.ToInt32((DateTime.Today - birthDayDate).TotalDays);
}
}
}
|
a698def933bc8ae1dcf837f853826c9f3755b7ff
|
C#
|
fat84/Fingerprint
|
/Repository/VisitorRepository.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Finger.Entity;
using System.Data.SQLite;
namespace Finger.Repository
{
public class VisitorRepository : BaseRepository
{
public int Insert(Visitor visitor)
{
string sql = "insert into visitor(id, name, mobile, identity, company, template) values(@id, @name, @mobile, @identity, @company, @template)";
SQLiteParameter[] parameters = new SQLiteParameter[6];
parameters[0] = new SQLiteParameter("@id", visitor.Id);
parameters[1] = new SQLiteParameter("@name", visitor.Name);
parameters[2] = new SQLiteParameter("@mobile", visitor.Mobile);
parameters[3] = new SQLiteParameter("@identity", visitor.Identity);
parameters[4] = new SQLiteParameter("@company", visitor.Company);
parameters[5] = new SQLiteParameter("@template", visitor.Template);
return SQLHelper.ExecuteNonQuery(sql, parameters);
}
public int Delete(string id)
{
string sql = "delete from visitor where id=@id";
SQLiteParameter[] parameters = new SQLiteParameter[1];
parameters[0] = new SQLiteParameter("@id", id);
return SQLHelper.ExecuteNonQuery(sql, parameters);
}
public List<Visitor> GetList()
{
string sql = "select id, name, mobile, identity, company, template from visitor";
SQLiteDataReader reader = SQLHelper.ExecuteReader(sql, null);
List<Visitor> list = new List<Visitor>();
while (reader.Read())
{
Visitor v = new Visitor();
v.Id = reader["id"].ToString();
v.Name = reader["name"].ToString();
v.Mobile = reader["mobile"].ToString();
v.Identity = reader["identity"].ToString();
v.Company = reader["company"].ToString();
v.Template = reader["template"].ToString();
list.Add(v);
}
return list;
}
}
}
|
dd94177ec3e26938478964da474151139e400653
|
C#
|
luketudor/PayslipGeneratorKata
|
/PayslipGenerator/DefaultTaxTable.cs
| 3.234375
| 3
|
namespace PayslipGenerator
{
public class DefaultTaxTable : ITaxTable
{
public double AnnualIncomeTax(double annualSalary)
{
var tax = 0.0;
if (annualSalary <= 18200)
{
tax = 0;
}
else if (annualSalary <= 37000)
{
tax = (annualSalary - 18200) * 0.19;
}
else if (annualSalary <= 80000)
{
tax = (annualSalary - 37000) * 0.325 + 3572;
}
else if (annualSalary <= 180000)
{
tax = (annualSalary - 80000) * 0.37 + 17547;
}
else
{
tax = (annualSalary - 180000) * 0.45 + 54547;
}
return tax;
}
}
}
|
e706c5bd415faa2b727e6dcde89eebf5e94ef4c6
|
C#
|
capsizedmoose/Basic-Garage-System
|
/BasicGarageSystem/GarageController.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml;
using System.IO;
namespace BasicGarageSystem
{
// The different types of vehicles that can be used
public enum v_Vehicle
{
Bus,
Car,
MC,
Truck
}
public class ParkingSpot
{
public int X { get; set; }
public int Y { get; set; }
// it looks too ugly if the numbers start at 0, so send them with +1
public override string ToString()
{
return $"[{X + 1},{Y + 1}]";
}
}
class GarageController
{
List<Vehicle> m_Vehicles; // maybe make a new list class later?
List<string> m_Receipts;
//Vehicle[] m_Vehicles; // array-version
bool[,] m_ParkingSpaces; // Making it 2-dimensional instead, would be a really strange garage if it had like 100 adjecent parking spaces
public int NumberOfParkingSpaces { get; set; }
public double ParkingFee { get; set; }
public int MaximumHours { get; set; }
public int SizeX { get; set; }
public int SizeY { get; set; }
private Random randomNumber;
// Constructor
// takes argument: int x - used to create the size of the garage (default is 5)
// takes argument: int y - used to create the size of the garage (default is 5)
// takes argument: double parkingFee - used to set the parking fee for the garage
// takes argument: int maximumHours - maximum number of hours allowed to park in the garage
public GarageController(int x = 10, int y = 25, double parkingFee = 50, int maximumHours = 24)
{
m_Vehicles = new List<Vehicle>();
m_Receipts = new List<string>();
//m_Vehicles = new Vehicle[num]; // the array-version
m_ParkingSpaces = new bool[x + 1, y + 1];
NumberOfParkingSpaces = x * y;
SizeX = x;
SizeY = y;
ParkingFee = parkingFee;
MaximumHours = maximumHours;
randomNumber = new Random();
}
// Prints out all vehicles in the list of vehicles
// takes: no arguments
// returns a list of strings with the basic information about the vehicles
public List<string> PrintAll()
{
return m_Vehicles.Where(v => v != null).Select(v => v.BasicInfo()).ToList();
}
// Prints out a single vehicle that matches the given registration number
// takes argument: string regNr - the registration number for the vehicle
// returns a string with all the info of the mathcing vehicle
public string PrintVehicle(string regNr)
{
return GetVehicle(regNr).ToString();
}
// Finds a specific vehicle with the given registration number
// takes argument: string reNr - the registration number
// returns a string with basic info of the matching vehicle
public string FindVehicle(string regNr)
{
return GetVehicle(regNr).BasicInfo();
}
// Finds all vehicles of the given type
// takes argument: v_Vehicle type - the type of the vehicle
// returns a string with the return message of the method
public List<string> FindVehiclesByType(v_Vehicle type)
{
return m_Vehicles.Where(v => v.vehicleType == type).Select(v => v.BasicInfo()).ToList();
}
// Adds a new Vehicle to the list of Vehicles
// Creates a new Vehicle instance and assigns it a free parking space if available
// takes no arguments
// returns a string with the return message of the method
public string ParkNewVehicle()
{
// Checks if the garage is full, so we can exit earlier if the garage is full
if (NumberOfParkingSpaces == m_Vehicles.Count)
{
return $"The garage is full.";
}
// Get the current date
string dateNow = GetDate();
// the new vehicle to be added
Vehicle vehicle = GenerateRandomVehicle();
// Redundant since this is being checked in the method that generates a random vehicle, but I'll leave it in here anyway
if (GetVehicle(vehicle.regNr) != null)
{
return $"A vehicle with the registration number: {vehicle.regNr} is already parked in the garage!";
}
// so we can exit earlier if there's not enough space in the garage
if (GetNumberOfFreeSpaces() < vehicle.vehicleSize)
{
return $"The garage is full!!.";
}
ParkingSpot index = FindFreeParkingSpace(vehicle.vehicleSize); // index used to find empty parking space
// checks if we found a free parking space for the type of vehicle
if (index.X == -1 && index.Y == -1)
{
return $"Not enough empty spaces in the garage for a vehicle of type: { vehicle.vehicleType.ToString()}.";
}
// sets the found parking space(s) to occupied/true
for (int i = 0; i < vehicle.vehicleSize; i++)
{
m_ParkingSpaces[index.X, index.Y + i] = !m_ParkingSpaces[index.X, index.Y + i];
}
// assigns the vehicle its parking space
vehicle.parkingSpot = index;
// add the new vehicle to the list
m_Vehicles.Add(vehicle);
return $"The vehicle of the type: {vehicle.vehicleType.ToString()} " +
$"with the registration number: {vehicle.regNr} \nwas parked in the garage at " +
$"parking space(s): {index.ToString()}" + (vehicle.vehicleSize > 1 ? $" to [{index.X + 1},{index.Y + vehicle.vehicleSize}]." : "");
}
// !Mainly used for manual testing with different vehicle types!
// Adds a new Vehicle to the list of Vehicles -
// Creates a new Vehicle instance and assigns it a free parking space if available
// takes argument v_Vehicle - type of vehicle to be created
// returns a string with the return message of the method
public string ParkVehicle(v_Vehicle type)
{
// Checks if the garage is full, so we can exit earlier if the garage is full
if (NumberOfParkingSpaces == m_Vehicles.Count)
{
return $"The garage is full.";
}
// Get the current date
string dateNow = GetDate();
// the new vehicle to be added
Vehicle vehicle; // = GenerateRandomVehicle();
switch (type)
{
case v_Vehicle.Bus:
vehicle = new Bus() { regNr = getRandomRegNr(), dateTime = dateNow };
break;
case v_Vehicle.Car:
vehicle = new Car() { regNr = getRandomRegNr(), dateTime = dateNow };
break;
case v_Vehicle.MC:
vehicle = new MC() { regNr = getRandomRegNr(), dateTime = dateNow };
break;
case v_Vehicle.Truck:
vehicle = new Truck() { regNr = getRandomRegNr(), dateTime = dateNow };
break;
default:
vehicle = null;
break;
}
// so we can exit earlier if there's not enough space in the garage
if (GetNumberOfFreeSpaces() < vehicle.vehicleSize)
{
return $"The garage is full!!.";
}
ParkingSpot index = FindFreeParkingSpace(vehicle.vehicleSize); // index used to find empty parking space
// checks if we found a free parking space for the type of vehicle
if (index.X == -1 && index.Y == -1)
{
return $"Not enough empty spaces in the garage for a vehicle of type: { vehicle.vehicleType.ToString()}.";
}
// sets the found parking space(s) to occupied/true
for (int i = 0; i < vehicle.vehicleSize; i++)
{
m_ParkingSpaces[index.X, index.Y + i] = !m_ParkingSpaces[index.X, index.Y + i];
}
// assigns the vehicle its parking space
vehicle.parkingSpot = index;
// add the new vehicle to the list
m_Vehicles.Add(vehicle);
return $"The vehicle of the type: {vehicle.vehicleType.ToString()} " +
$"with the registration number: {vehicle.regNr} \nwas parked in the garage at " +
$"parking space(s): {index.ToString()}" + (vehicle.vehicleSize > 1 ? $" to [{index.X + 1},{index.Y + vehicle.vehicleSize}]." : "");
}
// Removes a Vehicle from the list of Vehicles
//
// takes argument: string regNr - the registration number for the vehicle
// returns a string with the return message of the method
public string VehicleCheckout(string regNr)
{
var vehicle = GetVehicle(regNr);
if (vehicle == null)
{
return $"No vehicle found with the reigstration number: {regNr}.";
}
ParkingSpot index = vehicle.parkingSpot;
// Free the occupied parking spaces
for (int i = 0; i < vehicle.vehicleSize; i++)
{
m_ParkingSpaces[index.X, index.Y + i] = !m_ParkingSpaces[index.X, index.Y + i];
}
m_Vehicles = m_Vehicles.Where(v => v.regNr != regNr).ToList(); // remove the vehicle from the list;
string receipt = $"Total hours parked: {GetTotalHours(vehicle)} and total price: {GetTotalPrice(vehicle)}.";
m_Receipts.Add(receipt);
return $"The vehicle with the registration number: {regNr} " +
$"left the garage, freeing up the parking space(s) {index.ToString()}" + (vehicle.vehicleSize > 1 ? $" to [{index.X + 1},{index.Y + vehicle.vehicleSize}].\n" : ".\n") + receipt;
}
// Views how long a vehicle has been parked, and what the total price of the paarking fee is
//
// takes argument: string regNr - the registration number
// returns a string with the return message of the method
public string ViewParkedVehicle(string regNr)
{
var vehicle = GetVehicle(regNr);
int totalHours = GetTotalHours(vehicle);
double totalPrice = GetTotalPrice(vehicle);
if (vehicle == null)
{
return $"No vehicle found with the reigstration number: {regNr}.";
}
return ($"Vehicle with registration number: {regNr} is parked at {vehicle.parkingSpot.ToString()} " +
(vehicle.vehicleSize > 1 ? $" to [{vehicle.parkingSpot.X + 1},{vehicle.parkingSpot.Y + vehicle.vehicleSize}]" : "") +
$" and has parked for a total of {totalHours} hours (rounded up). Total price: {totalPrice}.");
}
// Help-method tyo get the total price for a parked vehicle
// checks if the vehicle has been parked for linger than the maximum hours allowed,
// and doubles the hourly fee then (for all hours), but doesn't send any kind of message about it atm
// I'll fix it if I found somethine else to add later (too lazy atm)
private double GetTotalPrice(Vehicle vehicle)
{
if (vehicle == null)
{
return -1;
}
int totalHours = GetTotalHours(vehicle);
// Total price, just at placeholder atm
return totalHours * vehicle.vehicleSize * (totalHours > MaximumHours ? 2 * ParkingFee : ParkingFee);
}
// Help-method to get the total hours parked for a parked vehicle
private int GetTotalHours(Vehicle vehicle)
{
if (vehicle == null)
{
return -1;
}
var parkedDate = DateTime.ParseExact(vehicle.dateTime, "yyyy-MM-dd HH:mm", System.Globalization.CultureInfo.InstalledUICulture);
// Total hours parked rounded up, so can never park (or pay) for less than one hour
return (int)(DateTime.Now - parkedDate).TotalHours + 1;
}
// Test method that views all the vehicles and removes them from the garage
public void RemoveAllVehicles()
{
// I'm really starting to like LINQ!
foreach (var regNr in m_Vehicles.Select(v => v.regNr))
{
Console.WriteLine($"\n{ViewParkedVehicle(regNr)}");
Console.WriteLine(VehicleCheckout(regNr));
}
}
// Returns the list with receipts
public List<string> GetReceipts()
{
return m_Receipts;
}
// Help-method to get the number of free spaces
// takes no arguments
// returns an int with the number of free spaces
private int GetNumberOfFreeSpaces()
{
return NumberOfParkingSpaces - m_Vehicles.Select(v => v.vehicleSize).Sum();
}
// Help-method to check if there are any free parking spacesa
// takes no arguments
// returns a PakringSpot with the free parking spot if one is found, otherwise it will have X = -1 and Y = -1
private ParkingSpot FindFreeParkingSpace(int vehicleSize)
{
bool found = false;
ParkingSpot ParkingSpot = new ParkingSpot() { X = -1, Y = -1 };
for (int i = 0; i < SizeX; i++)
{
for (int j = 0; j < SizeY - (vehicleSize - 1); j++)
{
if (!m_ParkingSpaces[i, j]) // Checks if the parking space is taken
{
// Checks if the vehicle will actually fit in the free parking space
for (int k = 0; k < vehicleSize; k++)
{
if (m_ParkingSpaces[i, j + k])
{
found = false; // if it can't fit; then we haven't found a free parking space
break;
}
found = true; // if it can fit; we have found a free parking space
}
}
if (found)
{
ParkingSpot.X = i;
ParkingSpot.Y = j;
return ParkingSpot;
}
}
}
return ParkingSpot;
}
// Help-method to get a string with the current date
// takes no arguments
// returns a string with the date formated like: yyyy-MM-dd HH:mm
private string GetDate()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm");
}
// Help-method to get a vehicle that matches the given registration number
// takes argument: string regNr - the registration number of the vehicle
// returns a Vehicle if it exists, otherwise null
private Vehicle GetVehicle(string regNr)
{
var query = m_Vehicles.Where(v => v != null && v.regNr == regNr);
return (query.Count() > 0 ? query.First() : null);
}
// Help-method to generate a random vehicle
// takes no arguments
// returns the generated Vehicle
private Vehicle GenerateRandomVehicle()
{
string regNr;
while (GetVehicle(regNr = getRandomRegNr()) != null) ; // Find a regNr that isn't already used by a vehicle in the garage
v_Vehicle type = GetRandomVehicleType();
string now = GetDate();
switch (type)
{
case v_Vehicle.Bus:
return new Bus() { regNr = regNr, dateTime = now };
case v_Vehicle.Car:
return new Car() { regNr = regNr, dateTime = now, };
case v_Vehicle.MC:
return new MC() { regNr = regNr, dateTime = now, };
case v_Vehicle.Truck:
return new Truck() { regNr = regNr, dateTime = now, };
default:
return null;
}
}
// Help-method to generate a random vehicle type
// takes no arguments
// returns a v_Vehicle with the vehicle type
public v_Vehicle GetRandomVehicleType()
{
var values = Enum.GetValues(typeof(v_Vehicle));
return (v_Vehicle)values.GetValue(randomNumber.Next(values.Length));
}
// Help-method to generate a random registration number
// takes no arguments
// returns a string with the generated registration number
public string getRandomRegNr()
{
int num;
string regNum = "";
for (int i = 0; i < 3; i++)
{
num = randomNumber.Next(97, 122);
regNum += (char)num;
}
for (int i = 0; i < 3; i++)
{
num = randomNumber.Next(0, 9);
regNum += num;
}
//Console.WriteLine(regNum.ToUpper());
return regNum.ToUpper();
}
// Park Vehicles from List
// Called when loading a garage from file
private void ParkVehiclesFromList(List<Vehicle> vehicles)
{
foreach (var vehicle in vehicles)
{
ParkingSpot index = vehicle.parkingSpot;
for (int i = 0; i < vehicle.vehicleSize; i++)
{
m_ParkingSpaces[index.X, index.Y + i] = !m_ParkingSpaces[index.X, index.Y + i];
}
m_Vehicles.Add(vehicle);
//Console.WriteLine(($"The vehicle of the type: {vehicle.vehicleType.ToString()} " +
//$"with the registration number: {vehicle.regNr} \nwas parked in the garage at " +
//$"parking space(s): {index.ToString()}" + (vehicle.vehicleSize > 1 ? $" to [{index.X + 1},{index.Y + vehicle.vehicleSize}]." : "")));
}
}
// Maybe move these somewhere else, maybe a new class?
// Saves the list of vehicles to a file
// takes string fileName - the file to save to
// returns: nothing (void)
public void SaveGarageToFile(string fileName = @"Garage.xml")
{
XElement xml = new XElement("Garage",
new XElement("Info",
new XAttribute("SizeX", SizeX),
new XAttribute("SizeY", SizeY),
new XAttribute("ParkingFee", ParkingFee),
new XAttribute("MaximumHours", MaximumHours)),
new XElement("Vehicles", m_Vehicles.Select(v =>
new XElement("Vehicle",
new XAttribute("vehicleType", v.vehicleType.ToString()),
new XAttribute("regNr", v.regNr),
new XAttribute("dateTime", v.dateTime),
new XAttribute("parkingSpot", v.parkingSpot.ToString()),
new XAttribute("vehicleSize", v.vehicleSize)
))));
xml.Save(XmlWriter.Create(new StringWriter()));
xml.Save(fileName);
}
// Loads a list of vehicles from a file
// takes string fileName - the file to load from
// returns a bool that will be true if everything went well
public bool LoadGarageFromFile(string fileName = @"Garage.xml")
{
XElement xml;
// if the file wasn't found
if (!File.Exists(fileName))
{
return false;
}
xml = XElement.Load(fileName);
// find the onfo about the garage itself
var info = xml.Descendants("Info").Select(v => new
{
x = v.Attribute("SizeX").Value.Trim(),
y = v.Attribute("SizeY").Value.Trim(),
fee = v.Attribute("ParkingFee").Value.Trim(),
max = v.Attribute("MaximumHours").Value.Trim()
}).First();
int xSize, ySize, maxHours;
double parkingFee;
// try to parse the values
if (!int.TryParse(info.x, out xSize) || !int.TryParse(info.y, out ySize) || !int.TryParse(info.max, out maxHours) || !double.TryParse(info.fee, out parkingFee))
{
return false;
}
// assign the values
ParkingFee = parkingFee;
SizeX = xSize;
SizeY = ySize;
MaximumHours = maxHours;
Vehicle vehicle;
m_ParkingSpaces = new bool[SizeX, SizeY];
// start parsing the vehicles
var vehicles = xml.Descendants("Vehicle")
.Where(v => Enum.TryParse(v.Attribute("vehicleType").Value, out v_Vehicle type)
&& int.TryParse(v.Attribute("parkingSpot").Value.Substring(v.Attribute("parkingSpot").Value.IndexOf('[') + 1, v.Attribute("parkingSpot").Value.IndexOf(',') - 1), out xSize)
&& int.TryParse(v.Attribute("parkingSpot").Value.Substring(v.Attribute("parkingSpot").Value.IndexOf(',') + 1, v.Attribute("parkingSpot").Value.IndexOf(']') - v.Attribute("parkingSpot").Value.IndexOf(',') - 1), out ySize))
.Select(v => {
Enum.TryParse(v.Attribute("vehicleType").Value, out v_Vehicle type);
switch (type)
{
case v_Vehicle.Bus:
vehicle = new Bus() { regNr = v.Attribute("regNr").Value, dateTime = v.Attribute("dateTime").Value, parkingSpot = new ParkingSpot() { X = xSize - 1, Y = ySize - 1 } };
break;
case v_Vehicle.Car:
vehicle = new Car() { regNr = v.Attribute("regNr").Value, dateTime = v.Attribute("dateTime").Value, parkingSpot = new ParkingSpot() { X = xSize - 1, Y = ySize - 1 } };
break;
case v_Vehicle.MC:
vehicle = new MC() { regNr = v.Attribute("regNr").Value, dateTime = v.Attribute("dateTime").Value, parkingSpot = new ParkingSpot() { X = xSize - 1, Y = ySize - 1 } };
break;
case v_Vehicle.Truck:
vehicle = new Truck() { regNr = v.Attribute("regNr").Value, dateTime = v.Attribute("dateTime").Value, parkingSpot = new ParkingSpot() { X = xSize - 1, Y = ySize - 1 } };
break;
default:
vehicle = null;
break;
}
return vehicle;
}).ToList();
// Park the loaded vehicles
ParkVehiclesFromList(vehicles);
return true;
}
}
}
|
4fa5e664d2512338e41335ebc6872ad61018af82
|
C#
|
shendongnian/download4
|
/code1/180731-39908609-128747330-4.cs
| 3.46875
| 3
|
public class MySingleton {
private static object myLock = new object();
private static volatile MySingleton mySingleton = null;
private MySingleton() {
}
public static MySingleton GetInstance() {
if (mySingleton == null) { // 1st check
lock (myLock) {
if (mySingleton == null) { // 2nd (double) check
mySingleton = new MySingleton();
// Write-release semantics are implicitly handled by marking mySingleton with
// 'volatile', which inserts the necessary memory barriers between the constructor call
// and the write to mySingleton. The barriers created by the lock are not sufficient
// because the object is made visible before the lock is released.
}
}
}
// The barriers created by the lock are not sufficient because not all threads will
// acquire the lock. A fence for read-acquire semantics is needed between the test of mySingleton
// (above) and the use of its contents.This fence is automatically inserted because mySingleton is
// marked as 'volatile'.
return mySingleton;
}
}
|
f4f318a47a4754f153f545d117cf162b8384f653
|
C#
|
LaughingFalcon/DesighPatternLibrary
|
/Event/Publisher.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPattern.Event
{
public class Publisher
{
int info2;
int info1;
IEventAggregator aggregator;
public Publisher(IEventAggregator EventAggregator)
{
aggregator = EventAggregator;
info1 = 3;
info2 = info1*10;
aggregator.Publish(info1, info2);
}
public void updateInfo(int info1, int info2)
{
this.info1 = info1;
this.info2 = info2;
aggregator.Publish(info1, info2);
}
public void updateInfo(int info1)
{
this.info1 = info1;
info2 = info1 * 10;
aggregator.Publish(info1, info2);
}
}
}
|
1db3aafc68c2b4debdba7fff91d64c340e9cb7c3
|
C#
|
vitoshacademy/04.ConsoleEntryAndExit
|
/08. IntegerN.cs
| 4.09375
| 4
|
//Write a program that reads an integer number n from the console
//and prints all the numbers in the interval [1..n], each on a single line.
using System;
class IntegerN
{
static void Main(string[] args)
{
uint n;
int i ;
Console.Write("Enter N:");
while (!uint.TryParse(Console.ReadLine(), out n) || n < 1)
{
Console.Write("invalid entry. Please try again: ");
}
for (i = 1; i <= n; i++)
{
Console.WriteLine("N: {0}", i);
}
}
}
|
e014e8324d795c87aa15c2560862136dd8011b97
|
C#
|
JustMeGaaRa/patterns-and-practices
|
/src/Silent.Practices.MetadataProvider/Context/TypeContextSet.cs
| 2.734375
| 3
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Silent.Practices.MetadataProvider.Context
{
public class TypeContextSet : IEnumerable<TypeContext>
{
private readonly Dictionary<string, TypeContext> _typesContexts = new Dictionary<string, TypeContext>();
public TypeContextSet() { }
public TypeContextSet(IEnumerable<TypeInfo> types) => types.Select(AddType).ToList();
public int Count => _typesContexts.Values.Count;
public bool ContainsType(TypeInfo type) => _typesContexts.ContainsKey(type.Name);
public TypeContext AddType(TypeInfo type) => _typesContexts[type.Name] = new TypeContext(type);
public TypeContext GetType(string typeName) => _typesContexts[typeName];
public IEnumerator<TypeContext> GetEnumerator() => _typesContexts.Values.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
|
5c8c6014e84b98ccf182289dd1a0df2192761ffb
|
C#
|
Kov-Vadim/Project20
|
/Project6/Task-1/Program.cs
| 3.328125
| 3
|
using System;
namespace Task_1
{
class Program
{ //Заполнить массив из десяти элементов значениями, вводимыми с клавиатуры в ходе выполнения программы.
static void Main(string[] args)
{
int b = 10;
int[] a = new int[b];
for (int i = 0; i < b; i++)
{
a[i] = Convert.ToByte(Console.ReadLine());
}
}
}
}
|
5783b69b438755ea35d694a0ce055c470456ccd3
|
C#
|
skarpdev/dotnetcore-hubspot-client
|
/src/Core/Requests/RequestDataConverter.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Skarp.HubSpotClient.Core.Interfaces;
namespace Skarp.HubSpotClient.Core.Requests
{
public class RequestDataConverter
{
private readonly ILogger<RequestDataConverter> _logger;
public RequestDataConverter(
ILogger<RequestDataConverter> logger)
{
_logger = logger;
}
/// <summary>
/// Converts the given <paramref name="entity"/> to a hubspot data entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="preformConversion">This by default performs a data conversion so that the HubSpot "property-value" syntax will be used for serialization. If this parameter is set to false no data conversion is performed (such that a standard object serialization can be performed). </param>
/// <returns></returns>
public dynamic ToHubspotDataEntity(IHubSpotEntity entity, bool preformConversion = true)
{
_logger.LogDebug("Convert ToHubspotDataEntity");
dynamic mapped = new ExpandoObject();
if (preformConversion)
{
mapped.Properties = new List<HubspotDataEntityProp>();
_logger.LogDebug("Use nameValue mapping?: {0}", entity.IsNameValue);
var allProps = entity.GetType().GetProperties();
_logger.LogDebug("Have {0} props to map", allProps.Length);
foreach (var prop in allProps)
{
if (prop.HasIgnoreDataMemberAttribute()) { continue; }
var propSerializedName = prop.GetPropSerializedName();
_logger.LogDebug("Mapping prop: '{0}' with serialization name: '{1}'", prop.Name, propSerializedName);
if (prop.Name.Equals("RouteBasePath") || prop.Name.Equals("IsNameValue")) { continue; }
// IF we have an complex type on the entity that we are trying to convert, let's NOT get the
// string value of it, but simply pass the object along - it will be serialized later as JSON...
var propValue = prop.GetValue(entity);
var value = propValue.IsComplexType() ? propValue : propValue?.ToString();
var item = new HubspotDataEntityProp
{
Property = propSerializedName,
Value = value
};
if (entity.IsNameValue)
{
item.Property = null;
item.Name = propSerializedName;
}
if (item.Value == null) { continue; }
mapped.Properties.Add(item);
}
_logger.LogDebug("Mapping complete, returning data");
}
else
{
mapped = entity;
}
return mapped;
}
/// <summary>
/// Converts the given <paramref name="entity"/> to a simple list of name/values.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns></returns>
public IEnumerable<HubspotDataEntityProp> ToNameValueList(object entity)
{
_logger.LogDebug("Convert ToNameValueList");
var properties = new List<HubspotDataEntityProp>();
var allProps = entity.GetType().GetProperties();
_logger.LogDebug("Have {0} props to map", allProps.Length);
foreach (var prop in allProps)
{
if (prop.HasIgnoreDataMemberAttribute()) { continue; }
var propSerializedName = prop.GetPropSerializedName();
_logger.LogDebug("Mapping prop: '{0}' with serialization name: '{1}'", prop.Name, propSerializedName);
if (prop.Name.Equals("RouteBasePath") || prop.Name.Equals("IsNameValue")) { continue; }
// IF we have an complex type on the entity that we are trying to convert, let's NOT get the
// string value of it, but simply pass the object along - it will be serialized later as JSON...
var propValue = prop.GetValue(entity);
var value = propValue.IsComplexType() ? propValue : propValue?.ToString();
var item = new HubspotDataEntityProp
{
Property = null,
Name = propSerializedName,
Value = value
};
if (item.Value == null) { continue; }
properties.Add(item);
}
_logger.LogDebug("Mapping complete, returning data");
return properties;
}
/// <summary>
/// Convert from the dynamicly typed <see cref="ExpandoObject"/> into a strongly typed <see cref="IHubSpotEntity"/>
/// </summary>
/// <param name="dynamicObject">The <see cref="ExpandoObject"/> representation of the returned json</param>
/// <returns></returns>
public T FromHubSpotResponse<T>(ExpandoObject dynamicObject) where T : IHubSpotEntity, new()
{
var data = (T)ConvertSingleEntity(dynamicObject, new T());
return data;
}
public T FromHubSpotListResponse<T>(ExpandoObject dynamicObject) where T : IHubSpotEntity, new()
{
// get a handle to the underlying dictionary values of the ExpandoObject
var expandoDict = (IDictionary<string, object>)dynamicObject;
// For LIST contacts the "contacts" property should be populated, for LIST companies the "companies" property should be populated, and so on
// in our T item, search for a property that is an IList<IHubSpotEntity> and use that as our prop name selector into the DynamoObject.....
// So on the IContactListHubSpotEntity we have a IList<IHubSpotEntity> Contacts - find that prop, lowercase to contacts and that prop should
// be in the DynamoObject from HubSpot! Tricky stuff
var targetType = typeof(IHubSpotEntity);
var data = new T();
var dataProps = data.GetType().GetProperties();
var dataTargetProp = dataProps.SingleOrDefault(p => targetType.IsAssignableFrom(p.PropertyType.GenericTypeArguments.FirstOrDefault()));
if (dataTargetProp == null)
{
throw new ArgumentException("Unable to locate a property on the data class that implements IList<T> where T is a IHubSpotEntity");
}
var propSerializedName = dataTargetProp.GetPropSerializedName();
if (!expandoDict.ContainsKey(propSerializedName))
{
throw new ArgumentException($"The json data does not contain a property of name {propSerializedName} which is required to decode the json data");
}
// Find the generic type for the List in question
var genericEntityType = dataTargetProp.PropertyType.GenericTypeArguments.First();
// get a handle to Add on the list (actually from ICollection)
var listAddMethod = dataTargetProp.PropertyType.FindMethodRecursively("Add", genericEntityType);
// Condensed version of : https://stackoverflow.com/a/4194063/1662254
var listInstance =
Activator.CreateInstance(typeof(List<>).MakeGenericType(genericEntityType));
if (listAddMethod == null)
{
throw new ArgumentException("Unable to locate Add method on the list of items to deserialize into - is it an IList?");
}
// Convert all the entities
var jsonEntities = expandoDict[propSerializedName];
foreach (var entry in jsonEntities as List<object>)
{
// convert single entity
var expandoEntry = entry as ExpandoObject;
var dto = ConvertSingleEntity(expandoEntry, Activator.CreateInstance(genericEntityType));
// add entity to list
listAddMethod.Invoke(listInstance, new[] { dto });
}
// assign our reflected list instance onto the data object
dataTargetProp.SetValue(data, listInstance);
var allPropNamesInSerializedFormat = GetAllPropsWithSerializedNameAsKey(dataProps);
// Now try to map any remaining props from the dynamo object into the response dto we shall return
foreach (var kvp in expandoDict)
{
// skip the property with all the items for the response as we have already mapped that
if (kvp.Key == propSerializedName) continue;
// The Key of the current item should be mapped, so we have to find a property in the target dto that "Serializes" into this value...
if (!allPropNamesInSerializedFormat.TryGetValue(kvp.Key, out PropertyInfo theProp))
{
continue;
}
// we have a property which name serializes to the kvp.Key, let's set the data
// If theProp is a complex type we cannot just use SetValue, we need a conversion
if (theProp.PropertyType.IsComplexType())
{
var expandoEntry = kvp.Value as ExpandoObject;
var dto = ConvertSingleEntity(expandoEntry, Activator.CreateInstance(theProp.PropertyType));
theProp.SetValue(data, dto);
}
else // simple value type, assign it
{
theProp.SetValue(data, kvp.Value);
}
}
return data;
}
private IDictionary<string, PropertyInfo> GetAllPropsWithSerializedNameAsKey(PropertyInfo[] dataProps)
{
var dict = new Dictionary<string, PropertyInfo>();
foreach (var prop in dataProps)
{
var propName = prop.GetPropSerializedName();
dict.Add(propName, prop);
}
return dict;
}
/// <summary>
/// Converts a single "dynamic" representation of an entity into a typed entity
/// </summary>
/// <remarks>
/// The dynamic object being passed in should have a prop called "properties" which contains all the object properties to map, as well
/// as vid and other root level objects stored in the HubSpot JSON response
/// </remarks>
/// <param name="dynamicObject">An <see cref="ExpandoObject"/> instance that contains a single HubSpot entity to deserialize</param>
/// <param name="dto">An instantiated DTO that shall receive data</param>
/// <returns>The populated DTO</returns>
internal object ConvertSingleEntity(ExpandoObject dynamicObject, object dto)
{
var expandoDict = (IDictionary<string, object>)dynamicObject;
var dtoProps = dto.GetType().GetProperties();
// The vid is the "id" of the entity
if (expandoDict.TryGetValue("vid", out var vidData))
{
// TODO use properly serialized name of prop to find it
var vidProp = dtoProps.SingleOrDefault(q => q.GetPropSerializedName() == "vid");
vidProp?.SetValue(dto, vidData);
}
// The dealId is the "id" of the deal entity
if (expandoDict.TryGetValue("dealId", out var dealIdData))
{
// TODO use properly serialized name of prop to find it
var dealIdProp = dtoProps.SingleOrDefault(q => q.GetPropSerializedName() == "dealId");
dealIdProp?.SetValue(dto, dealIdData);
}
// The companyId is the "id" of the company entity
if (expandoDict.TryGetValue("companyId", out var companyIdData))
{
// TODO use properly serialized name of prop to find it
var companyIdProp = dtoProps.SingleOrDefault(q => q.GetPropSerializedName() == "companyId");
companyIdProp?.SetValue(dto, companyIdData);
}
// The objectId is the "id" of CRM objects
if (expandoDict.TryGetValue("objectId", out var objectIdData))
{
// TODO use properly serialized name of prop to find it
var objectIdProp = dtoProps.SingleOrDefault(q => q.GetPropSerializedName() == "objectId");
objectIdProp?.SetValue(dto, objectIdData);
}
// The Properties object in the json / response data contains all the props we wish to map - if that does not exist
// we cannot proceeed
if (!expandoDict.TryGetValue("properties", out var dynamicProperties)) return dto;
foreach (var dynamicProp in dynamicProperties as ExpandoObject)
{
// prop.Key contains the name of the property we wish to map into the DTO
// prop.Value contains the data returned by HubSpot, which is also an object
// in there we need to go get the "value" prop to get the actual value
_logger.LogDebug("Looking at dynamic prop: {0}", dynamicProp.Key);
if (!((IDictionary<string, Object>)dynamicProp.Value).TryGetValue("value", out object dynamicValue))
{
continue;
}
// TODO use properly serialized name of prop to find and set it's value
var targetProp =
dtoProps.SingleOrDefault(q => q.GetPropSerializedName() == dynamicProp.Key);
_logger.LogDebug("Have target prop? '{0}' with name: '{1}' and actual value: '{2}'", targetProp != null,
dynamicProp.Key, dynamicValue);
if (targetProp != null)
{
// property type
var pt = targetProp.PropertyType;
var val = dynamicValue.ToString();
// skip any nullable properties with a empty value
if (Nullable.GetUnderlyingType(pt) != null && string.IsNullOrEmpty(val))
continue;
// convert to DateTime/DateTime?
if ((pt == typeof(DateTime) || pt == typeof(DateTime?)) && long.TryParse(val, out var milliseconds))
dynamicValue = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds);
// convert to DateTimeOffset/DateTimeOffset?
if ((pt == typeof(DateTimeOffset) || pt == typeof(DateTimeOffset?)) && long.TryParse(val, out milliseconds))
dynamicValue = DateTimeOffset.FromUnixTimeMilliseconds(milliseconds);
}
targetProp?.SetValue(dto, dynamicValue.GetType() == targetProp.PropertyType
? dynamicValue
: Convert.ChangeType(dynamicValue, Nullable.GetUnderlyingType(targetProp.PropertyType) ?? targetProp.PropertyType));
}
return dto;
}
}
}
|
091ba40e6b8d3b147ab3e15c9ec7521c1a6b18bd
|
C#
|
mattkgross/WorkoutLogPro
|
/Extensions/UserInfo.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
using WorkoutLogPro.Areas.Teams.Models;
namespace WorkoutLogPro.Extensions
{
public class AppUser : IdentityUser
{
public virtual UserInfo UserInfo { get; set; }
}
public class UserInfo : DbAccessibleModel
{
public int Id { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public virtual ICollection<Team> Teams { get; set; }
public UserInfo(string firstName, string lastName)
{
// Id autoset by entity upon db insertion.
FirstName = firstName;
LastName = lastName;
}
public string GetFullName()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
public class AppUserContext : IdentityDbContext<AppUser>, IUpdateableDbContext
{
public DbSet<UserInfo> UserInfo { get; set; }
public AppUserContext()
: base("DefaultConnection")
{
}
public DbSet GetDataSet(Type type)
{
// Don't need type in this case since there's only one data set.
return UserInfo;
}
}
}
|
2dbf1a2517982d34c98f73b1d9b4b3913972acd8
|
C#
|
Geralastel/CurrentlyInked
|
/CurrentlyInked/MainWindow.xaml.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CurrentlyInked
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string penListTxt = "penlist.txt";
string inkListTxt = "inklist.txt";
List<FountainPen> penList = new List<FountainPen>();
List<Ink> inkList = new List<Ink>();
public MainWindow()
{
InitializeComponent();
PopulatePenList();
PopulateInkList();
}
private void PensListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void InkListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void ButtonClick_Sort(object sender, RoutedEventArgs e)
{
//Sort pens and ink button
}
private void ButtonClick_AddPen(object sender, RoutedEventArgs e)
{
AddPen f = new AddPen();
//Add an event handler to update this form when the pen window is updated
f.PenListUpdated += new AddPen.InputUpdateHandler(AddPen_ButtonClicked);
f.ShowDialog();
}
private void AddPen_ButtonClicked(object sender, InputUpdateEventArgs e)
{
if (e.Input != null && e.Input2 != null && e.Input3 != null)
{
FountainPen pen = new FountainPen(e.Input, e.Input2, e.Input3);
penList.Add(pen);
//Add pen to penlist.txt
using (StreamWriter w = File.AppendText(penListTxt))
{
w.WriteLine(pen.ToTxt());
}
Console.WriteLine("{0} has been added", pen.Name);
}
PensListBox.Items.Refresh();
}
private void ButtonClick_AddInk(object sender, RoutedEventArgs e)
{
//Add ink button
AddInk f = new AddInk();
//Add an event handler to update this form when the pen window is updated
f.InkListUpdated += new AddInk.InputUpdateHandler(AddInk_ButtonClicked);
f.ShowDialog();
}
private void AddInk_ButtonClicked(object sender, InputUpdateEventArgs e)
{
if (e.Input != null && e.Input2 != null && e.Input3 != null)
{
Ink ink = new Ink(e.Input, e.Input2, e.Input3);
inkList.Add(ink);
//Add pen to penlist.txt
using (StreamWriter w = File.AppendText(inkListTxt))
{
w.WriteLine(ink.ToTxt());
}
Console.WriteLine("{0} has been added", ink.InkName);
}
InkListBox.Items.Refresh();
}
private void ButtonClick_Clear(object sender, RoutedEventArgs e)
{
if(InkListBox.SelectedIndex != -1)
{
InkListBox.SelectedIndex = -1;
}
if(PensListBox.SelectedIndex != -1)
{
PensListBox.SelectedIndex = -1;
}
}
private void ButtonClick_Remove(object sender, RoutedEventArgs e)
{
//Remove pen or ink button
//checks if an item is selected in the inklistbox
if (InkListBox.SelectedIndex != -1)
{
if (InkListBox.SelectedIndex > -1)
{
string line = null;
string inkInfo = inkList[InkListBox.SelectedIndex].ToTxt();
string tempFile = System.IO.Path.GetTempFileName();
//reads inklist file, writes to a temp file, deletes original file then moves temp file to original file location
using (StreamReader reader = new StreamReader(inkListTxt))
{
using (StreamWriter writer = new StreamWriter(tempFile))
{
while ((line = reader.ReadLine()) != null)
{
if (String.Compare(line, inkInfo) == 0)
{
Console.WriteLine("Comparing {0} and {1}", line, inkInfo);
continue;
}
writer.WriteLine(line);
}
}
}
File.Delete(inkListTxt);
File.Move(tempFile, inkListTxt);
inkList.RemoveAt(InkListBox.SelectedIndex);
InkListBox.Items.Refresh();
}
}
if (PensListBox.SelectedIndex != -1)
{
if (PensListBox.SelectedIndex > -1)
{
string line = null;
string penInfo = penList[PensListBox.SelectedIndex].ToTxt();
string tempFile = System.IO.Path.GetTempFileName();
//reads inklist file, writes to a temp file, deletes original file then moves temp file to original file location
using (StreamReader reader = new StreamReader(penListTxt))
{
using (StreamWriter writer = new StreamWriter(tempFile))
{
while ((line = reader.ReadLine()) != null)
{
if (String.Compare(line, penInfo) == 0)
{
Console.WriteLine("Comparing {0} and {1}", line, penInfo);
continue;
}
writer.WriteLine(line);
}
}
}
File.Delete(penListTxt);
File.Move(tempFile, penListTxt);
penList.RemoveAt(PensListBox.SelectedIndex);
PensListBox.Items.Refresh();
}
}
}
private void ButtonClick_AddToCurrentlyInked(object sender, RoutedEventArgs e)
{
//Add pen and ink to current rotation
}
private void ButtonClick_Done(object sender, RoutedEventArgs e)
{
//Done button, return to main menu
}
private void PensListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
}
private void PopulatePenList()
{
string[] lines = System.IO.File.ReadAllLines(penListTxt);
List<string> sortedList = new List<string>();
foreach (string line in lines)
{
sortedList.Add(line);
}
sortedList.Sort();
foreach (var line in sortedList)
{
String[] substrings = line.Split('*');
string brand, model, nib;
DateTime time;
brand = substrings[0];
model = substrings[1];
nib = substrings[2];
time = Convert.ToDateTime(substrings[3]);
penList.Add(new FountainPen(brand, model, nib, time));
}
PensListBox.ItemsSource = penList;
}
private void PopulateInkList()
{
string[] lines = System.IO.File.ReadAllLines(inkListTxt);
List<string> sortedList = new List<string>();
foreach (string line in lines)
{
sortedList.Add(line);
}
sortedList.Sort();
foreach (var line in sortedList)
{
string[] substrings = line.Split('*');
string brand, name, colour;
DateTime time;
brand = substrings[0];
name = substrings[1];
colour = substrings[2];
time = Convert.ToDateTime(substrings[3]);
inkList.Add(new Ink(brand, name, colour, time));
}
InkListBox.ItemsSource = inkList;
}
public string GetSubstringByString(string a, string b, string c)
{
return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b) - c.IndexOf(a) - a.Length));
}
private void PensListBox_SelectionChanged_2(object sender, SelectionChangedEventArgs e)
{
}
}
}
|
950dd520f15f079438b118a8136a8d82888d3070
|
C#
|
mricab/T6-TCP_Multithtreaded_v2
|
/Client/client/KeepAlive/KeepAlive.cs
| 3.1875
| 3
|
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace client
{
public class KeepAlive : IKeepAlive
{
// Properties
private static bool Keep;
private TcpClient Client;
private Thread KeeperThread;
// Events
public event EventHandler ServerDown;
public event EventHandler KeepAliveDown;
// Methods
public KeepAlive(TcpClient Client)
{
this.Client = Client;
}
public void Start()
{
Keep = true;
KeeperThread = new Thread(new ThreadStart(Process));
KeeperThread.Start();
}
public void Stop()
{
Keep = false;
}
private void Process()
{
Console.WriteLine("(Keeper)\tKeeper up.");
double delay = 2000; // 4s
DateTime lastTime = System.DateTime.Now;
DateTime now;
NetworkStream networkStream = Client.GetStream();
while (Keep)
{
now = System.DateTime.Now;
if ( now >= lastTime.AddMilliseconds(delay))
{
try
{
// Sending message
byte[] sendBytes;
GetInput(out sendBytes);
networkStream.Write(sendBytes, 0, sendBytes.Length);
// Receiving response
byte[] Bytes = new byte[Client.ReceiveBufferSize];
int BytesRead = networkStream.Read(Bytes, 0, (int)Client.ReceiveBufferSize);
GetResponse(Bytes, BytesRead);
}
catch (IOException) // Timeout
{
Console.WriteLine("(Keeper)\tServer timed out!");
OnServerDown();
break;
}
catch (SocketException)
{
Console.WriteLine("(Keeper)\tConection broken!");
break;
}
lastTime = now;
}
}
Console.WriteLine("(Keeper)\tKeeper stopped.");
OnKeepAliveDown();
}
private void GetResponse(byte[] Bytes, int BytesRead)
{
if (BytesRead > 0)
{
// Nothing
}
else
{
// Other end not responding (BytesRead == 0)
throw new System.Net.Sockets.SocketException();
}
}
private void GetInput(out byte[] Bytes)
{
Bytes = new byte[0];
String Data = "keep";
Bytes = Encoding.ASCII.GetBytes(Data);
}
// Dispachers
protected virtual void OnServerDown()
{
if (ServerDown != null)
{
ServerDown(this, EventArgs.Empty);
}
}
protected virtual void OnKeepAliveDown()
{
if (KeepAliveDown != null)
{
KeepAliveDown(this, EventArgs.Empty);
}
}
}
}
|
91e818ac9169c71f2eddf652fa77fb4ea30361b2
|
C#
|
marthinch/Reactive-Programming-Performance
|
/ReactiveProgramming/Program.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading.Tasks;
namespace ReactiveProgramming
{
class Program
{
static Stopwatch stopwatch = new Stopwatch();
static int generateNumber, divider;
static void Main(string[] args)
{
Console.WriteLine("Input number to generate data : ");
generateNumber = int.Parse(Console.ReadLine());
Console.WriteLine("Input number as divider : ");
divider = int.Parse(Console.ReadLine());
ReactiveData();
NonReactiveData();
//MultiTaskData().ConfigureAwait(false);
//ParallelData();
}
static List<int> Data(int generateNumber)
{
List<int> data = new List<int>();
for (int i = 0; i <= generateNumber; i++)
{
data.Add(i);
}
return data;
}
static void ReactiveData()
{
stopwatch.Reset();
stopwatch.Start();
Console.WriteLine("Reactive Data Start {0}", DateTime.Now);
Data(generateNumber).Where(item => item % divider == 0).ToObservable().SubscribeOn(Scheduler.NewThread).Subscribe(item =>
{
var newItem = item * 2;
//Console.WriteLine(newItem);
});
stopwatch.Stop();
Console.WriteLine("Reactive Data End {0} ms \n", stopwatch.Elapsed.TotalMilliseconds);
}
static void NonReactiveData()
{
stopwatch.Reset();
stopwatch.Start();
Console.WriteLine("Non-Reactive Data Start {0}", DateTime.Now);
foreach (int item in Data(generateNumber).Where(x => x % divider == 0))
{
var newItem = item * 2;
//Console.WriteLine(newItem);
}
stopwatch.Stop();
Console.WriteLine("Non-Reactive Data End {0} ms \n", stopwatch.Elapsed.TotalMilliseconds);
}
static async Task MultiTaskData()
{
stopwatch.Reset();
stopwatch.Start();
Console.WriteLine("Multi Task Data Start {0}", DateTime.Now);
List<Task> tasks = new List<Task>();
foreach (int item in Data(generateNumber).Where(item => item % divider == 0))
{
Task task = Task.Run(() =>
{
var newItem = item * 2;
//Console.WriteLine(newItem);
});
tasks.Add(task);
}
await Task.WhenAll(tasks);
stopwatch.Stop();
Console.WriteLine("Multi Task Data End {0} ms \n", stopwatch.Elapsed.TotalMilliseconds);
}
static void ParallelData()
{
stopwatch.Reset();
stopwatch.Start();
Console.WriteLine("Parallel Data Start {0}", DateTime.Now);
Parallel.ForEach(Data(generateNumber).Where(item => item % divider == 0), item =>
{
var newItem = item * 2;
//Console.WriteLine(newItem);
});
stopwatch.Stop();
Console.WriteLine("Parallel Data End {0} ms \n", stopwatch.Elapsed.TotalMilliseconds);
}
}
}
|
a8819e53d0bbc2c73df3ba690aefb63ac4bd6018
|
C#
|
cgcq007/Inventory
|
/InventoryTest/User/Detail.cs
| 2.546875
| 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 InventoryTest
{
public partial class Detail : Form
{
string sn;
string orderId;
string inOrOut;
public Detail(string sn, string orderId, string inOrOut)
{
this.sn = sn;
this.orderId = orderId;
this.inOrOut = inOrOut;
InitializeComponent();
}
private void Deatil_Load(object sender, EventArgs e)
{
using (ItemContext ctx = new ItemContext())
{
if (inOrOut == "In Inventory")
{
var item = ctx.Items.Where(s => s.SN == sn).FirstOrDefault<Item>();
itemInOperator.Text = item.ItemInOperator;
serviceMan.Text = item.ServiceMan;
returnCode.Text = item.ReturnCode;
}else
{
var item = ctx.ItemsDisposed.Where(o => o.OrderId == orderId).Where(s => s.SN == sn).FirstOrDefault<ItemDisposed>();
itemInOperator.Text = item.ItemInOperator;
serviceMan.Text = item.ServiceMan;
itemOutOperator.Text = item.ItemOutOperator;
returnCode.Text = item.ReturnCode;
}
}
}
}
}
|
2c072d7c3f2ef930c60cf1cb242c61453f8f212d
|
C#
|
Minddarkness/Organization
|
/11-12_HW2/HW11_2/Program.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace HW11_2
{
class Program
{
static void Main(string[] args)
{
Organization organization = new Organization("Org", new Manager("Mick", "Director"));
Department dep1 = new Department("dep1", new Manager("Gosha", "Director of dep1"));
Department dep2 = new Department("dep2", new Manager("Bob", "Director of dep2"));
dep1.AddWorker(new Employee("Masha", "Worcker", dep1));
dep1.AddWorker(new Employee("Pasha", "Worcker", dep1));
dep2.AddWorker(new Employee("Dasha", "Worcker", dep2));
Department dep11 = new Department("dep11", new Manager("Alisa", "Director of dep11"));
Department dep12 = new Department("dep12", new Manager("Bob", "Director of dep12"));
dep11.AddWorker(new Intern("Bill", "Worcker", dep11));
dep12.AddWorker(new Employee("Gosha", "Worcker", dep12));
Department dep111 = new Department("dep111", new Manager("Katerina", "Director of dep111"));
dep111.AddWorker(new Employee("Oleg", "Programmer", dep111));
dep11.AddSubDepartment(dep111);
Department dep21 = new Department("dep21", new Manager("Gosha", "Director of dep21"));
Department dep22 = new Department("dep22", new Manager("Bob", "Director of dep22"));
Department dep23 = new Department("dep23", new Manager("Gosha", "Director of dep23"));
dep21.AddWorker(new Intern("Bill", "Worcker", dep21));
dep21.AddWorker(new Employee("Gosha", "Worcker", dep21));
dep22.AddWorker(new Intern("Bill", "Worcker", dep22));
dep22.AddWorker(new Employee("Gosha", "Worcker", dep22));
dep23.AddWorker(new Intern("Bill", "Worcker", dep23));
dep23.AddWorker(new Employee("Gosha", "Worcker", dep23));
organization.AddSubDepartment(dep1);
organization.AddSubDepartment(dep2);
dep1.AddSubDepartment(dep11);
dep1.AddSubDepartment(dep12);
dep2.AddSubDepartment(dep21);
dep2.AddSubDepartment(dep22);
dep2.AddSubDepartment(dep23);
WriteLine(organization);
//organization.Serialization("Org1.json");
//organization.DeleteDepartmentByID(2, false);
organization.Serialization("Org1.json");
WriteLine("Удаление");
//WriteLine(organization);
Organization organization1 = Organization.Deserialization("Org1.json");
WriteLine(organization1);
}
}
}
|
4b466389948d8ba1b52a682ba3688b053643f0cc
|
C#
|
simonauner/knightbus
|
/knightbus/src/KnightBus.Core/JsonMessageSerializer.cs
| 2.828125
| 3
|
using System.Reflection;
using KnightBus.Messages;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace KnightBus.Core
{
/// <summary>
/// Default serializer
/// </summary>
public class JsonMessageSerializer : IMessageSerializer
{
public JsonSerializerSettings Settings { get; set; }
public JsonMessageSerializer()
{
Settings = new JsonSerializerSettings { ContractResolver = new IgnoreAttachmentsResolver() };
}
public string Serialize<T>(T message)
{
return JsonConvert.SerializeObject(message, Settings);
}
public T Deserialize<T>(string serializedString)
{
return JsonConvert.DeserializeObject<T>(serializedString, Settings);
}
public string ContentType => "application/json";
}
public class IgnoreAttachmentsResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var prop = base.CreateProperty(member, memberSerialization);
if (typeof(ICommandWithAttachment).IsAssignableFrom(member.DeclaringType) && member.Name == nameof(ICommandWithAttachment.Attachment))
{
prop.Ignored = true;
}
return prop;
}
}
}
|
534b18edb8197e7af860c86d619649f7b8cfdf6a
|
C#
|
VladislavBI/BlackJack---NP
|
/GameTable/NamespaceGame/GamesProcess.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GameTable.NamespacePlayers;
using GameTable.CardDeck;
using System.Windows;
namespace GameTable.NamespaceGame
{
public abstract class BaseGame
{
/// <summary>
/// Действия в начале игры
/// </summary>
/// <param name="CompPlayersQty"></param>
public abstract void GameStart(int CompPlayersQty);
/// <summary>
/// Создание поля игрока - привязка к WPF
/// </summary>
public void PlayersPoolCreate()
{
DelegatesData.HandlerCreateTableViewForCurrentPlayer();
}
#region Действия игрока-человека
/// <summary>
/// Возврат играющего игрока
/// </summary>
/// <returns>Текущий игрок</returns>
public abstract HumanPlayer GetCurrentHumanPlayer();
/// <summary>
/// Игрок берет новую карту
/// </summary>
public abstract void HumanPlayerGetsCard();
/// <summary>
/// Игрок заканчивает ход
/// </summary>
public abstract void HumanStopPlaying();
/// <summary>
/// Переход хода к следующему игроку
/// </summary>
public abstract void TurnComesToNextPlayer();
#endregion
/// <summary>
/// Объявление победителей
/// </summary>
public abstract void AnnouncementOfWinners();
/// <summary>
/// Создание новой колоды
/// </summary>
public abstract void CreateNewDeck();
/// <summary>
/// Создание следующей партии
/// </summary>
public abstract void GameRestart();
}
public class GamesProcess:BaseGame
{
#region Поля класса
/// <summary>
/// Список всех игроков
/// </summary>
List<Player> ActivePlayersList = new List<Player>();
/// <summary>
/// Номера игроков-людей
/// </summary>
Queue<int> HumanPlayerNumber = new Queue<int>();
/// <summary>
/// Номер текущего игрока
/// </summary>
int currentPlayerNumber=-1;
/// <summary>
/// Таблица результатов (номер игрока/количество очков)
/// </summary>
Dictionary<int, int> scoreTable = new Dictionary<int, int>();
/// <summary>
/// Игровая колода
/// </summary>
GeneralDeck genDeck;
#endregion
#region Создание стола
/// <summary>
/// Действия в начале игры
/// </summary>
/// <param name="CompPlayersQty"></param>
public override void GameStart(int CompPlayersQty)
{
CreateNewDeck();
//Присвоение делегата для следующего хода
DelegatesData.HandlerPlayerIsMoreThanEnough =
new DelegatesData.PlayerIsMoreThanEnough(TurnComesToNextPlayer);
//Создание игрового стола
BotPlayersCreate(CompPlayersQty);
GameStartsCommon();
}
/// <summary>
/// Создание следующей партии
/// </summary>
public override void GameRestart()
{
foreach (var item in ActivePlayersList)
{
item.cardsOnHand.NullifyDeck();
}
HumanPlayerQueueReCreate();
GameStartsCommon();
}
/// <summary>
/// Общее в двух классах-началах игры
/// </summary>
void GameStartsCommon()
{
//Изменение состояния кнопок
DelegatesData.HandlerTableButtonsIsEnanbleChange(true);
GetStartCards();
PlayersPoolCreate();
}
/// <summary>
/// Создание новой колоды
/// </summary>
public override void CreateNewDeck()
{
genDeck = new GeneralDeck();
}
/// <summary>
/// Казино раздает по 2 карты всем игрокам
/// </summary>
void GetStartCards()
{
for (int i = 0; i < 2; i++)
{
foreach (Player pl in ActivePlayersList)
{
pl.PutCardInDeck(genDeck.GetCard());
}
}
}
/// <summary>
/// Заполнение таблицы всех результатов игроков
/// </summary>
public void ResultsCalculating()
{
for (int i = 0; i < ActivePlayersList.Count; i++)
{
scoreTable.Add(i, ActivePlayersList[i].GetPlayersPoints());
}
}
/// <summary>
/// Создание новой общей колоды карт
/// </summary>
#endregion
#region Выбор победителя
/// <summary>
/// Объявление победителей
/// </summary>
public override void AnnouncementOfWinners()
{
List<Player> winnerList = WinnerChoose();
switch (winnerList.Count)
{
case 0:
MessageBox.Show("Победитей нет!");
break;
case 1:
MessageBox.Show(string.Format("Победил игрок {0} с {1} очками",
winnerList[0].playersName, winnerList[0].GetPlayersPoints()));
break;
default:
string winnerAnnounce =
"Победили игроки с количеством очков " + winnerList[0].GetPlayersPoints()+ "\n";
foreach (Player pl in winnerList)
{
winnerAnnounce += pl.playersName + "\n";
}
break;
}
}
/// <summary>
/// Процесс выбора победителей
/// </summary>
/// <returns>Список победителей</returns>
List<Player> WinnerChoose()
{
int currentWinScore = 0;
List<Player> winnersList = new List<Player>();
currentWinScore = BestScoreSeek();
winnersList = WinnersListCreating(currentWinScore);
return winnersList;
}
/// <summary>
/// Поиск лучшего счета среди игроков
/// </summary>
/// <returns>Лучший счет</returns>
int BestScoreSeek()
{
int test = 0;
foreach (Player pl in ActivePlayersList)
{
if (pl.GetPlayersPoints() <= 21 && pl.GetPlayersPoints() > test)
test = pl.GetPlayersPoints();
}
return test;
}
/// <summary>
/// Составление списка победителей
/// </summary>
/// <param name="BestScore">Лучший счет</param>
/// <returns>Список победителей</returns>
List<Player> WinnersListCreating(int BestScore)
{
//Нахождение всех игроков с определенным счетом
var WinnersList = from pl in ActivePlayersList where pl.GetPlayersPoints() == BestScore select pl;
List<Player> winners = new List<Player>();
//проверка на дилера (при равном счете он побеждает)
foreach (Player pl in WinnersList)
{
if (pl is Dealer)
{
winners.Clear();
winners.Add(pl);
return winners;
}
winners.Add(pl);
}
return winners;
}
#endregion
#region Создание игроков
/// <summary>
/// Создание нового игрока-человека
/// </summary>
/// <param name="name"></param>
public void HumanPlayerCreate(string name)
{
//Создание нового игрока типа HumanPlayer
ActivePlayersList.Add(new HumanPlayer(name));
//Фиксация номера этого игрока и установка его как текущего (если других небыло)
HumanPlayerQueueFix(ActivePlayersList.Count - 1);
}
/// <summary>
/// Фиксация номера игрока человека
/// </summary>
public void HumanPlayerQueueFix(int plNumber)
{
HumanPlayerNumber.Enqueue(plNumber);
if (HumanPlayerNumber.Count == 1)
currentPlayerNumber = HumanPlayerNumber.Peek();
}
/// <summary>
/// Пересоздание списка номеров игроков-людей
/// </summary>
public void HumanPlayerQueueReCreate()
{
HumanPlayerNumber.Clear();
for (int i = 0; i < ActivePlayersList.Count; i++)
{
if (ActivePlayersList[i] is HumanPlayer)
{
HumanPlayerQueueFix(i);
}
}
}
/// <summary>
/// Добавление дилера и ботов в игру
/// </summary>
/// <param name="quantity">Количество ботов</param>
void BotPlayersCreate(int quantity)
{
//Проверка на режим дуэли - игрок против игрока
if (quantity != 0)
{
//добавление в игру дилера
ActivePlayersList.Add(new Dealer());
//добавление ботов
for (int i = 0; i < quantity - 1; i++)
{
ActivePlayersList.Add(new CompPlayer());
}
}
}
#endregion
#region Действия игрока-человека
/// <summary>
/// Возврат играющего игрока
/// </summary>
/// <returns>Текущий игрок</returns>
public override HumanPlayer GetCurrentHumanPlayer()
{
return ActivePlayersList[currentPlayerNumber] as HumanPlayer;
}
/// <summary>
/// Игрок берет новую карту
/// </summary>
public override void HumanPlayerGetsCard()
{
ActivePlayersList[currentPlayerNumber].AchievingOfCard();
}
/// <summary>
/// Игрок заканчивает ход
/// </summary>
public override void HumanStopPlaying()
{
//игрок заканчивает свой ход
ActivePlayersList[currentPlayerNumber].PlayerStopsTurn();
}
/// <summary>
/// Переход хода к следующему игроку
/// </summary>
public override void TurnComesToNextPlayer()
{
currentPlayerNumber = HumanPlayerNumber.Dequeue();
//Назначение следующего активного игрока, создание его игрового стола
if (HumanPlayerNumber.Count != 0)
{
PlayersPoolCreate();
}
//Если игроков нет - играют боты
else
{
DelegatesData.HandlerTableButtonsIsEnanbleChange(false);
BotsAreMoving();
}
}
#endregion
/// <summary>
/// Ход ботов
/// </summary>
public void BotsAreMoving()
{
//список всех ботов за столом
var botsPlayers = ActivePlayersList.FindAll(item => item is CompPlayer);
//Проверка - есть ли боты
if (botsPlayers.Count > 0)
{
//каждый бот делает свой ход
foreach (CompPlayer pl in botsPlayers)
{
pl.CompsTurn();
}
}
DelegatesData.HandlerWinnerPlayerShow();
}
/// <summary>
/// Возврат списка имен всех игроков
/// </summary>
/// <returns>Список имен игроков</returns>
public List<String> GetActivePlayersList()
{
List<string> temp=new List<string>();
foreach (var pl in ActivePlayersList)
{
temp.Add(pl.playersName);
}
return temp;
}
}
}
|
8ec8e627e3dc64b081c0c00ad03862dc1053c1c1
|
C#
|
Miwss/MiwssTrash
|
/Преобразование типов/Преобразование типов/Program.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Преобразование_типов
{
class Program
{
static int x;
static double y = 10.09D;
static double z = 2.98D;
static void Main(string[] args)
{
x = (int)(y / z);
Console.WriteLine("x - " + x);
}
}
}
|
161ebe60d3671249dbb504f4aa5bcdfcfcc2067d
|
C#
|
FlorianGrimm/OfaSchlupfer
|
/OfaSchlupfer.MSSQLReflection/Model/ModelSqlObjectWithColumns.cs
| 2.625
| 3
|
namespace OfaSchlupfer.MSSQLReflection.Model {
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using OfaSchlupfer.Freezable;
/// <summary>
/// anything that owns columns
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public abstract class ModelSqlObjectWithColumns
: ModelSqlSchemaChild
, IScopeNameResolver
, IModelSqlObjectWithColumns {
/// <summary>
/// the columns
/// </summary>
[JsonIgnore]
protected FreezableOwnedKeyedCollection<ModelSqlObjectWithColumns, SqlName, ModelSqlColumn> _Columns;
[JsonIgnore]
protected FreezableOwnedKeyedCollection<ModelSqlObjectWithColumns, SqlName, ModelSqlIndex> _Indexes;
/// <summary>
/// Initializes a new instance of the <see cref="ModelSqlObjectWithColumns"/> class.
/// </summary>
public ModelSqlObjectWithColumns() {
this._Columns = new FreezableOwnedKeyedCollection<ModelSqlObjectWithColumns, SqlName, ModelSqlColumn>(
this,
(item) => item.Name,
SqlNameEqualityComparer.Level1,
(owner, item) => item.Owner = owner
);
this._Indexes = new FreezableOwnedKeyedCollection<ModelSqlObjectWithColumns, SqlName, ModelSqlIndex>(
this,
(item) => item.Name,
SqlNameEqualityComparer.Level1,
(owner, item) => item.Owner = owner
);
}
/// <summary>
/// Initializes a new instance of the <see cref="ModelSqlObjectWithColumns"/> class.
/// </summary>
/// <param name="src">the source instance.</param>
public ModelSqlObjectWithColumns(ModelSqlObjectWithColumns src)
: this() {
if ((object)src != null) {
this.Name = src.Name;
this._Columns.AddRange(src.Columns);
}
}
/// <summary>
/// Get the current scope
/// </summary>
/// <returns>this scope</returns>
public virtual SqlScope GetScope() => null;
/// <summary>
/// Gets the columns
/// </summary>
[JsonProperty]
public FreezableOwnedKeyedCollection<ModelSqlObjectWithColumns, SqlName, ModelSqlColumn> Columns => this._Columns;
[JsonIgnore]
IFreezableOwnedKeyedCollection<SqlName, ModelSqlColumn> IModelSqlObjectWithColumns.Columns => this._Columns;
[JsonProperty]
public FreezableOwnedKeyedCollection<ModelSqlObjectWithColumns, SqlName, ModelSqlIndex> Indexes => this._Indexes;
[JsonIgnore]
IFreezableOwnedKeyedCollection<SqlName, ModelSqlIndex> IModelSqlObjectWithColumns.Indexes => this._Indexes;
/// <summary>
/// Resolve the name.
/// </summary>
/// <param name="name">the name to find the item thats called name</param>
/// <param name="context">the resolver context.</param>
/// <returns>the named object or null.</returns>
public virtual object ResolveObject(SqlName name, IScopeNameResolverContext context) {
for (int idx = 0; idx < this.Columns.Count; idx++) {
var column = this.Columns[idx];
if (column.Name.Equals(name)) {
return column;
}
}
return null;
}
}
}
|
dbf1a611ce4a76eda7f06f950272c96ca01eab05
|
C#
|
platan-csoft/Platan
|
/frmInputManuallyTime.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace sprut
{
public partial class frmInputManuallyTime : Form
{
public string InputManualPlanTime;
public frmInputManuallyTime()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
InputManualPlanTime = txtBoxInputPlanValue.Text;
ValidateInputNumber(ref InputManualPlanTime);
this.Close();
}
private void ValidateInputNumber(ref string InputManualPlanTime)
{
InputManualPlanTime = InputManualPlanTime.Replace(" ", string.Empty);
InputManualPlanTime = InputManualPlanTime.Replace('.', ',');
double input = 0;
if (Double.TryParse(InputManualPlanTime, out input))
{
InputManualPlanTime = input.ToString();
}
else
{
InputManualPlanTime = "null";
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
InputManualPlanTime = "null";
this.Close();
}
private void txtBoxInputPlanValue_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnOK_Click(sender, (EventArgs)e);
}
}
}
}
|
aed64b9a5ec74f5c6333ed3f0889b4405bdd9788
|
C#
|
yCatDev/EndlessMaze
|
/EndlessMazeGame/Maze/MazeCell.cs
| 2.734375
| 3
|
using AbstractEngine.Core.Base;
namespace EndlessMazeGame.Maze
{
public struct MazeCell
{
public Point Position;
public bool IsEmpty { get; set; }
public bool IsVisited { get; set; }
public MazeCell(int x, int y, bool isVisited = false, bool isCell = true)
{
Position = new Point(x,y);
IsEmpty = isCell;
IsVisited = isVisited;
}
}
}
|
e98c1b00134450fe5e0e361d00792431d18f5712
|
C#
|
JavaBeginner66/Bachelor-project
|
/Assets/Scripts/GameMasterScript.cs
| 2.765625
| 3
|
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
/*
* Script handles status of game and different UI functions
*/
public class GameMasterScript : MonoBehaviour
{
public static GameMasterScript gameMasterScript; // Static reference for easy access
public static bool gameRunning; // Status of game
public static bool gameIsPaused; // True if game is paused
private bool gameIsOver; // True if player is dead
public GameObject pausePanel; // Pause panel UI object
public GameObject gameOverPanel; // Game over panel UI object
public GameObject player; // Player object reference
public EnemyAI enemyAI; // Boss object reference
public TextMeshProUGUI scoreText; // Score text displayed on game over screen
public TextMeshProUGUI topScoreText; // Top score text displayed on game over screen
public TextMeshProUGUI anyButtonStartText; // "Click any button to start" text at the start of game
public readonly string scoreKey = "Score"; // Key for saving score in PlayerPrefs
public readonly string stageKey = "Stage"; // Key for saving stage in PlayerPrefs
public GameObject[] minimalismObjects; // Array of objects that will disappear/appear from scene
/*
* Start sets up references and checks if PlayerPrefs has existing keys
*/
private void Start()
{
gameMasterScript = this;
enemyAI = EnemyAI.enemyAI;
gameIsPaused = false;
gameIsOver = false;
anyButtonStartText.text = "Click any button to start";
// Get volume and graphics stored in PlayerPrefs and set them
if (PlayerPrefs.HasKey(MenuScript.graphicsKey))
QualitySettings.SetQualityLevel(PlayerPrefs.GetInt(MenuScript.graphicsKey));
if (PlayerPrefs.HasKey(MenuScript.minimalismKey))
minimalism();
}
/*
* Update is used to detect player click to start the game, and "esc" to pause it
*/
private void Update()
{
if (Input.anyKeyDown)
{
if (!gameIsOver)
{
gameRunning = true;
StartCoroutine(enemyAI.PhaseMachine());
anyButtonStartText.text = "";
}
}
if (gameRunning)
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if (!gameIsPaused)
Pause();
else
Resume();
}
}
}
/*
* Method removes/adds some of the objects from the scene
*/
private void minimalism()
{
if (PlayerPrefs.GetInt(MenuScript.minimalismKey) == 1)
foreach (var item in minimalismObjects)
item.SetActive(false);
else
foreach (var item in minimalismObjects)
item.SetActive(true);
}
/*
* Method listens for click on "Play again" on game over screen, and reloads the scene through FadeTransition script
*/
public void PlayAgain()
{
FadeTransition.fade.fadeTo(SceneManager.GetActiveScene().buildIndex);
}
/*
* Method stops all game activity, and gets scores to show player in gameover screen
*/
public void GameOver()
{
gameRunning = false;
gameIsOver = true;
gameOverPanel.SetActive(true);
// Saving and getting highscore from playerprefs
int stage = enemyAI.getPhase();
int score = (int)enemyAI.getPlayerScore();
// Building the strings
string current = "Stage: " + stage + ", " + score.ToString("N0") + " Points";
string highest = "Highest score" + "\n" + "Stage: " + PlayerPrefs.GetInt(stageKey) + ", Score: " + PlayerPrefs.GetInt(scoreKey);
// If Playerprefs doesn't already have a key stores, the player plays for the first time and it will be a topscore
if (!PlayerPrefs.HasKey(scoreKey))
{
scoreText.text = "New topscore! " + "\n" + current;
PlayerPrefs.SetInt(stageKey, stage);
PlayerPrefs.SetInt(scoreKey, score);
}
else
{
// If a key exist, check current score compared to previous
if(stage >= PlayerPrefs.GetInt(stageKey) && score > PlayerPrefs.GetInt(scoreKey))
{
scoreText.text = "New topscore! " + "\n" + current;
}
else
{
scoreText.text = current;
topScoreText.text = highest;
}
}
}
/*
* Method pauses the game and freezes gametime
*/
public void Pause()
{
if (gameRunning)
{
pausePanel.SetActive(true);
gameIsPaused = true;
Time.timeScale = 0f;
}
}
/*
* Method resumes game and unfreezes gametime
*/
public void Resume()
{
if (gameRunning)
{
pausePanel.SetActive(false);
gameIsPaused = false;
Time.timeScale = 1f;
}
}
/*
* Method detects click on "Menu" on either pause screen or gameover screen,
* and changes scene to Menu trough FadeTransition script
*/
public void Menu()
{
Time.timeScale = 1f;
FadeTransition.fade.fadeTo(0);
}
/*
* Method detects click on "Quit" and quits game
*/
public void QuitGame()
{
Application.Quit();
}
/*
* Get method
*/
public GameObject getPlayer()
{
return player;
}
}
|
d3a82ac5060b4bd5a7716febc26d5371c9559364
|
C#
|
kuzmanovb/SoftUni
|
/4. C# OOP/OOP Exams/Exam - 18 Apr 2019 (Full)/1.Structure and Business Logic - 150%/PlayersAndMonsters/Core/Factories/PlayerFactory.cs
| 2.625
| 3
|
using PlayersAndMonsters.Core.Factories.Contracts;
using PlayersAndMonsters.Models.Players;
using PlayersAndMonsters.Models.Players.Contracts;
using PlayersAndMonsters.Repositories;
using System;
using System.Collections.Generic;
using System.Text;
namespace PlayersAndMonsters.Core.Factories
{
public class PlayerFactory : IPlayerFactory
{
public IPlayer CreatePlayer(string type, string username)
{
if (type == "Advanced")
{
return new Advanced(new CardRepository(), username);
}
else if (type == "Beginner")
{
return new Beginner(new CardRepository(), username);
}
else
{
return null;
}
}
}
}
|
5a30b92ae0752c2d8f5a6168e2846a3d2dbde1c0
|
C#
|
NinetailLabs/VaraniumSharp.Monolith
|
/VaraniumSharp.Monolith/Extensions/HostConfiguratorExtensions.cs
| 2.828125
| 3
|
using System.Collections.Generic;
using System.Linq;
using Topshelf.HostConfigurators;
using VaraniumSharp.Monolith.Enumerations;
namespace VaraniumSharp.Monolith.Extensions
{
/// <summary>
/// Extension methods for <see cref="HostConfigurator"/>
/// </summary>
public static class HostConfiguratorExtensions
{
#region Public Methods
/// <summary>
/// Apply valid TopShelf command line parameters to the TopShelf configurator
/// </summary>
/// <param name="configurator">TopShelf HostConfigurator</param>
/// <param name="arguments">List of command line arguments</param>
public static void ApplyValidCommandLine(this HostConfigurator configurator, List<string> arguments)
{
var validCommandlineParameters = new List<string>();
validCommandlineParameters.AddRange(arguments.Where(t => TopShelfCommandLineArguments.Verbs.Contains(t)));
validCommandlineParameters.AddRange(arguments.Where(t => TopShelfCommandLineArguments.Options.FirstOrDefault(t.StartsWith) != null));
validCommandlineParameters.AddRange(arguments.Where(t => TopShelfCommandLineArguments.Switches.FirstOrDefault(t.StartsWith) != null));
configurator.ApplyCommandLine(string.Join(" ", validCommandlineParameters));
}
#endregion
}
}
|
d4bf13115d12f7524f3ceae6f352668bbf2e457b
|
C#
|
robbieg9876/My-Code
|
/source/repos/Assessment1/CanvassTests/UnitTest1.cs
| 3.1875
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Drawing;
using Assessment1;
using System;
using System.Linq;
using Microsoft.VisualBasic;
namespace CanvassTests
{
[TestClass]
public class UnitTest1 {
//Initialises bitmap with set size
Bitmap OutputBitMap = new Bitmap(871, 548);
//Makes an instance of the Canvass class
readonly Canvass Test;
public UnitTest1()
{
//Sets graphics up on bitmap
Test = new Canvass(Graphics.FromImage(OutputBitMap));
}
[TestMethod]
public void MoveToTest()
{
//Sets integer variables
int toX = 250;
int toY = 250;
//Passes values as parameters to Test.MoveTo
Test.MoveTo(toX, toY);
//Checks if the statements are true as expected
Assert.IsTrue(toX == Test.xPos);
Assert.IsTrue(toY ==Test.yPos);
}
[TestMethod]
public void DrawToTest()
{
//Sets integer variables
int toX = 250;
int toY = 250;
//Passes values as parameters to Test.MoveTo
Test.DrawTo(toX, toY);
//Checks if the statements are true as expected
Assert.IsTrue(toX == Test.xPos);
Assert.IsTrue(toY == Test.yPos);
}
[TestMethod]
public void PenColourCheck()
{
//Sets integer variables
Color colour = Color.Red;
//Passes values as parameters to Test.MoveTo
Test.PenColour(colour);
//Checks if the statements are true as expected
Assert.AreEqual(colour, Test.Pen.Color);
}
[TestMethod]
public void ResetPenTest()
{
//Sets integer variables
int toX = 0;
int toY = 0;
//Passes values as parameters to Test.MoveTo
Test.resetPenPosition();
//Checks if the statements are true as expected
Assert.IsTrue(toX == Test.xPos);
Assert.IsTrue(toY == Test.yPos);
}
[TestMethod]
public void FillOnTest()
{
//Sets integer variables
Boolean fill = true;
//Checks if the statements are true as expected
Test.FillShape(fill);
Assert.AreEqual(fill,Test.Fill);
}
[TestMethod]
public void FillOffTest()
{
//Sets integer variables
Boolean fill = false;
//Checks if the statements are true as expected
Test.FillShape(fill);
Assert.AreEqual(fill, Test.Fill);
}
[TestMethod]
public void DrawSquareTest()
{
//Sets integer variables
int width = 50;
int toX = Test.xPos;
int toY = Test.yPos;
//Passes values as parameters to Test.MoveTo
Test.DrawSquare(width);
//Checks if the statements are true as expected
//Checks drawing position has not changed
Assert.IsTrue(toX == Test.xPos);
Assert.IsTrue(toY == Test.yPos);
//Checks shape is the same size as expected
Assert.IsTrue(toX + width == Test.xPos + width);
Assert.IsTrue(toY + width == Test.yPos + width);
}
[TestMethod]
public void DrawCircleTest()
{
//Sets integer variables
int radius = 50;
int toX = Test.xPos;
int toY = Test.yPos;
//Passes values as parameters to Test.MoveTo
Test.DrawCircle(radius);
//Checks if the statements are true as expected
//Checks drawing position has not changed
Assert.IsTrue(toX == Test.xPos);
Assert.IsTrue(toY == Test.yPos);
//Checks shape is the same size as expected
Assert.IsTrue(toX + radius == Test.xPos + radius);
Assert.IsTrue(toY + radius == Test.yPos + radius);
Assert.IsTrue(toX - radius == Test.xPos - radius);
Assert.IsTrue(toY - radius == Test.yPos - radius);
}
[TestMethod]
public void DrawTriangleTest()
{
//Sets integer variables
int width = 50;
int height = 150;
int toX = Test.xPos;
int toY = Test.yPos;
//Passes values as parameters to Test.MoveTo
Test.DrawTriangle(width,height);
//Checks if the statements are true as expected
//Checks drawing position has not changed
Assert.IsTrue(toX == Test.xPos);
Assert.IsTrue(toY == Test.yPos);
//Checks shape is the same size as expected
Assert.IsTrue(toX + width == Test.xPos + width);
Assert.IsTrue(toY + height == Test.yPos + height);
}
[TestMethod]
public void DrawRectangleTest()
{
//Sets integer variables
int width = 50;
int height = 150;
int toX = Test.xPos;
int toY = Test.yPos;
//Passes values as parameters to Test.MoveTo
Test.DrawRectangle(width, height);
//Checks if the statements are true as expected
//Checks drawing position has not changed
Assert.IsTrue(toX == Test.xPos);
Assert.IsTrue(toY == Test.yPos);
//Checks shape is the same size as expected
Assert.IsTrue(toX + width == Test.xPos + width);
Assert.IsTrue(toY + height == Test.yPos + height);
}
[TestMethod]
public void InitializeVariableTest()
{
String variableName = "Test";
int value = 50;
//Passes values as parameters to Test.MoveTo
Test.InitaliseVariable(variableName, value);
//Checks shape is the same size as expected
Assert.IsTrue(variableName == Test.CurrentVariableName);
Assert.IsTrue(value == Test.CurrentVariableValue);
}
[TestMethod]
public void LoopTest()
{
int startLine = 10;
int endLine = 15;
//Passes values as parameters to Test.MoveTo
Test.Loop(startLine, endLine);
//Checks shape is the same size as expected
Assert.IsTrue(startLine == Test.StartLine);
Assert.IsTrue(endLine == Test.EndLine);
}
[TestMethod]
public void IfStatementTest()
{
int startLine = 10;
int endLine = 15;
//Passes values as parameters to Test.MoveTo
Test.IfStatement(startLine, endLine);
//Checks shape is the same size as expected
Assert.IsTrue(startLine == Test.StartLine);
Assert.IsTrue(endLine == Test.EndLine);
}
[TestMethod]
public void MethodsTest()
{
string methodName = "MyMethod";
string[] Parameters = new string [100];
Parameters.Append("188");
Parameters.Append("200");
Parameters.Append("300");
//Passes values as parameters to Test.MoveTo
Test.Methods(methodName, Parameters);
//Checks shape is the same size as expected
Assert.IsTrue(methodName.Equals(Test.CurrentMethodName));
Assert.AreEqual(Parameters[0], Test.CurrentParameters[0]);
Assert.AreEqual(Parameters[1], Test.CurrentParameters[1]);
Assert.AreEqual(Parameters[2], Test.CurrentParameters[2]);
}
}
}
|
4a03466a7ec8a0c1c1de2c3fc421903b3f34e437
|
C#
|
TanimSarwar/University-Course-and-Result-Management-System
|
/UniversityCourseandresultManagementSystem/Manager/ClassRoomManager.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using UniversityCourseandresultManagementSystem.Gateway;
using UniversityCourseandresultManagementSystem.Models;
namespace UniversityCourseandresultManagementSystem.Manager
{
public class ClassRoomManager
{
ClassRoomGateway aClassRoomGateway = new ClassRoomGateway();
public string AllocateNewClassRoom(ClassRoomAllocation aClassRoomAllocation)
{
if (!aClassRoomGateway.IsClassRoomAllocatioPossible(aClassRoomAllocation))
{
return "ClassRoom is not availabe in this time";
}
else
{
int rowAffected = aClassRoomGateway.AllocateNewClassRoom(aClassRoomAllocation);
if (rowAffected>0)
{
return "ClassRoom Allocated Successfully";
}
return "ClassRoom Allocation Failed";
}
}
public List<ClassRoom> GetAllClassRooms()
{
return aClassRoomGateway.GetAllClassRooms();
}
public string UnAllocateClassRooms()
{
int rowAffected = aClassRoomGateway.UnAllocateClassRooms();
if (rowAffected > 0)
{
return "ClassRooms are Successfully UnAllocated";
}
else
{
return "UnAllocation of ClassRoom Failed";
}
}
public List<ClassSchedule> GetAllClassScheduleByDeptId(int departmentId)
{
return aClassRoomGateway.GetAllClassScheduleByDeptId(departmentId);
}
}
}
|
1e5b2c20ccdc390d2fbb20f0d2e6a3597dbdf4c1
|
C#
|
praveenshin/Angular-JS
|
/Final-master/AngularJSWebApi/Models/BusRepository.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace AngularJSWebApi.Models
{
public class BusRepository:IBusRepository
{
private DatabaseEntity7 db = new DatabaseEntity7();
public IEnumerable<Bus> GetAll()
{
return db.Buses.ToList();
}
public Bus GetBusById(int id)
{
return db.Buses.Find(id);
}
public Bus AddBus(Bus b)
{
if (b == null)
{
throw new NullReferenceException("Bus is null");
}
db.Buses.Add(b);
db.SaveChanges();
return b;
}
public bool UpdateBus(Bus b)
{
if (b == null)
{
throw new ArgumentNullException("Bus is Empty");
}
db.Entry(b).State = EntityState.Modified;
db.SaveChanges();
return true;
}
public bool RemoveBus(int id)
{
var b = db.Buses.Find(id);
if (b == null)
{
return false;
}
db.Buses.Remove(b);
db.SaveChanges();
return true;
}
}
}
|
4d99a8a3f999e80751c83fc6174811a24a54cc76
|
C#
|
zmalic/unity-scene-loader
|
/Assets/SLoader/Scripts/TipLoader.cs
| 2.765625
| 3
|
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
namespace SLoader
{
public class TipLoader : MonoBehaviour
{
[Tooltip("Load tip from web")]
public bool loadFromWeb = false;
/// <summary>
/// For example, we can download tips from web in specific json format
/// </summary>
[Tooltip("Web url with tooltips data")]
public string url = "";
public delegate void TipLoaded(Tip t);
public static event TipLoaded OnTipLoaded;
/// <summary>
/// Load tip
/// </summary>
public void Load()
{
if (loadFromWeb)
{
StartCoroutine(LoadTipFromWeb());
}
else
{
LoadTipFromResources();
}
}
/// <summary>
/// Load random tip from web
/// There is a specific format, but you can write your own method for this
/// </summary>
/// <returns></returns>
IEnumerator LoadTipFromWeb()
{
/// json request body (get one random tip between 0 and 15 from web
string jsonBody = "[{\"method\":\"tasks.search\",\"params\":[\"\",\"createdAt\",\"desc\"," + Random.Range(0, 15) + ",1]}]";
var www = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonBody);
www.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
www.timeout = 3;
yield return www.SendWebRequest();
if (www.isHttpError || www.isNetworkError)
{
Debug.Log("Error");
}
else
{
// Prepaire json for JsonUtility
string result = www.downloadHandler.text.Replace("\"results\":[[", "\"results\":{\"tips\":[").Replace("]]}", "]}}");
/// create UrlResponse object from json response
UrlResponse response = JsonUtility.FromJson<UrlResponse>(result);
// if tip is successful downloaded
if (response.success && !response.results.IsEmpty())
{
Tip tip = response.results.GetRandom();
// invoke event
OnTipLoaded?.Invoke(tip);
yield break;
}
}
// if tip is not loaded from web get one from resource
LoadTipFromResources();
}
/// <summary>
/// Load tip from Resources/tips.json file
/// </summary>
void LoadTipFromResources()
{
var tipsFile = Resources.Load("tips") as TextAsset;
TipList tipList = JsonUtility.FromJson<TipList>(tipsFile.text);
Tip tip = tipList.GetRandom();
// invoke event
OnTipLoaded?.Invoke(tip);
}
}
}
|
8872c023af51bae636baa80afdd09243eb84d6a6
|
C#
|
Nedvid/BlaBla
|
/BlaBla_Server/Connection.cs
| 3.21875
| 3
|
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Collections.Generic;
namespace BlaBla_Server
{
public class Connection
{
private TcpListener _server;
private Boolean _isRunning;
private IPAddress ipAd = IPAddress.Parse(GetLocalIPAddress());
private int port = 8001;
public Connection()
{
Console.WriteLine("Server is running...");
_server = new TcpListener(ipAd, port);
_server.Start();
_isRunning = true;
Console.WriteLine("ip server: " + ipAd);
Console.WriteLine("-----------------------------------------------------------------\n");
LoopClients();
}
public void LoopClients()
{
while (_isRunning)
{
// wait for client connection
TcpClient newClient = _server.AcceptTcpClient();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(newClient.Client.RemoteEndPoint + ": " + "connected");
Console.ResetColor();
// client found.
// create a thread to handle communication
Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
t.Start(newClient);
}
}
public void HandleClient(object obj)
{
// retrieve client from parameter passed to thread
TcpClient client = (TcpClient)obj;
// sets two streams
StreamWriter sWriter = new StreamWriter(client.GetStream(), Encoding.ASCII);
StreamReader sReader = new StreamReader(client.GetStream(), Encoding.ASCII);
// you could use the NetworkStream to read and write,
// but there is no forcing flush, even when requested
Boolean bClientConnected = true;
String sData = null;
while (bClientConnected)
{
// reads from stream
sData = sReader.ReadLine();
if (sData == "bye")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(client.Client.RemoteEndPoint + ": ");
Console.Write(sData + "\n");
Console.ResetColor();
string answer = "bye";
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(client.Client.RemoteEndPoint + ": ");
Console.ForegroundColor = ConsoleColor.White;
Console.Write(answer + "\n");
Console.ResetColor();
sWriter.WriteLine(answer);
sWriter.Flush();
bClientConnected = false;
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
// shows content on the console.
Console.Write(client.Client.RemoteEndPoint + ": ");
Console.ForegroundColor = ConsoleColor.White;
Console.Write(sData + "\n");
Console.ResetColor();
string answer = db_Functions.checker(sData);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(client.Client.RemoteEndPoint + ": ");
Console.ForegroundColor = ConsoleColor.White;
Console.Write(answer + "\n");
Console.ResetColor();
sWriter.WriteLine(answer);
sWriter.Flush();
}
}
}
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("Local IP Address Not Found!");
}
}
}
|
2d84a627f28740aadd35470ee9d0e231a6449074
|
C#
|
shendongnian/download4
|
/code8/1451030-39605230-127543284-2.cs
| 3.1875
| 3
|
var input = @"[952,M] [782,M] [782] {2[373,M]}
[1470] [352] [235] [234] {3[610]}{3[380]} [128] [127]";
var pattern = @"((:?\{(\d+)(.*?)\})|(:?\[.*?\]))";
MatchCollection matches = Regex.Matches(input, pattern);
var ls = new List<string>();
foreach(Match match in matches)
{
//check if the item has curly brackets
// if it did then the capture groups will be different
if( match.Groups[4].Success )
{
var value = match.Groups[4].Value;
//now parse the value in the curly braces
var count = int.Parse(match.Groups[3].Value);
for(int i=0;i<count;i++)
{
ls.Add(value);
}
}
else
{
//otherwise we know that square bracket input is in capture group one
ls.Add(match.Groups[1].Value);
}
}
|
b3f3aaef4956163ca0b3f2b7ab61e98a8ee251b2
|
C#
|
Jayx239/BrowseSharp
|
/BrowseSharp/Browsers/BrowserTyped.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BrowseSharp.Common.History;
using BrowseSharp.Browsers.Core;
using BrowseSharp.Common;
namespace BrowseSharp.Browsers
{
/// <summary>
/// Headless browser implementation that creates documents for each web request.
/// </summary>
public class BrowserTyped : TypedCore, IBrowserTyped, IHistorySync
{
/// <summary>
/// Default Constructor
/// </summary>
public BrowserTyped(): base()
{
}
/// <summary>
/// Contains all previous documents stored for each previous request
/// </summary>
public List<IDocument> History => _history.History;
/// <summary>
/// Stores the forward history when the back method is called
/// </summary>
public List<IDocument> ForwardHistory
{
get { return _history.ForwardHistory; }
}
/// <summary>
/// Clears browse history by re-initializing Documents
/// </summary>
public void ClearHistory()
{
_history.ClearHistory();
}
/// <summary>
/// Clears forward history
/// </summary>
public void ClearForwardHistory()
{
_history.ClearForwardHistory();
}
/// <summary>
/// Method for navigating to last browser state by re-issuing the previous request
/// </summary>
public IDocument Back()
{
return Back(false);
}
/// <summary>
/// Method for navigating to last browser state
/// </summary>
/// <param name="useCache">Determines whether to re-issue request or reload last document</param>
/// <returns>Previous document</returns>
public IDocument Back(bool useCache)
{
IDocument oldDocument = _history.Back(useCache);
if (useCache)
return oldDocument;
_restClient.BaseUrl = oldDocument.RequestUri;
return Execute<Object>(oldDocument.Request);
}
/// <summary>
/// Method for navigating to last browser state by re-issuing the previous request asynchronously
/// </summary>
/// <returns>Previous document</returns>
public async Task<IDocument> BackAsync()
{
return await BackAsync(false);
}
/// <summary>
/// Method for navigating to last browser state asynchronously
/// </summary>
/// <param name="useCache">Determines whether to re-issue request or reload last document</param>
/// <returns>Previous document</returns>
public async Task<IDocument> BackAsync(bool useCache)
{
IDocument oldDocument = _history.Back(useCache);
if (useCache)
return oldDocument;
_restClient.BaseUrl = oldDocument.RequestUri;
return await ExecuteTaskAsync<Object>(oldDocument.Request);
}
/// <summary>
/// Navigate to next document in forward history
/// </summary>
/// <returns>Forward history document</returns>
public IDocument Forward()
{
return Forward(false);
}
/// <summary>
/// Navigate to next document in forward history
/// </summary>
/// <param name="useCache">Determines whether to re-issue request or reload forward document</param>
/// <returns>Forward history document</returns>
public IDocument Forward(bool useCache)
{
IDocument forwardDocument = _history.Forward(useCache);
if (useCache)
return forwardDocument;
_restClient.BaseUrl = forwardDocument.RequestUri;
return Execute<Object>(forwardDocument.Request);
}
/// <summary>
/// Navigate to next document in forward history asynchronously
/// </summary>
/// <returns>Forward history document</returns>
public async Task<IDocument> ForwardAsync()
{
return await ForwardAsync(false);
}
/// <summary>
/// Navigate to next document in forward history asynchronously
/// </summary>
/// <param name="useCache">Determines whether to re-issue request or reload forward document</param>
/// <returns>Forward history document</returns>
public async Task<IDocument> ForwardAsync(bool useCache)
{
IDocument forwardDocument = _history.Forward(useCache);
if (useCache)
return forwardDocument;
_restClient.BaseUrl = forwardDocument.RequestUri;
return await ExecuteTaskAsync<Object>(forwardDocument.Request);
}
/// <summary>
/// Max amount of history/Documents to be stored by the browser (-1 for no limit)
/// </summary>
public int MaxHistorySize { get { return _history.MaxHistorySize; } set { _history.MaxHistorySize = value; } }
/// <summary>
/// Refresh page, re-submits last request
/// </summary>
/// <returns>Current document refreshed</returns>
public IDocument Refresh()
{
IDocument oldDocument = _history.Refresh();
_restClient.BaseUrl = oldDocument.RequestUri;
return Execute<Object>(oldDocument.Request);
}
/// <summary>
/// Refresh page, re-submits last request asynchronously
/// </summary>
/// <returns>Current document refreshed</returns>
public async Task<IDocument> RefreshAsync()
{
IDocument oldDocument = _history.Refresh();
_restClient.BaseUrl = oldDocument.RequestUri;
return await ExecuteTaskAsync<Object>(oldDocument.Request);
}
}
}
|
33ec03828cbf73655e1854b899099b3a69c4e222
|
C#
|
serminhas/EntitySorgular
|
/Desktop/EntitySorgular/EntitySorgular/Program.cs
| 2.96875
| 3
|
using System;
using EntitySorgular.Data;
using EntitySorgular.Models;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace EntitySorgular
{
class Program
{
public static void WriteToConsole(IEnumerable<object> items)
{
string header="";
foreach(var pName in items.FirstOrDefault().GetType().GetProperties())
{
header += $"{pName.Name}".PadRight(35);
}
Console.WriteLine(header);
Console.WriteLine(new String('-', header.Length));
foreach(var item in items)
{
string body="";
foreach (var prop in item.GetType().GetProperties())
{
body += $"{prop.GetValue(item)}".PadRight(35);
}
Console.WriteLine(body);
}
}
public static void Ornek1()
{
/*select ProductID, ProductName, UnitPrice, UnitsInStock,
(select CategoryName from Categories where Categories.CategoryID=Products.CategoryID)
from Products where UnitPrice>=20 and UnitPrice<=50
order by UnitPrice desc
veya
select ProductID as ID, ProductName UrunAdi, UnitPrice=Fiyat, UnitsInStock 'Stok Adedi', C.CategoryName [Kategori Adı]
from Products P join Categories C on C.CategoryID=P.CategoryID
where UnitPrice>=20 and UnitPrice<=50
order by UnitPrice desc*/
NorthwindContext context=new NorthwindContext();
var result=context.Products.Where(x => x.UnitPrice>=20 && x.UnitPrice<=50).OrderByDescending(x=>x.UnitPrice).Select(x=>new {
ID=x.ProductId,
UrunAdi=x.ProductName,
StokAdedi=x.UnitsInStock,
Fiyat=x.UnitPrice,
KategoriAdi=x.Category.CategoryName
});
WriteToConsole(result);
}
/*
select C.CompanyName, CONCAT(E.FirstName, ' ', E.LastName) as Personel,O.OrderID, O.OrderDate, [Kargo Firması]=s.CompanyName
from Orders O
join Customers C on O.CustomerID=C.CustomerID
join Employees E on O.EmployeeID=E.EmployeeID
join Shippers S on O.ShipVia=S.ShipperID
*/
public static void Ornek2()
{
using NorthwindContext context=new NorthwindContext();
var result=context.Orders.Select(x=>new{
MusteriSirketAdi=x.Customer.CompanyName,
Personel=$"{x.Employee.FirstName} {x.Employee.LastName}",
SiparişId=x.OrderId,
SiparisTarihi=x.OrderDate,
KargoSirketi=x.ShipViaNavigation.CompanyName
});
WriteToConsole(result);
}
/*select FirstName as 'Ad', LastName as 'Soyad', BirthDate as 'D.Tarihi',
DATEDIFF(YEAR, BirthDate, GETDATE()) as 'Yas' from Employees order by Yas*/
public static void Ornek3()
{
using NorthwindContext context=new NorthwindContext();
var result=context.Employees.Select(x=> new{
Ad = x.FirstName,
Soyad=x.LastName,
DogumTarihi=x.BirthDate.Value.ToShortDateString(),
Yas = DateTime.Now.Year-x.BirthDate.Value.Year
} ) ;
WriteToConsole(result);
}
/*
declare @name nvarchar(16) = 'Beverages', @Id int
if exists(select * from Categories where CategoryName = @name)
begin
select @Id = CategoryID from Categories where CategoryName = @name
insert into Products (ProductName, UnitPrice, UnitsInStock, CategoryID) values ('Kola', 5.00, 500, @Id)
select ProductID, ProductName, UnitPrice, UnitsInStock, (select CategoryName from Categories where Categories.CategoryID=Products.CategoryID) from Products where ProductName like 'Kola%'
end
else
begin
print 'kategori yok'
end
*/
public static void Ornek4()
{
using NorthwindContext context=new NorthwindContext();
Categories category=context.Categories.FirstOrDefault(x => x.CategoryName=="Beverages");
if(category==null)
{
Console.ForegroundColor=ConsoleColor.Red;
Console.WriteLine("Parametrede verdiğiniz kategori bulunamadı!");
Console.ResetColor();
return;
}
Products product=new Products();
product.ProductName="Kola 1";
product.UnitPrice=5.00M;
product.UnitsInStock=500;
product.CategoryId=category.CategoryId;
//product.CategoryId=context.Categories.FirstOrDefault(x=>x.CategoryName=="Beverages").CategoryId;
context.Products.Add(product);
bool result=context.SaveChanges()>0;
Console.WriteLine($"Kategori Ekleme İşlemi {(result ? "Başarılı" : "Başarısız" )}");
context.Categories.FirstOrDefault(x=>x.CategoryName=="Beverages").Products.Add(new Products
{
ProductName="Kola 2",
UnitPrice=5.00M,
UnitsInStock=500
});
result=context.SaveChanges()>0;
Console.WriteLine($"Kategori Ekleme İşlemi {(result ? "Başarılı" : "Başarısız" )}");
var products=context.Products.AsNoTracking()
.Where(x=>x.ProductName.StartsWith("Kola"))
.Select(x=>new
{
ID=x.ProductId,
UrunAdi=x.ProductName,
Fiyat=x.UnitPrice,
StokAdet=x.UnitsInStock,
Kategori=x.Category.CategoryName
});
WriteToConsole(products);
}
public static void Ornek5()
{
/*
-- Müşteriler tablosunda şirket adına Restaurant geçen şirketleri listeleyiniz.
select * from Customers where CompanyName like '%restaurant%'
*/
using NorthwindContext context=new NorthwindContext();
var result=context.Customers.Where(x=>x.CompanyName.Contains("Restaurant")).Select(x=>new{
x.CompanyName,
x.ContactTitle
});
WriteToConsole(result);
}
public static void Ornek6()
{
/*
select C.CategoryName, sum(P.UnitsInStock) as Adet from Products P join Categories C on P.CategoryID = C.CategoryID
group by C.CategoryName
order by Adet
*/
using NorthwindContext context=new NorthwindContext();
var result=context.Products.
GroupBy( x=> new{x.Category.CategoryName}).
Select( x=> new{
Kategori=x.Key,
Adet = x.Sum(p=>p.UnitsInStock)
}).
OrderByDescending(x=>x.Adet);
WriteToConsole(result);
}
static void Main(string[] args)
{
Console.Clear();
//Ornek1();
//Ornek2();
//Ornek3();
//Ornek4();
//Ornek5();
Ornek6();
}
}
}
|
94341f27f9cc1d6429168cb2fd2a26c10ed036c6
|
C#
|
AlexKaschuk/learning-C-
|
/Exam/Schedule.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Exam
{
[Serializable]
public class Schedule
{
public SortedList<DateTime, CinemaHall> Session = new SortedList<DateTime, CinemaHall>();
public SortedList<DateTime, Film> Films { get; } = new SortedList<DateTime, Film>();
public void AddFilm(Film film) {
DateTime startTime = DateTime.Today.AddHours(9); ;
DateTime time = Films.LastOrDefault().Key.AddMinutes(film.Length + 15); //15 перерва між фільмами
if (Films.Count == 0)
{
Films.Add(startTime, film);
Session.Add(startTime, new CinemaHall());
}
else if (time.Hour > 22 || time.Hour == 0)
{
Films.Add(startTime.AddDays(1), film);
Session.Add(startTime.AddDays(1), new CinemaHall());
}
else
{
Films.Add(time, film);
Session.Add(time, new CinemaHall());
}
}
public void ShowSchdule() {
DateTime start = Films.FirstOrDefault().Key;
foreach (KeyValuePair<DateTime, Film> pair in Films) {
if (pair.Key > DateTime.Now)
{
Console.WriteLine($"film {pair.Value} session {pair.Key}");
}
}
}
public void ShowSessonSits(DateTime date)
{
foreach (KeyValuePair<DateTime, Film> pair in Films)
{
if (pair.Key > DateTime.Now&& pair.Key.Day==date.Day&& pair.Key.Hour == date.Hour) {
Console.WriteLine($"film {pair.Value} session {pair.Key}");
Session.First(x => x.Key == pair.Key).Value.ShowSeats();
}
}
}
public void ShowSessonSits(string filmName)
{
foreach (KeyValuePair<DateTime, Film> pair in Films)
{
if (pair.Key > DateTime.Now && pair.Value.Name == filmName)
{
Console.WriteLine($"film {pair.Value} session {pair.Key}");
Session.First(x => x.Key == pair.Key).Value.ShowSeats(); //first тому що він з таким ключем створюється один на один зал
}
}
}
public void ShowSessonSitsToday(DateTime date)
{
foreach (KeyValuePair<DateTime, Film> pair in Films)
{
if (pair.Key > DateTime.Now && pair.Key.Day == date.Day)
{
Console.WriteLine($"film {pair.Value} session {pair.Key}");
Session.First(x => x.Key == pair.Key).Value.ShowSeats();
}
}
}
public CinemaHall GetHall(DateTime date) =>
Session.First(x => x.Key == date).Value;
public Film GetFilmName(DateTime date)
=> Films.First(x => x.Key == date).Value;
//public void ToBinary()
//{
// using (FileStream fs = new FileStream("film.bin", FileMode.Create, FileAccess.ReadWrite))
// {
// using (BinaryWriter bw = new BinaryWriter(fs, Encoding.Unicode))
// {
// foreach (KeyValuePair<DateTime, Film> i in Films)
// {
// bw.Write(i.Key.ToBinary());
// bw.Write(i.Value.Name);
// bw.Write(i.Value.Genre);
// bw.Write(i.Value.AgeLimit);
// bw.Write(i.Value.Length);
// }
// }
// }
// using (FileStream fs = new FileStream("hall.bin", FileMode.Create, FileAccess.ReadWrite))
// {
// using (BinaryWriter bw = new BinaryWriter(fs, Encoding.Unicode))
// {
// foreach (KeyValuePair<DateTime, CinemaHall> i in Session)
// {
// bw.Write(i.Key.ToBinary());
// bw.Write(i.Value.GetBlockedSeats());
// }
// }
// }
//}
//public void FromBinary()
//{
// Films.Clear();
// if (File.Exists("film.bin"))
// {
// using (FileStream fs = new FileStream("film.bin", FileMode.Open, FileAccess.ReadWrite))
// {
// using (BinaryReader br = new BinaryReader(fs, Encoding.Unicode))
// {
// while (br.BaseStream.Position != br.BaseStream.Length)
// {
// Films.Add(DateTime.FromBinary(br.ReadInt64()), new Film(br.ReadString(), br.ReadString(), br.ReadInt32(), br.ReadInt32()));
// }
// }
// }
// }
// Session.Clear();
// if (File.Exists("hall.bin"))
// {
// using (FileStream fs = new FileStream("hall.bin", FileMode.Open, FileAccess.ReadWrite))
// {
// using (BinaryReader br = new BinaryReader(fs, Encoding.Unicode))
// {
// while (br.BaseStream.Position != br.BaseStream.Length)
// {
// DateTime d = DateTime.FromBinary(br.ReadInt64());
// string[] blockedSits = br.ReadString().Split(',', '\n', ' ');
// CinemaHall h = new CinemaHall();
// if (blockedSits.Length > 1)
// {
// for (int i = 0; i < blockedSits.Length; i+=2)
// {
// if(blockedSits[i] != " "&& blockedSits[i] != "") {
// h.BlockSits(int.Parse(blockedSits[i]), int.Parse(blockedSits[i + 1]));
// }
// }
// }
// Session.Add(d, h);
// }
// }
// }
// }
//}
}
}
|
3f6edfa45a6bf3b47b1910fb8d5e57964356423b
|
C#
|
Kofili/pjTecNo
|
/DataConnection.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data.Sql;
namespace TPvorbereitung
{
class DataConnection
{
private string Db
{
get
{
string s = "Database";
return s;
}
}
private string Server
{
get
{
string s = "Server";
return s;
}
}
private string Uid
{
get
{
string s = "User";
return s;
}
}
private string Pw
{
get
{
string s = "Pwd";
return s;
}
}
private void connect()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = String.Format("Server ={0};Database={1}; User ID={2}; Pw={3}", Server, Db, Uid, Pw);
conn.Open();
}
}
public List<object> select( string clm, string tbl, string w)
{
List<object> list = new List<object>();
SqlCommand cmd = new SqlCommand("");
cmd.Parameters.Add(new SqlParameter("clm", clm));
cmd.Parameters.Add(new SqlParameter("tbl", tbl));
cmd.Parameters.Add(new SqlParameter("w", w));
return list;
}
}
}
|
cffae86e08916f1e64cc06862c233b0a18abfa8f
|
C#
|
elitsaleontieva/CSharp-OOP-Basics
|
/Interfaces and Abstraction - Exercise/05. Border Control/StartUp.cs
| 3.203125
| 3
|
using System;
using System.Linq;
using System.Collections.Generic;
namespace BorderControl
{
public class Program
{
static void Main(string[] args)
{
var input = Console.ReadLine();
var inputList = new List<string>();
inputList.Add(input);
while (input!="End")
{
input = Console.ReadLine();
inputList.Add(input);
}
var lastDigitsOfFakeIds = Console.ReadLine();
foreach (var inputLine in inputList.SkipLast(1))
{
var parts = inputLine.Split(' ').ToArray();
var partsLength = parts.Length;
if (parts.Length == 2)
{
var model = parts[0];
Robot robot = new Robot();
var id = parts[1];
if (robot.CheckId(id, lastDigitsOfFakeIds)==false)
{
robot = new Robot(model, id);
Console.WriteLine(robot.Id);
}
}
else if (parts.Length == 3)
{
var name = parts[0];
var age = int.Parse(parts[1]);
var id = parts[2];
Citizen citizen = new Citizen();
if (citizen.CheckId(id, lastDigitsOfFakeIds) == false)
{
citizen = new Citizen(name, age, id);
Console.WriteLine(citizen.Id);
}
}
}
}
}
}
|
b41c21462ced2e1c7b2f1d2e2b690f3a33b74eb3
|
C#
|
sissoux/LEDCloudConfigurator
|
/LEDCloudConfigurator/WAVParser.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LEDCloudConfigurator
{
/// [Bloc de déclaration d'un fichier au format WAVE]
///0 FileTypeBlocID(4 octets) : Constante «RIFF» (0x52,0x49,0x46,0x46)
///4 FileSize(4 octets) : Taille du fichier moins 8 octets
///8 FileFormatID(4 octets) : Format = «WAVE» (0x57,0x41,0x56,0x45)
/// [Bloc décrivant le format audio]
///12 FormatBlocID(4 octets) : Identifiant «fmt » (0x66,0x6D, 0x74,0x20)
///16 BlocSize(4 octets) : Nombre d'octets du bloc - 16 (0x10)
///20 AudioFormat(2 octets) : Format du stockage dans le fichier(1: PCM, ...)
///22 NbrCanaux(2 octets) : Nombre de canaux(de 1 à 6, cf.ci-dessous)
///24 Frequence(4 octets) : Fréquence d'échantillonnage (en hertz) [Valeurs standardisées : 11 025, 22 050, 44 100 et éventuellement 48 000 et 96 000]
///28 BytePerSec(4 octets) : Nombre d'octets à lire par seconde (c.-à-d., Frequence * BytePerBloc).
///32 BytePerBloc(2 octets) : Nombre d'octets par bloc d'échantillonnage(c.-à-d., tous canaux confondus : NbrCanaux* BitsPerSample/8).
///34 BitsPerSample(2 octets) : Nombre de bits utilisés pour le codage de chaque échantillon(8, 16, 24)
/// [Bloc des données]
///36 DataBlocID(4 octets) : Constante «data» (0x64,0x61,0x74,0x61)
///40 DataSize(4 octets) : Nombre d'octets des données (c.-à-d. "Data[]", c.-à-d. taille_du_fichier - taille_de_l'entête(qui fait 44 octets normalement).
///
public enum AudioFormat
{
PCM = 1,
IEEE_FLOAT = 3,
ALAW = 6,
MULAW = 7
}
public class WAVParser
{
public byte[] header;
public AudioFormat Format { get; private set; }
public UInt16 ChannelCount { get; private set; }
public UInt16 BitsPerSample { get; private set; }
public UInt16 BytesPerBlock { get; private set; }
public UInt32 Frequency { get; private set; }
public UInt32 BytePerSec { get; private set; }
public UInt32 DataSize { get; private set; }
public double FileDuration { get; private set; }
public string FileTypeBlocID { get; private set; }
public string FileFormatID { get; private set; }
public WAVParser(FileStream inputFile)
{
header = new byte[44];
inputFile.Read(header, 0, 44);
try
{
FileTypeBlocID = System.Text.Encoding.UTF8.GetString(header, 0, 4);
FileFormatID = System.Text.Encoding.UTF8.GetString(header, 8, 4);
AudioFormat temp;
Enum.TryParse<AudioFormat>(BitConverter.ToUInt16(header, 20).ToString(), out temp);
Format = temp;
ChannelCount = BitConverter.ToUInt16(header, 22);
BitsPerSample = BitConverter.ToUInt16(header, 34);
Frequency = BitConverter.ToUInt32(header, 24);
DataSize = BitConverter.ToUInt32(header, 40);
BytePerSec = BitConverter.ToUInt32(header, 28);
BytesPerBlock = BitConverter.ToUInt16(header, 32);
FileDuration = (double)DataSize / (double)BytePerSec;
}
catch (Exception)
{
throw;
}
}
public bool isValidWavefile(AudioFormat audioFormat, uint samplingFrequency, uint bytePerSample)
{
return samplingFrequency == this.Frequency && bytePerSample == this.BitsPerSample && audioFormat == this.Format;
}
}
}
|
253c4ded416d06d5cfedc0d8e876d98a5f768725
|
C#
|
cake-contrib/Cake.Bower
|
/src/Cake.Bower/BowerRunnerSettingsExtensions.cs
| 2.796875
| 3
|
using Cake.Core.IO;
namespace Cake.Bower
{
/// <summary>
/// Bower runner settings extensions
/// </summary>
public static class BowerRunnerSettingsExtensions
{
/// <summary>
/// Set the working directory for the bower runner settings
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="settings"></param>
/// <param name="directory"></param>
/// <returns></returns>
public static T UseWorkingDirectory<T>(this T settings, DirectoryPath directory) where T : BowerRunnerSettings
{
settings.WorkingDirectory = directory;
return settings;
}
/// <summary>
/// Add --force to the bower command
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
public static T WithForce<T>(this T settings) where T : BowerRunnerSettings
{
settings.Force = true;
return settings;
}
/// <summary>
/// Add --json
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
public static T WithJson<T>(this T settings) where T : BowerRunnerSettings
{
settings.Json = true;
return settings;
}
/// <summary>
/// Sets the log level e.g. --loglevel=warn
/// </summary>
/// <param name="settings"></param>
/// <param name="logLevel"></param>
/// <returns></returns>
public static T WithLogLevel<T>(this T settings, BowerLogLevel logLevel) where T : BowerRunnerSettings
{
settings.LogLevel = logLevel;
return settings;
}
/// <summary>
/// Add --offline
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
public static T WithOffline<T>(this T settings) where T : BowerRunnerSettings
{
settings.Offline = true;
return settings;
}
/// <summary>
/// Add --quiet
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
public static T WithQuiet<T>(this T settings) where T : BowerRunnerSettings
{
settings.Quiet = true;
return settings;
}
/// <summary>
/// Add --silent
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
public static T WithSilent<T>(this T settings) where T : BowerRunnerSettings
{
settings.Silent = true;
return settings;
}
/// <summary>
/// Add --verbose
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
public static T WithVerbose<T>(this T settings) where T : BowerRunnerSettings
{
settings.Verbose = true;
return settings;
}
/// <summary>
/// Add --allow-root
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
public static T WithAllowRoot<T>(this T settings) where T : BowerRunnerSettings
{
settings.AllowRoot = true;
return settings;
}
}
}
|
c76fb2b6649beb4e5103b383c8d1b8d6f5cc3270
|
C#
|
FlorianRossignol/Formative27Janvier
|
/Assets/Scripts/Monster/Snake.cs
| 2.6875
| 3
|
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine;
public class Snake : MonoBehaviour
{
[SerializeField] Animator snakeanim_;
private State currentstate_;
private enum State
{
NONE,
IDLE
}
void Start()
{
currentstate_ = State.IDLE;
}
void FixedUpdate()
{
}
void ChangeState(State state)
{
switch (state)
{
case State.IDLE:
snakeanim_.Play("idlesnake");
break;
default:
throw new ArgumentOutOfRangeException(nameof(state), state, null);
}
currentstate_ = state;
}
}
|
d5a73d0693411e705599ae7e311c640b2ebfab11
|
C#
|
Vimerum/pbcj-forca
|
/Assets/_Scripts/Words/WordManager.cs
| 3.171875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class WordManager : MonoBehaviour {
// Singleton
public static WordManager instance;
#region Public Variables
[Header("References")]
// Prefab para as letras
public GameObject letterPrefab;
// Transform do gameobject que ser o pai das letras a serem instanciadas
public Transform wordHolder;
// Palavra atual que o jogador esta tentando adivinhar
public string Word { get; private set; }
#endregion
#region Private Variables
// Lista das Letters que representam a palavra atual
private List<Letter> letters;
#endregion
#region Monobehaviour Callbacks
private void Awake() {
// Singleton
if (instance != null) {
Destroy(this);
return;
}
instance = this;
}
#endregion
#region Private Functions
/// <summary>
/// Retorna a Letter que representa o caractere <paramref name="character"/>
/// </summary>
/// <param name="character">O caractere a ser procurado</param>
/// <returns>A instancia de Letter que representa o caractere</returns>
private Letter GetLetter (char character) {
foreach (Letter l in letters) {
if (l.Char == character) {
return l;
}
}
Letter newLetter = new Letter(character);
letters.Add(newLetter);
return newLetter;
}
/// <summary>
/// Confere se a condio de vitria foi atingida
/// </summary>
private void CheckVictory () {
bool victory = true;
foreach (Letter l in letters) {
victory = victory && l.Revealed;
}
if (victory) {
GameManager.instance.Victory();
}
}
#endregion
#region Public Functions
/// <summary>
/// Inicializa o WordManager, escolhendo uma nova palavra e instanciando as letras na interface
/// </summary>
public void Initialize () {
Word = WordLoader.GetRandomWord();
Debug.Log("A palavra selecionada foi " + Word);
if (letters == null) {
letters = new List<Letter>();
} else {
letters.Clear();
}
if (wordHolder.childCount > 0) {
foreach (Transform child in wordHolder) {
Destroy(child.gameObject);
}
}
for (int i = 0; i < Word.Length; i++) {
Letter letter = GetLetter(Word[i]);
GameObject letterGO = Instantiate(letterPrefab, wordHolder) as GameObject;
TextMeshProUGUI letterText = letterGO.GetComponent<TextMeshProUGUI>();
letter.AddPosition(letterText);
}
}
/// <summary>
/// Confere se o caractere <paramref name="letter"/> esta presente na palavra, se estiver mostra ele e reconhece o acerto
/// </summary>
/// <param name="letter">O caractere a ser procurado</param>
public void ShowLetter (char letter) {
foreach (Letter l in letters) {
if (l.Char == letter) {
if (l.Reveal()) {
GameManager.instance.RecognizeHit();
CheckVictory();
}
return;
}
}
GameManager.instance.RecognizeError();
}
#endregion
}
|
ad2c38a3a7e3a735e51bc9113ee6f2359d432811
|
C#
|
vikingeff/monster_panic
|
/assets/script/InstantiateScript.cs
| 2.671875
| 3
|
using UnityEngine;
using System.Collections;
public class InstantiateScript : MonoBehaviour {
public GameObject monster;
public int count = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0) && count == 0)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 500f))
{
if (hit.collider.CompareTag("Ground"))
{
Vector3 pos = hit.point;
pos.y = 10;
Instantiate(monster, pos, Quaternion.Euler(0, 0, 0));
count++;
}
}
}
}
}
|
43e22400e14d941ad54272b6109544c657d95c85
|
C#
|
qk-li/StreamingClientLibrary
|
/Twitch/Twitch.Base/Models/Clients/Chat/ChatUserStatePacketModel.cs
| 2.9375
| 3
|
using System.Collections.Generic;
namespace Twitch.Base.Models.Clients.Chat
{
/// <summary>
/// Information about a chat user state packet.
/// </summary>
public class ChatUserStatePacketModel : ChatUserPacketModelBase
{
/// <summary>
/// The ID of the command for a chat user state.
/// </summary>
public const string CommandID = "USERSTATE";
/// <summary>
/// Indicates whether the user is a moderator.
/// </summary>
public bool Moderator { get; set; }
/// <summary>
/// Information to the user's emote sets.
/// </summary>
public string EmoteSets { get; set; }
/// <summary>
/// Creates a new instance of the ChatUserStatePacketModel class.
/// </summary>
/// <param name="packet">The Chat packet</param>
public ChatUserStatePacketModel(ChatRawPacketModel packet)
: base(packet)
{
this.Moderator = packet.GetTagBool("mod");
this.EmoteSets = packet.GetTagString("emote-sets");
}
/// <summary>
/// A list containing the user's available emote set IDs.
/// </summary>
public List<int> EmoteSetsDictionary
{
get
{
List<int> results = new List<int>();
if (!string.IsNullOrEmpty(this.EmoteSets))
{
string[] splits = this.EmoteSets.Split(new char[] { ',' });
if (splits != null && splits.Length > 0)
{
foreach (string split in splits)
{
if (int.TryParse(split, out int emoteSet))
{
results.Add(emoteSet);
}
}
}
}
return results;
}
}
}
}
|
8226456bb2625aff978fcbc040cba9576adc71dd
|
C#
|
deton/bjd5
|
/BJD/option/Dat.cs
| 2.609375
| 3
|
using System;
using System.Text;
using Bjd.ctrl;
using Bjd.util;
namespace Bjd.option{
public class Dat : ListBase<OneDat>{
private readonly bool[] _isSecretList;
private readonly int _colMax;
public Dat(CtrlType[] ctrlTypeList){
//カラム数の初期化
_colMax = ctrlTypeList.Length;
//isSecretListの生成
_isSecretList = new bool[_colMax];
for (int i = 0; i < _colMax; i++){
_isSecretList[i] = false;
if (ctrlTypeList[i] == CtrlType.Hidden){
_isSecretList[i] = true;
}
}
}
//文字列によるOneDatの追加
//内部で、OneDatの型がチェックされる
public bool Add(bool enable, string str){
if (str == null){
return false; //引数にnullが渡されました
}
var list = str.Split('\t');
if (list.Length != _colMax){
return false; //カラム数が一致しません
}
OneDat oneDat;
try{
oneDat = new OneDat(enable, list, _isSecretList);
}
catch (ValidObjException){
return false; // 初期化文字列が不正
}
Ar.Add(oneDat);
return true;
}
//文字列化
//isSecret 秘匿が必要なカラムを***に変換して出力する
public String ToReg(bool isSecret){
var sb = new StringBuilder();
foreach (var o in Ar){
if (sb.Length != 0){
sb.Append("\b");
}
sb.Append(o.ToReg(isSecret));
}
return sb.ToString();
}
//文字列による初期化
public bool FromReg(String str){
Ar.Clear();
if (string.IsNullOrEmpty(str)){
return false;
}
//Ver5.7.x以前のiniファイルをVer5.8用に修正する
var tmp = Util.ConvValStr(str);
str = tmp;
// 各行処理
String[] lines = str.Split('\b');
if (lines.Length <= 0){
return false; //"lines.length <= 0"
}
foreach (var l in lines){
var s = l;
//OneDatの生成
OneDat oneDat;
try{
oneDat = new OneDat(true, new String[_colMax], _isSecretList);
}
catch (ValidObjException){
return false;
}
if (s.Split('\t').Length != _isSecretList.Length + 1){
// +1はenableカラムの分
//カラム数の不一致
return false;
}
//fromRegによる初期化
if (oneDat.FromReg(s)){
Ar.Add(oneDat);
continue; // 処理成功
}
//処理失敗
Ar.Clear();
return false;
}
return true;
}
}
}
|
262a5f155c9f7fff380ae5f3181ca4f9b3351ecc
|
C#
|
ilya-zhidkov/compscie
|
/Source/CompScie.Core/CountingSort.cs
| 3.328125
| 3
|
namespace CompScie.Core
{
public class CountingSort
{
public void Sort(int[] array, int max, int min)
{
var frequencies = new int[max - min + 1];
var length = array.Length;
var sorted = new int[length];
for (var i = 0; i < length; i++)
frequencies[array[i] - min]++;
for (var i = 1; i < frequencies.Length; i++)
frequencies[i] += frequencies[i - 1];
for (var i = length - 1; i >= 0; i--)
sorted[--frequencies[array[i] - min]] = array[i];
for (var i = 0; i < length; i++)
array[i] = sorted[i];
}
}
}
|
2e80aed2130229eb224afb152e63aa2e1929155b
|
C#
|
Lanxh/Atlantis_Defense
|
/Assets/Scripts/Turret_HealthBar.cs
| 2.515625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;// per far funzionare la UI (la healthBar appunto)
public class Turret_HealthBar : MonoBehaviour
{
[Header("Variabili da riempire")]
public GameObject rovine; //dichiara il prefab da usare per le rovine (da definire nell'inspector)
public GameObject barPrefab; //dichiara il prefab da usare per la barra della vita (da definire nell'inspector)
[Header("Variabili autoriempienti")]
private Turret_Stats sentryStats; //statistiche della torretta
private float startHealth = 100f; //dichiara la variabile per la vita totale della torre
public float health = 100f; //dichiara la variabile per la vita attuale della torre
public float missingHealth=0; //variabile che altri script prendono per capire quanto riparare della torretta
private int repairCost = 1; //dichiara la variabile per il costo di riparazione
private Camera mainCamera; //telecamera di riferimento (quella principale)
protected Image bar; //dichiara l'immagine da usare per la barra della vita (protected così non appare nell'inspector)
protected Image barFilled; //dichiara l'immagine da usare per il riempimento della barra della vita
private bool isDying = false; //variabile di controllo per evitare bug (Die() chiamato più volte per frame)
private GameObject standingPlatform; //la piattaforma su cui poggia la torretta
void Start()
{
mainCamera = Camera.main; //trova la camera principale (che è anche l'unica)
SetHealth(); //funzione che setta la vita e la barra della vita della torretta
}
public void TakeDamage(int damage) //questo comando deve essere chiamato dichiarando sempre anche un valore int (utile perchè puoi chiamarlo da altri script, in questo caso è chiamato dal proiettile che tocca il bersaglio)
{
health -= damage; //sottrae alla vita il danno specificato dal comando TakeDamage
bar.fillAmount = 1; //farà apparire la barra della vita
barFilled.fillAmount = health / startHealth; //farà in modo che la barra della vita rifletta l'effettiva vita del nemico
missingHealth = startHealth - health; //calcola quanta vita manca
if ((health <= 0) && (isDying == false)) //se la vita scende a 0 e non è morto...
{
Die(); //parte il comando di morte
isDying = true; //ora sta morendo, quindi non richiamerà questo script
}
}
public void RepairDamage() //comando che ricarica la vita al massimo e nasconde di nuovo la barra
{
health = startHealth; //ripara la torretta al max
missingHealth = 0; //resetta la vita mancante a 0
bar.fillAmount = 0f; //nasconde la barra finchè non prende danni
barFilled.fillAmount = 0f; //nasconde la barra finchè non prende danni
}
void Die() //comando di morte (chiamato su TakeDamage() )
{
/*DA AGGIUNGERE QUI:
1)Animazione di morte
*/
Tower_Choice turretBuildScript = GameObject.Find("GameManager").GetComponent<Tower_Choice>();
turretBuildScript.CreateRubble(standingPlatform);//crea una rovina sulla piattaforma su cui è stata creata
standingPlatform.GetComponent<Platform_Status>().StoreDestrTurret(this.gameObject);
Turret_LookAtRobot turretBehaviourScript = GetComponent<Turret_LookAtRobot>();
turretBehaviourScript.removeHimselfFromTarget();
Destroy(bar); //distruggi la barra
//Destroy(gameObject);
return;
}
private void Update()
{
//WorldToScreenPoint trasforma un punto nel mondo in un punto sullo schermo (quindi perfetto per un canvas)
bar.transform.position = mainCamera.WorldToScreenPoint(transform.position + new Vector3(0, 3f, 0)); //posiziona la barra sotto la torretta
}
public void SetPlatform(GameObject ptf)
{
standingPlatform = ptf; //salva la piattaforma su cui viene creata
}
public void SetHealth()
{
isDying = false; //non sta morendo
sentryStats = GetComponent<Turret_LookAtRobot>().turretStats; //estrae le statistiche della torretta
startHealth = sentryStats.startingHealth; //estrae dallo script Enemy behaviour la variabile della vita
health = startHealth; //per far in modo che anche cambiando il valore della vita, la barra mostri la percentuale di vita correttamente
/*istanzia il prefab della barra al transform della canvas (siccome ce ne deve essere solo una findObject va bene).
Poi di quel prefab prendi l'immagine (GetComponent<Image>()) e assegnala alla variabile "bar" */
bar = Instantiate(barPrefab, FindObjectOfType<Canvas>().transform).GetComponent<Image>();
/*il riempimento della barra è assegnato creando una lista di tutti i componenti "Image" nella variabile "bar" e nei suoi figli che comprendono quindi 2
immagini: il background e il fill. A noi ci serve solo il fill, quindi in quella lista prendiamo solo
"quella che non appartiene a bar" (il comando è Find(img => img != bar)) */
barFilled = new List<Image>(bar.GetComponentsInChildren<Image>()).Find(img => img != bar);
bar.fillAmount = 0f; //nasconde la barra finchè non prende danni
barFilled.fillAmount = 0f; //nasconde la barra finchè non prende danni
}
}
|
0642e279f9a9851749040a568a6feaeab5feedea
|
C#
|
aguerot/mirlite
|
/libmirror/OutputEvent.cs
| 2.546875
| 3
|
using System;
using Mirror.UsbLibrary;
namespace Mirror
{
public class OutputEvent : OutputReport
{
public OutputEvent(EventType eventType, ushort messageId, HIDDevice mirrorDevice, byte[] data) : base(mirrorDevice)
{
EventType = eventType;
MessageId = messageId;
var eventBytes = BitConverter.GetBytes((Int32)EventType);
var messageIdBytes = BitConverter.GetBytes(MessageId);
Buffer[1] = eventBytes[1];
Buffer[2] = eventBytes[0];
Buffer[3] = messageIdBytes[0];
Buffer[4] = messageIdBytes[1];
if (data != null)
{
Buffer[5] = (byte) data.Length;
data.CopyTo(Buffer, 6);
}
}
public EventType EventType { get; set; }
public ushort MessageId { get; set; }
}
}
|
82eb1fd2d1b695c93dd72fe2444b61c9adc6a999
|
C#
|
shendongnian/download4
|
/first_version_download2/174807-13128206-31134080-2.cs
| 3.484375
| 3
|
class Program
{
static void Main(string[] args)
{
// Create a main window GUI
Form1 form1 = new Form1();
// Create a thread to listen concurrently to the GUI thread
Thread listenerThread = new Thread(new ParameterizedThreadStart(Listener));
listenerThread.IsBackground = true;
listenerThread.Start(form1);
// Run the form
System.Windows.Forms.Application.Run(form1);
}
static void Listener(object formObject)
{
Form1 form = (Form1)formObject;
// Do whatever we need to do
while (true)
{
Thread.Sleep(1000);
form.AddLineToTextBox("Hello");
}
}
}
|
7210aedbe2870b82e5ec4bd659de0f22ed1625c5
|
C#
|
HypahCode/Blueprint
|
/Blueprint/RenderEngine/PrimitiveRenderer.cs
| 2.78125
| 3
|
using System.Collections.Generic;
using System.Drawing;
using Blueprint.VectorImagess;
using BlueprintAddon;
using TrigonometryLib.Primitives;
namespace Blueprint.RenderEngine
{
internal class PrimitiveRenderer : Renderer
{
internal LayeredVectorImage layeredImage = null;
private bool isActive = false;
internal override void Draw(RenderContext context)
{
base.Draw(context);
if (layeredImage != null)
{
isActive = false;
for (int i = 0; i < layeredImage.Count; i++)
{
if (layeredImage.Get(i) != layeredImage.Image)
{
DrawPrimitiveList(context, layeredImage.Get(i).primitives);
}
}
isActive = true;
DrawPrimitiveList(context, layeredImage.Image.primitives);
}
}
private void DrawPrimitiveList(RenderContext context, List<Primitive2D> pList)
{
for (int i = 0; i < pList.Count; i++)
{
if (pList[i] is ICustomDrawable) ((ICustomDrawable)pList[i]).Draw(context, IsPrimitiveSelected(pList[i]));
else if (pList[i] is Vector2D) DrawVector2D(context, pList[i] as Vector2D);
else if (pList[i] is Line2D) DrawLine2D(context, pList[i] as Line2D);
else if (pList[i] is Triangle2D) DrawTriangle2D(context, pList[i] as Triangle2D);
else if (pList[i] is Circle2D) DrawCircle2D(context, pList[i] as Circle2D);
else if (pList[i] is Shape2D) DrawShape2D(context, pList[i] as Shape2D);
else if (pList[i] is ICompoundPrimitive2D) DrawPrimitiveList(context, (pList[i] as ICompoundPrimitive2D).GetPrimitives());
}
}
private void DrawVector2D(RenderContext context, Vector2D v)
{
if (context.ShowPoints)
{
context.Graphics.DrawPoint(context.PointToScreen(v), GetColor(v, Colors.Vector2D), 3);
}
}
private void DrawLine2D(RenderContext context, Line2D l)
{
if (context.ShowLines)
{
Vector2D p1 = context.PointToScreen(l.Start);
Vector2D p2 = context.PointToScreen(l.End);
context.Graphics.DrawLine(p1, p2, GetColor(l, Colors.Line2D), 2);
}
}
private void DrawTriangle2D(RenderContext context, Triangle2D t)
{
if ((context.ShowTriangles) || (context.ShowFilledTriangles))
{
Vector2D a = context.PointToScreen(t.a);
Vector2D b = context.PointToScreen(t.b);
Vector2D c = context.PointToScreen(t.c);
if (context.ShowFilledTriangles)
{
context.Graphics.FillPolygon(new Vector2D[] { a, b, c }, GetColor(t, Colors.Triangle2DFilled));
}
if (context.ShowTriangles)
{
context.Graphics.DrawLine(a, b, GetColor(t, Colors.Triangle2D), 2);
context.Graphics.DrawLine(b, c, GetColor(t, Colors.Triangle2D), 2);
context.Graphics.DrawLine(c, a, GetColor(t, Colors.Triangle2D), 2);
}
}
}
private void DrawCircle2D(RenderContext context, Circle2D c)
{
if (context.ShowCircles)
{
Vector2D p1 = context.PointToScreen(c.center - c.radius);
int wh = (int)(c.radius * 2 * context.DrawScale);
context.Graphics.DrawEllipse(new Rectangle2D(p1.x, p1.y, wh, wh), GetColor(c, Colors.Circle2D), 2);
}
}
private void DrawShape2D(RenderContext context, Shape2D s)
{
if (context.ShowShapes)
{
List<Line2D> lines = s.GetLines();
for (int i = 0; i < lines.Count; i++)
{
Vector2D p1 = context.PointToScreen(lines[i].Start);
Vector2D p2 = context.PointToScreen(lines[i].End);
context.Graphics.DrawLine(p1, p2, GetColor(s, Colors.Shape2D), 2);
}
}
}
private Color GetColor(Primitive2D p, Colors.ColorPair defaultColors)
{
if (!isActive)
return defaultColors.Inactive;
PrimitiveRenderData data = p.GetData<PrimitiveRenderData>();
if (data != null)
{
return data.isSelected ? defaultColors.Selected : data.GetColor(defaultColors.Active);
}
return defaultColors.Active;
}
private bool IsPrimitiveSelected(Primitive2D p)
{
PrimitiveRenderData data = p.GetData<PrimitiveRenderData>();
if (data != null)
{
return data.isSelected;
}
return false;
}
}
}
|
b3e99167b1f177343d6e4d134466687278d40bb8
|
C#
|
eunabae/A3
|
/SES_Add-On/WindowsFormsApp1/ControlMap.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SES_Add_ON
{
class ControlMap
{
MapForm mapform;
ControlPath controlpath = new ControlPath();
static private char[,] ControlMap_map;
static private int[] ControlMap_mapsize;
static private int[] ControlMap_start;
static private char temp;
static int checkColor=0; //이전 위치가 탐색지점인지 체크하는 변수
static int count = 1; //찾은 탐색지점의 개수를 체크하는 변수
public ControlMap() { temp = ' '; }
public ControlMap(MapForm mapform)
{
this.mapform = mapform;
}
public char[,] map
{
get { return ControlMap_map; }
}
public int[] mapsize
{
get { return ControlMap_mapsize; }
}
public int[] start
{
get { return ControlMap_start; }
}
public void setMapsize()
{
MapInfo mapinfo = new MapInfo(this);
ControlMap_mapsize = mapform.mapsize; // MapForm의 mapsize를 받아 ControlMap_mapsize로 저장
mapinfo.setMapSize(); // MapInfo에 지도크기 저장
}
public void setMap() {
MapInfo mapinfo = new MapInfo(this);
ControlMap_map = mapform.maze; //MapForm의 maze를 받아 ControlMap_mapdm로 저장
}
public void setMapstart()
{
MapInfo mapinfo = new MapInfo(this);
ControlMap_start = mapform.start; //MapForm의 start 받아 ControlMap_start로 저장
mapinfo.setMapstart();
}
public void saveMap() //MapInfo에 지도 저장
{
MapInfo mapinfo = new MapInfo(this);
mapinfo.setMapInfo();
}
public void createMap() //지도 생성
{
int i, j;
setMap();
setMapsize();
setMapstart();
ControlMap_map = new char[ControlMap_mapsize[0], ControlMap_mapsize[1]];
for (i = 0; i < ControlMap_mapsize[0]; i++)
{ //행
for (j = 0; j < ControlMap_mapsize[1]; j++)
{ //열
ControlMap_map[i, j] = '□';
}
}
saveMap();
mapform.printmap(ControlMap_map); //생성된 지도 출력
}
public void initStart(int [] start) // 시작위치 초기화
{
PositionInfo positioninfo = new PositionInfo();
ControlMap_map[start[0], start[1]] = '▣'; //로봇을 시작위치에
positioninfo.initPosition(start); // PositionInfo에 현재위치로 초기화
mapform.printmap(ControlMap_map);
}
public void initHazard(List<int[]> hazardset) // MapForm에서 입력받은 위험지점 추가
{
HazardInfo hazardinfo = new HazardInfo();
int i;
int x, y;
for (i = 0; i < hazardset.Count; i++)
{
x = hazardset[i][0];
y = hazardset[i][1];
ControlMap_map[x, y] = 'X'; //위험지역 표시
}
saveMap();
hazardinfo.initHazard(hazardset);
mapform.printmap(ControlMap_map);
}
public void initColorblob(List<int[]> colorset) // MapForm에서 입력받은 탐색지점 추가
{
ColorInfo colorinfo = new ColorInfo();
int i;
int x, y;
for (i = 0; i < colorset.Count; i++)
{
x = colorset[i][0];
y = colorset[i][1];
ControlMap_map[x, y] = '★'; //탐색지점 표시
}
saveMap();
colorinfo.initColor(colorset);
mapform.printmap(ControlMap_map); //지도 출력
}
public void updateHazard(int[] hazard) //Sensor로 발견된 위험지점을 지도에 추가
{
ControlMap_map[hazard[0], hazard[1]] = 'X';
saveMap();
}
public void updateColor(int[] color) //Sensor로 발견된 중요지점을 지도에 추가
{
ControlMap_map[color[0], color[1]] = '◆';
saveMap();
}
public void clearPosition(int[] position) //이전 위치 초기화
{
if (checkColor == 1)
{
ControlMap_map[position[0], position[1]] = '☆';
checkColor = 0;
}
else
{
switch (temp)
{
case '☆': ControlMap_map[position[0], position[1]] = '☆'; break;
case '★': ControlMap_map[position[0], position[1]] = '★'; break;
case '◆': ControlMap_map[position[0], position[1]] = '◆'; break;
case 'X': ControlMap_map[position[0], position[1]] = 'X'; break;
default: ControlMap_map[position[0], position[1]] = '□'; break;
}
}
saveMap();
}
public void updatePosition(int[] position) //움직인 위치 표시
{
if (ControlMap_map[position[0], position[1]] == '★')
{
checkColor = 1;
controlpath.setCount(count++); // 찾은 중요지점 개수를 넘김
}
temp = ControlMap_map[position[0], position[1]];
ControlMap_map[position[0], position[1]] = '▣'; // 다음 위치 표시
saveMap(); //지도저장
}
}
}
|
a9f32f059cc7d0d28151a2402c73ee3bc9843f73
|
C#
|
sandromirr/num-to-word
|
/num-to-word/UnitTest.cs
| 3.203125
| 3
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace num_to_word
{
[TestClass]
public class UnitTest
{
NumberConverter con;
[TestMethod]
public void ZeroTest()
{
con = new NumberConverter(0);
Assert.AreEqual("ნული", con.toWord());
}
[TestMethod]
public void InvalidInput()
{
con = new NumberConverter(-3333);
Assert.AreEqual("არასწორია ფორმატი!", con.toWord());
}
[TestMethod]
public void ThreeTest()
{
con = new NumberConverter(3);
Assert.AreEqual("სამი", con.toWord());
}
[TestMethod]
public void EightTest()
{
con = new NumberConverter(8);
Assert.AreEqual("რვა", con.toWord());
}
[TestMethod]
public void ElevenTest()
{
con = new NumberConverter(11);
Assert.AreEqual("თერთმეტი", con.toWord());
}
[TestMethod]
public void EightTeenTest()
{
con = new NumberConverter(18);
Assert.AreEqual("თვრამეტი", con.toWord());
}
[TestMethod]
public void TwentyTest()
{
con = new NumberConverter(20);
Assert.AreEqual("ოცი", con.toWord());
}
[TestMethod]
public void TwentyTwoTest()
{
con = new NumberConverter(22);
Assert.AreEqual("ოცდაორი", con.toWord());
}
[TestMethod]
public void Test30()
{
con = new NumberConverter(30);
Assert.AreEqual("ოცდაათი", con.toWord());
}
[TestMethod]
public void ThirtyFourTest()
{
con = new NumberConverter(34);
Assert.AreEqual("ოცდათოთხმეტი", con.toWord());
}
[TestMethod]
public void FourtyTest()
{
con = new NumberConverter(40);
Assert.AreEqual("ორმოცი", con.toWord());
}
[TestMethod]
public void FourtySixTest()
{
con = new NumberConverter(46);
Assert.AreEqual("ორმოცდაექვსი", con.toWord());
}
[TestMethod]
public void FiftyTest()
{
con = new NumberConverter(50);
Assert.AreEqual("ორმოცდაათი", con.toWord());
}
[TestMethod]
public void SeventyEightTest()
{
con = new NumberConverter(78);
Assert.AreEqual("სამოცდათვრამეტი", con.toWord());
}
[TestMethod]
public void EightThreeTest()
{
con = new NumberConverter(83);
Assert.AreEqual("ოთხმოცდასამი", con.toWord());
}
[TestMethod]
public void NinetyFiveTest()
{
con = new NumberConverter(95);
Assert.AreEqual("ოთხმოცდათხუთმეტი", con.toWord());
}
[TestMethod]
public void HundredTest()
{
con = new NumberConverter(100);
Assert.AreEqual("ასი", con.toWord());
}
[TestMethod]
public void HundredOneTest()
{
con = new NumberConverter(101);
Assert.AreEqual("ას ერთი", con.toWord());
}
[TestMethod]
public void HundredFiftyFiveTest()
{
con = new NumberConverter(155);
Assert.AreEqual("ას ორმოცდათხუთმეტი", con.toWord());
}
[TestMethod]
public void ThousandTest()
{
con = new NumberConverter(1000);
Assert.AreEqual("ათასი", con.toWord());
}
[TestMethod]
public void ThousandTwentyNineTest()
{
con = new NumberConverter(1029);
Assert.AreEqual("ათას ოცდაცხრა", con.toWord());
}
[TestMethod]
public void ThousandFiveHundredTwentyNineTest()
{
con = new NumberConverter(1529);
Assert.AreEqual("ათას ხუთ ას ოცდაცხრა", con.toWord());
}
[TestMethod]
public void ThousandSevenHundredFiftySixTest()
{
con = new NumberConverter(1756);
Assert.AreEqual("ათას შვიდ ას ორმოცდათექვსმეტი", con.toWord());
}
[TestMethod]
public void ThousandNineHundredFiftyTest()
{
con = new NumberConverter(1950);
Assert.AreEqual("ათას ცხრა ას ორმოცდაათი", con.toWord());
}
[TestMethod]
public void FiveThousandNineHundredFiftyTest()
{
con = new NumberConverter(5950);
Assert.AreEqual("ხუთი ათას ცხრა ას ორმოცდაათი", con.toWord());
}
[TestMethod]
public void ThreeThousandHundredFiftyOneTest()
{
con = new NumberConverter(3151);
Assert.AreEqual("სამი ათას ას ორმოცდათერთმეტი", con.toWord());
}
[TestMethod]
public void Test()
{
con = new NumberConverter(6459);
Assert.AreEqual("ექვსი ათას ოთხ ას ორმოცდაცხრამეტი", con.toWord());
}
[TestMethod]
public void TenThousand()
{
con = new NumberConverter(10000);
Assert.AreEqual("ათი ათასი", con.toWord());
}
[TestMethod]
public void ThreeThousandTwentyTwo()
{
con = new NumberConverter(3022);
Assert.AreEqual("სამი ათას ოცდაორი", con.toWord());
}
[TestMethod]
public void NinetySeven()
{
con = new NumberConverter(97);
Assert.AreEqual("ოთხმოცდაჩვიდმეტი", con.toWord());
}
[TestMethod]
public void FiveHundredFive()
{
con = new NumberConverter(505);
Assert.AreEqual("ხუთ ას ხუთი", con.toWord());
}
[TestMethod]
public void SixThousandSevenHunderedFiftyFour()
{
con = new NumberConverter(6754);
Assert.AreEqual("ექვსი ათას შვიდ ას ორმოცდათოთხმეტი", con.toWord());
}
[TestMethod]
public void SixThosand()
{
con = new NumberConverter(6000);
Assert.AreEqual("ექვსი ათასი", con.toWord());
}
}
}
|
04bea9ec73812d9fb48640fab4c449bd3a0c0b57
|
C#
|
Vasilev07/Softuni-2016-2017
|
/Fundamentals of Computer Programming - book/PrimitiveTypesAndVariables/04.VarInHexFormat/VarInHexFormat.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04.VarInHexFormat
{
class VarInHexFormat
{
static void Main(string[] args)
{
int a = 256;
string aInHex = a.ToString("X");
Console.WriteLine("{0} \'a\' in bin ; \n {1} \'a\' in hex ", a, aInHex);
}
}
}
|
076e0e8c72f4397b304cf8fc51069d3bbf871aa9
|
C#
|
felipelino/kafka-flow
|
/src/KafkaFlow/Consumers/OffsetsWatermark.cs
| 2.53125
| 3
|
namespace KafkaFlow.Consumers
{
using System;
using Confluent.Kafka;
internal readonly struct OffsetsWatermark : IOffsetsWatermark, IEquatable<OffsetsWatermark>
{
private readonly WatermarkOffsets watermark;
public OffsetsWatermark(WatermarkOffsets watermark)
{
this.watermark = watermark;
}
public long High => this.watermark.High.Value;
public long Low => this.watermark.Low.Value;
public bool Equals(OffsetsWatermark other)
{
return Equals(this.watermark, other.watermark);
}
public override bool Equals(object obj)
{
return obj is OffsetsWatermark other && this.Equals(other);
}
public override int GetHashCode()
{
return this.watermark != null ? this.watermark.GetHashCode() : 0;
}
}
}
|
6bcfc1180439455765e89e6ae35f4d3843bd6b27
|
C#
|
software-engineering-network/design-pattern-practice
|
/TinyTypes.Gerhard.ProductService/Test/PriceTest.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace TinyTypes.Gerhard.ProductService.Test
{
public class PriceTest
{
[Fact]
public void WhenPrice_IsValid_ItContainsValidDecimalValue()
{
decimal validPrice = 9.99m;
Price price = new Price(validPrice);
Assert.Equal(price.Value, validPrice);
}
[Fact]
public void WhenPrice_IsNegative_ItThrowsArgumentException()
{
decimal negativePrice = -9.99m;
Assert.Throws<ArgumentException>(() => new Price(negativePrice));
}
[Fact]
public void WhenPrice_IsMoreThanTwoDecimalPlaces_ItThrowsArgumentException()
{
decimal priceThatIsTooPrecise = 9.999m;
Assert.Throws<ArgumentException>(() => new Price(priceThatIsTooPrecise));
}
}
}
|
92e370a435833f6762bd2f03602f36f617af37b1
|
C#
|
sonawanenikita24/DeviceApplicationXamarin
|
/DeviceApplication/DeviceApplication/View/PhoneDailing.xaml.cs
| 2.8125
| 3
|
//--------------------------------------------------------------------------------------------------------------------
// <copyright file="MainPage.cs" company="BridgeLabz">
// copyright @2019
// </copyright>
// <creater name="Nikita Sonawane"/>
//------------------------------------------------------------------------------------------------------------------
namespace DeviceApplication.View
{
using System;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PhoneDailing : ContentPage
{
/// <summary>
/// Initializes a new instance of the <see cref="PhoneDailing"/> class.
/// </summary>
public PhoneDailing()
{
InitializeComponent();
}
/// <summary>
/// When overridden, allows application developers to customize behavior immediately prior to the <see cref="T:Xamarin.Forms.Page" /> becoming visible.
/// </summary>
/// <remarks>
/// To be added.
/// </remarks>
protected override void OnAppearing()
{
base.OnAppearing();
}
/// <summary>
/// Calls the specified number.
/// </summary>
/// <param name="number">The number.</param>
/// <returns></returns>
public async Task Call(string number)
{
try
{
PhoneDialer.Open(number);
}
catch (ArgumentNullException arex)
{
Console.WriteLine(arex.Message);
}
catch (FeatureNotSupportedException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// Handles the Clicked event of the Call_Button control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private async void Call_Button_Clicked(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtNumber.Text))
{
await Call(txtNumber.Text);
}
}
}
}
|
21b7c21b6d04991eb55621f8d058f9a03c1aaf22
|
C#
|
mridul2101/CabManager
|
/CabManagement/CabManagementPortal/Services/BookingService/BookingStrategy/MostIdleBookingStrategy.cs
| 2.65625
| 3
|
using CabManagementPortal.Services.InsightsService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CabManagementPortal.Services.BookingService.BookingStrategy
{
internal abstract class BaseBookingStrategy : IBookingStrategy
{
public abstract Strategy Strategy { get; }
public int GetCab(IList<int> availableCabs, IList<CabInsightEntity> cabInsights)
{
if(availableCabs.Count == 0)
{
throw new Exception("No Cab available");
}
if (cabInsights.Count == 0)
{
return availableCabs.First();
}
return GetCabInternal(availableCabs, cabInsights);
}
internal abstract int GetCabInternal(IList<int> availableCabs, IList<CabInsightEntity> cabInsights);
}
internal class MostIdleBookingStrategy : BaseBookingStrategy
{
public override Strategy Strategy => Strategy.MostIdle;
internal override int GetCabInternal(IList<int> availableCabs, IList<CabInsightEntity> cabInsights)
{
CabInsightEntity mostIdleCab = cabInsights.First();
foreach(var cab in cabInsights)
{
if(cab.IdleTime > mostIdleCab.IdleTime)
{
mostIdleCab = cab;
}
}
return mostIdleCab.CabId;
}
}
}
|
4a82f53f974c62a568fbb583c340bbaf6f9c307a
|
C#
|
JamieSandell/CSharp
|
/Program Restarter/Program Restarter/Form1.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Program_Restarter
{
public partial class FormMain : Form
{
#region Member Variables
private AboutBox m_aboutBox;
private bool m_buttonClick;
private Timer m_myTimer;
private Logic m_logic;
private Options m_optionsForm;
private string m_optionsFile;
#endregion
#region Constructors
public FormMain()
{
InitializeComponent();
m_logic = new Logic();
m_logic.SetInterval(2000);
m_myTimer = new Timer();
m_myTimer.Tick += new EventHandler(DisplayTimerEvent);
m_myTimer.Interval = 2000;
m_myTimer.Start();
m_buttonClick = false;
textBoxNumberOfCrashesThisSession.Text = "0";
m_optionsFile = ".//options.txt";
m_optionsForm = new Options(this);
m_aboutBox = new AboutBox();
string result = LoadOptionsFile();
if (result != "")
MessageBox.Show(result, "Program Restarter", MessageBoxButtons.OK);
}
#endregion
#region Accessors
/// <summary>
/// Gets the location (including filename) of the options file.
/// </summary>
/// <returns>The location (including the filename) of the options file.</returns>
public string GetOptionsFileLocation()
{
return m_optionsFile;
}
/// <summary>
/// Gets the name of the program to restart.
/// </summary>
/// <returns>The name of the program to restart.</returns>
public string GetProgramName()
{
return m_logic.GetProgramName();
}
/// <summary>
/// Sets the interval (in milli-seconds) between checks to see if the designated program hasn't crashed.
/// The value must be greater than zero and less than or equal to System.Int32.MaxValue.
/// </summary>
/// <param name="interval">The interval in milli-seconds</param>
/// <returns>An empty string if everything went OK, else an error message is returned.</returns>
public string SetInterval(double interval)
{
if (interval <= 0)
return "The interval must be greater than 0.";
else
{
string reply = m_logic.SetInterval(interval);
if (reply != "")
return reply;
return "";
}
}
#endregion
#region Member Methods
/// <summary>
/// Shows the about box.
/// </summary>
/// <param name="sender">The source that fired the event.</param>
/// <param name="e">Data for the event.</param>
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_aboutBox.IsDisposed)
m_aboutBox = new AboutBox();
m_aboutBox.Show(); ;
}
/// <summary>
/// Starts/Stops the monitoring of the program.
/// </summary>
/// <param name="sender">The object that fired the event.</param>
/// <param name="e">The event arguments.</param>
private void buttonStartStop_Click(object sender, EventArgs e)
{
if (m_buttonClick == false)
{
m_buttonClick = true;
buttonStartStop.Text = "Stop Monitoring";
m_logic.Start();
}
else
{
m_buttonClick = false;
buttonStartStop.Text = "Start Monitoring";
m_logic.Stop();
}
}
/// <summary>
/// Delegate for timer variable.
/// </summary>
/// <param name="source">The object that fired the event</param>
/// <param name="e">Data for the event.</param>
private void DisplayTimerEvent(object source, EventArgs e)
{
if (m_logic.GetErrorStartingProgram())
{
MessageBox.Show(m_logic.GetErrorString(), "Program Restarter", MessageBoxButtons.OK);
}
textBoxNumberOfCrashesThisSession.Text = (m_logic.GetNumberOfCrashesThisSession()).ToString();
}
/// <summary>
/// Closes the application.
/// </summary>
/// <param name="sender">The object that fired the event.</param>
/// <param name="e">Data for the event.</param>
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private string LoadOptionsFile()
{
string baseError = "There was a problem loading the options file. The error was:\r\n";
StreamReader sr = null;
// Try and open the options file, read from it, and then close it.
try
{
sr = new StreamReader(m_optionsFile);
string line = sr.ReadLine();
// Try and convert the read in line to the appropriate variable type
try
{
m_optionsForm.SetProgramToRestart(line);
line = sr.ReadLine();
double interval = Convert.ToDouble(line);
string result = m_logic.SetInterval(interval);
if (result != "")
return baseError + result;
decimal intervalDec = Convert.ToDecimal(interval);
m_optionsForm.SetInterval(intervalDec);
SetProgramParameters();
}
catch (System.FormatException ex)
{
return baseError + ex.ToString();
}
catch (System.OverflowException ex)
{
return baseError + ex.ToString();
}
catch (System.Exception ex)
{
return baseError + ex.ToString();
}
}
catch (System.ArgumentNullException ex)
{
return baseError + ex.ToString();
}
catch (System.ArgumentException ex)
{
return baseError + ex.ToString();
}
catch (System.IO.FileNotFoundException ex)
{
return baseError + ex.ToString();
}
catch (System.IO.DirectoryNotFoundException ex)
{
return baseError + ex.ToString();
}
catch (System.IO.IOException ex)
{
return baseError + ex.ToString();
}
catch (System.Exception ex)
{
return baseError + ex.ToString();
}
finally
{
if (sr != null)
sr.Close();
}
return "";
}
/// <summary>
/// Shows the options form.
/// </summary>
/// <param name="sender">The object that fired the event.</param>
/// <param name="e">Data for the event.</param>
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_optionsForm.IsDisposed)
m_optionsForm = new Options(this);
m_optionsForm.Show();
}
public void SetProgramParameters()
{
//OpenFileDialog ofd = m_optionsForm.GetOpenFileDialog();
//if (ofd != null)
//{
// m_logic.SetProgramName(ofd.FileName);
//}
m_logic.SetProgramName(m_optionsForm.GetProgramName());
}
#endregion
}
}
|
2384a17b6a8f9203c8b357a26cfb83265491e142
|
C#
|
wiltaylor/VMLab-CSharp-Legacy
|
/VMLab/Model/IIdempotentAction.cs
| 2.546875
| 3
|
using System.CodeDom;
using System.Collections;
using System.Linq;
using System.Management.Automation;
namespace VMLab.Model
{
public enum IdempotentActionResult
{
Ok,
Failed,
RebootRequired,
NotConfigured
}
public interface IIdempotentAction
{
string Name { get; }
ScriptBlock Test { get; }
ScriptBlock Update { get; }
string[] RequiredProperties { get; }
string[] OptionalProperties { get; }
IdempotentActionResult TestAction(Hashtable properties);
IdempotentActionResult UpdateAction(Hashtable properties);
}
public class IdempotentAction : IIdempotentAction
{
public string Name { get; }
public ScriptBlock Test { get; }
public ScriptBlock Update { get; }
public string[] RequiredProperties { get; }
public string[] OptionalProperties { get; }
public IdempotentAction(string name, ScriptBlock test, ScriptBlock update, string[] required, string[] optional)
{
Name = name;
Test = test;
Update = update;
RequiredProperties = required;
OptionalProperties = optional;
}
public IdempotentActionResult TestAction(Hashtable properties)
{
var results = Test.Invoke(properties).FirstOrDefault();
if(results?.BaseObject == null)
return IdempotentActionResult.NotConfigured;
if(results.BaseObject is bool && (bool)results.BaseObject)
return IdempotentActionResult.Ok;
var s = results.BaseObject as string;
if(s != null && s == "reboot")
return IdempotentActionResult.RebootRequired;
if (results.BaseObject is bool && !(bool)results.BaseObject)
return IdempotentActionResult.NotConfigured;
return IdempotentActionResult.Failed;
}
public IdempotentActionResult UpdateAction(Hashtable properties)
{
var results = Update.Invoke(properties).FirstOrDefault();
if (results?.BaseObject == null)
return IdempotentActionResult.NotConfigured;
if (results.BaseObject is bool && (bool)results.BaseObject)
return IdempotentActionResult.Ok;
if (results.BaseObject is bool && !(bool)results.BaseObject)
return IdempotentActionResult.NotConfigured;
var s = results.BaseObject as string;
if (s != null && s == "reboot")
return IdempotentActionResult.RebootRequired;
return IdempotentActionResult.Failed;
}
}
}
|
f99522259db99f2180227a21666f312b046c3103
|
C#
|
shendongnian/download4
|
/code10/1755203-52652279-183103675-6.cs
| 2.59375
| 3
|
public override void OnException(HttpActionExecutedContext context) {
// Any custom AD API Exception thrown will be serialized into our custom response
// Any other exception will be handled by the Microsoft framework
if (context.Exception is OurAdApiException contextException) {
try {
// This lets us use HTTP Status Codes to indicate REST results.
// An invalid parameter value becomes a 400 BAD REQUEST, while
// a configuration error is a 503 SERVICE UNAVAILABLE, for example.
// (Code for CreateCustomErrorResponse available upon request...
// we basically copied the .NET framework code because it wasn't
// possible to modify/override it :(
context.Response = context.Request.CreateCustomErrorResponse(contextException.HttpStatusCode, contextException);
}
catch (Exception exception) {
exception.Swallow($"Caught an exception creating the custom response; IIS will generate the default response for the object");
}
}
}
|
321051a5415719825d8a933baf4cc1c737b45344
|
C#
|
Softuni-Alex/Softuni
|
/DB-Advanced/09.Json-Exercises/Json/Json/Models/User.cs
| 2.53125
| 3
|
namespace Json.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class User
{
public User()
{
this.Sold = new List<Product>();
this.Bought = new List<Product>();
this.Friends = new List<User>();
}
public int Id { get; set; }
public string FirstName { get; set; }
[MinLength(3)]
public string LastName { get; set; }
public int Age { get; set; }
public virtual ICollection<Product> Sold { get; set; }
public virtual ICollection<Product> Bought { get; set; }
public virtual ICollection<User> Friends { get; set; }
}
}
|
b247df44231cbd5c18ece7e02cc77782b6f91c76
|
C#
|
shendongnian/download4
|
/code5/798233-19559595-147178847-2.cs
| 3.34375
| 3
|
public string Represent(string s)
{
int i = 0;
if (int.TryParse(s, out i))
{
return(i.ToString().PadLeft(6,'0'));
}
}
|
b3d187973669064eec49d1557d335d1cdc9d81a8
|
C#
|
kalmar98/TECHNOLOGY-FUNDAMENTALS
|
/Programming Fundamentals/C# Data Types and Variables - Exercises/19. Thea The Photographer.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Numerics;
namespace training
{
class Program
{
static void Main()
{
//Bring Me The Horizon - Empire
ulong amountPictures = ulong.Parse(Console.ReadLine());
ulong filterTimePerPicture = ulong.Parse(Console.ReadLine());
double filterFactor = double.Parse(Console.ReadLine())/100;
ulong uploadTimePerPicture = ulong.Parse(Console.ReadLine());
ulong filteredPictures = (ulong)(Math.Ceiling(amountPictures * filterFactor));
ulong totalTimeInSeconds = (amountPictures * filterTimePerPicture) + (filteredPictures * uploadTimePerPicture);
TimeSpan wholeTime = TimeSpan.FromSeconds(totalTimeInSeconds);
Console.WriteLine($"{wholeTime.Days}:{wholeTime.Hours:d2}:{wholeTime.Minutes:d2}:{wholeTime.Seconds:d2}");
}
}
}
|
2383fc2f94c3b54e6ac5ad39c0a600f77e086d6d
|
C#
|
PlumpMath/RayXu.HeadFirst.DesignPattern
|
/RayXu.HeadFirst.DesignPattern.Iterator/Concrete/Menu/PancakeHouseMenuInfo.cs
| 2.84375
| 3
|
/**************************************************
* Author: Ray Xu
* CLR Version: 4.0.30319.42000
* Create Time: 2016/5/12 7:06:46
* Description:
*
* Update History:
* 2016/5/12 7:06:46:Create.
*
**************************************************/
using RayXu.HeadFirst.DesignPattern.Iterator.Abstract;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RayXu.HeadFirst.DesignPattern.Iterator.Concrete
{
public class PancakeHouseMenuInfo : IMenu
{
#region Members
private ArrayList _menuItems;
#endregion
#region Properties
#endregion
#region Constructors
public PancakeHouseMenuInfo()
{
_menuItems = new ArrayList();
AddMenuItem("K&B's Pancake Breakfast", "Pancakes with scrambled eggs, and toast", true, 2.99);
AddMenuItem("Regular Pancake Breakfast", "Pancakes with fried eggs, and sausage", false, 2.99);
AddMenuItem("Blueberry Pancakes", "Pancakes made with fresh blueberries", true, 3.49);
AddMenuItem("Waffles", "Waffles, with your choice of blueberries or strawberries", true, 3.59);
}
#endregion
#region Methods
public void AddMenuItem(string name, string desc, bool isVege, double price)
{
MenuItemInfo item = new MenuItemInfo(name, desc, isVege, price);
_menuItems.Add(item);
}
#endregion
#region IMenu Methods
public IIterator CreateIterator()
{
return new PancakeHouseIterator(_menuItems);
}
#endregion
}
}
|
19a95d765866d6373a78c747825129b43b5ff98d
|
C#
|
PikataGitHub/CSharp-OOP
|
/06. Common Type System/Problem04.PersonClass/Person.cs
| 4.1875
| 4
|
namespace Problem04.PersonClass
{
using System;
public class Person
{
//Fields
private string name;
private int? age;
//Constructors
public Person(string inputName, int? inputAge)
{
this.Name = inputName;
this.Age = inputAge;
}
//Properties
public string Name
{
get { return this.name; }
private set
{
if (value.Length < 3)
{
throw new ArgumentException("Person Name must be at least 3 letters");
}
this.name = value;
}
}
public int? Age
{
get { return this.age; }
private set
{
if (value < 0 || value > 130)
{
throw new ArgumentException("Age must be between [0; 130]");
}
this.age = value;
}
}
//Methods
public override string ToString()
{
if (this.Age == null)
{
return string.Format("Person Name: {0}, Age: \"not specified\"", this.Name);
}
return string.Format("Person Name: {0}, Age: {1}", this.Name, this.Age);
}
}
}
|
1c8647fc4278a26f9cdaaefba97ccf54b94c0bb1
|
C#
|
BartoszKonkol/projects
|
/JAO/1.1/setup/JAO.cs
| 2.75
| 3
|
using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace JAO_Setup
{
static class JAO
{
public const string Title = "Java Application Open", Version = "1.1.1", ISA = "x64";
public static Form Window = new Window();
public static Taskbar Taskbar = new Taskbar();
public static volatile List<string> FileDownloadLast = new List<string>();
public static volatile int ProgressPercent = 0;
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
((Window) Window).InitializeWindow();
Application.Run(Window);
}
catch(Exception e)
{
CriticalError(e);
}
}
public static Assembly GiveAssembly(string library)
{
return Assembly.LoadFrom(Path.GetFullPath(library + ".dll"));
}
public static void CriticalError(Exception e)
{
Taskbar.Progress(Taskbar.ProgressState.Error);
if(MessageBox.Show("Wystąpił niezdefiniowany błąd krytyczny!\nPowód:\n " + e.Message.Replace("\n", "\n ") + "\n\nSpróbuj uruchomić instalator ponownie.\nJeśli błąd nie ustąpi, zgłoś zaistniałą sytuację do Polish Games Studio.\n\nCzy chcesz uzyskać opis techniczny powstałego błędu?", JAO.Title, MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes)
MessageBox.Show("Informacje techniczne dotyczące wystąpienia błędu krytycznego:\n\n\n~ !Message\n" + e.Message + "\n\n~ !StackTrace\n" + e.StackTrace + "\n\n~ !Source\n" + e.Source + "\n\n~ !TargetSite\n" + e.TargetSite + "\n\n~ !.GetType.FullName\n" + e.GetType().FullName + "\n\n~ ?DateTime.Now..ToString(string)\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm (dddd)") + "\n\n~ ?Directory..GetCurrentDirectory\n" + Directory.GetCurrentDirectory() + "\n\n~ ?Directory..GetDirectories(*'.GetCurrentDirectory).Length\n" + Directory.GetDirectories(Directory.GetCurrentDirectory()).Length + "\n\n~ ?Directory..GetFiles(*'.GetCurrentDirectory).Length\n" + Directory.GetFiles(Directory.GetCurrentDirectory()).Length, JAO.Title, MessageBoxButtons.OK, MessageBoxIcon.Information);
Environment.Exit(1);
}
public static void DirectoryDelete(string directory)
{
if(Directory.GetFiles(directory).Length == 0 && Directory.GetDirectories(directory).Length == 0)
{
Directory.Delete(directory);
DirectoryDelete(Path.GetDirectoryName(directory));
}
}
public static string FileDownload(string file, ProgressBar progress, float percent)
{
try
{
WebClient web = new WebClient();
web.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs args) => { progress.Value = ProgressPercent + (int)Math.Round(args.ProgressPercentage * (percent / 100)); };
web.DownloadFileCompleted += (object sendr, System.ComponentModel.AsyncCompletedEventArgs args) => {FileDownloadLast.Add(file); ProgressPercent += (int)Math.Round(percent); progress.Value = ProgressPercent;};
web.DownloadFileAsync(new Uri("http://www.res.jao.polishgames.net/" + file), file);
}
catch(WebException e)
{
Taskbar.Progress(Taskbar.ProgressState.Error);
DialogResult result = MessageBox.Show("Wystąpił błąd podczas próby pobierania pliku '" + file + "':\n " + e.Message + "\n\nSprawdź swoje połączenie internetowe i spróbuj ponownie.\nJeśli błąd nie ustąpi, zgłoś zaistniałą sytuację do Polish Games Studio.", JAO.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
if(result == DialogResult.OK)
Environment.Exit(2);
}
return file;
}
public static string ZipExtract(string file, string directory, Assembly assembly)
{
if(directory == null)
directory = ".";
if(directory.Length > 0)
Directory.CreateDirectory(directory);
Type type = assembly.GetType("Ionic.Zip.ZipFile");
Type typeEnum = assembly.GetType("Ionic.Zip.ExtractExistingFileAction");
object zip = Activator.CreateInstance(type, new object[] {file += "-" + ISA + ".zip"});
type.GetMethod("ExtractAll", new Type[]{Type.GetType("System.String"), typeEnum}).Invoke(zip, new object[]{directory, typeEnum.GetEnumValues().GetValue(1)});
type.GetMethod("Dispose").Invoke(zip, null);
return file;
}
}
}
|
fb6295924ed7e000339049322036ed7b47d8abe4
|
C#
|
shendongnian/download4
|
/first_version_download2/200230-15366882-37335229-2.cs
| 3.203125
| 3
|
var builder = new StringBuilder();
foreach (var type in typeof(MyClass).GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic))
{
if (!type.IsAbstract)
{
continue;
}
builder.AppendLine(type.Name);
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)) {
var msg = String.Format("{0} = {1}", field.Name, field.GetValue(null));
builder.AppendLine(msg);
}
}
string output = builder.ToString();
|
b8656f2a67faef8c8ceed3c45c164d500724c3f9
|
C#
|
Hegom/Employees
|
/Employee.Test/EmployeeTest.cs
| 2.921875
| 3
|
using Employees.Core.Dto;
using Employees.Core.Enum;
using Employees.Core.Intefaces;
using Employees.Infrastructure.Services;
using Xunit;
namespace Employee.Test
{
public class EmployeeTest
{
IEmployeeFactory EmployeeFactory;
public EmployeeTest()
{
EmployeeFactory = new EmployeeFactory();
}
[Fact]
public void ShouldCalculateAnnualSalaryForHourlyContract()
{
var employeeDto = new EmployeeDto { contractTypeName = ContractType.Hourly, hourlySalary = 300 };
var employeeAnaualSalary = 120 * employeeDto.hourlySalary * 12;
//act
var employee = EmployeeFactory.GetEmployee(employeeDto);
//assert
Assert.Equal(employeeAnaualSalary, employee.AnnualSalary);
}
[Fact]
public void ShouldCalculateAnnualSalaryForMonthlyContract()
{
var employeeDto = new EmployeeDto { contractTypeName = ContractType.Monthly, monthlySalary = 20000 };
var employeeAnaualSalary = employeeDto.monthlySalary * 12;
//act
var employee = EmployeeFactory.GetEmployee(employeeDto);
//assert
Assert.Equal(employeeAnaualSalary, employee.AnnualSalary);
}
}
}
|
49ca71b459942d98dd51be2a5fcb109ca5d4d864
|
C#
|
shendongnian/download4
|
/first_version_download2/423055-37166825-117837683-2.cs
| 3.046875
| 3
|
public static void ParseMsg(string msg)
{
string[] words = Regex.Split(msg, @"\s+");
foreach (string word in words)
{
switch (word)
{
case "tween":
// Do something
break;
case "stop":
// Do something
break;
}
}
}
|
2e5ea8ab513003876e3f4481154274d46b6f6e75
|
C#
|
bubdm/NatashaPad
|
/src/NatashaPad.Mvvm/DefaultViewContainer.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace NatashaPad.Mvvm
{
internal class DefaultViewContainer : IViewTypeInfoLocator
{
private readonly Dictionary<Type, Type> vmToviewMap;
private readonly Dictionary<Type, ViewInfo> viewToInfoMap;
public DefaultViewContainer()
{
vmToviewMap = new Dictionary<Type, Type>();
viewToInfoMap = new Dictionary<Type, ViewInfo>();
}
internal DefaultViewContainer(IEnumerable<RegisterInfo> infos)
{
vmToviewMap = infos.ToDictionary(x => x.ViewModelType, x => x.ViewType);
viewToInfoMap = infos.ToDictionary(x => x.ViewType, x => x.ViewInfo);
}
public Type GetView(Type vmType)
{
if (!vmToviewMap.TryGetValue(vmType, out var type))
{
throw new KeyNotFoundException(
string.Format(Properties.Resource.CannotFindMatchedViewTypeOfFormatString,
vmType.Name));
}
return type;
}
public ViewInfo GetViewInfo(Type viewType)
{
if (!viewToInfoMap.TryGetValue(viewType, out var info))
{
throw new KeyNotFoundException(
string.Format(Properties.Resource.CannotFindMatchedViewInfoOfFormatString,
viewType.Name));
}
return info;
}
}
internal class DefaultViewLocator : IViewInstanceLocator
{
private readonly IViewTypeInfoLocator viewLocator;
private readonly IServiceProvider serviceProvider;
public DefaultViewLocator(
IViewTypeInfoLocator viewLocator,
IServiceProvider serviceProvider)
{
this.viewLocator = viewLocator;
this.serviceProvider = serviceProvider;
}
public object GetView(Type viewModelType)
{
return serviceProvider.GetService(viewLocator.GetView(viewModelType));
}
}
}
|
96a5dba403a532238d0acc76ad956b3d4392f273
|
C#
|
serge-sedelnikov/xstate.net
|
/XStateNet.Tests/StateServicesDelayedTransitionTests.cs
| 2.671875
| 3
|
using System;
using Xunit;
using XStateNet;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
namespace NetState.Tests
{
public class StateServicesDelayedTransitionTests
{
[Fact]
public async Task DelayedTransitionRunSuccessfully()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
bool state2Triggered = false;
var state1 = new State("My test");
state1.WithTimeout(TimeSpan.FromSeconds(5), "My test 2");
var state2 = new State("My test 2")
.WithActionOnEnter(() =>
{
stopwatch.Stop();
state2Triggered = true;
});
var stateMachine = new StateMachine("test", "test", "My test");
stateMachine.States = new State[]{
state1, state2
};
var interpreter = new Interpreter(stateMachine);
interpreter.StartStateMachine();
// wait for 6 sec to be sure
await Task.Delay(TimeSpan.FromSeconds(6));
Assert.True(state2Triggered);
Assert.False(stopwatch.IsRunning);
// check that stopwatch timer shows about 5 sec
Assert.InRange(stopwatch.ElapsedMilliseconds,
TimeSpan.FromSeconds(4.9).TotalMilliseconds,
TimeSpan.FromSeconds(5.1).TotalMilliseconds);
}
[Fact]
public async Task DelayedTransitionRunSuccessfullyWithMiliseconds()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
bool state2Triggered = false;
var state1 = new State("My test");
state1.WithTimeout(5000, "My test 2");
var state2 = new State("My test 2")
.WithActionOnEnter(() =>
{
stopwatch.Stop();
state2Triggered = true;
});
var stateMachine = new StateMachine("test", "test", "My test");
stateMachine.States = new State[]{
state1, state2
};
var interpreter = new Interpreter(stateMachine);
interpreter.StartStateMachine();
// wait for 6 sec to be sure
await Task.Delay(TimeSpan.FromSeconds(6));
Assert.True(state2Triggered);
Assert.False(stopwatch.IsRunning);
// check that stopwatch timer shows about 5 sec
Assert.InRange(stopwatch.ElapsedMilliseconds,
TimeSpan.FromSeconds(4.9).TotalMilliseconds,
TimeSpan.FromSeconds(5.1).TotalMilliseconds);
}
[Fact]
public async Task DelayedTransitionDidNotRun()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
bool state2Triggered = false;
var state1 = new State("My test");
state1.WithTimeout(TimeSpan.FromSeconds(5), "My test 2");
var state2 = new State("My test 2")
.WithActionOnEnter(() =>
{
stopwatch.Stop();
state2Triggered = true;
});
var stateMachine = new StateMachine("test", "test", "My test");
stateMachine.States = new State[]{
state1, state2
};
var interpreter = new Interpreter(stateMachine);
interpreter.StartStateMachine();
// wait for 4 sec
await Task.Delay(TimeSpan.FromSeconds(4));
Assert.False(state2Triggered);
Assert.True(stopwatch.IsRunning);
}
[Fact]
public async Task DelayedTransitionServicesCanceledAfterDelay()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
bool state1ServiceRunning = false;
int state1ServiceCount = 0;
bool state2Triggered = false;
var state1 = new State("My test");
state1.WithTimeout(2000, "My test 2")
.WithInvoke(async (callback) =>
{
// start counting service
state1ServiceRunning = true;
while (state1ServiceRunning)
{
Interlocked.Increment(ref state1ServiceCount);
// count every half a sec to get 10 times to check
await Task.Delay(500);
}
}, () => { })
.WithActionOnExit(() =>
{
// stop the loop
state1ServiceRunning = false;
});
var state2 = new State("My test 2")
.WithActionOnEnter(() =>
{
stopwatch.Stop();
state2Triggered = true;
});
var stateMachine = new StateMachine("test", "test", "My test");
stateMachine.States = new State[]{
state1, state2
};
var interpreter = new Interpreter(stateMachine);
interpreter.StartStateMachine(); // no need to await here as it may take some time
// wait for 6 sec
await Task.Delay(TimeSpan.FromSeconds(6));
Assert.True(state2Triggered);
Assert.False(stopwatch.IsRunning);
// check that parallel service was stopped
Assert.False(state1ServiceRunning);
// how many times loop was running before stopped
Console.WriteLine(state1ServiceCount);
Assert.True(state1ServiceCount >= 4);
// check that stopwatch timer shows about 5 sec
Assert.InRange(stopwatch.ElapsedMilliseconds,
TimeSpan.FromSeconds(1.9).TotalMilliseconds,
TimeSpan.FromSeconds(2.1).TotalMilliseconds);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task DelayedTransitionRunAfterNotmalStateChange(bool timeout)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
bool timeoutStateTriggered = false;
bool successStateTriggered = false;
var state1 = new State("My test");
state1
// wait for timeout or success if success is provided
.WithTimeout(TimeSpan.FromSeconds(5), "timedout")
.WithTransition("SUCCESS_NO_TIMEOUT", "success")
.WithInvoke(async (callback) =>
{
await Task.Delay(2000);
if (!timeout)
{
await callback("SUCCESS_NO_TIMEOUT");
}
});
// timeout state
var timeoutState = new State("timedout")
.WithActionOnEnter(() =>
{
stopwatch.Stop();
timeoutStateTriggered = true;
successStateTriggered = false;
});
// not a timeout state
var successState = new State("success")
.WithActionOnEnter(() =>
{
stopwatch.Stop();
timeoutStateTriggered = false;
successStateTriggered = true;
});
var stateMachine = new StateMachine("test", "test", "My test");
stateMachine.States = new State[]{
state1, timeoutState, successState
};
var interpreter = new Interpreter(stateMachine);
interpreter.StartStateMachine();
// wait for 6 sec to be sure
await Task.Delay(TimeSpan.FromSeconds(6));
Assert.Equal(timeout, timeoutStateTriggered);
Assert.NotEqual(timeout, successStateTriggered);
if (timeout)
{
Assert.InRange(stopwatch.ElapsedMilliseconds,
TimeSpan.FromSeconds(4.9).TotalMilliseconds,
TimeSpan.FromSeconds(5.1).TotalMilliseconds);
}
else
{
Assert.InRange(stopwatch.ElapsedMilliseconds,
TimeSpan.FromSeconds(1.9).TotalMilliseconds,
TimeSpan.FromSeconds(2.1).TotalMilliseconds);
}
Assert.False(stopwatch.IsRunning);
}
[Fact]
public async Task TransientState_Run()
{
bool state1Entered = false;
bool state1Exited = false;
bool state2Entered = false;
bool state2Exited = false;
State state1 = new State("state1")
.AsTransientState("state2")
.WithActionOnEnter(() => {
state1Entered = true;
})
.WithActionOnExit(() => {
state1Exited = true;
});
State state2 = new State("state2")
.AsFinalState()
.WithActionOnEnter(() => {
state2Entered = true;
})
.WithActionOnExit(() => {
state2Exited = true;
});
var machine = new StateMachine("machine1", "machine1", "state1",
state1, state2);
var interpreter = new Interpreter(machine);
await interpreter.StartStateMachineAsync();
Assert.True(state1Entered);
Assert.True(state1Exited);
Assert.True(state2Entered);
Assert.True(state2Exited);
}
}
}
|
5df2189c90e37e96f94e037125ab10dd54b2447d
|
C#
|
Liuyonggang0731/XFramework
|
/XFramework/Assets/XFramework/Core/Runtime/Base/FSM/Fsm.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
namespace XFramework.Fsm
{
/// <summary>
/// 状态机
/// </summary>
/// <typeparam name="TState">子类状态机对应的状态基类</typeparam>
public class Fsm<TState> : IFsm where TState : FsmState
{
private bool m_IsActive;
private TState m_CurrentState;
/// <summary>
/// 存储该状态机包含的所有状态
/// </summary>
protected Dictionary<string, TState> m_StateDic;
/// <summary>
/// 是否处于激活状态
/// </summary>
public bool IsActive { get { return m_IsActive; } }
/// <summary>
/// 当前状态
/// </summary>
public TState CurrentState { get { return m_CurrentState; } }
public Fsm()
{
m_StateDic = new Dictionary<string, TState>();
m_IsActive = false;
}
/// <summary>
/// 每帧运行
/// </summary>
public virtual void OnUpdate()
{
if (CurrentState != null)
{
CurrentState.OnUpdate();
}
}
/// <summary>
/// 获取一个状态
/// </summary>
/// <typeparam name="T">状态类型</typeparam>
/// <returns>状态</returns>
protected FsmState GetState<T>()
{
return GetState(typeof(T));
}
/// <summary>
/// 获取一个状态
/// </summary>
/// <typeparam name="T">状态类型</typeparam>
/// <returns>状态</returns>
protected TState GetState(Type type)
{
m_StateDic.TryGetValue(type.Name, out TState state);
if (state == null)
{
state = CreateState(type) as TState;
m_StateDic.Add(type.Name, state);
}
return state;
}
/// <summary>
/// 创建一个状态
/// </summary>
/// <typeparam name="T">状态类型</typeparam>
/// <returns>状态</returns>
protected FsmState CreateState<T>()
{
return CreateState(typeof(T));
}
/// <summary>
/// 创建一个状态
/// </summary>
/// <param name="type">状态类型</param>
protected FsmState CreateState(Type type)
{
FsmState state = Utility.Reflection.CreateInstance<TState>(type);
if (!(state is TState))
throw new System.Exception("状态类型设置错误");
state.Init();
return state;
}
/// <summary>
/// 获取当前状态
/// </summary>
/// <returns></returns>
public FsmState GetCurrentState()
{
return m_CurrentState;
}
/// <summary>
/// 获取当前状态
/// </summary>
public T GetCurrentState<T>() where T : TState
{
return m_CurrentState as T;
}
/// <summary>
/// 开启状态机
/// </summary>
/// <param name="type">状态类型</param>
/// <param name="parms">启动参数</param>
private void StartFsm(Type type, params object[] parms)
{
if (!IsActive)
{
m_CurrentState = GetState(type);
OnStateChange(null, m_CurrentState);
m_CurrentState.OnEnter(parms);
m_IsActive = true;
}
}
/// <summary>
/// 状态切换
/// </summary>
/// <typeparam name="KState">状态类型</typeparam>
/// <param name="parms">启动参数</param>
public void ChangeState<KState>(params object[] parms) where KState : FsmState
{
ChangeState(typeof(KState), parms);
}
/// <summary>
/// 状态切换
/// </summary>
/// <param name="type">状态类型</param>
/// <param name="parms">启动参数</param>
public void ChangeState(Type type, params object[] parms)
{
if (IsActive)
{
TState newState = GetState(type);
if (m_CurrentState != newState)
{
m_CurrentState?.OnExit();
OnStateChange(m_CurrentState, newState);
m_CurrentState = newState;
m_CurrentState.OnEnter(parms);
}
}
else
{
StartFsm(type, parms);
}
}
protected virtual void OnStateChange(TState oldStart, TState newState) { }
public void OnDestroy()
{
m_CurrentState = null;
m_StateDic.Clear();
}
}
}
|
0cdf2e21e6deabc66ea3076ba262aac894e72f61
|
C#
|
rsalit/CSBC
|
/Lojack/Lojack/Lojack.Core/Models/Mapping/MatchedLojackHitUpdateMap.cs
| 2.53125
| 3
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace Lojack.Models.Mapping
{
public class MatchedLojackHitUpdateMap : EntityTypeConfiguration<MatchedLojackHitUpdate>
{
public MatchedLojackHitUpdateMap()
{
// Primary Key
this.HasKey(t => t.UpdateGUID);
// Properties
this.Property(t => t.UpdateDescription)
.IsRequired();
// Table & Column Mappings
this.ToTable("MatchedLojackHitUpdate");
this.Property(t => t.UpdateGUID).HasColumnName("UpdateGUID");
this.Property(t => t.UpdateDescription).HasColumnName("UpdateDescription");
this.Property(t => t.UpdateTypeID).HasColumnName("UpdateTypeID");
this.Property(t => t.CreationDate).HasColumnName("CreationDate");
this.Property(t => t.IsDeleted).HasColumnName("IsDeleted");
this.Property(t => t.UserGUID).HasColumnName("UserGUID");
this.Property(t => t.HitGUID).HasColumnName("HitGUID");
}
}
}
|
89766baad823c95d080ec0bd580aa5b80979ee5b
|
C#
|
SWDHouseProject/HouseChoseImprovement
|
/HouseSupportSystem/HouseSupportSystem/MainWindow.xaml.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace HouseSupportSystem
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var init = new AHP();
init.Initialize(3, 7, 5);
var score = init.startCounting();
this.score.Text = ConvertArrayToString(score);
init.CalculateConsistency();
/*
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Header = "1";
textColumn.Binding = new Binding("1");
dataGrid.Columns.Add(textColumn);
this.dataGrid.Items.Add(new TextBox().Text = "");
*/
generate_columns();
}
string ConvertArrayToString(double[] s)
{
string output = "";
foreach (var s1 in s)
{
output += s1.ToString() + " ";
}
return output;
}
public class Item
{
public int Num { get; set; }
public string Start { get; set; }
public string Finich { get; set; }
}
private void generate_columns()
{
DataGridTextColumn c1 = new DataGridTextColumn();
c1.Header = "Num";
c1.Binding = new Binding("Num");
c1.Width = 110;
this.dataGrid.Columns.Add(c1);
DataGridTextColumn c2 = new DataGridTextColumn();
c2.Header = "Start";
c2.Width = 110;
c2.Binding = new Binding("Start");
this.dataGrid.Columns.Add(c2);
DataGridTextColumn c3 = new DataGridTextColumn();
c3.Header = "Finich";
c3.Width = 110;
c3.Binding = new Binding("Finich");
this.dataGrid.Columns.Add(c3);
this.dataGrid.Items.Add(new Item() { Num = 1, Start = "2012, 8, 15", Finich = "2012, 9, 15" });
this.dataGrid.Items.Add(new Item() { Num = 2, Start = "2012, 12, 15", Finich = "2013, 2, 1" });
this.dataGrid.Items.Add(new Item() { Num = 3, Start = "2012, 8, 1", Finich = "2012, 11, 15" });
}
}
}
|
a8cf06980e016168b635ccb2e9037364fc1b2f4b
|
C#
|
herara-ofnir3/ProjectEuler
|
/ProjectEuler/ProjectEuler.Run/Problems.Part3/Problem56.cs
| 3.46875
| 3
|
using ProjectEuler.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace ProjectEuler.Run.Problems.Part3
{
/// <summary>
/// Problem 56 「もっとべき乗の数字和」
/// Googol (10^100)は非常に大きな数である: 1の後に0が100個続く. 100^100は想像を絶する. 1の後に0が200回続く. その大きさにも関わらず, 両者とも数字和 ( 桁の和 ) は1である.
///
/// a, b < 100 について自然数 a^b を考える. 数字和の最大値を答えよ.
/// </summary>
public class Problem56 : Problem
{
public override string Run()
{
// BigInteger強すぎ問題
var range = Enumerable.Range(1, 100 - 1);
var patterns = new List<BigInteger>();
foreach (var a in range)
foreach (var b in range)
patterns.Add(Pow(a, b));
var answer = patterns.Max(p => p.Digits().Sum());
return answer.ToString();
}
static BigInteger Pow(int b, int e)
{
return Enumerable.Range(1, e)
.Select(_ => (BigInteger)b)
.Aggregate((l, r) => l * r);
}
}
}
|
44c4a6974aed659564876cf1d19c1c89a5fcf2ad
|
C#
|
shendongnian/download4
|
/code11/1975656-60280144-215240293-2.cs
| 3.46875
| 3
|
public static int GetWeeksInYear(int year) {
if (year < DateTime.MinValue.Year || year > DateTime.MaxValue.Year)
throw new ArgumentOutOfRangeException(nameof(year));
var dw = new DateTime(year, 1, 1).DayOfWeek;
return (dw == DayOfWeek.Thursday) ||
(dw == DayOfWeek.Wednesday) && DateTime.IsLeapYear(year)
? 53
: 52;
}
|
88e2cd5edf8b95d77f7ba59fe6e5b60cec62b9cd
|
C#
|
suetarazi/DataStructuresAndAlgorithms
|
/PairWithTargetSum/PairWithTargetSum/Program.cs
| 4.09375
| 4
|
using System;
using System.Collections.Generic;
namespace PairWithTargetSum
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
/// <summary>
/// Standard two pointer approach
/// </summary>
/// <param name="arr">input array</param>
/// <param name="targetSum">target sum</param>
/// <returns>array of indices</returns>
public int[] search(int[] arr, int targetSum)
{
int leftPointer = 0;
int rightPointer = arr.Length -1;
while(leftPointer < rightPointer)
{
int currentSum = arr[leftPointer] + arr[rightPointer];
if(currentSum == targetSum)
{
return new int[] { leftPointer, rightPointer }; //search no further, we found our pair!
}
if (targetSum > currentSum)
{
leftPointer++; //sum is too small, we need to increment the left pointer
}
else
rightPointer--; //sum is too big, we need to decrement the right pointer
}
return new int[] { -1, -1 };
}
/// <summary>
/// This approach uses a Hashtable (or Dictionary):
/// Algorithm:
/// 1. iterate through the array one number at a time. Lets say each number is X.
/// 2. Mathematically, X + Y = Target, so we need to find Y. Mathematically, Y = Target - X. So, we search the hashtable for Target - X.
/// 3. If Target - X exists in the hashtable, then we have found our pair. Otherwise, put X into the hashtable and move to the next value X in the array.
/// </summary>
/// <param name="arr">input array</param>
/// <param name="targetSum">target sum</param>
/// <returns>array of indices</returns>
public int[] useHashtableToSearch(int[] arr, int targetSum)
{
Dictionary<int, int> table = new Dictionary<int, int>(); //make a table to store numbers in the array and their respective indices
for(int i=0; i < arr.Length; i++)
{
if (table.ContainsKey(targetSum - arr[i]))
{
return new int[] { table[targetSum - arr[i]], i }; //Bingo! We found Y = Target - X!
}
else
table.Add(arr[i], i); //put number and its index in the array
}
return new int[] { -1, -1 }; //pair not found
}
}
}
|
3d4c761ddf8ad50b8ecf889514ba0b45cb13ae7c
|
C#
|
kadiraciktan/YoreselSozluk
|
/YoreselSozluk.DataAccess/Operations/CityOperations/Commands/DeleteCity/DeleteCityCommand.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YoreselSozluk.DataAccess.Abstract;
namespace YoreselSozluk.DataAccess.Operations.CityOperations.Commands.DeleteCity
{
public class DeleteCityCommand
{
private readonly IContext _context;
public int CityId { get; set; }
public DeleteCityCommand(IContext context)
{
_context = context;
}
public void Handle()
{
var city = _context.Cities.FirstOrDefault(x => x.Id == CityId);
if (city is null)
{
throw new InvalidOperationException("Şehir Bulunamadı");
}
var heading = _context.Headings.FirstOrDefault(x=>x.CityId == CityId);
if (heading is not null)
{
throw new InvalidOperationException("Başlık Oluşturulan Bir Şehir Silinemez");
}
_context.Cities.Remove(city);
_context.SaveChanges();
}
}
}
|
6fc76247134483f38bdd074c18a6bbc959641fe2
|
C#
|
mike3293/OOTP_2s
|
/Паттерны/Lab_3/Lab_3/Memento.cs
| 3.609375
| 4
|
namespace Lab_3
{
public class PersonState
{
public string name { get; }
public int age { get; }
public PersonState(string Name, int Age)
{
name = Name;
age = Age;
}
}
public class Person
{
public string _name = "Jokar";
public int _age = 5;
public PersonState GetState()
{
PersonState person = new PersonState(_name, _age);
return person;
}
public void SetState(PersonState state)
{
_name = state.name;
_age = state.age;
}
}
}
|
407d05556037b84dbd3065123ebc0721d5be3f95
|
C#
|
aukgit/Object-Oriented-Programming-with-C-Sharp
|
/PreviousVideo Coding/OOP1/OOP1/PassingClassParameter/PassingClassParam.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OOP1.Polymorphism;
/*
* Written by Alim Ul Karim
* mailto: alim@developers-organism.com
* developers-organism.com
* find us on fb.com/developersOrganism
* */
namespace OOP1.PassingClassParameter {
class PassingClassParam {
public void test1(string name) {
name = "Hello Changed!";
}
public void ChangePerson(Person person) {
person.FirstName = "First Name Changed!";
person.LastName = "Last Name Changed!";
}
}
}
|
a4e7ede52cf7546c0b8c2201ba455143f073047a
|
C#
|
KAL-ATM-Software/KAL_XFS4IoT_SP-Dev
|
/Framework/ServiceClasses/CommonServiceProvider/VendorApplicationCapabilities.cs
| 2.59375
| 3
|
/***********************************************************************************************\
* (C) KAL ATM Software GmbH, 2022
* KAL ATM Software GmbH licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
*
\***********************************************************************************************/
using System;
namespace XFS4IoTFramework.Common
{
/// <summary>
/// VendorApplicationCapabilities
/// Store device capabilites for the vendor mode application interface for VDM
/// </summary>
public sealed class VendorApplicationCapabilitiesClass
{
[Flags]
public enum SupportedAccessLevelEnum
{
NotSupported = 0,
Basic = 1 << 0,
Intermediate = 1 << 1,
Full = 1 << 2,
}
public VendorApplicationCapabilitiesClass(SupportedAccessLevelEnum SupportedAccessLevels)
{
this.SupportedAccessLevels = SupportedAccessLevels;
}
/// <summary>
/// Specifies the supported access levels. This allows the application to show a user interface with
/// reduced or extended functionality depending on the access levels.The exact meaning or functionalities
/// definition is left to the vendor.If no access levels are supported this property will be omitted.
/// Otherwise this will report the supported access levels respectively.
/// </summary>
public SupportedAccessLevelEnum SupportedAccessLevels { get; init; }
}
}
|
f96180dae42adb7cd24702ee4afaa43d9a64625c
|
C#
|
klinki/bookmarks-manager.net
|
/Engine/Serializers/Json/JsonSerializer.cs
| 2.703125
| 3
|
using Engine.Serializers.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Engine.Serializers
{
public class JsonSerializer
{
public string Serialize(BookmarkNode node)
{
return this.Serialize(new BookmarkNode[] { node });
}
public string Serialize(IEnumerable<BookmarkNode> nodes)
{
var anonymous = new
{
Type = "Data",
Version = "0.1",
Data = new List<BookmarkNode>(nodes)
};
return JsonConvert.SerializeObject(anonymous, Formatting.Indented, new JsonSerializerSettings() {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Converters = new JsonConverter[] { new BookmarkNodeJsonConverter(), new StringEnumConverter() }
});
}
}
}
|
36a99367d8b4a2ac7f11ec473ff0145cad318ae1
|
C#
|
HTomasH/GestorColecciones
|
/GestorColecciones/frmEdicion.cs
| 2.65625
| 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 GestorColecciones
{
public partial class frmEdicion : Form
{
//---------- Indicar el Adapter y el DataSet
ColeccionesDSTableAdapters.LIBROSTableAdapter taLibros; //TableAdapter
ColeccionesDS ds=new ColeccionesDS(); //TRAMPA 1 : Instanciar el DataSet
//->Constructor del formulario
// donde vamos a pasar un libro inicial,
public frmEdicion( int idLibro )
{
//->Inicializamos el TableAdapter
taLibros = new ColeccionesDSTableAdapters.LIBROSTableAdapter();
//taLibros.GetData(); //El GetData pilla todos los registros,
// pero en nuestro caso solo queremos uno así que creamos un nuevo
// filtrado
//-->Para crear un nuevo filtrado sobre la tabla, el profre hace lo siguiente :
//-----------------------------------------------------------------------------
//Primero : No vamos a la derecha, al DataSet (gráfico)
//Segundo : En la tabla libros vamos a añadir una segunda consulta
//Tecerro : En este caso será * USAR INSTRUCCIONES SQL y del tipo SELECT
//Cuarto : En la select le añadimos un where IdLibro = @IdLibro para que solo pille uno
//Quinto : Dejamos los nombres por defecto
//----------------------------------------------------------//
//Sexto(1): Utilizamos la consulta llamada GetDataBy recien creada :
//taLibros.GetDataBy(idLibro);
//Sexto(2) : Vamos a guardar ese registro en el DataSet oJo FillBy es la segunda consulta
taLibros.FillBy(ds.LIBROS, idLibro);
//Séptimo : Vamos a rellenar el restos de campos del formulario.
InitializeComponent(); // TRAMPA 2 : Hay que inicializar los controles del formulario
// antes de operar con ellos.
this.tbxTitulo.Text = ds.LIBROS[0].Titulo; //¿porque hay que indicar [0] ?
this.tbxDescricion.Text = ds.LIBROS[0].Descripcion;
this.dtpCompra.Value = ds.LIBROS[0].FechaCompra;
//-->Y ahora para el DataTimePicket que lleva el checked debemos de comprobar primero que la fecha no sea NULL
// de lo contrario nos podria dar un estacazo
if (ds.LIBROS[0].IsFechaLecturaNull())
{
dtpLectura.Checked = false;
}
else
{
dtpLectura.Checked = true;
this.dtpLectura.Value = ds.LIBROS[0].FechaLectura;
}
//-->Tratamiento de la imagen para mostrar las portadas
//-------------------------------------------------------------------------------------------
/*
Vamos a pintar la imagen que tendremos guardada en la tabla de Libros,
en el campo lo que tenemos es un STREAM es decir una cadena que puede
leer de un origen como es una matriz en memoria, de un fichero en disco, etc..
En nuestro caso se trata de una matriz de bytes la cual debemos de convertirla a una imagen
Antes de pintar vamos a preguntar si es NULL que sino pega el estacazo
*/
if (! ds.LIBROS[0].IsPortadaNull())
{
var stream = new System.IO.MemoryStream(ds.LIBROS[0].Portada);
pbxPortada.Image = System.Drawing.Bitmap.FromStream(stream);
}
}
//---->Este metodo lo habra pintado sin darme cuenta yo...relamente no es necesario ya estoy haciendo yo
// la carga arriba
private void frmEdicion_Load_1(object sender, EventArgs e)
{
// TODO: esta línea de código carga datos en la tabla 'coleccionesDS.LIBROS' Puede moverla o quitarla según sea necesario.
// this.lIBROSTableAdapter.Fill(this.coleccionesDS.LIBROS);
}
//->Metodo que captura el evento de cierre del formulario para hacer las grabaciones
private void frmEdicion_FormClosing(object sender, FormClosingEventArgs e)
{
//-->Movemos la información de los objetos del formulario al DataSet
ds.LIBROS[0].Titulo = tbxTitulo.Text;
ds.LIBROS[0].Descripcion = tbxDescricion.Text;
ds.LIBROS[0].FechaCompra = dtpCompra.Value ;
//-->Para el campo Fecha Lectura, vamos a preguntar por el valor del check
// si estuviera marcado grabaremos la fecha de lo contrario la dejaremos con
// NULL que indicará que el libro no ha sido leido.
if ( dtpLectura.Checked)
{
ds.LIBROS[0].FechaLectura = dtpLectura.Value; //En el video está indicando la fecha de Compra!!!!!
}
else
{
// puta mierda no se queda siempre con el check marcado
ds.LIBROS[0].SetFechaLecturaNull();
}
//->Aqui vamos tratar la imagen
//-----------------------------------------------------------------
// Tenemos que volver a utilizar un STREAM
var fs = new System.IO.MemoryStream(); // OJO OJO el profe ha hecho aquí un truco para agregar la
// referencia a systemIO.
// Al escribir el MemoryStream sale una rallita debajo de la M
// Yo utilizo las sugerencias y lo pongo de esta forma
//->Hay que controlar que la imagen no sea NULL de lo contrario peta,
if (pbxPortada.Image == null)
{
MessageBox.Show("No hay imagen, no se guardara el dato" );
}
else
{
pbxPortada.Image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg); //Aqui guardamos en memoria
//el fichero seleccionado del formato jpeg
//que es el que permitimos cargar
ds.LIBROS[0].Portada = fs.ToArray(); //STREAM es una cadena de bytes
}
//->Utilizamos el método Update de nuestro adaptador
taLibros.Update(ds.LIBROS);
}
//-->Metodo para capturar las imagenes, con el doble click sobre el mismo control del formulario
private void pbxPortada_DoubleClick(object sender, EventArgs e)
{
//->Utilizaremos la búsqueda de ficheros standard ya existente
var dialogo = new OpenFileDialog(); //Porque OpenFileDialog abre por defecto la carpeta de Documentos y no otra??
//Podemos indicar la extensión, por un nombre concreto de archivo
dialogo.Filter = "Imagenes(jpg)|*.jpg"; //El palote es el de la tecla del 1
if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{ //->Si el dialogo es OK un jpg tal como hemos filtrado lo cargamos en el control
pbxPortada.Image = System.Drawing.Bitmap.FromFile(dialogo.FileName);
}
}
}
}
|
b95b5e5ce86478e305966c0da861997104fdd010
|
C#
|
vhuzii/Airport-ASP.NET-Core-Web-Api
|
/Presentation Layer/Controllers/CrewsController.cs
| 2.5625
| 3
|
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using AutoMapper;
using Business_Layer.Services;
using Data_Access_Layer.Interfaces;
using Data_Access_Layer.Models;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using Shared.DTos;
using Business_Layer.DTOValidation;
using System.Threading.Tasks;
namespace Presentation_Layer.Controllers
{
[Produces("application/json")]
[Route("api/Crews")]
public class CrewsController : Controller
{
private readonly AirportService _service;
private readonly IMapper _mapper;
CrewDTOValidator validator = new CrewDTOValidator();
public CrewsController(IMapper mapper, AirportService service)
{
_service = service;
_mapper = mapper;
}
// GET api/crews
[HttpGet]
public async Task<IEnumerable<CrewDTO>> Get()
{
return _mapper.Map<IEnumerable<Crew>, IEnumerable<CrewDTO>>(await _service.GetAll<Crew>());
}
// GET api/crews/id
[HttpGet("{id}")]
public async Task<CrewDTO> Get(int id)
{
return _mapper.Map<Crew, CrewDTO>(await _service.GetById<Crew>(id));
}
// POST api/crews
[HttpPost]
public async Task<HttpResponseMessage> Post([FromBody]CrewDTO crew)
{
foreach(var st in crew.Stewardesses)
{
st.CrewId = crew.Id;
}
if(ModelState.IsValid && crew != null && validator.Validate(crew).IsValid)
{
await _service.Post<Crew>(_mapper.Map<CrewDTO, Crew>(crew));
await _service.SaveChanges();
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
// POST api/crews/id
[HttpPut("{id}")]
public async Task<HttpResponseMessage> Put(int id, [FromBody]CrewDTO crew)
{
if (ModelState.IsValid && crew != null && validator.Validate(crew).IsValid)
{
await _service.Update<Crew>(id, _mapper.Map<CrewDTO, Crew>(crew));
await _service.SaveChanges();
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
// DELETE api/crews/id
[HttpDelete("{id}")]
public async Task Delete(int id)
{
await _service.Delete<Crew>(id);
await _service.SaveChanges();
}
}
}
|
922b98ea26f9fb2024547e2c82d40bd8f6b2e354
|
C#
|
Rox-Lvmaohua/TIRPClo
|
/TIRPClo/TIRPClo/BETiep.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TIRPClo
{
//This class represents a backward extension tiep from some i-th before/co period of time
public class BETiep
{
//Records and instances for each
public Dictionary<int, List<STI>> indexes;
public BETiep()
{
indexes = new Dictionary<int, List<STI>>();
}
//Add an instace of the tiep in some record
public void addOcc(int rec, STI sti)
{
if (!indexes.ContainsKey(rec))
{
indexes.Add(rec, new List<STI>());
}
indexes[rec].Add(sti);
}
}
}
|
c0b6a163b5d17e432363312f64e4aa1e6769c73a
|
C#
|
PacktPublishing/Mastering-Windows-Presentation-Foundation
|
/CompanyName.ApplicationName.DataModels/ThinProduct.cs
| 3.40625
| 3
|
using System;
namespace CompanyName.ApplicationName.DataModels
{
/// <summary>
/// Represents the basic details of a product in the application for use in large collections.
/// </summary>
public class ThinProduct : BaseDataModel
{
private Guid id = Guid.Empty;
private string name = string.Empty;
/// <summary>
/// Initialises a new ThinProduct object with the values provided by the input parameter.
/// </summary>
public ThinProduct(AuditableProduct product)
{
Id = product.Id;
Name = product.Name;
}
/// <summary>
/// Initialises a new empty ThinProduct object.
/// </summary>
public ThinProduct() { }
/// <summary>
/// Gets or sets the unique identification number of the ThinProduct object.
/// </summary>
public Guid Id
{
get { return id; }
set { if (id != value) { id = value; NotifyPropertyChanged(); } }
}
/// <summary>
/// Gets or sets the name of the ThinProduct object.
/// </summary>
public string Name
{
get { return name; }
set { if (name != value) { name = value; NotifyPropertyChanged(); } }
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return Name;
}
}
}
|
571248b83a5bfc2b572afa8abc9aeca1af0a1adf
|
C#
|
Sergio0694/ComputeSharp
|
/samples/ComputeSharp.SwapChain.Core.Shared/Converters/RenderingPauseConverter.cs
| 2.59375
| 3
|
#if WINDOWS_UWP
using Windows.UI.Xaml.Controls;
#else
using Microsoft.UI.Xaml.Controls;
#endif
namespace ComputeSharp.SwapChain.Core.Converters;
/// <summary>
/// A class with some static converters for rendering state.
/// </summary>
public static class RenderingPauseConverter
{
/// <summary>
/// Gets a symbol for an input rendering state.
/// </summary>
/// <param name="value">Whether or not the rendering is currently paused.</param>
/// <returns>A symbol representing the next action for the rendering.</returns>
public static Symbol ConvertPausedToSymbol(bool value)
{
return value ? Symbol.Play : Symbol.Pause;
}
}
|
b78e9a7884bd0c9d6cbf483a65b242b851320781
|
C#
|
sogoojo/JsonParser
|
/source/Liquid.Json/TypeSerializers/JsonArraySerializer.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Liquid.Json.TypeSerializers
{
internal class JsonArraySerializer<T> : IJsonTypeSerializer<T[]>
{
#region IJsonTypeSerializer<T[]> Members
public void Serialize(T[] @object, JsonSerializationContext context)
{
context.Writer.WriteStartArray();
foreach (T item in @object) {
context.Serialize(item);
}
context.Writer.WriteEnd();
}
public T[] Deserialize(JsonDeserializationContext context)
{
var resultList = new List<T>();
context.Reader.ReadNextAs(JsonTokenType.ArrayStart);
while (true) {
context.Reader.ReadNext();
if (context.Reader.Token ==
JsonTokenType.ArrayEnd)
break;
context.Reader.UndoRead();
resultList.Add(context.Deserialize<T>());
if (!context.Reader.ReadNext())
throw context.Reader.UnexpectedTokenException(JsonTokenType.Comma, JsonTokenType.ArrayEnd);
else if (context.Reader.Token ==
JsonTokenType.ArrayEnd)
break;
else if (context.Reader.Token ==
JsonTokenType.Comma)
continue;
else
throw context.Reader.UnexpectedTokenException(JsonTokenType.Comma, JsonTokenType.ArrayEnd);
}
Debug.Assert(context.Reader.Token == JsonTokenType.ArrayEnd);
return resultList.ToArray();
}
#endregion
}
}
|
15b521f5ed74fdbe33f4a6e27149df8ca3368df1
|
C#
|
not-mike-smith/DimensionsOfMeasurement
|
/DimensionsOfMeasurement.Test/FundamentalDimensionTests.cs
| 2.890625
| 3
|
using System.Linq;
using FluentAssertions;
using Xunit;
namespace DimensionsOfMeasurement.Test
{
public class FundamentalDimensionTests
{
[Fact]
public void HashCodesAreUnique()
{
var x = FundamentalDimension.All.Select(f => f.GetHashCode()).ToHashSet();
x.Count.Should().Be(FundamentalDimension.All.Count);
}
[Fact]
public void OrderShouldBeCorrect()
{
var x = FundamentalDimension.All.Reverse().OrderBy(f => f).ToList();
x[0].Should().Be(FundamentalDimension.Currency);
x[1].Should().Be(FundamentalDimension.AmountOfMatter);
x[2].Should().Be(FundamentalDimension.Mass);
x[3].Should().Be(FundamentalDimension.LuminousIntensity);
x[4].Should().Be(FundamentalDimension.ElectricCurrent);
x[5].Should().Be(FundamentalDimension.Length);
x[6].Should().Be(FundamentalDimension.Temperature);
x[7].Should().Be(FundamentalDimension.Angle);
x[8].Should().Be(FundamentalDimension.Time);
}
}
}
|
cfbdf7d37cf4b6e966827b578ff8f7e9646bc1af
|
C#
|
Vasiliy0209/xmlrpc
|
/MyService.ashx.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CookComputing.XmlRpc;
namespace MyXmlRpcApplication
{
/// <summary>
/// Сводное описание для MyService
/// </summary>
public class MyService : XmlRpcService
{
[XmlRpcMethod("myservice::helloworld",Description ="Метод, выводящий приветствие")]
public string HelloWorld()
{
return "Hello, world!";
}
[XmlRpcMethod("myservice::cities")]
public string Cities(int city_id)
{
Dictionary<int, string> cities = new Dictionary<int, string>();
cities.Add(74, "Челябинск");
cities.Add(96, "Екатеринбург");
cities.Add(77, "Москва");
if (!cities.ContainsKey(city_id))
throw new XmlRpcFaultException(100,"Город с таким кодом не найден");
return cities[city_id];
}
}
}
|
90423856ef08c4917ad5da2576adafd23598f84a
|
C#
|
oferns/vsnet
|
/VD.PayOn/BackOffice/Rebill.cs
| 2.859375
| 3
|
namespace VD.PayOn.BackOffice {
public readonly struct Rebill {
public Rebill(string referencedPaymentId) {
ReferencedPaymentId = referencedPaymentId;
}
public string ReferencedPaymentId { get; }
public readonly PaymentType PaymentType => PaymentType.Rebill;
public override string ToString() {
return $"payment.id={ReferencedPaymentId}&paymentType=RB";
}
public override bool Equals(object obj) {
return obj is Rebill rebill && rebill.Equals(ToString());
}
public static bool operator ==(Rebill left, Rebill right) {
return left.Equals(right);
}
public static bool operator !=(Rebill left, Rebill right) {
return !(left == right);
}
public override int GetHashCode() {
return this.ToString().GetHashCode();
}
}
}
|