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 |
|---|---|---|---|---|---|---|
68774fdf05ad5817f7acfb313f7e078610d65750 | C# | FadiaAlbadry/CIS405-PROJ | /KP Alg Greedy v. KP Alg DP/Time Plots/TimePlotProgram.cs | 3.28125 | 3 | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using KP_Alg_Greedy_v._KP_Alg_DP;
namespace Time_Plots
{
class TimePlotProgram
{
static void Main(string[] args)
{
//Vars
long worstCaseTime = 0;
long avgCaseTime = 0;
long bestCaseTime = 0;
long capAvg = 0;
int numItems;
int numberOfItemsIncluded = 0;
double percentOfItemsIncluded = 0.0;
Stopwatch sw = new Stopwatch();
Tuple<int[], int> solution;
//Prompt user for number of problems
Console.Write("How many problems? ");
numItems = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Generating Items.");
//Generate items
List<string> linesOfFile = new List<string>(File.ReadAllLines("..//Problems//PROBLEM_SIZE_5.txt"));
Tuple<int[], int[]> problem = ItemPicker.PickItems(linesOfFile, numItems);
Console.WriteLine("Done Generating Items. Doing WC Time.");
//Get Worst Case Time
//Note: Cap = 8_000_000_000 so everything will fit in knapsack
sw.Start();
KPGreedyAlg.Solve(problem.Item2, problem.Item1, 8_000_000_000, numItems);
sw.Stop();
worstCaseTime = sw.ElapsedMilliseconds;
sw.Reset();
Console.WriteLine("Done. Doing BC Time.");
//Get Best Case Time
//Note: Cap = 0 so nothing will fit in knapsack
sw.Start();
KPGreedyAlg.Solve(problem.Item2, problem.Item1, 0, numItems);
sw.Stop();
bestCaseTime = sw.ElapsedMilliseconds;
sw.Reset();
Console.WriteLine("Done. Doing AVG Case time.");
//Get Average Case Time
capAvg = numItems * 25;
sw.Start();
KPGreedyAlg.Solve(problem.Item2, problem.Item1, capAvg, numItems);
sw.Stop();
avgCaseTime = sw.ElapsedMilliseconds;
Console.WriteLine("Done. Wrapping up.");
//Calculate percentage of items included for average case
solution = KPGreedyAlg.Solve(problem.Item2, problem.Item1, capAvg, numItems);
for (int i = 0; i < solution.Item1.Length; i++)
{
if (solution.Item1[i] == 1)
{
++numberOfItemsIncluded;
}
}
percentOfItemsIncluded = (Convert.ToDouble(numberOfItemsIncluded)) / numItems;
//Display results on screen
Console.WriteLine($"Number of Items: {numItems}");
Console.WriteLine($"Worst Case Time: {worstCaseTime}");
Console.WriteLine($"Average Case Time: {avgCaseTime}");
Console.WriteLine($"Best Case Time: {bestCaseTime}");
Console.WriteLine($"Average Capacity: {capAvg}");
Console.WriteLine($"Percent Included: {percentOfItemsIncluded}");
Console.WriteLine($"Number of Items Included: {numberOfItemsIncluded}");
Console.ReadLine();
}
}
} |
0ea7abd4bc09110b793228788fe87cbc816d3b6a | C# | psychochou/Design | /Form1.cs | 2.640625 | 3 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Globalization;
using Shared;
using System.IO;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
namespace Design
{
public partial class Form1 : Form
{
KeyboardHook _keyboardHotKeyF1;
KeyboardHook _keyboardHotKeyF2;
KeyboardHook _keyboardHotKeyF3;
public Form1()
{
InitializeComponent();
}
public static string ConvertRGBStringToHex(string value)
{
var matches = Regex.Matches(value, "[0-9]{1,3}(?![0-9a-fA-F])");
var r = "";
var ls = new List<string>();
var count = 0;
foreach (Match item in matches)
{
r += int.Parse(item.Value).ToString("X2");
count++;
if (count % 3 == 0)
{
ls.Add(r);
r = "";
count = 0;
}
}
return string.Join("\r\n", ls);
}
public static string ConvertHexStringToRGB(string hexColor)
{
if (hexColor.IndexOf('#') != -1)
hexColor = hexColor.Replace("#", "");
int red = 0;
int green = 0;
int blue = 0;
if (hexColor.Length == 6)
{
//#RRGGBB
red = int.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier);
green = int.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier);
blue = int.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier);
}
else if (hexColor.Length == 3)
{
//#RGB
red = int.Parse(hexColor[0].ToString() + hexColor[0].ToString(), NumberStyles.AllowHexSpecifier);
green = int.Parse(hexColor[1].ToString() + hexColor[1].ToString(), NumberStyles.AllowHexSpecifier);
blue = int.Parse(hexColor[2].ToString() + hexColor[2].ToString(), NumberStyles.AllowHexSpecifier);
}
return $"R={red}, G={green}, B={blue}";
}
private void RGB_Click(object sender, EventArgs e)
{
}
private void HEX_Click(object sender, EventArgs e)
{
try
{
var v = Clipboard.GetText().Trim();
Clipboard.SetText(ConvertHexStringToRGB(v));
}
catch (
Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void 生成字母表和数字大写ToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
var s = Enumerable.Range('A', 'Z' - 'A' + 1).Select(i => (char)i);
var ss = Enumerable.Range(0, 10).Select(i => i.ToString());
Clipboard.SetText(string.Join("", s) + string.Join("", ss));
}
catch (
Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void switchCaseButton_ButtonClick(object sender, EventArgs e)
{
try
{
var v = Clipboard.GetText().Trim();
var iu = v.Any(i => char.IsUpper(i));
if (iu)
{
v = v.ToLower();
}
else
{
v = v.ToUpper();
}
Clipboard.SetText(v);
}
catch (
Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void 获取屏幕颜色F1ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_keyboardHotKeyF1 == null)
_keyboardHotKeyF1 = new KeyboardHook();
_keyboardHotKeyF1.RegisterHotKey(Shared.ModifierKeys.None, Keys.F1);
_keyboardHotKeyF1.KeyPressed += (o, k) =>
{
try
{
var (r, g, b) = Colors.GetColorAt();
Clipboard.SetText($"{r.ToString("X2")}{g.ToString("X2")}{b.ToString("X2")}");
}
catch (
Exception exception)
{
MessageBox.Show(exception.Message);
}
};
}
private void 中_Click(object sender, EventArgs e)
{
Bing.Instance().ChineseToEnglishFromClipboard();
}
private void 排序空白分割后最后一个ToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
var v = Clipboard.GetText().Trim();
var ls = v.Split('\n').Where(i => !string.IsNullOrWhiteSpace(i) && i.Contains("\t")).Select(i => i.Trim()).Distinct().OrderBy(i =>
{
if (i.Contains("\t"))
{
return i.Split('\t').Last();
}
else
{
return "";
}
}).ToArray();
Clipboard.SetText(string.Join(Environment.NewLine, ls));
}
catch (
Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void rGBHEXF2ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_keyboardHotKeyF2 == null)
{
_keyboardHotKeyF2 = new KeyboardHook();
}
_keyboardHotKeyF2.RegisterHotKey(Shared.ModifierKeys.None, Keys.F2);
_keyboardHotKeyF2.KeyPressed += (o, k) =>
{
try
{
var v = Clipboard.GetText().Trim();
Clipboard.SetText(ConvertRGBStringToHex(v));
}
catch (
Exception exception)
{
MessageBox.Show(exception.Message);
}
};
}
private void RGB_ButtonClick(object sender, EventArgs e)
{
try
{
var v = Clipboard.GetText().Trim();
Clipboard.SetText(Colors.ExtractRGB(v));
}
catch (
Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void rGBHEXF3ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_keyboardHotKeyF3 == null)
{
_keyboardHotKeyF3 = new KeyboardHook();
}
_keyboardHotKeyF3.RegisterHotKey(Shared.ModifierKeys.None, Keys.F3);
_keyboardHotKeyF3.KeyPressed += (o, k) =>
{
try
{
var v = Clipboard.GetText().Trim();
Clipboard.SetText(Colors.ConvertRGBStringToHex2(v));
}
catch (
Exception exception)
{
MessageBox.Show(exception.Message);
}
};
}
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
try
{
var v = Clipboard.GetText().Trim();
if (!Directory.Exists(v)) return;
var files = Directory.GetFiles(v, "*").Where(i => Regex.IsMatch(i, "\\.(?:ttf|otf)$", RegexOptions.IgnoreCase));
foreach (var item in files)
{
Fonts.ReNameFont(item);
}
}
catch (
Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void 生成二维码ToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
var v = Clipboard.GetText().Trim();
// instantiate a writer object
var barcodeWriter = new BarcodeWriter();
var options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 250,
Height = 250,
};
// set the barcode format
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
// write text and generate a 2-D barcode as a bitmap
barcodeWriter
.Write(v)
.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), Path.GetRandomFileName() + ".png"), System.Drawing.Imaging.ImageFormat.Png);
}
catch (
Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void qrButton_Click(object sender, EventArgs e)
{
try
{
var v = Clipboard.GetText().Trim();
// instantiate a writer object
var barcodeWriter = new BarcodeWriter();
var options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 250,
Height = 250,
};
// set the barcode format
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
// write text and generate a 2-D barcode as a bitmap
// Path.GetRandomFileName()
// Regex.Match(v,"(?<=/)[a-zA-Z\\.\\-0-9]+(?!:)").Value
barcodeWriter
.Write(v)
.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), Path.GetRandomFileName() + ".png"), System.Drawing.Imaging.ImageFormat.Png);
}
catch (
Exception exception)
{
MessageBox.Show(exception.Message);
}
}
}
}
|
4c542b372ffe476f22227a4dda257e6cd4e32720 | C# | MathieuHerranzPerez/HexaTowerDef | /Assets/Scripts/Turret/BulletTurret.cs | 2.546875 | 3 | using UnityEngine;
public abstract class BulletTurret : ShootingTurret
{
[Range(0.05f, 20f)]
[SerializeField]
protected float fireRate = 1f;
[SerializeField]
protected GameObject bulletPrefab;
// ---- INTERN ----
protected float fireCountdown = 0f;
protected bool canShoot = true;
protected float fireRateUp;
protected float baseFireRate;
protected Projectile lastBulletFired;
protected override void UpdateCall()
{
base.UpdateCall();
if (target != null)
{
if (canShoot)
{
if (CheckShootCondition())
{
Shoot();
canShoot = false;
fireCountdown = 1f / fireRate;
}
}
}
fireCountdown -= Time.deltaTime;
if(fireCountdown <= 0f)
canShoot = true;
}
protected abstract bool CheckShootCondition();
protected virtual void Shoot()
{
audioSource.PlayOneShot(fireSound, volumeFire); // play the sound
GameObject bulletGameObject = (GameObject)Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Projectile bullet = bulletGameObject.GetComponent<Projectile>();
bullet.Impulse(bullet.Speed);
Destroy(bulletGameObject, 5f);
lastBulletFired = bullet;
bullet.SetDamage((int) damage);
if (bullet != null)
{
bullet.SetTarget(target);
}
}
protected override void InitBaseStats()
{
base.InitBaseStats();
baseFireRate = fireRate;
baseDamage = damage;
}
protected override void InitUpStats()
{
base.InitUpStats();
BulletTurret bt = (BulletTurret)turretUp;
fireRateUp = bt.fireRate;
slowUp = bt.slowPercent;
damageUp = bt.bulletPrefab.GetComponent<Projectile>().Damage;
}
public override float GetFireRate()
{
return fireRate;
}
public override float GetFireRateUp()
{
return fireRateUp;
}
public override float GetSpeed()
{
return fireRate;
}
public override float GetSpeedUp()
{
return fireRateUp;
}
public override void BoostFireRate(float fireRatePercent, bool isBuff)
{
int multiplier = isBuff ? 1 : -1;
this.fireRate += (float)(((baseFireRate * fireRatePercent) / 100f) * multiplier);
}
}
|
18f6867a6b00976dcc5fa31e4e5f254eef06f4ad | C# | Seshasreet/assignment2 | /Program.cs | 3.359375 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace doublelinked
{
class Program
{
static void Main(string[] args)
{
Double ob = new Double();
int ch, ele = 0, pos, flag;
flag = 1;
while (flag == 1)
{
Console.WriteLine("1 Insert at begin");
Console.WriteLine("2 Insert at end");
Console.WriteLine("3 Insert position");
Console.WriteLine("4 Display ");
Console.WriteLine("5 Reverese Display");
Console.WriteLine("6 Print Last node");
Console.WriteLine("7 Find first occurance");
Console.WriteLine("8 Find nth occurance");
Console.WriteLine("9 Delete at the begin");
Console.WriteLine("10 Delete at the end");
Console.WriteLine("11 Delete at the position");
Console.WriteLine("12 Exit");
ch = int.Parse(Console.ReadLine());
if ((ch >= 1 && ch <= 3) || ch == 7 || ch == 8)
{
Console.WriteLine("Enter the element ");
ele = int.Parse(Console.ReadLine());
}
switch (ch)
{
case 1: ob.insertbegin(ele); break;
case 2: ob.insertend(ele); break;
case 3:
do
{
Console.WriteLine("Enter pos between {0} to {1}", 1, ob.count + 1);
pos = int.Parse(Console.ReadLine());
} while (pos < 1 || pos > ob.count + 1);
ob.insertpos(ele, pos);
break;
case 4: ob.display(); break;
case 5: ob.printrev(); break;
case 6:
Node ln = ob.lastnode();
Console.WriteLine("the last node data is " + ln.data);
break;
case 7:
pos = ob.find(ele);
if (pos == -1)
Console.WriteLine("search key not found");
else
Console.WriteLine("search key found at {0} pos ", pos);
break;
case 8:
int occ;
Console.WriteLine("Enter occurance");
occ = int.Parse(Console.ReadLine());
pos = ob.find(ele, occ);
if (pos == -1)
Console.WriteLine("search key not found");
else if (pos == -2)
Console.WriteLine("found search key but not occurance");
else
Console.WriteLine("search key found at {0} pos ", pos);
break;
case 9: ob.deletebegin(); break;
case 10: ob.deleteend(); break;
case 11:
do
{
Console.WriteLine("Enter pos between {0} to {1}", 1, ob.count);
pos = int.Parse(Console.ReadLine());
} while (pos < 1 || pos > ob.count);
ob.deletepos(pos);
break;
case 12: flag = 0; break;
default: Console.WriteLine("invalid choice"); break;
}
}
}
}
}
|
201bc19913f502237aae5562cd6b49d1754eead2 | C# | rareskog/playoff-pickem-scorer | /PostseasonPickEmScorer/WildcardRoundScorer.cs | 2.796875 | 3 | namespace PostseasonPickEmScorer
{
public class WildcardRoundScorer
{
private readonly string _winningTeam;
public WildcardRoundScorer(string winningTeam)
{
_winningTeam = winningTeam;
}
public int ScoreFor(string pickedTeam)
{
return pickedTeam == _winningTeam ? 2 : 0;
}
}
}
|
68534893d097798b2a11d8a0ea9d48094332de3d | C# | Iona777/portal | /BasicFrameworkTwo/Pages/LoginPage.cs | 2.796875 | 3 | using System;
using OpenQA.Selenium;
using BasicFrameworkTwo.Utilities; //Location of Driver class
namespace BasicFrameworkTwo.Pages
{
class LoginPage : BasePage
{
//Constructor
//It will just use the one from BasePage unless it needs something extra.
//WebElements
private readonly By _emailLocator = By.Id("Email");
private readonly By _passwordLocator = By.Id("Password");
private readonly By _loginButtonLocator = By.Id("Login-Btn");
//Methods
public void GotoLoginPage(string rootURL)
{
Driver.NavigateTo(rootURL);
}
public void EnterEmail(string emailAddress)
{
IWebElement email = GetClickableElement(_emailLocator);
email.SendKeys(emailAddress);
}
public void EnterPassword(string passwordText)
{
IWebElement password = GetClickableElement(_passwordLocator);
password.SendKeys(passwordText);
}
public void ClickLoginButton()
{
ClickOnElement(_loginButtonLocator);
}
}
}
|
8ecb22522d0bc6a31356fc1c1dbb152196e8f2e9 | C# | Autofire/Execute-R | /Assets/Scripts/VR/OverridePlayerMovement.cs | 2.640625 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class OverridePlayerMovement : MonoBehaviour
{
public enum Axis : int {
X = 0,
Y = 1,
Z = 2
}
public float moveSpeed;
public string hAxisName = "Horizontal";
public string vAxisName = "Vertical";
public Axis hAxis = Axis.X;
public Axis vAxis = Axis.Z;
[Tooltip("This triggers the FIRST time a move is registered.")]
public UnityEvent onFirstMove;
private bool triggeredFirstMoveEvent = false;
public void Update() {
float hAxisVal = Input.GetAxis(hAxisName);
float vAxisVal = Input.GetAxis(vAxisName);
if(Mathf.Abs(hAxisVal) > Mathf.Epsilon || Mathf.Abs(vAxisVal) > Mathf.Epsilon) {
if(!triggeredFirstMoveEvent) {
triggeredFirstMoveEvent = true;
onFirstMove.Invoke();
}
Vector3 desiredMove = Vector3.zero;
desiredMove[(int) hAxis] = hAxisVal * moveSpeed * Time.deltaTime;
desiredMove[(int) vAxis] = vAxisVal * moveSpeed * Time.deltaTime;
transform.position += desiredMove;
}
}
}
|
6116f8b5c210c4030e395a7325359a00bc01e67e | C# | JoshOtter/The-Tech-Academy-C-Sharp-and-Unity-Projects | /ExceptionAssignment/Program.cs | 3.78125 | 4 | using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> dividends = new List<int>() { 2, 4, 12, 15, 27, 36, 54 };
try
{
Console.WriteLine("Pick a number to divide each number in the dividends list.");
int divisor = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nHere are the results:");
foreach (int dividend in dividends)
{
Console.WriteLine(dividend / divisor);
}
}
catch (FormatException ex)
{
Console.WriteLine("Please enter a whole number.");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Please don't divide by zero.");
}
finally
{
Console.ReadLine();
}
}
}
|
f95ce5339201f51d3cb041e6a80668b936c9019c | C# | FranRM/FormacionASP.Net | /MVC/PracticaMVC/Controladores/ErrorController.cs | 2.765625 | 3 | using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace PracticaMVC.Controladores
{
public class ErrorController : Controller
{
private readonly ILogger _logger;
public ErrorController(ILogger<ErrorController> logger)
{
_logger = logger;
}
public IActionResult Show(int id)
{
var html = string.Empty;
if (id == 500)
{
var exceptionHandlerFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
var exception = exceptionHandlerFeature.Error;
var exceptionName = exception.GetType().Name;
_logger.LogError($"Exception thrown '{exceptionName}: {exception.Message}'");
html = GetHtmlPage(
statusCode: 500,
title: $"Server error",
description: $"We have detected a server error {exceptionName}"
);
}
else if (id == 404)
{
var statusCodeFeature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
var path = statusCodeFeature.OriginalPath;
_logger.LogError($"Error 404 for path '{path}'");
html = GetHtmlPage(
statusCode: 404,
title: "Not found",
description: $"No content found at '{path}'"
);
}
return Content(html, contentType: "text/html");
}
private string GetHtmlPage(int statusCode, string title, string description)
{
return $@"
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>{title}</title>
<link href='/styles/calculator.css' rel='stylesheet' />
</head>
<body>
<h1>
<span class='statusCode'>{statusCode}</span> {title}
</h1>
<p>{description}.</p>
<p><a href='javascript:history.back()'>Go back</a>.</p>
</body>
</html>
";
}
}
} |
bb1b350f73e1853b22ece4176da75dbfc433670f | C# | lincolnyu/gozeleme | /FileMatcher/FileMatcher/FileScanner.cs | 3.234375 | 3 | using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
namespace FileMatcher
{
/// <summary>
/// enumerates all files in the specified starting directory and its subdirectories
/// </summary>
public class FileScanner : IEnumerable<FileInfo>, INotifyPropertyChanged
{
#region Delegates
public delegate void UpdatedEventHandler();
#endregion
#region Fields
/// <summary>
/// starting dirctory of the scanning
/// </summary>
private readonly DirectoryInfo _startingDir;
private readonly ISet<string> _excludedDirs;
private DirectoryInfo _currentDirectory;
#endregion
#region Constructors
/// <summary>
/// Instantiates a scanner with the specified path and status updator
/// </summary>
/// <param name="startingPath">The path to the starting directory</param>
/// <param name="updateStatus">Delegate that updates the status to the progress displaying UI</param>
public FileScanner(string startingPath)
: this(new DirectoryInfo(startingPath))
{
}
/// <summary>
/// Instantiates a scanner with the specified directoryand status updator
/// </summary>
/// <param name="startingDir">The starting directory</param>
/// <param name="excludedDirs">The directories to be excluded from searching</param>
/// <param name="updateStatus">Delegate that updates the status to the progress displaying UI</param>
public FileScanner(DirectoryInfo startingDir, ISet<DirectoryInfo> excludedDirs = null)
{
_startingDir = startingDir;
if (excludedDirs != null)
{
_excludedDirs = new HashSet<string>();
foreach (var ed in excludedDirs)
{
_excludedDirs.Add(ed.FullName.ToLower());
}
}
else
{
_excludedDirs = null;
}
}
#endregion
#region Properties
#region INotifyPropertyChanged members
/// <summary>
/// event that updates status to the UI
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#endregion
public DirectoryInfo CurrentDirectory
{
get
{
return _currentDirectory;
}
private set
{
if (_currentDirectory != value)
{
_currentDirectory = value;
RaisePropertyChanged("CurrentDirectory");
}
}
}
#endregion
#region Methods
#region IEnumerable<FileInfo> members
/// <summary>
/// returns an enumerator of FileInfo objects
/// </summary>
/// <returns>The enumerator of FileInfo objects</returns>
public IEnumerator<FileInfo> GetEnumerator()
{
var qd = new Queue<DirectoryInfo>();
qd.Enqueue(_startingDir);
while (qd.Count > 0)
{
var d = qd.Dequeue();
var subds = TryGetDirectories(d);
foreach (var subd in subds)
{
if (_excludedDirs != null && _excludedDirs.Contains(subd.FullName.ToLower()))
{
continue;
}
qd.Enqueue(subd);
}
var fs = TryGetFiles(d);
foreach (var f in fs)
{
yield return f;
}
}
}
/// <summary>
/// returns an enumerator of FileInfo objects
/// </summary>
/// <returns>The enumerator of FileInfo objects</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
/// <summary>
/// tries to get sub-directories of the specified directory
/// </summary>
/// <param name="d">The directory to get sub-directories of</param>
/// <returns>All the subdirectory if successful or an empty list</returns>
IEnumerable<DirectoryInfo> TryGetDirectories(DirectoryInfo d)
{
try
{
return d.EnumerateDirectories();
}
catch (Exception)
{
return new DirectoryInfo[0];
}
}
/// <summary>
/// tries to get files in the specified directory
/// </summary>
/// <param name="d">The directory to get files from</param>
/// <returns>All the files if successful or an empty list</returns>
private IEnumerable<FileInfo> TryGetFiles(DirectoryInfo d)
{
try
{
CurrentDirectory = d;
return d.EnumerateFiles();
}
catch (Exception)
{
return new FileInfo[0];
}
}
private void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
#endregion
}
}
|
d4ca71ee440b2d5e2ffe36dcdc58a012a9c0c321 | C# | DavidckPixel/GreenLight_Informatica_UU | /GreenLight/GreenLight/src/Roads/Lanes/DrivingLane.cs | 3.140625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace GreenLight
{
// All Curved- and DiagonalRoads have a list of these DrivingLanes, a driving lane consists of a list of LanePoints
// Each object from this class also has its own Draw function, this draw feature
// draws every lane of the road next to each other.
// All DrivingLanes also have their own hitbox, and a function to change their direction around
public class DrivingLane : Lane
{
int roadLanes;
private LanePoints middle;
public Hitbox hitbox;
public DrivingLane(List<LanePoints> _points, string _dir, int _roadLanes, int _thisLane, Hitbox _hitbox)
{
this.points = _points;
this.dir = _dir;
this.roadLanes = _roadLanes;
this.thisLane = _thisLane;
this.hitbox = _hitbox;
this.flipped = true;
middle = this.points[this.points.Count() / 2];
AngleDir = middle.degree;
}
// Reverses the List of LanePoints and flips their angles to make cars drive in the opposite direction
public override void FlipPoints()
{
List<LanePoints> _templist = new List<LanePoints>();
points.Reverse();
flipped = !flipped;
foreach (LanePoints x in points)
{
x.Flip();
_templist.Add(x);
}
points = _templist;
middle = this.points[this.points.Count() / 2];
AngleDir = middle.degree;
if (beginConnectedTo.Count != 0 && endConnectedTo.Count != 0)
{
List<Lane> _tempconnections = new List<Lane>();
foreach (Lane _l in beginConnectedTo)
_tempconnections.Add(_l);
beginConnectedTo.Clear();
foreach (Lane _l in endConnectedTo)
beginConnectedTo.Add(_l);
endConnectedTo.Clear();
foreach (Lane _l in _tempconnections)
endConnectedTo.Add(_l);
}
else if (beginConnectedTo.Count != 0)
{
foreach (Lane _l in beginConnectedTo)
endConnectedTo.Add(_l);
beginConnectedTo.Clear();
}
else if (endConnectedTo.Count != 0)
{
foreach (Lane _l in endConnectedTo)
beginConnectedTo.Add(_l);
endConnectedTo.Clear();
}
}
// Decides if a dashed yellow line or a solid white line needs to be drawn at a side of a DrivingLane
public Pen getPen(int _side)
{
Pen p = new Pen(Color.FromArgb(248, 185, 0), 3);
if (thisLane > 1 && thisLane < roadLanes)
{
p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
}
else if (roadLanes == 1)
{
p.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
p.Width = 5;
p.Color = Color.White;
}
else if (thisLane == 1)
{
if (_side == 1)
{
p.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
p.Width = 5;
p.Color = Color.White;
}
else
{
p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
}
}
else if (thisLane == roadLanes)
{
if (_side == 1)
{
p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
}
else
{
p.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
p.Width = 5;
p.Color = Color.White;
}
}
return p;
}
// Draws the DrivingLane on the screen
public override void Draw(Graphics g)
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Pen p = new Pen(Color.FromArgb(21, 21, 21), Roads.Config.laneWidth);
Brush b = new SolidBrush(Color.FromArgb(21, 21, 21));
int drivingLaneDistance = Roads.Config.laneWidth;
double slp, slpPer, oneX, amountX;
int startAngle = 0, sweepAngle = 90;
Rectangle rect = new Rectangle();
Size size;
Rectangle outer, inner;
int side1 = 0, side2 = 0;
if (dir.Length > 1) //CurvedRoad
{
size = new Size(Math.Abs(points[points.Count - 1].cord.X - points[0].cord.X) * 2, Math.Abs(points[points.Count - 1].cord.Y - points[0].cord.Y) * 2);
switch (dir)
{
case "SE":
{
startAngle = 180;
rect = new Rectangle(new Point(Math.Min(points[0].cord.X, points[points.Count - 1].cord.X), Math.Min(points[0].cord.Y, points[points.Count - 1].cord.Y)), size);
side1 = 1;
side2 = 2;
}
break;
case "SW":
{
startAngle = 270;
rect = new Rectangle(new Point(Math.Max(points[0].cord.X, points[points.Count - 1].cord.X) - size.Width, Math.Min(points[0].cord.Y, points[points.Count - 1].cord.Y)), size);
side1 = 2;
side2 = 1;
}
break;
case "NW":
{
startAngle = 0;
rect = new Rectangle(new Point(Math.Max(points[0].cord.X, points[points.Count - 1].cord.X) - size.Width, Math.Max(points[0].cord.Y, points[points.Count - 1].cord.Y) - size.Height), size);
side1 = 2;
side2 = 1;
}
break;
case "NE":
{
startAngle = 90;
rect = new Rectangle(new Point(Math.Min(points[0].cord.X, points[points.Count - 1].cord.X), Math.Max(points[0].cord.Y, points[points.Count - 1].cord.Y) - size.Height), size);
side1 = 1;
side2 = 2;
}
break;
}
try
{
g.DrawArc(p, rect, startAngle, sweepAngle);
outer = new Rectangle(new Point(rect.Location.X - drivingLaneDistance / 2, rect.Location.Y - drivingLaneDistance / 2), new Size(rect.Width + drivingLaneDistance, rect.Height + drivingLaneDistance));
inner = new Rectangle(new Point(rect.Location.X + drivingLaneDistance / 2, rect.Location.Y + drivingLaneDistance / 2), new Size(rect.Width - drivingLaneDistance, rect.Height - drivingLaneDistance));
g.DrawArc(getPen(side1), outer, startAngle, sweepAngle);
g.DrawArc(getPen(side2), inner, startAngle, sweepAngle);
}
catch (Exception e)
{
}
}
else
{
if (dir == "D") //DiagonalRoad
{
Point[] polygon = new Point[4];
if (points[0].cord.X != points[points.Count - 1].cord.X && points[0].cord.Y != points[points.Count - 1].cord.Y)
{
slp = (double)(points[0].cord.Y - points[points.Count - 1].cord.Y) / (double)(points[points.Count - 1].cord.X - points[0].cord.X);
if (slp <= -1 || slp >= 1)
{
polygon[0] = new Point(points[0].cord.X - drivingLaneDistance / 2, points[0].cord.Y);
polygon[1] = new Point(points[0].cord.X + drivingLaneDistance / 2, points[0].cord.Y);
polygon[2] = new Point(points[points.Count - 1].cord.X + drivingLaneDistance / 2, points[points.Count - 1].cord.Y);
polygon[3] = new Point(points[points.Count - 1].cord.X - drivingLaneDistance / 2, points[points.Count - 1].cord.Y);
}
else
{
polygon[0] = new Point(points[0].cord.X, points[0].cord.Y - drivingLaneDistance / 2);
polygon[1] = new Point(points[0].cord.X, points[0].cord.Y + drivingLaneDistance / 2);
polygon[2] = new Point(points[points.Count - 1].cord.X, points[points.Count - 1].cord.Y + drivingLaneDistance / 2);
polygon[3] = new Point(points[points.Count - 1].cord.X, points[points.Count - 1].cord.Y - drivingLaneDistance / 2);
}
g.FillPolygon(b, polygon);
g.DrawLine(getPen(1), polygon[0], polygon[3]);
g.DrawLine(getPen(2), polygon[1], polygon[2]);
}
else if (points[0].cord.X == points[points.Count - 1].cord.X)
{
g.DrawLine(p, points[0].cord, points[points.Count - 1].cord);
g.DrawLine(getPen(1), new Point(points[0].cord.X - drivingLaneDistance / 2, points[0].cord.Y), new Point(points[points.Count - 1].cord.X - drivingLaneDistance / 2, points[points.Count - 1].cord.Y));
g.DrawLine(getPen(2), new Point(points[0].cord.X + drivingLaneDistance / 2, points[0].cord.Y), new Point(points[points.Count - 1].cord.X + drivingLaneDistance / 2, points[points.Count - 1].cord.Y));
}
else if (points[0].cord.Y == points[points.Count - 1].cord.Y)
{
g.DrawLine(p, points[0].cord, points[points.Count - 1].cord);
g.DrawLine(getPen(1), new Point(points[0].cord.X, points[0].cord.Y - drivingLaneDistance / 2), new Point(points[points.Count - 1].cord.X, points[points.Count - 1].cord.Y - drivingLaneDistance / 2));
g.DrawLine(getPen(2), new Point(points[0].cord.X, points[0].cord.Y + drivingLaneDistance / 2), new Point(points[points.Count - 1].cord.X, points[points.Count - 1].cord.Y + drivingLaneDistance / 2));
}
}
}
hitbox.Draw(g);
Bitmap _bitmap = DrawData.RotateImage(General_Form.Main.BuildScreen.builder.roadBuilder.ArrowBitmap, AngleDir);
g.DrawImage(_bitmap, new Rectangle(new Point(middle.cord.X - 7, middle.cord.Y - 7), new Size(15, 15)));
}
public override void DrawoffsetHitbox(Graphics g)
{
if (offsetHitbox != null)
{
offsetHitbox.Draw(g);
}
}
}
}
|
39de9cd762c76a8fd1ef52df01ece375f043b35c | C# | WojciechNagel/AlkoRank | /WebApplication11/Models/Wino.cs | 2.625 | 3 | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace WebApplication11.Models
{
public class Wino
{
public int WinoId { get; set; }
public string Nazwa { get; set; }
[SprawdzRok] public int RokProdukcji { get; set; }
public int Ocena { get; set; }
public int Cena { get; set; }
}
public class SprawdzRok : ValidationAttribute
{
public override bool IsValid(object value)
{
int rok = (int) value;
if (rok < 1500 || rok > System.DateTime.Now.Year)
{
return false;
}
else
return true;
}
public SprawdzRok()
{
ErrorMessage = "W tym roku nie stworzono zadnego wina";
}
}
} |
a6ccf3efcc75cfecbaec3b6deba5f7278678a857 | C# | itsthekeming/percolate | /src/Percolate/Builders/PercolateTypeBuilder.cs | 2.859375 | 3 | using Percolate.Models;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Percolate.Builders
{
public class PercolateEntityBuilder<TEntity> where TEntity : class
{
public PercolateEntityBuilder()
{
Model = new PercolateType<TEntity>();
}
public PercolateEntityBuilder(IPercolateEntity model)
{
Model = model;
}
public IPercolateEntity Model { get; set; }
public PercolateEntityBuilder<TEntity> CanPage(bool canPage = true)
{
Model.IsPagingEnabled = canPage;
return this;
}
public PercolateEntityBuilder<TEntity> CanSort(bool canSort = true)
{
Model.IsSortingEnabled = canSort;
return this;
}
public PercolateEntityBuilder<TEntity> CanFilter(bool canFilter = true)
{
Model.IsFilteringEnabled = canFilter;
return this;
}
public PercolateEntityBuilder<TEntity> HasDefaultPageSize(int defaultPageSize)
{
if (defaultPageSize < 1)
{
throw new ArgumentException();
}
Model.DefaultPageSize = defaultPageSize;
return this;
}
public PercolateEntityBuilder<TEntity> HasMaxPageSize(int maximumPageSize)
{
if (maximumPageSize < 1)
{
throw new ArgumentException($"{nameof(maximumPageSize)} cannot be less than 1.");
}
Model.MaximumPageSize = maximumPageSize;
return this;
}
public PercolatePropertyBuilder<TProperty> Property<TProperty>(Expression<Func<TEntity, TProperty>> propertyExpression)
{
PercolatePropertyBuilder<TProperty> propertyBuilder;
if (!(propertyExpression.Body is MemberExpression memberExpression))
{
throw new NotSupportedException();
}
if (!(memberExpression.Member is PropertyInfo propertyInfo))
{
throw new NotSupportedException();
}
var existingPropertyModel = Model.Properties
.FirstOrDefault(p => p.Name == propertyInfo.Name);
/*
* TODO:
* Right now, this method and its related methods and constructors only traverse down one level of the 'type graph.'
* Eventually, we'd like to support any level so that one can pass in (x => x.Foo.Bar).Whatever() and it will resolve properly.
* For now, we need to ensure that the expression that was passed in can resolve for TType. It will be a runtime error.
* Maybe there is a way to resolve this in the propertyExpression?
*
* The consequence of this is that any property of a type that does not implement ICompareable cannot be sorted and any property that isn't a value type
* cannot be filtered on. So this is a really important thing to implement. One can imagine when they might want to be able to sort on x.Foo.Bar.
* Reflection can be used to find that property and call SetValue on it, but configuring the model here for it is harder.
*
* GetProperties with the correct binding flags can get us some of the way there, but there are certain classes (DateTime is one) that will cause a stack overflow.
* So I'm not sure if there's a way to control for those certain cases that might blow it up. Maybe: get the properties, check if a stack overflow might occur by
* seeing if any of the retreived properties share a type with the type you retrieved the properties for, and only add subproperties if that check returns false?
* That will add any property that wouldn't cause a recursive stack overflow.
*/
if (!typeof(TEntity).GetProperties().Any(p => p.Name == propertyInfo.Name))
{
throw new NotSupportedException();
}
if (existingPropertyModel == default)
{
propertyBuilder = new PercolatePropertyBuilder<TProperty>(propertyInfo);
Model.Properties.Add(propertyBuilder.Model);
}
else
{
propertyBuilder = new PercolatePropertyBuilder<TProperty>(existingPropertyModel);
}
return propertyBuilder;
}
}
}
|
51a9d3fda232b71bf40407083d48bc3f8c48ba80 | C# | Nikpds/Skill-Test-Project-Address-Book | /AddressBook/AddressBook.Api/Services/DomainToViewMaps.cs | 2.859375 | 3 | using AddressBook.Api.Models;
using AddressBook.Api.Views;
using System.Linq;
namespace AddressBook.Api.Services
{
public static class DomainToViewMaps
{
public static UserView UserToView(this User user)
{
return new UserView()
{
Id = user.Id,
Email = user.Email,
Addresses = user.Addresses.Select(addr => AddressToView(addr)).ToList(),
Firstname = user.Firstname,
Lastname = user.Lastname
};
}
public static User UserViewToDomain(this UserView user)
{
User domain = new User();
domain.Id = user.Id;
domain.Email = user.Email;
domain.Addresses = user.Addresses.Select(addr => AddressInfoViewToDomain(addr)).ToList();
domain.Firstname = user.Firstname;
domain.Lastname = user.Lastname;
return domain;
}
public static AddressInfoView AddressToView(this AddressInfo add)
{
return new AddressInfoView()
{
Id = add.Id,
Address = add.Address,
Lat = add.Lat,
Lon = add.Lon,
UserId = add.UserId
};
}
public static AddressInfo AddressInfoViewToDomain(this AddressInfoView add)
{
AddressInfo domain = new AddressInfo();
domain.Id = add.Id;
domain.Address = add.Address;
domain.Lat = add.Lat;
domain.Lon = add.Lon;
domain.UserId = add.UserId;
return domain;
}
}
}
|
c541cd0ff5a5565be442ed20a36636964ca7c35c | C# | megha18walia/CSharpExample | /Threading/ThreadingNew/ThraedingNew/ThreadingStatic/Cart.cs | 2.875 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ThreadingStatic
{
public class Cart
{
public Cart()
{
GroceryItems = new GroceryItem[10];
GroceryItems[0] = new GroceryItem("Milk", 1.00f);
GroceryItems[1] = new GroceryItem("Bread", 1.00f);
GroceryItems[2] = new GroceryItem("Cheese", 1.00f);
GroceryItems[3] = new GroceryItem("Eggs", 1.00f);
GroceryItems[4] = new GroceryItem("Soda", 1.00f);
GroceryItems[5] = new GroceryItem("Candy", 1.00f);
GroceryItems[6] = new GroceryItem("Lettuc", 1.00f);
GroceryItems[7] = new GroceryItem("Tomato", 1.00f);
GroceryItems[8] = new GroceryItem("Fish", 1.00f);
GroceryItems[9] = new GroceryItem("Cereal", 1.00f);
}
public GroceryItem[] GroceryItems;
}
}
|
9797dd000b8c55cdef464735a4b0a540149669cc | C# | JuliaSlipchuk/BookingUZ | /Booking.DataAccess/Repositories/TrainRecurringRepository.cs | 2.78125 | 3 | using Booking.DataAccess.RepoInterfaces;
using Booking.DataAccess.Repositories;
using Booking.Models.DBModels;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Booking.DataAccess.Repositories
{
public class TrainRecurringRepository : BaseRepository, ITrainRecurringRepo
{
public void Create(TrainRecurring trainRecurring)
{
db.TrainsRecurring.Add(trainRecurring);
db.SaveChanges();
}
public void Update(TrainRecurring trainRecurring)
{
db.Entry(trainRecurring).State = EntityState.Modified;
db.SaveChanges();
}
public void Delete(int? trainRecurrId)
{
if (trainRecurrId != null && db.TrainsRecurring.Where(tr => tr.ID == trainRecurrId).Any())
{
db.TrainsRecurring.Remove(db.TrainsRecurring.Where(tr => tr.ID == trainRecurrId).ToList()[0]);
}
}
public List<TrainRecurring> GetAllItems()
{
if (db.TrainsRecurring.Any())
return db.TrainsRecurring.ToList();
return null;
}
public TrainRecurring GetItemById(int? id)
{
if (id != null && db.TrainsRecurring.Where(tr => tr.ID == id) != null)
{
return db.TrainsRecurring.Where(tr => tr.ID == id).ToList()[0];
}
return null;
}
public TrainRecurring GetByTrainId(int trainId)
{
IEnumerable<TrainRecurring> trRcr = db.TrainsRecurring.Where(tr=>tr.TrainID == trainId);
if (trRcr != null)
{
return trRcr.ToList()[0];
}
return null;
}
public TrainRecurring GetByDaysOfWeekIdAndTrainId(int dayOfWeekId, int trainId)
{
IEnumerable<TrainRecurring> trRcr = db.TrainsRecurring.Where(tr => tr.TrainID == trainId && tr.DayOfWeekID == dayOfWeekId);
if (trRcr != null)
{
return trRcr.ToList()[0];
}
return null;
}
}
}
|
b66a43ce12a828ce254cc5a773d2969ed80ecbae | C# | emurillojr/SofiasGrill | /App_Code/TableCS.cs | 2.703125 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
// Table Class to pull from DB table by ID
namespace SE256demoWEEK1
{
public class TableCS
{
#region Properties
//match
public int Tbl_ID { get; set; }
public int Sect_ID { get; set; }
public string Tbl_Name { get; set; }
public string Tbl_Desc { get; set; }
public int Tbl_Seat_Cnt { get; set; }
public bool Tbl_Active = false;
#endregion
#region Constructors
public TableCS() { }
public TableCS(int tbl_id)
{
DataTable dt = GetTableByID(tbl_id); //match
if (dt.Rows.Count > 0)
{
//match
this.Tbl_ID = (int)dt.Rows[0]["tbl_id"];
this.Sect_ID = (int)dt.Rows[0]["sect_id"];
this.Tbl_Name = dt.Rows[0]["tbl_name"].ToString();
this.Tbl_Desc = dt.Rows[0]["tbl_desc"].ToString();
this.Tbl_Seat_Cnt = (int)dt.Rows[0]["tbl_seat_cnt"];
this.Tbl_Active = (bool)dt.Rows[0]["tbl_active"];
}
}
#endregion
#region Methods/Functions
private static DataTable GetTableByID(int tbl_id) //match
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SE256_MurilloConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("[tables_getbyID]", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@tbl_id", SqlDbType.Int).Value = tbl_id;
DataTable dt = new DataTable();
try
{
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch
{
}
finally
{
cn.Close();
}
return dt;
}
public static bool UpdateTable(TableCS sr)
{
bool blnSuccess = false;
SqlConnection cn = new SqlConnection(
ConfigurationManager.ConnectionStrings["SE256_MurilloConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("tables_update", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(
"@tbl_id", SqlDbType.Int).Value = sr.Tbl_ID;
cmd.Parameters.Add(
"@sect_id", SqlDbType.Int).Value = sr.Sect_ID;
cmd.Parameters.Add(
"@tbl_name", SqlDbType.VarChar).Value = sr.Tbl_Name;
cmd.Parameters.Add(
"@tbl_desc", SqlDbType.VarChar).Value = sr.Tbl_Desc;
cmd.Parameters.Add(
"@tbl_seat_cnt", SqlDbType.Int).Value = sr.Tbl_Seat_Cnt;
cmd.Parameters.Add(
"@tbl_active", SqlDbType.Bit).Value = sr.Tbl_Active;
try
{
cn.Open();
cmd.ExecuteNonQuery();
blnSuccess = true;
}
catch (Exception exc)
{
//error -> notify user
exc.ToString();
blnSuccess = false;
}
finally
{
cn.Close();
}
return blnSuccess;
}
public static bool InsertTable(TableCS sr)
{
bool blnSuccess = false;
SqlConnection cn = new SqlConnection(
ConfigurationManager.ConnectionStrings["SE256_MurilloConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("tables_insert", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(
"@sect_id", SqlDbType.Int).Value = sr.Sect_ID;
cmd.Parameters.Add(
"@tbl_name", SqlDbType.VarChar).Value = sr.Tbl_Name;
cmd.Parameters.Add(
"@tbl_desc", SqlDbType.VarChar).Value = sr.Tbl_Desc;
cmd.Parameters.Add(
"@tbl_seat_cnt", SqlDbType.Int).Value = sr.Tbl_Seat_Cnt;
cmd.Parameters.Add(
"@tbl_active", SqlDbType.Bit).Value = sr.Tbl_Active;
try
{
cn.Open();
//execute -> stored procedure
cmd.ExecuteNonQuery();
blnSuccess = true;
}
catch (Exception exc)
{
//error -> notify user
exc.ToString();
blnSuccess = false;
}
finally
{
cn.Close();
}
return blnSuccess;
}
#endregion
}
}
|
3775cf3dc2debc6ae76dcded6c5024829fa01d71 | C# | SorenZ/DataFramework | /src/DF.Core/Contracts/IRepository[TAggregate,TKey].cs | 2.625 | 3 | using DF.Core.Models;
namespace DF.Core.Contracts
{
/// <summary>
/// Represents a generic repository.
/// </summary>
public interface IRepository<TEntity, in TKey> : IRepository<TEntity>
where TEntity : IEntity<TKey>
{
/// <summary>
/// Gets an item by its key.
/// </summary>
/// <returns> </returns>
TEntity GetItemByKey(TKey id);
/// <summary>
/// Delete the specific aggregate by Id (permanently)
/// </summary>
/// <param name="id"></param>
void DeleteItemByKey(TKey id);
}
}
|
f3810f4782149ac8cb8d9d1c33c5e4326d084a39 | C# | personalnexus/ShUtilities | /Collections/SortedListExtensions.cs | 3.21875 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
namespace ShUtilities.Collections
{
public static class SortedListExtensions
{
/// <summary>
/// Copies the elements below and above the <paramref name="pivot"/> element in <paramref name="list"/> into the given spans.
/// If the pivot is contained in the list, it is excluded. The number of desired elments is determined by the lengths of
/// <paramref name="below"/> and <paramref name="above"/>. The return value tuple indicates how many items were actually
/// copied into the spans in case there weren't enough in the source list.
/// </summary>
public static (int resultBelowCount, int resultAboveCount) GetBelowAndAbove<TKey, TValue>(this SortedList<TKey, TValue> list, TKey pivot, Span<TValue> below, Span<TValue> above)
{
int aboveStart = TryGetIndexOf(list.Keys, list.Comparer, pivot, out int pivotIndex) ? pivotIndex + 1 : pivotIndex;
return (list.Values.SliceInBounds(pivotIndex - below.Length, below.Length, below),
list.Values.SliceInBounds(aboveStart, above.Length, above));
}
/// <summary>
/// Tries to return all values from a <see cref="SortedList{TKey, TValue}"/> whose keys fall into the given range.
/// </summary>
/// <returns>True, if at least one matching value was found, otherwise false.</returns>
public static bool TryGetRange<TKey, TValue>(this SortedList<TKey, TValue> list, TKey lowerBound, TKey upperBound, out IEnumerable<TValue> values)
{
bool result = TryGetRange(list, list.Values, lowerBound, upperBound, out values);
return result;
}
/// <summary>
/// Tries to return all key-value-pairs from a <see cref="SortedList{TKey, TValue}"/> whose keys fall into the given range.
/// </summary>
/// <returns>True, if at least one matching value was found, otherwise false.</returns>
public static bool TryGetRange<TKey, TValue>(this SortedList<TKey, TValue> list, TKey lowerBound, TKey upperBound, out IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs)
{
bool result = TryGetRange(list, list, lowerBound, upperBound, out keyValuePairs);
return result;
}
private static bool TryGetRange<TKey, TValue, TResult>(this SortedList<TKey, TValue> list, IEnumerable<TResult> resultSourceItems, TKey lowerBound, TKey upperBound, out IEnumerable<TResult> resultItems)
{
if (list.Comparer.Compare(lowerBound, upperBound) > 0)
{
throw new ArgumentException($"{nameof(lowerBound)} must be less than or equal to {nameof(upperBound)}.");
}
TryGetIndexOf(list.Keys, list.Comparer, lowerBound, out int lowerIndex);
int upperIndex = lowerIndex;
while (upperIndex < list.Count)
{
if (list.Comparer.Compare(upperBound, list.Keys[upperIndex]) < 0)
{
break;
}
upperIndex++;
}
int valueCount = upperIndex - lowerIndex;
bool result = valueCount != 0;
resultItems = result ? resultSourceItems.Skip(lowerIndex).Take(valueCount) : Enumerable.Empty<TResult>();
return result;
}
/// <summary>
/// Used internally by TryGetRange on a SortedList's keys and therefore assumes the list <paramref name="keys"/> is sorted and does not contain duplicates.
/// </summary>
private static bool TryGetIndexOf<TKey>(IList<TKey> keys, IComparer<TKey> comparer, TKey key, out int index)
{
bool result = false;
index = 0;
int lowerBound = 0;
int upperBound = keys.Count - 1;
while (lowerBound <= upperBound && !result)
{
int pivot = lowerBound + (upperBound - lowerBound) / 2;
int comparisonResult = comparer.Compare(key, keys[pivot]);
if (comparisonResult == 0)
{
result = true;
index = pivot;
}
else if (comparisonResult < 0)
{
upperBound = pivot - 1;
}
else
{
lowerBound = pivot + 1;
}
}
if (!result)
{
index = lowerBound;
}
return result;
}
}
}
|
c9bc926185386d3f9b54c48d4fee347f927c2e92 | C# | anfavretto/AnalisadorLexico | /AnalizadorLexico/Token.cs | 2.9375 | 3 | namespace AnalizadorLexico
{
public abstract class Token
{
public TokenType Type { get; set; }
public Token(TokenType type)
{
this.Type = type;
}
public abstract string GetValue();
}
}
|
cd901b77ee30168621fed3fd2380d62de91465a9 | C# | eto4detak/Kingdom | /Assets/Scripts/Game/Tumbler.cs | 2.59375 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Tumbler : Singleton<Tumbler>
{
public Button tumbler;
public TublerState state;
private Text txtTubler;
protected void Start()
{
txtTubler = tumbler.GetComponentInChildren<Text>();
tumbler.onClick.AddListener(ChangeTumbler);
ChangeTumbler(TublerState.path);
}
public void ChangeTumbler(TublerState data)
{
state = data;
txtTubler.text = state.ToString();
}
public void ChangeTumbler()
{
if (state == TublerState.bonus)
{
state = TublerState.path;
}
else
{
state = TublerState.bonus;
}
txtTubler.text = state.ToString();
}
}
public enum TublerState
{
bonus,
path,
} |
a8a49eed2429676f9db4bc5d9a6f4a65cb41a742 | C# | MercuryNuGet/SuperTuples | /SuperTuples.Test/JsonSerializationTests.cs | 3.109375 | 3 | using Mercury;
using Newtonsoft.Json;
using NUnit.Framework;
namespace SuperTuples.Test
{
public sealed class JsonSerializationTests : MercurySuite
{
protected override void Specifications()
{
Specs += "When serializing #1 to json"
.ArrangeNull()
.With(new Person("Alan", "Evans", 35), "{\"FirstName\":\"Alan\",\"LastName\":\"Evans\",\"Age\":35}")
.With(new Person("John", "Doe", 45), "{\"FirstName\":\"John\",\"LastName\":\"Doe\",\"Age\":45}")
.Act((_, p, e) => JsonConvert.SerializeObject(p))
.Assert("expect json to not include protected members", (r, expected) => Assert.AreEqual(expected, r));
Specs += "When round trip serializing #1 to and from json"
.ArrangeNull()
.With(new Person("Alan", "Evans", 35))
.With(new Person("John", "Doe", 45))
.Act((_, p) => JsonConvert.DeserializeObject<Person>(JsonConvert.SerializeObject(p)))
.Assert("expect result to not be same object", (r, p) => Assert.AreNotSame(p, r))
.Assert("expect result to be equal to original", (r, p) => Assert.AreEqual(p, r));
}
public class Person : Suple<string, string, int>
{
public Person(string firstName, string lastName, int age)
: base(firstName, lastName, age)
{
}
public string FirstName => Item1;
public string LastName => Item2;
public int Age => Item3;
}
}
}
|
e8f57f958729ac5e1875f03e6478349ec99ce99a | C# | monosan9/csharp | /Wzorki/Program.cs | 3.46875 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wzorki
{
class Program
{
const char CHAR = '*';
static void Star() => Console.Write(CHAR);
static void StarLn() => Console.WriteLine(CHAR);
static void Space() => Console.Write(" ");
static void SpaceLn() => Console.WriteLine(" ");
static void NewLine() => Console.WriteLine();
// Prostokąt
//public static void Prostokat(int n, int m) //n - szerokosc, linia pionowa, m - dlugosc, linia pozioma
//{
// for (int i = 0; i < n; i++)
// {
// Star();
// }
// NewLine();
// for (int j = 1; j < m - 1; j++)
// {
// Star();
// for (int i = 1; i < n - 1; i++)
// Space();
// StarLn();
// }
// for (int i = 0; i < n; i++)
// {
// Star();
// }
// NewLine();
//}
//public static void Main(string[] args)
//{
// Prostokat(5, 7);
//}
//Litera X
static void LiteraX(int n) // n- wysokosc, linie pionowe
{
if (n < 3) throw new ArgumentException("zbyt mały rozmiar");
if (n % 2 == 0) n = n + 1;
//górna połówka
for (int i = 0; i < n / 2; i++) // 01234 w sumie 5 narysowanych gwiazdek 0<5 etc
{
for (int j = 0; j < i; j++)
Space();
Star();
for (int j = 0; j < n - 2 - 2 * i; j++) //j < 10 - 2 - 2 x i
Space();
StarLn();
}
//pojedyncza gwiazdka w środku
for (int i = 0; i < n / 2; i++)
{
Space();
}
StarLn();
//dolna połówka, symetrycznie do górnej
for (int i = 0; i < n / 2; i++)
{
for (int j = 0; j< (n/2)-i -1; j++)
Space();
Star();
for (int j = 0; j < 2 * i +1; j++)
Space();
StarLn();
}
}
static void Main(string[] args)
{
LiteraX(12);
}
}
}
|
2dd7cd868387ceedb122ca934bc32087c7bc06db | C# | HospitableHost/CSharpHomeWork | /The first week/Windows Version/Form1.cs | 3.0625 | 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 四则运算计算器窗体版
{
public partial class 四则运算计算器 : Form
{
public 四则运算计算器()
{
InitializeComponent();
}
double val1, val2;//两个操作数
string cultype;//运算类型
bool flag1;//指明string转double是否成功
bool flag2;//指明string转double是否成功
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text == "")
val2 = 0;
else
{
flag2 = Double.TryParse(textBox2.Text,out val2);
}
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
cultype = textBox4.Text;
}
private void button1_Click(object sender, EventArgs e)
{
switch (cultype)
{
case "+" :
textBox3.Text = $"{val1+val2}";
label2.Text = "计算正确";
break;
case "-":
textBox3.Text = $"{val1-val2}";
label2.Text = "计算正确";
break;
case "*":
textBox3.Text = $"{val1*val2}";
label2.Text = "计算正确";
break;
case "/":
if (val2 == 0)
{
label2.Text = "被除数为0,不能计算,请重新输入被除数";
textBox3.Text = "error";
}
else
{
textBox3.Text = $"{val1 / val2}";
label2.Text = "计算正确";
}
break;
default:
label2.Text = "运算符错误,只支持四则运算,请重新输入运算符";
textBox3.Text = "error";
break;
}
if (!(flag1 && flag2))//检测两个操作数是否正确
{
label2.Text = "操作数出错,请检查操作数";
textBox3.Text = "error";
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "")
val1 = 0;
else
{
flag1 = Double.TryParse(textBox1.Text, out val1);
}
}
}
}
|
fe59ef528e92f0121d4a19c301b0308dfbb162d5 | C# | Michael-BCM/First-Person-Controller | /First Person Shooter/Assets/Imports/Utilities/Billboarder.cs | 3.09375 | 3 | using UnityEngine;
/// <summary>
/// Place this MonoBehaviour onto an object to enable billboarding around the selected axis.
/// </summary>
public class Billboarder : MonoBehaviour
{
/// <summary>
/// If true, this object will rotate around the 'x' axis.
/// </summary>
[Header("Axes to rotate around.")]
[SerializeField]
private bool X;
/// <summary>
/// If true, this object will rotate around the 'y' axis.
/// </summary>
[SerializeField]
private bool Y;
/// <summary>
/// If true, this object will rotate around the 'z' axis.
/// </summary>
[SerializeField]
private bool Z;
private void Update ()
{
Vector3 camPos = Camera.main.transform.position;
Vector3 thisPos = transform.position;
transform.LookAt(new Vector3(
billboardFloat(X, camPos.x, thisPos.x),
billboardFloat(Y, camPos.y, thisPos.y),
billboardFloat(Z, camPos.z, thisPos.z)));
}
/// <summary>
/// Returns one of two float values based on the value of 'coOrdinate'.
/// </summary>
/// <param name="coOrdinate">The boolean value to check against.</param>
/// <param name="trueValue">The value to return if 'coOrdinate' is true.</param>
/// <param name="falseValue">The value to return if 'coOrdinate' is false.</param>
/// <returns></returns>
private float billboardFloat (bool coOrdinate, float trueValue, float falseValue)
{
if(!coOrdinate)
return trueValue;
return falseValue;
}
} |
b3ca63d424b379bfeef25dc3575238165c33efa3 | C# | dotnet/dotnet-api-docs | /snippets/csharp/System.Net/HttpWebResponse/StatusCode/httpwebresponse_statuscode_statusdescription.cs | 3.5 | 4 | // System.Net.HttpWebResponse.StatusCode; System.Net.HttpWebResponse.StatusDescription
/* This program demonstrates the 'StatusCode' and 'StatusDescription' property of the 'HttpWebResponse' class.
It creates a web request and queries for a response. */
using System;
using System.Net;
class HttpWebResponseSnippet
{
public static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("\nPlease enter the url as command line parameter");
Console.WriteLine("Example:");
Console.WriteLine("HttpWebResponse_StatusCode_StatusDescription http://www.microsoft.com/net/");
}
else
{
GetPage(args[0]);
}
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
return;
}
// <Snippet1>
// <Snippet2>
public static void GetPage(String url)
{
try
{
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for a response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
Console.WriteLine("\r\nResponse Status Code is OK and StatusDescription is: {0}",
myHttpWebResponse.StatusDescription);
// Releases the resources of the response.
myHttpWebResponse.Close();
}
catch(WebException e)
{
Console.WriteLine("\r\nWebException Raised. The following error occurred : {0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("\nThe following Exception was raised : {0}",e.Message);
}
}
// </Snippet1>
// </Snippet2>
}
|
fd595b514f5a4862e42ec4fb009eea9ce2878a0f | C# | yifangyun/fangcloud-csharp-sdk | /Yfy.Api/Utils/StreamHelper.cs | 3.125 | 3 | namespace Yfy.Api
{
using System.IO;
internal static class StreamHelper
{
public static void CopyStream(Stream input, Stream output, int bufferSize = 4096)
{
byte[] buffer = new byte[bufferSize];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
}
}
|
fc40caa9871b9575ef09c69c1d62d3121af8f68d | C# | paillave/Etl.Net | /src/Paillave.Etl.GraphApi/Provider/Writers/EqualsMethodWriter.cs | 2.515625 | 3 | using System;
using System.Linq.Expressions;
namespace Paillave.Etl.GraphApi.Provider.Writers;
public class EqualsMethodWriter : IMethodCallWriter
{
public bool CanHandle(MethodCallExpression expression)
{
return expression.Method.Name == "Equals";
}
public string Handle(MethodCallExpression expression, Func<Expression, string> expressionWriter, ODataExpressionConverterSettings settings)
{
return string.Format(
"{0} eq {1}",
expressionWriter(expression.Object),
expressionWriter(expression.Arguments[0]));
}
}
|
19d893332532db2286633124b24cc8831e0982e0 | C# | vish35/FoodOrdering | /Models/ShoppingCart.cs | 2.78125 | 3 | using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Foodordering.Models
{
public class ShoppingCart
{
private readonly Foodorderingdbcontext _foodorderingDbContext;
public string ShoppingCartId { get; set; }
public List<ShoppingCartItem> ShoppingCartItems { get; set; }
public ShoppingCart(Foodorderingdbcontext foodorderingDbContext)
{
_foodorderingDbContext = foodorderingDbContext;
}
public List<ShoppingCartItem> GetShoppingCartItems()
{
return ShoppingCartItems =_foodorderingDbContext.ShoppingCartItems.Where(s=>s.ShoppingCartId==ShoppingCartId
).Include(s => s.item).ToList();
}
public static ShoppingCart GetCart(IServiceProvider services)
{
ISession session = services.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session;
var context = services.GetService<Foodorderingdbcontext>();
string cartId = session.GetString("CartId") ?? Guid.NewGuid().ToString();
session.SetString("CartId", cartId);
return new ShoppingCart(context) { ShoppingCartId = cartId };
}
internal decimal GetShoppingCartTotal()
{
var total = _foodorderingDbContext.ShoppingCartItems.Where(c => ShoppingCartId == ShoppingCartId)
.Select(c => c.item.price * c.quantity).Sum();
return (decimal)total;
}
public void AddToCart(FoodItem item)
{
var shoppingCartItem =
_foodorderingDbContext.ShoppingCartItems.SingleOrDefault(
s => s.item.id == item.id && s.ShoppingCartId == ShoppingCartId);
if (shoppingCartItem == null)
{
shoppingCartItem = new ShoppingCartItem
{
ShoppingCartId = ShoppingCartId,
item = item,
quantity = 1
};
_foodorderingDbContext.ShoppingCartItems.Add(shoppingCartItem);
}
else
{
shoppingCartItem.quantity++;
}
_foodorderingDbContext.SaveChanges();
}
public void RemoveFromCart(FoodItem selectedItem)
{
_foodorderingDbContext.ShoppingCartItems.Remove(_foodorderingDbContext.ShoppingCartItems.Where(s=>s.item.id==selectedItem.id).FirstOrDefault());
_foodorderingDbContext.SaveChanges();
}
public void ClearCart()
{
List<int> allitemsid = _foodorderingDbContext.ShoppingCartItems.Where(x => x.ShoppingCartId == ShoppingCartId).Select(x => x.ShoppingCartItemId).ToList();
foreach (var item in allitemsid)
{
_foodorderingDbContext.ShoppingCartItems.Remove(_foodorderingDbContext.ShoppingCartItems.Where(s => s.ShoppingCartItemId == item).FirstOrDefault());
_foodorderingDbContext.SaveChanges();
}
}
public void EditItemQuantity(FoodItem selectedItem)
{
var cart = _foodorderingDbContext.ShoppingCartItems.FirstOrDefault(s => s.item.id == selectedItem.id);
cart.quantity -= 1;
if(cart.quantity==0)
{
_foodorderingDbContext.ShoppingCartItems.Remove(_foodorderingDbContext.ShoppingCartItems.Where(s => s.item.id == selectedItem.id).FirstOrDefault());
}
_foodorderingDbContext.SaveChanges();
// _foodorderingDbContext.ShoppingCartItems.Update(ShoppingCartItems.Where(s=>s.item==selectedItem.id));
}
public void EditItemQuantityIncrease(FoodItem selectedItem)
{
var cart = _foodorderingDbContext.ShoppingCartItems.FirstOrDefault(s => s.item.id == selectedItem.id);
cart.quantity += 1;
_foodorderingDbContext.SaveChanges();
// _foodorderingDbContext.ShoppingCartItems.Update(ShoppingCartItems.Where(s=>s.item==selectedItem.id));
}
}
}
|
24d634e6f30e29f1fbfc29de5288b00b5aad6f8d | C# | vee-infosys/Yort.AfterPay.InStore | /src/Yort.AfterPay.InStore.Shared/AfterPayApiError.cs | 2.578125 | 3 | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Yort.AfterPay.InStore
{
/// <summary>
/// Represents an error response from the AfterPay API.
/// </summary>
/// <remarks>
/// <para>See the AfterPay documentation for more information; https://docs.afterpay.com.au/instore-api-v1.html#errors</para>
/// </remarks>
public class AfterPayApiError
{
/// <summary>
/// The HTTP status code that was sent in the response that contained this data.
/// </summary>
[JsonProperty("httpStatusCode")]
public int HttpStatusCode { get; set; }
/// <summary>
/// A string containing a unique error ID.
/// </summary>
[JsonProperty("errorId")]
public string ErrorId { get; set; }
/// <summary>
/// A string representing the type of error returned, e.g. invalid_object, transaction_error, or server_error.
/// </summary>
[JsonProperty("errorCode")]
public string ErrorCode { get; set; }
/// <summary>
/// A string containing a human-readable message giving more details about the error. For card errors, these messages can be shown to your users.
/// </summary>
[JsonProperty("message")]
public string Message { get; set; }
}
} |
2c25dc92f907b034e0302258b6dfb003fe18962b | C# | Xicy/Comidat | /Comidat.Runtime/Runtime/Command/Command.cs | 3.109375 | 3 | using System;
namespace Comidat.Runtime.Command
{
/// <summary>
/// Command returns
/// </summary>
public enum CommandResult
{
/// <summary>
/// Command is successfull
/// </summary>
Okay,
/// <summary>
/// command failed
/// </summary>
Fail,
/// <summary>
/// command arguments invalid
/// </summary>
InvalidArgument,
/// <summary>
/// stop the console reading
/// </summary>
Break
}
/// <summary>
/// Generalized command holder
/// </summary>
/// <typeparam name="TFunc">function of command</typeparam>
public abstract class Command<TFunc> where TFunc : class
{
/// <summary>
/// constractor of command
/// </summary>
/// <param name="name">Command name</param>
/// <param name="usage">how to use command information</param>
/// <param name="description">description of command</param>
/// <param name="func">function of command</param>
protected Command(string name, string usage, string description, TFunc func)
{
if (!typeof(TFunc).IsSubclassOf(typeof(Delegate)))
throw new InvalidOperationException(string.Format(Localization.Get("Comidat.Util.Command.Command.Constructor.InvalidOperationException"), typeof(TFunc).Name));
Name = name;
Usage = usage;
Description = description;
Func = func;
}
public string Name { get; protected set; }
public string Usage { get; protected set; }
public string Description { get; protected set; }
public TFunc Func { get; protected set; }
}
} |
a96aed3867390d73358290ac3c7a559154d0e8ec | C# | Saint-of-Grey/RimworldGastroliths | /Source/Constants.cs | 2.84375 | 3 | using RimWorld;
using Verse;
namespace Gastroliths
{
class Constants
{
public static bool is_animal(Pawn pawn)
{
return pawn.RaceProps.Animal;
}
public static Thing makeGastrolith()
{
ThingDef what = Constants.whatGastrolith();
if (what != null)
{
Log.Message("Generating Gastrolith", false);
Thing t = ThingMaker.MakeThing(what, null);
t.stackCount = Rand.RangeInclusive(0, 6) + 1;
return t;
}
else
{
Log.Message("Gastrlith declined", false);
}
return null;
}
public static ThingDef whatGastrolith()
{
float roll = Rand.Value;
roll %= 1.0f;
// Roll 1d20: 1-10 Nothing, 10-15 Chunks, 16 - Component, 17- Plastisteel, 18- Silver, 19-Gold, 20-Steel
if (roll < .95f)
{
return ThingDefOf.Steel;
}else if (roll < .90f)
{
return ThingDefOf.Gold;
}else if (roll < .85f)
{
return ThingDefOf.Silver;
}
else if (roll < .80f)
{
return ThingDefOf.Plasteel;
}
else if (roll < .75f)
{
return ThingDefOf.ComponentIndustrial;
}
else if (roll < .50f)
{
return ThingDefOf.Granite;
}
else
{
return ThingDefOf.Hay;
}
}
}
}
|
506a96662ed7a789e17883475d469fff3d0eadab | C# | iorilan/aspnetcore101 | /16-DI/DIWithAutofac/GreetingService2.cs | 3.390625 | 3 | namespace DIWithAutofac
{
public class GreetingService2 : IGreetingService
{
public string Greet(string name) {
var greet = "";
var h = System.DateTime.Now.Hour;
if(h < 12){
greet = "Morning";
}
else if(h >= 12 && h < 18){
greet = "Afternoon";
}
else{
greet = "Evening";
}
return $"{greet}, {name}";
}
}
}
|
74f3af2a35fd4f5357edbee4f31f77a6350003bd | C# | mnasif786/Safe-Check | /EvaluationChecklist/EvaluationChecklist.Generator/Mappers/ConsultantMapper.cs | 2.640625 | 3 | using System;
using System.Linq;
using System.Collections.Generic;
using BusinessSafe.Domain.Entities.SafeCheck;
using EvaluationChecklist.Models;
namespace EvaluationChecklist.Mappers
{
public static class ConsultantMapper
{
public static ConsultantViewModel Map(this Consultant consultant)
{
return new ConsultantViewModel()
{
Id = consultant.Id,
Forename = consultant.Forename,
Surname = consultant.Surname,
Fullname = consultant.Forename + ' ' + (!String.IsNullOrEmpty(consultant.Surname) ? consultant.Surname : ""),
Email = consultant.Email,
Blacklisted = consultant.PercentageOfChecklistsToSendToQualityControl == 100,
QaAdvisorAssigned = consultant.QaAdvisorAssigned
};
}
public static IEnumerable<ConsultantViewModel> Map(this IEnumerable<Consultant> consultants)
{
return consultants.Select(x => x.Map());
}
}
} |
16a4084275a5c8e25d17576d47d2b8d9f6f12b2c | C# | JornWildt/Ramone | /Ramone/Utility/MethodDescription.cs | 3.046875 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ramone.Utility
{
public class MethodDescription
{
public string Method { get; protected set; }
public bool BodyAllowed { get; protected set; }
private MethodDescription(string method, bool bodyAllowed)
{
Method = method;
BodyAllowed = bodyAllowed;
}
protected static Dictionary<string, MethodDescription> Methods = new Dictionary<string, MethodDescription>();
static MethodDescription()
{
RegisterMethod("GET", false);
RegisterMethod("HEAD", false);
RegisterMethod("DELETE", false);
RegisterMethod("OPTIONS", false);
RegisterMethod("TRACE", false);
RegisterMethod("POST", true);
RegisterMethod("PUT", true);
RegisterMethod("PATCH", true);
}
public static void RegisterMethod(string method, bool bodyAllowed)
{
method = method.ToUpper();
Methods[method] = new MethodDescription(method, bodyAllowed);
}
public static MethodDescription GetMethod(string method)
{
method = method.ToUpper();
if (!Methods.ContainsKey(method))
throw new InvalidOperationException(string.Format("Trying to get meta information about method '{0}' but cannot find it: unknown method.", method));
return Methods[method];
}
}
}
|
2750ec2ee9cfc187900ddf28b0e17262e11b7824 | C# | AndyRobbAVT/RestfulTravelClub | /Infrastructure/RouteLinker.cs | 2.75 | 3 | using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Http.Controllers;
namespace Infrastructure
{
public class RouteLinker : IResourceLinker
{
private readonly ContextWrapper _contextWrapper;
public RouteLinker(ContextWrapper contextWrapper)
{
_contextWrapper = contextWrapper;
}
public Uri GetUri<T>(Expression<Action<T>> method)
{
if (method == null)
throw new ArgumentNullException("method");
var methodCallExp = method.Body as MethodCallExpression;
if (methodCallExp == null)
throw new ArgumentException("The expression's body must be a MethodCallExpression. The code block supplied should invoke a method.\nExample: x => x.Foo().", "method");
var routeValues = methodCallExp.Method.GetParameters().ToDictionary(p => p.Name, p => GetValue(methodCallExp, p));
var controllerName = methodCallExp.Method.ReflectedType.Name.ToLowerInvariant().Replace("controller", "");
routeValues.Add("controller", controllerName);
var relativeUri = _contextWrapper.Context.Url.Route("DefaultApi", routeValues);
return new Uri(_contextWrapper.BaseUri, relativeUri);
}
private static object GetValue(MethodCallExpression methodCallExp,ParameterInfo p)
{
var arg = methodCallExp.Arguments[p.Position];
var lambda = Expression.Lambda(arg);
return lambda.Compile().DynamicInvoke().ToString();
}
}
} |
2332bacf46e328c60b6de050826f51c0c1237c8f | C# | mavrovski/SoftUni | /Programming Basics - Exercises/07.Advanced Loops/01. Numbers 1...N with Step 3.cs | 2.703125 | 3 | using System;
public class Program
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
for(int i = 1;i<=n;i+=3)
{
Console.WriteLine(i);
}
}
}
|
f47d355e7902642cd792f06543de93639a5a124f | C# | russjudge/ArtemisModLoader | /ArtemisComm/ShipActionSubPackets/SetStationSubPacket.cs | 2.84375 | 3 | using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ArtemisComm.ShipActionSubPackets
{
public class SetStationSubPacket : IPackage
{
//**CONFIRMED
public static Packet GetPacket(StationTypes station, bool isSelected)
{
SetStationSubPacket sstp = new SetStationSubPacket(station, isSelected);
ShipActionPacket sap = new ShipActionPacket(sstp);
return new Packet(sap);
}
static readonly ILog _log = LogManager.GetLogger(typeof(SetStationSubPacket));
//public SetStationSubPacket()
//{
// if (_log.IsDebugEnabled) { _log.DebugFormat("Starting {0}", MethodBase.GetCurrentMethod().ToString()); }
// _isSelected = 0;
// if (_log.IsDebugEnabled) { _log.DebugFormat("Ending {0}", MethodBase.GetCurrentMethod().ToString()); }
//}
public SetStationSubPacket(StationTypes station, bool isSelected)
{
if (_log.IsDebugEnabled) { _log.DebugFormat("Starting {0}", MethodBase.GetCurrentMethod().ToString()); }
IsSelected = isSelected;
Station = station;
if (_log.IsDebugEnabled) { _log.DebugFormat("Ending {0}", MethodBase.GetCurrentMethod().ToString()); }
}
public SetStationSubPacket(byte[] byteArray)
{
if (_log.IsDebugEnabled) { _log.DebugFormat("Starting {0}", MethodBase.GetCurrentMethod().ToString()); }
if (byteArray != null)
{
if (_log.IsInfoEnabled) { _log.InfoFormat("{0}--bytes in: {1}", MethodBase.GetCurrentMethod().ToString(), Utility.BytesToDebugString(byteArray)); }
if (byteArray.Length > 3)
{
Station = (StationTypes)BitConverter.ToInt32(byteArray, 0);
}
if (byteArray.Length > 7)
{
_isSelected = BitConverter.ToInt32(byteArray, 4);
}
if (_log.IsInfoEnabled) { _log.InfoFormat("{0}--Result bytes: {1}", MethodBase.GetCurrentMethod().ToString(), Utility.BytesToDebugString(this.GetBytes())); }
}
if (_log.IsDebugEnabled) { _log.DebugFormat("Ending {0}", MethodBase.GetCurrentMethod().ToString()); }
}
public StationTypes Station { get; set; }
int _isSelected = 0;
public bool IsSelected
{
get
{
return Convert.ToBoolean(_isSelected);
}
set
{
_isSelected = Convert.ToInt32(value);
}
}
public byte[] GetBytes()
{
List<byte> retVal = new List<byte>();
retVal.AddRange(BitConverter.GetBytes((int)Station));
retVal.AddRange(BitConverter.GetBytes(_isSelected));
return retVal.ToArray();
}
}
} |
ca66a3c63014124d93da7a099c82b6351c803f64 | C# | suterds/VR-Game-Virtual-Runners | /Virtual Runners/Assets/Scripts/Tools/ToolCollideWithObstacle.cs | 2.765625 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Script Purpose: Detect when the tool has collided with a trigger collider attached to an obstacle with a ToolEnter.cs script component
// If the CollidedObject does have a ToolEnter.cs script, an Event will be sent to the Subscribed Object
public class ToolCollideWithObstacle : MonoBehaviour
{
// Detect when the attached object has entered a trigger collider
private void OnTriggerEnter(Collider other)
{
// Tell 'other' the tool has entered the collider
ToolEnter obj = other.GetComponent<ToolEnter>();
if (obj)
{
GameEvents.current.ToolEnter(obj.GetInstanceID(), gameObject, other);
}
}
// Detect when the attached object has left a trigger collider
private void OnTriggerExit(Collider other)
{
// Tell 'other' the test subject has left the collider
ToolEnter obj = other.GetComponent<ToolEnter>();
if (obj)
{
GameEvents.current.ToolExit(obj.GetInstanceID(), gameObject, other);
}
}
}
|
9e11d4023a7b93d9a3119f7f9efe5dd329b41f5b | C# | elindanielsson/Nybus | /src/engines/Nybus.Engine.RabbitMq/RabbitMq/BufferSubject.cs | 2.859375 | 3 | using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
namespace Nybus.RabbitMq
{
public class BufferSubject<T> : ISubject<T>
{
private readonly Subject<T> _subject = new Subject<T>();
private readonly Queue<Action<IObserver<T>>> _actions = new Queue<Action<IObserver<T>>>();
private bool _isCompleted = false;
private Exception _error;
public bool IsRunning => !_isCompleted && _error == null;
public bool HasObservers => _refCount > 0;
public void OnCompleted()
{
_isCompleted = true;
if (!HasObservers)
{
_actions.Enqueue(o => o.OnCompleted());
}
_subject.OnCompleted();
}
public void OnError(Exception error)
{
_error = error;
if (!HasObservers)
{
_actions.Enqueue(o => o.OnError(error));
}
_subject.OnError(error);
}
public void OnNext(T value)
{
if (IsRunning)
{
if (HasObservers)
{
_subject.OnNext(value);
}
else
{
_actions.Enqueue(o => o.OnNext(value));
}
}
}
private int _refCount = 0;
public IDisposable Subscribe(IObserver<T> observer)
{
var disposable = new CompositeDisposable(
Observable.Create<T>(o => ConsumeActions(o)).Concat(_subject).Subscribe(observer),
Disposable.Create(() => Interlocked.Decrement(ref _refCount))
);
Interlocked.Increment(ref _refCount);
return disposable;
}
private IDisposable ConsumeActions(IObserver<T> observable)
{
while (_actions.Count > 0)
{
var action = _actions.Dequeue();
action(observable);
}
observable.OnCompleted();
return Disposable.Empty;
}
}
} |
9b967c8d88f136a44d30b6707baf7487256adbd7 | C# | autofac/Autofac | /src/Autofac/Util/Enforce.cs | 2.703125 | 3 | // Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Globalization;
using System.Reflection;
namespace Autofac.Util;
/// <summary>
/// Helper methods used throughout the codebase.
/// </summary>
internal static class Enforce
{
/// <summary>
/// Enforce that sequence does not contain null. Returns the
/// value if valid so that it can be used inline in
/// base initialiser syntax.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="name">The parameter name.</param>
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
public static IEnumerable<T> ArgumentElementNotNull<T>(IEnumerable<T> value, string name)
where T : class
{
if (value == null)
{
throw new ArgumentNullException(name);
}
if (value.Any(e => e == null))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, EnforceResources.ElementCannotBeNull, name));
}
return value;
}
/// <summary>
/// Enforces that the provided object is non-null.
/// </summary>
/// <typeparam name="T">The type of value being checked.</typeparam>
/// <param name="value">The value.</param>
/// <returns><paramref name="value"/> if not null.</returns>
public static T NotNull<T>([ValidatedNotNull] T value)
where T : class
{
if (value == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, EnforceResources.CannotBeNull, typeof(T).FullName));
}
return value;
}
/// <summary>
/// Enforce that an argument is not null or empty. Returns the
/// value if valid so that it can be used inline in
/// base initialiser syntax.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="description">The description.</param>
/// <returns><paramref name="value"/>if not null or empty.</returns>
public static string ArgumentNotNullOrEmpty([ValidatedNotNull] string value, string description)
{
if (description == null)
{
throw new ArgumentNullException(nameof(description));
}
if (value == null)
{
throw new ArgumentNullException(description);
}
if (value.Length == 0)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, EnforceResources.CannotBeEmpty, description));
}
return value;
}
/// <summary>
/// Enforce that the argument is a delegate type.
/// </summary>
/// <param name="delegateType">The type to test.</param>
public static void ArgumentTypeIsFunction(Type delegateType)
{
if (delegateType == null)
{
throw new ArgumentNullException(nameof(delegateType));
}
MethodInfo invoke = delegateType.GetDeclaredMethod("Invoke") ?? throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, EnforceResources.NotDelegate, delegateType));
if (invoke.ReturnType == typeof(void))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, EnforceResources.DelegateReturnsVoid, delegateType));
}
}
}
|
fa309f424c2de4e6b6b22e93a95d8c0a3a05bc04 | C# | aristeoibarra/HackerRank_Exercises | /Exercises/Abstract Classes/Book.cs | 3.09375 | 3 | namespace Abstract_Classes
{
abstract class Book
{
protected string title;
protected string author;
public Book(string title, string author)
{
this.title = title;
this.author = author;
}
public abstract void Display();
}
} |
e6443fc91800bc2326133f1cc188ded47d28b32e | C# | JosephZhu1983/WcfExtension | /QuickStart/QuickStart.Demo.Client/Program.cs | 2.65625 | 3 | namespace QuickStart.Demo.Client
{
using System;
using System.Threading;
using QuickStart.Services.Interface;
using WcfExtension;
class Program
{
protected static void Main(params string[] args)
{
Console.WriteLine("Wait 3 seconds");
Thread.Sleep(3000);
try
{
while (true)
{
var proxy = WcfServiceLocator.Create<IQsService>();
var result = proxy.SayHelloWorld("Batman");
Console.WriteLine("Result is " + result);
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
|
c3e524cd09e3f84e07db7ea287d384981e9f1b97 | C# | devdor/SQLiteORMapper | /src/Dto/Category.cs | 2.703125 | 3 | using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace SQLiteORMapper.Dto {
[Table("category")]
public class Category : AbstractDataItem {
#region Fields and Properties
[AppColumn("name")]
public string Name {
get;
set;
}
#endregion
public static Category Create(string name) {
if (String.IsNullOrEmpty(name))
throw new ArgumentNullException("Name");
return new Category() {
Name = name
};
}
}
}
|
7a0c93112a843abadeb7f05ff27f497de867159f | C# | darshanrampatel/Advent-of-Code-2017 | /AoC2017.Tests/Day13Test.cs | 2.953125 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace AoC2017.Tests
{
public class Day13Test
{
[Theory]
[InlineData(@"0: 3
1: 2
4: 4
6: 4", 24)]
public void Part1(string input, int output)
{
var result = Day13.Part1(input);
Assert.True(result == output, $"Expected: {output}, Received: {result}");
}
[Theory]
[InlineData(@"0: 3
1: 2
4: 4
6: 4", 10)]
public void Part2(string input, int output)
{
var result = Day13.Part2(input);
Assert.True(result == output, $"Expected: {output}, Received: {result}");
}
}
}
|
54d10cd7a8af2d8e634b68b710c9bcefcdc9a2a6 | C# | AndreYamasaki/Exercicio_23 | /Exercicio_23/Exercicio_02.aspx.cs | 2.5625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Exercicio_23
{
public partial class Exercicio_02 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
/*
* Nome: André Tsutae Yamasaki
* RA: 1550781921015
* Data: 27/04/2021
* Exercício Número: 02
* Questionário Número: 23
*/
String A, B, C;
A = txtA.Text;
B = txtB.Text;
C = A;
A = B;
B = C;
lblResultadoA.Text = A;
lblResultadoB.Text = B;
}
}
} |
a888d66be91a90e7db074c550cbbf844749d8251 | C# | PracticaNetRom/andreea.mateiasi | /SummerCamp2017/API/DataAccess/CategoryMap.cs | 2.6875 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace API.DataAccess
{
public class CategoryMap : EntityTypeConfiguration<Category>
{
public CategoryMap()
{
// Primary Key
this.HasKey(t => t.CategoryId);
// Table & Column Mappings
this.ToTable("Category");
this.Property(t => t.CategoryId).HasColumnName("CategoryId").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(t => t.Name).HasColumnName("Name").IsRequired().HasMaxLength(32);
}
}
} |
fc765217e4611d2f5a840f038f84baff0bf9203c | C# | leith-bartrich/libplatform | /Platform.cs | 2.9375 | 3 | //Copyright (C) 2011, FIE LLC.
//See LICENSE.TXT for details.
using System;
using System.Diagnostics;
namespace libplatform
{
/// <summary>
/// Utility class. Helps deal with platform detection and possibly platform specific functionality.
/// We're not going to simplify this to the point that we just return an enumerated value for the platform.
/// Instead, we're going to effectively provide the ability to ask questions about capabilities as much as possible.
///
/// Hence, not just "is_linux", "is_windows", "is_osx".
/// But rather, "is_unix_style" "is_windows" "is_osx" "is_linux"
/// </summary>
public class CurrentPlatform
{
/// <summary>
/// Returns true if the system is a unix styled system such as Linux, BSD or OSX.
/// If "unix styled system" becomes ambiguous at some point, we'll need to modify this.
/// </summary>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public static bool IsUnixStyle()
{
//yes, this is odd code. check the explanation at the mono-project site for why.
int p = (int)System.Environment.OSVersion.Platform;
return (p == 4 || p == 6 || p == 128);
}
/// <summary>
/// Returns true if the system is a Linux system.
/// </summary>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public static bool IsLinux()
{
if (IsUnixStyle())
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName = "uname";
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
p.WaitForExit();
string unameRet = p.StandardOutput.ReadLine();
if (unameRet == "Darwin")
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the system is a Windows system.
/// </summary>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public static bool IsWindows()
{
if (IsUnixStyle())
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// Returns true if the system is an OSX system.
/// </summary>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public static bool IsOSX()
{
if (IsUnixStyle())
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName = "uname";
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
p.WaitForExit();
string unameRet = p.StandardOutput.ReadLine();
if (unameRet == "Darwin")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
}
|
b734874e4d06fa95e03f3cb301b6a4129929a2e0 | C# | Technology-Community/Computer-Timer-manager | /ShutDown/ShutdownManager/frmSelectMonth.cs | 2.53125 | 3 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ShutdownManager
{
public partial class frmSelectMonth : Form
{
public frmSelectMonth()
{
InitializeComponent();
}
public static bool boolCheck1 = true;
public static bool boolCheck2 = true;
public static bool boolCheck3 = true;
public static bool boolCheck4 = true;
public static bool boolCheck5 = true;
public static bool boolCheck6 = true;
public static bool boolCheck7 = true;
public static bool boolCheck8 = true;
public static bool boolCheck9 = true;
public static bool boolCheck10 = true;
public static bool boolCheck11 = true;
public static bool boolCheck12 = true;
#region Event
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
boolCheck1 = true;
}
else
{
boolCheck1 = false;
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked)
{
boolCheck2 = true;
}
else
{
boolCheck2 = false;
}
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked)
{
boolCheck3 = true;
}
else
{
boolCheck3 = false;
}
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
if (checkBox4.Checked)
{
boolCheck4 = true;
}
else
{
boolCheck4 = false;
}
}
private void checkBox5_CheckedChanged(object sender, EventArgs e)
{
if (checkBox5.Checked)
{
boolCheck5 = true;
}
else
{
boolCheck5 = false;
}
}
private void checkBox6_CheckedChanged(object sender, EventArgs e)
{
if (checkBox6.Checked)
{
boolCheck6 = true;
}
else
{
boolCheck6 = false;
}
}
private void checkBox7_CheckedChanged(object sender, EventArgs e)
{
if (checkBox7.Checked)
{
boolCheck7 = true;
}
else
{
boolCheck7 = false;
}
}
private void checkBox8_CheckedChanged(object sender, EventArgs e)
{
if (checkBox8.Checked)
{
boolCheck8 = true;
}
else
{
boolCheck8 = false;
}
}
private void checkBox9_CheckedChanged(object sender, EventArgs e)
{
if (checkBox9.Checked)
{
boolCheck9 = true;
}
else
{
boolCheck9 = false;
}
}
private void checkBox10_CheckedChanged(object sender, EventArgs e)
{
if (checkBox10.Checked)
{
boolCheck10 = true;
}
else
{
boolCheck10 = false;
}
}
private void checkBox11_CheckedChanged(object sender, EventArgs e)
{
if (checkBox11.Checked)
{
boolCheck11 = true;
}
else
{
boolCheck11 = false;
}
}
private void checkBox12_CheckedChanged(object sender, EventArgs e)
{
if (checkBox12.Checked)
{
boolCheck12 = true;
}
else
{
boolCheck12 = false;
}
}
private void btnOK_Click(object sender, EventArgs e)
{
if (!(boolCheck1) && !(boolCheck2) && !(boolCheck3) && !(boolCheck4) &&
!(boolCheck5) && !(boolCheck6) && !(boolCheck7) && !(boolCheck8) &&
!(boolCheck9) && !(boolCheck10) && !(boolCheck11) && !(boolCheck12))
{
MessageBox.Show("Bạn Phải Chọn Ít Nhất Là Một Tháng", "Time Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
this.Close();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void frmSelectMonth_Load(object sender, EventArgs e)
{
checkBox1.Checked = boolCheck1;
checkBox2.Checked = boolCheck2;
checkBox3.Checked = boolCheck4;
checkBox4.Checked = boolCheck4;
checkBox5.Checked = boolCheck5;
checkBox6.Checked = boolCheck6;
}
private void frmSelectMonth_Resize(object sender, EventArgs e)
{
this.Size = new Size(301, 345);
}
#endregion
}
} |
76d17c4c91cb6d4b9d29d9516b1064812832edd6 | C# | rkaszczuk/NETCoreCourseSamples | /07_MethodChaining/Samples/OrderCompositionSample.cs | 3.5625 | 4 | using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace _07_MethodChaining.Samples
{
public enum PaymentOptions { Cash, CreditCard, BankTransfer}
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
public class Order
{
public string Address { get; set; }
public List<Product> Products { get; set; } = new List<Product>();
public decimal TotalPrice { get; set; }
public PaymentOptions PaymentOption { get; set; }
}
public class OrderCompositionSample
{
private Order order;
public OrderCompositionSample()
{
order = new Order();
}
public OrderCompositionSample AddProduct(Product product)
{
order.Products.Add(product);
return this;
}
public OrderCompositionSample SetAddress(string address)
{
order.Address = address;
return this;
}
public OrderCompositionSample SetPaymentOption(PaymentOptions paymentOption)
{
order.PaymentOption = paymentOption;
return this;
}
public Order ComposeOrder()
{
order.TotalPrice = order.Products.Sum(x => x.Price);
return order;
}
}
public class OrderCompositionStaticInitSample
{
private Order order;
private OrderCompositionStaticInitSample()
{
order = new Order();
}
public static OrderCompositionStaticInitSample Init()
{
return new OrderCompositionStaticInitSample();
}
public OrderCompositionStaticInitSample AddProduct(Product product)
{
order.Products.Add(product);
return this;
}
public OrderCompositionStaticInitSample SetAddress(string address)
{
order.Address = address;
return this;
}
public OrderCompositionStaticInitSample SetPaymentOption(PaymentOptions paymentOption)
{
order.PaymentOption = paymentOption;
return this;
}
public Order ComposeOrder()
{
order.TotalPrice = order.Products.Sum(x => x.Price);
return order;
}
}
}
|
3ceda5ac12fa361ed0a09de6f0d3de8090dd2a1a | C# | twilio/twilio-csharp | /src/Twilio/Types/OutboundSmsPrice.cs | 2.78125 | 3 | using System.Collections.Generic;
using Newtonsoft.Json;
namespace Twilio.Types
{
/// <summary>
/// POCO to represent an outbound SMS price
/// </summary>
public class OutboundSmsPrice
{
/// <summary>
/// SMS mcc
/// </summary>
[JsonProperty("mcc")]
public string Mcc { get; }
/// <summary>
/// SMS mnc
/// </summary>
[JsonProperty("mnc")]
public string Mnc { get; }
/// <summary>
/// Carrier name
/// </summary>
[JsonProperty("carrier")]
public string Carrier { get; }
/// <summary>
/// List of prices
/// </summary>
[JsonProperty("prices")]
public List<InboundSmsPrice> Prices { get; }
/// <summary>
/// Create a new OutboundSmsPrice
/// </summary>
/// <param name="mcc">SMS mcc</param>
/// <param name="mnc">SMS mnc</param>
/// <param name="carrier">Carrier name</param>
/// <param name="prices">List of prices</param>
public OutboundSmsPrice (
string mcc,
string mnc,
string carrier,
List<InboundSmsPrice> prices
)
{
Mcc = mcc;
Mnc = mnc;
Carrier = carrier;
Prices = prices;
}
}
}
|
e48640e098b9df7c5c3d5cb5b7cc50607337a28e | C# | ShemSkillman/AIN254-TankShooter3D | /TankShooter3D/Assets/Scripts/Core/GameSession.cs | 2.640625 | 3 | using System.Collections;
using UnityEngine;
using TankShooter.Combat;
namespace TankShooter.Core
{
public class GameSession : MonoBehaviour
{
[SerializeField] int pointsPerKill = 15;
[SerializeField] Health player;
public int Kills { get { return kills; } }
public int TotalScore { get { return totalScore; } }
public string Time { get { return time; } }
public Health Player { get { return player; } }
int kills = 0;
int totalScore = 0;
string time;
public delegate void OnEnemyKilled(int killCount, int totalScore);
public event OnEnemyKilled onEnemyKilled;
public delegate void OnTimerTick(string time);
public event OnTimerTick onTimerTick;
private void Start()
{
StartCoroutine(UpdateTimer());
}
public void EnemyDestroyed()
{
kills++;
totalScore += pointsPerKill;
onEnemyKilled?.Invoke(kills, totalScore);
}
IEnumerator UpdateTimer()
{
int totalSeconds = 0;
while (true)
{
yield return new WaitForSeconds(1f);
totalSeconds += 1;
int seconds = totalSeconds;
int hours = seconds / 3600;
seconds -= hours * 3600;
int minutes = seconds / 60;
seconds -= minutes * 60;
time = string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
onTimerTick?.Invoke(time);
}
}
}
}
|
c0a0d2bff90f2988beb4d279d30cfd17ec66b225 | C# | spacecalm/csharpsortarray | /ConsoleExt.cs | 3.03125 | 3 | namespace System.ConsoleExt
{
public static class ConsoleExt
{
public static void WriteArrayIFormattable<T>(T[] array) where T : IFormattable
{
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i]);
if (i != array.Length - 1)
Console.Write(", ");
}
Console.Write(";");
}
}
}
|
52e65d2b262819322177c84e4e59d8524be987db | C# | UNFDanmark/GDC2017-GR9 | /Raft Adventures/Assets/Scripts/CameraScript.cs | 2.515625 | 3 | using UnityEngine;
using System.Collections;
public class CameraScript : MonoBehaviour {
Camera cam;
private GameObject selectedGameObject;
Rigidbody thisRigidbody;
float distance;
// Use this for initialization
void Start() {
cam = GetComponent<Camera>();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray,out hit,300f,1<<LayerMask.NameToLayer("Enemies"))) {
selectedGameObject = hit.transform.gameObject;
}
}
if (Input.GetMouseButtonUp(0)) {
selectedGameObject = null;
}
if (Input.GetMouseButton(0) && selectedGameObject != null) {
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 300f, 1 << LayerMask.NameToLayer("Enemy Height"))) {
selectedGameObject.transform.position = hit.point;
}
}
}
}
/*
Vector3 getPointVector( Vector3 camPoint, Vector3 hitPoint,float height) {
return ((height- camPoint.y) / transform.position.y) * transform.position + camPoint;
Vector3 vecline = (selectedGameObject.transform.position - transform.position);
selectedGameObject.transform.position = getPointVector(vecline,hit.point, selectedGameObject.transform.lossyScale.y);
*/ |
d76e68a5dbdd8174939e281fc0f9a09420b54e5a | C# | g-mirchev/A-Tailor-s-Tale-of-Shoemaking | /Assets/Scripts/Ending.cs | 2.75 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ending
{
private string endTitle;
public string EndTitle
{
set{endTitle = value;}
get{return endTitle;}
}
private string endStory;
public string EndStory
{
set{endStory = value;}
get{return endStory;}
}
private int endNum;
public int EndNum
{
set{endNum = value;}
get{return endNum;}
}
public Ending(int p)
{
SetEnding(p);
}
public void SetEnding(int p)
{
switch (p)
{
case 1:
case 2:
EndNum = 1;
EndTitle = "The Friend Who Wasn't There";
EndStory = "After losing his wife and unborn child while on military service, the Shoemaker fell into a severe depression to the point where he wouldn't care about himself nor his workshop. He ended up commiting suicide during the Royal Wedding. Witnesses say they found him lying dead with a smile on his face. His former best friend Vismund, who couldn't bare the guilt of abandoning the Shoemaker in his moments of need, followed his example about a week later.";
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
EndNum = 2;
EndTitle = "Well You Tried... Now What?";
EndStory = "After working a few days and taking a few days off the Shoemaker eventually failed to gather the money for his council tax and was thus kicked out by the council. Some people state that they have seen the old man scavaging the streets, making footware from dead rodent hides and attempting to sell them. Others believe he is now dead. Vismund was found dead from tuberculosis one night after coughing and wheezing in agony for what seemend like ages.";
break;
case 10:
EndNum = 3;
EndTitle = "National Traitor";
EndStory = "After personally making a sacred oath to Her Majesty The Queen, the local Shoemaker proceeded to go back on his word and malliciosly sabotaged the Royal Wedding. Her Majesty and the entire Royal Family are still in shock from this vial demonstration of terrorism. His accomplice Vismund was also procecuted and despite pleading guilty, both men were publicly flayed and executed. Their corpses are to stay in front of Winchester Cathedras for the next fornight as a symbol of peace";
break;
case 12:
EndNum = 4;
EndTitle = "Artician Shoemaker";
EndStory = "After countless nights of hard work almost no sleep, the Shoemaker managed to pay his council tax and even had enough money left over to start his own trademark 'The Shoemaker's Eves'. Several charges have been placed on the company for using child labor, however all were dismissed due to the lack of substantial evidence. Local salesman Vismund was the main issuer of these charges, until he went missing for a few weeks. His body was recently discovered burried near an old worksop like house on the outskirts of Winchester";
break;
case 13:
EndNum = 5;
EndTitle = "A Kind Old Bloke";
EndStory = "The Shoemaker failed to get enough money for the council tax and ended up losing the workshop. He was however promoted by vismund to become a trainer in the local tailoring accademy. He spent the rest of his days teaching young tailors the tricks of the trait. Vismund's children were one of his first and best desciples. They managed to start a business of their own and were finally able to afford a cure for their father's tuberculosis";
break;
}
}
}
|
feccc331685095d10c3861adb50323bbff6b7d78 | C# | jedimastermaniac/ValheimMapMerge | /ValheimMapMerge/MainWindow.xaml.cs | 2.640625 | 3 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace ValheimMapMerge
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow : Window
{
private long _worldId;
private List<PlayerProfile> _profiles = new List<PlayerProfile>();
public MainWindow()
{
InitializeComponent();
}
private void ImagePanel_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
InitProfiles((string[])e.Data.GetData(DataFormats.FileDrop));
}
}
private void InitProfiles(string [] files)
{
LoadProfilesFromDisk(files);
if(LocateSharedWorld())
{
LogLine($"Shared world found with id {_worldId.ToString("X")}");
btnMerge.Visibility = Visibility.Visible;
btnReset.Visibility = Visibility.Visible;
}
else
{
LogLine($"No shared world found for these profiles");
btnReset.Visibility = Visibility.Visible;
}
}
private void LoadProfilesFromDisk(string[] files)
{
foreach (string file in files)
{
lbLog.Items.Add(new Label { Content = file, Padding = new Thickness(0) });
PlayerProfile mpp = new PlayerProfile(file);
if (!mpp.LoadPlayerFromDisk(out string error))
{
lbLog.Items.Add(new Label { Content = error, Padding = new Thickness(0) });
return;
}
foreach (var w in mpp.m_worldData)
{
LogLine($"world: {w.Key.ToString("X")}");
}
_profiles.Add(mpp);
}
}
private bool LocateSharedWorld()
{
Dictionary<long, int> _worlds = new Dictionary<long, int>();
foreach(var pp in _profiles)
{
foreach (var w in pp.m_worldData)
{
if (_worlds.ContainsKey(w.Key))
_worlds[w.Key]++;
else
_worlds.Add(w.Key, 1);
}
}
_worldId = _worlds.SingleOrDefault(x => x.Value == _profiles.Count()).Key;
return _worldId > 0;
}
public async Task Merge()
{
foreach (var p in _profiles)
{
if (p.MergeToDisk(_worldId, _profiles))
{
Dispatcher.Invoke(new Action(() =>
{
LogLine($"Profile {p.m_filename} was merged");
btnMerge.Content = "Merge";
btnMerge.Visibility = Visibility.Collapsed;
btnClose.Visibility = Visibility.Visible;
btnReset.Visibility = Visibility.Collapsed;
}));
}
else
{
Dispatcher.Invoke(new Action(() =>
{
LogLine($"Failed to merge Profile {p.m_filename}");
btnMerge.Content = "Merge";
btnMerge.Visibility = Visibility.Visible;
}));
}
}
}
private void LogLine(string line)
{
lbLog.Items.Add(new Label { Content = line, Padding = new Thickness(0) });
lbLog.Items.MoveCurrentToLast();
lbLog.ScrollIntoView(lbLog.Items.CurrentItem);
}
private void btnMerge_Click(object sender, RoutedEventArgs e)
{
btnMerge.Content = "Please wait...";
var t = Task.Run(async () =>
{
await Merge();
});
}
private void btnReset_Click(object sender, RoutedEventArgs e)
{
btnReset.Visibility = Visibility.Collapsed;
btnMerge.Visibility = Visibility.Collapsed;
_worldId = 0;
_profiles = new List<PlayerProfile>();
lbLog.Items.Clear();
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
|
6f7eebf61ed23a113297c962f7533628e349f7a0 | C# | PointmanDev/WePay.NET | /WePay.NET/Account/Structure/Balances.cs | 2.671875 | 3 | using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using WePay.Shared;
namespace WePay.Account.Structure
{
/// <summary>
/// The balances structure contains information on the account balances and automated withdrawals.
/// Accounts can have multiple balances (one for each currency they support).
/// </summary>
public class Balances
{
[JsonIgnore]
private const string Identifier = "WePay.Account.Structure.Balances";
/// <summary>
/// The ISO 4217 currency code.
/// (Enumeration of these values can be found in WePay.Shared.Common.Currencies)
/// </summary>
[ValidateWePayValue(ErrorMessage = Identifier, WePayValuesClassName = "WePay.Shared.Common.Currencies")]
public string Currency { get; set; }
/// <summary>
/// The available balance for this account (specific to the currency specified).
/// </summary>
public double? Balance { get; set; }
/// <summary>
/// The amount of money that being sent to the account that is still pending.
/// </summary>
public double? IncomingPendingAmount { get; set; }
/// <summary>
/// The amount of money being settled to the merchant (either via check or ACH) that is still pending.
/// </summary>
public double? OutgoingPendingAmount { get; set; }
/// <summary>
/// The amount of money held in reserves.
/// </summary>
public double? ReservedAmount { get; set; }
/// <summary>
/// The amount of money disputed either via chargeback or through WePay.
/// </summary>
public double? DisputedAmount { get; set; }
/// <summary>
/// How the money will be settled to the merchant.
/// (Enumeration of these values can be found in WePay.Shared.Common.SettlementPaymentMethods)
/// </summary>
[ValidateWePayValue(ErrorMessage = Identifier, WePayValuesClassName = "WePay.Shared.Common.SettlementPaymentMethods")]
public string WthdrawlType { get; set; }
/// <summary>
/// (Enumeration of these values can be found in WePay.Shared.Common.Frequencies )
/// </summary>
[ValidateWePayValue(ErrorMessage = Identifier, WePayValuesClassName = "WePay.Shared.Common.Frequencies")]
public string WithdrawalPeriod { get; set; }
/// <summary>
/// The Unix timestamp (UTC) for the next scheduled settlement.
/// </summary>
public long? WithdrawalNextTime { get; set; }
/// <summary>
/// The masked name of the entity funds will be settled to.
/// If a check is being sent, this will be the name of the entity the check was mailed to (the "pay to the order of" field).
/// </summary>
[StringLength(6, ErrorMessage = Identifier + " - WithdrawalBankName cannot exceed 6 characters")]
public string WithdrawalBankName { get; set; }
}
} |
33b0d4b2224ee500a2d53a37a31f71550b6cba6a | C# | OstapTsizh/ChatBot | /Services/NotificationService/NotificationService.cs | 2.8125 | 3 | using Services.NotificationService.Interfaces;
using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Services.NotificationService
{
public class NotificationService : ServiceBase
{
private readonly List<Task> _workerTasks = new List<Task>();
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
public NotificationService()
{
//Set initializer DbContext here if needed:
//Database.SetInitializer<DbContext>(null);
}
protected override void OnStart(string[] args)
{
StartService();
}
protected override void OnStop()
{
StopService();
}
public void StartService()
{
AddAssemblyWorkers();
foreach (var workerTask in _workerTasks)
{
workerTask.Start();
}
Console.WriteLine("Notification Service succesfuly started.");
}
public void StopService()
{
_cancellationTokenSource.Cancel();
Task.WaitAll(_workerTasks.ToArray());
}
private void AddAssemblyWorkers()
{
foreach (var type in GetType().Assembly.GetTypes())
{
InitServerWorker(type);
}
}
private void InitServerWorker(Type type)
{
if ((type == typeof(IServerWorker)) || !typeof(IServerWorker).IsAssignableFrom(type))
{
return;
}
var serverWorker = Activator.CreateInstance(type) as IServerWorker;
if (serverWorker == null)
{
return;
}
serverWorker.Initialize();
var workerTask = new Task(() => serverWorker.DoWork(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
_workerTasks.Add(workerTask);
}
}
}
|
cc183368b7da016464e609f7913ba8dad368c244 | C# | jporter7/YCP-RT-ControlRoom | /ControlRoomApplication/ControlRoomApplication/Entities/SpectraCyber/SpectraCyberConfig.cs | 2.84375 | 3 | using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ControlRoomApplication.Entities
{
[Table("spectracyber_config")]
[Serializable]
public class SpectraCyberConfig
{
public SpectraCyberConfig(SpectraCyberModeTypeEnum mode, SpectraCyberIntegrationTimeEnum integration_time,
double offset_voltage, double if_gain, SpectraCyberDCGainEnum dc_gain, SpectraCyberBandwidthEnum bandwidth)
{
Mode = mode;
IntegrationTime = integration_time;
OffsetVoltage = offset_voltage;
IFGain = if_gain;
DCGain = dc_gain;
Bandwidth = bandwidth;
}
public SpectraCyberConfig(SpectraCyberModeTypeEnum mode)
{
Mode = mode;
IntegrationTime = SpectraCyberIntegrationTimeEnum.MID_TIME_SPAN;
OffsetVoltage = 0;
IFGain = 10;
DCGain = SpectraCyberDCGainEnum.X1;
Bandwidth = SpectraCyberBandwidthEnum.SMALL_BANDWIDTH;
}
public SpectraCyberConfig() : this(SpectraCyberModeTypeEnum.UNKNOWN) { }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Column("mode")]
public SpectraCyberModeTypeEnum Mode { get; set; }
[Required]
[Column("integration_time")]
public SpectraCyberIntegrationTimeEnum IntegrationTime { get; set; }
[Required]
[Column("offset_voltage")]
public double OffsetVoltage { get; set; }
[Required]
[Column("if_gain")]
public double IFGain { get; set; }
[Required]
[Column("dc_gain")]
public SpectraCyberDCGainEnum DCGain { get; set; }
[Required]
[Column("bandwidth")]
public SpectraCyberBandwidthEnum Bandwidth { get; set; }
/// <summary>
/// Checks if the current SpectraCyberConfig is Equal to another SpectraCyberConfig
/// and it checks if the other SpectraCyberConfig is null
/// </summary>
public override bool Equals(object obj)
{
SpectraCyberConfig other = obj as SpectraCyberConfig; //avoid double casting
if (ReferenceEquals(other, null))
{
return false;
}
return Mode == other.Mode &&
IntegrationTime == other.IntegrationTime &&
OffsetVoltage == other.OffsetVoltage &&
IFGain == other.IFGain &&
DCGain == other.DCGain &&
Bandwidth == other.Bandwidth;
}
/// <summary>
/// Returns the HashCode of the Orientation's Id
/// </summary>
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
}
|
fb21f73e2f584bad6707c17fbb4191a796c11155 | C# | VoThiThao/my-first-project | /QuanLyTaiKhoan/QuanLyTaiKhoan/UserDao.cs | 2.71875 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace QuanLyTaiKhoan
{
public class UserDao
{
string connectionString = ConfigurationManager.ConnectionStrings["CN_Net"].ConnectionString;
public DataTable GetAllUser()
{
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM UserInfo", connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(table);
return table;
}
public bool checkUser(string tenDangNhap)
{
string sql = @"SELECT COUNT(*) FROM UserInfo WHERE UserName = @tdn";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@tdn", tenDangNhap);
connection.Open();
int count = (int)command.ExecuteScalar();
return (count >= 1);
}
}
public bool Insert(User user)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = @"INSERT INTO UserInfo(UserName,PassWord, FisrtName, LastName, Email, Gender, Address, Avatar) VALUES(@username,@password,@firstname,@lastname,@email,@gender,@address,@avatar)";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@username", user.Username);
cmd.Parameters.AddWithValue("@password", user.Password);
cmd.Parameters.AddWithValue("@firstname", user.Firstname);
cmd.Parameters.AddWithValue("@lastname", user.Lastname);
cmd.Parameters.AddWithValue("@email", user.Email);
cmd.Parameters.AddWithValue("@gender", user.Gender);
cmd.Parameters.AddWithValue("@address", user.Address);
cmd.Parameters.AddWithValue("@avatar", user.AvatarFileName);
connection.Open();
int result = cmd.ExecuteNonQuery();
return (result >= 1);
}
}
public User GetUserByUserName(string username)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = @"SELECT * FROM UserInfo WHERE UserName = @tdn ";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@tdn", username);
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
User user = new User
{
Firstname = (string)reader["FisrtName"],
Lastname = (string)reader["LastName"],
Email = (string)reader["Email"],
Password = (string)reader["PassWord"],
Address = (string)reader["Address"],
Gender = (Boolean)reader["Gender"],
Username = (string)reader["UserName"]
};
return user;
}
return null;
}
}
public bool UpdateUser(User user)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = @"UPDATE UserInfo SET FisrtName = @firstname, LastName = @lastname, Email = @email, Gender = @gender, Address = @address, PassWord = @password , Avatar=@avatar WHERE UserName = @username";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@username", user.Username);
cmd.Parameters.AddWithValue("@password", user.Password);
cmd.Parameters.AddWithValue("@firstname", user.Firstname);
cmd.Parameters.AddWithValue("@lastname", user.Lastname);
cmd.Parameters.AddWithValue("@email", user.Email);
cmd.Parameters.AddWithValue("@gender", user.Gender);
cmd.Parameters.AddWithValue("@address", user.Address);
cmd.Parameters.AddWithValue("@avatar", user.AvatarFileName);
connection.Open();
int result = cmd.ExecuteNonQuery();
if (result >= 1)
{
return true;
}
}
return false;
}
public bool DeleteUser(string username)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = @"DELETE FROM UserInfo WHERE UserName = @username";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@username", username);
connection.Open();
int result = cmd.ExecuteNonQuery();
if (result >= 1)
{
return true;
}
}
return false;
}
/* public bool TimKiemUser(string timUser)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = @"SELECT * FROM UserInfo WHERE UserName = @username ";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@username", timUser);
connection.Open();
int result = cmd.ExecuteNonQuery();
if (result >= 1)
{
return true;
}
}
return false;
}
public bool checkUserTim(string timUser)
{
string sql = @"SELECT COUNT(*) FROM UserInfo WHERE UserName = @t";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@t", timUser);
connection.Open();
int count = (int)command.ExecuteScalar();
return (count >= 1);
}
}*/
}
}
|
86476270a169800857edc22013a9f4696281a9c5 | C# | always-on/always | /plugins/rummy-plugin/Rummy.Game/LayOffMove.cs | 3.1875 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Rummy
{
public class LayOffMove : Move
{
private readonly Card _card;
public Card Card
{
get { return _card; }
}
private readonly Meld _meld;
public Meld Meld
{
get { return _meld; }
}
public Card GetCard()
{
return _card;
}
public LayOffMove(Player player, Card card, Meld meld)
: base(player)
{
_card = card;
_meld = meld;
}
public override bool Equals(Object obj)
{
if (obj == null || obj.GetType() != typeof(LayOffMove))
return false;
var theOther = (LayOffMove)obj;
if (theOther.Player != this.Player)
return false;
if (!theOther._card.Equals(this._card))
return false;
if (!theOther._meld.Equals(this._meld))
return false;
return true;
}
public override int GetHashCode()
{
return (int)Player + _card.GetHashCode() * 2 + _meld.GetHashCode() * 2;
}
public override void Realize(GameState gameState)
{
gameState.LayOff(Player, _card, _meld);
}
public override string ToString()
{
return string.Format("Player {0} -- LayOff {1} to meld", Player, _card);
}
}
}
|
98724e617cf7b7986ba1559e80efb6c7ca7c5be9 | C# | PontusIvarsson/Softinsight | /src/Services/Blogging/Blogging.Tests/Domain/Hashtag.cs | 2.75 | 3 | using Blogging.Domain.BlogAggregate;
using System;
using Xunit;
namespace Blogging.Tests.Domain
{
[Trait(TestHelper.TestType, TestHelper.UnitTest)]
public class HashtagShould
{
[Fact]
public void BeCreated()
{
Hashtag sut = new Hashtag("test");
Assert.Equal("test", sut.Value);
}
[Theory]
[InlineData("#a")]
[InlineData("#aa")]
[InlineData("#aaa")]
public void Accept(string value)
{
Hashtag sut = new Hashtag(value);
Assert.Equal(value, sut.Value);
}
[Theory]
[InlineData("a_ 1")]
[InlineData("a a")]
[InlineData("#a _aa")]
public void NotAccept(string value)
{
//arrange
//act
Action act = () => new Hashtag(value);
//assert
Assert.Throws<ApplicationException>(act);
}
}
}
|
99707f4185af6ec16e7c1e5ba878dbe3b185f5a2 | C# | cofie27/AB-Geometrie1 | /Kreis.cs | 3.34375 | 3 | using System;
using System.Collections.Generic;
using System.Text;
namespace AB_Geometrie1
{
class Kreis
{
private int Radius;
private double Durchmesser;
private double Umfang;
private double Flaeche;
public Kreis()
{
Radius = 1;
Durchmesser = 2;
Umfang = 0;
Flaeche = 0;
}
public void EingabeRadius()
{
Console.WriteLine("Bitte Radius eingeben: ");
Radius = Convert.ToInt32(Console.ReadLine());
}
public void DruckeRadius()
{
Console.WriteLine(Radius);
}
public void DruckeUmfang()
{
Umfang = 2 * Math.PI * Radius;
Console.WriteLine("Umfang: " + Umfang);
}
public void DruckeFlaeche()
{
Flaeche = Math.PI * Radius * Radius;
Console.WriteLine("Flaeche: " + Flaeche);
}
public void DruckeDurchmesser()
{
Durchmesser = 2 * Radius;
Console.WriteLine("Durchmesser: " + Durchmesser);
}
}
} |
3a0f965dbfaacfcbd7c73cbaf40c74815b6eb3e1 | C# | shendongnian/download4 | /code3/403462-8987579-20344698-2.cs | 2.75 | 3 | using System;
using System.IO;
using System.Threading;
using System.Windows;
namespace Node
{
class Program
{
public static void Main()
{
var app = new Application();
app.Startup += ServerStart;
app.Run();
}
private static void ServerStart(object sender, StartupEventArgs e)
{
var dispatcher = ((Application) sender).Dispatcher;
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
var path = Environment.ExpandEnvironmentVariables(
@"%SystemRoot%\Notepad.exe");
var fs = new FileStream(path, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite, 1024 * 4, true);
var bytes = new byte[1024];
fs.BeginRead(bytes, 0, bytes.Length, ar =>
{
dispatcher.BeginInvoke(new Action(() =>
{
var res = fs.EndRead(ar);
// Are we in the same thread?
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
}));
}, null);
}
}
}
|
6ab78590bef095d2ab54e0d3d4d8f632884e9bce | C# | s00132263/Worksheet1 | /Worksheet1/pages/WS1b.cshtml.cs | 3.046875 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Worksheet1.pages
{
public class WS1bModel : PageModel
{
public string Message { get; set; }
[BindProperty]
public int Number1 { get; set; }
[BindProperty]
public int Number2 { get; set; }
public void OnGet()
{
}
public void OnPost(string firstname, int Number1, int Number2, string operation)
{
Message = $"{Number1} + {Number2} = {Number1 + Number2}";
switch (operation)
{
case "plus":
Message = $"{Number1} plus {Number2} equals {Number1 + Number2}";
break;
case "minus":
Message = $"{Number1} minus {Number2} equals {Number1 - Number2}";
break;
case "multiply":
Message = $"{Number1} multipled by {Number2} equals {Number1 * Number2}";
break;
case "divide":
float Num2 = (float)Number2; // necessary because result might not be an integer
Message = $"{Number1} divided by {Number2} equals {Number1 / Num2}";
break;
}
}
}
} |
2dd962ac25c1ccb6b62625cc4a2b19ee49a0d562 | C# | rozek1szymon/LeetCode | /C#LeetCode/Reverse String/Reverse String/Program.cs | 3.34375 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Reverse_String
{
public class Solution
{
public void ReverseString(char[] s)
{
s = s.Reverse().ToArray<char>();
}
}
class Program
{
static void Main(string[] args)
{
char[] array = { 'h', 'e', 'l', 'l', 'o' };
Solution solution = new Solution();
solution.ReverseString(array);
Console.ReadKey();
}
}
}
|
3fb9bcc53263068ce9a14ecb784b591cbf47e425 | C# | steve600/VersatileMediaManager | /Source/Infrastructure/VersatileMediaManager.Communication/Enigma2/Enigma2WebInterfaceDataAdapter.cs | 2.609375 | 3 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using VersatileMediaManager.Communication.Interfaces;
namespace VersatileMediaManager.Communication.Enigma2
{
public enum Enigma2WebInterfacesMethods
{
GetDeviceInfo,
GetLocationList,
GetCurrentLocation,
GetServiceList,
GetTimerList,
AddTimer,
DeleteTimer
}
public class Enigma2WebInterfaceDataAdapter<T> : IDataAdapter<T, Enigma2WebInterfacesMethods, IDictionary<string, string>, object, object>, IDisposable
{
#region CTOR
#region CTOR
/// <summary>
/// CTOR
/// </summary>
private Enigma2WebInterfaceDataAdapter()
{
}
/// <summary>
/// CTOR
/// </summary>
/// <param name="connection">The connection</param>
public Enigma2WebInterfaceDataAdapter(IConnection connection)
{
this.Connection = connection;
}
#endregion CTOR
#endregion CTOR
public T Execute(Enigma2WebInterfacesMethods method)
{
T result = default(T);
try
{
var uri = this.GetPostUri(method);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.Method = "POST";
//request.Timeout = this.Connection.ConnectionSettings.Timeout;
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8))
{
//string resultString = responseReader.ReadToEnd();
// Deserialize XML
XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
result = (T)xSerializer.Deserialize(responseReader);
}
}
}
}
catch (Exception ex)
{
//string exceptionMessage = String.Format(@"Error while calling \\n\\n JSON RPC method {0} \\n\\n with parameters \\n\\n {1}", jsonRequest.Method, jsonRequest.Params);
//throw new JsonRpcCommunicationException(exceptionMessage, ex);
}
return result;
}
public T Execute(Enigma2WebInterfacesMethods method, IDictionary<string, string> parameters)
{
T result = default(T);
string p = "?";
try
{
// Check parameters
if (parameters != null && parameters.Count > 0)
{
foreach (var d in parameters)
{
p += d.Key + "=" + d.Value;
}
}
string uri = this.GetPostUri(method) + p;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.Method = "POST";
//request.Timeout = this.Connection.ConnectionSettings.Timeout;
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8))
{
//string resultString = responseReader.ReadToEnd();
// Deserialize XML
XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
result = (T)xSerializer.Deserialize(responseReader);
}
}
}
}
catch (Exception ex)
{
}
return result;
}
public T Execute(IDictionary<string, string> t3, object t4)
{
throw new NotImplementedException();
}
public T Execute(object t4, object t5)
{
throw new NotImplementedException();
}
#region Properties
private IConnection connection = null;
/// <summary>
/// The connection
/// </summary>
public IConnection Connection
{
get
{
return this.connection;
}
private set
{
this.connection = value;
}
}
private string GetPostUri(Enigma2WebInterfacesMethods method)
{
string result = string.Empty;
switch(method)
{
case Enigma2WebInterfacesMethods.GetDeviceInfo:
result = this.Connection.ConnectionSettings.URIString + "/web/deviceinfo";
break;
case Enigma2WebInterfacesMethods.GetServiceList:
result = this.Connection.ConnectionSettings.URIString + "/web/getservices";
break;
case Enigma2WebInterfacesMethods.GetLocationList:
result = this.Connection.ConnectionSettings.URIString + "/web/getlocations";
break;
case Enigma2WebInterfacesMethods.GetCurrentLocation:
result = this.Connection.ConnectionSettings.URIString + "/web/getcurrlocation";
break;
case Enigma2WebInterfacesMethods.GetTimerList:
result = this.Connection.ConnectionSettings.URIString + "/web/timerlist";
break;
default:
result = string.Empty;
break;
}
return result;
}
#region IDisposable Support
private bool disposedValue = false; // Dient zur Erkennung redundanter Aufrufe.
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: verwalteten Zustand (verwaltete Objekte) entsorgen.
}
// TODO: nicht verwaltete Ressourcen (nicht verwaltete Objekte) freigeben und Finalizer weiter unten überschreiben.
// TODO: große Felder auf Null setzen.
disposedValue = true;
}
}
// TODO: Finalizer nur überschreiben, wenn Dispose(bool disposing) weiter oben Code für die Freigabe nicht verwalteter Ressourcen enthält.
// ~Enigma2WebInterfaceDataAdapter() {
// // Ändern Sie diesen Code nicht. Fügen Sie Bereinigungscode in Dispose(bool disposing) weiter oben ein.
// Dispose(false);
// }
// Dieser Code wird hinzugefügt, um das Dispose-Muster richtig zu implementieren.
public void Dispose()
{
// Ändern Sie diesen Code nicht. Fügen Sie Bereinigungscode in Dispose(bool disposing) weiter oben ein.
Dispose(true);
// TODO: Auskommentierung der folgenden Zeile aufheben, wenn der Finalizer weiter oben überschrieben wird.
// GC.SuppressFinalize(this);
}
#endregion
#endregion Properties
}
}
|
cc8c17455b262774791536f8d9fc7cd76c96cbfd | C# | nahidhasanswe/AngularjsTokenAuthentication | /AngularjsTokenAuthentication/App-Code/CreateFromNumbers.cs | 2.796875 | 3 | using AngularjsTokenAuthentication.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace AngularjsTokenAuthentication.App_Code
{
public static class CreateFromNumbers
{
public static string FromNumber(NumberSection model)
{
string regexp = "";
if (model.category == "All")
{
regexp = "0-9";
}else if (model.category == "Custom")
{
regexp = FromCustomNumber(model.customNumber);
}
return regexp;
}
private static string FromCustomNumber(string customNumber)
{
string SeparateNumber = "";
string[] textArray = Regex.Split(customNumber, ",");
foreach (string str in textArray)
{
SeparateNumber = SeparateNumber + str;
}
return SeparateNumber;
}
public static string FromAtLeastOne(NumberSection model)
{
string atleat = "";
if (model.atLeastOne)
{
atleat = atleat + "(?=.*[0-9])";
}
return atleat;
}
public static string FromAtLeastOne(NumberSection model, bool isOk)
{
string atleast = "";
if (model.atLeastOne)
{
atleast = atleast + "0-9";
}
return atleast;
}
}
} |
93cb233799df8edadffeb0777aa92b77f412a223 | C# | shendongnian/download4 | /code11/1950339-59196362-210614361-2.cs | 2.765625 | 3 | c#
services
.AddEntityFrameworkSqlServer()
.AddScoped<IMigrationsSqlGenerator, SchemaMigrationsSqlGenerator>()
.AddScoped<MigrationsSqlGenerator, SqlServerMigrationsSqlGenerator>()
.AddDbContext<AppDbContext>((serviceProvider, sqlOpt) =>
{
sqlOpt.UseInternalServiceProvider(serviceProvider)
.UseSqlServer(
connectionString,
// Make sure thge migration table is also in that schema
opt => opt.MigrationsHistoryTable("__EFMigrationsHistory", yourSchema));
});
And create a new class:
c#
/// <summary>
/// A class injected into the SQL command generation
/// in order to replace the schema with the one we want.
/// </summary>
public sealed class SchemaMigrationsSqlGenerator : IMigrationsSqlGenerator
{
#region Fields
private readonly MigrationsSqlGenerator mOriginal;
private readonly ISchemaStorage mSchema;
#endregion
#region Init aned clean-up
/// <summary>
/// Constructor for dependency injection.
/// </summary>
/// <param name="original">Previously used SQL generator</param>
/// <param name="schema">Where the schema name is stored</param>
public SchemaMigrationsSqlGenerator(MigrationsSqlGenerator original, ISchemaStorage schema)
{
mOriginal = original;
mSchema = schema;
}
#endregion
#region IMigrationsSqlGenerator API
/// <inheritdoc />
/// <remarks>
/// Overwrite the schema generated during Add-Migration,
/// then call the original SQL generator.
/// </remarks>
IReadOnlyList<MigrationCommand> IMigrationsSqlGenerator.Generate(
IReadOnlyList<MigrationOperation> operations, IModel model)
{
foreach (var operation in operations)
{
switch (operation)
{
case SqlServerCreateDatabaseOperation _:
break;
case EnsureSchemaOperation ensureOperation:
ensureOperation.Name = mSchema.Schema;
break;
case CreateTableOperation tblOperation:
tblOperation.Schema = mSchema.Schema;
break;
case CreateIndexOperation idxOperation:
idxOperation.Schema = mSchema.Schema;
break;
default:
throw new NotImplementedException(
$"Migration operation of type {operation.GetType().Name} is not supported by SchemaMigrationsSqlGenerator.");
}
}
return mOriginal.Generate(operations, model);
}
#endregion
}
The code above forces the migrations to be executed in the schema injected with a trivial `ISchemaStorage` interface.
|
8071ab31c2785c10f532f6b224aef3bd19bf5fb3 | C# | TheBerkin/Devcom | /Devcom/PropertyConvar.cs | 3.03125 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DeveloperCommands
{
/// <summary>
/// Represents a convar bound to a static property.
/// </summary>
public sealed class PropertyConvar : Convar
{
private readonly PropertyInfo _property;
internal PropertyConvar(PropertyInfo property, string name, string desc, string cat, object defaultValue, bool savable) : base(name, desc, cat, defaultValue, savable)
{
if (property != null)
{
if (!property.GetGetMethod().IsStatic)
{
throw new ArgumentException("Convar creation failed: The property '" + property.Name + "' is not static.");
}
_property = property;
if (defaultValue != null)
{
_property.SetValue(null, defaultValue);
}
}
else
{
throw new ArgumentNullException("property");
}
}
public override dynamic Value
{
get { return _property.GetValue(null); }
set
{
try
{
_property.SetValue(null, Util.ChangeType(value, _property.PropertyType));
}
catch
{
_property.SetValue(null, null);
}
}
}
}
}
|
618150e8d0f6b72e75d13c9b3b5d82801fa4a5a1 | C# | lontivero/Torpedo | /test/Ed25519Tests.cs | 2.5625 | 3 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Torpedo;
using Xunit;
namespace test;
public static class LinqExtensions
{
public static IEnumerable<IEnumerable<T>> SplitBy<T>(this IEnumerable<T> source, Func<T, bool> when)
{
int grouper = 0;
return source
.GroupBy(x => grouper += when(x) ? 1 : 0)
.Select(x => x.AsEnumerable().Where(x => !when(x)))
.Where(x => x.Any());
}
}
public class Ed25519Tests
{
[Fact]
public void Test1()
{
var vectors = File
.ReadAllLines("data/ed25519-vectors.txt")
.Where(line => !line.StartsWith("#"))
.SplitBy(line => string.IsNullOrWhiteSpace(line))
.Select(tst => tst
.Select(line => line.Split(':'))
.Select(parts => (parts[0].Trim(), parts[1].Trim()))
.ToDictionary(x => x.Item1, x => x.Item2)
)
.Select(x => new
{
Name = x["TST"],
SecretKey = StringConverter.ToByteArray(x["SK"]),
PublicKey = Ed25519Point.DecodePoint(StringConverter.ToByteArray(x["PK"])),
Message = StringConverter.ToByteArray(x["MSG"]),
Signature = StringConverter.ToByteArray(x["SIG"])
});
foreach (var vector in vectors)
{
var signature = Ed25519.Signature(vector.Message, vector.SecretKey, vector.PublicKey);
Assert.Equal(vector.Signature, signature);
}
}
private byte[] Version = new byte[]{ 3 };
[Fact]
public void xxx()
{
var pkBytes = StringConverter.ToByteArray("b82b69e96f886f7bc417894b6ece47d606f178b5f872411024e51fb27cb4a961");
var pub = Ed25519.PublicKey(pkBytes).EncodePoint();
var checkdigits = GetCheckdigits(pub);
var all = pub.Concat(checkdigits).Concat(Version).ToArray();
var serviceId = Base32.ToBase32String(all).ToLower();
var url = serviceId;
var y = Base32.FromBase32String("6qoibdde2qea7aruts3rft64pqg2bm6oa5jvgsobm6cn2cggdjphk7qd".ToUpper());
}
private byte[] GetCheckdigits(byte[] pubKey)
{
var salt = ".onion checksum";
var x = Encoding.UTF8.GetBytes(salt).Concat(pubKey).Concat(Version).ToArray();
return x.Sha256().TakeLast(2).ToArray();
}
/*
func getCheckdigits(pub ed25519.PublicKey) []byte {
// Calculate checksum sha3(".onion checksum" || publicKey || version)
checkstr := []byte(salt)
checkstr = append(checkstr, pub...)
checkstr = append(checkstr, version)
checksum := sha3.Sum256(checkstr)
return checksum[:2]
}
*/
} |
1e8da6bd0bb6a09103f431bcc61b179a48076229 | C# | MIT-Reality-Hack-2020/A11YTK-Demo | /Assets/Scripts/SimpleGazeScript.cs | 2.515625 | 3 | using System.Collections;
using System.Collections.Generic;
using A11YTK;
using UnityEngine;
public class SimpleGazeScript : MonoBehaviour {
public Camera viewCamera;
public GameObject cursorPrefab;
public float maxCursorDistance = 30;
public LayerMask cursorLayerMask;
private GameObject cursorInstance;
// Start is called before the first frame update
void Start () {
cursorInstance = Instantiate (cursorPrefab);
}
// Update is called once per frame
void Update () {
UpdateCursor ();
}
private void UpdateCursor () {
// Create a gaze ray pointing forward from the camera
Ray ray = new Ray (viewCamera.transform.position, viewCamera.transform.rotation * Vector3.forward);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, Mathf.Infinity, cursorLayerMask)) {
Debug.Log ("I WORK");
if (Input.GetKeyDown (KeyCode.Space)) {
var component = hit.collider.gameObject.GetComponent<SubtitleController> ();
if (component != null) {
component.PlayOneShot ();
Debug.Log ("I REALLY WORK");
}
}
// If the ray hits something, set the position to the hit point
// and rotate based on the normal vector of the hit
cursorInstance.transform.position = hit.point;
cursorInstance.transform.rotation = Quaternion.FromToRotation (Vector3.up, hit.normal);
} else {
// If the ray doesn't hit anything, set the position to the maxCursorDistance
// and rotate to point away from the camera
cursorInstance.transform.position = ray.origin + ray.direction.normalized * maxCursorDistance;
cursorInstance.transform.rotation = Quaternion.FromToRotation (Vector3.up, -ray.direction);
}
}
} |
cfb8a39260fa3c101ad4703cb7df71f60a3d6ab9 | C# | serolmar/matutils | /Utilities/Parsers/IParse.cs | 2.984375 | 3 | namespace Utilities
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// Enumeração dos níveis de erro possíveis numa leitura.
/// </summary>
public enum EParseErrorLevel
{
/// <summary>
/// Erro de leitura.
/// </summary>
ERROR = 0
}
/// <summary>
/// Define um leitor de símbolos num objecto.
/// </summary>
/// <typeparam name="T">O tipo de objecto a ser lido.</typeparam>
/// <typeparam name="SymbValue">O tipo de objecto que constitui o valor dos símbolos lidos.</typeparam>
/// <typeparam name="SymbType">O tipo de objecto que constitui o tipo dos símbolos lidos.</typeparam>
public interface IParse<out T, SymbValue, SymbType>
{
/// <summary>
/// Realiza a leitura.
/// </summary>
/// <remarks>
/// Se a leitura não for bem-sucedida, os erros de leitura serão registados no diário
/// e será retornado o objecto por defeito.
/// </remarks>
/// <param name="symbolListToParse">O vector de símbolos a ser lido.</param>
/// <param name="errorLogs">O objecto que irá manter o registo do diário da leitura.</param>
/// <returns>O valor lido.</returns>
T Parse(
ISymbol<SymbValue, SymbType>[] symbolListToParse,
ILogStatus<string, EParseErrorLevel> errorLogs);
}
}
|
374c3934cb7e4481765c3430c3b9f6ebd1fea5d6 | C# | VowpalWabbit/reinforcement_learning | /bindings/cs/rl.net.cli/Stats.cs | 2.953125 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Rl.Net.Cli
{
public class OnlineWelford
{
int count;
double mean, m2;
double sum;
double min = double.MaxValue;
double max = double.MinValue;
public void Update(double value)
{
sum += value;
min = Math.Min(min, value);
max = Math.Max(max, value);
++count;
var d = value - mean;
mean += d / count;
var d2 = value - mean;
m2 += d * d2;
}
public double EstimatedMean => mean;
public double EstimatedVariance => m2 / count;
public double SampleVariance => m2 / (count - 1);
public double Min => min;
public double Max => max;
public int N => count;
public double Sum => sum;
}
public interface IHistogram
{
void Update(double value);
int Bins { get; }
double Min { get; }
double Max { get; }
double ObservedMin { get; }
double ObservedMax { get; }
int[] Counts { get; }
}
public class Histogram : IHistogram
{
int[] counts;
int count;
double actualMin, actualMax;
readonly double min, max;
public Histogram(double min, double max, int bins)
{
if (max <= min + 1)
max = min + 1;
this.min = min;
this.max = max;
this.actualMin = double.MaxValue;
this.actualMax = double.MinValue;
this.counts = new int[bins];
}
public Histogram(OnlineWelford est, int bins)
{
//this should capture the majority of the data
var range = 1.96 * Math.Sqrt(est.SampleVariance);
min = Math.Max(0, est.EstimatedMean - range);
max = est.EstimatedMean + range;
if (max <= min + 1)
max = min + 1;
this.actualMin = double.MaxValue;
this.actualMax = double.MinValue;
this.counts = new int[bins];
}
public Histogram(JObject json)
{
min = (double)json["Min"];
max = (double)json["Max"];
actualMin = min;
actualMax = max;
List<int> lst = new List<int>();
foreach (var elem in json["Counts"])
{
lst.Add((int)elem);
}
this.counts = lst.ToArray();
this.count = this.counts.Sum();
}
public double Sample(Random rand)
{
int draw = rand.Next(count);
int d = draw;
int idx = 0;
for (int i = 0; i < counts.Length; ++i)
{
if (draw < counts[i])
{
break;
}
draw -= counts[i];
++idx;
}
double step = (max - min) / (counts.Length - 1);
double val = min + step * idx;
return val;
}
public void Update(double val)
{
double ov = val;
this.actualMin = Math.Min(this.actualMin, val);
this.actualMax = Math.Max(this.actualMax, val);
//clamp val min/max
val = Math.Max(val, min);
val = Math.Min(val, max);
double step = (max - min) / (counts.Length - 1);
int idx = Math.Max(0, Math.Min(counts.Length - 1, (int)Math.Floor((val - min) / step)));
++counts[idx];
++count;
}
//Ugg but ok
public int Bins => this.counts.Length;
public int[] Counts => counts;
public double ObservedMin => actualMin;
public double ObservedMax => actualMax;
public double Min => min;
public double Max => max;
}
class HistogramWithSampledBounds : IHistogram
{
readonly int samples;
readonly int bins;
List<double> values;
Histogram histogram, tmpHistogram;
public HistogramWithSampledBounds(int samples, int bins)
{
this.samples = samples;
this.bins = bins;
this.values = new List<double>(samples);
}
Histogram CreateHistogram()
{
if (values.Count == 0)
{
return new Histogram(0, 1, 1);
}
var res = new Histogram(values.Min(), values.Max(), bins);
foreach (var v in values)
res.Update(v);
return res;
}
public void Update(double val)
{
tmpHistogram = null;
if (histogram != null)
{
histogram.Update(val);
}
else
{
values.Add(val);
if (values.Count >= samples)
{
histogram = CreateHistogram();
values = null;
}
}
}
private Histogram Hist
{
get
{
if (histogram != null)
return histogram;
if (tmpHistogram != null)
return tmpHistogram;
tmpHistogram = CreateHistogram();
return tmpHistogram;
}
}
public int Bins => Hist.Bins;
public int[] Counts => Hist.Counts;
public double ObservedMin => Hist.ObservedMin;
public double ObservedMax => Hist.ObservedMax;
public double Min => Hist.Min;
public double Max => Hist.Max;
}
public class HashedDistanceHistogram
{
int[] counts;
int[] foundHashes;
int insertHead;
int notFound;
int entries;
HashSet<int> uniqueActions = new HashSet<int>();
public HashedDistanceHistogram(int maxDistance)
{
counts = new int[maxDistance];
foundHashes = new int[maxDistance];
}
public HashedDistanceHistogram(JObject json)
{
int unique = (int)json["UniqueActions"];
this.uniqueActions = new HashSet<int>(Enumerable.Range(0, unique));
if (json.ContainsKey("Hist") && json.ContainsKey("Entries"))
{
entries = (int)json["Entries"];
int bins = json["Hist"].Count();
counts = new int[bins];
foundHashes = new int[bins];
int idx = 0;
foreach (var elem in json["Hist"])
{
this.counts[idx++] = (int)elem;
}
}
}
public int Entries => entries;
public int MissCount => notFound;
public int[] Hist => counts;
public int UniqueActions => uniqueActions.Count;
public void Update(string str)
{
int hash = str.GetHashCode();
if (hash == 0)
hash = ("_" + str).GetHashCode();
uniqueActions.Add(hash);
int distance = 0;
int foundDistance = -1;
for (int i = foundHashes.Length - 1; i >= 0; --i)
{
int idx = (i + insertHead) % foundHashes.Length;
if (foundHashes[idx] == hash)
{
foundDistance = distance;
break;
}
++distance;
}
++entries;
if (foundDistance == -1)
{
++notFound;
}
else
{
++counts[foundDistance];
}
foundHashes[insertHead] = hash;
insertHead = (insertHead + 1) % foundHashes.Length;
}
public override string ToString()
{
string hist = string.Join(' ', counts.Select(i => i.ToString()));
string hash = string.Join(' ', foundHashes.Select(i => i.ToString()));
return $"nf: {notFound} hist: {hist} hashes: {hash}";
}
public int Sample(Random rand)
{
if(entries == 0)
{
return -1;
}
int draw = rand.Next(entries);
int d = draw;
int idx = 0;
for (int i = 0; i < counts.Length; ++i)
{
if (draw < counts[i])
{
break;
}
draw -= counts[i];
++idx;
}
if (idx == counts.Length)
idx = -1;
return idx;
}
}
}
|
a73394879580f74152091daf7603f7fb217349e9 | C# | AutomateThePlanet/AutomateThePlanet-Learning-Series | /dotnet/AutomationTools-Series/Jenkins-CSharp-Api/Services/BuildService.cs | 2.53125 | 3 | // <copyright file="BuildService.cs" company="Automate The Planet Ltd.">
// Copyright 2016 Automate The Planet Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Anton Angelov</author>
// <site>http://automatetheplanet.com/</site>
using System;
using System.Diagnostics;
using System.Net;
using System.Threading;
using JenkinsCSharpApi.Interfaces;
namespace JenkinsCSharpApi.Services
{
/// <summary>
/// Contains Methods that create Jenkins Build and Wait for its execution.
/// </summary>
public class BuildService
{
private readonly IBuildAdapter buildAdapter;
/// <summary>
/// Initializes a new instance of the <see cref="BuildService" /> class.
/// </summary>
/// <param name="buildAdapter">The build service.</param>
/// <exception cref="System.ArgumentNullException">The Jenkins Server URL cannot be null or empty.
/// or
/// The Project Name cannot be null or empty.
/// or
/// The Build Name cannot be null or empty.</exception>
public BuildService(IBuildAdapter buildAdapter)
{
if (buildAdapter == null)
{
throw new ArgumentNullException("The ArgumentNullException was not throwed in case of BuildService is equal to null.");
}
this.buildAdapter = buildAdapter;
}
/// <summary>
/// Runs the specified Jenkins build and waits for its execution.
/// </summary>
/// <param name="tfsBuildNumber">The TFS build number.</param>
/// <returns>The build Result status.</returns>
public string Run(string tfsBuildNumber)
{
// If the tfsBuildNumber passed by the WF Activity is not passed, we assign Guid in order the name to be unique.
if (string.IsNullOrEmpty(tfsBuildNumber))
{
tfsBuildNumber = Guid.NewGuid().ToString();
}
// We get the nextBuildNumber from the Jenkins Build Status XML, but we don't know if this number will be really our build number when we trigger
// the build. A race condition may occur.
string nextBuildNumber = this.GetNextBuildNumber();
// We trigger the build.
this.TriggerBuild(tfsBuildNumber, nextBuildNumber);
// Wait until it starts -> Not throwing web exception 404 Not Found for the specific jenkins build URL.
this.WaitUntilBuildStarts(nextBuildNumber);
// When we are sure that the build is already triggered, we foreach all build numbers from the Project Build Status XML,
// if the custom parameter TfsBuildNumber is the parameter that we have passed the build number is returned.
string realBuildNumber = this.GetRealBuildNumber(tfsBuildNumber);
// Initialize the specific build URL with the potentially new build number.
this.buildAdapter.InitializeSpecificBuildUrl(realBuildNumber);
// Wait unitil the build finishes. We check the Specific Build XML for the property IsBuilding.
this.WaitUntilBuildFinish(realBuildNumber);
// When the build finishes, we get the build status from the Specific Build XML.
string buildResult = this.GetBuildStatus(realBuildNumber);
return buildResult;
}
/// <summary>
/// Gets the build status from the Specific Build URL. Status XML node.
/// </summary>
/// <param name="realBuildNumber">The real build number.</param>
/// <returns>The build status.</returns>
internal string GetBuildStatus(string realBuildNumber)
{
string buildStatus = this.buildAdapter.GetSpecificBuildStatusXml(realBuildNumber);
string buildResult = this.buildAdapter.GetBuildResult(buildStatus);
Debug.WriteLine("Result from the build: {0}", buildResult);
return buildResult;
}
/// <summary>
/// Waits unitil the build finishes. We check the Specific Build XML for the property IsBuilding.
/// </summary>
/// <param name="realBuildNumber">The real build number.</param>
internal void WaitUntilBuildFinish(string realBuildNumber)
{
bool shouldContinue = false;
string buildStatus = string.Empty;
do
{
buildStatus = this.buildAdapter.GetSpecificBuildStatusXml(realBuildNumber);
bool isProjectBuilding = this.buildAdapter.IsProjectBuilding(buildStatus);
if (!isProjectBuilding)
{
shouldContinue = true;
}
Debug.WriteLine("Waits 5 seconds before the new check if the build is completed...");
Thread.Sleep(5000);
}
while (!shouldContinue);
}
/// <summary>
/// When we are sure that the build is already triggered, we foreach all build numbers from the Project Build Status XML,
/// if the custom parameter TfsBuildNumber is the parameter that we have passed the build number is returned.
/// </summary>
/// <param name="tfsBuildNumber">The TFS build number.</param>
/// <returns>The real build number.</returns>
internal string GetRealBuildNumber(string tfsBuildNumber)
{
string buildStatus = this.buildAdapter.GetBuildStatusXml();
string nextBuildNumber = this.buildAdapter.GetQueuedBuildNumber(buildStatus, tfsBuildNumber).ToString();
return nextBuildNumber;
}
/// <summary>
/// Waits until the build starts -> Not throwing web exception 404 Not Found for the specific jenkins build URL.
/// </summary>
/// <param name="nextBuildNumber">The next build number.</param>
internal void WaitUntilBuildStarts(string nextBuildNumber)
{
int retryCount = 30;
bool isBuildtriggered = false;
string buildStatus = string.Empty;
do
{
if (!isBuildtriggered && retryCount == 0)
{
throw new Exception("The build didn't start in 30 seconds.");
}
try
{
buildStatus = this.buildAdapter.GetSpecificBuildStatusXml(nextBuildNumber);
Debug.WriteLine(buildStatus);
isBuildtriggered = true;
}
catch (WebException ex)
{
if (ex.Message.Equals("The remote server returned an error: (404) Not Found."))
{
retryCount--;
Thread.Sleep(1000);
Debug.WriteLine("wait 1 second until the build is triggered...");
}
}
}
while (!isBuildtriggered || retryCount == 0);
}
/// <summary>
/// Triggers the build.
/// </summary>
/// <param name="tfsBuildNumber">The TFS build number.</param>
/// <param name="nextBuildNumber">The next build number.</param>
/// <returns>The response.</returns>
/// <exception cref="System.Exception">Another build with the same build number is already triggered.</exception>
internal string TriggerBuild(string tfsBuildNumber, string nextBuildNumber)
{
string buildStatus = string.Empty;
bool isAlreadyBuildTriggered = false;
try
{
buildStatus = this.buildAdapter.GetSpecificBuildStatusXml(nextBuildNumber);
Debug.WriteLine(buildStatus);
}
catch (WebException ex)
{
if (!ex.Message.Equals("The remote server returned an error: (404) Not Found."))
{
isAlreadyBuildTriggered = true;
}
}
if (isAlreadyBuildTriggered)
{
throw new Exception("Another build with the same build number is already triggered.");
}
string response = this.buildAdapter.TriggerBuild(tfsBuildNumber);
return response;
}
/// <summary>
/// We get the nextBuildNumber from the Jenkins Build Status XML, but we don't know if this number will be really our build number when we trigger
/// the build. A race condition may occur.
/// </summary>
/// <returns>The next Build number.</returns>
internal string GetNextBuildNumber()
{
string buildStatus = this.buildAdapter.GetBuildStatusXml();
string nextBuildNumber = this.buildAdapter.GetNextBuildNumber(buildStatus);
return nextBuildNumber;
}
}
} |
bc268b64987f08dafc66e50d3f07bfab1c31d82c | C# | Daladwyn/Camping2000 | /Camping2000/Models/IdentityModels.cs | 2.625 | 3 | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Camping2000.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
//[Required]
public string GuestId { get; set; }
//[Required]
[MaxLength(80)]
//[RegularExpression("^[<>.!@#%/]+$", ErrorMessage = "First name is invalid.")]
public string GuestFirstName { get; set; }
// [Required]
[MaxLength(80)]
//[RegularExpression("^[<>.!@#%/]+$", ErrorMessage = "Last name is invalid.")]
public string GuestLastName { get; set; }
// [Required]
[MaxLength(40)]
//[RegularExpression("^[<>.!@#%/]+$", ErrorMessage = "Nationality is invalid.")]
public string GuestNationality { get; set; }
//[Required]
public bool GuestHasReserved { get; set; }
// [Required]
public bool GuestHasCheckedIn { get; set; }
public decimal GuestHasToPay { get; set; } //this property is used for gathering the amount the guest have to pay.
public decimal GuestHasPaid { get; set; }// This property is used as a checker if the guest have paid.
[MaxLength(20)]
//[RegularExpression("^[<>.!@#%/]+$", ErrorMessage = "Phone number is invalid.")]
public string GuestPhoneNumber { get; set; }
[MaxLength(20)]
//[RegularExpression("^[<>.!@#%/]+$", ErrorMessage = "Mobile number is invalid.")]
public string GuestMobileNumber { get; set; }// public int UserTelephoneNr { get; set; } Is located in ManageViewModel as PhoneNumber
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class Camping2000Db : IdentityDbContext<ApplicationUser>
{
public Camping2000Db() : base("Camping2000Db", throwIfV1Schema: false)
{
}
public static Camping2000Db Create()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Camping2000Db, Migrations.Configuration>());
return new Camping2000Db();
}
public DbSet<Camping> Camping { get; set; }
public DbSet<Booking> Bookings { get; set; }
public DbSet<Adress> Adresses { get; set; }
public DbSet<Receptionist> Receptionists { get; set; }
public DbSet<LinkBooking> LinkBookings { get; set; }
// /// <summary>
// /// Function that accepts one or two strings and return a list of guests
// /// </summary>
// /// <param name="firstName"></param>
// /// <param name="lastName"></param>
// /// <returns></returns>
public static List<ApplicationUser> SearchForPeople(string firstName, string lastName)
{
Camping2000Db Db = new Camping2000Db();
List<ApplicationUser> foundGuests = new List<ApplicationUser>();
firstName = firstName.ToLower();
lastName = lastName.ToLower();
if ((firstName != "") && (lastName == ""))
{
foreach (var guest in Db.Users)
{
if (guest.GuestFirstName.ToLower() == firstName)
{
foundGuests.Add(guest);
}
}
}
else if ((firstName != "") && (lastName != ""))
{
foreach (var guest in Db.Users)
{
if ((guest.GuestFirstName.ToLower() == firstName) && (guest.GuestLastName.ToLower() == lastName))
{
foundGuests.Add(guest);
}
}
}
else if ((firstName == "") && (lastName != ""))
{
foreach (var guest in Db.Users)
{
if (guest.GuestLastName.ToLower() == lastName)
{
foundGuests.Add(guest);
}
}
}
return foundGuests;
}
}
} |
52cd34713472a2e019926056468ebcf9ae06b2e8 | C# | Simon-PJ/Design-Patterns | /DesignPatterns/Structural/Facade/DuneFacade.cs | 2.546875 | 3 | namespace DesignPatterns.Structural.Facade
{
/// <summary>
/// Facade participant
/// </summary>
class DuneFacade
{
private readonly HouseArtreides _houseArtreides;
private readonly HouseHarkonnen _houseHarkonnen;
private readonly Fremen _fremen;
public DuneFacade(HouseArtreides houseArtreides, HouseHarkonnen houseHarkonnen, Fremen fremen)
{
_houseArtreides = houseArtreides;
_houseHarkonnen = houseHarkonnen;
_fremen = fremen;
}
public void RunPlot()
{
_houseArtreides.ReceiveArrakis();
_houseHarkonnen.RetakeArrakis();
_fremen.IntegratePaul();
_fremen.AttackHarkonnenWithSandWorms();
_houseArtreides.ReceiveArrakis();
}
}
}
|
0b78cf0ac3520ce2603ca3c92d920b11d00f0474 | C# | MohammadmehdiKhani/BFS_AdjMatrix | /Program.cs | 2.671875 | 3 | using System;
namespace BFS
{
class Program
{
static void Main(string[] args)
{
int[,] input = GraphHelper.Parse(@".\input.txt");
Graph graph = new Graph(input);
graph.BFS();
graph.PrintTree();
}
}
} |
f8eafa36530de7cdeb403cea4c275a7ca79044bb | C# | willianmarquesfsa/cursoCsharp | /Aula06/aula06.cs | 3.3125 | 3 | using System;
class Aula06{
static void Main(){
int n1, n2, n3;
n1=10; n2=30; n3=70;
Console.WriteLine("n1=\t{0}, \nn2=\t{1}, \nn3=\t{2}",n1,n2,n3);
double valorCompra=5.5;
double valorVenda;
double lucro=0.1;
string produto="Pastel";
valorVenda=valorCompra+(valorCompra*lucro);
Console.WriteLine("Produto.....:{0,15}",produto);
Console.WriteLine("Val.Compra..:{0,15:c}",valorCompra);
Console.WriteLine("Lucro.......:{0,15:p}", lucro);
Console.WriteLine("Val.Venda...:{0,15:c}", valorVenda);
}
} |
c9995ca026e00095cf1efe16325195df22ce54a8 | C# | makarenk0/wumpus-world | /Wumpus/AI/MultiAgent.cs | 3.109375 | 3 | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pacman.AI
{
public class MultiAgent
{
private int[,] _map;
private int _width, _height;
private MinimaxTree _tree;
private Dictionary<int, List<Point>> _agentPoints;
private bool treeIsExhausted;
public Node GetTreeRoot()
{
return _tree.Root;
}
public MultiAgent(int[,] map, Point player, Point[] enemies)
{
_map = map;
_width = _map.GetLength(0);
_height = _map.GetLength(1);
TreeIsExhausted = true;
}
public bool TreeIsExhausted {
get => treeIsExhausted;
set => treeIsExhausted = value;
}
public void ConstructMinimaxTree(Point player, Point[] enemies)
{
_tree = new MinimaxTree(_map, player, enemies);
_agentPoints = _tree.GetStepsForEachAgent();
TreeIsExhausted = false;
}
public Point GetEnemyNextPoint(int n)
{
Point p = new Point(_agentPoints[n].ElementAt(0).X, _agentPoints[n].ElementAt(0).Y);
_agentPoints[n].RemoveAt(0);
if(_agentPoints[n].Count == 0)
{
TreeIsExhausted = true;
}
return p;
}
public Point GetPlayerNextPoint()
{
return GetEnemyNextPoint(0);
}
}
}
|
f23ac06d4ae547a65015028ca69ae86b1b8ad19a | C# | MaxxWyndham/ToxicRagers | /ToxicRagers/CarmageddonReincarnation/Formats/crSetupLOL.cs | 2.65625 | 3 | using System.IO;
using ToxicRagers.CarmageddonReincarnation.Helpers;
namespace ToxicRagers.CarmageddonReincarnation.Formats
{
public enum SetupContext
{
Vehicle
}
public class Setup
{
SetupContext context;
LUACodeBlock settings;
public LUACodeBlock Settings
{
get => settings;
set => settings = value;
}
public Setup() { }
public Setup(SetupContext context)
{
switch (context)
{
case SetupContext.Vehicle:
this.context = SetupContext.Vehicle;
settings = new VehicleSetupCode();
break;
}
}
public static Setup Load(string path)
{
Setup setup = new Setup();
LOL lol = LOL.Load(path);
using (MemoryStream ms = new MemoryStream(lol.ReadAllBytes()))
using (StreamReader sr = new StreamReader(ms))
{
string testLine = sr.ReadLine();
string setupFile = testLine + "\r\n" + sr.ReadToEnd();
switch (testLine.Split(':')[0])
{
case "car":
setup.context = SetupContext.Vehicle;
setup.settings = VehicleSetupCode.Parse(setupFile);
break;
default:
return null;
}
}
return setup;
}
public void Save(string path)
{
switch (context)
{
case SetupContext.Vehicle:
using (StreamWriter sw = new StreamWriter(path + "\\setup.lol"))
{
sw.WriteLine(settings.ToString());
}
break;
}
}
}
public class VehicleSetupCode : LUACodeBlock
{
public VehicleSetupCode()
{
blockPrefix = "car";
underScored = false;
AddMethod(LUACodeBlockMethodType.Set,
"CollisionEffect",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.String, Name = "Effect", Value = "effects.f_carsharpnel06", ForceOutput = true },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Int, Name = "Value", Value = 10.5f, ForceOutput = true }
);
AddMethod(
LUACodeBlockMethodType.Set,
"PowerMultiplier",
"Multiplies up engine power",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(
LUACodeBlockMethodType.Set,
"TractionFactor",
"Gives extra traction with no extra lateral grip. 1 is normal",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Factor", Value = 1 }
);
AddMethod(
LUACodeBlockMethodType.Set,
"FinalDrive",
"Final Drive Ratio",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(
LUACodeBlockMethodType.Set,
"RearGrip",
"Controls the grip of the rear tyres(in g) 1.5 is normal",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1.4f }
);
AddMethod(LUACodeBlockMethodType.Set,
"FrontGrip",
"Controls the grip of the front tyres (in g) 1.5 is normal",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1.5f }
);
AddMethod(LUACodeBlockMethodType.Set,
"CMPosY",
"Height of centre of mass, in metres. 0 is at ground level, positive is up",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.52f }
);
AddMethod(LUACodeBlockMethodType.Set,
"CMPosZ",
"Forwards/Backwards position of centre of mass of car. 0.0 half way between wheels, 1.0 is over front axle, -1.0 is over rear axel. Suspension is adjusted to keep car level",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", ForceOutput = true }
);
AddMethod(LUACodeBlockMethodType.Set,
"FrontDownforce",
"Down force at front axle in kg",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Int, Name = "Value", Value = 20 }
);
AddMethod(LUACodeBlockMethodType.Set,
"RearDownforce",
"Down force at rear axle in kg",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Int, Name = "Value", Value = 20 }
);
AddMethod(LUACodeBlockMethodType.Set,
"FrontRoll",
"Front anti roll bar setting. 0.0 = soft, 1.0 = strong",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.5f }
);
AddMethod(LUACodeBlockMethodType.Set,
"RearRoll",
"Rear anti roll bar setting. 0.0 = soft, 1.0 = strong",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.5f }
);
AddMethod(LUACodeBlockMethodType.Set,
"FrontCriticalAngle",
"Angle at which front tyres loose traction (degrees)",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 6 }
);
AddMethod(LUACodeBlockMethodType.Set,
"RearCriticalAngle",
"Angle at which rear tyres loose traction (degrees)",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 6 }
);
AddMethod(LUACodeBlockMethodType.Set,
"FrontSuspGive",
"Amount of suspension compression due to the weight of the car (front)",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.0667f }
);
AddMethod(LUACodeBlockMethodType.Set,
"RearSuspGive",
"Amount of suspension compression due to the weight of the car (rear)",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.0667f }
);
AddMethod(LUACodeBlockMethodType.Set,
"SuspDamping",
"Adjust suspension damping. 1 = critical damping",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(LUACodeBlockMethodType.Set,
"SuspensionRollFactor",
"Controls roll. 1.0 = physically realistic",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(LUACodeBlockMethodType.Set,
"SuspensionPitchFactor",
"Controls pitch. 1.0 = physically realistic",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(LUACodeBlockMethodType.Set,
"MomentOfInertiaMultiplier",
"Moment of inertia multiplier of car in y axis",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(LUACodeBlockMethodType.Set,
"SteerSpeed1",
"Controls how fast the steering is. 1.0 is normal",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(LUACodeBlockMethodType.Set,
"SteerSpeed2",
"Controls how fast the steering is at SteerSpeedVel. Actual steerspeed is interpolated between this and the steerspeed value, depending on the cars velocity",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.5f }
);
AddMethod(LUACodeBlockMethodType.Set,
"SteerSpeedVel",
"Controls how fast the steering is. See SteerSpeed2",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 150 }
);
AddMethod(LUACodeBlockMethodType.Set,
"SteerCentreMultiplier",
"Controls how fast the steering returns to centre. 0.0 is a special case which means centre immediately key is pressed",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(LUACodeBlockMethodType.Set,
"MaxSteeringAngle",
"The angle in degrees that the wheels turn from straight ahead to full lock",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 40 }
);
AddMethod(LUACodeBlockMethodType.Set,
"BrakeBalance",
"Controls the percentage of brake force applied to the front wheels",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 60 }
);
AddMethod(LUACodeBlockMethodType.Set,
"BrakeForce",
"The brake force applied per KG(in m/s^2). Will be limited by tyre grip",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 60 }
);
AddMethod(LUACodeBlockMethodType.Set,
"HandBrakeStrength",
"Controls the decceleration force in Newtons per kg that the handbrake applies to the car",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 10 }
);
AddMethod(LUACodeBlockMethodType.Set,
"TorqueSplit",
"Fraction of torque passed to rear wheels",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 65 }
);
AddMethod(LUACodeBlockMethodType.Set,
"LSDThresholdF",
"Front differential Rotation speed difference in rad/s needed to lock differential",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 10 }
);
AddMethod(LUACodeBlockMethodType.Set,
"LSDThresholdR",
"Rear differential Rotation speed difference in rad/s needed to lock differential",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 10 }
);
AddMethod(LUACodeBlockMethodType.Set,
"LSDThresholdM",
"Mid differential Rotation speed difference in rad/s needed to lock differential",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 10 }
);
AddMethod(LUACodeBlockMethodType.Set,
"ReversePowerMulitplier",
"Reduces power when reversing",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(LUACodeBlockMethodType.Set,
"WheelMass",
"Average mass of a wheel per 1000kg of car",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 10 }
);
AddMethod(LUACodeBlockMethodType.Set,
"DragCoefficient",
"Fraction of air resistance force compared to a flat plate of the same/ncross-sectional area",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.5f }
);
AddMethod(LUACodeBlockMethodType.Set,
"SteerLimit1",
"Prevents wheels being turned to much for the given speed. 0 is off",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", ForceOutput = true }
);
AddMethod(LUACodeBlockMethodType.Set,
"SteerLimit2",
"Prevents wheels being turned to much for the given speed. 0 is off",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", ForceOutput = true }
);
AddMethod(LUACodeBlockMethodType.Set,
"SteerLimitSpeed",
"Speed at which steer limit 2 is applied",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", ForceOutput = true }
);
AddMethod(LUACodeBlockMethodType.Set,
"CastorSpeed1",
"Controls how stable the steering is. 0.0 is no castor 1.0 is max",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", ForceOutput = true }
);
AddMethod(LUACodeBlockMethodType.Set,
"CastorSpeed2",
"Controls how stable the steering is at SteerSpeedVel. Actual castor speed is interpolated between this and the castor speed value, depending on the cars velocity",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(LUACodeBlockMethodType.Set,
"CastorSpeedVel",
"Controls how stable the steering is. See CastorSpeed2",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 100 }
);
AddMethod(LUACodeBlockMethodType.Set,
"SteerGyroscope",
"Tends to make the front wheels preserve there world space alignment. This helps make the car stable. 0.0 is off, 1.0 is maximum",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(LUACodeBlockMethodType.Set,
"BrakeAttack",
"Time taken to apply the full brake force in seconds",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(LUACodeBlockMethodType.Set,
"HandBrakeAttack",
"Time taken in seconds for handbrake to reach full strength",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.1f }
);
AddMethod(LUACodeBlockMethodType.Set,
"SlideSpinRecovery",
"When recovering from a slide, this prevents car spinning out the other way",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 1 }
);
AddMethod(LUACodeBlockMethodType.Set,
"RollingResistance",
"Rolling resistance force in Newtons per newton of vertical force per ms^-1 of velocity",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.018f }
);
AddMethod(LUACodeBlockMethodType.Set,
"DriveMI",
"Moment of inertia due to drive system (Including gear box, wheels etc)",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 2.2f }
);
AddMethod(LUACodeBlockMethodType.Set,
"EngineMI",
"Moment of inertyia of engine",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.06f }
);
AddMethod(LUACodeBlockMethodType.Set,
"RedLine",
"Maximum safe revs of engine",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Int, Name = "Value", Value = 6500 }
);
AddMethod(LUACodeBlockMethodType.Set,
"MaxRevs",
"Maximum revs of engine",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Int, Name = "Value", Value = 8000 }
);
AddMethod(LUACodeBlockMethodType.Set,
"LimitRevs",
"Prevents engine over reving. Can be on or off. (will reduce wheelspin when on)",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Boolean, Name = "Value", Value = true }
);
AddMethod(LUACodeBlockMethodType.Set,
"ConstantEngineFriction",
"Constant retardation torque in engine",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 833 }
);
AddMethod(LUACodeBlockMethodType.Set,
"LinearEngineFriction",
"Retardation torque in engine proportional to angular velocity",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", ForceOutput = true }
);
AddMethod(LUACodeBlockMethodType.Set,
"QuadraticEngineFriction",
"Retardation torque in engine proportional to square of angular velocity",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.0023f }
);
AddMethod(LUACodeBlockMethodType.Set,
"ConstantDriveFriction",
"Constant retardation torque in drive system",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 9.1f }
);
AddMethod(LUACodeBlockMethodType.Set,
"LinearDriveFriction",
"Retardation torque in drive proportional to angular velocity",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", ForceOutput = true }
);
AddMethod(LUACodeBlockMethodType.Set,
"QuadraticDriveFriction",
"Retardation torque in drive proportional to square of angular velocity",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.0008f }
);
AddMethod(LUACodeBlockMethodType.Set,
"EngineBrakeDelay",
"Period of between releasing accelerator and engine braking starting",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.5f }
);
AddMethod(LUACodeBlockMethodType.Set,
"EngineBrakeAttack",
"Period from engine braking starting to full engine braking (i.e. zero throttle)",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.28f }
);
AddMethod(LUACodeBlockMethodType.Set,
"ClutchDelay",
"Period clutch is down when changing gear (s)",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", ForceOutput = true }
);
AddMethod(LUACodeBlockMethodType.Set,
"Mass",
"Set the mass of the vehicle in Kg",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 2000 }
);
AddMethod(LUACodeBlockMethodType.Set,
"NumGears",
"Number of gears (excluding R and N)",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 5 }
);
AddMethod(LUACodeBlockMethodType.Set,
"GearRatios",
"Engine revs / wheel revs",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Int, Name = "Count", Value = 10 },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "1", Value = 13.86f },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "2", Value = 8.2193f },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "3", Value = 5.7005f },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "4", Value = 4.2327f },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "5", Value = 3.2277f },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "6", Value = 2.6775f },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "7", Value = 2.1616f },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "8", Value = 1.7157f },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "9", Value = 1.3752f },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "10", Value = 1.1346f }
);
AddMethod(LUACodeBlockMethodType.Set,
"TorqueCurve",
"Engine torque in Nm",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Int, Name = "Count", Value = 20 },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "1", Value = 80 },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "2", Value = 208 },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "3", Value = 264 },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "4", Value = 280 },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "5", Value = 264 },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "6", Value = 240 },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "7", Value = 208 },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "8", Value = 160 },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "9" },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "10" },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "11" },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "12" },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "13" },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "14" },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "15" },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "16" },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "17" },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "18" },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "19" },
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "20" }
);
AddMethod(LUACodeBlockMethodType.Set,
"StabilityGripChange",
"Amount grip can be adjusted to stabilise car",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.4f }
);
AddMethod(LUACodeBlockMethodType.Set,
"StabilityThreshold",
"Adjust point that stability control kicks in 0.0 = immediately, 1.0 = quit late, -1 = never",
new LUACodeBlockMethodParameter { Type = LUACodeBlockMethodParameterType.Float, Name = "Value", Value = 0.5f }
);
}
public static VehicleSetupCode Parse(string cdata)
{
return Parse<VehicleSetupCode>(cdata);
}
}
} |
00c5c3000bb839cdb4ba25716cd85620ae732dd8 | C# | andrewtovkach/EpamTraining | /Transport/Transport/Comparers/ComparerByOccupiedVolume.cs | 2.9375 | 3 | using System.Collections.Generic;
using Transport.Model.Carriages;
namespace Transport.Comparers
{
public class ComparerByOccupiedVolume : IComparer<Carriage>
{
public int Compare(Carriage x, Carriage y)
{
var carriageFirst = x as FreightCarriage;
var carriageSecond = y as FreightCarriage;
if (carriageFirst != null && carriageSecond != null)
return carriageFirst.OccupiedVolume.CompareTo(carriageSecond.OccupiedVolume);
return x.CompareTo(y);
}
}
}
|
25d0006f17da47ebb0910aded31497b00043a409 | C# | Fur1ok/Duplicity | /src/Duplicity/Filtering/ObservableFilters.cs | 2.765625 | 3 | using System;
using System.Collections.Generic;
using Duplicity.Filtering.Aggregation;
namespace Duplicity.Filtering
{
internal static class ObservableFilters
{
/// <summary>
/// Merge changes in the given observable sequence of buffers to minimise output.
/// For example, created then deleted changes to the same file will be excluded entirely since the end result is no file.
/// </summary>
/// <param name="source">Source sequence to filter.</param>
/// <returns>An observable sequence of buffers.</returns>
public static IObservable<IList<FileSystemChange>> PrioritizeFileSystemChanges(this IObservable<IList<FileSystemChange>> source)
{
if (source == null) throw new ArgumentNullException("source");
return new IgnoreChangesBeforeDeletionsFilter(source);
}
}
}
|
35e04d7959f84bad69d62d04e168d8bf5966557a | C# | shendongnian/download4 | /code6/1133817-29860726-88980215-2.cs | 3.375 | 3 | using System;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
ConfigFile f = ConfigFile.Load();
f.ServerAddress = "0.0.0.0";
f.ServerPort = "8080";
f.ServerTimeout = "400";
f.Save();
}
public class ConfigFile
{
public string ServerAddress { get; set; }
public string ServerPort { get; set; }
public string ServerTimeout { get; set; }
public void Save()
{
var fileContent = JsonConvert.SerializeObject(this);
Console.WriteLine(fileContent);
}
public static ConfigFile Load()
{
var fileContents = @"{ ServerAddress: null, ServerPort: null, ServerTimeout: null }";
ConfigFile f = JsonConvert.DeserializeObject<ConfigFile>(fileContents);
return f;
}
}
}
|
0a930c5dedd5ea98fd3b9c4413bf1b8dfa604901 | C# | gustavocbjunior/GameLoanManager | /Backend/GameLoanManager.Data/Maps/UserMap.cs | 2.703125 | 3 | using System;
using GameLoanManager.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace GameLoanManager.Data.Maps
{
public class UserMap : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable("User");
builder.HasKey(x => x.Id);
builder.HasIndex(u => u.Email).IsUnique();
builder.Property(u => u.Email).HasMaxLength(120).HasColumnType("varchar(120)");
builder.Property(u => u.Name)
.IsRequired()
.HasMaxLength(80)
.HasColumnType("varchar(80)");
builder.Property(u => u.Login)
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
builder.Property(u => u.Password)
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
builder.Property(p => p.Phone)
.IsRequired()
.HasMaxLength(11)
.HasColumnType("varchar(11)");
}
}
}
|
bc50da471b82c2c818a237d16ee3f3758a1a810c | C# | GuJlGaMesh/password_storage | /Password Storage/PasswordGenerationRules/LowerChar.cs | 3.296875 | 3 | using System;
namespace Password_Storage
{
public class LowerChar : IGenerator
{
private const string lowerCase = "abcdefghijklmnopqursuvwxyz";
private readonly Random random = new Random();
public virtual int MinLength => 1;
public string GetChar() => lowerCase[random.Next(0, lowerCase.Length)].ToString();
}
}
|
03bbc06c59d07ce0e9f6f8d8ecc7cc9747f5eec9 | C# | team-hades/EventsSystem | /EventsSystem/EventsSystem.Server/EventsSystem.Api/Controllers/EventsController.cs | 2.578125 | 3 | namespace EventsSystem.Api.Controllers
{
using System.Linq;
using System.Web.Http;
using AutoMapper.QueryableExtensions;
using EventsSystem.Api.Infrastructure.Mapping;
using EventsSystem.Api.Models.Events;
using Providers;
using EventsSystem.Data.Data.Repositories;
using EventsSystem.Data.Models;
using System.Collections.Generic;
using AutoMapper;
using Infrastructure.Validation;
/// <summary>
/// Responsible for Events actions main prefix api/events
/// </summary>
[RoutePrefix("api/events")]
public class EventsController : BaseController
{
IMappingService mapservices;
public EventsController(IEventsSystemData data, IMappingService mapservices)
: base(data)
{
this.mapservices = mapservices;
}
/// <summary>
/// All listed events - public / admin / registered users action
/// </summary>
/// <returns>All events ordered by start date (for admin)</returns>
/// <returns>All user events (for registered user with created events)</returns>
/// <returns>All tagged events (for registered user without created events)</returns>
/// <returns>Top 10 public events ordered by start date (for visitors)</returns>
[HttpGet]
public IHttpActionResult All()
{
// TODO: If current user is admin: get all events
if (this.User.IsInRole("Admin"))
{
var allAdminEvents = this.data.Events
.All()
.OrderByDescending(d => d.StartDate)
.ProjectTo<EventResponseModel>();
return this.Ok(allAdminEvents);
}
if (this.User.Identity.IsAuthenticated)
{
var currentUserName = this.User.Identity.Name;
var currentUser = this.data.Users.All().Where(u => u.UserName == currentUserName).FirstOrDefault();
var allEventsWithTagedUser = currentUser.Events
.OrderByDescending(e => e.StartDate)
.AsQueryable()
.ProjectTo<EventsForUserResponseModel>()
.ToList();
if (allEventsWithTagedUser.Count() > 0)
{
return this.Ok(allEventsWithTagedUser);
}
return this.BadRequest("No events were found.");
}
// Non Registered users will see only top 10 non private events
var allVisibleEvents = this.data.Events
.All()
.Where(ev => ev.IsPrivate != true)
.OrderBy(d => d.StartDate)
.Take(10)
.ProjectTo<EventResponseModel>();
return this.Ok(allVisibleEvents);
}
/// <summary>
/// All listed events by Id - public action
/// </summary>
/// <param name="id"></param>
/// <returns>All events by Id</returns>
[HttpGet]
public IHttpActionResult All(int id)
{
var eventToReturn = this.data.Events.All().Where(ev => ev.Id == id).ProjectTo<EventResponseModel>();
if (eventToReturn == null)
{
// TODO Add some message
return this.BadRequest("No events were found.");
}
// TODO we need to include a collection of comments in the model to work
return this.Ok(eventToReturn);
}
/// <summary>
/// Paging - All listed events by page - public action
/// </summary>
/// <param name="page">Specific page to display</param>
/// <returns>10 events from specific page</returns>
[HttpGet]
public IHttpActionResult AllByPage(string page)
{
int pageSize = int.Parse(page);
int defaultPageSize = 10;
// TODO check if skip and take work
var eventsToReturn = this.data.Events.All()
.OrderByDescending(e => e.StartDate)
.Skip(defaultPageSize * pageSize)
.Take(defaultPageSize)
.ProjectTo<EventResponseModel>();
if (eventsToReturn == null)
{
// TODO Add some message
return this.BadRequest("No events were not found.");
}
return this.Ok(eventsToReturn);
}
/// <summary>
/// All events by Category
/// </summary>
/// <param name="category">Specific category</param>
/// <returns>First 10 events in the specific category by date</returns>
[HttpGet]
public IHttpActionResult AllByCategoryByCategory(string category)
{
var eventsFromCategory = this.data.Events.All()
.Where(e => e.Category.Name == category)
.OrderByDescending(x => x.StartDate)
.Take(10)
.ProjectTo<EventResponseModel>();
if (eventsFromCategory == null)
{
return this.BadRequest("No events were found.");
}
return this.Ok(eventsFromCategory);
}
/// <summary>
/// All events by town - public action
/// </summary>
/// <param name="town">Specific town</param>
/// <returns>First 10 events by town ordered by start date</returns>
[HttpGet]
public IHttpActionResult AllByCategoryByTown(string town)
{
var eventsFromCategory = this.data.Events.All()
.Where(e => e.Town.Name == town)
.OrderByDescending(x => x.StartDate)
.Take(10)
.ProjectTo<EventResponseModel>();
if (eventsFromCategory == null)
{
return this.BadRequest("No events were found.");
}
return this.Ok(eventsFromCategory);
}
/// <summary>
/// All events by town and category - public action
/// </summary>
/// <param name="category">Specific category</param>
/// <param name="town">Specific town</param>
/// <returns>All events ordered by start date</returns>
[HttpGet]
public IHttpActionResult AllByCategoryAndTown(string category, string town)
{
var eventsFromCategory = this.data.Events.All()
.Where(e => e.Category.Name == category && e.Town.Name == town)
.OrderByDescending(x => x.StartDate)
.ProjectTo<EventResponseModel>();
if (eventsFromCategory == null)
{
return this.BadRequest("No events were found.");
}
return this.Ok(eventsFromCategory);
}
/// <summary>
/// Adding new event - authorised action
/// </summary>
/// <param name="model">Expects event model</param>
/// <returns>Added event Id</returns>
/// <returns>PubNub notification with event name</returns>
[HttpPost]
[ValidateModel]
public IHttpActionResult Post(EventSaveModel model)
{
var town = this.data.Towns.All().Where(t => t.Name == model.Town).FirstOrDefault();
var category = this.data.Categories.All().Where(c => c.Name == model.Category).FirstOrDefault();
var currentUserName = this.User.Identity.Name;
var currentUser = this.data.Users.All().Where(u => u.UserName == currentUserName).FirstOrDefault();
var eventToAdd = this.mapservices.Map<Event>(model);
eventToAdd.CategoryId = category.Id;
eventToAdd.TownId = town.Id;
if (model.Tags != null)
{
var tagsFromDb = this.data.Tags.All().ToList();
var tagsToAdd = new List<Tag>();
foreach (var tag in model.Tags)
{
var tagFromDb = tagsFromDb.FirstOrDefault(t => t.Name == tag);
if (tagFromDb == null)
{
tagsToAdd.Add(new Tag { Name = tag });
}
else
{
tagsToAdd.Add(tagFromDb);
}
}
eventToAdd.Tags = tagsToAdd;
}
this.data.Events.Add(eventToAdd);
this.data.Savechanges();
PubNubNotificationProvider.Notify(eventToAdd.Name);
return this.Created("api/events", new
{
EventId = eventToAdd.Id
});
}
/// <summary>
/// Changes specific event - authorised action
/// </summary>
/// <param name="id">Event id to change</param>
/// <param name="model">New event model</param>
/// <returns>Updated event Id</returns>
[HttpPut]
[ValidateModel]
public IHttpActionResult Put(int id, EventSaveModel model)
{
var eventToUpdate = this.data.Events.All().Where(ev => ev.Id == id).FirstOrDefault();
if (eventToUpdate == null)
{
return this.BadRequest("The event was not found.");
}
var town = this.data.Towns.All().Where(t => t.Name == model.Town).FirstOrDefault();
var category = this.data.Categories.All().Where(x => x.Name == model.Category).FirstOrDefault();
eventToUpdate.Name = model.Name ?? eventToUpdate.Name;
eventToUpdate.IsPrivate = model.IsPrivate;
eventToUpdate.StartDate = model.StartDate;
eventToUpdate.EndDate = model.EndDate;
eventToUpdate.TownId = town.Id;
eventToUpdate.CategoryId = category.Id;
this.data.Events.Update(eventToUpdate);
this.data.Savechanges();
return this.Ok(eventToUpdate.Id);
}
/// <summary>
/// Deletes an event - authorised action
/// </summary>
/// <param name="id">Event Id</param>
/// <returns>Delete notification</returns>
[HttpDelete]
public IHttpActionResult Delete(int id)
{
var eventToDelete = this.data.Events.All().Where(ev => ev.Id == id).FirstOrDefault();
if (eventToDelete == null)
{
return this.BadRequest("The event was not found.");
}
this.data.Events.Delete(eventToDelete);
this.data.Savechanges();
return this.Ok("Event was deleted");
}
/// <summary>
/// Join an event - authorised action
/// </summary>
/// <param name="eventId">Event Id</param>
/// <returns>Event Id</returns>
[Authorize]
[HttpPost]
[Route("join/{eventId}")]
public IHttpActionResult Join(int eventId)
{
//if (!this.User.Identity.IsAuthenticated)
//{
// return this.BadRequest("You have to be logged in to do this operation");
//}
var eventToJoin = this.data.Events.All().Where(ev => ev.Id == eventId).FirstOrDefault();
if (eventToJoin == null)
{
return this.BadRequest("The event was not found.");
}
var currentUserName = this.User.Identity.Name;
var currentUser = this.data.Users.All().Where(u => u.UserName == currentUserName).FirstOrDefault();
//eventToJoin.Users.Add(currentUser);
//this.data.Events.Update(eventToJoin);
//this.data.Savechanges();
currentUser.Events.Add(eventToJoin);
this.data.Savechanges();
return this.Ok(eventToJoin.Id);
}
/// <summary>
/// Leave an event - authorised action
/// </summary>
/// <param name="eventId">Event Id</param>
/// <returns>Successfull leave notification</returns>
[Authorize]
[HttpPut]
[Route("leave/{eventId}")]
public IHttpActionResult Leave(int eventId)
{
//if (!this.User.Identity.IsAuthenticated)
//{
// return this.BadRequest("You have to be logged in to do this operation");
//}
var eventToLeave = this.data.Events.All().Where(ev => ev.Id == eventId).FirstOrDefault();
if (eventToLeave == null)
{
return this.BadRequest("The event was not found.");
}
var currentUserName = this.User.Identity.Name;
var currentUser = this.data.Users.All().Where(u => u.UserName == currentUserName).FirstOrDefault();
eventToLeave.Users.Remove(currentUser);
this.data.Events.Update(eventToLeave);
this.data.Savechanges();
return this.Ok("Leave");
}
/// <summary>
/// Rate an event - required authorisation.
/// </summary>
/// <param name="eventId">Id of the event to be rated.</param>
/// <param name="rating">Rating between 1 and 5, inclusive.</param>
/// <returns>Id of the event which is rated.</returns>
//[Authorize]
[HttpPost]
[Route("rate/{eventId}/{rating}")]
public IHttpActionResult Rate(int eventId, int rating)
{
//if (!this.User.Identity.IsAuthenticated)
//{
// return this.BadRequest("You have to be logged in to do this operation");
//}
if (rating <= 0 || rating > 5)
{
return this.BadRequest("Rating must be integer between 1 and 5, inclusive.");
}
var eventWithRating = this.data.Events.All().Where(ev => ev.Id == eventId).FirstOrDefault();
if (eventWithRating == null)
{
return this.BadRequest("The event was not found.");
}
var currentUserName = this.User.Identity.Name;
var currentUser = this.data.Users.All().Where(u => u.UserName == currentUserName).FirstOrDefault();
var ratingToAdd = new Rating
{
EventId = eventWithRating.Id,
UserId = currentUser.Id,
Value = rating
};
this.data.Ratings.Add(ratingToAdd);
this.data.Savechanges();
return this.Ok(mapservices.Map<EventResponseModel>(eventWithRating));
}
/// <summary>
/// Update an event's rate - required authorisation.
/// </summary>
/// <param name="eventId">Id of the event to be rated.</param>
/// <param name="rating">Rating between 1 and 5, inclusive.</param>
/// <returns>Id of the event which is rated.</returns>
[Authorize]
[HttpPut]
[Route("rate/{eventId}/{rating}")]
public IHttpActionResult UpdateRate(int eventId, int rating)
{
if (rating <= 0 || rating > 5)
{
return this.BadRequest("Rating must be integer between 1 and 5, inclusive.");
}
var eventWithRating = this.data.Events.All().Where(ev => ev.Id == eventId).FirstOrDefault();
if (eventWithRating == null)
{
return this.BadRequest("The event was not found.");
}
var currentUserName = this.User.Identity.Name;
var currentUser = this.data.Users.All().Where(u => u.UserName == currentUserName).FirstOrDefault();
var ratingToUpdate = eventWithRating.Ratings.Where(e => e.UserId == currentUser.Id).FirstOrDefault();
ratingToUpdate.Value = rating;
this.data.Ratings.Update(ratingToUpdate);
this.data.Savechanges();
return this.Ok(mapservices.Map<EventResponseModel>(eventWithRating));
}
}
} |
57df64c1e746b8b75be55f144b1d3a14b49d4d40 | C# | nmitha/HelpdeskBot | /TheMakerShowBot/Controllers/MessagesController.cs | 2.5625 | 3 | using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using Microsoft.Bot.Connector;
using Newtonsoft.Json;
using Microsoft.Cognitive.LUIS;
using System.Diagnostics;
using Microsoft.Bot.Builder.Dialogs;
using HelpBot.FormFlows;
using Microsoft.Bot.Builder.FormFlow;
namespace HelpBot
{
[BotAuthentication]
public class MessagesController : ApiController
{
LuisClient luisClient = new LuisClient(
/*appid:*/ "36ce03d4-3cd6-49f7-a847-88746b4120dc",
/*appkey:*/ "ae4c72bef69a477e898d3cad9b57714e"
);
//LuisClient cortanaLuisClient = new LuisClient(
// "c413b2ef-382c-45bd-8ff0-f76d60e2a821",
// "ae4c72bef69a477e898d3cad9b57714e"
// );
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
if (activity.Type != ActivityTypes.Message)
{
HandleSystemMessage(activity);
}
else
{
string msg = activity.Text;
// Parse the user's meaning (intent) via Language Understanding (LUIS) in Cognitive Services
string replyMsg = await GetReplyMessage(msg);
bool isConversationAboutAddingPrinter = BotState.ConversationsInPrinterDialog.Contains(activity.Conversation.Id);
if (isConversationAboutAddingPrinter || replyMsg == "[addprinter]") // quick hack for this demo and special case
{
if (!isConversationAboutAddingPrinter)
{
BotState.ConversationsInPrinterDialog.Add(activity.Conversation.Id); // it is now
}
await Microsoft.Bot.Builder.Dialogs.Conversation.SendAsync(activity, MakeRootAddPrinterDialog);
}
else
{
Activity reply = activity.CreateReply(replyMsg);
if (replyMsg.Contains("restart"))
{
reply.Attachments.Add(new Attachment()
{
ContentUrl = "http://cdn.makeuseof.com/wp-content/uploads/2015/07/Windows-10-Restart.png",
ContentType = "image/png",
Name = "Rebooting in Windows 10"
});
}
await connector.Conversations.ReplyToActivityAsync(reply);
}
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
private async Task<string> GetReplyMessage(string msg)
{
string defaultReplyMsg = "I'm not so good at chit chat, but tell me about the IT support you need and I can help!";
string replyMsg = defaultReplyMsg;
var luisResult = await luisClient.Predict(msg);
string intent = luisResult.GetTopIntentName();
// Not using a switch statement because I might want to add more conditions (e.g. check intent and also check entities or something else)
if (string.IsNullOrEmpty(intent) || intent == "None")
{
// Try fall back to Cortana if we don't know what to do with this message:
//var cortanaResult = await cortanaLuisClient.Predict(msg);
//if (! cortanaResult.HasIntent())
//{
// return defaultReplyMsg;
//}
//replyMsg = $"(Cortana) Intent: {cortanaResult.TopScoringIntent.Name}";
//string dialogPrompt = string.Empty;
//if (cortanaResult.isAwaitingDialogResponse() && cortanaResult.DialogResponse != null && !string.IsNullOrEmpty(cortanaResult.DialogResponse.Prompt))
//{
// replyMsg += $"\r\nPrompt: {cortanaResult.DialogResponse.Prompt}";
//}
return defaultReplyMsg;
}
else if (intent == "thank you")
{
replyMsg = "You're welcome. Let me know if there's anything else.";
}
else if (intent == "computer slow")
{
replyMsg = "If you're computer is slow, maybe you should try to restart it.\r\n\r\nIt seems to me like you're using Windows 10, so here's how you'd restart: ";
}
else if (intent == "printer issue")
{
replyMsg = "It sounds like you're having an issue with a printer :(\r\n\r\nThis isn't something I'm programmed to help with yet, but rest assured that Building Facilities is automatically notified of most printer issues, and someone should be on their way!";
}
else if (intent == "add a printer")
{
replyMsg = "[addprinter]"; //this is a hack to indicate we should enter the add printer dialog. previous: "I can help you add a printer. First, are you using Windows XP, Windows 7 or a Mac?";
}
else if (intent == "access to system")
{
string system = MapSystemNameToFriendlyName(luisResult.GetEntityValue("system"));
replyMsg = $"It sounds like you need access to {system}. That should be no problem."
+ $"\r\n\r\nIn order to go ahead and do that, I just need your manager Katie Jordan to chat with me about it (or tell her to email the details to me at helpbot@cloud.com). Once she confirms you're authorized for that I should be able to set you up with access!"
+ $"\r\n\r\nI've gone ahead and created a ticket in our system for your access request. The ticket # is _{DateTime.Now.ToString("MMddHHmmss")}_, but you can always ask me about any of your IT Support tickets even if you don't have the ticket number handy.";
}
else
{
replyMsg = $"I think what you're saying has to do with '{intent}' but I'm not programmed to help with that yet. Sorry!";
}
return replyMsg;
}
internal static string MapSystemNameToFriendlyName(string system)
{
if (string.IsNullOrEmpty(system))
{
return "an application or system we manage";
}
else if (system.Equals("sharepoint", StringComparison.OrdinalIgnoreCase))
{
return "a SharePoint site";
}
else
{
return system.ToUpper();
}
}
internal static IDialog<AddPrinterInfo> MakeRootAddPrinterDialog()
{
return Chain.From(() => FormDialog.FromForm(AddPrinterInfo.BuildForm));
}
private Activity HandleSystemMessage(Activity activity)
{
if (activity.Type == ActivityTypes.Ping)
{
// Check if service is alive
}
else if (activity.Type == ActivityTypes.DeleteUserData)
{
// Implement user deletion here
// If we handle user deletion, return a real message
}
else if (activity.Type == ActivityTypes.ContactRelationUpdate)
{
// Handle add/remove from contact lists
// Activity.From + Activity.Action represent what happened
}
else if (activity.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels
}
else if (activity.Type == ActivityTypes.Typing)
{
// Lets your bot indicate whether the user or bot is typing
}
return null;
}
}
} |
3023752115abd55a73bc261fbee88ddda4255163 | C# | sandor-karajz/RobotFootball | /RobotFootball/RobotFootballGame/Ball.cs | 3.140625 | 3 | using RobotFootball.RobotFootballGame.Extensions;
using RobotFootball.RobotFootballGame.Helper;
using System;
namespace RobotFootball.RobotFootballGame
{
public class Ball : GameObject
{
private static readonly double DRAG = 0.2;
private static readonly double SHOT_SPEED = 40.0;
private static readonly double COLLISION_SPEED_ABSORPTION = 20.0;
public double Speed { get; set; }
public Vector Direction { get; set; }
public void Move(double elapsedTime)
{
var movement = Direction.MultNew(Speed * elapsedTime);
Position.Plus(movement);
Speed -= movement.Magnitude() * DRAG;
}
public void ModifyMovement(Vector normal, bool isShot)
{
ModifyDirection(normal);
ModifySpeed(isShot);
}
private void ModifyDirection(Vector normal)
{
if (Direction.IsNullVector())
{
Direction.Set(normal.MultNew(-1));
}
var ballAngle = Direction.Angle.EnsurePositiveAngle();
var normalAngle = normal.Angle.EnsurePositiveAngle();
var angleFromWall = (normalAngle - ballAngle - Math.PI / 2).EnsurePositiveAngle();
var remainingFrom180 = (Math.PI - angleFromWall).EnsurePositiveAngle();
var smallerAngleFromWall = angleFromWall < remainingFrom180 ? angleFromWall : remainingFrom180;
var rotation = Math.PI - (smallerAngleFromWall * 2);
if (angleFromWall == smallerAngleFromWall)
{
Direction.Rotate(-rotation);
}
else
{
Direction.Rotate(rotation);
}
Direction.Mult(-1);
}
private void ModifySpeed(bool isShot)
{
if (isShot)
{
Speed = SHOT_SPEED;
}
else
{
Speed = Speed * (100 - COLLISION_SPEED_ABSORPTION) / 100;
}
}
}
}
|
8a6897e33ae586432e4dd6a8d7c3841c1bc40ea6 | C# | rog1039/Rogero.NumberSystems | /src/Rogero.NumberSystems/Rogero.NumberSystems.Tests/AtoBTests.cs | 2.96875 | 3 | using FluentAssertions;
using Xunit;
namespace Rogero.NumberSystems.Tests;
public class AtoBTests
{
[Fact]
public void ZeroTest()
{
var convertAction = new Action(() => NumberConverter.ConvertFromDecimal(0, NumberSystem.AToB_OneIndex));
convertAction.ShouldThrow<ArgumentException>();
}
[Fact]
public void OneTest()
{
var result = NumberConverter.ConvertFromDecimal(1, NumberSystem.AToB_OneIndex);
result.Value.Should().Be("A");
}
[Fact]
public void TwoTest()
{
var result = NumberConverter.ConvertFromDecimal(2, NumberSystem.AToB_OneIndex);
result.Value.Should().Be("B");
}
[Fact]
public void ThreeTest()
{
var result = NumberConverter.ConvertFromDecimal(3, NumberSystem.AToB_OneIndex);
result.Value.Should().Be("AA");
}
[Fact]
public void FourTest()
{
var result = NumberConverter.ConvertFromDecimal(4, NumberSystem.AToB_OneIndex);
result.Value.Should().Be("AB");
}
[Fact]
public void FiveTest()
{
var result = NumberConverter.ConvertFromDecimal(5, NumberSystem.AToB_OneIndex);
result.Value.Should().Be("BA");
}
[Fact]
public void SixTest()
{
var result = NumberConverter.ConvertFromDecimal(6, NumberSystem.AToB_OneIndex);
result.Value.Should().Be("BB");
}
[Fact]
public void SevenTest()
{
var result = NumberConverter.ConvertFromDecimal(7, NumberSystem.AToB_OneIndex);
result.Value.Should().Be("AAA");
}
[Fact]
public void AlphabetTest()
{
var range = Enumerable.Range(1, 10).ToList();
for (int i = range.First(); i < range.Count; i++)
{
var alphaValue = NumberConverter.ConvertFromDecimal(i, NumberSystem.AToB_OneIndex);
Console.WriteLine($"{i,3} => {alphaValue}");
}
}
} |
5d39337259a3e0796eb3a0e02dcd4c1145496824 | C# | CurtisVonRubenhoff/Nightmares | /Assets/Scripts/MainMenu.cs | 2.65625 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour {
[SerializeField]
Image Veil;
[SerializeField]
Text Message;
private bool fadeIn = false;
private float counter = 0f;
public void StartGame() {
StartCoroutine(FadeAndStart());
}
private IEnumerator FadeAndStart() {
fadeIn = true;
Debug.Log("waiting");
yield return new WaitForSeconds(1);
Debug.Log("Done waiting");
SceneManager.LoadSceneAsync(1);
}
public void Update() {
if (fadeIn){
Debug.Log("doing something");
counter += Time.deltaTime;
var curTex = Message.color;
var curVeil = Veil.color;
Message.color = Color.Lerp(curTex, new Color(curTex.r, curTex.g, curTex.b, 1f), counter);
Veil.color = Color.Lerp(curVeil, new Color(curVeil.r, curVeil.g, curVeil.b, 1f), counter);
}
}
}
|
79dae7d6527672c86d8f220916444acab44e6343 | C# | MarSolMar/PCyP-2021 | /Ejercicio 1/Ejercicio 1/Triangulo.cs | 3.546875 | 4 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicio_1
{
class Triangulo
{
//Lado del triángulo
private int ladoT;
//Método constructor
public Triangulo()
{
Console.WriteLine("Ingrese el valor del lado del tritángulo:");
ladoT = int.Parse(Console.ReadLine());
}
// Método que calcula la altura del triángulo
public double alturaTriangulo()
{
double altura;
altura = Math.Sqrt(
(Math.Pow(ladoT, 2)) - (Math.Pow((ladoT / 2), 2))
);
return altura;
}
//Método que calcula el área de un triángulo
public double areaTriangulo()
{
double areaTriangulo;
areaTriangulo = (ladoT * alturaTriangulo()) / 2;
return areaTriangulo;
}
//Método que calcula el perímetro de un Triángulo
public double perimetroTriangulo()
{
double perimetroTriangulo;
perimetroTriangulo = ladoT * 3;
return perimetroTriangulo;
}
}
}
|
ddb0c04c936b4fd9f6fb2b7879abf048aa27b4d0 | C# | detachmode/Dexel | /Dexel/Dexel.Model/Common/Extensions.cs | 2.765625 | 3 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Dexel.Model.DataTypes;
namespace Dexel.Model.Common
{
public static class Extensions
{
public static bool IsDefinitionIn(this DataStream defintion, IEnumerable<DataStreamDefinition> enumerable)
{
return enumerable.Any(x => x.IsEquals(defintion));
}
public static bool IsEquals(this DataStreamDefinition def1, DataStreamDefinition def2)
{
return def1.DataNames == def2.DataNames && def1.ActionName == def2.ActionName;
}
public static bool IsEquals(this DataStreamDefinition def1, DataStream def2)
{
return def1.DataNames == def2.DataNames;
}
public static void WhenProperty(this PropertyChangedEventArgs propertyChangedEventArgs, string propname,
Action isPropertyAction)
{
if (propertyChangedEventArgs.PropertyName == propname)
{
isPropertyAction();
}
}
}
} |
236820c635ab1d20dff0589aef8f0fb8ad8df456 | C# | cfields93/GroupBlog | /Models/Data/BlogRepository.cs | 2.71875 | 3 | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity.Validation;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace GroupBlog.Models.Data
{
public class BlogRepository : ApplicationDbContext
{
ApplicationDbContext repo = new ApplicationDbContext();
public List<Blog> GetAll()
{
List<Blog> blogs = new List<Blog>();
foreach (var blog in repo.Blogs)
{
blogs.Add(blog);
}
return blogs;
//using (SqlConnection conn = new SqlConnection())
//{
// conn.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
// conn.Open();
// SqlCommand cmd = new SqlCommand();
// cmd.Connection = conn;
// cmd.CommandType = System.Data.CommandType.StoredProcedure;
// cmd.CommandText = "GetAll";
// using (SqlDataReader reader = cmd.ExecuteReader())
// {
// while (reader.Read())
// {
// Blog blog = new Blog();
// blog.Id = int.Parse(reader[0].ToString());
// blog.Title = reader[1].ToString();
// blog.Body = reader[2].ToString();
// blog.Date = DateTime.Parse(reader[3].ToString());
// blogs.Add(blog);
// }
// }
// return blogs;
}
public void Add(Blog blog)
{
blog.Date = DateTime.Now;
repo.Blogs.Add(blog);
repo.SaveChanges();
//using (SqlConnection conn = new SqlConnection())
//{
// conn.ConnectionString = ConfigurationManager.ConnectionStrings["GroupBlog"].ConnectionString;
// conn.Open();
// SqlCommand cmd = new SqlCommand();
// cmd.Connection = conn;
// cmd.CommandType = System.Data.CommandType.StoredProcedure;
// cmd.CommandText = "Create";
// cmd.Parameters.AddWithValue("@Title", blog.Title);
// cmd.Parameters.AddWithValue("@Body", blog.Body);
// cmd.Parameters.AddWithValue("@Date", blog.Date);
// cmd.ExecuteNonQuery();
//}
}
public void Delete(int id)
{
repo.Blogs.Remove(repo.Blogs.FirstOrDefault(b => b.Id == id));
repo.SaveChanges();
}
public void Update(Blog blog)
{
Blog found = repo.Blogs.FirstOrDefault(b => b.Id == blog.Id);
found.Approved = blog.Approved;
found.Title = blog.Title;
found.Body = blog.Body;
found.Date = DateTime.Now;
try
{
repo.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;
}
}
}
} |
c985af349d835543dcbd08e4c4b78e0e351e0579 | C# | Katarinich/BookLibrary | /Book-library/BookLibrary.ApiTest/RandomUserDraftGenerator.cs | 2.875 | 3 | using System;
namespace BookLibrary.Api
{
class RandomUserDraftGenerator : IUserDraftGenerator
{
public UserDraft GenerateUserDraft()
{
var userDraft = new UserDraft();
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const string charsForName = "abcdefghijklmnopqrstuvwxyz";
const string numericChars = "1234567890";
var start = new DateTime(1946, 1, 1);
var generator = new Generator();
userDraft.userName = generator.GenerateString(chars);
userDraft.firstName = generator.GenerateString(charsForName);
userDraft.firstName = char.ToUpper(userDraft.firstName[0]) + userDraft.firstName.Substring(1);
userDraft.lastName = generator.GenerateString(charsForName);
userDraft.lastName = char.ToUpper(userDraft.lastName[0]) + userDraft.lastName.Substring(1);
userDraft.email = userDraft.firstName.ToLower() + "." + userDraft.lastName.ToLower() + "@gmail.com";
userDraft.password = "123456";
userDraft.dateOfBirth = DateTime.Now.Subtract(generator.GenerateDate(start)).TotalSeconds.ToString();
userDraft.mobilePhone = "+" + generator.GenerateString(numericChars);
userDraft.country = generator.GenerateString(charsForName);
userDraft.country = char.ToUpper(userDraft.country[0]) + userDraft.country.Substring(1);
userDraft.state = generator.GenerateString(charsForName);
userDraft.state = char.ToUpper(userDraft.state[0]) + userDraft.state.Substring(1);
userDraft.city = generator.GenerateString(charsForName);
userDraft.city = char.ToUpper(userDraft.city[0]) + userDraft.city.Substring(1);
userDraft.addresLine = generator.GenerateString(chars);
userDraft.zipCode = generator.GenerateString(numericChars);
return userDraft;
}
}
}
|
3cae76860c7857873d6d837d377d68486ae868b2 | C# | jnavero/Taller1POO | /EjemploPOO/Coche.cs | 3.34375 | 3 | using System;
namespace EjemploPOO
{
//Ejemplo Estados de un coche.
//Heredamos de vehiculo
//En este ejemplo veremos, Herencia, Abstraccion, sobrecarga, sobreescritura y manejo de errores.
//Ejercicio propuesto:
//Modificar esta clase que permita meter varios coches (un array) y cada uno de esos coches tenga un estado (tipoEstado)
//Poder consultar el estado de cada uno de los coches mediante una funcion que liste dichos coches.
public class Coche : Vehiculo
{
public Coche()
{
Estado = TipoEstado.Parado;
}
public Coche(TipoEstado estado)
{
Estado = estado;
}
public override void Acelerar()
{
if (Estado != TipoEstado.Parado)
{
Estado = TipoEstado.Acelerando;
}
else
{
throw new CambioEstadoException("No puedes acelerar un coche que está parado");
}
}
public override void Arrancar()
{
if (Estado == TipoEstado.Parado)
{
Estado = TipoEstado.Arrancado;
}
else
{
throw new Exception("El coche ya está arrancado...");
}
}
public override void Frenar()
{
if (Estado != TipoEstado.Parado)
{
Estado = TipoEstado.Arrancado;
}
else
{
throw new Exception("El coche está parado...");
}
}
public override void Parar()
{
if (Estado != TipoEstado.Parado)
{
Estado = TipoEstado.Parado;
}
else
{
throw new Exception("El coche está parado...");
}
}
}
}
|
e6a5afc95e29b6ab022ee084da7b68970ced6a4e | C# | vitoresan/LibWebSystem | /Infraestrutura/Domain/Models/Sessao.cs | 2.578125 | 3 | namespace Infraestrutura.Domain.Models
{
using Infraestrutura.Domain.Interfaces;
using System;
using System.Data;
public class Sessao : ISessao
{
private IDbConnection _conexao;
private Int32 _timeout;
private IDbTransaction _transacao;
public IDbConnection Conexao { get { return _conexao; } }
public Int32 Timeout { get { return _timeout; } }
public IDbTransaction Transacao { get { return _transacao; } }
public Sessao(IDatabase database)
{
_conexao = database.Conexao;
}
public Sessao(IDatabase database, Int32 timeout)
{
_conexao = database.Conexao;
_timeout = timeout;
}
public void Begin(IsolationLevel isolation = IsolationLevel.ReadCommitted)
{
if (_conexao.State != ConnectionState.Open)
_conexao.Open();
_transacao = _conexao.BeginTransaction(isolation);
}
public void Commit()
{
_transacao.Commit();
_transacao = null;
}
public void Rollback()
{
_transacao.Rollback();
_transacao = null;
}
public void Close(IsolationLevel isolation = IsolationLevel.ReadCommitted)
{
if (_conexao.State != ConnectionState.Closed)
_conexao.Close();
}
public void Dispose()
{
if (_conexao.State != ConnectionState.Closed)
{
if (_transacao != null)
_transacao.Rollback();
_conexao.Close();
_conexao = null;
}
GC.SuppressFinalize(this);
}
}
}
|
da41457ce5e88b579274359962253b4347949443 | C# | Athos06/PongTest | /Assets/Scripts/GameManagement/TimerCountdown.cs | 2.6875 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System;
public class TimerCountdown : MonoBehaviour
{
public Action OnCountdownFinished;
private int countdownTime;
private int timerCurrentTime;
public int TimerCurrentTime { get { return timerCurrentTime; } }
private Coroutine timerCoroutine;
public void StartCountdown(Action<string> displayTimer, int timeSeconds)
{
countdownTime = timeSeconds;
timerCurrentTime = countdownTime;
timerCoroutine = StartCoroutine(CountdownCoroutine(displayTimer));
}
public void StartTimer(Action<string> displayTimer)
{
timerCoroutine = StartCoroutine(TimerCoroutine(displayTimer));
}
public void StopTimer()
{
if (timerCoroutine != null)
StopCoroutine(timerCoroutine);
}
private IEnumerator CountdownCoroutine(Action<string> displayTimer)
{
float countdown = countdownTime;
while(countdown >= 0)
{
countdown -= Time.deltaTime;
timerCurrentTime = (int)countdown;
displayTimer(TimeFormatHelper.GetTimeInFormat(timerCurrentTime));
yield return null;
}
if (OnCountdownFinished != null)
OnCountdownFinished.Invoke();
yield return null;
}
private IEnumerator TimerCoroutine(Action<string> displayTimer)
{
float countdown = 0;
while (countdown >= 0)
{
countdown += Time.deltaTime;
timerCurrentTime = (int)countdown;
displayTimer(TimeFormatHelper.GetTimeInFormat(timerCurrentTime));
yield return null;
}
if (OnCountdownFinished != null)
OnCountdownFinished.Invoke();
yield return null;
}
}
|
f4b4053921da25afd9d96db3474ed1f0e0761760 | C# | bubdm/Cinchoo | /src/ExtensioinMethods/ChoArrayEx.cs | 3.3125 | 3 | namespace System
{
#region NameSpaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#endregion NameSpaces
public static class ChoArrayEx
{
public static T GetNValue<T>(this T[] array, int index)
{
if (array == null) return default(T);
if (index < array.Length)
return array[index];
else
return default(T);
}
public static bool IsNullOrEmpty(this Array array)
{
return array == null || array.Length == 0;
}
public static void CheckIndex(this Array array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (index == 0 && array.Length == 0)
return;
if (index < 0 || (uint)index >= (uint)array.Length)
throw new ArgumentOutOfRangeException("index");
}
public static void CheckRange(this Array array, int idx, int count)
{
if (array == null)
throw new ArgumentNullException("array");
int size = array.Length;
if (idx < 0)
throw new ArgumentOutOfRangeException("index");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if ((uint)idx + (uint)count > (uint)size)
throw new ArgumentException("index and count exceed length of list");
}
public static T[] Join<T>(this T[] x, T[] y)
{
if (x == null || x.Length == 0)
return y;
else if (y == null || y.Length == 0)
return x;
else
{
var z = new T[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
return z;
}
}
}
}
|
bc0ee4337f0b19ecf4a96620be8b291c298d2721 | C# | StPeteFrank/VillageCharacters | /Controllers/VillageController.cs | 2.5625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using villagecharacters.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace villagecharacters.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class VillageController : ControllerBase
{
private DatabaseContext db;
public VillageController()
{
this.db = new DatabaseContext();
}
[HttpGet]
public ActionResult<List<Village>> GetAllVillages()
{
var results = this.db.Village;
return results.ToList();
}
[HttpPost]
public ActionResult<Village> Post([FromBody] Village newVillage)
{
this.db.Village.Add(newVillage);
this.db.SaveChanges();
return newVillage;
}
[HttpPut]
public ActionResult<Village> Put([FromBody] Village updateVillage)
{
this.db.Village.Update(updateVillage);
this.db.SaveChanges();
return updateVillage;
}
[HttpDelete]
public ActionResult<Village> Delete([FromBody] Village deleteVillage)
{
this.db.Village.Remove(deleteVillage);
this.db.SaveChanges();
return deleteVillage;
}
}
} |