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
|
|---|---|---|---|---|---|---|
6fb0129805d9022e43f7543243faa2b875e369d7
|
C#
|
bgoonz/UsefulResourceRepo2.0
|
/MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/__MY_OPRIGINAL_DS/_Extra-Practice/09_dynamic_programming/csharp/01_longest_common_subsequence/Program.cs
| 2.765625
| 3
|
using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
if (word_a[i] == word_b[1])
{
cell[i][j] = cell[i - 1][j - 1] + 1;
}
else
{
cell[i][j] = Math.Max(cell[i - 1][j], cell[i][j - 1]);
}
}
}
}
|
3c7ec0f582a519901e54ca0ceadab6e532c08198
|
C#
|
larrynPL/RankOne-Umbraco-SEO-Tool
|
/src/RankOne.SEO.Tool/Analyzers/Performance/JavascriptMinificationAnalyzer.cs
| 2.578125
| 3
|
using HtmlAgilityPack;
using RankOne.Attributes;
using RankOne.ExtensionMethods;
using RankOne.Helpers;
using RankOne.Interfaces;
using RankOne.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace RankOne.Analyzers.Performance
{
[AnalyzerCategory(SummaryName = "Performance", Alias = "javascriptminificationanalyzer")]
public class JavascriptMinificationAnalyzer : BaseAnalyzer
{
private readonly MinificationHelper _minificationHelper;
public JavascriptMinificationAnalyzer()
{
_minificationHelper = new MinificationHelper();
}
public override AnalyzeResult Analyse(IPageData pageData)
{
var result = new AnalyzeResult();
var url = new Uri(pageData.Url);
var localJsFiles = GetLocalJsFiles(pageData, url);
foreach (var localJsFile in localJsFiles)
{
CheckFile(localJsFile, url, result);
}
if (!result.ResultRules.Any())
{
result.AddResultRule("all_minified", ResultType.Success);
}
return result;
}
private void CheckFile(HtmlNode localJsFile, Uri url, AnalyzeResult result)
{
var address = localJsFile.GetAttribute("src");
if (address != null)
{
var fullPath = address.Value;
var content = GetContent(fullPath, url);
if (content != null)
{
var isMinified = _minificationHelper.IsMinified(content);
if (isMinified)
{
var resultRule = new ResultRule
{
Alias = "file_not_minified",
Type = ResultType.Hint
};
resultRule.Tokens.Add(fullPath);
result.ResultRules.Add(resultRule);
}
}
}
}
private string GetContent(string fullPath, Uri url)
{
if (fullPath.StartsWith("/"))
{
fullPath = string.Format("{0}://{1}{2}", url.Scheme, url.Host, fullPath);
}
try
{
var webClient = new WebClient();
return webClient.DownloadString(fullPath);
}
catch (Exception)
{
// ignored
}
return null;
}
private IEnumerable<HtmlNode> GetLocalJsFiles(IPageData pageData, Uri url)
{
return pageData.Document.GetElementsWithAttribute("script", "src").
Where(x =>
x.Attributes.Any(y => y.Name == "src" && y.Value.EndsWith("js") && ((y.Value.StartsWith("/") && !y.Value.StartsWith("//"))
|| y.Value.StartsWith(url.Host)
))
);
}
}
}
|
a971db15459c01a0077a6592df38b27940367a87
|
C#
|
yagizayer/Fps_Reflex_Game_v03
|
/Assets/Scripts/Helpers/Extesions.cs
| 2.578125
| 3
|
using UnityEngine;
using System.Collections.Generic;
namespace Helper
{
public enum Vector3Values
{
X, Y, Z, XY, XZ, YZ, XYZ
}
public static class Extesions
{
public static Vector3 Modify(this Vector3 oldValues, Vector3Values axis, float newValue)
{
switch (axis)
{
case Vector3Values.X:
return new Vector3(newValue, oldValues.y, oldValues.z);
case Vector3Values.Y:
return new Vector3(oldValues.x, newValue, oldValues.z);
case Vector3Values.Z:
return new Vector3(oldValues.x, oldValues.y, newValue);
}
return oldValues;
}
public static Vector3 Modify(this Vector3 oldValues, Vector3Values axis, Vector3 newValues)
{
switch (axis)
{
case Vector3Values.X:
return new Vector3(newValues.x, oldValues.y, oldValues.z);
case Vector3Values.Y:
return new Vector3(oldValues.x, newValues.y, oldValues.z);
case Vector3Values.Z:
return new Vector3(oldValues.x, oldValues.y, newValues.z);
case Vector3Values.XY:
return new Vector3(newValues.x, newValues.y, oldValues.z);
case Vector3Values.XZ:
return new Vector3(newValues.x, oldValues.y, newValues.z);
case Vector3Values.YZ:
return new Vector3(oldValues.x, newValues.y, newValues.z);
case Vector3Values.XYZ:
return newValues;
}
return oldValues;
}
public static Vector3 toVector3(this Vector2 vector2)
{
return new Vector3(vector2.x, vector2.y, 0);
}
public static Transform Clear(this Transform transform)
{
foreach (Transform child in transform)
{
GameObject.Destroy(child.gameObject);
}
return transform;
}
public static List<Transform> Children(this Transform transform)
{
List<Transform> result = new List<Transform>();
foreach (Transform child in transform)
result.Add(child);
return result;
}
public static bool HasChild(this Transform transform)
{
foreach (Transform child in transform)
return true;
return false;
}
public static void Reset(this Transform transform)
{
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
transform.localScale = Vector3.one;
}
public static Transform ResetPosition(this Transform transform)
{
transform.localPosition = Vector3.zero;
return transform;
}
public static RectTransform Reset(this RectTransform transform)
{
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
transform.localScale = Vector3.one;
transform.anchorMin = Vector2.zero;
transform.anchorMax = Vector2.one;
transform.sizeDelta = Vector2.zero;
transform.rect.Set(0, 0, 100, 100);
return transform;
}
public static Dictionary<T1, T2> AddRange<T1, T2>(this Dictionary<T1, T2> me, Dictionary<T1, T2> other)
{
foreach (KeyValuePair<T1, T2> item in other)
me.Add(item.Key, item.Value);
return me;
}
public static Transform LookTarget(this Transform me, Transform target)
{
me.rotation = Quaternion.LookRotation(me.position - target.position, Vector3.up);
return me;
}
public static Transform GetFirstChild(this Transform me)
{
foreach (Transform item in me)
{
return item;
}
return null;
}
public static Vector3 RelativeToCamera(this Vector3 me, Transform currentCamera)
{
Vector3 rawMoveDir = me;
Vector3 cameraForwardNormalized = Vector3.ProjectOnPlane(currentCamera.forward, Vector3.up);
Quaternion rotationToCamNormal = Quaternion.LookRotation(cameraForwardNormalized, Vector3.up);
Vector3 finalMoveDir = rotationToCamNormal * rawMoveDir;
return finalMoveDir;
}
public static float Remap(this float value, float from1, float to1, float from2, float to2)
{
return (value - from1) / (to1 - from1) * (to2 - from2) + from2;
}
}
}
|
f46247c3b71905f90fdf8259a1ec6150e94ee41e
|
C#
|
ahristoff/Database-Advanced
|
/3_CODE-FIRST/Exercises/P01_HospitalDatabase/StartUp.cs
| 2.765625
| 3
|
using P01_HospitalDatabase.Data;
using P01_HospitalDatabase.Data.Models;
using System;
using System.Linq;
using System.Text;
namespace P01_HospitalDatabase
{
class StartUp
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
using (var context = new HospitalContext())
{
Restart(context);
var patients = context.Patients
.Select(p => new
{
p.FirstName,
p.LastName,
p.Address,
p.Email,
p.HasInsurance,
Diagnoses = p.Diagnoses.Select(c => new
{
c.Name,
c.Comments
}),
Visitations = p.Visitations.Select(v => new
{
v.Comments,
v.Doctor
}),
Prescriptions = p.Prescriptions.Select(pm => new
{
pm.Medicament
}).ToArray()
});
foreach (var x in patients)
{
Console.WriteLine($"Name: {x.FirstName} {x.LastName}");
Console.WriteLine($"Address: {x.Address}");
Console.WriteLine($"Email: {x.Email}");
Console.WriteLine($"IsInsurance: {x.HasInsurance}");
Console.WriteLine($"Diagnoses: ");
foreach (var y in x.Diagnoses)
{
Console.WriteLine($"--{y.Name} -> {y.Comments}");
}
Console.WriteLine($"Doctor: ");
foreach (var z in x.Visitations)
{
Console.WriteLine($"----{z.Doctor.Name} -> {z.Comments}");
}
Console.WriteLine($"Medicament: ");
foreach (var r in x.Prescriptions)
{
Console.WriteLine($"------{r.Medicament.Name}");
}
Console.WriteLine("===================================================================");
}
}
}
private static void Restart(HospitalContext context)
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
Seed(context);
}
private static void Seed(HospitalContext context)
{
var patients = new[]
{
new Patient
{
FirstName = "Paul",
LastName = "Jones",
Address = "New York",
Email = "paulj",
HasInsurance = true
},
new Patient
{
FirstName = "Jan",
LastName = "Clark",
Address = "Seatle",
Email = "Jonny",
HasInsurance = true
},
new Patient
{
FirstName = "Pit",
LastName = "Holms",
Address = "LA",
Email = "pity",
HasInsurance = false
}
};
context.Patients.AddRange(patients);
var doctors = new []
{
new Doctor { Name = "Pesho", Specialty = "brain surgeon"},
new Doctor { Name = "Gosho", Specialty = "gynecologist"},
new Doctor { Name = "Ivancho", Specialty = "traumatologist"}
};
context.Doctors.AddRange(doctors);
var medicaments = new[]
{
new Medicament{Name = "Aspirin"},
new Medicament{Name = "Viagra"},
new Medicament{Name = "Antibiotic"},
};
context.Medicaments.AddRange(medicaments);
var patientmedicament = new[]
{
new PatientMedicament{ Patient = patients[0], Medicament = medicaments[0]},
new PatientMedicament{ Patient = patients[1], Medicament = medicaments[1]},
new PatientMedicament{ Patient = patients[2], Medicament = medicaments[2]},
};
context.Prescriptions.AddRange(patientmedicament);
var visitations = new[]
{
new Visitation{ Patient = patients[0], Doctor = doctors[0], Comments = "njama da go bade"},
new Visitation{ Patient = patients[1], Doctor = doctors[1], Comments = "bez lekarstva ne stava"},
new Visitation{ Patient = patients[2], Doctor = doctors[2], Comments = "dano ne se muchi mnogo"},
};
context.Visitations.AddRange(visitations);
var diagnoses = new[]
{
new Diagnose { Name = "schizophrenia", Comments = "Lud za vrazvane", Patient = patients[0]},
new Diagnose { Name = "not potent", Comments = "Ne moje da go vdigne", Patient = patients[1]},
new Diagnose { Name = "broken neck", Comments = "няма да ходи повече", Patient = patients[2]},
};
context.Diagnoses.AddRange(diagnoses);
context.SaveChanges();
}
}
}
|
f5c78c70b2a6e74637fa8a6f46a436e7b4146747
|
C#
|
madhu0699/StockMarket
|
/StockMarketApi/StockMarket.AdminAPI/Services/StockExchangeService.cs
| 2.578125
| 3
|
using StockMarket.AdminAPI.Models;
using StockMarket.AdminAPI.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StockMarket.AdminAPI.Services
{
public class StockExchangeService : IStockExchangeService
{
private IStockExchangeRepository seRepo;
public StockExchangeService() { }
public StockExchangeService(IStockExchangeRepository _userRepo)
{
this.seRepo = _userRepo;
}
//StockExchangeRepository seRepo = new StockExchangeRepository();
public void AddSE(StockExchange value)
{
seRepo.AddSE(value);
}
public void DeleteSE(int id)
{
seRepo.DeleteSE(id);
}
public void DeleteSEByName(string name)
{
seRepo.DeleteSEByName(name);
}
public List<StockExchange> GetAllSE()
{
return seRepo.GetAllSE();
}
public StockExchange GetSE(int id)
{
return seRepo.GetSE(id);
}
public StockExchange GetSEByName(string name)
{
return seRepo.GetSEByName(name);
}
public void UpdateSE(StockExchange value)
{
seRepo.UpdateSE(value);
}
}
}
|
e6a6637c9b0bcf738997323a4dbeee66497040da
|
C#
|
dkoudela/unity-programming-theory
|
/Assets/Scripts/Health.cs
| 2.78125
| 3
|
using UnityEngine;
public class Health : MonoBehaviour
{
// ENCAPSULATION
private int health;
private string healthTextPrefix = "Health: ";
// Start is called before the first frame update
void Start()
{
if (gameObject.CompareTag("Player"))
{
health = 10;
}
else if (gameObject.CompareTag("Enemy"))
{
health = 2;
if (gameObject.name.Contains("Boss Enemy"))
{
health = 5;
}
}
if (gameObject.CompareTag("Player"))
{
Utilities.ChangeText("Health", healthTextPrefix + health);
}
}
// Update is called once per frame
void Update()
{
if (0 >= health)
{
Destroy(gameObject);
}
}
public void DecreaseHealth()
{
health--;
UpdatePlayerHealthText();
}
public void IncreaseHealth(int newHealth)
{
health += newHealth;
UpdatePlayerHealthText();
}
private void UpdatePlayerHealthText()
{
if (gameObject.CompareTag("Player"))
{
Utilities.ChangeText("Health", healthTextPrefix + health);
}
}
}
|
c9217ec6250198c879db77d0dcd25a2ffe261453
|
C#
|
y497068561/Inflexion2
|
/00-Examples/EF/CommonDomain/Domain/EntityB/EntityB.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Inflexion2.Domain;
using System.ComponentModel.DataAnnotations;
namespace CommonDomain
{
[Serializable]
public class EntityB : AggregateRoot<EntityB, int>, IEntityB
{
private string name;
[Required]
public virtual string Name { get; set; }
private IList<EntityA> entitiesofA;
[ChildrenRelationshipDeleteBehavior(Delete.Cascade)]
public virtual ICollection<EntityA> EntitiesofA
{
get
{
return entitiesofA;
}
}
/// <summary>
/// constructor vacio inicializamos las colecciones con objeto de que puedan ser utilizadas
/// </summary>
private EntityB(): base()
{
entitiesofA = new List<EntityA>();
}
/// <summary>
/// Constructor con parametros de propiedades requeridas
/// </summary>
/// <param name="name"></param>
protected internal EntityB(string name)
: this()
{
this.Name = name;
}
public virtual void AddB(EntityA b)
{
this.entitiesofA.Add(b);
}
}
}
|
4f7e55b17dcb34edb62c923e410835626c2ce07a
|
C#
|
adecker794/Serial-Transfer-Program
|
/Serial Transfer Program/Receiving/ReceivingData.cs
| 3.453125
| 3
|
using System.Configuration;
using System;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
namespace Serial_Transfer_Program
{
class ReceivingData
{
public static string comport = Settings1.Default.ComPort;
public static int baudrateInt = Settings1.Default.BaudRate;
public static string destinationFile = Settings1.Default.DestinationFile;
[STAThread]
public static void receivingDataStart()
{
Console.WriteLine("You have picked {0} as the ComPort and {1} as the BaudRate ", comport, baudrateInt);
Console.WriteLine("Your destination file is {0}", destinationFile);
// Instantiate the communications
// port with some basic settings
SerialPort port = new SerialPort(comport, baudrateInt, Parity.None, 8, StopBits.One);
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
//Keeps the application open and awaiting data
Application.Run();
}
public static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//Brings in the serialport connection
SerialPort sp = (SerialPort)sender;
//Reads the lines as they come into the connection
string line = sp.ReadLine();
Console.WriteLine(line);
// WriteAllLines creates a file, writes a collection of strings to the file,
// It then converts the file from Base64 to a "readable" string and sends it to a specified file
System.IO.File.WriteAllText(@"tempwritefile.txt", line, System.Text.Encoding.Default);
string linesRead = File.ReadAllText(@"tempwritefile.txt");
Byte[] bytes1 = Convert.FromBase64String(linesRead);
File.WriteAllBytes(destinationFile, bytes1);
//Deletes the old file originially used to write the data to
File.Delete(@"tempwritefile.txt");
//Closes the connection and starts a new one so the loop continues
Console.WriteLine("File transfer has completed, starting to receive again.");
sp.Close();
ReceivingData.receivingDataStart();
}
}
}
|
20766b0ca331ab92d4abbff8e0c7778e364effcc
|
C#
|
GelyaTh/lab4_a
|
/PrimitivesSearch.cs
| 2.75
| 3
|
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab4_AOCI
{
class PrimitivesSearch
{
private Image<Bgr, byte> srcImg;
private int lastContoursCount;
public int LastContoursCount { get => lastContoursCount; }
public Image<Bgr, byte> SrcImg { get => srcImg; }
public PrimitivesSearch(Image<Bgr, byte> image)
{
srcImg = image;
lastContoursCount = 0;
}
private VectorOfVectorOfPoint findContours(int trsh, bool colorSearch)
{
//var cannyEdges = bluredImage.Canny(1, 250);
// imageBox2.Image = cannyEdges.Resize(640, 480, Inter.Linear);
Image<Gray, byte> binarizedImage;
if (colorSearch)
binarizedImage = binarizeImageByColorSearch();
else
binarizedImage = binarizeImage(trsh);
var contours = new VectorOfVectorOfPoint(); // контейнер для хранения контуров
CvInvoke.FindContours(
binarizedImage, // исходное чёрно-белое изображение
contours, // найденные контуры
null, // объект для хранения иерархии контуров (в данном случае не используется)
RetrType.List, // структура возвращаемых данных (в данном случае список)
ChainApproxMethod.ChainApproxSimple);
var approxContours = new VectorOfVectorOfPoint();
for (int i = 0; i < contours.Size; i++)
{
var approxContour = new VectorOfPoint();
CvInvoke.ApproxPolyDP(
contours[i], // исходный контур
approxContour, // контур после аппроксимации
CvInvoke.ArcLength(contours[i], true) * 0.05, // точность аппроксимации, прямо
//пропорциональная площади контура
true); // контур становится закрытым (первая и последняя точки соединяются)
approxContours.Push(approxContour);
}
lastContoursCount = approxContours.Size;
return approxContours;
}
public Image<Bgr, byte> drawContours(int thrs, bool colorSearch)
{
var contours = findContours(thrs, colorSearch);
var contoursImage = srcImg.Copy(); //создание "пустой" копии исходного изображения
for (int i = 0; i < contours.Size; i++)
{
var points = contours[i].ToArray();
contoursImage.Draw(points, new Bgr(Color.GreenYellow), 2); // отрисовка точек }
}
return contoursImage;
}
public Image<Bgr, byte> findRectangles(int thrs, int area, bool colorSearch)
{
var contours = findContours(thrs, colorSearch);
lastContoursCount = 0;
var contoursImage = srcImg.Copy(); //создание "пустой" копии исходного изображения
for (int i=0; i<contours.Size; i++)
{
if (CvInvoke.ContourArea(contours[i], false) > area)
{
if (isRectangle(contours[i].ToArray()))
{
contoursImage.Draw(CvInvoke.MinAreaRect(contours[i]),
new Bgr(Color.GreenYellow), 2);
lastContoursCount++;
}
}
}
return contoursImage;
}
public Image<Bgr, byte> findTriangles(int thrs, int area, bool colorSearch)
{
var contours = findContours(thrs, colorSearch);
lastContoursCount = 0;
var contoursImage = srcImg.Copy(); //создание "пустой" копии исходного изображения
for (int i = 0; i < contours.Size; i++)
{
if (CvInvoke.ContourArea(contours[i], false) > area)
{
if (contours[i].Size == 3) // если контур содержит 3 точки, то рисуется треугольник
{
var points = contours[i].ToArray();
contoursImage.Draw(new Triangle2DF(points[0], points[1], points[2]),
new Bgr(Color.GreenYellow), 2);
lastContoursCount++;
}
}
}
return contoursImage;
}
public Image<Bgr, byte> findCircles(int thrs, bool colorSearch)
{
lastContoursCount = 0;
Image<Gray, byte> grayImage;
/*if (colorSearch)
grayImage = binarizeImageByColorSearch();
else*/
grayImage = srcImg.Convert<Gray, byte>();
var bluredImage = grayImage.SmoothGaussian(9);
List<CircleF> circles = new List<CircleF>(CvInvoke.HoughCircles(bluredImage,
HoughModes.Gradient,
1.0,
250, //minDistance
100,
thrs, //acTreshold
2, //minRadius
500)); //maxRadius
var resultImage = srcImg.Copy();
foreach (CircleF circle in circles) resultImage.Draw(circle, new Bgr(Color.GreenYellow), 2);
lastContoursCount = circles.Count;
return resultImage;
}
private Image<Gray, byte> binarizeImage(int trsh)
{
var grayImage = srcImg.Convert<Gray, byte>();
int kernelSize = 5; // радиус размытия
var bluredImage = grayImage.SmoothGaussian(kernelSize);
var threshold = new Gray(trsh); // пороговое значение
var color = new Gray(255); // этим цветом будут закрашены пиксели, имеющие значение > threshold
return bluredImage.ThresholdBinary(threshold, color);
}
private Image<Gray, byte> binarizeImageByColorSearch()
{
var hsvImage = srcImg.Convert<Hsv, byte>(); // конвертация в HSV
var hueChannel = hsvImage.Split()[0]; // выделение канала Hue
byte color = 30; // соответствует желтому тону в Emgu.CV
byte rangeDelta = 10; // величина разброса цвета
return hueChannel.InRange(new Gray(color - rangeDelta), new Gray(color + rangeDelta)); // выделение
}
private bool isRectangle(Point[] points)
{
int delta = 10; // максимальное отклонение от прямого угла
LineSegment2D[] edges = PointCollection.PolyLine(points, true);
for (int i = 0; i < edges.Length; i++) // обход всех ребер контура
{
double angle = Math.Abs(edges[(i + 1) %
edges.Length].GetExteriorAngleDegree(edges[i]));
if (angle < 90 - delta || angle > 90 + delta) // если угол непрямой
{
return false;
}
}
return true;
}
}
}
|
d0833f25eb11d9322dc8e3244f21b28f78c953f7
|
C#
|
aurelioromeu/P3Image
|
/TesteP3Image/TesteP3Image/Models/NHibernate/CamposRepository.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Linq;
namespace TesteP3Image.Models.NHibernate
{
public class CamposRepository
{
public IList<Campos> ObterTodos()
{
using (ISession session = NHibernateSession.OpenSession())
{
return session.Query<Campos>().ToList();
}
}
public Campos BuscarPorId(int id)
{
using (ISession session = NHibernateSession.OpenSession())
{
return session.CreateCriteria<Campos>().Add(Restrictions.Eq("CampoId", id)).UniqueResult<Campos>();
}
}
public int UltimaOrdem()
{
using (ISession session = NHibernateSession.OpenSession())
{
return (session.Query<Campos>().Select(x => x.Ordem).OrderByDescending(x => x).FirstOrDefault() + 1);
}
}
}
}
|
d234946aa47aed35711c0c40dbec23c4ef327e0b
|
C#
|
nikhilmurthy/CPTS-421-423
|
/NewITSDemo/NewITS_v21/NewITS/Building.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NewITS
{
public class Building
{
private int id;
private string sname;
private string lname;
public int ID
{
get { return id; }
set { id = value; }
}
public string SName
{
get { return sname; }
set { sname = value; }
}
public string LName
{
get { return lname; }
set { lname = value; }
}
}
public class BuildingStore
{
private static BuildingStore bs = null;
public static BuildingStore getInstance
{
get
{
if (bs == null)
{
bs = new BuildingStore();
}
return bs;
}
}
private List<Building> bList;
private int nextBuild;
private BuildingStore()
{
bList = new List<Building>();
nextBuild = 1;
}
public int NewBuilding(string shortname, string longname)
{
Building b;
b = new Building(); // Create new building
// Assign building values
b.ID = nextBuild;
b.SName = shortname;
b.LName = longname;
// Add to building list
bList.Add(b);
nextBuild++;
return b.ID;
}
public List<string> OrderBuild()
{
List<string> ol = new List<string>();
foreach (Building b in bList)
ol.Add(b.SName);
return ol;
}
}
}
|
b46eba4033e1c38f3bc3c0b374421e6203752521
|
C#
|
2014-sed-team3/term-project
|
/project/Src/NodeXL/ExcelTemplate/EventArgs/Commands/RunNoParamCommandEventArgs.cs
| 2.578125
| 3
|
using System;
using System.Diagnostics;
namespace Smrf.NodeXL.ExcelTemplate
{
//*****************************************************************************
// Class: RunNoParamCommandEventArgs
//
/// <summary>
/// Provides information for a command that needs to be run, where the command
/// does not require any parameters.
/// </summary>
///
/// <remarks>
/// See <see cref="RunCommandEventArgs" /> for information about how NodeXL
/// sends commands from one UI object to another.
///
/// <para>
/// There are many commands that do not require any parameters. Instead of
/// deriving a class from RunCommandEventArgs for each such command, this class
/// consolidates all of them. They are distinguished by a <see
/// cref="NoParamCommand" /> value passed to the constructor.
/// </para>
///
/// </remarks>
//*****************************************************************************
public class RunNoParamCommandEventArgs : RunCommandEventArgs
{
//*************************************************************************
// Constructor: RunNoParamCommandEventArgs()
//
/// <summary>
/// Initializes a new instance of the <see
/// cref="RunNoParamCommandEventArgs" /> class.
/// </summary>
///
/// <param name="noParamCommand">
/// The no-parameter command that needs to be run.
/// </param>
//*************************************************************************
public RunNoParamCommandEventArgs
(
NoParamCommand noParamCommand
)
{
m_eNoParamCommand = noParamCommand;
AssertValid();
}
//*************************************************************************
// Property: NoParamCommand
//
/// <summary>
/// Gets the no-parameter command that needs to be run.
/// </summary>
///
/// <value>
/// The no-parameter command that needs to be run.
/// </value>
//*************************************************************************
public NoParamCommand
NoParamCommand
{
get
{
AssertValid();
return (m_eNoParamCommand);
}
}
//*************************************************************************
// Method: AssertValid()
//
/// <summary>
/// Asserts if the object is in an invalid state. Debug-only.
/// </summary>
//*************************************************************************
// [Conditional("DEBUG")]
public override void
AssertValid()
{
base.AssertValid();
// m_eNoParamCommand
}
//*************************************************************************
// Protected member data
//*************************************************************************
/// The no-parameter command that needs to be run.
protected NoParamCommand m_eNoParamCommand;
}
//*****************************************************************************
// Enum: NoParamCommand
//
/// <summary>
/// Specifies a command that needs to be run, where the command does not
/// require any parameters.
/// </summary>
//*****************************************************************************
public enum
NoParamCommand
{
/// <summary>
/// Group by vertex attribute.
/// </summary>
GroupByVertexAttribute,
/// <summary>
/// Calculate connected components.
/// </summary>
CalculateConnectedComponents,
/// <summary>
/// Group by motif.
/// </summary>
GroupByMotif,
/// <summary>
/// Let the user edit the group user settings.
/// </summary>
EditGroupUserSettings,
/// <summary>
/// Show the dynamic filters dialog.
/// </summary>
ShowDynamicFilters,
/// <summary>
/// Read the workbook into the graph pane.
/// </summary>
ReadWorkbook,
/// <summary>
/// Show the graph pane, then read the workbook into the graph pane.
/// </summary>
ShowGraphAndReadWorkbook,
/// <summary>
/// Let the user edit the layout settings.
/// </summary>
EditLayoutUserSettings,
/// <summary>
/// Show the readability metrics dialog.
/// </summary>
ShowReadabilityMetrics,
/// <summary>
/// Export the graph to the NodeXL Graph Gallery.
/// </summary>
ExportToNodeXLGraphGallery,
/// <summary>
/// Export the graph to email.
/// </summary>
ExportToEmail,
/// <summary>
/// Open the application's home page in a browser window.
/// </summary>
OpenHomePage,
/// <summary>
/// Open the application's discussion page in a browser window.
/// </summary>
OpenDiscussionPage,
/// <summary>
/// Open the NodeXL Graph Gallery in a browser window.
/// </summary>
OpenNodeXLGraphGallery,
/// <summary>
/// Load the user settings maintained by the command handler.
/// </summary>
LoadUserSettings,
/// <summary>
/// Save the user settings maintained by the command handler.
/// </summary>
SaveUserSettings,
/// <summary>
/// Show the graph legend in the TaskPane.
/// </summary>
ShowGraphLegend,
/// <summary>
/// Hide the graph legend in the TaskPane.
/// </summary>
HideGraphLegend,
/// <summary>
/// Show the graph axes in the TaskPane.
/// </summary>
ShowGraphAxes,
/// <summary>
/// Hide the graph axes in the TaskPane.
/// </summary>
HideGraphAxes,
/// <summary>
/// Update the layout in the TaskPane.
/// </summary>
UpdateLayout,
/// <summary>
/// Show and hide the column groups specified in the user settings.
/// </summary>
ShowAndHideColumnGroups,
/// <summary>
/// Let the user edit the import data user settings.
/// </summary>
EditImportDataUserSettings,
/// <summary>
/// Import edges from another open workbook (to be specified by the user)
/// that contains a graph represented as an adjacency matrix.
/// </summary>
ImportFromMatrixWorkbook,
/// <summary>
/// Import edges and vertices from another open workbook (to be specified
/// by the user).
/// </summary>
ImportFromWorkbook,
/// <summary>
/// Import the contents of a UCINET full matrix DL file into the workbook.
/// </summary>
ImportFromUcinetFile,
/// <summary>
/// Import the contents of a GraphML file into the workbook.
/// </summary>
ImportFromGraphMLFile,
/// <summary>
/// Import a set of GraphML files into a set of new NodeXL workbooks.
/// </summary>
ImportFromGraphMLFiles,
/// <summary>
/// Import the contents of a Pajek file into the workbook.
/// </summary>
ImportFromPajekFile,
/// <summary>
/// Export the selected rows of the edge and vertex tables to a new NodeXL
/// workbook.
/// </summary>
ExportSelectionToNewNodeXLWorkbook,
/// <summary>
/// Export the edge and vertex tables to a new UCINET full matrix DL file.
/// </summary>
ExportToUcinetFile,
/// <summary>
/// Export the edge and vertex tables to a new GraphML file.
/// </summary>
ExportToGraphMLFile,
/// <summary>
/// Export the edge and vertex tables to a new Pajek text file.
/// </summary>
ExportToPajekFile,
/// <summary>
/// Export the edge table to a new workbook as an adjacency matrix.
/// </summary>
ExportToNewMatrixWorkbook,
/// <summary>
/// Aggregate graph metrics from multiple workbooks.
/// </summary>
AggregateGraphMetrics,
/// <summary>
/// Open a dialog that lets the user run multiple tasks.
/// </summary>
AutomateTasks,
/// <summary>
/// Immediately run multiple tasks on this workbook. The task automation
/// dialog is not shown.
/// </summary>
AutomateThisWorkbook,
/// <summary>
/// Delete any subgraph image thumbnails in the vertex worksheet.
/// </summary>
DeleteSubgraphThumbnails,
/// Show the dialog that analyzes a user's email network and write the
/// results to the edge worksheet.
AnalyzeEmailNetwork,
/// <summary>
/// Copy a NodeXL workbook created on another machine and convert the copy
/// to work on this machine.
/// </summary>
ConvertNodeXLWorkbook,
/// <summary>
/// Allow the user to register for email updates.
/// </summary>
RegisterUser,
/// Show the dialog that lists available graph metrics and calculate them
/// if requested by the user.
ShowGraphMetrics,
/// Create a subgraph of each of the graph's vertices and save the images
/// to disk or the workbook.
CreateSubgraphImages,
/// Show the dialog that fills edge and vertex attribute columns using
/// values from user-specified source columns.
AutoFillWorkbook,
/// Create a new NodeXL workbook.
CreateNodeXLWorkbook,
/// Show the graph summary dialog.
ShowGraphSummary,
}
}
|
98ba74005654673b3d0eb57672419c6f1591f60d
|
C#
|
BruceBayne/Friday.NET
|
/Friday.Base/ValueTypes/Percent.cs
| 3.25
| 3
|
using System;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace Friday.Base.ValueTypes
{
[Serializable]
public struct Percent : IComparable<Percent>, ISerializable, IEquatable<Percent>
{
public readonly decimal Value;
private Percent(decimal value)
{
Value = value;
}
/// <summary>
/// 0% Percent
/// </summary>
public static Percent Zero => From(0);
/// <summary>
/// 1% Percent
/// </summary>
public static Percent One => From(1);
/// <summary>
/// 10% Percents
/// </summary>
public static Percent Ten => From(10);
/// <summary>
/// 50% Percents
/// </summary>
public static Percent Fifty => From(50);
public override string ToString()
{
return $"{Value} %";
}
private Percent(SerializationInfo info, StreamingContext para)
{
Value = info.GetDecimal(nameof(Value));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
info.AddValue(nameof(Value), Value);
}
/// <summary>
/// 100% Percents
/// </summary>
public static Percent Hundred => From(100);
public static Percent From(byte value)
{
return new Percent(value);
}
public static Percent From(decimal value)
{
return new Percent(value);
}
public static decimal CalculatePercentAmountFromValue(decimal value, Percent percent)
{
return value * percent.Value / 100;
}
public static int CalculatePercentAmountFromValue(int value, Percent percent)
{
return (int)Math.Round(value * percent.Value / 100);
}
public static long CalculatePercentAmountFromValue(long value, Percent percent)
{
return (long)Math.Round(value * percent.Value / 100);
}
public static uint CalculatePercentAmountFromValue(uint value, Percent percent)
{
return (uint)Math.Round(value * percent.Value / 100);
}
public static ulong CalculatePercentAmountFromValue(ulong value, Percent percent)
{
return (ulong)Math.Round(value * percent.Value / 100);
}
public static int operator +(int m1, Percent m2)
{
return m1 + CalculatePercentAmountFromValue(m1, m2);
}
public static long operator +(long m1, Percent m2)
{
return m1 + CalculatePercentAmountFromValue(m1, m2);
}
public static uint operator +(uint m1, Percent m2)
{
return m1 + CalculatePercentAmountFromValue(m1, m2);
}
public static ulong operator +(ulong m1, Percent m2)
{
return m1 + CalculatePercentAmountFromValue(m1, m2);
}
public static decimal operator +(decimal m1, Percent m2)
{
return m1 + CalculatePercentAmountFromValue(m1, m2);
}
public static int operator -(int m1, Percent m2)
{
return m1 - CalculatePercentAmountFromValue(m1, m2);
}
public static long operator -(long m1, Percent m2)
{
return m1 - CalculatePercentAmountFromValue(m1, m2);
}
public static uint operator -(uint m1, Percent m2)
{
return m1 - CalculatePercentAmountFromValue(m1, m2);
}
public static ulong operator -(ulong m1, Percent m2)
{
return m1 - CalculatePercentAmountFromValue(m1, m2);
}
public static decimal operator -(decimal m1, Percent m2)
{
return m1 - CalculatePercentAmountFromValue(m1, m2);
}
public static Percent operator +(Percent m1, Percent m2)
{
return From(m1.Value + m2.Value);
}
public static Percent operator -(Percent m1, Percent m2)
{
return From(m1.Value - m2.Value);
}
public static bool operator >(Percent m1, Percent m2)
{
return m1.Value > m2.Value;
}
public static bool operator <(Percent m1, Percent m2)
{
return m1.Value < m2.Value;
}
public static bool operator <=(Percent m1, Percent m2)
{
return m1.Value <= m2.Value;
}
public static bool operator >=(Percent m1, Percent m2)
{
return m1.Value >= m2.Value;
}
public static bool operator ==(Percent m1, Percent m2)
{
return m1.Value == m2.Value;
}
public static bool operator !=(Percent m1, Percent m2)
{
return m1.Value != m2.Value;
}
[Pure]
public int CompareTo(Percent other)
{
return Value.CompareTo(other.Value);
}
[Pure]
public bool Equals(Percent other)
{
return Value == other.Value;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Percent percent && Equals(percent);
}
[Pure]
public override int GetHashCode()
{
return Value.GetHashCode();
}
}
}
|
16c0f354ec7bdb1d5cb96f939493c5ba6cd774b8
|
C#
|
felipejunges/Formula1
|
/Formula1.Domain/Extensions/CriptoExtensions.cs
| 2.84375
| 3
|
namespace Formula1.Domain.Extensions
{
public static class CriptoExtensions
{
public static string GetBCrypt(this string senha, int salt = 12)
{
return BCrypt.Net.BCrypt.HashPassword(senha, BCrypt.Net.BCrypt.GenerateSalt(salt));
}
public static bool CheckBCrypt(this string hash, string senha)
{
try
{
return BCrypt.Net.BCrypt.Verify(senha, hash);
}
catch
{
return false;
}
}
}
}
|
213678f31e1e11225be4f7da7c17de55e1185d4a
|
C#
|
PalmeR147/TowerDefense
|
/TDPalm/TDPalm/TDPalm/Tiles.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
namespace TDPalm
{
public static class Tiles
{
public static List<Tile> Tiless = new List<Tile>();
public static Tower[,] Towers =
{
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
{null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null},
};
//public static List<Tower> Towers = new List<Tower>();
public static ContentManager content;
public static void CreateMap()
{
for (int x = 0; x < Map.Map1.GetLength(1); x++)
{
for (int y = 0; y < Map.Map1.GetLength(0); y++)
{
Tiless.Add(new Tile(Map.Map1[y, x], x, y, content));
}
}
}
public static int GetTowerPrice(int id)
{
switch (id)
{
case 5:
return 500;
default:
return 1;
}
}
public static void AddTower(int xTile, int yTile, int id, int range)
{
if (Game1.money >= GetTowerPrice(id))
{
Towers[yTile, xTile] = new Tower(id, xTile, yTile, content, range);
Game1.money -= GetTowerPrice(id);
}
}
public static void RemoveTower(int xTile, int yTile)
{
int id = Towers[yTile, xTile].id;
Game1.money += (int)(GetTowerPrice(id) * 0.75);
Towers[yTile, xTile] = null;
}
public static void Update(GameTime gameTime)
{
foreach (Tile t in Tiless)
{
t.Update(gameTime);
}
for (int x = 0; x < Towers.GetLength(1); x++)
{
for (int y = 0; y < Towers.GetLength(0); y++)
{
if (Towers[y, x] != null)
{
Towers[y, x].Update();
}
}
}
}
public static void DrawTiles(SpriteBatch spriteBatch)
{
foreach (Tile t in Tiless)
{
t.Draw(spriteBatch);
}
}
public static void DrawTowers(SpriteBatch spriteBatch)
{
for (int x = 0; x < Towers.GetLength(1); x++)
{
for (int y = 0; y < Towers.GetLength(0); y++)
{
if (Towers[y, x] != null)
{
Towers[y, x].Draw(spriteBatch);
}
}
}
}
}
}
|
d4b190aa24772a7ffb3afed85fb8f8c1a75505ab
|
C#
|
eladj/UnityProjects
|
/HootOwlHoot3D/Assets/Tests/EditMode/GameLogicTest.cs
| 2.75
| 3
|
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
public class GameLogicTest
{
[Test]
public void InitDefaultTest()
{
GameLogic gameLogic = new GameLogic();
gameLogic.InitGame();
Assert.AreEqual(GameLogicStage.Ongoing, gameLogic.Stage());
}
[Test]
public void InitFromGameLogicConfigTest()
{
GameLogicConfig gameLogicConfig = new GameLogicConfig(4, 5, numSunCardToLose_: 9);
GameLogic gameLogic = new GameLogic(gameLogicConfig);
gameLogic.InitGame();
Assert.AreEqual(GameLogicStage.Ongoing, gameLogic.Stage());
Assert.AreEqual(4, gameLogic.GetConfig().numPlayers);
Assert.AreEqual(5, gameLogic.GetConfig().numDragons);
Assert.AreEqual(9, gameLogic.GetConfig().numSunCardToLose);
}
[Test]
public void SunCardsMovesTest()
{
// Generate a deck with only Sun cards
GameLogicConfig gameLogicConfig = new GameLogicConfig(2, 3, numColorCardsInDeck_: 0, numSunCardToLose_: 5, numSunCardsInDeck_: 40);
GameLogic gameLogic = new GameLogic(gameLogicConfig);
// Try to play before init
Assert.AreEqual(GameLogicStage.Uninitialized, gameLogic.Stage());
Assert.False(gameLogic.MakeMoveSunCard(0));
Assert.False(gameLogic.MakeMoveSunCard(0));
// Play after initalization
gameLogic.InitGame();
Assert.AreEqual(GameLogicStage.Ongoing, gameLogic.Stage());
// Play 5 sun card and expect to lose
for (int i = 0; i < 5; i++)
{
bool success = gameLogic.MakeMoveSunCard(0);
Assert.True(success);
}
Assert.AreEqual(GameLogicStage.Lost, gameLogic.Stage());
// Try to play after we already lost
Assert.False(gameLogic.MakeMoveSunCard(0));
Assert.False(gameLogic.MakeMoveSunCard(0));
// Initalize again and play
gameLogic.InitGame();
Assert.AreEqual(GameLogicStage.Ongoing, gameLogic.Stage());
for (int i = 0; i < 5; i++)
{
bool success = gameLogic.MakeMoveSunCard(0);
Assert.True(success);
}
Assert.AreEqual(GameLogicStage.Lost, gameLogic.Stage());
// Make sure all cards are sun
List<CardType> cards = gameLogic.GetCards(0);
foreach (CardType card in cards)
{
Assert.True(card == CardType.Sun);
}
}
[Test]
public void ColorCardsMovesTest()
{
// Generate a deck with only color cards and a game with only single dragon,
// so we are guarnteed to win after 40 iterations at most, given we have 40 islands.
GameLogicConfig gameLogicConfig = new GameLogicConfig(2, 1, numColorCardsInDeck_: 10, numSunCardToLose_: 100, numSunCardsInDeck_: 0);
GameLogic gameLogic = new GameLogic(gameLogicConfig);
// Try to play before init
Assert.AreEqual(GameLogicStage.Uninitialized, gameLogic.Stage());
Assert.False(gameLogic.MakeMoveColorAndDragon(0, 0));
Assert.False(gameLogic.MakeMoveColorAndDragon(0, 0));
// Play after initalization
gameLogic.InitGame();
Assert.AreEqual(GameLogicStage.Ongoing, gameLogic.Stage());
for (int i = 0; i < 40; i++)
{
bool success = gameLogic.MakeMoveColorAndDragon(0, 0);
}
Assert.AreEqual(GameLogicStage.Won, gameLogic.Stage());
// Try to play after we already won
Assert.False(gameLogic.MakeMoveSunCard(0));
Assert.False(gameLogic.MakeMoveSunCard(0));
// Initalize again and play
gameLogic.InitGame();
Assert.AreEqual(GameLogicStage.Ongoing, gameLogic.Stage());
for (int i = 0; i < 40; i++)
{
bool success = gameLogic.MakeMoveColorAndDragon(0, 0);
if (!success) break;
}
Assert.AreEqual(GameLogicStage.Won, gameLogic.Stage());
// Make sure all cards are colors
List<CardType> cards = gameLogic.GetCards(0);
foreach (CardType card in cards)
{
Assert.True(card != CardType.Sun);
}
}
[Test]
public void IlegalMovesTest()
{
GameLogicConfig gameLogicConfig = new GameLogicConfig(2, 3, numCardsPerPlayer_: 4, numColorCardsInDeck_: 0, numSunCardToLose_: 5, numSunCardsInDeck_: 40);
GameLogic gameLogic = new GameLogic(gameLogicConfig);
gameLogic.InitGame();
// We shouldn't have any color card
Assert.False(gameLogic.MakeMoveColorAndDragon(0, 0));
// There are only 3 dragons
Assert.False(gameLogic.MakeMoveColorAndDragon(0, 3));
// We have only 4 cards per player
Assert.False(gameLogic.MakeMoveColorAndDragon(4, 0));
gameLogicConfig = new GameLogicConfig(2, 3, numCardsPerPlayer_: 4, numColorCardsInDeck_: 10, numSunCardToLose_: 5, numSunCardsInDeck_: 0);
gameLogic = new GameLogic(gameLogicConfig);
gameLogic.InitGame();
// We shouldn't have any sun card
Assert.False(gameLogic.MakeMoveSunCard(0));
// We have only 4 cards per player
Assert.False(gameLogic.MakeMoveSunCard(4));
}
[Test]
public void GetDragonIslandTest()
{
GameLogicConfig gameLogicConfig = new GameLogicConfig(4, numDragons_: 6);
GameLogic gameLogic = new GameLogic(gameLogicConfig);
gameLogic.InitGame();
List<int> dragonIslands = gameLogic.GetDragonsIslandIndices();
for (int i = 0, expected = 5; i < dragonIslands.Count; i++, expected--)
{
Assert.AreEqual(expected, dragonIslands[i]);
}
}
[Test]
public void InvalidConfigTest()
{
Assert.Throws<System.ArgumentException>(() => new GameLogicConfig(numPlayers_: 0, numDragons_: 3));
Assert.Throws<System.ArgumentException>(() => new GameLogicConfig(numPlayers_: 5, numDragons_: 3));
Assert.Throws<System.ArgumentException>(() => new GameLogicConfig(numPlayers_: 2, numDragons_: 0));
Assert.Throws<System.ArgumentException>(() => new GameLogicConfig(numPlayers_: 2, numDragons_: 7));
Assert.Throws<System.ArgumentException>(() => new GameLogicConfig(numPlayers_: 2, numDragons_: 3, numCardsPerPlayer_: 0));
}
}
|
24fe89b1062e1996da732fa573e3181f5426e228
|
C#
|
Omlet144/army_
|
/Shields/ShieldAbstruct.cs
| 2.96875
| 3
|
namespace Shields{
public class ShieldAbstruct{
public int DefendHP { get; set; }
protected ShieldAbstruct(int defendHP){
this.DefendHP = defendHP;
}
public void Defend(Soldiers.SoldierAbstruct holder, int damage){
holder.HP -= (this.DefendHP - damage);
}
}
}
|
14f610fbf216c59437950111ee2b9caeff3e9f77
|
C#
|
PatrykOlejniczak/WPK.TransportSystem
|
/Business.Services/AuthenticationCustomerManager.cs
| 2.71875
| 3
|
using System;
using System.Linq;
using System.ServiceModel;
using Business.Contracts;
using Business.Entities;
using Core.Common.Secure;
using Data.Core.Repository;
using Data.Core.UnitOfWork;
namespace Business.Services
{
public class AuthenticationCustomerManager : ICustomerAuthenticationService
{
private readonly IUnitOfWork _unitOfWork;
private readonly IRepository<Data.Entities.Customer> _customerRepository;
public AuthenticationCustomerManager(IUnitOfWork unitOfWork,
IRepository<Data.Entities.Customer> customerRepository)
{
_customerRepository = customerRepository;
_unitOfWork = unitOfWork;
_customerRepository.EnrollUnitOfWork(_unitOfWork);
}
public bool IsCustomerExists(string email)
{
var result = _customerRepository.FindBy(c => c.Email == email);
return result.Any();
}
public bool IsCorrectCredentialsCorrect(string email, string password)
{
var result = _customerRepository
.FindBy(c => c.Email == email && PasswordHash.ValidatePassword(password, c.HashPassword));
return result.Any();
}
public Customer GetInfoAboutCustomer(string email, string password)
{
var result = _customerRepository
.FindBy(c => c.Email == email && PasswordHash.ValidatePassword(password, c.HashPassword));
return ConvertToReturn(result.First());
}
public bool Register(string email, string password)
{
bool returnValue = false;
if (!IsCustomerExists(email))
{
try
{
Data.Entities.Customer newCustomer = new Data.Entities.Customer()
{
Email = email,
HashPassword = PasswordHash.CreateHash(password)
};
_customerRepository.Add(newCustomer);
_unitOfWork.Commit();
}
catch (Exception exception)
{
throw new FaultException(exception.Message);
}
returnValue = true;
}
return returnValue;
}
public void SendPasswordReminder(string email)
{
//TODO
}
private Customer ConvertToReturn(Data.Entities.Customer customer)
{
return AutoMapper.Mapper.Map<Customer>(customer);
}
}
}
|
65733851e1c0105634540e9c9d277a1c3af60dcf
|
C#
|
hatelove/expectedObjects
|
/src/ExpectedObjects.Specs/ObjectShouldNotMatchSpecs.cs
| 2.65625
| 3
|
using System;
using ExpectedObjects.Specs.TestTypes;
using Machine.Specifications;
namespace ExpectedObjects.Specs
{
public class when_comparing_different_types_with_same_member_for_equality_with_actual_as_subject
{
static TypeWithString2 _actual;
static Exception _exception;
static ExpectedObject _expected;
Establish context = () =>
{
_expected = new TypeWithString
{
StringProperty = "this is a test"
}.ToExpectedObject();
_actual = new TypeWithString2
{
StringProperty = "this is a test"
};
};
Because of = () => _exception = Catch.Exception(() => _expected.ShouldEqual(_actual));
It should_throw_exception_with_TypeWithString_message = () => _exception.Message.ShouldEqual(
string.Format("For TypeWithString2, expected {0} but found {1}.{2}",
typeof (TypeWithString).FullName,
typeof (TypeWithString2).FullName,
Environment.NewLine));
}
}
|
400e1a78e6e944a8ce24b3822bc52fd95e392c23
|
C#
|
cassiofariasmachado/pi-api
|
/src/Pi.Api/Controllers/GpioController.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Unosquare.RaspberryIO;
using Unosquare.RaspberryIO.Gpio;
using RaspberryPi = Unosquare.RaspberryIO.Pi;
namespace Pi.Api.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class GpioController : ControllerBase
{
// GET api/values/5
[HttpGet("{id}")]
public bool Get(uint id)
{
var pin = GetPin(id);
pin.PinMode = GpioPinDriveMode.Output;
var isOn = pin.Read();
pin.Write(!isOn);
return !isOn;
}
private GpioPin GetPin(uint value)
{
GpioPin pin;
switch (value)
{
case 0:
pin = RaspberryPi.Gpio.Pin00;
break;
case 1:
pin = RaspberryPi.Gpio.Pin01;
break;
case 2:
pin = RaspberryPi.Gpio.Pin02;
break;
case 3:
pin = RaspberryPi.Gpio.Pin03;
break;
case 4:
pin = RaspberryPi.Gpio.Pin04;
break;
case 5:
pin = RaspberryPi.Gpio.Pin05;
break;
case 6:
pin = RaspberryPi.Gpio.Pin06;
break;
case 7:
pin = RaspberryPi.Gpio.Pin07;
break;
case 8:
pin = RaspberryPi.Gpio.Pin08;
break;
case 9:
pin = RaspberryPi.Gpio.Pin09;
break;
case 10:
pin = RaspberryPi.Gpio.Pin10;
break;
case 11:
pin = RaspberryPi.Gpio.Pin11;
break;
case 12:
pin = RaspberryPi.Gpio.Pin12;
break;
case 13:
pin = RaspberryPi.Gpio.Pin13;
break;
case 14:
pin = RaspberryPi.Gpio.Pin14;
break;
case 15:
pin = RaspberryPi.Gpio.Pin15;
break;
case 16:
pin = RaspberryPi.Gpio.Pin16;
break;
case 17:
pin = RaspberryPi.Gpio.Pin17;
break;
case 18:
pin = RaspberryPi.Gpio.Pin18;
break;
case 19:
pin = RaspberryPi.Gpio.Pin19;
break;
case 20:
pin = RaspberryPi.Gpio.Pin20;
break;
case 21:
pin = RaspberryPi.Gpio.Pin21;
break;
case 22:
pin = RaspberryPi.Gpio.Pin22;
break;
case 23:
pin = RaspberryPi.Gpio.Pin23;
break;
case 24:
pin = RaspberryPi.Gpio.Pin24;
break;
case 25:
pin = RaspberryPi.Gpio.Pin25;
break;
case 26:
pin = RaspberryPi.Gpio.Pin26;
break;
case 27:
pin = RaspberryPi.Gpio.Pin27;
break;
case 28:
pin = RaspberryPi.Gpio.Pin28;
break;
case 29:
pin = RaspberryPi.Gpio.Pin29;
break;
case 30:
pin = RaspberryPi.Gpio.Pin30;
break;
case 31:
pin = RaspberryPi.Gpio.Pin31;
break;
default:
throw new ArgumentOutOfRangeException(nameof(value), "Value must be between 0 and 31");
}
return pin;
}
}
}
|
46c7924a8c5b4ec5dc0342fe0a8195d46cf51b85
|
C#
|
Pandinosaurus/C2_Collaboration_V1
|
/Assets/Plugins/DeepMotion/Runtime/DemoScripts/MathUtils_FOP.cs
| 3.140625
| 3
|
using System;
public static class MathUtils_FOP
{
//This function need to be later changed to me more flexible on min max mapping direction
//Remap range, with the option of clamping the output
public static int Remap(int value, int a1, int a2, int b1, int b2, bool clamp = true)
{
int ret = (value - a1) / (a2 - a1) * (b2 - b1) + b1;
if (clamp) { ret = Math.Min(Math.Max(ret, b1), b2); }
return ret;
}
//This function need to be later changed to me more flexible on min max mapping direction
//Remap range, with the option of clamping the output
public static float Remap(float value, float a1, float a2, float b1, float b2, bool clamp = true)
{
float ret = (value - a1) / (a2 - a1) * (b2 - b1) + b1;
if (clamp) { ret = Math.Min(Math.Max(ret, b1), b2); }
return ret;
}
}
|
0b5591521935de84d2a977e835e7acb2e1f4b2d4
|
C#
|
PMinkova/SoftUni-tasks-and-projects
|
/C# Programming Basics/17. Programming Basics Sample Exam - 24 November 2019/01/Problem01.cs
| 3.40625
| 3
|
using System;
namespace _01
{
class Program
{
static void Main(string[] args)
{
double moneyFoodforOneDay = double.Parse(Console.ReadLine());
double moneySouvenirsforOneDay = double.Parse(Console.ReadLine());
double moneyHotelForOneDay = double.Parse(Console.ReadLine());
double totalMoneyForTraveling = 420.0 / 100.0 * 7 * 1.85;
double totalMoneyForsouvenirs = 3 * moneySouvenirsforOneDay;
double totalMoneyForFood = 3 * moneyFoodforOneDay;
double moneyForHotelFirstDay = moneyHotelForOneDay - 0.10 * moneyHotelForOneDay;
double moneyForHotelSecondDay = moneyHotelForOneDay - 0.15 * moneyHotelForOneDay;
double moneyForHotelThirdDay = moneyHotelForOneDay - 0.20 * moneyHotelForOneDay;
double totalMoneyForHotel = moneyForHotelFirstDay + moneyForHotelSecondDay + moneyForHotelThirdDay;
double totalSum = totalMoneyForTraveling + totalMoneyForFood + totalMoneyForsouvenirs + totalMoneyForHotel;
Console.WriteLine($"Money needed: {totalSum:f2}");
}
}
}
|
80ca6ff7e8629105cc5387f7131378929df7b403
|
C#
|
lewismcg/BreakThoseBricks
|
/Assets/Scripts/LevelManager.cs
| 2.640625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelManager : MonoBehaviour {
public GameObject[] bricks;
public int count = 0;
private GameManager gameManager;
public string FinishTime;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
bricks = GameObject.FindGameObjectsWithTag ("Brick");
Debug.Log ("Brick Count: " + bricks.Length);
count = bricks.Length;
if (count == 0) {
Debug.Log ("All bricks are gone!");
//Wait before returning to Main Scene
StartCoroutine(Pause());
}
}
IEnumerator Pause(){
print ("Before Waiting 5 secs");
//Switch Game Manager state
gameManager = GameObject.FindObjectOfType<GameManager>();
gameManager.SwitchState (GameState.Completed);
gameManager.ChangeText ("You Win!");
FinishTime = gameManager.formattedTime;
Debug.Log ("Took " + FinishTime + " to finish the game!");
yield return new WaitForSeconds(5);
//Reload Main Menu
LoadScene(0);
print("After waiting 5 seconds");
}
public void LoadScene(int level){
Application.LoadLevel (level);
}
}
|
43a74eb500a533b868282bbfe37c4977d6abc740
|
C#
|
PreciseNZ/GildedRose-Refactoring-Kata
|
/csharp/GildedRoseTest.cs
| 2.609375
| 3
|
using System.Collections.Generic;
using NUnit.Framework;
namespace csharp
{
[TestFixture]
public class GildedRoseTest
{
[Test]
public void BaseItem_WhenExpired_DecreasesByTwo()
{
var items = new List<Item> {new Item {Name = "Potion", SellIn = 0, Quality = 4}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(2));
}
[Test]
public void BaseItem_WhenNotExpired_DecreasesByOne()
{
var items = new List<Item> {new Item {Name = "Potion", SellIn = 2, Quality = 4}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(3));
}
[Test]
public void BaseItem_ZeroQuality_DoesNotGoNegative()
{
var items = new List<Item> {new Item {Name = "Potion", SellIn = 2, Quality = 0}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(0));
}
[Test]
public void AgedBrie_WhenNotExpired_IncreasesInQualityByOne()
{
var items = new List<Item> {new Item {Name = "Aged Brie", SellIn = 2, Quality = 0}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(1));
}
[Test]
public void AgedBrie_WhenExpired_IncreasesInQualityByTwo()
{
var items = new List<Item> {new Item {Name = "Aged Brie", SellIn = 0, Quality = 0}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(2));
}
[Test]
public void AgedBrie_DoesNotGoAbove50()
{
var items = new List<Item> {new Item {Name = "Aged Brie", SellIn = 5, Quality = 50}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(50));
}
[Test]
public void Sulfuras_Expired_QualityDoesntChange()
{
var items = new List<Item> {new Item {Name = "Sulfuras, Hand of Ragnaros", SellIn = 0, Quality = 80}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(80));
}
[Test]
public void Sulfuras_NotExpired_QualityDoesntChange()
{
var items = new List<Item> {new Item {Name = "Sulfuras, Hand of Ragnaros", SellIn = 2, Quality = 80}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(80));
}
[Test]
public void BackStagePass_ExpiresIn5Days_IncreaseInQualityByThree()
{
var items = new List<Item>
{new Item {Name = "Backstage passes to a TAFKAL80ETC concert", SellIn = 5, Quality = 40}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(43));
}
[Test]
public void BackStagePass_ExpiresIn10Days_IncreaseInQualityByTwo()
{
var items = new List<Item>
{new Item {Name = "Backstage passes to a TAFKAL80ETC concert", SellIn = 10, Quality = 40}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(42));
}
[Test]
public void BackStagePass_ExpiresIn20Days_IncreaseInQualityByOne()
{
var items = new List<Item>
{new Item {Name = "Backstage passes to a TAFKAL80ETC concert", SellIn = 20, Quality = 40}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(41));
}
[Test]
public void BackStagePass_Expired_QualityIsZero()
{
var items = new List<Item>
{new Item {Name = "Backstage passes to a TAFKAL80ETC concert", SellIn = 0, Quality = 40}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(0));
}
[Test]
public void ConjuredManaCake_NotExpired_QualityDecreasesByTwo()
{
var items = new List<Item> {new Item {Name = "Conjured Mana Cake", SellIn = 3, Quality = 6}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(4));
}
[Test]
public void ConjuredManaCake_NotExpiredQuality1_QualityIsZero()
{
var items = new List<Item> {new Item {Name = "Conjured Mana Cake", SellIn = 3, Quality = 1}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(0));
}
[Test]
public void ConjuredManaCake_Expired_QualityDecreasesByFour()
{
var items = new List<Item> {new Item {Name = "Conjured Mana Cake", SellIn = 0, Quality = 6}};
var app = new GildedRose(items);
app.UpdateQuality();
Assert.That(items[0].Quality, Is.EqualTo(2));
}
}
}
|
30d86087a4eb2199b35bfedc72d5a6a7bb2de7c5
|
C#
|
CodeDrivesUs/DurbanlockAssignment
|
/DurbanlockAssignment/Models/DocumentDbRepository.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
namespace DurbanlockAssignment.Models
{
public static class DocumentDBRepository<T> where T : class
{
private static readonly string DatabaseId = "studentdb";
private static readonly string CollectionId = "studentcol";
private static DocumentClient client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);
public static async Task<Item> GetItemAsync(string id)
{
try
{
Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), new RequestOptions { PartitionKey = new PartitionKey(Undefined.Value) });
return (Item)(dynamic)document;
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
else
{
throw;
}
}
}
public static async Task<IEnumerable<Item>> GetItemsAsync(Expression<Func<Item, bool>> predicate)
{
var option = new FeedOptions { EnableCrossPartitionQuery = true };
IDocumentQuery<Item> query = client.CreateDocumentQuery<Item>(
UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
option)
.Where(predicate)
.AsDocumentQuery();
List<Item> results = new List<Item>();
while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<Item>());
}
return results;
}
public static async Task<IEnumerable<Item>> GetItemesAsync()
{
var option = new FeedOptions { EnableCrossPartitionQuery = true };
IDocumentQuery<Item> query = client.CreateDocumentQuery<Item>(
UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
option)
.AsDocumentQuery();
List<Item> results = new List<Item>();
while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<Item>());
}
return results;
}
public static async Task<IEnumerable<Item>> SearchAsync(string search)
{
var option = new FeedOptions { EnableCrossPartitionQuery = true };
List<Item> results = new List<Item>();
IDocumentQuery<Item> query = client.CreateDocumentQuery<Item>(
UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
option)
.Where(x => x.FirstName == search ||x.LastName==search|| x.StudentNum==search|| x.EmailAddress==search||x.PhoneNumber==search)
.AsDocumentQuery();
while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<Item>());
}
return results;
}
public static async Task<IEnumerable<Item>> Search2Async(string search)
{
var option = new FeedOptions { EnableCrossPartitionQuery = true };
List<Item> results = new List<Item>();
IDocumentQuery<Item> query = client.CreateDocumentQuery<Item>(
UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
option)
.Where(x => x.StudentNum == search)
.AsDocumentQuery();
while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<Item>());
}
return results;
}
public static async Task<Document> CreateItemAsync(Item item)
{
return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), item);
}
public static async Task<Document> UpdateItemAsync(string id, T item)
{
return await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), item);
}
public static async Task DeleteItemAsync(string id)
{
await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), new RequestOptions { PartitionKey = new PartitionKey(Undefined.Value) });
}
public static void Initialize()
{
client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);
CreateDatabaseIfNotExistsAsync().Wait();
CreateCollectionIfNotExistsAsync().Wait();
}
private static async Task CreateDatabaseIfNotExistsAsync()
{
try
{
await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
await client.CreateDatabaseAsync(new Database { Id = DatabaseId });
}
else
{
throw;
}
}
}
//public static bool valideate(string stud)
//{
// var option = new FeedOptions { EnableCrossPartitionQuery = true };
// List<Item> results = new List<Item>();
// IDocumentQuery<Item> query = client.CreateDocumentQuery<Item>(
// UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
// option)
// .Where(x => x.StudentNum == stud)
// .AsDocumentQuery();
// while (query.HasMoreResults)
// {
// results.AddRange( query.ExecuteNextAsync<Item>());
// }
// return true;
//}
private static async Task CreateCollectionIfNotExistsAsync()
{
try
{
await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId));
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
await client.CreateDocumentCollectionAsync(
UriFactory.CreateDatabaseUri(DatabaseId),
new DocumentCollection { Id = CollectionId },
new RequestOptions { OfferThroughput = 1000 });
}
else
{
throw;
}
}
}
}
}
|
86a6b3cc94e1aa7e63eabdc880d54dd562a99bf0
|
C#
|
Babelz/blackjack-sharp
|
/src/Blackjack-Sharp/Card.cs
| 3.6875
| 4
|
namespace Blackjack_Sharp
{
/// <summary>
/// Class that represents a standard French playing card defined by it's
/// suit and face.
/// </summary>
public sealed class Card
{
#region Properties
/// <summary>
/// Gets the face of the card.
/// </summary>
public CardFace Face
{
get;
}
/// <summary>
/// Gets the suit of the card.
/// </summary>
public CardSuit Suit
{
get;
}
#endregion
public Card(CardFace face, CardSuit suit)
{
Face = face;
Suit = suit;
}
public sealed override string ToString()
{
var prefix = char.ToUpper(Suit.ToString()[0]);
var suffix = (Face) switch
{
CardFace.Ace => "ace",
CardFace.Jack => "jack",
CardFace.Queen => "queen",
CardFace.King => "king",
_ => ((byte)Face).ToString(),
};
return $"{prefix}-{suffix}";
}
}
}
|
d99af961a1949900bd184eeab7563dd48adcfbbd
|
C#
|
TheOnlyGithubEnjoyer/Quiz
|
/Program.cs
| 3.296875
| 3
|
using System;
WriteCentered("QUIZ (PRESS ENTER TO START)");
Console.ReadLine();
static void WriteCentered(string text)
{
// string text = "Hello world!";
int numberOfSpaces = Console.WindowWidth / 2 - text.Length /2;
int i = 0;
while (i < numberOfSpaces)
{
i++;
Console.Write(" ");
}
Console.WriteLine(text);
}
Console.WriteLine("First Question! What is the Capital of England? a) London b) Paris c) Rome");
string answer = Console.ReadLine();
answer = answer.ToLower();
int points = 0;
if (answer == "a" || answer == "london") {
points = points + 1;
Console.WriteLine("Yay you got it right! " + "Points = " + points + " (PRESS ENTER TO CONTINUE)");
}
else {
Console.WriteLine("You got it wrong! " + "Points = " + points + " (PRESS ENTER TO CONTINUE)");
}
Console.ReadLine();
Console.WriteLine("Second Question! Which object is yellow? a) Stove b) Banana c) Palm tree");
string answer2 = Console.ReadLine();
answer2 = answer2.ToLower();
if (answer2 == "b" || answer2 == "banana") {
points = points +1;
Console.WriteLine("You got it right! " + "Points = " + points + " (PRESS ENTER TO CONTINUE)");
}
else {
Console.WriteLine("Man how did you get that wrong? " + "Points = " + points + " (PRESS ENTER TO CONTINUE)");
}
Console.ReadLine();
Console.WriteLine("Third Question! What is the tallest building in the world? a) Empire state building b) Burj Khalifa c) Shanghai Tower");
string answer3 = Console.ReadLine();
answer3 = answer3.ToLower();
if (answer3 == "b")
{
points = points +1;
Console.WriteLine("Congrats! You got the right answer. " + "Points = " + points + " (PRESS ENTER TO CONTINUE)");
}
else {
Console.WriteLine("You got it wrong. " + "Points = " + points + " (PRESS ENTER TO CONTINUE)");
}
Console.ReadLine();
Console.WriteLine("Fourth and final Question! Points are TRIPLED! Which movie was made by Christopher Nolan? a) Interstellar b) Inception c) Memento");
string answer4 = Console.ReadLine();
answer4 = answer4.ToLower();
if (answer4 == "all three" || answer4 == "a, b and c" || answer4 == "abc") {
points = points +3;
Console.WriteLine("Good Job! You got the final question right " + "Final Points = " + points + " (PRESS ENTER TO CONTINUE)");
}
else {
Console.WriteLine("Come on! You should know that it was a trick question. " + "Final Points = " + points + " / 6" + " (PRESS ENTER TO CONTINUE)");
}
Console.ReadLine();
|
cbb16578bff4801405b28a0e1a158468e1b71897
|
C#
|
Birdistheword/BeeeHave
|
/BeeeHave/Assets/Scripts/Flower/FlowerSpawner.cs
| 2.53125
| 3
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class FlowerSpawner : MonoBehaviour
{
[SerializeField] int xRange = 100;
[SerializeField] int yRange = 100;
[SerializeField] int xspawnDistance;
[SerializeField] int zspawnDistance;
[SerializeField] GameObject flowerSpawnPointPrefab;
[SerializeField] GameObject[,] flowerSpawnPoints;
[SerializeField] List<FlowerSpawnPoint> flowerPointList;
[SerializeField] GameObject flowerPrefab;
GameObject flowerSpawnPoint;
[SerializeField] float flowerSpawnHeight = 1;
int flowerCount;
bool flowersMaxed = false;
public void SpawnFlower(GameObject flowerPrefab)
{
int i = Random.Range(-1, flowerPointList.Count);
if (i < 0)
{
return;
}
Instantiate(flowerPrefab, flowerPointList[i].transform.position, Quaternion.identity);
flowerCount++;
if (flowerCount == xRange * yRange)
{
print("max Amount of flowers reached");
flowersMaxed = true;
}
flowerPointList.Remove(flowerPointList[i]);
}
public bool FlowersMaxed()
{
return flowersMaxed;
}
public int GetFlowerCount()
{
return flowerCount;
}
private void Start()
{
flowerSpawnPoints = new GameObject[xRange, yRange];
SpawnFlowerPoints();
for (int i = 0; i < 3; i++)
{
SpawnFlower(flowerPrefab);
}
}
private void SpawnFlowerPoints()
{
for (int i = 0; i < xRange; i++)
{
for (int j = 0; j < yRange; j++)
{
flowerSpawnPoints[i, j] = flowerSpawnPointPrefab;
flowerSpawnPoint = Instantiate(flowerSpawnPoints[i, j], new Vector3(i * xspawnDistance, flowerSpawnHeight, j * zspawnDistance), Quaternion.identity);
flowerPointList.Add(flowerSpawnPoint.GetComponent<FlowerSpawnPoint>());
}
}
}
}
|
3f4ab2d825296d884e8e88d29082baeafe30e68c
|
C#
|
Leaktor/TetrisWinForm
|
/TetrisWinForm/Cell.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace TetrisWinForm
{
class Cell
{
int cellsize = 25;
int filledcellsize = 20;
int startpointy;
int startpointx;
SolidBrush color;
Graphics g;
public Cell(Color color, Graphics g)
{
this.color = new SolidBrush(color);
this.g = g;
}
private Point[] points()
{
Point p1 = new Point(startpointy * cellsize, startpointx * cellsize);
Point p2 = new Point(startpointy * cellsize + filledcellsize, startpointx * cellsize);
Point p3 = new Point(startpointy * cellsize, startpointx * cellsize + filledcellsize);
Point p4 = new Point(startpointy * cellsize + filledcellsize, startpointx * cellsize + filledcellsize);
return new Point[] { p1, p3, p4, p2 };
}
public void getCell(int startpointx, int startpointy)
{
this.startpointy = startpointy;
this.startpointx = startpointx;
g.FillPolygon(color, points());
}
}
}
|
f63bc4a19cf497db679b3b732a8ff2706c5c7747
|
C#
|
shendongnian/download4
|
/code5/803829-33040314-101460585-2.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
namespace ExampleNameSpace
{
[Cmdlet(VerbsCommon.Get, "Something")]
[OutputType("PSCustomObject")]
public class GetSomething : PSCmdlet
{
public enum ExampleEnum { A, B, C };
[Parameter(
HelpMessage = "Enter A, B, or C.",
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = true
)]
public ExampleEnum ExampleParameter { get; set; }
protected override void ProcessRecord()
{
WriteObject(ExampleParameter);
switch (ExampleParameter)
{
case ExampleEnum.A:
WriteObject("Case A");
break;
case ExampleEnum.B:
WriteObject("Case B");
break;
case ExampleEnum.C:
WriteObject("Case C");
break;
default:
break;
}
}
}
}
|
96ede70705bf50849b22c4ec8a176c0b610361a7
|
C#
|
unzueta/guineu
|
/Source/Guineu.Runtime.Desktop/Functions/UPPER.cs
| 2.671875
| 3
|
using Guineu.Expression;
namespace Guineu.Functions
{
class UPPER : FunctionBase
{
override internal void Compile(Compiler comp)
{
GetParameters(comp, 1);
}
override internal Variant GetVariant(CallingContext context)
{
if (Param[0].CheckString(context, false))
return new Variant(VariantType.Character, true);
return new Variant(Param[0].GetString(context).ToUpper(System.Globalization.CultureInfo.InvariantCulture));
}
}
}
|
3d1656590e14f264d1ad6f5800c46ec8236d4a6f
|
C#
|
tungvodoi/Vtc-Freelancer
|
/Services/RequestService.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Vtc_Freelancer.Models;
namespace Vtc_Freelancer.Services
{
public class RequestService
{
private MyDbContext dbContext;
public RequestService(MyDbContext dbContext)
{
this.dbContext = dbContext;
}
public bool CreateRequest(int? UserId, string inputRequest, string category, string SubCategory, string inputDeliveredTime, double inputBudget, string urlFile)
{
try
{
Request req = new Request();
req.Description = inputRequest;
req.DeliveredTime = inputDeliveredTime;
req.Budget = inputBudget;
req.Category = category;
req.SubCategory = SubCategory;
req.LinkFile = urlFile;
req.TimeCreate = DateTime.Now;
req.QuantityOffers = 0;
req.Status = 0;
req.UserId = UserId;
dbContext.Add(req);
dbContext.SaveChanges();
return true;
}
catch (System.Exception ex)
{
Console.WriteLine("Error : " + ex.Message);
return false;
}
}
public Request getRequestByRequestId(int? requestId)
{
return dbContext.Request.FirstOrDefault(x => x.RequestId == requestId);
}
public List<Request> getListRequestByUserId(int userId)
{
return dbContext.Request.Where(x => x.UserId == userId).ToList();
}
public List<Request> getListRequestByCategory(List<Category> listCategory)
{
if (listCategory.Count > 0)
{
List<Request> listRequest = new List<Request>();
foreach (var item in listCategory)
{
List<Request> SubListRequest = dbContext.Request.Where(x => x.Category == item.CategoryName).ToList();
listRequest.AddRange(SubListRequest);
}
return listRequest;
}
return null;
}
public List<Offer> GetOffersByRequestId(int? requestId)
{
List<Offer> offers = new List<Offer>();
offers = dbContext.Offer.Where(x => x.RequestId == requestId).ToList();
return offers;
}
// public List<Service> GetServiceByRequestId(int? requestId)
// {
// List<Service> services = new List<Service>();
// services = dbContext.
// }
public List<Request> GetRequestByUserId(int? userId)
{
List<Request> requests = new List<Request>();
requests = dbContext.Request.Where(x => x.UserId == userId).ToList();
return requests;
}
}
}
|
2741b3872fe9c02095b165a4ff6e549b39057358
|
C#
|
michaelmahung/Roguebeat
|
/RogueBeat/Assets/Scripts/Bosses/TileBoss/Tiles/TileAttacks/GridAttack.cs
| 2.734375
| 3
|
public class GridAttack : TileAttack
{
bool gridSwitch;
int totalLoops;
public override void Attack(TileController.OnAttackFinished listener, BossTiles[,] tiles)
{
allTiles = tiles;
_listener = listener;
tileGridSize = tiles.GetLength(0);
SetValues();
currentState = TileAttackStates.Active;
GridAttackLogic(0);
}
protected override void SetValues()
{
totalLoops = 0;
}
void GridAttackLogic(int index)
{
if (index > tileGridSize - 1)
{
currentState = TileAttackStates.Buffer;
return;
}
int i = 0;
if (gridSwitch)
{
i = 1;
}
while (i < tileGridSize)
{
ActivateTile(allTiles, i, index);
i += 2;
}
gridSwitch = !gridSwitch;
totalLoops++;
GridAttackLogic(index + 1);
return;
}
void Update()
{
switch (currentState)
{
case TileAttackStates.Default:
break;
case TileAttackStates.Idle:
break;
case TileAttackStates.Active:
break;
case TileAttackStates.Buffer:
BufferLoop();
break;
default:
break;
}
}
}
|
b5a6ee8aedd5aa77b0936671b696c9abfc7f96a1
|
C#
|
jeremiahflaga/simple-shape-REST-api
|
/ShapesApi/Shapes.Api/Controllers/Shapes/ShapeViewModelFactory.cs
| 3.078125
| 3
|
using Shapes.Domain.Model;
using Shapes.Domain.Model.Shapes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Shapes.Api.Controllers.Shapes
{
public static class ShapeViewModelFactory
{
public static ShapeViewModel CreateFrom(Shape shape)
{
if (shape.GetType() == typeof(Line))
{
var line = (Line)shape;
return new LineViewModel
{
Id = shape.Id.Value.ToString(),
Type = shape.Type.Name.ToLower(),
Length = line.Length,
Area = shape.ComputeArea(),
Perimeter = shape.ComputePerimeter()
};
}
else if (shape.GetType() == typeof(Circle))
{
var circle = (Circle)shape;
return new CircleViewModel
{
Id = shape.Id.Value.ToString(),
Type = shape.Type.Name.ToLower(),
Radius = circle.Radius,
Circumference = circle.ComputeCircumference(),
Area = shape.ComputeArea()
};
}
else if (shape.GetType() == typeof(Square))
{
var square = (Square)shape;
return new SquareViewModel
{
Id = shape.Id.Value.ToString(),
Type = shape.Type.Name.ToLower(),
Side = square.Side,
Perimeter = shape.ComputePerimeter(),
Area = shape.ComputeArea()
};
}
else if (shape.GetType() == typeof(Rectangle))
{
var rectangle = (Rectangle)shape;
return new RectangleViewModel
{
Id = shape.Id.Value.ToString(),
Type = shape.Type.Name.ToLower(),
Length = rectangle.Length,
Width = rectangle.Width,
Perimeter = shape.ComputePerimeter(),
Area = shape.ComputeArea()
};
}
return new ShapeViewModel();
}
//public static ShapeViewModelDynamic CreateDynamicFrom(Shape shape)
//{
// dynamic vm = new ShapeViewModelDynamic();
// vm.Id = shape.Id.Value.ToString();
// vm.Type = shape.Type.Name.ToLower();
// vm.Area = shape.ComputeArea();
// vm.Perimeter = shape.ComputePerimeter();
// if (shape.GetType() == typeof(Line))
// {
// var line = (Line)shape;
// vm.Length = line.Length;
// }
// else if (shape.GetType() == typeof(Circle))
// {
// var circle = (Circle)shape;
// vm.Radius = circle.Radius;
// vm.Circumference = circle.ComputeCircumference();
// }
// else if (shape.GetType() == typeof(Square))
// {
// var square = (Square)shape;
// vm.Side = square.Side;
// }
// else if (shape.GetType() == typeof(Rectangle))
// {
// var rectangle = (Rectangle)shape;
// vm.Length = rectangle.Length;
// vm.Width = rectangle.Width;
// }
// return vm;
//}
}
}
|
20ce44d0b6d884306552895bc7be8cb3ae527349
|
C#
|
jgglg/Razor
|
/src/Microsoft.AspNet.Razor/TagHelpers/TagHelperDesignTimeDescriptor.cs
| 2.546875
| 3
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Razor.TagHelpers
{
/// <summary>
/// A metadata class containing design time information about a tag helper.
/// </summary>
public class TagHelperDesignTimeDescriptor
{
/// <summary>
/// Instantiates a new instance of <see cref="TagHelperDesignTimeDescriptor"/>.
/// </summary>
/// <param name="summary">A summary on how to use a tag helper.</param>
/// <param name="remarks">Remarks on how to use a tag helper.</param>
/// <param name="outputElementHint">The HTML element a tag helper may output.</param>
public TagHelperDesignTimeDescriptor(string summary, string remarks, string outputElementHint)
{
Summary = summary;
Remarks = remarks;
OutputElementHint = outputElementHint;
}
/// <summary>
/// A summary of how to use a tag helper.
/// </summary>
public string Summary { get; }
/// <summary>
/// Remarks about how to use a tag helper.
/// </summary>
public string Remarks { get; }
/// <summary>
/// The HTML element a tag helper may output.
/// </summary>
/// <remarks>
/// In IDEs supporting IntelliSense, may override the HTML information provided at design time.
/// </remarks>
public string OutputElementHint { get; }
}
}
|
743a85dca0f8da34a74f2b7770cc999ddf4175d9
|
C#
|
NewVoxel/Project-Euler
|
/ProjectEulerSolutions/Problem005.cs
| 4
| 4
|
using System;
using System.Diagnostics;
namespace ProjectEulerSolutions
{
/// <summary>
/// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
/// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
/// </summary>
class Problem005
{
public void run()
{
//Create a stopwatch to calculate how long program takes to execute
var watch = Stopwatch.StartNew();
//Loop through numbers in increments of 20 until conditions are met
//Use 20 because it has to be divided by this amount so we may awell
//save ourselves from iterating over 19 pointless steps
for(int i = 20; true; i+=20)
{
//If current number is divisible by numbers 1-20 leave the loop
//No need to check numbers 1-10 since if they are divisible by
//Numbers 11-20 we already know they are
if ((i % 11) == 0 && (i % 12) == 0 && (i % 13) == 0 && (i % 14) == 0
&& (i % 15) == 0 && (i % 16) == 0 && (i % 17) == 0 && (i % 18) == 0
&& (i % 19) == 0 && (i % 20) == 0)
{
Console.Out.WriteLine("The smallest number that is evenly divisible by numbers 1-20 is : " + i);
break;
}
}
//Display time taken to execute program
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.Out.Write("Program completed in : " + elapsedMs + "ms");
}
}
}
|
bccbb76853a8e9d50ba771a808b7bc611bd483bc
|
C#
|
Chillisoft/splunk4net
|
/source/splunk4net/StringExtensions.cs
| 2.8125
| 3
|
using System.Text.RegularExpressions;
namespace splunk4net
{
// kudos to mindplay.dk, http://stackoverflow.com/questions/188892/glob-pattern-matching-in-net
// provides a shim for simple glob matching to Regex
public static class StringExtensions
{
public static bool Like(this string str, string pattern)
{
return new Regex(
"^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
RegexOptions.IgnoreCase | RegexOptions.Singleline
).IsMatch(str);
}
}
}
|
0271b76f8489a02c4f65032c37ef4ab1c17c13f5
|
C#
|
carloscadena/Data-Structures-and-Algorithms
|
/Data-Structures/BinaryTree/BinaryTree/Classes/BinarySearchTree.cs
| 3.625
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BinaryTree.Classes
{
public class BinarySearchTree
{
public Node Root { get; set; }
public BinarySearchTree(Node node)
{
Root = node;
}
public int Search(int num)
{
Node curr = Root;
while (curr != null)
{
if (curr.Value == num) return curr.Value;
if (curr.Value < num) curr = curr.LChild;
if (curr.Value > num) curr = curr.RChild;
}
return -1;
}
public string Add(Node node)
{
Node curr = Root;
while (curr != null)
{
if (node.Value >= curr.Value)
{
if (curr.RChild == null)
{
curr.RChild = node;
return "Node Successfully Added";
}
else curr = curr.RChild;
}
else if (node.Value < curr.Value)
{
if (curr.LChild == null)
{
curr.LChild = node;
return "Node successfully added";
}
else curr = curr.LChild;
}
}
return "Node succesfully added";
}
}
}
|
a5afdd61c017292e490da698aea9781c64ecaa77
|
C#
|
shendongnian/download4
|
/code9/1641938-46416703-156988145-2.cs
| 2.859375
| 3
|
public class MyColor{
public MyColor(string color, float maxSize){
Color = color;
MaxSize = maxsize;
}
public string Color { get; }
public float MaxSize { get; }
}
|
e1b1066c7cc3a00945eb590986aa6a24bf13b77a
|
C#
|
dotnetcore/Util
|
/src/Util.Core/Helpers/File.cs
| 3.09375
| 3
|
namespace Util.Helpers;
/// <summary>
/// 文件流操作
/// </summary>
public static class File {
#region ToBytes
/// <summary>
/// 流转换为字节数组
/// </summary>
/// <param name="stream">流</param>
public static byte[] ToBytes( Stream stream ) {
stream.Seek( 0, SeekOrigin.Begin );
var buffer = new byte[stream.Length];
stream.Read( buffer, 0, buffer.Length );
return buffer;
}
/// <summary>
/// 字符串转换成字节数组
/// </summary>
/// <param name="data">数据,默认字符编码utf-8</param>
public static byte[] ToBytes( string data ) {
return ToBytes( data, Encoding.UTF8 );
}
/// <summary>
/// 字符串转换成字节数组
/// </summary>
/// <param name="data">数据</param>
/// <param name="encoding">字符编码</param>
public static byte[] ToBytes( string data, Encoding encoding ) {
if ( string.IsNullOrWhiteSpace( data ) )
return new byte[] { };
return encoding.GetBytes( data );
}
#endregion
#region ToBytesAsync
/// <summary>
/// 流转换为字节数组
/// </summary>
/// <param name="stream">流</param>
/// <param name="cancellationToken">取消令牌</param>
public static async Task<byte[]> ToBytesAsync( Stream stream, CancellationToken cancellationToken = default ) {
stream.Seek( 0, SeekOrigin.Begin );
var buffer = new byte[stream.Length];
await stream.ReadAsync( buffer, 0, buffer.Length, cancellationToken );
return buffer;
}
#endregion
#region ToStream
/// <summary>
/// 字符串转换成流
/// </summary>
/// <param name="data">数据</param>
public static Stream ToStream( string data ) {
return ToStream( data, Encoding.UTF8 );
}
/// <summary>
/// 字符串转换成流
/// </summary>
/// <param name="data">数据</param>
/// <param name="encoding">字符编码</param>
public static Stream ToStream( string data, Encoding encoding ) {
if ( data.IsEmpty() )
return Stream.Null;
return new MemoryStream( ToBytes( data, encoding ) );
}
#endregion
#region ExistsByFile
/// <summary>
/// 判断文件是否存在
/// </summary>
/// <param name="path">文件绝对路径</param>
public static bool ExistsByFile( string path ) {
return System.IO.File.Exists( path );
}
#endregion
#region ExistsByDirectory
/// <summary>
/// 判断目录是否存在
/// </summary>
/// <param name="path">目录绝对路径</param>
public static bool ExistsByDirectory( string path ) {
return Directory.Exists( path );
}
#endregion
#region CreateDirectory
/// <summary>
/// 创建目录
/// </summary>
/// <param name="path">文件或目录绝对路径</param>
public static void CreateDirectory( string path ) {
if ( path.IsEmpty() )
return;
var file = new FileInfo( path );
var directoryPath = file.Directory?.FullName;
if ( Directory.Exists( directoryPath ) )
return;
Directory.CreateDirectory( directoryPath );
}
#endregion
#region ReadToString
/// <summary>
/// 读取文件到字符串
/// </summary>
/// <param name="filePath">文件绝对路径</param>
public static string ReadToString( string filePath ) {
return ReadToString( filePath, Encoding.UTF8 );
}
/// <summary>
/// 读取文件到字符串
/// </summary>
/// <param name="filePath">文件绝对路径</param>
/// <param name="encoding">字符编码</param>
public static string ReadToString( string filePath, Encoding encoding ) {
if( System.IO.File.Exists( filePath ) == false )
return string.Empty;
using var reader = new StreamReader( filePath, encoding );
return reader.ReadToEnd();
}
#endregion
#region ReadToStringAsync
/// <summary>
/// 读取文件到字符串
/// </summary>
/// <param name="filePath">文件绝对路径</param>
public static async Task<string> ReadToStringAsync( string filePath ) {
return await ReadToStringAsync( filePath, Encoding.UTF8 );
}
/// <summary>
/// 读取文件到字符串
/// </summary>
/// <param name="filePath">文件绝对路径</param>
/// <param name="encoding">字符编码</param>
public static async Task<string> ReadToStringAsync( string filePath, Encoding encoding ) {
if( System.IO.File.Exists( filePath ) == false )
return string.Empty;
using var reader = new StreamReader( filePath, encoding );
return await reader.ReadToEndAsync();
}
#endregion
#region ReadToStream
/// <summary>
/// 读取文件流
/// </summary>
/// <param name="filePath">文件绝对路径</param>
public static Stream ReadToStream( string filePath ) {
return new FileStream( filePath, FileMode.Open );
}
#endregion
#region ReadToBytes
/// <summary>
/// 将文件读取到字节流中
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static byte[] ReadToBytes( string filePath ) {
if ( !System.IO.File.Exists( filePath ) )
return null;
var fileInfo = new FileInfo( filePath );
using var reader = new BinaryReader( fileInfo.Open( FileMode.Open ) );
return reader.ReadBytes( (int)fileInfo.Length );
}
#endregion
#region Write
/// <summary>
/// 将字符串写入文件
/// </summary>
/// <param name="filePath">文件绝对路径</param>
/// <param name="content">内容</param>
public static void Write( string filePath, string content ) {
Write( filePath, Convert.ToBytes( content ) );
}
/// <summary>
/// 将字节流写入文件
/// </summary>
/// <param name="filePath">文件绝对路径</param>
/// <param name="content">内容</param>
public static void Write( string filePath, byte[] content ) {
if( string.IsNullOrWhiteSpace( filePath ) )
return;
if( content == null )
return;
CreateDirectory( filePath );
System.IO.File.WriteAllBytes( filePath, content );
}
#endregion
#region WriteAsync
/// <summary>
/// 将字符串写入文件
/// </summary>
/// <param name="filePath">文件绝对路径</param>
/// <param name="content">内容</param>
public static async Task WriteAsync( string filePath, string content ) {
await WriteAsync( filePath, Convert.ToBytes( content ) );
}
/// <summary>
/// 将字节流写入文件
/// </summary>
/// <param name="filePath">文件绝对路径</param>
/// <param name="content">内容</param>
public static async Task WriteAsync( string filePath, byte[] content ) {
if( string.IsNullOrWhiteSpace( filePath ) )
return;
if( content == null )
return;
CreateDirectory( filePath );
await System.IO.File.WriteAllBytesAsync( filePath, content );
}
#endregion
#region Delete
/// <summary>
/// 删除文件
/// </summary>
/// <param name="filePaths">文件绝对路径集合</param>
public static void Delete( IEnumerable<string> filePaths ) {
foreach( var filePath in filePaths )
Delete( filePath );
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="filePath">文件绝对路径</param>
public static void Delete( string filePath ) {
if( string.IsNullOrWhiteSpace( filePath ) )
return;
if( System.IO.File.Exists( filePath ) )
System.IO.File.Delete( filePath );
}
#endregion
#region GetAllFiles
/// <summary>
/// 获取全部文件,包括所有子目录
/// </summary>
/// <param name="path">目录路径</param>
/// <param name="searchPattern">搜索模式</param>
public static List<FileInfo> GetAllFiles( string path,string searchPattern ) {
return Directory.GetFiles( path, searchPattern, SearchOption.AllDirectories )
.Select( filePath => new FileInfo( filePath ) ).ToList();
}
#endregion
}
|
49b0c5590135dc3503ac4b5874e7f028b8918386
|
C#
|
kaloqnkolev555/xml-generator
|
/src/KPMG.XmlGenerator.Core/Extensions/SqlDatabaseTypeSizeAttribute.cs
| 2.890625
| 3
|
namespace KPMG.XmlGenerator.Core.Extensions
{
using System;
/// <summary>
/// SqlDatabaseTypeSizeAttribute class
/// </summary>
/// <seealso cref="System.Attribute" />
[AttributeUsage(AttributeTargets.Property)]
public class SqlDatabaseTypeSizeAttribute : Attribute
{
private readonly int size;
/// <summary>
/// Initializes a new instance of the <see cref="SqlDatabaseTypeSizeAttribute"/> class.
/// </summary>
/// <param name="size">The size.</param>
public SqlDatabaseTypeSizeAttribute(int size)
{
this.size = size;
}
/// <summary>
/// Gets the size.
/// </summary>
/// <value>
/// The size.
/// </value>
public virtual int Size
{
get { return size; }
}
}
}
|
3f9322649355f7a086c8a828d1a8abb0d83d3f98
|
C#
|
DmitryZinchenko/blog-WrappedHttpActionResult
|
/Acme.Web/Api/Controllers/CalcController.cs
| 2.609375
| 3
|
using System;
using System.Web.Http;
using Acme.Web.Api.Helpers;
using Acme.Web.Domain;
namespace Acme.Web.Api.Controllers
{
public class CalcController : ApiController
{
private readonly ICalcEngine _calcEngine;
public CalcController(ICalcEngine calcEngine)
{
_calcEngine = calcEngine;
}
[HttpGet, Route("api/calc/a/{value}")]
public IHttpActionResult CalcAValue(int value)
{
return Ok(_calcEngine.Calc(value));
}
[HttpGet, Route("api/calc/b/{value}")]
public IHttpActionResult CalcBValue(int value)
{
try
{
return Ok(_calcEngine.Calc(value));
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpGet, Route("api/calc/c/{value}")]
public IHttpActionResult CalcCValue(int value)
{
try
{
return Ok(_calcEngine.Calc(value));
}
catch (Exception ex)
{
return InternalServerError(ex).With("Internal Server Error: Check your calculation!");
}
}
}
}
|
012223eb45814581da7efa8813a3bbba78698b60
|
C#
|
slavisharper/DictionariesHashTablesAndSets
|
/Phonebook/TextReader.cs
| 3.484375
| 3
|
namespace Phonebook
{
using System.Collections.Generic;
using System.IO;
public class TextReader
{
private StreamReader reader;
private List<string> textLines;
private string path;
public TextReader(string path)
{
this.path = path;
}
public string Path { get; set; }
public string[] GetLines()
{
this.reader = new StreamReader(this.path);
this.textLines = new List<string>();
using (reader)
{
string line = reader.ReadLine();
while (line != null)
{
this.textLines.Add(line);
line = reader.ReadLine();
}
}
return this.textLines.ToArray();
}
public string GetFullText()
{
string fullText = string.Empty;
this.reader = new StreamReader(this.path);
using (reader)
{
fullText = reader.ReadToEnd();
}
return fullText;
}
}
}
|
9c5d16ea1017096e3ce798c8abf8f36ef771fbfe
|
C#
|
AtiBahrani/CompareIT
|
/Blazor Tier I/Blazor Tier I/WebApplication/Data/Wishlist.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication.Data
{
public class Wishlist
{
public Wishlist()
{
AddWish (new UserWish { ID = "claire", Title = "Claire", URL = "the link is that" });
}
public string Username { get; set; } = "";
public List<UserWish> wishlist { get; set; } = new List<UserWish>();
public void AddWish(UserWish wish)
{
wishlist.Add(wish);
}
public void DeleteWish(UserWish wish)
{
wishlist.Remove(wish);
}
}
}
|
9fdf4144cdbdf9fe5b6c934398fcb6522217fcc0
|
C#
|
rtstreinamentos/git-remote-add-origin-https---github.com-renatoadsumus-aplicacao
|
/Reference/DynamicData/Futures/Attributes/.svn/text-base/LocalizedDisplayNameAttribute.cs.svn-base
| 2.578125
| 3
|
using System.ComponentModel;
using System;
namespace Microsoft.Web.DynamicData {
public class LocalizedDisplayNameAttribute : DisplayNameAttribute {
private ResourceProxy ResourceProxy { get; set; }
public LocalizedDisplayNameAttribute(Type resourceManager, String resource)
: base("Need to localize") {
ResourceProxy = new ResourceProxy(resourceManager, resource);
}
public override string DisplayName {
get {
return ResourceProxy.GetResource();
}
}
}
}
|
22cf5ef7ef0be09b232678d300a5099b094c2de5
|
C#
|
flame78/TelerikAcademy
|
/HQC/Exam/Computers-problem/Computers.Tests/Computers.Motherboar.SquareNumber.Test.cs
| 2.703125
| 3
|
namespace Computers.Tests
{
using System;
using Computers.Lib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var vc = new Mock<IVideoCard>();
string result;
vc.Setup(h => h.Draw(It.IsAny<string>())).Callback<string>(r => result = r);
var motherboard = new Motherboard(2, 32, new Ram(1), vc.Object);
motherboard.SaveRamValue(1000);
motherboard.SquareNumber();
Assert.IsTrue(true);
}
}
}
|
29d2d996a06952fa073bee81d875495de2f1be9b
|
C#
|
FooKittens/Team_Practice
|
/Teamcollab/Teamcollab/Engine/WorldManagement/Cluster.cs
| 2.5625
| 3
|
using Teamcollab.Engine.Helpers;
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Teamcollab.Resources;
using System.Runtime.InteropServices;
namespace Teamcollab.Engine.WorldManagement
{
public enum ClusterType : byte
{
Undefined = 0,
Evergreen,
}
[Serializable]
public struct ClusterData
{
public ClusterType Type;
public Tile[] Tiles;
public Coordinates Coordinates;
}
/// <summary>
/// Handles a collection of Tiles
/// </summary>
[Serializable]
public class Cluster
{
#region Properties
public long HashCode { get; private set; }
public ClusterType Type { get; private set; }
public bool Active { get; private set; }
public bool Loaded { get; private set; }
#endregion
#region Members
private Tile[] tiles;
public Coordinates Coordinates;
#endregion
static ResourceCollection<Texture2D> tileTextures;
// Static Constructor for loading tiletextures initially.
static Cluster()
{
tileTextures = ResourceManager.TileTextureBank;
}
public Cluster(ClusterType type, int x, int y)
{
Type = type;
tiles = new Tile[Constants.ClusterWidth * Constants.ClusterHeight];
Active = false;
Coordinates = new Coordinates(x, y);
HashCode = GetHashCode();
}
public Cluster(ClusterType type, Coordinates coordinates)
:this(type, coordinates.X, coordinates.Y) { }
public Cluster(ClusterData data)
{
Type = data.Type;
tiles = data.Tiles;
Coordinates = data.Coordinates;
SetHashCode();
Active = false;
}
public void Unload()
{
Loaded = false;
tiles = null;
squareRes = null;
}
public void Load(ClusterData data)
{
if (HashCode != GetHashFromXY(data.Coordinates.X, data.Coordinates.Y))
{
throw new Exception("Data does not match the cluster");
}
squareRes = ResourceManager.TileTextureBank.Query("Grass");
tiles = data.Tiles;
SetHashCode();
}
// TODO REMOVE
Resource<Texture2D> squareRes;
Resource<Texture2D> grassRes;
public void Draw(SpriteBatch spriteBatch)
{
// TODO REMOVE
if (squareRes == null)
{
squareRes = tileTextures.Query("Square");
grassRes = tileTextures.Query("Grass");
}
for (int y = 0; y < Constants.ClusterHeight; ++y)
{
for (int x = 0; x < Constants.ClusterWidth; ++x)
{
Tile tile = GetTileAt(x, y);
Vector2 tilePos = new Vector2(
x - Constants.ClusterWidth / 2,
y - Constants.ClusterHeight / 2
);
Vector2 drawPos = WorldManager.TransformByCluster(tilePos, Coordinates);
drawPos = WorldManager.GetTileScreenPosition(drawPos);
Resource<Texture2D> texture = tile.Type == TileType.Water ? grassRes : squareRes;
spriteBatch.Draw(texture, drawPos, null, Color.White, 0f, new Vector2(16, 16), 1f, SpriteEffects.None, 0f);
}
}
}
/// <summary>
/// Retrieves the bounding rectangle for a cluster in pixels.
/// </summary>
/// <param name="cluster">Cluster to get bounds from.</param>
public static Rectangle GetClusterBounds(Cluster cluster)
{
// Creates cluster edges with clockwise winding.
Vector2[] vertices = new[] {
new Vector2(-0.5f, -0.5f), // Top Left
new Vector2(0.5f, -0.5f), // Top Right
new Vector2(0.5f, 0.5f), // Bottom Right
new Vector2(-0.5f, 0.5f) // Bottom Left
};
// Matrix for translating into tilespace and then scaling to screen.
// Matrix mat = ClusterTileTransform * TileScreenTransform;
/* Translate all vertices to the correct cluster and transform
* into pixel coordinates. */
for (int i = 0; i < vertices.Length; ++i)
{
vertices[i] += cluster.Coordinates;
vertices[i] = WorldManager.GetClusterScreenCenter(vertices[i]);
//vertices[i] = Vector2.Transform(vertices[i], mat);
}
// Bounding Rectangle.
Rectangle rect = new Rectangle(
(int)vertices[0].X,
(int)vertices[0].Y,
(int)(vertices[1].X - vertices[0].X),
(int)(vertices[2].Y - vertices[1].Y)
);
return rect;
}
public void SetTileAt(int x, int y, Tile newTile)
{
tiles[y * Constants.ClusterWidth + x] = newTile;
}
public void SetTileAt(Coordinates coord, Tile newTile)
{
SetTileAt(coord.X, coord.Y, newTile);
}
/// <summary>
/// Retrieves the tile at the input coordinates relative
/// to the cluster.
/// </summary>
public Tile GetTileAt(int x, int y)
{
return tiles[y * Constants.ClusterWidth + x];
}
/// <summary>
/// Retrieves the tile at the input coordinates relative
/// to the cluster.
/// </summary>
private Tile GetTileAt(Coordinates coord)
{
return GetTileAt(coord.X, coord.Y);
}
public override string ToString()
{
return string.Format("({0}, {1})", Coordinates.X, Coordinates.Y);
}
/// <summary>
/// Tells the Cluster to generate its hashcode.
/// </summary>
public void SetHashCode()
{
HashCode = GetHashFromXY(Coordinates.X, Coordinates.Y);
}
/// <summary>
/// Retrieve a hashcode using the same algorithm as
/// the cluster uses to generate its hashcode from
/// two coordinates.
/// </summary>
public static long GetHashFromXY(int x, int y)
{
long hash = ((long)x << 32) + y;
return hash;
}
public ClusterData GetData()
{
ClusterData data = new ClusterData();
data.Coordinates = Coordinates;
data.Tiles = tiles;
data.Type = Type;
return data;
}
/// <summary>
/// Gets the cluster as a byte array, uses huffman encoding
/// for tiledata.
/// </summary>
/// <returns></returns>
public byte[] GetClusterBytes()
{
const int clusterLength = Constants.ClusterWidth * Constants.ClusterHeight;
byte[] data = new byte[1];
data[0] = (byte)Type;
//for(int i = 1; i < clusterLength + 1; ++i)
//{
// data[i] = (byte)tiles[i - 1].Type;
//}
int tileDataIndex = 1;
for (int i = 0; i < clusterLength; ++i)
{
byte b = (byte)tiles[i].Type;
int nCount = i;
// Count the consecutive occurences.
while (tiles[nCount++].Type == (TileType)b && nCount < clusterLength) ;
// Consecutive occurences of the same tiletype.
int oCount = nCount - i;
i += oCount - 1;
// Tiledata is always 5 bytes, 1 byte for the type, 4 for the int counter.
byte[] tileData = new byte[5];
// Set the type
tileData[0] = b;
for (int k = 0; k < 4; ++k)
tileData[k + 1] = BitConverter.GetBytes(oCount)[k];
// Resize the data array so the tiledata will fit.
Array.Resize<byte>(ref data, data.Length + tileData.Length);
// Insert tile data.
for (int k = 0; k < tileData.Length; ++k)
{
data[tileDataIndex++] = tileData[k];
}
}
// Resize array to fit a coordinates object.
Array.Resize<byte>(ref data, data.Length + Marshal.SizeOf(Coordinates));
byte[] coordBytes = new byte[8];
for (int i = 0; i < 4; ++i)
{
coordBytes[i] = BitConverter.GetBytes(Coordinates.X)[i];
}
for (int i = 4; i < 8; ++i)
{
coordBytes[i] = BitConverter.GetBytes(Coordinates.Y)[i - 4];
}
for (int i = 0; i < coordBytes.Length; ++i)
{
data[tileDataIndex++] = coordBytes[i];
}
return data;
}
}
}
|
25cd55cd06faf05e41075baf08f451bcdd64cf35
|
C#
|
espermichael/quadratic
|
/Program.cs
| 3.859375
| 4
|
using System;
namespace quadratic
{
class Program
{
static void Main(string[] args)
{
//opening statement
Console.WriteLine("Solve the roots of a quadratic, Ax^2 + Bx + C = 0");
//collect values of A, B, and C
Console.WriteLine("Enter value of A:");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of B:");
int b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of C:");
int c = Convert.ToInt32(Console.ReadLine());
//A can't be zero.
if (a != 0 ){
// define the determinate.
int d = b*b-(4*a*c);
//Test is determinate is non-negative
if (d >= 0)
{
double rootOne = (-b + Math.Sqrt(d))/(2*a);
double rootTwo = (-b - Math.Sqrt(d))/(2*a);
Console.WriteLine("The determinate is non-negative with a value of: " + d);
Console.WriteLine("The roots of the equation are: " + rootOne + " and " + rootTwo);
}
else
{
Console.WriteLine("The determinate is negative with a value of: " + d + " No real roots exist");
}
}
else {
Console.WriteLine("Coefficent A can't be 0. This is not a quadratic equation");
}
}
}
}
|
e1566e73578f0c8b44c27f8228ada9f58dd04aa8
|
C#
|
take91/csharp
|
/HelloWorld/Test3/Program.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test3
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
for (int i = 0; i < 10; i++)
{
Console.Write("숫자-{0} : ", i);
sum += int.Parse(Console.ReadLine());
}
Console.WriteLine("합 : {0}",sum);
Console.WriteLine("평균 : {0}",(sum/10.0));
}
}
}
|
2cf43f8b4986f2621077c9aa7191eacf21728370
|
C#
|
muraczewski/Trainings
|
/RestApiCoreTrainings/Common/Exceptions/HttpCustomException.cs
| 2.828125
| 3
|
using System;
namespace Common.Exceptions
{
public class HttpCustomException : ApplicationException
{
public int StatusCode { get; }
public HttpCustomException(int statusCode) : this("Problematic status code", statusCode)
{
}
public HttpCustomException(string message, int statusCode) : this(message, null, statusCode)
{
}
public HttpCustomException(string message, Exception exception, int statusCode) : base(message, exception)
{
StatusCode = statusCode;
}
}
}
|
f2781ae0ef94ed53143a2ac8e0a08feeb806e867
|
C#
|
tecsun-chenjiayin/YT-2020-02-27-2_new
|
/YTH/Functions/TimeTag.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YTH.Functions
{
/// <summary>
/// 时间标记
/// </summary>
class TimeTag
{
private string tag = "";
public string updateTag()
{
tag = GetTime();
return tag;
}
public string getTag()
{
return tag;
}
public bool equal(string timeTag)
{
return tag == timeTag;
}
public static string GetTime()
{
return DateTime.Now.ToString("yyyy-MM-dd HHmmss");
}
public static string GetTime2()
{
return DateTime.Now.ToString(@"yyyy.MM.dd dddd");// + DateTime.Now.ToString("dddd");//2017-05-02星期二
}
}
}
|
db654e15776b9a2fdc7c66c7a3aa9b8b63956006
|
C#
|
Brixel/QuizMaster
|
/QuizMaster.Shared/Exceptions/NotFoundException.cs
| 2.578125
| 3
|
using System;
using QuizMaster.Shared.Models.Base;
namespace QuizMaster.Shared.Exceptions
{
public class NotFoundException<T> : Exception where T : Model
{
public int IdNotFound { get; set; } = -1;
public NotFoundException()
{
}
public NotFoundException(string message)
: base(message)
{
}
public NotFoundException(int idNotFound, string message)
: base(message)
{
IdNotFound = idNotFound;
}
public NotFoundException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
|
43c1fc643be6040792335d08107997844b94027c
|
C#
|
shendongnian/download4
|
/latest_version_download2/247783-56243164-198181708-2.cs
| 2.625
| 3
|
var controller = new ValuesController();
controller.Configuration = new System.Web.Http.HttpConfiguration();
controller.Request = new System.Net.Http.HttpRequestMessage();
var result = controller.Get(1);
var response = result.ExecuteAsync(new System.Threading.CancellationToken());
String deserialized = response.Result.Content.ReadAsStringAsync().Result;
Assert.AreEqual("\"value\"", deserialized);
|
dfc6a78ee7e138e2f3f805e525e9b18754f7665c
|
C#
|
amcp9/ForestShooter
|
/Server/Shooter_Server/Stats/BaseStat.cs
| 3.015625
| 3
|
using System;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using Common;
namespace War_Server.Stats
{
public class BaseStat
{
public List<StatBonus> BaseAdditives { get; set; }
public BaseStatType StatType{ get; set; }
public int BaseValue{ get; set; }
public string StatName{ get; set; }
public string StatDescription { get; set; }
public int FinalValue{ get; set; }
public BaseStat(int baseValue,string statName,string statDescription)
{
this.BaseAdditives = new List<StatBonus>();
this.BaseValue = baseValue;
this.StatName = statName;
this.StatDescription = statDescription;
}
public BaseStat(BaseStatType baseStatType,int basevalue,string statName)
{
this.BaseAdditives = new List<StatBonus>();
this.StatType = baseStatType;
this.BaseValue = basevalue;
this.StatName = statName;
}
public void AddExtraValue(StatBonus statBonus)
{
this.BaseAdditives.Add(statBonus);
}
public void RemoveExtraValue(StatBonus statBonus)
{
this.BaseAdditives.Remove(statBonus);
}
public int GetFinalValue()
{
this.FinalValue = 0;
this.BaseAdditives.ForEach(x => this.FinalValue += x.Value);
this.FinalValue += this.BaseValue;
return this.FinalValue;
}
public void ClearAdditive()
{
this.BaseAdditives.Clear();
}
public void SubBaseValue(int value)
{
this.BaseValue -= value;
}
public void AddBaseValue(int value)
{
this.BaseValue += value;
}
public void ChangeBaseValue(int value)
{
this.BaseValue = value;
}
}
}
|
7487d7c5bf87138f50413ab418b4a496d6a5cfc3
|
C#
|
linsen1983/adobe-pdf-library-samples
|
/DotNET/Sample_Source/ContentCreation/MakeDocWithICCBasedColorSpace/MakeDocWithICCBasedColorSpace.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Datalogics.PDFL;
/*
* This sample demonstrates creating a file containing an ICC-based color space.
*
* For more detail see the description of the ColorSpace sample programs on our Developers site,
* http://dev.datalogics.com/adobe-pdf-library/sample-program-descriptions/net-sample-programs/getting-pdf-documents-using-color-spaces
*
* Copyright (c) 2007-2017, Datalogics, Inc. All rights reserved.
*
* For complete copyright information, refer to:
* http://dev.datalogics.com/adobe-pdf-library/license-for-downloaded-pdf-samples/
*
*/
namespace MakeDocWithICCBasedColorSpace
{
class MakeDocWithICCBasedColorSpace
{
static void Main(string[] args)
{
using (Library lib = new Library())
{
String sInput = "../../Resources/Sample_Input/sRGB_IEC61966-2-1_noBPC.icc";
String sOutput = "../ICCBased-out.pdf";
if (args.Length > 0)
sInput = args[0];
if (args.Length > 1)
sOutput = args[1];
Console.WriteLine("Writing to output " + sOutput);
Document doc = new Document();
Page page = doc.CreatePage(Document.BeforeFirstPage, new Rect(0, 0, 5 * 72, 4 * 72));
Content content = page.Content;
Font font = new Font("Times-Roman", FontCreateFlags.Embedded | FontCreateFlags.Subset);
FileStream stream = new FileStream(sInput, FileMode.Open);
PDFStream pdfStream = new PDFStream(stream, doc, null, null);
ColorSpace cs = new ICCBasedColorSpace(pdfStream, 3);
GraphicState gs = new GraphicState();
gs.FillColor = new Color(cs, new Double[] { 1.0, 0.0, 0.0 });
Matrix textMatrix = new Matrix(24, 0, 0, 24, // Set font width and height to 24 point size
1 * 72, 2 * 72); // x, y coordinate on page, 1" x 2"
TextRun textRun = new TextRun("Hello World!", font, gs, new TextState(), textMatrix);
Text text = new Text();
text.AddRun(textRun);
content.AddElement(text);
page.UpdateContent();
doc.EmbedFonts();
doc.Save(SaveFlags.Full, sOutput);
}
}
}
}
|
3dd5a6b40d6dfcda5e48cd3ba21451f01c94f5e9
|
C#
|
Toocanzs/Mooncord-Game-Jam-2020
|
/Assets/Scripts/Entities/HealthComponent.cs
| 2.921875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthComponent : MonoBehaviour
{
public delegate void OnHealthChange(int difference);
public OnHealthChange on_health_change;
public int max_health;
private int current_health;
public int Health {
get { return current_health; }
}
private void Awake() {
current_health = max_health;
}
public void ChangeHealth(int value) {
var last_health = current_health;
current_health = Mathf.Clamp(current_health + value, 0, max_health);
var health_diff = current_health - last_health;
on_health_change?.Invoke(health_diff);
}
public bool isDead() {
return current_health == 0;
}
}
|
4aef5b0d33a4fbf72e2aa0b80810a59fd469ef31
|
C#
|
cucumber/gherkin
|
/dotnet/Gherkin/Ast/Scenario.cs
| 2.515625
| 3
|
using System.Collections.Generic;
namespace Gherkin.Ast
{
public class Scenario : StepsContainer, IHasTags
{
public IEnumerable<Tag> Tags { get; private set; }
public IEnumerable<Examples> Examples { get; private set; }
public Scenario(Tag[] tags, Location location, string keyword, string name, string description, Step[] steps, Examples[] examples)
: base(location, keyword, name, description, steps)
{
Tags = tags;
Examples = examples;
}
}
}
|
7f2260a4ed2dbf10cd87c48311fa181539fb5590
|
C#
|
alexander-t/swss
|
/Assets/Scripts/PulseLight.cs
| 3.046875
| 3
|
using System.Collections;
using UnityEngine;
/**
* Pulses a light by modifying its intensity.
*/
[RequireComponent(typeof(Light))]
public class PulseLight : MonoBehaviour
{
public float waitTime = 0.1f;
private bool pulsingUp = true;
private new Light light;
public void Awake()
{
light = GetComponent<Light>();
}
void Start()
{
light.intensity = 0;
StartCoroutine("Pulse");
}
private IEnumerator Pulse() {
while (true)
{
for (int i = 0; i < 10; i++)
{
if (pulsingUp)
{
light.intensity += 0.1f;
}
else {
light.intensity -= 0.1f;
}
yield return new WaitForSeconds(waitTime);
}
pulsingUp = !pulsingUp;
}
}
}
|
0e1d29a2ea3a392533fcecc8a58552e506fdbd90
|
C#
|
bearinarmor/TestPlayer
|
/TestPlayer/MusicSource.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace TestPlayer
{
public class MusicSource
{
private List<Music> Music = new List<Music>();
private int CurrentSongIndex=0;
private void GetSongNameAndUrl(string SongUrl)
{
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString(SongUrl);
int i = 0;
string DounloadUrl;
while (i < htmlCode.Length-22)
{
//ищем имя
//тут у меня возникли проблемы с кодировкой русских названий. пришлось отказаться
/*if (htmlCode.Substring(i, 7) == "\"name\">")
{
i = i + 7;
int j = i;
while (htmlCode.Substring(j, 1) != "<")//первая часть
{
j++;
};
string SongName;
SongName= htmlCode.Substring(i, j - i);
j = i;
while (htmlCode.Substring(j, 1) != ">")//пропускаем </span>
{
j++;
};
i = j + 1; j = i;
while (htmlCode.Substring(j, 1) != "\t")//вторая часть
{
j++;
};
SongName =SongName + htmlCode.Substring(i, j - i);
i = j;
};*/
//ищем ссылку
if (htmlCode.Substring(i, 21) == "http://dl.zaycev.net/")
{
int j = i;
while (htmlCode.Substring(j, 1) != "\"")
{
j++;
};
DounloadUrl = htmlCode.Substring(i, j - i);
//вырежем название на английском из имени файла
j = DounloadUrl.Length;
while (DounloadUrl.Substring(j-1, 1) != "_")
{
j--;
};
int k = j;
while (DounloadUrl.Substring(k, 1) != "/")
{
k--;
};
string Name = DounloadUrl.Substring(k+1, j - k-2);
Music.Add(new Music { name = Name, url = DounloadUrl });
};
i++;
};
}
}
public void GetSongs(){
using (WebClient client = new WebClient()){
string htmlCode = client.DownloadString("http://zaycev.net/");
int i=0;
bool flagAgainsDoubles = true;
string SongUrl;
while(i<htmlCode.Length-8){
if(htmlCode.Substring(i, 7) == "/pages/") {
int j = i;
while (htmlCode.Substring(j,1)!="\""){
j++;
};
SongUrl = "http://zaycev.net" + htmlCode.Substring(i, j - i);
if (flagAgainsDoubles){
GetSongNameAndUrl(SongUrl);
flagAgainsDoubles = !flagAgainsDoubles;
}
else {
flagAgainsDoubles = !flagAgainsDoubles;
}
i = j;
};
i++;
};
}
}
public string GetSongName(){
string name = Music.ElementAt(CurrentSongIndex).name;
return name;
}
public string GetSongName(int index)
{
string name = Music.ElementAt(index).name;
return name;
}
public int count()
{
int i = this.Music.Count;
return i;
}
public string GetSongUrl(){
string url=Music.ElementAt(CurrentSongIndex).url;
return url;
}
public List<string> GetSongsList(){
List<string> SongList = new List<string>();
for (int i=0; i < Music.Count; i++) {
SongList.Add(this.GetSongName() + "\n");
}
return SongList;
}
public void NextSong(){
if (CurrentSongIndex < Music.Count)
{
CurrentSongIndex++;
}
}
public void PreviosSong() {
if (CurrentSongIndex > 0) {
CurrentSongIndex--;
}
}
public void SetCurrentSong(int i) {
if (i >= 0 && i < Music.Count) {
this.CurrentSongIndex = i;
}
}
public int CurrentSong() {
return this.CurrentSongIndex;
}
}
}
|
f076436fb7ac0055d8cfd849e719a6e00b0de898
|
C#
|
sadipgiri/3D-Models
|
/Form1/Form1/Form1.cs
| 2.75
| 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 Form1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Bitmap bmpImage = new Bitmap("sagarmatha.jpg");
pictureBox1.Image = new Bitmap("sagarmatha.jpg");
int width = bmpImage.Width;
int height = bmpImage.Height;
for (int j = 0; j< height; j++)
{
for (int i = 0; i< width; i++)
{
Color pixel1 = bmpImage.GetPixel(i, j);
Color newcolor = Color.FromArgb(pixel1.A, pixel1.R, 0, 0);
bmpImage.SetPixel(i, j, newcolor);
}
bmpImage.Save("output_redscale.jpg");
}
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
Color pixel1 = bmpImage.GetPixel(i, j);
int average = (pixel1.R + pixel1.G + pixel1.B) / 3;
Color newcolor = Color.FromArgb(0, average, average, average);
bmpImage.SetPixel(i, j, newcolor);
}
bmpImage.Save("output_grayscale.jpg");
}
pictureBox2.Image = new Bitmap("output_redscale.jpg");
pictureBox3.Image = new Bitmap("output_grayscale.jpg");
}
}
}
|
46433813338743865d462c61333a4187432ace83
|
C#
|
nidza0/HealthCareSystem
|
/SIMS/Repository/CSVFileRepository/Csv/Converter/HospitalManagementConverter/TimeTableConverter.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SIMS.Model.UserModel;
using SIMS.Util;
namespace SIMS.Repository.CSVFileRepository.Csv.Converter.HospitalManagementConverter
{
class TimeTableConverter : ICSVConverter<TimeTable>
{
private readonly string _delimiter = ">";
private readonly string _listDelimiter = "~";
private readonly string _secondListDelimiter = "_";
private readonly string _dateTimeFormat = "dd.MM.yyyy. HH:mm";
public TimeTableConverter()
{
}
public TimeTable ConvertCSVToEntity(string csv)
{
string[] tokens = SplitStringByDelimiter(csv, _delimiter);
return new TimeTable(
long.Parse(tokens[0]),
GetWorkTime(tokens[1])
);
}
public string ConvertEntityToCSV(TimeTable entity)
=> string.Join(_delimiter,
entity.GetId(),
GetDictionaryCSV(entity.WorkingHours)
);
private string[] SplitStringByDelimiter(string stringToSplit, string delimiter)
=> stringToSplit.Split(delimiter.ToCharArray());
// private long _id;
//private Dictionary<WorkingDaysEnum, TimeInterval> _workingHours;
private string GetDictionaryCSV(Dictionary<WorkingDaysEnum, TimeInterval> dict)
=> string.Join(_listDelimiter, dict.Select(workingDay => workingDay.Key + _secondListDelimiter + transformTimeIntervalToCSV(workingDay.Value)));
private string transformTimeIntervalToCSV(TimeInterval timeInterval)
=> string.Join(_secondListDelimiter, timeInterval.StartTime.ToString(_dateTimeFormat), timeInterval.EndTime.ToString(_dateTimeFormat));
private Dictionary<WorkingDaysEnum, TimeInterval> GetWorkTime(string workTimeCSV)
{
Dictionary<WorkingDaysEnum, TimeInterval> retVal = new Dictionary<WorkingDaysEnum, TimeInterval>();
string[] perDayString = SplitStringByDelimiter(workTimeCSV, _listDelimiter);
foreach (string dayLine in perDayString)
{
if (string.IsNullOrEmpty(dayLine)) continue; //It will skip invalid line. Known situation : entity was written to the file with an empty dict.
string[] dayInfo = SplitStringByDelimiter(dayLine, _secondListDelimiter);
WorkingDaysEnum day = (WorkingDaysEnum)Enum.Parse(typeof(WorkingDaysEnum), dayInfo[0]); //Casting
TimeInterval timeInterval = GetTimeInterval(dayInfo[1],dayInfo[2]);
retVal.Add(day, timeInterval);
}
return retVal;
}
private DateTime GetDateTimeFromString(string dateTime)
=> DateTime.ParseExact(dateTime, _dateTimeFormat, null);
private TimeInterval GetTimeInterval(string startDate, string endDate)
=> new TimeInterval(GetDateTimeFromString(startDate), GetDateTimeFromString(endDate));
}
}
|
b40f2f0a75b96307c122204460e83a12d26acfa4
|
C#
|
horker/pscntk
|
/source/Horker.PSCNTK/MsgPack/MsgPackSerializer.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using MsgPack.Serialization;
namespace Horker.PSCNTK
{
public class MsgPackSerializer
{
private static Dictionary<string, Tuple<float[], int[]>> ConvertToSerializableObject(DataSourceSet dss)
{
var obj = new Dictionary<string, Tuple<float[], int[]>>();
foreach (var entry in dss.Features)
{
var ds = entry.Value;
obj[entry.Key] = new Tuple<float[], int[]>(ds.Data.ToArray(), ds.Shape.Dimensions);
}
return obj;
}
private static DataSourceSet ConvertFromSerializableObject(Dictionary<string, Tuple<float[], int[]>> obj)
{
var dss = new DataSourceSet();
foreach (var entry in obj)
dss.Add(entry.Key, DataSourceFactory.Create(entry.Value.Item1, entry.Value.Item2));
return dss;
}
public static void Serialize(DataSourceSet dss, Stream stream, bool compress = false)
{
var serializer = MessagePackSerializer.Get<Dictionary<string, Tuple<float[], int[]>>>();
var obj = ConvertToSerializableObject(dss);
if (compress)
{
using (var zstream = new DeflateStream(stream, CompressionLevel.Optimal, true))
{
serializer.Pack(zstream, obj);
}
}
else
serializer.Pack(stream, obj);
}
public static void Serialize(DataSourceSet dss, string path, bool compress = false)
{
using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
Serialize(dss, stream, compress);
}
}
public static DataSourceSet Deserialize(Stream stream, bool decompress = false)
{
var serializer = MessagePackSerializer.Get<Dictionary<string, Tuple<float[], int[]>>>();
if (decompress)
{
using (var zstream = new DeflateStream(stream, CompressionMode.Decompress))
{
return ConvertFromSerializableObject(serializer.Unpack(zstream));
}
}
else
return ConvertFromSerializableObject(serializer.Unpack(stream));
}
public static List<DataSourceSet> Deserialize(string path, bool decompress = false)
{
var serializer = MessagePackSerializer.Get<DataSourceSet>();
var result = new List<DataSourceSet>();
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
if (decompress)
{
using (var zstream = new DeflateStream(stream, CompressionMode.Decompress))
{
while (true)
{
var dss = serializer.Unpack(zstream);
if (dss == null)
break;
result.Add(dss);
}
}
}
else
{
while (true)
{
var dss = serializer.Unpack(stream);
if (dss == null)
break;
result.Add(dss);
}
}
return result;
}
}
}
}
|
f887d2522069d14687c5a5c40ddc31ca1fb64da8
|
C#
|
zhyt1985/slowandsteadyparser
|
/SlowAndSteadyParser/VBAEngine/Utl/PerformanceBalance.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace SlowAndSteadyParser
{
public class Balancer : IDisposable
{
//PerformanceCounter
private PerformanceCounter m_pc = null;
//希望保持的CPU占用率
private float m_atticpatecpuusage = 100;
//移动平均计算周期数
private int m_circleofcaclulatation = 20;
//到目前为止的移动平均值
private float m_movingaveragecpuusage = 50;
//CPU利用率采样时间间隔
private int m_samplinginterval = 5;
//目前使用Sleep值
private int m_threadsleepvalue = 50;
//Sleep增减数
private int m_sleepvalueincrement = 10;
//线程
private Thread m_samplingthread = null;
//Name
private string m_name;
//Enable
private bool m_enable = false;
//在程序重复运行的后面放置这个平衡点函数
public void InvokeBalancePoint()
{
if (m_enable)
{
Thread.Sleep(m_threadsleepvalue);
if (m_samplingthread == null)
{
m_samplingthread = new Thread(SamplingThread);
m_samplingthread.Name = m_name + "'s SamplingThread";
m_samplingthread.Start();
}
}
}
public int AnticapateCPUUsage
{
get { return (int)m_atticpatecpuusage; }
set { m_atticpatecpuusage = (float)value; }
}
public int CircleOfCaclulation
{
get { return m_circleofcaclulatation ; }
set { m_circleofcaclulatation = value; }
}
public int SamplingInterval
{
get { return m_samplinginterval; }
set { m_samplinginterval = value; }
}
private void SamplingThread()
{
while (true)
{
float k = 2 / (float)(m_circleofcaclulatation + 1);
float u = m_pc.NextValue();
m_movingaveragecpuusage = m_movingaveragecpuusage * (1 - k) + u * k;
if (m_movingaveragecpuusage < m_atticpatecpuusage - 5)
{
m_threadsleepvalue = m_threadsleepvalue - m_sleepvalueincrement;
}
else if (m_movingaveragecpuusage > m_atticpatecpuusage + 5)
m_threadsleepvalue = m_threadsleepvalue + m_sleepvalueincrement;
if (m_threadsleepvalue <= 0) m_threadsleepvalue = 1;
//采样周期
Thread.Sleep(m_samplinginterval * 1000);
}
}
public Balancer(string name, bool m_enable)
{
m_name = name;
m_enable = m_enable;
m_pc = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
m_pc.NextValue();
}
#region IDisposable 成员
private bool IsDisposed = false;
public virtual void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool Disposing)
{
if(!IsDisposed)
{
if (Disposing)
{
//清理托管资源
}
//清理非托管资源
if (m_samplingthread != null && m_samplingthread.IsAlive)
{
m_samplingthread.Abort();
m_samplingthread = null;
}
}
IsDisposed=true;
}
~Balancer()
{
Dispose(false);
}
#endregion
}
public class PerformanceBalancer
{
private static bool isRunning = false;
private static Dictionary<string, Balancer> m_dictBalancer = new Dictionary<string, Balancer>();
public static void Init(bool isrunning)
{
isRunning = isrunning;
}
public static Balancer GetBalancer(string Name)
{
if (m_dictBalancer.ContainsKey(Name))
return m_dictBalancer[Name];
else
{
Balancer p = new Balancer(Name,isRunning);
m_dictBalancer.Add(Name, p);
return p;
}
}
public static void Dispose()
{
foreach (Balancer b in m_dictBalancer.Values)
b.Dispose();
m_dictBalancer.Clear();
}
}
}
|
c58a00d1e65bfd5efa62e6a302c8c5e4af2bdcfe
|
C#
|
lsikkes/HealthInformatics1
|
/Visual Studio - Map/Visualizer/Visualizer/Surroundings/Tree.cs
| 3.0625
| 3
|
// <copyright file="Tree.cs" company="HI1">
// Copyright © 2016
// </copyright>
// <summary></summary>
// ***********************************************************************
namespace Visualizer.Surroundings
{
using System.Windows.Media;
using System.Windows.Shapes;
/// <summary>
/// Class Tree.
/// </summary>
/// <seealso cref="Visualizer.Surroundings.Surrounding" />
public class Tree : Surrounding
{
#region Fields
/// <summary>
/// The width of the tree
/// </summary>
private int w,
/// <summary>
/// The height of the tree
/// </summary>
h,
/// <summary>
/// The x coordinate of the tree
/// </summary>
x,
/// <summary>
/// The y coordinate of the tree
/// </summary>
y;
/// <summary>
/// The tree color
/// </summary>
private Color treeColor = Colors.Green;
#endregion Fields
#region Constructors
/// <summary>
/// Constructor of Tree
/// </summary>
/// <param name="x"> x position</param>
/// <param name="y"> y position</param>
/// <param name="rotation"> rotation of object</param>
/// <param name="id"> id of object</param>
/// <param name="name">name of object</param>
/// <param name="w"> width of tree</param>
/// <param name="h"> height of tree</param>
/// <param name="mx"> margin x of tree</param>
/// <param name="my"> margin y of tree</param>
public Tree(int x, int y, int rotation, int id, string name, int w, int h, int mx, int my)
: base(x, y, rotation, id, name)
{
this.w = w;
this.h = h;
this.x = mx;
this.y = my;
}
#endregion Constructors
#region Methods
/// <summary>
/// Makes a rectangle for a tree object.
/// </summary>
/// <returns>Rectangle object.</returns>
public override Rectangle GetRect()
{
Rectangle rect = MakeRect(this.x, this.y, this.w, this.h);
rect.Fill = new SolidColorBrush(this.treeColor);
return rect;
}
#endregion Methods
}
}
|
70d0fd43f69d7b5561b38a61c5dee2ce6c06e5c4
|
C#
|
myangmi/Sales501
|
/Individual Submissions/PA2 CIS 501 Brandon Shaver/CIS 501 project 1/Item.cs
| 3.40625
| 3
|
using System;
namespace CIS_501_project_1
{
public struct Item
{
// Constructors:
public Item(string name, int id, double cost, string description = "") : this()
{
Name = name;
ID = id;
Cost = cost;
Description = description;
}
// Properties:
public String Description { get; set; }
public int ID { get; set; }
public string Name { get; set; }
public double Cost { get; set; }
// Methods:
public override string ToString()
{
String s = "Name: " + this.Name + "\n";
s += "ID: " + this.ID.ToString() + "\n";
s += "Cost: " + this.Cost.ToString() + "\n";
s += "Description: " + this.Description + "\n";
return s;
}
}
}
|
ef660f025576208e7e37f692d9f646a9928b359f
|
C#
|
hanbo1904/1612.netA-
|
/HospitalScheds/HospitalScheds.Serverce/VacationServerce.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HospitalScheds.IServerce;
using HospitalScheds.Model;
using Microsoft.EntityFrameworkCore;
namespace HospitalScheds.Serverce
{
//public class VacationServerce : IVacationServerce
//{
// DataContext db = new DataContext();
// /// <summary>
// /// 添加
// /// </summary>
// /// <param name="vacation"></param>
// /// <returns></returns>
// public int AddVacation(Vacation vacation)
// {
// db.Vacationlist.Add(vacation);
// int i = db.SaveChanges();
// return i;
// }
// /// <summary>
// ///
// /// </summary>
// /// <param name="id"></param>
// /// <returns></returns>
// public int DeleteVacation(int id)
// {
// var list = db.Vacationlist.Find(id);
// db.Vacationlist.Remove(list);
// int i = db.SaveChanges();
// return i;
// }
// /// <summary>
// ///
// /// </summary>
// /// <param name="vacation"></param>
// /// <returns></returns>
// public int EditVacation(Vacation vacation)
// {
// db.Entry(vacation).State = EntityState.Modified;
// int i = db.SaveChanges();
// return i;
// }
// /// <summary>
// ///
// /// </summary>
// /// <param name="id"></param>
// /// <returns></returns>
// public Vacation GetModel(int id)
// {
// var lsit = db.Vacationlist.Find(id);
// return lsit;
// }
// /// <summary>
// /// 显示
// /// </summary>
// /// <param name="pageIndex"></param>
// /// <param name="pageSize"></param>
// /// <returns></returns>
// public PageModel<Vacation> GetVacation( int pageIndex = 1, int pageSize = 3)
// {
// PageModel<Vacation> pagemodel = new PageModel<Vacation>();
// int totalcount = db.Vacationlist.Where(m => m.Contains("")).ToList().Count();
// //分页
// var list = db.Vacationlist.Where(m => m.Contains("")).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
// pagemodel.TotalCount = totalcount;
// pagemodel.Data = list;
// return pagemodel;
// }
//}
}
|
8661ae2ba48c2a6f519cc4f1cd0347231715d633
|
C#
|
SAGARPATWAL/VirtualChemistry
|
/ExternalResources/Apparatuses/Chemical.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExternalResources.Apparatuses
{
public abstract class Chemical
{
protected double _volume;
protected string _chemicalName;
private string _experiments;
public string Experiments
{
get { return _experiments; }
set
{
_experiments = value;
}
}
public double Volume
{
get { return Volume; }
set
{
Volume = value;
}
}
public string ChemicalName
{
get { return _chemicalName; }
set
{
_chemicalName = value;
}
}
}
}
|
740ce4d5c261b511ebcd1b7b7d2be7ae8563fd79
|
C#
|
Shal1928/useabilities
|
/UseAbilities/UseAbilities.WPF/Converters/TimeSpanToDateTimeConverter.cs
| 2.75
| 3
|
using System;
using System.Globalization;
using System.Windows.Data;
using UseAbilities.WPF.Converters.Base;
namespace UseAbilities.WPF.Converters
{
[ValueConversion(typeof(TimeSpan), typeof(DateTime))]
public class TimeSpanToDateTimeConverter : ConverterBase<TimeSpanToDateTimeConverter>
{
public TimeSpanToDateTimeConverter()
{
//
}
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is DateTime)) throw new ArgumentException("value is not DateTime");
var dateTimeValue = (DateTime)value;
return new TimeSpan(0, dateTimeValue.Hour, dateTimeValue.Minute, dateTimeValue.Second, dateTimeValue.Millisecond);
}
public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is TimeSpan)) throw new ArgumentException("value is not TimeSpan");
var timeSpanValue = (TimeSpan)value;
return new DateTime(1,1,1, timeSpanValue.Hours, timeSpanValue.Minutes, timeSpanValue.Seconds, timeSpanValue.Milliseconds);
}
}
[ValueConversion(typeof(DateTime), typeof(TimeSpan))]
public class DateTimeTimeSpanConverter : ConverterBase<DateTimeTimeSpanConverter>
{
public DateTimeTimeSpanConverter()
{
//
}
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is TimeSpan)) throw new ArgumentException("value is not TimeSpan");
var timeSpanValue = (TimeSpan)value;
return new DateTime(1, 1, 1, timeSpanValue.Hours, timeSpanValue.Minutes, timeSpanValue.Seconds, timeSpanValue.Milliseconds);
}
public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is DateTime)) throw new ArgumentException("value is not DateTime");
var dateTimeValue = (DateTime)value;
return new TimeSpan(0, dateTimeValue.Hour, dateTimeValue.Minute, dateTimeValue.Second, dateTimeValue.Millisecond);
}
}
}
|
1895e7690919eaa057176b5cb857c8c4588a7a7b
|
C#
|
avaneszdes/RazorUdpChat
|
/RazorUdpChat/MessageManager.cs
| 2.90625
| 3
|
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace RazorUdpChat
{
public class MessageManager: IDisposable
{
private readonly UdpClient _updClient;
private readonly IPEndPoint _interlocutorEndpoint;
public MessageManager(IPEndPoint interlocutorEndpoint, IPEndPoint endpointToListen)
{
_updClient = new UdpClient(endpointToListen);
_interlocutorEndpoint = interlocutorEndpoint;
}
public void ListenMessageRecieve(Action<string> onRecieve)
{
Task.Factory.StartNew(async () =>
{
while (true)
{
var result = await _updClient.ReceiveAsync();
onRecieve(Encoding.UTF8.GetString(result.Buffer) + $" {DateTime.Now.Hour}:{DateTime.Now.Minute}\r\n");
}
});
}
public void SentTextMessage(string message)
{
if (string.IsNullOrWhiteSpace(message))
{
return;
}
byte[] data = Encoding.UTF8.GetBytes(message);
_updClient.Send(data, data.Length, _interlocutorEndpoint);
}
public void Dispose()
{
_updClient.Dispose();
_updClient.Close();
}
}
}
|
3b5d324c87c8c5bea6135f10262385af5571020e
|
C#
|
shankarpratap/yuwahack2017
|
/yuwa/OneWebApp/OneWebApp/Models/StudentDetail.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OneWebApp.Models
{
public class StudentDetail
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string NickName { get; set; }
public string Gender { get; set; }
public DateTime Birthdate { get; set; }
public DateTime DOJ_Yuwa { get; set; }
public string Address { get; set; }
public string BloodGroup { get; set; }
public string Village { get; set; }
public string Phone { get; set; }
public bool IsStudent { get; set; }
public bool IsCoach { get; set; }
public string Name
{
get
{
return this.FirstName + " " + this.LastName;
}
set { }
}
public string Age
{
get
{
return (Math.Ceiling((DateTime.Now - this.Birthdate).TotalDays / 365)).ToString();
}
set { }
}
}
}
|
67eac094b98e26db0d7e45c118d928c246c28acd
|
C#
|
Zrp200/SharpExtensions
|
/SharpExtensions45.Tests/DateTimeExtensionsTests.cs
| 2.5625
| 3
|
using System;
using NUnit.Framework;
namespace SharpExtensions.Tests
{
[TestFixture]
public class DateTimeExtensionsTests
{
[Test]
public void FromUnixTime()
{
var dateTime = 100L.FromUnixTime();
Assert.IsTrue(dateTime == new DateTime(1970, 1, 1, 0, 1, 40, DateTimeKind.Utc));
dateTime = 100.FromUnixTime();
Assert.IsTrue(dateTime == new DateTime(1970, 1, 1, 0, 1, 40, DateTimeKind.Utc));
}
}
}
|
87eb3bdb05b7e3c902baedbabac8ac255ab7a06b
|
C#
|
reallyfancy/unity-fmod-examples
|
/UpdateEventParameterWithKeyPresses.cs
| 3.390625
| 3
|
using UnityEngine;
using FMODUnity;
// This is a simple example of how to update a parameter of your FMOD event using scripting.
// In this example we increase the value of the parameter every time the space bar is pressed.
// Instructions for use:
// 1. Place this script on the same GameObject as the StudioEventEmitter that you want to update
// 3. Type the name of the parameter that you want to update in the "Parameter Name" field in the Inspector panel
// 3. When you enter Play Mode, the chosen parameter of the StudioEventEmitter will increase each time you press the space bar
public class UpdateEventParameterWithKeyPresses : MonoBehaviour
{
// This line creates a field in the Inspector panel where you can type the name of the parameter you want to update
public string parameterName;
// This line creates a checkbox in the Inspector panel. If ticked, it will print a message to the console when it updates the parameter.
public bool showDebugMessage;
// This code is private - it's just used to keep track of things within the script, and doesn't create a field in the Inspector panel
private StudioEventEmitter eventEmitter;
private int numberOfPresses;
// Awake is called when the GameObject with this script on it first appears in the game
void Awake ()
{
// Set up a reference to the StudioEventEmitter on the same GameObject as this script
eventEmitter = GetComponent<StudioEventEmitter>();
// Set our counter to 0
numberOfPresses = 0;
}
// Update is called once per frame
void Update ()
{
// IF the spacebar has just been pressed...
if(Input.GetKeyDown(KeyCode.Space))
{
// If it has, increase our counter by 1
numberOfPresses += 1;
// Now pass the data to the StudioEventEmitter, using the parameter name we set in the Inspector panel
eventEmitter.SetParameter(parameterName, numberOfPresses);
// If the "show debug message" checkbox is ticked, send a message to the console
if(showDebugMessage)
{
Debug.Log("Setting parameter " + parameterName + " to " + numberOfPresses, gameObject);
}
}
}
}
|
261723b700d20f99c61d88d23c5c0b2ea6ead2f2
|
C#
|
mathjeff/SCGSim
|
/Hearthstone/HearthstoneReferee.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Knows the rules of Hearthstone
namespace Games
{
class HearthstoneReferee : Referee
{
public HearthstoneReferee()
{
this.StartingHealth = 30;
this.Starting_HandSize = 3;
this.Max_HandSize = 10;
this.legalCards = new List<ReadableCard>{LeperGnome, ArgentSquire, ZombieChow, ElvenArcher,
BloodfenRaptor, HauntedCreeper, LootHorder, Wrath,
EarthenRingFarseer, IronfurGrizzly, ArcaneIntellect, FanOfKnives,
ChillwindYeti, SenjinShieldMasta, Fireball, Hellfire, Consecration,
AzureDrake, SludgeBelcher, Starfall, SilverHandKnight,
Sunwalker, CairneBloodhoof, FireElemental, Starfire,
WarGolem, Sprint, Flamestrike,
IronbarkProtector,
Cenarius};
//this.legalCards = new List<ReadableCard>{LeperGnome, ElvenArcher};
}
public List<GameEffect> Get_AvailableGameActions(Game game, Readable_GamePlayer player)
{
// This function only gets called when there are no effects in progress (like choosing the target of a triggered effect).
List<GameEffect> options = new List<GameEffect>();
// So, a player has these types of options: 1. Play a card. 2. Attack with a monster. 3. Activate their special ability. 4. End their turn
// Let the player play any card
foreach (ID<ReadableCard> cardId in player.Get_ReadableHand())
{
ReadableCard card = game.Get_ReadableSnapshot(cardId);
if (card.IsPlayable(game))
options.Add(new PlayCard_Effect(card.GetID((ReadableCard)null)));
}
// Let the player attack with any monster
IEnumerable<ID<Readable_MonsterCard>> availableAttacker_IDs = player.Get_MonsterIDsInPlay();
// first figure out which monsters can be attacked (if any monsters have Taunt, they are the only ones that may be attacked)
foreach (ID<Readable_GamePlayer> playerId in game.TurnOrder)
{
// make sure this is a different player
if (!playerId.Equals(player.GetID((Readable_GamePlayer)null)))
{
LinkedList<ID<Readable_LifeTarget>> requiredTarget_IDs = new LinkedList<ID<Readable_LifeTarget>>();
LinkedList<ID<Readable_LifeTarget>> allTarget_Ids = new LinkedList<ID<Readable_LifeTarget>>();
Readable_GamePlayer controller = game.Get_ReadableSnapshot(playerId);
foreach (ID<Readable_MonsterCard> monsterId in controller.Get_MonsterIDsInPlay())
{
Readable_MonsterCard monster = game.Get_ReadableSnapshot(monsterId);
ID<Readable_LifeTarget> convertedID = monster.GetID((Readable_LifeTarget)null);
allTarget_Ids.AddLast(convertedID);
if (monster.Get_MustBeAttacked())
requiredTarget_IDs.AddLast(convertedID);
}
if (requiredTarget_IDs.Count != 0)
{
// There is a monster with taunt, so the only valid targets are the monsters with taunt
allTarget_Ids = requiredTarget_IDs;
}
else
{
// There are no monsters with taunt, so the valid targets are all monsters and the opponent too
allTarget_Ids.AddLast(controller.GetID((Readable_LifeTarget)null));
}
// Now allow each monster to attack each available target
foreach (ID<Readable_MonsterCard> attackerId in availableAttacker_IDs)
{
if (game.Get_ReadableSnapshot(attackerId).Get_CanAttack())
{
foreach (ID<Readable_LifeTarget> targetId in allTarget_Ids)
{
options.Add(new AttackEffect(attackerId.AsType((Readable_LifeTarget)null), targetId));
}
}
}
}
}
// Let the player end their turn
options.Add(new EndTurn_Effect(player.GetID((Readable_GamePlayer)null)));
return options;
}
public Game NewGame(TournamentPlayer player1, TournamentPlayer player2)
{
List<TournamentPlayer> players = new List<TournamentPlayer>();
players.Add(player1);
players.Add(player2);
foreach (ReadableCard card in player1.MainDeck)
{
if (player2.MainDeck.Contains(card))
{
Console.WriteLine("Error: two players have the same instance of a card in their deck");
}
}
return this.NewGame(players);
}
public Game NewGame(List<TournamentPlayer> players)
{
if (players.Count != 2)
{
throw new ArgumentException("Hearthstone games must have exactly 2 players");
}
Game game = new Game(this);
int numBonusCards = 0;
foreach (TournamentPlayer templatePlayer in players)
{
if (templatePlayer.MainDeck.Count() != this.Starting_DeckSize)
throw new ArgumentException("Hearthstone decks must start with exactly 30 cards");
Writable_GamePlayer newPlayer = new Writable_GamePlayer(templatePlayer);
newPlayer.InitializeHealth(30);
game.AddPlayer(newPlayer);
// draw a bunch of cards from the player's deck
DrawEffect drawEffect = new DrawEffect(new ConstantValueProvider<Writable_GamePlayer, Controlled>(newPlayer), DrawFromDeck_Provider.FromController(),
new ConstantValueProvider<int, Controlled>(this.Starting_HandSize + numBonusCards));
drawEffect.ControllerID = newPlayer.GetID((Readable_GamePlayer)null);
drawEffect.Process(game);
// potentially draw a Coin too
DrawEffect bonusCards = new DrawEffect(new ConstantValueProvider<Writable_GamePlayer, Controlled>(newPlayer), new ConstantValueProvider<ReadableCard, Controlled>(HearthstoneReferee.Coin),
new ConstantValueProvider<int, Controlled>(numBonusCards));
bonusCards.ControllerID = newPlayer.GetID((Readable_GamePlayer)null);
bonusCards.Process(game);
// each player gets one more card than the previous and one additional Coin
numBonusCards++;
}
return game;
}
public void AddHealth(int amount, Writable_GamePlayer player)
{
int newHealth = player.Health + amount;
if (newHealth > this.MaxHealth)
newHealth = this.MaxHealth;
player.Health = newHealth;
// we'll check afterward for game losses, in case multiple players lose during the same effect
}
public bool IsPlayable(Readable_MonsterCard card, Game game)
{
Readable_GamePlayer controller = game.Get_ReadableSnapshot(card.Get_ControllerID());
IEnumerable<ID<Readable_MonsterCard>> cardsInPlay = controller.Get_MonsterIDsInPlay();
if (cardsInPlay.Count() < 7)
return true;
return false;
}
public void NewTurn(ID<Readable_GamePlayer> playerID, Game game)
{
Writable_GamePlayer player = game.GetWritable(playerID);
// gain 1 crystal
if (player.ResourcesPerTurn.ToNumber() < 10)
player.ResourcesPerTurn = player.ResourcesPerTurn.Plus(new Resource(1));
// replenish existing crystals
player.CurrentResources = player.ResourcesPerTurn;
// give one attack to each monster
foreach (ID<Readable_MonsterCard> monsterId in player.MonsterIDsInPlay.GetReadable())
{
Writable_MonsterCard card = game.GetWritable(monsterId);
card.NumAttacksRemaining = card.NumAttacksPerTurn;
}
// draw a card if there's room
this.AddCardToHand(player.Deck.Dequeue(), player, game);
}
public Readable_GamePlayer GetWinner(Game game)
{
List<Readable_GamePlayer> losers = this.GetLosers(game);
List<Readable_GamePlayer> winners = new List<Readable_GamePlayer>();
foreach (Readable_GamePlayer player in game.Players)
{
if (!losers.Contains(player))
{
winners.Add(player);
}
}
if (winners.Count == 1)
{
return winners[0];
}
return null;
}
public List<Readable_GamePlayer> GetLosers(Game game)
{
List<Readable_GamePlayer> losers = new List<Readable_GamePlayer>();
foreach (Readable_GamePlayer player in game.Players)
{
if (player.GetHealth() <= 0)
{
losers.Add(player);
}
}
return losers;
}
public void AddCardToHand(ReadableCard card, Writable_GamePlayer player, Game game)
{
if (player.Get_ReadableHand().Count >= this.Max_HandSize)
return;
if (card == null)
{
// take damage for having no cards left
player.NumDrawsSkipped++;
player.AddHealth(new Specific_LifeEffect(null, -player.NumDrawsSkipped), game);
}
else
{
player.DrawCard(card, game);
}
}
public int StartingHealth { get; set; }
public int MaxHealth
{
get
{
return this.StartingHealth;
}
}
public int Starting_HandSize { get; set; }
public int Max_HandSize { get; set; }
public int Starting_DeckSize { get { return 30; } }
private List<ReadableCard> legalCards;
// Lots of cards
public IList<ReadableCard> LegalCards
{
get
{
return this.legalCards;
}
}
public static ReadableCard Coin
{
get
{
// The card named "Coin" that costs 0
SpellCard card = new SpellCard("Coin", new Resource(0));
// Make a trigger that happens after playing this card, which adds 1 resource this turn to the controller of the effect
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(new ResourceEffect(new ConstantValueProvider<Resource, Controlled>(new Resource(1)), new WritableController_Provider())));
return card;
}
}
public static Readable_MonsterCard ZombieChow
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Zombie Chow", new Resource(1), 2, 3);
ValueProvider<IList<Readable_LifeTarget>, Controlled> controllerProvider = new OpponentsProvider();
card.Add_AfterDeath_Trigger(new GameTrigger<GameEffect>(LifeEffect.Targeted(new ConstantValueProvider<int, Controlled>(5), new OpponentsProvider(), new ReadableController_Provider())));
return card;
}
}
public static Readable_MonsterCard ArgentSquire
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Argent Squire", new Resource(1), 1, 1);
card.Add_SingleUse_Shield();
return card;
}
}
public static Readable_MonsterCard LeperGnome
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Leper Gnome", new Resource(1), 2, 1);
// 2 damage to the opponent when it dies
card.Add_AfterDeath_Trigger(new GameTrigger<GameEffect>(LifeEffect.Targeted(new ConstantValueProvider<int, Controlled>(-2), new OpponentsProvider(), new ReadableController_Provider())));
return card;
}
}
public static Readable_MonsterCard ElvenArcher
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Elven Archer", new Resource(1), 1, 1);
// Deals 1 damage when it comes into play
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(LifeEffect.Targeted(new ConstantValueProvider<int, Controlled>(-1), new LifeTarget_Choices_Provider(), new ReadableController_Provider())));
return card;
}
}
public static Readable_MonsterCard BloodfenRaptor
{
get
{
return new Writable_MonsterCard("Bloodfen Raptor", new Resource(2), 3, 2);
}
}
public static Readable_MonsterCard RiverCrocolisk
{
get
{
return new Writable_MonsterCard("River Crocolisk", new Resource(2), 2, 3);
}
}
public static Readable_MonsterCard HauntedCreeper
{
get
{
// There is a card called "Haunted Creeper" that costs 2 and is a 1/2
Writable_MonsterCard card = new Writable_MonsterCard("Haunted Creeper", new Resource(2), 1, 2);
// Add a trigger that triggers after this monster dies, which generates an effect that spawns two 1/1 monsters for the controller of this monster
card.Add_AfterDeath_Trigger(new GameTrigger<GameEffect>(new SpawnMonster_Effect(new Writable_MonsterCard("Insect", new Resource(1), 1, 1), new WritableController_Provider(), new ConstantValueProvider<int, Controlled>(2))));
return card;
}
}
public static Readable_MonsterCard LootHorder
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Loot Horder", new Resource(2), 2, 1);
card.Add_AfterDeath_Trigger(new GameTrigger<GameEffect>(new DrawEffect(new WritableController_Provider())));
return card;
}
}
public static SpellCard Wrath
{
get
{
SpellCard card = new SpellCard("Wrath", new Resource(2));
GameEffect bigDamage = LifeEffect.Targeted(new ConstantValueProvider<int, Controlled>(-3), new AllMonsters_Provider(), new ReadableController_Provider());
GameEffect smallDamage = LifeEffect.Targeted(new ConstantValueProvider<int, Controlled>(-1), new AllMonsters_Provider(), new ReadableController_Provider());
GameEffect draw = new DrawEffect(new WritableController_Provider());
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(new ChoiceEffect(bigDamage, new Composite_GameEffect(smallDamage, draw))));
return card;
}
}
public static Readable_MonsterCard EarthenRingFarseer
{
get
{
// There is a monster called "Earthen Ring Farseer" that costs 3 and is a 3/3
Writable_MonsterCard card = new Writable_MonsterCard("Earthen Ring Farseer", new Resource(3), 3, 3);
// Make a trigger that triggers after playing this card, which generates an effect that provides 3 life to the controller of the effect
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(LifeEffect.Targeted(new ConstantValueProvider<int, Controlled>(3), new LifeTarget_Choices_Provider(), new ReadableController_Provider())));
return card;
}
}
public static Readable_MonsterCard IronfurGrizzly
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Ironfur Grizzly", new Resource(3), 3, 3);
card.MustBeAttacked = true;
return card;
}
}
public static SpellCard ArcaneIntellect
{
get
{
SpellCard card = new SpellCard("Arcane Intellect", new Resource(3));
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(new DrawEffect(new WritableController_Provider(), DrawFromDeck_Provider.FromController(), new ConstantValueProvider<int, Controlled>(2))));
return card;
}
}
public static SpellCard FanOfKnives
{
get
{
SpellCard card = new SpellCard("Fan of Knives", new Resource(3));
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(LifeEffect.Blanket(new ConstantValueProvider<int, Controlled>(-1), new EnemyMonsters_Provider())));
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(new DrawEffect()));
return card;
}
}
/*public static Readable_MonsterCard KingMukla
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("King Mukla", new Resource(3), 5, 5);
//card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(new DrawEffect(new OpponentsProvider(), new ConstantValueProvider<ReadableCard, Controlled>(new SpellCard))))
return card;
}
}*/
public static Readable_MonsterCard ChillwindYeti
{
get
{
return new Writable_MonsterCard("Chillwind Yeti", new Resource(4), 4, 5);
}
}
public static Readable_MonsterCard SenjinShieldMasta
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Sen'jin SheildMasta", new Resource(4), 3, 5);
card.MustBeAttacked = true;
return card;
}
}
public static SpellCard Fireball
{
get
{
SpellCard card = new SpellCard("Fireball", new Resource(4));
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(LifeEffect.Targeted(new ConstantValueProvider<int, Controlled>(-6), new LifeTarget_Choices_Provider(), new ReadableController_Provider())));
return card;
}
}
public static SpellCard Hellfire
{
get
{
SpellCard card = new SpellCard("Hellfire", new Resource(4));
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(LifeEffect.Blanket(new ConstantValueProvider<int, Controlled>(-3), new LifeTarget_Choices_Provider())));
return card;
}
}
public static SpellCard Consecration
{
get
{
SpellCard card = new SpellCard("Consecration", new Resource(4));
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(LifeEffect.Blanket(new ConstantValueProvider<int, Controlled>(-2), new OpponentsProvider())));
return card;
}
}
public static Readable_MonsterCard AzureDrake
{
get
{
// There is a card called "Azure Drake" that costs 5 and is a 4/4
Writable_MonsterCard card = new Writable_MonsterCard("Azure Drake", new Resource(5), 4, 4);
// Make a trigger that triggers after playing this card, and has the effect's controller draw one card from his/her deck
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(new DrawEffect(new WritableController_Provider())));
// TODO: add in the spell damage effect from Azure Drake once the engine works
return card;
}
}
public static Readable_MonsterCard SludgeBelcher
{
get
{
// There is a card called "Sludge Belcher" that costs 5 and is a 3/5
Writable_MonsterCard card = new Writable_MonsterCard("Sludge Belcher", new Resource(5), 3, 5);
card.MustBeAttacked = true; // Taunt
// Create a 1/2 taunt for referencing in a moment
Writable_MonsterCard slime = new Writable_MonsterCard("Slime", new Resource(1), 1, 2);
slime.MustBeAttacked = true;
card.Add_AfterDeath_Trigger(new GameTrigger<GameEffect>(new SpawnMonster_Effect(slime, new WritableController_Provider())));
return card;
}
}
public static SpellCard Starfall
{
get
{
SpellCard card = new SpellCard("Starfall", new Resource(5));
GameEffect blanket = LifeEffect.Blanket(new ConstantValueProvider<int, Controlled>(-2), new EnemyMonsters_Provider());
GameEffect target = LifeEffect.Targeted(new ConstantValueProvider<int, Controlled>(-5), new EnemyMonsters_Provider(), new ReadableController_Provider());
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(new ChoiceEffect(blanket, target)));
return card;
}
}
public static Readable_MonsterCard SilverHandKnight
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Silver Hand Knight", new Resource(5), 4, 4);
Writable_MonsterCard squire = new Writable_MonsterCard("Squire", new Resource(1), 2, 2);
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(new SpawnMonster_Effect(squire)));
return card;
}
}
public static Readable_MonsterCard Sunwalker
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Sunwalker", new Resource(6), 4, 5);
card.Add_SingleUse_Shield(); // Divine Shield
card.MustBeAttacked = true; // Taunt
return card;
}
}
public static Readable_MonsterCard CairneBloodhoof
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Cairne Bloodhoof", new Resource(6), 4, 5);
Writable_MonsterCard reincarnation = new Writable_MonsterCard("Baine Bloodhoof", new Resource(4), 4, 5);
card.Add_AfterDeath_Trigger(new GameTrigger<GameEffect>(new SpawnMonster_Effect(reincarnation, new WritableController_Provider())));
return card;
}
}
public static Readable_MonsterCard FireElemental
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Fire Elemental", new Resource(6), 6, 5);
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(LifeEffect.Targeted(new ConstantValueProvider<int, Controlled>(-3), new LifeTarget_Choices_Provider(), new ReadableController_Provider())));
return card;
}
}
public static SpellCard Starfire
{
get
{
SpellCard card = new SpellCard("Starfire", new Resource(6));
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(LifeEffect.Targeted(new ConstantValueProvider<int, Controlled>(-5), new LifeTarget_Choices_Provider(), new ReadableController_Provider())));
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(new DrawEffect(new WritableController_Provider())));
return card;
}
}
public static Readable_MonsterCard WarGolem
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("War Golemn", new Resource(7), 7, 7);
return card;
}
}
public static SpellCard Sprint
{
get
{
SpellCard card = new SpellCard("Sprint", new Resource(7));
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(new DrawEffect(new WritableController_Provider(), DrawFromDeck_Provider.FromController(), new ConstantValueProvider<int, Controlled>(4))));
return card;
}
}
public static SpellCard Flamestrike
{
get
{
SpellCard card = new SpellCard("Flamestrike", new Resource(7));
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(LifeEffect.Blanket(new ConstantValueProvider<int, Controlled>(-4), new EnemyMonsters_Provider())));
return card;
}
}
public static Readable_MonsterCard IronbarkProtector
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Ironbark Protector", new Resource(8), 8, 8);
card.MustBeAttacked = true;
return card;
}
}
public static Readable_MonsterCard Cenarius
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Cenarius", new Resource(9), 5, 8);
Writable_MonsterCard treant = new Writable_MonsterCard("Treant", new Resource(2), 2, 2);
treant.MustBeAttacked = true;
card.Add_AfterPlayCard_Trigger(new GameTrigger<GameEffect>(new SpawnMonster_Effect(treant, new WritableController_Provider(), new ConstantValueProvider<int, Controlled>(2))));
return card;
}
}
public static Readable_MonsterCard AlAkir
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Al'Akir the Windlord", new Resource(8), 3, 5);
card.Add_SingleUse_Shield();
card.MustBeAttacked = true;
card.NumAttacksPerTurn = card.NumAttacksRemaining = 2;
return card;
}
}
/*
public static Readable_MonsterCard Ragnaros
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Ragnaros, the Firelord", new Resource(8), 8, 8);
card.NumAttacksPerTurn = 0;
}
}
*/
/*public static Readable_MonsterCard Ysera
{
get
{
Writable_MonsterCard card = new Writable_MonsterCard("Ysera", new Resource(9), 4, 12);
return card;
}
}
*/
}
}
|
01eb4b770daf5287eb7924af68660c1862d90811
|
C#
|
BobbyWeaver2015/SuperConfig
|
/exporter/exporter/ExporterCS.cs
| 2.734375
| 3
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace exporter
{
public static partial class Exporter
{
static string FixFloat(string format)
{
Regex reg = new Regex("\\d+\\.\\d+(?!f)");
return reg.Replace(format, match => match.Value + "f");
}
public static string TitleToUpper(this string str)
{
if (string.IsNullOrWhiteSpace(str))
return string.Empty;
char[] s = str.ToCharArray();
char c = s[0];
if ('a' <= c && c <= 'z')
c = (char) (c & ~0x20);
s[0] = c;
return new string(s);
}
/// <summary>
/// 声明CS
/// </summary>
static void AppendCSDeclara(ISheet sheet, int col, bool canWrite, StringBuilder sb)
{
Dictionary<string, List<int>> sameKeyDeclaras = new Dictionary<string, List<int>>();
Regex regex = new Regex(@"(\d+)$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
for (int i = 0; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null)
continue;
ICell cell1 = row.GetCell(col, MissingCellPolicy.RETURN_NULL_AND_BLANK);
ICell cell2 = row.GetCell(col + 1, MissingCellPolicy.RETURN_NULL_AND_BLANK);
if (cell1 == null || cell2 == null || cell1.CellType == CellType.Blank ||
cell2.CellType == CellType.Blank)
continue;
if (cell1.CellType != CellType.String || cell2.CellType != CellType.String)
throw new System.Exception("检查输入第" + (i + 1) + "行,sheetname=" + sheet.SheetName);
string note = cell1.StringCellValue;
string name = cell2.StringCellValue;
if (string.IsNullOrEmpty(note) || string.IsNullOrEmpty(name) || name.StartsWith("_"))
continue;
sb.Append("public float Get" + name.Substring(0, 1).ToUpper() + name.Substring(1) + "() { //" + note +
"\r\n");
sb.Append("\treturn get(" + ((i + 1) * 1000 + col * 1 + 3) + ");\r\n");
sb.Append("}\r\n");
if (canWrite)
{
sb.Append("public void Set" + name.Substring(0, 1).ToUpper() + name.Substring(1) + "(float v) {//" +
note + "\r\n");
sb.Append("\tset(" + ((i + 1) * 1000 + col + 3) + ",v);\r\n");
sb.Append("}\r\n");
}
var m = regex.Match(name);
if (m.Success && name.Length > m.Value.Length)
{
var key = name.Substring(0, name.Length - m.Value.Length);
if (!sameKeyDeclaras.ContainsKey(key))
sameKeyDeclaras.Add(key, new List<int>());
sameKeyDeclaras[key].Add(int.Parse(m.Value));
}
}
foreach (var sd in sameKeyDeclaras)
{
if (sd.Value.Count < 2)
continue;
var name = sd.Key.Substring(0, 1).ToUpper() + sd.Key.Substring(1);
sb.Append("public float Get" + name + "(int key) {\r\n");
sb.Append("switch (key){\r\n");
foreach (var kv in sd.Value.OrderBy(kv => kv))
sb.Append("case " + kv + ": return Get" + name + kv + "();\r\n");
sb.Append("}\r\n");
sb.Append("return 0;\r\n");
sb.Append("}\r\n");
if (!canWrite)
continue;
sb.Append("public void Set" + name + "(int key, float v) {\r\n");
sb.Append("switch (key){\r\n");
foreach (var kv in sd.Value.OrderBy(kv => kv))
sb.Append("case " + kv + ": Set" + name + kv + "(v); break;\r\n");
sb.Append("}\r\n");
sb.Append("}\r\n");
}
}
static int CmpLen(List<object> l, List<object> r)
{
var sr = (string) r[1];
var sl = (string) l[1];
return sr.Length.CompareTo(sl.Length);
}
public static string DealWithFormulaSheetCS(ISheet sheet)
{
CodeTemplate.curlang = CodeTemplate.Langue.CS;
StringBuilder sb = new StringBuilder();
Dictionary<CellCoord, List<CellCoord>> abouts = new Dictionary<CellCoord, List<CellCoord>>();
string sheetName = sheet.SheetName.Substring(3);
string SheetName = sheetName.Substring(0, 1).ToUpper() + sheetName.Substring(1);
string className = SheetName + "FormulaSheet";
sb.Append("using System;\r\n");
sb.Append("using System.Collections;\r\n");
sb.Append("using System.Collections.Generic;\r\n");
sb.Append("\r\n");
// 扩展Config类统一获取某个表的实例对象
sb.Append("public partial class Config {\r\n");
sb.Append("\tpublic static " + className + " New" + className + "(){\r\n");
sb.Append("\t\tvar formula = new " + className + "();\r\n");
sb.Append("\t\tformula.Init();\r\n");
sb.Append("\t\treturn formula;\r\n");
sb.Append("\t}\r\n");
sb.Append("}\r\n");
//------
// 开始生成这个配置表的算法类
sb.Append("public class " + className + " : FormulaSheet { //定义数据表类开始\r\n");
sb.Append("public void Init(){\r\n");
// 数据内容
for (int rownum = 0;
rownum <= sheet.LastRowNum;
rownum++)
{
IRow row = sheet.GetRow(rownum);
if (row == null)
continue;
for (int i = 0; i < row.Cells.Count; i++)
{
ICell cell = row.Cells[i];
int colnum = cell.ColumnIndex;
// in、out声明忽略
if (colnum == 0 || colnum == 1 || colnum == 3 || colnum == 4)
continue;
if (cell.CellType == CellType.Boolean || cell.CellType == CellType.Numeric)
{
sb.Append("this.datas[" + ((rownum + 1) * 1000 + colnum + 1) + "] = " +
(cell.CellType == CellType.Boolean
? (cell.BooleanCellValue ? 1 : 0).ToString()
: cell.NumericCellValue.ToString()) + "f;\r\n");
}
else if (cell.CellType == CellType.Formula)
{
List<CellCoord> about;
sb.Append("this.funcs[" + ((rownum + 1) * 1000 + colnum + 1) + "] = ins => {\r\n");
string content = Formula2Code.Translate(sheet, cell.CellFormula, cell.ToString(), out about);
if (CodeTemplate.curlang == CodeTemplate.Langue.CS)
{
content = FixFloat(content);
}
sb.Append("\treturn (float)" + content + ";\r\n");
sb.Append("};\r\n");
CellCoord cur = new CellCoord(rownum + 1, colnum + 1);
foreach (CellCoord cc in about)
{
if (!abouts.ContainsKey(cc))
abouts.Add(cc, new List<CellCoord>());
if (!abouts[cc].Contains(cur))
abouts[cc].Add(cur);
}
}
}
}
// 数据影响关联递归统计
bool change;
do
{
change = false;
foreach (var item in abouts)
{
for (int i = 0; i < item.Value.Count; i++)
{
if (abouts.ContainsKey(item.Value[i]))
{
foreach (var c in abouts[item.Value[i]])
{
if (!item.Value.Contains(c))
{
item.Value.Add(c);
change = true;
}
}
}
}
}
} while (change);
// 数据影响关联
foreach (var item in abouts)
sb.Append("this.relation[" + (item.Key.row * 1000 + item.Key.col) + "] = new int[]{" +
string.Join(",", item.Value.Select(c => { return c.row * 1000 + c.col; })) + "};\r\n");
sb.Append("} // 初始化数据结束\r\n");
// 声明
AppendCSDeclara(sheet, 0, true, sb);
AppendCSDeclara(sheet, 3, false, sb);
// 枚举器
foreach (var item in FormulaEnumerator.GetList(sheet))
{
// 写结构
sb.Append("public struct " + item.fullName + " {\r\n");
// 属性
sb.Append("\tpublic " + className + " sheet;\r\n");
sb.Append("\t int line;\r\n");
for (int i = 0;
i < item.propertys.Count;
i++)
sb.Append("\tfloat " + item.propertys[i] + "; // " + item.notes[i] + "\r\n");
// 枚举方法
sb.Append("public bool MoveNext() {\r\n");
// MoveNext
sb.Append("\tif (line <= 0) {\r\n");
sb.Append("\t\tline = " + (item.start + 1) * 1000 + ";\r\n");
sb.Append("\t} else {\r\n");
sb.Append("\t\tline = line + " + item.div * 1000 + ";\r\n");
sb.Append("}\r\n");
sb.Append("\tif (line >= " + (item.end + 1) * 1000 + ") {\r\n");
sb.Append("\t\treturn false;\r\n");
sb.Append("}\r\n");
sb.Append("\tif (sheet.get(line+" + (6 + 1000 * (item.key - 1)) + ") == 0 ) {\r\n");
sb.Append("\t\treturn MoveNext();\r\n");
sb.Append("}\r\n");
for (int i = 0;
i < item.propertys.Count;
i++)
sb.Append("" + item.propertys[i] + " = sheet.get(line+" + (6 + 1000 * i) + ");\r\n");
sb.Append("\treturn true;\r\n");
sb.Append("} // 枚举方法next结束\r\n");
sb.Append("} // 枚举struct定义结束\r\n");
// GetEnumerator
sb.Append("public " + item.fullName + " Get" + item.name + "Enumerator(){\r\n");
sb.Append("\tvar enumerator = new " + item.fullName + "();\r\n");
sb.Append("\t\tenumerator.sheet = this;\r\n");
sb.Append("\t\treturn enumerator;\r\n");
sb.Append("}\r\n");
}
sb.Append("}\r\n");
// 结果
formulaContents.Add(SheetName, sb.ToString());
return string.Empty;
}
public static string ExportCS(string codeExportDir, string configExportDir)
{
// 目录清理
if (Directory.Exists(configExportDir))
new DirectoryInfo(configExportDir).GetFiles().Where(f => f.Extension == ".json")
.ToList().ForEach(fi => { fi.Delete(); });
else
Directory.CreateDirectory(configExportDir);
if (!Directory.Exists(codeExportDir)) Directory.CreateDirectory(codeExportDir);
new DirectoryInfo(codeExportDir).GetFiles("data_*.cs").ToList<FileInfo>().ForEach(fi => { fi.Delete(); });
new DirectoryInfo(codeExportDir).GetFiles("formula_*.cs").ToList<FileInfo>()
.ForEach(fi => { fi.Delete(); });
// stream加载的接口
Dictionary<string, string> typestream_read = new Dictionary<string, string>();
typestream_read.Add("int", "ReadInt32");
typestream_read.Add("string", "ReadString");
typestream_read.Add("double", "ReadDouble");
typestream_read.Add("float", "ReadSingle");
typestream_read.Add("int32", "ReadInt32");
typestream_read.Add("long", "ReadInt64");
// 类型转换
Dictionary<string, string> typeconvert = new Dictionary<string, string>();
typeconvert.Add("int", "int");
typeconvert.Add("int32", "int");
typeconvert.Add("long", "long");
typeconvert.Add("string", "string");
typeconvert.Add("float", "float");
typeconvert.Add("double", "double");
typeconvert.Add("[]int", "int[]");
typeconvert.Add("[]int32", "int[]");
typeconvert.Add("[]long", "long[]");
typeconvert.Add("[]string", "string[]");
typeconvert.Add("[]double", "double[]");
typeconvert.Add("[]float", "float[]");
// 索引类型转换
Dictionary<string, string> mapTypeConvert = new Dictionary<string, string>();
mapTypeConvert.Add("int", "int");
mapTypeConvert.Add("float", "float");
mapTypeConvert.Add("int32", "int");
mapTypeConvert.Add("string", "string");
mapTypeConvert.Add("float32", "float");
mapTypeConvert.Add("double", "double");
int goWriteCount = 0;
List<string> loadfuncs = new List<string>();
List<string> clearfuncs = new List<string>();
List<string> savefuncs = new List<string>();
// 写公式
foreach (var formula in formulaContents)
{
File.WriteAllText(codeExportDir + "formula_" + formula.Key.ToLower() + ".cs", formula.Value,
new UTF8Encoding(false));
Interlocked.Increment(ref goWriteCount);
// lock (loadfuncs) loadfuncs.Add("loadFormula" + formula.Key);
}
List<string> results = new List<string>();
// 写cs
foreach (var data in datas.Values)
{
ThreadPool.QueueUserWorkItem(ooo =>
{
string str = data.name.Substring(0, 1).ToUpper() + data.name.Substring(1);
string text = str + "Table";
string text2 = str + "Config";
string text3 = str + "TableGroup";
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.Append("using System;\r\n");
stringBuilder2.Append("using UnityEngine;\r\n");
stringBuilder2.Append("using System.Collections;\r\n");
stringBuilder2.Append("using System.Collections.Generic;\r\n");
stringBuilder2.Append("using Model.Load;\r\n");
stringBuilder2.Append("\r\n");
stringBuilder2.Append("public partial class Config {\r\n");
stringBuilder2.Append(string.Concat(new string[]
{
"\tstatic ",
text,
" _",
text,
";\r\n"
}));
stringBuilder2.Append(string.Concat(new string[]
{
"\tpublic static ",
text,
" Get",
text,
"(){\r\n"
}));
stringBuilder2.Append(string.Format("\tif({0} == null) Load{1}();\r\n", "_" + text, text));
stringBuilder2.Append("\t\treturn _" + text + ";\r\n");
stringBuilder2.Append("\t}\r\n");
stringBuilder2.Append("\tpublic static void Load" + text + "(){\r\n");
stringBuilder2.Append(string.Format(
"\t\tvar json = SuperLoader.LoadConfig(\"{0}\").text;\r\n", data.name));
stringBuilder2.Append(string.Format("\t\t{0} = LitJson.JsonMapper.ToObject<{1}>(json);\r\n",
"_" + text, text));
stringBuilder2.Append("\t}\r\n");
stringBuilder2.Append(string.Format("\tpublic static void Clear{0} () {{\r\n", text));
stringBuilder2.Append(string.Format("\t\t_{0} = null;\r\n", text));
stringBuilder2.Append("\t}\r\n");
lock (clearfuncs)
{
clearfuncs.Add("Config.Clear" + text);
}
stringBuilder2.Append("}\r\n");
stringBuilder2.Append("public class " + text3 + " {\r\n");
foreach (KeyValuePair<string, string[]> current4 in data.groups)
{
stringBuilder2.Append("\tpublic ");
string[] value = current4.Value;
for (int i = 0; i < value.Length; i++)
{
string text4 = value[i];
stringBuilder2.Append("Dictionary<string,");
}
stringBuilder2.Append("int[]");
string[] value2 = current4.Value;
for (int j = 0; j < value2.Length; j++)
{
string text5 = value2[j];
stringBuilder2.Append(">");
}
stringBuilder2.Append(" ");
string str2 = current4.Key.Substring(0, 1).ToUpper() +
current4.Key.Replace("|", "_").Substring(1);
stringBuilder2.Append(str2 + ";\r\n");
}
stringBuilder2.Append("}\r\n");
stringBuilder2.Append("public class " + text2 + " {\r\n");
for (int k = 0; k < data.keys.Count; k++)
{
stringBuilder2.Append(string.Concat(new string[]
{
"\tpublic ",
typeconvert[data.types[k]],
" ",
data.keys[k].Substring(0, 1).ToUpper(),
data.keys[k].Substring(1),
"; // ",
data.keyNames[k],
"\r\n"
}));
}
stringBuilder2.Append("}\r\n");
stringBuilder2.Append("// " + string.Join(",", data.files) + "\r\n");
stringBuilder2.Append("public class " + text + " {\r\n");
stringBuilder2.Append("\tpublic string Name;\r\n");
stringBuilder2.Append(string.Format("\tpublic Dictionary<string, {0}> _Datas;\r\n", text2));
stringBuilder2.Append(string.Format("\tpublic {0} _Group;\r\n", text3));
foreach (KeyValuePair<string, string[]> current5 in data.groups)
{
string str3 = current5.Key.Substring(0, 1).ToUpper() +
current5.Key.Replace("|", "_").Substring(1);
stringBuilder2.Append("\tprivate ");
stringBuilder2.Append("Dictionary<string,");
stringBuilder2.Append(text2 + "[]> " + str3 + "_Cached = new ");
stringBuilder2.Append("Dictionary<string," + text2 + "[]>();\r\n");
}
stringBuilder2.Append("public " + text2 + " Get(int id) {\r\n");
stringBuilder2.Append("\tstring k = id.ToString();\r\n");
stringBuilder2.Append("\t" + text2 + " ret;\r\n");
stringBuilder2.Append("\tif (_Datas.TryGetValue(k,out ret))\r\n");
stringBuilder2.Append("\t\treturn ret;\r\n");
stringBuilder2.Append("\treturn null;\r\n");
stringBuilder2.Append("}\r\n");
foreach (KeyValuePair<string, string[]> current6 in data.groups)
{
string text6 = current6.Key.Substring(0, 1).ToUpper() +
current6.Key.Replace("|", "_").Substring(1);
stringBuilder2.Append(string.Concat(new string[]
{
"\tpublic ",
text2,
"[] Get_",
current6.Key.Replace("|", "_"),
"("
}));
string[] value3 = current6.Value;
for (int l = 0; l < value3.Length; l++)
{
string text7 = value3[l];
stringBuilder2.Append(string.Concat(new string[]
{
mapTypeConvert[typeconvert[data.types[data.keys.IndexOf(text7)]]],
" ",
text7.Substring(0, 1).ToUpper(),
text7.Substring(1),
","
}));
}
stringBuilder2.Remove(stringBuilder2.Length - 1, 1);
stringBuilder2.Append(") {\r\n");
string text8 = "string.Empty";
string[] value4 = current6.Value;
for (int m = 0; m < value4.Length; m++)
{
string text9 = value4[m];
string str4 = text9.Substring(0, 1).ToUpper() + text9.Substring(1);
text8 = text8 + "+" + str4 + "+\"_\"";
}
string str5 = text6 + "_Cached";
stringBuilder2.Append("string cach_key = " + text8 + ";\r\n");
stringBuilder2.Append(text2 + "[] ret;\r\n");
stringBuilder2.Append("if(" + str5 + ".TryGetValue(cach_key,out ret))\r\n");
stringBuilder2.Append("\treturn ret;\r\n");
string text10 = "_Group." + text6;
string text11 = "";
for (int n = 0; n < current6.Value.Length; n++)
{
bool flag4 = n == 0;
if (flag4)
{
stringBuilder2.Append("if (" + text10 + ".ContainsKey(");
text11 = current6.Value[n].Substring(0, 1).ToUpper() + current6.Value[n].Substring(1);
stringBuilder2.Append(text11 + ".ToString()) ){\r\n");
}
else
{
string text12 = "tmp" + (n - 1);
stringBuilder2.Append(string.Concat(new string[]
{
"var ",
text12,
" = ",
text10,
"[",
text11,
".ToString()];\r\n"
}));
stringBuilder2.Append("if (" + text12 + ".ContainsKey(");
text10 = text12;
text11 = current6.Value[n].Substring(0, 1).ToUpper() + current6.Value[n].Substring(1);
stringBuilder2.Append(text11 + ".ToString()) ){\r\n");
}
}
stringBuilder2.Append(string.Concat(new string[]
{
"var ids = ",
text10,
"[",
text11,
".ToString()];\r\n"
}));
stringBuilder2.Append("var configs = new " + text2 + "[ids.Length];\r\n");
stringBuilder2.Append("for (int i = 0; i < ids.Length; i++) {\r\n");
stringBuilder2.Append("\tvar id = ids[i];\r\n");
stringBuilder2.Append("\tconfigs[i] = Get(id);\r\n");
stringBuilder2.Append("}\r\n");
stringBuilder2.Append("\t" + str5 + "[cach_key]=configs;\r\n");
stringBuilder2.Append("return configs;\r\n");
for (int num = 0; num < current6.Value.Length; num++)
{
stringBuilder2.Append("}\r\n");
}
stringBuilder2.Append("return new " + text2 + "[0];\r\n");
stringBuilder2.Append("}\r\n");
}
for (int num2 = 0; num2 < data.keys.Count; num2++)
{
bool flag5 = data.types[num2] == "string" || data.types[num2].StartsWith("[]");
if (!flag5)
{
stringBuilder2.Append(string.Concat(new object[]
{
"\tpublic float data_",
data.name,
"_vlookup_",
data.cols[num2] + 1,
"(int id) {\r\n"
}));
stringBuilder2.Append(string.Concat(new string[]
{
"\treturn (float)(Config.Get",
text,
"()._Datas[id.ToString()].",
data.keys[num2].Substring(0, 1).ToUpper(),
data.keys[num2].Substring(1),
");\r\n"
}));
stringBuilder2.Append("}\r\n");
}
}
stringBuilder2.Append("}\r\n");
File.WriteAllText(codeExportDir + "data_" + data.name + ".cs", stringBuilder2.ToString());
Interlocked.Increment(ref goWriteCount);
lock (loadfuncs)
{
loadfuncs.Add("Config.Load" + text);
}
lock (results)
{
results.Add(string.Empty);
}
});
}
// 写json
foreach (var data in datas.Values)
{
ThreadPool.QueueUserWorkItem(ooo =>
{
JObject config = new JObject();
config["Name"] = data.name;
config["Crc32"] = data.crc32;
JObject datas = new JObject();
config["_Datas"] = datas;
foreach (var line in data.dataContent)
{
JObject ll = new JObject();
for (int j = 0; j < data.keys.Count; j++)
ll[data.keys[j].TitleToUpper()] = JToken.FromObject(line[j]);
datas[line[0].ToString()] = ll;
}
JObject group = new JObject();
config["_Group"] = group;
Dictionary<string, string[]>.Enumerator enumerator = data.groups.GetEnumerator();
while (enumerator.MoveNext())
group[enumerator.Current.Key.Replace("|", "_").TitleToUpper()] = new JObject();
foreach (var values in data.dataContent)
{
enumerator = data.groups.GetEnumerator();
while (enumerator.MoveNext())
{
JObject cur = group[enumerator.Current.Key.Replace("|", "_").TitleToUpper()] as JObject;
string key = string.Empty;
for (int j = 0; j < enumerator.Current.Value.Length - 1; j++)
{
key = values[data.groupindexs[enumerator.Current.Key][j]].ToString();
if (cur[key] == null)
cur[key] = new JObject();
cur = cur[key] as JObject;
}
key = values[data.groupindexs[enumerator.Current.Key][enumerator.Current.Value.Length - 1]]
.ToString();
if (cur[key] == null)
cur[key] = new JArray();
(cur[key] as JArray).Add(JToken.FromObject(values[0]));
}
}
StringWriter textWriter = new StringWriter();
textWriter.NewLine = "\r\n";
JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
{
Formatting = Formatting.Indented,
Indentation = 4,
IndentChar = ' '
};
new JsonSerializer().Serialize(jsonWriter, config);
var content = textWriter.ToString();
File.WriteAllText(configExportDir + data.name + ".json", content, new UTF8Encoding(false));
lock (results)
results.Add(string.Empty);
});
}
// 格式化代码
while (goWriteCount < formulaContents.Count + datas.Values.Count)
Thread.Sleep(10);
// 写加载
loadfuncs.Sort();
StringBuilder loadcode = new StringBuilder();
loadcode.Append("using System;\r\n");
loadcode.Append("using System.Collections;\r\n");
loadcode.Append("using System.Collections.Generic;\r\n");
loadcode.Append("\r\n");
// 扩展Config类统一获取某个表的实例对象
loadcode.Append("public partial class Config {\r\n");
// load all
loadcode.Append("\tpublic static void Load() {\r\n");
foreach (var str in loadfuncs)
loadcode.Append("\t" + str + "();\r\n");
loadcode.Append("}\r\n");
// clear all
clearfuncs.Sort();
loadcode.Append("\tpublic static void Clear() {\r\n");
foreach (var str in clearfuncs)
loadcode.Append("\t" + str + "();\r\n");
loadcode.Append("}\r\n");
// save all
savefuncs.Sort();
loadcode.Append("\tpublic static void Save() {\r\n");
foreach (var str in savefuncs)
loadcode.Append("\t" + str + "();\r\n");
loadcode.Append("}\r\n");
loadcode.Append("}\r\n");
File.WriteAllText(codeExportDir + "load.cs", loadcode.ToString());
// 等待所有文件完成
while (results.Count < datas.Values.Count * 2)
Thread.Sleep(TimeSpan.FromSeconds(0.01));
return string.Empty;
}
}
}
|
72d1bb40b3958b33b390793b3484d725cf832db9
|
C#
|
nkyurkchiyski/Calculator
|
/Calculator/Calculator.App/Commands/Memory/RetrieveMemoryCommand.cs
| 2.8125
| 3
|
using Calculator.App.Contracts;
using System;
using System.Collections.Generic;
using System.Text;
namespace Calculator.App.Commands.Memory
{
public class RetrieveMemoryCommand : ICommand
{
private IMemoryController memoryController;
public RetrieveMemoryCommand(IMemoryController memoryController, IList<string> args)
{
this.memoryController = memoryController;
this.Arguments = args;
}
public IList<string> Arguments { get; }
public string Execute()
{
string num = this.memoryController.Memory.ToString();
return num;
}
}
}
|
ac7fa3910c0c14f452aaf854613b8348c5eb57b3
|
C#
|
VicenzoMartinelli/seisicite-api
|
/Application.Api/Messages/IdentityErrorDescriber.cs
| 2.53125
| 3
|
using Domain.Core.Enumerators;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Text;
namespace Application.Api.Messages
{
public class PersonalIdentityErrorDescriber : Microsoft.AspNetCore.Identity.IdentityErrorDescriber
{
private IdentityError GetErrorByReturnCode(ReturnCode code)
{
return new IdentityError()
{
Code = ((int) code).ToString(),
Description = code.GetDisplayValue()
};
}
public override IdentityError DefaultError()
{
return GetErrorByReturnCode(ReturnCode.ImpossivelFinalizarAcao);
}
public override IdentityError ConcurrencyFailure()
{
return DefaultError();
}
public override IdentityError DuplicateEmail(string email)
{
return GetErrorByReturnCode(ReturnCode.EmailExiste);
}
public override IdentityError DuplicateUserName(string userName)
{
return GetErrorByReturnCode(ReturnCode.EmailExiste);
}
public override IdentityError PasswordMismatch()
{
return GetErrorByReturnCode(ReturnCode.UsuarioOuSenhaErrados);
}
public override IdentityError PasswordTooShort(int length)
{
return GetErrorByReturnCode(ReturnCode.TamanhoSenhaInvalido);
}
}
}
|
5e45dd8aeca46325d986b6d1d5ec2b4bb466c2f2
|
C#
|
scopely/leaderboard-csharp
|
/Leaderboard/Redis/RedisConnectionManager.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BookSleeve;
namespace Leaderboard.Redis
{
public class RedisConnectionManager : IRedisConnectionManager
{
private volatile RedisConnection _connection;
private readonly object _connectionLock = new object();
public string Host { get; set; }
public int Port { get; set; }
public int IOTimeout { get; set; }
public string Password { get; set; }
public int MaxUnsent { get; set; }
public bool AllowAdmin { get; set; }
public int SyncTimeout { get; set; }
public RedisConnectionManager(string host, int port = 6379, int ioTimeout = -1, string password = null, int maxUnsent = Int32.MaxValue, bool allowAdmin = false, int syncTimeout = 10000)
{
Host = host;
Port = port;
IOTimeout = ioTimeout;
Password = password;
MaxUnsent = maxUnsent;
AllowAdmin = allowAdmin;
SyncTimeout = syncTimeout;
}
public RedisConnection GetConnection()
{
return GetConnection(false);
}
public RedisConnection GetConnection(bool waitOnOpen)
{
var connection = _connection;
if (connection == null)
{
lock (_connectionLock)
{
if (_connection == null)
{
_connection = new RedisConnection(Host, Port, IOTimeout, Password, MaxUnsent, AllowAdmin, SyncTimeout);
_connection.Shutdown += ConnectionOnShutdown;
var openTask = _connection.Open();
if (waitOnOpen) { _connection.Wait(openTask); }
}
connection = _connection;
}
}
return connection;
}
public void Reset()
{
Reset(false);
}
public void Reset(bool abort)
{
lock (_connectionLock)
{
if (_connection != null)
{
_connection.Close(abort);
_connection = null;
}
}
}
public void Dispose()
{
lock (_connectionLock)
{
if (_connection != null)
{
_connection.Dispose();
_connection = null;
}
}
}
private void ConnectionOnShutdown(object sender, ErrorEventArgs errorEventArgs)
{
lock (_connectionLock)
{
_connection.Shutdown -= ConnectionOnShutdown;
_connection = null;
}
}
}
}
|
6f6869ac80078ec07e4dcb20601ca553dc384c3f
|
C#
|
joecamp/Tactical-RPG
|
/Assets/Scripts/Utilities.cs
| 2.890625
| 3
|
public static class Utilities {
public static float Normalize (float val, float min, float max) {
return (val - min) / (max - min);
}
}
|
ce581111d658286d515bb750cf03ddfb560082d3
|
C#
|
lanicon/sharpneat-refactor
|
/src/SharpNeat/Graphs/IActivationFunctionLibrary.cs
| 2.59375
| 3
|
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2020 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software; you can redistribute it and/or modify
* it under the terms of The MIT License (MIT).
*
* You should have received a copy of the MIT License
* along with SharpNEAT; if not, see https://opensource.org/licenses/MIT.
*/
using SharpNeat.NeuralNets;
namespace SharpNeat.Graphs
{
/// <summary>
/// Represents a library of activation functions. Primarily for use in HyperNEAT CPPNs which define
/// a activation function per CPPN node.
/// </summary>
public interface IActivationFunctionLibrary
{
/// <summary>
/// Gets an instance of an activation function with the specified index in the library.
/// </summary>
/// <param name="idx">Activation function index.</param>
/// <typeparam name="T">Activation function numeric data type.</typeparam>
/// <returns>An instance of <see cref="IActivationFunction{T}"/> from the library.</returns>
IActivationFunction<T> GetActivationFunction<T>(int idx) where T : struct;
/// <summary>
/// Gets an instance of an activation function with the specified ID in the library.
/// </summary>
/// <param name="id">Activation function ID.</param>
/// <typeparam name="T">Activation function numeric data type.</typeparam>
/// <returns>An instance of <see cref="IActivationFunction{T}"/> from the library.</returns>
IActivationFunction<T> GetActivationFunction<T>(string id) where T : struct;
}
}
|
e4b9cb5e24aa46dc266f1caab2d77e0e9ef4ca86
|
C#
|
mattorus/CodingPatterns
|
/ListNode.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingPatterns
{
public class ListNode
{
public int Val { get; set; }
public ListNode Next { get; set; }
public ListNode(int val = -1, ListNode next = null)
{
Val = val;
Next = next;
}
}
}
|
d2b7f60b8e8bc4f25d74bb3d417f31cba30b64d1
|
C#
|
venkidamon/CSharp_EntityFramework_MSSQL_WebApplication
|
/CarPoolingV1/Repository/RideRepository.cs
| 2.890625
| 3
|
using CarPool.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web;
namespace CarPool.Repository
{
public class RideRepository : IRideRepository
{
private RideDbContext db;
public RideRepository(RideDbContext context)
{
this.db = context;
}
public int AddRide(Ride ride)
{
try
{
db.Rides.Add(ride);
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
/*return -1;*/
}
return 1;
}
public int Disable(string rideCode)
{
Ride ride = GetRideByCode(rideCode);
if (ride != null)
{
db.Rides.Remove(ride);
db.SaveChanges();
return 1;
}
return -1;
}
public List<Ride> GetActiveRides()
{
return(db.Rides.Where(x => (x.BookedCount < x.SeatCount) && (x.Status == "New")).ToList());
}
public List<Ride> GetActiveRidesByRider(string rider)
{
return db.Rides.Where(x => (x.RiderName == rider)).ToList();
}
public Ride GetRideByCode(string rideCode)
{
return db.Rides.Find(rideCode);
}
public int UpdateRide(Ride c)
{
db.Entry(c).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return 1;
}
public int? UpdateRideManagementCount(string RideCode)
{
throw new NotImplementedException();
}
}
}
|
ab28810e1dea9eb0388c7572a8d4203c55e9b093
|
C#
|
Taqmuraz/2D_Engine_Full
|
/2DEngine/Game/Rendering/TextRenderer.cs
| 2.828125
| 3
|
namespace _2DEngine.Game
{
public sealed class TextRenderer : Renderer
{
protected override int queue => int.MaxValue;
protected override bool isActive => true;
public string text { get; set; } = "New Text";
public Color32 color { get; set; } = new Color32(1f, 1f, 1f, 1f);
public Vector2 screenSpacePosition { get; set; }
protected override void Draw(IGraphics graphics)
{
graphics.DrawString(screenSpacePosition, text, color);
}
}
}
|
3c1c99abe15d17cd83a544a394c4550ad15418e3
|
C#
|
Zealdequar/tvprogviewer
|
/src/TVProgViewer/Classes/Statics.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using TVProgViewer.TVProgApp.Dialogs;
using TVProgViewer.TVProgApp.Logger;
using TVProgViewer.TVProgApp.Properties;
namespace TVProgViewer.TVProgApp.Classes
{
static class Statics
{
private static Thread splashThread;
private static PleaseWaitForm splash;
public static ExceptionLogger EL;
public static DialogResult ShowDialog(string caption, string text,
MessageDialog.MessageIcon messageIcon, MessageDialog.MessageButtons messageButtons)
{
MessageDialog msgDlg = new MessageDialog(caption, text, messageIcon, messageButtons);
return msgDlg.ShowDialog();
}
public static void ShowTODO ()
{
MessageBox.Show("TODO");
}
private static void ShowThread()
{
splash = new PleaseWaitForm();
splash.Show();
Application.Run(splash);
}
/// <summary>
/// Отображение
/// </summary>
public static void ShowLogo(string txt, int value)
{
if (Settings.Default.FlagDontShowLogo) return;
Status = txt;
Progress = value;
if (splashThread != null)
return;
splashThread = new Thread(ShowThread) { IsBackground = true };
//splashThread.ApartmentState = ApartmentState.MTA;
splashThread.Start();
Status = txt;
Progress = value;
}
/// <summary>
/// Скрытие
/// </summary>
public static void HideLogo()
{
if (Settings.Default.FlagDontShowLogo) return;
if (splashThread == null) return;
if (splash == null) return;
try
{
if (splash.InvokeRequired)
{
splash.Invoke(new MethodInvoker(splash.Hide));
}
else {splash.Hide();}
}
catch (Exception ex)
{
Statics.EL.LogException(ex);
}
splashThread = null;
splash = null;
}
/// <summary>
/// Задание Статуса(лейбла)
/// </summary>
public static string Status
{
set
{
if (splash == null)
{
Thread.CurrentThread.Join(600);
}
try
{
splash.TXT = value;
}
catch (NullReferenceException)
{
}
}
get
{
if (splash == null)
{
return "";
}
return splash.TXT;
}
}
/// <summary>
/// Задание значения прогресса
/// </summary>
public static int Progress
{
set
{
if (splash == null)
{
Thread.CurrentThread.Join(600);
}
try
{
splash.Value = value;
}
catch (NullReferenceException)
{
}
}
get
{
if (splash == null)
{
return 0;
}
return splash.Value;
}
}
}
}
|
91fab6d34c34531f7d8f319f8febc413cab45d0f
|
C#
|
ComputationalReflection/StaDyn
|
/Wrong Test Cases/KnownIssues/Partially.Fixed.Unboxing.ObjectAttr.cs
| 3.140625
| 3
|
using System;
namespace Boxing.CastExpression
{
public class Program
{
public object attr;
public static void Main(string[] args)
{
Program p = new Program();
p.attr = 220;
//Causes a silent error. Condition is false ('unbox.any int32' missing after pushing the object attr.)
//Fixed at revision 1596:
//Added a Promotion in VisitorILCodeGeneration::Visit(CastExpression) when the CastType is a valueType
//and the expression to cast is interanally an object. Is a more specific condition needed??
int myInteger = (int)p.attr;
if(myInteger == 220)
Console.WriteLine("OK");
else Console.WriteLine("Test failed");
}
}
}
|
5138a54c35c37da16d2dbdf5d62e86592fd2df22
|
C#
|
AbrahamMolleda/ProyectoRedesTercerParcial
|
/Controllers/AlumnosControllers.cs
| 2.546875
| 3
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Alumnado.Models;
using Alumnado.Data;
namespace Alumnado.Controllers
{
//api/alumnos
[Route("api/alumnos")]
[ApiController]
public class AlumnosControllers : ControllerBase
{
private readonly IAlumnadoRepo _repository;
public AlumnosControllers(IAlumnadoRepo repositorio)
{
_repository = repositorio;
}
//private readonly MockAlumnosRepo _repository = new MockAlumnosRepo();
//Get api/alumnos
[HttpGet]
public ActionResult<IEnumerable<Alumno>> ObtenerTodoslosAlumnos()
{
var alumnos = _repository.ObtenerTodoslosAlumnos();
return Ok(alumnos);
}
//Get api/alumnos/{id}
[HttpGet("{id}")]
public ActionResult<Alumno> ObtenerAlumnoporID(int id)
{
var alumno = _repository.ObtenerAlumnoporId(id);
return Ok(alumno);
}
}
}
|
c73d74df68050cd6a139cdbdbb527d5004760368
|
C#
|
Juchnowski/TheCommonLibrary
|
/TCL.Extensions.Tests/MathTests.cs
| 2.734375
| 3
|
using NUnit.Framework;
using System;
using TCL.Extensions;
namespace TCL.Extensions.Tests
{
[TestFixture]
public class MathTests
{
[TestCase("2.3000000E-2", 0.023)]
[TestCase("2.3E2", 230)]
[TestCase("2.453E-5", 0.00002453)]
public void ConvertFromStringValid(string input, decimal expected)
{
var result = ExponentsHelper.ConvertFromString(input);
Assert.AreEqual(expected, result);
}
[TestCase(0.00002453, "2.453E-5")]
[TestCase(321, "3.21E+2")]
public void ConvertFromDecimalValid(decimal input, string expected)
{
var result = ExponentsHelper.ConvertFromDecimal(input);
Assert.AreEqual(expected, result);
}
}
}
|
761d82bffa15a067c86aa7881fe31a8cc51f217e
|
C#
|
umardev0/FabLabReservationSystem
|
/client/PWPClient/PWPClient/RESTfulHandler.cs
| 2.828125
| 3
|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PWPClient
{
public class Users
{
}
public class RESTfulHandler
{
public String HTTPGet(String URI)
{
String resp = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
request.AutomaticDecompression = DecompressionMethods.GZip;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
resp = reader.ReadToEnd();
}
}
catch (WebException e)
{
MessageBox.Show("ERROR");
}
return resp;
}
public void HTTPPut(String URI, JObject JSONData)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
request.Method = "PUT";
request.ContentType = "application/json";
byte[] byteArray = Encoding.UTF8.GetBytes(JSONData.ToString());
try
{
request.ContentLength = byteArray.Length;
Stream streamRequest = request.GetRequestStream();
streamRequest.Write(byteArray, 0, byteArray.Length);
streamRequest.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
MessageBox.Show("Status Code: " + (int)response.StatusCode);
}
catch (WebException e)
{
MessageBox.Show("WebException:" +e.Status+ "With response:" +e.Message);
}
}
public void HTTPPost(String URI, JObject JSONData)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
byte[] byteArray = Encoding.UTF8.GetBytes(JSONData.ToString());
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
Console.WriteLine(JSONData.ToString());
try
{
Stream streamRequest = request.GetRequestStream();
streamRequest.Write(byteArray, 0, byteArray.Length);
streamRequest.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
MessageBox.Show("Status Code: " + (int)response.StatusCode);
}
catch (WebException e)
{
MessageBox.Show("WebException:" + e.Status + "With response:" + e.Message);
}
}
public void HTTPDelete(String URI)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
request.Method = "DELETE";
request.ContentType = "application/json";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
MessageBox.Show("Status Code: " + (int)response.StatusCode);
}
catch (WebException e)
{
MessageBox.Show("WebException:" + e.Status + "With response:" + e.Message);
}
}
}
}
|
fce2b5323e3e3a6e637570ed7a01e9a04eb635f1
|
C#
|
phanvanthong/NNLT
|
/AutomataLib/State.cs
| 2.875
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace AutomataLib
{
public class State : BaseMouseHandler, Selectable
{
int _X, _Y;
int _mouse_dx, _mouse_dy;
List<Transition> _transitionList;
Hashtable _transitionHash;
static List<State> stateCollection = new List<State>();
/// <summary>
/// Initializes a new instance of the State class.
/// </summary>
/// <param name="name"></param>
public State(String name)
{
_transitionList = new List<Transition>();
_transitionHash = new Hashtable();
_Label = name;
stateCollection.Add(this);
OnPositionChanged();
}
static State()
{
DisplaySize = 50;
}
public bool IsSelected
{
get;
set;
}
private Rectangle _BoundingRect;
public Rectangle BoundingRect
{
get { return _BoundingRect; }
}
public static State GetStateFromName(string name)
{
foreach (State state in stateCollection)
{
if(state.Label == name)
return state;
}
return null;
}
public static void Clear_stateCollection()
{
stateCollection.Clear();
}
public Hashtable Transitions
{
get
{
return _transitionHash;
}
}
public override bool TrackMouse(object sender, List<BaseMouseHandler> sourceChain,
System.Windows.Forms.MouseEventArgs e)
{
var enumerator = sourceChain.GetEnumerator();
enumerator.MoveNext();
if (sourceChain.Count == 0 ||
(sender is StateConnector && sender == enumerator.Current))
{
/* base.TrackMouse(sender, sourceChain, e);*/
_mouse_dx = e.X - _X;
_mouse_dy = e.Y - _Y;
return true;
}
return false;
}
public override bool HandleMouseEvent(object sender, List<BaseMouseHandler> sourceChain, System.Windows.Forms.MouseEventArgs e)
{
/* chỉ quảng bá nếu tôi được nhận sự kiện này đầu tiên
hoặc nhận được từ phía connector kết nối trực tiếp với mình
và connector đó nhận được sự kiện đầu tiên */
var enumerator = sourceChain.GetEnumerator();
enumerator.MoveNext();
if (sourceChain.Count == 0 ||
(sender is StateConnector && sender == enumerator.Current))
{
_X = e.X - _mouse_dx;
_Y = e.Y - _mouse_dy;
OnPositionChanged();
/*base.HandleMouseEvent(sender, sourceChain, e);*/
return true;
}
return false;
}
public void AddTransition(char TransitChar, State sTo)
{
if(!_transitionHash.ContainsKey(TransitChar))
{
List<State> newList = new List<State>();
_transitionHash.Add(TransitChar, newList);
}
var list = _transitionHash[TransitChar] as List<State>;
list.Add(sTo);
}
public void AddTransition(string transitChars, State sTo)
{
Transition newTransition = new Transition
{
TransitChars = transitChars, DestinedState = sTo
};
_transitionList.Add(newTransition);
}
private string _Label;
public string Label
{
get
{
return _Label;
}
}
public int X
{
get
{
return _X;
}
set
{
_X = value;
OnPositionChanged();
}
}
public int Y
{
get
{
return _Y;
}
set
{
_Y = value;
OnPositionChanged();
}
}
private Point _Position;
public Point Position
{
get { return _Position; }
}
private void OnPositionChanged()
{
int r = DisplaySize / 2;
_BoundingRect = new Rectangle(_X - r, Y - r, DisplaySize, DisplaySize);
_Position = new Point(_X, _Y);
}
public static int DisplaySize { get; set; }
public bool IsBeginState { get; set; }
public bool IsEndState { get; set; }
public bool HitTest(Point pt, Graphics g)
{
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(BoundingRect);
if(gp.IsVisible(pt, g))
{
gp.Dispose();
return true;
}
gp.Dispose();
return false;
}
}
struct Transition
{
public string TransitChars;
public State DestinedState;
}
}
|
9dbdbd5bfea17053e416c3b8fcc6ba8f137c7bc9
|
C#
|
sjarske/Forum1
|
/DAL/UserSQLContext.cs
| 2.734375
| 3
|
using DAL.Interface;
using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace DAL
{
public class UserSQLContext : IUser
{
private readonly string _connectionString = @"Server=mssql.fhict.local;Database=dbi389621_forum;User Id=dbi389621_forum;Password=sjors;";
public User GetById(int id)
{
User user = new User();
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("spGetUserById", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", id));
cmd.ExecuteNonQuery();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
user.Id = id;
user.Username = (string)reader["Username"];
user.Email = (string)reader["Email"];
}
}
return user;
}
public User GetUser(User _user)
{
User user = new User();
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("spLogin", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@Username", _user.Username));
command.Parameters.Add(new SqlParameter("@Password", _user.Password));
command.ExecuteNonQuery();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
user.Id = (int)reader["UserId"];
user.Username = (string)reader["Username"];
user.Email = (string)reader["Email"];
}
reader.Close();
}
return user;
}
public IEnumerable<string> GetUserRoles(User user)
{
var roles = new List<string>();
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("spGetUserRoles", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@Username", user.Username));
command.ExecuteNonQuery();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
roles.Add(reader["AuthorizationName"].ToString());
}
reader.Close();
connection.Close();
}
return roles;
}
public bool Login(User user)
{
bool loginSuccesfull = false;
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("spLogin", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@Username", user.Username));
command.Parameters.Add(new SqlParameter("@Password", user.Password));
command.ExecuteNonQuery();
var reader = command.ExecuteReader();
while (reader.Read())
{
loginSuccesfull = true;
}
reader.Close();
}
return loginSuccesfull;
}
public void Register(User user)
{
throw new NotImplementedException();
}
}
}
|
c21cf6c076ac6c6f5f04221fb9841a4378d3d065
|
C#
|
andreysamsykin/WeatherDiary
|
/Result.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Windows.Forms;
using System.Linq;
namespace WeatherDiary
{
public partial class Result : Form
{
public Result(GenerateDiary form)
{
InitializeComponent();
GetData(form);
}
public List<WeatherConditions> classExemps = new List<WeatherConditions>();
static string path = @"Weather.json";
FileInfo fileInf = new FileInfo(path); //путь к файлу
DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(List<WeatherConditions>)); //переменная сериализации
//массив заголовков для таблицы
string[] headers = new string[] { "Дата", "Длина дня", "Время", "Время года", "Место наблюдения", "Температура", "Давление", "Ветер", "Скорость ветра", "Облачность", "Влажность", "Кол-во осадков", "Осадки" };
IEnumerable<WeatherConditions> iewc;
string percipCheck = "";
private void GetData(GenerateDiary form)
{
using (FileStream fsr = new FileStream("Weather.json", FileMode.OpenOrCreate))
{
classExemps = (List<WeatherConditions>)jsonFormatter.ReadObject(fsr);
}
dataGridView1.Columns.Clear();
iewc = from c in classExemps where c.choosedDate == form.StartDatePicker.Value select c;
//генерация по дате
if (form.DateRadioBTN.Checked)
{
iewc = from c in classExemps where c.choosedDate == form.StartDatePicker.Value select c;
}
//по месту наблюдения
else if (form.PlaceRadioBTN.Checked)
{
iewc = from c in classExemps where c.watchPlace == form.WatchPlacetextBox.Text select c;
}
//по времени года
else if (form.SeasonRadioBTN.Checked)
{
iewc = from c in classExemps where c.season == form.SeasonBox.SelectedItem.ToString() select c;
}
//по времени наблюдения
else if (form.TimeRadioBTN.Checked)
{
iewc = from c in classExemps where c.time == form.TimeMTBox.Text select c;
}
//по погодным условиям
else if (form.WeatherRadioBTN.Checked)
{
WeatherConditionsMode(form);
}
//по промежутку времени
else if (form.DateGapRadioBTN.Checked)
{
iewc = from c in classExemps where c.choosedDate >= form.StartDatePicker.Value && c.choosedDate <= form.EndDatePicker.Value select c;
}
FillDataGrid(iewc.ToList<WeatherConditions>());
}
//заполнение датагрида данными
void FillDataGrid(List<WeatherConditions> iewc)
{
dataGridView1.DataSource = iewc;
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
dataGridView1.Columns[i].HeaderText = headers[i];
}
}
//функция выборки по погоде
void WeatherConditionsMode(GenerateDiary form)
{
//по температуре
if (form.TemperatureUpDown.Value !=0)
{
iewc = from c in classExemps where Convert.ToDecimal(c.temperature) == form.TemperatureUpDown.Value select c;
}
//по навправлению ветра
if (Convert.ToString(form.WindDirectionBox.SelectedItem) != "")
{
iewc = from c in classExemps where c.wind == form.WindDirectionBox.SelectedItem.ToString() select c;
}
//по облачности
if (Convert.ToString(form.CloudBox.SelectedItem) != "")
{
iewc = from c in classExemps where c.cloudness == form.CloudBox.SelectedItem.ToString() select c;
}
//по давлению
if (form.PressureUpDown.Value != 0)
{
iewc = from c in classExemps where Convert.ToDecimal(c.atmPressure) == form.PressureUpDown.Value select c;
}
//по силе ветра
if (form.WindUpDown.Value != 0)
{
iewc = from c in classExemps where Convert.ToDecimal(c.windSpeed) == form.WindUpDown.Value select c;
}
//по влажности
if (form.HumidityUpDown.Value != 0)
{
iewc = from c in classExemps where Convert.ToDecimal(c.humidity) == form.HumidityUpDown.Value select c;
}
//по кол-ву осадков
if (form.PercipitationUpDown.Value != 0)
{
iewc = from c in classExemps where Convert.ToDecimal(c.percipitationAmmount) == form.PercipitationUpDown.Value select c;
}
//----------------------------------------------------------------------------------------------------------------------------
//без осадков
if (form.NothingCB.Checked)
{
percipCheck += form.NothingCB.Text;
iewc = from c in classExemps where c.percipitations == percipCheck select c;
}
//град
if (form.HailCB.Checked)
{
percipCheck += form.HailCB.Text;
iewc = from c in classExemps where c.percipitations == percipCheck select c;
}
//туман
if (form.FogCB.Checked)
{
percipCheck += form.FogCB.Text;
iewc = from c in classExemps where c.percipitations == percipCheck select c;
}
//гроза
if (form.ThunderstormCB.Checked)
{
percipCheck += form.ThunderstormCB.Text;
iewc = from c in classExemps where c.percipitations == percipCheck select c;
}
//снег
if (form.SnowCB.Checked)
{
percipCheck += form.SnowCB.Text;
iewc = from c in classExemps where c.percipitations == percipCheck select c;
}
//дождь
if (form.RainCB.Checked)
{
percipCheck += form.RainCB.Text;
iewc = from c in classExemps where c.percipitations == percipCheck select c;
}
}
}
}
|
aab56c95bba148df3d6524a9227d59f942f4732d
|
C#
|
mwoden/ChopshopSignin
|
/ChopshopSignin/Person.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace ChopshopSignin
{
sealed internal class Person : IEquatable<Person>
{
public enum RoleType { Invalid, Student, Mentor }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string FullName { get { return LastName + ", " + FirstName; } }
/// <summary>
/// Returns the most recent location from today's timestamps
/// </summary>
public Scan.LocationType CurrentLocation
{
get
{
var today = Timestamps.Where(x => x.ScanTime.Date == DateTime.Today);
if (today.Count() == 0)
return Scan.LocationType.Out;
return today.Last().Direction;
}
}
public bool IsSignedIn { get { return CurrentLocation == Scan.LocationType.In; } }
/// <summary>
/// Returns the most recent time in for the current day
/// </summary>
public DateTime? TimeIn
{
get
{
var lastInScan = Timestamps.Where(x => x.ScanTime.Date == DateTime.Today).Where(x => x.Direction == Scan.LocationType.In).LastOrDefault();
if (lastInScan == null)
return null;
return lastInScan.ScanTime;
}
}
public RoleType Role { get; private set; }
public List<Scan> Timestamps { get; private set; }
private Person()
{
Timestamps = new List<Scan>();
}
private Person(string lastName, string firstName, RoleType role)
: this()
{
Role = role;
LastName = lastName.Trim();
FirstName = firstName.Trim();
}
private Person(string lastName, string firstName, bool isMentor)
: this(lastName, firstName, isMentor ? RoleType.Mentor : RoleType.Student)
{ }
public Person(XElement personXml)
{
FirstName = (string)personXml.Attribute("firstName");
LastName = (string)personXml.Attribute("lastName");
RoleType result;
if (!Enum.TryParse<RoleType>((string)personXml.Attribute("role"), true, out result))
result = RoleType.Student;
Role = result;
Timestamps = personXml.Element("Scans").Elements().Select(x => new Scan(x)).OrderBy(x => x.ScanTime).ToList();
}
public static Person Create(string scanData)
{
if (string.IsNullOrWhiteSpace(scanData) || !scanData.Contains(','))
return null;
RoleType role = Person.RoleType.Student;
// Check for a mentor scan
if (IsMentor(scanData))
{
role = Person.RoleType.Mentor;
scanData = GetMentorName(scanData);
}
return new Person(scanData.Split(',').First(), scanData.Split(',').Last(), role);
}
public bool Equals(Person other)
{
if (other == null)
return false;
return FullName.Equals(other.FullName, StringComparison.OrdinalIgnoreCase);
}
public override bool Equals(object obj)
{
return this.Equals(obj as Person);
}
public override int GetHashCode()
{
return FullName.GetHashCode();
}
public static bool operator ==(Person a, Person b)
{
if (object.ReferenceEquals(a, null))
return object.ReferenceEquals(a, b);
return a.Equals(b);
}
public static bool operator !=(Person a, Person b)
{
return !(a == b);
}
public override string ToString()
{
return string.Format("{0} : {1} : {2}", FullName, Role.ToString(), CurrentLocation.ToString());
}
/// <summary>
/// Toggle the person in or out
/// </summary>
/// <returns></returns>
public SignInOutResult Toggle()
{
return SignInOrOut(!IsSignedIn);
}
/// <summary>
/// Signs a person in or out, and returns an corresponding sign in/out result
/// </summary>
/// <param name="signingIn">If true, indicates the person is signing in</param>
/// <returns>The result of the operatoin</returns>
public SignInOutResult SignInOrOut(bool signingIn)
{
if (signingIn)
return SignIn();
return SignOut();
}
/// <summary>
/// Serialize the person to XML
/// </summary>
public XElement ToXml()
{
return new XElement("Person",
new XAttribute("lastName", LastName),
new XAttribute("firstName", FirstName),
new XAttribute("role", Role),
new XElement("Scans", Timestamps.Select(x => x.ToXml())));
}
/// <summary>
/// Saves a list of people to the specified files
/// Only people with at least 1 timestamp will be saved,
/// sorted by Student/Mentor, then by name (last name first)
/// </summary>
public static void Save(IEnumerable<Person> people, string filePath)
{
new XElement("SignInList", people.Where(x => x.Timestamps.Any())
.OrderBy(x => x.Role)
.ThenBy(x => x.FullName)
.Select(x => x.ToXml())).Save(filePath);
}
/// <summary>
/// Load all the people from the file
/// This will make a backup copy in the BackupFolder folder first
/// </summary>
public static IEnumerable<Person> Load(string filePath)
{
if (System.IO.File.Exists(filePath))
{
BackupDataFile(filePath);
return XElement.Load(filePath).Elements().Select(x => new Person(x));
}
return Enumerable.Empty<Person>();
}
/// <summary>
/// Removes all entries prior to the date specified by the cut-off parameter
/// </summary>
/// <param name="cutoff">Date which indicates the oldest scan that will be kept. Time will be ignored, only date is used.</param>
public void Prune(DateTime cutoff)
{
var discard = Timestamps.Where(x => x.ScanTime < cutoff.Date).ToList();
var keep = Timestamps.Where(x => x.ScanTime >= cutoff.Date).ToList();
Timestamps = Timestamps.Where(x => x.ScanTime >= cutoff.Date).ToList();
}
public IDictionary<DateTime, TimeSpan> GetTimeSummary()
{
// Get the person's timestamps and group them by week
return Timestamps.OrderBy(x => x.ScanTime)
.GroupBy(x => x.ScanTime.Date)
.ToDictionary(x => x.Key, x => GetDayTotalTime(x));
}
/// <summary>
/// Get the total amount of time spent by the person since startTime
/// </summary>
public TimeSpan GetTotalTimeSince(DateTime startTime)
{
// Returns the total time spent since the start time
return Timestamps.Where(x => x.ScanTime > startTime)
.GroupBy(x => x.ScanTime.Date)
.Select(x => GetDayTotalTime(x.OrderBy(y => y.ScanTime)))
.Aggregate(TimeSpan.Zero, (accumulator, x) => accumulator.Add(x));
}
/// <summary>
/// Get the total time spent for a given day
/// </summary>
/// <param name="scanTimes">A single day's worth of scans</param>
/// <returns>The time spent that day</returns>
private TimeSpan GetDayTotalTime(IEnumerable<Scan> scanTimes)
{
var pairs = new List<SignInPair>();
Scan prev = null;
foreach (var scan in scanTimes.OrderBy(x => x.ScanTime))
{
// If the scan indicates in
if (scan.Direction == Scan.LocationType.In)
{
// If the there isn't an in scan already
if (prev == null)
{
// Add it
prev = scan;
}
else
{
var t = new SignInPair(new[] { prev });
pairs.Add(t);
prev = scan;
}
}
else if (scan.Direction == Scan.LocationType.Out)
{
if (prev != null)
{
var t = new SignInPair(new[] { prev, scan });
pairs.Add(t);
prev = null;
}
}
}
if (prev != null)
{
var t = new SignInPair(new[] { prev });
pairs.Add(t);
}
return pairs.Aggregate(TimeSpan.Zero, (accumulate, x) => accumulate = accumulate.Add(x.TotalTime()));
}
/// <summary>
/// Signs a person in, and returns an corresponding sign in/out result
/// </summary>
private SignInOutResult SignIn()
{
if (CurrentLocation == Scan.LocationType.Out)
{
Timestamps.Add(new Scan(true));
var statusMessage = string.Format("{0} {1} in at {2}", FirstName, LastName, Timestamps.Last().ScanTime.ToShortTimeString());
return new SignInOutResult(true, statusMessage);
}
else
{
var statusMessage = "You are already signed in, scan \"OUT\" instead";
return new SignInOutResult(false, statusMessage);
}
}
/// <summary>
/// Signs a person out, and returns an corresponding sign in/out result
/// </summary>
/// <returns></returns>
private SignInOutResult SignOut()
{
if (CurrentLocation == Scan.LocationType.In)
{
Timestamps.Add(new Scan(false));
var statusMessage = string.Format("{0} {1} out at {2}", FirstName, LastName, Timestamps.Last().ScanTime.ToShortTimeString());
return new SignInOutResult(true, statusMessage);
}
else
{
var statusMessage = "You are already signed out, scan \"IN\" instead";
return new SignInOutResult(false, statusMessage);
}
}
/// <summary>
/// Make a backup copy of the specified file a 'Backup' subdirectory
/// The backup file will be prefixed with yyyy-MM-dd HH_mm_ss
/// </summary>
private static void BackupDataFile(string originalFilePath)
{
if (System.IO.File.Exists(originalFilePath))
{
var backupFolder = System.IO.Path.Combine(Utility.OutputFolder, Properties.Settings.Default.BackupFolder);
if (!System.IO.Directory.Exists(backupFolder))
System.IO.Directory.CreateDirectory(backupFolder);
var backupFile = DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss") + " " + System.IO.Path.GetFileName(originalFilePath);
var backupFilePath = System.IO.Path.Combine(backupFolder, backupFile);
System.IO.File.Copy(originalFilePath, backupFilePath);
var archiveFolder = ChopshopSignin.Properties.Settings.Default.ArchiveFolder;
// Check if the archive location is set (not empty) and the path is available
if (!string.IsNullOrWhiteSpace(archiveFolder) && System.IO.Directory.Exists(archiveFolder))
{
var archiveFile = System.IO.Path.Combine(archiveFolder, backupFile);
// Copy the latest backup file to archive
System.IO.File.Copy(backupFilePath, archiveFile);
}
// Clean out the backup folder
ManageBackupFiles(backupFolder, Properties.Settings.Default.MaxBackupFilesToKeep);
}
}
/// <summary>
/// Manage the backup folder and only keep a certain number of the most recent files. Older ones will be deleted
/// </summary>
/// <param name="maxFilesKept">The maximum number of files that will be kept. The the newer files will be kept</param>
private static void ManageBackupFiles(string backupFolder, int maxFilesKept)
{
var filesToDelete = System.IO.Directory.EnumerateFiles(backupFolder)
.Select(x => new System.IO.FileInfo(x))
.OrderByDescending(x => x.CreationTime)
.Skip(maxFilesKept);
foreach (var file in filesToDelete)
file.Delete();
}
/// <summary>
/// Detects a mentor scan
/// </summary>
private static bool IsMentor(string rawScanData)
{
return Regex.IsMatch(rawScanData, MentorIdPattern, RegexOptions.IgnoreCase);
}
/// <summary>
/// Returns the mentor name only, stripping out the mentor ID string
/// </summary>
private static string GetMentorName(string rawScanData)
{
var match = Regex.Match(rawScanData, MentorIdPattern, RegexOptions.IgnoreCase);
if (!match.Success)
throw new ArgumentException("should have a mentor prefix but doesn't", "rawScanData");
return rawScanData.Substring(match.Value.Length);
}
/// <summary>
/// Contains the week defintion, by FIRST season standards
/// </summary>
public static readonly DayOfWeek[] FirstWeek = new[]
{
DayOfWeek.Saturday,
DayOfWeek.Sunday,
DayOfWeek.Monday,
DayOfWeek.Tuesday,
DayOfWeek.Wednesday,
DayOfWeek.Thursday,
DayOfWeek.Friday
};
/// <summary>
/// The regex pattern to detect a mentor scan
/// </summary>
private const string MentorIdPattern = @"\Amentor[^a-z]+";
}
}
|
8cffcb98a3ccfce8b9e61c15b222898731a0a14e
|
C#
|
Bojidarist/RemoteController
|
/RCDesktopUI/ValueConverters/IntToVisibilityConverter.cs
| 3.203125
| 3
|
using System;
using System.Globalization;
using System.Windows;
namespace RCDesktopUI.ValueConverters
{
public class IntToVisibilityConverter : BaseValueConverter<IntToVisibilityConverter>
{
/// <summary>
/// Converts integer value to visibility (0 = Collapsed, 1 = Hidden, 2 = Visible)
/// </summary>
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Find the requested visibility
switch ((int)value)
{
case 0:
return Visibility.Collapsed;
case 1:
return Visibility.Hidden;
case 2:
return Visibility.Visible;
default:
// Return collapsed as default
return Visibility.Collapsed;
}
}
/// <summary>
/// Not implemented
/// </summary>
public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
754bdca056d4541d103eb9e450b6bf77bcdaa862
|
C#
|
jxnkwlp/DotnetSpiderLite
|
/src/DotnetSpiderLite.HtmlAgilityPack/PageExtensions.cs
| 2.546875
| 3
|
//using DotnetSpiderLite;
//using HtmlAgilityPack;
//using System;
//namespace DotnetSpiderLite.HtmlAgilityPack
//{
// public static class PageExtensions
// {
// //public static HtmlDocument ToHtmlDocument(this string html)
// //{
// // var doc = new HtmlDocument();
// // doc.LoadHtml(html);
// // return doc;
// //}
// public static string SelectSingle(this Page page, string xpath)
// {
// HtmlDocument htmlDocument = new HtmlDocument();
// htmlDocument.LoadHtml(page.Html);
// return htmlDocument.DocumentNode.SelectSingleNode(xpath)?.InnerHtml;
// }
// }
//}
|
518b5723dd75fec6dfb4555d8d320e503fa14e3e
|
C#
|
C-Kennelly/HaloSharp
|
/Source/HaloSharp/Model/HaloWars2/Metadata/CampaignLog/CampaignLog.cs
| 2.734375
| 3
|
using System;
namespace HaloSharp.Model.HaloWars2.Metadata.CampaignLog
{
[Serializable]
public class CampaignLog : IEquatable<CampaignLog>
{
public int Id { get; set; }
public bool Equals(CampaignLog other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Id == other.Id;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(CampaignLog))
{
return false;
}
return Equals((CampaignLog) obj);
}
public override int GetHashCode()
{
return Id;
}
public static bool operator ==(CampaignLog left, CampaignLog right)
{
return Equals(left, right);
}
public static bool operator !=(CampaignLog left, CampaignLog right)
{
return !Equals(left, right);
}
}
}
|
abb293121fb41f7c663712afabeeefaea51c309d
|
C#
|
hevey/Sharpie
|
/src/Sharpie/Models/Elements/Head.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
namespace Sharpie.Models.Elements
{
public class Head : HtmlElement
{
public Head()
{
AllowedSiblingTypes = new List<Type>
{
typeof(Body)
};
}
public override string? Render()
{
if (!IsChildAllowed(ChildNode?.GetType()))
{
throw new InvalidOperationException($"Child of type {ChildNode?.GetType()} is not allowed");
}
if (!IsSiblingAllowed(SiblingNode?.GetType()))
{
throw new InvalidOperationException($"Sibling of type {SiblingNode?.GetType()} is not allowed");
}
Content = ChildNode?.Render();
Content = Content != null ? $"<head>{Content}</head>" : "<head></head>";
return Content + SiblingNode?.Render();
}
}
}
|
daa28eca97cd37a324918d3c63a0cbc403e4a516
|
C#
|
vophiminhhieu/__VoPhiMinhHieu__
|
/Source/Test_C_sharp_Co_Ban/Test_C_sharp_Co_Ban/Program.cs
| 3.21875
| 3
|
using System;
/// VÕ Phi Minh Hiếu. Thời gian kết thúc 11:00
// Các tính năng chưa có: GUI đẹp
// Xử lý đầu vào chưa hiệu quả, ví dụ nhập số thực nếu nhập tùm lum thì bug
// Chỉ có 4 tính năng cộng trừ nhân chia
namespace Test_C_sharp_Co_Ban
{
class Program
{
static void Menu()
{
Console.WriteLine("");
Console.WriteLine(" May Tinh Co Ban");
Console.WriteLine("1. Cong Hai So ");
Console.WriteLine("2. Tru Hai So ");
Console.WriteLine("3. Nhan Hai So ");
Console.WriteLine("4. Chia Hai So ");
Console.WriteLine("5. Thoat ");
Console.Write("Moi ban nhap tinh nang: ");
}
static void input(ref double a, ref double b)
{
Console.WriteLine("");
Console.Write("Moi ban nhap so dau tien: ");
a = Convert.ToDouble(Console.ReadLine());
Console.Write("Moi ban nhap so thu hai: ");
b = Convert.ToDouble(Console.ReadLine());
}
static double Add(double a, double b)
{
return a + b;
}
static double Substract(double a, double b)
{
return a - b;
}
static double Multi(double a, double b)
{
return a * b;
}
static double Device(double a, double b)
{
return a / b;
}
static void OutputResult(double result)
{
result = Math.Round(result, 2);
Console.WriteLine("Ket qua cua ban la: " + result);
}
static void ClearScreen()
{
Console.WriteLine("Moi ban Enter de tiep tuc");
Console.ReadLine();
Console.SetCursorPosition(0, 0);
for (int i = 0; i < 15; i++)
{
Console.WriteLine(" ");
}
}
static void Main(string[] args)
{
double a = 0.0F;
double b = 0.0F;
Menu();
int choice = Convert.ToInt32(Console.ReadLine());
while (choice != 5)
{
input(ref a, ref b);
if (choice == 1)
{
OutputResult(Add(a, b));
}
if (choice == 2)
{
OutputResult(Substract(a, b));
}
if (choice == 3)
{
OutputResult(Multi(a, b));
}
if (choice == 4)
{
OutputResult(Device(a, b));
}
ClearScreen();
Console.SetCursorPosition(0, 0);
Menu();
choice = Convert.ToInt32(Console.ReadLine());
}
}
}
}
|
af233db20c60d72d685262ec4c2b45e531e4b1dd
|
C#
|
scriptorum/LD38
|
/Assets/Scripts/BombManager.cs
| 2.59375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Spewnity;
public class BombManager : MonoBehaviour
{
public GameObject bombPrefab;
public List<GameObject> bombs;
private Vector2 guide;
private float spacing = 10f;
public void Awake()
{
guide = transform.Find("BombGuide").GetComponent<RectTransform>().anchoredPosition;
}
public void reset()
{
foreach(GameObject bomb in bombs)
Destroy(bomb.gameObject);
bombs.Clear();
}
public void setBombs(int count)
{
Debug.Assert(count >= 0);
if(count == 0)
reset();
// Add bombs
else if (count > bombs.Count)
{
while(bombs.Count < count)
{
GameObject go = Instantiate(bombPrefab, bombPrefab.transform.position, bombPrefab.transform.rotation);
go.transform.SetParent(transform, false);
go.name = "Bomb" + bombs.Count;
Vector2 pos = guide;
pos.x += spacing * bombs.Count;
go.GetComponent<RectTransform>().anchoredPosition = pos;
bombs.Add(go);
}
}
// Remove bombs
else
{
while(bombs.Count > count)
{
GameObject lastBomb = bombs[bombs.Count - 1];
bombs.Remove(lastBomb);
Destroy(lastBomb);
}
}
}
}
|
e605ed22ca4f05490b317e8a4ec5e104ed1a391f
|
C#
|
rita0222/FK
|
/CLI/2017/Test/FK_CLI_Audio/Audio.cs
| 2.609375
| 3
|
using System;
using FK_CLI;
namespace FK_CLI_Audio
{
class Program
{
static void Main(string[] args)
{
// マテリアル初期化
fk_Material.InitDefault();
// ウィンドウの各種設定
var win = new fk_AppWindow();
WindowSetup(win);
// 立方体の各種設定
var blockModel = new fk_Model();
BlockSetup(blockModel, win);
// BGM用変数の作成
var bgm = new fk_BGM("epoq.ogg");
double volume = 0.5;
// SE用変数の作成
var se = new fk_Sound(2);
// 音源読み込み (IDは0番)
se.LoadData(0, "MIDTOM2.wav");
// 音源読み込み (IDは1番)
se.LoadData(1, "SDCRKRM.wav");
// ウィンドウ表示
win.Open();
// BGM再生スタート
bgm.Start();
// SE出力スタンバイ
se.Start();
var origin = new fk_Vector(0.0, 0.0, 0.0);
while (win.Update())
{
blockModel.GlRotateWithVec(origin, fk_Axis.Y, Math.PI / 360.0);
// volume値の変更
volume = ChangeVolume(volume, win);
bgm.Gain = volume;
// SE再生
PlaySE(se, win);
}
// BGM変数とSE変数に終了を指示
// (最後にこれをやらないといつまでも再生が止まらずプログラムが終了しません)
bgm.StopStatus = true;
se.StopStatus = true;
}
// ウィンドウ設定メソッド
static void WindowSetup(fk_AppWindow argWin)
{
argWin.CameraPos = new fk_Vector(0.0, 1.0, 20.0);
argWin.CameraFocus = new fk_Vector(0.0, 1.0, 0.0);
argWin.Size = new fk_Dimension(600, 600);
argWin.BGColor = new fk_Color(0.6, 0.7, 0.8);
argWin.ShowGuide(fk_Guide.GRID_XZ);
argWin.TrackBallMode = true;
argWin.FPS = 60;
}
// 立方体モデル設定メソッド
static void BlockSetup(fk_Model argModel, fk_AppWindow argWin)
{
// 立方体の各種設定
var block = new fk_Block(1.0, 1.0, 1.0);
argModel.Shape = block;
argModel.GlMoveTo(3.0, 3.0, 0.0);
argModel.Material = fk_Material.Yellow;
argWin.Entry(argModel);
}
// 音量調整メソッド
static double ChangeVolume(double argVol, fk_AppWindow argWin)
{
double tmpV = argVol;
// 上矢印キーで BGM 音量アップ
if (argWin.GetSpecialKeyStatus(fk_Key.UP, fk_Switch.DOWN) == true)
{
tmpV += 0.1;
if (tmpV > 1.0)
{
tmpV = 1.0;
}
}
// 下矢印キーで BGM 音量ダウン
if (argWin.GetSpecialKeyStatus(fk_Key.DOWN, fk_Switch.DOWN) == true)
{
tmpV -= 0.1;
if (tmpV < 0.0)
{
tmpV = 0.0;
}
}
return tmpV;
}
// SE再生(トリガー)メソッド
static void PlaySE(fk_Sound argSE, fk_AppWindow argWin)
{
// Z キーで 0 番の SE を再生開始
if (argWin.GetKeyStatus('Z', fk_Switch.DOWN) == true)
{
argSE.StartSound(0);
}
// X キーで 1 番の SE を再生開始
if (argWin.GetKeyStatus('X', fk_Switch.DOWN) == true)
{
argSE.StartSound(1);
}
}
}
}
|
026018a599b92e076b329cf74ee2486d70105af1
|
C#
|
EntangledBits/mui
|
/1.0/FirstFloor.ModernUI/FirstFloor.ModernUI/Presentation/CommandBase.cs
| 3.1875
| 3
|
using System;
using System.Windows.Input;
namespace FirstFloor.ModernUI.Presentation
{
/// <summary>
/// The base implementation of a command.
/// </summary>
public abstract class CommandBase
: ICommand
{
/// <summary>
/// Occurs when changes occur that affect whether or not the command should execute.
/// </summary>
public event EventHandler CanExecuteChanged
{
add { System.Windows.Input.CommandManager.RequerySuggested += value; }
remove { System.Windows.Input.CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Raises the <see cref="CanExecuteChanged" /> event.
/// </summary>
public void OnCanExecuteChanged()
{
System.Windows.Input.CommandManager.InvalidateRequerySuggested();
}
/// <summary>
/// Defines the method that determines whether the command can execute in its current state.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
/// <returns>
/// true if this command can be executed; otherwise, false.
/// </returns>
public virtual bool CanExecute(object parameter)
{
return true;
}
/// <summary>
/// Defines the method to be called when the command is invoked.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
public void Execute(object parameter)
{
if (!CanExecute(parameter)) {
return;
}
OnExecute(parameter);
}
/// <summary>
/// Executes the command.
/// </summary>
/// <param name="parameter">The parameter.</param>
protected abstract void OnExecute(object parameter);
}
}
|
950b741081030344be758200d2a932ffb861754c
|
C#
|
MinhTranCA/FarNet
|
/Zoo/FarNet.Tools/SubsetForm.cs
| 2.890625
| 3
|
// FarNet.Tools library for FarNet
// Copyright (c) Roman Kuzmin
using System;
using System.Collections.Generic;
using FarNet.Forms;
namespace FarNet.Tools
{
/// <summary>
/// A form to select an ordered subset from a set of input items.
/// </summary>
/// <remarks>
/// Create the form, set its <see cref="Items"/> and initial <see cref="Indexes"/>,
/// call <see cref="Show"/>, get result <see cref="Indexes"/>.
/// </remarks>
public sealed class SubsetForm : Form
{
const int DLG_XSIZE = 78;
const int DLG_YSIZE = 22;
/// <summary>
/// Gets or sets indexes of the selected items.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public int[] Indexes { get; set; }
/// <summary>
/// Gets or sets the items to select from.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public object[] Items { get; set; }
/// <summary>
/// Gets or sets an optional converter of items to strings.
/// </summary>
public Func<object, string> ItemToString { get; set; }
IListBox _ListBox1;
IListBox _ListBox2;
/// <summary>
/// New subset form.
/// </summary>
public SubsetForm()
{
Title = "Select";
Dialog.KeyPressed += OnKeyPressed;
// "available" and "selected" list
const int L1 = 4;
const int R2 = DLG_XSIZE - 5;
const int R1 = (L1 + R2) / 2;
const int L2 = R1 + 1;
const int BB = DLG_YSIZE - 4;
_ListBox1 = Dialog.AddListBox(L1, 2, R1, BB, "Available");
_ListBox1.NoClose = true;
_ListBox1.MouseClicked += OnListBox1Clicked;
_ListBox2 = Dialog.AddListBox(L2, 2, R2, BB, "Selected");
_ListBox2.NoClose = true;
_ListBox2.MouseClicked += OnListBox2Clicked;
// buttons
const int yButton = DLG_YSIZE - 3;
IButton button;
button = Dialog.AddButton(0, yButton, "Add");
button.CenterGroup = true;
button.ButtonClicked += OnAddButtonClicked;
button = Dialog.AddButton(0, yButton, "Remove");
button.CenterGroup = true;
button.ButtonClicked += OnRemoveButtonClicked;
button = Dialog.AddButton(0, yButton, "Up");
button.CenterGroup = true;
button.ButtonClicked += OnUpButtonClicked;
button = Dialog.AddButton(0, yButton, "Down");
button.CenterGroup = true;
button.ButtonClicked += OnDownButtonClicked;
button = Dialog.AddButton(0, yButton, "OK");
button.CenterGroup = true;
Dialog.Default = button;
button = Dialog.AddButton(0, yButton, "Cancel");
button.CenterGroup = true;
Dialog.Cancel = button;
}
/// <summary>
/// Shows the subset form.
/// </summary>
public override bool Show()
{
// no job
if (Items == null || Items.Length == 0)
return false;
// drop items, Show() may be called several times
_ListBox1.Items.Clear();
_ListBox2.Items.Clear();
// fill both lists
if (Indexes != null && Indexes.Length > 0)
{
for (int index1 = 0; index1 < Items.Length; ++index1)
{
FarItem item;
if (Array.IndexOf(Indexes, index1) < 0)
item = _ListBox1.Add(DoItemToString(Items[index1]));
else
item = _ListBox2.Add(DoItemToString(Items[index1]));
item.Data = index1;
}
}
else
{
for (int index1 = 0; index1 < Items.Length; ++index1)
_ListBox1.Add(DoItemToString(Items[index1])).Data = index1;
}
// the last fake selected item for inserting to the end
_ListBox2.Add(String.Empty).Data = -1;
_ListBox2.SelectLast = true;
// go!
if (!base.Show())
return false;
// collect and reset selected indexes
var r = new List<int>();
foreach (FarItem item in _ListBox2.Items)
{
int index = (int)item.Data;
if (index < 0)
break;
r.Add(index);
}
Indexes = r.ToArray();
return true;
}
void DoAdd()
{
int selected1 = _ListBox1.Selected;
if (selected1 >= 0)
{
FarItem item = _ListBox1.Items[selected1];
_ListBox1.Items.RemoveAt(selected1);
int selected2 = _ListBox2.Selected;
_ListBox2.Items.Insert(selected2, item);
_ListBox2.Selected = selected2 + 1;
}
}
string DoItemToString(object value)
{
if (ItemToString != null)
return ItemToString(value);
if (value == null)
return string.Empty;
return value.ToString();
}
void DoRemove()
{
int selected2 = _ListBox2.Selected;
if (selected2 >= 0 && selected2 < _ListBox2.Items.Count - 1)
{
FarItem item = _ListBox2.Items[selected2];
int index2 = (int)item.Data;
_ListBox2.Items.RemoveAt(selected2);
for (int i = 0; i < _ListBox1.Items.Count; ++i)
{
int index1 = (int)_ListBox1.Items[i].Data;
if (index2 < index1)
{
_ListBox1.Items.Insert(i, item);
return;
}
}
_ListBox1.Items.Add(item);
}
}
void DoDown()
{
int selected2 = _ListBox2.Selected;
if (selected2 >= 0 && selected2 < _ListBox2.Items.Count - 2)
{
FarItem item = _ListBox2.Items[selected2];
FarItem next = _ListBox2.Items[selected2 + 1];
_ListBox2.Items[selected2] = next;
_ListBox2.Items[selected2 + 1] = item;
_ListBox2.Selected = selected2 + 1;
}
}
void DoUp()
{
int selected2 = _ListBox2.Selected;
if (selected2 > 0 && selected2 < _ListBox2.Items.Count - 1)
{
FarItem item = _ListBox2.Items[selected2];
FarItem prev = _ListBox2.Items[selected2 - 1];
_ListBox2.Items[selected2] = prev;
_ListBox2.Items[selected2 - 1] = item;
_ListBox2.Selected = selected2 - 1;
}
}
void OnAddButtonClicked(object sender, ButtonClickedEventArgs e)
{
e.Ignore = true;
DoAdd();
}
//! Do not add Close() on Enter, Enter is called on ButtonClick (why?)
void OnKeyPressed(object sender, KeyPressedEventArgs e)
{
switch (e.Key.VirtualKeyCode)
{
case KeyCode.UpArrow:
if (e.Key.IsCtrl())
{
e.Ignore = true;
Dialog.SetFocus(_ListBox2.Id);
DoUp();
return;
}
break;
case KeyCode.DownArrow:
if (e.Key.IsCtrl())
{
e.Ignore = true;
Dialog.SetFocus(_ListBox2.Id);
DoDown();
return;
}
break;
case KeyCode.Tab:
if (Dialog.Focused == _ListBox2)
{
e.Ignore = true;
Dialog.SetFocus(_ListBox1.Id);
return;
}
break;
case KeyCode.Enter:
case KeyCode.Spacebar:
if (Dialog.Focused == _ListBox1)
{
e.Ignore = true;
DoAdd();
return;
}
else if (Dialog.Focused == _ListBox2)
{
e.Ignore = true;
DoRemove();
return;
}
break;
}
}
void OnListBox1Clicked(object sender, MouseClickedEventArgs e)
{
if (e.Mouse.Action == MouseAction.DoubleClick)
{
e.Ignore = true;
DoAdd();
}
}
void OnListBox2Clicked(object sender, MouseClickedEventArgs e)
{
if (e.Mouse.Action == MouseAction.DoubleClick)
{
e.Ignore = true;
DoRemove();
}
}
void OnRemoveButtonClicked(object sender, ButtonClickedEventArgs e)
{
e.Ignore = true;
DoRemove();
}
void OnDownButtonClicked(object sender, ButtonClickedEventArgs e)
{
e.Ignore = true;
DoDown();
}
void OnUpButtonClicked(object sender, ButtonClickedEventArgs e)
{
e.Ignore = true;
DoUp();
}
}
}
|