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
|
|---|---|---|---|---|---|---|
d71949ec1a28ef632eed014d0b8a9d300ae4e285
|
C#
|
Skvorecz/Colors
|
/Colors/Scheme.cs
| 3.171875
| 3
|
using System.Windows.Forms;
using System.Drawing;
namespace Colors
{
abstract class Scheme
{
protected ColorCircle colorCircle;
public abstract void Paint(PaintEventArgs e, Form form, params Color[] colors);
public abstract Point[] PointersPositions(Point basePoint);
public Scheme(ColorCircle colorCircle)
{
this.colorCircle = colorCircle;
}
protected static void PaintHalves(PaintEventArgs e, Form form, params Color[] colors)
{
e.Graphics.FillRectangle(new SolidBrush(colors[0]), 0, 0, form.Width / 2, form.Height);
e.Graphics.FillRectangle(new SolidBrush(colors[1]), form.Width / 2, 0, form.Width / 2, form.Height);
}
protected static void PaintThirds(PaintEventArgs e, Form form, params Color[] colors)
{
Point center = new Point(form.Width / 2, form.Height / 2);
Point topLeft = new Point(0, 0);
Point topRight = new Point(form.Width, 0);
Point bottomLeft = new Point(0, form.Height);
Point bottomRight = new Point(form.Width, form.Height);
Point bottomCenter = new Point(form.Width / 2, form.Height);
e.Graphics.FillPolygon(new SolidBrush(colors[0]), new Point[] { topLeft, topRight, center });
e.Graphics.FillPolygon(new SolidBrush(colors[1]), new Point[] { topLeft, center, bottomCenter, bottomLeft });
e.Graphics.FillPolygon(new SolidBrush(colors[2]), new Point[] { bottomCenter, center, topRight, bottomRight });
}
}
}
|
d5df4b29d9e3d1f273eccdb0df28d5fdcdc4ebce
|
C#
|
BladeScar/TestingSystemFinal
|
/TestingSystem/ViewModel/TeacherViewModel.cs
| 2.953125
| 3
|
using System.Collections.Generic;
using TestingSystem.Model;
namespace TestingSystem.ViewModel
{
public class TeacherViewModel
{
public enum EQuestionState
{
eNew,
ePresent,
eInvalid
}
public TeacherViewModel()
{
}
public EQuestionState AddNewQuestion(string question, List<string> answers, int currentTeacherId)
{
using (var ctx = new TestSystemDbContext())
{
Teacher currentTeacher = null;
foreach (var teacher in ctx.Teachers)
{
if (teacher.Id == currentTeacherId)
{
currentTeacher = teacher;
}
}
foreach (var entry in ctx.QuizEntries)
{
if (question == entry.Question && currentTeacher.Id == entry.TeacherId)
{
return EQuestionState.ePresent;
}
}
var newEntry = new QuizEntry();
newEntry.Question = question;
foreach (var ans in answers)
{
var newAns = new Answer();
newAns.Content = ans;
newEntry.Answers.Add(newAns);
}
newEntry.TeacherId = currentTeacher.Id;
newEntry.Teacher = currentTeacher;
ctx.QuizEntries.Add(newEntry);
ctx.SaveChanges();
}
return EQuestionState.eNew;
}
}
}
|
cd0524338195efbe9b56dfd758bd1ac09fd377a4
|
C#
|
tedigor/avaliacao-p2-dotnet
|
/ApiDeGastosMensais.API/Controllers/GastoControler.cs
| 2.59375
| 3
|
using ApiDeGastosMensais.DATA;
using ApiDeGastosMensais.DATA.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiDeGastosMensais.API.Controllers
{
[Route("api/gasto")]
[ApiController]
public class GastoControler: ControllerBase
{
private readonly DataContext _context;
public GastoControler(DataContext context)
{
_context = context;
}
[HttpGet]
public ActionResult<List<Gasto>> GetAll()
{
return _context.Gasto.ToList();
}
[HttpGet("{id}")]
public ActionResult<Gasto> GetById(int id)
{
return _context.Gasto.Find(id);
}
[HttpPost]
public ActionResult<Gasto> Create([FromBody] Gasto gasto)
{
_context.Gasto.Add(gasto);
_context.SaveChanges();
return gasto;
}
[HttpPut]
public ActionResult<Gasto> Update([FromBody] Gasto gasto)
{
_context.Entry(gasto).State = EntityState.Modified;
_context.SaveChanges();
return gasto;
}
[HttpDelete("{id}")]
public void Delete(int id)
{
Gasto gasto = _context.Gasto.Find(id);
_context.Gasto.Remove(gasto);
_context.SaveChanges();
}
}
}
|
6d85577abd4eb6bb9216476e2dbebdd7588f6d64
|
C#
|
gitlinhleqtgh/C
|
/C#/Delegate/Logs.cs
| 3.0625
| 3
|
using System;
namespace Delegate
{
public class Logs{
public delegate void ShowLog(string message);
static public void Info(string s){
Console.ForegroundColor=ConsoleColor.Green;
Console.WriteLine(string.Format("Info: {0}",s));
Console.ResetColor();
}
static public void Warning(string s){
Console.ForegroundColor=ConsoleColor.Red;
Console.WriteLine(string.Format("Warning {0}",s));
Console.ResetColor();
}
public static void TestShowLog()
{
ShowLog showLog;
showLog=Info;
showLog("Thong bao !");
showLog=Warning;
showLog("Warning !");
}
}
}
|
a8ee7b148fc56a114524835c66068fbcced14344
|
C#
|
jclarkGRC/aspwebformcatwords
|
/WebFormsHelloWorld/Game.aspx.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsHelloWorld
{
public partial class Game : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
object savedCategory = Session["currentCategory"];
currentCategory.Text = savedCategory.ToString();
if (!IsPostBack)
{
Session["Timer"] = DateTime.Now.AddSeconds(30).ToString();
}
// Page.ClientScript.RegisterStartupScript(this.GetType(), "JsFunc", "alert('hello world');", true);
}
protected void CountSeconds_Tick(object sender, EventArgs e)
{
if(DateTime.Compare(DateTime.Now, DateTime.Parse(Session["Timer"].ToString())) < 0)
{
msg.Text = "Time Left: " + (((Int32)DateTime.Parse(Session["Timer"].ToString()).Subtract(DateTime.Now).TotalSeconds)%60).ToString() + " Seconds";
}
if(msg.Text == "Time Left: 0 Seconds")
{
Response.Redirect("Scores.aspx");
}
}
protected void Save_Word(object sender, EventArgs e)
{
// Get the current word from the text field
string currentWord = CurrentWord.Text;
// Update the label text with the starting letter
SavedWord.Text = "Enter a word that starts with: "
+ Get_Last_Letter_Of_Word(currentWord);
// Push the word to the used words list
usedWords.Items.Insert(0 ,currentWord);
// clear the text field after submission
CurrentWord.Text = "";
//Reset the timer after entering a word
Session["Timer"] = DateTime.Now.AddSeconds(30).ToString();
}
protected char Get_Last_Letter_Of_Word(string word)
{
char lastLetter = word[word.Length - 1];
lastLetter = char.ToUpper(lastLetter);
return lastLetter;
}
}
}
|
549ff0ddfc1453ca9a0f860e18afd1d96d36c494
|
C#
|
sm-valery/gTravel
|
/WebApplication1/helpers.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace gTravel
{
public class helpers
{
public static MvcHtmlString ContractStatus(gTravel.Models.Status s)
{
string sbody = "";
switch (s.Code.Trim())
{
case "project":
sbody += string.Format("<span class=\"label label-default\">Статус: {0} </span>", s.Name);
break;
case "confirmed":
sbody += string.Format("<span class=\"label label-primary\">Статус: {0} </span>", s.Name);
break;
case "bordero":
sbody += string.Format("<span class=\"label label-success\">Статус: {0} </span>", s.Name);
break;
}
return MvcHtmlString.Create(sbody);
}
public static MvcHtmlString BuildCond(int idx, gTravel.Models.ContractCondition cond)
{
StringBuilder sbody = new StringBuilder();
sbody.AppendFormat("<input type=\"hidden\" name=\"ContractConditions[{0}].ContractCondId\" value=\"{1}\">", idx, cond.ContractCondId);
sbody.AppendFormat("<input type=\"hidden\" name=\"ContractConditions[{0}].ConditionId\" value=\"{1}\">", idx, cond.ConditionId.Value);
sbody.AppendFormat("<input type=\"hidden\" name=\"ContractConditions[{0}].Contractid\" value=\"{1}\">", idx, cond.Contractid);
sbody.AppendFormat("<input type=\"hidden\" name=\"ContractConditions[{0}].num\" value=\"{1}\">", idx, cond.num);
sbody.AppendFormat("<input type=\"hidden\" name=\"ContractConditions[{0}].link_text\" value=\"{1}\">", idx, cond.link_text);
sbody.AppendFormat("<input type=\"hidden\" name=\"ContractConditions[{0}].Val_id\" value=\"{1}\">", idx, cond.Val_id);
switch (cond.Condition.Type)
{
case "L":
sbody.AppendFormat("<div class=\"checkbox\"><label><input {1} type=\"checkbox\" name=\"ContractConditions[{0}].Val_c\"> {2}</label></div>",
idx,
(cond.Val_c=="on") ? "checked" : "",
cond.Condition.Name);
break;
case "C":
sbody.AppendFormat("<div class=\"row\"> <div class=\"col-md-2\"> <label>{2}:</label> </div> <div class=\"col-md-10\">" +
"<input type=\"text\" name=\"ContractConditions[{0}].Val_c\" value=\"{1}\" {3} class=\"form-control input-sm input-value\" >",
idx,
cond.Val_c,
(string.IsNullOrEmpty(cond.link_text)) ? cond.Condition.Name : string.Format("<a href='{0}'>{1}</a>", cond.link_text, cond.Condition.Name)
,(cond.Val_id!=null)?"readonly":""
);
if(!string.IsNullOrEmpty( cond.link_text))
{
sbody.AppendFormat(" <a href='{0}' title='Перейти'><span class='glyphicon glyphicon-share'></span></a>", cond.link_text);
}
sbody.Append("</div> </div>");
break;
case "S":
sbody.AppendFormat("<div class=\"row\"><div class=\"col-md-2\"><label>{2}:</label></div><div class=\"col-md-10\">" +
"<textarea name =\"ContractConditions[{0}].Val_c\" class=\"form-control input-sm input-value\" style = \"width:300px;\">{1}</textarea> </div> </div>",
idx,
cond.Val_c,
cond.Condition.Name);
break;
}
return MvcHtmlString.Create(sbody.ToString());
}
}
}
|
0aec6c56f3f3972fc8421fe2fa31861bac7d1c04
|
C#
|
mkalkere/MoreLINQ
|
/MoreLinq/MaxBy.cs
| 2.796875
| 3
|
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. All rights reserved.
//
// 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.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
static partial class MoreEnumerable
{
/// <summary>
/// Returns the maximal elements of the given sequence, based on
/// the given projection.
/// </summary>
/// <remarks>
/// This overload uses the default comparer for the projected type.
/// This operator uses deferred execution. The results are evaluated
/// and cached on first use to returned sequence.
/// </remarks>
/// <typeparam name="TSource">Type of the source sequence</typeparam>
/// <typeparam name="TKey">Type of the projected element</typeparam>
/// <param name="source">Source sequence</param>
/// <param name="selector">Selector to use to pick the results to compare</param>
/// <returns>The maximal element, according to the projection.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null</exception>
/// <exception cref="InvalidOperationException"><paramref name="source"/> is empty</exception>
public static IEnumerable<TSource> MaxBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> selector)
{
return source.MaxBy(selector, null);
}
/// <summary>
/// Returns the maximal elements of the given sequence, based on
/// the given projection and the specified comparer for projected values.
/// </summary>
/// <remarks>
/// This operator uses deferred execution. The results are evaluated
/// and cached on first use to returned sequence.
/// </remarks>
/// <typeparam name="TSource">Type of the source sequence</typeparam>
/// <typeparam name="TKey">Type of the projected element</typeparam>
/// <param name="source">Source sequence</param>
/// <param name="selector">Selector to use to pick the results to compare</param>
/// <param name="comparer">Comparer to use to compare projected values</param>
/// <returns>The maximal element, according to the projection.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/>, <paramref name="selector"/>
/// or <paramref name="comparer"/> is null</exception>
/// <exception cref="InvalidOperationException"><paramref name="source"/> is empty</exception>
public static IEnumerable<TSource> MaxBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> selector, IComparer<TKey> comparer)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (selector == null) throw new ArgumentNullException(nameof(selector));
comparer = comparer ?? Comparer<TKey>.Default;
return ExtremaBy(source, selector, (x, y) => comparer.Compare(x, y));
}
// > In mathematical analysis, the maxima and minima (the respective
// > plurals of maximum and minimum) of a function, known collectively
// > as extrema (the plural of extremum), ...
// >
// > - https://en.wikipedia.org/wiki/Maxima_and_minima
static IEnumerable<TSource> ExtremaBy<TSource, TKey>(IEnumerable<TSource> source,
Func<TSource, TKey> selector, Func<TKey, TKey, int> comparer)
{
foreach (var item in Extrema())
yield return item;
IEnumerable<TSource> Extrema()
{
using (var e = source.GetEnumerator())
{
if (!e.MoveNext())
return new List<TSource>();
var extrema = new List<TSource> { e.Current };
var extremaKey = selector(e.Current);
while (e.MoveNext())
{
var item = e.Current;
var key = selector(item);
var comparison = comparer(key, extremaKey);
if (comparison > 0)
{
extrema = new List<TSource> { item };
extremaKey = key;
}
else if (comparison == 0)
{
extrema.Add(item);
}
}
return extrema;
}
}
}
}
}
|
ca93702eb5238e3991707cd4278a5c02b15e358e
|
C#
|
SeeminglyScience/PSValueWildcard
|
/src/PSValueWildcard/WildcardInstruction.cs
| 2.96875
| 3
|
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace PSValueWildcard
{
[DebuggerDisplay("{GetDebuggerDisplayString()}")]
internal readonly struct WildcardInstruction : IEquatable<WildcardInstruction>
{
public static readonly WildcardInstruction AnyAny = new WildcardInstruction(WildcardStepKind.AnyAny, default);
public static readonly WildcardInstruction AnyOne = new WildcardInstruction(WildcardStepKind.AnyOne, default);
public readonly WildcardStepKind Kind;
internal readonly StringPart Args;
private WildcardInstruction(WildcardStepKind kind, StringPart arguments)
{
Kind = kind;
Args = arguments;
}
public readonly ReadOnlySpan<char> Arguments => Args.AsSpan();
internal static WildcardInstruction AnyOf(StringPart arguments, bool isPartial = false)
=> new WildcardInstruction(
isPartial ? WildcardStepKind.PartialAnyOf : WildcardStepKind.AnyOf,
arguments);
internal static WildcardInstruction PartialAnyOf(StringPart arguments)
=> new WildcardInstruction(WildcardStepKind.PartialAnyOf, arguments);
internal static WildcardInstruction Exact(StringPart arguments)
=> new WildcardInstruction(WildcardStepKind.Exact, arguments);
public static bool operator ==(WildcardInstruction left, WildcardInstruction right) => left.Equals(right);
public static bool operator !=(WildcardInstruction left, WildcardInstruction right) => !left.Equals(right);
public readonly bool TryGetLength(out int length)
{
length = Kind switch
{
WildcardStepKind.AnyOf => 1,
WildcardStepKind.AnyOne => 1,
WildcardStepKind.Exact => Args.Length,
_ => -1,
};
return length != -1;
}
public readonly bool Equals(WildcardInstruction other)
{
return Kind == other.Kind && Args.SequenceEqual(other.Args);
}
public override bool Equals(object? obj) => obj is WildcardInstruction other && Equals(other);
public override int GetHashCode() => HashCodes.Combine(Kind, Args);
#if DEBUG
[ExcludeFromCodeCoverage]
private string GetDebuggerDisplayString()
{
return Kind switch
{
WildcardStepKind.AnyAny => "*",
WildcardStepKind.AnyOne => "?",
WildcardStepKind.AnyOf => string.Format("AO: {0}", Args.ToString()),
WildcardStepKind.PartialAnyOf => string.Format("PAO: {0}", Args.ToString()),
WildcardStepKind.Exact => string.Format("E: {0}", Args.ToString()),
_ => string.Empty,
};
}
#endif
}
}
|
c8bb942a6cda2e1c20630e0535db26fcc72e962b
|
C#
|
NGPONG/code
|
/csharp/c#学习-01/test/Student.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Student:Person
{
private string hobby;
public string Hobby
{
get { return hobby; }
set { hobby = value; }
}
public void SayHello()
{
Console.WriteLine("大家好,我叫{0},我今年{1}岁了,爱好是{2}",Name,Age,Hobby);
}
}
}
|
eaaf894b9e139b7eaa0f6a2b9643b4c7f30febef
|
C#
|
MaryArt/Meteor
|
/DalFake/ExpeditionRepository.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
namespace DalFake
{
public class ExpeditionRepository
{
private MyContext _myContext;
public ExpeditionRepository(MyContext context)
{
_myContext = context;
}
public IEnumerable<Expedition> GetAll()
{
return _myContext.Expeditions;
}
public Expedition Get(int id)
{
return _myContext.Expeditions.Find(m => m.Id == id);
}
public void Create(Expedition expedition)
{
_myContext.Expeditions.Add(expedition);
}
public void Update(Expedition expedition)
{
var i = _myContext.Expeditions.IndexOf(_myContext.Expeditions.First(m => m.Id == expedition.Id));
_myContext.Expeditions[i] = expedition;
}
public IEnumerable<Expedition> Find(Func<Expedition, bool> predicate)
{
return _myContext.Expeditions.Where(predicate).ToList();
}
public void Delete(int id)
{
var expedition = _myContext.Expeditions.Find(m => m.Id == id);
if (expedition == null) return;
_myContext.Expeditions.Remove(expedition);
}
}
}
|
0344dda1e959d1c41cb683525e726f10b1e4d2c0
|
C#
|
huynxtb/C-Sharp-Projects
|
/SimpleCsharp/SimpleCsharp/Manager.cs
| 3.453125
| 3
|
using java.lang;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace SimpleCsharp
{
class Manager
{
public void calculatorTwoDigt()
{
double sum = 0;
Console.WriteLine("Nhập số a: ");
double a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Nhập số b: ");
double b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Tổng {0} + {1} = {2}", a, b, (a + b));
Console.WriteLine();
}
public void checkIsLeapYear()
{
Console.WriteLine("Nhập năm muốn kiểm tra : ");
int year = Convert.ToInt32(Console.ReadLine());
if (DateTime.IsLeapYear(year))
{
Console.WriteLine("{0} là năm nhuận ", year);
}
else
{
Console.WriteLine("{0} không phải là năm nhuận ", year);
}
Console.WriteLine();
}
public void calculatorSumS()
{
Console.WriteLine("Nhập số tự nhiên n > 0:");
int n = Convert.ToInt32(Console.ReadLine());
double sum = 0;
for (int i = 1; i <= n; i++)
{
sum += 1 / (double)i;
}
Console.WriteLine("Tổng S= {0}", sum);
Console.WriteLine();
}
public void gameRandomNumber()
{
Random random = new Random();
int com = random.Next(0, 100);
int human, count = 3;
bool flag = true;
Console.WriteLine("COM: {0}", com);
Console.WriteLine("Máy tính đã chọn ra 1 số ngẫu nhiên từ 0 -> 100 ( Bạn có 3 lần đoán )");
Console.WriteLine("Xin mời đoán: ");
while (true)
{
human = Convert.ToInt32(Console.ReadLine());
count--;
if (human > 100 || human < 0)
{
Console.WriteLine("Số chỉ nằm trong khoảng 0 -> 100", com);
flag = false;
}
if (human > com)
{
Console.WriteLine("Số của bạn lớn hơn số máy", com);
flag = false;
}
else if(human < com)
{
Console.WriteLine("Số của bạn nhỏ hơn số máy", com);
flag = false;
}
else if (human == com)
{
Console.WriteLine("Chúc mừng bạn đã đoán trúng, Số của máy là {0}", com);
Console.WriteLine();
flag = true;
return;
}
if (!flag)
{
Console.WriteLine("Bạn đã đoán sai!");
Console.WriteLine("Bạn còn {0} lần đoán.", count);
Console.WriteLine();
if (count == 0)
{
Console.WriteLine("Bạn đã thua!");
Console.WriteLine("Số của máy là {0}", com);
Console.WriteLine();
return;
}
}
}
Console.WriteLine();
}
public void processString()
{
int chu_hoa = 0, chu_thuong = 0, so = 0, khoang_trang = 0;
Console.WriteLine("Mời bạn nhập chuỗi: ");
string text = Convert.ToString(Console.ReadLine());
khoang_trang = text.Count(Char.IsWhiteSpace);
string[] list_string = text.Split(',', ' ');
foreach (string s in list_string)
{
if (Regex.IsMatch(s, @"^\d+$")) so++;
if (!s.Any(char.IsUpper) && !Regex.IsMatch(s, @"^\d+$")) chu_thuong++;
if (s.Any(char.IsUpper)) chu_hoa++;
}
Console.WriteLine("Chuỗi của bạn có {0} chữ hoa", chu_hoa);
Console.WriteLine("Chuỗi của bạn có {0} chữ thường", chu_thuong);
Console.WriteLine("Chuỗi của bạn có {0} chữ số", so);
Console.WriteLine("Chuỗi của bạn có {0} khoảng trắng", khoang_trang);
Console.WriteLine();
}
public void chooseCalculation()
{
double a, b;
double result = 0;
char op;
bool flag = true;
Console.WriteLine("Nhập số a: ");
a = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Nhập số b: ");
b = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Nhập phép tính bạn muốn thực hiện ( +, -, *, / ): ");
op = Convert.ToChar(Console.ReadLine());
switch (op)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
if (b == 0)
{
Console.WriteLine("Không thể thực hiện phép chia cho 0");
Console.WriteLine();
flag = false;
break;
}
else
result = a / b;
break;
default:
Console.WriteLine("Phép tính không hợp lệ");
flag = false;
Console.WriteLine();
break;
}
if (flag)
Console.WriteLine("Kết quả của phép tính {0} {1} {2} = {3} ", a, op, b, result);
Console.WriteLine();
}
public void ptb2()
{
double a, b, c;
double delta = 0;
Console.WriteLine("Nhập tham số a: ");
a = Convert.ToDouble(Console.ReadLine());
if (a == 0)
{
Console.WriteLine("Phương trình của bạn sẽ có dạng ax+b=0");
}
Console.WriteLine("Nhập tham số b: ");
b = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Nhập tham số c: ");
c = Convert.ToDouble(Console.ReadLine());
if (a == 0)
{
if (b == 0)
{
if (c == 0)
{
Console.WriteLine("Phương trình của bạn sẽ có dạng 0=0 => PT vô số nghiệm");
Console.WriteLine();
}
else
{
Console.WriteLine("PT {0}x + {1} = 0 vô nghiệm", b, c);
Console.WriteLine();
}
}
else
{
Console.WriteLine("PT {0}x + {1} = 0 có 1 nghiệm x = {2}", b, c, (-b / a));
Console.WriteLine();
}
}
else
{
delta = System.Math.Pow(b, 2) - 4 * a * c;
if (delta < 0)
{
Console.WriteLine("PT {0}x^2 + {1}x + {2} = 0 vô nghiệm", a, b, c);
Console.WriteLine();
}
else if (delta == 0)
{
Console.WriteLine("PT {0}x^2 + {1}x + {2} = 0 có 1 nghiệm duy nhất x = {3}", a, b, c, (-b / (2 * a)));
Console.WriteLine();
}
else
{
Console.WriteLine("PT {0}x^2 + {1}x + {2} = 0 có 2 nghiệm phân biệt x1 = {3}, x2 = {4}",
a, b, c, ((-b + System.Math.Sqrt(delta)) / (2 * a)), ((-b - System.Math.Sqrt(delta)) / (2 * a)));
Console.WriteLine();
}
}
}
public int menu()
{
int choice;
Console.WriteLine("1. Tính tổng 2 số nguyên");
Console.WriteLine("2. Kiểm tra năm nhuận");
Console.WriteLine("3. Tính tổng S=1+1/2+1/3+..+1/n");
Console.WriteLine("4. Thực hiện phép toán được chỉ định cho 2 số");
Console.WriteLine("5. Tính phương trình bậc 2");
Console.WriteLine("6. Đếm số lượng chữ hoa, thường, số, khoảng trắng");
Console.WriteLine("7. Game đoán số từ 0 đến 100");
Console.WriteLine("8. Tính Sum = 1 + 2 + 3 +...+ n");
Console.WriteLine("0. Thoát");
Console.WriteLine("Lựa chọn chức năng của chương trình:");
choice = checkInputLimit(0, 7);
Console.WriteLine();
return choice;
}
public int checkInputLimit(int min, int max)
{
while (true)
{
try
{
int result = Convert.ToInt32(Console.ReadLine());
if (result < min || result > max)
{
Console.WriteLine("Hãy nhập số trong khoảng {0}-{1}", min, max);
Console.WriteLine();
}
return result;
}
catch (System.Exception e)
{
Console.WriteLine("Hãy nhập số trong khoảng {0}-{1}", min, max);
Console.WriteLine();
}
}
}
public double checkInputDouble(string message)
{
while (true)
{
try
{
Console.WriteLine(message);
double result = Convert.ToDouble(Console.ReadLine());
if (result < 0)
{
throw new NumberFormatException();
}
return result;
}
catch (System.Exception e)
{
}
}
}
//public int checkInputInt()
//{
// try
// {
// }
// catch (Exception)
// {
// throw;
// }
//}
public int sum(int n)
{
int s = 0;
for (int i = 0; i < n; i++)
{
s += i;
}
return s;
}
}
}
|
2f4d07bfd395cdff23f03241211bf86335887d67
|
C#
|
hxmtl/Visio-Power-Tools
|
/VisioPowerTools2010/VisioPowerTools2010/SimpleHTML5Writer.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Xml;
using VA=VisioAutomation;
using IVisio = Microsoft.Office.Interop.Visio;
namespace VisioPowerTools2010
{
public class SimpleHtml5Writer : IDisposable
{
protected XmlWriter _xw;
private readonly Stack<string> _element_stack;
public SimpleHtml5Writer(XmlWriter xmlwriter)
{
if (xmlwriter == null)
{
throw new ArgumentNullException("xmlwriter");
}
this._xw = xmlwriter;
this._element_stack = new Stack<string>();
}
public SimpleHtml5Writer(string filename)
{
if (filename == null)
{
throw new ArgumentNullException("filename");
}
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
this._xw = XmlWriter.Create(filename, settings);
this._element_stack = new Stack<string>();
}
public void DocType(string s)
{
string pubid = null;
string sysid = null;
string subset = null;
this._xw.WriteDocType(s,pubid,sysid,subset);
}
public void Start(string s)
{
this._xw.WriteStartElement(s);
this._element_stack.Push(s);
}
public void End(string s)
{
if (this._element_stack.Count < 1)
{
string msg = string.Format("No matching starting element for <{0}>", s);
throw new ArgumentException(msg, "s");
}
string ontop = this._element_stack.Pop();
if (ontop != s)
{
string msg = string.Format("Cannot end element <{0}>, expected to end <{1}>", s, ontop);
throw new ArgumentException(msg);
}
this._xw.WriteEndElement();
}
public void Element(string name, string s)
{
this._xw.WriteElementString(name, s);
}
public void Attribute(string name, string s)
{
this._xw.WriteAttributeString(name, s);
}
public void Text(string s)
{
this._xw.WriteString(s);
}
public void AttributeIfNotNull(string name, string s)
{
if (s != null)
{
this._xw.WriteAttributeString(name, s);
}
}
public void Close()
{
this._xw.Close();
}
public void Dispose()
{
this.Close();
}
}
}
|
0cf157ce8f52f26e7ced0b8102c32668fba897ba
|
C#
|
za-webdev/CSharp-Programmimg
|
/Example/Example/Program.cs
| 3.6875
| 4
|
using System;
using Example.Math;
namespace Example
{
public enum Gender
{
male,
female,
unknown
}
class Person {
public string firstname;
public string lastname;
public Gender gender;
public bool isAlive;
public void introduce()
{
var live = (isAlive) ? "alive" : "not alive";
Console.WriteLine(string.Format("Name is {0} {1} and gender is {2} and is {3}",firstname,lastname,gender,live));
}
}
class Program
{
static void Main(string[] args)
{
var me = new Person();
me.firstname = "zoya";
me.lastname = "ali";
me.isAlive = true;
me.gender = Gender.female;
me.introduce();
}
}
}
|
a7c3548bc36fa5b49e3db25579b9e68db555723f
|
C#
|
JanDotNet/ThinkSharp.Licensing
|
/ThinkSharp.Licensing/CheckSum.cs
| 3.28125
| 3
|
// Copyright (c) Jan-Niklas Schäfer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
namespace ThinkSharp.Licensing
{
/// <summary>
/// Class for creating check sum for an array of bytes.
/// </summary>
public class CheckSum
{
private readonly char[] myValidCharacters;
private readonly int myLenght;
/// <summary>
/// Creates a new instance of the class.
/// </summary>
/// <param name="supportedCharacters">
/// List of supported characters for the check sum.
/// </param>
/// <param name="length">
/// The lenght of the check sum.
/// </param>
public CheckSum(char[] supportedCharacters, int length)
{
if (supportedCharacters == null)
throw new ArgumentNullException(nameof(supportedCharacters));
if (supportedCharacters.Length == 0)
throw new ArgumentException(nameof(supportedCharacters));
if (length <= 0)
throw new ArgumentException(nameof(length));
myValidCharacters = supportedCharacters.Distinct().ToArray();
myLenght = length;
}
/// <summary>
/// Creates a new instance of the class.
/// Check sum consists of the characters [A-Z] and [0-9].
/// </summary>
/// <param name="length">
/// The length of the check sum.
/// </param>
public CheckSum(int length)
: this(Constants.ValidCharacters.ToCharArray(), length)
{ }
/// <summary>
/// Gets the length of the check sum.
/// </summary>
public int Length => myLenght;
/// <summary>
/// Creates the check sum for the specified byte array.
/// </summary>
/// <param name="bytes">
/// The byte array to create the check sum for.
/// </param>
/// <returns>
/// A string that represents the check sum of the specified byte array.
/// </returns>
public string Create(byte[] bytes)
{
bytes = AdjustSize(bytes, myLenght);
var checkSum = bytes.Select(ToCheckSumChar).ToArray();
return new string(checkSum);
}
private char ToCheckSumChar(byte b)
{
return myValidCharacters[b % myValidCharacters.Length];
}
private static byte[] AdjustSize(byte[] bytes, int length)
{
if (bytes.Length > length)
return ReduceSize(bytes, length);
if (bytes.Length < length)
return InflateSize(bytes, length);
return bytes;
}
private static byte[] InflateSize(byte[] bytes, int length)
{
var result = new byte[length];
for (int i = 0; i < length; i++)
result[i] ^= bytes[i % bytes.Length];
return result;
}
private static byte[] ReduceSize(byte[] bytes, int length)
{
var result = new byte[length];
for (int i = 0; i < bytes.Length; i++)
result[i % length] ^= bytes[i];
return result;
}
}
}
|
5e1efc17f79813781cc912e977910a8a585c4aeb
|
C#
|
AlexanderPro/Utilities
|
/Utilities.Tests/Extensions/ObjectExtensionsTests.cs
| 2.609375
| 3
|
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Utilities.Extensions;
namespace Utilities.Tests.Extensions
{
[TestClass]
public class ObjectExtensionsTests
{
[TestMethod]
public void TestObjectIsNull()
{
Object obj1 = (String)null;
Object obj2 = (StringBuilder)null;
Object obj3 = null;
Object obj4 = new List<String>();
Object obj5 = DBNull.Value;
Assert.IsTrue(obj1.IsNull());
Assert.IsTrue(obj2.IsNull());
Assert.IsTrue(obj3.IsNull());
Assert.IsFalse(obj4.IsNull());
Assert.IsFalse(obj5.IsNull());
}
[TestMethod]
public void TestObjectIsNotNull()
{
Object obj1 = (String)null;
Object obj2 = (StringBuilder)null;
Object obj3 = null;
Object obj4 = new List<String>();
Object obj5 = DBNull.Value;
Assert.IsFalse(obj1.IsNotNull());
Assert.IsFalse(obj2.IsNotNull());
Assert.IsFalse(obj3.IsNotNull());
Assert.IsTrue(obj4.IsNotNull());
Assert.IsTrue(obj5.IsNotNull());
}
[TestMethod]
public void TestObjectIsNullOrDbNull()
{
Object obj1 = (String)null;
Object obj2 = (StringBuilder)null;
Object obj3 = null;
Object obj4 = new List<String>();
Object obj5 = DBNull.Value;
Assert.IsTrue(obj1.IsNullOrDBNull());
Assert.IsTrue(obj2.IsNullOrDBNull());
Assert.IsTrue(obj3.IsNullOrDBNull());
Assert.IsFalse(obj4.IsNullOrDBNull());
Assert.IsTrue(obj5.IsNullOrDBNull());
}
[TestMethod]
public void TestObjectIsNotNullOrDbNull()
{
Object obj1 = (String)null;
Object obj2 = (StringBuilder)null;
Object obj3 = null;
Object obj4 = new List<String>();
Object obj5 = DBNull.Value;
Assert.IsFalse(obj1.IsNotNullOrNotDBNull());
Assert.IsFalse(obj2.IsNotNullOrNotDBNull());
Assert.IsFalse(obj3.IsNotNullOrNotDBNull());
Assert.IsTrue(obj4.IsNotNullOrNotDBNull());
Assert.IsFalse(obj5.IsNotNullOrNotDBNull());
}
[TestMethod]
public void ConvertObjectToAnotherType()
{
Decimal obj1 = 5m;
Double obj2 = 5f;
Assert.AreEqual(5, obj1.ConvertTo<Decimal, Int32>());
Assert.AreEqual(5, obj2.ConvertTo<Double, Int32>());
}
[TestMethod]
public void ConvertObjectToNullableType()
{
Object source1 = null;
Object source2 = DBNull.Value;
Int32? result1 = null;
Assert.AreEqual(result1, source1.ConvertTo<Int32>());
Assert.AreEqual(result1, source2.ConvertTo<Int32>());
}
}
}
|
c9abd325afcd021b74295897f338f7c005ee4af2
|
C#
|
rakibj/SideScroller-CodeExample-Rakib
|
/Assets/_Project/Scripts/Platform/RandomBackgroundSelector.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
namespace _Project.Scripts.Platform
{
public class RandomBackgroundSelector : MonoBehaviour, IRandomSelector
{
[SerializeField] private List<Sprite> backgroundObjects;
private SpriteRenderer m_spriteRenderer;
private void Awake()
{
m_spriteRenderer = GetComponent<SpriteRenderer>();
Initialize();
}
public void Initialize()
{
//Randomly decide if there should be any backgroundObject here
if (Random.Range(0f, 1f) > .8f)
return;
//Randomly select which one should appear
m_spriteRenderer.sprite = backgroundObjects[Random.Range(0, backgroundObjects.Count)];
}
}
}
|
12e0d108a6f8c604fe88e45e69397193d40d313d
|
C#
|
ArvidSilvmarker/WebApiLab
|
/WebApiLab/WebApiLab/Controllers/Ex4Controller.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApiLab.Controllers
{
[Route("api/ex3")]
public class Ex4Controller : Controller
{
[Route("addperson"), HttpPost]
public IActionResult AddPerson(SimplePerson person)
{
return Ok($"Person med namn: {person.Name} och ålder: {person.Age} har nu lagt till i databasen.");
}
[Route("validateperson"), HttpPost]
public IActionResult ValidatePerson(SimplePerson person)
{
List<string> errorMessage = new List<string>();
if (string.IsNullOrWhiteSpace(person.Name))
errorMessage.Add("Personen måste ha ett namn.");
else if (person.Name.Length > 20)
errorMessage.Add("Namn får inte vara längre än 20 tecken.");
if (person.Age == null)
errorMessage.Add("Personen måste ha en ålder.");
else if (person.Age < 0 || person.Age > 120)
errorMessage.Add("Ålder måste vara mellan 0 och 120.");
if (errorMessage.Count > 0)
return BadRequest(string.Join(' ', errorMessage.ToArray()));
return Ok($"Person med namn: {person.Name} och ålder: {person.Age} har nu lagt till i databasen.");
}
[Route("validatepersonattributes"), HttpPost]
public IActionResult ValidatePersonWithAttributes(SimplePersonWithAttributes person)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok($"Person med namn: {person.Name} och ålder: {person.Age} har nu lagt till i databasen.");
}
}
public class SimplePerson
{
public string Name { get; set; }
public int? Age { get; set; }
}
public class SimplePersonWithAttributes
{
[Required(ErrorMessage = "Måste ha ett namn.")]
[StringLength(20, ErrorMessage = "Namn får inte vara längre än 20 tecken.")]
public string Name { get; set; }
[Required(ErrorMessage = "Måste ha en ålder.")]
[Range(0,120, ErrorMessage = "Ålder måste vara mellan 0 och 120.")]
public int Age { get; set; }
}
}
|
c3bd5e9347ffd825db6307f4b0fbd7051c586f8c
|
C#
|
gfrancischini/xml-language-server
|
/XmlLanguageServerConsole/XmlValidationEngine/XsdCache.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using XmlValidation.FileTypes;
namespace XmlValidation
{
public class XsdCache
{
/// <summary>
/// Cache that Holds all the loaded XSDs
/// </summary>
private Dictionary<string, XsdFile> xsds = new Dictionary<string, XsdFile>();
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public XsdFile Load(string path)
{
// load the new xsd
if (File.Exists(path) == false)
{
//TODO : create a specific extesion
throw new Exception("XSD File doest not exist");
}
XsdFile xsdFileInfo = new XsdFile()
{
Name = Path.GetFileName(path),
Path = path
};
this.xsds.Add(path, xsdFileInfo);
return xsdFileInfo;
}
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public XsdFile Get(string path)
{
//check if the file is loaded
if (xsds.ContainsKey(path))
{
//return from cache
return xsds[path];
}
return this.Load(path);
}
}
}
|
b4b7afc2bc0ea3a129917d0114727cc653cb9bed
|
C#
|
Alex-Reich/Console-Slap
|
/BatmanGame.cs
| 3.34375
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using csharp_intro.Models;
namespace csharp_intro
{
public class BatmanGame
{
private List<Target> _targets = new List<Target>();
private void Setup()
{
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Clear();
CreateEnemies();
}
private void CreateEnemies()
{
_targets.Clear();
_targets.Add(new Target("The Joker", 100));
_targets.Add(new Target("Scarecrow", 87));
_targets.Add(new Target("Bane", 150));
_targets.Add(new Target("ScaryFace", 99.9m));
_targets.Add(new Target("SupermanWeak", 1000000000m));
_targets.Add(new Target("Superman", 9999999999999999999m));
}
public void Play()
{
Setup();
Target currentTarget = EnemySelect();
BattleTarget(currentTarget);
}
private void BattleTarget(Target currentTarget)
{
Console.Clear();
var t = new Stopwatch();
t.Start();
while (currentTarget.Alive)
{
if (currentTarget.Name == "SupermanWeak")
{
currentTarget.Attack();
continue;
}
Console.WriteLine("The Batman is fighting " + currentTarget.Name + " remaining health: " + currentTarget.Health);
Console.WriteLine("What do you do? (fight, flee)");
var action = Console.ReadLine();
Console.Clear();
if (action == "fight")
{
currentTarget.Attack();
Console.Beep();
Console.WriteLine(currentTarget.GetOuchWord());
}
else if (action == "flee")
{
Console.WriteLine("The Batman never flees");
}
else
{
Console.WriteLine("Stop joking around >;}");
}
}
t.Stop();
Console.Clear();
Console.WriteLine("that took: " + t.ElapsedMilliseconds /1000 + " seconds" );
Console.WriteLine("You have defeated " + currentTarget.Name);
Console.WriteLine("Goodbye");
}
private Target EnemySelect()
{
Target currentTarget = null;
while (currentTarget == null)
{
Console.Clear();
Console.WriteLine("Hello The Batman.... who would you like to fight?");
_targets.ForEach(t => Console.WriteLine(t.Name));
var choice = Console.ReadLine();
currentTarget = _targets.Find(t => t.Name == choice);
}
return currentTarget;
}
}
}
|
786a9b411e6fcbecc3148f2c09b5f8c717b94c92
|
C#
|
LGinC/ImageLable
|
/ImageLable/LogTraceListener.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace ImageLable
{
public class LogTraceListener : TraceListener
{
static string logfile;
FixedTimeAction ChangeFile;
DateTime logTime;
public LogTraceListener()
{
string basePath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\";
if (!Directory.Exists(basePath))//如果Logs文件夹不存在则创建
{
Directory.CreateDirectory(basePath);
}
logTime = DateTime.Now;
logfile = basePath + string.Format("Log-{0}.txt", logTime.ToString("yyyyMMdd"));
ChangeFile = new FixedTimeAction(new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Local), "day");
ChangeFile.DoEvent += () => { logfile = basePath + string.Format("Log-{0}.txt", logTime.ToString("yyyyMMdd")); };
}
public override void Write(string message)
{
message = Format(message, "");
File.AppendAllText(logfile, message);
}
public override void Write(object obj)
{
string message = Format(obj, "");
File.AppendAllText(logfile, message);
}
public override void Write(object obj, string category)
{
string message = Format(obj, category);
File.AppendAllText(logfile, message);
}
public override void WriteLine(string message)
{
message = Format(message + "\r\n", "");
File.AppendAllText(logfile, message);
}
public override void WriteLine(object obj)
{
string message = Format(obj, "");
File.AppendAllText(logfile, message + "\r\n");
}
public override void WriteLine(object obj, string category)
{
string message = Format(obj, category);
File.AppendAllText(logfile, message + "\r\n");
}
private string Format(object o, string category)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendFormat(" {0} ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
if (!string.IsNullOrEmpty(category))//参数 category不为空
{
stringBuilder.AppendFormat("[{0}]", category);
}
if (o is Exception)//如果传入的o是异常类对象
{
var t = o as Exception;
stringBuilder.Append(t.Message + "\n\r");//追加Message 和 StackTrace,即异常信息和异常位置
stringBuilder.Append(t.StackTrace + "\r\n");
}
else
{
stringBuilder.Append(o.ToString());
}
return stringBuilder.ToString();
}
//private void DateModified()
//{
// if (logTime.Date != DateTime.Now.Date)
// {
// string basePath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\";
// if (!Directory.Exists(basePath))//如果Logs文件夹不存在则创建
// {
// Directory.CreateDirectory(basePath);
// }
// logTime = DateTime.Now;
// logfile = basePath + string.Format("Log-{0}.txt", logTime.ToString("yyyyMMdd"));
// }
//}
}
public class FixedTimeAction
{
System.Threading.Timer timer, timer1;
DateTime ExecTime;
int hour;
public event Action DoEvent;
/// <summary>
/// 初始化
/// </summary>
/// <param name="StartExecTime">执行时间 只需传入时分秒</param>
/// <param name="interval">间隔时间,day,week,month,year</param>
public FixedTimeAction(DateTime StartExecTime, string interval)
{
TimeSpan period;
ExecTime = StartExecTime;
hour = ExecTime.Hour == 0 ? 24 : ExecTime.Hour;
switch (interval)
{
case "day":
period = TimeSpan.FromDays(1);
break;
case "week":
period = TimeSpan.FromDays(7);
break;
case "month":
period = TimeSpan.FromDays(30);
break;
case "year":
period = TimeSpan.FromDays(365);
break;
default:
throw new InvalidOperationException("传入非法的时间间隔参数,请传入day,week,month,year string类型");
}
timer = new System.Threading.Timer(Dotime, null, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(60));
timer1 = new System.Threading.Timer(Exec, null, System.Threading.Timeout.Infinite, 3000);
}
private void Exec(object state)
{
if (DateTime.Now.Minute == ExecTime.Minute)
{
DoEvent?.Invoke();
}
}
private void Dotime(object state)
{
if (DateTime.Now.Hour - hour == -1)
{
timer1.Change(1000, 3000);
}
else
{
timer1.Change(-1, 3000);
}
}
}
}
|
6e9dfa1d69ead57fa47f1e6914b2265ce9f24787
|
C#
|
nioktn/Caesar_ITA
|
/CaesarLib/MainPage/CenterContainer/ScheduleContent/ScheduleContent.cs
| 2.546875
| 3
|
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
namespace CaesarLib
{
public class ScheduleContent
{
//Fields
private IWebDriver _driverInstance;
private IWebElement _scheduleCogwheell;
private IWebElement _monthButton;
private IWebElement _weekButton;
private IWebElement _keyDatesButton;
private WeekTab _weekTabInstance;
private MonthTab _monthTabInstance;
private KeyDatesTab _keyDatesTabInstance;
private EditScheduleWindow _editScheduleWindowInstance;
//Constructor
public ScheduleContent(IWebDriver driverInstance)
{
_driverInstance = driverInstance;
}
// Properties
public IWebElement ScheduleCogwheell
{
get
{
if (_scheduleCogwheell != null) return _scheduleCogwheell;
else
{
_scheduleCogwheell = _driverInstance.FindElement(By.XPath("//button[@class='btn editBtn']//i[@class='fa fa-cog fa-2x']"));
return _scheduleCogwheell;
}
}
}
public IWebElement MonthButton
{
get
{
if (_monthButton != null) return _monthButton;
else
{
_monthButton = _driverInstance.FindElement(By.XPath("//button[contains(@class,'monthBtn')]"));
return _monthButton;
}
}
}
public IWebElement WeekButton
{
get
{
if (_weekButton != null) return _weekButton;
else
{
_weekButton = _driverInstance.FindElement(By.XPath("//button[contains(@class,'weekBtn')]"));
return _weekButton;
}
}
}
public IWebElement KeyDatesButton
{
get
{
if (_keyDatesButton != null) return _keyDatesButton;
else
{
_keyDatesButton = _driverInstance.FindElement(By.XPath("//button[contains(@class,'keyDatesBtn')]"));
return _keyDatesButton;
}
}
}
public MonthTab MonthTabInstance
{
get
{
if (_monthTabInstance != null) return _monthTabInstance;
else
{
_monthTabInstance = new MonthTab(_driverInstance);
return _monthTabInstance;
}
}
}
public WeekTab WeekTabInstance
{
get
{
if (_weekTabInstance != null) return _weekTabInstance;
else
{
_weekTabInstance = new WeekTab(_driverInstance);
return _weekTabInstance;
}
}
}
public KeyDatesTab KeyDatesTabInstance
{
get
{
if (_keyDatesTabInstance != null) return _keyDatesTabInstance;
else
{
_keyDatesTabInstance = new KeyDatesTab(_driverInstance);
return _keyDatesTabInstance;
}
}
}
public EditScheduleWindow EditScheduleWindowInstance
{
get
{
_editScheduleWindowInstance = new EditScheduleWindow(_driverInstance);
return _editScheduleWindowInstance;
}
}
//Actions
public EditScheduleWindow ClickCogwheel(WebDriverWait wait)
{
ScheduleCogwheell.Click();
wait.Until((d) => EditScheduleWindowInstance.IsScheduleEditorDisplayed(_driverInstance));
return new EditScheduleWindow(_driverInstance);
}
public WeekTab OpenWeekTab(WebDriverWait wait)
{
WeekButton.Click();
wait.Until((d) => WeekTabInstance.IsWeekTabDisplayed(_driverInstance));
return new WeekTab(_driverInstance);
}
public MonthTab OpenMonthTab(WebDriverWait wait)
{
MonthButton.Click();
wait.Until((d) => MonthTabInstance.IsMonthTabDisplayed(_driverInstance));
return new MonthTab(_driverInstance);
}
public KeyDatesTab OpenKeyDatesTab(WebDriverWait wait)
{
KeyDatesButton.Click();
wait.Until((d) =>KeyDatesTabInstance.IsKeyDatesDisplayed(_driverInstance));
return new KeyDatesTab(_driverInstance);
}
public bool IsOpened(IWebDriver driver)
{
return driver.FindElements(By.ClassName("scheduleView")).Count > 0 ?
true : false;
}
}
}
|
802c94172813338a116852d7e471c9385a64f8c8
|
C#
|
gnux/CSExtensions
|
/ExtensionsTest/Program.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using gnux.Extensions.extEnums;
using System.ComponentModel;
namespace gnux.ExtensionsTest
{
enum TEST
{
none=0,
[Description("first Value")]
first=1,
[Description("second Value")]
second=2,
[Description("third Value")]
third=4,
[Description("fourth Value")]
fourth=8,
[Description("fifth Value")]
fifth=16,
[Description("sixth Value")]
sixth=32
}
class Program
{
static void Main(string[] args)
{
TEST testen= TEST.fifth | TEST.first | TEST.third;
testen = (TEST) testen.FromDescriptionString("sixth Value", false);
Console.WriteLine(testen.ToDescriptionString() + "\n");
testen= TEST.fifth | TEST.second ;//| TEST.third;
testen = TEST.third|TEST.fifth | TEST.second;// | TEST.none;
Console.WriteLine(testen.ToString()+ "\n");
foreach (string str in testen.GetSelectedValuesAsDescriptions())
Console.WriteLine(str);
Console.ReadKey();
}
}
}
|
c9771c29e2c551c757d5374942baaa7c11da2a12
|
C#
|
claret-alexander1999/Calculator
|
/XamarinCalculator/XamarinCalculator/MainPage.xaml.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace XamarinCalculator
{
public partial class MainPage : ContentPage
{
int currentState = 1;
string myoperator;
double firstNumber, secondNumber;
public MainPage()
{
InitializeComponent();
OnClear(this, null);
}
void OnSelectNumber(object sender, EventArgs e)
{
Button button = (Button)sender;
string pressed = button.Text;
//validation before button is pressed
//if the current result is 0 in text box then we will direct the calculator to exclude 0 when pressing busttons
if (this.resultText.Text == "0" || currentState < 0)//at first current state is 1
{
this.resultText.Text = "";//here the text value will be cleared when pressing button
if (currentState < 0) //at first current value is 1 so this condition is excluded
currentState *= -1;
}
this.resultText.Text += pressed;// this condition is called when current state is greater and text box will aquire the pressed
double number;//if we are going to assign two dynamic number for a given variable using try parse method
if (double.TryParse(this.resultText.Text, out number))
{
this.resultText.Text = number.ToString("N0");
if (currentState == 1)
{
firstNumber = number;//at first current state will be 1 and it will assign first number with the pressed number variable
}
else
{
secondNumber = number;//it will be implemented as the number of current state changes i.e. 2
}
}
}
void OnSelectOperator(object sender, EventArgs e)//event is called when the select operator is called
{
currentState = -2;
Button button = (Button)sender;
string pressed = button.Text;
myoperator = pressed;
}
void OnClear(object sender, EventArgs e)// this method is called when we press the AC button
{
firstNumber = 0;
secondNumber = 0;
currentState = 1;
this.resultText.Text = "0";
}
void OnPercentage(object sender, EventArgs e) //This method is useful when we are going to find out percentage of last rsulting variable or the initial variable
{
if ((currentState == -1) || (currentState == 1))//please use some break point to check when we are going to get current state value as -1 or 1
{
//var result = OperatorHelper.MyPercentage(firstNumber, myoperator);
var result = firstNumber / 100;
this.resultText.Text = result.ToString();
firstNumber = result;
currentState = -1;
}
}
void OnCalculate(object sender, EventArgs e) //This method is called when we have both first number and second number and we are going to evaluate those number
{
if (currentState == 2)
{
var result = OperatorHelper.Calculate(firstNumber, secondNumber, myoperator);
this.resultText.Text = result.ToString();
firstNumber = result;
currentState = -1;
}
}
void OnSquareRoot(object sender, EventArgs e) //We call this event when we have one resulting number or initial number ,we are going to find out the square root of that number
{
if ((currentState == -1) || (currentState == 1))
{
//var result = OperatorHelper.MySquareRoot(firstNumber, myoperator);
var result = Math.Sqrt(firstNumber);
this.resultText.Text = result.ToString();
firstNumber = result;
currentState = -1;
}
}
private void LightModeClicked(object sender, EventArgs e)
{
if (this.BackgroundColor.Equals(Color.FromHex("#2F3B73")))
{
this.BackgroundColor = Color.White;
resultText.TextColor = Color.Black;
LightMode.Text = "Light";
}
else
{
this.BackgroundColor = Color.FromHex("#2F3B73");
resultText.TextColor = Color.White;
LightMode.Text = "Dark";
}
}
private void squareclicked(object sender, EventArgs e)//We call this method when we have one resulting number or initial number ,we are going to find out the square root of that number
{
if ((currentState == -1) || (currentState == 1))
{
//var result = OperatorHelper.MySquare(firstNumber, myoperator);
var result = firstNumber * firstNumber;
this.resultText.Text = result.ToString();
firstNumber = result;
currentState = -1;
}
}
}
}
|
5cd08a921230c13c8c4f9ecee4b21f508f4d3988
|
C#
|
arkirakosyan/MyStories
|
/MyStories.Test/UnitTests/Fake/MyStoriesFakeDbSets.cs
| 2.671875
| 3
|
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MyStories.Entities.Models;
using Repository.Pattern.Ef6;
namespace MyStories.Test.UnitTests.Fake
{
public class StoryDbSet : FakeDbSet<Story>
{
public override Story Find(params object[] keyValues)
{
return this.SingleOrDefault(t => t.Id == (int)keyValues.FirstOrDefault());
}
public override Task<Story> FindAsync(CancellationToken cancellationToken, params object[] keyValues)
{
return new Task<Story>(() => Find(keyValues));
}
}
public class GroupDbSet : FakeDbSet<Group>
{
public override Group Find(params object[] keyValues)
{
return this.SingleOrDefault(t => t.Id == (int)keyValues.FirstOrDefault());
}
public override Task<Group> FindAsync(CancellationToken cancellationToken, params object[] keyValues)
{
return new Task<Group>(() => Find(keyValues));
}
}
}
|
2d01e6df4528ddfcaca13a9fff82cf3bad6d4986
|
C#
|
dlovesl/spotcc
|
/Services/IPlayCountProducer.cs
| 2.640625
| 3
|
using Microsoft.Extensions.Logging;
using Spotcc.Services.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace Spotcc.Services
{
public interface IPlayCountProducer
{
Task ProduceAsync(PlayCount playCount, CancellationToken cancellationToken);
}
public class PlayCountProducer : IPlayCountProducer
{
private readonly ChannelWriter<PlayCount> _writer;
private readonly ILogger<PlayCountProducer> _logger;
public PlayCountProducer(ILogger<PlayCountProducer> logger, ChannelWriter<PlayCount> writer)
{
_logger = logger;
_writer = writer;
}
public async Task ProduceAsync(PlayCount playCount, CancellationToken cancellationToken = default(CancellationToken))
{
await _writer.WriteAsync(playCount, cancellationToken);
}
}
}
|
201e556abade18544f93e3b339d8682f6995ca43
|
C#
|
voiddaek/STD
|
/STD/STD/Components/Movements/CheckPointMovement.cs
| 2.71875
| 3
|
using Otter;
using STD.Entities.Common;
using System.Collections.Generic;
namespace STD.Components.Movements
{
public class CheckPointMovement : EntityMovement
{
public LinkedListNode<Vector2> CheckPoints;
public CheckPointMovement(EntityWithDirection entity, LinkedListNode<Vector2> checkPoints)
{
EntityWithDirection = entity;
CheckPoints = checkPoints;
}
public override void Update()
{
base.Update();
EntityWithDirection.Direction.X = CheckPoints.Value.X - Entity.X;
EntityWithDirection.Direction.Y = CheckPoints.Value.Y - Entity.Y;
EntityWithDirection.Direction.Normalize(EntityWithDirection.Speed);
MoveXY((int)EntityWithDirection.Direction.X, (int)EntityWithDirection.Direction.Y);
var distance = Vector2.Distance(CheckPoints.Value, new Vector2(Entity.X, Entity.Y));
if (distance <= EntityWithDirection.Speed / SpeedScale)
CheckPoints = CheckPoints.NextOrFirst();
}
}
}
|
189b8d6e6418a4d94f17169ae79bc35b366ba410
|
C#
|
gtvilela/design-patterns
|
/design-patterns/Program.cs
| 2.625
| 3
|
using Design_Patterns.Desconto;
using Design_Patterns.Impostos;
using Design_Patterns.Impostos.Interfaces;
using Design_Patterns.Investimentos;
using System;
namespace Design_Patterns
{
class Program
{
static void Main(string[] args)
{
Orcamento reforma = new Orcamento(500.0);
Imposto iccc = new ICCC();
Console.WriteLine(iccc.Calcula(reforma));
Imposto icms = new ICMS();
Console.WriteLine(icms.Calcula(reforma));
Imposto iss = new ISS();
Console.WriteLine(iss.Calcula(reforma));
var conta = new Conta();
conta.Deposita(200.0, "Gabriela", "5325", DateTime.Now);
var investimento = new RealizadorDeInvestimentos();
investimento.Realiza(conta, new Moderado());
Orcamento orcamento = new Orcamento(400);
orcamento.AdicionaItem(new Item("CANETA", 200));
orcamento.AdicionaItem(new Item("LAPIS", 200));
orcamento.AdicionaItem(new Item("GELADEIRA", 250));
orcamento.AdicionaItem(new Item("TV", 250));
orcamento.AdicionaItem(new Item("ARMARIO", 250));
orcamento.AdicionaItem(new Item("MICROONDAS", 250));
double desconto = new CalculadorDeDescontos().Calcula(orcamento);
Console.WriteLine(desconto);
//Decorator
Imposto iss2 = new ISS(new ICMS(new IKCV()));
orcamento = new Orcamento(500);
double valorIss = iss2.Calcula(orcamento);
Console.WriteLine(valorIss);
Imposto impostoAlto = new ImpostoMuitoAlto(new ISS());
double valorImpostoAlto = impostoAlto.Calcula(orcamento);
Console.WriteLine(valorImpostoAlto);
}
}
}
|
9c443ca3d63d60ea5e731dfd3c87c94e99fdbe21
|
C#
|
vblain/ImprovingPerformance
|
/Multiplication/Program.cs
| 2.96875
| 3
|
using System;
using System.Diagnostics;
using System.Numerics;
namespace Multiplication
{
class Program
{
private static BigInteger result;
static void Main(string[] args)
{
//Program.QuickTest();
//Program.NaiveTimeTest(new BigInteger(3), new BigInteger(2));
//Program.NaiveTimeTest(new BigInteger(30), new BigInteger(20));
//Program.NaiveTimeTest(new BigInteger(3000), new BigInteger(2000));
//Program.NaiveTimeTest(new BigInteger(300000), new BigInteger(200000));
Program.NaiveTimeTest(new BigInteger(30000000), new BigInteger(20000000));
//Program.NaiveTimeTest(new BigInteger(30000000), new BigInteger(0));
//Program.NaiveTimeTest(new BigInteger(0), new BigInteger(30000000));
//var data = Program.Generate(50, 4);
//Program.Execute(data, Program.MultiplyViaOperation);
//Program.Execute(data, Program.MultiplyViaAddition);
}
private static BigInteger[] Generate(int count, int maxSize)
{
var result = new BigInteger[count];
var random = new Random();
for(var i = 0; i < count; i++)
{
var data = new byte[random.Next(maxSize)];
random.NextBytes(data);
result[i] = new BigInteger(data);
}
return result;
}
private static void Execute(BigInteger[] values,
Func<BigInteger, BigInteger, BigInteger> f)
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Program.result = f(new BigInteger(200), new BigInteger(300));
var operationTime = new Stopwatch();
for(var i = 0; i < values.Length / 2; i++)
{
var a = values[i];
var b = values[i + 1];
operationTime.Start();
Program.result = f(a, b);
operationTime.Stop();
}
Console.Out.WriteLine($"Execute time: {operationTime.Elapsed}");
}
private static void NaiveTimeTest(BigInteger a, BigInteger b)
{
var operationTime = Stopwatch.StartNew();
Program.MultiplyViaOperation(a, b);
operationTime.Stop();
Console.Out.WriteLine(
$"NaiveTestTime.MultiplyViaOperation({a}, {b}) time: {operationTime.Elapsed}");
var additionTime = Stopwatch.StartNew();
Program.MultiplyViaAddition(a, b);
additionTime.Stop();
Console.Out.WriteLine(
$"NaiveTestTime.MultiplyViaAddition({a}, {b}) time: {additionTime.Elapsed}");
}
private static void QuickTest()
{
Console.Out.WriteLine(
$"346 * 27 : MultiplyViaOperation is {Program.MultiplyViaOperation(new BigInteger(346), new BigInteger(27))}");
Console.Out.WriteLine(
$"346 * 27 : MultiplyViaAddition is {Program.MultiplyViaAddition(new BigInteger(346), new BigInteger(27))}");
Console.Out.WriteLine(
$"-346 * 27 : MultiplyViaOperation is {Program.MultiplyViaOperation(new BigInteger(-346), new BigInteger(27))}");
Console.Out.WriteLine(
$"-346 * 27 : MultiplyViaAddition is {Program.MultiplyViaAddition(new BigInteger(-346), new BigInteger(27))}");
Console.Out.WriteLine(
$"346 * 27 : MultiplyViaOperation is {Program.MultiplyViaOperation(new BigInteger(346), new BigInteger(-27))}");
Console.Out.WriteLine(
$"346 * -27 : MultiplyViaAddition is {Program.MultiplyViaAddition(new BigInteger(346), new BigInteger(-27))}");
Console.Out.WriteLine(
$"-346 * -27 : MultiplyViaOperation is {Program.MultiplyViaOperation(new BigInteger(-346), new BigInteger(-27))}");
Console.Out.WriteLine(
$"-346 * -27 : MultiplyViaAddition is {Program.MultiplyViaAddition(new BigInteger(-346), new BigInteger(-27))}");
}
private static BigInteger MultiplyViaOperation(BigInteger a, BigInteger b)
{
return a * b;
}
private static BigInteger MultiplyViaAddition(BigInteger a, BigInteger b)
{
var result = BigInteger.Zero;
var value = BigInteger.Abs(a);
for (var i = BigInteger.Zero; i < BigInteger.Abs(b); i++)
{
result += value;
}
return a.Sign < 0 ^ b.Sign < 0 ? BigInteger.Negate(result) : result;
}
}
}
|
29052b79e7fe4e12fa81e39318abe3d972c5b9f7
|
C#
|
shendongnian/download4
|
/code6/1138103-29980696-89450009-2.cs
| 2.734375
| 3
|
private float lastClickTime;
public float catchTime = 0.25f;
void Update ()
{
if(Input.GetButtonDown("Fire1"))
{
if(Time.time - lastClickTime < catchTime)
{
//double click
print("Double click");
}
else
{
//normal click
}
lastClickTime = Time.time;
}
}
|
493ad7bdccc02277fa5089d0bf54b78093c0fe25
|
C#
|
shendongnian/download4
|
/latest_version_download2/120072-23673012-65258788-2.cs
| 2.734375
| 3
|
var b = new byte[8];
b[0] = 0x20;
b[1] = 0x64;
b[2] = 0xa8;
b[3] = 0xac;
b[4] = 0xb6;
b[5] = 0x65;
b[6] = 0xe4;
b[7] = 0x40;
var dbl = BitConverter.ToDouble(b, 0);
var dt = DateTime.FromOADate(dbl);
Console.WriteLine("{0:s}", dt);
|
3f8406f73f76f2250fc595d8ded6963f97dc73b5
|
C#
|
rianjs/RepoInspector
|
/RepoInspector/RepoInspector/Analysis/RepositoryAnalyzer.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using RepoInspector.Records;
namespace RepoInspector.Analysis
{
public class RepositoryAnalyzer :
IRepositoryAnalyzer
{
private readonly IClock _clock;
public RepositoryAnalyzer(IClock clock)
{
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
// TODO: Nothing in this implementation considers anything outside of pull requests, but often commits are made directly to main
public List<MetricSnapshot> CalculateRepositoryMetricsOverTime(IList<PullRequestMetrics> prMetrics)
{
var now = _clock.DateTimeOffsetUtcNow();
var snapshotsByDate = prMetrics
.GroupBy(m => m.ClosedAt.Date)
.Select(dateGroup =>
{
var medianCommentCount = dateGroup.Select(pr => pr.CommentCount).CalculateMedian();
var medianWordsPerComment = dateGroup.Select(s => s.CommentWordCount).CalculateMedian();
var medianTimeToClosure = dateGroup.Select(s => s.OpenFor).CalculateMedian();
var medianBusinessDaysToClose = dateGroup.Select(s => s.BusinessDaysOpen).CalculateMedian();
var commentCountPopulationVariance = dateGroup.Select(s => (double) s.CommentCount).CalculatePopulationVariance();
var wordsPerCommentPopulationVariance = dateGroup.Select(s => (double) s.CommentWordCount).CalculatePopulationVariance();
var dateSnapshot = new MetricSnapshot
{
UpdatedAt = now,
Date = dateGroup.Key,
MedianSecondsToPullRequestClosure = (int) medianTimeToClosure.TotalSeconds,
MedianBusinessDaysToPullRequestClosure = medianBusinessDaysToClose,
MedianCommentCountPerPullRequest = medianCommentCount,
MedianWordsPerComment = medianWordsPerComment,
CommentCountPopulationVariance = commentCountPopulationVariance,
CommentWordCountVariance = wordsPerCommentPopulationVariance,
PullRequestMetrics = dateGroup.ToDictionary(dg => dg.Number),
};
return dateSnapshot;
})
.ToList();
return snapshotsByDate;
}
}
}
|
dd677b2ee1700108151533f444717cf422dc7b29
|
C#
|
matheuscarvalholp/Reflection
|
/Form1.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp5
{
public partial class Form1 : Form
{
static Assembly testeAssembly = Assembly.LoadFile(@"C:\Users\mathe\source\repos\WindowsFormsApp5\ClassLibrary1\obj\Debug\netstandard2.0\ClassLibrary1.dll");
static Type classe = testeAssembly.GetType("ClassLibrary1.Class1");
object ClasseInstance = Activator.CreateInstance(classe);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Somar_Click(object sender, EventArgs e)
{
object ClasseInstance = Activator.CreateInstance(classe);
var somaa = classe.InvokeMember("Somar", BindingFlags.InvokeMethod
| BindingFlags.Public
| BindingFlags.Instance, null, ClasseInstance,
new object[] {Convert.ToInt32(valor1.Text), Convert.ToInt32(valor2.Text) });
resultado.Text = somaa.ToString();
}
private void Subtrair_Click(object sender, EventArgs e)
{
object ClasseInstance = Activator.CreateInstance(classe);
var subtrairr= classe.InvokeMember("Subtrair", BindingFlags.InvokeMethod
| BindingFlags.Public
| BindingFlags.Instance, null, ClasseInstance,
new object[] { Convert.ToInt32(valor1.Text), Convert.ToInt32(valor2.Text) });
resultado.Text = subtrairr.ToString();
}
private void Multiplicar_Click(object sender, EventArgs e)
{
object ClasseInstance = Activator.CreateInstance(classe);
var multiplicarr = classe.InvokeMember("Multiplicar", BindingFlags.InvokeMethod
| BindingFlags.Public
| BindingFlags.Instance, null, ClasseInstance,
new object[] { Convert.ToInt32(valor1.Text), Convert.ToInt32(valor2.Text) });
resultado.Text = multiplicarr.ToString();
}
private void Dividir_Click(object sender, EventArgs e)
{
object ClasseInstance = Activator.CreateInstance(classe);
var dividirr = classe.InvokeMember("Dividir", BindingFlags.InvokeMethod
| BindingFlags.Public
| BindingFlags.Instance, null, ClasseInstance,
new object[] { Convert.ToInt32(valor1.Text), Convert.ToInt32(valor2.Text) });
resultado.Text = dividirr.ToString();
}
}
}
|
e2524c7d77b90bb4d5726f67d9bda085a841c089
|
C#
|
khiemnd777/aaron-core
|
/v3.2.5/Project.Aaron/Libraries/Aaron.Core/TextExtensions.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Aaron.Core
{
public enum TitleStyle
{
UpperCase,
FirstCaps
}
public class ImageDimension
{
public int Width{get;set;}
public int Height{get;set;}
}
public static class TextExtensions
{
public static string ToAscii(this string text)
{
var unicodeString = text.ToLower();
unicodeString = Regex.Replace(unicodeString, "[áàảãạâấầẩẫậăắằẳẵặ]", "a");
unicodeString = Regex.Replace(unicodeString, "[éèẻẽẹêếềểễệ]", "e");
unicodeString = Regex.Replace(unicodeString, "[iíìỉĩị]", "i");
unicodeString = Regex.Replace(unicodeString, "[óòỏõọơớờởỡợôốồổỗộ]", "o");
unicodeString = Regex.Replace(unicodeString, "[úùủũụưứừửữự]", "u");
unicodeString = Regex.Replace(unicodeString, "[yýỳỷỹỵ]", "y");
unicodeString = Regex.Replace(unicodeString, "[đ]", "d");
return unicodeString;
}
public static string ToSystemName(this string text)
{
var unicodeString = ToAscii(text);
unicodeString = Regex.Replace(unicodeString, "-", "");
unicodeString = Regex.Replace(unicodeString, @"\b[a-z]\w+", delegate (Match m)
{
string v = m.ToString();
if (m.Index == 0) return v;
return char.ToUpper(v[0]) + v.Substring(1);
});
unicodeString = Regex.Replace(unicodeString, @"\s", "");
return unicodeString;
}
public static string ToSEName(this string text)
{
text = ToAscii(text);
text = Regex.Replace(text, @"\W", delegate(Match m)
{
string v = m.ToString();
if (m.Index == text.Length - 1 || m.Index == 0)
return "";
return '-' + v.Substring(1);
});
return text;
}
public static string ToTitle(this string text, TitleStyle style)
{
var unicode = String.Empty;
switch (style)
{
case TitleStyle.FirstCaps:
unicode = text.ToLower();
unicode = Regex.Replace(unicode, @"\b[a-z]\w+", delegate(Match m)
{
string v = m.ToString();
return char.ToUpper(v[0]) + v.Substring(1);
});
break;
case TitleStyle.UpperCase:
unicode = text.ToUpper();
break;
}
return unicode;
}
public static string ToFileName(this string text)
{
var result = text.Substring(text.LastIndexOf("/") + 1);
return result;
}
public static string SplitCapitalizedWords(this string source)
{
if (string.IsNullOrEmpty(source)) return String.Empty;
var newText = new StringBuilder(source.Length * 2);
newText.Append(source[0]);
for (int i = 1; i < source.Length; i++)
{
if (char.IsUpper(source[i]))
newText.Append(' ');
newText.Append(source[i]);
}
return newText.ToString();
}
public static ImageDimension ToImageDimension(this string dimension)
{
var arr = dimension.Split('x');
return new ImageDimension
{
Width = Int32.Parse(arr[0].Trim()),
Height = Int32.Parse(arr[1].Trim())
};
}
public static string ToTemplateView(this string source)
{
var result = source.Substring(source.LastIndexOf("/") + 1);
return result.Split('.')[0];
}
public static string ToSeparateString(this int source)
{
string strInput = string.Empty;
string strOutput = string.Empty;
List<string> list = new List<string>();
strInput = source.ToString();
char[] proc_I = strInput.ToCharArray();
string proc_II = string.Empty;
int pos = 0;
if (proc_I.Length > 3)
{
for (int i = (proc_I.Length - 1); i >= 0; i--)
{
if (pos == 2 || pos == 5 || pos == 8 || pos == 11 || pos == 14 || pos == 17 || pos == 20)
{
list.Add(proc_I[i].ToString());
if (i == 0)
{
break;
}
else
{
list.Add(".");
}
}
else
{
list.Add(proc_I[i].ToString());
}
pos++;
}
}
else
{
strOutput = strInput;
}
foreach (string s in list)
{
proc_II += s;
}
char[] proc_III = proc_II.ToCharArray();
for (int i = (proc_III.Length - 1); i >= 0; i--)
{
strOutput += proc_III[i];
}
return strOutput;
}
public static int ToOriginalNumber(this string source)
{
string[] _price = source.Split(new string[] { ",", "." }, StringSplitOptions.RemoveEmptyEntries);
string priceOut = string.Empty;
foreach (string p in _price)
{
priceOut += p;
}
return Convert.ToInt32(priceOut);
}
}
}
|
2a8e9e2a0bbdd3feb188c269718ecd13c5a8e995
|
C#
|
benfulton/Twarkee
|
/TeleTwitter.Lib/TeleTwitter.Lib/StatusConverter.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Newtonsoft.Json;
namespace TeleTwitter.Lib.Json
{
/// <summary>
/// Converts a JSON string to a Status object
/// </summary>
public class StatusConverter : JsonConverter
{
#region Writing
public override void WriteJson(JsonWriter writer, object value)
{
Status status = value as Status;
if (status == null)
throw new ArgumentException("Value must be a Status", "value");
writer.WriteStartObject();
//"created_at"
writer.WritePropertyName("created_at");
writer.WriteValue(status.CreatedAt);
//"text"
writer.WritePropertyName("text");
writer.WriteValue(status.Text);
//"id"
writer.WritePropertyName("id");
writer.WriteValue(status.Id);
//"user"
writer.WritePropertyName("user");
new UserConverter().WriteJson(writer, status.User);
writer.WriteEndObject();
}
#endregion
#region Reading
public override object ReadJson(JsonReader reader, Type objectType)
{
// maybe have CanReader and a CanWrite methods so this sort of test wouldn't be necessary
if (objectType != typeof(Status))
throw new JsonSerializationException("StatusConverter only supports deserializing Status objects");
Status status = new Status();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string memberName = reader.Value.ToString();
if (!reader.Read())
throw new JsonSerializationException(string.Format("Unexpected end when setting {0}'s value.", memberName));
switch (memberName)
{
//"created_at"
case "created_at":
{
status.CreatedAt = DateTime.ParseExact(GetReaderValue(reader.Value), "ddd MMM dd HH:mm:ss zzzzz yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
break;
}
//"description":"",
case "text":
{
status.Text = GetReaderValue(reader.Value);
break;
}
//"id"
case "id":
{
status.Id = GetReaderValue(reader.Value);
break;
}
//"user"
case "user":
{
UserConverter converter = new UserConverter();
status.User = converter.ReadJson(reader, typeof(User)) as User;
break;
}
}
break;
case JsonToken.EndObject:
return status;
default:
throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
}
}
throw new JsonSerializationException("Unexpected end when deserializing object.");
return null;
}
#endregion
public override bool CanConvert(Type valueType)
{
return typeof(Status).IsAssignableFrom(valueType);
}
private string GetReaderValue(object value)
{
string rtn = string.Empty;
if (value != null)
{
rtn = value.ToString();
}
return rtn;
}
}
}
|
5b7e7dd86933f48c441b3391f6fa8ed14d4351ff
|
C#
|
elleyerium/Elysium-Server
|
/NetCoreServer/Server/User/Files/Avatar.cs
| 2.859375
| 3
|
using System.IO;
namespace NetCoreServer.Server.User.Files
{
public class Avatar
{
private readonly string _source;
public Avatar(string source)
{
_source = source;
}
public byte[] GetRawData() //Get raw data to create new texture from this information
{
var fs = new FileStream($@"{_source}", FileMode.Open, FileAccess.Read);
var buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
return buffer;
}
}
}
|
ba5c816481d2cffabbc9b256404955246331ce3d
|
C#
|
dev-vinay/Evolent-Health
|
/EHI.WebSite/DataRepository/EHIDataRepository.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using EHI.WebSite.Infrastructure;
namespace EHI.WebSite.DataRepository {
public class EHIDataRepository : IEHIDataRepository {
private readonly EHIDBEntities _ehiDbContext;
private bool _disposed = false;
public EHIDataRepository(EHIDBEntities ehiDbContext) {
if (ehiDbContext == null) new ArgumentNullException(nameof(ehiDbContext));
_ehiDbContext = ehiDbContext;
}
public void Add(Patient entity) {
_ehiDbContext.Set<Patient>().Add(entity);
}
public void Delete(Patient entity) {
_ehiDbContext.Set<Patient>().Remove(entity);
}
public void Update(Patient entity) {
_ehiDbContext.Entry(entity).State = EntityState.Modified;
}
public Patient Save(Patient entity) {
_ehiDbContext.SaveChanges();
return entity;
}
public IEnumerable<Patient> GetPatients() {
var patientList = _ehiDbContext.Patients.ToList();
return patientList;
}
public Patient GetPatient(int? id) {
var patient = _ehiDbContext.Patients.Find(id);
return patient;
}
public virtual void Dispose(bool disposing) {
if (!_disposed) {
if (disposing) {
_ehiDbContext.Dispose();
}
}
_disposed = true;
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
private bool PatientContactExists(int id) {
return _ehiDbContext.Patients.Any(e => e.PatientID == id);
}
}
public interface IEHIDataRepository : IDisposable {
void Add(Patient entity);
void Update(Patient entity);
void Delete(Patient entity);
IEnumerable<Patient> GetPatients();
Patient GetPatient(int? id);
Patient Save(Patient entity);
}
}
|
5a43f853c6ea82a6ac17def89a4702d2c5cd221c
|
C#
|
vjeeva11/MethodHiding
|
/MethodHiding/Program.cs
| 3.96875
| 4
|
using System;
namespace OOPS_Basics
{
class Program
{
static void Main(string[] args)
{
MethodHidingExample();
AbstractMethodExample();
}
private static void AbstractMethodExample()
{
// Abstract - Override
// instance for derived class
// creation of derived class instance will invoke the base class constructor
// followed by derived class constructor will be invoked
DerivedClass d = new DerivedClass();
// it will invoke the Base class method
d.Write();
// it will invoke the derived class method
d.VirtualWrite();
// it will invoke the base class method
d.VirtualWriteBase();
Console.ReadLine();
}
private static void MethodHidingExample()
{
// Method hiding
// Instance for the Child Class
Child c1 = new Child();
// It will invoke the child class method
c1.Write();
// To call the Parent class method
((Parent)c1).Write();
Console.ReadLine();
}
}
public class Parent
{
// Declare the same method in the Parent class
public void Write()
{
Console.WriteLine("Parent Class Write Method");
}
}
public class Child : Parent
{
// Declare the same method in child class
// using a new keyword
public new void Write()
{
Console.WriteLine("Child Class Write Method");
}
}
// Base Class Defined with Abstract keyword
// abstract class cannot be instantiated
public abstract class BaseClass
{
// Base Class Default Constructor
public BaseClass()
{
Console.WriteLine("Base Class Constructor");
}
// Base class method
// It can be accessed using child class instance or
// base.Write()
public void Write()
{
Console.WriteLine("Base Class Write Method");
}
// this method must be implement in derived class
// it is just an declarations
public abstract void NewWrite();
// it is an virtual method , it can be accessed using base.
// if derived class uses this method name then it must be override
// in derived class
public virtual void VirtualWrite()
{
Console.WriteLine("Base Class Virtual Write");
}
// method not overidden at derived class
public virtual void VirtualWriteBase()
{
Console.WriteLine("Base Class Virtual Write Base");
}
}
// Derived class when it is declared as sealed
// it cannot be derived , instance can be created
public sealed class DerivedClass : BaseClass
{
// Derived class Constructor
public DerivedClass()
{
Console.WriteLine("Derived Class Constructor");
}
// implemneted the abstract method
public override void NewWrite()
{
Console.WriteLine("Derived Class New Write Method Overridden");
}
// overridden the base class method
public override void VirtualWrite()
{
base.VirtualWrite();
Console.WriteLine("Derived Class Virtual Write");
}
}
}
|
0fe99d61812aca7fa92915306af7a5838509b296
|
C#
|
gregmulvihill/BenchmarkFloatVsDouble
|
/BenchmarkFloatVsDouble/Program.cs
| 2.90625
| 3
|
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace BenchmarkFloatVsDouble
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("OSDescription: {0}", RuntimeInformation.OSDescription);
Console.WriteLine("OSArchitecture: {0}", RuntimeInformation.OSArchitecture);
Console.WriteLine("ProcessArchitecture: {0}", RuntimeInformation.ProcessArchitecture);
Console.WriteLine("FrameworkDescription: {0}", RuntimeInformation.FrameworkDescription);
Console.WriteLine();
var ev = Environment.GetEnvironmentVariables();
Console.WriteLine("PROCESSOR_ARCHITEW6432: {0}", ev["PROCESSOR_ARCHITEW6432"]);
Console.WriteLine("PROCESSOR_ARCHITECTURE: {0}", ev["PROCESSOR_ARCHITECTURE"]);
Console.WriteLine("PROCESSOR_IDENTIFIER: {0}", ev["PROCESSOR_IDENTIFIER"]);
Console.WriteLine("NUMBER_OF_PROCESSORS: {0}", ev["NUMBER_OF_PROCESSORS"]);
Console.WriteLine();
Console.WriteLine("Is64BitProcess: {0}", Environment.Is64BitProcess);
Console.WriteLine("Is64BitOperatingSystem: {0}", Environment.Is64BitOperatingSystem);
Console.WriteLine();
using (var p = Process.GetCurrentProcess())
{
p.PriorityClass = ProcessPriorityClass.RealTime;
}
var template = "{0,15}, {1,15}, {2,15}, {3,15}";
Console.WriteLine(
template,
"Func1Double",
"Func1Float",
"Func2Double",
"Func2Float");
var count = 100 * 1000 * 1000;
var v1 = 1.23456789D;
var v2 = 1.23456789F;
for (var ii = 0; ii < 10; ii++)
{
var t1 = Environment.TickCount;
for (var i = 0; i < count; i++) Func1Double(v1);
var d1 = Environment.TickCount - t1;
var t2 = Environment.TickCount;
for (var i = 0; i < count; i++) Func1Float(v2);
var d2 = Environment.TickCount - t2;
var t3 = Environment.TickCount;
for (var i = 0; i < count; i++) Func2Double(v1);
var d3 = Environment.TickCount - t3;
var t4 = Environment.TickCount;
for (var i = 0; i < count; i++) Func2Float(v2);
var d4 = Environment.TickCount - t4;
Console.WriteLine(template, d1, d2, d3, d4);
}
Console.WriteLine("Done");
Console.ReadKey();
}
public static double Func1Double(double x)
{
return Math.Exp(-x * x);
}
public static float Func1Float(float x)
{
return (float)Math.Exp(-x * x);
}
public static double Func2Double(double x)
{
return 1d - (1d / (1d + (x * x)));
}
public static float Func2Float(float x)
{
return 1f - (1f / (1f + (x * x)));
}
}
}
|
d7a291ec3a6b1e7aad6922cc585d5bdd308c965b
|
C#
|
PavelTarlev1/WIMS
|
/ManagementSystem/ManagementSystem/Core/PrintMessages.cs
| 2.703125
| 3
|
using System.Collections.Generic;
namespace ManagementSystem.Core
{
public static class PrintMessages
{
public const string ExitCommand = "Exit";
public const string NullProvidersExceptionMessage = "cannot be null.";
public static List<string> menuItemsNotLogged = new List<string>()
{
"Login",
"Register",
"Exit"
};
public static List<string> ShowMenu = new List<string>()
{
"ShowMenu",
"Exit"
};
public static List<string> menuList = new List<string>()
{
"CreateBoard",
"ShowAllBoards",
"ShowBoardActivity",
"--------------------",
"AddCommentToWorkItem",
"ShowAllWorkItems",
"AssignWorkItem",
"UnassignWorkItem",
"--------------------",
"CreateBug",
"ChangeBugStatus",
"ChangeBugSeverity",
"ChangeBugPriority",
"--------------------",
"CreateFeedback",
"ChangeFeedbackStatus",
"ChangeFeedbackRating",
"--------------------",
"CreateMember",
"ShowAllMembers",
"ShowMemberHistory",
"--------------------",
"CreateTeam",
"AddBoardToTeam",
"AddMemberToTeam",
"ShowAllTeamMembers",
"ShowAllTeams",
"ShowAllTeamBoards",
"ShowAllTeamActivity",
"--------------------",
"CreateStory",
"ChangeStoryPriority",
"ChangeStoryStatus",
"ChangeStorySize",
"--------------------",
"FilterWorkItemByStatus",
"FilterWorkItemByAssignee",
"ListAllItems",
"ListWorkItems",
"SortWorkItems"
};
public const string commandNotFound = "The passed command is not found!";
//REQUIREMENTS
public const string usernameRequirements = "Username should contain at least 8 symbols.";
public const string passwordRequirements =
"Password must be at least 8 symbols long, must contain at least one digit and at least one " +
"UpperCase and LowerCase letter.";
public const string titleRequirements = "The title must be between 10 and 50 characters.";
public const string descriptionRequirements = "The title must be between 10 and 500 characters.";
public const string feedbackRequirements = "Rating must be positive number.";
//REGISTRATION AND LOGIN
public const string userName = "Username: ";
public const string password = "Password: ";
public const string memberAlreadyExists = "Member already exists!";
public const string successfullyRegistered = "Member successfully added!";
public const string successfullyLoggedIn = "Member successfully logged in!";
public const string memberNotLoggedIn = "Member did not manage to log in!";
public const string wrongPassword = "Wrong Password! Please try again!";
//ENUMS
public const string choosePriority = "Choose priority: ";
public const string chooseStatus = "Choose status: ";
public const string chooseSeverity = "Choose severity: ";
public const string chooseSize = "Choose size: ";
//BOARD
public const string AllBoards = "Boards in database: ";
public const string title = "Title: ";
public const string ChooseBoard = "Go up and down with the arrows and press enter to choose a board.";
public const string writeNameOfBoard = "Name of board: ";
public const string boardDoesNotExist = "This board does not exist!";
public const string boardAlreadyExists = "This board name already exists!";
public const string boardSuccessfullyCreated = "You have successfully created a board!";
public const string boardSuccessfullyAddedToTeam = "You have successfully added the board to team!";
//BUG
public const string writeNameOfBug = "Name of bug: ";
public const string description = "Description: ";
public const string stepsToProduce = "Steps to produce: ";
public const string chooseNumberOfSteps = "Write number of steps: ";
public const string inputINTneeded = "Please enter a number: ";
public const string chooseAssignee = "Choose assignee: ";
public const string bugDoesNotExist = "This bug does not exist.";
public const string bugSuccesfullyCreated = "Bug successfully created!";
//MEMBER
public const string memberNOTSuccessfullyAddedToTeam = "Please choose a valid team and member.";
public const string memberSuccessfullyAddedToTeam = "Member successfully added!";
public const string memberSuccessfullyCreated = "Member successfully created!";
public const string memberHistoryEmpty = "There is no history of this member.";
public const string memberDoesNotExist = "This member does not exist.";
public const string addMembersToTeam = "Numbers of members to be added: ";
//STORY
public const string storySuccesfullyCreated = "Story successfully created!";
public const string storySizeSuccessfullyChanged = "Story size successfully changed!";
public const string storySizeNOTChanged = "Story size NOT changed!";
//FEEDBACK
public const string FeedbackRating = "Rating: ";
public const string newFeedbackRating = "New rating: ";
public const string feedbackRatingChanged = "Feedback rating successfully changed!";
public const string feedbackRatingNotChanged = "Please provide valid rating.";
public const string feedbackSuccesfullyCreated = "Feedback successfully created!";
public const string feedbackStatusChanged = "Feedback Status successfully changed!";
public const string feedbackStatusNotChanged = "Please provide valid status.";
//TEAM
public const string teamSuccesfullyCreated = "Team successfully created!";
public const string teamAlreadyExist = "Team with this name already exists!";
public const string teamNOTfound = "This member does not exist.";
//ENUMS
public const string priorityChanged = "Priority has been successfully changed.";
public const string priorityNotChanged = "Please provide valid priority.";
public const string severityChanged = "Severity has been successfully changed.";
public const string severityNotChanged = "Please provide valid severity.";
public const string statusChanged = "Status has been successfully changed.";
public const string statusNotChanged = "Please provide valid status.";
//WORKITEM
public const string successfullyAddedComment = "Successfully added a comment.";
public const string workItemSuccessfullyAssigned = "Work item successfully assigned.";
public const string workItemSuccessfullyUnassigned = "Work item successfully unassigned.";
//COMMON
public const string noAssignees = "There are no assigned members.";
public const string chooseSort = "Choose between the options for sorting: ";
}
}
|
28a4d32799104d57f94b5d8b14844a73b6c56269
|
C#
|
cornelius-sevald/EvoBox
|
/src/Vector2.cs
| 3.671875
| 4
|
using System;
namespace evobox {
/// <summary>
/// 2D Vectors and points.
/// </summary>
public struct Vector2 {
public double x, y;
/// <summary>
/// Construct a new vector with a x and y coordinate.
/// </summary>
public Vector2(double x, double y) {
this.x = x;
this.y = y;
}
public static Vector2 zero = new Vector2(0, 0);
public static Vector2 one = new Vector2(1, 1);
public static Vector2 up = new Vector2(0, 1);
public static Vector2 down = new Vector2(0, -1);
public static Vector2 left = new Vector2(-1, 0);
public static Vector2 right = new Vector2(1, 0);
public static Vector2 FromAngle(double angle) {
return new Vector2(Math.Cos(angle), Math.Sin(angle));
}
/// <summary>
/// The squared length of this vector.
/// </summary>
public double SqrtMagnitude {
get {
return x * x + y * y;
}
}
/// <summary>
/// The length of this vector.
/// </summary>
public double Magnitude {
get {
return Math.Sqrt(this.SqrtMagnitude);
}
}
/// <summary>
/// This vector with a length of 1.
/// </summary>
public Vector2 Normalized {
get {
return this / this.Magnitude;
}
}
public double this[int i] {
get {
switch (i) {
case 0: return x;
case 1: return y;
default:
throw new IndexOutOfRangeException("Index " + i +
" out of bounds.");
}
}
set {
switch (i) {
case 0: x = value; break;
case 1: y = value; break;
default:
throw new IndexOutOfRangeException("Index " + i +
" out of bounds.");
}
}
}
public void Rotate(double angle) {
double x0 = x, y0 = y;
double ca = Math.Cos(angle), sa = Math.Sin(angle);
x = ca * x0 - sa * y0;
y = sa * x0 + ca * y0;
}
/// <summary>
/// Restricts a vector between a minimum and a maximum value.
/// </summary>
public Vector2 Clamp(Vector2 min, Vector2 max) {
Vector2 u = new Vector2(this.x, this.y);
if (u.x < min.x) {
u.x = min.x;
}
if (u.y < min.y) {
u.y = min.y;
}
if (u.x > max.x) {
u.x = max.x;
}
if (u.y > max.y) {
u.y = max.y;
}
return u;
}
public override string ToString() {
return "(" + x + ", " + y + ")";
}
public static Vector2 operator +(Vector2 v) => v;
/// <summary>
/// Negate a vector
/// </summary>
public static Vector2 operator -(Vector2 v) => new Vector2(-v.x, -v.y);
/// <summary>
/// Add two vectors.
/// </summary>
public static Vector2 operator +(Vector2 v, Vector2 u) =>
new Vector2(v.x + u.x, v.y + u.y);
/// <summary>
/// Subsract one vector from another.
/// </summary>
public static Vector2 operator -(Vector2 v, Vector2 u) => v + (-u);
/// <summary>
/// Scale a vector.
/// </summary>
public static Vector2 operator *(Vector2 v, double a) =>
new Vector2(v.x * a, v.y * a);
/// <summary>
/// Scale a vector.
/// </summary>
public static Vector2 operator *(double a, Vector2 v) => v * a;
/// <summary>
/// Inverse scale a vector.
/// </summary>
public static Vector2 operator /(Vector2 v, double a) => v * (1 / a);
/// <summary>
/// The dot product of two vectors.
/// </summary>
public static double operator *(Vector2 v, Vector2 u) =>
v.x * u.x + v.y * u.y;
}
}
|
fed64aa03633d5699e694ad3d198922e3e4e2224
|
C#
|
hg222dt/vt14-1-4-gissa-det-hemliga-talet
|
/SecretNumber/SecretNumber/Model/SecretNumber.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.ObjectModel;
namespace SecretNumber.Model
{
public class SecretNumber
{
//Hemligt nummer sparas i detta fält
private int _number;
//Lista som innehåller alla tidigare gissningar
private List<int> _previousGuesses;
//Konstant som anger maximala antalet gissningar
private const int MaxNumberOfGuesses = 7;
//Egenskap som returnerar huruvida användaren kan göra fler gissningar eller inte
public bool CanMakeGuess
{
get
{
if(Count >= MaxNumberOfGuesses)
{
return false;
}
else
{
return true;
}
}
}
//Egneskap som returnerar hur många gissningar som gjorts.
public int Count
{
get
{
int c = 1;
foreach(int i in PreviousGuesses)
{
c++;
}
return c;
}
}
//Egenskap som returnerar det hemliga talet, OM det inte går att göra fler gissningar.
public int? Number
{
get
{
if(CanMakeGuess)
{
return null;
}
else
{
return _number;
}
}
}
//Egenskap av enum-typen Outcome som håller koll på senaste gissningens status.
public Outcome Outcome { get; set; }
//Egenskap som gör att tidigare gissningar bli läsbara utifrån objektet.
public ReadOnlyCollection<int> PreviousGuesses
{
get
{
//Vet inte om det går att göra så. omvandla till IEnumerable??
return _previousGuesses.AsReadOnly();
}
}
//Metod som initierar ett spel genom att slumpa fram ett nytt tal, och sätter Outcome till Indefinite.
public void Initialize()
{
Random rnd = new Random();
_number = rnd.Next(1, 100);
_previousGuesses.Clear();
Outcome = Model.Outcome.Indefinite;
}
//Metod som anropas när användare gör en gissning. Sätter enum-typen Outcome till rätt status beroende på gissning.
public Outcome MakeGuess(int guess)
{
bool guessExcisits = false;
if (guess < 1 || guess > 100)
{
throw new ArgumentOutOfRangeException();
}
else
{
if (CanMakeGuess)
{
if (guess < _number)
{
Outcome = Model.Outcome.Low;
}
else if (guess > _number)
{
Outcome = Model.Outcome.High;
}
else if (guess == _number)
{
Outcome = Model.Outcome.Correct;
}
//Loopar igenom alla tidigare gissningar för att se om det gissade talet tidigare har gissats på.
foreach (int i in PreviousGuesses)
{
if (i == guess)
{
guessExcisits = true;
Outcome = Model.Outcome.PreviousGuess;
break;
}
}
}
else
{
Outcome = Model.Outcome.NoMoreGuesses;
}
//Om gissningen inte gissats på tidigare.
if (!guessExcisits)
{
//Ytterliggare ett element läggs till listan som håller kolla på tidigare gissninger och lägger gissningens värde i detta sista element.
_previousGuesses.Add(guess);
}
}
return Outcome;
}
//Konstruktor
public SecretNumber()
{
//Lista för tidigare gissningar skapas.
_previousGuesses = new List<int>();
//Initialize anropas
Initialize();
}
}
//Enum-typ som är till för att hålla koll på senaste gissningens status.
public enum Outcome
{
Indefinite,
Low,
High,
Correct,
NoMoreGuesses,
PreviousGuess
}
}
|
14166c1f484466671181fb66160d2b194613621d
|
C#
|
John-Pier/parking-constructor
|
/ParkingConstructorLib/models/Coors.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ParkingConstructorLib.models
{
public class Coors : IComparable //Класс координат
{
public int ColumnIndex;
public int RowIndex;
public Coors(int columnIndex, int rowIndex)
{
this.ColumnIndex = columnIndex;
this.RowIndex = rowIndex;
}
public override bool Equals(object obj)
{
var coors = (Coors) obj;
return coors != null && ColumnIndex == coors.ColumnIndex && RowIndex == coors.RowIndex;
}
public int CompareTo(object obj)
{
throw new NotImplementedException();
}
}
}
|
60e062c741e4f30d4eac7a7197888acd5af75dce
|
C#
|
stehlika/SGM-iPhone-Slaves
|
/SGM-group-project/Assets/Scripts/Interactable.cs
| 2.8125
| 3
|
using UnityEngine;
public class Interactable : MonoBehaviour
{
public float radius = 4f;
public Transform interactionTransform;
private GameObject player1;
private GameObject player2;
bool hasInteracted = false;
void Start()
{
player1 = GameManagement.Instance.getPlayer1();
player2 = GameManagement.Instance.getPlayer2();
}
public virtual void Interact()
{
Debug.Log("Interacting with " + transform.name);
}
void Update()
{
if (Input.GetButtonDown("Interact_P1"))
{
Action(player1);
}
if (Input.GetButtonDown("Interact_P2") )
{
Action(player2);
}
}
private void OnDrawGizmosSelected()
{
if (interactionTransform == null)
interactionTransform = transform;
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(interactionTransform.position, radius);
}
private void OnCollisionExit(Collision collision)
{
Debug.Log("collicion exited");
hasInteracted = false;
}
private void Action(GameObject obj)
{
if (!hasInteracted)
{
float distance = Vector3.Distance(obj.transform.position, interactionTransform.position);
if (distance <= radius)
{
Interact();
hasInteracted = true;
}
}
}
}
|
f2ea716ed5eeaff7f5c781a304d5f4019a00f8aa
|
C#
|
CameronSA/RaceTracker
|
/RaceTracker/LogicHelpers/CommandLine.cs
| 2.671875
| 3
|
using System.Diagnostics;
namespace RaceTracker.LogicHelpers
{
public static class CommandLine
{
public static void ExecuteCommand(string command)
{
Process cmd = new Process();
cmd.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
cmd.StartInfo.WorkingDirectory = @"C:\Windows\System32";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Verb = "runas";
cmd.StartInfo.Arguments = command;
cmd.Start();
cmd.WaitForExit();
}
}
}
|
63f2499b61bac5c976e9f06869909c028686d8fd
|
C#
|
butchchr/gclab11movies
|
/gclab11movies/Program.cs
| 3.21875
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gclab11movies
{
class Program
{
const string Animated = "animated";
const string Drama = "drama";
const string Horror = "horror";
const string Scifi = "scifi";
static void Main(string[] args)
{
List<Movie> movieList = new List<Movie>();
movieList.Add(new Movie("Finding Nemo", "animated"));
movieList.Add(new Movie("Shrek", "animated"));
movieList.Add(new Movie("Frozen", "animated"));
movieList.Add(new Movie("Citizen Kane", "drama"));
movieList.Add(new Movie("Metropolis", "drama"));
movieList.Add(new Movie("The Godfather", "drama"));
movieList.Add(new Movie("Blair Witch Project", "horror"));
movieList.Add(new Movie("It", "horror"));
movieList.Add(new Movie("The Ring", "horror"));
movieList.Add(new Movie("The Matrix", "scifi"));
movieList.Add(new Movie("Galaxy Quest", "scifi"));
movieList.Add(new Movie("Star Trek II, The Wrath of Khan", "scifi"));
bool y = true;
while (y)
{
Console.WriteLine($"Welcome to the Movies List Application\nThere are num number of movies in this list.\nWhat category are you interested in? (animated, drama, horror, scifi) ");
string userChoice = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(userChoice))
{
if (userChoice == Animated)
{
foreach(Movie movie in movieList)
{
if(movie.GetGenre() == Animated)
{
Console.WriteLine(movie.GetTitle());
}
}
}
else if (userChoice == Drama)
{
foreach (Movie movie in movieList)
{
if (movie.GetGenre() == Drama)
{
Console.WriteLine(movie.GetTitle());
}
}
}
else if (userChoice == Horror)
{
foreach (Movie movie in movieList)
{
if (movie.GetGenre() == Horror)
{
Console.WriteLine(movie.GetTitle());
}
}
}
else if (userChoice == Scifi)
{
foreach (Movie movie in movieList)
{
if (movie.GetGenre() == Scifi)
{
Console.WriteLine(movie.GetTitle());
}
}
}
}
else
{
Console.WriteLine("You did not enter a valid genre");
}
//continue y/n
bool invalid = true;
while (invalid)
{
Console.WriteLine("Continue? (y/n):");
ConsoleKeyInfo pressed = Console.ReadKey();
Console.WriteLine();
bool isY = pressed.Key == ConsoleKey.Y;
bool isN = pressed.Key == ConsoleKey.N;
invalid = !isY && !isN;
y = isY;
}
}
}
}
}
|
98aec09578e369511d787dc8946b009aefaa1d64
|
C#
|
Apostolova/TelerikAcademy
|
/C_Charp/Object Oriented Programing/OOP-Principle-Part2/2.Bank/DepositAccount.cs
| 3.4375
| 3
|
using System;
namespace _2.Bank
{
class DepositAccount : Account, IDrawMoney, IDepositeMoney
{
public DepositAccount(Customer customer, double balance, double interestRate, DateTime start)
: base(customer, balance, interestRate, new DateTime())
{
}
public override double CalculateInterest()
{
if (this.Balance > 0 && this.Balance < 1000)
{
return 0;
}
else return this.InterestRate;
}
public void Deposite(double sum)
{
this.Balance += sum;
}
public void Draw(double sum)
{
this.Balance -= sum;
}
}
}
|
cd053b89aedf270e4a63c12d8ea756019dd2cc06
|
C#
|
CH3COOH/Softbuild.Data
|
/Softbuild.Data.WinPhone71/UnitTestLibrary/MainPage.xaml.cs
| 2.75
| 3
|
using System;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Softbuild.Data;
namespace UnitTestLibrary
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
TestInitialize();
TestMethod1();
TestMethod2();
TestMethod3();
TestMethod4();
TestMethod5();
}
void TestInitialize()
{
Settings.Remove("TestMethod1");
Settings.Remove("TestMethod2");
Settings.Remove("TestMethod3");
Settings.Remove("TestMethod4");
Settings.Remove("TestMethod5");
}
void AssertEquals<T>(T a, T b)
{
if (!a.Equals(b))
{
throw new Exception();
}
}
void TestMethod1()
{
var value = "てすと";
Settings.Set("TestMethod1", value);
var getValue = Settings.Get<string>("TestMethod1");
AssertEquals(getValue, value);
}
void TestMethod2()
{
var value = 23;
Settings.Set("TestMethod2", value);
var getValue = Settings.Get<int>("TestMethod2");
AssertEquals(getValue, value);
}
void TestMethod3()
{
var value = 44.3;
Settings.Set("TestMethod3", value);
var getValue = Settings.Get<double>("TestMethod3");
AssertEquals(getValue, value);
}
void TestMethod4()
{
Settings.Remove("TestMethod4");
var value = 44.3;
var getValue = Settings.Get("TestMethod4", value);
AssertEquals(getValue, value);
}
void TestMethod5()
{
Settings.Remove("TestMethod5");
try
{
var getValue = Settings.Get<double>("TestMethod5");
// Settings.Getメソッドで例外が発生しなければテストFailed
throw new Exception();
}
catch
{
// テストSuccess
}
}
}
}
|
019938fa5642abccdfd0cb0de5281b96d1eac28d
|
C#
|
Sheharyarkehar/C-SharpLogicBuildingPrograms
|
/ConsoleApplication52/ConsoleApplication52/Program.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication52
{
class Program
{
public static void Main(String[] args)
{
new A();
new B();
}
}
public class A
{
public int i = 7;
public A()
{
setI(20);
Console.WriteLine("i from A is " + i);
}
public virtual void setI(int i)
{
this.i = 2 * i;
}
}
public class B : A
{
public B()
{
Console.WriteLine("i from B is " + i);
}
public override void setI(int i)
{
this.i = 3 * i;
}
}
}
|
a1bb231d8bcf5e46076df662fa530458ce538a7a
|
C#
|
nphmuller/Roslynator
|
/source/Core/CSharp/Syntax/NullCheckExpression.cs
| 2.5625
| 3
|
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Roslynator.CSharp.Syntax
{
internal struct NullCheckExpression
{
public NullCheckExpression(
ExpressionSyntax containingNode,
ExpressionSyntax expression,
NullCheckKind kind)
{
ContainingNode = containingNode;
Expression = expression;
Kind = kind;
}
public ExpressionSyntax ContainingNode { get; }
public ExpressionSyntax Expression { get; }
public NullCheckKind Kind { get; }
public bool IsCheckingNull
{
get { return Kind == NullCheckKind.EqualsToNull || Kind == NullCheckKind.NotHasValue; }
}
public bool IsCheckingNotNull
{
get { return Kind == NullCheckKind.NotEqualsToNull || Kind == NullCheckKind.HasValue; }
}
public static bool TryCreate(
SyntaxNode node,
SemanticModel semanticModel,
out NullCheckExpression result,
CancellationToken cancellationToken = default(CancellationToken))
{
if (node != null)
{
var expression = node as ExpressionSyntax;
if (expression != null)
{
expression = expression.WalkDownParentheses();
SyntaxKind kind = expression.Kind();
switch (kind)
{
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
{
var binaryExpression = (BinaryExpressionSyntax)expression;
ExpressionSyntax left = binaryExpression.Left?.WalkDownParentheses();
ExpressionSyntax right = binaryExpression.Right?.WalkDownParentheses();
return TryCreate(binaryExpression, kind, left, right, semanticModel, cancellationToken, out result)
|| TryCreate(binaryExpression, kind, right, left, semanticModel, cancellationToken, out result);
}
case SyntaxKind.SimpleMemberAccessExpression:
{
if (SyntaxUtility.IsPropertyOfNullableOfT(expression, "HasValue", semanticModel, cancellationToken))
{
var memberAccessExpression = (MemberAccessExpressionSyntax)expression;
result = new NullCheckExpression(expression, memberAccessExpression.Expression, NullCheckKind.HasValue);
return true;
}
break;
}
case SyntaxKind.LogicalNotExpression:
{
var logicalNotExpression = (PrefixUnaryExpressionSyntax)expression;
ExpressionSyntax operand = logicalNotExpression.Operand?.WalkDownParentheses();
if (operand?.IsKind(SyntaxKind.SimpleMemberAccessExpression) == true
&& SyntaxUtility.IsPropertyOfNullableOfT(operand, "HasValue", semanticModel, cancellationToken))
{
var memberAccessExpression = (MemberAccessExpressionSyntax)operand;
result = new NullCheckExpression(expression, memberAccessExpression.Expression, NullCheckKind.NotHasValue);
return true;
}
break;
}
}
}
}
result = default(NullCheckExpression);
return false;
}
private static bool TryCreate(
BinaryExpressionSyntax binaryExpression,
SyntaxKind kind,
ExpressionSyntax expression1,
ExpressionSyntax expression2,
SemanticModel semanticModel,
CancellationToken cancellationToken,
out NullCheckExpression result)
{
if (expression1 != null
&& expression2 != null)
{
switch (expression1.Kind())
{
case SyntaxKind.NullLiteralExpression:
{
result = new NullCheckExpression(
binaryExpression,
expression2,
(kind == SyntaxKind.EqualsExpression) ? NullCheckKind.EqualsToNull : NullCheckKind.NotEqualsToNull);
return true;
}
case SyntaxKind.TrueLiteralExpression:
{
if (expression2?.IsKind(SyntaxKind.SimpleMemberAccessExpression) == true
&& SyntaxUtility.IsPropertyOfNullableOfT(expression2, "HasValue", semanticModel, cancellationToken))
{
result = new NullCheckExpression(
binaryExpression,
((MemberAccessExpressionSyntax)expression2).Expression,
(kind == SyntaxKind.EqualsExpression) ? NullCheckKind.HasValue : NullCheckKind.NotHasValue);
return true;
}
break;
}
case SyntaxKind.FalseLiteralExpression:
{
if (expression2?.IsKind(SyntaxKind.SimpleMemberAccessExpression) == true
&& SyntaxUtility.IsPropertyOfNullableOfT(expression2, "HasValue", semanticModel, cancellationToken))
{
result = new NullCheckExpression(
binaryExpression,
((MemberAccessExpressionSyntax)expression2).Expression,
(kind == SyntaxKind.EqualsExpression) ? NullCheckKind.NotHasValue : NullCheckKind.HasValue);
return true;
}
break;
}
}
}
result = default(NullCheckExpression);
return false;
}
public override string ToString()
{
return ContainingNode?.ToString() ?? base.ToString();
}
}
}
|
40086f55e43e21ad1bd26fdecc30a22487b51df1
|
C#
|
jlwalkerlg/cqrs-student-management-dotnet-react-demo
|
/api/tests/StudentManagement.ApplicationTests/Students/RegisterStudentCommandTests.cs
| 2.5625
| 3
|
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using StudentManagement.Application.Students;
using StudentManagement.ApplicationTests.Doubles;
using StudentManagement.Domain.Students;
using Xunit;
namespace StudentManagement.ApplicationTests.Students
{
public class RegisterStudentCommandTests
{
private StudentRepositorySpy studentRepositorySpy;
private readonly UnitOfWorkSpy unitOfWork;
private NotificationServiceSpy notificationService;
private RegisterStudentCommandHandler handler;
public RegisterStudentCommandTests()
{
unitOfWork = new UnitOfWorkSpy();
studentRepositorySpy = unitOfWork.StudentRepositorySpy;
notificationService = new NotificationServiceSpy();
handler = new RegisterStudentCommandHandler(unitOfWork, notificationService);
}
[Fact]
public async Task It_Returns_A_Failed_Result_If_Student_Already_Exists()
{
var student = new Student(
new StudentName("Jordan Walker"),
new EmailAddress("walker.jlg@gmail.com")
);
await studentRepositorySpy.Add(student);
var command = new RegisterStudentCommand("Jordan Walker", "walker.jlg@gmail.com");
var result = await handler.Handle(command, new CancellationToken());
Assert.True(result.IsFailure);
Assert.IsType<StudentAlreadyRegisteredError>(result.Error);
}
[Fact]
public async Task It_Adds_A_Student_To_The_Repository()
{
var command = new RegisterStudentCommand("Jordan Walker", "walker.jlg@gmail.com");
var result = await handler.Handle(command, new CancellationToken());
Assert.Single(studentRepositorySpy.Students);
Assert.Equal("Jordan Walker", studentRepositorySpy.Students[0].Name.Name);
Assert.Equal("walker.jlg@gmail.com", studentRepositorySpy.Students[0].Email.Address);
Assert.True(unitOfWork.WasCommited);
}
[Fact]
public async Task It_Notifies_The_Student_Of_The_Registration()
{
var command = new RegisterStudentCommand("Jordan Walker", "walker.jlg@gmail.com");
var result = await handler.Handle(command, new CancellationToken());
var notification = notificationService.Registrations.FirstOrDefault();
Assert.NotNull(notification);
Assert.Single(notificationService.Registrations);
Assert.Equal(result.Value, notification.Id);
Assert.Equal("Jordan Walker", notification.Name);
Assert.Equal("walker.jlg@gmail.com", notification.Email);
}
[Fact]
public async Task It_Returns_A_Student_Id()
{
var command = new RegisterStudentCommand("Jordan Walker", "walker.jlg@gmail.com");
var result = await handler.Handle(command, new CancellationToken());
Assert.True(result.IsSuccess);
Assert.Equal(studentRepositorySpy.Students[0].Id, result.Value);
}
}
}
|
d7c9d998a14bb47dca6465c7365d54650619a109
|
C#
|
tatiana-zozulina/RiaParser
|
/RiaParser/NewsParser.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using AngleSharp.Html.Parser;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RiaParser
{
class NewsParser
{
private readonly HtmlParser parser;
public NewsParser()
{
parser = new HtmlParser();
}
public List<string> ParseNewsList(string htmlPage)
{
var page = parser.ParseDocument(htmlPage);
var news = page.All
.Where(x => x.ClassName == "list-item")
.Select(x => x.OuterHtml)
.ToList();
return news;
}
public DateTime ParseTimeOfNews(string htmlNews)
{
var news = parser.ParseDocument(htmlNews);
var time = news.All
.Where(x => x.ClassName == "list-item__date")
.Select(x => x.InnerHtml)
.First()
.Split(':');
DateTime dateTime;
if (time[0].StartsWith("Вчера") || int.Parse(time[0]) > DateTime.Now.Hour)
{
dateTime = new DateTime(DateTime.Today.Year,
DateTime.Today.Month,
DateTime.Today.Day - 1,
int.Parse(time[0].Substring(time[0].Length - 2)),
int.Parse(time[1]),
59);
}
else
{
dateTime = new DateTime(DateTime.Today.Year,
DateTime.Today.Month,
DateTime.Today.Day,
int.Parse(time[0]),
int.Parse(time[1]),
59);
}
return dateTime;
}
public string ParseHrefOfNews(string htmlNews)
{
var news = parser.ParseDocument(htmlNews);
var href = news.All
.Where(x => x.ClassName == "share")
.Select(x => x.GetAttribute("data-url"))
.First();
return href;
}
public string ParseTextOfNews(string htmlPage)
{
var news = parser.ParseDocument(htmlPage);
var text = news.All
.Where(x => x.ClassName == "article__text")
.Select(x => x.InnerHtml);
var fullText = new StringBuilder();
foreach (var textblock in text)
{
fullText.AppendLine(textblock);
}
return Regex.Replace(fullText.ToString(), @"<[^>]*>", " ");
}
public static void CalculateStats(NewsItem item, WordFilter filter, Dictionary<string, int> newsDictionary)
{
var wordsArray = NormalizeText(item.Text);
foreach (var word in wordsArray)
{
if (filter.IsUseless(word))
{
continue;
}
if (newsDictionary.ContainsKey(word))
{
newsDictionary[word]++;
}
else
{
newsDictionary.Add(word, 1);
}
}
}
private static string[] NormalizeText(string text)
{
var noPunctuationNews = string.Concat(text.Where(c => !char.IsPunctuation(c))
.Select(c => char.ToLower(c)));
var wordsArray = noPunctuationNews.Trim().Split(new char[0], StringSplitOptions.RemoveEmptyEntries);
return wordsArray;
}
public static IEnumerable<KeyValuePair<string, int>> GetSortedDictionary(Dictionary<string, int> newsDictionary)
{
return newsDictionary.OrderByDescending(kv => kv.Value)
.Take(100);
}
}
}
|
a8d233e826632ee7cb979a1a94548b00047deca4
|
C#
|
wareismymind/Guardian
|
/wimm.Guardian/TypeArgumentException.cs
| 3.28125
| 3
|
using System;
namespace wimm.Guardian
{
/// <summary>
/// Thrown when a generic method is invoked with an invalid type parameter.
/// </summary>
public class TypeArgumentException : Exception
{
/// <summary>
/// The name of the type parameter for which a type was invalid.
/// </summary>
public string TypeParamName { get; }
/// <summary>
/// The value of the invalid type parameter.
/// </summary>
public Type Type { get; }
internal TypeArgumentException(string typeParamName, Type type)
: this(typeParamName, type, null)
{
}
internal TypeArgumentException(string typeParamName, Type type, string additionalMessage)
: base($"{typeParamName} does not support type {type.FullName}.{additionalMessage ?? string.Empty}")
{
TypeParamName = typeParamName.Require(nameof(typeParamName)).IsNotNull().Value;
Type = type.Require(nameof(type)).IsNotNull().Value;
}
}
}
|
a3c6dfe66caf537db046569435903b56d7c66642
|
C#
|
IjazHussain786/CSharp
|
/OOP_UniversityLearningSystem/BULS/Models/Course.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using Buls.Interfaces;
using Buls.Data;
namespace Buls.Models
{
public class Course
{
private const int CourseNameDefaultLength = 5;
private string courseName;
public Course(string courseName)
{
this.Name = courseName;
this.Lectures = new Repository<Lecture>();
this.Students = new Repository<User>();
}
public string Name
{
get
{
return this.courseName;
}
private set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException("The course name cannot be empty.");
}
if (value.Length < CourseNameDefaultLength)
{
throw new ArgumentException(string.Format("The course name must be at least {0} symbols long.",
CourseNameDefaultLength));
}
this.courseName = value;
}
}
public IRepository<Lecture> Lectures { get; private set; }
public IRepository<User> Students { get; private set; }
}
}
|
8ac3f73e4ca9294b0a488f6248fdf3b1c772253e
|
C#
|
bubdm/CSharpScripts-1
|
/src/DataTypes/tuples.csx
| 3.546875
| 4
|
var employee1 = GetEmployee1();
WriteLine($"Employee. Id: {employee1.Item1}, First Name: {employee1.Item2}, Last Name: {employee1.Item3}");
var employee2 = GetEmployee2();
WriteLine($"Employee. Id: {employee2.Item1}, First Name: {employee2.Item2}, Last Name: {employee2.Item3}");
(int Id, string FirstName, string LastName) employee3 = GetEmployee2();
WriteLine($"Employee. Id: {employee3.Id}, First Name: {employee3.FirstName}, Last Name: {employee3.LastName}");
var employee4 = (Id: 1001, FirstName: "James", LastName: "Brown");
WriteLine($"Employee. Id: {employee4.Id}, First Name: {employee4.FirstName}, Last Name: {employee4.LastName}");
public Tuple<int, string, string> GetEmployee1() => Tuple.Create(1001, "James", "Brown");
public (int, string, string) GetEmployee2() => (1001, "James", "Brown");
|
915115b51f9d4112f8285284352a77594a839c59
|
C#
|
Danil20-8/FlyOn
|
/Assets/UI/ViewScripts/EventScripts/MessageListener.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
public class MessageListener : MonoBehaviour
{
Dictionary<Type, List<IListener>> listeners = new Dictionary<Type, List<IListener>>();
public void Send(object sender, object message)
{
List<IListener> ls;
if (listeners.TryGetValue(message.GetType(), out ls))
foreach (var l in ls)
l.Invoke(sender, message);
}
public void AddListener<T>(Action<object, T> listener)
{
List<IListener> ls;
if (listeners.TryGetValue(typeof(T), out ls))
ls.Add(new Listener<T>(listener));
else
{
ls = new List<IListener>() { new Listener<T>(listener) };
listeners.Add(typeof(T), ls);
}
}
public void RemoveListener<T>(Action<object, T> listener)
{
List<IListener> ls;
if (listeners.TryGetValue(typeof(T), out ls))
for (int i = 0; i < ls.Count; i++)
if (ls[i].Equals(listener))
ls.RemoveAt(i);
}
interface IListener
{
void Invoke(object sender, object message);
}
struct Listener<T>: IListener
{
public Action<object, T> listener;
public Listener (Action<object, T> listener)
{
this.listener = listener;
}
public void Invoke(object sender, object message)
{
listener(sender, (T)message);
}
public override bool Equals(object obj)
{
return listener.Equals(obj);
}
}
}
|
b2c1c1cf60d73f5099f55c71344dd15d93bfed8c
|
C#
|
leakalmar/ISBolnice
|
/Projekat/Hospital-IS/Service/PatientService.cs
| 2.546875
| 3
|
using Hospital_IS.Model;
using Hospital_IS.Service;
using Hospital_IS.Storages;
using Model;
using System;
using System.Collections.Generic;
namespace Service
{
public class PatientService
{
//private PatientFileStorage pfs = new PatientFileStorage();
public List<Patient> AllPatients { get; set; }
public IStorageFactory<PatientFileStorage> patientFileStorageFactory;
public PatientFileStorage PatientStorage { get; set; }
private static PatientService instance = null;
public static PatientService Instance
{
get
{
if (instance == null)
{
instance = new PatientService();
}
return instance;
}
}
private PatientService()
{
patientFileStorageFactory = new PatientFileStorageFactory();
PatientStorage = patientFileStorageFactory.GetStorage();
AllPatients = PatientStorage.GetAll();
UpdatePatientTrollMechanism();
}
public void AddPatient(Patient patient)
{
ChartService.Instance.SaveChart(new MedicalHistory(patient.Id));
AllPatients.Add(patient);
PatientStorage.Add(patient);
}
public void UpdatePatient(Patient patient)
{
for (int i = 0; i < AllPatients.Count; i++)
{
if (patient.Id.Equals(AllPatients[i].Id))
{
AllPatients.Remove(AllPatients[i]);
AllPatients.Insert(i, patient);
PatientStorage.Update(patient);
}
}
}
public void DeletePatient(Patient patient)
{
for (int i = 0; i < AllPatients.Count; i++)
{
if (patient.Id.Equals(AllPatients[i].Id))
{
AllPatients.Remove(AllPatients[i]);
ChartService.Instance.DeleteChart(patient.Id);
PatientStorage.Delete(patient);
}
}
}
public bool CheckIfAllergicToComponent(string medicineName, List<String> allergies)
{
bool isAllergic = false;
List<MedicineComponent> components = MedicineService.Instance.GetByName(medicineName).Composition;
foreach (MedicineComponent c in components)
{
foreach (String allergie in allergies)
{
Medicine medicine = MedicineService.Instance.GetByName(allergie);
if (medicine != null)
{
List<MedicineComponent> allergieComponents = medicine.Composition;
foreach (MedicineComponent allergieComp in allergieComponents)
{
if (c.Component.ToLower().Equals(allergieComp.Component.ToLower()))
{
isAllergic = true;
}
}
}
}
}
return isAllergic;
}
public bool CheckIfAllergicToMedicine(List<String> allergies, string name)
{
bool isAllergic = false;
foreach (String allergie in allergies)
{
if (name.ToLower().Contains(allergie.ToLower()))
{
isAllergic = true;
}
}
return isAllergic;
}
public List<int> GetPatientIDs()
{
List<int> allPatientIDs = new List<int>();
foreach (Patient patient in AllPatients)
{
allPatientIDs.Add(patient.Id);
}
return allPatientIDs;
}
public bool IsPatientTroll(Patient patient, DoctorAppointment doctorAppointment)
{
int timeRange = 10;
int maxAppointmentsInTimeRange = 3;
if (doctorAppointment.AppointmentStart < patient.TrollMechanism.TrollCheckStartDate.AddDays(timeRange))
{
patient.TrollMechanism.AppointmentCounterInTimeRange++;
if (patient.TrollMechanism.AppointmentCounterInTimeRange >= maxAppointmentsInTimeRange)
{
patient.TrollMechanism.IsTroll = true;
patient.TrollMechanism.TrollCheckStartDate = doctorAppointment.AppointmentStart.Date;
return patient.TrollMechanism.IsTroll;
}
}
return patient.TrollMechanism.IsTroll;
}
private void UpdatePatientTrollMechanism()
{
int timeRange = 10;
int maxAppointmentsInTimeRange = 3;
foreach (Patient patient in AllPatients)
{
if (patient.TrollMechanism.TrollCheckStartDate.AddDays(timeRange) == DateTime.Today)
{
patient.TrollMechanism.TrollCheckStartDate = DateTime.Today;
SetPatientTrollMechanism(patient, timeRange, maxAppointmentsInTimeRange);
}
}
}
private void SetPatientTrollMechanism(Patient patient,int timeRange, int maxAppointmentsInTimeRange)
{
if (DoctorAppointmentService.Instance.GetNumberOfAppointmentsInTimeRange(patient.Id, DateTime.Today, DateTime.Today.AddDays(timeRange)) > maxAppointmentsInTimeRange)
{
patient.TrollMechanism.IsTroll = true;
patient.TrollMechanism.AppointmentCounterInTimeRange = DoctorAppointmentService.Instance.GetNumberOfAppointmentsInTimeRange(patient.Id, DateTime.Today, DateTime.Today.AddDays(timeRange));
}
else
{
patient.TrollMechanism.IsTroll = false;
patient.TrollMechanism.AppointmentCounterInTimeRange = DoctorAppointmentService.Instance.GetNumberOfAppointmentsInTimeRange(patient.Id, DateTime.Today, DateTime.Today.AddDays(timeRange));
}
}
public List<Patient> GetAllRegisteredPatients()
{
List<Patient> registeredPatients = new List<Patient>();
foreach (Patient patient in AllPatients)
{
if (!patient.IsGuest)
registeredPatients.Add(patient);
}
return registeredPatients;
}
public List<Patient> GetAllGuests()
{
List<Patient> guests = new List<Patient>();
foreach (Patient patient in AllPatients)
{
if (patient.IsGuest)
guests.Add(patient);
}
return guests;
}
public Patient GetPatientByID(int id)
{
return PatientStorage.GetById(id);
}
public void ReloadPatients()
{
AllPatients = PatientStorage.GetAll();
}
public PatientNote GetNoteForPatientByAppointmentId(int patientId, int appointmentId)
{
PatientNote patientNote = null;
Patient patient = GetPatientByID(patientId);
foreach (PatientNote note in patient.PatientNotes)
{
if (note.AppointmentId.Equals(appointmentId))
{
patientNote = note;
}
}
return patientNote;
}
public void AddAppointmentNote(int patientId, PatientNote patientNote)
{
Patient patient = GetPatientByID(patientId);
patient.PatientNotes.Add(patientNote);
PatientStorage.Update(patient);
}
public List<PatientNote> GetNotesByPatient(int patientId)
{
Patient patient = GetPatientByID(patientId);
return patient.PatientNotes;
}
}
}
|
d104d002abf05e149368922ec4ca907302189673
|
C#
|
VisualVault/VSExampleProjects
|
/SOAP Web Service API Examples/VisualVault.Forms.Import/BusinessLogic/FormImportEngine.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using VVRuntime.VisualVault;
using VVRuntime.VisualVault.Forms;
using VisualVault.Forms.Import.Entities;
using VisualVault.Forms.Import.Entities.Profiles;
namespace VisualVault.Forms.Import.BusinessLogic
{
class FormImportEngine
{
#region Fields
internal delegate void ProgressChanged(object sender, ProgressChangedArgs args);
internal event ProgressChanged OnProgressChanged;
private readonly FormTemplate _targetFormTemplate;
private readonly string _csvFilePath;
private readonly Vault _vault;
private int _createCount;
private int _updateCount;
private int _skippedCount;
private readonly Profile _profile;
#endregion
/// <summary>
/// Read CSV file and import forms. For this simple example assume the column names
/// in the CSV file match the user properties.
/// </summary>
public FormImportEngine(string filePath, Vault vault, FormTemplate template, Profile profile)
{
_profile = profile;
_csvFilePath = filePath;
_vault = vault;
_targetFormTemplate = template;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public List<Form> ImportFormDataFromCsvFile()
{
//Read the csv file and populates a VisualVault form for each row in the CSV file
//If the column name in the CSV file matches a form field name in the target form template
//then the field value will be updated if updateExisting == true
var formList = new List<Form>();
var lineCount = CountLinesInCsv(_csvFilePath);
var linesProcessed = 0;
_createCount = 0;
_updateCount = 0;
_skippedCount = 0;
try
{
var columnNames = GetCsvColumnNames();
lineCount -= 1; //do not count header row
if (lineCount > 0)
{
var foundFields = ValidateFormFieldsExist(columnNames);
if (foundFields)
{
using (var sr = File.OpenText(_csvFilePath))
{
var fileRow = sr.ReadLine();
if (linesProcessed == 0)
{
//skip first row which has column names
fileRow = sr.ReadLine();
var statusMessage = string.Format("Starting import of {0} forms...", lineCount);
InvokeOnProgressChanged(new ProgressChangedArgs
{
TotalItems = lineCount,
ProgressMessage = statusMessage,
ErrorMessage = "",
ImportStatus = ProgressStatus.Starting
});
}
while (fileRow != null)
{
//pattern to find a delimiter and ignore other occurences of the delimiter character which occur within quotes
const string pattern = "," + "(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))";
var regex = new Regex(pattern);
var delimStr = _profile.CsvDelimeterCharacter;
var delimiter = delimStr.ToCharArray();
var values = _profile.CsvLineItemsQuoted ? regex.Split(fileRow) : fileRow.Split(delimiter);
Form existingFormInstance = null;
var updateExisting = _profile.AllowUpdate;
try
{
if (updateExisting)
{
var formId = values[0];
existingFormInstance = _vault.Forms.GetFormDataInstance(formId);
}
}
catch (Exception)
{
updateExisting = false;
}
var statusMessage = string.Format("Processing form {0} of {1}", linesProcessed, lineCount);
InvokeOnProgressChanged(new ProgressChangedArgs
{
TotalItems = lineCount,
ProgressMessage = statusMessage,
ErrorMessage = "",
ImportStatus = ProgressStatus.Processing
});
Form newFormInstance = existingFormInstance != null ? UpdateFormInstance(existingFormInstance, columnNames, values) : CreateFormInstance(columnNames, values);
if (newFormInstance != null)
{
formList.Add(newFormInstance);
linesProcessed++;
}
//read next line in CSV file
fileRow = sr.ReadLine();
//stop importing if an empty lines is found
if (fileRow != null)
{
if (fileRow.Length == 0)
{
break;
}
}
}
}
}
else
{
//no fields found
const string statusMessage = "No matching form field names found";
InvokeOnProgressChanged(new ProgressChangedArgs { TotalItems = 0, ProgressMessage = statusMessage });
}
}
else
{
//no rows found
const string statusMessage = "No data rows found in CSV file";
InvokeOnProgressChanged(new ProgressChangedArgs { TotalItems = 0, ProgressMessage = statusMessage });
}
}
catch (InvalidDataException ex)
{
const string statusMessage = "Invalid Data";
InvokeOnProgressChanged(new ProgressChangedArgs { TotalItems = 0, ProgressMessage = statusMessage, ErrorMessage = string.Format("{0}", ex.Message), ImportStatus = ProgressStatus.Processing });
}
catch (Exception ex)
{
const string statusMessage = "Unexpected error";
InvokeOnProgressChanged(new ProgressChangedArgs { TotalItems = 0, ProgressMessage = statusMessage, ErrorMessage = string.Format("{0} {1}", ex.Message, ex.StackTrace), ImportStatus = ProgressStatus.Processing });
}
var completedStatusMessage = string.Format("Processed {0} Forms. Created:{1} - Updated:{2} - Skipped:{3}", linesProcessed, _createCount, _updateCount, _skippedCount);
InvokeOnProgressChanged(new ProgressChangedArgs
{
TotalItems = lineCount,
ProgressMessage = completedStatusMessage,
ErrorMessage = "",
ImportStatus = ProgressStatus.Completed
});
return formList;
}
#region Methods
private string[] GetCsvColumnNames()
{
//Read the csv file and populates an array of the column names
//Column names must be located in the first row
string[] columnNames = null;
using (var sr = File.OpenText(_csvFilePath))
{
var fileRow = sr.ReadLine();
if (fileRow != null)
{
//pattern to find a delimiter and ignore other occurences of the delimiter character which occur within quotes
const string pattern = "," + "(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))";
var r = new Regex(pattern);
var delimStr = _profile.CsvDelimeterCharacter;
var delimiter = delimStr.ToCharArray();
columnNames = _profile.CsvHeadersQuoted ? r.Split(fileRow) : fileRow.Split(delimiter);
}
}
return columnNames;
}
private static int CountLinesInCsv(string fileName)
{
var count = 0;
using (var r = new StreamReader(fileName))
{
while (r.ReadLine() != null)
{
count++;
}
}
return count;
}
private bool ValidateFormFieldsExist(string[] columnNames)
{
if (columnNames != null)
{
for (var i = 0; i < columnNames.Length; i += 1)
{
foreach (FormField templateField in _targetFormTemplate.FormFields)
{
if (columnNames[i].Trim().ToLower() == templateField.FieldName.ToLower())
{
return true;
}
}
}
}
return false;
}
private Form CreateFormInstance(string[] columnNames, string[] values)
{
var fieldCount = columnNames.Length;
Form vvForm = null;
if (fieldCount > 0)
{
vvForm = _targetFormTemplate.GetNewFormDataInstance();
//populate form data instance with values
for (var i = 0; i < fieldCount; i += 1)
{
foreach (FormField field in vvForm.FormFields)
{
if (columnNames[i].Trim().ToLower() == field.FieldName.Trim().ToLower())
{
string fieldValue;
switch (field.FormFieldType)
{
case FormFieldTypes.SumField:
case FormFieldTypes.CellField:
fieldValue = values[i].Trim();
double doubleVal;
if (double.TryParse(fieldValue, out doubleVal))
{
field.FieldValue = doubleVal.ToString(CultureInfo.InvariantCulture);
}
break;
case FormFieldTypes.Calendar:
fieldValue = values[i].Trim();
//validate dates to ensure they match one of the supplied formats
if (!string.IsNullOrEmpty(fieldValue))
{
DateTime dateVal;
string[] dateFormats = _profile.DateTimeFormat.Split(',');
if (DateTime.TryParseExact(fieldValue, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dateVal))
{
//store date value in string using ISO 8601 date format
//iso 8601 is
field.FieldValue = dateVal.ToString("O");
}
else
{
throw new InvalidDataException(string.Format("DateTime Value {0} does not match Date Time Format String {1}", fieldValue, _profile.DateTimeFormat));
}
}
else
{
field.FieldValue = "";
}
break;
default:
fieldValue = Regex.Replace(values[i].Trim(), _vault.VaultConfiguration.RegularExpressionRules.FolderNameReplaceRegEx, "");
field.FieldValue = fieldValue.Trim();
break;
}
break;
}
}
}
//save the form intance
vvForm.SaveForm();
_createCount++;
}
return vvForm;
}
private Form UpdateFormInstance(Form existingFormInstance, string[] columnNames, string[] values)
{
var fieldCount = columnNames.Length;
var vvForm = existingFormInstance;
if (fieldCount > 0 && existingFormInstance != null)
{
var changesDetected = false;
//determine if any field values have changed
for (var i = 0; i < fieldCount; i += 1)
{
foreach (FormField field in vvForm.FormFields)
{
if (columnNames[i].Trim().ToLower() == field.FieldName.ToLower())
{
if (field.FieldValue != values[i])
{
changesDetected = true;
}
break;
}
}
if (changesDetected) break;
}
if (changesDetected)
{
vvForm = existingFormInstance.GetNewDataInstanceRevision();
//populate new revision of the form data instance with values
for (var i = 0; i < fieldCount; i += 1)
{
foreach (FormField field in vvForm.FormFields)
{
if (columnNames[i].Trim().ToLower() == field.FieldName.Trim().ToLower())
{
string fieldValue;
switch (field.FormFieldType)
{
case FormFieldTypes.SumField:
case FormFieldTypes.CellField:
fieldValue = values[i].Trim();
double doubleVal;
if (double.TryParse(fieldValue, out doubleVal))
{
field.FieldValue = doubleVal.ToString(CultureInfo.InvariantCulture);
}
break;
case FormFieldTypes.Calendar:
fieldValue = values[i].Trim();
DateTime dateVal;
string[] dateFormats = _profile.DateTimeFormat.Split(',');
if (DateTime.TryParseExact(fieldValue, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dateVal))
{
//store date value in string using ISO 8601 date format
field.FieldValue = dateVal.ToString("O");
}
else
{
throw new Exception("Invalid DateTime");
}
break;
default:
fieldValue = Regex.Replace(values[i].Trim(), _vault.VaultConfiguration.RegularExpressionRules.FolderNameReplaceRegEx, "");
field.FieldValue = fieldValue.Trim();
break;
}
break;
}
}
}
//save the form intance
vvForm.SaveForm();
_updateCount++;
}
else
{
_skippedCount++;
}
}
return vvForm;
}
private Form CreateFormInstanceRevision(Form existingFormInstance)
{
var vvForm = existingFormInstance.GetNewDataInstanceRevision();
vvForm.SaveForm();
_updateCount++;
return vvForm;
}
internal void InvokeOnProgressChanged(ProgressChangedArgs args)
{
var handler = OnProgressChanged;
if (handler != null) handler(this, args);
}
#endregion
}
}
|
ea97f818044e595c200f153d79869c38bd6919b6
|
C#
|
Szune/DeconstructPattern
|
/Program.cs
| 3.1875
| 3
|
//#define TEST
using System;
using System.Text;
using System.IO;
#if TEST
using DeconstructPattern;
#endif
namespace test_csharp_stuff
{
static class Program
{
static void Main(string[] args)
{
#if TEST
Test();
#else
GenerateDeconstructs(15);
#endif
}
static void Test()
{
#if TEST
var s = "TEST 10 P 1 2 3".Split(' ');
var parsed = s switch {
("TEST", var count, var flag, var rest) => (count, flag, string.Join(" ", rest)),
("INFO", var rest) => ("", "", string.Join(" ", rest)),
_ => throw new NotImplementedException(),
};
Console.WriteLine(parsed);
#endif
}
static void GenerateDeconstructs(int amount)
{
var sb = new StringBuilder();
sb.AppendLine("namespace DeconstructPattern");
sb.AppendLine("{");
sb.AppendLine("\tpublic static class _");
sb.AppendLine("\t{");
for (int i = 2; i < amount + 1; i++)
{
sb.AppendLine($"\t\t/* Deconstruct<T> for {i} out parameters */");
sb.Append($"\t\tpublic static void Deconstruct<T>(this T[] v");
for(int j = 0; j < i; j++)
{
if (j == i - 1)
{
sb.Append($", out T[] v{j}");
}
else
{
sb.Append($", out T v{j}");
}
}
sb.AppendLine(")");
sb.AppendLine("\t\t{");
for(int j = 0; j < i; j++)
{
sb.AppendLine($"\t\t\tv{j} = default;");
}
for(int j = 0; j < i; j++)
{
sb.AppendLine($"\t\t\tif (v.Length < {(j + 1)})");
sb.AppendLine($"\t\t\t\treturn;");
if (j == i - 1)
{
sb.AppendLine($"\t\t\tv{j} = v[{j}..];");
}
else
{
sb.AppendLine($"\t\t\tv{j} = v[{j}];");
}
}
sb.AppendLine("\t\t}");
sb.AppendLine();
}
sb.AppendLine("\t}");
sb.AppendLine("}");
File.WriteAllText("DeconstructPattern.cs", sb.ToString());
}
}
}
|
419ca117c1c6f510445cfe11ded3881803519374
|
C#
|
TnS101/SoftUni
|
/C# Advanced/Exercises/Funct program ex-4/Funct program ex-4/Program.cs
| 3.859375
| 4
|
using System;
using System.Linq;
using System.Collections.Generic;
namespace Funct_program_ex_4
{
class Program
{
static void Main(string[] args)
{
int[] input = Console.ReadLine()
.Split().Select(int.Parse)
.ToArray();
int lowerBounds = input[0];
int upperBounds = input[1];
List<int> numbers = new List<int>();
string numberType = Console.ReadLine();
for (int i = lowerBounds; i <= upperBounds; i++)
{
numbers.Add(i);
}
Predicate<int> isEven = number => number % 2 == 0;
Predicate<int> isOdd = number => number % 2 != 0;
Action<List<int>> printedNumbers = outputNumbers => Console.WriteLine
(string.Join(" ",outputNumbers));
if (numberType=="odd")
{
numbers=numbers.Where(x => isOdd(x)).ToList();
}
else
{
numbers = numbers.Where(x => isEven(x)).ToList();
}
printedNumbers(numbers);
}
}
}
|
3768d34bcd59c705d4118eda15be0860a0806a9b
|
C#
|
formist/LinkMe
|
/Framework/Host/Service/Source/ServiceMain.cs
| 2.5625
| 3
|
using System;
using LinkMe.Environment.CommandLines;
namespace LinkMe.Framework.Host.Service
{
internal class ServiceMain
{
private static void Main(string[] args)
{
CommandManager manager;
try
{
// Create a manager from the configuration information.
manager = CommandManager.ReadSection(Constants.Config.UtilSection);
}
catch (Exception ex)
{
CommandManager.WriteExceptionSummary(ex);
return;
}
try
{
// Ask the manager to create a command.
var commandLine = new CommandLine(args);
var command = manager.CreateCommand(commandLine);
// If there is a command then execute it, else show the usage.
if (command != null)
command.Execute();
else
Console.Write(manager.GetUsage());
}
catch (Exception ex)
{
manager.WriteException(ex);
}
}
}
}
|
101943a7ad8123be881b060fec8a0285ad621c55
|
C#
|
punker76/Umbrella
|
/Umbrella.Tests/Reflection/TypeExtensionsFixture.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using nVentive.Umbrella.Extensions;
using System.Reflection;
namespace nVentive.Umbrella.Tests.Reflection
{
public class TypeExtensionsFixture
{
[Fact]
public void GetMemberInfoExpressionMethod()
{
var info = (null as IDisposable).Reflection().GetDescriptor(i => i.Dispose());
Assert.Equal(info.MemberInfo, typeof(IDisposable).GetMethod("Dispose"));
}
[Fact]
public void GetMemberInfoExpressionProperty()
{
var info = GetType().Reflection<Type>().GetDescriptor(i => i.Assembly);
Assert.Equal(info.MemberInfo, typeof(Type).GetProperty("Assembly"));
}
[Fact]
public void GetMemberInfoExpressionField()
{
var info = new Dummy().Reflection().GetDescriptor(i => i.A);
Assert.Equal(info.MemberInfo, typeof(Dummy).GetField("A"));
}
class Dummy
{
public int A;
}
}
}
|
e65f51a8c78380f3bcfd037e5fd9eb0eb062fef7
|
C#
|
NathanDavis97/contracts
|
/Services/ContractsService.cs
| 2.6875
| 3
|
using contracts.Models;
using contracts.Repositories;
namespace contracts.Service
{
public class ContractsService
{
private readonly ContractsRepository _repo;
public ContractsService(ContractsRepository repo)
{
_repo = repo;
}
public Contract Create(Contract newContract)
{
int id = _repo.Create(newContract);
newContract.Id = id;
return newContract;
}
internal string Delete(int id)
{
_repo.Delete(id);
return "Successfully Deleted";
}
}
}
|
fdd44bb3ad1daae30c68f6c9ac7361735e0daf54
|
C#
|
alexnestorov/TelerikAcademy
|
/07.ComponentTesting/03.Mocking/Cars/Cars.Tests.JustMock/CarsControllersTests.cs
| 2.890625
| 3
|
namespace Cars.Tests.JustMock
{
using System;
using System.Collections.Generic;
using System.Linq;
using Cars.Contracts;
using Cars.Controllers;
using Cars.Models;
using Cars.Tests.JustMock.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class CarsControllerTests
{
private readonly ICarsRepository carsData;
private CarsController controller;
public CarsControllerTests()
: this(new MoqCarsRepository())
{
}
private CarsControllerTests(ICarsRepositoryMock carsDataMock)
{
this.carsData = carsDataMock.CarsData;
}
[TestInitialize]
public void CreateController()
{
this.controller = new CarsController(this.carsData);
}
[TestMethod]
public void IndexShouldReturnAllCars()
{
var model = (ICollection<Car>)this.GetModel(() => this.controller.Index());
Assert.AreEqual(4, model.Count);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void AddingCarShouldThrowArgumentNullExceptionIfCarIsNull()
{
var model = (Car)this.GetModel(() => this.controller.Add(null));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void AddingCarShouldThrowArgumentNullExceptionIfCarMakeIsNull()
{
var car = new Car
{
Id = 15,
Make = "",
Model = "330d",
Year = 2014
};
var model = (Car)this.GetModel(() => this.controller.Add(car));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void AddingCarShouldThrowArgumentNullExceptionIfCarModelIsNull()
{
var car = new Car
{
Id = 15,
Make = "BMW",
Model = "",
Year = 2014
};
var model = (Car)this.GetModel(() => this.controller.Add(car));
}
[TestMethod]
public void AddingCarShouldReturnADetail()
{
var car = new Car
{
Id = 15,
Make = "BMW",
Model = "330d",
Year = 2014
};
var model = (Car)this.GetModel(() => this.controller.Add(car));
Assert.AreEqual(15, model.Id);
Assert.AreEqual("BMW", model.Make);
Assert.AreEqual("330d", model.Model);
Assert.AreEqual(2014, model.Year);
}
[TestMethod]
public void SearchByIdShouldReturnDetail()
{
var model = (Car)this.GetModel(() => this.controller.Details(1));
Assert.AreEqual(1, model.Id);
Assert.AreEqual("Audi", model.Make);
Assert.AreEqual("A5", model.Model);
Assert.AreEqual(2001, model.Year);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SearchByInvalidIdShouldThrow()
{
var model = (Car)this.GetModel(() => this.controller.Details(-1));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SearchByNullIdShouldThrow()
{
var model = (Car)this.GetModel(() => this.controller.Details(int.MaxValue));
}
[TestMethod]
public void SearchByValidMakeShouldReturnDetail()
{
var cars = (IList<Car>)this.GetModel(() => this.controller.Search("BMW"));
foreach (var car in cars)
{
Assert.AreEqual(car.Make, "BMW");
}
}
[TestMethod]
public void SearchByInvalidMakeShouldThrow()
{
var cars = (IList<Car>)this.GetModel(() => this.controller.Search(""));
foreach (var car in cars)
{
Assert.AreEqual(car.Make, "BMW");
}
}
[TestMethod]
public void SearchByValidModelShouldThrow()
{
var cars = (IList<Car>)this.GetModel(() => this.controller.Search("Astra"));
foreach (var car in cars)
{
Assert.AreEqual(car.Make, "Opel");
}
}
[TestMethod]
public void SortByMakeReturnSortedCollection()
{
var cars = (IList<Car>)this.GetModel(() => this.controller.Sort("make"));
var sortedCars = cars.OrderBy(c => c.Make);
Assert.IsTrue(sortedCars.SequenceEqual(cars));
}
[TestMethod]
public void SortByYearReturnSortedCollection()
{
var cars = (IList<Car>)this.GetModel(() => this.controller.Sort("year"));
var sortedCars = cars.OrderBy(c => c.Year);
Assert.IsTrue(sortedCars.SequenceEqual(cars));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void SortByInvalidOptionShouldThrow()
{
var cars = (IList<Car>)this.GetModel(() => this.controller.Sort("invalid"));
}
private object GetModel(Func<IView> funcView)
{
var view = funcView();
return view.Model;
}
}
}
|
9a348a63f684f62b85330668bdcb0e0e502b8ae9
|
C#
|
Tokotome/AdvancedCSharp
|
/HomeworkSetsAndDictionaries/ListDemo/ListDemo.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ListDemo
{
class ListDemo
{
static void Main(string[] args)
{
List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
System.Console.WriteLine(numbers.Sum());
}
}
}
|
45bb8551799418d5611cb220a8cba46721c443d3
|
C#
|
shendongnian/download4
|
/code9/1571767-43727020-144401570-2.cs
| 2.53125
| 3
|
namespace foo.Controllers
{
public class BarController : Controller
{
private IHostingEnvironment _env;
public BarController(IHostingEnvironment env)
{
_env = env;
}
public IActionResult Index()
{
var text1 = "site.css";
ViewData["textInfo"] = Path.Combine( _env.WebRootPath,"css" , text1); //becomes myapppath/wwwroot/css/site.css
return View();
}
}
}
|
be1a60366a037eae509d5f018eba2882139cdb9a
|
C#
|
pirinit/TelerikAcademy
|
/ProgrammerTrack/1.c#Part1/6.Loops/8.GreatestCommonDivisor/GreatestCommonDivisor.cs
| 3.828125
| 4
|
using System;
class GreatestCommonDivisor
{
static void Main()
{
string input = Console.ReadLine();
int firstNumber = int.Parse(input);
input = Console.ReadLine();
int secondNumber = int.Parse(input);
int temp;
if (firstNumber < secondNumber)
{
temp = firstNumber;
firstNumber = secondNumber;
secondNumber = temp;
}
Console.Write("The greatest common divisor of {0} and {1} is", firstNumber, secondNumber);
while (firstNumber != secondNumber)
{
if (firstNumber > secondNumber * 2)
{
firstNumber = secondNumber + firstNumber % secondNumber;
}
if (firstNumber == secondNumber)
{
break;
}
firstNumber = firstNumber - secondNumber;
if (firstNumber < secondNumber)
{
temp = firstNumber;
firstNumber = secondNumber;
secondNumber = temp;
}
}
Console.WriteLine(" {0}.",firstNumber);
}
}
|
0772e1ac3dd9b1e0778b871c1fd2ea0887e96c05
|
C#
|
rantingmong/GameForest
|
/GameForest/GameForestGameCore/Messages/GFXGameSendUserData.cs
| 2.703125
| 3
|
using GameForestCore.Database;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace GameForestCoreWebSocket.Messages
{
/// <summary>
/// Message sent by the client informing there will be a game state modification/addition.
/// </summary>
public class GFXGameSendUserData : GFXSocketListener
{
public override string Subject
{
get { return "GFX_SEND_USER_DATA"; }
}
public override GFXSocketResponse DoMessage (GFXServerCore server, GFXSocketInfo info, Fleck.IWebSocketConnection ws)
{
try
{
// get the lobby the player is in
List<GFXLobbySessionRow> lobbySessions = new List<GFXLobbySessionRow>(server.LobbySessionList.Select(string.Format("SessionId = '{0}'", info.SessionId)));
if (lobbySessions.Count <= 0)
return constructResponse(GFXResponseType.InvalidInput, "User is not playing any games!");
GFXLobbySessionRow currentPlayer = lobbySessions[0];
// get the data store
GFXGameData dataStore = server.GameDataList[currentPlayer.LobbyID];
if (dataStore.UserData.ContainsKey(currentPlayer.SessionID))
{
dataStore.UserData[currentPlayer.SessionID] = info.Message;
// send message to other connected players
List<GFXLobbySessionRow> players = new List<GFXLobbySessionRow>(server.LobbySessionList.Select(string.Format("LobbyId = '{0}'", lobbySessions[0].LobbyID)));
foreach (var player in players)
{
server.WebSocketList[player.SessionID].Send(JsonConvert.SerializeObject(new GFXSocketResponse
{
Subject = "GFX_DATA_CHANGED",
Message = JsonConvert.SerializeObject(dataStore),
ResponseCode = GFXResponseType.Normal
}));
}
}
else
{
return constructResponse(GFXResponseType.DoesNotExist, "User is not in this lobby!");
}
return constructResponse(GFXResponseType.Normal, "");
}
catch (Exception exp)
{
return constructResponse(GFXResponseType.FatalError, exp.Message);
}
}
}
}
|
71164b36e911057bf16887fc8c11d67598baf702
|
C#
|
christinebittle/varsity_mvp
|
/varsity_w_auth/Controllers/PlayerController.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using varsity_w_auth.Models;
using varsity_w_auth.Models.ViewModels;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Diagnostics;
using System.Web.Script.Serialization;
namespace varsity_w_auth.Controllers
{
public class PlayerController : Controller
{
//Http Client is the proper way to connect to a webapi
//https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0
private JavaScriptSerializer jss = new JavaScriptSerializer();
private static readonly HttpClient client;
/// <summary>
/// This allows us to access a pre-defined C# HttpClient 'client' variable for sending POST and GET requests to the data access layer.
/// </summary>
static PlayerController()
{
HttpClientHandler handler = new HttpClientHandler()
{
AllowAutoRedirect = false,
//cookies are manually set in RequestHeader
UseCookies = false
};
client = new HttpClient(handler);
//change this to match your own local port number
client.BaseAddress = new Uri("http://varsityproject-env.eba-f83mxjuc.us-east-2.elasticbeanstalk.com/api/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
/// <summary>
/// Grabs the authentication credentials which are sent to the Controller.
/// This is NOT considered a proper authentication technique for the WebAPI. It piggybacks the existing authentication set up in the template for Individual User Accounts. Considering the existing scope and complexity of the course, it works for now.
///
/// Here is a descriptive article which walks through the process of setting up authorization/authentication directly.
/// https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api
/// </summary>
private void GetApplicationCookie()
{
string token = "";
//HTTP client is set up to be reused, otherwise it will exhaust server resources.
//This is a bit dangerous because a previously authenticated cookie could be cached for
//a follow-up request from someone else. Reset cookies in HTTP client before grabbing a new one.
client.DefaultRequestHeaders.Remove("Cookie");
if (!User.Identity.IsAuthenticated) return;
HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get(".AspNet.ApplicationCookie");
if (cookie != null) token = cookie.Value;
//collect token as it is submitted to the controller
//use it to pass along to the WebAPI.
Debug.WriteLine("Token Submitted is : " + token);
if (token != "") client.DefaultRequestHeaders.Add("Cookie", ".AspNet.ApplicationCookie=" + token);
return;
}
// GET: Player/List?{PageNum}
// If the page number is not included, set it to 0
public ActionResult List(int PageNum=0)
{
ListPlayers ViewModel = new ListPlayers();
ViewModel.isadmin = User.IsInRole("Admin");
// Grab all players
string url = "playerdata/getplayers";
// Send off an HTTP request
// GET : /api/playerdata/getplayers
// Retrieve response
HttpResponseMessage response = client.GetAsync(url).Result;
// If the response is a success, proceed
if (response.IsSuccessStatusCode)
{
// Fetch the response content into IEnumerable<PlayerDto>
IEnumerable<PlayerDto> SelectedPlayers = response.Content.ReadAsAsync<IEnumerable<PlayerDto>>().Result;
// -- Start of Pagination Algorithm --
// Find the total number of players
int PlayerCount = SelectedPlayers.Count();
// Number of players to display per page
int PerPage = 8;
// Determines the maximum number of pages (rounded up), assuming a page 0 start.
int MaxPage = (int)Math.Ceiling((decimal)PlayerCount / PerPage) - 1;
// Lower boundary for Max Page
if (MaxPage < 0) MaxPage = 0;
// Lower boundary for Page Number
if (PageNum < 0) PageNum = 0;
// Upper Bound for Page Number
if (PageNum > MaxPage) PageNum = MaxPage;
// The Record Index of our Page Start
int StartIndex = PerPage * PageNum;
//Helps us generate the HTML which shows "Page 1 of ..." on the list view
ViewData["PageNum"] = PageNum;
ViewData["PageSummary"] = " "+(PageNum + 1) + " of " + (MaxPage + 1)+" ";
// -- End of Pagination Algorithm --
// Send back another request to get players, this time according to our paginated logic rules
// GET api/playerdata/getplayerspage/{startindex}/{perpage}
url = "playerdata/getplayerspage/" + StartIndex + "/" + PerPage;
response = client.GetAsync(url).Result;
// Retrieve the response of the HTTP Request
IEnumerable<PlayerDto> SelectedPlayersPage = response.Content.ReadAsAsync<IEnumerable<PlayerDto>>().Result;
ViewModel.players = SelectedPlayersPage;
//Return the paginated of players instead of the entire list
return View(ViewModel);
}
else
{
// If we reach here something went wrong with our list algorithm
return RedirectToAction("Error");
}
}
// GET: Player/Details/5
public ActionResult Details(int id)
{
ShowPlayer ViewModel = new ShowPlayer();
//Pass along to the view information about who is logged in
ViewModel.isadmin = User.IsInRole("Admin");
string url = "playerdata/findplayer/" + id;
HttpResponseMessage response = client.GetAsync(url).Result;
//Can catch the status code (200 OK, 301 REDIRECT), etc.
//Debug.WriteLine(response.StatusCode);
if (response.IsSuccessStatusCode)
{
//Put data into player data transfer object
PlayerDto SelectedPlayer = response.Content.ReadAsAsync<PlayerDto>().Result;
ViewModel.player = SelectedPlayer;
url = "playerdata/findteamforplayer/" + id;
response = client.GetAsync(url).Result;
TeamDto SelectedTeam = response.Content.ReadAsAsync<TeamDto>().Result;
ViewModel.team = SelectedTeam;
return View(ViewModel);
}
else
{
return RedirectToAction("Error");
}
}
// GET: Player/Create
// only administrators get to this page
[Authorize(Roles="Admin")]
public ActionResult Create()
{
UpdatePlayer ViewModel = new UpdatePlayer();
//get information about teams this player COULD play for.
string url = "teamdata/getteams";
HttpResponseMessage response = client.GetAsync(url).Result;
IEnumerable<TeamDto> PotentialTeams = response.Content.ReadAsAsync<IEnumerable<TeamDto>>().Result;
ViewModel.allteams = PotentialTeams;
return View(ViewModel);
}
// POST: Player/Create
[HttpPost]
[ValidateAntiForgeryToken()]
[Authorize(Roles = "Admin")]
public ActionResult Create(Player PlayerInfo)
{
//pass along authentication credential in http request
GetApplicationCookie();
//Debug.WriteLine(PlayerInfo.PlayerFirstName);
//Debug.WriteLine(jss.Serialize(PlayerInfo));
string url = "playerdata/addplayer";
HttpContent content = new StringContent(jss.Serialize(PlayerInfo));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = client.PostAsync(url,content).Result;
if (response.IsSuccessStatusCode)
{
int playerid = response.Content.ReadAsAsync<int>().Result;
return RedirectToAction("Details", new { id=playerid });
}
else
{
return RedirectToAction("Error");
}
}
// GET: Player/Edit/5
[Authorize(Roles = "Admin")]
public ActionResult Edit(int id)
{
UpdatePlayer ViewModel = new UpdatePlayer();
string url = "playerdata/findplayer/" + id;
HttpResponseMessage response = client.GetAsync(url).Result;
//Can catch the status code (200 OK, 301 REDIRECT), etc.
//Debug.WriteLine(response.StatusCode);
if (response.IsSuccessStatusCode)
{
//Put data into player data transfer object
PlayerDto SelectedPlayer = response.Content.ReadAsAsync<PlayerDto>().Result;
ViewModel.player = SelectedPlayer;
//get information about teams this player COULD play for.
url = "teamdata/getteams";
response = client.GetAsync(url).Result;
IEnumerable<TeamDto> PotentialTeams = response.Content.ReadAsAsync<IEnumerable<TeamDto>>().Result;
ViewModel.allteams = PotentialTeams;
return View(ViewModel);
}
else
{
return RedirectToAction("Error");
}
}
// POST: Player/Edit/5
[HttpPost]
[ValidateAntiForgeryToken()]
[Authorize(Roles = "Admin")]
public ActionResult Edit(int id, Player PlayerInfo, HttpPostedFileBase PlayerPic)
{
//pass along authentication credential in http request
GetApplicationCookie();
//Debug.WriteLine(PlayerInfo.PlayerFirstName);
string url = "playerdata/updateplayer/"+id;
Debug.WriteLine(jss.Serialize(PlayerInfo));
HttpContent content = new StringContent(jss.Serialize(PlayerInfo));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = client.PostAsync(url, content).Result;
//Debug.WriteLine(response.StatusCode);
if (response.IsSuccessStatusCode)
{
//only attempt to send player picture data if we have it
if (PlayerPic != null) {
Debug.WriteLine("Calling Update Image method.");
//Send over image data for player
url = "playerdata/updateplayerpic/"+id;
//Debug.WriteLine("Received player picture "+PlayerPic.FileName);
MultipartFormDataContent requestcontent = new MultipartFormDataContent();
HttpContent imagecontent = new StreamContent(PlayerPic.InputStream);
requestcontent.Add(imagecontent,"PlayerPic",PlayerPic.FileName);
response = client.PostAsync(url, requestcontent).Result;
}
return RedirectToAction("Details", new { id = id });
}
else
{
return RedirectToAction("Error");
}
}
// GET: Player/Delete/5
[HttpGet]
[Authorize(Roles = "Admin")]
public ActionResult DeleteConfirm(int id)
{
string url = "playerdata/findplayer/" + id;
HttpResponseMessage response = client.GetAsync(url).Result;
//Can catch the status code (200 OK, 301 REDIRECT), etc.
//Debug.WriteLine(response.StatusCode);
if (response.IsSuccessStatusCode)
{
//Put data into player data transfer object
PlayerDto SelectedPlayer = response.Content.ReadAsAsync<PlayerDto>().Result;
return View(SelectedPlayer);
}
else
{
return RedirectToAction("Error");
}
}
// POST: Player/Delete/5
[HttpPost]
[ValidateAntiForgeryToken()]
[Authorize(Roles = "Admin")]
public ActionResult Delete(int id)
{
//pass along authentication credential in http request
GetApplicationCookie();
string url = "playerdata/deleteplayer/" + id;
//post body is empty
HttpContent content = new StringContent("");
HttpResponseMessage response = client.PostAsync(url,content).Result;
//Can catch the status code (200 OK, 301 REDIRECT), etc.
//Debug.WriteLine(response.StatusCode);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("List");
}
else
{
return RedirectToAction("Error");
}
}
public ActionResult Error()
{
return View();
}
}
}
|
584955b5e3a3781d6535eedf27044e29ac49c882
|
C#
|
vardars/ci-factory
|
/tags/0.8.0.58/Product/Production/CIScript/CIScript.Core/Attributes/BuildElementAttribute.cs
| 3.078125
| 3
|
// CIScript - A .NET build tool
// Copyright (C) 2001-2004 Gerry Shaw
// Copyright (c) 2007 Jay Flowers (jay.flowers@gmail.com)
// Ian MacLean ( ian@maclean.ms )
// Scott Hernandez (ScottHernandez_at_HOtMail_dot_dot_dot_com?)
using System;
namespace CIScript.Core.Attributes {
/// <summary>
/// Indicates that the property should be treated as an XML element and
/// further processing should be done.
/// </summary>
/// <remarks>
/// <para>
/// Should only be applied to properties exposing strongly typed arrays or
/// strongly typed collections.
/// </para>
/// <para>
/// The XML format is like this:
/// <code>
/// <![CDATA[
/// <task>
/// <elementName ...>
/// <morestuff />
/// </elementName>
/// </task>
/// ]]>
/// </code>
/// </para>
/// </remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, Inherited=true)]
public class BuildElementAttribute : Attribute {
#region Protected Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="BuildElementAttribute" /> with the
/// specified name.
/// </summary>
/// <param name="name">The name of the attribute.</param>
/// <exception cref="ArgumentNullException"><paramref name="name" /> is <see langword="null" />.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="name" /> is a zero-length <see cref="string" />.</exception>
public BuildElementAttribute(string name) {
Name = name;
}
#endregion Protected Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the name of the attribute.
/// </summary>
/// <value>
/// The name of the attribute.
/// </value>
public string Name {
get { return _name; }
set {
if (value == null) {
throw new ArgumentNullException("name");
}
// XML element names cannot have whitespace at the beginning,
// or end.
_name = value.Trim();
if (_name.Length == 0) {
throw new ArgumentOutOfRangeException("name", value, "A zero-length string is not an allowed value.");
}
}
}
/// <summary>
/// Gets or sets a value indicating whether the attribute is required.
/// </summary>
/// <value>
/// <see langword="true" /> if the attribute is required; otherwise,
/// <see langword="false" />. The default is <see langword="false" />.
/// </value>
public bool Required {
get { return _required; }
set { _required = value; }
}
/// <summary>
/// Used to specify how this element will be handled as the XML is parsed
/// and given to the element.
/// </summary>
/// <value>
/// <see langword="true" /> if XML should be processed; otherwise
/// <see langword="false" />. The default is <see langword="true" />.
/// </value>
public bool ProcessXml {
get { return _processXml; }
set { _processXml = value; }
}
#endregion Public Instance Properties
#region Private Instance Fields
private string _name;
private bool _required = false;
private bool _processXml = true;
#endregion Private Instance Fields
}
}
|
4e36e4d74afda708cf7dd2a734d09db0bbb40dcb
|
C#
|
rlclare92/MajorProjectJSV
|
/CSharp /blackJackGame.cs
| 3.234375
| 3
|
using System;
namespace classes
{
class BlackJack
{
string input;
int playersNextCard;
int dealersTotalOfFirstDraw;
int playersTotal;
int playersHandTotal;
public void playersHand()
{
Random rnd = new Random();
int playersFirstCard = rnd.Next(1, 12);
Console.WriteLine("Your first card is: {0}", playersFirstCard);
int playersSecondCard = rnd.Next(1, 12);
Console.WriteLine("Your second card is: {0}", playersSecondCard);
playersTotal = playersFirstCard + playersSecondCard;
Console.WriteLine("Your total is: {0}", playersTotal);
PlayerChoices();
}
public void PlayerChoices()
{
Console.WriteLine("Hit or Stand?");
input = Console.ReadLine();
Random rnd = new Random();
if (input == "Hit")
{
playersNextCard = rnd.Next(1, 12);
Console.WriteLine("Your next card is {0}", playersNextCard);
playersTotal += playersNextCard;
Console.WriteLine("Your total is: {0}", playersTotal);
ScoreCheckPlayer(playersTotal);
input = Console.ReadLine();
PlayerChoices();
}
else if (input == "Stand")
{
playersHandTotal += playersTotal;
Console.WriteLine("You have stand at {0}, dealers turn", playersHandTotal);
if (playersTotal >= 22)
{
Console.WriteLine("Bust");
CSharp.Program casinoGame = new CSharp.Program();
casinoGame.HouseWinning();
}
else if (playersTotal == 21)
{
Console.WriteLine("BlackJack!!");
CSharp.Program casinoGame = new CSharp.Program();
casinoGame.PlayerWinnings();
}
Console.Read();
dealersHand();
}
}
public void ScoreCheckPlayer(int playersTotal)
{
if (playersTotal >= 22)
{
Console.WriteLine("Bust");
CSharp.Program casinoGame = new CSharp.Program();
casinoGame.HouseWinning();
}
else if (playersTotal == 21)
{
Console.WriteLine("BlackJack!!");
CSharp.Program casinoGame = new CSharp.Program();
casinoGame.PlayerWinnings();
}
else
{
PlayerChoices();
}
}
public void dealersHand()
{
Random rnd = new Random();
int dealersFirstCard = rnd.Next(1, 12);
Console.WriteLine("Dealer's first card is: {0}", dealersFirstCard);
int dealersSecondCard = rnd.Next(1, 12);
Console.WriteLine("Dealer's second card is: {0}", dealersSecondCard);
dealersTotalOfFirstDraw = dealersFirstCard += dealersSecondCard;
Console.WriteLine("Dealer's total is: {0}", dealersTotalOfFirstDraw);
if (dealersTotalOfFirstDraw == 21)
{
Console.WriteLine("BlackJack!! Dealer Wins");
CSharp.Program casinoGame = new CSharp.Program();
casinoGame.PlayerWinnings();
}
else
{
dealersChoice(dealersTotalOfFirstDraw);
}
}
public void dealersChoice(int dealersTotalOfFirstDraw)
{
Random rnd = new Random();
if (dealersTotalOfFirstDraw < playersHandTotal)
{
int dealersNextCard = 0;
dealersNextCard = rnd.Next(1, 12);
Console.WriteLine("Dealer's next card is {0}", dealersNextCard);
dealersTotalOfFirstDraw += dealersNextCard;
Console.WriteLine("Dealer's current total is: {0}", dealersTotalOfFirstDraw);
ScoreCheckDealer(dealersTotalOfFirstDraw);
}
else if (dealersTotalOfFirstDraw > playersHandTotal)
{
Console.WriteLine("Dealer Wins!!");
CSharp.Program casinoGame = new CSharp.Program();
casinoGame.HouseWinning();
}
else if (dealersTotalOfFirstDraw == playersHandTotal)
{
Console.WriteLine("Tie");
CSharp.Program casinoGame = new CSharp.Program();
casinoGame.playAgain();
}
}
public void ScoreCheckDealer(int dealersTotalOfFirstDraw)
{
if (dealersTotalOfFirstDraw >= 22)
{
Console.WriteLine("Dealer bust, player wins");
CSharp.Program casinoGame = new CSharp.Program();
casinoGame.PlayerWinnings();
}
else if (dealersTotalOfFirstDraw == 21)
{
Console.WriteLine("BlackJack!! Dealer wins!!");
CSharp.Program casinoGame = new CSharp.Program();
casinoGame.HouseWinning();
}
else
{
dealersChoice(dealersTotalOfFirstDraw);
}
}
}
}
|
09d26b778da3a0a2eab005642e70807d2e799f1f
|
C#
|
embarbosa/SellsEverythingPracticeTestSolution
|
/SellsEverything.Data/GenderData.cs
| 2.53125
| 3
|
using SellsEverything.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SellsEverything.Data
{
public class GenderData
{
public List<GenderModel> GetGenders()
{
using (SellsEverythingDatabase context = new SellsEverythingDatabase())
{
return (from Gender in context.Gender
select new GenderModel
{
ID = Gender.Id,
Name = Gender.Name
}).ToList();
}
}
}
}
|
59c6babfb32a2161d0d9788365de6c4435643e43
|
C#
|
DanielaPuerta9815/Final
|
/Presentacion/aiCENTRO.cs
| 2.5625
| 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 LogicaNegocio;
namespace Presentacion
{
public partial class aiCENTRO : Form
{
public aiCENTRO()
{
InitializeComponent();
}
string nombre;
public aiCENTRO(string nombreCentro)
{
InitializeComponent();
nombre = nombreCentro;
}
GestorMedico medico = new GestorMedico();
Gestorcentro centro = new Gestorcentro();
private void buttonInsert_Click(object sender, EventArgs e)
{
if ((centro.verificarNumero(textCEDULA.Text)==true) && (textNOMBRE.Text!=string.Empty) && (textAPELLIDO.Text != string.Empty)&& (textCEDULA.Text != string.Empty))
{
medico.Insertarmedico(textNOMBRE.Text, textAPELLIDO.Text, Convert.ToInt32(textCEDULA.Text), nombre);
MessageBox.Show("Registrado Correctamente");
textNOMBRE.Text = string.Empty;
textAPELLIDO.Text = string.Empty;
textCEDULA.Text = string.Empty;
}
else
{
MessageBox.Show("Algunos de los campos tienen entradas de texto incorrectas o estan vacios, verifiquelos e intente de nuevo");
}
}
public void verificarLetra(KeyPressEventArgs parametro)
{
if (!(char.IsLetter(parametro.KeyChar)) && (parametro.KeyChar != (char)Keys.Back))
{
MessageBox.Show("No se permiten campos vacios ni con espacios, ingrese letras");
parametro.Handled = true;
return;
}
}
private void button1_Click(object sender, EventArgs e)
{
Centro cmedico = new Centro();
cmedico.Visible = true;
Visible = false;
}
private void textNOMBRE_KeyPress(object sender, KeyPressEventArgs e)
{
verificarLetra(e);
}
private void textAPELLIDO_KeyPress(object sender, KeyPressEventArgs e)
{
verificarLetra(e);
}
private void textNombreCentro_KeyPress(object sender, KeyPressEventArgs e)
{
verificarLetra(e);
}
private void textNombreCentro_TextChanged(object sender, EventArgs e)
{
}
private void textNOMBRE_TextChanged(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
}
}
|
51e70945638d3fffc08eedce5bafa900e255f745
|
C#
|
shendongnian/download4
|
/first_version_download2/604339-59060111-210045299-2.cs
| 2.9375
| 3
|
ASPxTextBase MakeControl(String Type, String Name, int Length)
{
ASPxTextBase tbBase = null;
switch (Type)
{
case "COMBO":
tbBase = new ComboBox()
{
Items = new List<string>()
};
break;
case "DATE":
tbBase = new DateEdit()
{
Date = DateTime.Now
};
break;
default:
throw new ArgumentException(nameof(Type));
}
tbBase.Name = Name;
tbBase.Length = Length;
return tbBase;
}
I made some fake properties for what I imagined the Combo or Date types might have.
|
b4d917c4e86d97d243a8eb1ac9f6228a3732b1a7
|
C#
|
ljl123asd/BookShop
|
/BookShop.Web/App_Code/ProDisplay.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// ProDisplay 的摘要说明
/// </summary>
public class ProDisplay
{
public static string GetProInfoCard(int bookId, string bookName, string bookPrice, string bookPath)
{
if (bookPath.Length==0)
{
bookPath = "~/Images/null.png";
}
string str1 = "<div class='layui-col-lg2'><div class='layui-card text-center'><div class='layui-card-header text-hidden'><a href='ProDetails.aspx?Book_Id=" + bookId + "'>" + bookName + "</a></div>"; //卡片头部标题
string str2 = "<div class='layui-card-body'><a href='ProDetails.aspx?Book_Id=" + bookId + "' target='_blank'><img src='" +
bookPath.Substring(2) + "' width='150px' height='150px'/></a>"; //卡片图片显示
string str3 = "<div style='color: red; font-size:medium; '>¥" + bookPrice + "</div></div></div></div>"; //卡片价格显示
return str1 + str2 + str3;
}
}
|
6452e9d5f1042416188f7a664ff17b285b829837
|
C#
|
jathalls/BatRecordingManager_v8.n
|
/DataVirtualizationLibrary/ItemsProvider.cs
| 2.859375
| 3
|
/*
* Copyright 2013 Paul McClean
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.
*/
using System.Collections.Generic;
namespace DataVirtualizationLibrary
{
/// <summary>
/// Represents a provider of collection details.
/// </summary>
/// <typeparam name="T">The type of items in the collection.</typeparam>
public interface IItemsProvider<T>
{
/// <summary>
/// Default function returns an empty example of T, not null
/// </summary>
/// <returns></returns>
T Default();
/// <summary>
/// Fetches the total number of items available.
/// </summary>
/// <returns></returns>
int FetchCount();
/// <summary>
/// Fetches a range of items.
/// </summary>
/// <param name="startIndex">The start index.</param>
/// <param name="count">The number of items to fetch.</param>
/// <returns></returns>
IList<T> FetchRange(int startIndex, int count);
T Refresh(T data);
void RefreshCount();
void SetSortColumn(string column);
}
}
|
4256ce82d9258a4e10354472cee2228fb83d8167
|
C#
|
Novach/OpenDoor
|
/PhoneMarket/Models/DBInitilaizer.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace PhoneMarket.Models
{
public class DBInitilaizer : DropCreateDatabaseAlways<PhoneContext>
{
protected override void Seed(PhoneContext context)
{
context.Phones.Add(new Phone() { Name = "XIAOMI MI8", price = 27000, Producer = "XIAOMI" });
context.Phones.Add(new Phone() { Name = "Meizu 16th", price = 30000, Producer = "Meizu" });
context.Phones.Add(new Phone() { Name = "Samsung S9", price = 58000, Producer = "Samsung" });
base.Seed(context);
}
}
}
|
596edd9a2a99a5352f1751c713b4ca78f9577739
|
C#
|
AlbertAY/Chromelion-Driver
|
/Chromeleon/DDK Examples/SinusChannel/Channel.cs
| 2.546875
| 3
|
/////////////////////////////////////////////////////////////////////////////
//
// Channel.cs
// //////////
//
// SinusChannel Chromeleon DDK Code Example
//
// Channel class for the SinusChannel example driver.
// The SinusChannel driver creates two channel devices that
// generate a sinus waveform during acquisition.
//
// Copyright (C) 2005-2016 Thermo Fisher Scientific
//
/////////////////////////////////////////////////////////////////////////////
using System.Timers;
using Dionex.Chromeleon.DDK; // Chromeleon DDK Interface
using Dionex.Chromeleon.Symbols; // Chromeleon Symbol Interface
namespace MyCompany.SinusChannel
{
/////////////////////////////////////////////////////////////////////////////
/// Channel Device Class
internal class Channel
{
#region Data Members
/// our Chromeleon DDK channel interface
private IChannel m_MyCmDevice;
/// We use a timer to send a data packet each second.
private System.Timers.Timer m_Timer = new System.Timers.Timer(1000);
/// This is our internal time used to generate the sinus curve.
private int m_totalDataIdx;
/// We can also write a spectrum
private ISpectrumWriter m_SpectrumWriter;
private IDoubleProperty m_WavelengthProperty;
#endregion
#region Construction
public Channel()
{
m_Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
}
#endregion
#region IChannel
/// Create our Chromeleon symbols
internal IChannel Create(IDDK cmDDK, string name)
{
// Create a data type for our signal
ITypeInt tSignal = cmDDK.CreateInt(-100, 100);
tSignal.Unit = "mV";
// Create the channel symbol
m_MyCmDevice = cmDDK.CreateChannel(name, "This is a channel that can generate a sinus curve.", tSignal);
// Attach our handlers to the AcquisitionOffCommand and AcquisitionOnCommand of the channel
m_MyCmDevice.AcquisitionOffCommand.OnCommand += new CommandEventHandler(OnAcqOff);
m_MyCmDevice.AcquisitionOnCommand.OnCommand += new CommandEventHandler(OnAcqOn);
m_MyCmDevice.TimeStepFactorProperty.DataType.Minimum = 100;
m_MyCmDevice.TimeStepFactorProperty.DataType.Maximum = 100;
m_MyCmDevice.TimeStepFactorProperty.Writeable = false;
m_MyCmDevice.TimeStepDivisorProperty.DataType.Minimum = 1;
m_MyCmDevice.TimeStepDivisorProperty.DataType.Maximum = 100;
m_MyCmDevice.TimeStepDivisorProperty.OnSetProperty += new SetPropertyEventHandler(OnTimeStepDivisor);
ITypeDouble tWavelength = cmDDK.CreateDouble(200, 400, 1);
tWavelength.Unit = "nm";
m_WavelengthProperty = m_MyCmDevice.CreateStandardProperty(StandardPropertyID.Wavelength, tWavelength);
// We want to have the wavelength available as a report variable and therefore add it to the channel info.
m_MyCmDevice.AddPropertyToChannelInfo(m_WavelengthProperty);
// What do we actually measure?
m_MyCmDevice.PhysicalQuantity = "MotorCurrent";
// This channel doesn't have peaks, we don't want to have it integrated.
m_MyCmDevice.NeedsIntegration = false;
// Create a command for writing a spectrum
ICommand writeSpectrumCommand = m_MyCmDevice.CreateCommand("WriteSpectrum", "Write a spectrum");
writeSpectrumCommand.OnCommand += new CommandEventHandler(OnWriteSpectrum);
// Create an interface for spectrum writing
m_SpectrumWriter = m_MyCmDevice.CreateSpectrumWriter();
return m_MyCmDevice;
}
internal void Connect()
{
// initialize our properties
m_MyCmDevice.TimeStepFactorProperty.Update(100);
m_MyCmDevice.TimeStepDivisorProperty.Update(60);
m_MyCmDevice.AcquisitionStateProperty.Update((int)AcquisitionState.Idle);
m_WavelengthProperty.Update(200.0);
}
internal void Disconnect()
{
}
/// OnAcqOn will be called when CM calls StartAcq
private void OnAcqOn(CommandEventArgs args)
{
// initialize our internal time to the current retention time
m_totalDataIdx = 0;
// enable the timer
m_Timer.Enabled = true;
}
/// OnAcqOn will be called when CM calls StopAcq
private void OnAcqOff(CommandEventArgs args)
{
// We will stop the data acquisition in OnTimedEvent
}
/// Write a spectrum
private void OnWriteSpectrum(CommandEventArgs args)
{
m_SpectrumWriter.Name = "Spectrum";
m_SpectrumWriter.Comment = "This is a sample spectrum";
m_SpectrumWriter.Retention = args.RetentionTime;
m_SpectrumWriter.SignalFactor = 1.0;
m_SpectrumWriter.WavelengthMinimum = 2000;
m_SpectrumWriter.WavelengthMaximum = 4000;
m_SpectrumWriter.Unit = "AU";
int[] DataPoints = new int[200];
for (int i = 0; i < 200; i++)
DataPoints[i] = i;
m_SpectrumWriter.DataPoints = DataPoints;
m_SpectrumWriter.Save();
}
private void OnTimeStepDivisor(SetPropertyEventArgs args)
{
SetIntPropertyEventArgs intPropertyArgs = args as SetIntPropertyEventArgs;
m_MyCmDevice.TimeStepDivisorProperty.Update(intPropertyArgs.NewValue);
}
#endregion
private void OnTimedEvent(object source, ElapsedEventArgs args)
{
// we use the timer to update our data.
// The timer event occurs each second.
// We send data at a rate of 100 Hz, this means we have to create 100 data points for each timer event.
int[] data = new int[60];
for (int i = 0; i < 60; i++)
{
data[i] = (int)(m_totalDataIdx % 60) * 10000;
m_totalDataIdx++;
}
// Send the new data to Chromeleon
m_MyCmDevice.UpdateData(0, data);
// If acquisition was stopped disable the timer.
if (m_MyCmDevice.AcquisitionStateProperty.Value == (int)AcquisitionState.Idle)
{
m_Timer.Enabled = false;
// Notify Chromeleon that there will be no more data available.
// We could also send this if our hardware has finished data acquisition.
m_MyCmDevice.NoMoreData();
}
}
}
}
|
236bcb876348627e917e6a505d82d00a993a7f8c
|
C#
|
NearHuscarl/BotExtended
|
/src/RandomBots/Program.cs
| 2.625
| 3
|
using SFDGameScriptInterface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RandomBots
{
public partial class Program : GameScriptInterface
{
/// <summary>
/// Placeholder constructor that's not to be included in the ScriptWindow!
/// </summary>
public Program() : base(null) { }
// Config Start
private static readonly string WIN_STATUS_NOBODY = "Nobody wins";
private static readonly string WIN_STATUS_NO_HUMAN = "No human players remaining!";
private static readonly string WIN_STATUS_TEAM = "Team {0} wins";
private static readonly string WIN_STATUS_PLAYER_WIN = "{0} wins";
// Config End
// GameWorld.cs#UpdateGameOver()
private static readonly uint GAME_OVER_DELAY = 3000;
private static bool _allowOnlyBots = false;
public void OnStartup() { Initialize(); }
private static void Initialize()
{
RandomHelper.Initialize();
Events.PlayerDeathCallback.Start(OnPlayerDealth);
Events.UserMessageCallback.Start(Command.OnUserMessage);
_allowOnlyBots = Storage.GetAllowOnlyBots();
var spawners = RandomHelper.Shuffle(ScriptHelper.GetPlayerSpawners(emptyOnly: true));
if (spawners.Count > 0)
{
var isRandom = Storage.GetIsRandom();
var index = 0;
Storage.GetBotsData().ForEach(botData =>
{
if (index > spawners.Count - 1) return;
var bot = Game.CreatePlayer(spawners[index].GetWorldPosition());
bot.SetProfile(isRandom ? RandomHelper.RandomizeProfile() : botData.Profile);
bot.SetBotName(isRandom ? RandomHelper.RandomizeName() : botData.Name);
bot.SetTeam(botData.Team);
bot.SetBotBehaviorSet(BotBehaviorSet.GetBotBehaviorPredefinedSet(botData.AI));
bot.SetBotBehaviorActive(true);
index++;
});
}
}
private static void OnPlayerDealth(IPlayer player)
{
CheckGameoverStatus();
}
private static void CheckGameoverStatus()
{
if (Game.IsGameOver) return;
// wait a bit to see if there is any extra time change
Events.UpdateCallback.Start(_ =>
{
var alivePlayers = new List<IPlayer>();
var aliveBots = new List<IPlayer>();
var lastPlayerSurvive = (IPlayer)null;
foreach (var p in Game.GetPlayers())
{
if (p.IsDead) continue;
if (p.IsBot) aliveBots.Add(p);
else alivePlayers.Add(p);
lastPlayerSurvive = p;
}
if (alivePlayers.Count > 0 || aliveBots.Count > 0)
{
if (alivePlayers.Count == 0 && aliveBots.Count > 1 && !_allowOnlyBots)
{
Game.SetGameOver(WIN_STATUS_NO_HUMAN);
return;
}
var teamsLeft = ScriptHelper.GetAliveTeams();
if (teamsLeft.Count == 1)
{
var teamLeft = teamsLeft[0];
if (teamLeft == PlayerTeam.Independent)
{
if (alivePlayers.Count + aliveBots.Count == 1)
Game.SetGameOver(string.Format(WIN_STATUS_PLAYER_WIN, lastPlayerSurvive.Name));
}
else
Game.SetGameOver(string.Format(WIN_STATUS_TEAM, ScriptHelper.GetTeamNumber(teamLeft)));
}
}
else
{
Game.SetGameOver(WIN_STATUS_NOBODY);
}
}, GAME_OVER_DELAY - 100, 1);
}
}
}
|
2327703273fc12cfbed5d2e40fbf57006894fa88
|
C#
|
BlueNoteDevelopment/database.edge.lib
|
/database.edge.lib/conversion/Row.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace database.edge.lib.conversion
{
public class Row
{
private List<object> _values;
public List<object> Values
{
get
{
if (_values == null){_values = new List<object>();}
return _values;
}
}
public Row()
{
_values = new List<object>();
}
public Row(IEnumerable<object> ItemArray)
{
_values = new List<object>();
_values.AddRange(ItemArray);
}
}
}
|
9d4207699593e88fbbbccada9528670b87fa19ff
|
C#
|
levani1994/windows-forms
|
/WindowsFormsApp1/Form1.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
string connection = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
int UserId;
List<KeyValuePair<int, string>> ComboSource = new List<KeyValuePair<int, string>>();
public Form1()
{
InitializeComponent();
GridFill();
ComboFill();
}
private void GridFill()
{
List<User> UsersList = new List<User>();
SqlConnection conn = new SqlConnection(connection);
try
{
conn.Open();
string query = @"select
U.ID,
U.Name,
U.Surname,
U.Birthdate,
U.CreateDate,
G.GroupName
from Users U
LEFT JOIN Groups G on U.GroupID=G.ID
order by U.CreateDate desc";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader Reader = cmd.ExecuteReader();
while (Reader.Read())
{
User user = new User();
user.ID = Convert.ToInt32(Reader["ID"]);
user.Name = Reader["Name"].ToString();
user.Surname = Reader["Surname"].ToString();
user.BirthDate = Convert.ToDateTime(Reader["Birthdate"]);
user.CreateDate = Convert.ToDateTime(Reader["CreateDate"]);
user.GroupName = Reader["GroupName"].ToString();
UsersList.Add(user);
}
UsersGridView.DataSource = UsersList;
UsersGridView.Columns["ID"].Visible = false;
}
catch (Exception e)
{
MessageBox.Show("შეცდომა მონაცემების დამუშავების დროს: " + e.Message);
}
finally
{
conn.Close();
}
}
public void ComboFill()
{
SqlConnection conn = new SqlConnection(connection);
string query = @"select ID, GroupName from Groups";
SqlCommand cmd = new SqlCommand(query, conn);
ComboGroupsList.DataSource = null;
ComboGroupsList.Items.Clear();
ComboSource = new List<KeyValuePair<int, string>>();
try
{
conn.Open();
SqlDataReader Reader = cmd.ExecuteReader();
while (Reader.Read())
{
Group group = new Group();
group.Name = Reader["GroupName"].ToString();
group.ID = Convert.ToInt32(Reader["ID"]);
ComboSource.Add(new KeyValuePair<int, string>(group.ID, group.Name));
}
ComboGroupsList.ValueMember = "key";
ComboGroupsList.DisplayMember = "Value";
ComboGroupsList.DataSource = ComboSource;
}
catch (Exception e)
{
MessageBox.Show("შეცდომა მონაცემების დამუშავების დროს: " + e.Message);
}
finally
{
conn.Close();
}
}
public bool VlidateUserViewModel(string name, string surname)
{
var IsValid = false;
if (!string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(surname))
{
IsValid = true;
}
return IsValid;
}
public void AddUser(string Name, string Surname, DateTime Birthdate, int GroupID)
{
SqlConnection conn = new SqlConnection(connection);
try
{
conn.Open();
string query = "INSERT INTO [Users](Name, Surname, Birthdate, CreateDate, GroupID)" + " values (@name, @surname, @birthdate, @createDate, @GroupID)";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("@name", SqlDbType.NVarChar, 50).Value = Name;
cmd.Parameters.Add("@surname", SqlDbType.NVarChar, 50).Value = Surname;
cmd.Parameters.Add("@birthdate", SqlDbType.Date).Value = Birthdate;
cmd.Parameters.Add("@createDate", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("@GroupID", SqlDbType.Int).Value = GroupID;
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
conn.Close();
}
}
public void AddGroup(string GroupName)
{
SqlConnection conn = new SqlConnection(connection);
try
{
conn.Open();
string query = "insert into Groups (GroupName) values (@groupName)";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("@groupName", SqlDbType.NVarChar, 50).Value = GroupName;
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
conn.Close();
}
}
public void UpdateUser(int id, string Name, string surname, DateTime birthdate, int GroupID)
{
SqlConnection conn = new SqlConnection(connection);
try
{
conn.Open();
string query = $@"UPDATE Users SET
Name = @name,
Surname = @surname,
Birthdate = @birthdate,
GroupID = @GroupID
where ID = {id} ";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("@name", SqlDbType.NVarChar, 50).Value = Name;
cmd.Parameters.Add("@surname", SqlDbType.NVarChar, 50).Value = surname;
cmd.Parameters.Add("@birthdate", SqlDbType.Date).Value = birthdate;
cmd.Parameters.Add("@GroupID", SqlDbType.Int).Value = GroupID;
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
conn.Close();
}
}
private void BtnAddUser_Click(object sender, EventArgs e)
{
string Name = TxbUserName.Text;
string Surname = TxbUserLastName.Text;
int GroupId = ((KeyValuePair<int, string>)ComboGroupsList.SelectedItem).Key;
DateTime Birthdate = DtBirthdate.Value;
if (VlidateUserViewModel(Name, Surname))
{
AddUser(Name, Surname, Birthdate, GroupId);
GridFill();
}
else
{
MessageBox.Show("sheavset carieli velebi");
}
}
private void UsersGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
var item = e.RowIndex;
DataGridViewRow selectedRow = UsersGridView.Rows[item];
UserId = Convert.ToInt32(selectedRow.Cells[0].Value);
SqlConnection sqlConnection = new SqlConnection(connection);
string query = $@"SELECT
U.Name,
U.Surname,
U.Birthdate,
U.GroupID
from Users U
inner JOIN Groups G on U.GroupID=G.ID
where
U.ID = {UserId} ";
SqlCommand cmd = new SqlCommand(query, sqlConnection);
try
{
sqlConnection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
TxbUserName.Text = reader["Name"].ToString();
TxbUserLastName.Text = reader["Surname"].ToString();
DtBirthdate.Value = Convert.ToDateTime(reader["Birthdate"]);
ComboGroupsList.SelectedItem = ComboSource.Find(Item => Item.Key == Convert.ToInt32(reader["GroupID"]));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sqlConnection.Close();
}
}
private void BtnUpdateUser_Click(object sender, EventArgs e)
{
string name = TxbUserName.Text;
string surname = TxbUserLastName.Text;
DateTime birthdate = DtBirthdate.Value;
int GroupId = ((KeyValuePair<int, string>)ComboGroupsList.SelectedItem).Key;
if (VlidateUserViewModel(name: name, surname: surname))
{
UpdateUser(UserId, name, surname, birthdate, GroupId);
TxbUserName.Clear();
TxbUserLastName.Clear();
DtBirthdate.ResetText();
TxbGroup.Clear();
GridFill();
}
else
{
MessageBox.Show("sheavset carieli velebi");
}
}
private void BtnAddGroup_Click(object sender, EventArgs e)
{
string groupName = TxbGroup.Text;
if (string.IsNullOrWhiteSpace(groupName))
{
MessageBox.Show("sheavset carieli velebi");
}
else
{
AddGroup(GroupName: groupName);
ComboFill();
TxbGroup.Clear();
}
}
}
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime BirthDate { get; set; }
public DateTime CreateDate { get; set; }
public string GroupName { get; set; }
}
public class Group
{
public int ID { get; set; }
public string Name { get; set; }
}
}
|
2801091b6e4ee26d2469d8350173b4b36cc03096
|
C#
|
QsCompany/Q-Hoster
|
/App/Services/GuidService.cs
| 2.640625
| 3
|
using System;
using System.Threading;
using Server;
namespace QServer.Services
{
[Core.HosteableObject(typeof(SessionIdService))]
public class SessionIdService : Service
{
private static Guid _gsessionId = Guid.NewGuid();
private static string _sessionID = "\"" + _gsessionId.ToString("N") + "\"";
public static string SessionId
{
get
{
return _sessionID;
}
}
public static Guid Guid { get { return _gsessionId; } }
public SessionIdService() : base("SessionId")
{
}
static object _syncObject = new object();
public override bool Get(RequestArgs args)
{
args.Send(SessionId);
return true;
}
}
[Core.HosteableObject(typeof(GuidService ),typeof(GuidSerializer))]
public class GuidService:Service
{
public GuidService():base("Guid")
{
}
static object _syncObject = new object();
public static long GetGuid() {
lock (_syncObject)
{
var dt = DateTime.Now;
var Y = dt.Year;
var M = dt.Month;
var D = dt.Day;
var H = dt.Hour;
var MN = dt.Minute;
var S = dt.Second;
var MS = dt.Millisecond;
var id = (((long)((((Y - 2000) * 12 + M) * 31 + D) * 24 + H) * 60 + MN) * 60 + S) * 1000 + MS;
Thread.Sleep(2);
return id;
}
}
public override bool Get(RequestArgs args)
{
var s = GetGuid();
args.Send("[" + s + "," + s + 1000 + "]");
return true;
}
}
}
|
e90d4a6179f4598d8517bf1c72a3026a91334760
|
C#
|
Fehler42/Pong
|
/Pong/Pong/Player2.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFML.Window;
using SFML.Graphics;
namespace Pong
{
class Player2
{
Vector2f playerPosition2;
Sprite playerSprite2;
public Vector2f getPosition()
{
return playerPosition2;
}
public float getHeight()
{
return playerSprite2.Texture.Size.Y * playerSprite2.Scale.Y;
}
public float getWidth()
{
return playerSprite2.Texture.Size.X * playerSprite2.Scale.X;
}
public Player2()
{
Texture playerTexture = new Texture("Pics/player2.png");
playerSprite2 = new Sprite(playerTexture);
playerPosition2 = new Vector2f(340, 540);
playerSprite2.Position = playerPosition2;
playerSprite2.Scale = new Vector2f(1, 1); //new Vector2f(0.2f, 0.05f);
}
public void move(GameTime time)
{
float runningSpeed = 0.3f * time.EllapsedTime.Milliseconds;
if (Keyboard.IsKeyPressed(Keyboard.Key.Left))
playerPosition2 = new Vector2f(playerPosition2.X - 3.2f, playerPosition2.Y);
if (Keyboard.IsKeyPressed(Keyboard.Key.Right))
playerPosition2 = new Vector2f(playerPosition2.X + 3.2f, playerPosition2.Y);
playerSprite2.Position = playerPosition2;
}
public void draw(RenderWindow win)
{
win.Draw(playerSprite2);
}
}
}
|
e4712b0568f6969abf494486a72b32d8718b604d
|
C#
|
L-Harrison/Lib
|
/Lib.Drawing/Knowledge/ImageExtends.cs
| 3.4375
| 3
|
using System.Drawing;
namespace Lib.Drawing
{
public class StringToImageParameter
{
public string String { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public Font Font { get; set; }
public Brush Foreground { get; set; }
public Brush Background { get; set; }
}
public static class ImageExtends
{
public static Image StringToImage(StringToImageParameter parameter)
{
Bitmap bitmap = new Bitmap(parameter.Width, parameter.Height);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.Optimize();
if (default(Brush) != parameter.Background && Brushes.Transparent != parameter.Background)//不画就是透明
{
if (parameter.Background is SolidBrush) graphics.Clear((parameter.Background as SolidBrush).Color);
else graphics.FillRectangle(parameter.Background, 0, 0, parameter.Width, parameter.Height);
}
graphics.DrawString(parameter.String, parameter.Font, parameter.Foreground, parameter.Width / 2, parameter.Height / 2, new StringFormat {
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
});
return bitmap;
}
}
}
|
d7a63bd0adcc57aa90873c39a6c58b69368a59a4
|
C#
|
abousias/cab
|
/src/Providers/IAppInfoProvider.cs
| 2.59375
| 3
|
namespace ConsoleAppBase.Providers
{
/// <summary>
/// Defines a provider for retrieving info about the actual application executing.
/// </summary>
public interface IAppInfoProvider
{
/// <summary>
/// Gets the short version of the version information.
/// </summary>
string ShortVersion { get; }
/// <summary>
/// Gets or sets the long version of the version information.
/// </summary>
string LongVersion { get; set; }
/// <summary>
/// Gets or sets the application name.
/// </summary>
string AppName { get; set; }
}
}
|
5d8640b8793c833c6ac5e2c752ef21b4bbe5b382
|
C#
|
Cornflakes1009/oop_one_class
|
/DailyTemps/DailyTemps/Program.cs
| 4.09375
| 4
|
using System;
using static System.Console;
class DailyTemps
{
static void Main()
{
int temp = 0;
int total = 0;
int average = 0;
int tempCount = 0;
int sentinelValue = 999;
while (temp != sentinelValue)
{
WriteLine("Please enter a number valid temperature ranging from -20 to 130");
temp = Convert.ToInt32(ReadLine());
if(temp >= -20 && temp <= 130)
{
tempCount++;
total += temp;
}
else if(temp == sentinelValue)
{
average = total / tempCount;
WriteLine("The total average temperature is {0}, with a combined total of {1} for all temperatures. {2} temperatures were entered.", average, total, tempCount);
}
else
{
WriteLine("Invalid temperature. Temperature must be between -20 and 130.");
}
}
ReadLine(); // added so the console doesn't close and can see the outcome.
}
}
|
b1c9c8d24ad1325b625c0ec6f72230a0619fd283
|
C#
|
shenchauhan/UWPCommunityToolkit
|
/Microsoft.Toolkit.Uwp.SampleApp/Common/ThicknessConverter.cs
| 2.75
| 3
|
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************
using System;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace Microsoft.Toolkit.Uwp.SampleApp.Common
{
public class ThicknessConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is string)
{
return value;
}
var thickness = (Thickness)value;
return thickness.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value is string thicknessString)
{
var thicknessTokens = thicknessString.Split(',')
.Where(tkn => !string.IsNullOrWhiteSpace(tkn))
.ToArray();
switch (thicknessTokens.Length)
{
case 1:
var thicknessValue = double.Parse(thicknessString);
return new Thickness
{
Left = thicknessValue,
Top = thicknessValue,
Right = thicknessValue,
Bottom = thicknessValue
};
case 2:
var thicknessHorizontalValue = double.Parse(thicknessTokens[0]);
var thicknessVerticalValue = double.Parse(thicknessTokens[1]);
return new Thickness
{
Left = thicknessHorizontalValue,
Top = thicknessVerticalValue,
Right = thicknessHorizontalValue,
Bottom = thicknessVerticalValue
};
case 4:
return new Thickness
{
Left = double.Parse(thicknessTokens[0]),
Top = double.Parse(thicknessTokens[1]),
Right = double.Parse(thicknessTokens[2]),
Bottom = double.Parse(thicknessTokens[3])
};
default:
return default(Thickness);
}
}
return value.ToString();
}
}
}
|
982ef0bc12b0a134e66c2d8f69e6a4d0c0d48fea
|
C#
|
NickRatchev/PrintingHouse
|
/PrintingHouse.ConsoleClient/Program.cs
| 2.78125
| 3
|
namespace PrintingHouse.ConsoleClient
{
using Data;
using System;
using System.Linq;
using Models;
using Data.Calculations;
class Program
{
static void Main()
{
//Utility.InitializeDatabase();
using (var context = new PrintingHouseContext())
{
// Order Data
string companyName = "Economedia";
string productTitle = "Capital Daily";
int issue = 52;
var date = DateTime.Parse("2017-04-12");
int printRun = 250001;
decimal paperGrammage = 42.5m;
var paper = context.Papers.FirstOrDefault(p => p.Grammage == paperGrammage);
// End Order Data
var order = new Order()
{
Client = context.Clients.SingleOrDefault(c => c.CompanyName == companyName),
Product = context.Products.SingleOrDefault(p => p.Title == productTitle),
Issue = issue,
PrintRun = printRun,
Paper = paper,
Date = date
};
context.Orders.Add(order);
context.SaveChanges();
// Component Data
byte pages = 56;
byte Pairs4Color = 14;
byte Pairs3Color = 0;
byte Pairs2Color = 0;
byte Pairs1Color = 14;
var machineData = context.MachineData.FirstOrDefault(m => m.NumberOfPages == pages);
// End Component Data
var component = new Component()
{
Order = order,
MachineData = machineData,
MachineDataId = machineData.Id,
Pairs4Color = Pairs4Color,
Pairs3Color = Pairs3Color,
Pairs2Color = Pairs2Color,
Pairs1Color = Pairs1Color
};
context.Components.Add(component);
order.Components.Add(component);
context.SaveChanges();
var paperkg = Calculations.CalculatePaperKg(order.Components);
var paperWastekg = Calculations.CalculatePaperWasteKg(order.Components);
var blackInkKg = Calculations.CalculateBlackInkKg(order.Components);
var colorInkKg = Calculations.CalculateColorInkKg(order.Components);
var wischwasserKg = Calculations.CalculateWischwasserKg(order.Components);
var foilKg = Calculations.CalculateFoilKg(order.Components);
var tapeMeters = Calculations.CalculateTapeMeters(order.Components);
var plates = Calculations.CalculatePlates(order.Components);
var blinds = Calculations.CalculateBlinds(order.Components);
var paperPrice = Calculations.CalculatePaperPrice(paperkg, date);
var paperWastePrice = Calculations.CalculatePaperPrice(paperWastekg, date);
var blackInkPrice = Calculations.CalculateBlackInkPrice(blackInkKg, date);
var colorInkPrice = Calculations.CalculateColorInkPrice(colorInkKg, date);
var wischwasserPrice = Calculations.CalculateWischwasserPrice(wischwasserKg, date);
var foilPrice = Calculations.CalculateFoilPrice(foilKg, date);
var tapePrice = Calculations.CalculateTapePrice(tapeMeters, date);
var platesPrice = Calculations.CalculatePlatesPrice(plates, date);
var blindsPrice = Calculations.CalculateBlindsPrice(blinds, date);
var plateExposing = Calculations.CalculatePlatesExposingPrice(plates, date);
var machineSetup = Calculations.CalculateMachineSetupPrice(order.Components);
var printing = Calculations.CalculatePrintingPrice(order.Components);
var packing = Calculations.CalculatePackingPrice(order.Components);
Console.WriteLine($"Number of Pages: {pages}");
Console.WriteLine($"Printrun: {printRun}");
Console.WriteLine($"Paper: {paperkg:F1} kg - {paperPrice:F2} lv.");
Console.WriteLine($"Paper Waste: {paperWastekg:F1} kg - {paperWastePrice:F2} lv.");
Console.WriteLine($"Black Ink: {blackInkKg:F1} kg - {blackInkPrice:F2} lv.");
Console.WriteLine($"Color Ink: {colorInkKg:F1} kg - {colorInkPrice:F2} lv.");
Console.WriteLine($"Wischwasser: {wischwasserKg:F1} kg - {wischwasserPrice:F2} lv.");
Console.WriteLine($"Foil: {foilKg:F1} kg - {foilPrice:F2} lv.");
Console.WriteLine($"Tape: {tapeMeters:F1} m - {tapePrice:F2} lv.");
Console.WriteLine($"Plates: {plates:F1} pcs - {platesPrice:F2} lv.");
Console.WriteLine($"Blinds: {blinds:F1} pcs - {blindsPrice:F2} lv.");
Console.WriteLine($"-------------------------------");
decimal totalMaterialsCost = paperPrice + paperWastePrice + blackInkPrice +
colorInkPrice + wischwasserPrice
+ foilPrice + tapePrice + platesPrice + blindsPrice;
Console.WriteLine($"TOTAL Materials Cost: {totalMaterialsCost:F2} lv.");
Console.WriteLine($"\n\nPlate Exposing: {plateExposing:F2} lv.");
Console.WriteLine($"Machine Setup: {machineSetup:F2} lv.");
Console.WriteLine($"Printing: {printing:F2} lv.");
Console.WriteLine($"Packing: {packing:F2} lv.");
Console.WriteLine($"-------------------------------");
decimal totalServiceCost = plateExposing + machineSetup + printing + packing;
Console.WriteLine($"TOTAL Service Cost: {totalServiceCost:F2} lv.");
Console.WriteLine($"\n===============================");
Console.WriteLine($" FINAL PRICE: {totalMaterialsCost + totalServiceCost:F2} lv.\n");
}
}
}
}
|
c6237a4479c8e168409e74a22b25e1325917b9f1
|
C#
|
exyi/redwood
|
/src/Redwood.Framework/Binding/ViewModelJTokenEvaluationVisitor.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Newtonsoft.Json.Linq;
using Redwood.Framework.Parser;
using Redwood.Framework.Resources;
namespace Redwood.Framework.Binding
{
public class ViewModelJTokenEvaluationVisitor : CSharpSyntaxVisitor<JToken>
{
private Stack<JToken> hierarchy = new Stack<JToken>();
/// <summary>
/// Initializes a new instance of the <see cref="ViewModelJTokenEvaluationVisitor"/> class.
/// </summary>
public ViewModelJTokenEvaluationVisitor(JToken root)
{
hierarchy.Push(root);
}
/// <summary>
/// Backs up current state.
/// </summary>
public void BackUpCurrentPosition(JToken current)
{
hierarchy.Push(current);
}
/// <summary>
/// Visits the expression statement.
/// </summary>
public override JToken VisitExpressionStatement(ExpressionStatementSyntax node)
{
return Visit(node.Expression);
}
/// <summary>
/// Visits the name of the identifier.
/// </summary>
public override JToken VisitIdentifierName(IdentifierNameSyntax node)
{
return GetObjectProperty(hierarchy.Peek(), node.Identifier.ToString());
}
/// <summary>
/// Visits the member access expression.
/// </summary>
public override JToken VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
return GetObjectProperty(Visit(node.Expression), node.Name.ToString());
}
/// <summary>
/// Visits the element access expression.
/// </summary>
public override JToken VisitElementAccessExpression(ElementAccessExpressionSyntax node)
{
var array = Visit(node.Expression) as JArray;
if (array == null) return null;
if (node.ArgumentList.Arguments.Count == 1)
{
var index = Visit(node.ArgumentList.Arguments.First()).Value<int?>();
if (index != null)
{
return array[index.Value];
}
}
return base.VisitElementAccessExpression(node);
}
/// <summary>
/// Visits the argument.
/// </summary>
public override JToken VisitArgument(ArgumentSyntax node)
{
return Visit(node.Expression);
}
/// <summary>
/// Visits the literal expression.
/// </summary>
public override JToken VisitLiteralExpression(LiteralExpressionSyntax node)
{
if (node.IsKind(SyntaxKind.NumericLiteralExpression))
{
return node.Token.Value as int?;
}
return base.VisitLiteralExpression(node);
}
/// <summary>
/// Gets the object property.
/// </summary>
private JToken GetObjectProperty(JToken target, string propertyName)
{
if (target == null) return null;
if (propertyName == Constants.ParentSpecialBindingProperty)
{
hierarchy.Pop();
return hierarchy.Peek();
}
else if (propertyName == Constants.RootSpecialBindingProperty)
{
while (hierarchy.Count > 1)
{
hierarchy.Pop();
}
return hierarchy.Peek();
}
else if (propertyName == Constants.ThisSpecialBindingProperty)
{
return target;
}
else
{
return target[propertyName];
}
}
public override JToken DefaultVisit(SyntaxNode node)
{
throw new ParserException(string.Format(Parser_RwHtml.Binding_UnsupportedExpressionInDataContext, node));
}
}
}
|
d4fa12aa3e28ede4efcb8e39efc18c750b9a7c3c
|
C#
|
Grimnak/LoZGame
|
/LoZGame/controller/Commands/Controllers/MouseController.cs
| 2.875
| 3
|
namespace LoZClone
{
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
/// <summary>
/// Controller for mouse inputs.
/// </summary>
public class MouseController : IController
{
private readonly MouseCommandLoader allCommands;
private ICommand currentCommand;
private MouseState oldState;
/// <summary>
/// Initializes a new instance of the <see cref="MouseController"/> class.
/// </summary>
/// <param name="allCommands">The command loader for mouse commands.</param>
public MouseController(MouseCommandLoader allCommands)
{
this.allCommands = allCommands;
oldState = Mouse.GetState();
}
/// <inheritdoc/>
public void Update()
{
MouseState state = Mouse.GetState();
Vector2 position = new Vector2(state.X, state.Y);
if (state.LeftButton == ButtonState.Pressed && oldState.LeftButton == ButtonState.Released)
{
// Vector logic
if (position.X > 400)
{
if (position.Y - 174 > (3 * position.X) / 5)
{
currentCommand = allCommands.GetCommandRoomDown;
}
else if (position.Y - 174 < (480 - ((3 * position.X) / 5)))
{
currentCommand = allCommands.GetCommandRoomUp;
}
else
{
currentCommand = allCommands.GetCommandRoomRight;
}
}
else
{
if (position.Y - 174 > (480 - ((3 * position.X) / 5)))
{
currentCommand = allCommands.GetCommandRoomDown;
}
else if (position.Y - 174 < (3 * position.X) / 5)
{
currentCommand = allCommands.GetCommandRoomUp;
}
else
{
currentCommand = allCommands.GetCommandRoomLeft;
}
}
currentCommand.Execute();
}
oldState = state;
}
}
}
|
94feb296a7c154105b34545a20ee2b07bc694c3e
|
C#
|
sphinx20/GitHub-sahalux
|
/C#/Programs/Duplicates.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace My_Personal_Projects
{
public class Duplicates
{
public void Start()
{
int[] arr = new[] { 3, 6, 7, 9, 9, 10, 12, 13, 13, 13, 16, 19, 21, 34 };
int previous = -9999;
for (int i = 0; i < arr.Length; i++)
{
if (previous != arr[i])
{
Console.WriteLine(arr[i]);
}
previous = arr[i];
}
Console.ReadLine();
}
}
}
|
7efc97670beedfea4b70fcd31aea357e9b380b07
|
C#
|
dbaldwin/DroneBlocksAirSim
|
/DroneBlocksAirSim/MissionBuilder.cs
| 2.875
| 3
|
using DroneBlocksAirSim.Commands;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DroneBlocksAirSim
{
// A basic mission
// takeoff|fly_forward,20,in|fly_backward,20,in|fly_left,20,in|fly_left,20,in|fly_up,20,in|fly_down,20,in|land
class MissionBuilder
{
private string missionString;
public MissionBuilder(string missionString)
{
this.missionString = missionString;
}
public ArrayList parseMission()
{
// In some cases when there's a single block we need to remove the leading pipe
if (missionString.IndexOf("|") == 0)
{
missionString = missionString.Remove(0, 1);
}
// Initialize the command list
ArrayList commandList = new ArrayList();
// Let's enable API control
// Need to make this more intelligent to determine if drone is in air
commandList.Add(new EnableApiControl().GetCommand());
foreach (var commandString in missionString.Split("|"))
{
string[] parameters = commandString.Split(",");
string command = parameters[0];
if (command.IndexOf("disarm") > -1)
{
commandList.Add(new ArmDisarm(false).GetCommand());
}
else if (command.IndexOf("arm") > -1)
{
commandList.Add(new ArmDisarm(true).GetCommand());
}
else if (command.IndexOf("takeoff") > -1)
{
commandList.Add(new Takeoff().GetCommand());
}
else if (command.IndexOf("coordinate_system") > -1)
{
}
// We can handle these in the same statement because the blocks will send a negative value for backward flight
else if (command.IndexOf("fly_x") > -1)
{
float xvelocity = float.Parse(parameters[1]);
float duration = float.Parse(parameters[2]);
Debug.WriteLine("fly by x velocity {0} for {1} s", xvelocity, duration);
commandList.Add(new MoveByVelocity(xvelocity, 0, 0, duration).GetCommand());
}
else if (command.IndexOf("fly_y") > -1)
{
float yvelocity = float.Parse(parameters[1]);
float duration = float.Parse(parameters[2]);
Debug.WriteLine("fly by y velocity {0} for {1} s", yvelocity, duration);
commandList.Add(new MoveByVelocity(0, yvelocity, 0, duration).GetCommand());
}
else if (command.IndexOf("fly_z") > -1)
{
float zvelocity = float.Parse(parameters[1]);
float duration = float.Parse(parameters[2]);
Debug.WriteLine("fly by z velocity {0} for {1} s", zvelocity, duration);
commandList.Add(new MoveByVelocity(0, 0, zvelocity, duration).GetCommand());
}
else if (command.IndexOf("fly_to_location") > -1)
{
float xposition = float.Parse(parameters[1]);
float yposition = float.Parse(parameters[2]);
float zposition = float.Parse(parameters[3]);
Debug.WriteLine("flying to location {0}, {1}, {2}", xposition, yposition, zposition);
commandList.Add(new MoveToPosition(xposition, yposition, zposition).GetCommand());
}
else if (command.IndexOf("fly_rpy") > -1)
{
float roll = float.Parse(parameters[1]);
float pitch = float.Parse(parameters[2]);
float yaw = float.Parse(parameters[3]);
float duration = float.Parse(parameters[4]);
Debug.WriteLine("flying with roll {0}, pitch {1}, yaw {2}, for {3} seconds", roll, pitch, yaw, duration);
commandList.Add(new MoveByRollPitchYaw(roll, pitch, yaw, duration).GetCommand());
}
else if (command.IndexOf("hover") > -1)
{
float delay = float.Parse(parameters[1]);
commandList.Add(new Hover(delay).GetCommand());
}
else if (command.IndexOf("rotate_to_yaw") > -1)
{
float yaw = float.Parse(parameters[1]);
commandList.Add(new RotateToYaw(yaw).GetCommand());
}
else if (command.IndexOf("rotate_yaw_rate") > -1)
{
float yawRate = float.Parse(parameters[1]);
float duration = float.Parse(parameters[2]);
commandList.Add(new RotateByYawRate(yawRate, duration).GetCommand());
}
else if (command.IndexOf("wind") > -1)
{
int x_vel = int.Parse(parameters[1]);
int y_vel = int.Parse(parameters[2]);
int z_vel = int.Parse(parameters[3]);
commandList.Add(new Wind(x_vel, y_vel, z_vel).GetCommand());
}
else if (command.IndexOf("weather_enable") > -1)
{
bool enable = bool.Parse(parameters[1]);
commandList.Add(new WeatherEnable(enable).GetCommand());
}
else if (command.IndexOf("weather_set") > -1)
{
int weatherType = int.Parse(parameters[1]);
float intensity = float.Parse(parameters[2]);
commandList.Add(new WeatherSet(weatherType, intensity).GetCommand());
}
else if (command.IndexOf("land") > -1)
{
// Before landing we're going to need to introduce a delay
// It seems like AirSim ignores the command if the drone is
// trying to stabilize itself
commandList.Add(new Hover(3).GetCommand());
commandList.Add(new Land().GetCommand());
}
}
return commandList;
}
}
}
|
669509634bb16504ecf3b95bab26ced6df6726d6
|
C#
|
jkoh2020/HangManGame
|
/HangManRepo.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Media;
namespace HangManGame
{
public class HangManRepo
{
public string isLetter(string word, List<string> letterGuessed) // to see letter is correct
{
string correctletters = " ";
for (int i = 0; i < word.Length; i++)
{
string c = Convert.ToString(word[i]);
if (letterGuessed.Contains(c))
{
correctletters += c;
}
else
{
correctletters += " _ ";
}
}
return correctletters + "\n\n";
}
public bool isWord(string word, List<string> letterGuessed) // to see you get the right word
{
bool a = false;
for (int i = 0; i < word.Length; i++)
{
string c = Convert.ToString(word[i]);
if (letterGuessed.Contains(c))
{
a = true;
}
else
{
return a = false;
}
}
return a;
}
public void WinningSound() // method: it plays the winning sound when you win a game
{
var myPlayer = new SoundPlayer();
myPlayer.SoundLocation = @"C:\ElevenFiftyProjects\SDLessons69\HangManGame\Tada-sound.wav";
myPlayer.Play();
}
public void LoserSound() // method: it plays sound when you lose
{
var myPlayer = new SoundPlayer();
myPlayer.SoundLocation = @"C:\ElevenFiftyProjects\SDLessons69\HangManGame\screamandchoke.wav";
myPlayer.Play();
}
}
}
|
f2c80cb96fa6f845fa1f4ec6dbfd4d5f9321355e
|
C#
|
shendongnian/download4
|
/code5/925477-23200833-63363056-2.cs
| 3.171875
| 3
|
public abstract class CalendarBaseItem
{
abstract void Process(SomeData somedata);
//...
}
public class RotaItem : CalendarBaseItem
{
public override void Process(SomeData somedata)
{
// now we know we're dealing with a `RotaItem` instance,
// and the specialized ProcessItem can be called
someData.ProcessItem(this);
}
//...
}
public class SomeData
{
public void ProcessItem(RotaItem item)
{
//...
}
public void ProcessItem(NoteItem item)
{
//...
}
}
|
601806cd9e44da7e9bf7d95e20b38fb2b06d0fe9
|
C#
|
haoxinwong/p1
|
/WebUI/Models/OrderVM.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Models;
namespace WebUI.Models
{
public class OrderVM
{
public OrderVM() { }
public OrderVM(Order order)
{
this.LineItems = order.LineItems;
this.Id = order.Id;
this.Total = order.Total;
this.Time = order.Time;
this.Location = order.Location;
this.CustomerId = order.CustomerId;
this.StoreId = order.StoreId;
}
public decimal Total { get; set; }
public List<LineItem> LineItems { get; set; }
public DateTime Time { get; set; }
[Required]
[RegularExpression("^[a-zA-Z0-9 !?']+$", ErrorMessage = "Location name can only have alphanumeric characters, !, and ?.")]
public string Location { get; set; }
public int StoreId { get; set; }
public int CustomerId { get; set; }
public int Id { get; set; }
public Order ToModel()
{
Order newOrder;
try
{
newOrder = new Order
{
Id = this.Id,
Total = this.Total,
Location = this.Location ?? "",
StoreId = this.StoreId,
CustomerId = this.CustomerId,
Time = this.Time
};
//ternary
// IfStatement ? ifTrue : ifFalse
// null checker
// ifExists/notNull ?? ifFalse
// IsNull?.Prperty
}
catch
{
throw;
}
return newOrder;
}
}
}
|
c7f1dbcdbbfa9770f039c82406e923a9f3771f54
|
C#
|
luisurbinanet/apolloniax
|
/Open Dental/OpenDentBusiness/TableTypes/ProgramProperty.cs
| 2.65625
| 3
|
using System;
namespace OpenDentBusiness{
///<summary>Some program links (bridges), have properties that need to be set. The property names are always hard coded. User can change the value. The property is usually retrieved based on its name.</summary>
public class ProgramProperty{
///<summary>Primary key.</summary>
public int ProgramPropertyNum;
///<summary>FK to program.ProgramNum</summary>
public int ProgramNum;
///<summary>The description or prompt for this property.</summary>
public string PropertyDesc;
///<summary>The value.</summary>
public string PropertyValue;
}
}
|
955543620ea5d2e397f61816bb0eb7b17ceb8678
|
C#
|
vishalishere/typec
|
/src/TypeC/TypeC/ProbingAssemblyDirectory.cs
| 3.171875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace TypeC
{
public class ProbingAssemblyDirectory
{
private string _directoryName;
private List<string> _dllNames = new List<string>();
/// <summary>
/// Setting the directory name will expand all the DLLs in the directory
/// </summary>
public string DirectoryName
{
get { return _directoryName; }
//do a regex based check
set
{
_directoryName = value;
//remove the last backweard slash, if present
if (_directoryName.LastIndexOf(@"\") == _directoryName.Length - 1)
{
_directoryName = _directoryName.Substring(0, _directoryName.Length - 1);
}
//add filter for system directories in future
LoadDllNames();
}
}
/// <summary>
/// LoadDllNames() will reset the existing dll collection
/// </summary>
public void LoadDllNames()
{
if (string.IsNullOrEmpty(_directoryName))
{
return;
}
if (!Directory.Exists(_directoryName))
{
return;
}
string[] files = Directory.GetFiles(_directoryName);
_dllNames = new List<string>();
foreach (var fileName in files)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Extension.Equals(".dll"))
{
continue;
}
_dllNames.Add(fi.Name);
}
}
public List<string> DllNames
{
get { return _dllNames; }
set { _dllNames = value; }
}
}
}
|
56011fa40c7a733b6e7f097340f8777344db4a1e
|
C#
|
srikanthpragada/MSNET_11_FEB_2019_CSHARPDEMO
|
/DelegateDemo.cs
| 3.375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace csharpdemo
{
class DelegateDemo
{
static bool IsEven(int n)
{
return n % 2 == 0;
}
static void Main(string[] args)
{
int[] a = { 10, 15, 20, 25, 30 };
// var res = Array.FindAll(a, IsEven);
var res = Array.FindAll(a, n => n % 2 == 0);
foreach (int v in res)
Console.WriteLine(v);
}
}
}
|
bcaade6cf76eed66a945c636baa2ddcd2f1eec11
|
C#
|
rocklee2015/RicoSamples
|
/13-linqpad/00-sample/02-linq pad sample lib/ThinkingInLINQ/Chapter 7 Static Code Analysis/7-6. Generating Documentation Automatically.linq
| 2.734375
| 3
|
<Query Kind="Program">
<Reference>C:\Evaluant.Linq.Compiler.dll</Reference>
<Namespace>Evaluant.Linq.Compiler</Namespace>
<Namespace>MoreLinq</Namespace>
</Query>
public string GetSummary(string total, string methodName)
{
string search = methodName;
string summary = total.Substring(
total.IndexOf(search)+search.Length);
summary = summary.Substring(
summary.IndexOf("<summary>")+"<summary>".Length);
summary = summary.Substring(0,summary.IndexOf("</summary"));
return summary;
}
void Main()
{
string moreLINQdll = @"C:\MoreLINQ\MoreLINQ.dll";
string xmlFilePath = @"C:\MoreLINQ\MoreLinq.xml";
StreamReader sr = new StreamReader (xmlFilePath);
string total = sr.ReadToEnd();
sr.Close();
total = total
.Replace("<c>",string.Empty).Replace("</c>",string.Empty)
.Replace("<","<").Replace(">",">");
var allMethods = Assembly
.LoadFrom(moreLINQdll)
.GetTypes()
.Where (a => a.IsPublic )
.ToList()
.Select(t => new KeyValuePair<string,
List<KeyValuePair<string,string>>>(t.Name,t.GetMethods()
.Where (x => x.IsPublic
&& (!x.Name.StartsWith("get_")
&& !x.Name.StartsWith("set_")
&& !x.Name.StartsWith("GetHashCode")
&& !x.Name.StartsWith("ToString")
&& !x.Name.StartsWith("Equals")
&& !x.Name.StartsWith("CompareTo")
&& !x.Name.StartsWith("GetType")))
.Select (x => new KeyValuePair<string,string>(x.Name, GetSummary(total,t.Name+"."+x.Name)))
.DistinctBy(z => z.Key)
.ToList()))
.First()
.Dump();
}
|
5348997b1fbe528204db1978743fe4290043b12c
|
C#
|
unity-game-framework/ugf-editortools
|
/Packages/UGF.EditorTools/Runtime/IMGUI.Types/TypeReference`1.cs
| 2.953125
| 3
|
using System;
using UnityEngine;
namespace UGF.EditorTools.Runtime.IMGUI.Types
{
[Serializable]
public struct TypeReference<TType> : IEquatable<TypeReference<TType>>, IComparable<TypeReference<TType>>
{
[SerializeField] private string m_value;
public string Value { get { return HasValue ? m_value : throw new ArgumentException("Value not specified."); } set { m_value = value; } }
public bool HasValue { get { return !string.IsNullOrEmpty(m_value); } }
public Type Type { get { return typeof(TType); } }
public TypeReference(string value)
{
if (string.IsNullOrEmpty(value)) throw new ArgumentException("Value cannot be null or empty.", nameof(value));
m_value = value;
}
public Type Get()
{
return TryGet(out Type type) ? type : throw new ArgumentException($"Type not found by the specified type name: '{m_value}'.");
}
public bool TryGet(out Type type)
{
type = Type.GetType(m_value);
return type != null;
}
public void Set(Type type)
{
if (type == null) throw new ArgumentNullException(nameof(type));
m_value = type.AssemblyQualifiedName;
}
public void Clear()
{
m_value = string.Empty;
}
public bool Equals(TypeReference<TType> other)
{
return m_value == other.m_value;
}
public override bool Equals(object obj)
{
return obj is TypeReference<TType> other && Equals(other);
}
public override int GetHashCode()
{
return m_value != null ? m_value.GetHashCode() : 0;
}
public int CompareTo(TypeReference<TType> other)
{
return string.Compare(m_value, other.m_value, StringComparison.Ordinal);
}
public static bool operator ==(TypeReference<TType> first, TypeReference<TType> second)
{
return first.Equals(second);
}
public static bool operator !=(TypeReference<TType> first, TypeReference<TType> second)
{
return !first.Equals(second);
}
public override string ToString()
{
return $"{nameof(m_value)}: {m_value}";
}
}
}
|
b4110663bd142e6c2280f910bf2bf426168f3b68
|
C#
|
MadsMosu/marching-cubes-gpu
|
/Assets/GPU Version/ChunkInstance.cs
| 2.625
| 3
|
/*
Author: Gus Tahara-Edmonds
Date: Summer 2019
Purpose: Used to communicate and hold some data for one specific chunk. Nothing too complicated.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChunkInstance : MonoBehaviour {
public Mesh mesh;
public MeshRenderer rend;
public Vector3 coord;
public int lodIndex;
public MeshCollider collider;
//when this chunk is created, function is called to make sure chunk is setup properly
public void Setup(Vector3 worldPos, int lodModifier, bool useCollisions) {
coord = worldPos;
this.lodIndex = lodModifier;
rend = gameObject.AddComponent<MeshRenderer>();
MeshFilter filter = gameObject.AddComponent<MeshFilter>();
mesh = new Mesh {
indexFormat = UnityEngine.Rendering.IndexFormat.UInt32
};
filter.mesh = mesh;
if (useCollisions) {
collider = gameObject.AddComponent<MeshCollider>();
collider.sharedMesh = mesh;
}
}
//sets the material this chunk uses to render
public void SetMat(Material mat) {
rend.material = mat;
}
}
|